From c818d68a48f633ce78634b7508838510d01c0690 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 28 Jun 2013 11:44:33 -0700 Subject: [PATCH 01/15] Ported ICE plugin to TinyMCE4 --- demo/index-mce4.html | 78 + .../jscripts/tinymce4/classes/AddOnManager.js | 370 + .../jscripts/tinymce4/classes/Compat.js | 41 + .../jscripts/tinymce4/classes/Editor.js | 2064 + .../tinymce4/classes/EditorCommands.js | 691 + .../tinymce4/classes/EditorManager.js | 501 + .../jscripts/tinymce4/classes/EnterKey.js | 611 + lib/tinymce/jscripts/tinymce4/classes/Env.js | 117 + .../jscripts/tinymce4/classes/ForceBlocks.js | 127 + .../jscripts/tinymce4/classes/Formatter.js | 2366 ++ .../jscripts/tinymce4/classes/LegacyInput.js | 73 + .../jscripts/tinymce4/classes/Shortcuts.js | 111 + .../jscripts/tinymce4/classes/UndoManager.js | 301 + .../tinymce4/classes/WindowManager.js | 175 + .../tinymce4/classes/dom/ControlSelection.js | 450 + .../jscripts/tinymce4/classes/dom/DOMUtils.js | 2067 + .../jscripts/tinymce4/classes/dom/DomQuery.js | 719 + .../tinymce4/classes/dom/EventUtils.js | 525 + .../jscripts/tinymce4/classes/dom/Range.js | 774 + .../tinymce4/classes/dom/RangeUtils.js | 267 + .../tinymce4/classes/dom/ScriptLoader.js | 249 + .../tinymce4/classes/dom/Selection.js | 1314 + .../tinymce4/classes/dom/Serializer.js | 385 + .../tinymce4/classes/dom/Sizzle.jQuery.js | 28 + .../jscripts/tinymce4/classes/dom/Sizzle.js | 1923 + .../tinymce4/classes/dom/TreeWalker.js | 71 + .../tinymce4/classes/dom/TridentSelection.js | 496 + .../tinymce4/classes/html/DomParser.js | 752 + .../tinymce4/classes/html/Entities.js | 261 + .../jscripts/tinymce4/classes/html/Node.js | 496 + .../tinymce4/classes/html/SaxParser.js | 390 + .../jscripts/tinymce4/classes/html/Schema.js | 917 + .../tinymce4/classes/html/Serializer.js | 156 + .../jscripts/tinymce4/classes/html/Styles.js | 297 + .../jscripts/tinymce4/classes/html/Writer.js | 199 + .../tinymce4/classes/jquery.tinymce.js | 357 + .../tinymce4/classes/ui/AbsoluteLayout.js | 46 + .../jscripts/tinymce4/classes/ui/Button.js | 67 + .../tinymce4/classes/ui/ButtonGroup.js | 41 + .../jscripts/tinymce4/classes/ui/Checkbox.js | 80 + .../tinymce4/classes/ui/CheckboxGroup.js | 19 + .../tinymce4/classes/ui/Collection.js | 407 + .../tinymce4/classes/ui/ColorButton.js | 186 + .../jscripts/tinymce4/classes/ui/ComboBox.js | 181 + .../jscripts/tinymce4/classes/ui/Container.js | 325 + .../jscripts/tinymce4/classes/ui/Control.js | 1266 + .../jscripts/tinymce4/classes/ui/DomUtils.js | 70 + .../tinymce4/classes/ui/DragHelper.js | 125 + .../tinymce4/classes/ui/ElementPath.js | 64 + .../jscripts/tinymce4/classes/ui/Factory.js | 78 + .../jscripts/tinymce4/classes/ui/FieldSet.js | 49 + .../tinymce4/classes/ui/FilePicker.js | 43 + .../jscripts/tinymce4/classes/ui/FitLayout.js | 39 + .../tinymce4/classes/ui/FlexLayout.js | 240 + .../tinymce4/classes/ui/FloatPanel.js | 204 + .../tinymce4/classes/ui/FlowLayout.js | 32 + .../jscripts/tinymce4/classes/ui/Form.js | 130 + .../jscripts/tinymce4/classes/ui/FormItem.js | 44 + .../tinymce4/classes/ui/FormatControls.js | 573 + .../tinymce4/classes/ui/GridLayout.js | 201 + .../jscripts/tinymce4/classes/ui/Iframe.js | 43 + .../tinymce4/classes/ui/KeyboardNavigation.js | 302 + .../jscripts/tinymce4/classes/ui/Label.js | 102 + .../jscripts/tinymce4/classes/ui/Layout.js | 75 + .../jscripts/tinymce4/classes/ui/ListBox.js | 84 + .../jscripts/tinymce4/classes/ui/Menu.js | 99 + .../jscripts/tinymce4/classes/ui/MenuBar.js | 28 + .../tinymce4/classes/ui/MenuButton.js | 183 + .../jscripts/tinymce4/classes/ui/MenuItem.js | 198 + .../tinymce4/classes/ui/MessageBox.js | 135 + .../jscripts/tinymce4/classes/ui/Movable.js | 93 + .../jscripts/tinymce4/classes/ui/Panel.js | 82 + .../tinymce4/classes/ui/PanelButton.js | 57 + .../jscripts/tinymce4/classes/ui/Path.js | 112 + .../jscripts/tinymce4/classes/ui/Radio.js | 71 + .../tinymce4/classes/ui/RadioGroup.js | 19 + .../jscripts/tinymce4/classes/ui/Resizable.js | 38 + .../tinymce4/classes/ui/ResizeHandle.js | 93 + .../tinymce4/classes/ui/Scrollable.js | 145 + .../jscripts/tinymce4/classes/ui/Selector.js | 356 + .../jscripts/tinymce4/classes/ui/Spacer.js | 29 + .../tinymce4/classes/ui/SplitButton.js | 92 + .../tinymce4/classes/ui/StackLayout.js | 26 + .../jscripts/tinymce4/classes/ui/TabPanel.js | 135 + .../jscripts/tinymce4/classes/ui/TextBox.js | 150 + .../jscripts/tinymce4/classes/ui/Throbber.js | 47 + .../jscripts/tinymce4/classes/ui/Toolbar.js | 45 + .../jscripts/tinymce4/classes/ui/Tooltip.js | 63 + .../jscripts/tinymce4/classes/ui/Widget.js | 99 + .../jscripts/tinymce4/classes/ui/Window.js | 384 + .../jscripts/tinymce4/classes/util/Class.js | 165 + .../jscripts/tinymce4/classes/util/JSON.js | 109 + .../jscripts/tinymce4/classes/util/JSONP.js | 38 + .../tinymce4/classes/util/JSONRequest.js | 110 + .../tinymce4/classes/util/LocalStorage.js | 175 + .../tinymce4/classes/util/Observable.js | 188 + .../jscripts/tinymce4/classes/util/Quirks.js | 932 + .../jscripts/tinymce4/classes/util/Tools.js | 496 + .../jscripts/tinymce4/classes/util/URI.js | 352 + .../jscripts/tinymce4/classes/util/VK.js | 37 + .../jscripts/tinymce4/classes/util/XHR.js | 84 + .../jscripts/tinymce4/jquery.tinymce.min.js | 1 + lib/tinymce/jscripts/tinymce4/langs/readme.md | 1 + lib/tinymce/jscripts/tinymce4/license.txt | 504 + .../tinymce4/plugins/advlist/plugin.js | 93 + .../tinymce4/plugins/advlist/plugin.min.js | 1 + .../tinymce4/plugins/anchor/plugin.js | 39 + .../tinymce4/plugins/anchor/plugin.min.js | 1 + .../tinymce4/plugins/autolink/plugin.js | 159 + .../tinymce4/plugins/autolink/plugin.min.js | 1 + .../tinymce4/plugins/autoresize/plugin.js | 87 + .../tinymce4/plugins/autoresize/plugin.min.js | 1 + .../tinymce4/plugins/autosave/plugin.js | 127 + .../tinymce4/plugins/autosave/plugin.min.js | 1 + .../tinymce4/plugins/bbcode/plugin.js | 123 + .../tinymce4/plugins/bbcode/plugin.min.js | 1 + .../tinymce4/plugins/charmap/plugin.js | 361 + .../tinymce4/plugins/charmap/plugin.min.js | 1 + .../tinymce4/plugins/chocobo/plugin.js | 38 + .../tinymce4/plugins/chocobo/plugin.min.js | 1 + .../jscripts/tinymce4/plugins/code/plugin.js | 44 + .../tinymce4/plugins/code/plugin.min.js | 1 + .../plugins/compat3x/editable_selects.js | 70 + .../tinymce4/plugins/compat3x/form_utils.js | 210 + .../tinymce4/plugins/compat3x/mctabs.js | 162 + .../plugins/compat3x/tiny_mce_popup.js | 435 + .../tinymce4/plugins/compat3x/validate.js | 252 + .../tinymce4/plugins/contextmenu/plugin.js | 70 + .../plugins/contextmenu/plugin.min.js | 1 + .../tinymce4/plugins/directionality/plugin.js | 64 + .../plugins/directionality/plugin.min.js | 1 + .../plugins/emoticons/img/smiley-cool.gif | Bin 0 -> 354 bytes .../plugins/emoticons/img/smiley-cry.gif | Bin 0 -> 329 bytes .../emoticons/img/smiley-embarassed.gif | Bin 0 -> 331 bytes .../emoticons/img/smiley-foot-in-mouth.gif | Bin 0 -> 342 bytes .../plugins/emoticons/img/smiley-frown.gif | Bin 0 -> 340 bytes .../plugins/emoticons/img/smiley-innocent.gif | Bin 0 -> 336 bytes .../plugins/emoticons/img/smiley-kiss.gif | Bin 0 -> 338 bytes .../plugins/emoticons/img/smiley-laughing.gif | Bin 0 -> 343 bytes .../emoticons/img/smiley-money-mouth.gif | Bin 0 -> 321 bytes .../plugins/emoticons/img/smiley-sealed.gif | Bin 0 -> 323 bytes .../plugins/emoticons/img/smiley-smile.gif | Bin 0 -> 344 bytes .../emoticons/img/smiley-surprised.gif | Bin 0 -> 338 bytes .../emoticons/img/smiley-tongue-out.gif | Bin 0 -> 328 bytes .../emoticons/img/smiley-undecided.gif | Bin 0 -> 337 bytes .../plugins/emoticons/img/smiley-wink.gif | Bin 0 -> 350 bytes .../plugins/emoticons/img/smiley-yell.gif | Bin 0 -> 336 bytes .../tinymce4/plugins/emoticons/plugin.js | 77 + .../tinymce4/plugins/emoticons/plugin.min.js | 1 + .../tinymce4/plugins/example/plugin.js | 45 + .../tinymce4/plugins/example/plugin.min.js | 1 + .../plugins/example_dependency/plugin.js | 22 + .../plugins/example_dependency/plugin.min.js | 1 + .../tinymce4/plugins/fullpage/plugin.js | 436 + .../tinymce4/plugins/fullpage/plugin.min.js | 1 + .../tinymce4/plugins/fullscreen/plugin.js | 115 + .../tinymce4/plugins/fullscreen/plugin.min.js | 1 + .../jscripts/tinymce4/plugins/hr/plugin.js | 30 + .../tinymce4/plugins/hr/plugin.min.js | 1 + .../jscripts/tinymce4/plugins/ice/css/ice.css | 27 + .../tinymce4/plugins/ice/img/accept.gif | Bin 0 -> 197 bytes .../plugins/ice/img/ice-accept-change.png | Bin 0 -> 3228 bytes .../tinymce4/plugins/ice/img/ice-accept.png | Bin 0 -> 3450 bytes .../plugins/ice/img/ice-reject-change.png | Bin 0 -> 3125 bytes .../tinymce4/plugins/ice/img/ice-reject.png | Bin 0 -> 3405 bytes .../plugins/ice/img/ice-showchanges.png | Bin 0 -> 944 bytes .../plugins/ice/img/ice-togglechanges.png | Bin 0 -> 3259 bytes .../tinymce4/plugins/ice/img/reject.gif | Bin 0 -> 165 bytes .../tinymce4/plugins/ice/js/ice.min.js | 6 + .../jscripts/tinymce4/plugins/ice/plugin.js | 460 + .../icesearchreplace/css/searchreplace.css | 6 + .../plugins/icesearchreplace/editor_plugin.js | 61 + .../icesearchreplace/js/searchreplace.js | 160 + .../plugins/icesearchreplace/langs/en_dlg.js | 16 + .../plugins/icesearchreplace/plugin.js | 61 + .../icesearchreplace/searchreplace.htm | 100 + .../jscripts/tinymce4/plugins/image/plugin.js | 110 + .../tinymce4/plugins/image/plugin.min.js | 1 + .../tinymce4/plugins/insertdatetime/plugin.js | 98 + .../plugins/insertdatetime/plugin.min.js | 1 + .../jscripts/tinymce4/plugins/layer/plugin.js | 225 + .../tinymce4/plugins/layer/plugin.min.js | 1 + .../tinymce4/plugins/legacyoutput/plugin.js | 110 + .../plugins/legacyoutput/plugin.min.js | 1 + .../jscripts/tinymce4/plugins/link/plugin.js | 122 + .../tinymce4/plugins/link/plugin.min.js | 1 + .../jscripts/tinymce4/plugins/lists/plugin.js | 612 + .../tinymce4/plugins/lists/plugin.min.js | 1 + .../tinymce4/plugins/media/moxieplayer.swf | Bin 0 -> 19980 bytes .../jscripts/tinymce4/plugins/media/plugin.js | 550 + .../tinymce4/plugins/media/plugin.min.js | 1 + .../tinymce4/plugins/nonbreaking/plugin.js | 43 + .../plugins/nonbreaking/plugin.min.js | 1 + .../tinymce4/plugins/noneditable/plugin.js | 533 + .../plugins/noneditable/plugin.min.js | 1 + .../tinymce4/plugins/pagebreak/plugin.js | 86 + .../tinymce4/plugins/pagebreak/plugin.min.js | 1 + .../plugins/paste/classes/Clipboard.js | 216 + .../tinymce4/plugins/paste/classes/Plugin.js | 40 + .../tinymce4/plugins/paste/classes/Quirks.js | 110 + .../plugins/paste/classes/WordFilter.js | 259 + .../tinymce4/plugins/paste/plugin.dev.js | 119 + .../jscripts/tinymce4/plugins/paste/plugin.js | 721 + .../tinymce4/plugins/paste/plugin.min.js | 1 + .../tinymce4/plugins/preview/plugin.js | 62 + .../tinymce4/plugins/preview/plugin.min.js | 1 + .../jscripts/tinymce4/plugins/print/plugin.js | 27 + .../tinymce4/plugins/print/plugin.min.js | 1 + .../jscripts/tinymce4/plugins/save/plugin.js | 93 + .../tinymce4/plugins/save/plugin.min.js | 1 + .../tinymce4/plugins/searchreplace/plugin.js | 533 + .../plugins/searchreplace/plugin.min.js | 1 + .../spellchecker/classes/DomTextMatcher.js | 278 + .../plugins/spellchecker/classes/Plugin.js | 262 + .../plugins/spellchecker/plugin.dev.js | 117 + .../tinymce4/plugins/spellchecker/plugin.js | 630 + .../plugins/spellchecker/plugin.min.js | 1 + .../tinymce4/plugins/tabfocus/plugin.js | 112 + .../tinymce4/plugins/tabfocus/plugin.min.js | 1 + .../plugins/table/classes/CellSelection.js | 161 + .../tinymce4/plugins/table/classes/Plugin.js | 706 + .../tinymce4/plugins/table/classes/Quirks.js | 340 + .../plugins/table/classes/TableGrid.js | 811 + .../tinymce4/plugins/table/plugin.dev.js | 119 + .../jscripts/tinymce4/plugins/table/plugin.js | 2114 ++ .../tinymce4/plugins/table/plugin.min.js | 1 + .../tinymce4/plugins/template/plugin.js | 196 + .../tinymce4/plugins/template/plugin.min.js | 1 + .../plugins/visualblocks/css/visualblocks.css | 114 + .../plugins/visualblocks/img/address.gif | Bin 0 -> 104 bytes .../plugins/visualblocks/img/article.gif | Bin 0 -> 99 bytes .../plugins/visualblocks/img/aside.gif | Bin 0 -> 86 bytes .../plugins/visualblocks/img/blockquote.gif | Bin 0 -> 120 bytes .../tinymce4/plugins/visualblocks/img/div.gif | Bin 0 -> 72 bytes .../plugins/visualblocks/img/figure.gif | Bin 0 -> 93 bytes .../tinymce4/plugins/visualblocks/img/h1.gif | Bin 0 -> 64 bytes .../tinymce4/plugins/visualblocks/img/h2.gif | Bin 0 -> 67 bytes .../tinymce4/plugins/visualblocks/img/h3.gif | Bin 0 -> 66 bytes .../tinymce4/plugins/visualblocks/img/h4.gif | Bin 0 -> 67 bytes .../tinymce4/plugins/visualblocks/img/h5.gif | Bin 0 -> 67 bytes .../tinymce4/plugins/visualblocks/img/h6.gif | Bin 0 -> 67 bytes .../plugins/visualblocks/img/hgroup.gif | Bin 0 -> 96 bytes .../tinymce4/plugins/visualblocks/img/p.gif | Bin 0 -> 63 bytes .../tinymce4/plugins/visualblocks/img/pre.gif | Bin 0 -> 76 bytes .../plugins/visualblocks/img/section.gif | Bin 0 -> 98 bytes .../tinymce4/plugins/visualblocks/plugin.js | 72 + .../plugins/visualblocks/plugin.min.js | 1 + .../tinymce4/plugins/visualchars/plugin.js | 80 + .../plugins/visualchars/plugin.min.js | 1 + .../tinymce4/plugins/wordcount/plugin.js | 64 + .../tinymce4/plugins/wordcount/plugin.min.js | 1 + .../skins/lightgray/AbsoluteLayout.less | 17 + .../tinymce4/skins/lightgray/Animations.less | 10 + .../tinymce4/skins/lightgray/Button.less | 115 + .../tinymce4/skins/lightgray/ButtonGroup.less | 44 + .../tinymce4/skins/lightgray/Checkbox.less | 27 + .../tinymce4/skins/lightgray/ColorButton.less | 44 + .../tinymce4/skins/lightgray/ComboBox.less | 34 + .../tinymce4/skins/lightgray/Container.less | 9 + .../tinymce4/skins/lightgray/Content.less | 81 + .../tinymce4/skins/lightgray/FieldSet.less | 15 + .../tinymce4/skins/lightgray/FitLayout.less | 9 + .../tinymce4/skins/lightgray/FloatPanel.less | 67 + .../tinymce4/skins/lightgray/FlowLayout.less | 17 + .../tinymce4/skins/lightgray/Icons.Ie7.less | 97 + .../tinymce4/skins/lightgray/Icons.less | 91 + .../tinymce4/skins/lightgray/Iframe.less | 6 + .../tinymce4/skins/lightgray/Label.less | 20 + .../tinymce4/skins/lightgray/ListBox.less | 20 + .../tinymce4/skins/lightgray/Menu.less | 29 + .../tinymce4/skins/lightgray/MenuBar.less | 23 + .../tinymce4/skins/lightgray/MenuButton.less | 5 + .../tinymce4/skins/lightgray/MenuItem.less | 89 + .../tinymce4/skins/lightgray/Mixins.less | 60 + .../tinymce4/skins/lightgray/Panel.less | 6 + .../tinymce4/skins/lightgray/Path.less | 39 + .../tinymce4/skins/lightgray/Radio.less | 19 + .../tinymce4/skins/lightgray/Reset.less | 36 + .../skins/lightgray/ResizeHandle.less | 18 + .../tinymce4/skins/lightgray/Scrollable.less | 44 + .../tinymce4/skins/lightgray/Select.less | 6 + .../tinymce4/skins/lightgray/Spacer.less | 5 + .../tinymce4/skins/lightgray/SplitButton.less | 23 + .../tinymce4/skins/lightgray/StackLayout.less | 5 + .../tinymce4/skins/lightgray/TabPanel.less | 28 + .../tinymce4/skins/lightgray/TextBox.less | 28 + .../tinymce4/skins/lightgray/Throbber.less | 9 + .../tinymce4/skins/lightgray/TinyMCE.less | 105 + .../tinymce4/skins/lightgray/ToolTip.less | 135 + .../tinymce4/skins/lightgray/Variables.less | 123 + .../tinymce4/skins/lightgray/Window.less | 108 + .../tinymce4/skins/lightgray/content.min.css | 1 + .../skins/lightgray/fonts/icomoon.dev.svg | 150 + .../skins/lightgray/fonts/icomoon.eot | Bin 0 -> 8196 bytes .../skins/lightgray/fonts/icomoon.svg | 150 + .../skins/lightgray/fonts/icomoon.ttf | Bin 0 -> 8032 bytes .../skins/lightgray/fonts/icomoon.woff | Bin 0 -> 8340 bytes .../tinymce4/skins/lightgray/fonts/readme.md | 1 + .../tinymce4/skins/lightgray/img/anchor.gif | Bin 0 -> 53 bytes .../tinymce4/skins/lightgray/img/loader.gif | Bin 0 -> 2608 bytes .../tinymce4/skins/lightgray/img/object.gif | Bin 0 -> 152 bytes .../tinymce4/skins/lightgray/img/trans.gif | Bin 0 -> 43 bytes .../tinymce4/skins/lightgray/img/wline.gif | Bin 0 -> 46 bytes .../skins/lightgray/skin.classic.min.css | 1 + .../tinymce4/skins/lightgray/skin.ie7.min.css | 1 + .../tinymce4/skins/lightgray/skin.less | 37 + .../tinymce4/skins/lightgray/skin.min.css | 1 + .../jscripts/tinymce4/themes/modern/theme.js | 479 + .../tinymce4/themes/modern/theme.min.js | 1 + lib/tinymce/jscripts/tinymce4/tinymce.dev.js | 213 + .../jscripts/tinymce4/tinymce.jquery.dev.js | 212 + .../jscripts/tinymce4/tinymce.jquery.js | 30495 +++++++++++++++ .../jscripts/tinymce4/tinymce.jquery.min.js | 9 + lib/tinymce/jscripts/tinymce4/tinymce.js | 31217 ++++++++++++++++ lib/tinymce/jscripts/tinymce4/tinymce.min.js | 10 + 315 files changed, 111290 insertions(+) create mode 100644 demo/index-mce4.html create mode 100644 lib/tinymce/jscripts/tinymce4/classes/AddOnManager.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/Compat.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/Editor.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/EditorCommands.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/EditorManager.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/EnterKey.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/Env.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ForceBlocks.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/Formatter.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/LegacyInput.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/Shortcuts.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/UndoManager.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/WindowManager.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/dom/ControlSelection.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/dom/DOMUtils.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/dom/DomQuery.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/dom/EventUtils.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/dom/Range.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/dom/RangeUtils.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/dom/ScriptLoader.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/dom/Selection.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/dom/Serializer.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/dom/Sizzle.jQuery.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/dom/Sizzle.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/dom/TreeWalker.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/dom/TridentSelection.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/html/DomParser.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/html/Entities.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/html/Node.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/html/SaxParser.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/html/Schema.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/html/Serializer.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/html/Styles.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/html/Writer.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/jquery.tinymce.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/AbsoluteLayout.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Button.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/ButtonGroup.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Checkbox.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/CheckboxGroup.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Collection.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/ColorButton.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/ComboBox.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Container.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Control.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/DomUtils.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/DragHelper.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/ElementPath.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Factory.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/FieldSet.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/FilePicker.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/FitLayout.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/FlexLayout.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/FloatPanel.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/FlowLayout.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Form.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/FormItem.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/FormatControls.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/GridLayout.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Iframe.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/KeyboardNavigation.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Label.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Layout.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/ListBox.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Menu.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/MenuBar.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/MenuButton.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/MenuItem.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/MessageBox.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Movable.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Panel.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/PanelButton.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Path.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Radio.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/RadioGroup.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Resizable.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/ResizeHandle.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Scrollable.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Selector.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Spacer.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/SplitButton.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/StackLayout.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/TabPanel.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/TextBox.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Throbber.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Toolbar.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Tooltip.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Widget.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/ui/Window.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/util/Class.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/util/JSON.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/util/JSONP.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/util/JSONRequest.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/util/LocalStorage.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/util/Observable.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/util/Quirks.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/util/Tools.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/util/URI.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/util/VK.js create mode 100644 lib/tinymce/jscripts/tinymce4/classes/util/XHR.js create mode 100644 lib/tinymce/jscripts/tinymce4/jquery.tinymce.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/langs/readme.md create mode 100644 lib/tinymce/jscripts/tinymce4/license.txt create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/advlist/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/advlist/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/anchor/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/anchor/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/autolink/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/autolink/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/autoresize/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/autoresize/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/autosave/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/autosave/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/bbcode/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/bbcode/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/charmap/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/charmap/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/chocobo/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/chocobo/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/code/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/code/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/compat3x/editable_selects.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/compat3x/form_utils.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/compat3x/mctabs.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/compat3x/tiny_mce_popup.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/compat3x/validate.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/contextmenu/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/contextmenu/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/directionality/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/directionality/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-cool.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-cry.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-embarassed.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-foot-in-mouth.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-frown.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-innocent.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-kiss.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-laughing.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-money-mouth.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-sealed.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-smile.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-surprised.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-tongue-out.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-undecided.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-wink.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-yell.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/emoticons/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/example/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/example/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/example_dependency/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/example_dependency/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/fullpage/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/fullpage/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/fullscreen/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/fullscreen/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/hr/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/hr/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/ice/css/ice.css create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/ice/img/accept.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/ice/img/ice-accept-change.png create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/ice/img/ice-accept.png create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/ice/img/ice-reject-change.png create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/ice/img/ice-reject.png create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/ice/img/ice-showchanges.png create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/ice/img/ice-togglechanges.png create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/ice/img/reject.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/ice/js/ice.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/css/searchreplace.css create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/editor_plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/js/searchreplace.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/langs/en_dlg.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/searchreplace.htm create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/image/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/image/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/insertdatetime/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/insertdatetime/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/layer/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/layer/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/legacyoutput/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/legacyoutput/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/link/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/link/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/lists/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/lists/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/media/moxieplayer.swf create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/media/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/media/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/nonbreaking/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/nonbreaking/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/noneditable/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/noneditable/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/pagebreak/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/pagebreak/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/paste/classes/Clipboard.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/paste/classes/Plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/paste/classes/Quirks.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/paste/classes/WordFilter.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/paste/plugin.dev.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/paste/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/paste/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/preview/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/preview/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/print/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/print/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/save/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/save/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/searchreplace/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/searchreplace/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/spellchecker/classes/DomTextMatcher.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/spellchecker/classes/Plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/spellchecker/plugin.dev.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/spellchecker/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/spellchecker/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/tabfocus/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/tabfocus/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/table/classes/CellSelection.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/table/classes/Plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/table/classes/Quirks.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/table/classes/TableGrid.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/table/plugin.dev.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/table/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/table/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/template/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/template/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/css/visualblocks.css create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/address.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/article.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/aside.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/blockquote.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/div.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/figure.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h1.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h2.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h3.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h4.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h5.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h6.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/hgroup.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/p.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/pre.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/section.gif create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualblocks/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualchars/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/visualchars/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/wordcount/plugin.js create mode 100644 lib/tinymce/jscripts/tinymce4/plugins/wordcount/plugin.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/AbsoluteLayout.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Animations.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Button.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/ButtonGroup.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Checkbox.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/ColorButton.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/ComboBox.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Container.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Content.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/FieldSet.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/FitLayout.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/FloatPanel.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/FlowLayout.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Icons.Ie7.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Icons.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Iframe.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Label.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/ListBox.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Menu.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/MenuBar.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/MenuButton.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/MenuItem.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Mixins.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Panel.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Path.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Radio.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Reset.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/ResizeHandle.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Scrollable.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Select.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Spacer.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/SplitButton.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/StackLayout.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/TabPanel.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/TextBox.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Throbber.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/TinyMCE.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/ToolTip.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Variables.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/Window.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/content.min.css create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.dev.svg create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.eot create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.svg create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.ttf create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.woff create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/readme.md create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/img/anchor.gif create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/img/loader.gif create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/img/object.gif create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/img/trans.gif create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/img/wline.gif create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/skin.classic.min.css create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/skin.ie7.min.css create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/skin.less create mode 100644 lib/tinymce/jscripts/tinymce4/skins/lightgray/skin.min.css create mode 100644 lib/tinymce/jscripts/tinymce4/themes/modern/theme.js create mode 100644 lib/tinymce/jscripts/tinymce4/themes/modern/theme.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/tinymce.dev.js create mode 100644 lib/tinymce/jscripts/tinymce4/tinymce.jquery.dev.js create mode 100644 lib/tinymce/jscripts/tinymce4/tinymce.jquery.js create mode 100644 lib/tinymce/jscripts/tinymce4/tinymce.jquery.min.js create mode 100644 lib/tinymce/jscripts/tinymce4/tinymce.js create mode 100644 lib/tinymce/jscripts/tinymce4/tinymce.min.js diff --git a/demo/index-mce4.html b/demo/index-mce4.html new file mode 100644 index 00000000..85f8c4cf --- /dev/null +++ b/demo/index-mce4.html @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

Ice Demo

+ + +
+
+ Set User: + +
+
+
+ +
+
+
+ + + +
+ + diff --git a/lib/tinymce/jscripts/tinymce4/classes/AddOnManager.js b/lib/tinymce/jscripts/tinymce4/classes/AddOnManager.js new file mode 100644 index 00000000..26534193 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/AddOnManager.js @@ -0,0 +1,370 @@ +/** + * AddOnManager.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles the loading of themes/plugins or other add-ons and their language packs. + * + * @class tinymce.AddOnManager + */ +define("tinymce/AddOnManager", [ + "tinymce/dom/ScriptLoader", + "tinymce/util/Tools" +], function(ScriptLoader, Tools) { + var each = Tools.each; + + function AddOnManager() { + var self = this; + + self.items = []; + self.urls = {}; + self.lookup = {}; + } + + AddOnManager.prototype = { + /** + * Returns the specified add on by the short name. + * + * @method get + * @param {String} name Add-on to look for. + * @return {tinymce.Theme/tinymce.Plugin} Theme or plugin add-on instance or undefined. + */ + get: function(name) { + if (this.lookup[name]) { + return this.lookup[name].instance; + } else { + return undefined; + } + }, + + dependencies: function(name) { + var result; + + if (this.lookup[name]) { + result = this.lookup[name].dependencies; + } + + return result || []; + }, + + /** + * Loads a language pack for the specified add-on. + * + * @method requireLangPack + * @param {String} name Short name of the add-on. + */ + requireLangPack: function(name) { + var settings = AddOnManager.settings; + + if (settings && settings.language && settings.language_load !== false) { + ScriptLoader.ScriptLoader.add(this.urls[name] + '/langs/' + settings.language + '.js'); + } + }, + + /** + * Adds a instance of the add-on by it's short name. + * + * @method add + * @param {String} id Short name/id for the add-on. + * @param {tinymce.Theme/tinymce.Plugin} addOn Theme or plugin to add. + * @return {tinymce.Theme/tinymce.Plugin} The same theme or plugin instance that got passed in. + * @example + * // Create a simple plugin + * tinymce.create('tinymce.plugins.TestPlugin', { + * TestPlugin: function(ed, url) { + * ed.on('click', function(e) { + * ed.windowManager.alert('Hello World!'); + * }); + * } + * }); + * + * // Register plugin using the add method + * tinymce.PluginManager.add('test', tinymce.plugins.TestPlugin); + * + * // Initialize TinyMCE + * tinymce.init({ + * ... + * plugins: '-test' // Init the plugin but don't try to load it + * }); + */ + add: function(id, addOn, dependencies) { + this.items.push(addOn); + this.lookup[id] = {instance: addOn, dependencies: dependencies}; + + return addOn; + }, + + createUrl: function(baseUrl, dep) { + if (typeof dep === "object") { + return dep; + } else { + return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix}; + } + }, + + /** + * Add a set of components that will make up the add-on. Using the url of the add-on name as the base url. + * This should be used in development mode. A new compressor/javascript munger process will ensure that the + * components are put together into the plugin.js file and compressed correctly. + * @param pluginName {String} name of the plugin to load scripts from (will be used to get the base url for the plugins). + * @param scripts {Array} Array containing the names of the scripts to load. + */ + addComponents: function(pluginName, scripts) { + var pluginUrl = this.urls[pluginName]; + + each(scripts, function(script) { + ScriptLoader.ScriptLoader.add(pluginUrl + "/" + script); + }); + }, + + /** + * Loads an add-on from a specific url. + * + * @method load + * @param {String} n Short name of the add-on that gets loaded. + * @param {String} u URL to the add-on that will get loaded. + * @param {function} cb Optional callback to execute ones the add-on is loaded. + * @param {Object} s Optional scope to execute the callback in. + * @example + * // Loads a plugin from an external URL + * tinymce.PluginManager.load('myplugin', '/some/dir/someplugin/plugin.js'); + * + * // Initialize TinyMCE + * tinymce.init({ + * ... + * plugins: '-myplugin' // Don't try to load it again + * }); + */ + load: function(n, u, cb, s) { + var t = this, url = u; + + function loadDependencies() { + var dependencies = t.dependencies(n); + + 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(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 = AddOnManager.baseURL + '/' + url; + } + + t.urls[n] = url.substring(0, url.lastIndexOf('/')); + + if (t.lookup[n]) { + loadDependencies(); + } else { + ScriptLoader.ScriptLoader.add(url, loadDependencies, s); + } + } + }; + + AddOnManager.PluginManager = new AddOnManager(); + AddOnManager.ThemeManager = new AddOnManager(); + + return AddOnManager; +}); + +/** + * TinyMCE theme class. + * + * @class tinymce.Theme + */ + +/** + * Initializes the theme. + * + * @method init + * @param {tinymce.Editor} editor Editor instance that created the theme instance. + * @param {String} url Absolute URL where the theme is located. + */ + +/** + * Meta info method, this method gets executed when TinyMCE wants to present + * information about the theme for example in the about/help dialog. + * + * @method getInfo + * @return {Object} Returns an object with meta information about the theme the current items are + * longname, author, authorurl, infourl and version. + */ + +/** + * This method is responsible for rendering/generating the overall user interface with toolbars, buttons, iframe containers etc. + * + * @method renderUI + * @param {Object} obj Object parameter containing the targetNode DOM node that will be replaced visually with an editor instance. + * @return {Object} an object with items like iframeContainer, editorContainer, sizeContainer, deltaWidth, deltaHeight. + */ + +/** + * Plugin base class, this is a pseudo class that describes how a plugin is to be created for TinyMCE. The methods below are all optional. + * + * @class tinymce.Plugin + * @example + * // Create a new plugin class + * tinymce.create('tinymce.plugins.ExamplePlugin', { + * init: function(ed, url) { + * // Register an example button + * ed.addButton('example', { + * title: 'example.desc', + * onclick: function() { + * // Display an alert when the user clicks the button + * ed.windowManager.alert('Hello world!'); + * }, + * 'class': 'bold' // Use the bold icon from the theme + * }); + * } + * }); + * + * // Register plugin with a short name + * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); + * + * // Initialize TinyMCE with the new plugin and button + * tinymce.init({ + * ... + * plugins: '-example', // - means TinyMCE will not try to load it + * theme_advanced_buttons1: 'example' // Add the new example button to the toolbar + * }); + */ + +/** + * Initialization function for the plugin. This will be called when the plugin is created. + * + * @method init + * @param {tinymce.Editor} editor Editor instance that created the plugin instance. + * @param {String} url Absolute URL where the plugin is located. + * @example + * // Creates a new plugin class + * tinymce.create('tinymce.plugins.ExamplePlugin', { + * init: function(ed, url) { + * // Register the command so that it can be invoked by using tinymce.activeEditor.execCommand('mceExample'); + * ed.addCommand('mceExample', function() { + * ed.windowManager.open({ + * file: url + '/dialog.htm', + * width: 320 + ed.getLang('example.delta_width', 0), + * height: 120 + ed.getLang('example.delta_height', 0), + * inline: 1 + * }, { + * plugin_url: url, // Plugin absolute URL + * some_custom_arg: 'custom arg' // Custom argument + * }); + * }); + * + * // Register example button + * ed.addButton('example', { + * title: 'example.desc', + * cmd: 'mceExample', + * image: url + '/img/example.gif' + * }); + * + * // Add a node change handler, selects the button in the UI when a image is selected + * ed.on('NodeChange', function(e) { + * cm.setActive('example', e.element.nodeName == 'IMG'); + * }); + * } + * }); + * + * // Register plugin + * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); + */ + +/** + * Meta info method, this method gets executed when TinyMCE wants to present information about the plugin + * for example in the about/help dialog. + * + * @method getInfo + * @return {Object} Returns an object with meta information about the plugin the current items are longname, + * author, authorurl, infourl and version. + * @example + * // Creates a new plugin class + * tinymce.create('tinymce.plugins.ExamplePlugin', { + * // Meta info method + * getInfo: function() { + * return { + * longname: 'Example plugin', + * author: 'Some author', + * authorurl: 'http://www.tinymce.com', + * infourl: 'http://www.tinymce.com/wiki.php/Plugin:Plugins/example', + * version: "1.0" + * }; + * } + * }); + * + * // Register plugin + * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); + * + * // Initialize TinyMCE with the new plugin + * tinymce.init({ + * ... + * plugins: '-example' // - means TinyMCE will not try to load it + * }); + */ + +/** + * Gets called when a new control instance is created. + * + * @method createControl + * @param {String} name Control name to create for example "mylistbox" + * @param {tinymce.ControlManager} controlman Control manager/factory to use to create the control. + * @return {tinymce.ui.Control} Returns a new control instance or null. + * @example + * // Creates a new plugin class + * tinymce.create('tinymce.plugins.ExamplePlugin', { + * createControl: function(n, cm) { + * switch (n) { + * case 'mylistbox': + * var mlb = cm.createListBox('mylistbox', { + * title: 'My list box', + * onselect: function(v) { + * tinymce.activeEditor.windowManager.alert('Value selected:' + v); + * } + * }); + * + * // Add some values to the list box + * mlb.add('Some item 1', 'val1'); + * mlb.add('some item 2', 'val2'); + * mlb.add('some item 3', 'val3'); + * + * // Return the new listbox instance + * return mlb; + * } + * + * return null; + * } + * }); + * + * // Register plugin + * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); + * + * // Initialize TinyMCE with the new plugin and button + * tinymce.init({ + * ... + * plugins: '-example', // - means TinyMCE will not try to load it + * theme_advanced_buttons1: 'mylistbox' // Add the new mylistbox control to the toolbar + * }); + */ diff --git a/lib/tinymce/jscripts/tinymce4/classes/Compat.js b/lib/tinymce/jscripts/tinymce4/classes/Compat.js new file mode 100644 index 00000000..b0511f02 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/Compat.js @@ -0,0 +1,41 @@ +/** + * Compat.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Adds various compatibility items. + */ +define("tinymce/Compat", [ + "tinymce/dom/DOMUtils", + "tinymce/dom/EventUtils", + "tinymce/dom/ScriptLoader", + "tinymce/AddOnManager", + "tinymce/util/Tools", + "tinymce/Env" +], function(DOMUtils, EventUtils, ScriptLoader, AddOnManager, Tools, Env) { + var tinymce = window.tinymce; + + tinymce.DOM = DOMUtils.DOM; + tinymce.ScriptLoader = ScriptLoader.ScriptLoader; + tinymce.PluginManager = AddOnManager.PluginManager; + tinymce.ThemeManager = AddOnManager.ThemeManager; + + tinymce.dom = tinymce.dom || {}; + tinymce.dom.Event = EventUtils.Event; + + Tools.each(Tools, function(func, key) { + tinymce[key] = func; + }); + + Tools.each('isOpera isWebKit isIE isGecko isMac'.split(' '), function(name) { + tinymce[name] = Env[name.substr(2).toLowerCase()]; + }); + + return {}; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/Editor.js b/lib/tinymce/jscripts/tinymce4/classes/Editor.js new file mode 100644 index 00000000..850401d6 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/Editor.js @@ -0,0 +1,2064 @@ +/** + * Editor.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint scripturl:true */ + +/** + * This class contains the core logic for a TinyMCE editor. + * + * @class tinymce.Editor + * @example + * // Add a class to all paragraphs in the editor. + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass'); + * + * // Gets the current editors selection as text + * tinymce.activeEditor.selection.getContent({format: 'text'}); + * + * // Creates a new editor instance + * var ed = new tinymce.Editor('textareaid', { + * some_setting: 1 + * }, tinymce.EditorManager); + * + * // Select each item the user clicks on + * ed.on('click', function(e) { + * ed.selection.select(e.target); + * }); + * + * ed.render(); + */ +define("tinymce/Editor", [ + "tinymce/dom/DOMUtils", + "tinymce/AddOnManager", + "tinymce/html/Node", + "tinymce/dom/Serializer", + "tinymce/html/Serializer", + "tinymce/dom/Selection", + "tinymce/Formatter", + "tinymce/UndoManager", + "tinymce/EnterKey", + "tinymce/ForceBlocks", + "tinymce/EditorCommands", + "tinymce/util/URI", + "tinymce/dom/ScriptLoader", + "tinymce/dom/EventUtils", + "tinymce/WindowManager", + "tinymce/html/Schema", + "tinymce/html/DomParser", + "tinymce/util/Quirks", + "tinymce/Env", + "tinymce/util/Tools", + "tinymce/util/Observable", + "tinymce/Shortcuts" +], function( + DOMUtils, AddOnManager, Node, DomSerializer, Serializer, + Selection, Formatter, UndoManager, EnterKey, ForceBlocks, EditorCommands, + URI, ScriptLoader, EventUtils, WindowManager, + Schema, DomParser, Quirks, Env, Tools, Observable, Shortcuts +) { + // Shorten these names + var DOM = DOMUtils.DOM, ThemeManager = AddOnManager.ThemeManager, PluginManager = AddOnManager.PluginManager; + var extend = Tools.extend, each = Tools.each, explode = Tools.explode; + var inArray = Tools.inArray, trim = Tools.trim, resolve = Tools.resolve; + var Event = EventUtils.Event; + var isGecko = Env.gecko, isIE = Env.ie, isOpera = Env.opera; + + function getEventTarget(editor, eventName) { + // Need to bind mousedown/mouseup etc to document not body in iframe mode + // Since the user might click on the HTML element not the BODY + if (!editor.inline && /^mouse|click|contextmenu/.test(eventName)) { + return editor.getDoc(); + } + + return editor.getBody(); + } + + /** + * Constructs a editor instance by id. + * + * @constructor + * @method Editor + * @param {String} id Unique id for the editor. + * @param {Object} settings Settings for the editor. + * @param {tinymce.EditorManager} editorManager EditorManager instance. + * @author Moxiecode + */ + function Editor(id, settings, editorManager) { + var self = this, documentBaseUrl, baseUri; + + documentBaseUrl = self.documentBaseUrl = editorManager.documentBaseURL; + baseUri = editorManager.baseURI; + + /** + * Name/value collection with editor settings. + * + * @property settings + * @type Object + * @example + * // Get the value of the theme setting + * tinymce.activeEditor.windowManager.alert("You are using the " + tinymce.activeEditor.settings.theme + " theme"); + */ + self.settings = settings = extend({ + id: id, + theme: 'modern', + delta_width: 0, + delta_height: 0, + popup_css: '', + plugins: '', + document_base_url: 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, + doctype: '', + visual: true, + font_size_style_values: 'xx-small,x-small,small,medium,large,x-large,xx-large', + + // See: http://www.w3.org/TR/CSS2/fonts.html#propdef-font-size + font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%', + apply_source_formatting: true, + directionality: 'ltr', + forced_root_block: 'p', + hidden_input: true, + padd_empty_editor: true, + render_ui: true, + indentation: '30px', + 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,option,optgroup,datalist', + 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,option,optgroup,datalist', + validate: true, + entity_encoding: 'named', + url_converter: self.convertURL, + url_converter_scope: self, + ie7_compat: true + }, settings); + + // TODO: Fix this + AddOnManager.settings = settings; + AddOnManager.baseURL = editorManager.baseURL; + + /** + * Editor instance id, normally the same as the div/textarea that was replaced. + * + * @property id + * @type String + */ + self.id = settings.id = id; + + /** + * State to force the editor to return false on a isDirty call. + * + * @property isNotDirty + * @type Boolean + * @example + * function ajaxSave() { + * var ed = tinymce.get('elm1'); + * + * // Save contents using some XHR call + * alert(ed.getContent()); + * + * ed.isNotDirty = 1; // Force not dirty state + * } + */ + self.isNotDirty = false; + + /** + * Name/Value object containting plugin instances. + * + * @property plugins + * @type Object + * @example + * // Execute a method inside a plugin directly + * tinymce.activeEditor.plugins.someplugin.someMethod(); + */ + self.plugins = {}; + + /** + * URI object to document configured for the TinyMCE instance. + * + * @property documentBaseURI + * @type tinymce.util.URI + * @example + * // Get relative URL from the location of document_base_url + * tinymce.activeEditor.documentBaseURI.toRelative('/somedir/somefile.htm'); + * + * // Get absolute URL from the location of document_base_url + * tinymce.activeEditor.documentBaseURI.toAbsolute('somefile.htm'); + */ + self.documentBaseURI = new URI(settings.document_base_url || documentBaseUrl, { + base_uri: baseUri + }); + + /** + * URI object to current document that holds the TinyMCE editor instance. + * + * @property baseURI + * @type tinymce.util.URI + * @example + * // Get relative URL from the location of the API + * tinymce.activeEditor.baseURI.toRelative('/somedir/somefile.htm'); + * + * // Get absolute URL from the location of the API + * tinymce.activeEditor.baseURI.toAbsolute('somefile.htm'); + */ + self.baseURI = baseUri; + + /** + * Array with CSS files to load into the iframe. + * + * @property contentCSS + * @type Array + */ + self.contentCSS = []; + + /** + * Array of CSS styles to add to head of document when the editor loads. + * + * @property contentStyles + * @type Array + */ + self.contentStyles = []; + + // Creates all events like onClick, onSetContent etc see Editor.Events.js for the actual logic + self.shortcuts = new Shortcuts(self); + + // Internal command handler objects + self.execCommands = {}; + self.queryStateCommands = {}; + self.queryValueCommands = {}; + + self.suffix = editorManager.suffix; + self.editorManager = editorManager; + self.inline = settings.inline; + + // Call setup + self.execCallback('setup', self); + } + + Editor.prototype = { + /** + * Renderes the editor/adds it to the page. + * + * @method render + */ + render: function() { + var self = this, settings = self.settings, id = self.id, suffix = self.suffix; + + // Page is not loaded yet, wait for it + if (!Event.domLoaded) { + DOM.bind(window, 'ready', function() { + self.render(); + }); + return; + } + + self.editorManager.settings = settings; + + // Element not found, then skip initialization + if (!self.getElement()) { + return; + } + + // No editable support old iOS versions etc + if (!Env.contentEditable) { + return; + } + + // Hide target element early to prevent content flashing + if (!settings.inline) { + self.orgVisibility = self.getElement().style.visibility; + self.getElement().style.visibility = 'hidden'; + } else { + self.inline = true; + } + + var form = self.getElement().form || DOM.getParent(id, 'form'); + if (form) { + self.formElement = form; + + // Add hidden input for non input elements inside form elements + if (settings.hidden_input && !/TEXTAREA|INPUT/i.test(self.getElement().nodeName)) { + DOM.insertAfter(DOM.create('input', {type: 'hidden', name: id}), id); + } + + // Pass submit/reset from form to editor instance + self.formEventDelegate = function(e) { + self.fire(e.type, e); + }; + + DOM.bind(form, 'submit reset', self.formEventDelegate); + + // Reset contents in editor when the form is reset + self.on('reset', function() { + self.setContent(self.startContent, {format: 'raw'}); + }); + + // Check page uses id="submit" or name="submit" for it's submit button + if (settings.submit_patch && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) { + form._mceOldSubmit = form.submit; + form.submit = function() { + self.editorManager.triggerSave(); + self.isNotDirty = 1; + + return form._mceOldSubmit(form); + }; + } + } + + /** + * Window manager reference, use this to open new windows and dialogs. + * + * @property windowManager + * @type tinymce.WindowManager + * @example + * // Shows an alert message + * tinymce.activeEditor.windowManager.alert('Hello world!'); + * + * // Opens a new dialog with the file.htm file and the size 320x240 + * // It also adds a custom parameter this can be retrieved by using tinyMCEPopup.getWindowArg inside the dialog. + * tinymce.activeEditor.windowManager.open({ + * url: 'file.htm', + * width: 320, + * height: 240 + * }, { + * custom_param: 1 + * }); + */ + self.windowManager = new WindowManager(self); + + if (settings.encoding == 'xml') { + self.on('GetContent', function(e) { + if (e.save) { + e.content = DOM.encode(e.content); + } + }); + } + + if (settings.add_form_submit_trigger) { + self.on('submit', function() { + if (self.initialized) { + self.save(); + self.isNotDirty = 1; + } + }); + } + + if (settings.add_unload_trigger) { + self._beforeUnload = function() { + if (self.initialized && !self.destroyed && !self.isHidden()) { + self.save({format: 'raw', no_events: true}); + } + }; + + self.editorManager.on('BeforeUnload', self._beforeUnload); + } + + // Load scripts + function loadScripts() { + var scriptLoader = ScriptLoader.ScriptLoader; + + if (settings.language) { + scriptLoader.add(self.editorManager.baseURL + '/langs/' + settings.language + '.js'); + } + + if (settings.theme && typeof settings.theme != "function" && + settings.theme.charAt(0) != '-' && !ThemeManager.urls[settings.theme]) { + ThemeManager.load(settings.theme, 'themes/' + settings.theme + '/theme' + suffix + '.js'); + } + + if (Tools.isArray(settings.plugins)) { + settings.plugins = settings.plugins.join(' '); + } + + each(settings.plugins.split(/[ ,]/), function(plugin) { + plugin = trim(plugin); + + if (plugin && !PluginManager.urls[plugin]) { + if (plugin.charAt(0) == '-') { + plugin = plugin.substr(1, plugin.length); + + var dependencies = PluginManager.dependencies(plugin); + + each(dependencies, function(dep) { + var defaultSettings = { + prefix:'plugins/', + resource: dep, + suffix:'/plugin' + suffix + '.js' + }; + + dep = PluginManager.createUrl(defaultSettings, dep); + PluginManager.load(dep.resource, dep); + }); + } else { + PluginManager.load(plugin, { + prefix: 'plugins/', + resource: plugin, + suffix: '/plugin' + suffix + '.js' + }); + } + } + }); + + scriptLoader.loadQueue(function() { + if (!self.removed) { + self.init(); + } + }); + } + + loadScripts(); + }, + + /** + * Initializes the editor this will be called automatically when + * all plugins/themes and language packs are loaded by the rendered method. + * This method will setup the iframe and create the theme and plugin instances. + * + * @method init + */ + init: function() { + var self = this, settings = self.settings, elm = self.getElement(); + var w, h, minHeight, n, o, url, bodyId, bodyClass, re, i, initializedPlugins = []; + + self.editorManager.add(self); + + settings.aria_label = settings.aria_label || DOM.getAttrib(elm, 'aria-label', self.getLang('aria.rich_text_area')); + + /** + * Reference to the theme instance that was used to generate the UI. + * + * @property theme + * @type tinymce.Theme + * @example + * // Executes a method on the theme directly + * tinymce.activeEditor.theme.someMethod(); + */ + if (settings.theme) { + if (typeof settings.theme != "function") { + settings.theme = settings.theme.replace(/-/, ''); + o = ThemeManager.get(settings.theme); + self.theme = new o(self, ThemeManager.urls[settings.theme]); + + if (self.theme.init) { + self.theme.init(self, ThemeManager.urls[settings.theme] || self.documentBaseUrl.replace(/\/$/, '')); + } + } else { + self.theme = settings.theme; + } + } + + function initPlugin(plugin) { + var constr = PluginManager.get(plugin), url, pluginInstance; + + url = PluginManager.urls[plugin] || self.documentBaseUrl.replace(/\/$/, ''); + plugin = trim(plugin); + if (constr && inArray(initializedPlugins, plugin) === -1) { + each(PluginManager.dependencies(plugin), function(dep){ + initPlugin(dep); + }); + + pluginInstance = new constr(self, url); + + self.plugins[plugin] = pluginInstance; + + if (pluginInstance.init) { + pluginInstance.init(self, url); + initializedPlugins.push(plugin); + } + } + } + + // Create all plugins + each(settings.plugins.replace(/\-/g, '').split(/[ ,]/), initPlugin); + + // Enables users to override the control factory + self.fire('BeforeRenderUI'); + + // Measure box + if (settings.render_ui && self.theme) { + self.orgDisplay = elm.style.display; + + if (typeof settings.theme != "function") { + w = settings.width || elm.style.width || elm.offsetWidth; + h = settings.height || elm.style.height || elm.offsetHeight; + minHeight = settings.min_height || 100; + 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), minHeight); + } + + // Render UI + o = self.theme.renderUI({ + targetNode: elm, + width: w, + height: h, + deltaWidth: settings.delta_width, + deltaHeight: settings.delta_height + }); + + // Resize editor + if (!settings.content_editable) { + DOM.setStyles(o.sizeContainer || o.editorContainer, { + wi2dth: w, + // TODO: Fix this + h2eight: h + }); + + h = (o.iframeHeight || h) + (typeof(h) == 'number' ? (o.deltaHeight || 0) : ''); + if (h < minHeight) { + h = minHeight; + } + } + } else { + o = settings.theme(self, elm); + + // Convert element type to id:s + if (o.editorContainer.nodeType) { + o.editorContainer = o.editorContainer.id = o.editorContainer.id || self.id + "_parent"; + } + + // Convert element type to id:s + if (o.iframeContainer.nodeType) { + o.iframeContainer = o.iframeContainer.id = o.iframeContainer.id || self.id + "_iframecontainer"; + } + + // Use specified iframe height or the targets offsetHeight + h = o.iframeHeight || elm.offsetHeight; + } + + self.editorContainer = o.editorContainer; + } + + // Load specified content CSS last + if (settings.content_css) { + each(explode(settings.content_css), function(u) { + self.contentCSS.push(self.documentBaseURI.toAbsolute(u)); + }); + } + + // Load specified content CSS last + if (settings.content_style) { + self.contentStyles.push(settings.content_style); + } + + // Content editable mode ends here + if (settings.content_editable) { + elm = n = o = null; // Fix IE leak + return self.initContentBody(); + } + + // User specified a document.domain value + if (document.domain && location.hostname != document.domain) { + self.editorManager.relaxedDomain = document.domain; + } + + self.iframeHTML = settings.doctype + ''; + + // 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 (settings.document_base_url != self.documentBaseUrl) { + self.iframeHTML += ''; + } + + // IE8 doesn't support carets behind images setting ie7_compat would force IE8+ to run in IE7 compat mode. + if (!Env.caretAfter && settings.ie7_compat) { + self.iframeHTML += ''; + } + + self.iframeHTML += ''; + + // Load the CSS by injecting them into the HTML this will reduce "flicker" + for (i = 0; i < self.contentCSS.length; i++) { + self.iframeHTML += ''; + } + + self.contentCSS = []; + + bodyId = settings.body_id || 'tinymce'; + if (bodyId.indexOf('=') != -1) { + bodyId = self.getParam('body_id', '', 'hash'); + bodyId = bodyId[self.id] || bodyId; + } + + bodyClass = settings.body_class || ''; + if (bodyClass.indexOf('=') != -1) { + bodyClass = self.getParam('body_class', '', 'hash'); + bodyClass = bodyClass[self.id] || ''; + } + + self.iframeHTML += '
'; + + // Domain relaxing enabled, then set document domain + // TODO: Fix this old stuff + if (self.editorManager.relaxedDomain && (isIE || (isOpera && parseFloat(window.opera.version()) < 11))) { + // We need to write the contents here in IE since multiple writes messes up refresh button and back button + url = 'javascript:(function(){document.open();document.domain="' + document.domain + '";' + + 'var ed = window.parent.tinymce.get("' + self.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: self.id + "_ifr", + src: url || 'javascript:""', // Workaround for HTTPS warning in IE6/7 + frameBorder: '0', + allowTransparency: "true", + title: self.editorManager.translate( + "Rich Text Area. Press ALT-F9 for menu. " + + "Press ALT-F10 for toolbar. Press ALT-0 for help" + ), + style: { + width: '100%', + height: h, + display: 'block' // Important for Gecko to render the iframe correctly + } + }); + + self.contentAreaContainer = o.iframeContainer; + + if (o.editorContainer) { + DOM.get(o.editorContainer).style.display = self.orgDisplay; + } + + DOM.get(self.id).style.display = 'none'; + DOM.setAttrib(self.id, 'aria-hidden', true); + + if (!self.editorManager.relaxedDomain || !url) { + self.initContentBody(); + } + + elm = n = o = null; // Cleanup + }, + + /** + * This method get called by the init method ones the iframe is loaded. + * It will fill the iframe with contents, setups DOM and selection objects for the iframe. + * + * @method initContentBody + * @private + */ + initContentBody: function() { + var self = this, settings = self.settings, targetElm = DOM.get(self.id), doc = self.getDoc(), body, contentCssText; + + // Restore visibility on target element + self.getElement().style.visibility = self.orgVisibility; + + // Setup iframe body + if ((!isIE || !self.editorManager.relaxedDomain) && !settings.content_editable) { + doc.open(); + doc.write(self.iframeHTML); + doc.close(); + + if (self.editorManager.relaxedDomain) { + doc.domain = self.editorManager.relaxedDomain; + } + } + + if (settings.content_editable) { + DOM.addClass(targetElm, 'mce-content-body'); + targetElm.tabIndex = -1; + 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; + + // TODO: Fix this + settings.root_name = targetElm.nodeName.toLowerCase(); + } + + // 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; + + /** + * Schema instance, enables you to validate elements and it's children. + * + * @property schema + * @type tinymce.html.Schema + */ + self.schema = new Schema(settings); + + /** + * DOM instance for the editor. + * + * @property dom + * @type tinymce.dom.DOMUtils + * @example + * // Adds a class to all paragraphs within the editor + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass'); + */ + self.dom = new 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, + onSetAttrib: function(e) { + self.fire('SetAttrib', e); + } + }); + + /** + * HTML parser will be used when contents is inserted into the editor. + * + * @property parser + * @type tinymce.html.DomParser + */ + self.parser = new 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) { + 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) { + 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) { + var i = nodes.length, node, nonEmptyElements = self.schema.getNonEmptyElements(); + + while (i--) { + node = nodes[i]; + + if (node.isEmpty(nonEmptyElements)) { + node.empty().append(new Node('br', 1)).shortEnded = true; + } + } + }); + + /** + * DOM serializer for the editor. Will be used when contents is extracted from the editor. + * + * @property serializer + * @type tinymce.dom.Serializer + * @example + * // Serializes the first paragraph in the editor into a string + * tinymce.activeEditor.serializer.serialize(tinymce.activeEditor.dom.select('p')[0]); + */ + self.serializer = new DomSerializer(settings, self); + + /** + * Selection instance for the editor. + * + * @property selection + * @type tinymce.dom.Selection + * @example + * // Sets some contents to the current selection in the editor + * tinymce.activeEditor.selection.setContent('Some contents'); + * + * // Gets the current selection + * alert(tinymce.activeEditor.selection.getContent()); + * + * // Selects the first paragraph found + * tinymce.activeEditor.selection.select(tinymce.activeEditor.dom.select('p')[0]); + */ + self.selection = new Selection(self.dom, self.getWin(), self.serializer, self); + + /** + * Formatter instance. + * + * @property formatter + * @type tinymce.Formatter + */ + self.formatter = new Formatter(self); + + /** + * Undo manager instance, responsible for handling undo levels. + * + * @property undoManager + * @type tinymce.UndoManager + * @example + * // Undoes the last modification to the editor + * tinymce.activeEditor.undoManager.undo(); + */ + self.undoManager = new UndoManager(self); + + self.forceBlocks = new ForceBlocks(self); + self.enterKey = new EnterKey(self); + self.editorCommands = new EditorCommands(self); + + self.fire('PreInit'); + + if (!settings.browser_spellcheck && !settings.gecko_spellcheck) { + doc.body.spellcheck = false; + } + + self.fire('PostRender'); + + self.quirks = Quirks(self); + + if (settings.directionality) { + body.dir = settings.directionality; + } + + if (settings.nowrap) { + body.style.whiteSpace = "nowrap"; + } + + if (settings.protect) { + self.on('BeforeSetContent', function(e) { + each(settings.protect, function(pattern) { + e.content = e.content.replace(pattern, function(str) { + return ''; + }); + }); + }); + } + + self.on('SetContent', function() { + self.addVisual(self.getBody()); + }); + + // Remove empty contents + if (settings.padd_empty_editor) { + self.on('PostProcess', function(e) { + e.content = e.content.replace(/^(]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
[\r\n]*)$/, ''); + }); + } + + self.load({initial: true, format: 'html'}); + self.startContent = self.getContent({format: 'raw'}); + + /** + * Is set to true after the editor instance has been initialized + * + * @property initialized + * @type Boolean + * @example + * function isEditorInitialized(editor) { + * return editor && editor.initialized; + * } + */ + self.initialized = true; + + each(self._pendingNativeEvents, function(name) { + self.dom.bind(getEventTarget(self, name), name, function(e) { + self.fire(e.type, e); + }); + }); + + self.fire('init'); + self.focus(true); + self.nodeChanged({initial: true}); + self.execCallback('init_instance_callback', self); + + // Add editor specific CSS styles + if (self.contentStyles.length > 0) { + contentCssText = ''; + + each(self.contentStyles, function(style) { + contentCssText += style + "\r\n"; + }); + + self.dom.addStyle(contentCssText); + } + + // 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 = self.editorManager.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; + }, + + /** + * Focuses/activates the editor. This will set this editor as the activeEditor in the tinymce collection + * it will also place DOM focus inside the editor. + * + * @method focus + * @param {Boolean} skip_focus Skip DOM focus. Just set is as the active editor. + */ + focus: function(skip_focus) { + var oed, self = this, selection = self.selection, contentEditable = self.settings.content_editable, rng; + var controlElm, doc = self.getDoc(), body; + + if (!skip_focus) { + if ((rng = selection.lastRng)) { + selection.lastRng = null; + selection.setRng(rng); + self.nodeChanged(); + } + + // Get selected control element + rng = selection.getRng(); + if (rng.item) { + controlElm = rng.item(0); + } + + self._refreshContentEditable(); + + // Focus the window iframe + if (!contentEditable) { + self.getWin().focus(); + } + + // Focus the body as well since it's contentEditable + if (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) { + rng = doc.body.createControlRange(); + rng.addElement(controlElm); + rng.select(); + } + } + + if (self.editorManager.activeEditor != self) { + if ((oed = self.editorManager.activeEditor)) { + oed.fire('deactivate', {relatedTarget: self}); + } + + self.fire('activate', {relatedTarget: oed}); + } + + self.editorManager.activeEditor = self; + }, + + /** + * Executes a legacy callback. This method is useful to call old 2.x option callbacks. + * There new event model is a better way to add callback so this method might be removed in the future. + * + * @method execCallback + * @param {String} name Name of the callback to execute. + * @return {Object} Return value passed from callback function. + */ + execCallback: function(name) { + var self = this, callback = self.settings[name], scope; + + if (!callback) { + return; + } + + // Look through lookup + if (self.callbackLookup && (scope = self.callbackLookup[name])) { + callback = scope.func; + scope = scope.scope; + } + + if (typeof(callback) === 'string') { + scope = callback.replace(/\.\w+$/, ''); + scope = scope ? resolve(scope) : 0; + callback = resolve(callback); + self.callbackLookup = self.callbackLookup || {}; + self.callbackLookup[name] = {func: callback, scope: scope}; + } + + return callback.apply(scope || self, Array.prototype.slice.call(arguments, 1)); + }, + + /** + * Translates the specified string by replacing variables with language pack items it will also check if there is + * a key mathcin the input. + * + * @method translate + * @param {String} text String to translate by the language pack data. + * @return {String} Translated string. + */ + translate: function(text) { + var lang = this.settings.language || 'en', i18n = this.editorManager.i18n; + + if (!text) { + return ''; + } + + return i18n[lang + '.' + text] || text.replace(/\{\#([^\}]+)\}/g, function(a, b) { + return i18n[lang + '.' + b] || '{#' + b + '}'; + }); + }, + + /** + * Returns a language pack item by name/key. + * + * @method getLang + * @param {String} name Name/key to get from the language pack. + * @param {String} defaultVal Optional default value to retrive. + */ + getLang: function(name, defaultVal) { + return ( + this.editorManager.i18n[(this.settings.language || 'en') + '.' + name] || + (defaultVal !== undefined ? defaultVal : '{#' + name + '}') + ); + }, + + /** + * Returns a configuration parameter by name. + * + * @method getParam + * @param {String} name Configruation parameter to retrive. + * @param {String} defaultVal Optional default value to return. + * @param {String} type Optional type parameter. + * @return {String} Configuration parameter value or default value. + * @example + * // Returns a specific config value from the currently active editor + * var someval = tinymce.activeEditor.getParam('myvalue'); + * + * // Returns a specific config value from a specific editor instance by id + * var someval2 = tinymce.get('my_editor').getParam('myvalue'); + */ + getParam: function(name, defaultVal, type) { + var value = name in this.settings ? this.settings[name] : defaultVal, output; + + if (type === 'hash') { + output = {}; + + if (typeof(value) === 'string') { + each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function(value) { + value = value.split('='); + + if (value.length > 1) { + output[trim(value[0])] = trim(value[1]); + } else { + output[trim(value[0])] = trim(value); + } + }); + } else { + output = value; + } + + return output; + } + + return value; + }, + + /** + * Distpaches out a onNodeChange event to all observers. This method should be called when you + * need to update the UI states or element path etc. + * + * @method nodeChanged + */ + nodeChanged: function() { + var self = this, selection = self.selection, node, parents, root; + + // Fix for bug #1896577 it seems that this can not be fired while the editor is loading + if (self.initialized && !self.settings.disable_nodechange) { + // Get start node + root = self.getBody(); + node = selection.getStart() || root; + node = isIE && node.ownerDocument != self.getDoc() ? self.getBody() : node; // Fix for IE initial state + + // Edge case for

|

+ if (node.nodeName == 'IMG' && selection.isCollapsed()) { + node = node.parentNode; + } + + // Get parents and add them to object + parents = []; + self.dom.getParent(node, function(node) { + if (node === root) { + return true; + } + + parents.push(node); + }); + + self.fire('NodeChange', {element: node, parents: parents}); + } + }, + + /** + * Adds a button that later gets created by the ControlManager. This is a shorter and easier method + * of adding buttons without the need to deal with the ControlManager directly. But it's also less + * powerfull if you need more control use the ControlManagers factory methods instead. + * + * @method addButton + * @param {String} name Button name to add. + * @param {Object} settings Settings object with title, cmd etc. + * @example + * // Adds a custom button to the editor and when a user clicks the button it will open + * // an alert box with the selected contents as plain text. + * tinymce.init({ + * ... + * + * theme_advanced_buttons1: 'example,..' + * + * setup: function(ed) { + * // Register example button + * ed.addButton('example', { + * title: 'example.desc', + * image: '../js/tinymce/plugins/example/img/example.gif', + * onclick: function() { + * ed.windowManager.alert('Hello world!! Selection: ' + ed.selection.getContent({format: 'text'})); + * } + * }); + * } + * }); + */ + addButton: function(name, settings) { + var self = this; + + if (settings.cmd) { + settings.onclick = function() { + self.execCommand(settings.cmd); + }; + } + + self.buttons = self.buttons || {}; + settings.tooltip = settings.tooltip || settings.title; + settings.icon = settings.icon || (settings.icon !== false ? name : false); + self.buttons[name] = settings; + }, + + addMenuItem: function(name, settings) { + var self = this; + + if (settings.cmd) { + settings.onclick = function() { + self.execCommand(settings.cmd); + }; + } + + self.menuItems = self.menuItems || {}; + self.menuItems[name] = settings; + }, + + /** + * Adds a custom command to the editor, you can also override existing commands with this method. + * The command that you add can be executed with execCommand. + * + * @method addCommand + * @param {String} name Command name to add/override. + * @param {addCommandCallback} callback Function to execute when the command occurs. + * @param {Object} scope Optional scope to execute the function in. + * @example + * // Adds a custom command that later can be executed using execCommand + * tinymce.init({ + * ... + * + * setup: function(ed) { + * // Register example command + * ed.addCommand('mycommand', function(ui, v) { + * ed.windowManager.alert('Hello world!! Selection: ' + ed.selection.getContent({format: 'text'})); + * }); + * } + * }); + */ + addCommand: function(name, callback, scope) { + /** + * Callback function that gets called when a command is executed. + * + * @callback addCommandCallback + * @param {Boolean} ui Display UI state true/false. + * @param {Object} value Optional value for command. + * @return {Boolean} True/false state if the command was handled or not. + */ + this.execCommands[name] = {func: callback, scope: scope || this}; + }, + + /** + * Adds a custom query state command to the editor, you can also override existing commands with this method. + * The command that you add can be executed with queryCommandState function. + * + * @method addQueryStateHandler + * @param {String} name Command name to add/override. + * @param {addQueryStateHandlerCallback} callback Function to execute when the command state retrival occurs. + * @param {Object} scope Optional scope to execute the function in. + */ + addQueryStateHandler: function(name, callback, scope) { + /** + * Callback function that gets called when a queryCommandState is executed. + * + * @callback addQueryStateHandlerCallback + * @return {Boolean} True/false state if the command is enabled or not like is it bold. + */ + this.queryStateCommands[name] = {func: callback, scope: scope || this}; + }, + + /** + * Adds a custom query value command to the editor, you can also override existing commands with this method. + * The command that you add can be executed with queryCommandValue function. + * + * @method addQueryValueHandler + * @param {String} name Command name to add/override. + * @param {addQueryValueHandlerCallback} callback Function to execute when the command value retrival occurs. + * @param {Object} scope Optional scope to execute the function in. + */ + addQueryValueHandler: function(name, callback, scope) { + /** + * Callback function that gets called when a queryCommandValue is executed. + * + * @callback addQueryValueHandlerCallback + * @return {Object} Value of the command or undefined. + */ + this.queryValueCommands[name] = {func: callback, scope: scope || this}; + }, + + /** + * Adds a keyboard shortcut for some command or function. + * + * @method addShortcut + * @param {String} pattern Shortcut pattern. Like for example: ctrl+alt+o. + * @param {String} desc Text description for the command. + * @param {String/Function} cmdFunc Command name string or function to execute when the key is pressed. + * @param {Object} sc Optional scope to execute the function in. + * @return {Boolean} true/false state if the shortcut was added or not. + */ + addShortcut: function(pattern, desc, cmdFunc, scope) { + this.shortcuts.add(pattern, desc, cmdFunc, scope); + }, + + /** + * Executes a command on the current instance. These commands can be TinyMCE internal commands prefixed with "mce" or + * they can be build in browser commands such as "Bold". A compleate list of browser commands is available on MSDN or Mozilla.org. + * This function will dispatch the execCommand function on each plugin, theme or the execcommand_callback option if none of these + * return true it will handle the command as a internal browser command. + * + * @method execCommand + * @param {String} cmd Command name to execute, for example mceLink or Bold. + * @param {Boolean} ui True/false state if a UI (dialog) should be presented or not. + * @param {mixed} value Optional command value, this can be anything. + * @param {Object} a Optional arguments object. + */ + execCommand: function(cmd, ui, value, args) { + var self = this, state = 0, cmdItem; + + if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(cmd) && (!args || !args.skip_focus)) { + self.focus(); + } + + args = extend({}, args); + self.fire('BeforeExecCommand', {command: cmd, ui: ui, value: value}); + if (args.terminate) { + return false; + } + + // Registred commands + if ((cmdItem = self.execCommands[cmd])) { + // Fall through on true + if (cmdItem.func.call(cmdItem.scope, ui, value) !== true) { + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + return true; + } + } + + // Plugin commands + each(self.plugins, function(p) { + if (p.execCommand && p.execCommand(cmd, ui, value)) { + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + state = true; + return false; + } + }); + + if (state) { + return state; + } + + // Theme commands + if (self.theme && self.theme.execCommand && self.theme.execCommand(cmd, ui, value)) { + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + return true; + } + + // Editor commands + if (self.editorCommands.execCommand(cmd, ui, value)) { + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + return true; + } + + // Browser commands + self.getDoc().execCommand(cmd, ui, value); + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + }, + + /** + * Returns a command specific state, for example if bold is enabled or not. + * + * @method queryCommandState + * @param {string} cmd Command to query state from. + * @return {Boolean} Command specific state, for example if bold is enabled or not. + */ + queryCommandState: function(cmd) { + var self = this, queryItem, returnVal; + + // Is hidden then return undefined + if (self._isHidden()) { + return; + } + + // Registred commands + if ((queryItem = self.queryStateCommands[cmd])) { + returnVal = queryItem.func.call(queryItem.scope); + + // Fall though on true + if (returnVal !== true) { + return returnVal; + } + } + + // Editor commands + returnVal = self.editorCommands.queryCommandState(cmd); + if (returnVal !== -1) { + return returnVal; + } + + // Browser commands + try { + return self.getDoc().queryCommandState(cmd); + } catch (ex) { + // Fails sometimes see bug: 1896577 + } + }, + + /** + * Returns a command specific value, for example the current font size. + * + * @method queryCommandValue + * @param {string} cmd Command to query value from. + * @return {Object} Command specific value, for example the current font size. + */ + queryCommandValue: function(cmd) { + var self = this, queryItem, returnVal; + + // Is hidden then return undefined + if (self._isHidden()) { + return; + } + + // Registred commands + if ((queryItem = self.queryValueCommands[cmd])) { + returnVal = queryItem.func.call(queryItem.scope); + + // Fall though on true + if (returnVal !== true) { + return returnVal; + } + } + + // Editor commands + returnVal = self.editorCommands.queryCommandValue(cmd); + if (returnVal !== undefined) { + return returnVal; + } + + // Browser commands + try { + return self.getDoc().queryCommandValue(cmd); + } catch (ex) { + // Fails sometimes see bug: 1896577 + } + }, + + /** + * Shows the editor and hides any textarea/div that the editor is supposed to replace. + * + * @method show + */ + show: function() { + var self = this; + + DOM.show(self.getContainer()); + DOM.hide(self.id); + self.load(); + self.fire('show'); + }, + + /** + * Hides the editor and shows any textarea/div that the editor is supposed to replace. + * + * @method hide + */ + hide: function() { + var self = this, doc = self.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(); + + // defer the call to hide to prevent an IE9 crash #4921 + DOM.hide(self.getContainer()); + DOM.setStyle(self.id, 'display', self.orgDisplay); + self.fire('hide'); + }, + + /** + * Returns true/false if the editor is hidden or not. + * + * @method isHidden + * @return {Boolean} True/false if the editor is hidden or not. + */ + isHidden: function() { + return !DOM.isHidden(this.id); + }, + + /** + * Sets the progress state, this will display a throbber/progess for the editor. + * This is ideal for asycronous operations like an AJAX save call. + * + * @method setProgressState + * @param {Boolean} state Boolean state if the progress should be shown or hidden. + * @param {Number} time Optional time to wait before the progress gets shown. + * @return {Boolean} Same as the input state. + * @example + * // Show progress for the active editor + * tinymce.activeEditor.setProgressState(true); + * + * // Hide progress for the active editor + * tinymce.activeEditor.setProgressState(false); + * + * // Show progress after 3 seconds + * tinymce.activeEditor.setProgressState(true, 3000); + */ + setProgressState: function(state, time) { + this.fire('ProgressState', {state: state, time: time}); + }, + + /** + * Loads contents from the textarea or div element that got converted into an editor instance. + * This method will move the contents from that textarea or div into the editor by using setContent + * so all events etc that method has will get dispatched as well. + * + * @method load + * @param {Object} args Optional content object, this gets passed around through the whole load process. + * @return {String} HTML string that got set into the editor. + */ + load: function(args) { + var self = this, elm = self.getElement(), html; + + if (elm) { + args = args || {}; + args.load = true; + + html = self.setContent(elm.value !== undefined ? elm.value : elm.innerHTML, args); + args.element = elm; + + if (!args.no_events) { + self.fire('LoadContent', args); + } + + args.element = elm = null; + + return html; + } + }, + + /** + * Saves the contents from a editor out to the textarea or div element that got converted into an editor instance. + * This method will move the HTML contents from the editor into that textarea or div by getContent + * so all events etc that method has will get dispatched as well. + * + * @method save + * @param {Object} args Optional content object, this gets passed around through the whole save process. + * @return {String} HTML string that got set into the textarea/div. + */ + save: function(args) { + var self = this, elm = self.getElement(), html, form; + + if (!elm || !self.initialized) { + return; + } + + args = args || {}; + args.save = true; + + args.element = elm; + html = args.content = self.getContent(args); + + if (!args.no_events) { + self.fire('SaveContent', args); + } + + html = args.content; + + if (!/TEXTAREA|INPUT/i.test(elm.nodeName)) { + elm.innerHTML = html; + + // Update hidden form element + if ((form = DOM.getParent(self.id, 'form'))) { + each(form.elements, function(elm) { + if (elm.name == self.id) { + elm.value = html; + return false; + } + }); + } + } else { + elm.value = html; + } + + args.element = elm = null; + + return html; + }, + + /** + * Sets the specified content to the editor instance, this will cleanup the content before it gets set using + * the different cleanup rules options. + * + * @method setContent + * @param {String} content Content to set to editor, normally HTML contents but can be other formats as well. + * @param {Object} args Optional content object, this gets passed around through the whole set process. + * @return {String} HTML string that got set into the editor. + * @example + * // Sets the HTML contents of the activeEditor editor + * tinymce.activeEditor.setContent('some html'); + * + * // Sets the raw contents of the activeEditor editor + * tinymce.activeEditor.setContent('some html', {format: 'raw'}); + * + * // Sets the content of a specific editor (my_editor in this example) + * tinymce.get('my_editor').setContent(data); + * + * // Sets the bbcode contents of the activeEditor editor if the bbcode plugin was added + * tinymce.activeEditor.setContent('[b]some[/b] html', {format: 'bbcode'}); + */ + setContent: function(content, args) { + var self = this, 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.fire('BeforeSetContent', 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 (!isIE && (content.length === 0 || /^\s+$/.test(content))) { + forcedRootBlockName = self.settings.forced_root_block; + + // Check if forcedRootBlock is configured and that the block is a valid child of the body + if (forcedRootBlockName && self.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) { + content = '<' + forcedRootBlockName + '>
'; + } else { + content = '
'; + } + + body.innerHTML = content; + self.selection.select(body, true); + self.selection.collapse(true); + return; + } + + // Parse and serialize the html + if (args.format !== 'raw') { + content = new Serializer({}, self.schema).serialize( + self.parser.parse(content, {isRootContent: true}) + ); + } + + // Set the new cleaned contents to the editor + args.content = trim(content); + self.dom.setHTML(body, args.content); + + // Do post processing + if (!args.no_events) { + self.fire('SetContent', args); + } + + // Don't normalize selection if the focused element isn't the body in content editable mode since it will steal focus otherwise + if (!self.settings.content_editable || document.activeElement === self.getBody()) { + self.selection.normalize(); + } + + return args.content; + }, + + /** + * Gets the content from the editor instance, this will cleanup the content before it gets returned using + * the different cleanup rules options. + * + * @method getContent + * @param {Object} args Optional content object, this gets passed around through the whole get process. + * @return {String} Cleaned content string, normally HTML contents. + * @example + * // Get the HTML contents of the currently active editor + * console.debug(tinymce.activeEditor.getContent()); + * + * // Get the raw contents of the currently active editor + * tinymce.activeEditor.getContent({format: 'raw'}); + * + * // Get content of a specific editor: + * tinymce.get('content id').getContent() + */ + getContent: function(args) { + var self = this, content, body = self.getBody(); + + // Setup args object + args = args || {}; + args.format = args.format || 'html'; + args.get = true; + args.getInner = true; + + // Do preprocessing + if (!args.no_events) { + self.fire('BeforeGetContent', args); + } + + // Get raw contents or by default the cleaned contents + if (args.format == 'raw') { + content = body.innerHTML; + } else if (args.format == 'text') { + content = body.innerText || body.textContent; + } else { + content = self.serializer.serialize(body, args); + } + + // Trim whitespace in beginning/end of HTML + if (args.format != 'text') { + args.content = trim(content); + } else { + args.content = content; + } + + // Do post processing + if (!args.no_events) { + self.fire('GetContent', args); + } + + return args.content; + }, + + /** + * Inserts content at caret position. + * + * @method insertContent + * @params {String} content Content to insert. + */ + insertContent: function(content) { + this.execCommand('mceInsertContent', false, content); + }, + + /** + * Returns true/false if the editor is dirty or not. It will get dirty if the user has made modifications to the contents. + * + * @method isDirty + * @return {Boolean} True/false if the editor is dirty or not. It will get dirty if the user has made modifications to the contents. + * @example + * if (tinymce.activeEditor.isDirty()) + * alert("You must save your contents."); + */ + isDirty: function() { + return !this.isNotDirty && this.undoManager.hasUndo(); + }, + + /** + * Returns the editors container element. The container element wrappes in + * all the elements added to the page for the editor. Such as UI, iframe etc. + * + * @method getContainer + * @return {Element} HTML DOM element for the editor container. + */ + getContainer: function() { + var self = this; + + if (!self.container) { + self.container = DOM.get(self.editorContainer || self.id + '_parent'); + } + + return self.container; + }, + + /** + * Returns the editors content area container element. The this element is the one who + * holds the iframe or the editable element. + * + * @method getContentAreaContainer + * @return {Element} HTML DOM element for the editor area container. + */ + getContentAreaContainer: function() { + return this.contentAreaContainer; + }, + + /** + * Returns the target element/textarea that got replaced with a TinyMCE editor instance. + * + * @method getElement + * @return {Element} HTML DOM element for the replaced element. + */ + getElement: function() { + return DOM.get(this.settings.content_element || this.id); + }, + + /** + * Returns the iframes window object. + * + * @method getWin + * @return {Window} Iframe DOM window object. + */ + getWin: function() { + var self = this, elm; + + if (!self.contentWindow) { + elm = DOM.get(self.id + "_ifr"); + + if (elm) { + self.contentWindow = elm.contentWindow; + } + } + + return self.contentWindow; + }, + + /** + * Returns the iframes document object. + * + * @method getDoc + * @return {Document} Iframe DOM document object. + */ + getDoc: function() { + var self = this, win; + + if (!self.contentDocument) { + win = self.getWin(); + + if (win) { + self.contentDocument = win.document; + } + } + + return self.contentDocument; + }, + + /** + * Returns the iframes body element. + * + * @method getBody + * @return {Element} Iframe body element. + */ + getBody: function() { + return this.bodyElement || this.getDoc().body; + }, + + /** + * URL converter function this gets executed each time a user adds an img, a or + * any other element that has a URL in it. This will be called both by the DOM and HTML + * manipulation functions. + * + * @method convertURL + * @param {string} url URL to convert. + * @param {string} name Attribute name src, href etc. + * @param {string/HTMLElement} elm Tag name or HTML DOM element depending on HTML or DOM insert. + * @return {string} Converted URL string. + */ + 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 || url.length === 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; + }, + + /** + * Adds visual aid for tables, anchors etc so they can be more easily edited inside the editor. + * + * @method addVisual + * @param {Element} elm Optional root element to loop though to find tables etc that needs the visual aid. + */ + addVisual: function(elm) { + var self = this, settings = self.settings, dom = self.dom, cls; + + elm = elm || self.getBody(); + + if (self.hasVisual === undefined) { + self.hasVisual = settings.visual; + } + + each(dom.select('table,a', elm), function(elm) { + var value; + + switch (elm.nodeName) { + case 'TABLE': + cls = settings.visual_table_class || 'mce-item-table'; + value = dom.getAttrib(elm, 'border'); + + if (!value || value == '0') { + if (self.hasVisual) { + dom.addClass(elm, cls); + } else { + dom.removeClass(elm, cls); + } + } + + return; + + case 'A': + if (!dom.getAttrib(elm, 'href', false)) { + value = dom.getAttrib(elm, 'name') || elm.id; + cls = 'mce-item-anchor'; + + if (value) { + if (self.hasVisual) { + dom.addClass(elm, cls); + } else { + dom.removeClass(elm, cls); + } + } + } + + return; + } + }); + + self.fire('VisualAid', {element: elm, hasVisual: self.hasVisual}); + }, + + /** + * Removes the editor from the dom and tinymce collection. + * + * @method remove + */ + remove: function() { + var self = this, elm = self.getContainer(), doc = self.getDoc(); + + if (!self.removed) { + self.removed = 1; // Cancels post remove event execution + + // 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.setStyle(self.id, 'display', self.orgDisplay); + + // 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.unbind(self.getWin()); + Event.unbind(self.getDoc()); + } + + Event.unbind(self.getBody()); + Event.unbind(elm); + + self.fire('remove'); + + self.editorManager.remove(self); + DOM.remove(elm); + } + }, + + bindNative: function(name) { + var self = this; + + if (self.initialized) { + self.dom.bind(getEventTarget(self, name), name, function(e) { + self.fire(name, e); + }); + } else { + if (!self._pendingNativeEvents) { + self._pendingNativeEvents = [name]; + } else { + self._pendingNativeEvents.push(name); + } + } + }, + + unbindNative: function(name) { + var self = this; + + if (self.initialized) { + self.dom.unbind(name); + } + }, + + /** + * Destroys the editor instance by removing all events, element references or other resources + * that could leak memory. This method will be called automatically when the page is unloaded + * but you can also call it directly if you know what you are doing. + * + * @method destroy + * @param {Boolean} automatic Optional state if the destroy is an automatic destroy or user called one. + */ + destroy: function(automatic) { + var self = this, form; + + // One time is enough + if (self.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(self.getDoc()); + Event.unbind(self.getWin()); + Event.unbind(self.getBody()); + } + + if (!automatic) { + self.editorManager.off(self._beforeUnload); + + // Manual destroy + if (self.theme && self.theme.destroy) { + self.theme.destroy(); + } + + // Destroy controls, selection and dom + self.selection.destroy(); + self.dom.destroy(); + } + + form = self.formElement; + if (form) { + form.submit = form._mceOldSubmit; + form._mceOldSubmit = null; + DOM.unbind(form, 'submit reset', self.formEventDelegate); + } + + self.contentAreaContainer = self.formElement = self.container = null; + self.settings.content_element = self.bodyElement = self.contentDocument = self.contentWindow = null; + + if (self.selection) { + self.selection = self.selection.win = self.selection.dom = self.selection.dom.doc = null; + } + + self.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 sel; + + if (!isGecko) { + return 0; + } + + // Weird, wheres that cursor selection? + sel = this.selection.getSel(); + return (!sel || !sel.rangeCount || sel.rangeCount === 0); + } + }; + + extend(Editor.prototype, Observable); + + return Editor; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/EditorCommands.js b/lib/tinymce/jscripts/tinymce4/classes/EditorCommands.js new file mode 100644 index 00000000..67dedb1d --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/EditorCommands.js @@ -0,0 +1,691 @@ +/** + * EditorCommands.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class enables you to add custom editor commands and it contains + * overrides for native browser commands to address various bugs and issues. + * + * @class tinymce.EditorCommands + */ +define("tinymce/EditorCommands", [ + "tinymce/html/Serializer", + "tinymce/Env", + "tinymce/util/Tools" +], function(Serializer, Env, Tools) { + // Added for compression purposes + var each = Tools.each, extend = Tools.extend; + var map = Tools.map, inArray = Tools.inArray, explode = Tools.explode; + var isGecko = Env.gecko, isIE = Env.ie; + var TRUE = true, FALSE = false; + + return function(editor) { + var dom = editor.dom, + selection = editor.selection, + commands = {state: {}, exec: {}, value: {}}, + settings = editor.settings, + formatter = editor.formatter, + bookmark; + + /** + * Executes the specified command. + * + * @method execCommand + * @param {String} command Command to execute. + * @param {Boolean} ui Optional user interface state. + * @param {Object} value Optional value for command. + * @return {Boolean} true/false if the command was found or not. + */ + function execCommand(command, ui, value) { + var func; + + command = command.toLowerCase(); + if ((func = commands.exec[command])) { + func(command, ui, value); + return TRUE; + } + + return FALSE; + } + + /** + * Queries the current state for a command for example if the current selection is "bold". + * + * @method queryCommandState + * @param {String} command Command to check the state of. + * @return {Boolean/Number} true/false if the selected contents is bold or not, -1 if it's not found. + */ + function queryCommandState(command) { + var func; + + command = command.toLowerCase(); + if ((func = commands.state[command])) { + return func(command); + } + + return -1; + } + + /** + * Queries the command value for example the current fontsize. + * + * @method queryCommandValue + * @param {String} command Command to check the value of. + * @return {Object} Command value of false if it's not found. + */ + function queryCommandValue(command) { + var func; + + command = command.toLowerCase(); + if ((func = commands.value[command])) { + return func(command); + } + + return FALSE; + } + + /** + * Adds commands to the command collection. + * + * @method addCommands + * @param {Object} command_list Name/value collection with commands to add, the names can also be comma separated. + * @param {String} type Optional type to add, defaults to exec. Can be value or state as well. + */ + 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 + extend(this, { + execCommand: execCommand, + queryCommandState: queryCommandState, + queryCommandValue: queryCommandValue, + addCommands: addCommands + }); + + // Private methods + + function execNativeCommand(command, ui, value) { + if (ui === undefined) { + ui = FALSE; + } + + if (value === undefined) { + 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} : undefined); + editor.nodeChanged(); + } + + 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 (isGecko) { + editor.windowManager.confirm(editor.getLang('clipboard_msg'), function(state) { + if (state) { + window.open('http://www.mozilla.org/editor/midasdemo/securityprefs.html', '_blank'); + } + }); + } else { + editor.windowManager.alert( + "Your browser doesn't support direct access to the clipboard. " + + "Please use the Ctrl+X/C/V keyboard shortcuts instead." + ); + } + } + }, + + // 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); + + if (align == 'full') { + align = 'justify'; + } + + // Remove all other alignments first + each('left,center,right,justify'.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 = explode(settings.font_size_style_values); + fontClasses = 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() { + 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; + var marker, nodeRect, viewPortRect, rng, node, node2, bookmarkHtml, viewportBodyElement; + + function trimOrPaddLeftRight(html) { + var rng, container, offset; + + rng = selection.getRng(true); + container = rng.startContainer; + offset = rng.startOffset; + + function hasSiblingText(siblingName) { + return container[siblingName] && container[siblingName].nodeType == 3; + } + + if (container.nodeType == 3) { + if (offset > 0) { + html = html.replace(/^ /, ' '); + } else if (!hasSiblingText('previousSibling')) { + html = html.replace(/^ /, ' '); + } + + if (offset < container.length) { + html = html.replace(/ (
|)$/, ' '); + } else if (!hasSiblingText('nextSibling')) { + html = html.replace(/( | )(
|)$/, ' '); + } + } + + return html; + } + + // Check for whitespace before/after value + if (/^ | $/.test(value)) { + value = trimOrPaddLeftRight(value); + } + + // Setup parser and serializer + parser = editor.parser; + serializer = new Serializer({}, editor.schema); + bookmarkHtml = ''; + + // Run beforeSetContent handlers on the HTML to be inserted + args = {content: value, format: 'html', selection: true}; + editor.fire('BeforeSetContent', 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 = 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(//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 = 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); + + // TODO: Why can't we normalize on IE + if (!isIE) { + node2 = marker.nextSibling; + if (node2 && node2.nodeType == 3) { + node.appendData(node2.data); + node2.parentNode.removeChild(node2); + } + } + } 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 + editor.fire('SetContent', 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; + }) + ); + }, + + mceToggleFormat: function(command, ui, value) { + toggleFormat(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, 10); + + 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) { + var indentStyleName; + + if (element.nodeName != "LI") { + indentStyleName = dom.getStyle(element, 'direction', true) == 'rtl' ? 'paddingRight' : 'paddingLeft'; + + if (command == 'outdent') { + value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue); + dom.setStyle(element, indentStyleName, value ? value + indentUnit : ''); + } else { + value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit; + dom.setStyle(element, indentStyleName, value); + } + } + }); + } else { + execNativeCommand(command); + } + }, + + mceRepaint: function() { + if (isGecko) { + try { + storeSelection(TRUE); + + if (selection.getSel()) { + selection.getSel().selectAllChildren(editor.getBody()); + } + + selection.collapse(TRUE); + restoreSelection(); + } catch (ex) { + // Ignore + } + } + }, + + InsertHorizontalRule: function() { + editor.execCommand('mceInsertContent', false, '
'); + }, + + 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(); + + // Old IE does a better job with selectall than new versions + if (selection.getRng().setStart) { + rng.setStart(root, 0); + rng.setEnd(root, root.childNodes.length); + + selection.setRng(rng); + } else { + execNativeCommand('SelectAll'); + } + }, + + mceNewDocument: function() { + editor.setContent(''); + } + }); + + // Add queryCommandState overrides + addCommands({ + // Override justify commands + 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) { + var name = 'align' + command.substring(7); + var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks(); + var matches = map(nodes, function(node) { + return !!formatter.matchNode(node, name); + }); + return 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, 10) > 0) { + return TRUE; + } + + if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { + return TRUE; + } + } + + return ( + queryCommandState('InsertUnorderedList') || + queryCommandState('InsertOrderedList') || + (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')) + ); + }, + + 'InsertUnorderedList,InsertOrderedList': function(command) { + var list = dom.getParent(selection.getNode(), 'ul,ol'); + + return list && + ( + command === 'insertunorderedlist' && list.tagName === 'UL' || + command === 'insertorderedlist' && list.tagName === '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(); + } + }); + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/EditorManager.js b/lib/tinymce/jscripts/tinymce4/classes/EditorManager.js new file mode 100644 index 00000000..d565067c --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/EditorManager.js @@ -0,0 +1,501 @@ +/** + * EditorManager.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class used as a factory for manager for tinymce.Editor instaces. + * + * @class tinymce.EditorManager + */ +define("tinymce/EditorManager", [ + "tinymce/Editor", + "tinymce/dom/DOMUtils", + "tinymce/util/URI", + "tinymce/Env", + "tinymce/util/Tools", + "tinymce/util/Observable" +], function(Editor, DOMUtils, URI, Env, Tools, Observable) { + var DOM = DOMUtils.DOM; + var explode = Tools.explode, each = Tools.each, extend = Tools.extend; + var instanceCounter = 0, beforeUnloadDelegate; + + var EditorManager = { + /** + * Major version of TinyMCE build. + * + * @property majorVersion + * @type String + */ + majorVersion : '@@majorVersion@@', + + /** + * Minor version of TinyMCE build. + * + * @property minorVersion + * @type String + */ + minorVersion : '@@minorVersion@@', + + /** + * Release date of TinyMCE build. + * + * @property releaseDate + * @type String + */ + releaseDate: '@@releaseDate@@', + + /** + * Collection of editor instances. + * + * @property editors + * @type Object + * @example + * for (edId in tinymce.editors) + * tinymce.editors[edId].save(); + */ + editors: [], + + /** + * Collection of language pack data. + * + * @property i18n + * @type Object + */ + i18n: {}, + + /** + * Currently active editor instance. + * + * @property activeEditor + * @type tinymce.Editor + * @example + * tinyMCE.activeEditor.selection.getContent(); + * tinymce.EditorManager.activeEditor.selection.getContent(); + */ + activeEditor: null, + + setup: function() { + var self = this, baseURL, documentBaseURL, suffix = "", preInit; + + // Get base URL for the current document + documentBaseURL = document.location.href.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, ''); + if (!/[\/\\]$/.test(documentBaseURL)) { + documentBaseURL += '/'; + } + + // If tinymce is defined and has a base use that or use the old tinyMCEPreInit + preInit = window.tinymce || window.tinyMCEPreInit; + if (preInit) { + baseURL = preInit.base || preInit.baseURL; + suffix = preInit.suffix; + } else { + // Get base where the tinymce script is located + var scripts = document.getElementsByTagName('script'); + for (var i = 0; i < scripts.length; i++) { + var src = scripts[i].src; + + if (/tinymce(\.jquery|)(\.min|\.dev|).js/.test(src)) { + if (src.indexOf('.min') != -1) { + suffix = '.min'; + } + + baseURL = src.substring(0, src.lastIndexOf('/')); + break; + } + } + } + + /** + * Base URL where the root directory if TinyMCE is located. + * + * @property baseURL + * @type {String} + */ + self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL); + + /** + * Document base URL where the current document is located. + * + * @property documentBaseURL + * @type {String} + */ + self.documentBaseURL = documentBaseURL; + + /** + * Absolute baseURI for the installation path of TinyMCE. + * + * @property baseURI + * @type tinymce.util.URI + */ + self.baseURI = new URI(self.baseURL); + + /** + * Current suffix to add to each plugin/theme that gets loaded for example ".min". + * + * @property suffix + * @type {String} + */ + self.suffix = suffix; + }, + + /** + * Initializes a set of editors. This method will create editors based on various settings. + * + * @method init + * @param {Object} settings Settings object to be passed to each editor instance. + * @example + * // Initializes a editor using the longer method + * tinymce.EditorManager.init({ + * some_settings : 'some value' + * }); + * + * // Initializes a editor instance using the shorter version + * tinyMCE.init({ + * some_settings : 'some value' + * }); + */ + init: function(settings) { + var self = this, editors = [], editor; + + 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; + } + + 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); + } + + self.settings = settings; + + DOM.bind(window, 'ready', function() { + var l, co; + + execCallback(settings, 'onpageload'); + + switch (settings.mode) { + case "exact": + l = settings.elements || ''; + + if(l.length > 0) { + each(explode(l), function(v) { + if (DOM.get(v)) { + editor = new Editor(v, settings, self); + editors.push(editor); + editor.render(true); + } else { + each(document.forms, function(f) { + each(f.elements, function(e) { + if (e.name === v) { + v = 'mce_editor_' + instanceCounter++; + DOM.setAttrib(e, 'id', v); + + editor = new Editor(v, settings, self); + editors.push(editor); + editor.render(1); + } + }); + }); + } + }); + } + break; + + case "textareas": + case "specific_textareas": + each(DOM.select('textarea'), function(elm) { + if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) { + return; + } + + if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) { + editor = new Editor(createId(elm), settings, self); + editors.push(editor); + editor.render(true); + } + }); + break; + + default: + if (settings.types) { + // Process type specific selector + each(settings.types, function(type) { + each(DOM.select(type.selector), function(elm) { + var editor = new Editor(createId(elm), extend({}, settings, type), self); + editors.push(editor); + editor.render(1); + }); + }); + } else if (settings.selector) { + // Process global selector + each(DOM.select(settings.selector), function(elm) { + var editor = new Editor(createId(elm), settings, self); + editors.push(editor); + editor.render(1); + }); + } + } + + // Call onInit when all editors are initialized + if (settings.oninit) { + l = co = 0; + + each(editors, function(ed) { + co++; + + if (!ed.initialized) { + // Wait for it + ed.on('init', function() { + l++; + + // All done + if (l == co) { + execCallback(settings, 'oninit'); + } + }); + } else { + l++; + } + + // All done + if (l == co) { + execCallback(settings, 'oninit'); + } + }); + } + }); + }, + + /** + * Returns a editor instance by id. + * + * @method get + * @param {String/Number} id Editor instance id or index to return. + * @return {tinymce.Editor} Editor instance to return. + * @example + * // Adds an onclick event to an editor by id (shorter version) + * tinymce.get('mytextbox').on('click', function(e) { + * ed.windowManager.alert('Hello world!'); + * }); + * + * // Adds an onclick event to an editor by id (longer version) + * tinymce.EditorManager.get('mytextbox').on('click', function(e) { + * ed.windowManager.alert('Hello world!'); + * }); + */ + get: function(id) { + if (id === undefined) { + return this.editors; + } + + return this.editors[id]; + }, + + /** + * Adds an editor instance to the editor collection. This will also set it as the active editor. + * + * @method add + * @param {tinymce.Editor} editor Editor instance to add to the collection. + * @return {tinymce.Editor} The same instance that got passed in. + */ + add: function(editor) { + var self = this, editors = self.editors; + + // Add named and index editor instance + editors[editor.id] = editor; + editors.push(editor); + + self.activeEditor = editor; + self.fire('AddEditor', {editor: editor}); + + if (!beforeUnloadDelegate) { + beforeUnloadDelegate = function() { + self.fire('BeforeUnload'); + }; + + DOM.bind(window, 'beforeunload', beforeUnloadDelegate); + } + + return editor; + }, + + /** + * Creates an editor instance and adds it to the EditorManager collection. + * + * @param {Object} settings Editor instance settings. + * @return {tinymce.Editor} Editor instance that got created. + */ + createEditor: function(settings) { + return this.add(new Editor(settings)); + }, + + /** + * Removes a editor instance from the collection. + * + * @method remove + * @param {tinymce.Editor} e Editor instance to remove. + * @return {tinymce.Editor} The editor that got passed in will be return if it was found otherwise null. + */ + remove: function(editor) { + var self = this, i, editors = self.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 (self.activeEditor == editor) { + self.activeEditor = editors[0]; + } + + editor.destroy(); + self.fire('RemoveEditor', {editor: editor}); + + if (!editors.length) { + DOM.unbind(window, 'beforeunload', beforeUnloadDelegate); + } + + return editor; + }, + + /** + * Executes a specific command on the currently active editor. + * + * @method execCommand + * @param {String} c Command to perform for example Bold. + * @param {Boolean} u Optional boolean state if a UI should be presented for the command or not. + * @param {String} v Optional value parameter like for example an URL to a link. + * @return {Boolean} true/false if the command was executed or not. + */ + execCommand: function(cmd, ui, value) { + var self = this, editor = self.get(value); + + // Manager commands + switch (cmd) { + case "mceAddEditor": + if (!self.get(value)) { + new Editor(value, self.settings, self).render(); + } + + return true; + + case "mceRemoveEditor": + if (editor) { + editor.remove(); + } + + return true; + + case 'mceToggleEditor': + if (!editor) { + self.execCommand('mceAddEditor', 0, value); + return true; + } + + if (editor.isHidden()) { + editor.show(); + } else { + editor.hide(); + } + + return true; + } + + // Run command on active editor + if (self.activeEditor) { + return self.activeEditor.execCommand(cmd, ui, value); + } + + return false; + }, + + /** + * Calls the save method on all editor instances in the collection. This can be useful when a form is to be submitted. + * + * @method triggerSave + * @example + * // Saves all contents + * tinyMCE.triggerSave(); + */ + triggerSave: function() { + each(this.editors, function(editor) { + editor.save(); + }); + }, + + /** + * Adds a language pack, this gets called by the loaded language files like en.js. + * + * @method addI18n + * @param {String} code Optional language code. + * @param {Object} items Name/value object with translations. + */ + addI18n: function(code, items) { + extend(this.i18n, items || code); + }, + + /** + * Translates the specified string using the language pack items. + * + * @param {String/Array} str String to translate + * @return {String} Translated string. + */ + translate: function(str) { + if (typeof(str) !== "string") { + return (this.i18n[str[0]] || str[0]).replace(/%d/, str[1]); + } + + return this.i18n[str] || str; + } + }; + + EditorManager.setup(); + + // Export EditorManager as tinymce/tinymce in global namespace + window.tinymce = window.tinyMCE = EditorManager; + + extend(EditorManager, Observable); + + return EditorManager; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/EnterKey.js b/lib/tinymce/jscripts/tinymce4/classes/EnterKey.js new file mode 100644 index 00000000..ebaab6c4 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/EnterKey.js @@ -0,0 +1,611 @@ +/** + * EnterKey.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Contains logic for handling the enter key to split/generate block elements. + */ +define("tinymce/EnterKey", [ + "tinymce/dom/TreeWalker", + "tinymce/Env" +], function(TreeWalker, Env) { + var isIE = Env.ie; + + return function(editor) { + var dom = editor.dom, selection = editor.selection, settings = editor.settings; + var undoManager = editor.undoManager, schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements(); + + function handleEnterKey(evt) { + var rng = selection.getRng(true), tmpRng, editableRoot, container, offset, parentBlock, documentMode, shiftKey, + 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|FORM)$/.test(node.nodeName) && + !/^(fixed|absolute)/i.test(node.style.position) && + dom.getContentEditable(node) !== "true"; + } + + // Renders empty block on IE + function renderBlockOnIE(block) { + var oldRng; + + if (dom.isBlock(block)) { + oldRng = selection.getRng(); + block.appendChild(dom.create('span', null, '\u00a0')); + selection.select(block); + block.lastChild.outerHTML = ''; + selection.setRng(oldRng); + } + } + + // Remove the first empty inline element of the block so this:

x

becomes this:

x

+ function trimInlineElementsOnLeftSideOfBlock(block) { + var node = block, firstChilds = [], i; + + // Find inner most first child ex:

*

+ while ((node = node.firstChild)) { + if (dom.isBlock(node)) { + return; + } + + if (node.nodeType == 1 && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) { + firstChilds.push(node); + } + } + + i = firstChilds.length; + while (i--) { + node = firstChilds[i]; + if (!node.hasChildNodes() || (node.firstChild == node.lastChild && node.firstChild.nodeValue === '')) { + dom.remove(node); + } else { + // Remove see #5381 + if (node.nodeName == "A" && (node.innerText || node.textContent) === ' ') { + dom.remove(node); + } + } + } + } + + // 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, 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 (nonEmptyElementsMap[node.nodeName.toLowerCase()]) { + 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); + selection.scrollIntoView(root); + } + + // 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)) { + // Never clone a caret containers + if (node.id == '_mce_caret') { + continue; + } + + 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 (!isIE) { + caretNode.innerHTML = '
'; + } + + 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; + } + + // If the caret if before the first element in parentBlock + if (start && container.nodeType == 1 && container == parentBlock.firstChild) { + 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); + + // If caret is in beginning or end of a text block then jump to the next/previous node + if (container.nodeType == 3) { + if (start && offset === 0) { + walker.prev(); + } else if (!start && offset == container.nodeValue.length) { + walker.next(); + } + } + + while ((node = walker.current())) { + if (node.nodeType === 1) { + // Ignore bogus elements + if (!node.getAttribute('data-mce-bogus')) { + // Keep empty elements like but not trailing br:s like

text|

+ name = node.nodeName.toLowerCase(); + if (nonEmptyElementsMap[name] && name !== 'br') { + return false; + } + } + } else if (node.nodeType === 3 && !/^[ \t\r\n]*$/.test(node.nodeValue)) { + return false; + } + + if (start) { + walker.prev(); + } else { + walker.next(); + } + } + + 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, rootBlockName, blockName = newBlockName || 'P'; + + // Not in a block element or in a table cell or caption + parentBlock = dom.getParent(container, dom.isBlock); + rootBlockName = editor.getBody().nodeName.toLowerCase(); + 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 && schema.isValidChild(rootBlockName, blockName.toLowerCase())) { + 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; + } + + function getContainerBlock() { + var containerBlockParent = containerBlock.parentNode; + + if (containerBlockParent.nodeName == 'LI') { + return containerBlockParent; + } + + return containerBlock; + } + + // Check if we are in an nested list + var containerBlockParentName = containerBlock.parentNode.nodeName; + if (/^(OL|UL|LI)$/.test(containerBlockParentName)) { + newBlockName = 'LI'; + } + + newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR'); + + if (isFirstOrLastLi(true) && isFirstOrLastLi()) { + if (containerBlockParentName == 'LI') { + // Nested list is inside a LI + dom.insertAfter(newBlock, getContainerBlock()); + } else { + // Is first and last list item then replace the OL/UL with a text block + dom.replace(newBlock, containerBlock); + } + } else if (isFirstOrLastLi(true)) { + if (containerBlockParentName == 'LI') { + // List nested in an LI then move the list to a new sibling LI + dom.insertAfter(newBlock, getContainerBlock()); + newBlock.appendChild(dom.doc.createTextNode(' ')); // Needed for IE so the caret can be placed + newBlock.appendChild(containerBlock); + } else { + // 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 remove LI and add text block after list + dom.insertAfter(newBlock, getContainerBlock()); + renderBlockOnIE(newBlock); + } 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 + containerBlock = getContainerBlock(); + 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 hasRightSideContent() { + var walker = new TreeWalker(container, parentBlock), node; + + while ((node = walker.next())) { + if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) { + return true; + } + } + } + + // Inserts a BR element if the forced_root_block option is set to false or empty string + function insertBr() { + var brElm, extraBr, marker; + + if (container && container.nodeType == 3 && offset >= container.nodeValue.length) { + // Insert extra BR element at the end block elements + if (!isIE && !hasRightSideContent()) { + 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 (isIE && parentBlockName == 'PRE' && (!documentMode || documentMode < 8)) { + brElm.parentNode.insertBefore(dom.doc.createTextNode('\r'), brElm); + } + + // Insert temp marker and scroll to that + marker = dom.create('span', {}, ' '); + brElm.parentNode.insertBefore(marker, brElm); + selection.scrollIntoView(marker); + dom.remove(marker); + + 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; + } + + // Adds a BR at the end of blocks that only contains an IMG or INPUT since + // these might be floated and then they won't expand the block + function addBrToBlockIfNeeded(block) { + var lastChild; + + // IE will render the blocks correctly other browsers needs a BR + if (!isIE) { + block.normalize(); // Remove empty text nodes that got left behind by the extract + + // Check if the block is empty or contains a floated last child + lastChild = block.lastChild; + if (!lastChild || (/^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true)))) { + dom.add(block, 'br'); + } + } + } + + // 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.force_p_newlines ? 'p' : '') || settings.forced_root_block; + newBlockName = newBlockName ? newBlockName.toUpperCase() : ''; + documentMode = dom.doc.documentMode; + shiftKey = evt.shiftKey; + + // 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; + if (isAfterLastNodeInContainer && container.nodeType == 3) { + offset = container.nodeValue.length; + } else { + 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 || shiftKey) { + insertBr(); + } + + return; + } + + // Wrap the current node and it's sibling in a default block if it's needed. + // for example this text|text2 will become this

text|text2

+ // This won't happen if root blocks are disabled or the shiftKey is pressed + if ((newBlockName && !shiftKey) || (!newBlockName && 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 + + // Enter inside block contained within a LI then split or insert before/after LI + if (containerBlockName == 'LI' && !evt.ctrlKey) { + parentBlock = containerBlock; + parentBlockName = containerBlockName; + } + + // Handle enter in LI + if (parentBlockName == 'LI') { + if (!newBlockName && shiftKey) { + insertBr(); + return; + } + + // Handle enter inside an empty list item + if (dom.isEmpty(parentBlock)) { + 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 (!shiftKey) { + insertBr(); + return; + } + } else { + // If no root block is configured then insert a BR by default or if the shiftKey is pressed + if ((!newBlockName && !shiftKey && parentBlockName != 'LI') || (newBlockName && shiftKey)) { + insertBr(); + return; + } + } + + // If parent block is root then never insert new blocks + if (newBlockName && parentBlock === editor.getBody()) { + 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|FIGURE)$/.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); + } + + moveToCaretPosition(newBlock); + } else if (isCaretAtStartOrEndOfBlock(true)) { + // Insert new block before + newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock); + renderBlockOnIE(newBlock); + } 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); + trimInlineElementsOnLeftSideOfBlock(newBlock); + addBrToBlockIfNeeded(parentBlock); + moveToCaretPosition(newBlock); + } + + dom.setAttrib(newBlock, 'id', ''); // Remove ID since it needs to be document unique + undoManager.add(); + } + + editor.on('keydown', function(evt) { + if (evt.keyCode == 13) { + if (handleEnterKey(evt) !== false) { + evt.preventDefault(); + } + } + }); + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/Env.js b/lib/tinymce/jscripts/tinymce4/classes/Env.js new file mode 100644 index 00000000..f0452361 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/Env.js @@ -0,0 +1,117 @@ +/** + * Env.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/Env", [], function() { + var nav = navigator, userAgent = nav.userAgent; + var opera, webkit, ie, gecko, mac, iDevice; + + opera = window.opera && window.opera.buildNumber; + webkit = /WebKit/.test(userAgent); + ie = !webkit && !opera && (/MSIE/gi).test(userAgent) && (/Explorer/gi).test(nav.appName); + ie = ie && /MSIE (\w+)\./.exec(userAgent)[1]; + gecko = !webkit && /Gecko/.test(userAgent); + mac = userAgent.indexOf('Mac') != -1; + iDevice = /(iPad|iPhone)/.test(userAgent); + + // Is a iPad/iPhone and not on iOS5 sniff the WebKit version since older iOS WebKit versions + // says it has contentEditable support but there is no visible caret. + var contentEditable = !iDevice || userAgent.match(/AppleWebKit\/(\d*)/)[1] >= 534; + + return { + /** + * Constant that is true if the browser is Opera. + * + * @property opera + * @type Boolean + * @final + */ + opera: opera, + + /** + * Constant that is true if the browser is WebKit (Safari/Chrome). + * + * @property webKit + * @type Boolean + * @final + */ + webkit: webkit, + + /** + * Constant that is more than zero if the browser is IE. + * + * @property ie + * @type Boolean + * @final + */ + ie: ie, + + /** + * Constant that is true if the browser is Gecko. + * + * @property gecko + * @type Boolean + * @final + */ + gecko: gecko, + + /** + * Constant that is true if the os is Mac OS. + * + * @property mac + * @type Boolean + * @final + */ + mac: mac, + + /** + * Constant that is true if the os is iOS. + * + * @property iOS + * @type Boolean + * @final + */ + iOS: iDevice, + + /** + * Constant that is true if the browser supports editing. + * + * @property contentEditable + * @type Boolean + * @final + */ + contentEditable: contentEditable, + + /** + * Transparent image data url. + * + * @property transparentSrc + * @type Boolean + * @final + */ + transparentSrc: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", + + /** + * Returns true/false if the browser can or can't place the caret after a inline block like an image. + * + * @property noCaretAfter + * @type Boolean + * @final + */ + caretAfter: ie != 8, + + /** + * Constant that is true if the browser supports native DOM Ranges. IE 9+. + * + * @property range + * @type Boolean + */ + range: window.getSelection && "Range" in window + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ForceBlocks.js b/lib/tinymce/jscripts/tinymce4/classes/ForceBlocks.js new file mode 100644 index 00000000..55e68b3c --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ForceBlocks.js @@ -0,0 +1,127 @@ +/** + * ForceBlocks.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/ForceBlocks", [], function() { + return function(editor) { + var settings = editor.settings, dom = editor.dom, selection = editor.selection; + var schema = editor.schema, blockElements = schema.getBlockElements(); + + function addRootBlocks() { + var node = selection.getStart(), rootNode = editor.getBody(), rng; + var startContainer, startOffset, endContainer, endOffset, rootBlockNode; + var tempNode, offset = -0xFFFFFF, wrapped, restoreSelection; + var tmpRng, rootNodeName, forcedRootBlock; + + forcedRootBlock = settings.forced_root_block; + + if (!node || node.nodeType !== 1 || !forcedRootBlock) { + return; + } + + // Check if node is wrapped in block + while (node && 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; + restoreSelection = editor.getDoc().activeElement === rootNode; + } else { + // Force control range into text range + if (rng.item) { + node = rng.item(0); + rng = editor.getDoc().body.createTextRange(); + rng.moveToElementText(node); + } + + restoreSelection = rng.parentElement().ownerDocument === editor.getDoc(); + 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; + rootNodeName = rootNode.nodeName.toLowerCase(); + while (node) { + // TODO: Break this up, too complex + if (((node.nodeType === 3 || (node.nodeType == 1 && !blockElements[node.nodeName]))) && + schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase())) { + // Remove empty text nodes + if (node.nodeType === 3 && node.nodeValue.length === 0) { + tempNode = node; + node = node.nextSibling; + dom.remove(tempNode); + continue; + } + + if (!rootBlockNode) { + rootBlockNode = dom.create(forcedRootBlock); + node.parentNode.insertBefore(rootBlockNode, node); + wrapped = true; + } + + tempNode = node; + node = node.nextSibling; + rootBlockNode.appendChild(tempNode); + } else { + rootBlockNode = null; + node = node.nextSibling; + } + } + + if (wrapped && restoreSelection) { + if (rng.setStart) { + rng.setStart(startContainer, startOffset); + rng.setEnd(endContainer, endOffset); + selection.setRng(rng); + } else { + // Only select if the previous selection was inside the document to prevent auto focus in quirks mode + 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.on('KeyUp NodeChange', addRootBlocks); + } + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/Formatter.js b/lib/tinymce/jscripts/tinymce4/classes/Formatter.js new file mode 100644 index 00000000..b2f751b2 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/Formatter.js @@ -0,0 +1,2366 @@ +/** + * Formatter.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Text formatter engine class. This class is used to apply formats like bold, italic, font size + * etc to the current selection or specific nodes. This engine was build to replace the browsers + * default formatting logic for execCommand due to it's inconsistant and buggy behavior. + * + * @class tinymce.Formatter + * @example + * tinymce.activeEditor.formatter.register('mycustomformat', { + * inline: 'span', + * styles: {color: '#ff0000'} + * }); + * + * tinymce.activeEditor.formatter.apply('mycustomformat'); + */ +define("tinymce/Formatter", [ + "tinymce/dom/TreeWalker", + "tinymce/dom/RangeUtils", + "tinymce/util/Tools" +], function(TreeWalker, RangeUtils, Tools) { + /** + * Constructs a new formatter instance. + * + * @constructor Formatter + * @param {tinymce.Editor} ed Editor instance to construct the formatter engine to. + */ + return function(ed) { + var formats = {}, + dom = ed.dom, + selection = ed.selection, + rangeUtils = new RangeUtils(dom), + isValid = ed.schema.isValidChild, + isBlock = dom.isBlock, + forcedRootBlock = ed.settings.forced_root_block, + nodeIndex = dom.nodeIndex, + INVISIBLE_CHAR = '\uFEFF', + MCE_ATTR_RE = /^(src|href|style)$/, + FALSE = false, + TRUE = true, + formatChangeData, + undef, + getContentEditable = dom.getContentEditable, + disableCaretContainer, + markCaretContainersBogus; + + var each = Tools.each, + grep = Tools.grep, + walk = Tools.walk, + extend = Tools.extend; + + function isTextBlock(name) { + if (name.nodeType) { + name = name.nodeName; + } + + return !!ed.schema.getTextBlockElements()[name.toLowerCase()]; + } + + 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,tr,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,tr,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,tr,div,ul,ol,li', styles: {textAlign: 'right'}, defaultBlock: 'div'}, + {selector: 'img,table', collapsed: false, styles: {'float': 'right'}} + ], + + alignjustify: [ + {selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,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'}, + code: {inline: 'code'}, + + link: {inline: 'a', selector: 'a', remove: 'all', split: true, deep: true, + onmatch: function() { + 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 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 + + /** + * Returns the format by name or all formats if no name is specified. + * + * @method get + * @param {String} name Optional name to retrive by. + * @return {Array/Object} Array/Object with all registred formats or a specific format. + */ + function get(name) { + return name ? formats[name] : formats; + } + + /** + * Registers a specific format by name. + * + * @method register + * @param {Object/String} name Name of the format for example "bold". + * @param {Object/Array} format Optional format object or array of format variants + * can only be omitted if the first arg is an object. + */ + 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; + } + } + } + + function getTextDecoration(node) { + var decoration; + + ed.dom.getParent(node, function(n) { + decoration = ed.dom.getStyle(n, 'text-decoration'); + return decoration && decoration !== 'none'; + }); + + return decoration; + } + + function processUnderlineAndColor(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); + } + } + } + + /** + * Applies the specified format to the current selection or specified node. + * + * @method apply + * @param {String} name Name of format to apply. + * @param {Object} vars Optional list of variables to replace within format before applying it. + * @param {Node} node Optional node to apply the format to defaults to current selection. + */ + function apply(name, vars, node) { + var formatList = get(name), format = formatList[0], bookmark, rng, isCollapsed = !node && 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(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(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; + + /** + * Process a list of nodes wrap them. + */ + 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 + // TODO: Break this if up, too complex + if (contentEditable && !hasContentEditableState && format.block && + !format.wrapper && isTextBlock(nodeName) && isValid(parentName, wrapName)) { + 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 + // TODO: Break this if up, too complex + 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) && + (!format.inline || !isBlock(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(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 = grep(node.childNodes); + for (i = 0; i < children.length; i++) { + currentWrapElm.appendChild(children[i]); + } + + node.appendChild(currentWrapElm); + } + + each(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

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: text + // will become: text + 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 texttext becomes texttext + 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.mce-item-selected,th.mce-item-selected').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)) { + walk(curSelNode, processUnderlineAndColor, 'childNodes'); + processUnderlineAndColor(curSelNode); + } + + selection.moveToBookmark(bookmark); + moveStart(selection.getRng(TRUE)); + ed.nodeChanged(); + } else { + performCaretAction('apply', name, vars); + } + } + } + } + + /** + * Removes the specified format from the current selection or specified node. + * + * @method remove + * @param {String} name Name of format to remove. + * @param {Object} vars Optional list of variables to replace within format before removing it. + * @param {Node/Range} node Optional node or DOM range to remove the format from defaults to current selection. + */ + function remove(name, vars, node) { + var formatList = get(name), format = formatList[0], bookmark, rng, contentEditable = true; + + // Merges the styles for each node + function process(node) { + var children, i, l, 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 = 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; + + 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 + if (/^(TR|TD)$/.test(startContainer.nodeName) && startContainer.firstChild) { + if (startContainer.nodeName == "TD") { + startContainer = startContainer.firstChild || startContainer; + } else { + startContainer = startContainer.firstChild.firstChild || startContainer; + } + } + + // 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.mce-item-selected,th.mce-item-selected').length) { + bookmark = selection.getBookmark(); + removeRngStyle(selection.getRng(TRUE)); + selection.moveToBookmark(bookmark); + + // Check if start element still has formatting then we are at: "text|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); + } + } + + /** + * Toggles the specified format on/off. + * + * @method toggle + * @param {String} name Name of format to apply/remove. + * @param {Object} vars Optional list of variables to replace within format before applying/removing it. + * @param {Node} node Optional node to apply the format to or remove from. Defaults to current selection. + */ + 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); + } + } + + /** + * Return true/false if the specified node has the specified format. + * + * @method matchNode + * @param {Node} node Node to check the format on. + * @param {String} name Format name to check. + * @param {Object} vars Optional list of variables to replace before checking it. + * @param {Boolean} similar Match format that has similar properties. + * @return {Object} Returns the format object it matches or undefined if it doesn't match. + */ + 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; + } + } + } + } + + /** + * Matches the current selection or specified node against the specified format name. + * + * @method match + * @param {String} name Name of format to match. + * @param {Object} vars Optional list of variables to replace before checking it. + * @param {Node} node Optional node to check. + * @return {boolean} true/false if the specified selection/node matches the 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; + } + + /** + * Matches the current selection against the array of formats and returns a new array with matching formats. + * + * @method matchAll + * @param {Array} names Name of format to match. + * @param {Object} vars Optional list of variables to replace before checking it. + * @return {Array} Array with matched formats. + */ + function matchAll(names, vars) { + var startElement, matchedFormatNames = [], checkedMap = {}; + + // 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); + } + } + }, dom.getRoot()); + + return matchedFormatNames; + } + + /** + * Returns true/false if the specified format can be applied to the current selection or not. It + * will currently only check the state for selector formats, it returns true on all other format types. + * + * @method canApply + * @param {String} name Name of format to check. + * @return {boolean} true/false if the specified format can be applied to the current selection/node. + */ + 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; + } + + /** + * Executes the specified callback when the current selection matches the formats or not. + * + * @method formatChanged + * @param {String} formats Comma separated list of formats to check for. + * @param {function} callback Callback with state and args when the format is changed/toggled on/off. + * @param {Boolean} similar True/false state if the match should handle similar or exact formats. + */ + function formatChanged(formats, callback, similar) { + var currentFormats; + + // Setup format node change logic + if (!formatChangeData) { + formatChangeData = {}; + currentFormats = {}; + + ed.on('NodeChange', function(e) { + var parents = getParents(e.element), matchedFormats = {}; + + // Check for new formats + each(formatChangeData, function(callbacks, format) { + each(parents, function(node) { + if (matchNode(node, format, {}, callbacks.similar)) { + if (!currentFormats[format]) { + // Execute callbacks + each(callbacks, function(callback) { + callback(true, {node: node, format: format, parents: parents}); + }); + + currentFormats[format] = callbacks; + } + + matchedFormats[format] = callbacks; + return false; + } + }); + }); + + // Check if current formats still match + each(currentFormats, function(callbacks, format) { + if (!matchedFormats[format]) { + delete currentFormats[format]; + + each(callbacks, function(callback) { + callback(false, {node: e.element, format: format, parents: parents}); + }); + } + }); + }); + } + + // Add format listeners + each(formats.split(','), function(format) { + if (!formatChangeData[format]) { + formatChangeData[format] = []; + formatChangeData[format].similar = similar; + } + + formatChangeData[format].push(callback); + }); + + return this; + } + + // Expose to public + extend(this, { + get: get, + register: register, + apply: apply, + remove: remove, + toggle: toggle, + match: match, + matchAll: matchAll, + matchNode: matchNode, + canApply: canApply, + formatChanged: formatChanged + }); + + // Initialize + defaultFormats(); + addKeyboardShortcuts(); + ed.on('BeforeGetContent', function() { + if (markCaretContainersBogus) { + markCaretContainersBogus(); + } + }); + ed.on('mouseup keydown', function(e) { + if (disableCaretContainer) { + disableCaretContainer(e); + } + }); + + // Private functions + + /** + * Checks if the specified nodes name matches the format inline/block or selector. + * + * @private + * @param {Node} node Node to match against the specified format. + * @param {Object} format Format object o match with. + * @return {boolean} true/false if the format matches. + */ + 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 node.nodeType == 1 && dom.is(node, format.selector); + } + } + + /** + * Compares two string/nodes regardless of their case. + * + * @private + * @param {String/Node} Node or string to compare. + * @param {String/Node} Node or string to compare. + * @return {boolean} True/false if they match. + */ + function isEq(str1, str2) { + str1 = str1 || ''; + str2 = str2 || ''; + + str1 = '' + (str1.nodeName || str1); + str2 = '' + (str2.nodeName || str2); + + return str1.toLowerCase() == str2.toLowerCase(); + } + + /** + * Returns the style by name on the specified node. This method modifies the style + * contents to make it more easy to match. This will resolve a few browser issues. + * + * @private + * @param {Node} node to get style from. + * @param {String} name Style name to get. + * @return {String} Style item value. + */ + 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; + } + + /** + * Replaces variables in the value. The variable format is %var. + * + * @private + * @param {String} value Value to replace variables in. + * @param {Object} vars Name/value array with variables to replace. + * @return {String} New value with replaced variables. + */ + 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; + } + + /** + * Expands the specified range like object to depending on format. + * + * For example on block formats it will move the start/end position + * to the beginning of the current block. + * + * @private + * @param {Object} rng Range like object. + * @param {Array} formats Array with formats to expand by. + * @return {Object} Expanded range like object. + */ + function expandRng(rng, format, remove) { + var 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, sibling, siblingName, root; + + container = parent = start ? startContainer : endContainer; + siblingName = start ? 'previousSibling' : 'nextSibling'; + root = dom.getRoot(); + + function isBogusBr(node) { + return node.nodeName == "BR" && node.getAttribute('data-mce-bogus') && !node.nextSibling; + } + + // 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) && !isBogusBr(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) { + 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, isTextBlock); + } + + // 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 !: !

*texttext*

! + // 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 + }; + } + + /** + * Removes the specified format for the specified node. It will also remove the node if it doesn't have + * any attributes if the format specifies it to do so. + * + * @private + * @param {Object} format Format object with items to remove from node. + * @param {Object} vars Name/value object with variables to apply to format. + * @param {Node} node Node to remove the format styles on. + * @param {Node} compare_node Optional compare node, if specified the styles will be compared to that node. + * @return {Boolean} True/false if the node was removed or not. + */ + 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 or + if (format.remove != 'none') { + removeNode(node, format); + return TRUE; + } + } + + /** + * Removes the node and wrap it's children in paragraphs before doing so or + * appends BR elements to the beginning/end of the block element if forcedRootBlocks is disabled. + * + * If the div in the node below gets removed: + * text
text
text + * + * Output becomes: + * text

text
text + * + * So when the div is removed the result is: + * text
text
text + * + * @private + * @param {Node} node Node to remove + apply BR/P elements to. + * @param {Object} format Format rule. + * @return {Node} Input node. + */ + 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(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); + } + + /** + * Returns the next/previous non whitespace node. + * + * @private + * @param {Node} node Node to start at. + * @param {boolean} next (Optional) Include next or previous node defaults to previous. + * @param {boolean} inc (Optional) Include the current node in checking. Defaults to false. + * @return {Node} Next or previous node or undefined if it wasn't found. + */ + 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; + } + } + } + } + + /** + * Checks if the specified node is a bookmark node or not. + * + * @param {Node} node Node to check if it's a bookmark node or not. + * @return {Boolean} true/false if the node is a bookmark node. + */ + function isBookmarkNode(node) { + return node && node.nodeType == 1 && node.getAttribute('data-mce-type') == 'bookmark'; + } + + /** + * Merges the next/previous sibling element if they match. + * + * @private + * @param {Node} prev Previous node to compare/merge. + * @param {Node} next Next node to compare/merge. + * @return {Node} Next node if we didn't merge and prev node if we did. + */ + function mergeSiblings(prev, next) { + var sibling, tmpSibling; + + /** + * Compares two nodes and checks if it's attributes and styles matches. + * This doesn't compare classes as items since their order is significant. + * + * @private + * @param {Node} node1 First node to compare with. + * @param {Node} node2 Second node to compare with. + * @return {boolean} True/false if the nodes are the same or not. + */ + function compareElements(node1, node2) { + // Not the same name + if (node1.nodeName != node2.nodeName) { + return FALSE; + } + + /** + * Returns all the nodes attributes excluding internal ones, styles and classes. + * + * @private + * @param {Node} node Node to get attributes from. + * @return {Object} Name/value object with attributes and attribute values. + */ + 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; + } + + /** + * Compares two objects checks if it's key + value exists in the other one. + * + * @private + * @param {Object} obj1 First object to compare. + * @param {Object} obj2 Second object to compare. + * @return {boolean} True/false if the objects matches or not. + */ + 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(grep(next.childNodes), function(node) { + prev.appendChild(node); + }); + + return prev; + } + } + + return next; + } + + function getContainer(rng, start) { + var container, offset, lastIdx; + + 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); + } + } + + // Checks if the parent caret container node isn't empty if that is the case it + // will remove the bogus state on all children that isn't empty + function unmarkBogusCaretParents() { + var caretContainer; + + caretContainer = getParentCaretContainer(selection.getStart()); + if (caretContainer && !dom.isEmpty(caretContainer)) { + walk(caretContainer, function(node) { + if (node.nodeType == 1 && node.id !== caretContainerId && !dom.isEmpty(node)) { + dom.setAttrib(node, 'data-mce-bogus', null); + } + }, 'childNodes'); + } + } + + // Only bind the caret events once + if (!ed._hasCaretEvents) { + // Mark current caret container elements as bogus when getting the contents so we don't end up with empty elements + markCaretContainersBogus = 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'); + } + } + }; + + disableCaretContainer = function(e) { + var keyCode = e.keyCode; + + removeCaretContainer(); + + // Remove caret container on keydown and it's a backspace, enter or left/right arrow keys + if (keyCode == 8 || keyCode == 37 || keyCode == 39) { + removeCaretContainer(getParentCaretContainer(selection.getStart())); + } + + unmarkBogusCaretParents(); + }; + + // Remove bogus state if they got filled by contents using editor.selection.setContent + ed.on('SetContent', function(e) { + if (e.selection) { + unmarkBogusCaretParents(); + } + }); + ed._hasCaretEvents = true; + } + + // Do apply or remove caret format + if (type == "apply") { + applyCaretFormat(); + } else { + removeCaretFormat(); + } + } + + /** + * Moves the start to the first suitable text node. + */ + 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; + } + } + } + } + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/LegacyInput.js b/lib/tinymce/jscripts/tinymce4/classes/LegacyInput.js new file mode 100644 index 00000000..09813300 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/LegacyInput.js @@ -0,0 +1,73 @@ +/** + * LegacyInput.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/LegacyInput", [ + "tinymce/EditorManager", + "tinymce/util/Tools" +], function(EditorManager, Tools) { + var each = Tools.each, explode = Tools.explode; + + EditorManager.on('AddEditor', function(e) { + var ed = e.editor; + + ed.on('preInit', function() { + var filters, fontSizes, dom, settings = ed.settings; + + function replaceWithSpan(node, styles) { + each(styles, function(value, name) { + if (value) { + dom.setStyle(node, name, value); + } + }); + + dom.rename(node, 'span'); + } + + function convert(e) { + dom = ed.dom; + + if (settings.convert_fonts_to_spans) { + each(dom.select('font,u,strike', e.node), function(node) { + filters[node.nodeName.toLowerCase()](dom, node); + }); + } + } + + if (settings.inline_styles) { + fontSizes = 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.on('PreProcess SetContent', convert); + } + }); + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/Shortcuts.js b/lib/tinymce/jscripts/tinymce4/classes/Shortcuts.js new file mode 100644 index 00000000..3d4dd1ff --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/Shortcuts.js @@ -0,0 +1,111 @@ +/** + * Shortcuts.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Contains all logic for handling of keyboard shortcuts. + */ +define("tinymce/Shortcuts", [ + "tinymce/util/Tools", + "tinymce/Env" +], function(Tools, Env) { + var each = Tools.each, explode = Tools.explode; + + var keyCodeLookup = { + "f9": 120, + "f10": 121, + "f11": 122 + }; + + return function(editor) { + var self = this, shortcuts = {}; + + editor.on('keyup keypress keydown', function(e) { + if (e.altKey || e.ctrlKey || e.metaKey) { + each(shortcuts, function(shortcut) { + var ctrlState = Env.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 (e.type == "keydown") { + shortcut.func.call(shortcut.scope); + } + + return true; + } + }); + } + }); + + /** + * Adds a keyboard shortcut for some command or function. + * + * @method addShortcut + * @param {String} pattern Shortcut pattern. Like for example: ctrl+alt+o. + * @param {String} desc Text description for the command. + * @param {String/Function} cmdFunc Command name string or function to execute when the key is pressed. + * @param {Object} sc Optional scope to execute the function in. + * @return {Boolean} true/false state if the shortcut was added or not. + */ + self.add = function(pattern, desc, cmdFunc, scope) { + var cmd; + + cmd = cmdFunc; + + if (typeof(cmdFunc) === 'string') { + cmdFunc = function() { + editor.execCommand(cmd, false, null); + }; + } else if (cmdFunc.length) { + cmdFunc = function() { + editor.execCommand(cmd[0], cmd[1], cmd[2]); + }; + } + + each(explode(pattern.toLowerCase()), function(pattern) { + var shortcut = { + func: cmdFunc, + scope: scope || editor, + desc: editor.translate(desc), + alt: false, + ctrl: false, + shift: false + }; + + each(explode(pattern, '+'), function(value) { + switch (value) { + case 'alt': + case 'ctrl': + case 'shift': + shortcut[value] = true; + break; + + default: + shortcut.charCode = value.charCodeAt(0); + shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0); + } + }); + + shortcuts[ + (shortcut.ctrl ? 'ctrl' : '') + ',' + + (shortcut.alt ? 'alt' : '') + ',' + + (shortcut.shift ? 'shift' : '') + ',' + + shortcut.keyCode + ] = shortcut; + }); + + return true; + }; + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/UndoManager.js b/lib/tinymce/jscripts/tinymce4/classes/UndoManager.js new file mode 100644 index 00000000..330ca999 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/UndoManager.js @@ -0,0 +1,301 @@ +/** + * UndoManager.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles the undo/redo history levels for the editor. Since the build in undo/redo has major drawbacks a custom one was needed. + * + * @class tinymce.UndoManager + */ +define("tinymce/UndoManager", [ + "tinymce/Env", + "tinymce/util/Tools" +], function(Env, Tools) { + var trim = Tools.trim, trimContentRegExp; + + trimContentRegExp = new RegExp([ + ']+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\\/span>', // Trim bogus spans like caret containers + ']+data-mce-bogus[^>]+><\\/div>', // Trim bogus divs like resize handles + '\\s?data-mce-selected="[^"]+"' // Trim temporaty data-mce prefixed attributes like data-mce-selected + ].join('|'), 'gi'); + + return function(editor) { + var self, index = 0, data = [], beforeBookmark; + + // Returns a trimmed version of the current editor contents + function getContent() { + return trim(editor.getContent({format: 'raw', no_events: 1}).replace(trimContentRegExp, '')); + } + + function addNonTypingUndoLevel() { + self.typing = false; + self.add(); + } + + // Add initial undo level when the editor is initialized + editor.on('init', function() { + self.add(); + }); + + // Get position before an execCommand is processed + editor.on('BeforeExecCommand', function(e) { + var cmd = e.command; + + if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint') { + self.beforeChange(); + } + }); + + // Add undo level after an execCommand call was made + editor.on('ExecCommand', function(e) { + var cmd = e.command; + + if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint') { + self.add(); + } + }); + + editor.on('ObjectResizeStart', function() { + self.beforeChange(); + }); + + editor.on('SaveContent ObjectResized', addNonTypingUndoLevel); + editor.dom.bind(editor.dom.getRoot(), 'dragend', addNonTypingUndoLevel); + editor.dom.bind(editor.getBody(), 'focusout', function() { + if (!editor.removed && self.typing) { + addNonTypingUndoLevel(); + } + }); + + editor.on('KeyUp', function(e) { + var keyCode = e.keyCode; + + if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 45 || keyCode == 13 || e.ctrlKey) { + addNonTypingUndoLevel(); + editor.nodeChanged(); + } + + if (keyCode == 46 || keyCode == 8 || (Env.isMac && (keyCode == 91 || keyCode == 93))) { + editor.nodeChanged(); + } + }); + + editor.on('KeyDown', function(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.on('MouseDown', function() { + 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'); + + editor.on('AddUndo Undo Redo ClearUndos MouseUp', function(e) { + if (!e.isDefaultPrevented()) { + editor.nodeChanged(); + } + }); + + self = { + // Explose for debugging reasons + data: data, + + /** + * State if the user is currently typing or not. This will add a typing operation into one undo + * level instead of one new level for each keystroke. + * + * @field {Boolean} typing + */ + typing: false, + + /** + * Stores away a bookmark to be used when performing an undo action so that the selection is before + * the change has been made. + * + * @method beforeChange + */ + beforeChange: function() { + beforeBookmark = editor.selection.getBookmark(2, true); + }, + + /** + * Adds a new undo level/snapshot to the undo list. + * + * @method add + * @param {Object} l Optional undo level object to add. + * @return {Object} Undo level that got added or null it a level wasn't needed. + */ + add: function(level) { + var i, settings = editor.settings, lastLevel; + + level = level || {}; + level.content = getContent(); + + if (editor.fire('BeforeAddUndo', {level: level}).isDefaultPrevented()) { + return null; + } + + // 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; + + editor.fire('AddUndo', {level: level, lastLevel: lastLevel}); + editor.isNotDirty = 0; + + return level; + }, + + /** + * Undoes the last action. + * + * @method undo + * @return {Object} Undo level or null if no undo was performed. + */ + undo: function() { + var level; + + 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); + + editor.fire('undo', {level: level}); + } + + return level; + }, + + /** + * Redoes the last action. + * + * @method redo + * @return {Object} Redo level or null if no redo was performed. + */ + redo: function() { + var level; + + if (index < data.length - 1) { + level = data[++index]; + + editor.setContent(level.content, {format: 'raw'}); + editor.selection.moveToBookmark(level.bookmark); + + editor.fire('redo', {level: level}); + } + + return level; + }, + + /** + * Removes all undo levels. + * + * @method clear + */ + clear: function() { + data = []; + index = 0; + self.typing = false; + editor.fire('ClearUndos'); + }, + + /** + * Returns true/false if the undo manager has any undo levels. + * + * @method hasUndo + * @return {Boolean} true/false if the undo manager has any undo levels. + */ + hasUndo: function() { + // Has undo levels or typing and content isn't the same as the initial level + return index > 0 || (self.typing && data[0] && getContent() != data[0].content); + }, + + /** + * Returns true/false if the undo manager has any redo levels. + * + * @method hasRedo + * @return {Boolean} true/false if the undo manager has any redo levels. + */ + hasRedo: function() { + return index < data.length - 1 && !this.typing; + }, + + /** + * Executes the specified function in an undo transation. The selection + * before the modification will be stored to the undo stack and if the DOM changes + * it will add a new undo level. + * + * @method transact + * @params {function} callback + */ + transact: function(callback) { + self.beforeChange(); + callback(); + self.add(); + } + }; + + return self; + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/WindowManager.js b/lib/tinymce/jscripts/tinymce4/classes/WindowManager.js new file mode 100644 index 00000000..484f12c7 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/WindowManager.js @@ -0,0 +1,175 @@ +/** + * WindowManager.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles the creation of native windows and dialogs. This class can be extended to provide for example inline dialogs. + * + * @class tinymce.WindowManager + * @example + * // Opens a new dialog with the file.htm file and the size 320x240 + * // It also adds a custom parameter this can be retrieved by using tinyMCEPopup.getWindowArg inside the dialog. + * tinymce.activeEditor.windowManager.open({ + * url: 'file.htm', + * width: 320, + * height: 240 + * }, { + * custom_param: 1 + * }); + * + * // Displays an alert box using the active editors window manager instance + * tinymce.activeEditor.windowManager.alert('Hello world!'); + * + * // Displays an confirm box and an alert message will be displayed depending on what you choose in the confirm + * tinymce.activeEditor.windowManager.confirm("Do you want to do something", function(s) { + * if (s) + * tinymce.activeEditor.windowManager.alert("Ok"); + * else + * tinymce.activeEditor.windowManager.alert("Cancel"); + * }); + */ +define("tinymce/WindowManager", [ + "tinymce/ui/Window", + "tinymce/ui/MessageBox" +], function(Window, MessageBox) { + return function(editor) { + var self = this, windows = []; + + self.windows = windows; + + /** + * Opens a new window. + * + * @method open + * @param {Object} args Optional name/value settings collection contains things like width/height/url etc. + * @option {String} title Window title. + * @option {String} file URL of the file to open in the window. + * @option {Number} width Width in pixels. + * @option {Number} height Height in pixels. + * @option {Boolean} resizable Specifies whether the popup window is resizable or not. + * @option {Boolean} maximizable Specifies whether the popup window has a "maximize" button and can get maximized or not. + * @option {String/bool} scrollbars Specifies whether the popup window can have scrollbars if required (i.e. content + * larger than the popup size specified). + */ + self.open = function(args) { + var win; + + // Handle URL + args.url = args.url || args.file; // Legacy + if (args.url) { + args.width = parseInt(args.width || 320, 10); + args.height = parseInt(args.height || 240, 10); + } + + // Handle body + if (args.body) { + args.items = { + defaults: args.defaults, + type: args.bodyType || 'form', + items: args.body + }; + } + + if (!args.url && !args.buttons) { + args.buttons = [ + {text: 'Ok', subtype: 'primary', minWidth: 50, onclick: function() { + win.find('form')[0].submit(); + win.close(); + }}, + + {text: 'Cancel', onclick: function() { + win.close(); + }} + ]; + } + + win = new Window(args); + windows.push(win); + + win.on('close', function() { + var i = windows.length; + + while (i--) { + if (windows[i] === win) { + windows.splice(i, 1); + } + } + + editor.focus(); + }); + + // Handle data + if (args.data) { + win.on('postRender', function() { + this.find('*').each(function(ctrl) { + var name = ctrl.name(); + + if (name in args.data) { + ctrl.value(args.data[name]); + } + }); + }); + } + + return win.renderTo(document.body).reflow(); + }; + + /** + * Creates a alert dialog. Please don't use the blocking behavior of this + * native version use the callback method instead then it can be extended. + * + * @method alert + * @param {String} message Text to display in the new alert dialog. + * @param {function} callback Callback function to be executed after the user has selected ok. + * @param {Object} scope Optional scope to execute the callback in. + * @example + * // Displays an alert box using the active editors window manager instance + * tinymce.activeEditor.windowManager.alert('Hello world!'); + */ + self.alert = function(message, callback, scope) { + MessageBox.alert(message, function() { + callback.call(scope || this); + }); + }; + + /** + * Creates a confirm dialog. Please don't use the blocking behavior of this + * native version use the callback method instead then it can be extended. + * + * @method confirm + * @param {String} messageText to display in the new confirm dialog. + * @param {function} callback Callback function to be executed after the user has selected ok or cancel. + * @param {Object} scope Optional scope to execute the callback in. + * @example + * // Displays an confirm box and an alert message will be displayed depending on what you choose in the confirm + * tinymce.activeEditor.windowManager.confirm("Do you want to do something", function(s) { + * if (s) + * tinymce.activeEditor.windowManager.alert("Ok"); + * else + * tinymce.activeEditor.windowManager.alert("Cancel"); + * }); + */ + self.confirm = function(message, callback, scope) { + MessageBox.confirm(message, function(state) { + callback.call(scope || this, state); + }); + }; + + /** + * Closes the top most window. + * + * @method close + */ + self.close = function() { + if (windows.length) { + windows[window.length - 1].win.close(); + } + }; + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/dom/ControlSelection.js b/lib/tinymce/jscripts/tinymce4/classes/dom/ControlSelection.js new file mode 100644 index 00000000..78946337 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/dom/ControlSelection.js @@ -0,0 +1,450 @@ +/** + * ControlSelection.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles control selection of elements. Controls are elements + * that can be resized and needs to be selected as a whole. It adds custom resize handles + * to all browser engines that support properly disabling the built in logic. + * + * @class tinymce.dom.ControlSelection + */ +define("tinymce/dom/ControlSelection", [ + "tinymce/util/VK", + "tinymce/util/Tools", + "tinymce/Env" +], function(VK, Tools, Env) { + return function(selection, editor) { + var dom = editor.dom, each = Tools.each; + var selectedElm, selectedElmGhost, resizeHandles, selectedHandle; + var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted; + var width, height, editableDoc = editor.getDoc(), rootDocument = document, isIE = Env.ie; + + // Details about each resize handle how to scale etc + resizeHandles = { + // Name: x multiplier, y multiplier, delta size x, delta size y + n: [0.5, 0, 0, -1], + e: [1, 0.5, 1, 0], + s: [0.5, 1, 0, 1], + w: [0, 0.5, -1, 0], + nw: [0, 0, -1, -1], + ne: [1, 0, 1, -1], + se: [1, 1, 1, 1], + sw: [0, 1, -1, 1] + }; + + // Add CSS for resize handles, cloned element and selected + var rootClass = '.mce-content-body'; + editor.contentStyles.push( + rootClass + ' div.mce-resizehandle {' + + 'position: absolute;' + + 'border: 1px solid black;' + + 'background: #FFF;' + + 'width: 5px;' + + 'height: 5px;' + + 'z-index: 10000' + + '}' + + rootClass + ' .mce-resizehandle:hover {' + + 'background: #000' + + '}' + + rootClass + ' img[data-mce-selected], hr[data-mce-selected] {' + + 'outline: 1px solid black;' + + 'resize: none' + // Have been talks about implementing this in browsers + '}' + + rootClass + ' .mce-clonedresizable {' + + 'position: absolute;' + + (Env.gecko ? '' : 'outline: 1px dashed black;') + // Gecko produces trails while resizing + 'opacity: .5;' + + 'filter: alpha(opacity=50);' + + 'z-index: 10000' + + '}' + ); + + function isResizable(elm) { + if (editor.settings.object_resizing === false) { + return false; + } + + if (!/TABLE|IMG|DIV/.test(elm.nodeName)) { + return false; + } + + if (elm.getAttribute('data-mce-resize') === 'false') { + return false; + } + + return true; + } + + function resizeGhostElement(e) { + var deltaX, deltaY; + + // Calc new width/height + deltaX = e.screenX - startX; + deltaY = e.screenY - startY; + + // Calc new size + width = deltaX * selectedHandle[2] + startW; + height = deltaY * selectedHandle[3] + startH; + + // Never scale down lower than 5 pixels + width = width < 5 ? 5 : width; + height = height < 5 ? 5 : height; + + // Constrain proportions when modifier key is pressed or if the nw, ne, sw, se corners are moved on an image + if (VK.modifierPressed(e) || (selectedElm.nodeName == "IMG" && selectedHandle[2] * selectedHandle[3] !== 0)) { + width = Math.round(height / ratio); + height = Math.round(width * ratio); + } + + // Update ghost size + dom.setStyles(selectedElmGhost, { + width: width, + height: height + }); + + // Update ghost X position if needed + if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) { + dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width)); + } + + // Update ghost Y position if needed + if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) { + dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height)); + } + + if (!resizeStarted) { + editor.fire('ObjectResizeStart', {target: selectedElm, width: startW, height: startH}); + resizeStarted = true; + } + } + + function endGhostResize() { + resizeStarted = false; + + function setSizeProp(name, value) { + if (value) { + // Resize by using style or attribute + if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) { + dom.setStyle(selectedElm, name, value); + } else { + dom.setAttrib(selectedElm, name, value); + } + } + } + + // Set width/height properties + setSizeProp('width', width); + setSizeProp('height', height); + + dom.unbind(editableDoc, 'mousemove', resizeGhostElement); + dom.unbind(editableDoc, 'mouseup', endGhostResize); + + if (rootDocument != editableDoc) { + dom.unbind(rootDocument, 'mousemove', resizeGhostElement); + dom.unbind(rootDocument, 'mouseup', endGhostResize); + } + + // Remove ghost and update resize handle positions + dom.remove(selectedElmGhost); + + if (!isIE || selectedElm.nodeName == "TABLE") { + showResizeRect(selectedElm); + } + + editor.fire('ObjectResized', {target: selectedElm, width: width, height: height}); + editor.nodeChanged(); + } + + function showResizeRect(targetElm, mouseDownHandleName, mouseDownEvent) { + var position, targetWidth, targetHeight, e, rect; + + // Get position and size of target + position = dom.getPos(targetElm, editor.getBody()); + selectedElmX = position.x; + selectedElmY = position.y; + rect = targetElm.getBoundingClientRect(); // Fix for Gecko offsetHeight for table with caption + targetWidth = rect.width; + targetHeight = rect.height; + + // Reset width/height if user selects a new image/table + if (selectedElm != targetElm) { + detachResizeStartListener(); + selectedElm = targetElm; + width = height = 0; + } + + // Makes it possible to disable resizing + e = editor.fire('ObjectSelected', {target: targetElm}); + + if (isResizable(targetElm) && !e.isDefaultPrevented()) { + each(resizeHandles, function(handle, name) { + var handleElm, handlerContainerElm; + + function startDrag(e) { + resizeStarted = true; + + startX = e.screenX; + startY = e.screenY; + startW = selectedElm.clientWidth; + startH = selectedElm.clientHeight; + ratio = startH / startW; + selectedHandle = handle; + + selectedElmGhost = selectedElm.cloneNode(true); + dom.addClass(selectedElmGhost, 'mce-clonedresizable'); + selectedElmGhost.contentEditable = false; // Hides IE move layer cursor + selectedElmGhost.unSelectabe = true; + dom.setStyles(selectedElmGhost, { + left: selectedElmX, + top: selectedElmY, + margin: 0 + }); + + selectedElmGhost.removeAttribute('data-mce-selected'); + editor.getBody().appendChild(selectedElmGhost); + + dom.bind(editableDoc, 'mousemove', resizeGhostElement); + dom.bind(editableDoc, 'mouseup', endGhostResize); + + if (rootDocument != editableDoc) { + dom.bind(rootDocument, 'mousemove', resizeGhostElement); + dom.bind(rootDocument, 'mouseup', endGhostResize); + } + } + + if (mouseDownHandleName) { + // Drag started by IE native resizestart + if (name == mouseDownHandleName) { + startDrag(mouseDownEvent); + } + + return; + } + + // Get existing or render resize handle + handleElm = dom.get('mceResizeHandle' + name); + if (!handleElm) { + handlerContainerElm = editor.getBody(); + + handleElm = dom.add(handlerContainerElm, 'div', { + id: 'mceResizeHandle' + name, + 'data-mce-bogus': true, + 'class': 'mce-resizehandle', + contentEditable: false, // Hides IE move layer cursor + unSelectabe: true, + style: 'cursor:' + name + '-resize; margin:0; padding:0' + }); + + dom.bind(handleElm, 'mousedown', function(e) { + e.preventDefault(); + startDrag(e); + }); + } else { + dom.show(handleElm); + } + + /* + var halfHandleW = handleElm.offsetWidth / 2; + var halfHandleH = handleElm.offsetHeight / 2; + + // Position element + dom.setStyles(handleElm, { + left: Math.floor((targetWidth * handle[0] + selectedElmX) - halfHandleW + (handle[2] * halfHandleW)), + top: Math.floor((targetHeight * handle[1] + selectedElmY) - halfHandleH + (handle[3] * halfHandleH)) + }); + */ + + // Position element + dom.setStyles(handleElm, { + left: (targetWidth * handle[0] + selectedElmX) - (handleElm.offsetWidth / 2), + top: (targetHeight * handle[1] + selectedElmY) - (handleElm.offsetHeight / 2) + }); + }); + } else { + hideResizeRect(); + } + + selectedElm.setAttribute('data-mce-selected', '1'); + } + + function hideResizeRect() { + var name, handleElm; + + if (selectedElm) { + selectedElm.removeAttribute('data-mce-selected'); + } + + for (name in resizeHandles) { + handleElm = dom.get('mceResizeHandle' + name); + if (handleElm) { + dom.unbind(handleElm); + dom.remove(handleElm); + } + } + } + + function updateResizeRect(e) { + var controlElm; + + function isChildOrEqual(node, parent) { + do { + if (node === parent) { + return true; + } + } while ((node = node.parentNode)); + } + + // Remove data-mce-selected from all elements since they might have been copied using Ctrl+c/v + each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function(img) { + img.removeAttribute('data-mce-selected'); + }); + + controlElm = e.type == 'mousedown' ? e.target : selection.getNode(); + controlElm = dom.getParent(controlElm, isIE ? 'table' : 'table,img,hr'); + + if (controlElm) { + if (isChildOrEqual(selection.getStart(), controlElm) && isChildOrEqual(selection.getEnd(), controlElm)) { + if (!isIE || (controlElm != selection.getStart() && selection.getStart().nodeName !== 'IMG')) { + showResizeRect(controlElm); + return; + } + } + } + + hideResizeRect(); + } + + function attachEvent(elm, name, func) { + if (elm && elm.attachEvent) { + elm.attachEvent('on' + name, func); + } + } + + function detachEvent(elm, name, func) { + if (elm && elm.detachEvent) { + elm.detachEvent('on' + name, func); + } + } + + function resizeNativeStart(e) { + var target = e.srcElement, pos, name, corner, cornerX, cornerY, relativeX, relativeY; + + pos = target.getBoundingClientRect(); + relativeX = e.clientX - pos.left; + relativeY = e.clientY - pos.top; + + // Figure out what corner we are draging on + for (name in resizeHandles) { + corner = resizeHandles[name]; + + cornerX = target.offsetWidth * corner[0]; + cornerY = target.offsetHeight * corner[1]; + + if (Math.abs(cornerX - relativeX) < 8 && Math.abs(cornerY - relativeY) < 8) { + selectedHandle = corner; + break; + } + } + + // Remove native selection and let the magic begin + resizeStarted = true; + editor.getDoc().selection.empty(); + showResizeRect(target, name, e); + } + + function nativeControlSelect(e) { + var target = e.srcElement; + + if (target != selectedElm) { + detachResizeStartListener(); + + if (target.id.indexOf('mceResizeHandle') === 0) { + e.returnValue = false; + return; + } + + if (target.nodeName == 'IMG' || target.nodeName == 'TABLE') { + hideResizeRect(); + selectedElm = target; + attachEvent(target, 'resizestart', resizeNativeStart); + } + } + } + + function detachResizeStartListener() { + detachEvent(selectedElm, 'resizestart', resizeNativeStart); + } + + function controlSelect(elm) { + var ctrlRng; + + if (!isIE) { + return; + } + + ctrlRng = editableDoc.body.createControlRange(); + + try { + ctrlRng.addElement(elm); + ctrlRng.select(); + return true; + } catch (ex) { + // Ignore since the element can't be control selected for example a P tag + } + } + + editor.on('init', function() { + if (isIE) { + // Hide the resize rect on resize and reselect the image + editor.on('ObjectResized', function(e) { + if (e.target.nodeName != 'TABLE') { + hideResizeRect(); + controlSelect(e.target); + } + }); + + attachEvent(editor.getBody(), 'controlselect', nativeControlSelect); + } else { + try { + // Disable object resizing on Gecko + editor.getDoc().execCommand('enableObjectResizing', false, false); + } catch (ex) { + // Ignore + } + } + + editor.on('nodechange mousedown ResizeEditor', updateResizeRect); + + // Update resize rect while typing in a table + editor.on('keydown keyup', function(e) { + if (selectedElm && selectedElm.nodeName == "TABLE") { + updateResizeRect(e); + } + }); + + // Hide rect on focusout since it would float on top of windows otherwise + //editor.on('focusout', hideResizeRect); + }); + + function destroy() { + selectedElm = selectedElmGhost = null; + + if (isIE) { + detachResizeStartListener(); + detachEvent(editor.getBody(), 'controlselect', nativeControlSelect); + } + } + + return { + controlSelect: controlSelect, + destroy: destroy + }; + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/dom/DOMUtils.js b/lib/tinymce/jscripts/tinymce4/classes/dom/DOMUtils.js new file mode 100644 index 00000000..ea6c5bb3 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/dom/DOMUtils.js @@ -0,0 +1,2067 @@ +/** + * DOMUtils.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Utility class for various DOM manipulation and retrival functions. + * + * @class tinymce.dom.DOMUtils + * @example + * // Add a class to an element by id in the page + * tinymce.DOM.addClass('someid', 'someclass'); + * + * // Add a class to an element by id inside the editor + * tinymce.activeEditor.dom.addClass('someid', 'someclass'); + */ +define("tinymce/dom/DOMUtils", [ + "tinymce/dom/Sizzle", + "tinymce/html/Styles", + "tinymce/dom/EventUtils", + "tinymce/dom/TreeWalker", + "tinymce/dom/Range", + "tinymce/html/Entities", + "tinymce/Env", + "tinymce/util/Tools" +], function(Sizzle, Styles, EventUtils, TreeWalker, Range, Entities, Env, Tools) { + // Shorten names + var each = Tools.each, is = Tools.is, grep = Tools.grep, trim = Tools.trim, extend = Tools.extend; + var isWebKit = Env.webkit, isIE = Env.ie; + var simpleSelectorRe = /^([a-z0-9],?)+$/i; + var whiteSpaceRegExp = /^[ \t\r\n]*$/; + var numericCssMap = Tools.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' '); + + /** + * Constructs a new DOMUtils instance. Consult the Wiki for more details on settings etc for this class. + * + * @constructor + * @method DOMUtils + * @param {Document} d Document reference to bind the utility class to. + * @param {settings} s Optional settings collection. + */ + function DOMUtils(doc, settings) { + var self = this, blockElementsMap; + + self.doc = doc; + self.win = window; + self.files = {}; + self.counter = 0; + self.stdMode = !isIE || doc.documentMode >= 8; + self.boxModel = !isIE || doc.compatMode == "CSS1Compat" || self.stdMode; + self.hasOuterHTML = "outerHTML" in doc.createElement("a"); + + self.settings = settings = extend({ + keep_values: false, + hex_colors: 1 + }, settings); + + self.schema = settings.schema; + self.styles = new Styles({ + url_converter: settings.url_converter, + url_converter_scope: settings.url_converter_scope + }, settings.schema); + + self.fixDoc(doc); + self.events = settings.ownEvents ? new EventUtils(settings.proxy) : EventUtils.Event; + blockElementsMap = settings.schema ? settings.schema.getBlockElements() : {}; + + /** + * Returns true/false if the specified element is a block element or not. + * + * @method isBlock + * @param {Node/String} node Element/Node to check. + * @return {Boolean} True/False state if the node is a block element or not. + */ + self.isBlock = function(node) { + // Fix for #5446 + if (!node) { + return false; + } + + // 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]; + }; + } + + DOMUtils.prototype = { + root: null, + 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" + }, + + 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; + }, + + /** + * Returns the root node of the document this is normally the body but might be a DIV. Parents like getParent will not + * go above the point of this root node. + * + * @method getRoot + * @return {Element} Root element for the utility class. + */ + getRoot: function() { + var self = this; + + return self.get(self.settings.root_element) || self.doc.body; + }, + + /** + * Returns the viewport of the window. + * + * @method getViewPort + * @param {Window} win Optional window to get viewport of. + * @return {Object} Viewport object with fields x, y, w and h. + */ + getViewPort: function(win) { + var doc, rootElm; + + win = !win ? this.win : win; + doc = win.document; + rootElm = this.boxModel ? doc.documentElement : doc.body; + + // Returns viewport size excluding scrollbars + return { + x: win.pageXOffset || rootElm.scrollLeft, + y: win.pageYOffset || rootElm.scrollTop, + w: win.innerWidth || rootElm.clientWidth, + h: win.innerHeight || rootElm.clientHeight + }; + }, + + /** + * Returns the rectangle for a specific element. + * + * @method getRect + * @param {Element/String} elm Element object or element ID to get rectange from. + * @return {object} Rectange for specified element object with x, y, w, h fields. + */ + getRect: function(elm) { + var self = this, pos, size; + + elm = self.get(elm); + pos = self.getPos(elm); + size = self.getSize(elm); + + return { + x: pos.x, y: pos.y, + w: size.w, h: size.h + }; + }, + + /** + * Returns the size dimensions of the specified element. + * + * @method getSize + * @param {Element/String} elm Element object or element ID to get rectange from. + * @return {object} Rectange for specified element object with w, h fields. + */ + getSize: function(elm) { + var self = this, w, h; + + elm = self.get(elm); + w = self.getStyle(elm, 'width'); + h = self.getStyle(elm, '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) || elm.offsetWidth || elm.clientWidth, + h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight + }; + }, + + /** + * Returns a node by the specified selector function. This function will + * loop through all parent nodes and call the specified function for each node. + * If the function then returns true indicating that it has found what it was looking for, the loop execution will then end + * and the node it found will be returned. + * + * @method getParent + * @param {Node/String} node DOM node to search parents on or ID string. + * @param {function} selector Selection function or CSS selector to execute on each node. + * @param {Node} root Optional root element, never go below this point. + * @return {Node} DOM Node or null if it wasn't found. + */ + getParent: function(node, selector, root) { + return this.getParents(node, selector, root, false); + }, + + /** + * Returns a node list of all parents matching the specified selector function or pattern. + * If the function then returns true indicating that it has found what it was looking for and that node will be collected. + * + * @method getParents + * @param {Node/String} node DOM node to search parents on or ID string. + * @param {function} selector Selection function to execute on each node or CSS pattern. + * @param {Node} root Optional root element, never go below this point. + * @return {Array} Array of nodes or null if it wasn't found. + */ + getParents: function(node, selector, root, collect) { + var self = this, selectorVal, result = []; + + node = self.get(node); + collect = collect === undefined; + + // Wrap node name as func + if (is(selector, 'string')) { + selectorVal = selector; + + if (selector === '*') { + selector = function(node) {return node.nodeType == 1;}; + } else { + selector = function(node) { + return self.is(node, selectorVal); + }; + } + } + + while (node) { + if (node == root || !node.nodeType || node.nodeType === 9) { + break; + } + + if (!selector || selector(node)) { + if (collect) { + result.push(node); + } else { + return node; + } + } + + node = node.parentNode; + } + + return collect ? result : null; + }, + + /** + * Returns the specified element by ID or the input element if it isn't a string. + * + * @method get + * @param {String/Element} n Element id to look for or element to just pass though. + * @return {Element} Element matching the specified id or null if it wasn't found. + */ + get: function(elm) { + var name; + + if (elm && this.doc && typeof(elm) == 'string') { + name = elm; + elm = this.doc.getElementById(elm); + + // IE and Opera returns meta elements when they match the specified input ID, but getElementsByName seems to do the trick + if (elm && elm.id !== name) { + return this.doc.getElementsByName(name)[1]; + } + } + + return elm; + }, + + /** + * Returns the next node that matches selector or function + * + * @method getNext + * @param {Node} node Node to find siblings from. + * @param {String/function} selector Selector CSS expression or function. + * @return {Node} Next node item matching the selector or null if it wasn't found. + */ + getNext: function(node, selector) { + return this._findSib(node, selector, 'nextSibling'); + }, + + /** + * Returns the previous node that matches selector or function + * + * @method getPrev + * @param {Node} node Node to find siblings from. + * @param {String/function} selector Selector CSS expression or function. + * @return {Node} Previous node item matching the selector or null if it wasn't found. + */ + getPrev: function(node, selector) { + return this._findSib(node, selector, 'previousSibling'); + }, + + // #ifndef jquery + + /** + * Selects specific elements by a CSS level 3 pattern. For example "div#a1 p.test". + * This function is optimized for the most common patterns needed in TinyMCE but it also performes good enough + * on more complex patterns. + * + * @method select + * @param {String} selector CSS level 3 pattern to select/find elements by. + * @param {Object} scope Optional root element/scope element to search in. + * @return {Array} Array with all matched elements. + * @example + * // Adds a class to all paragraphs in the currently active editor + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass'); + * + * // Adds a class to all spans that has the test class in the currently active editor + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('span.test'), 'someclass') + */ + select: function(selector, scope) { + var self = this; + + //Sizzle.selectors.cacheLength = 0; + return Sizzle(selector, self.get(scope) || self.get(self.settings.root_element) || self.doc, []); + }, + + /** + * Returns true/false if the specified element matches the specified css pattern. + * + * @method is + * @param {Node/NodeList} elm DOM node to match or an array of nodes to match. + * @param {String} selector CSS pattern to match the element agains. + */ + is: function(elm, selector) { + var i; + + // If it isn't an array then try to do some simple selectors instead of Sizzle for to boost performance + if (elm.length === undefined) { + // Simple all selector + if (selector === '*') { + return elm.nodeType == 1; + } + + // Simple selector just elements + if (simpleSelectorRe.test(selector)) { + selector = selector.toLowerCase().split(/,/); + elm = elm.nodeName.toLowerCase(); + + for (i = selector.length - 1; i >= 0; i--) { + if (selector[i] == elm) { + return true; + } + } + + return false; + } + } + + return Sizzle.matches(selector, elm.nodeType ? [elm] : elm).length > 0; + }, + + // #endif + + /** + * Adds the specified element to another element or elements. + * + * @method add + * @param {String/Element/Array} parentElm Element id string, DOM node element or array of id's or elements to add to. + * @param {String/Element} name Name of new element to add or existing element to add. + * @param {Object} attrs Optional object collection with arguments to add to the new element(s). + * @param {String} html Optional inner HTML contents to add for each element. + * @return {Element/Array} Element that got created or array with elements if multiple elements where passed. + * @example + * // Adds a new paragraph to the end of the active editor + * tinymce.activeEditor.dom.add(tinymce.activeEditor.getBody(), 'p', {title: 'my title'}, 'Some content'); + */ + add: function(parentElm, name, attrs, html, create) { + var self = this; + + return this.run(parentElm, function(parentElm) { + var newElm; + + newElm = is(name, 'string') ? self.doc.createElement(name) : name; + self.setAttribs(newElm, attrs); + + if (html) { + if (html.nodeType) { + newElm.appendChild(html); + } else { + self.setHTML(newElm, html); + } + } + + return !create ? parentElm.appendChild(newElm) : newElm; + }); + }, + + /** + * Creates a new element. + * + * @method create + * @param {String} name Name of new element. + * @param {Object} attrs Optional object name/value collection with element attributes. + * @param {String} html Optional HTML string to set as inner HTML of the element. + * @return {Element} HTML DOM node element that got created. + * @example + * // Adds an element where the caret/selection is in the active editor + * var el = tinymce.activeEditor.dom.create('div', {id: 'test', 'class': 'myclass'}, 'some content'); + * tinymce.activeEditor.selection.setNode(el); + */ + create: function(name, attrs, html) { + return this.add(this.doc.createElement(name), name, attrs, html, 1); + }, + + /** + * Create HTML string for element. The element will be closed unless an empty inner HTML string is passed. + * + * @method createHTML + * @param {String} name Name of new element. + * @param {Object} attrs Optional object name/value collection with element attributes. + * @param {String} html Optional HTML string to set as inner HTML of the element. + * @return {String} String with new HTML element like for example: test. + * @example + * // Creates a html chunk and inserts it at the current selection/caret location + * tinymce.activeEditor.selection.setContent(tinymce.activeEditor.dom.createHTML('a', {href: 'test.html'}, 'some line')); + */ + createHTML: function(name, attrs, html) { + var outHtml = '', key; + + outHtml += '<' + name; + + for (key in attrs) { + if (attrs.hasOwnProperty(key)) { + outHtml += ' ' + key + '="' + this.encode(attrs[key]) + '"'; + } + } + + // A call to tinymce.is doesn't work for some odd reason on IE9 possible bug inside their JS runtime + if (typeof(html) != "undefined") { + return outHtml + '>' + html + ''; + } + + return outHtml + ' />'; + }, + + /** + * Creates a document fragment out of the specified HTML string. + * + * @method createFragment + * @param {String} html Html string to create fragment from. + * @return {DocumentFragment} Document fragment node. + */ + createFragment: function(html) { + var frag, node, doc = this.doc, container; + + container = doc.createElement("div"); + frag = doc.createDocumentFragment(); + + if (html) { + container.innerHTML = html; + } + + while ((node = container.firstChild)) { + frag.appendChild(node); + } + + return frag; + }, + + /** + * Removes/deletes the specified element(s) from the DOM. + * + * @method remove + * @param {String/Element/Array} node ID of element or DOM element object or array containing multiple elements/ids. + * @param {Boolean} keep_children Optional state to keep children or not. If set to true all children will be + * placed at the location of the removed element. + * @return {Element/Array} HTML DOM element that got removed or array of elements depending on input. + * @example + * // Removes all paragraphs in the active editor + * tinymce.activeEditor.dom.remove(tinymce.activeEditor.dom.select('p')); + * + * // Removes a element by id in the document + * tinymce.DOM.remove('mydiv'); + */ + 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 (!isIE || child.nodeType !== 3 || child.nodeValue) { + parent.insertBefore(child, node); + } else { + node.removeChild(child); + } + } + } + + return parent.removeChild(node); + }); + }, + + /** + * Sets the CSS style value on a HTML element. The name can be a camelcase string + * or the CSS style name like background-color. + * + * @method setStyle + * @param {String/Element/Array} n HTML element/Element ID or Array of elements/ids to set CSS style value on. + * @param {String} na Name of the style value to set. + * @param {String} v Value to set on the style. + * @example + * // Sets a style value on all paragraphs in the currently active editor + * tinymce.activeEditor.dom.setStyle(tinymce.activeEditor.dom.select('p'), 'background-color', 'red'); + * + * // Sets a style value to an element by id in the current document + * tinymce.DOM.setStyle('mydiv', 'background-color', 'red'); + */ + setStyle: function(elm, name, value) { + return this.run(elm, function(elm) { + var self = this, style, key; + + if (name) { + if (typeof(name) === 'string') { + style = elm.style; + + // Camelcase it, if needed + name = name.replace(/-(\D)/g, function(a, b) { + return b.toUpperCase(); + }); + + // Default px suffix on these + if (typeof(value) === 'number' && !numericCssMap[name]) { + value += 'px'; + } + + // IE specific opacity + if (name === "opacity" && elm.runtimeStyle && typeof(elm.runtimeStyle.opacity) === "undefined") { + style.filter = value === '' ? '' : "alpha(opacity=" + (value * 100) + ")"; + } + + try { + style[name] = value; + } catch (ex) { + // Ignore IE errors + } + + // Force update of the style data + if (self.settings.update_styles) { + elm.removeAttribute('data-mce-style'); + } + } else { + for (key in name) { + self.setStyle(elm, key, name[key]); + } + } + } + }); + }, + + /** + * Returns the current style or runtime/computed value of a element. + * + * @method getStyle + * @param {String/Element} elm HTML element or element id string to get style from. + * @param {String} name Style name to return. + * @param {Boolean} computed Computed style. + * @return {String} Current style or computed style value of a element. + */ + getStyle: function(elm, name, computed) { + elm = this.get(elm); + + if (!elm) { + return; + } + + // W3C + if (this.doc.defaultView && computed) { + // Remove camelcase + name = name.replace(/[A-Z]/g, function(a){ + return '-' + a; + }); + + try { + return this.doc.defaultView.getComputedStyle(elm, null).getPropertyValue(name); + } catch (ex) { + // Old safari might fail + return null; + } + } + + // Camelcase it, if needed + name = name.replace(/-(\D)/g, function(a, b) { + return b.toUpperCase(); + }); + + if (name == 'float') { + name = isIE ? 'styleFloat' : 'cssFloat'; + } + + // IE & Opera + if (name.currentStyle && computed) { + return elm.currentStyle[name]; + } + + return elm.style ? elm.style[name] : undefined; + }, + + /** + * Sets multiple styles on the specified element(s). + * + * @method setStyles + * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to set styles on. + * @param {Object} o Name/Value collection of style items to add to the element(s). + * @example + * // Sets styles on all paragraphs in the currently active editor + * tinymce.activeEditor.dom.setStyles(tinymce.activeEditor.dom.select('p'), {'background-color': 'red', 'color': 'green'}); + * + * // Sets styles to an element by id in the current document + * tinymce.DOM.setStyles('mydiv', {'background-color': 'red', 'color': 'green'}); + */ + setStyles: function(elm, styles) { + this.setStyle(elm, styles); + }, + + css: function(elm, name, value) { + this.setStyle(elm, name, value); + }, + + /** + * Removes all attributes from an element or elements. + * + * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to remove attributes from. + */ + 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)); + } + }); + }, + + /** + * Sets the specified attributes value of a element or elements. + * + * @method setAttrib + * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to set attribute on. + * @param {String} n Name of attribute to set. + * @param {String} v Value to set on the attribute of this value is falsy like null 0 or '' it will remove the attribute instead. + * @example + * // Sets an attribute to all paragraphs in the active editor + * tinymce.activeEditor.dom.setAttrib(tinymce.activeEditor.dom.select('p'), 'class', 'myclass'); + * + * // Sets an attribute to a specific element in the current page + * tinymce.dom.setAttrib('mydiv', 'class', 'myclass'); + */ + setAttrib: function(e, n, v) { + var t = this; + + // Whats the point + if (!e || !n) { + return; + } + + 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) { + 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 (originalValue != v && s.onSetAttrib) { + s.onSetAttrib({attrElm: e, attrName: n, attrValue: v}); + } + }); + }, + + /** + * Sets the specified attributes of a element or elements. + * + * @method setAttribs + * @param {Element/String/Array} elm DOM element, element id string or array of elements/ids to set attributes on. + * @param {Object} attrs Name/Value collection of attribute items to add to the element(s). + * @example + * // Sets some attributes to all paragraphs in the active editor + * tinymce.activeEditor.dom.setAttribs(tinymce.activeEditor.dom.select('p'), {'class': 'myclass', title: 'some title'}); + * + * // Sets some attributes to a specific element in the current page + * tinymce.DOM.setAttribs('mydiv', {'class': 'myclass', title: 'some title'}); + */ + setAttribs: function(elm, attrs) { + var self = this; + + return this.run(elm, function(elm) { + each(attrs, function(value, name) { + self.setAttrib(elm, name, value); + }); + }); + }, + + /** + * Returns the specified attribute by name. + * + * @method getAttrib + * @param {String/Element} elm Element string id or DOM element to get attribute from. + * @param {String} name Name of attribute to get. + * @param {String} defaultVal Optional default value to return if the attribute didn't exist. + * @return {String} Attribute value string, default value or null if the attribute wasn't found. + */ + getAttrib: function(elm, name, defaultVal) { + var value, self = this, undef; + + elm = self.get(elm); + + if (!elm || elm.nodeType !== 1) { + return defaultVal === undef ? false : defaultVal; + } + + if (!is(defaultVal)) { + defaultVal = ''; + } + + // Try the mce variant for these + if (/^(src|href|style|coords|shape)$/.test(name)) { + value = elm.getAttribute("data-mce-" + name); + + if (value) { + return value; + } + } + + if (isIE && self.props[name]) { + value = elm[self.props[name]]; + value = value && value.nodeValue ? value.nodeValue : value; + } + + if (!value) { + value = elm.getAttribute(name, 2); + } + + // Check boolean attribs + if (/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noshade|nowrap|readonly|selected)$/.test(name)) { + if (elm[self.props[name]] === true && value === '') { + return name; + } + + return value ? name : ''; + } + + // Inner input elements will override attributes on form elements + if (elm.nodeName === "FORM" && elm.getAttributeNode(name)) { + return elm.getAttributeNode(name).nodeValue; + } + + if (name === 'style') { + value = value || elm.style.cssText; + + if (value) { + value = self.serializeStyle(self.parseStyle(value), elm.nodeName); + + if (self.settings.keep_values) { + elm.setAttribute('data-mce-style', value); + } + } + } + + // Remove Apple and WebKit stuff + if (isWebKit && name === "class" && value) { + value = value.replace(/(apple|webkit)\-[a-z\-]+/gi, ''); + } + + // Handle IE issues + if (isIE) { + switch (name) { + case 'rowspan': + case 'colspan': + // IE returns 1 as default value + if (value === 1) { + value = ''; + } + + break; + + case 'size': + // IE returns +0 as default value for size + if (value === '+0' || value === 20 || value === 0) { + value = ''; + } + + break; + + case 'width': + case 'height': + case 'vspace': + case 'checked': + case 'disabled': + case 'readonly': + if (value === 0) { + value = ''; + } + + break; + + case 'hspace': + // IE returns -1 as default value + if (value === -1) { + value = ''; + } + + break; + + case 'maxlength': + case 'tabindex': + // IE returns default value + if (value === 32768 || value === 2147483647 || value === '32768') { + value = ''; + } + + break; + + case 'multiple': + case 'compact': + case 'noshade': + case 'nowrap': + if (value === 65535) { + return name; + } + + return defaultVal; + + case 'shape': + value = value.toLowerCase(); + break; + + default: + // IE has odd anonymous function for event attributes + if (name.indexOf('on') === 0 && value) { + value = ('' + value).replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/, '$1'); + } + } + } + + return (value !== undef && value !== null && value !== '') ? '' + value : defaultVal; + }, + + /** + * Returns the absolute x, y position of a node. The position will be returned in a object with x, y fields. + * + * @method getPos + * @param {Element/String} n HTML element or element id to get x, y position from. + * @param {Element} ro Optional root element to stop calculations at. + * @return {object} Absolute position of the specified element object with x, y fields. + */ + getPos: function(elm, rootElm) { + var self = this, x = 0, y = 0, offsetParent, doc = self.doc, pos; + + elm = self.get(elm); + rootElm = rootElm || doc.body; + + if (elm) { + // Use getBoundingClientRect if it exists since it's faster than looping offset nodes + if (rootElm === doc.body && elm.getBoundingClientRect) { + pos = elm.getBoundingClientRect(); + rootElm = self.boxModel ? doc.documentElement : doc.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 = pos.left + (doc.documentElement.scrollLeft || doc.body.scrollLeft) - rootElm.clientTop; + y = pos.top + (doc.documentElement.scrollTop || doc.body.scrollTop) - rootElm.clientLeft; + + return {x: x, y: y}; + } + + offsetParent = elm; + while (offsetParent && offsetParent != rootElm && offsetParent.nodeType) { + x += offsetParent.offsetLeft || 0; + y += offsetParent.offsetTop || 0; + offsetParent = offsetParent.offsetParent; + } + + offsetParent = elm.parentNode; + while (offsetParent && offsetParent != rootElm && offsetParent.nodeType) { + x -= offsetParent.scrollLeft || 0; + y -= offsetParent.scrollTop || 0; + offsetParent = offsetParent.parentNode; + } + } + + return {x: x, y: y}; + }, + + /** + * Parses the specified style value into an object collection. This parser will also + * merge and remove any redundant items that browsers might have added. It will also convert non hex + * colors to hex values. Urls inside the styles will also be converted to absolute/relative based on settings. + * + * @method parseStyle + * @param {String} cssText Style value to parse for example: border:1px solid red;. + * @return {Object} Object representation of that style like {border: '1px solid red'} + */ + parseStyle: function(cssText) { + return this.styles.parse(cssText); + }, + + /** + * Serializes the specified style object into a string. + * + * @method serializeStyle + * @param {Object} styles Object to serialize as string for example: {border: '1px solid red'} + * @param {String} name Optional element name. + * @return {String} String representation of the style object for example: border: 1px solid red. + */ + serializeStyle: function(styles, name) { + return this.styles.serialize(styles, name); + }, + + /** + * Adds a style element at the top of the document with the specified cssText content. + * + * @method addStyle + * @param {String} cssText CSS Text style to add to top of head of document. + */ + addStyle: function(cssText) { + var self = this, doc = self.doc, head, styleElm; + + // Prevent inline from loading the same styles twice + if (self !== DOMUtils.DOM && doc === document) { + var addedStyles = DOMUtils.DOM.addedStyles; + + addedStyles = addedStyles || []; + if (addedStyles[cssText]) { + return; + } + + addedStyles[cssText] = true; + DOMUtils.DOM.addedStyles = addedStyles; + } + + // Create style element if needed + styleElm = doc.getElementById('mceDefaultStyles'); + if (!styleElm) { + styleElm = doc.createElement('style'), + styleElm.id = 'mceDefaultStyles'; + styleElm.type = 'text/css'; + + head = doc.getElementsByTagName('head')[0]; + if (head.firstChild) { + head.insertBefore(styleElm, head.firstChild); + } else { + head.appendChild(styleElm); + } + } + + // Append style data to old or new style element + if (styleElm.styleSheet) { + styleElm.styleSheet.cssText += cssText; + } else { + styleElm.appendChild(doc.createTextNode(cssText)); + } + }, + + /** + * Imports/loads the specified CSS file into the document bound to the class. + * + * @method loadCSS + * @param {String} u URL to CSS file to load. + * @example + * // Loads a CSS file dynamically into the current document + * tinymce.DOM.loadCSS('somepath/some.css'); + * + * // Loads a CSS file into the currently active editor instance + * tinymce.activeEditor.dom.loadCSS('somepath/some.css'); + * + * // Loads a CSS file into an editor instance by id + * tinymce.get('someid').dom.loadCSS('somepath/some.css'); + * + * // Loads multiple CSS files into the current document + * tinymce.DOM.loadCSS('somepath/some.css,somepath/someother.css'); + */ + loadCSS: function(url) { + var self = this, doc = self.doc, head; + + // Prevent inline from loading the same CSS file twice + if (self !== DOMUtils.DOM && doc === document) { + DOMUtils.DOM.loadCSS(url); + return; + } + + if (!url) { + url = ''; + } + + head = doc.getElementsByTagName('head')[0]; + + each(url.split(','), function(url) { + var link; + + if (self.files[url]) { + return; + } + + self.files[url] = true; + link = self.create('link', {rel: 'stylesheet', href: url}); + + // 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 && doc.documentMode && doc.recalc) { + link.onload = function() { + if (doc.recalc) { + doc.recalc(); + } + + link.onload = null; + }; + } + + head.appendChild(link); + }); + }, + + /** + * Adds a class to the specified element or elements. + * + * @method addClass + * @param {String/Element/Array} elm Element ID string or DOM element or array with elements or IDs. + * @param {String} cls Class name to add to each element. + * @return {String/Array} String with new class value or array with new class values for all elements. + * @example + * // Adds a class to all paragraphs in the active editor + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'myclass'); + * + * // Adds a class to a specific element in the current page + * tinymce.DOM.addClass('mydiv', 'myclass'); + */ + addClass: function(elm, cls) { + return this.run(elm, function(elm) { + var clsVal; + + if (!cls) { + return 0; + } + + if (this.hasClass(elm, cls)) { + return elm.className; + } + + clsVal = this.removeClass(elm, cls); + elm.className = clsVal = (clsVal !== '' ? (clsVal + ' ') : '') + cls; + + return clsVal; + }); + }, + + /** + * Removes a class from the specified element or elements. + * + * @method removeClass + * @param {String/Element/Array} elm Element ID string or DOM element or array with elements or IDs. + * @param {String} cls Class name to remove to each element. + * @return {String/Array} String with new class value or array with new class values for all elements. + * @example + * // Removes a class from all paragraphs in the active editor + * tinymce.activeEditor.dom.removeClass(tinymce.activeEditor.dom.select('p'), 'myclass'); + * + * // Removes a class from a specific element in the current page + * tinymce.DOM.removeClass('mydiv', 'myclass'); + */ + removeClass: function(elm, cls) { + var self = this, re; + + return self.run(elm, function(elm) { + var val; + + if (self.hasClass(elm, cls)) { + if (!re) { + re = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", "g"); + } + + val = elm.className.replace(re, ' '); + val = trim(val != ' ' ? val : ''); + + elm.className = val; + + // Empty class attr + if (!val) { + elm.removeAttribute('class'); + elm.removeAttribute('className'); + } + + return val; + } + + return elm.className; + }); + }, + + /** + * Returns true if the specified element has the specified class. + * + * @method hasClass + * @param {String/Element} n HTML element or element id string to check CSS class on. + * @param {String} c CSS class to check for. + * @return {Boolean} true/false if the specified element has the specified class. + */ + hasClass: function(elm, cls) { + elm = this.get(elm); + + if (!elm || !cls) { + return false; + } + + return (' ' + elm.className + ' ').indexOf(' ' + cls + ' ') !== -1; + }, + + /** + * Toggles the specified class on/off. + * + * @method toggleClass + * @param {Element} elm Element to toggle class on. + * @param {[type]} cls Class to toggle on/off. + * @param {[type]} state Optional state to set. + */ + toggleClass: function(elm, cls, state) { + state = state === undefined ? !this.hasClass(elm, cls) : state; + + if (this.hasClass(elm, cls) !== state) { + if (state) { + this.addClass(elm, cls); + } else { + this.removeClass(elm, cls); + } + } + }, + + /** + * Shows the specified element(s) by ID by setting the "display" style. + * + * @method show + * @param {String/Element/Array} elm ID of DOM element or DOM element or array with elements or IDs to show. + */ + show: function(elm) { + return this.setStyle(elm, 'display', 'block'); + }, + + /** + * Hides the specified element(s) by ID by setting the "display" style. + * + * @method hide + * @param {String/Element/Array} e ID of DOM element or DOM element or array with elements or IDs to hide. + * @example + * // Hides a element by id in the document + * tinymce.DOM.hide('myid'); + */ + hide: function(elm) { + return this.setStyle(elm, 'display', 'none'); + }, + + /** + * Returns true/false if the element is hidden or not by checking the "display" style. + * + * @method isHidden + * @param {String/Element} e Id or element to check display state on. + * @return {Boolean} true/false if the element is hidden or not. + */ + isHidden: function(elm) { + elm = this.get(elm); + + return !elm || elm.style.display == 'none' || this.getStyle(elm, 'display') == 'none'; + }, + + /** + * Returns a unique id. This can be useful when generating elements on the fly. + * This method will not check if the element allready exists. + * + * @method uniqueId + * @param {String} prefix Optional prefix to add infront of all ids defaults to "mce_". + * @return {String} Unique id. + */ + uniqueId: function(prefix) { + return (!prefix ? 'mce_' : prefix) + (this.counter++); + }, + + /** + * Sets the specified HTML content inside the element or elements. The HTML will first be processed this means + * URLs will get converted, hex color values fixed etc. Check processHTML for details. + * + * @method setHTML + * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to set HTML inside. + * @param {String} h HTML content to set as inner HTML of the element. + * @example + * // Sets the inner HTML of all paragraphs in the active editor + * tinymce.activeEditor.dom.setHTML(tinymce.activeEditor.dom.select('p'), 'some inner html'); + * + * // Sets the inner HTML of a element by id in the document + * tinymce.DOM.setHTML('mydiv', 'some inner html'); + */ + 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 = '
' + 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 + var newElement = self.create('div'); + newElement.innerHTML = '
' + html; + + // Add all children from div to target + each (grep(newElement.childNodes), function(node, i) { + // Skip br element + if (i && element.canHaveHTML) { + element.appendChild(node); + } + }); + } + } else { + element.innerHTML = html; + } + + return html; + }); + }, + + /** + * Returns the outer HTML of an element. + * + * @method getOuterHTML + * @param {String/Element} elm Element ID or element object to get outer HTML from. + * @return {String} Outer HTML string. + * @example + * tinymce.DOM.getOuterHTML(editorElement); + * tinymce.activeEditor.getOuterHTML(tinymce.activeEditor.getBody()); + */ + 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; + }, + + /** + * Sets the specified outer HTML on a element or elements. + * + * @method setOuterHTML + * @param {Element/String/Array} elm DOM element, element id string or array of elements/ids to set outer HTML on. + * @param {Object} html HTML code to set as outer value for the element. + * @param {Document} doc Optional document scope to use in this process defaults to the document of the DOM class. + * @example + * // Sets the outer HTML of all paragraphs in the active editor + * tinymce.activeEditor.dom.setOuterHTML(tinymce.activeEditor.dom.select('p'), '
some html
'); + * + * // Sets the outer HTML of a element by id in the document + * tinymce.DOM.setOuterHTML('mydiv', '
some html
'); + */ + setOuterHTML: function(elm, html, doc) { + var self = this; + + return self.run(elm, function(elm) { + function set() { + var node, tempElm; + + tempElm = doc.createElement("body"); + tempElm.innerHTML = html; + + node = tempElm.lastChild; + while (node) { + self.insertAfter(node.cloneNode(true), elm); + node = node.previousSibling; + } + + self.remove(elm); + } + + // Only set HTML on elements + if (elm.nodeType == 1) { + doc = doc || elm.ownerDocument || self.doc; + + if (isIE) { + try { + // Try outerHTML for IE it sometimes produces an unknown runtime error + if (elm.nodeType == 1 && self.hasOuterHTML) { + elm.outerHTML = html; + } else { + set(); + } + } catch (ex) { + // Fix for unknown runtime error + set(); + } + } else { + set(); + } + } + }); + }, + + /** + * Entity decode a string, resolves any HTML entities like å. + * + * @method decode + * @param {String} s String to decode entities on. + * @return {String} Entity decoded string. + */ + decode: Entities.decode, + + /** + * Entity encodes a string, encodes the most common entities <>"& into entities. + * + * @method encode + * @param {String} text String to encode with entities. + * @return {String} Entity encoded string. + */ + encode: Entities.encodeAllRaw, + + /** + * Inserts a element after the reference element. + * + * @method insertAfter + * @param {Element} node Element to insert after the reference. + * @param {Element/String/Array} reference_node Reference element, element id or array of elements to insert after. + * @return {Element/Array} Element that got added or an array with elements. + */ + 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; + }); + }, + + /** + * Replaces the specified element or elements with the specified element, the new element will + * be cloned if multiple inputs elements are passed. + * + * @method replace + * @param {Element} newElm New element to replace old ones with. + * @param {Element/String/Array} oldELm Element DOM node, element id or array of elements or ids to replace. + * @param {Boolean} k Optional keep children state, if set to true child nodes from the old object will be added to new ones. + */ + replace: function(newElm, oldElm, keepChildren) { + var self = this; + + return self.run(oldElm, function(oldElm) { + if (is(oldElm, 'array')) { + newElm = newElm.cloneNode(true); + } + + if (keepChildren) { + each(grep(oldElm.childNodes), function(node) { + newElm.appendChild(node); + }); + } + + return oldElm.parentNode.replaceChild(newElm, oldElm); + }); + }, + + /** + * Renames the specified element to a new name and keep it's attributes and children. + * + * @method rename + * @param {Element} elm Element to rename. + * @param {String} name Name of the new element. + * @return New element or the old element if it needed renaming. + */ + rename: function(elm, name) { + var self = this, newElm; + + if (elm.nodeName != name.toUpperCase()) { + // Rename block element + newElm = self.create(name); + + // Copy attribs to new block + each(self.getAttribs(elm), function(attr_node) { + self.setAttrib(newElm, attr_node.nodeName, self.getAttrib(elm, attr_node.nodeName)); + }); + + // Replace block + self.replace(newElm, elm, 1); + } + + return newElm || elm; + }, + + /** + * Find the common ancestor of two elements. This is a shorter method than using the DOM Range logic. + * + * @method findCommonAncestor + * @param {Element} a Element to find common ancestor of. + * @param {Element} b Element to find common ancestor of. + * @return {Element} Common ancestor element of the two input elements. + */ + 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; + }, + + /** + * Parses the specified RGB color value and returns a hex version of that color. + * + * @method toHex + * @param {String} rgbVal RGB string value like rgb(1,2,3) + * @return {String} Hex version of that RGB value like #FF00FF. + */ + toHex: function(rgbVal) { + return this.styles.toHex(Tools.trim(rgbVal)); + }, + + /** + * Returns a array of all single CSS classes in the document. A single CSS class is a simple + * rule like ".class" complex ones like "div td.class" will not be added to output. + * + * @method getClasses + * @return {Array} Array with class objects each object has a class field might be other fields in the future. + */ + getClasses: function() { + var self = this, classList = [], lookup = {}, filter = self.settings.class_filter, oldVal; + + if (self.classes) { + return self.classes; + } + + function addClasses(stylesheet) { + // IE style imports + each(stylesheet.imports, function(r) { + addClasses(r); + }); + + each(stylesheet.cssRules || stylesheet.rules, function(rule) { + // Real type or fake it on IE + switch (rule.type || 1) { + // Rule + case 1: + if (rule.selectorText) { + each(rule.selectorText.split(','), function(value) { + value = value.replace(/^\s*|\s*$|^\s\./g, ""); + + // Is internal or it doesn't contain a class + if (/\.mce/.test(value) || !/\.[\w\-]+$/.test(value)) { + return; + } + + // Remove everything but class name + oldVal = value; + value = value.replace(/.*\.([a-z0-9_\-]+).*/i, '$1'); + + // Filter classes + if (filter && !(value = filter(value, oldVal))) { + return; + } + + if (!lookup[value]) { + classList.push({'class': value}); + lookup[value] = 1; + } + }); + } + break; + + // Import + case 3: + addClasses(rule.styleSheet); + break; + } + }); + } + + try { + each(self.doc.styleSheets, addClasses); + } catch (ex) { + // Ignore + } + + if (classList.length > 0) { + self.classes = classList; + } + + return classList; + }, + + /** + * Executes the specified function on the element by id or dom element node or array of elements/id. + * + * @method run + * @param {String/Element/Array} Element ID or DOM element object or array with ids or elements. + * @param {function} f Function to execute for each item. + * @param {Object} s Optional scope to execute the function in. + * @return {Object/Array} Single object or array with objects depending on multiple input or not. + */ + run: function(elm, func, scope) { + var self = this, result; + + if (typeof(elm) === 'string') { + elm = self.get(elm); + } + + if (!elm) { + return false; + } + + scope = scope || this; + if (!elm.nodeType && (elm.length || elm.length === 0)) { + result = []; + + each(elm, function(elm, i) { + if (elm) { + if (typeof(elm) == 'string') { + elm = self.get(elm); + } + + result.push(func.call(scope, elm, i)); + } + }); + + return result; + } + + return func.call(scope, elm); + }, + + /** + * Returns an NodeList with attributes for the element. + * + * @method getAttribs + * @param {HTMLElement/string} elm Element node or string id to get attributes from. + * @return {NodeList} NodeList with attributes. + */ + getAttribs: function(elm) { + var attrs; + + elm = this.get(elm); + + if (!elm) { + return []; + } + + if (isIE) { + attrs = []; + + // Object will throw exception in IE + if (elm.nodeName == 'OBJECT') { + return elm.attributes; + } + + // IE doesn't keep the selected attribute if you clone option elements + if (elm.nodeName === 'OPTION' && this.getAttrib(elm, 'selected')) { + attrs.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 + var attrRegExp = /<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi; + elm.cloneNode(false).outerHTML.replace(attrRegExp, '').replace(/[\w:\-]+/gi, function(a) { + attrs.push({specified: 1, nodeName: a}); + }); + + return attrs; + } + + return elm.attributes; + }, + + /** + * Returns true/false if the specified node is to be considered empty or not. + * + * @example + * tinymce.DOM.isEmpty(node, {img: true}); + * @method isEmpty + * @param {Object} elements Optional name/value object with elements that are automatically treated as non empty elements. + * @return {Boolean} true/false if the node is empty or not. + */ + isEmpty: function(node, elements) { + var self = this, i, attributes, type, walker, name, brCount = 0; + + node = node.firstChild; + if (node) { + walker = new 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 + name = node.nodeName.toLowerCase(); + if (elements && elements[name]) { + // Ignore single BR elements in blocks like


or


+ if (name === 'br') { + brCount++; + continue; + } + + return false; + } + + // Keep elements with data-bookmark attributes or name attribute like + 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; + }, + + /** + * Created a new DOM Range object. This will use the native DOM Range API if it's + * available if it's not it will fallback to the custom TinyMCE implementation. + * + * @method createRng + * @return {DOMRange} DOM Range object. + * @example + * var rng = tinymce.DOM.createRng(); + * alert(rng.startContainer + "," + rng.startOffset); + */ + createRng: function() { + var doc = this.doc; + + return doc.createRange ? doc.createRange() : new Range(this); + }, + + /** + * Returns the index of the specified node within it's parent. + * + * @param {Node} node Node to look for. + * @param {boolean} normalized Optional true/false state if the index is what it would be after a normalization. + * @return {Number} Index of the specified node. + */ + 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; + }, + + /** + * Splits an element into two new elements and places the specified split + * element or element between the new ones. For example splitting the paragraph at the bold element in + * this example

abcabc123

would produce

abc

abc

123

. + * + * @method split + * @param {Element} parentElm Parent element to split. + * @param {Element} splitElm Element to split at. + * @param {Element} replacementElm Optional replacement element to replace the split element by. + * @return {Element} Returns the split element or the replacement element if that is specified. + */ + split: function(parentElm, splitElm, replacementElm) { + var self = this, r = self.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: + //

text 1CHOPtext 2

+ // would produce: + //

text 1

CHOP

text 2

+ // this function will then trim of empty edges and produce: + //

text 1

CHOP

text 2

+ function trimNode(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--) { + trimNode(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 "

" + // Also keep text nodes with only spaces if surrounded by spans. + // eg. "

a b

" should keep space between a and b + var trimmedLength = trim(node.nodeValue).length; + if (!self.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; + + // TODO fix this complex if + 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; + } + } + + self.remove(node); + } + + return node; + } + + if (parentElm && splitElm) { + // Get before chunk + r.setStart(parentElm.parentNode, self.nodeIndex(parentElm)); + r.setEnd(splitElm.parentNode, self.nodeIndex(splitElm)); + bef = r.extractContents(); + + // Get after chunk + r = self.createRng(); + r.setStart(splitElm.parentNode, self.nodeIndex(splitElm) + 1); + r.setEnd(parentElm.parentNode, self.nodeIndex(parentElm) + 1); + aft = r.extractContents(); + + // Insert before chunk + pa = parentElm.parentNode; + pa.insertBefore(trimNode(bef), parentElm); + + // Insert middle chunk + if (replacementElm) { + pa.replaceChild(replacementElm, splitElm); + } else { + pa.insertBefore(splitElm, parentElm); + } + + // Insert after chunk + pa.insertBefore(trimNode(aft), parentElm); + self.remove(parentElm); + + return replacementElm || splitElm; + } + }, + + /** + * Adds an event handler to the specified object. + * + * @method bind + * @param {Element/Document/Window/Array/String} o Object or element id string to add event + * handler to or an array of elements/ids/documents. + * @param {String} n Name of event handler to add for example: click. + * @param {function} f Function to execute when the event occurs. + * @param {Object} s Optional scope to execute the function in. + * @return {function} Function callback handler the same as the one passed in. + */ + bind: function(target, name, func, scope) { + return this.events.bind(target, name, func, scope || this); + }, + + /** + * Removes the specified event handler by name and function from a element or collection of elements. + * + * @method unbind + * @param {String/Element/Array} o Element ID string or HTML element or an array of elements or ids to remove handler from. + * @param {String} n Event handler name like for example: "click" + * @param {function} f Function to remove. + * @return {bool/Array} Bool state if true if the handler was removed or an array with states if multiple elements where passed in. + */ + unbind: function(target, name, func) { + return this.events.unbind(target, name, func); + }, + + /** + * Fires the specified event name with object on target. + * + * @method fire + * @param {Node/Document/Window} target Target element or object to fire event on. + * @param {String} name Name of the event to fire. + * @param {Object} evt Event object to send. + * @return {Event} Event object. + */ + 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; + }, + + /** + * Destroys all internal references to the DOM to solve IE leak issues. + * + * @method destroy + */ + destroy: function() { + var self = this; + + self.win = self.doc = self.root = self.events = self.frag = null; + }, + + // #ifdef debug + + dumpRng: function(r) { + return ( + 'startContainer: ' + r.startContainer.nodeName + + ', startOffset: ' + r.startOffset + + ', endContainer: ' + r.endContainer.nodeName + + ', endOffset: ' + r.endOffset + ); + }, + + // #endif + + _findSib: function(node, selector, name) { + var self = this, func = selector; + + if (node) { + // If expression make a function of it using is + if (typeof(func) == 'string') { + func = function(node) { + return self.is(node, selector); + }; + } + + // Loop all siblings + for (node = node[name]; node; node = node[name]) { + if (func(node)) { + return node; + } + } + } + + return null; + } + }; + + /** + * Instance of DOMUtils for the current document. + * + * @property DOM + * @member tinymce + * @type tinymce.dom.DOMUtils + * @example + * // Example of how to add a class to some element by id + * tinymce.DOM.addClass('someid', 'someclass'); + */ + DOMUtils.DOM = new DOMUtils(document); + + return DOMUtils; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/dom/DomQuery.js b/lib/tinymce/jscripts/tinymce4/classes/dom/DomQuery.js new file mode 100644 index 00000000..fae010cb --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/dom/DomQuery.js @@ -0,0 +1,719 @@ +/** + * DomQuery.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + * + * Some of this logic is based on jQuery code that is released under + * MIT license that grants us to sublicense it under LGPL. + */ + +define("tinymce/dom/DomQuery", [ + "tinymce/dom/EventUtils", + "tinymce/dom/Sizzle" +], function(EventUtils, Sizzle) { + var doc = document, push = Array.prototype.push, slice = Array.prototype.slice; + var rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/; + var Event = EventUtils.Event; + + function isDefined(obj) { + return typeof obj !== "undefined"; + } + + function isString(obj) { + return typeof obj === "string"; + } + + function createFragment(html) { + var frag, node, container; + + container = doc.createElement("div"); + frag = doc.createDocumentFragment(); + container.innerHTML = html; + + while ((node = container.firstChild)) { + frag.appendChild(node); + } + + return frag; + } + + function domManipulate(targetNodes, sourceItem, callback) { + var i; + + if (typeof sourceItem === "string") { + sourceItem = createFragment(sourceItem); + } else if (sourceItem.length) { + for (i = 0; i < sourceItem.length; i++) { + domManipulate(targetNodes, sourceItem[i], callback); + } + + return targetNodes; + } + + i = targetNodes.length; + while (i--) { + callback.call(targetNodes[i], sourceItem.parentNode ? sourceItem : sourceItem); + } + + return targetNodes; + } + + function hasClass(node, className) { + return node && className && (' ' + node.className + ' ').indexOf(' ' + className + ' ') !== -1; + } + + /** + * Makes a map object out of a string that gets separated by a delimiter. + * + * @method makeMap + * @param {String} items Item string to split. + * @param {Object} map Optional object to add items to. + * @return {Object} name/value object with items as keys. + */ + function makeMap(items, map) { + var i; + + items = items || []; + + if (typeof(items) == "string") { + items = items.split(' '); + } + + map = map || {}; + + i = items.length; + while (i--) { + map[items[i]] = {}; + } + + return map; + } + + var numericCssMap = makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom'); + + function DomQuery(selector, context) { + return new DomQuery.fn.init(selector, context); + } + + /** + * Extends the specified object with another object. + * + * @method extend + * @param {Object} target Object to extend. + * @param {Object..} obj Multiple objects to extend with. + * @return {Object} Same as target, the extended object. + */ + function extend(target) { + var args = arguments, arg, i, key; + + for (i = 1; i < args.length; i++) { + arg = args[i]; + + for (key in arg) { + target[key] = arg[key]; + } + } + + return target; + } + + /** + * Converts the specified object into a real JavaScript array. + * + * @method toArray + * @param {Object} obj Object to convert into array. + * @return {Array} Array object based in input. + */ + function toArray(obj) { + var array = [], i, l; + + for (i = 0, l = obj.length; i < l; i++) { + array[i] = obj[i]; + } + + return array; + } + + /** + * Returns the index of the specified item inside the array. + * + * @method inArray + * @param {Object} item Item to look for. + * @param {Array} array Array to look for item in. + * @return {Number} Index of the item or -1. + */ + function inArray(item, array) { + var i; + + if (array.indexOf) { + return array.indexOf(item); + } + + i = array.length; + while (i--) { + if (array[i] === item) { + return i; + } + } + + return -1; + } + + /** + * Returns true/false if the specified object is an array. + * + * @method isArray + * @param {Object} obj Object to check if it's an array. + * @return {Boolean} true/false if the input object is array or not. + */ + var isArray = Array.isArray || function(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + + var whiteSpaceRegExp = /^\s*|\s*$/g; + var trim = function(str) { + return (str === null || str === undefined) ? '' : ("" + str).replace(whiteSpaceRegExp, ''); + }; + + /** + * Executes the callback function for each item in array/object. If you return false in the + * callback it will break the loop. + * + * @method each + * @param {Object} obj Object to iterate. + * @param {function} callback Callback function to execute for each item. + */ + function each(obj, callback) { + var length, key, i, undef, value; + + if (obj) { + length = obj.length; + + if (length === undef) { + // Loop object items + for (key in obj) { + if (obj.hasOwnProperty(key)) { + value = obj[key]; + if (callback.call(value, value, key) === false) { + break; + } + } + } + } else { + // Loop array items + for (i = 0; i < length; i++) { + value = obj[i]; + if (callback.call(value, value, key) === false) { + break; + } + } + } + } + + return obj; + } + + DomQuery.fn = DomQuery.prototype = { + constructor: DomQuery, + selector: "", + length: 0, + + init: function(selector, context) { + var self = this, match, node; + + if (!selector) { + return self; + } + + if (selector.nodeType) { + self.context = self[0] = selector; + self.length = 1; + + return self; + } + + if (isString(selector)) { + if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) { + match = [null, selector, null]; + } else { + match = rquickExpr.exec(selector); + } + + if (match) { + if (match[1]) { + node = createFragment(selector).firstChild; + while (node) { + this.add(node); + node = node.nextSibling; + } + } else { + node = doc.getElementById(match[2]); + + if (node.id !== match[2]) { + return self.find(selector); + } + + self.length = 1; + self[0] = node; + } + } else { + return DomQuery(context || document).find(selector); + } + } else { + this.add(selector); + } + + return self; + }, + + toArray: function() { + return toArray(this); + }, + + add: function(items) { + var self = this; + + // Force single item into array + if (!isArray(items)) { + if (items instanceof DomQuery) { + self.add(items.toArray()); + } else { + push.call(self, items); + } + } else { + push.apply(self, items); + } + + return self; + }, + + attr: function(name, value) { + var self = this; + + if (typeof name === "object") { + each(name, function(value, name) { + self.attr(name, value); + }); + } else if (isDefined(value)) { + this.each(function() { + if (this.nodeType === 1) { + this.setAttribute(name, value); + } + }); + } else { + return self[0] && self[0].nodeType === 1 ? self[0].getAttribute(name) : undefined; + } + + return self; + }, + + css: function(name, value) { + var self = this; + + if (typeof name === "object") { + each(name, function(value, name) { + self.css(name, value); + }); + } else { + // Camelcase it, if needed + name = name.replace(/-(\D)/g, function(a, b) { + return b.toUpperCase(); + }); + + if (isDefined(value)) { + // Default px suffix on these + if (typeof(value) === 'number' && !numericCssMap[name]) { + value += 'px'; + } + + self.each(function() { + var style = this.style; + + // IE specific opacity + if (name === "opacity" && this.runtimeStyle && typeof(this.runtimeStyle.opacity) === "undefined") { + style.filter = value === '' ? '' : "alpha(opacity=" + (value * 100) + ")"; + } + + try { + style[name] = value; + } catch (ex) { + // Ignore + } + }); + } else { + return self[0] ? self[0].style[name] : undefined; + } + } + + return self; + }, + + remove: function() { + var self = this, node, i = this.length; + + while (i--) { + node = self[i]; + Event.clean(node); + + if (node.parentNode) { + node.parentNode.removeChild(node); + } + } + + return this; + }, + + empty: function() { + var self = this, node, i = this.length; + + while (i--) { + node = self[i]; + while (node.firstChild) { + node.removeChild(node.firstChild); + } + } + + return this; + }, + + html: function(value) { + var self = this, i; + + if (isDefined(value)) { + i = self.length; + while (i--) { + self[i].innerHTML = value; + } + + return self; + } + + return self[0] ? self[0].innerHTML : ''; + }, + + text: function(value) { + var self = this, i; + + if (isDefined(value)) { + i = self.length; + while (i--) { + self[i].innerText = self[0].textContent = value; + } + + return self; + } + + return self[0] ? self[0].innerText || self[0].textContent : ''; + }, + + append: function() { + return domManipulate(this, arguments, function(node) { + if (this.nodeType === 1) { + this.appendChild(node); + } + }); + }, + + prepend: function() { + return domManipulate(this, arguments, function(node) { + if (this.nodeType === 1) { + this.insertBefore(node, this.firstChild); + } + }); + }, + + before: function() { + var self = this; + + if (self[0] && self[0].parentNode) { + return domManipulate(self, arguments, function(node) { + this.parentNode.insertBefore(node, this.nextSibling); + }); + } + + return self; + }, + + after: function() { + var self = this; + + if (self[0] && self[0].parentNode) { + return domManipulate(self, arguments, function(node) { + this.parentNode.insertBefore(node, this); + }); + } + + return self; + }, + + appendTo: function(val) { + DomQuery(val).append(this); + + return this; + }, + + addClass: function(className) { + return this.toggleClass(className, true); + }, + + removeClass: function(className) { + return this.toggleClass(className, false); + }, + + toggleClass: function(className, state) { + var self = this; + + if (className.indexOf(' ') !== -1) { + each(className.split(' '), function() { + self.toggleClass(this, state); + }); + } else { + self.each(function() { + var node = this, existingClassName; + + if (hasClass(node, className) !== state) { + existingClassName = node.className; + + if (state) { + node.className += existingClassName ? ' ' + className : className; + } else { + node.className = trim((" " + existingClassName + " ").replace(' ' + className + ' ', ' ')); + } + } + }); + } + + return self; + }, + + hasClass: function(className) { + return hasClass(this[0], className); + }, + + each: function(callback) { + return each(this, callback); + }, + + on: function(name, callback) { + return this.each(function() { + Event.bind(this, name, callback); + }); + }, + + off: function(name, callback) { + return this.each(function() { + Event.unbind(this, name, callback); + }); + }, + + show: function() { + return this.css('display', ''); + }, + + hide: function() { + return this.css('display', 'none'); + }, + + slice: function() { + return new DomQuery(slice.apply(this, arguments)); + }, + + eq: function(index) { + return index === -1 ? this.slice(index) : this.slice(index, +index + 1); + }, + + first: function() { + return this.eq(0); + }, + + last: function() { + return this.eq(-1); + }, + + replaceWith: function(content) { + var self = this; + + if (self[0]) { + self[0].parentNode.replaceChild(DomQuery(content)[0], self[0]); + } + + return self; + }, + + wrap: function(wrapper) { + wrapper = DomQuery(wrapper)[0]; + + return this.each(function() { + var self = this, newWrapper = wrapper.cloneNode(false); + self.parentNode.insertBefore(newWrapper, self); + newWrapper.appendChild(self); + }); + }, + + unwrap: function() { + return this.each(function() { + var self = this, node = self.firstChild, currentNode; + + while (node) { + currentNode = node; + node = node.nextSibling; + self.parentNode.insertBefore(currentNode, self); + } + }); + }, + + clone: function() { + var result = []; + + this.each(function() { + result.push(this.cloneNode(true)); + }); + + return DomQuery(result); + }, + + find: function(selector) { + var i, l, ret = []; + + for (i = 0, l = this.length; i < l; i++) { + DomQuery.find(selector, this[i], ret); + } + + return DomQuery(ret); + }, + + push: push, + sort: [].sort, + splice: [].splice + }; + + // Static members + extend(DomQuery, { + extend: extend, + toArray: toArray, + inArray: inArray, + isArray: isArray, + each: each, + trim: trim, + makeMap: makeMap, + + // Sizzle + find: Sizzle, + expr: Sizzle.selectors, + unique: Sizzle.uniqueSort, + text: Sizzle.getText, + isXMLDoc: Sizzle.isXML, + contains: Sizzle.contains, + filter: function(expr, elems, not) { + if (not) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [] : + DomQuery.find.matches(expr, elems); + } + }); + + function dir(el, prop, until) { + var matched = [], cur = el[prop]; + + while (cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !DomQuery(cur).is(until))) { + if (cur.nodeType === 1) { + matched.push(cur); + } + + cur = cur[prop]; + } + + return matched; + } + + function sibling(n, el, siblingName, nodeType) { + var r = []; + + for(; n; n = n[siblingName]) { + if ((!nodeType || n.nodeType === nodeType) && n !== el) { + r.push(n); + } + } + + return r; + } + + each({ + parent: function(node) { + var parent = node.parentNode; + + return parent && parent.nodeType !== 11 ? parent : null; + }, + + parents: function(node) { + return dir(node, "parentNode"); + }, + + parentsUntil: function(node, until) { + return dir(node, "parentNode", until); + }, + + next: function(node) { + return sibling(node, 'nextSibling', 1); + }, + + prev: function(node) { + return sibling(node, 'previousSibling', 1); + }, + + nextNodes: function(node) { + return sibling(node, 'nextSibling'); + }, + + prevNodes: function(node) { + return sibling(node, 'previousSibling'); + }, + + children: function(node) { + return sibling(node.firstChild, 'nextSibling', 1); + }, + + contents: function(node) { + return toArray((node.nodeName === "iframe" ? node.contentDocument || node.contentWindow.document : node).childNodes); + } + }, function(name, fn){ + DomQuery.fn[name] = function(selector) { + var self = this, result; + + if (self.length > 1) { + throw new Error("DomQuery only supports traverse functions on a single node."); + } + + if (self[0]) { + result = fn(self[0], selector); + } + + result = DomQuery(result); + + if (selector && name !== "parentsUntil") { + return result.filter(selector); + } + + return result; + }; + }); + + DomQuery.fn.filter = function(selector) { + return DomQuery.filter(selector); + }; + + DomQuery.fn.is = function(selector) { + return !!selector && this.filter(selector).length > 0; + }; + + DomQuery.fn.init.prototype = DomQuery.fn; + + return DomQuery; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/dom/EventUtils.js b/lib/tinymce/jscripts/tinymce4/classes/dom/EventUtils.js new file mode 100644 index 00000000..5e16af28 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/dom/EventUtils.js @@ -0,0 +1,525 @@ +/** + * EventUtils.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint loopfunc:true*/ + +define("tinymce/dom/EventUtils", [], function() { + "use strict"; + + var eventExpandoPrefix = "mce-data-"; + + /** + * Binds a native event to a callback on the speified target. + */ + function addEvent(target, name, callback, capture) { + if (target.addEventListener) { + target.addEventListener(name, callback, capture || false); + } else if (target.attachEvent) { + target.attachEvent('on' + name, callback); + } + } + + /** + * Unbinds a native event callback on the specified target. + */ + function removeEvent(target, name, callback, capture) { + if (target.removeEventListener) { + target.removeEventListener(name, callback, capture || false); + } else if (target.detachEvent) { + target.detachEvent('on' + name, callback); + } + } + + /** + * Normalizes a native event object or just adds the event specific methods on a custom event. + */ + function fix(originalEvent, 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 originalEvent) { + // layerX/layerY is deprecated in Chrome and produces a warning + if (name !== "layerX" && name !== "layerY") { + event[name] = originalEvent[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 (originalEvent) { + if (originalEvent.preventDefault) { + originalEvent.preventDefault(); + } else { + originalEvent.returnValue = false; // IE + } + } + }; + + // Add stopPropagation + event.stopPropagation = function() { + event.isPropagationStopped = returnTrue; + + // Execute stopPropagation on the original event object + if (originalEvent) { + if (originalEvent.stopPropagation) { + originalEvent.stopPropagation(); + } else { + originalEvent.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; + } + + /** + * Bind a DOMContentLoaded event across browsers and executes the callback once the page DOM is initialized. + * It will also set/check the domLoaded state of the event_utils instance so ready isn't called multiple times. + */ + function bindOnReady(win, callback, eventUtils) { + var doc = win.document, event = {type: 'ready'}; + + if (eventUtils.domLoaded) { + callback(event); + return; + } + + // Gets called when the DOM is ready + function readyHandler() { + if (!eventUtils.domLoaded) { + eventUtils.domLoaded = true; + callback(event); + } + } + + function waitForDomLoaded() { + if (doc.readyState === "complete") { + removeEvent(doc, "readystatechange", waitForDomLoaded); + readyHandler(); + } + } + + function tryScroll() { + 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(tryScroll, 0); + return; + } + + readyHandler(); + } + + // Use W3C method + if (doc.addEventListener) { + addEvent(win, 'DOMContentLoaded', readyHandler); + } else { + // Use IE method + addEvent(doc, "readystatechange", waitForDomLoaded); + + // Wait until we can scroll, when we can the DOM is initialized + if (doc.documentElement.doScroll && win === win.top) { + tryScroll(); + } + } + + // Fallback if any of the above methods should fail for some odd reason + addEvent(win, 'load', readyHandler); + } + + /** + * This class enables you to bind/unbind native events to elements and normalize it's behavior across browsers. + */ + function EventUtils() { + var self = this, events = {}, count, expando, hasFocusIn, hasMouseEnterLeave, mouseEnterLeave; + + expando = eventExpandoPrefix + (+new Date()).toString(32); + 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; + + /** + * Executes all event handler callbacks for a specific event. + * + * @param {Event} evt Event object. + * @param {String} id Expando id value to look for. + */ + 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; + } + } + } + } + + /** + * Binds a callback to an event on the specified target. + * + * @method bind + * @param {Object} target Target node/window or custom object. + * @param {String} names Name of the event to bind. + * @param {function} callback Callback function to execute when the event occurs. + * @param {Object} scope Scope to call the callback function on, defaults to target. + * @return {function} Callback function that got bound. + */ + 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]; + } + + // 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 && name === "ready" && target.readyState == 'complete') { + 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; + + // Check if the target has native events support + + if (name === "ready") { + bindOnReady(target, nativeHandler, self); + } else { + addEvent(target, fakeName || name, nativeHandler, capture); + } + } else { + if (name === "ready" && self.domLoaded) { + callback({type: name}); + } 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; + }; + + /** + * Unbinds the specified event by name, name and callback or all events on the target. + * + * @method unbind + * @param {Object} target Target node/window or custom object. + * @param {String} names Optional event name to unbind. + * @param {function} callback Optional callback function to unbind. + * @return {EventUtils} Event utils instance. + */ + 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, callbackList.nativeHandler, callbackList.capture); + } + } + } + } else { + // All events for a specific element + for (name in eventMap) { + callbackList = eventMap[name]; + removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, 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; + }; + + /** + * Fires the specified event on the specified target. + * + * @method fire + * @param {Object} target Target node/window or custom object. + * @param {String} name Event name to fire. + * @param {Object} args Optional arguments to send to the observers. + * @return {EventUtils} Event utils instance. + */ + self.fire = function(target, name, args) { + var id; + + // 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 + args = fix(null, args); + args.type = name; + args.target = target; + + do { + // Found an expando that means there is listeners to execute + id = target[expando]; + if (id) { + executeHandlers(args, id); + } + + // Walk up the DOM + target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow; + } while (target && !args.isPropagationStopped()); + + return self; + }; + + /** + * Removes all bound event listeners for the specified target. This will also remove any bound + * listeners to child nodes within that target. + * + * @method clean + * @param {Object} target Target node/window object. + * @return {EventUtils} Event utils instance. + */ + 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; + }; + + /** + * Destroys the event object. Call this on IE to remove memory leaks. + */ + self.destory = function() { + events = {}; + }; + + // Legacy function for canceling events + self.cancel = function(e) { + if (e) { + e.preventDefault(); + e.stopImmediatePropagation(); + } + + return false; + }; + } + + EventUtils.Event = new EventUtils(); + EventUtils.Event.bind(window, 'ready', function() {}); + + return EventUtils; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/dom/Range.js b/lib/tinymce/jscripts/tinymce4/classes/dom/Range.js new file mode 100644 index 00000000..5fb52ea7 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/dom/Range.js @@ -0,0 +1,774 @@ +/** + * Range.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/dom/Range", [ + "tinymce/util/Tools" +], function(Tools) { + // 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 = Tools.extend, + nodeIndex = dom.nodeIndex; + + 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; + var 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]; + var 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); + } + + function toStringIE() { + return dom.create('body', null, cloneContents()).outerText; + } + + 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, + toStringIE: toStringIE + }); + + return t; + } + + // Older IE versions doesn't let you override toString by it's constructor so we have to stick it in the prototype + Range.prototype.toString = function() { + return this.toStringIE(); + }; + + return Range; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/dom/RangeUtils.js b/lib/tinymce/jscripts/tinymce4/classes/dom/RangeUtils.js new file mode 100644 index 00000000..d99339fb --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/dom/RangeUtils.js @@ -0,0 +1,267 @@ +/** + * Range.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/dom/RangeUtils", [ + "tinymce/util/Tools" +], function(Tools) { + var each = Tools.each; + + function RangeUtils(dom) { + /** + * Walks the specified range like object and executes the callback for each sibling collection it finds. + * + * @param {Object} rng Range like object. + * @param {function} callback Callback function to execute for each sibling collection. + */ + 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.mce-item-selected,th.mce-item-selected'); + if (nodes.length > 0) { + each(nodes, function(node) { + callback([node]); + }); + + return; + } + + /** + * Excludes start/end text node if they are out side the range + * + * @private + * @param {Array} nodes Nodes to exclude items from. + * @return {Array} Array with nodes excluding the start/end container if needed. + */ + 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; + } + + /** + * Collects siblings + * + * @private + * @param {Node} node Node to collect siblings from. + * @param {String} name Name of the sibling to check for. + * @return {Array} Array of collected siblings. + */ + function collectSiblings(node, name, end_node) { + var siblings = []; + + for (; node && node != end_node; node = node[name]) { + siblings.push(node); + } + + return siblings; + } + + /** + * Find an end point this is the node just before the common ancestor root. + * + * @private + * @param {Node} node Node to start at. + * @param {Node} root Root/ancestor element to stop just before. + * @return {Node} Node just before the root element. + */ + 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); + }; + + /** + * Splits the specified range at it's start/end points. + * + * @param {Range/RangeObject} rng Range to split. + * @return {Object} Range position object. + */ + 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 + }; + }; + } + + /** + * Compares two ranges and checks if they are equal. + * + * @static + * @param {DOMRange} rng1 First range to compare. + * @param {DOMRange} rng2 First range to compare. + * @return {Boolean} true/false if the ranges are equal. + */ + 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; + }; + + return RangeUtils; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/dom/ScriptLoader.js b/lib/tinymce/jscripts/tinymce4/classes/dom/ScriptLoader.js new file mode 100644 index 00000000..3294cdc9 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/dom/ScriptLoader.js @@ -0,0 +1,249 @@ +/** + * ScriptLoader.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*globals console*/ + +/** + * This class handles asynchronous/synchronous loading of JavaScript files it will execute callbacks + * when various items gets loaded. This class is useful to load external JavaScript files. + * + * @class tinymce.dom.ScriptLoader + * @example + * // Load a script from a specific URL using the global script loader + * tinymce.ScriptLoader.load('somescript.js'); + * + * // Load a script using a unique instance of the script loader + * var scriptLoader = new tinymce.dom.ScriptLoader(); + * + * scriptLoader.load('somescript.js'); + * + * // Load multiple scripts + * var scriptLoader = new tinymce.dom.ScriptLoader(); + * + * scriptLoader.add('somescript1.js'); + * scriptLoader.add('somescript2.js'); + * scriptLoader.add('somescript3.js'); + * + * scriptLoader.loadQueue(function() { + * alert('All scripts are now loaded.'); + * }); + */ +define("tinymce/dom/ScriptLoader", [ + "tinymce/dom/DOMUtils", + "tinymce/util/Tools" +], function(DOMUtils, Tools) { + var DOM = DOMUtils.DOM; + var each = Tools.each, grep = Tools.grep; + + function ScriptLoader() { + var QUEUED = 0, + LOADING = 1, + LOADED = 2, + states = {}, + queue = [], + scriptLoadedCallbacks = {}, + queueLoadedCallbacks = [], + loading = 0, + undef; + + /** + * Loads a specific script directly without adding it to the load queue. + * + * @method load + * @param {String} url Absolute URL to script to add. + * @param {function} callback Optional callback function to execute ones this script gets loaded. + * @param {Object} scope Optional scope to execute callback in. + */ + function loadScript(url, callback) { + var dom = DOM, elm, 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(); + + // Create new script element + elm = document.createElement('script'); + elm.id = id; + elm.type = 'text/javascript'; + elm.src = url; + + elm.onload = done; + elm.onreadystatechange = function() { + if (/loaded|complete/.test(elm.readyState)) { + done(); + } + }; + + // Add onerror event will get fired on some browsers but not all of them + elm.onerror = error; + + // Add script to document + (document.getElementsByTagName('head')[0] || document.body).appendChild(elm); + } + + /** + * Returns true/false if a script has been loaded or not. + * + * @method isDone + * @param {String} url URL to check for. + * @return [Boolean} true/false if the URL is loaded. + */ + this.isDone = function(url) { + return states[url] == LOADED; + }; + + /** + * Marks a specific script to be loaded. This can be useful if a script got loaded outside + * the script loader or to skip it from loading some script. + * + * @method markDone + * @param {string} u Absolute URL to the script to mark as loaded. + */ + this.markDone = function(url) { + states[url] = LOADED; + }; + + /** + * Adds a specific script to the load queue of the script loader. + * + * @method add + * @param {String} url Absolute URL to script to add. + * @param {function} callback Optional callback function to execute ones this script gets loaded. + * @param {Object} scope Optional scope to execute callback in. + */ + this.add = this.load = function(url, callback, scope) { + var 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 + }); + } + }; + + /** + * Starts the loading of the queue. + * + * @method loadQueue + * @param {function} callback Optional callback to execute when all queued items are loaded. + * @param {Object} scope Optional scope to execute the callback in. + */ + this.loadQueue = function(callback, scope) { + this.loadScripts(queue, callback, scope); + }; + + /** + * Loads the specified queue of files and executes the callback ones they are loaded. + * This method is generally not used outside this class but it might be useful in some scenarios. + * + * @method loadScripts + * @param {Array} scripts Array of queue items to load. + * @param {function} callback Optional callback to execute ones all items are loaded. + * @param {Object} scope Optional scope to execute callback in. + */ + this.loadScripts = function(scripts, callback, scope) { + var loadScripts; + + function execScriptLoadedCallbacks(url) { + // Execute URL callback functions + each(scriptLoadedCallbacks[url], function(callback) { + callback.func.call(callback.scope); + }); + + scriptLoadedCallbacks[url] = undef; + } + + queueLoadedCallbacks.push({ + func: callback, + scope: scope || this + }); + + loadScripts = function() { + var loadingScripts = grep(scripts); + + // Current scripts has been handled + scripts.length = 0; + + // Load scripts that needs to be loaded + 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) { + each(queueLoadedCallbacks, function(callback) { + callback.func.call(callback.scope); + }); + + queueLoadedCallbacks.length = 0; + } + }; + + loadScripts(); + }; + } + + ScriptLoader.ScriptLoader = new ScriptLoader(); + + return ScriptLoader; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/dom/Selection.js b/lib/tinymce/jscripts/tinymce4/classes/dom/Selection.js new file mode 100644 index 00000000..fee8305f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/dom/Selection.js @@ -0,0 +1,1314 @@ +/** + * Selection.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles text and control selection it's an crossbrowser utility class. + * Consult the TinyMCE Wiki API for more details and examples on how to use this class. + * + * @class tinymce.dom.Selection + * @example + * // Getting the currently selected node for the active editor + * alert(tinymce.activeEditor.selection.getNode().nodeName); + */ +define("tinymce/dom/Selection", [ + "tinymce/dom/TreeWalker", + "tinymce/dom/TridentSelection", + "tinymce/dom/ControlSelection", + "tinymce/Env", + "tinymce/util/Tools" +], function(TreeWalker, TridentSelection, ControlSelection, Env, Tools) { + var each = Tools.each, grep = Tools.grep, trim = Tools.trim; + var isIE = Env.ie, isOpera = Env.opera; + + /** + * Constructs a new selection instance. + * + * @constructor + * @method Selection + * @param {tinymce.dom.DOMUtils} dom DOMUtils object reference. + * @param {Window} win Window to bind the selection object to. + * @param {tinymce.dom.Serializer} serializer DOM serialization class to use for getContent. + */ + function Selection(dom, win, serializer, editor) { + var self = this; + + self.dom = dom; + self.win = win; + self.serializer = serializer; + self.editor = editor; + + self.controlSelection = new ControlSelection(self, editor); + + editor.on('nodechange', function() { + var rng; + + // Use old style IE range since we want to restore control selections + if (editor.getDoc().selection) { + rng = editor.getDoc().selection.createRange(); + } else { + rng = self.getRng(); + } + + self.lastRng = rng; + }); + + // No W3C Range support + if (!self.win.getSelection) { + self.tridentSel = new TridentSelection(self); + } + } + + Selection.prototype = { + /** + * Move the selection cursor range to the specified node and offset. + * @param node Node to put the cursor in. + * @param offset Offset from the start of the node to put the cursor at. + */ + setCursorLocation: function(node, offset) { + var self = this, rng = self.dom.createRng(); + rng.setStart(node, offset); + rng.setEnd(node, offset); + self.setRng(rng); + self.collapse(false); + }, + + /** + * Returns the selected contents using the DOM serializer passed in to this class. + * + * @method getContent + * @param {Object} s Optional settings class with for example output format text or html. + * @return {String} Selected contents in for example HTML format. + * @example + * // Alerts the currently selected contents + * alert(tinymce.activeEditor.selection.getContent()); + * + * // Alerts the currently selected contents as plain text + * alert(tinymce.activeEditor.selection.getContent({format: 'text'})); + */ + getContent: function(args) { + var self = this, rng = self.getRng(), tmpElm = self.dom.create("body"); + var se = self.getSel(), whiteSpaceBefore, whiteSpaceAfter, fragment; + + args = args || {}; + whiteSpaceBefore = whiteSpaceAfter = ''; + args.get = true; + args.format = args.format || 'html'; + args.selection = true; + self.editor.fire('BeforeGetContent', args); + + if (args.format == 'text') { + return self.isCollapsed() ? '' : (rng.text || (se.toString ? se.toString() : '')); + } + + if (rng.cloneContents) { + fragment = rng.cloneContents(); + + if (fragment) { + tmpElm.appendChild(fragment); + } + } else if (rng.item !== undefined || rng.htmlText !== undefined) { + // 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. + tmpElm.innerHTML = '
' + (rng.item ? rng.item(0).outerHTML : rng.htmlText); + tmpElm.removeChild(tmpElm.firstChild); + } else { + tmpElm.innerHTML = rng.toString(); + } + + // Keep whitespace before and after + if (/^\s/.test(tmpElm.innerHTML)) { + whiteSpaceBefore = ' '; + } + + if (/\s+$/.test(tmpElm.innerHTML)) { + whiteSpaceAfter = ' '; + } + + args.getInner = true; + + args.content = self.isCollapsed() ? '' : whiteSpaceBefore + self.serializer.serialize(tmpElm, args) + whiteSpaceAfter; + self.editor.fire('GetContent', args); + + return args.content; + }, + + /** + * Sets the current selection to the specified content. If any contents is selected it will be replaced + * with the contents passed in to this function. If there is no selection the contents will be inserted + * where the caret is placed in the editor/page. + * + * @method setContent + * @param {String} content HTML contents to set could also be other formats depending on settings. + * @param {Object} args Optional settings object with for example data format. + * @example + * // Inserts some HTML contents at the current selection + * tinymce.activeEditor.selection.setContent('Some contents'); + */ + setContent: function(content, args) { + var self = this, rng = self.getRng(), caretNode, doc = self.win.document, frag, temp; + + args = args || {format: 'html'}; + args.set = true; + args.selection = true; + content = args.content = content; + + // Dispatch before set content event + if (!args.no_events) { + self.editor.fire('BeforeSetContent', args); + } + + content = args.content; + + if (rng.insertNode) { + // Make caret marker since insertNode places the caret in the beginning of text after insert + content += '_'; + + // 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('_' + content); + self.dom.remove('__mce_tmp'); + } else { + rng.pasteHTML(content); + } + } + + // Dispatch set content event + if (!args.no_events) { + self.editor.fire('SetContent', args); + } + }, + + /** + * Returns the start element of a selection range. If the start is in a text + * node the parent element will be returned. + * + * @method getStart + * @return {Element} Start element of selection range. + */ + getStart: function() { + var self = this, rng = self.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(); + if (startElement.ownerDocument !== self.dom.doc) { + startElement = self.dom.getRoot(); + } + + // 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; + } + }, + + /** + * Returns the end element of a selection range. If the end is in a text + * node the parent element will be returned. + * + * @method getEnd + * @return {Element} End element of selection range. + */ + getEnd: function() { + var self = this, rng = self.getRng(), endElement, endOffset; + + if (rng.duplicate || rng.item) { + if (rng.item) { + return rng.item(0); + } + + rng = rng.duplicate(); + rng.collapse(0); + endElement = rng.parentElement(); + if (endElement.ownerDocument !== self.dom.doc) { + endElement = self.dom.getRoot(); + } + + if (endElement && endElement.nodeName == 'BODY') { + return endElement.lastChild || endElement; + } + + return endElement; + } else { + endElement = rng.endContainer; + endOffset = rng.endOffset; + + if (endElement.nodeType == 1 && endElement.hasChildNodes()) { + endElement = endElement.childNodes[endOffset > 0 ? endOffset - 1 : endOffset]; + } + + if (endElement && endElement.nodeType == 3) { + return endElement.parentNode; + } + + return endElement; + } + }, + + /** + * Returns a bookmark location for the current selection. This bookmark object + * can then be used to restore the selection after some content modification to the document. + * + * @method getBookmark + * @param {Number} type Optional state if the bookmark should be simple or not. Default is complex. + * @param {Boolean} normalized Optional state that enables you to get a position that it would be after normalization. + * @return {Object} Bookmark object, use moveToBookmark with this object to restore the selection. + * @example + * // Stores a bookmark of the current selection + * var bm = tinymce.activeEditor.selection.getBookmark(); + * + * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content'); + * + * // Restore the selection bookmark + * tinymce.activeEditor.selection.moveToBookmark(bm); + */ + getBookmark: function(type, normalized) { + var t = this, dom = t.dom, rng, rng2, id, collapsed, name, element, chr = '', styles; + + function findIndex(name, element) { + var index = 0; + + each(dom.select(name), function(node, i) { + if (node == element) { + index = i; + } + }); + + return index; + } + + function normalizeTableCellSelection(rng) { + function moveEndPoint(start) { + var container, offset, childNodes, prefix = start ? 'start' : 'end'; + + container = rng[prefix + 'Container']; + offset = rng[prefix + 'Offset']; + + if (container.nodeType == 1 && container.nodeName == "TR") { + childNodes = container.childNodes; + container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)]; + if (container) { + offset = start ? 0 : container.childNodes.length; + rng['set' + (start ? 'Start' : 'End')](container, offset); + } + } + } + + moveEndPoint(true); + moveEndPoint(); + + return rng; + } + + 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) { + element = t.getNode(); + name = element.nodeName; + + if (name == 'IMG') { + return {name: name, index: findIndex(name, element)}; + } + + 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 = t.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('' + chr + ''); + + // Insert end marker + if (!collapsed) { + rng2.collapse(false); + + // Detect the empty space after block elements in IE and move the + // end back one character

] becomes

]

+ rng.moveToElementText(rng2.parentElement()); + if (rng.compareEndPoints('StartToEnd', rng2) === 0) { + rng2.move('character', -1); + } + + rng2.pasteHTML('' + chr + ''); + } + } 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)}; + } + + // W3C method + rng2 = normalizeTableCellSelection(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 = normalizeTableCellSelection(rng); + 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}; + }, + + /** + * Restores the selection to the specified bookmark. + * + * @method moveToBookmark + * @param {Object} bookmark Bookmark to restore selection from. + * @return {Boolean} true/false if it was successful or not. + * @example + * // Stores a bookmark of the current selection + * var bm = tinymce.activeEditor.selection.getBookmark(); + * + * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content'); + * + * // Restore the selection bookmark + * tinymce.activeEditor.selection.moveToBookmark(bm); + */ + moveToBookmark: function(bookmark) { + var t = this, dom = t.dom, 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(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 && !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 = '
'; + } + + 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); + } + } + }, + + /** + * Selects the specified element. This will place the start and end of the selection range around the element. + * + * @method select + * @param {Element} node HMTL DOM element to select. + * @param {Boolean} content Optional bool state if the contents should be selected or not on non IE browser. + * @return {Element} Selected element the same element as the one that got passed in. + * @example + * // Select the first paragraph in the active editor + * tinymce.activeEditor.selection.select(tinymce.activeEditor.dom.select('p')[0]); + */ + 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 && 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) { + if (!content && t.controlSelection.controlSelect(node)) { + return; + } + + 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; + }, + + /** + * Returns true/false if the selection range is collapsed or not. Collapsed means if it's a caret or a larger selection. + * + * @method isCollapsed + * @return {Boolean} true/false state if the selection range is collapsed or not. + * Collapsed means if it's a caret or a larger selection. + */ + isCollapsed: function() { + var self = this, rng = self.getRng(), sel = self.getSel(); + + if (!rng || rng.item) { + return false; + } + + if (rng.compareEndPoints) { + return rng.compareEndPoints('StartToEnd', rng) === 0; + } + + return !sel || rng.collapsed; + }, + + /** + * Collapse the selection to start or end of range. + * + * @method collapse + * @param {Boolean} to_start Optional boolean state if to collapse to end or not. Defaults to start. + */ + 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); + }, + + /** + * Returns the browsers internal selection object. + * + * @method getSel + * @return {Selection} Internal browser selection object. + */ + getSel: function() { + var win = this.win; + + return win.getSelection ? win.getSelection() : win.document.selection; + }, + + /** + * Returns the browsers internal range object. + * + * @method getRng + * @param {Boolean} w3c Forces a compatible W3C range on IE. + * @return {Range} Internal browser range object. + * @see http://www.quirksmode.org/dom/range_intro.html + * @see http://www.dotvoid.com/2001/03/using-the-range-object-in-mozilla/ + */ + getRng: function(w3c) { + var self = this, selection, rng, elm, doc = self.win.document; + + // Found tridentSel object then we need to use that one + if (w3c && self.tridentSel) { + return self.tridentSel.getRangeAt(0); + } + + try { + if ((selection = self.getSel())) { + if (selection.rangeCount > 0) { + rng = selection.getRangeAt(0); + } else { + rng = selection.createRange ? selection.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 (isIE && rng && rng.setStart && doc.selection.createRange().item) { + elm = doc.selection.createRange().item(0); + rng = doc.createRange(); + rng.setStartBefore(elm); + rng.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 (!rng) { + rng = doc.createRange ? doc.createRange() : doc.body.createTextRange(); + } + + // If range is at start of document then move it to start of body + if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) { + elm = self.dom.getRoot(); + rng.setStart(elm, 0); + rng.setEnd(elm, 0); + } + + if (self.selectedRange && self.explicitRange) { + if (rng.compareBoundaryPoints(rng.START_TO_START, self.selectedRange) === 0 && + rng.compareBoundaryPoints(rng.END_TO_END, self.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. + rng = self.explicitRange; + } else { + self.selectedRange = null; + self.explicitRange = null; + } + } + + return rng; + }, + + /** + * Changes the selection to the specified DOM range. + * + * @method setRng + * @param {Range} rng Range to select. + */ + setRng: function(rng, forward) { + var self = this, sel; + + self.lastRng = null; + + // Is IE specific range + if (rng.select) { + try { + rng.select(); + } catch (ex) { + // Needed for some odd IE bug #1843306 + } + + return; + } + + if (!self.tridentSel) { + sel = self.getSel(); + + if (sel) { + self.explicitRange = rng; + + try { + sel.removeAllRanges(); + } catch (ex) { + // IE9 might throw errors here don't know why + } + + sel.addRange(rng); + + // Forward is set to false and we have an extend function + if (forward === false && sel.extend) { + sel.collapse(rng.endContainer, rng.endOffset); + sel.extend(rng.startContainer, rng.startOffset); + } + + // adding range isn't always successful so we need to check range count otherwise an exception can occur + self.selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null; + } + } else { + // Is W3C Range fake range on IE + if (rng.cloneRange) { + try { + self.tridentSel.addRange(rng); + return; + } catch (ex) { + //IE9 throws an error here if called before selection is placed in the editor + } + } + } + }, + + /** + * Sets the current selection to the specified DOM element. + * + * @method setNode + * @param {Element} elm Element to set as the contents of the selection. + * @return {Element} Returns the element that got passed in. + * @example + * // Inserts a DOM node at current selection/caret location + * tinymce.activeEditor.selection.setNode(tinymce.activeEditor.dom.create('img', {src: 'some.gif', title: 'some title'})); + */ + setNode: function(elm) { + var self = this; + + self.setContent(self.dom.getOuterHTML(elm)); + + return elm; + }, + + /** + * Returns the currently selected element or the common ancestor element for both start and end of the selection. + * + * @method getNode + * @return {Element} Currently selected element or common ancestor element. + * @example + * // Alerts the currently selected elements node name + * alert(tinymce.activeEditor.selection.getNode().nodeName); + */ + getNode: function() { + var self = this, rng = self.getRng(), elm; + var startContainer = rng.startContainer, endContainer = rng.endContainer; + var startOffset = rng.startOffset, endOffset = rng.endOffset; + + function skipEmptyTextNodes(node, forwards) { + var orig = node; + + while (node && node.nodeType === 3 && node.length === 0) { + node = forwards ? node.nextSibling : node.previousSibling; + } + + return node || orig; + } + + // Range maybe lost after the editor is made visible again + if (!rng) { + return self.dom.getRoot(); + } + + if (rng.setStart) { + elm = rng.commonAncestorContainer; + + // Handle selection a image or other control like element such as anchors + if (!rng.collapsed) { + if (startContainer == endContainer) { + if (endOffset - startOffset < 2) { + if (startContainer.hasChildNodes()) { + elm = startContainer.childNodes[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 (startContainer.nodeType === 3 && endContainer.nodeType === 3) { + if (startContainer.length === startOffset) { + startContainer = skipEmptyTextNodes(startContainer.nextSibling, true); + } else { + startContainer = startContainer.parentNode; + } + + if (endOffset === 0) { + endContainer = skipEmptyTextNodes(endContainer.previousSibling, false); + } else { + endContainer = endContainer.parentNode; + } + + if (startContainer && startContainer === endContainer) { + return startContainer; + } + } + } + + if (elm && elm.nodeType == 3) { + return elm.parentNode; + } + + return elm; + } + + return rng.item ? rng.item(0) : rng.parentElement(); + }, + + getSelectedBlocks: function(startElm, endElm) { + var self = this, dom = self.dom, node, selectedBlocks = []; + + startElm = dom.getParent(startElm || self.getStart(), dom.isBlock); + endElm = dom.getParent(endElm || self.getEnd(), dom.isBlock); + + if (startElm) { + selectedBlocks.push(startElm); + } + + if (startElm && endElm && startElm != endElm) { + node = startElm; + + var walker = new TreeWalker(startElm, dom.getRoot()); + while ((node = walker.next()) && node != endElm) { + if (dom.isBlock(node)) { + selectedBlocks.push(node); + } + } + } + + if (endElm && startElm != endElm) { + selectedBlocks.push(endElm); + } + + return selectedBlocks; + }, + + isForward: function(){ + var dom = this.dom, sel = this.getSel(), anchorRange, focusRange; + + // No support for selection direction then always return true + if (!sel || !sel.anchorNode || !sel.focusNode) { + return true; + } + + anchorRange = dom.createRng(); + anchorRange.setStart(sel.anchorNode, sel.anchorOffset); + anchorRange.collapse(true); + + focusRange = dom.createRng(); + focusRange.setStart(sel.focusNode, sel.focusOffset); + focusRange.collapse(true); + + return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0; + }, + + normalize: function() { + var self = this, rng, normalized, collapsed; + + function normalizeEndPoint(start) { + var container, offset, walker, dom = self.dom, body = dom.getRoot(), node, nonEmptyElementsMap, nodeName; + + function hasBrBeforeAfter(node, left) { + var walker = new TreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || body); + + while ((node = walker[left ? 'prev' : 'next']())) { + if (node.nodeName === "BR") { + return true; + } + } + } + + function isPrevNode(node, name) { + return node.previousSibling && node.previousSibling.nodeName == name; + } + + // 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 = dom.getRoot(); + 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()) { + offset = Math.min(!start && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1); + container = container.childNodes[offset]; + offset = 0; + + // Don't walk into elements that doesn't have any child nodes like a IMG + if (container.hasChildNodes() && !/TABLE/.test(container.nodeName)) { + // 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: x|x + // Becomes: x|x + // 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: |
+ // Becomes: |
+ // Seems that only gecko has issues with this. + // Special edge case for

x|

since we don't want

x|

+ if (container.nodeType === 1) { + node = container.childNodes[offset]; + if(node && node.nodeName === 'BR' && !isPrevNode(node, 'A') && + !hasBrBeforeAfter(node) && !hasBrBeforeAfter(node, true)) { + findTextNodeRelative(true, container.childNodes[offset]); + } + } + } + + // Lean the start of the selection right if possible + // So this: x[x] + // Becomes: x[x] + 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); + } + } + + // Normalize only on non IE browsers for now + if (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, self.isForward()); + } + }, + + /** + * Executes callback of the current selection matches the specified selector or not and passes the state and args to the callback. + * + * @method selectorChanged + * @param {String} selector CSS selector to check for. + * @param {function} callback Callback with state and args when the selector is matches or not. + */ + selectorChanged: function(selector, callback) { + var self = this, currentSelectors; + + if (!self.selectorChangedData) { + self.selectorChangedData = {}; + currentSelectors = {}; + + self.editor.on('NodeChange', function(e) { + var node = e.element, dom = self.dom, parents = dom.getParents(node, null, dom.getRoot()), matchedSelectors = {}; + + // Check for new matching selectors + each(self.selectorChangedData, function(callbacks, selector) { + each(parents, function(node) { + if (dom.is(node, selector)) { + if (!currentSelectors[selector]) { + // Execute callbacks + each(callbacks, function(callback) { + callback(true, {node: node, selector: selector, parents: parents}); + }); + + currentSelectors[selector] = callbacks; + } + + matchedSelectors[selector] = callbacks; + return false; + } + }); + }); + + // Check if current selectors still match + each(currentSelectors, function(callbacks, selector) { + if (!matchedSelectors[selector]) { + delete currentSelectors[selector]; + + each(callbacks, function(callback) { + callback(false, {node: node, selector: selector, parents: parents}); + }); + } + }); + }); + } + + // Add selector listeners + if (!self.selectorChangedData[selector]) { + self.selectorChangedData[selector] = []; + } + + self.selectorChangedData[selector].push(callback); + + return self; + }, + + scrollIntoView: function(elm) { + var y, viewPort, self = this, dom = self.dom; + + viewPort = dom.getViewPort(self.editor.getWin()); + y = dom.getPos(elm).y; + if (y < viewPort.y || y + 25 > viewPort.y + viewPort.h) { + self.editor.getWin().scrollTo(0, y < viewPort.y ? y : y - viewPort.h + 25); + } + }, + + destroy: function() { + this.win = this.lastRng = null; + this.controlSelection.destroy(); + } + }; + + return Selection; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/dom/Serializer.js b/lib/tinymce/jscripts/tinymce4/classes/dom/Serializer.js new file mode 100644 index 00000000..30a21459 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/dom/Serializer.js @@ -0,0 +1,385 @@ +/** + * Serializer.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is used to serialize DOM trees into a string. Consult the TinyMCE Wiki API for + * more details and examples on how to use this class. + * + * @class tinymce.dom.Serializer + */ +define("tinymce/dom/Serializer", [ + "tinymce/dom/DOMUtils", + "tinymce/html/DomParser", + "tinymce/html/Entities", + "tinymce/html/Serializer", + "tinymce/html/Node", + "tinymce/html/Schema", + "tinymce/Env", + "tinymce/util/Tools" +], function(DOMUtils, DomParser, Entities, Serializer, Node, Schema, Env, Tools) { + var each = Tools.each, trim = Tools.trim; + var DOM = DOMUtils.DOM; + + /** + * Constucts a new DOM serializer class. + * + * @constructor + * @method Serializer + * @param {Object} settings Serializer settings object. + * @param {tinymce.Editor} editor Optional editor to bind events to and get schema/dom from. + */ + return function(settings, editor) { + var dom, schema, htmlParser; + + if (editor) { + dom = editor.dom; + schema = editor.schema; + } + + // Default DOM and Schema if they are undefined + dom = dom || DOM; + schema = schema || new Schema(settings); + settings.entity_encoding = settings.entity_encoding || 'named'; + settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true; + + htmlParser = new 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; + var 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<..> or mceSelected + htmlParser.addAttributeFilter('class', function(nodes) { + var i = nodes.length, node, value; + + while (i--) { + node = nodes[i]; + value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\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) { + var i = nodes.length; + + while (i--) { + nodes[i].attr(name, null); + } + }); + + htmlParser.addNodeFilter('noscript', function(nodes) { + var i = nodes.length, node; + + while (i--) { + node = nodes[i].firstChild; + + if (node) { + node.value = Entities.decode(node.value); + } + } + }); + + // 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) { + /*jshint maxlen:255 */ + return value.replace(/()/g, '\n') + .replace(/^[\r\n]*|[\r\n]*$/g, '') + .replace(/^\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 = '// '; + } + } else { + if (value.length > 0) { + node.firstChild.value = ''; + } + } + } + }); + + // Convert comments to cdata and handle protected comments + htmlParser.addNodeFilter('#comment', function(nodes) { + 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) { + 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,data-mce-selected', function(nodes, name) { + var i = nodes.length; + + while (i--) { + nodes[i].attr(name, null); + } + }); + + // Return public methods + return { + /** + * Schema instance that was used to when the Serializer was constructed. + * + * @field {tinymce.html.Schema} schema + */ + schema: schema, + + /** + * Adds a node filter function to the parser used by the serializer, the parser will collect the specified nodes by name + * and then execute the callback ones it has finished parsing the document. + * + * @example + * parser.addNodeFilter('p,h1', function(nodes, name) { + * for (var i = 0; i < nodes.length; i++) { + * console.log(nodes[i].name); + * } + * }); + * @method addNodeFilter + * @method {String} name Comma separated list of nodes to collect. + * @param {function} callback Callback function to execute once it has collected nodes. + */ + addNodeFilter: htmlParser.addNodeFilter, + + /** + * Adds a attribute filter function to the parser used by the serializer, the parser will + * collect nodes that has the specified attributes + * and then execute the callback ones it has finished parsing the document. + * + * @example + * parser.addAttributeFilter('src,href', function(nodes, name) { + * for (var i = 0; i < nodes.length; i++) { + * console.log(nodes[i].name); + * } + * }); + * @method addAttributeFilter + * @method {String} name Comma separated list of nodes to collect. + * @param {function} callback Callback function to execute once it has collected nodes. + */ + addAttributeFilter: htmlParser.addAttributeFilter, + + /** + * Serializes the specified browser DOM node into a HTML string. + * + * @method serialize + * @param {DOMNode} node DOM node to serialize. + * @param {Object} args Arguments option that gets passed to event handlers. + */ + serialize: function(node, args) { + var self = this, 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 (Env.ie && 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 + // 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'; + + // Don't wrap content if we want selected html + if (args.selection) { + args.forced_root_block = ''; + } + + // Pre process + if (!args.no_events) { + args.node = node; + self.onPreProcess(args); + } + + // Setup serializer + htmlSerializer = new Serializer(settings, schema); + + // Parse and serialize HTML + args.content = htmlSerializer.serialize( + htmlParser.parse(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/g, ''); + } + + // Post process + if (!args.no_events) { + self.onPostProcess(args); + } + + // Restore the old document if it was changed + if (oldDoc) { + dom.doc = oldDoc; + } + + args.node = null; + + return args.content; + }, + + /** + * Adds valid elements rules to the serializers schema instance this enables you to specify things + * like what elements should be outputted and what attributes specific elements might have. + * Consult the Wiki for more details on this format. + * + * @method addRules + * @param {String} rules Valid elements rules string to add to schema. + */ + addRules: function(rules) { + schema.addValidElements(rules); + }, + + /** + * Sets the valid elements rules to the serializers schema instance this enables you to specify things + * like what elements should be outputted and what attributes specific elements might have. + * Consult the Wiki for more details on this format. + * + * @method setRules + * @param {String} rules Valid elements rules string. + */ + setRules: function(rules) { + schema.setValidElements(rules); + }, + + onPreProcess: function(args) { + if (editor) { + editor.fire('PreProcess', args); + } + }, + + onPostProcess: function(args) { + if (editor) { + editor.fire('PostProcess', args); + } + } + }; + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/dom/Sizzle.jQuery.js b/lib/tinymce/jscripts/tinymce4/classes/dom/Sizzle.jQuery.js new file mode 100644 index 00000000..21de9bcc --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/dom/Sizzle.jQuery.js @@ -0,0 +1,28 @@ +/** + * Sizzle.jQuery.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global jQuery:true */ + +/* + * Fake Sizzle using jQuery. + */ +define("tinymce/dom/Sizzle", [], function() { + var $ = jQuery; + + function Sizzle(selector, context, results, seed) { + return $.find(selector, context, results, seed); + } + + Sizzle.matches = function(expr, elements) { + return $(elements).is(expr) ? elements : []; + }; + + return Sizzle; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/dom/Sizzle.js b/lib/tinymce/jscripts/tinymce4/classes/dom/Sizzle.js new file mode 100644 index 00000000..98f25f93 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/dom/Sizzle.js @@ -0,0 +1,1923 @@ +/** + * Sizzle.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint bitwise:false, expr:true, noempty:false, sub:true, eqnull:true, latedef:false, maxlen:255 */ + +/* + * Sizzle CSS Selector Engine + * Copyright, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +define("tinymce/dom/Sizzle", [], function() { +var i, + cachedruns, + Expr, + getText, + isXML, + compile, + outermostContext, + recompare, + sortInput, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + -(new Date()), + preferredDoc = window.document, + support = {}, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + hasDuplicate = false, + sortOrder = function() { return 0; }, + + // General-purpose constants + strundefined = typeof undefined, + MAX_NEGATIVE = 1 << 31, + + // Array methods + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf if we can't use a native one + indexOf = arr.indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + + // 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/, + + // 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 ); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +/** + * 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 = []; + + 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() ]; + } + cache[ key ] = value; + return value; + }; + + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // 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 ( documentIsHTML && !seed ) { + + // Shortcuts + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // QSA path + if ( support.qsa && !rbuggyQSA.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, + newContext.querySelectorAll( newSelector ) + ); + 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 + documentIsHTML = !isXML( doc ); + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = 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 = ""; + 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.getElementsByClassName = assert(function( div ) { + // Opera can't find a second classname (in 9.6) + div.innerHTML = ""; + 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 getElementsByName privileges form controls or returns elements by ID + // If so, assume (for broader support) that getElementById returns elements by name + support.getByName = assert(function( div ) { + // Inject content + div.id = expando + 0; + // Support: Windows 8 Native Apps + // Assigning innerHTML with "name" attributes throws uncatchable exceptions + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx + div.appendChild( document.createElement("a") ).setAttribute( "name", expando ); + div.appendChild( document.createElement("i") ).setAttribute( "name", expando ); + docElem.appendChild( div ); + + // 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; + + // Cleanup + docElem.removeChild( div ); + + return pass; + }); + + // Support: Webkit<537.32 + // Detached nodes confoundingly follow *each other* + support.sortDetached = assert(function( div1 ) { + return div1.compareDocumentPosition && + // Should return 1, but Webkit returns 4 (following) + (div1.compareDocumentPosition( document.createElement("div") ) & 1); + }); + + // IE6/7 return modified attributes + Expr.attrHandle = assert(function( div ) { + div.innerHTML = ""; + 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.getByName ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + 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.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var elem, + tmp = [], + i = 0, + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Name + Expr.find["NAME"] = support.getByName && function( tag, context ) { + if ( typeof context.getElementsByName !== strundefined ) { + return context.getElementsByName( name ); + } + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { + 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 explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // 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 = ""; + 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 = rbuggyMatches.length && 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 ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); + + if ( compare ) { + // Disconnected nodes + if ( compare & 1 || + (recompare && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === doc || contains(preferredDoc, a) ) { + return -1; + } + if ( b === doc || contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } + + // Not directly comparable, sort on existence of method + return a.compareDocumentPosition ? -1 : 1; + } : + function( a, b ) { + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Parentless nodes are either documents or disconnected + } else if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return 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 && documentIsHTML && (!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 ( documentIsHTML ) { + name = name.toLowerCase(); + } + if ( (val = Expr.attrHandle[ name ]) ) { + return val( elem ); + } + if ( !documentIsHTML || 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 = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + // Compensate for sort limitations + recompare = !support.sortDetached; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + return results; +}; + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns Returns -1 if a precedes b, 1 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +// Returns a function to use in pseudos for input types +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.slice( -check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), + // not comment, processing instructions, or others + // Thanks to Diego Perini for the nodeName shortcut + // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +// 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 && 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 ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); + + if ( outermost ) { + outermostContext = context !== document && context; + cachedruns = matcherCachedRuns; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + for ( ; (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + cachedruns = ++matcherCachedRuns; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !group ) { + group = tokenize( selector ); + } + i = group.length; + while ( i-- ) { + cached = matcherFromTokens( group[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + } + return cached; +}; + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function select( selector, context, results, seed ) { + var i, tokens, token, type, find, + match = tokenize( selector ); + + if ( !seed ) { + // Try to minimize operations if there is only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && context.parentNode || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + } + + // Compile and execute a filtering function + // Provide `match` to avoid retokenization if we modified the selector above + compile( selector, match )( + seed, + context, + !documentIsHTML, + results, + rsibling.test( selector ) + ); + return results; +} + +// Deprecated +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +// Check sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Initialize with the default document +setDocument(); + +// Always assume the presence of duplicates if sort doesn't +// pass them to our comparison function (as in Google Chrome). +[0, 0].sort( sortOrder ); +support.detectDuplicates = hasDuplicate; + +// EXPOSE +if ( typeof define === "function" && define.amd ) { + define(function() { return Sizzle; }); +} else { + window.Sizzle = Sizzle; +} + +// EXPOSE +return Sizzle; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/dom/TreeWalker.js b/lib/tinymce/jscripts/tinymce4/classes/dom/TreeWalker.js new file mode 100644 index 00000000..c774ceef --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/dom/TreeWalker.js @@ -0,0 +1,71 @@ +/** + * TreeWalker.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/dom/TreeWalker", [], function() { + return 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; + } + } + } + } + } + + /** + * Returns the current node. + * + * @return {Node} Current node where the walker is. + */ + this.current = function() { + return node; + }; + + /** + * Walks to the next node in tree. + * + * @return {Node} Current node where the walker is after moving to the next node. + */ + this.next = function(shallow) { + node = findSibling(node, 'firstChild', 'nextSibling', shallow); + return node; + }; + + /** + * Walks to the previous node in tree. + * + * @return {Node} Current node where the walker is after moving to the previous node. + */ + this.prev = function(shallow) { + node = findSibling(node, 'lastChild', 'previousSibling', shallow); + return node; + }; + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/dom/TridentSelection.js b/lib/tinymce/jscripts/tinymce4/classes/dom/TridentSelection.js new file mode 100644 index 00000000..cb1dcd07 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/dom/TridentSelection.js @@ -0,0 +1,496 @@ +/** + * TridentSelection.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/dom/TridentSelection", [], function() { + function Selection(selection) { + var self = this, dom = selection.dom, 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; + + // 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(), 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, offset; + + 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, sibling, + doc = selection.dom.doc, body = doc.body, nativeRng, ctrlElm; + + 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
|
+ // Setting innerHTML with a span marker then remove that marker seems to keep empty block elements open + container.innerHTML = ''; + 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

+ if (startOffset == endOffset && !startContainer.hasChildNodes()) { + if (startContainer.canHaveHTML) { + // Check if previous sibling is an empty block if it is then we need to render it + // IE would otherwise move the caret into the sibling instead of the empty startContainer see: #5236 + // Example this:

|

would become this:

|

+ sibling = startContainer.previousSibling; + if (sibling && !sibling.hasChildNodes() && dom.isBlock(sibling)) { + sibling.innerHTML = ''; + } else { + sibling = null; + } + + startContainer.innerHTML = ''; + ieRng.moveToElementText(startContainer.lastChild); + ieRng.select(); + dom.doc.selection.clear(); + startContainer.innerHTML = ''; + + if (sibling) { + sibling.innerHTML = ''; + } + return; + } else { + startOffset = dom.nodeIndex(startContainer); + startContainer = startContainer.parentNode; + } + } + + if (startOffset == endOffset - 1) { + try { + ctrlElm = startContainer.childNodes[startOffset]; + ctrlRng = body.createControlRange(); + ctrlRng.addElement(ctrlElm); + ctrlRng.select(); + + // Check if the range produced is on the correct element and is a control range + // On IE 8 it will select the parent contentEditable container if you select an inner element see: #5398 + nativeRng = selection.getRng(); + if (nativeRng.item && ctrlElm === nativeRng.item(0)) { + 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; + } + + return Selection; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/html/DomParser.js b/lib/tinymce/jscripts/tinymce4/classes/html/DomParser.js new file mode 100644 index 00000000..1d5ee75f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/html/DomParser.js @@ -0,0 +1,752 @@ +/** + * DomParser.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class parses HTML code into a DOM like structure of nodes it will remove redundant whitespace and make + * sure that the node tree is valid according to the specified schema. + * So for example:

a

b

c

will become

a

b

c

+ * + * @example + * var parser = new tinymce.html.DomParser({validate: true}, schema); + * var rootNode = parser.parse('

content

'); + * + * @class tinymce.html.DomParser + * @version 3.4 + */ +define("tinymce/html/DomParser", [ + "tinymce/html/Node", + "tinymce/html/Schema", + "tinymce/html/SaxParser", + "tinymce/util/Tools" +], function(Node, Schema, SaxParser, Tools) { + var makeMap = Tools.makeMap, each = Tools.each, explode = Tools.explode, extend = Tools.extend; + + /** + * Constructs a new DomParser instance. + * + * @constructor + * @method DomParser + * @param {Object} settings Name/value collection of settings. comment, cdata, text, start and end are callbacks. + * @param {tinymce.html.Schema} schema HTML Schema class to use when parsing. + */ + return 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 Schema(); + + function fixInvalidChildren(nodes) { + var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i; + var nonEmptyElements, nonSplitableElements, textBlockElements, sibling, nextNode; + + nonSplitableElements = makeMap('tr,td,th,tbody,thead,tfoot,table'); + nonEmptyElements = schema.getNonEmptyElements(); + textBlockElements = schema.getTextBlockElements(); + + for (ni = 0; ni < nodes.length; ni++) { + node = nodes[ni]; + + // Already removed or fixed + if (!node.parent || node.fixed) { + continue; + } + + // If the invalid element is a text block and the text block is within a parent LI element + // Then unwrap the first text block and convert other sibling text blocks to LI elements similar to Word/Open Office + if (textBlockElements[node.name] && node.parent.name == 'li') { + // Move sibling text blocks after LI element + sibling = node.next; + while (sibling) { + if (textBlockElements[sibling.name]) { + sibling.name = 'li'; + sibling.fixed = true; + node.parent.insert(sibling, node.parent); + } else { + break; + } + + sibling = sibling.next; + } + + // Unwrap current text block + node.unwrap(node); + 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


+ 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(); + } + } + } + } + } + + /** + * Runs the specified node though the element and attributes filters. + * + * @param {tinymce.html.Node} Node the node to run filters on. + * @return {tinymce.html.Node} The passed in node. + */ + 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; + }; + + /** + * Adds a node filter function to the parser, the parser will collect the specified nodes by name + * and then execute the callback ones it has finished parsing the document. + * + * @example + * parser.addNodeFilter('p,h1', function(nodes, name) { + * for (var i = 0; i < nodes.length; i++) { + * console.log(nodes[i].name); + * } + * }); + * @method addNodeFilter + * @method {String} name Comma separated list of nodes to collect. + * @param {function} callback Callback function to execute once it has collected nodes. + */ + self.addNodeFilter = function(name, callback) { + each(explode(name), function(name) { + var list = nodeFilters[name]; + + if (!list) { + nodeFilters[name] = list = []; + } + + list.push(callback); + }); + }; + + /** + * Adds a attribute filter function to the parser, the parser will collect nodes that has the specified attributes + * and then execute the callback ones it has finished parsing the document. + * + * @example + * parser.addAttributeFilter('src,href', function(nodes, name) { + * for (var i = 0; i < nodes.length; i++) { + * console.log(nodes[i].name); + * } + * }); + * @method addAttributeFilter + * @method {String} name Comma separated list of nodes to collect. + * @param {function} callback Callback function to execute once it has collected nodes. + */ + self.addAttributeFilter = function(name, callback) { + each(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]}); + }); + }; + + /** + * Parses the specified HTML string into a DOM like node tree and returns the result. + * + * @example + * var rootNode = new DomParser({...}).parse('text'); + * @method parse + * @param {String} html Html string to sax parse. + * @param {Object} args Optional args object that gets passed to all filter functions. + * @return {tinymce.html.Node} Root node containing the tree. + */ + self.parse = function(html, args) { + var parser, rootNode, node, nodes, i, l, fi, fl, list, name, validate; + var blockElements, startWhiteSpaceRegExp, invalidChildren = [], isInWhiteSpacePreservedElement; + var endWhiteSpaceRegExp, allWhiteSpaceRegExp, isAllWhiteSpaceRegExp, whiteSpaceElements; + var children, nonEmptyElements, rootBlockName; + + args = args || {}; + matchedNodes = {}; + matchedAttributes = {}; + blockElements = extend(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; + isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/; + + function addRootBlocks() { + var node = rootNode.firstChild, next, rootBlockNode; + + // Removes whitespace at beginning and end of block so: + //

x

->

x

+ function trim(rootBlockNode) { + if (rootBlockNode) { + node = rootBlockNode.firstChild; + if (node && node.type == 3) { + node.value = node.value.replace(startWhiteSpaceRegExp, ''); + } + + node = rootBlockNode.lastChild; + if (node && node.type == 3) { + node.value = node.value.replace(endWhiteSpaceRegExp, ''); + } + } + } + + // Check if rootBlock is valid within rootNode for example if P is valid in H1 if H1 is the contentEditabe root + if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) { + return; + } + + 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 { + trim(rootBlockNode); + rootBlockNode = null; + } + + node = next; + } + + trim(rootBlockNode); + } + + 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; + } + } + } + + function cloneAndExcludeBlocks(input) { + var name, output = {}; + + for (name in input) { + if (name !== 'li' && name != 'p') { + output[name] = input[name]; + } + } + + return output; + } + + parser = new SaxParser({ + validate: validate, + + // Exclude P and LI from DOM parsing since it's treated better by the DOM parser + self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()), + + 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, attrName, 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
or + 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 of the first node in a block + textNode = node.firstChild; + if (textNode && textNode.type === 3) { + text = textNode.value.replace(startWhiteSpaceRegExp, ''); + + // Any characters left after trim or should we remove it + if (text.length > 0) { + textNode.value = text; + textNode = textNode.next; + } else { + sibling = textNode.next; + textNode.remove(); + textNode = sibling; + + // Remove any pure whitespace siblings + while (textNode && textNode.type === 3) { + text = textNode.value; + sibling = textNode.next; + + if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) { + textNode.remove(); + textNode = sibling; + } + + textNode = sibling; + } + } + } + + // Trim whitespace of the last node in a block + textNode = node.lastChild; + if (textNode && textNode.type === 3) { + text = textNode.value.replace(endWhiteSpaceRegExp, ''); + + // Any characters left after trim or should we remove it + if (text.length > 0) { + textNode.value = text; + textNode = textNode.prev; + } else { + sibling = textNode.prev; + textNode.remove(); + textNode = sibling; + + // Remove any pure whitespace siblings + while (textNode && textNode.type === 3) { + text = textNode.value; + sibling = textNode.prev; + + if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) { + textNode.remove(); + textNode = sibling; + } + + textNode = sibling; + } + } + } + } + + // Trim start white space + // Removed due to: #5424 + /*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 + if (!node.attributes.map.name && !node.attributes.map.id) { + 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' || args.isRootContent)) { + 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
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) { + var i, l = nodes.length, node, blockElements = extend({}, schema.getBlockElements()); + var nonEmptyElements = schema.getNonEmptyElements(), parent, lastParent, prev, prevName; + var elementRule, textNode; + + // Remove brs from body element as well + blockElements.body = 1; + + // Must loop forwards since it will otherwise remove all brs in

a


+ 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

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 Node('#text', 3)).value = '\u00a0'; + } + } + } + } + } else { + // Replaces BR elements inside inline elements like


+ // so they become

 

+ lastParent = node; + while (parent.firstChild === lastParent && parent.lastChild === lastParent) { + lastParent = parent; + + if (blockElements[parent.name]) { + break; + } + + parent = parent.parent; + } + + if (lastParent === parent) { + textNode = new 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('id,name', function(nodes) { + var i = nodes.length, sibling, prevSibling, parent, node; + + while (i--) { + node = nodes[i]; + if (node.name === 'a' && node.firstChild && !node.attr('href')) { + parent = node.parent; + + // Move children after current node + sibling = node.lastChild; + do { + prevSibling = sibling.prev; + parent.insert(sibling, node); + sibling = prevSibling; + } while (sibling); + } + } + }); + } + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/html/Entities.js b/lib/tinymce/jscripts/tinymce4/classes/html/Entities.js new file mode 100644 index 00000000..7fbd8c4d --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/html/Entities.js @@ -0,0 +1,261 @@ +/** + * Entities.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint bitwise:false */ + +/** + * Entity encoder class. + * + * @class tinymce.html.Entities + * @static + * @version 3.4 + */ +define("tinymce/html/Entities", [ + "tinymce/util/Tools" +], function(Tools) { + var makeMap = Tools.makeMap; + + 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 = { + '\"': '"', // Needs to be escaped since the YUI compressor would otherwise break the code + "'": ''', + '<': '<', + '>': '>', + '&': '&' + }; + + // Reverse lookup table for raw entities + reverseEntities = { + '<': '<', + '>': '>', + '&': '&', + '"': '"', + ''': "'" + }; + + // 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); + + var Entities = { + /** + * Encodes the specified string using raw entities. This means only the required XML base entities will be endoded. + * + * @method encodeRaw + * @param {String} text Text to encode. + * @param {Boolean} attr Optional flag to specify if the text is attribute contents. + * @return {String} Entity encoded text. + */ + encodeRaw: function(text, attr) { + return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { + return baseEntities[chr] || chr; + }); + }, + + /** + * Encoded the specified text with both the attributes and text entities. This function will produce larger text contents + * since it doesn't know if the context is within a attribute or text node. This was added for compatibility + * and is exposed as the DOMUtils.encode function. + * + * @method encodeAllRaw + * @param {String} text Text to encode. + * @return {String} Entity encoded text. + */ + encodeAllRaw: function(text) { + return ('' + text).replace(rawCharsRegExp, function(chr) { + return baseEntities[chr] || chr; + }); + }, + + /** + * Encodes the specified string using numeric entities. The core entities will be + * encoded as named ones but all non lower ascii characters will be encoded into numeric entities. + * + * @method encodeNumeric + * @param {String} text Text to encode. + * @param {Boolean} attr Optional flag to specify if the text is attribute contents. + * @return {String} Entity encoded text. + */ + 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) + ';'; + }); + }, + + /** + * Encodes the specified string using named entities. The core entities will be encoded + * as named ones but all non lower ascii characters will be encoded into named entities. + * + * @method encodeNamed + * @param {String} text Text to encode. + * @param {Boolean} attr Optional flag to specify if the text is attribute contents. + * @param {Object} entities Optional parameter with entities to use. + * @return {String} Entity encoded text. + */ + encodeNamed: function(text, attr, entities) { + entities = entities || namedEntities; + + return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { + return baseEntities[chr] || entities[chr] || chr; + }); + }, + + /** + * Returns an encode function based on the name(s) and it's optional entities. + * + * @method getEncodeFunc + * @param {String} name Comma separated list of encoders for example named,numeric. + * @param {String} entities Optional parameter with entities to use instead of the built in set. + * @return {function} Encode function to be used. + */ + getEncodeFunc: function(name, 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 = 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; + }, + + /** + * Decodes the specified string, this will replace entities with raw UTF characters. + * + * @param {String} text Text to entity decode. + * @return {String} Entity decoded string. + */ + 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); + }); + } + }; + + return Entities; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/html/Node.js b/lib/tinymce/jscripts/tinymce4/classes/html/Node.js new file mode 100644 index 00000000..acfc57a9 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/html/Node.js @@ -0,0 +1,496 @@ +/** + * Node.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is a minimalistic implementation of a DOM like node used by the DomParser class. + * + * @example + * var node = new tinymce.html.Node('strong', 1); + * someRoot.append(node); + * + * @class tinymce.html.Node + * @version 3.4 + */ +define("tinymce/html/Node", [], function() { + 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; + } + } + } + } + + /** + * Constructs a new Node instance. + * + * @constructor + * @method Node + * @param {String} name Name of the node type. + * @param {Number} type Numeric type representing the node. + */ + function Node(name, type) { + this.name = name; + this.type = type; + + if (type === 1) { + this.attributes = []; + this.attributes.map = {}; + } + } + + Node.prototype = { + /** + * Replaces the current node with the specified one. + * + * @example + * someNode.replace(someNewNode); + * + * @method replace + * @param {tinymce.html.Node} node Node to replace the current node with. + * @return {tinymce.html.Node} The old node that got replaced. + */ + replace: function(node) { + var self = this; + + if (node.parent) { + node.remove(); + } + + self.insert(node, self); + self.remove(); + + return self; + }, + + /** + * Gets/sets or removes an attribute by name. + * + * @example + * someNode.attr("name", "value"); // Sets an attribute + * console.log(someNode.attr("name")); // Gets an attribute + * someNode.attr("name", null); // Removes an attribute + * + * @method attr + * @param {String} name Attribute name to set or get. + * @param {String} value Optional value to set. + * @return {String/tinymce.html.Node} String or undefined on a get operation or the current node on a set operation. + */ + 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]; + } + } + }, + + /** + * Does a shallow clones the node into a new node. It will also exclude id attributes since + * there should only be one id per document. + * + * @example + * var clonedNode = node.clone(); + * + * @method clone + * @return {tinymce.html.Node} New copy of the original node. + */ + 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; + }, + + /** + * Wraps the node in in another node. + * + * @example + * node.wrap(wrapperNode); + * + * @method wrap + */ + wrap: function(wrapper) { + var self = this; + + self.parent.insert(wrapper, self); + wrapper.append(self); + + return self; + }, + + /** + * Unwraps the node in other words it removes the node but keeps the children. + * + * @example + * node.unwrap(); + * + * @method unwrap + */ + unwrap: function() { + var self = this, node, next; + + for (node = self.firstChild; node; ) { + next = node.next; + self.insert(node, self, true); + node = next; + } + + self.remove(); + }, + + /** + * Removes the node from it's parent. + * + * @example + * node.remove(); + * + * @method remove + * @return {tinymce.html.Node} Current node that got removed. + */ + 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; + }, + + /** + * Appends a new node as a child of the current node. + * + * @example + * node.append(someNode); + * + * @method append + * @param {tinymce.html.Node} node Node to append as a child of the current one. + * @return {tinymce.html.Node} The node that got appended. + */ + 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; + }, + + /** + * Inserts a node at a specific position as a child of the current node. + * + * @example + * parentNode.insert(newChildNode, oldChildNode); + * + * @method insert + * @param {tinymce.html.Node} node Node to insert as a child of the current node. + * @param {tinymce.html.Node} ref_node Reference node to set node before/after. + * @param {Boolean} before Optional state to insert the node before the reference node. + * @return {tinymce.html.Node} The node that got inserted. + */ + 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; + }, + + /** + * Get all children by name. + * + * @method getAll + * @param {String} name Name of the child nodes to collect. + * @return {Array} Array with child nodes matchin the specified name. + */ + 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; + }, + + /** + * Removes all children of the current node. + * + * @method empty + * @return {tinymce.html.Node} The current node that got cleared. + */ + 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; + }, + + /** + * Returns true/false if the node is to be considered empty or not. + * + * @example + * node.isEmpty({img: true}); + * @method isEmpty + * @param {Object} elements Name/value object with elements that are automatically treated as non empty elements. + * @return {Boolean} true/false if the node is empty or not. + */ + 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 + if (elements[node.name]) { + return false; + } + + // Keep elements with data attributes or name attribute like
+ i = node.attributes.length; + while (i--) { + name = node.attributes[i].name; + if (name === "name" || name.indexOf('data-mce-') === 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; + }, + + /** + * Walks to the next or previous node and returns that node or null if it wasn't found. + * + * @method walk + * @param {Boolean} prev Optional previous node state defaults to false. + * @return {tinymce.html.Node} Node that is next to or previous of the current node. + */ + walk: function(prev) { + return walk(this, null, prev); + } + }; + + /** + * Creates a node of a specific type. + * + * @static + * @method create + * @param {String} name Name of the node type to create for example "b" or "#text". + * @param {Object} attrs Name/value collection of attributes that will be applied to elements. + */ + 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; + }; + + return Node; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/html/SaxParser.js b/lib/tinymce/jscripts/tinymce4/classes/html/SaxParser.js new file mode 100644 index 00000000..f58e7b49 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/html/SaxParser.js @@ -0,0 +1,390 @@ +/** + * SaxParser.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class parses HTML code using pure JavaScript and executes various events for each item it finds. It will + * always execute the events in the right order for tag soup code like

. It will also remove elements + * and attributes that doesn't fit the schema if the validate setting is enabled. + * + * @example + * var parser = new tinymce.html.SaxParser({ + * validate: true, + * + * comment: function(text) { + * console.log('Comment:', text); + * }, + * + * cdata: function(text) { + * console.log('CDATA:', text); + * }, + * + * text: function(text, raw) { + * console.log('Text:', text, 'Raw:', raw); + * }, + * + * start: function(name, attrs, empty) { + * console.log('Start:', name, attrs, empty); + * }, + * + * end: function(name) { + * console.log('End:', name); + * }, + * + * pi: function(name, text) { + * console.log('PI:', name, text); + * }, + * + * doctype: function(text) { + * console.log('DocType:', text); + * } + * }, schema); + * @class tinymce.html.SaxParser + * @version 3.4 + */ +define("tinymce/html/SaxParser", [ + "tinymce/html/Schema", + "tinymce/html/Entities", + "tinymce/util/Tools" +], function(Schema, Entities, Tools) { + var each = Tools.each; + + /** + * Constructs a new SaxParser instance. + * + * @constructor + * @method SaxParser + * @param {Object} settings Name/value collection of settings. comment, cdata, text, start and end are callbacks. + * @param {tinymce.html.Schema} schema HTML Schema class to use when parsing. + */ + return function(settings, schema) { + var self = this, noop = function() {}; + + settings = settings || {}; + self.schema = schema = schema || new Schema(); + + if (settings.fix_self_closing !== false) { + settings.fix_self_closing = true; + } + + // Add handler functions from settings and setup default handlers + each('comment cdata text start end pi doctype'.split(' '), function(name) { + if (name) { + self[name] = settings[name] || noop; + } + }); + + /** + * Parses the specified HTML string and executes the callbacks for each item it finds. + * + * @example + * new SaxParser({...}).parse('text'); + * @method parse + * @param {String} html Html string to sax parse. + */ + self.parse = function(html) { + var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name; + var isInternalElement, removeInternalElements, shortEndedElements, fillAttrsMap, isShortEnded; + var validate, elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns; + var attributesRequired, attributesDefault, attributesForced; + var anyAttributesRequired, selfClosing, tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0; + var decode = Entities.decode, fixSelfClosing; + + 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-mce-') !== 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; + + // Setup lookup tables for empty elements and boolean attributes + shortEndedElements = schema.getShortEndedElements(); + selfClosing = settings.self_closing_elements || schema.getSelfClosingElements(); + fillAttrsMap = schema.getBoolAttrs(); + validate = settings.validate; + removeInternalElements = settings.remove_internals; + fixSelfClosing = settings.fix_self_closing; + specialElements = schema.getSpecialElements(); + + 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 (value.charAt(0) === ':') { + 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 (value.charAt(0) === ':') { + value = value.substr(1); + } + + isShortEnded = value in shortEndedElements; + + // Is self closing tag for example an
  • after an open
  • + 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; + anyAttributesRequired = elementRule.removeEmptyAttrs; + + // Check if any attribute exists + if (anyAttributesRequired && !attrList.length) { + isValidElement = false; + } + + // 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) { + if (text.length > 0) { + self.text(text, true); + } + + 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); + } + } + }; + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/html/Schema.js b/lib/tinymce/jscripts/tinymce4/classes/html/Schema.js new file mode 100644 index 00000000..6e027cc2 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/html/Schema.js @@ -0,0 +1,917 @@ +/** + * Schema.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Schema validator class. + * + * @class tinymce.html.Schema + * @example + * if (tinymce.activeEditor.schema.isValidChild('p', 'span')) + * alert('span is valid child of p.'); + * + * if (tinymce.activeEditor.schema.getElementRule('p')) + * alert('P is a valid element.'); + * + * @class tinymce.html.Schema + * @version 3.4 + */ +define("tinymce/html/Schema", [ + "tinymce/util/Tools" +], function(Tools) { + var mapCache = {}; + var makeMap = Tools.makeMap, each = Tools.each, extend = Tools.extend, explode = Tools.explode, inArray = Tools.inArray; + + function split(items, delim) { + return items ? items.split(delim || ' ') : []; + } + + /** + * Builds a schema lookup table + * + * @param {String} type html4, html5 or html5-strict schema type. + * @return {Object} Schema lookup table. + */ + function compileSchema(type) { + var schema = {}, globalAttributes, eventAttributes, blockContent; + var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent; + + function add(name, attributes, children) { + var ni, i, attributesOrder, args = arguments; + + function arrayToMap(array) { + var map = {}, i, l; + + for (i = 0, l = array.length; i < l; i++) { + map[array[i]] = {}; + } + + return map; + } + + children = children || []; + attributes = attributes || ""; + + if (typeof(children) === "string") { + children = split(children); + } + + // Split string children + for (i = 3; i < args.length; i++) { + if (typeof(args[i]) === "string") { + args[i] = split(args[i]); + } + + children.push.apply(children, args[i]); + } + + name = split(name); + ni = name.length; + while (ni--) { + attributesOrder = [].concat(globalAttributes, split(attributes)); + schema[name[ni]] = { + attributes: arrayToMap(attributesOrder), + attributesOrder: attributesOrder, + children: arrayToMap(children) + }; + } + } + + function addAttrs(name, attributes) { + var ni, schemaItem, i, l; + + name = split(name); + ni = name.length; + attributes = split(attributes); + while (ni--) { + schemaItem = schema[name[ni]]; + for (i = 0, l = attributes.length; i < l; i++) { + schemaItem.attributes[attributes[i]] = {}; + schemaItem.attributesOrder.push(attributes[i]); + } + } + } + + // Use cached schema + if (mapCache[type]) { + return mapCache[type]; + } + + // Attributes present on all elements + globalAttributes = split("id accesskey class dir lang style tabindex title"); + + // Event attributes can be opt-in/opt-out + eventAttributes = split("onabort onblur oncancel oncanplay oncanplaythrough onchange onclick onclose oncontextmenu oncuechange " + + "ondblclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop ondurationchange onemptied onended " + + "onerror onfocus oninput oninvalid onkeydown onkeypress onkeyup onload onloadeddata onloadedmetadata onloadstart " + + "onmousedown onmousemove onmouseout onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange " + + "onreset onscroll onseeked onseeking onseeking onselect onshow onstalled onsubmit onsuspend ontimeupdate onvolumechange " + + "onwaiting" + ); + + // Block content elements + blockContent = split( + "address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul" + ); + + // Phrasing content elements from the HTML5 spec (inline) + phrasingContent = split( + "a abbr b bdo br button cite code del dfn em embed i iframe img input ins kbd " + + "label map noscript object q s samp script select small span strong sub sup " + + "textarea u var #text #comment" + ); + + // Add HTML5 items to globalAttributes, blockContent, phrasingContent + if (type != "html4") { + globalAttributes.push.apply(globalAttributes, split("contenteditable contextmenu draggable dropzone " + + "hidden spellcheck translate")); + blockContent.push.apply(blockContent, split("article aside details dialog figure header footer hgroup section nav")); + phrasingContent.push.apply(phrasingContent, split("audio canvas command datalist mark meter output progress time wbr " + + "video ruby bdi keygen")); + } + + // Add HTML4 elements unless it's html5-strict + if (type != "html5-strict") { + globalAttributes.push("xml:lang"); + + html4PhrasingContent = split("acronym applet basefont big font strike tt"); + phrasingContent.push.apply(phrasingContent, html4PhrasingContent); + + each(html4PhrasingContent, function(name) { + add(name, "", phrasingContent); + }); + + html4BlockContent = split("center dir isindex noframes"); + blockContent.push.apply(blockContent, html4BlockContent); + + // Flow content elements from the HTML5 spec (block+inline) + flowContent = [].concat(blockContent, phrasingContent); + + each(html4BlockContent, function(name) { + add(name, "", flowContent); + }); + } + + // Flow content elements from the HTML5 spec (block+inline) + flowContent = flowContent || [].concat(blockContent, phrasingContent); + + // HTML4 base schema TODO: Move HTML5 specific attributes to HTML5 specific if statement + // Schema items , , + add("html", "manifest", "head body"); + add("head", "", "base command link meta noscript script style title"); + add("title hr noscript br"); + add("base", "href target"); + add("link", "href rel media hreflang type sizes hreflang"); + add("meta", "name http-equiv content charset"); + add("style", "media type scoped"); + add("script", "src async defer type charset"); + add("body", "onafterprint onbeforeprint onbeforeunload onblur onerror onfocus " + + "onhashchange onload onmessage onoffline ononline onpagehide onpageshow " + + "onpopstate onresize onscroll onstorage onunload", flowContent); + add("address dt dd div caption", "", flowContent); + add("h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn", "", phrasingContent); + add("blockquote", "cite", flowContent); + add("ol", "reversed start type", "li"); + add("ul", "", "li"); + add("li", "value", flowContent); + add("dl", "", "dt dd"); + add("a", "href target rel media hreflang type", phrasingContent); + add("q", "cite", phrasingContent); + add("ins del", "cite datetime", flowContent); + add("img", "src alt usemap ismap width height"); + add("iframe", "src name width height", flowContent); + add("embed", "src type width height"); + add("object", "data type typemustmatch name usemap form width height", flowContent, "param"); + add("param", "name value"); + add("map", "name", flowContent, "area"); + add("area", "alt coords shape href target rel media hreflang type"); + add("table", "border", "caption colgroup thead tfoot tbody tr" + (type == "html4" ? " col" : "")); + add("colgroup", "span", "col"); + add("col", "span"); + add("tbody thead tfoot", "", "tr"); + add("tr", "", "td th"); + add("td", "colspan rowspan headers", flowContent); + add("th", "colspan rowspan headers scope abbr", flowContent); + add("form", "accept-charset action autocomplete enctype method name novalidate target", flowContent); + add("fieldset", "disabled form name", flowContent, "legend"); + add("label", "form for", phrasingContent); + add("input", "accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate " + + "formtarget height list max maxlength min multiple name pattern readonly required size src step type value width" + ); + add("button", "disabled form formaction formenctype formmethod formnovalidate formtarget name type value", + type == "html4" ? flowContent : phrasingContent); + add("select", "disabled form multiple name required size", "option optgroup"); + add("optgroup", "disabled label", "option"); + add("option", "disabled label selected value"); + add("textarea", "cols dirname disabled form maxlength name readonly required rows wrap"); + add("menu", "type label", flowContent, "li"); + add("noscript", "", flowContent); + + // Extend with HTML5 elements + if (type != "html4") { + add("wbr"); + add("ruby", "", phrasingContent, "rt rp"); + add("figcaption", "", flowContent); + add("mark rt rp summary bdi", "", phrasingContent); + add("canvas", "width height", flowContent); + add("video", "src crossorigin poster preload autoplay mediagroup loop " + + "muted controls width height", flowContent, "track source"); + add("audio", "src crossorigin preload autoplay mediagroup loop muted controls", flowContent, "track source"); + add("source", "src type media"); + add("track", "kind src srclang label default"); + add("datalist", "", phrasingContent, "option"); + add("article section nav aside header footer", "", flowContent); + add("hgroup", "", "h1 h2 h3 h4 h5 h6"); + add("figure", "", flowContent, "figcaption"); + add("time", "datetime", phrasingContent); + add("dialog", "open", flowContent); + add("command", "type label icon disabled checked radiogroup command"); + add("output", "for form name", phrasingContent); + add("progress", "value max", phrasingContent); + add("meter", "value min max low high optimum", phrasingContent); + add("details", "open", flowContent, "summary"); + add("keygen", "autofocus challenge disabled form keytype name"); + } + + // Extend with HTML4 attributes unless it's html5-strict + if (type != "html5-strict") { + addAttrs("script", "language xml:space"); + addAttrs("style", "xml:space"); + addAttrs("object", "declare classid codebase codetype archive standby align border hspace vspace"); + addAttrs("param", "valuetype type"); + addAttrs("a", "charset name rev shape coords"); + addAttrs("br", "clear"); + addAttrs("applet", "codebase archive code object alt name width height align hspace vspace"); + addAttrs("img", "name longdesc align border hspace vspace"); + addAttrs("iframe", "longdesc frameborder marginwidth marginheight scrolling align"); + addAttrs("font basefont", "size color face"); + addAttrs("input", "usemap align"); + addAttrs("select", "onchange"); + addAttrs("textarea"); + addAttrs("h1 h2 h3 h4 h5 h6 div p legend caption", "align"); + addAttrs("ul", "type compact"); + addAttrs("li", "type"); + addAttrs("ol dl menu dir", "compact"); + addAttrs("pre", "width xml:space"); + addAttrs("hr", "align noshade size width"); + addAttrs("isindex", "prompt"); + addAttrs("table", "summary width frame rules cellspacing cellpadding align bgcolor"); + addAttrs("col", "width align char charoff valign"); + addAttrs("colgroup", "width align char charoff valign"); + addAttrs("thead", "align char charoff valign"); + addAttrs("tr", "align char charoff valign bgcolor"); + addAttrs("th", "axis align char charoff valign nowrap bgcolor width height"); + addAttrs("form", "accept"); + addAttrs("td", "abbr axis scope align char charoff valign nowrap bgcolor width height"); + addAttrs("tfoot", "align char charoff valign"); + addAttrs("tbody", "align char charoff valign"); + addAttrs("area", "nohref"); + addAttrs("body", "background bgcolor text link vlink alink"); + } + + // Extend with HTML5 attributes unless it's html4 + if (type != "html4") { + addAttrs("input button select textarea", "autofocus"); + addAttrs("input textarea", "placeholder"); + addAttrs("a", "download"); + addAttrs("link script img", "crossorigin"); + addAttrs("iframe", "srcdoc sandbox seamless allowfullscreen"); + } + + // Special: iframe, ruby, video, audio, label + + // Delete children of the same name from it's parent + // For example: form can't have a child of the name form + each(split('a form meter progress dfn'), function(name) { + if (schema[name]) { + delete schema[name].children[name]; + } + }); + + // Delete header, footer, sectioning and heading content descendants + /*each('dt th address', function(name) { + delete schema[name].children[name]; + });*/ + + // Caption can't have tables + delete schema.caption.children.table; + + // TODO: LI:s can only have value if parent is OL + + // TODO: Handle transparent elements + // a ins del canvas map + + mapCache[type] = schema; + + return schema; + } + + /** + * Constructs a new Schema instance. + * + * @constructor + * @method Schema + * @param {Object} settings Name/value settings object. + */ + return function(settings) { + var self = this, elements = {}, children = {}, patternElements = [], validStyles, schemaItems; + var whiteSpaceElementsMap, selfClosingElementsMap, shortEndedElementsMap, boolAttrMap; + var blockElementsMap, nonEmptyElementsMap, textBlockElementsMap, customElementsMap = {}, specialElements = {}; + + // Creates an lookup table map object for the specified option or the default value + function createLookupTable(option, default_value, extendWith) { + 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 = extend(value, extendWith); + + mapCache[option] = value; + } + } else { + // Create custom map + value = makeMap(value, ',', makeMap(value.toUpperCase(), ' ')); + } + + return value; + } + + settings = settings || {}; + schemaItems = compileSchema(settings.schema); + + // 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] = explode(value); + }); + } + + // Setup map objects + whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object'); + selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr'); + shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' + + 'meta param embed source wbr track'); + boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + + 'noshade nowrap readonly selected autoplay loop controls'); + nonEmptyElementsMap = createLookupTable('non_empty_elements', 'td th iframe video audio object', shortEndedElementsMap); + textBlockElementsMap = createLookupTable('text_block_elements', 'h1 h2 h3 h4 h5 h6 p div address pre form ' + + 'blockquote center dir fieldset header footer article section hgroup aside nav figure'); + blockElementsMap = createLookupTable('block_elements', 'hr table tbody thead tfoot ' + + 'th tr td li ol ul caption dl dt dd noscript menu isindex samp option ' + + 'datalist select optgroup', textBlockElementsMap); + + each((settings.special || 'script noscript style textarea').split(' '), function(name) { + specialElements[name] = new RegExp('<\/' + name + '[^>]*>','gi'); + }); + + // 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, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, + prefix, outputName, globalAttributes, globalAttributesOrder, key, 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[5]; + + // 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; + } + + if (matches[4] === '!') { + element.removeEmptyAttrs = 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(inArray(attributesOrder, attrName), 1); + continue; + } + + // Default value + if (prefix) { + // Default value + if (prefix === '=') { + element.attributesDefault = element.attributesDefault || []; + element.attributesDefault.push({name: attrName, value: value}); + attr.defaultValue = value; + } + + // Forced value + if (prefix === ':') { + element.attributesForced = element.attributesForced || []; + element.attributesForced.push({name: attrName, value: value}); + attr.forcedValue = value; + } + + // Required values + if (prefix === '<') { + attr.validValues = makeMap(value, '?'); + } + } + + // Check for attribute patterns + if (hasPatternsRegExp.test(attrName)) { + element.attributePatterns = element.attributePatterns || []; + attr.pattern = patternToRegExp(attrName); + element.attributePatterns.push(attr); + } else { + // Add attribute to order list if it doesn't already exist + if (!attributes[attrName]) { + attributesOrder.push(attrName); + } + + attributes[attrName] = attr; + } + } + } + } + + // Global rule, store away these for later usage + if (!globalAttributes && elementName == '@') { + globalAttributes = attributes; + globalAttributesOrder = attributesOrder; + } + + // Handle substitute elements such as b/strong + if (outputName) { + element.outputName = elementName; + elements[outputName] = element; + } + + // Add pattern or exact element + if (hasPatternsRegExp.test(elementName)) { + element.pattern = patternToRegExp(elementName); + patternElements.push(element); + } else { + elements[elementName] = element; + } + } + } + } + } + + function setValidElements(valid_elements) { + elements = {}; + patternElements = []; + + addValidElements(valid_elements); + + each(schemaItems, function(element, name) { + children[name] = element.children; + }); + } + + // Adds custom non HTML elements to the schema + function addCustomElements(custom_elements) { + var customElementRegExp = /^(~)?(.+)$/; + + if (custom_elements) { + each(split(custom_elements, ','), function(rule) { + var matches = customElementRegExp.exec(rule), + inline = matches[1] === '~', + cloneName = inline ? 'span' : 'div', + name = matches[2]; + + children[name] = children[cloneName]; + customElementsMap[name] = cloneName; + + // If it's not marked as inline then add it to valid block elements + if (!inline) { + blockElementsMap[name.toUpperCase()] = {}; + blockElementsMap[name] = {}; + } + + // Add elements clone if needed + if (!elements[name]) { + elements[name] = elements[cloneName]; + } + + // Add custom elements at span/div positions + each(children, function(element) { + 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; + }); + + // Remove these if they have no attributes + each(split('span'), function(name) { + elements[name].removeEmptyAttrs = 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) { + each(explode(settings.invalid_elements), function(item) { + if (elements[item]) { + delete elements[item]; + } + }); + } + + // If the user didn't allow span only allow internal spans + if (!getElementRule('span')) { + addValidElements('span[!data-mce-type|*]'); + } + + /** + * Name/value map object with valid parents and children to those parents. + * + * @example + * children = { + * div:{p:{}, h1:{}} + * }; + * @field children + * @type {Object} + */ + self.children = children; + + /** + * Name/value map object with valid styles for each element. + * + * @field styles + * @type {Object} + */ + self.styles = validStyles; + + /** + * Returns a map with boolean attributes. + * + * @method getBoolAttrs + * @return {Object} Name/value lookup map for boolean attributes. + */ + self.getBoolAttrs = function() { + return boolAttrMap; + }; + + /** + * Returns a map with block elements. + * + * @method getBlockElements + * @return {Object} Name/value lookup map for block elements. + */ + self.getBlockElements = function() { + return blockElementsMap; + }; + + /** + * Returns a map with text block elements. Such as: p,h1-h6,div,address + * + * @method getTextBlockElements + * @return {Object} Name/value lookup map for block elements. + */ + self.getTextBlockElements = function() { + return textBlockElementsMap; + }; + + /** + * Returns a map with short ended elements such as BR or IMG. + * + * @method getShortEndedElements + * @return {Object} Name/value lookup map for short ended elements. + */ + self.getShortEndedElements = function() { + return shortEndedElementsMap; + }; + + /** + * Returns a map with self closing tags such as
  • . + * + * @method getSelfClosingElements + * @return {Object} Name/value lookup map for self closing tags elements. + */ + self.getSelfClosingElements = function() { + return selfClosingElementsMap; + }; + + /** + * Returns a map with elements that should be treated as contents regardless if it has text + * content in them or not such as TD, VIDEO or IMG. + * + * @method getNonEmptyElements + * @return {Object} Name/value lookup map for non empty elements. + */ + self.getNonEmptyElements = function() { + return nonEmptyElementsMap; + }; + + /** + * Returns a map with elements where white space is to be preserved like PRE or SCRIPT. + * + * @method getWhiteSpaceElements + * @return {Object} Name/value lookup map for white space elements. + */ + self.getWhiteSpaceElements = function() { + return whiteSpaceElementsMap; + }; + + /** + * Returns a map with special elements. These are elements that needs to be parsed + * in a special way such as script, style, textarea etc. The map object values + * are regexps used to find the end of the element. + * + * @method getSpecialElements + * @return {Object} Name/value lookup map for special elements. + */ + self.getSpecialElements = function() { + return specialElements; + }; + + /** + * Returns true/false if the specified element and it's child is valid or not + * according to the schema. + * + * @method isValidChild + * @param {String} name Element name to check for. + * @param {String} child Element child to verify. + * @return {Boolean} True/false if the element is a valid child of the specified parent. + */ + self.isValidChild = function(name, child) { + var parent = children[name]; + + return !!(parent && parent[child]); + }; + + /** + * Returns true/false if the specified element name and optional attribute is + * valid according to the schema. + * + * @method isValid + * @param {String} name Name of element to check. + * @param {String} attr Optional attribute name to check for. + * @return {Boolean} True/false if the element and attribute is valid. + */ + self.isValid = function(name, attr) { + var attrPatterns, i, rule = getElementRule(name); + + // Check if it's a valid element + if (rule) { + if (attr) { + // Check if attribute name exists + if (rule.attributes[attr]) { + return true; + } + + // Check if attribute matches a regexp pattern + attrPatterns = rule.attributePatterns; + if (attrPatterns) { + i = attrPatterns.length; + while (i--) { + if (attrPatterns[i].pattern.test(name)) { + return true; + } + } + } + } else { + return true; + } + } + + // No match + return false; + }; + + /** + * Returns true/false if the specified element is valid or not + * according to the schema. + * + * @method getElementRule + * @param {String} name Element name to check for. + * @return {Object} Element object or undefined if the element isn't valid. + */ + self.getElementRule = getElementRule; + + /** + * Returns an map object of all custom elements. + * + * @method getCustomElements + * @return {Object} Name/value map object of all custom elements. + */ + self.getCustomElements = function() { + return customElementsMap; + }; + + /** + * Parses a valid elements string and adds it to the schema. The valid elements + format is for example "element[attr=default|otherattr]". + * Existing rules will be replaced with the ones specified, so this extends the schema. + * + * @method addValidElements + * @param {String} valid_elements String in the valid elements format to be parsed. + */ + self.addValidElements = addValidElements; + + /** + * Parses a valid elements string and sets it to the schema. The valid elements + * format is for example "element[attr=default|otherattr]". + * Existing rules will be replaced with the ones specified, so this extends the schema. + * + * @method setValidElements + * @param {String} valid_elements String in the valid elements format to be parsed. + */ + self.setValidElements = setValidElements; + + /** + * Adds custom non HTML elements to the schema. + * + * @method addCustomElements + * @param {String} custom_elements Comma separated list of custom elements to add. + */ + self.addCustomElements = addCustomElements; + + /** + * Parses a valid children string and adds them to the schema structure. The valid children + * format is for example: "element[child1|child2]". + * + * @method addValidChildren + * @param {String} valid_children Valid children elements string to parse + */ + self.addValidChildren = addValidChildren; + + self.elements = elements; + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/html/Serializer.js b/lib/tinymce/jscripts/tinymce4/classes/html/Serializer.js new file mode 100644 index 00000000..041272af --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/html/Serializer.js @@ -0,0 +1,156 @@ +/** + * Serializer.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is used to serialize down the DOM tree into a string using a Writer instance. + * + * + * @example + * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('

    text

    ')); + * @class tinymce.html.Serializer + * @version 3.4 + */ +define("tinymce/html/Serializer", [ + "tinymce/html/Writer", + "tinymce/html/Schema" +], function(Writer, Schema) { + /** + * Constructs a new Serializer instance. + * + * @constructor + * @method Serializer + * @param {Object} settings Name/value settings object. + * @param {tinymce.html.Schema} schema Schema instance to use. + */ + return function(settings, schema) { + var self = this, writer = new Writer(settings); + + settings = settings || {}; + settings.validate = "validate" in settings ? settings.validate : true; + + self.schema = schema = schema || new Schema(); + self.writer = writer; + + /** + * Serializes the specified node into a string. + * + * @example + * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('

    text

    ')); + * @method serialize + * @param {tinymce.html.Node} node Node instance to serialize. + * @return {String} String with HTML based on DOM tree. + */ + self.serialize = function(node) { + var handlers, validate; + + validate = settings.validate; + + handlers = { + // #text + 3: function(node) { + 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(); + }; + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/html/Styles.js b/lib/tinymce/jscripts/tinymce4/classes/html/Styles.js new file mode 100644 index 00000000..1d869ff2 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/html/Styles.js @@ -0,0 +1,297 @@ +/** + * Styles.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is used to parse CSS styles it also compresses styles to reduce the output size. + * + * @example + * var Styles = new tinymce.html.Styles({ + * url_converter: function(url) { + * return url; + * } + * }); + * + * styles = Styles.parse('border: 1px solid red'); + * styles.color = 'red'; + * + * console.log(new tinymce.html.StyleSerializer().serialize(styles)); + * + * @class tinymce.html.Styles + * @version 3.4 + */ +define("tinymce/html/Styles", [], function() { + return function(settings, schema) { + /*jshint maxlen:255 */ + 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+$/, + undef, i, encodingLookup = {}, encodingItems, invisibleChar = '\uFEFF'; + + settings = settings || {}; + + encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' '); + for (i = 0; i < encodingItems.length; i++) { + encodingLookup[encodingItems[i]] = invisibleChar + i; + encodingLookup[invisibleChar + i] = encodingItems[i]; + } + + function toHex(match, r, g, b) { + function hex(val) { + val = parseInt(val, 10).toString(16); + + return val.length > 1 ? val : '0' + val; // 0 -> 00 + } + + return '#' + hex(r) + hex(g) + hex(b); + } + + return { + /** + * Parses the specified RGB color value and returns a hex version of that color. + * + * @method toHex + * @param {String} color RGB string value like rgb(1,2,3) + * @return {String} Hex version of that RGB value like #FF00FF. + */ + toHex: function(color) { + return color.replace(rgbRegExp, toHex); + }, + + /** + * Parses the specified style value into an object collection. This parser will also + * merge and remove any redundant items that browsers might have added. It will also convert non hex + * colors to hex values. Urls inside the styles will also be converted to absolute/relative based on settings. + * + * @method parse + * @param {String} css Style value to parse for example: border:1px solid red;. + * @return {Object} Object representation of that style like {border: '1px solid red'} + */ + 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]; + } + + /** + * Checks if the specific style can be compressed in other words if all border-width are equal. + */ + 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; + } + + /** + * Compresses multiple styles into one style. + */ + 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 _ + function encode(str) { + isEncoded = true; + + return encodingLookup[str]; + } + + // Decodes the specified string by replacing all _ 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; + }, + + /** + * Serializes the specified style object into a string. + * + * @method serialize + * @param {Object} styles Object to serialize as string for example: {border: '1px solid red'} + * @param {String} element_name Optional element name, if specified only the styles that matches the schema will be serialized. + * @return {String} String representation of the style object for example: border: 1px solid red. + */ + 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; + } + }; + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/html/Writer.js b/lib/tinymce/jscripts/tinymce4/classes/html/Writer.js new file mode 100644 index 00000000..0f9eaaef --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/html/Writer.js @@ -0,0 +1,199 @@ +/** + * Writer.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is used to write HTML tags out it can be used with the Serializer or the SaxParser. + * + * @class tinymce.html.Writer + * @example + * var writer = new tinymce.html.Writer({indent: true}); + * var parser = new tinymce.html.SaxParser(writer).parse('


    '); + * console.log(writer.getContent()); + * + * @class tinymce.html.Writer + * @version 3.4 + */ +define("tinymce/html/Writer", [ + "tinymce/html/Entities", + "tinymce/util/Tools" +], function(Entities, Tools) { + var makeMap = Tools.makeMap; + + /** + * Constructs a new Writer instance. + * + * @constructor + * @method Writer + * @param {Object} settings Name/value settings object. + */ + return function(settings) { + var html = [], indent, indentBefore, indentAfter, encode, htmlOutput; + + settings = settings || {}; + indent = settings.indent; + indentBefore = makeMap(settings.indent_before || ''); + indentAfter = makeMap(settings.indent_after || ''); + encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities); + htmlOutput = settings.element_format == "html"; + + return { + /** + * Writes the a start element such as

    . + * + * @method start + * @param {String} name Name of the element. + * @param {Array} attrs Optional attribute array or undefined if it hasn't any. + * @param {Boolean} empty Optional empty state if the tag should end like
    . + */ + 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'); + } + } + }, + + /** + * Writes the a end element such as

    . + * + * @method end + * @param {String} name Name of the element. + */ + 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(''); + + if (indent && indentAfter[name] && html.length > 0) { + value = html[html.length - 1]; + + if (value.length > 0 && value !== '\n') { + html.push('\n'); + } + } + }, + + /** + * Writes a text node. + * + * @method text + * @param {String} text String to write out. + * @param {Boolean} raw Optional raw state if true the contents wont get encoded. + */ + text: function(text, raw) { + if (text.length > 0) { + html[html.length] = raw ? text : encode(text); + } + }, + + /** + * Writes a cdata node such as . + * + * @method cdata + * @param {String} text String to write out inside the cdata. + */ + cdata: function(text) { + html.push(''); + }, + + /** + * Writes a comment node such as . + * + * @method cdata + * @param {String} text String to write out inside the comment. + */ + comment: function(text) { + html.push(''); + }, + + /** + * Writes a PI node such as . + * + * @method pi + * @param {String} name Name of the pi. + * @param {String} text String to write out inside the pi. + */ + pi: function(name, text) { + if (text) { + html.push(''); + } else { + html.push(''); + } + + if (indent) { + html.push('\n'); + } + }, + + /** + * Writes a doctype node such as . + * + * @method doctype + * @param {String} text String to write out inside the doctype. + */ + doctype: function(text) { + html.push('', indent ? '\n' : ''); + }, + + /** + * Resets the internal buffer if one wants to reuse the writer. + * + * @method reset + */ + reset: function() { + html.length = 0; + }, + + /** + * Returns the contents that got serialized. + * + * @method getContent + * @return {String} HTML contents that got written down. + */ + getContent: function() { + return html.join('').replace(/\n$/, ''); + } + }; + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/jquery.tinymce.js b/lib/tinymce/jscripts/tinymce4/classes/jquery.tinymce.js new file mode 100644 index 00000000..df983279 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/jquery.tinymce.js @@ -0,0 +1,357 @@ +/** + * jquery.tinymce.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true, jQuery */ + +(function($) { + var undef, + lazyLoading, + delayedInits = [], + win = window; + + $.fn.tinymce = function(settings) { + var self = this, url, base, lang, suffix = ""; + + // No match then just ignore the call + if (!self.length) { + return self; + } + + // Get editor instance + if (!settings) { + return tinymce.get(self[0].id); + } + + self.css('visibility', 'hidden'); // Hide textarea to avoid flicker + + function init() { + var editors = [], initCount = 0; + + // Apply patches to the jQuery object, only once + if (applyPatch) { + applyPatch(); + applyPatch = null; + } + + // Create an editor instance for each matched node + self.each(function(i, node) { + var ed, id = node.id, oninit = settings.oninit; + + // Generate unique id for target element if needed + if (!id) { + node.id = id = tinymce.DOM.uniqueId(); + } + + // Create editor instance and render it + ed = new tinymce.Editor(id, settings, tinymce.EditorManager); + editors.push(ed); + + ed.on('init', function() { + var scope, func = oninit; + + self.css('visibility', ''); + + // Run this if the oninit setting is defined + // this logic will fire the oninit callback ones each + // matched editor instance is initialized + if (oninit) { + // Fire the oninit event ones each editor instance is initialized + if (++initCount == editors.length) { + if (typeof(func) === "string") { + scope = (func.indexOf(".") === -1) ? null : tinymce.resolve(func.replace(/\.\w+$/, "")); + func = tinymce.resolve(func); + } + + // Call the oninit function with the object + func.apply(scope || tinymce, editors); + } + } + }); + }); + + // Render the editor instances in a separate loop since we + // need to have the full editors array used in the onInit calls + $.each(editors, function(i, ed) { + ed.render(); + }); + } + + // Load TinyMCE on demand, if we need to + if (!win.tinymce && !lazyLoading && (url = settings.script_url)) { + lazyLoading = 1; + base = url.substring(0, url.lastIndexOf("/")); + + // Check if it's a dev/src version they want to load then + // make sure that all plugins, themes etc are loaded in source mode aswell + if (url.indexOf('.min') != -1) { + suffix = ".min"; + } + + // Setup tinyMCEPreInit object this will later be used by the TinyMCE + // core script to locate other resources like CSS files, dialogs etc + // You can also predefined a tinyMCEPreInit object and then it will use that instead + win.tinymce = win.tinyMCEPreInit || { + base: base, + suffix: suffix + }; + + // url contains gzip then we assume it's a compressor + if (url.indexOf('gzip') != -1) { + lang = settings.language || "en"; + url = url + (/\?/.test(url) ? '&' : '?') + "js=true&core=true&suffix=" + escape(suffix) + + "&themes=" + escape(settings.theme) + "&plugins=" + escape(settings.plugins) + "&languages=" + lang; + + // Check if compressor script is already loaded otherwise setup a basic one + if (!win.tinyMCE_GZ) { + win.tinyMCE_GZ = { + start: function() { + function load(url) { + tinymce.ScriptLoader.markDone(tinymce.baseURI.toAbsolute(url)); + } + + // Add core languages + load("langs/" + lang + ".js"); + + // Add themes with languages + load("themes/" + settings.theme + "/theme" + suffix + ".js"); + load("themes/" + settings.theme + "/langs/" + lang + ".js"); + + // Add plugins with languages + $.each(settings.plugins.split(","), function(i, name) { + if (name) { + load("plugins/" + name + "/plugin" + suffix + ".js"); + load("plugins/" + name + "/langs/" + lang + ".js"); + } + }); + }, + + end: function() { + } + }; + } + } + + var script = document.createElement('script'); + script.type = 'text/javascript'; + script.onload = script.onreadystatechange = function(e) { + e = e || event; + + if (e.type == 'load' || /complete|loaded/.test(script.readyState)) { + tinymce.dom.Event.domLoaded = 1; + lazyLoading = 2; + + // Execute callback after mainscript has been loaded and before the initialization occurs + if (settings.script_loaded) { + settings.script_loaded(); + } + + init(); + + $.each(delayedInits, function(i, init) { + init(); + }); + } + }; + script.src = url; + document.body.appendChild(script); + } else { + // Delay the init call until tinymce is loaded + if (lazyLoading === 1) { + delayedInits.push(init); + } else { + init(); + } + } + + return self; + }; + + // Add :tinymce psuedo selector this will select elements that has been converted into editor instances + // it's now possible to use things like $('*:tinymce') to get all TinyMCE bound elements. + $.extend($.expr[":"], { + tinymce: function(e) { + return !!(e.id && "tinymce" in window && tinymce.get(e.id)); + } + }); + + // This function patches internal jQuery functions so that if + // you for example remove an div element containing an editor it's + // automatically destroyed by the TinyMCE API + function applyPatch() { + // Removes any child editor instances by looking for editor wrapper elements + function removeEditors(name) { + // If the function is remove + if (name === "remove") { + this.each(function(i, node) { + var ed = tinyMCEInstance(node); + + if (ed) { + ed.remove(); + } + }); + } + + this.find("span.mceEditor,div.mceEditor").each(function(i, node) { + var ed = tinymce.get(node.id.replace(/_parent$/, "")); + + if (ed) { + ed.remove(); + } + }); + } + + // Loads or saves contents from/to textarea if the value + // argument is defined it will set the TinyMCE internal contents + function loadOrSave(value) { + var self = this, ed; + + // Handle set value + if (value !== undef) { + removeEditors.call(self); + + // Saves the contents before get/set value of textarea/div + self.each(function(i, node) { + var ed; + + if ((ed = tinymce.get(node.id))) { + ed.setContent(value); + } + }); + } else if (self.length > 0) { + // Handle get value + if ((ed = tinymce.get(self[0].id))) { + return ed.getContent(); + } + } + } + + // Returns tinymce instance for the specified element or null if it wasn't found + function tinyMCEInstance(element) { + var ed = null; + + if (element && element.id && win.tinymce) { + ed = tinymce.get(element.id); + } + + return ed; + } + + // Checks if the specified set contains tinymce instances + function containsTinyMCE(matchedSet) { + return !!((matchedSet) && (matchedSet.length) && (win.tinymce) && (matchedSet.is(":tinymce"))); + } + + // Patch various jQuery functions + var jQueryFn = {}; + + // Patch some setter/getter functions these will + // now be able to set/get the contents of editor instances for + // example $('#editorid').html('Content'); will update the TinyMCE iframe instance + $.each(["text", "html", "val"], function(i, name) { + var origFn = jQueryFn[name] = $.fn[name], + textProc = (name === "text"); + + $.fn[name] = function(value) { + var self = this; + + if (!containsTinyMCE(self)) { + return origFn.apply(self, arguments); + } + + if (value !== undef) { + loadOrSave.call(self.filter(":tinymce"), value); + origFn.apply(self.not(":tinymce"), arguments); + + return self; // return original set for chaining + } else { + var ret = ""; + var args = arguments; + + (textProc ? self : self.eq(0)).each(function(i, node) { + var ed = tinyMCEInstance(node); + + if (ed) { + ret += textProc ? ed.getContent().replace(/<(?:"[^"]*"|'[^']*'|[^'">])*>/g, "") : ed.getContent({save: true}); + } else { + ret += origFn.apply($(node), args); + } + }); + + return ret; + } + }; + }); + + // Makes it possible to use $('#id').append("content"); to append contents to the TinyMCE editor iframe + $.each(["append", "prepend"], function(i, name) { + var origFn = jQueryFn[name] = $.fn[name], + prepend = (name === "prepend"); + + $.fn[name] = function(value) { + var self = this; + + if (!containsTinyMCE(self)) { + return origFn.apply(self, arguments); + } + + if (value !== undef) { + self.filter(":tinymce").each(function(i, node) { + var ed = tinyMCEInstance(node); + + if (ed) { + ed.setContent(prepend ? value + ed.getContent() : ed.getContent() + value); + } + }); + + origFn.apply(self.not(":tinymce"), arguments); + + return self; // return original set for chaining + } + }; + }); + + // Makes sure that the editor instance gets properly destroyed when the parent element is removed + $.each(["remove", "replaceWith", "replaceAll", "empty"], function(i, name) { + var origFn = jQueryFn[name] = $.fn[name]; + + $.fn[name] = function() { + removeEditors.call(this, name); + + return origFn.apply(this, arguments); + }; + }); + + jQueryFn.attr = $.fn.attr; + + // Makes sure that $('#tinymce_id').attr('value') gets the editors current HTML contents + $.fn.attr = function(name, value) { + var self = this, args = arguments; + + if ((!name) || (name !== "value") || (!containsTinyMCE(self))) { + if (value !== undef) { + return jQueryFn.attr.apply(self, args); + } else { + return jQueryFn.attr.apply(self, args); + } + } + + if (value !== undef) { + loadOrSave.call(self.filter(":tinymce"), value); + jQueryFn.attr.apply(self.not(":tinymce"), args); + + return self; // return original set for chaining + } else { + var node = self[0], ed = tinyMCEInstance(node); + + return ed ? ed.getContent({save: true}) : jQueryFn.attr.apply($(node), args); + } + }; + } +})(jQuery); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/AbsoluteLayout.js b/lib/tinymce/jscripts/tinymce4/classes/ui/AbsoluteLayout.js new file mode 100644 index 00000000..efe9b35d --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/AbsoluteLayout.js @@ -0,0 +1,46 @@ +/** + * AbsoluteLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less AbsoluteLayout.less + * @class tinymce.ui.AbsoluteLayout + * @extends tinymce.ui.Layout + */ +define("tinymce/ui/AbsoluteLayout", [ + "tinymce/ui/Layout" +], function(Layout) { + "use strict"; + + return Layout.extend({ + Defaults: { + containerClass: 'abs-layout', + controlClass: 'abs-layout-item' + }, + + recalc: function(container) { + container.items().filter(':visible').each(function(ctrl) { + var settings = ctrl.settings; + + ctrl.layoutRect({ + x: settings.x, + y: settings.y, + w: settings.w, + h: settings.h + }); + + if (ctrl.recalc) { + ctrl.recalc(); + } + }); + }, + + renderHtml: function(container) { + return '
    ' + this._super(container); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Button.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Button.js new file mode 100644 index 00000000..70c8ef26 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Button.js @@ -0,0 +1,67 @@ +/** + * Button.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Button.less + * @class tinymce.ui.Button + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Button", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + Defaults: { + classes: "widget btn", + role: "button" + }, + + init: function(settings) { + var self = this, size; + + self.on('click mousedown', function(e) { + e.preventDefault(); + }); + + self._super(settings); + size = settings.size; + + if (settings.subtype) { + self.addClass(settings.subtype); + } + + if (size) { + self.addClass('btn-' + size); + } + }, + + repaint: function() { + var btnStyle = this.getEl().firstChild.style; + + btnStyle.width = btnStyle.height = "100%"; + + this._super(); + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; + var image = self.settings.image ? ' style="background-image: url(\'' + self.settings.image + '\')"' : ''; + + return ( + '
    ' + + '' + + '
    ' + ); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/ButtonGroup.js b/lib/tinymce/jscripts/tinymce4/classes/ui/ButtonGroup.js new file mode 100644 index 00000000..5a435bde --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/ButtonGroup.js @@ -0,0 +1,41 @@ +/** + * ButtonGroup.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ButtonGroup.less + * @class tinymce.ui.ButtonGroup + * @extends tinymce.ui.Container + */ +define("tinymce/ui/ButtonGroup", [ + "tinymce/ui/Container" +], function(Container) { + "use strict"; + + return Container.extend({ + Defaults: { + defaultType: 'button', + role: 'toolbar' + }, + + renderHtml: function() { + var self = this, layout = self._layout; + + self.addClass('btn-group'); + self.preRender(); + layout.preRender(self); + + return ( + '
    '+ + '
    '+ + (self.settings.html || '') + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Checkbox.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Checkbox.js new file mode 100644 index 00000000..be0682b7 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Checkbox.js @@ -0,0 +1,80 @@ +/** + * Checkbox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Checkbox.less + * @class tinymce.ui.Checkbox + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/Checkbox", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + Defaults: { + classes: "checkbox", + role: "checkbox", + checked: false + }, + + init: function(settings) { + var self = this; + + self._super(settings); + + self.on('click mousedown', function(e) { + e.preventDefault(); + }); + + self.on('click', function(e) { + e.preventDefault(); + + if (!self.disabled()) { + self.checked(!self.checked()); + } + }); + + self.checked(self.settings.checked); + }, + + checked: function(state) { + var self = this; + + if (typeof state != "undefined") { + if (state) { + self.addClass('checked'); + } else { + self.removeClass('checked'); + } + + self._checked = state; + self.aria('checked', state); + + return self; + } + + return self._checked; + }, + + value: function(state) { + return this.checked(state); + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + + return ( + '
    ' + + '' + + '' + self._text + '' + + '
    ' + ); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/CheckboxGroup.js b/lib/tinymce/jscripts/tinymce4/classes/ui/CheckboxGroup.js new file mode 100644 index 00000000..8a77e8f9 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/CheckboxGroup.js @@ -0,0 +1,19 @@ +/** + * CheckboxGroup.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.CheckboxGroup + * @extends tinymce.ui.Container + */ +define("tinymce/ui/CheckboxGroup", [ + "tinymce/ui/Container" +], function(Container) { + "use strict"; + + return Container.extend({}); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Collection.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Collection.js new file mode 100644 index 00000000..da293806 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Collection.js @@ -0,0 +1,407 @@ +/** + * Collection.js + * + * Copyright 2003-2013, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Control collection, this class contains control instances and it + * enables you to perform actions on all the contained items. This is very similar to how jQuery works. + * + * @class tinymce.ui.Collection + */ +define("tinymce/ui/Collection", [ + "tinymce/util/Tools", + "tinymce/ui/Selector", + "tinymce/util/Class" +], function(Tools, Selector, Class) { + "use strict"; + + var Collection, proto, push = Array.prototype.push, slice = Array.prototype.slice; + + proto = { + /** + * Current number of contained control instances. + * + * @field length + * @type Number + */ + length: 0, + + /** + * Constructor for the collection. + * + * @constructor + * @method init + * @param {Array} items Optional array with items to add. + */ + init: function(items) { + if (items) { + this.add(items); + } + }, + + /** + * Adds new items to the control collection. + * + * @method add + * @param {Array} items Array if items to add to collection. + * @return {tinymce.ui.Collection} Current collection instance. + */ + add: function(items) { + var self = this; + + // Force single item into array + if (!Tools.isArray(items)) { + if (items instanceof Collection) { + self.add(items.toArray()); + } else { + push.call(self, items); + } + } else { + push.apply(self, items); + } + + return self; + }, + + /** + * Sets the contents of the collection. This will remove any existing items + * and replace them with the ones specified in the input array. + * + * @method set + * @param {Array} items Array with items to set into the Collection. + * @return {tinymce.ui.Collection} + */ + set: function(items) { + var self = this, len = self.length, i; + + self.length = 0; + self.add(items); + + // Remove old entries + for (i = self.length; i < len; i++) { + delete self[i]; + } + + return self; + }, + + /** + * Filters the collection item based on the specified selector expression or selector function. + * + * @method filter + * @param {String} selector Selector expression to filter items by. + * @return {tinymce.ui.Collection} Collection containing the filtered items. + */ + filter: function(selector) { + var self = this, i, l, matches = [], item, match; + + // Compile string into selector expression + if (typeof(selector) === "string") { + selector = new Selector(selector); + + match = function(item) { + return selector.match(item); + }; + } else { + // Use selector as matching function + match = selector; + } + + for (i = 0, l = self.length; i < l; i++) { + item = self[i]; + + if (match(item)) { + matches.push(item); + } + } + + return new Collection(matches); + }, + + /** + * Slices the items within the collection. + * + * @method slice + * @param {Number} index Index to slice at. + * @param {Number} len Optional length to slice. + * @return {tinymce.ui.Collection} Current collection. + */ + slice: function() { + return new Collection(slice.apply(this, arguments)); + }, + + /** + * Makes the current collection equal to the specified index. + * + * @method eq + * @param {Number} index Index of the item to set the collection to. + * @return {tinymce.ui.Collection} Current collection. + */ + eq: function(index) { + return index === -1 ? this.slice(index) : this.slice(index, +index + 1); + }, + + /** + * Executes the specified callback on each item in collection. + * + * @method each + * @param {function} callback Callback to execute for each item in collection. + * @return {tinymce.ui.Collection} Current collection instance. + */ + each: function(callback) { + Tools.each(this, callback); + + return this; + }, + + /** + * Returns an JavaScript array object of the contents inside the collection. + * + * @method toArray + * @return {Array} Array with all items from collection. + */ + toArray: function() { + return Tools.toArray(this); + }, + + /** + * Finds the index of the specified control or return -1 if it isn't in the collection. + * + * @method indexOf + * @param {Control} ctrl Control instance to look for. + * @return {Number} Index of the specified control or -1. + */ + indexOf: function(ctrl) { + var self = this, i = self.length; + + while (i--) { + if (self[i] === ctrl) { + break; + } + } + + return i; + }, + + /** + * Returns a new collection of the contents in reverse order. + * + * @method reverse + * @return {tinymce.ui.Collection} Collection instance with reversed items. + */ + reverse: function() { + return new Collection(Tools.toArray(this).reverse()); + }, + + /** + * Returns true/false if the class exists or not. + * + * @method hasClass + * @param {String} cls Class to check for. + * @return {Boolean} true/false state if the class exists or not. + */ + hasClass: function(cls) { + return this[0] ? this[0].hasClass(cls) : false; + }, + + /** + * Sets/gets the specific property on the items in the collection. The same as executing control.(); + * + * @method prop + * @param {String} name Property name to get/set. + * @param {Object} value Optional object value to set. + * @return {tinymce.ui.Collection} Current collection instance or value of the first item on a get operation. + */ + prop: function(name, value) { + var self = this, undef, item; + + if (value !== undef) { + self.each(function(item) { + if (item[name]) { + item[name](value); + } + }); + + return self; + } + + item = self[0]; + + if (item && item[name]) { + return item[name](); + } + }, + + /** + * Executes the specific function name with optional arguments an all items in collection if it exists. + * + * @example collection.exec("myMethod", arg1, arg2, arg3); + * @method exec + * @param {String} name Name of the function to execute. + * @param {Object} ... Multiple arguments to pass to each function. + * @return {tinymce.ui.Collection} Current collection. + */ + exec: function(name) { + var self = this, args = Tools.toArray(arguments).slice(1); + + self.each(function(item) { + if (item[name]) { + item[name].apply(item, args); + } + }); + + return self; + } + + /** + * Fires the specified event by name and arguments on the control. This will execute all + * bound event handlers. + * + * @method fire + * @param {String} name Name of the event to fire. + * @param {Object} args Optional arguments to pass to the event. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // fire: function(event, args) {}, -- Generated by code below + + /** + * Binds a callback to the specified event. This event can both be + * native browser events like "click" or custom ones like PostRender. + * + * The callback function will have two parameters the first one being the control that recieved the event + * the second one will be the event object either the browsers native event object or a custom JS object. + * + * @method on + * @param {String} name Name of the event to bind. For example "click". + * @param {String/function} callback Callback function to execute ones the event occurs. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // on: function(name, callback) {}, -- Generated by code below + + /** + * Unbinds the specified event and optionally a specific callback. If you omit the name + * parameter all event handlers will be removed. If you omit the callback all event handles + * by the specified name will be removed. + * + * @method off + * @param {String} name Optional name for the event to unbind. + * @param {function} callback Optional callback function to unbind. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // off: function(name, callback) {}, -- Generated by code below + + /** + * Shows the items in the current collection. + * + * @method show + * @return {tinymce.ui.Collection} Current collection instance. + */ + // show: function() {}, -- Generated by code below + + /** + * Hides the items in the current collection. + * + * @method hide + * @return {tinymce.ui.Collection} Current collection instance. + */ + // hide: function() {}, -- Generated by code below + + /** + * Sets/gets the text contents of the items in the current collection. + * + * @method text + * @return {tinymce.ui.Collection} Current collection instance or text value of the first item on a get operation. + */ + // text: function(value) {}, -- Generated by code below + + /** + * Sets/gets the name contents of the items in the current collection. + * + * @method name + * @return {tinymce.ui.Collection} Current collection instance or name value of the first item on a get operation. + */ + // name: function(value) {}, -- Generated by code below + + /** + * Sets/gets the disabled state on the items in the current collection. + * + * @method disabled + * @return {tinymce.ui.Collection} Current collection instance or disabled state of the first item on a get operation. + */ + // disabled: function(state) {}, -- Generated by code below + + /** + * Sets/gets the active state on the items in the current collection. + * + * @method active + * @return {tinymce.ui.Collection} Current collection instance or active state of the first item on a get operation. + */ + // active: function(state) {}, -- Generated by code below + + /** + * Sets/gets the selected state on the items in the current collection. + * + * @method selected + * @return {tinymce.ui.Collection} Current collection instance or selected state of the first item on a get operation. + */ + // selected: function(state) {}, -- Generated by code below + + /** + * Sets/gets the selected state on the items in the current collection. + * + * @method visible + * @return {tinymce.ui.Collection} Current collection instance or visible state of the first item on a get operation. + */ + // visible: function(state) {}, -- Generated by code below + + /** + * Adds a class to all items in the collection. + * + * @method addClass + * @param {String} cls Class to add to each item. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // addClass: function(cls) {}, -- Generated by code below + + /** + * Removes the specified class from all items in collection. + * + * @method removeClass + * @param {String} cls Class to remove from each item. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // removeClass: function(cls) {}, -- Generated by code below + }; + + // Extend tinymce.ui.Collection prototype with some generated control specific methods + Tools.each('fire on off show hide addClass removeClass append prepend before after reflow'.split(' '), function(name) { + proto[name] = function() { + var args = Tools.toArray(arguments); + + this.each(function(ctrl) { + if (name in ctrl) { + ctrl[name].apply(ctrl, args); + } + }); + + return this; + }; + }); + + // Extend tinymce.ui.Collection prototype with some property methods + Tools.each('text name width height disabled active selected checked visible parent value data'.split(' '), function(name) { + proto[name] = function(value) { + return this.prop(name, value); + }; + }); + + // Create class based on the new prototype + Collection = Class.extend(proto); + + // Stick Collection into Selector to prevent circual references + Selector.Collection = Collection; + + return Collection; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/ColorButton.js b/lib/tinymce/jscripts/tinymce4/classes/ui/ColorButton.js new file mode 100644 index 00000000..8fd35db6 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/ColorButton.js @@ -0,0 +1,186 @@ +/** + * ColorButton.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ColorButton.less + * @class tinymce.ui.ColorButton + * @extends tinymce.ui.MenuButton + */ +define("tinymce/ui/ColorButton", [ + "tinymce/ui/Button", + "tinymce/ui/FloatPanel", + "tinymce/ui/KeyboardNavigation" +], function(Button, FloatPanel, KeyboardNavigation) { + "use strict"; + + function mapColors() { + var i, colors = [], colorMap; + + colorMap = [ + "000000", "Black", + "993300", "Burnt orange", + "333300", "Dark olive", + "003300", "Dark green", + "003366", "Dark azure", + "000080", "Navy Blue", + "333399", "Indigo", + "333333", "Very dark gray", + "800000", "Maroon", + "FF6600", "Orange", + "808000", "Olive", + "008000", "Green", + "008080", "Teal", + "0000FF", "Blue", + "666699", "Grayish blue", + "808080", "Gray", + "FF0000", "Red", + "FF9900", "Amber", + "99CC00", "Yellow green", + "339966", "Sea green", + "33CCCC", "Turquoise", + "3366FF", "Royal blue", + "800080", "Purple", + "999999", "Medium gray", + "FF00FF", "Magenta", + "FFCC00", "Gold", + "FFFF00", "Yellow", + "00FF00", "Lime", + "00FFFF", "Aqua", + "00CCFF", "Sky blue", + "993366", "Brown", + "C0C0C0", "Silver", + "FF99CC", "Pink", + "FFCC99", "Peach", + "FFFF99", "Light yellow", + "CCFFCC", "Pale green", + "CCFFFF", "Pale cyan", + "99CCFF", "Light sky blue", + "CC99FF", "Plum", + "FFFFFF", "White" + ]; + + for (i = 0; i < colorMap.length; i += 2) { + colors.push({ + text: colorMap[i + 1], + color: colorMap[i] + }); + } + + return colors; + } + + return Button.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('colorbutton'); + self.on('click', function(e) { + if (e.control == self) { + self.showPicker(); + } + }); + self.hasPopup = true; + }, + + showPicker: function() { + var self = this, html = '', size, x, y, prefix = self.classPrefix, colors; + + if (!self.picker) { + colors = mapColors(); + + html = ''; + size = Math.ceil(Math.sqrt(colors.length)); + + for (y = 0; y < 5; y++) { + html += ''; + + for (x = 0; x < 8; x++) { + var color = colors[y * 8 + x]; + + html += ( + '' + ); + } + + html += ''; + } + + html += ''; + + self.picker = new FloatPanel({ + popover: true, + autohide: true, + html: html, + border: 1, + classes: 'colorpicker' + }).parent(self).renderTo(self.getContainerElm()); + + self.picker._hasBody = false; + self.picker.reflow(); + self.picker.parent(self); + self.picker.on('cancel', function(e) { + if (e.control === self.menu) { + self.focus(); + } + }); + self.picker.on('click', function(e) { + var value; + + if ((value = e.target.getAttribute('data-mce-color'))) { + self.picker.hide(); + value = '#' + value; + self.showPreview(value); + self.fire('select', {value: value}); + } + }); + + self.keyboardNavigation = new KeyboardNavigation({ + root: self.picker, + items: self.picker.getEl().getElementsByTagName('div'), + onCancel: function() { + self.picker.hide(); + self.fire('cancel'); + } + }); + } + + self.picker.show(); + self.picker.moveRel(self.getEl(), 'bc-tl'); + self.keyboardNavigation.focusFirst(); + }, + + showPreview: function(color) { + this.getEl('preview').style.backgroundColor = color; + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; + var image = self.settings.image ? ' style="background-image: url(\'' + self.settings.image + '\')"' : ''; + + return ( + '
    ' + + '' + + '
    ' + ); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/ComboBox.js b/lib/tinymce/jscripts/tinymce4/classes/ui/ComboBox.js new file mode 100644 index 00000000..da25b464 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/ComboBox.js @@ -0,0 +1,181 @@ +/** + * ComboBox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ComboBox.less + * @class tinymce.ui.ComboBox + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/ComboBox", [ + "tinymce/ui/Widget", + "tinymce/ui/DomUtils" +], function(Widget, DomUtils) { + "use strict"; + + return Widget.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('combobox'); + + self.on('click', function(e) { + var elm = e.target; + + while (elm) { + if (elm.id && elm.id.indexOf('-open') != -1) { + self.fire('action'); + } + + elm = elm.parentNode; + } + }); + + // TODO: Rework this + self.on('keydown', function(e) { + if (e.target.nodeName == "INPUT" && e.keyCode == 13) { + self.parents().reverse().each(function(ctrl) { + e.preventDefault(); + self.fire('change'); + + if (ctrl.submit) { + ctrl.submit(); + return false; + } + }); + } + }); + + if (settings.placeholder) { + self.addClass('placeholder'); + + self.on('focusin', function() { + if (!self._hasOnChange) { + DomUtils.on(self.getEl('inp'), 'change', function() { + self.fire('change'); + }); + + self._hasOnChange = true; + } + + if (self.hasClass('placeholder')) { + self.getEl('inp').value = ''; + self.removeClass('placeholder'); + } + }); + + self.on('focusout', function() { + if (self.value().length === 0) { + self.getEl('inp').value = settings.placeholder; + self.addClass('placeholder'); + } + }); + } + }, + + value: function(value) { + var self = this; + + if (typeof(value) != "undefined") { + self._value = value; + self.removeClass('placeholder'); + + if (self._rendered) { + self.getEl('inp').value = value; + } + + return self; + } + + if (self._rendered) { + value = self.getEl('inp').value; + + if (value != self.settings.placeholder) { + return value; + } + + return ''; + } + + return self._value; + }, + + repaint: function() { + var self = this, elm = self.getEl(), openElm = self.getEl('open'), rect = self.layoutRect(); + + if (openElm) { + DomUtils.css(elm.firstChild, { + width: rect.w - openElm.offsetWidth - 10 + //lineHeight: (self.layoutRect().h - 2) + 'px' + }); + } else { + DomUtils.css(elm.firstChild, { + width: rect.w - 10 + }); + } + + self._super(); + + return self; + }, + + disabled: function(state) { + var self = this; + + self._super(state); + + if (self._rendered) { + self.getEl().disabled = state; + } + }, + + focus: function() { + this.getEl('inp').focus(); + }, + + postRender: function() { + var self = this; + + DomUtils.on(this.getEl('inp'), 'change', function() { + self.fire('change'); + }); + + return self._super(); + }, + + renderHtml: function() { + var self = this, id = self._id, settings = self.settings, prefix = self.classPrefix; + var value = settings.value || settings.placeholder || ''; + var icon, text, openBtnHtml = ''; + + icon = settings.icon ? prefix + 'ico ' + prefix + 'i-' + settings.icon : ''; + text = self._text; + + if (icon || text) { + openBtnHtml = ( + '
    ' + + '' + + '
    ' + ); + + self.addClass('has-open'); + } + + return ( + '
    ' + + '' + + openBtnHtml + + '
    ' + ); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Container.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Container.js new file mode 100644 index 00000000..48dabde3 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Container.js @@ -0,0 +1,325 @@ +/** + * Container.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Base container control. This will be extended by all controls + * that can have children such as panels etc. + * + * @-x-less Container.less + * @class tinymce.ui.Container + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Container", [ + "tinymce/ui/Control", + "tinymce/ui/Collection", + "tinymce/ui/Selector", + "tinymce/ui/Factory", + "tinymce/util/Tools", + "tinymce/ui/DomUtils" +], function(Control, Collection, Selector, Factory, Tools, DomUtils) { + "use strict"; + + var selectorCache = {}; + + return Control.extend({ + layout: '', + innerClass: 'container-inner', + + /** + * Constructor for the control. + * + * @constructor + * @method init + * @param {Object} settings Settings name/value object. + */ + init: function(settings) { + var self = this; + + self._super(settings); + settings = self.settings; + + self._items = new Collection(); + + self.addClass('container'); + self.addClass('container-body', 'body'); + + if (settings.containerCls) { + self.addClass(settings.containerCls); + } + + self._layout = Factory.create((settings.layout || self.layout) + 'layout'); + + if (self.settings.items) { + self.add(self.settings.items); + } + + // TODO: Fix this! + self._hasBody = true; + }, + + /** + * Returns a collection of child items that the container currently have. + * + * @method items + * @return {tinymce.ui.Collection} Control collection direct child controls. + */ + items: function() { + return this._items; + }, + + /** + * Find child controls by selector. + * + * @method find + * @param {String} selector Selector CSS pattern to find children by. + * @return {tinymce.ui.Collection} Control collection with child controls. + */ + find: function(selector) { + selector = selectorCache[selector] = selectorCache[selector] || new Selector(selector); + + return selector.find(this); + }, + + /** + * Adds one or many items to the current container. This will create instances of + * the object representations if needed. + * + * @method add + * @param {Array/Object/tinymce.ui.Control} items Array or item that will be added to the container. + * @return {tinymce.ui.Collection} Current collection control. + */ + add: function(items) { + var self = this; + + self.items().add(self.create(items)).parent(self); + + return self; + }, + + focus: function() { + var self = this; + + if (self.keyNav) { + self.keyNav.focusFirst(); + } else { + self._super(); + } + + return self; + }, + + replace: function(oldItem, newItem) { + var ctrlElm, items = this.items(), i = items.length; + + // Replace the item in collection + while (i--) { + if (items[i] === oldItem) { + items[i] = newItem; + break; + } + } + + if (i >= 0) { + // Remove new item from DOM + ctrlElm = newItem.getEl(); + if (ctrlElm) { + ctrlElm.parentNode.removeChild(ctrlElm); + } + + // Remove old item from DOM + ctrlElm = oldItem.getEl(); + if (ctrlElm) { + ctrlElm.parentNode.removeChild(ctrlElm); + } + } + + // Adopt the item + newItem.parent(this); + }, + + create: function(items) { + var self = this, settings, ctrlItems = []; + + // Non array structure, then force it into an array + if (!Tools.isArray(items)) { + items = [items]; + } + + // Add default type to each child control + Tools.each(items, function(item) { + if (item !== null) { + // Construct item if needed + if (!(item instanceof Control)) { + // Name only then convert it to an object + if (typeof(item) == "string") { + item = {type: item}; + } + + // Create control instance based on input settings and default settings + settings = Tools.extend({}, self.settings.defaults, item); + item.type = settings.type = settings.type || item.type || self.settings.defaultType || + (settings.defaults ? settings.defaults.type : null); + item = Factory.create(settings); + } + + ctrlItems.push(item); + } + }); + + return ctrlItems; + }, + + renderNew: function() { + var self = this; + + // Render any new items + self.items().each(function(ctrl, index) { + var containerElm, fragment; + + ctrl.parent(self); + + if (!ctrl._rendered) { + containerElm = self.getEl('body'); + fragment = DomUtils.createFragment(ctrl.renderHtml()); + + // Insert or append the item + if (containerElm.hasChildNodes() && index <= containerElm.childNodes.length - 1) { + containerElm.insertBefore(fragment, containerElm.childNodes[index]); + } else { + containerElm.appendChild(fragment); + } + + ctrl.postRender(); + } + }); + + self._layout.applyClasses(self); + self._lastRect = null; + + return self; + }, + + append: function(items) { + return this.add(items).renderNew(); + }, + + prepend: function(items) { + var self = this; + + self.items().set(self.create(items).concat(self.items().toArray())); + + return self.renderNew(); + }, + + insert: function(items, index, before) { + var self = this, curItems, beforeItems, afterItems; + + items = self.create(items); + curItems = self.items(); + + if (!before) { + index += 1; + } + + if (index >= 0 && index < curItems.length) { + beforeItems = curItems.slice(0, index).toArray(); + afterItems = curItems.slice(index).toArray(); + curItems.set(beforeItems.concat(items, afterItems)); + } + + return self.renderNew(); + }, + + preRender: function() { + }, + + renderHtml: function() { + var self = this, layout = self._layout; + + self.preRender(); + layout.preRender(self); + + return ( + '
    ' + + '
    '+ + (self.settings.html || '') + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + }, + + postRender: function() { + var self = this, box; + + self.items().exec('postRender'); + self._super(); + + self._layout.postRender(self); + self._rendered = true; + + if (self.settings.style) { + DomUtils.css(self.getEl(), self.settings.style); + } + + if (self.settings.border) { + box = self.borderBox(); + DomUtils.css(self.getEl(), { + 'border-top-width': box.top, + 'border-right-width': box.right, + 'border-bottom-width': box.bottom, + 'border-left-width': box.left + }); + } + + return self; + }, + + initLayoutRect: function() { + var self = this, layoutRect = self._super(); + + // Recalc container size by asking layout manager + self._layout.recalc(self); + + return layoutRect; + }, + + recalc: function() { + var self = this, rect = self._layoutRect, lastRect = self._lastRect; + + if (!lastRect || lastRect.w != rect.w || lastRect.h != rect.h) { + self._layout.recalc(self); + rect = self.layoutRect(); + self._lastRect = {x: rect.x, y: rect.y, w: rect.w, h: rect.h}; + return true; + } + }, + + reflow: function() { + var i, items; + + if (this.visible()) { + Control.repaintControls = []; + Control.repaintControls.map = {}; + + items = this.recalc(); + i = Control.repaintControls.length; + + while (i--) { + Control.repaintControls[i].repaint(); + } + + // TODO: Fix me! + if (this.settings.layout !== "flow" && this.settings.layout !== "stack") { + this.repaint(); + } + + Control.repaintControls = []; + } + + return this; + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Control.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Control.js new file mode 100644 index 00000000..bb7ebe97 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Control.js @@ -0,0 +1,1266 @@ +/** + * Control.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * ... + * + * @class tinymce.ui.Control + */ +define("tinymce/ui/Control", [ + "tinymce/util/Class", + "tinymce/util/Tools", + "tinymce/ui/Collection", + "tinymce/ui/DomUtils" +], function(Class, Tools, Collection, DomUtils) { + "use strict"; + + var nativeEvents = Tools.makeMap("focusin focusout scroll click dblclick mousedown mouseup mousemove mouseover" + + " mouseout mouseenter mouseleave wheel keydown keypress keyup contextmenu", " "); + + var elementIdCache = {}; + var hasMouseWheelEventSupport = "onmousewheel" in document; + var hasWheelEventSupport = false; + + /** + * Base control. All controls extend this class. + * + * @class tinymce.ui.Control + */ + var Control = Class.extend({ + Statics: { + controlIdLookup: {} + }, + + classPrefix: "mce-", + + getContainerElm: function() { + return document.body; + }, + + getParentCtrl: function(elm) { + var ctrl; + + while (elm) { + ctrl = Control.controlIdLookup[elm.id]; + if (ctrl) { + break; + } + + elm = elm.parentNode; + } + + return ctrl; + }, + + /** + * Constructor for the control. + * + * @constructor + * @method init + * @param {Object} settings Settings name/value object. + */ + init: function(settings) { + var self = this, classes, i; + + self.settings = settings = Tools.extend({}, self.Defaults, settings); + + // Initial states + self._id = DomUtils.id(); + self._text = self._name = ''; + self._width = self._height = 0; + self._aria = {role: settings.role}; + + // Setup classes + classes = settings.classes; + if (classes) { + classes = classes.split(' '); + classes.map = {}; + i = classes.length; + while (i--) { + classes.map[classes[i]] = true; + } + } + + self._classes = classes || []; + self.visible(true); + + // Set some properties + Tools.each('title text width height name classes visible disabled active value'.split(' '), function(name) { + var value = settings[name], undef; + + if (value !== undef) { + self[name](value); + } else if (self['_' + name] === undef) { + self['_' + name] = false; + } + }); + + self.on('click', function() { + if (self.disabled()) { + return false; + } + }); + + if (settings.classes) { + Tools.each(settings.classes.split(' '), function(cls) { + self.addClass(cls); + }); + } + + self.settings = settings; + + self._borderBox = self.parseBox(settings.border); + self._paddingBox = self.parseBox(settings.padding); + self._marginBox = self.parseBox(settings.margin); + + if (settings.hidden) { + self.hide(); + } + }, + + // Will generate getter/setter methods for these properties + Properties: 'parent,title,text,width,height,disabled,active,name,value', + + // Will generate empty dummy functions for these + Methods: 'renderHtml,refresh', + + parseBox: function(value) { + var len, radix = 10; + + if (!value) { + return; + } + + if (typeof(value) === "number") { + value = value || 0; + + return { + top: value, + left: value, + bottom: value, + right: value + }; + } + + value = value.split(' '); + len = value.length; + + if (len === 1) { + value[1] = value[2] = value[3] = value[0]; + } else if (len === 2) { + value[2] = value[0]; + value[3] = value[1]; + } else if (len === 3) { + value[3] = value[1]; + } + + return { + top: parseInt(value[0], radix) || 0, + right: parseInt(value[1], radix) || 0, + bottom: parseInt(value[2], radix) || 0, + left: parseInt(value[3], radix) || 0 + }; + }, + + borderBox: function() { + return this._borderBox; + }, + + paddingBox: function() { + return this._paddingBox; + }, + + marginBox: function() { + return this._marginBox; + }, + + measureBox: function(elm, prefix) { + function getStyle(name) { + var defaultView = document.defaultView; + + if (defaultView) { + // Remove camelcase + name = name.replace(/[A-Z]/g, function(a) { + return '-' + a; + }); + + return defaultView.getComputedStyle(elm, null).getPropertyValue(name); + } + + return elm.currentStyle[name]; + } + + function getSide(name) { + var val = parseInt(getStyle(name), 10); + + return isNaN(val) ? 0 : val; + } + + return { + top: getSide(prefix + "TopWidth"), + right: getSide(prefix + "RightWidth"), + bottom: getSide(prefix + "BottomWidth"), + left: getSide(prefix + "LeftWidth") + }; + }, + + initLayoutRect: function() { + var self = this, settings = self.settings, borderBox, layoutRect; + var elm = self.getEl(), width, height, minWidth, minHeight, autoResize; + var startMinWidth, startMinHeight; + + // Measure boxes + borderBox = self._borderBox = self._borderBox || self.measureBox(elm, 'border'); + self._paddingBox = self._paddingBox || self.measureBox(elm, 'padding'); + self._marginBox = self._marginBox || self.measureBox(elm, 'margin'); + + // Setup minWidth/minHeight and width/height + startMinWidth = settings.minWidth; + startMinHeight = settings.minHeight; + minWidth = startMinWidth || elm.offsetWidth; + minHeight = startMinHeight || elm.offsetHeight; + width = settings.width; + height = settings.height; + autoResize = settings.autoResize; + autoResize = typeof(autoResize) != "undefined" ? autoResize : !width && !height; + + width = width || minWidth; + height = height || minHeight; + + var deltaW = borderBox.left + borderBox.right; + var deltaH = borderBox.top + borderBox.bottom; + + var maxW = settings.maxWidth || 0xFFFF; + var maxH = settings.maxHeight || 0xFFFF; + + // Setup initial layout rect + self._layoutRect = layoutRect = { + x: settings.x || 0, + y: settings.y || 0, + w: width, + h: height, + deltaW: deltaW, + deltaH: deltaH, + contentW: width - deltaW, + contentH: height - deltaH, + innerW: width - deltaW, + innerH: height - deltaH, + startMinWidth: startMinWidth || 0, + startMinHeight: startMinHeight || 0, + minW: Math.min(minWidth, maxW), + minH: Math.min(minHeight, maxH), + maxW: maxW, + maxH: maxH, + autoResize: autoResize, + scrollW: 0 + }; + + self._lastLayoutRect = {}; + + return layoutRect; + }, + + layoutRect: function(newRect) { + var self = this, curRect = self._layoutRect, lastLayoutRect, size, deltaWidth, deltaHeight, undef, repaintControls; + + // Initialize default layout rect + if (!curRect) { + curRect = self.initLayoutRect(); + } + + // Set new rect values + if (newRect) { + // Calc deltas between inner and outer sizes + deltaWidth = curRect.deltaW; + deltaHeight = curRect.deltaH; + + // Set x position + if (newRect.x !== undef) { + curRect.x = newRect.x; + } + + // Set y position + if (newRect.y !== undef) { + curRect.y = newRect.y; + } + + // Set minW + if (newRect.minW !== undef) { + curRect.minW = newRect.minW; + } + + // Set minH + if (newRect.minH !== undef) { + curRect.minH = newRect.minH; + } + + // Set new width and calculate inner width + size = newRect.w; + if (size !== undef) { + size = size < curRect.minW ? curRect.minW : size; + size = size > curRect.maxW ? curRect.maxW : size; + curRect.w = size; + curRect.innerW = size - deltaWidth; + } + + // Set new height and calculate inner height + size = newRect.h; + if (size !== undef) { + size = size < curRect.minH ? curRect.minH : size; + size = size > curRect.maxH ? curRect.maxH : size; + curRect.h = size; + curRect.innerH = size - deltaHeight; + } + + // Set new inner width and calculate width + size = newRect.innerW; + if (size !== undef) { + size = size < curRect.minW - deltaWidth ? curRect.minW - deltaWidth : size; + size = size > curRect.maxW - deltaWidth ? curRect.maxW - deltaWidth : size; + curRect.innerW = size; + curRect.w = size + deltaWidth; + } + + // Set new height and calculate inner height + size = newRect.innerH; + if (size !== undef) { + size = size < curRect.minH - deltaHeight ? curRect.minH - deltaHeight : size; + size = size > curRect.maxH - deltaHeight ? curRect.maxH - deltaHeight : size; + curRect.innerH = size; + curRect.h = size + deltaHeight; + } + + // Set new contentW + if (newRect.contentW !== undef) { + curRect.contentW = newRect.contentW; + } + + // Set new contentH + if (newRect.contentH !== undef) { + curRect.contentH = newRect.contentH; + } + + // Compare last layout rect with the current one to see if we need to repaint or not + lastLayoutRect = self._lastLayoutRect; + if (lastLayoutRect.x !== curRect.x || lastLayoutRect.y !== curRect.y || + lastLayoutRect.w !== curRect.w || lastLayoutRect.h !== curRect.h) { + repaintControls = Control.repaintControls; + + if (repaintControls) { + if (repaintControls.map && !repaintControls.map[self._id]) { + repaintControls.push(self); + repaintControls.map[self._id] = true; + } + } + + lastLayoutRect.x = curRect.x; + lastLayoutRect.y = curRect.y; + lastLayoutRect.w = curRect.w; + lastLayoutRect.h = curRect.h; + } + + return self; + } + + return curRect; + }, + + repaint: function() { + var self = this, style, bodyStyle, rect, borderBox, borderW = 0, borderH = 0, lastRepaintRect; + + style = self.getEl().style; + rect = self._layoutRect; + lastRepaintRect = self._lastRepaintRect || {}; + + borderBox = self._borderBox; + borderW = borderBox.left + borderBox.right; + borderH = borderBox.top + borderBox.bottom; + + if (rect.x !== lastRepaintRect.x) { + style.left = rect.x + 'px'; + lastRepaintRect.x = rect.x; + } + + if (rect.y !== lastRepaintRect.y) { + style.top = rect.y + 'px'; + lastRepaintRect.y = rect.y; + } + + if (rect.w !== lastRepaintRect.w) { + style.width = (rect.w - borderW) + 'px'; + lastRepaintRect.w = rect.w; + } + + if (rect.h !== lastRepaintRect.h) { + style.height = (rect.h - borderH) + 'px'; + lastRepaintRect.h = rect.h; + } + + // Update body if needed + if (self._hasBody && rect.innerW !== lastRepaintRect.innerW) { + bodyStyle = self.getEl('body').style; + bodyStyle.width = (rect.innerW) + 'px'; + lastRepaintRect.innerW = rect.innerW; + } + + if (self._hasBody && rect.innerH !== lastRepaintRect.innerH) { + bodyStyle = bodyStyle || self.getEl('body').style; + bodyStyle.height = (rect.innerH) + 'px'; + lastRepaintRect.innerH = rect.innerH; + } + + self._lastRepaintRect = lastRepaintRect; + self.fire('repaint', {}, false); + }, + + /** + * Binds a callback to the specified event. This event can both be + * native browser events like "click" or custom ones like PostRender. + * + * The callback function will be passed a DOM event like object that enables yout do stop propagation. + * + * @method on + * @param {String} name Name of the event to bind. For example "click". + * @param {String/function} callback Callback function to execute ones the event occurs. + * @return {tinymce.ui.Control} Current control object. + */ + on: function(name, callback) { + var self = this, bindings, handlers, names, i; + + function resolveCallbackName(name) { + var callback, scope; + + return function(e) { + if (!callback) { + self.parents().each(function(ctrl) { + var callbacks = ctrl.settings.callbacks; + + if (callbacks && (callback = callbacks[name])) { + scope = ctrl; + return false; + } + }); + } + + return callback.call(scope, e); + }; + } + + if (callback) { + if (typeof(callback) == 'string') { + callback = resolveCallbackName(callback); + } + + names = name.toLowerCase().split(' '); + i = names.length; + while (i--) { + name = names[i]; + + bindings = self._bindings; + if (!bindings) { + bindings = self._bindings = {}; + } + + handlers = bindings[name]; + if (!handlers) { + handlers = bindings[name] = []; + } + + handlers.push(callback); + + if (nativeEvents[name]) { + if (!self._nativeEvents) { + self._nativeEvents = {name: true}; + } else { + self._nativeEvents[name] = true; + } + + if (self._rendered) { + self.bindPendingEvents(); + } + } + } + } + + return self; + }, + + /** + * Unbinds the specified event and optionally a specific callback. If you omit the name + * parameter all event handlers will be removed. If you omit the callback all event handles + * by the specified name will be removed. + * + * @method off + * @param {String} name Optional name for the event to unbind. + * @param {function} callback Optional callback function to unbind. + * @return {mxex.ui.Control} Current control object. + */ + off: function(name, callback) { + var self = this, i, bindings = self._bindings, handlers, bindingName, names, hi; + + if (bindings) { + if (name) { + names = name.toLowerCase().split(' '); + i = names.length; + while (i--) { + name = names[i]; + handlers = bindings[name]; + + // Unbind all handlers + if (!name) { + for (bindingName in bindings) { + bindings[bindingName].length = 0; + } + + return self; + } + + if (handlers) { + // Unbind all by name + if (!callback) { + handlers.length = 0; + } else { + // Unbind specific ones + hi = handlers.length; + while (hi--) { + if (handlers[hi] === callback) { + handlers.splice(hi, 1); + } + } + } + } + } + } else { + self._bindings = []; + } + } + + return self; + }, + + /** + * Fires the specified event by name and arguments on the control. This will execute all + * bound event handlers. + * + * @method fire + * @param {String} name Name of the event to fire. + * @param {Object} args Optional arguments to pass to the event. + * @param {Boolean} bubble Optional value to control bubbeling. Defaults to true. + * @return {tinymce.ui.Control} Current control object. + */ + fire: function(name, args, bubble) { + var self = this, i, l, handlers, parentCtrl; + + name = name.toLowerCase(); + + // 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; + } + + // Setup empty object if args is omited + args = args || {}; + + // Stick type into event object + if (!args.type) { + args.type = name; + } + + // Stick control into event + if (!args.control) { + args.control = self; + } + + // Add event delegation methods if they are missing + if (!args.preventDefault) { + // Add preventDefault method + args.preventDefault = function() { + args.isDefaultPrevented = returnTrue; + }; + + // Add stopPropagation + args.stopPropagation = function() { + args.isPropagationStopped = returnTrue; + }; + + // Add stopImmediatePropagation + args.stopImmediatePropagation = function() { + args.isImmediatePropagationStopped = returnTrue; + }; + + // Add event delegation states + args.isDefaultPrevented = returnFalse; + args.isPropagationStopped = returnFalse; + args.isImmediatePropagationStopped = returnFalse; + } + + if (self._bindings) { + handlers = self._bindings[name]; + + if (handlers) { + for (i = 0, l = handlers.length; i < l; i++) { + // Execute callback and break if the callback returns a false + if (!args.isImmediatePropagationStopped() && handlers[i].call(self, args) === false) { + break; + } + } + } + } + + // Bubble event up to parent controls + if (bubble !== false) { + parentCtrl = self.parent(); + while (parentCtrl && !args.isPropagationStopped()) { + parentCtrl.fire(name, args, false); + parentCtrl = parentCtrl.parent(); + } + } + + return args; + }, + + /** + * Returns a control collection with all parent controls. + * + * @method parents + * @param {String} selector Optional selector expression to find parents. + * @return {tinymce.ui.Collection} Collection with all parent controls. + */ + parents: function(selector) { + var ctrl = this, parents = new Collection(); + + // Add each parent to collection + for (ctrl = ctrl.parent(); ctrl; ctrl = ctrl.parent()) { + parents.add(ctrl); + } + + // Filter away everything that doesn't match the selector + if (selector) { + parents = parents.filter(selector); + } + + return parents; + }, + + next: function() { + var parentControls = this.parent().items(); + + return parentControls[parentControls.indexOf(this) + 1]; + }, + + prev: function() { + var parentControls = this.parent().items(); + + return parentControls[parentControls.indexOf(this) - 1]; + }, + + findCommonAncestor: function(ctrl1, ctrl2) { + var parentCtrl; + + while (ctrl1) { + parentCtrl = ctrl2; + + while (parentCtrl && ctrl1 != parentCtrl) { + parentCtrl = parentCtrl.parent(); + } + + if (ctrl1 == parentCtrl) { + break; + } + + ctrl1 = ctrl1.parent(); + } + + return ctrl1; + }, + + /** + * Returns true/false if the specific control has the specific class. + * + * @param {String} cls Class to check for. + * @return {Boolean} True/false if the control has the specified class. + */ + hasClass: function(cls, group) { + var classes = this._classes[group || 'control']; + + cls = this.classPrefix + cls; + + return classes && !!classes.map[cls]; + }, + + /** + * Adds the specified class to the control + * + * @param {String} cls Class to check for. + * @return {tinymce.ui.Control} Current control object. + */ + addClass: function(cls, group) { + var self = this, classes, elm; + + cls = this.classPrefix + cls; + classes = self._classes[group || 'control']; + + if (!classes) { + classes = []; + classes.map = {}; + self._classes[group || 'control'] = classes; + } + + if (!classes.map[cls]) { + classes.map[cls] = cls; + classes.push(cls); + + if (self._rendered) { + elm = self.getEl(group); + + if (elm) { + elm.className = classes.join(' '); + } + } + } + + return self; + }, + + /** + * Removed the specified class from the control. + * + * @param {String} cls Class to remove. + * @return {tinymce.ui.Control} Current control object. + */ + removeClass: function(cls, group) { + var self = this, classes, i, elm; + + cls = this.classPrefix + cls; + classes = self._classes[group || 'control']; + if (classes && classes.map[cls]) { + delete classes.map[cls]; + + i = classes.length; + while (i--) { + if (classes[i] === cls) { + classes.splice(i, 1); + } + } + } + + if (self._rendered) { + elm = self.getEl(group); + + if (elm) { + elm.className = classes.join(' '); + } + } + + return self; + }, + + toggleClass: function(cls, state, group) { + var self = this; + + if (state) { + self.addClass(cls, group); + } else { + self.removeClass(cls, group); + } + + return self; + }, + + classes: function(group) { + var classes = this._classes[group || 'control']; + + return classes ? classes.join(' ') : ''; + }, + + getEl: function(suffix, dropCache) { + var elm, id = suffix ? this._id + '-' + suffix : this._id; + + elm = elementIdCache[id] = (dropCache === true ? null : elementIdCache[id]) || DomUtils.get(id); + + return elm; + }, + + /** + * Sets/gets the visible for the control. + * + * @method visible + * @param {Boolean} state Value to set to control. + * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get. + */ + visible: function(state) { + var self = this, parentCtrl; + + if (typeof(state) !== "undefined") { + if (self._visible !== state) { + if (self._rendered) { + self.getEl().style.display = state ? '' : 'none'; + } + + self._visible = state; + + // Parent container needs to reflow + parentCtrl = self.parent(); + if (parentCtrl) { + parentCtrl._lastRect = null; + } + + self.fire(state ? 'show' : 'hide'); + } + + return self; + } + + return self._visible; + }, + + /** + * Sets the visible state to true. + * + * @return {tinymce.ui.Control} Current control instance. + */ + show: function() { + return this.visible(true); + }, + + /** + * Sets the visible state to false. + * + * @return {tinymce.ui.Control} Current control instance. + */ + hide: function() { + return this.visible(false); + }, + + focus: function() { + this.getEl().focus(); + }, + + blur: function() { + this.getEl().blur(); + }, + + aria: function(name, value) { + var self = this, elm = self.getEl(); + + if (typeof(value) === "undefined") { + return self._aria[name]; + } else { + self._aria[name] = value; + } + + if (self._rendered) { + if (name == 'label') { + elm.setAttribute('aria-labeledby', self._id); + } + + elm.setAttribute(name == 'role' ? name : 'aria-' + name, value); + } + + return self; + }, + + encode: function(text, translate) { + if (translate !== false && Control.translate) { + text = Control.translate(text); + } + + return (text || '').replace(/[&<>"]/g, function(match) { + return '&#' + match.charCodeAt(0) + ';'; + }); + }, + + before: function(items) { + var self = this, parent = self.parent(); + + if (parent) { + parent.insert(items, parent.items().indexOf(self), true); + } + + return self; + }, + + after: function(items) { + var self = this, parent = self.parent(); + + if (parent) { + parent.insert(items, parent.items().indexOf(self)); + } + + return self; + }, + + remove: function() { + var self = this, elm = self.getEl(), parent = self.parent(), newItems; + + if (self.items) { + var controls = self.items().toArray(); + var i = controls.length; + while (i--) { + controls[i].remove(); + } + } + + if (parent && parent.items) { + newItems = []; + + parent.items().each(function(item) { + if (item !== self) { + newItems.push(item); + } + }); + + parent.items().set(newItems); + parent._lastRect = null; + } + + if (self._eventsRoot && self._eventsRoot == self) { + DomUtils.off(elm); + } + + delete Control.controlIdLookup[self._id]; + + if (elm.parentNode) { + elm.parentNode.removeChild(elm); + } + + return self; + }, + + renderBefore: function(elm) { + var self = this; + + elm.parentNode.insertBefore(DomUtils.createFragment(self.renderHtml()), elm); + self.postRender(); + + return self; + }, + + renderTo: function(elm) { + var self = this; + + elm = elm || self.getContainerElm(); + elm.appendChild(DomUtils.createFragment(self.renderHtml())); + self.postRender(); + + return self; + }, + + postRender: function() { + var self = this, settings = self.settings, elm, box, parent, name, parentEventsRoot; + + // Bind on settings + for (name in settings) { + if (name.indexOf("on") === 0) { + self.on(name.substr(2), settings[name]); + } + } + + if (self._eventsRoot) { + for (parent = self.parent(); !parentEventsRoot && parent; parent = parent.parent()) { + parentEventsRoot = parent._eventsRoot; + } + + if (parentEventsRoot) { + for (name in parentEventsRoot._nativeEvents) { + self._nativeEvents[name] = true; + } + } + } + + self.bindPendingEvents(); + + if (settings.style) { + elm = self.getEl(); + if (elm) { + elm.setAttribute('style', settings.style); + elm.style.cssText = settings.style; + } + } + + if (!self._visible) { + DomUtils.css(self.getEl(), 'display', 'none'); + } + + if (self.settings.border) { + box = self.borderBox(); + DomUtils.css(self.getEl(), { + 'border-top-width': box.top, + 'border-right-width': box.right, + 'border-bottom-width': box.bottom, + 'border-left-width': box.left + }); + } + + // Add instance to lookup + Control.controlIdLookup[self._id] = self; + + for (var key in self._aria) { + self.aria(key, self._aria[key]); + } + + self.fire('postrender', {}, false); + }, + + scrollIntoView: function(align) { + function getOffset(elm, rootElm) { + var x, y, parent = elm; + + x = y = 0; + while (parent && parent != rootElm && parent.nodeType) { + x += parent.offsetLeft || 0; + y += parent.offsetTop || 0; + parent = parent.offsetParent; + } + + return {x: x, y: y}; + } + + var elm = this.getEl(), parentElm = elm.parentNode; + var x, y, width, height, parentWidth, parentHeight; + var pos = getOffset(elm, parentElm); + + x = pos.x; + y = pos.y; + width = elm.offsetWidth; + height = elm.offsetHeight; + parentWidth = parentElm.clientWidth; + parentHeight = parentElm.clientHeight; + + if (align == "end") { + x -= parentWidth - width; + y -= parentHeight - height; + } else if (align == "center") { + x -= (parentWidth / 2) - (width / 2); + y -= (parentHeight / 2) - (height / 2); + } + + parentElm.scrollLeft = x; + parentElm.scrollTop = y; + }, + + bindPendingEvents: function() { + var self = this, i, l, parents, eventRootCtrl, nativeEvents, name; + + function delegate(e) { + var control = self.getParentCtrl(e.target); + + if (control) { + control.fire(e.type, e); + } + } + + function mouseLeaveHandler() { + var ctrl = eventRootCtrl._lastHoverCtrl; + + if (ctrl) { + ctrl.fire("mouseleave", {target: ctrl.getEl()}); + + ctrl.parents().each(function(ctrl) { + ctrl.fire("mouseleave", {target: ctrl.getEl()}); + }); + + eventRootCtrl._lastHoverCtrl = null; + } + } + + function mouseEnterHandler(e) { + var ctrl = self.getParentCtrl(e.target), lastCtrl = eventRootCtrl._lastHoverCtrl, idx = 0, i, parents, lastParents; + + // Over on a new control + if (ctrl !== lastCtrl) { + eventRootCtrl._lastHoverCtrl = ctrl; + + parents = ctrl.parents().toArray().reverse(); + parents.push(ctrl); + + if (lastCtrl) { + lastParents = lastCtrl.parents().toArray().reverse(); + lastParents.push(lastCtrl); + + for (idx = 0; idx < lastParents.length; idx++) { + if (parents[idx] !== lastParents[idx]) { + break; + } + } + + for (i = lastParents.length - 1; i >= idx; i--) { + lastCtrl = lastParents[i]; + lastCtrl.fire("mouseleave", { + target : lastCtrl.getEl() + }); + } + } + + for (i = idx; i < parents.length; i++) { + ctrl = parents[i]; + ctrl.fire("mouseenter", { + target : ctrl.getEl() + }); + } + } + } + + function fixWheelEvent(e) { + e.preventDefault(); + + if (e.type == "mousewheel") { + e.deltaY = - 1/40 * e.wheelDelta; + + if (e.wheelDeltaX) { + e.deltaX = -1/40 * e.wheelDeltaX; + } + } else { + e.deltaX = 0; + e.deltaY = e.detail; + } + + e = self.fire("wheel", e); + } + + self._rendered = true; + + nativeEvents = self._nativeEvents; + if (nativeEvents) { + // Find event root element if it exists + parents = self.parents().toArray(); + parents.unshift(self); + for (i = 0, l = parents.length; !eventRootCtrl && i < l; i++) { + eventRootCtrl = parents[i]._eventsRoot; + } + + // Event root wasn't found the use the root control + if (!eventRootCtrl) { + eventRootCtrl = parents[parents.length - 1] || self; + } + + // Set the eventsRoot property on children that didn't have it + self._eventsRoot = eventRootCtrl; + for (l = i, i = 0; i < l; i++) { + parents[i]._eventsRoot = eventRootCtrl; + } + + // Bind native event delegates + for (name in nativeEvents) { + if (!nativeEvents) { + return false; + } + + if (name === "wheel" && !hasWheelEventSupport) { + if (hasMouseWheelEventSupport) { + DomUtils.on(self.getEl(), "mousewheel", fixWheelEvent); + } else { + DomUtils.on(self.getEl(), "DOMMouseScroll", fixWheelEvent); + } + + continue; + } + + // Special treatment for mousenter/mouseleave since these doesn't bubble + if (name === "mouseenter" || name === "mouseleave") { + // Fake mousenter/mouseleave + if (!eventRootCtrl._hasMouseEnter) { + DomUtils.on(eventRootCtrl.getEl(), "mouseleave", mouseLeaveHandler); + DomUtils.on(eventRootCtrl.getEl(), "mouseover", mouseEnterHandler); + eventRootCtrl._hasMouseEnter = 1; + } + } else if (!eventRootCtrl[name]) { + DomUtils.on(eventRootCtrl.getEl(), name, delegate); + eventRootCtrl[name] = true; + } + + // Remove the event once it's bound + nativeEvents[name] = false; + } + } + }, + + reflow: function() { + this.repaint(); + + return this; + } + + /** + * Sets/gets the parent container for the control. + * + * @method parent + * @param {tinymce.ui.Container} parent Optional parent to set. + * @return {tinymce.ui.Control} Parent control or the current control on a set action. + */ + // parent: function(parent) {} -- Generated + + /** + * Sets/gets the text for the control. + * + * @method text + * @param {String} value Value to set to control. + * @return {String/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // text: function(value) {} -- Generated + + /** + * Sets/gets the width for the control. + * + * @method width + * @param {Number} value Value to set to control. + * @return {Number/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // width: function(value) {} -- Generated + + /** + * Sets/gets the height for the control. + * + * @method height + * @param {Number} value Value to set to control. + * @return {Number/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // height: function(value) {} -- Generated + + /** + * Sets/gets the disabled for the control. + * + * @method disabled + * @param {Boolean} state Value to set to control. + * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get. + */ + // disabled: function(state) {} -- Generated + + /** + * Sets/gets the active for the control. + * + * @method active + * @param {Boolean} state Value to set to control. + * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get. + */ + // active: function(state) {} -- Generated + + /** + * Sets/gets the name for the control. + * + * @method name + * @param {String} value Value to set to control. + * @return {String/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // name: function(value) {} -- Generated + + /** + * Sets/gets the title for the control. + * + * @method title + * @param {String} value Value to set to control. + * @return {String/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // title: function(value) {} -- Generated + }); + + return Control; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/DomUtils.js b/lib/tinymce/jscripts/tinymce4/classes/ui/DomUtils.js new file mode 100644 index 00000000..7f107357 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/DomUtils.js @@ -0,0 +1,70 @@ +/** + * DomUtils.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +define("tinymce/ui/DomUtils", [ + "tinymce/util/Tools", + "tinymce/dom/DOMUtils" +], function(Tools, DOMUtils) { + "use strict"; + + return { + id: function() { + return DOMUtils.DOM.uniqueId(); + }, + + createFragment: function(html) { + return DOMUtils.DOM.createFragment(html); + }, + + getWindowSize: function() { + return DOMUtils.DOM.getViewPort(); + }, + + getSize: function(elm) { + return DOMUtils.DOM.getSize(elm); + }, + + getPos: function(elm, root) { + return DOMUtils.DOM.getPos(elm, root); + }, + + get: function(id) { + return document.getElementById(id); + }, + + addClass : function(elm, cls) { + return DOMUtils.DOM.addClass(elm, cls); + }, + + removeClass : function(elm, cls) { + return DOMUtils.DOM.removeClass(elm, cls); + }, + + hasClass : function(elm, cls) { + return DOMUtils.DOM.hasClass(elm, cls); + }, + + toggleClass: function(elm, cls, state) { + return DOMUtils.DOM.toggleClass(elm, cls, state); + }, + + css: function(elm, name, value) { + return DOMUtils.DOM.setStyle(elm, name, value); + }, + + on: function(target, name, callback, scope) { + return DOMUtils.DOM.bind(target, name, callback, scope); + }, + + off: function(target, name, callback) { + return DOMUtils.DOM.unbind(target, name, callback); + }, + + fire: function(target, name, args) { + return DOMUtils.DOM.fire(target, name, args); + } + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/DragHelper.js b/lib/tinymce/jscripts/tinymce4/classes/ui/DragHelper.js new file mode 100644 index 00000000..2392d8a1 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/DragHelper.js @@ -0,0 +1,125 @@ +/** + * DragHelper.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Drag/drop helper class. + * + * @example + * var dragHelper = new tinymce.ui.DragHelper('mydiv', { + * start: function(evt) { + * }, + * + * drag: function(evt) { + * }, + * + * end: function(evt) { + * } + * }); + */ +define("tinymce/ui/DragHelper", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + function getDocumentSize() { + var doc = document, documentElement, body, scrollWidth, clientWidth; + var offsetWidth, scrollHeight, clientHeight, offsetHeight, max = Math.max; + + documentElement = doc.documentElement; + body = doc.body; + + scrollWidth = max(documentElement.scrollWidth, body.scrollWidth); + clientWidth = max(documentElement.clientWidth, body.clientWidth); + offsetWidth = max(documentElement.offsetWidth, body.offsetWidth); + + scrollHeight = max(documentElement.scrollHeight, body.scrollHeight); + clientHeight = max(documentElement.clientHeight, body.clientHeight); + offsetHeight = max(documentElement.offsetHeight, body.offsetHeight); + + return { + width: scrollWidth < offsetWidth ? clientWidth : scrollWidth, + height: scrollHeight < offsetHeight ? clientHeight : scrollHeight + }; + } + + return function(id, settings) { + var eventOverlayElm, doc = document, downButton, start, stop, drag, startX, startY; + + settings = settings || {}; + + function getHandleElm() { + return doc.getElementById(settings.handle || id); + } + + start = function(e) { + var docSize = getDocumentSize(), handleElm, cursor; + + e.preventDefault(); + downButton = e.button; + handleElm = getHandleElm(); + startX = e.screenX; + startY = e.screenY; + + // Grab cursor from handle + if (window.getComputedStyle) { + cursor = window.getComputedStyle(handleElm, null).getPropertyValue("cursor"); + } else { + cursor = handleElm.runtimeStyle.cursor; + } + + // Create event overlay and add it to document + eventOverlayElm = doc.createElement('div'); + DomUtils.css(eventOverlayElm, { + position: "absolute", + top: 0, left: 0, + width: docSize.width, + height: docSize.height, + zIndex: 0xFFFF, + opacity: 0.0001, + background: 'red', + cursor: cursor + }); + + doc.body.appendChild(eventOverlayElm); + + // Bind mouse events + DomUtils.on(doc, 'mousemove', drag); + DomUtils.on(doc, 'mouseup', stop); + + // Begin drag + settings.start(e); + }; + + drag = function(e) { + if (e.button !== downButton) { + return stop(e); + } + + e.deltaX = e.screenX - startX; + e.deltaY = e.screenY - startY; + + e.preventDefault(); + settings.drag(e); + }; + + stop = function(e) { + DomUtils.off(doc, 'mousemove', drag); + DomUtils.off(doc, 'mouseup', stop); + + eventOverlayElm.parentNode.removeChild(eventOverlayElm); + + if (settings.stop) { + settings.stop(e); + } + }; + + this.destroy = function() { + DomUtils.off(getHandleElm()); + }; + + DomUtils.on(getHandleElm(), 'mousedown', start); + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/ElementPath.js b/lib/tinymce/jscripts/tinymce4/classes/ui/ElementPath.js new file mode 100644 index 00000000..b351e967 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/ElementPath.js @@ -0,0 +1,64 @@ +/** + * ElementPath.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.ElementPath + * @extends tinymce.ui.Path + */ +define("tinymce/ui/ElementPath", [ + "tinymce/ui/Path", + "tinymce/EditorManager" +], function(Path, EditorManager) { + return Path.extend({ + postRender: function() { + var self = this, editor = EditorManager.activeEditor; + + function isBogus(elm) { + return elm.nodeType === 1 && (elm.nodeName == "BR" || !!elm.getAttribute('data-mce-bogus')); + } + + self.on('select', function(e) { + var parents = [], node = editor.selection.getNode(), body = editor.getBody(); + + while (node) { + if (!isBogus(node)) { + parents.push(node); + } + + node = node.parentNode; + if (node == body) { + break; + } + } + + editor.focus(); + editor.selection.select(parents[parents.length - 1 - e.index]); + editor.nodeChanged(); + }); + + editor.on('nodeChange', function(e) { + var parents = [], selectionParents = e.parents, i = selectionParents.length; + + while (i--) { + if (!isBogus(selectionParents[i])) { + var args = editor.fire('ResolveName', { + name: selectionParents[i].nodeName.toLowerCase(), + target: selectionParents[i] + }); + + parents.push({name: args.name}); + } + } + + self.data(parents); + }); + + return self._super(); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Factory.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Factory.js new file mode 100644 index 00000000..eeb2bb51 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Factory.js @@ -0,0 +1,78 @@ +/** + * Factory.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/*global tinymce:true */ + +/** + * .. + * + * @class tinymce.ui.Factory + */ +define("tinymce/ui/Factory", [], function() { + "use strict"; + + var types = {}, namespaceInit; + + return { + add: function(type, typeClass) { + types[type.toLowerCase()] = typeClass; + }, + + has: function(type) { + return !!types[type.toLowerCase()]; + }, + + /** + * Creates a new control instance based on the settings provided. The instance created will be + * based on the specified type property. + * + * @method create + * @example tinymce.ui.Factory.create({type: 'button', text: 'Hello world!'}); + * @param {Object/String} settings Name/Value object with items used to create the type. + * @return {tinymce.ui.Control} Control instance based on the specified type. + */ + create: function(type, settings) { + var ControlType, name, namespace; + + // Build type lookup + if (!namespaceInit) { + namespace = tinymce.ui; + + for (name in namespace) { + types[name.toLowerCase()] = namespace[name]; + } + + namespaceInit = true; + } + + // If string is specified then use it as the type + if (typeof(type) == 'string') { + settings = settings || {}; + settings.type = type; + } else { + settings = type; + type = settings.type; + } + + // Find control type + type = type.toLowerCase(); + ControlType = types[type]; + + // #if debug + + if (!ControlType) { + throw new Error("Could not find control by type: " + type); + } + + // #endif + + ControlType = new ControlType(settings); + ControlType.type = type; // Set the type on the instance, this will be used by the Selector engine + + return ControlType; + } + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/FieldSet.js b/lib/tinymce/jscripts/tinymce4/classes/ui/FieldSet.js new file mode 100644 index 00000000..3e9fdcb5 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/FieldSet.js @@ -0,0 +1,49 @@ +/** + * FieldSet.js + * + * Copyright 2003-2013, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less FieldSet.less + * @class tinymce.ui.FieldSet + * @extends tinymce.ui.Form + */ +define("tinymce/ui/FieldSet", [ + "tinymce/ui/Form" +], function(Form) { + "use strict"; + + return Form.extend({ + Defaults: { + containerCls: 'fieldset', + layout: 'flex', + direction: 'column', + align: 'stretch', + flex: 1, + padding: "25 15 5 15", + labelGap: 30, + spacing: 10, + border: 1 + }, + + renderHtml: function() { + var self = this, layout = self._layout, prefix = self.classPrefix; + + self.preRender(); + layout.preRender(self); + + return ( + '
    ' + + (self.settings.title ? ('' + + self.settings.title + '') : '') + + '
    ' + + (self.settings.html || '') + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/FilePicker.js b/lib/tinymce/jscripts/tinymce4/classes/ui/FilePicker.js new file mode 100644 index 00000000..85bd8413 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/FilePicker.js @@ -0,0 +1,43 @@ +/** + * FilePicker.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/*global tinymce:true */ + +/** + * .. + * + * @class tinymce.ui.FilePicker + * @extends tinymce.ui.ComboBox + */ +define("tinymce/ui/FilePicker", [ + "tinymce/ui/ComboBox" +], function(ComboBox) { + "use strict"; + + return ComboBox.extend({ + init: function(settings) { + var self = this, editor = tinymce.activeEditor, fileBrowserCallback; + + settings.spellcheck = false; + + fileBrowserCallback = editor.settings.file_browser_callback; + if (fileBrowserCallback) { + settings.icon = 'browse'; + + settings.onaction = function() { + fileBrowserCallback( + self.getEl('inp').id, + self.getEl('inp').value, + settings.filetype, + window + ); + }; + } + + self._super(settings); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/FitLayout.js b/lib/tinymce/jscripts/tinymce4/classes/ui/FitLayout.js new file mode 100644 index 00000000..24d2168f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/FitLayout.js @@ -0,0 +1,39 @@ +/** + * FitLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * This class jada jada. + * + * var x = 3; + * + * @-x-less FitLayout.less + * @class tinymce.ui.FitLayout + * @extends tinymce.ui.AbsoluteLayout + */ +define("tinymce/ui/FitLayout", [ + "tinymce/ui/AbsoluteLayout" +], function(AbsoluteLayout) { + "use strict"; + + return AbsoluteLayout.extend({ + recalc: function(container) { + var contLayoutRect = container.layoutRect(), paddingBox = container.paddingBox(); + + container.items().filter(':visible').each(function(ctrl) { + ctrl.layoutRect({ + x: paddingBox.left, + y: paddingBox.top, + w: contLayoutRect.innerW - paddingBox.right - paddingBox.left, + h: contLayoutRect.innerH - paddingBox.top - paddingBox.bottom + }); + + if (ctrl.recalc) { + ctrl.recalc(); + } + }); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/FlexLayout.js b/lib/tinymce/jscripts/tinymce4/classes/ui/FlexLayout.js new file mode 100644 index 00000000..a4f22fa0 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/FlexLayout.js @@ -0,0 +1,240 @@ +/** + * FlexLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * Settings: + * direction=row|row-reverse|column|column-reverse + * flex= + * align=start|end|center|stretch + * pack=start|end|justify + * + * @class tinymce.ui.layout.FlexLayout + * @extends tinymce.ui.AbsoluteLayout + */ +define("tinymce/ui/FlexLayout", [ + "tinymce/ui/AbsoluteLayout" +], function(AbsoluteLayout) { + "use strict"; + + return AbsoluteLayout.extend({ + recalc: function(container) { + var i, l, items, contLayoutRect, contPaddingBox, contSettings, align, pack, spacing, totalFlex, availableSpace, direction; + var ctrl, ctrlLayoutRect, ctrlSettings, flex, maxSizeItems = [], size, maxSize, ratio, rect, pos, maxAlignEndPos; + var sizeName, minSizeName, posName, maxSizeName, beforeName, innerSizeName, afterName, deltaSizeName, contentSizeName; + var alignAxisName, alignInnerSizeName, alignSizeName, alignMinSizeName, alignMaxSizeName, alignBeforeName, alignAfterName; + var alignDeltaSizeName, alignContentSizeName; + var max = Math.max, min = Math.min; + + // Get container items, properties and settings + items = container.items().filter(':visible'); + contLayoutRect = container.layoutRect(); + contPaddingBox = container._paddingBox; + contSettings = container.settings; + direction = contSettings.direction; + align = contSettings.align; + pack = contSettings.pack; + spacing = contSettings.spacing || 0; + + if (direction == "row-reversed" || direction == "column-reverse") { + items = items.set(items.toArray().reverse()); + direction = direction.split('-')[0]; + } + + // Setup axis variable name for row/column direction since the calculations is the same + if (direction == "column") { + posName = "y"; + sizeName = "h"; + minSizeName = "minH"; + maxSizeName = "maxH"; + innerSizeName = "innerH"; + beforeName = 'top'; + afterName = 'bottom'; + deltaSizeName = "deltaH"; + contentSizeName = "contentH"; + + alignBeforeName = "left"; + alignSizeName = "w"; + alignAxisName = "x"; + alignInnerSizeName = "innerW"; + alignMinSizeName = "minW"; + alignMaxSizeName = "maxW"; + alignAfterName = "right"; + alignDeltaSizeName = "deltaW"; + alignContentSizeName = "contentW"; + } else { + posName = "x"; + sizeName = "w"; + minSizeName = "minW"; + maxSizeName = "maxW"; + innerSizeName = "innerW"; + beforeName = 'left'; + afterName = 'right'; + deltaSizeName = "deltaW"; + contentSizeName = "contentW"; + + alignBeforeName = "top"; + alignSizeName = "h"; + alignAxisName = "y"; + alignInnerSizeName = "innerH"; + alignMinSizeName = "minH"; + alignMaxSizeName = "maxH"; + alignAfterName = "bottom"; + alignDeltaSizeName = "deltaH"; + alignContentSizeName = "contentH"; + } + + // Figure out total flex, availableSpace and collect any max size elements + availableSpace = contLayoutRect[innerSizeName] - contPaddingBox[beforeName] - contPaddingBox[beforeName]; + maxAlignEndPos = totalFlex = 0; + for (i = 0, l = items.length; i < l; i++) { + ctrl = items[i]; + ctrlLayoutRect = ctrl.layoutRect(); + ctrlSettings = ctrl.settings; + flex = ctrlSettings.flex; + availableSpace -= (i < l - 1 ? spacing : 0); + + if (flex > 0) { + totalFlex += flex; + + // Flexed item has a max size then we need to check if we will hit that size + if (ctrlLayoutRect[maxSizeName]) { + maxSizeItems.push(ctrl); + } + + ctrlLayoutRect.flex = flex; + } + + availableSpace -= ctrlLayoutRect[minSizeName]; + + // Calculate the align end position to be used to check for overflow/underflow + size = contPaddingBox[alignBeforeName] + ctrlLayoutRect[alignMinSizeName] + contPaddingBox[alignAfterName]; + if (size > maxAlignEndPos) { + maxAlignEndPos = size; + } + } + + // Calculate minW/minH + rect = {}; + if (availableSpace < 0) { + rect[minSizeName] = contLayoutRect[minSizeName] - availableSpace + contLayoutRect[deltaSizeName]; + } else { + rect[minSizeName] = contLayoutRect[innerSizeName] - availableSpace + contLayoutRect[deltaSizeName]; + } + + rect[alignMinSizeName] = maxAlignEndPos + contLayoutRect[alignDeltaSizeName]; + + rect[contentSizeName] = contLayoutRect[innerSizeName] - availableSpace; + rect[alignContentSizeName] = maxAlignEndPos; + rect.minW = min(rect.minW, contLayoutRect.maxW); + rect.minH = min(rect.minH, contLayoutRect.maxH); + rect.minW = max(rect.minW, contLayoutRect.startMinWidth); + rect.minH = max(rect.minH, contLayoutRect.startMinHeight); + + // Resize container container if minSize was changed + if (contLayoutRect.autoResize && (rect.minW != contLayoutRect.minW || rect.minH != contLayoutRect.minH)) { + rect.w = rect.minW; + rect.h = rect.minH; + + container.layoutRect(rect); + this.recalc(container); + + // Forced recalc for example if items are hidden/shown + if (container._lastRect === null) { + var parentCtrl = container.parent(); + if (parentCtrl) { + parentCtrl._lastRect = null; + parentCtrl.recalc(); + } + } + + return; + } + + // Handle max size elements, check if they will become to wide with current options + ratio = availableSpace / totalFlex; + for (i = 0, l = maxSizeItems.length; i < l; i++) { + ctrl = maxSizeItems[i]; + ctrlLayoutRect = ctrl.layoutRect(); + maxSize = ctrlLayoutRect[maxSizeName]; + size = ctrlLayoutRect[minSizeName] + Math.ceil(ctrlLayoutRect.flex * ratio); + + if (size > maxSize) { + availableSpace -= (ctrlLayoutRect[maxSizeName] - ctrlLayoutRect[minSizeName]); + totalFlex -= ctrlLayoutRect.flex; + ctrlLayoutRect.flex = 0; + ctrlLayoutRect.maxFlexSize = maxSize; + } else { + ctrlLayoutRect.maxFlexSize = 0; + } + } + + // Setup new ratio, target layout rect, start position + ratio = availableSpace / totalFlex; + pos = contPaddingBox[beforeName]; + rect = {}; + + // Handle pack setting moves the start position to end, center + if (totalFlex === 0) { + if (pack == "end") { + pos = availableSpace + contPaddingBox[beforeName]; + } else if (pack == "center") { + pos = Math.round( + (contLayoutRect[innerSizeName] / 2) - ((contLayoutRect[innerSizeName] - availableSpace) / 2) + ) + contPaddingBox[beforeName]; + + if (pos < 0) { + pos = contPaddingBox[beforeName]; + } + } else if (pack == "justify") { + pos = contPaddingBox[beforeName]; + spacing = Math.floor(availableSpace / (items.length - 1)); + } + } + + // Default aligning (start) the other ones needs to be calculated while doing the layout + rect[alignAxisName] = contPaddingBox[alignBeforeName]; + + // Start laying out controls + for (i = 0, l = items.length; i < l; i++) { + ctrl = items[i]; + ctrlLayoutRect = ctrl.layoutRect(); + size = ctrlLayoutRect.maxFlexSize || ctrlLayoutRect[minSizeName]; + + // Align the control on the other axis + if (align === "center") { + rect[alignAxisName] = Math.round((contLayoutRect[alignInnerSizeName] / 2) - (ctrlLayoutRect[alignSizeName] / 2)); + } else if (align === "stretch") { + rect[alignSizeName] = max( + ctrlLayoutRect[alignMinSizeName] || 0, + contLayoutRect[alignInnerSizeName] - contPaddingBox[alignBeforeName] - contPaddingBox[alignAfterName] + ); + rect[alignAxisName] = contPaddingBox[alignBeforeName]; + } else if (align === "end") { + rect[alignAxisName] = contLayoutRect[alignInnerSizeName] - ctrlLayoutRect[alignSizeName] - contPaddingBox.top; + } + + // Calculate new size based on flex + if (ctrlLayoutRect.flex > 0) { + size += Math.ceil(ctrlLayoutRect.flex * ratio); + } + + rect[sizeName] = size; + rect[posName] = pos; + ctrl.layoutRect(rect); + + // Recalculate containers + if (ctrl.recalc) { + ctrl.recalc(); + } + + // Move x/y position + pos += size + spacing; + } + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/FloatPanel.js b/lib/tinymce/jscripts/tinymce4/classes/ui/FloatPanel.js new file mode 100644 index 00000000..2662ec01 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/FloatPanel.js @@ -0,0 +1,204 @@ +/** + * FloatPanel.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less FloatPanel.less + * @class tinymce.ui.FloatPanel + * @extends tinymce.ui.Panel + */ +define("tinymce/ui/FloatPanel", [ + "tinymce/ui/Panel", + "tinymce/ui/Movable", + "tinymce/ui/Resizable", + "tinymce/ui/DomUtils" +], function(Panel, Movable, Resizable, DomUtils) { + "use strict"; + + var documentClickHandler, autoHidePanels = []; + var zOrder = [], hasModal; + + var FloatPanel = Panel.extend({ + Mixins: [Movable, Resizable], + + init: function(settings) { + var self = this; + + function reorder() { + var i, zIndex = FloatPanel.zIndex || 0xFFFF, topModal; + + if (zOrder.length) { + for (i = 0; i < zOrder.length; i++) { + if (zOrder[i].modal) { + zIndex++; + topModal = zOrder[i]; + } + + zOrder[i].getEl().style.zIndex = zIndex; + zOrder[i].zIndex = zIndex; + zIndex++; + } + } + + var modalBlockEl = document.getElementById(self.classPrefix + 'modal-block'); + + if (topModal) { + DomUtils.css(modalBlockEl, 'z-index', topModal.zIndex - 1); + } else if (modalBlockEl) { + modalBlockEl.parentNode.removeChild(modalBlockEl); + hasModal = false; + } + + FloatPanel.currentZIndex = zIndex; + } + + function isChildOf(ctrl, parent) { + while (ctrl) { + if (ctrl == parent) { + return true; + } + + ctrl = ctrl.parent(); + } + } + + self._super(settings); + self._eventsRoot = self; + + self.addClass('floatpanel'); + + // Hide floatpanes on click out side the root button + if (settings.autohide) { + if (!documentClickHandler) { + documentClickHandler = function(e) { + var i, clickCtrl = self.getParentCtrl(e.target); + + // Hide any float panel when a click is out side that float panel and the + // float panels direct parent for example a click on a menu button + i = autoHidePanels.length; + while (i--) { + if (clickCtrl) { + if (isChildOf(clickCtrl, autoHidePanels[i]) || autoHidePanels[i].parent() === clickCtrl) { + continue; + } + } + + autoHidePanels[i].hide(); + } + }; + + DomUtils.on(document, 'click', documentClickHandler); + } + + autoHidePanels.push(self); + } + + self.on('postrender show', function(e) { + if (e.control == self) { + var modalBlockEl, prefix = self.classPrefix; + + if (self.modal && !hasModal) { + modalBlockEl = DomUtils.createFragment('
    '); + modalBlockEl = modalBlockEl.firstChild; + + self.getContainerElm().appendChild(modalBlockEl); + + setTimeout(function() { + DomUtils.addClass(modalBlockEl, prefix + 'in'); + DomUtils.addClass(self.getEl(), prefix + 'in'); + }, 0); + + hasModal = true; + } + + zOrder.push(self); + reorder(); + } + }); + + self.on('close hide', function(e) { + if (e.control == self) { + var i = zOrder.length; + + while (i--) { + if (zOrder[i] === self) { + zOrder.splice(i, 1); + } + } + + reorder(); + } + }); + + if (settings.popover) { + self._preBodyHtml = '
    '; + self.addClass('popover').addClass('bottom').addClass('start'); + } + }, + + show: function() { + var self = this, i, state = self._super(); + + i = autoHidePanels.length; + while (i--) { + if (autoHidePanels[i] === self) { + break; + } + } + + if (self.settings.autohide && i === -1) { + autoHidePanels.push(self); + } + + return state; + }, + + hide: function() { + var i; + + i = autoHidePanels.length; + while (i--) { + if (autoHidePanels[i] === this) { + autoHidePanels.splice(i, 1); + } + } + + return this._super(); + }, + + hideAll: function() { + FloatPanel.hideAll(); + }, + + close: function() { + var self = this; + + self.fire('close'); + + return self.remove(); + }, + + remove: function() { + var self = this; + + self._super(); + } + }); + + FloatPanel.hideAll = function() { + var i = autoHidePanels.length; + + while (i--) { + autoHidePanels[i].fire('cancel', {}, false); + autoHidePanels[i].hide(); + autoHidePanels.splice(i, 1); + } + }; + + return FloatPanel; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/FlowLayout.js b/lib/tinymce/jscripts/tinymce4/classes/ui/FlowLayout.js new file mode 100644 index 00000000..28d91136 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/FlowLayout.js @@ -0,0 +1,32 @@ +/** + * FlowLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less FlowLayout.less + * @class tinymce.ui.FlowLayout + * @extends tinymce.ui.Layout + */ +define("tinymce/ui/FlowLayout", [ + "tinymce/ui/Layout" +], function(Layout) { + return Layout.extend({ + Defaults: { + containerClass: 'flow-layout', + controlClass: 'flow-layout-item', + endClass : 'break' + }, + + recalc: function(container) { + container.items().filter(':visible').each(function(ctrl) { + if (ctrl.recalc) { + ctrl.recalc(); + } + }); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Form.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Form.js new file mode 100644 index 00000000..87513f11 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Form.js @@ -0,0 +1,130 @@ +/** + * Form.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.Form + * @extends tinymce.ui.Container + */ +define("tinymce/ui/Form", [ + "tinymce/ui/Container", + "tinymce/ui/FormItem" +], function(Container, FormItem) { + "use strict"; + + return Container.extend({ + Defaults: { + containerCls: 'form', + layout: 'flex', + direction: 'column', + align: 'stretch', + flex: 1, + padding: 20, + labelGap: 30, + spacing: 10 + }, + + preRender: function() { + var self = this, items = self.items(); + + // Wrap any labeled items in FormItems + items.each(function(ctrl) { + var formItem, label = ctrl.settings.label; + + if (label) { + formItem = new FormItem({ + layout: 'flex', + autoResize: "overflow", + defaults: {flex: 1}, + items: [ + {type: 'label', text: label, flex: 0, forId: ctrl._id} + ] + }); + + formItem.type = 'formitem'; + + if (typeof(ctrl.settings.flex) == "undefined") { + ctrl.settings.flex = 1; + } + + self.replace(ctrl, formItem); + formItem.add(ctrl); + } + }); + }, + + recalcLabels: function() { + var self = this, maxLabelWidth = 0, labels = [], i, labelGap; + + if (self.settings.labelGapCalc === false) { + return; + } + + self.items().filter('formitem').each(function(item) { + var labelCtrl = item.items()[0], labelWidth = labelCtrl.getEl().clientWidth; + + maxLabelWidth = labelWidth > maxLabelWidth ? labelWidth : maxLabelWidth; + labels.push(labelCtrl); + }); + + labelGap = self.settings.labelGap || 0; + + i = labels.length; + while (i--) { + labels[i].settings.minWidth = maxLabelWidth + labelGap; + } + }, + + visible: function(state) { + var val = this._super(state); + + if (state === true && this._rendered) { + this.recalcLabels(); + } + + return val; + }, + + fromJSON: function(data) { + var self = this; + + if (data) { + for (var name in data) { + self.find('#' + name).value(data[name]); + } + } + + return self; + }, + + toJSON: function() { + var self = this, data = {}; + + self.find('*').each(function(ctrl) { + var name = ctrl.name(), value = ctrl.value(); + + if (name && typeof(value) != "undefined") { + data[name] = value; + } + }); + + return data; + }, + + submit: function() { + return this.fire('submit', {data: this.toJSON()}); + }, + + postRender: function() { + var self = this; + + self._super(); + self.recalcLabels(); + self.fromJSON(self.settings.data); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/FormItem.js b/lib/tinymce/jscripts/tinymce4/classes/ui/FormItem.js new file mode 100644 index 00000000..90c8d269 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/FormItem.js @@ -0,0 +1,44 @@ +/** + * FormItem.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.FormItem + * @extends tinymce.ui.Container + */ +define("tinymce/ui/FormItem", [ + "tinymce/ui/Container" +], function(Container) { + "use strict"; + + return Container.extend({ + Defaults: { + layout: 'flex', + align: 'center', + defaults: { + flex: 1 + } + }, + + renderHtml: function() { + var self = this, layout = self._layout, prefix = self.classPrefix; + + self.addClass('formitem'); + layout.preRender(self); + + return ( + '
    ' + + (self.settings.title ? ('
    ' + + self.settings.title + '
    ') : '') + + '
    ' + + (self.settings.html || '') + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/FormatControls.js b/lib/tinymce/jscripts/tinymce4/classes/ui/FormatControls.js new file mode 100644 index 00000000..73c748af --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/FormatControls.js @@ -0,0 +1,573 @@ +/** + * FormatControls.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * + * @class tinymce.ui.FormatControls + */ +define("tinymce/ui/FormatControls", [ + "tinymce/ui/Factory", + "tinymce/ui/Control", + "tinymce/ui/FloatPanel", + "tinymce/util/Tools", + "tinymce/EditorManager" +], function(Factory, Control, FloatPanel, Tools, EditorManager) { + var each = Tools.each; + + Control.translate = function(text) { + return EditorManager.translate(text); + }; + + // Generates a preview for a format + function getPreviewCss(editor, format) { + var name, previewElm, dom = editor.dom, previewCss = '', parentFontSize, previewStyles; + + previewStyles = editor.settings.preview_styles; + + // No preview forced + if (previewStyles === false) { + return ''; + } + + // Default preview + if (!previewStyles) { + previewStyles = 'font-family font-size font-weight text-decoration text-transform color background-color border border-radius'; + } + + // Removes any variables since these can't be previewed + function removeVars(val) { + return val.replace(/%(\w+)/g, ''); + } + + // Create block/inline element to use for preview + format = editor.formatter.get(format); + if (!format) { + return; + } + + format = format[0]; + name = format.block || format.inline || 'span'; + previewElm = dom.create(name); + + // Add format styles to preview element + each(format.styles, function(value, name) { + value = removeVars(value); + + if (value) { + dom.setStyle(previewElm, name, value); + } + }); + + // Add attributes to preview element + each(format.attributes, function(value, name) { + value = removeVars(value); + + if (value) { + dom.setAttrib(previewElm, name, value); + } + }); + + // Add classes to preview element + each(format.classes, function(value) { + value = removeVars(value); + + if (!dom.hasClass(previewElm, value)) { + dom.addClass(previewElm, value); + } + }); + + editor.fire('PreviewFormats'); + + // Add the previewElm outside the visual area + dom.setStyles(previewElm, {position: 'absolute', left: -0xFFFF}); + editor.getBody().appendChild(previewElm); + + // Get parent container font size so we can compute px values out of em/% for older IE:s + parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true); + parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0; + + each(previewStyles.split(' '), function(name) { + var value = dom.getStyle(previewElm, name, true); + + // If background is transparent then check if the body has a background color we can use + if (name == 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) { + value = dom.getStyle(editor.getBody(), name, true); + + // Ignore white since it's the default color, not the nicest fix + // TODO: Fix this by detecting runtime style + if (dom.toHex(value).toLowerCase() == '#ffffff') { + return; + } + } + + if (name == 'color') { + // Ignore black since it's the default color, not the nicest fix + // TODO: Fix this by detecting runtime style + if (dom.toHex(value).toLowerCase() == '#000000') { + return; + } + } + + // Old IE won't calculate the font size so we need to do that manually + if (name == 'font-size') { + if (/em|%$/.test(value)) { + if (parentFontSize === 0) { + return; + } + + // Convert font size from em/% to px + value = parseFloat(value, 10) / (/%$/.test(value) ? 100 : 1); + value = (value * parentFontSize) + 'px'; + } + } + + if (name == "border" && value) { + previewCss += 'padding:0 2px;'; + } + + previewCss += name + ':' + value + ';'; + }); + + editor.fire('AfterPreviewFormats'); + + //previewCss += 'line-height:normal'; + + dom.remove(previewElm); + + return previewCss; + } + + function createFormats(formats) { + formats = formats.split(';'); + + var i = formats.length; + while (i--) { + formats[i] = formats[i].split('='); + } + + return formats; + } + + EditorManager.on('AddEditor', function(e) { + var editor = e.editor, formatMenu; + + function createFormatMenu() { + var count = 0, newFormats = []; + + var defaultStyleFormats = [ + {title: 'Headers', items: [ + {title: 'Header 1', format: 'h1'}, + {title: 'Header 2', format: 'h2'}, + {title: 'Header 3', format: 'h3'}, + {title: 'Header 4', format: 'h4'}, + {title: 'Header 5', format: 'h5'}, + {title: 'Header 6', format: 'h6'} + ]}, + + {title: 'Inline', items: [ + {title: 'Bold', icon: 'bold', format: 'bold'}, + {title: 'Italic', icon: 'italic', format: 'italic'}, + {title: 'Underline', icon: 'underline', format: 'underline'}, + {title: 'Strikethrough', icon: 'strikethrough', format: 'strikethrough'}, + {title: 'Superscript', icon: 'superscript', format: 'superscript'}, + {title: 'Subscript', icon: 'subscript', format: 'subscript'}, + {title: 'Code', icon: 'code', format: 'code'} + ]}, + + {title: 'Blocks', items: [ + {title: 'Paragraph', format: 'p'}, + {title: 'Blockquote', format: 'blockquote'}, + {title: 'Div', format: 'div'}, + {title: 'Pre', format: 'pre'} + ]}, + + {title: 'Alignment', items: [ + {title: 'Left', icon: 'alignleft', format: 'alignleft'}, + {title: 'Center', icon: 'aligncenter', format: 'aligncenter'}, + {title: 'Right', icon: 'alignright', format: 'alignright'}, + {title: 'Justify', icon: 'alignjustify', format: 'alignjustify'} + ]} + ]; + + function createMenu(formats) { + var menu = []; + + if (!formats) { + return; + } + + each(formats, function(format) { + var menuItem = { + text: format.title, + icon: format.icon + }; + + if (format.items) { + menuItem.menu = createMenu(format.items); + } else { + var formatName = format.format || "custom" + count++; + + if (!format.format) { + format.name = formatName; + newFormats.push(format); + } + + menuItem.textStyle = function() { + return getPreviewCss(editor, formatName); + }; + + menuItem.onclick = function() { + editor.execCommand('mceToggleFormat', false, formatName); + }; + } + + menu.push(menuItem); + }); + + return menu; + } + + editor.on('init', function() { + each(newFormats, function(format) { + editor.formatter.register(format.name, format); + }); + }); + + var menu = createMenu(editor.settings.style_formats || defaultStyleFormats); + + return menu; + } + + formatMenu = createFormatMenu(); + + // Simple format controls : + each({ + bold: 'Bold', + italic: 'Italic', + underline: 'Underline', + strikethrough: 'Strikethrough', + subscript: 'Subscript', + superscript: 'Superscript' + }, function(text, name) { + editor.addButton(name, { + tooltip: text, + onPostRender: function() { + var self = this; + + // TODO: Fix this + if (editor.formatter) { + editor.formatter.formatChanged(name, function(state) { + self.active(state); + }); + } else { + editor.on('init', function() { + editor.formatter.formatChanged(name, function(state) { + self.active(state); + }); + }); + } + }, + onclick: function() { + editor.execCommand('mceToggleFormat', false, name); + } + }); + }); + + // Simple command controls :[,] + each({ + outdent: ['Decrease indent', 'Outdent'], + indent: ['Increase indent', 'Indent'], + cut: ['Cut', 'Cut'], + copy: ['Copy', 'Copy'], + paste: ['Paste', 'Paste'], + help: ['Help', 'mceHelp'], + selectall: ['Select all', 'SelectAll'], + hr: ['Insert horizontal rule', 'InsertHorizontalRule'], + removeformat: ['Clear formatting', 'RemoveFormat'], + visualaid: ['Visual aids', 'mceToggleVisualAid'], + newdocument: ['New document', 'mceNewDocument'] + }, function(item, name) { + editor.addButton(name, { + tooltip: item[0], + cmd: item[1] + }); + }); + + // Simple command controls with format state + each({ + blockquote: ['Toggle blockquote', 'mceBlockQuote'], + numlist: ['Numbered list', 'InsertOrderedList'], + bullist: ['Bulleted list', 'InsertUnorderedList'], + subscript: ['Subscript', 'Subscript'], + superscript: ['Superscript', 'Superscript'], + alignleft: ['Align left', 'JustifyLeft'], + aligncenter: ['Align center', 'JustifyCenter'], + alignright: ['Align right', 'JustifyRight'], + alignjustify: ['Justify', 'JustifyFull'] + }, function(item, name) { + editor.addButton(name, { + tooltip: item[0], + cmd: item[1], + onPostRender: function() { + var self = this; + + // TODO: Fix this + if (editor.formatter) { + editor.formatter.formatChanged(name, function(state) { + self.active(state); + }); + } else { + editor.on('init', function() { + editor.formatter.formatChanged(name, function(state) { + self.active(state); + }); + }); + } + } + }); + }); + + function hasUndo() { + return editor.undoManager ? editor.undoManager.hasUndo() : false; + } + + function hasRedo() { + return editor.undoManager ? editor.undoManager.hasRedo() : false; + } + + function toggleUndoState() { + var self = this; + + self.disabled(!hasUndo()); + editor.on('Undo Redo AddUndo', function() { + self.disabled(!hasUndo()); + }); + } + + function toggleRedoState() { + var self = this; + + self.disabled(!hasRedo()); + editor.on('Undo Redo AddUndo', function() { + self.disabled(!hasRedo()); + }); + } + + function toggleVisualAidState() { + var self = this; + + editor.on('VisualAid', function(e) { + self.active(e.hasVisual); + }); + + self.active(editor.hasVisual); + } + + editor.addButton('forecolor', { + type: 'colorbutton', + tooltip: 'Text color', + onselect: function(e) { + editor.execCommand('ForeColor', false, e.value); + } + }); + + editor.addButton('backcolor', { + type: 'colorbutton', + tooltip: 'Background color', + onselect: function(e) { + editor.execCommand('HiliteColor', false, e.value); + } + }); + + editor.addButton('undo', { + tooltip: 'Undo', + onPostRender: toggleUndoState, + cmd: 'undo' + }); + + editor.addButton('redo', { + tooltip: 'Redo', + onPostRender: toggleRedoState, + cmd: 'redo' + }); + + editor.addMenuItem('newdocument', { + text: 'New document', + shortcut: 'Ctrl+N', + icon: 'newdocument', + cmd: 'mceNewDocument' + }); + + editor.addMenuItem('undo', { + text: 'Undo', + icon: 'undo', + shortcut: 'Ctrl+Z', + onPostRender: toggleUndoState, + cmd: 'undo' + }); + + editor.addMenuItem('redo', { + text: 'Redo', + icon: 'redo', + shortcut: 'Ctrl+Y', + onPostRender: toggleRedoState, + cmd: 'redo' + }); + + editor.addMenuItem('visualaid', { + text: 'Visual aids', + selectable: true, + onPostRender: toggleVisualAidState, + cmd: 'mceToggleVisualAid' + }); + + each({ + cut: ['Cut', 'Cut', 'Ctrl+X'], + copy: ['Copy', 'Copy', 'Ctrl+C'], + paste: ['Paste', 'Paste', 'Ctrl+V'], + selectall: ['Select all', 'SelectAll', 'Ctrl+A'], + bold: ['Bold', 'Bold', 'Ctrl+B'], + italic: ['Italic', 'Italic', 'Ctrl+I'], + underline: ['Underline', 'Underline'], + strikethrough: ['Strikethrough', 'Strikethrough'], + subscript: ['Subscript', 'Subscript'], + superscript: ['Superscript', 'Superscript'], + removeformat: ['Clear formatting', 'RemoveFormat'] + }, function(item, name) { + editor.addMenuItem(name, { + text: item[0], + icon: name, + shortcut: item[2], + cmd: item[1] + }); + }); + + editor.on('mousedown', function() { + FloatPanel.hideAll(); + }); + + function toggleFormat(e) { + if (e.control.settings.format) { + EditorManager.activeEditor.execCommand('mceToggleFormat', false, e.control.settings.format); + } + } + + Factory.add('styleselect', function(settings) { + var menu = [].concat(formatMenu); + + /* + menu.push({text: '-'}); + menu.push({ + text: 'Remove formatting', + icon: 'removeformat', + onclick: function() { + editor.execCommand('RemoveFormat'); + } + }); + */ + + return Factory.create('menubutton', Tools.extend({ + text: 'Formats', + menu: menu + }, settings)); + }); + + Factory.add('formatselect', function(settings) { + var items = [], blocks = createFormats( + 'Paragraph=p;' + + 'Address=address;' + + 'Pre=pre;' + + 'Header 1=h1;' + + 'Header 2=h2;' + + 'Header 3=h3;' + + 'Header 4=h4;' + + 'Header 5=h5;' + + 'Header 6=h6' + ); + + each(blocks, function(block) { + items.push({ + text: block[0], + format: block[1], + textStyle: function() { + return getPreviewCss(editor, block[1]); + } + }); + }); + + return Factory.create('listbox', Tools.extend({ + text: blocks[0][0], + menu: items, + onclick: toggleFormat + }, settings)); + }); + + Factory.add('fontselect', function(settings) { + var items = [], fonts = createFormats( + 'Andale Mono=andale mono,times;' + + 'Arial=arial,helvetica,sans-serif;' + + 'Arial Black=arial black,avant garde;' + + 'Book Antiqua=book antiqua,palatino;' + + 'Comic Sans MS=comic sans ms,sans-serif;' + + 'Courier New=courier new,courier;' + + 'Georgia=georgia,palatino;' + + 'Helvetica=helvetica;' + + 'Impact=impact,chicago;' + + 'Symbol=symbol;' + + 'Tahoma=tahoma,arial,helvetica,sans-serif;' + + 'Terminal=terminal,monaco;' + + 'Times New Roman=times new roman,times;' + + 'Trebuchet MS=trebuchet ms,geneva;' + + 'Verdana=verdana,geneva;' + + 'Webdings=webdings;' + + 'Wingdings=wingdings,zapf dingbats' + ); + + each(fonts, function(font) { + items.push({ + text: font[0], + format: font[1], + style: font[1].indexOf('dings') == -1 ? 'font-family:' + font[1] : '' + }); + }); + + return Factory.create('listbox', Tools.extend({ + text: 'Font Family', + menu: items, + onclick: function(e) { + if (e.control.settings.format) { + EditorManager.activeEditor.execCommand('FontName', false, e.control.settings.format); + } + } + }, settings)); + }); + + Factory.add('fontsizeselect', function(settings) { + var items = []; + + each('8pt 10pt 12pt 14pt 18pt 24pt 36pt'.split(' '), function(item) { + items.push({text: item, format: item}); + }); + + return Factory.create('listbox', Tools.extend({ + text: 'Font Sizes', + menu: items, + onclick: function(e) { + if (e.control.settings.format) { + EditorManager.activeEditor.execCommand('FontSize', false, e.control.settings.format); + } + } + }, settings)); + }); + + editor.addMenuItem('formats', { + text: 'Formats', + menu: formatMenu + }); + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/GridLayout.js b/lib/tinymce/jscripts/tinymce4/classes/ui/GridLayout.js new file mode 100644 index 00000000..86efc2ef --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/GridLayout.js @@ -0,0 +1,201 @@ +/** + * GridLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.GridLayout + * @extends tinymce.ui.AbsoluteLayout + */ +define("tinymce/ui/GridLayout", [ + "tinymce/ui/AbsoluteLayout" +], function(AbsoluteLayout) { + "use strict"; + + return AbsoluteLayout.extend({ + recalc: function(container) { + var settings = container.settings, rows, cols, items, contLayoutRect, width, height, rect, + ctrlLayoutRect, ctrl, x, y, posX, posY, ctrlSettings, contPaddingBox, align, spacingH, spacingV, alignH, alignV, maxX, maxY, + colWidths = [], rowHeights = [], ctrlMinWidth, ctrlMinHeight, alignX, alignY, availableWidth, availableHeight; + + // Get layout settings + settings = container.settings; + items = container.items().filter(':visible'); + contLayoutRect = container.layoutRect(); + cols = settings.columns || Math.ceil(Math.sqrt(items.length)); + rows = Math.ceil(items.length / cols); + spacingH = settings.spacingH || settings.spacing || 0; + spacingV = settings.spacingV || settings.spacing || 0; + alignH = settings.alignH || settings.align; + alignV = settings.alignV || settings.align; + contPaddingBox = container._paddingBox; + + // Zero padd columnWidths + for (x = 0; x < cols; x++) { + colWidths.push(0); + } + + // Zero padd rowHeights + for (y = 0; y < rows; y++) { + rowHeights.push(0); + } + + // Calculate columnWidths and rowHeights + for (y = 0; y < rows; y++) { + for (x = 0; x < cols; x++) { + ctrl = items[y * cols + x]; + + // Out of bounds + if (!ctrl) { + break; + } + + ctrlLayoutRect = ctrl.layoutRect(); + ctrlMinWidth = ctrlLayoutRect.minW; + ctrlMinHeight = ctrlLayoutRect.minH; + + colWidths[x] = ctrlMinWidth > colWidths[x] ? ctrlMinWidth : colWidths[x]; + rowHeights[y] = ctrlMinHeight > rowHeights[y] ? ctrlMinHeight : rowHeights[y]; + } + } + + // Calculate maxX + availableWidth = contLayoutRect.innerW - contPaddingBox.left - contPaddingBox.right; + for (maxX = 0, x = 0; x < cols; x++) { + maxX += colWidths[x] + (x > 0 ? spacingH : 0); + availableWidth -= (x > 0 ? spacingH : 0) + colWidths[x]; + } + + // Calculate maxY + availableHeight = contLayoutRect.innerH - contPaddingBox.top - contPaddingBox.bottom; + for (maxY = 0, y = 0; y < rows; y++) { + maxY += rowHeights[y] + (y > 0 ? spacingV : 0); + availableHeight -= (y > 0 ? spacingV : 0) + rowHeights[y]; + } + + maxX += contPaddingBox.left + contPaddingBox.right; + maxY += contPaddingBox.top + contPaddingBox.bottom; + + // Calculate minW/minH + rect = {}; + rect.minW = maxX + (contLayoutRect.w - contLayoutRect.innerW); + rect.minH = maxY + (contLayoutRect.h - contLayoutRect.innerH); + + rect.contentW = rect.minW - contLayoutRect.deltaW; + rect.contentH = rect.minH - contLayoutRect.deltaH; + rect.minW = Math.min(rect.minW, contLayoutRect.maxW); + rect.minH = Math.min(rect.minH, contLayoutRect.maxH); + rect.minW = Math.max(rect.minW, contLayoutRect.startMinWidth); + rect.minH = Math.max(rect.minH, contLayoutRect.startMinHeight); + + // Resize container container if minSize was changed + if (contLayoutRect.autoResize && (rect.minW != contLayoutRect.minW || rect.minH != contLayoutRect.minH)) { + rect.w = rect.minW; + rect.h = rect.minH; + + container.layoutRect(rect); + this.recalc(container); + + // Forced recalc for example if items are hidden/shown + if (container._lastRect === null) { + var parentCtrl = container.parent(); + if (parentCtrl) { + parentCtrl._lastRect = null; + parentCtrl.recalc(); + } + } + + return; + } + + // Update contentW/contentH so absEnd moves correctly + if (contLayoutRect.autoResize) { + rect = container.layoutRect(rect); + rect.contentW = rect.minW - contLayoutRect.deltaW; + rect.contentH = rect.minH - contLayoutRect.deltaH; + } + + var flexV; + + if (settings.packV == 'start') { + flexV = 0; + } else { + flexV = availableHeight > 0 ? Math.floor(availableHeight / rows) : 0; + } + + // Calculate totalFlex + var totalFlex = 0; + var flexWidths = settings.flexWidths; + if (flexWidths) { + for (x = 0; x < flexWidths.length; x++) { + totalFlex += flexWidths[x]; + } + } else { + totalFlex = cols; + } + + // Calculate new column widths based on flex values + var ratio = availableWidth / totalFlex; + for (x = 0; x < cols; x++) { + colWidths[x] += flexWidths ? Math.ceil(flexWidths[x] * ratio) : ratio; + } + + // Move/resize controls + posY = contPaddingBox.top; + for (y = 0; y < rows; y++) { + posX = contPaddingBox.left; + height = rowHeights[y] + flexV; + + for (x = 0; x < cols; x++) { + ctrl = items[y * cols + x]; + + // No more controls to render then break + if (!ctrl) { + break; + } + + // Get control settings and calculate x, y + ctrlSettings = ctrl.settings; + ctrlLayoutRect = ctrl.layoutRect(); + width = colWidths[x]; + alignX = alignY = 0; + ctrlLayoutRect.x = posX; + ctrlLayoutRect.y = posY; + + // Align control horizontal + align = ctrlSettings.alignH || alignH; + if (align == "center") { + ctrlLayoutRect.x = posX + (width / 2) - (ctrlLayoutRect.w / 2); + } else if (align == "right") { + ctrlLayoutRect.x = posX + width - ctrlLayoutRect.w; + } else if (align == "stretch") { + ctrlLayoutRect.w = width; + } + + // Align control vertical + align = ctrlSettings.alignV || alignV; + if (align == "center") { + ctrlLayoutRect.y = posY + (height / 2) - (ctrlLayoutRect.h / 2); + } else if (align == "bottom") { + ctrlLayoutRect.y = posY + height - ctrlLayoutRect.h; + } else if (align == "stretch") { + ctrlLayoutRect.h = height; + } + + ctrl.layoutRect(ctrlLayoutRect); + + posX += width + spacingH; + + if (ctrl.recalc) { + ctrl.recalc(); + } + } + + posY += height + spacingV; + } + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Iframe.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Iframe.js new file mode 100644 index 00000000..9008aaae --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Iframe.js @@ -0,0 +1,43 @@ +/** + * Iframe.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/*jshint scripturl:true */ + +/** + * .. + * + * @-x-less Iframe.less + * @class tinymce.ui.Iframe + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/Iframe", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + renderHtml: function() { + var self = this; + + self.addClass('iframe'); + self.canFocus = false; + + return ( + '' + ); + }, + + src: function(src) { + this.getEl().src = src; + }, + + html: function(html) { + this.getEl().contentWindow.document.body.innerHTML = html; + return this; + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/KeyboardNavigation.js b/lib/tinymce/jscripts/tinymce4/classes/ui/KeyboardNavigation.js new file mode 100644 index 00000000..147ba054 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/KeyboardNavigation.js @@ -0,0 +1,302 @@ +/** + * KeyboardFocus.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.KeyboardNavigation + */ +define("tinymce/ui/KeyboardNavigation", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + /** + * Create a new KeyboardNavigation instance to handle the focus for a specific element. + * + * @constructor + * @method KeyboardNavigation + * @param {Object} settings the settings object to define how keyboard navigation works. + * + * @setting {tinymce.ui.Control} root the root control navigation focus movement is scoped to this root. + * @setting {Array} items an array containing the items to move focus between. Every object in this array must have an + * id attribute which maps to the actual DOM element and it must be able to have focus i.e. tabIndex=-1. + * @setting {Function} onCancel the callback for when the user presses escape or otherwise indicates cancelling. + * @setting {Function} onAction (optional) the action handler to call when the user activates an item. + * @setting {Boolean} enableLeftRight (optional, default) when true, the up/down arrows move through items. + * @setting {Boolean} enableUpDown (optional) when true, the up/down arrows move through items. + * Note for both up/down and left/right explicitly set both enableLeftRight and enableUpDown to true. + */ + return function(settings) { + var root = settings.root, enableUpDown = settings.enableUpDown !== false; + var enableLeftRight = settings.enableLeftRight !== false; + var items = settings.items, focussedId; + + /** + * Initializes the items array if needed. This will collect items/elements + * from the specified root control. + */ + function initItems() { + if (!items) { + items = []; + + if (root.find) { + // Root is a container then get child elements using the UI API + root.find('*').each(function(ctrl) { + if (ctrl.canFocus) { + items.push(ctrl.getEl()); + } + }); + } else { + // Root is a control/widget then get the child elements of that control + var elements = root.getEl().getElementsByTagName('*'); + for (var i = 0; i < elements.length; i++) { + if (elements[i].id && elements[i]) { + items.push(elements[i]); + } + } + } + } + } + + /** + * Returns the currently focused element. + * + * @return {Element} Currently focused element. + */ + function getFocusElement() { + return document.getElementById(focussedId); + } + + /** + * Returns the currently focused elements wai aria role. + * + * @param {Element} elm Optional element to get role from. + * @return {String} Role of specified element. + */ + function getRole(elm) { + elm = elm || getFocusElement(); + + return elm && elm.getAttribute('role'); + } + + /** + * Returns the role of the parent element. + * + * @param {Element} elm Optional element to get parent role from. + * @return {String} Role of the first parent that has a role. + */ + function getParentRole(elm) { + var role, parent = elm || getFocusElement(); + + while ((parent = parent.parentNode)) { + if ((role = getRole(parent))) { + return role; + } + } + } + + /** + * Returns an wai aria property by name. + * + * @param {String} name Name of the aria property to get for example "disabled". + * @return {String} Aria property value. + */ + function getAriaProp(name) { + var elm = document.getElementById(focussedId); + + if (elm) { + return elm.getAttribute('aria-' + name); + } + } + + /** + * Executes the onAction event callback. This is when the user presses enter/space. + */ + function action() { + var focusElm = getFocusElement(); + + if (focusElm && (focusElm.nodeName == "TEXTAREA" || focusElm.type == "text")) { + return; + } + + if (settings.onAction) { + settings.onAction(focussedId); + } else { + DomUtils.fire(getFocusElement(), 'click', {keyboard: true}); + } + + return true; + } + + /** + * Cancels the current navigation. The same as pressing the Esc key. + */ + function cancel() { + var focusElm; + + if (settings.onCancel) { + if ((focusElm = getFocusElement())) { + focusElm.blur(); + } + + settings.onCancel(); + } else { + settings.root.fire('cancel'); + } + } + + /** + * Moves the focus to the next or previous item. It will wrap to start/end if it can't move. + * + * @param {Number} dir Direction for move -1 or 1. + */ + function moveFocus(dir) { + var idx = -1, focusElm, i; + + initItems(); + + i = items.length; + while (i--) { + if (items[i].id === focussedId) { + idx = i; + break; + } + } + + idx += dir; + if (idx < 0) { + idx = items.length - 1; + } else if (idx >= items.length) { + idx = 0; + } + + focusElm = items[idx]; + focusElm.focus(); + focussedId = focusElm.id; + + if (settings.actOnFocus) { + action(); + } + } + + /** + * Moves focus to the first item or the last focused item if root is a toolbar. + * + * @return {[type]} [description] + */ + function focusFirst() { + var i, rootRole; + + rootRole = getRole(settings.root.getEl()); + initItems(); + + i = items.length; + while (i--) { + if (rootRole == 'toolbar' && items[i].id === focussedId) { + items[i].focus(); + return; + } + } + + items[0].focus(); + } + + // Handle accessible keys + root.on('keydown', function(e) { + var DOM_VK_LEFT = 37, DOM_VK_RIGHT = 39, DOM_VK_UP = 38, DOM_VK_DOWN = 40; + var DOM_VK_ESCAPE = 27, DOM_VK_ENTER = 14, DOM_VK_RETURN = 13, DOM_VK_SPACE = 32, DOM_VK_TAB = 9; + var preventDefault; + + switch (e.keyCode) { + case DOM_VK_LEFT: + if (enableLeftRight) { + if (settings.leftAction) { + settings.leftAction(); + } else { + moveFocus(-1); + } + + preventDefault = true; + } + break; + + case DOM_VK_RIGHT: + if (enableLeftRight) { + if (getRole() == 'menuitem' && getParentRole() == 'menu') { + if (getAriaProp('haspopup')) { + action(); + } + } else { + moveFocus(1); + } + + preventDefault = true; + } + break; + + case DOM_VK_UP: + if (enableUpDown) { + moveFocus(-1); + preventDefault = true; + } + break; + + case DOM_VK_DOWN: + if (enableUpDown) { + if (getRole() == 'menuitem' && getParentRole() == 'menubar') { + action(); + } else if (getRole() == 'button' && getAriaProp('haspopup')) { + action(); + } else { + moveFocus(1); + } + + preventDefault = true; + } + break; + + case DOM_VK_TAB: + preventDefault = true; + + if (e.shiftKey) { + moveFocus(-1); + } else { + moveFocus(1); + } + break; + + case DOM_VK_ESCAPE: + preventDefault = true; + cancel(); + break; + + case DOM_VK_ENTER: + case DOM_VK_RETURN: + case DOM_VK_SPACE: + preventDefault = action(); + break; + } + + if (preventDefault) { + e.stopPropagation(); + e.preventDefault(); + } + }); + + // Init on focus in + root.on('focusin', function(e) { + initItems(); + focussedId = e.target.id; + }); + + return { + moveFocus: moveFocus, + focusFirst: focusFirst, + cancel: cancel + }; + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Label.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Label.js new file mode 100644 index 00000000..b5d76d4b --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Label.js @@ -0,0 +1,102 @@ +/** + * Label.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Label.less + * @class tinymce.ui.Label + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Label", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('widget'); + self.addClass('label'); + + if (settings.multiline) { + self.addClass('autoscroll'); + } + + if (settings.strong) { + self.addClass('strong'); + } + }, + + initLayoutRect: function() { + var self = this, layoutRect = self._super(); + + if (self.settings.multiline) { + // Check if the text fits within maxW if not then try word wrapping it + if (self.getEl().offsetWidth > layoutRect.maxW) { + layoutRect.minW = layoutRect.maxW; + self.addClass('multiline'); + } + + self.getEl().style.width = layoutRect.minW + 'px'; + layoutRect.startMinH = layoutRect.h = layoutRect.minH = Math.min(layoutRect.maxH, self.getEl().offsetHeight); + } + + return layoutRect; + }, + + disabled: function(state) { + var self = this, undef; + + if (state !== undef) { + self.toggleClass('label-disabled', state); + + if (self._rendered) { + self.getEl()[0].className = self.classes(); + } + } + + return self._super(state); + }, + + repaint: function() { + var self = this; + + if (!self.settings.multiline) { + self.getEl().style.lineHeight = self.layoutRect().h + 'px'; + } + + return self._super(); + }, + + text: function(text) { + var self = this; + + if (self._rendered && text) { + self.getEl().innerHTML = self.encode(text); + } + + return self._super(text); + }, + + /** + * ... + * + * @method render + */ + renderHtml: function() { + var self = this, forId = self.settings.forId; + + return ( + '' + ); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Layout.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Layout.js new file mode 100644 index 00000000..44b8ea78 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Layout.js @@ -0,0 +1,75 @@ +/** + * Layout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Base layout manager class. + * + * @class tinymce.ui.Layout + */ +define("tinymce/ui/Layout", [ + "tinymce/util/Class", + "tinymce/util/Tools" +], function(Class, Tools) { + "use strict"; + + return Class.extend({ + Defaults: { + firstControlClass: 'first', + lastControlClass: 'last' + }, + + init: function(settings) { + this.settings = Tools.extend({}, this.Defaults, settings); + }, + + preRender: function(container) { + container.addClass(this.settings.containerClass, 'body'); + }, + + applyClasses: function(container) { + var self = this, settings = self.settings, items, firstClass, lastClass; + + items = container.items().filter(':visible'); + firstClass = settings.firstControlClass; + lastClass = settings.lastControlClass; + + items.each(function(item) { + item.removeClass(firstClass).removeClass(lastClass); + + if (settings.controlClass) { + item.addClass(settings.controlClass); + } + }); + + items.eq(0).addClass(firstClass); + items.eq(-1).addClass(lastClass); + }, + + renderHtml: function(container) { + var self = this, settings = self.settings, items, html = ''; + + items = container.items(); + items.eq(0).addClass(settings.firstControlClass); + items.eq(-1).addClass(settings.lastControlClass); + + items.each(function(item) { + if (settings.controlClass) { + item.addClass(settings.controlClass); + } + + html += item.renderHtml(); + }); + + return html; + }, + + recalc: function() { + }, + + postRender: function() { + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/ListBox.js b/lib/tinymce/jscripts/tinymce4/classes/ui/ListBox.js new file mode 100644 index 00000000..4eb6c25a --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/ListBox.js @@ -0,0 +1,84 @@ +/** + * ListBox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ListBox.less + * @class tinymce.ui.ListBox + * @extends tinymce.ui.MenuButton + */ +define("tinymce/ui/ListBox", [ + "tinymce/ui/MenuButton" +], function(MenuButton) { + "use strict"; + + return MenuButton.extend({ + init: function(settings) { + var self = this, values, i, selected, selectedText; + + self._values = values = settings.values; + if (values) { + for (i = 0; i < values.length; i++) { + selected = values[i].selected || settings.value === values[i].value; + + if (selected) { + selectedText = selectedText || values[i].text; + self._value = values[i].value; + } + } + + settings.menu = values; + } + + settings.text = settings.text || selectedText || values[0].text; + + self._super(settings); + self.addClass('listbox'); + + self.on('select', function(e) { + if (settings.multiple) { + e.control.active(!e.control.active()); + } else { + self.value(e.control.settings.value); + } + }); + }, + + value: function(value) { + var self = this, active, selectedText, menu, i; + + if (typeof(value) != "undefined") { + if (self.menu) { + self.menu.items().each(function(ctrl) { + active = ctrl.value() === value; + + if (active) { + selectedText = selectedText || ctrl.text(); + } + + ctrl.active(active); + }); + } else { + menu = self.settings.menu; + for (i = 0; i < menu.length; i++) { + active = menu[i].value == value; + + if (active) { + selectedText = selectedText || menu[i].text; + } + + menu[i].active = active; + } + } + + self.text(selectedText); + } + + return self._super(value); + } + }); +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Menu.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Menu.js new file mode 100644 index 00000000..e4f60c16 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Menu.js @@ -0,0 +1,99 @@ +/** + * Menu.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Menu.less + * @class tinymce.ui.Menu + * @extends tinymce.ui.FloatPanel + */ +define("tinymce/ui/Menu", [ + "tinymce/ui/FloatPanel", + "tinymce/ui/KeyboardNavigation", + "tinymce/ui/MenuItem" +], function(FloatPanel, KeyboardNavigation, MenuItem) { + "use strict"; + + var Menu = FloatPanel.extend({ + Defaults: { + defaultType: 'menuitem', + border: 1, + layout: 'stack', + role: 'menu' + }, + + init: function(settings) { + var self = this; + + settings.autohide = true; + + self._super(settings); + self.addClass('menu'); + + self.keyNav = new KeyboardNavigation({ + root: self, + enableUpDown: true, + enableLeftRight: true, + + leftAction: function() { + if (self.parent() instanceof MenuItem) { + self.keyNav.cancel(); + } + }, + + onCancel: function() { + self.fire('cancel', {}, false); + self.hide(); + } + }); + }, + + repaint: function() { + this.toggleClass('menu-align', true); + + this._super(); + + this.getEl().style.height = ''; + this.getEl('body').style.height = ''; + + return this; + }, + + cancel: function() { + var self = this; + + self.hideAll(); + self.fire('cancel'); + self.fire('select'); + }, + + hideAll: function() { + var self = this; + + this.find('menuitem').exec('hideMenu'); + + return self._super(); + }, + + preRender: function() { + var self = this; + + self.items().each(function(ctrl) { + var settings = ctrl.settings; + + if (settings.icon || settings.selectable) { + self._hasIcons = true; + return false; + } + }); + + return self._super(); + } + }); + + return Menu; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/MenuBar.js b/lib/tinymce/jscripts/tinymce4/classes/ui/MenuBar.js new file mode 100644 index 00000000..6d666a2c --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/MenuBar.js @@ -0,0 +1,28 @@ +/** + * MenuBar.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less MenuBar.less + * @class tinymce.ui.MenuBar + * @extends tinymce.ui.Container + */ +define("tinymce/ui/MenuBar", [ + "tinymce/ui/Toolbar" +], function(Toolbar) { + "use strict"; + + return Toolbar.extend({ + Defaults: { + role: 'menubar', + containerCls: 'menubar', + defaults: { + type: 'menubutton' + } + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/MenuButton.js b/lib/tinymce/jscripts/tinymce4/classes/ui/MenuButton.js new file mode 100644 index 00000000..fa0171b1 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/MenuButton.js @@ -0,0 +1,183 @@ +/** + * MenuButton.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less MenuButton.less + * @class tinymce.ui.MenuButton + * @extends tinymce.ui.Button + */ +define("tinymce/ui/MenuButton", [ + "tinymce/ui/Button", + "tinymce/ui/Factory", + "tinymce/ui/MenuBar" +], function(Button, Factory, MenuBar) { + "use strict"; + + // TODO: Maybe add as some global function + function isChildOf(node, parent) { + while (node) { + if (parent === node) { + return true; + } + + node = node.parentNode; + } + + return false; + } + + var MenuButton = Button.extend({ + init: function(settings) { + var self = this; + + self._renderOpen = true; + self._super(settings); + + self.addClass('menubtn'); + + self.aria('haspopup', true); + self.hasPopup = true; + }, + + showMenu: function() { + var self = this, settings = self.settings, menu; + + if (!self.menu) { + menu = settings.menu || []; + + // Is menu array then auto constuct menu control + if (menu.length) { + menu = { + type: 'menu', + items: menu + }; + } else { + menu.type = menu.type || 'menu'; + } + + self.menu = Factory.create(menu).parent(self).renderTo(self.getContainerElm()); + self.fire('createmenu'); + self.menu.reflow(); + self.menu.on('cancel', function(e) { + if (e.control === self.menu) { + self.focus(); + } + }); + + self.menu.on('show hide', function(e) { + if (e.control == self.menu) { + self.activeMenu(e.type == 'show'); + } + }).fire('show'); + + self.aria('expanded', true); + } + + self.menu.show(); + self.menu.layoutRect({w: self.layoutRect().w}); + self.menu.moveRel(self.getEl(), 'bl-tl'); + }, + + hideMenu: function() { + var self = this; + + if (self.menu) { + self.menu.items().each(function(item) { + if (item.hideMenu) { + item.hideMenu(); + } + }); + + self.menu.hide(); + self.aria('expanded', false); + } + }, + + activeMenu: function(state) { + this.toggleClass('active', state); + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; + + self.aria('role', self.parent() instanceof MenuBar ? 'menuitem' : 'button'); + + return ( + '
    ' + + '' + + '
    ' + ); + }, + + postRender: function() { + var self = this; + + self.on('click', function(e) { + if (e.control === self && isChildOf(e.target, self.getEl())) { + self.showMenu(); + + if (e.keyboard) { + self.menu.items()[0].focus(); + } + } + }); + + self.on('mouseenter', function(e) { + var overCtrl = e.control, parent = self.parent(), hasVisibleSiblingMenu; + + if (overCtrl && parent && overCtrl instanceof MenuButton && overCtrl.parent() == parent) { + parent.items().filter('MenuButton').each(function(ctrl) { + if (ctrl.hideMenu && ctrl != overCtrl) { + if (ctrl.menu && ctrl.menu.visible()) { + hasVisibleSiblingMenu = true; + } + + ctrl.hideMenu(); + } + }); + + if (hasVisibleSiblingMenu) { + overCtrl.showMenu(); + } + } + }); + + return self._super(); + }, + + text: function(text) { + var self = this, i, children; + + if (self._rendered) { + children = self.getEl('open').childNodes; + for (i = 0; i < children.length; i++) { + if (children[i].nodeType == 3) { + children[i].data = text; + } + } + } + + return this._super(text); + }, + + remove: function() { + this._super(); + + if (this.menu) { + this.menu.remove(); + } + } + }); + + return MenuButton; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/MenuItem.js b/lib/tinymce/jscripts/tinymce4/classes/ui/MenuItem.js new file mode 100644 index 00000000..46c69a88 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/MenuItem.js @@ -0,0 +1,198 @@ +/** + * MenuItem.js + * + * Copyright 2003-2013, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less MenuItem.less + * @class tinymce.ui.MenuItem + * @extends tinymce.ui.Control + */ +define("tinymce/ui/MenuItem", [ + "tinymce/ui/Widget", + "tinymce/ui/Factory" +], function(Widget, Factory) { + "use strict"; + + return Widget.extend({ + Defaults: { + border: 0, + role: 'menuitem' + }, + + init: function(settings) { + var self = this; + + self.hasPopup = true; + + self._super(settings); + + settings = self.settings; + + self.addClass('menu-item'); + + if (settings.menu) { + self.addClass('menu-item-expand'); + } + + if (self._text === '-' || self._text === '|') { + self.addClass('menu-item-sep'); + self.aria('role', 'separator'); + self.canFocus = false; + self._text = '-'; + } + + if (settings.selectable) { + self.aria('role', 'menuitemcheckbox'); + self.aria('checked', true); + self.addClass('menu-item-checkbox'); + settings.icon = 'selected'; + } + + self.on('mousedown', function(e) { + e.preventDefault(); + }); + + self.on('mouseenter click', function(e) { + if (e.control === self) { + if (!settings.menu && e.type === 'click') { + self.parent().hideAll(); + self.fire('cancel'); + self.fire('select'); + } else { + self.showMenu(); + + if (e.keyboard) { + setTimeout(function() { + self.menu.items()[0].focus(); + }, 0); + } + } + } + }); + + if (settings.menu) { + self.aria('haspopup', true); + } + }, + + hasMenus: function() { + return !!this.settings.menu; + }, + + showMenu: function() { + var self = this, settings = self.settings, menu; + + self.parent().items().each(function(ctrl) { + if (ctrl !== self) { + ctrl.hideMenu(); + } + }); + + if (settings.menu) { + if (!self.menu) { + menu = settings.menu; + + // Is menu array then auto constuct menu control + if (menu.length) { + menu = { + type: 'menu', + items: menu + }; + } else { + menu.type = menu.type || 'menu'; + } + + self.menu = Factory.create(menu).parent(self).renderTo(self.getContainerElm()); + self.menu.reflow(); + self.menu.fire('show'); + self.menu.on('cancel', function() { + self.focus(); + }); + + self.menu.on('hide', function(e) { + if (e.control === self.menu) { + self.removeClass('selected'); + } + }); + } else { + self.menu.show(); + } + + self.menu._parentMenu = self.parent(); + + self.menu.addClass('menu-sub'); + self.menu.moveRel(self.getEl(), 'tr-tl'); + self.addClass('selected'); + self.aria('expanded', true); + } + }, + + hideMenu: function() { + var self = this; + + if (self.menu) { + self.menu.items().each(function(item) { + if (item.hideMenu) { + item.hideMenu(); + } + }); + + self.menu.hide(); + self.aria('expanded', false); + } + + return self; + }, + + renderHtml: function() { + var self = this, id = self._id, settings = self.settings, prefix = self.classPrefix, text = self.encode(self._text); + var icon = self.settings.icon; + + if (icon) { + self.parent().addClass('menu-has-icons'); + } + + icon = prefix + 'ico ' + prefix + 'i-' + (self.settings.icon || 'none'); + + return ( + '
    ' + + (text !== '-' ? ' ' : '') + + (text !== '-' ? '' + text + '' : '') + + (settings.shortcut ? '
    ' + + settings.shortcut + '
    ' : '') + + (settings.menu ? '
    ' : '') + + '
    ' + ); + }, + + postRender: function() { + var self = this, settings = self.settings; + + var textStyle = settings.textStyle; + if (typeof(textStyle) == "function") { + textStyle = textStyle(); + } + + if (textStyle) { + var textElm = self.getEl('text'); + if (textElm) { + textElm.setAttribute('style', textStyle); + } + } + + return self._super(); + }, + + remove: function() { + this._super(); + + if (this.menu) { + this.menu.remove(); + } + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/MessageBox.js b/lib/tinymce/jscripts/tinymce4/classes/ui/MessageBox.js new file mode 100644 index 00000000..947876b7 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/MessageBox.js @@ -0,0 +1,135 @@ +/** + * MessageBox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.Window + * @extends tinymce.ui.FloatPanel + */ +define("tinymce/ui/MessageBox", [ + "tinymce/ui/Window" +], function(Window) { + "use strict"; + + var MessageBox = Window.extend({ + init: function(settings) { + settings = { + border: 1, + padding: 20, + layout: 'flex', + pack: "center", + align: "center", + containerCls: 'panel', + autoScroll: true, + buttons: {type: "button", text: "Ok", action: "ok"}, + items: { + type: "label", + multiline: true, + maxWidth: 500, + maxHeight: 200 + } + }; + + this._super(settings); + }, + + Statics: { + OK: 1, + OK_CANCEL: 2, + YES_NO: 3, + YES_NO_CANCEL: 4, + + msgBox: function(settings) { + var buttons, callback = settings.callback || function() {}; + + switch (settings.buttons) { + case MessageBox.OK_CANCEL: + buttons = [ + {type: "button", text: "Ok", subtype: "primary", onClick: function(e) { + e.control.parents()[1].close(); + callback(true); + }}, + + {type: "button", text: "Cancel", onClick: function(e) { + e.control.parents()[1].close(); + callback(false); + }} + ]; + break; + + case MessageBox.YES_NO: + buttons = [ + {type: "button", text: "Ok", subtype: "primary", onClick: function(e) { + e.control.parents()[1].close(); + callback(true); + }} + ]; + break; + + case MessageBox.YES_NO_CANCEL: + buttons = [ + {type: "button", text: "Ok", subtype: "primary", onClick: function(e) { + e.control.parents()[1].close(); + }} + ]; + break; + + default: + buttons = [ + {type: "button", text: "Ok", subtype: "primary", onClick: function(e) { + e.control.parents()[1].close(); + }} + ]; + break; + } + + return new Window({ + padding: 20, + x: settings.x, + y: settings.y, + minWidth: 300, + minHeight: 100, + layout: "flex", + pack: "center", + align: "center", + buttons: buttons, + title: settings.title, + items: { + type: "label", + multiline: true, + maxWidth: 500, + maxHeight: 200, + text: settings.text + }, + onClose: settings.onClose + }).renderTo(document.body).reflow(); + }, + + alert: function(settings, callback) { + if (typeof(settings) == "string") { + settings = {text: settings}; + } + + settings.callback = callback; + return MessageBox.msgBox(settings); + }, + + confirm: function(settings, callback) { + if (typeof(settings) == "string") { + settings = {text: settings}; + } + + settings.callback = callback; + settings.buttons = MessageBox.OK_CANCEL; + + return MessageBox.msgBox(settings); + } + } + }); + + return MessageBox; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Movable.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Movable.js new file mode 100644 index 00000000..c1c37f25 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Movable.js @@ -0,0 +1,93 @@ +/** + * Movable.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +define("tinymce/ui/Movable", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + return { + moveRel: function(elm, rel) { + var self = this, ctrlElm, pos, x, y, selfW, selfH, targetW, targetH; + + // Get pos of target + pos = DomUtils.getPos(elm); + x = pos.x; + y = pos.y; + + // Get size of self + ctrlElm = self.getEl(); + selfW = ctrlElm.offsetWidth; + selfH = ctrlElm.offsetHeight; + + // Get size of target + targetW = elm.offsetWidth; + targetH = elm.offsetHeight; + + // Parse align string + rel = (rel || '').split(''); + + // Target corners + if (rel[0] === 'b') { + y += targetH; + } + + if (rel[1] === 'r') { + x += targetW; + } + + if (rel[0] === 'c') { + y += Math.round(targetH / 2); + } + + if (rel[1] === 'c') { + x += Math.round(targetW / 2); + } + + // Self corners + if (rel[3] === 'b') { + y -= selfH; + } + + if (rel[4] === 'r') { + x -= selfW; + } + + if (rel[3] === 'c') { + y -= Math.round(selfH / 2); + } + + if (rel[4] === 'c') { + x -= Math.round(selfW / 2); + } + + self.moveTo(x, y); + + return self; + }, + + moveBy: function(dx, dy) { + var self = this, rect = self.layoutRect(); + + self.moveTo(rect.x + dx, rect.y + dy); + + return self; + }, + + moveTo: function(x, y) { + var self = this; + + if (self._rendered) { + self.layoutRect({x: x, y: y}).repaint(); + } else { + self.settings.x = x; + self.settings.y = y; + } + + return self; + } + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Panel.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Panel.js new file mode 100644 index 00000000..af4cd719 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Panel.js @@ -0,0 +1,82 @@ +/** + * Panel.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Panel.less + * @class tinymce.ui.Panel + * @extends tinymce.ui.Container + */ +define("tinymce/ui/Panel", [ + "tinymce/ui/Container", + "tinymce/ui/Scrollable" +], function(Container, Scrollable) { + "use strict"; + + var Panel = Container.extend({ + Defaults: { + layout: 'fit', + containerCls: 'panel' + }, + + Mixins: [Scrollable], + + fromJSON: function(data) { + var self = this; + + for (var name in data) { + self.find('#' + name).value(data[name]); + } + + return self; + }, + + toJSON: function() { + var self = this, data = {}; + + self.find('*').each(function(ctrl) { + var name = ctrl.name(), value = ctrl.value(); + + if (name && typeof(value) != "undefined") { + data[name] = value; + } + }); + + return data; + }, + + renderHtml: function() { + var self = this, layout = self._layout, innerHtml = self.settings.html; + + self.preRender(); + layout.preRender(self); + + if (typeof(innerHtml) == "undefined") { + innerHtml = ( + '
    ' + + layout.renderHtml(self) + + '
    ' + ); + } else { + if (typeof(innerHtml) == 'function') { + innerHtml = innerHtml(); + } + + self._hasBody = false; + } + + return ( + '
    ' + + (self._preBodyHtml || '') + + innerHtml + + '
    ' + ); + } + }); + + return Panel; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/PanelButton.js b/lib/tinymce/jscripts/tinymce4/classes/ui/PanelButton.js new file mode 100644 index 00000000..a7e7b2e6 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/PanelButton.js @@ -0,0 +1,57 @@ +/** + * MenuButton.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.MenuButton + * @extends tinymce.ui.Button + */ +define("tinymce/ui/PanelButton", [ + "tinymce/ui/Button", + "tinymce/ui/FloatPanel" +], function(Button, FloatPanel) { + "use strict"; + + var PanelButton = Button.extend({ + showPanel: function() { + var self = this, settings = self.settings; + + settings.panel.popover = true; + self.active(true); + + if (!self.panel) { + self.panel = new FloatPanel(settings.panel).on('hide', function() { + self.active(false); + }).parent(self).renderTo(self.getContainerElm()).reflow().moveRel(self.getEl(), settings.popoverAlign || 'bc-tc'); + } else { + self.panel.show(); + } + }, + + hidePanel: function() { + var self = this; + + if (self.panel) { + self.panel.hide(); + } + }, + + postRender: function() { + var self = this; + + self.on('click', function(e) { + if (e.control === self) { + self.showPanel(); + } + }); + + return self._super(); + } + }); + + return PanelButton; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Path.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Path.js new file mode 100644 index 00000000..a5be054f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Path.js @@ -0,0 +1,112 @@ +/** + * Path.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Path.less + * @class tinymce.ui.Path + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Path", [ + "tinymce/ui/Control", + "tinymce/ui/KeyboardNavigation" +], function(Control, KeyboardNavigation) { + "use strict"; + + return Control.extend({ + Defaults: { + delimiter: "\u00BB" + }, + + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('path'); + self.canFocus = true; + + self.on('click', function(e) { + var index, target = e.target; + + if ((index = target.getAttribute('data-index'))) { + self.fire('select', {value: self.data()[index], index: index}); + } + }); + }, + + focus: function() { + var self = this; + + self.keyNav = new KeyboardNavigation({ + root: self, + enableLeftRight: true + }); + + self.keyNav.focusFirst(); + + return self; + }, + + data: function(data) { + var self = this; + + if (typeof(data) !== "undefined") { + self._data = data; + self.update(); + + return self; + } + + return self._data; + }, + + update: function() { + var self = this, parts = self._data, i, l, html = '', prefix = self.classPrefix; + + for (i = 0, l = parts.length; i < l; i++) { + html += ( + (i > 0 ? '' : '') + + '
    ' + parts[i].name + '
    ' + ); + } + + self.getEl().innerHTML = html; + }, + + postRender: function() { + var self = this; + + self._super(); + + self.data(self.settings.data); + }, + + repa2int: function() { + var self = this; + + self.getEl('text').style.lineHeight = self.layoutRect().h + 'px'; + + return self._super(); + }, + + /** + * ... + * + * @method render + */ + renderHtml: function() { + var self = this, prefix = self.classPrefix; + + return ( + '
    ' + + '
     
    ' + + '
    ' + ); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Radio.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Radio.js new file mode 100644 index 00000000..84176a9e --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Radio.js @@ -0,0 +1,71 @@ +/** + * Radio.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Radio.less + * @class tinymce.ui.Radio + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/Radio", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + Defaults: { + classes: "radio", + checked: false + }, + + init: function(settings) { + var self = this; + + self._super(settings); + + self.on('click', function(e) { + e.preventDefault(); + + if (!self.disabled() && !self.checked()) { + self.parent().items().filter('radio:checked').exec('checked', false); + self.checked(true); + } + }); + + self.checked(settings.checked); + }, + + checked: function(state) { + var self = this; + + if (typeof state != "undefined") { + if (state) { + self.addClass('checked'); + } else { + self.removeClass('checked'); + } + + self._checked = state; + + return self; + } + + return self._checked; + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + + return ( + '' + ); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/RadioGroup.js b/lib/tinymce/jscripts/tinymce4/classes/ui/RadioGroup.js new file mode 100644 index 00000000..c47a2b8c --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/RadioGroup.js @@ -0,0 +1,19 @@ +/** + * RadioGroup.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.RadioGroup + * @extends tinymce.ui.Container + */ +define("tinymce/ui/RadioGroup", [ + "tinymce/ui/Container" +], function(Container) { + "use strict"; + + return Container.extend({}); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Resizable.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Resizable.js new file mode 100644 index 00000000..c80dd7ea --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Resizable.js @@ -0,0 +1,38 @@ +/** + * Resizable.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +define("tinymce/ui/Resizable", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + return { + resizeToContent: function() { + this._layoutRect.autoResize = true; + this._lastRect = null; + this.reflow(); + }, + + resizeTo: function(w, h) { + // TODO: Fix hack + if (w <= 1 || h <= 1) { + var rect = DomUtils.getWindowSize(); + + w = w <= 1 ? w * rect.w : w; + h = h <= 1 ? h * rect.h : h; + } + + this._layoutRect.autoResize = false; + return this.layoutRect({minW: w, minH: h, w: w, h: h}).reflow(); + }, + + resizeBy: function(dw, dh) { + var self = this, rect = self.layoutRect(); + + return self.resizeTo(rect.w + dw, rect.h + dh); + } + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/ResizeHandle.js b/lib/tinymce/jscripts/tinymce4/classes/ui/ResizeHandle.js new file mode 100644 index 00000000..79187e29 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/ResizeHandle.js @@ -0,0 +1,93 @@ +/** + * ResizeHandle.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ResizeHandle.less + * @class tinymce.ui.ResizeHandle + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/ResizeHandle", [ + "tinymce/ui/Widget", + "tinymce/ui/DragHelper", + "tinymce/ui/DomUtils" +], function(Widget, DragHelper, DomUtils) { + "use strict"; + + return Widget.extend({ + renderHtml: function() { + var self = this, prefix = self.classPrefix; + + self.addClass('resizehandle'); + + if (self.settings.both) { + self.addClass('resizehandle-both'); + } + + self.canFocus = false; + + return ( + '
    ' + ); + }, + + postRender: function() { + var self = this, iframeStartSize, editor = self.settings.editor; + + self._super(); + + function getSize(elm) { + return { + width: elm.clientWidth, + height: elm.clientHeight + }; + } + + function resizeIframe(width, height) { + var containerElm, iframeElm, containerSize, iframeSize, settings = editor.settings; + + containerElm = editor.getContainer(); + iframeElm = editor.getContentAreaContainer().firstChild; + containerSize = getSize(containerElm); + iframeSize = getSize(iframeElm); + + width = Math.max(settings.min_width || 100, width); + height = Math.max(settings.min_height || 100, height); + width = Math.min(settings.max_width || 0xFFFF, width); + height = Math.min(settings.max_height || 0xFFFF, height); + + if (self.settings.both) { + DomUtils.css(containerElm, 'width', width + (containerSize.width - iframeSize.width)); + } + + DomUtils.css(containerElm, 'height', height + (containerSize.height - iframeSize.height)); + + if (self.settings.both) { + DomUtils.css(iframeElm, 'width', width); + } + + DomUtils.css(iframeElm, 'height', height); + + editor.fire('ResizeEditor'); + } + + self.resizeDragHelper = new DragHelper(this._id, { + start: function() { + iframeStartSize = getSize(editor.getContentAreaContainer().firstChild); + }, + + drag: function(evt) { + resizeIframe(iframeStartSize.width + evt.deltaX, iframeStartSize.height + evt.deltaY); + }, + + end: function() { + } + }); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Scrollable.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Scrollable.js new file mode 100644 index 00000000..ec8e226d --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Scrollable.js @@ -0,0 +1,145 @@ +/** + * Scrollable.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Scrollable.less + * @mixin tinymce.ui.Scrollable + */ +define("tinymce/ui/Scrollable", [ + "tinymce/ui/DomUtils", + "tinymce/ui/DragHelper" +], function(DomUtils, DragHelper) { + "use strict"; + + return { + init: function() { + var self = this; + self.on('repaint', self.renderScroll); + }, + + renderScroll: function() { + var self = this, margin = 2; + + function repaintScroll() { + var hasScrollH, hasScrollV, bodyElm; + + function repaintAxis(axisName, posName, sizeName, contentSizeName, hasScroll, ax) { + var containerElm, scrollBarElm, scrollThumbElm; + var containerSize, scrollSize, ratio, rect; + var posNameLower, sizeNameLower; + + scrollBarElm = self.getEl('scroll' + axisName); + if (scrollBarElm) { + posNameLower = posName.toLowerCase(); + sizeNameLower = sizeName.toLowerCase(); + + if (self.getEl('absend')) { + DomUtils.css(self.getEl('absend'), posNameLower, self.layoutRect()[contentSizeName] - 1); + } + + if (!hasScroll) { + DomUtils.css(scrollBarElm, 'display', 'none'); + return; + } + + DomUtils.css(scrollBarElm, 'display', 'block'); + containerElm = self.getEl('body'); + scrollThumbElm = self.getEl('scroll' + axisName + "t"); + containerSize = containerElm["client" + sizeName] - (margin * 2); + containerSize -= hasScrollH && hasScrollV ? scrollBarElm["client" + ax] : 0; + scrollSize = containerElm["scroll" + sizeName]; + ratio = containerSize / scrollSize; + + rect = {}; + rect[posNameLower] = containerElm["offset" + posName] + margin; + rect[sizeNameLower] = containerSize; + DomUtils.css(scrollBarElm, rect); + + rect = {}; + rect[posNameLower] = containerElm["scroll" + posName] * ratio; + rect[sizeNameLower] = containerSize * ratio; + DomUtils.css(scrollThumbElm, rect); + } + } + + bodyElm = self.getEl('body'); + hasScrollH = bodyElm.scrollWidth > bodyElm.clientWidth; + hasScrollV = bodyElm.scrollHeight > bodyElm.clientHeight; + + repaintAxis("h", "Left", "Width", "contentW", hasScrollH, "Height"); + repaintAxis("v", "Top", "Height", "contentH", hasScrollV, "Width"); + } + + function addScroll() { + function addScrollAxis(axisName, posName, sizeName, deltaPosName, ax) { + var scrollStart, axisId = self._id + '-scroll' + axisName, prefix = self.classPrefix; + + self.getEl().appendChild(DomUtils.createFragment( + '
    ' + + '
    ' + + '
    ' + )); + + self.draghelper = new DragHelper(axisId + 't', { + start: function() { + scrollStart = self.getEl('body')["scroll" + posName]; + DomUtils.addClass(DomUtils.get(axisId), prefix + 'active'); + }, + + drag: function(e) { + var ratio, hasScrollH, hasScrollV, containerSize, layoutRect = self.layoutRect(); + + hasScrollH = layoutRect.contentW > layoutRect.innerW; + hasScrollV = layoutRect.contentH > layoutRect.innerH; + containerSize = self.getEl('body')["client" + sizeName] - (margin * 2); + containerSize -= hasScrollH && hasScrollV ? self.getEl('scroll' + axisName)["client" + ax] : 0; + + ratio = containerSize / self.getEl('body')["scroll" + sizeName]; + self.getEl('body')["scroll" + posName] = scrollStart + (e["delta" + deltaPosName] / ratio); + }, + + stop: function() { + DomUtils.removeClass(DomUtils.get(axisId), prefix + 'active'); + } + }); +/* + self.on('click', function(e) { + if (e.target.id == self._id + '-scrollv') { + + } + });*/ + } + + self.addClass('scroll'); + + addScrollAxis("v", "Top", "Height", "Y", "Width"); + addScrollAxis("h", "Left", "Width", "X", "Height"); + } + + if (self.settings.autoScroll) { + if (!self._hasScroll) { + self._hasScroll = true; + addScroll(); + + self.on('wheel', function(e) { + var bodyEl = self.getEl('body'); + + bodyEl.scrollLeft += (e.deltaX || 0) * 10; + bodyEl.scrollTop += e.deltaY * 10; + + repaintScroll(); + }); + + DomUtils.on(self.getEl('body'), "scroll", repaintScroll); + } + + repaintScroll(); + } + } + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Selector.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Selector.js new file mode 100644 index 00000000..c29f039f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Selector.js @@ -0,0 +1,356 @@ +/** + * Selector.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Selector engine, enables you to select controls by using CSS like expressions. + * We currently only support basic CSS expressions to reduce the size of the core + * and the ones we support should be enough for most cases. + * + * Supported expressions: + * element + * element#name + * element.class + * element[attr] + * element[attr*=value] + * element[attr~=value] + * element[attr!=value] + * element[attr^=value] + * element[attr$=value] + * element: + * element:not() + * element:first + * element:last + * element:odd + * element:even + * element element + * element > element + * @class tinymce.ui.Selector + */ +define("tinymce/ui/Selector", [ + "tinymce/util/Class", + "tinymce/util/Tools" +], function(Class, Tools) { + "use strict"; + + /** + * Produces an array with a unique set of objects. It will not compare the values + * but the references of the objects. + * + * @method unqiue + * @param {Array} array Array to make into an array with unique items. + * @return {Array} Array with unique items. + */ + function unique(array) { + var uniqueItems = [], i = array.length, item; + + while (i--) { + item = array[i]; + + if (!item.__checked) { + uniqueItems.push(item); + item.__checked = 1; + } + } + + i = uniqueItems.length; + while (i--) { + delete uniqueItems[i].__checked; + } + + return uniqueItems; + } + + var expression = /^([\w\\*]+)?(?:#([\w\\]+))?(?:\.([\w\\\.]+))?(?:\[\@?([\w\\]+)([\^\$\*!~]?=)([\w\\]+)\])?(?:\:(.+))?/i; + + /*jshint maxlen:255 */ + var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + whiteSpace = /^\s*|\s*$/g, + Collection; + + var Selector = Class.extend({ + /** + * Constructs a new Selector instance. + * + * @contructor + * @method init + * @param {String} selector CSS like selector expression. + */ + init: function(selector) { + var match = this.match; + + function compileNameFilter(name) { + if (name) { + name = name.toLowerCase(); + + return function(item) { + return name === '*' || item.type === name; + }; + } + } + + function compileIdFilter(id) { + if (id) { + return function(item) { + return item._name === id; + }; + } + } + + function compileClassesFilter(classes) { + if (classes) { + classes = classes.split('.'); + + return function(item) { + var i = classes.length; + + while (i--) { + if (!item.hasClass(classes[i])) { + return false; + } + } + + return true; + }; + } + } + + function compileAttrFilter(name, cmp, check) { + if (name) { + return function(item) { + var value = item[name] ? item[name]() : ''; + + return !cmp ? !!check : + cmp === "=" ? value === check : + cmp === "*=" ? value.indexOf(check) >= 0 : + cmp === "~=" ? (" " + value + " ").indexOf(" " + check + " ") >= 0 : + cmp === "!=" ? value != check : + cmp === "^=" ? value.indexOf(check) === 0 : + cmp === "$=" ? value.substr(value.length - check.length) === check : + false; + }; + } + } + + function compilePsuedoFilter(name) { + var notSelectors; + + if (name) { + name = /(?:not\((.+)\))|(.+)/i.exec(name); + + if (!name[1]) { + name = name[2]; + + return function(item, index, length) { + return name === 'first' ? index === 0 : + name === 'last' ? index === length - 1 : + name === 'even' ? index % 2 === 0 : + name === 'odd' ? index % 2 === 1 : + item[name] ? item[name]() : + false; + }; + } else { + // Compile not expression + notSelectors = parseChunks(name[1], []); + + return function(item) { + return !match(item, notSelectors); + }; + } + } + } + + function compile(selector, filters, direct) { + var parts; + + function add(filter) { + if (filter) { + filters.push(filter); + } + } + + // Parse expression into parts + parts = expression.exec(selector.replace(whiteSpace, '')); + + add(compileNameFilter(parts[1])); + add(compileIdFilter(parts[2])); + add(compileClassesFilter(parts[3])); + add(compileAttrFilter(parts[4], parts[5], parts[6])); + add(compilePsuedoFilter(parts[7])); + + // Mark the filter with psuedo for performance + filters.psuedo = !!parts[7]; + filters.direct = direct; + + return filters; + } + + // Parser logic based on Sizzle by John Resig + function parseChunks(selector, selectors) { + var parts = [], extra, matches, i; + + do { + chunker.exec(""); + matches = chunker.exec(selector); + + if (matches) { + selector = matches[3]; + parts.push(matches[1]); + + if (matches[2]) { + extra = matches[3]; + break; + } + } + } while (matches); + + if (extra) { + parseChunks(extra, selectors); + } + + selector = []; + for (i = 0; i < parts.length; i++) { + if (parts[i] != '>') { + selector.push(compile(parts[i], [], parts[i - 1] === '>')); + } + } + + selectors.push(selector); + + return selectors; + } + + this._selectors = parseChunks(selector, []); + }, + + /** + * Returns true/false if the selector matches the specified control. + * + * @method match + * @param {tinymce.ui.Control} control Control to match agains the selector. + * @param {Array} selectors Optional array of selectors, mostly used internally. + * @return {Boolean} true/false state if the control matches or not. + */ + match: function(control, selectors) { + var i, l, si, sl, selector, fi, fl, filters, index, length, siblings, count, item; + + selectors = selectors || this._selectors; + for (i = 0, l = selectors.length; i < l; i++) { + selector = selectors[i]; + sl = selector.length; + item = control; + count = 0; + + for (si = sl - 1; si >= 0; si--) { + filters = selector[si]; + + while (item) { + // Find the index and length since a psuedo filter like :first needs it + if (filters.psuedo) { + siblings = item.parent().items(); + index = Tools.inArray(item, siblings); + length = siblings.length; + } + + for (fi = 0, fl = filters.length; fi < fl; fi++) { + if (!filters[fi](item, index, length)) { + fi = fl + 1; + break; + } + } + + if (fi === fl) { + count++; + break; + } else { + // If it didn't match the right most expression then + // break since it's no point looking at the parents + if (si === sl - 1) { + break; + } + } + + item = item.parent(); + } + } + + // If we found all selectors then return true otherwise continue looking + if (count === sl) { + return true; + } + } + + return false; + }, + + /** + * Returns a tinymce.ui.Collection with matches of the specified selector inside the specified container. + * + * @method find + * @param {tinymce.ui.Control} container Container to look for items in. + * @return {tinymce.ui.Collection} Collection with matched elements. + */ + find: function(container) { + var matches = [], i, l, selectors = this._selectors; + + function collect(items, selector, index) { + var i, l, fi, fl, item, filters = selector[index]; + + for (i = 0, l = items.length; i < l; i++) { + item = items[i]; + + // Run each filter agains the item + for (fi = 0, fl = filters.length; fi < fl; fi++) { + if (!filters[fi](item, i, l)) { + fi = fl + 1; + break; + } + } + + // All filters matched the item + if (fi === fl) { + // Matched item is on the last expession like: panel toolbar [button] + if (index == selector.length - 1) { + matches.push(item); + } else { + // Collect next expession type + if (item.items) { + collect(item.items(), selector, index + 1); + } + } + } else if (filters.direct) { + return; + } + + // Collect child items + if (item.items) { + collect(item.items(), selector, index); + } + } + } + + if (container.items) { + for (i = 0, l = selectors.length; i < l; i++) { + collect(container.items(), selectors[i], 0); + } + + // Unique the matches if needed + if (l > 1) { + matches = unique(matches); + } + } + + // Fix for circular reference + if (!Collection) { + // TODO: Fix me! + Collection = Selector.Collection; + } + + return new Collection(matches); + } + }); + + return Selector; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Spacer.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Spacer.js new file mode 100644 index 00000000..3eb691a7 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Spacer.js @@ -0,0 +1,29 @@ +/** + * Spacer.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Spacer.less + * @class tinymce.ui.Spacer + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/Spacer", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + renderHtml: function() { + var self = this; + + self.addClass('spacer'); + self.canFocus = false; + + return '
    '; + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/SplitButton.js b/lib/tinymce/jscripts/tinymce4/classes/ui/SplitButton.js new file mode 100644 index 00000000..fe73a254 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/SplitButton.js @@ -0,0 +1,92 @@ +/** + * SplitButton.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less SplitButton.less + * @class tinymce.ui.SplitButton + * @extends tinymce.ui.Button + */ +define("tinymce/ui/SplitButton", [ + "tinymce/ui/MenuButton", + "tinymce/dom/DOMUtils" +], function(MenuButton, DomUtils) { + var DOM = DomUtils.DOM; + + return MenuButton.extend({ + Defaults: { + classes: "widget btn splitbtn", + role: "splitbutton" + }, + + repaint: function() { + var self = this, elm = self.getEl(), rect = self.layoutRect(), mainButtonElm, menuButtonElm, btnStyle; + + self._super(); + + mainButtonElm = elm.firstChild; + menuButtonElm = elm.lastChild; + + DOM.css(mainButtonElm, { + width: rect.w - menuButtonElm.offsetWidth, + height: rect.h - 2 + }); + + DOM.css(menuButtonElm, { + height: rect.h - 2 + }); + + btnStyle = mainButtonElm.firstChild.style; + btnStyle.width = btnStyle.height = "100%"; + + btnStyle = menuButtonElm.firstChild.style; + btnStyle.width = btnStyle.height = "100%"; + + return self; + }, + + activeMenu: function(state) { + var self = this; + + DOM.toggleClass(self.getEl().lastChild, self.classPrefix + 'active', state); + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; + + return ( + '
    ' + + '' + + '' + + '
    ' + ); + }, + + postRender: function() { + var self = this, onClickHandler = self.settings.onclick; + + self.on('click', function(e) { + if (e.control == this && !DOM.getParent(e.target, '.' + this.classPrefix + 'open')) { + e.stopImmediatePropagation(); + onClickHandler.call(this, e); + } + }); + + delete self.settings.onclick; + + return self._super(); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/StackLayout.js b/lib/tinymce/jscripts/tinymce4/classes/ui/StackLayout.js new file mode 100644 index 00000000..4e81e57f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/StackLayout.js @@ -0,0 +1,26 @@ +/** + * StackLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less StackLayout.less + * @class tinymce.ui.StackLayout + * @extends tinymce.ui.FlowLayout + */ +define("tinymce/ui/StackLayout", [ + "tinymce/ui/FlowLayout" +], function(FlowLayout) { + "use strict"; + + return FlowLayout.extend({ + Defaults: { + containerClass: 'stack-layout', + controlClass: 'stack-layout-item', + endClass : 'break' + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/TabPanel.js b/lib/tinymce/jscripts/tinymce4/classes/ui/TabPanel.js new file mode 100644 index 00000000..6fdf1697 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/TabPanel.js @@ -0,0 +1,135 @@ +/** + * TabPanel.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less TabPanel.less + * @class tinymce.ui.TabPanel + * @extends tinymce.ui.Panel + */ +define("tinymce/ui/TabPanel", [ + "tinymce/ui/Panel", + "tinymce/ui/DomUtils" +], function(Panel, DomUtils) { + "use stict"; + + return Panel.extend({ + lastIdx: 0, + + Defaults: { + layout: 'absolute', + defaults: { + type: 'panel' + } + }, + + activateTab: function(idx) { + if (this.activeTabId) { + DomUtils.removeClass(this.getEl(this.activeTabId), this.classPrefix + 'active'); + } + + this.activeTabId = 't' + idx; + + DomUtils.addClass(this.getEl('t' + idx), this.classPrefix + 'active'); + + if (idx != this.lastIdx) { + this.items()[this.lastIdx].hide(); + this.lastIdx = idx; + } + + this.items()[idx].show().fire('showtab'); + this.reflow(); + }, + + renderHtml: function() { + var self = this, layout = self._layout, tabsHtml = '', prefix = self.classPrefix; + + self.preRender(); + layout.preRender(self); + + self.items().each(function(ctrl, i) { + tabsHtml += ( + '
    ' + + ctrl.settings.title + + '
    ' + ); + }); + + return ( + '
    ' + + '
    ' + + tabsHtml + + '
    ' + + '
    ' + + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + }, + + postRender: function() { + var self = this; + + self._super(); + + self.settings.activeTab = self.settings.activeTab || 0; + self.activateTab(self.settings.activeTab); + + this.on('click', function(e) { + var targetParent = e.target.parentNode; + + if (e.target.parentNode.id == self._id + '-head') { + var i = targetParent.childNodes.length; + + while (i--) { + if (targetParent.childNodes[i] == e.target) { + self.activateTab(i); + } + } + } + }); + }, + + initLayoutRect: function() { + var self = this, rect, minW, minH; + + minW = minH = 0; + self.items().each(function(item, i) { + minW = Math.max(minW, item.layoutRect().minW); + minH = Math.max(minH, item.layoutRect().minH); + if (self.settings.activeTab != i) { + item.hide(); + } + }); + + self.items().each(function(ctrl) { + ctrl.settings.x = 0; + ctrl.settings.y = 0; + ctrl.settings.w = minW; + ctrl.settings.h = minH; + + ctrl.layoutRect({ + x: 0, + y: 0, + w: minW, + h: minH + }); + }); + + var headH = self.getEl('head').offsetHeight; + + self.settings.minWidth = minW; + self.settings.minHeight = minH + headH; + + rect = self._super(); + rect.deltaH += self.getEl('head').offsetHeight; + rect.innerH = rect.h - rect.deltaH; + + return rect; + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/TextBox.js b/lib/tinymce/jscripts/tinymce4/classes/ui/TextBox.js new file mode 100644 index 00000000..dd55c56c --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/TextBox.js @@ -0,0 +1,150 @@ +/** + * TextBox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less TextBox.less + * @class tinymce.ui.TextBox + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/TextBox", [ + "tinymce/ui/Widget", + "tinymce/ui/DomUtils" +], function(Widget, DomUtils) { + "use strict"; + + return Widget.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + + self._value = settings.value || ''; + self.addClass('textbox'); + + if (settings.multiline) { + self.addClass('multiline'); + } else { + // TODO: Rework this + self.on('keydown', function(e) { + if (e.keyCode == 13) { + self.parents().reverse().each(function(ctrl) { + e.preventDefault(); + + if (ctrl.submit) { + ctrl.submit(); + return false; + } + }); + } + }); + } + }, + + value: function(value) { + var self = this; + + if (typeof(value) != "undefined") { + self._value = value; + + if (self._rendered) { + self.getEl().value = value; + } + + return self; + } + + if (self._rendered) { + return self.getEl().value; + } + + return self._value; + }, + + repaint: function() { + var self = this, style, rect, borderBox, borderW = 0, borderH = 0, lastRepaintRect; + + style = self.getEl().style; + rect = self._layoutRect; + lastRepaintRect = self._lastRepaintRect || {}; + + borderBox = self._borderBox; + borderW = borderBox.left + borderBox.right + 8; + borderH = borderBox.top + borderBox.bottom + (self.settings.multiline ? 8 : 0); + + if (rect.x !== lastRepaintRect.x) { + style.left = rect.x + 'px'; + lastRepaintRect.x = rect.x; + } + + if (rect.y !== lastRepaintRect.y) { + style.top = rect.y + 'px'; + lastRepaintRect.y = rect.y; + } + + if (rect.w !== lastRepaintRect.w) { + style.width = (rect.w - borderW) + 'px'; + lastRepaintRect.w = rect.w; + } + + if (rect.h !== lastRepaintRect.h) { + style.height = (rect.h - borderH) + 'px'; + lastRepaintRect.h = rect.h; + } + + /*if (!self.settings.multiline) { + //style.lineHeight = (rect.h - borderH) + 'px'; + }*/ + + self._lastRepaintRect = lastRepaintRect; + self.fire('repaint', {}, false); + + return self; + }, + + renderHtml: function() { + var self = this, id = self._id, settings = self.settings, value = self.encode(self._value, false), extraAttrs = ''; + + if ("spellcheck" in settings) { + extraAttrs += ' spellcheck="' + settings.spellcheck + '"'; + } + + if (settings.maxLength) { + extraAttrs += ' maxlength="' + settings.maxLength + '"'; + } + + if (settings.size) { + extraAttrs += ' size="' + settings.size + '"'; + } + + if (settings.subtype) { + extraAttrs += ' type="' + settings.subtype + '"'; + } + + if (settings.multiline) { + return ( + '' + ); + } + + return ''; + }, + + postRender: function() { + var self = this; + + DomUtils.on(self.getEl(), 'change', function(e) { + self.fire('change', e); + }); + + return self._super(); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Throbber.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Throbber.js new file mode 100644 index 00000000..f58acb1b --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Throbber.js @@ -0,0 +1,47 @@ +/** + * Throbber.js + * + * Copyright 2003-2013, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Throbber.less + * @class tinymce.ui.Throbber + */ +define("tinymce/ui/Throbber", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + return function(elm) { + var self = this, state; + + self.show = function(time) { + self.hide(); + + state = true; + + window.setTimeout(function() { + if (state) { + elm.appendChild(DomUtils.createFragment('
    ')); + } + }, time || 0); + + return self; + }, + + self.hide = function() { + var child = elm.lastChild; + + if (child && child.className.indexOf('throbber') != -1) { + child.parentNode.removeChild(child); + } + + state = false; + + return self; + }; + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Toolbar.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Toolbar.js new file mode 100644 index 00000000..98846003 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Toolbar.js @@ -0,0 +1,45 @@ +/** + * Toolbar.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.Toolbar + * @extends tinymce.ui.Container + */ +define("tinymce/ui/Toolbar", [ + "tinymce/ui/Container", + "tinymce/ui/KeyboardNavigation" +], function(Container, KeyboardNavigation) { + "use strict"; + + return Container.extend({ + Defaults: { + role: 'toolbar', + layout: 'flow' + }, + + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('toolbar'); + }, + + postRender: function() { + var self = this; + + self.items().addClass('toolbar-item'); + + self.keyNav = new KeyboardNavigation({ + root: self, + enableLeftRight: true + }); + + return self._super(); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Tooltip.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Tooltip.js new file mode 100644 index 00000000..8038d3ae --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Tooltip.js @@ -0,0 +1,63 @@ +/** + * Tooltip.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ToolTip.less + * @class tinymce.ui.ToolTip + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Tooltip", [ + "tinymce/ui/Control", + "tinymce/ui/Movable" +], function(Control, Movable) { + return Control.extend({ + Mixins: [Movable], + + Defaults: { + classes: 'widget tooltip tooltip-n' + }, + + text: function(value) { + var self = this; + + if (typeof(value) != "undefined") { + self._value = value; + + if (self._rendered) { + self.getEl().lastChild.innerHTML = self.encode(value); + } + + return self; + } + + return self._value; + }, + + renderHtml: function() { + var self = this, prefix = self.classPrefix; + + return ( + '' + ); + }, + + repaint: function() { + var self = this, style, rect; + + style = self.getEl().style; + rect = self._layoutRect; + + style.left = rect.x + 'px'; + style.top = rect.y + 'px'; + style.zIndex = 0xFFFF + 0xFFFF; + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Widget.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Widget.js new file mode 100644 index 00000000..80782ac1 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Widget.js @@ -0,0 +1,99 @@ +/** + * Widget.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * + * @class tinymce.ui.Widget + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Widget", [ + "tinymce/ui/Control", + "tinymce/ui/Tooltip" +], function(Control, Tooltip) { + "use strict"; + + var tooltip; + + return Control.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + self.canFocus = true; + + if (settings.tooltip) { + self.on('mouseenter mouseleave', function(e) { + if (e.control == self && e.type == 'mouseenter') { + self.tooltip().moveTo(-0xFFFF).text(settings.tooltip).show().moveRel(self.getEl(), 'bc tc'); + } else { + self.tooltip().moveTo(-0xFFFF).hide(); + } + }); + } + + self.aria('label', settings.tooltip); + }, + + tooltip: function() { + var self = this; + + if (!tooltip) { + tooltip = new Tooltip({type: 'tooltip'}); + tooltip.renderTo(self.getContainerElm()); + } + + return tooltip; + }, + + active: function(state) { + var self = this, undef; + + if (state !== undef) { + self.aria('pressed', state); + self.toggleClass('active', state); + } + + return self._super(state); + }, + + disabled: function(state) { + var self = this, undef; + + if (state !== undef) { + self.aria('disabled', state); + self.toggleClass('disabled', state); + } + + return self._super(state); + }, + + postRender: function() { + var self = this, settings = self.settings; + + self._rendered = true; + + self._super(); + + if (!self.parent() && (settings.width || settings.height)) { + self.initLayoutRect(); + self.repaint(); + } + + if (settings.autofocus) { + self.focus(); + } + }, + + remove: function() { + this._super(); + + if (tooltip) { + tooltip.remove(); + tooltip = null; + } + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/ui/Window.js b/lib/tinymce/jscripts/tinymce4/classes/ui/Window.js new file mode 100644 index 00000000..483bfe3b --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/ui/Window.js @@ -0,0 +1,384 @@ +/** + * Window.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Window.less + * @class tinymce.ui.Window + * @extends tinymce.ui.FloatPanel + */ +define("tinymce/ui/Window", [ + "tinymce/ui/FloatPanel", + "tinymce/ui/Panel", + "tinymce/ui/DomUtils", + "tinymce/ui/KeyboardNavigation", + "tinymce/ui/DragHelper" +], function(FloatPanel, Panel, DomUtils, KeyboardNavigation, DragHelper) { + "use strict"; + + var Window = FloatPanel.extend({ + modal: true, + + Defaults: { + border: 1, + layout: 'flex', + containerCls: 'panel', + role: 'dialog', + callbacks: { + submit: function() { + this.fire('submit', {data: this.toJSON()}); + }, + + close: function() { + this.close(); + } + } + }, + + init: function(settings) { + var self = this; + + self._super(settings); + + self.addClass('window'); + + // Create statusbar + if (settings.buttons) { + self.statusbar = new Panel({ + layout: 'flex', + border: '1 0 0 0', + spacing: 3, + padding: 10, + align: 'center', + pack: 'end', + defaults: { + type: 'button' + }, + items: settings.buttons + }); + + self.statusbar.addClass('foot'); + self.statusbar.parent(self); + } + + self.on('click', function(e) { + if (e.target.className.indexOf(self.classPrefix + 'close') != -1) { + self.close(); + } + }); +/* + self.on('postrender show', function(e) { + if (e.control == self) { + var parentWin = getTopMostWindow(), zIndex = FloatPanel.zIndex; + + if (parentWin) { + zIndex = parentWin.zIndex; + } + + if (!DomUtils.get(prefix + 'modal-block')) { + var modalBlockEl = DomUtils.createFragment('
    '); + + modalBlockEl = modalBlockEl.firstChild; + + self.getContainerElm().appendChild(modalBlockEl); + + setTimeout(function() { + DomUtils.addClass(modalBlockEl, prefix + 'in'); + DomUtils.addClass(self.getEl(), prefix + 'in'); + }, 0); + + FloatPanel.zOrder.push({zIndex: zIndex}); + DomUtils.css(self.getEl(), 'z-index', zIndex + 1); + } + + DomUtils.css(DomUtils.get(prefix + 'modal-block'), 'z-index', zIndex - 1); + } + }); + + self.on('close hide', function(e) { + if (e.control == self) { + var topWin = getTopMostWindow(); + + if (!topWin) { + var modalBlockEl = document.getElementById(prefix + 'modal-block'); + if (modalBlockEl) { + modalBlockEl.parentNode.removeChild(modalBlockEl); + } + } else { + DomUtils.css(DomUtils.get(prefix + 'modal-block'), 'z-index', topWin.zIndex - 1); + } + } + }); +*/ + self.aria('label', settings.title); + self._fullscreen = false; + }, + + recalc: function() { + var self = this, statusbar = self.statusbar, layoutRect, width, needsRecalc; + + if (self._fullscreen) { + self.layoutRect(DomUtils.getWindowSize()); + self.layoutRect().contentH = self.layoutRect().innerH; + } + + self._super(); + + layoutRect = self.layoutRect(); + + // Resize window based on title width + if (self.settings.title && !self._fullscreen) { + width = layoutRect.headerW; + if (width > layoutRect.minW) { + layoutRect.minW = layoutRect.w = width + (layoutRect.w - layoutRect.innerW); + layoutRect.innerW = layoutRect.w - layoutRect.deltaW; + needsRecalc = true; + } + } + + // Resize window based on statusbar width + if (statusbar) { + statusbar.layoutRect({w: self.layoutRect().innerW}).recalc(); + + width = statusbar.layoutRect().minW + layoutRect.deltaW; + if (width > layoutRect.minW) { + layoutRect.minW = layoutRect.w = width; + layoutRect.innerW = layoutRect.w - layoutRect.deltaW; + needsRecalc = true; + } + } + + // Recalc body and disable auto resize + if (needsRecalc) { + self.recalc(); + return; + } + }, + + initLayoutRect: function() { + var self = this, layoutRect = self._super(), deltaH = 0, headEl; + + // Reserve vertical space for title + if (self.settings.title && !self._fullscreen) { + headEl = self.getEl('head'); + layoutRect.headerW = headEl.offsetWidth; + layoutRect.headerH = headEl.offsetHeight; + deltaH += layoutRect.headerH; + } + + // Reserve vertical space for statusbar + if (self.statusbar) { + deltaH += self.statusbar.layoutRect().h; + } + + layoutRect.deltaH += deltaH; + layoutRect.minH += deltaH; + //layoutRect.innerH -= deltaH; + layoutRect.h += deltaH; + + var rect = DomUtils.getWindowSize(); + + layoutRect.x = Math.max(0, rect.w / 2 - layoutRect.w / 2); + layoutRect.y = Math.max(0, rect.h / 2 - layoutRect.h / 2); + + return layoutRect; + }, + + renderHtml: function() { + var self = this, layout = self._layout, id = self._id, prefix = self.classPrefix; + var settings = self.settings, headerHtml = '', footerHtml = '', html = settings.html; + + self.preRender(); + layout.preRender(self); + + if (settings.title) { + headerHtml = ( + '
    ' + + '
    ' + settings.title + '
    ' + + '' + + '
    ' + + '
    ' + ); + } + + if (settings.url) { + html = ''; + } + + if (typeof(html) == "undefined") { + html = layout.renderHtml(self); + } + + if (self.statusbar) { + footerHtml = self.statusbar.renderHtml(); + } + + return ( + '
    ' + + headerHtml + + '
    ' + + html + + '
    ' + + footerHtml + + '
    ' + ); + }, + + fullscreen: function(state) { + var self = this, documentElement = document.documentElement, slowRendering, prefix = self.classPrefix, layoutRect; + + if (state != self._fullscreen) { + DomUtils.on(window, 'resize', function() { + var time; + + if (self._fullscreen) { + // Time the layout time if it's to slow use a timeout to not hog the CPU + if (!slowRendering) { + time = new Date().getTime(); + + var rect = DomUtils.getWindowSize(); + self.moveTo(0, 0).resizeTo(rect.w, rect.h); + + if ((new Date().getTime()) - time > 50) { + slowRendering = true; + } + } else { + if (!self._timer) { + self._timer = setTimeout(function() { + var rect = DomUtils.getWindowSize(); + self.moveTo(0, 0).resizeTo(rect.w, rect.h); + + self._timer = 0; + }, 50); + } + } + } + }); + + layoutRect = self.layoutRect(); + self._fullscreen = state; + + if (!state) { + self._borderBox = self.parseBox(self.settings.border); + self.getEl('head').style.display = ''; + layoutRect.deltaH += layoutRect.headerH; + DomUtils.removeClass(documentElement, prefix + 'fullscreen'); + DomUtils.removeClass(document.body, prefix + 'fullscreen'); + self.removeClass('fullscreen'); + self.moveTo(self._initial.x, self._initial.y).resizeTo(self._initial.w, self._initial.h); + } else { + self._initial = {x: layoutRect.x, y: layoutRect.y, w: layoutRect.w, h: layoutRect.h}; + + self._borderBox = self.parseBox('0'); + self.getEl('head').style.display = 'none'; + layoutRect.deltaH -= layoutRect.headerH + 2; + DomUtils.addClass(documentElement, prefix + 'fullscreen'); + DomUtils.addClass(document.body, prefix + 'fullscreen'); + self.addClass('fullscreen'); + + var rect = DomUtils.getWindowSize(); + self.moveTo(0, 0).resizeTo(rect.w, rect.h); + } + } + + return self.reflow(); + }, + + postRender: function() { + var self = this, items = [], focusCtrl, autoFocusFound, startPos; + + setTimeout(function() { + self.addClass('in'); + }, 0); + + self.find('*').each(function(ctrl) { + if (ctrl.canFocus) { + autoFocusFound = autoFocusFound || ctrl.settings.autofocus; + focusCtrl = focusCtrl || ctrl; + + // TODO: Figure out a better way + if (ctrl.type == 'filepicker') { + items.push(ctrl.getEl('inp')); + + if (ctrl.getEl('open')) { + items.push(ctrl.getEl('open').firstChild); + } + } else { + items.push(ctrl.getEl()); + } + } + }); + + if (self.statusbar) { + self.statusbar.find('*').each(function(ctrl) { + if (ctrl.canFocus) { + autoFocusFound = autoFocusFound || ctrl.settings.autofocus; + focusCtrl = focusCtrl || ctrl; + items.push(ctrl.getEl()); + } + }); + } + + self.keyboardNavigation = new KeyboardNavigation({ + root: self, + enableLeftRight: false, + enableUpDown: false, + items: items, + onCancel: function() { + self.close(); + } + }); + + self._super(); + + if (self.statusbar) { + self.statusbar.postRender(); + } + + if (!autoFocusFound && focusCtrl) { + focusCtrl.focus(); + } + + this.dragHelger = new DragHelper(self._id + '-dragh', { + start: function() { + startPos = { + x: self.layoutRect().x, + y: self.layoutRect().y + }; + }, + + drag: function(e) { + self.moveTo(startPos.x + e.deltaX, startPos.y + e.deltaY); + } + }); + + self.on('submit', function(e) { + if (!e.isDefaultPrevented()) { + self.close(); + } + }); + }, + + submit: function() { + return this.fire('submit', {data: this.toJSON()}); + }, + + remove: function() { + var self = this; + + self._super(); + self.dragHelger.destroy(); + + if (self.statusbar) { + this.statusbar.remove(); + } + } + }); + + return Window; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/util/Class.js b/lib/tinymce/jscripts/tinymce4/classes/util/Class.js new file mode 100644 index 00000000..223e3f41 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/util/Class.js @@ -0,0 +1,165 @@ +/** + * Class.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * This utilitiy class is used for easier inheritage. + * + * Features: + * * Exposed super functions: this._super(); + * * Mixins + * * Dummy functions + * * Property functions: var value = object.value(); and object.value(newValue); + * * Static functions + * * Defaults settings + */ +define("tinymce/util/Class", [ + "tinymce/util/Tools" +], function(Tools) { + var each = Tools.each, extend = Tools.extend; + + var extendClass, initializing; + + function Class() { + } + + // Provides classical inheritance, based on code made by John Resig + Class.extend = extendClass = function(prop) { + var Self = this, _super = Self.prototype, prototype, name, member; + + // The dummy class constructor + function Class() { + var i, mixins, mixin, self; + + // All construction is actually done in the init method + if (!initializing) { + self = this; + + // Run class constuctor + if (self.init) { + self.init.apply(self, arguments); + } + + // Run mixin constructors + mixins = self.Mixins; + if (mixins) { + i = mixins.length; + while (i--) { + mixin = mixins[i]; + if (mixin.init) { + mixin.init.apply(self, arguments); + } + } + } + } + } + + // Dummy function, needs to be extended in order to provide functionality + function dummy() { + return this; + } + + // Creates a overloaded method for the class + // this enables you to use this._super(); to call the super function + function createMethod(name, fn) { + return function(){ + var self = this, tmp = self._super, ret; + + self._super = _super[name]; + ret = fn.apply(self, arguments); + self._super = tmp; + + return ret; + }; + } + + // Instantiate a base class (but only create the instance, + // don't run the init constructor) + initializing = true; + prototype = new Self(); + initializing = false; + + // Add mixins + if (prop.Mixins) { + each(prop.Mixins, function(mixin) { + mixin = mixin; + + for (var name in mixin) { + if (name !== "init") { + prop[name] = mixin[name]; + } + } + }); + + if (_super.Mixins) { + prop.Mixins = _super.Mixins.concat(prop.Mixins); + } + } + + // Generate dummy methods + if (prop.Methods) { + each(prop.Methods.split(','), function(name) { + prop[name] = dummy; + }); + } + + // Generate property methods + if (prop.Properties) { + each(prop.Properties.split(','), function(name) { + var fieldName = '_' + name; + + prop[name] = function(value) { + var self = this, undef; + + // Set value + if (value !== undef) { + self[fieldName] = value; + + return self; + } + + // Get value + return self[fieldName]; + }; + }); + } + + // Static functions + if (prop.Statics) { + each(prop.Statics, function(func, name) { + Class[name] = func; + }); + } + + // Default settings + if (prop.Defaults && _super.Defaults) { + prop.Defaults = extend({}, _super.Defaults, prop.Defaults); + } + + // Copy the properties over onto the new prototype + for (name in prop) { + member = prop[name]; + + if (typeof member == "function" && _super[name]) { + prototype[name] = createMethod(name, member); + } else { + prototype[name] = member; + } + } + + // Populate our constructed prototype object + Class.prototype = prototype; + + // Enforce the constructor to be what we expect + Class.constructor = Class; + + // And make this class extendible + Class.extend = extendClass; + + return Class; + }; + + return Class; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/util/JSON.js b/lib/tinymce/jscripts/tinymce4/classes/util/JSON.js new file mode 100644 index 00000000..621369e4 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/util/JSON.js @@ -0,0 +1,109 @@ +/** + * JSON.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * JSON parser and serializer class. + * + * @class tinymce.util.JSON + * @static + * @example + * // JSON parse a string into an object + * var obj = tinymce.util.JSON.parse(somestring); + * + * // JSON serialize a object into an string + * var str = tinymce.util.JSON.serialize(obj); + */ +define("tinymce/util/JSON", [], 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 && Object.prototype.toString.call(o) === '[object Array]') { + for (i=0, 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; + } + + return { + /** + * Serializes the specified object as a JSON string. + * + * @method serialize + * @param {Object} obj Object to serialize as a JSON string. + * @param {String} quote Optional quote string defaults to ". + * @return {string} JSON string serialized from input. + */ + serialize: serialize, + + /** + * Unserializes/parses the specified JSON string into a object. + * + * @method parse + * @param {string} s JSON String to parse into a JavaScript object. + * @return {Object} Object from input JSON string or undefined if it failed. + */ + parse: function(text) { + try { + // Trick uglify JS + return window[String.fromCharCode(101) + 'val']('(' + text + ')'); + } catch (ex) { + // Ignore + } + } + + /**#@-*/ + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/util/JSONP.js b/lib/tinymce/jscripts/tinymce4/classes/util/JSONP.js new file mode 100644 index 00000000..3c0bf67d --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/util/JSONP.js @@ -0,0 +1,38 @@ +/** + * JSONP.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/util/JSONP", [ + "tinymce/dom/DOMUtils" +], function(DOMUtils) { + return { + callbacks: {}, + count: 0, + + send: function(settings) { + var self = this, dom = DOMUtils.DOM, count = settings.count !== undefined ? settings.count : self.count; + var id = 'tinymce_jsonp_' + count; + + self.callbacks[count] = function(json) { + dom.remove(id); + delete self.callbacks[count]; + + settings.callback(json); + }; + + dom.add(dom.doc.body, 'script', { + id: id, + src: settings.url, + type: 'text/javascript' + }); + + self.count++; + } + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/util/JSONRequest.js b/lib/tinymce/jscripts/tinymce4/classes/util/JSONRequest.js new file mode 100644 index 00000000..44d3e88f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/util/JSONRequest.js @@ -0,0 +1,110 @@ +/** + * JSONRequest.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class enables you to use JSON-RPC to call backend methods. + * + * @class tinymce.util.JSONRequest + * @example + * var json = new tinymce.util.JSONRequest({ + * url: 'somebackend.php' + * }); + * + * // Send RPC call 1 + * json.send({ + * method: 'someMethod1', + * params: ['a', 'b'], + * success: function(result) { + * console.dir(result); + * } + * }); + * + * // Send RPC call 2 + * json.send({ + * method: 'someMethod2', + * params: ['a', 'b'], + * success: function(result) { + * console.dir(result); + * } + * }); + */ +define("tinymce/util/JSONRequest", [ + "tinymce/util/JSON", + "tinymce/util/XHR", + "tinymce/util/Tools" +], function(JSON, XHR, Tools) { + var extend = Tools.extend; + + function JSONRequest(settings) { + this.settings = extend({}, settings); + this.count = 0; + } + + /** + * Simple helper function to send a JSON-RPC request without the need to initialize an object. + * Consult the Wiki API documentation for more details on what you can pass to this function. + * + * @method sendRPC + * @static + * @param {Object} o Call object where there are three field id, method and params this object should also contain callbacks etc. + */ + JSONRequest.sendRPC = function(o) { + return new JSONRequest().send(o); + }; + + JSONRequest.prototype = { + /** + * Sends a JSON-RPC call. Consult the Wiki API documentation for more details on what you can pass to this function. + * + * @method send + * @param {Object} args Call object where there are three field id, method and params this object should also contain callbacks etc. + */ + send: function(args) { + var ecb = args.error, scb = args.success; + + args = extend(this.settings, args); + + args.success = function(c, x) { + c = JSON.parse(c); + + if (typeof(c) == 'undefined') { + c = { + error : 'JSON Parse error.' + }; + } + + if (c.error) { + ecb.call(args.error_scope || args.scope, c.error, x); + } else { + scb.call(args.success_scope || args.scope, c.result); + } + }; + + args.error = function(ty, x) { + if (ecb) { + ecb.call(args.error_scope || args.scope, ty, x); + } + }; + + args.data = JSON.serialize({ + id : args.id || 'c' + (this.count++), + method : args.method, + params : args.params + }); + + // JSON content type for Ruby on rails. Bug: #1883287 + args.content_type = 'application/json'; + + XHR.send(args); + } + }; + + return JSONRequest; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/util/LocalStorage.js b/lib/tinymce/jscripts/tinymce4/classes/util/LocalStorage.js new file mode 100644 index 00000000..e169555e --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/util/LocalStorage.js @@ -0,0 +1,175 @@ +/** + * LocalStorage.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class will simulate LocalStorage on IE 7 and return the native version on modern browsers. + * Storage is done using userData on IE 7 and a special serialization format. The format is designed + * to be as small as possible by making sure that the keys and values doesn't need to be encoded. This + * makes it possible to store for example HTML data. + * + * Storage format for userData: + * ,,,,... + * + * For example this data key1=value1,key2=value2 would be: + * 4,key1,6,value1,4,key2,6,value2 + * + * @class tinymce.util.LocalStorage + * @static + * @version 4.0 + * @example + * tinymce.util.LocalStorage.setItem('key', 'value'); + * var value = tinymce.util.LocalStorage.getItem('key'); + */ +define("tinymce/util/LocalStorage", [], function() { + var LocalStorage, storageElm, items, keys, userDataKey; + + // Check for native support + if (window.localStorage) { + return localStorage; + } + + userDataKey = "tinymce"; + storageElm = document.documentElement; + storageElm.addBehavior('#default#userData'); + + /** + * Gets the keys names and updates LocalStorage.length property. Since IE7 doesn't have any getters/setters. + */ + function updateKeys() { + keys = []; + + for (var key in items) { + keys.push(key); + } + + LocalStorage.length = keys.length; + } + + /** + * Loads the userData string and parses it into the items structure. + */ + function load() { + var key, data, value, pos = 0; + + items = {}; + + function next(end) { + var value, nextPos; + + nextPos = end !== undefined ? pos + end : data.indexOf(',', pos); + if (nextPos === -1 || nextPos > data.length) { + return null; + } + + value = data.substring(pos, nextPos); + pos = nextPos + 1; + + return value; + } + + storageElm.load(userDataKey); + data = storageElm.getAttribute(userDataKey) || ''; + + do { + key = next(parseInt(next(), 32) || 0); + if (key !== null) { + value = next(parseInt(next(), 32) || 0); + items[key] = value; + } + } while (key !== null); + + updateKeys(); + } + + /** + * Saves the items structure into a the userData format. + */ + function save() { + var value, data = ''; + + for (var key in items) { + value = items[key]; + data += (data ? ',' : '') + key.length.toString(32) + ',' + key + ',' + value.length.toString(32) + ',' + value; + } + + storageElm.setAttribute(userDataKey, data); + storageElm.save(userDataKey); + updateKeys(); + } + + LocalStorage = { + /** + * Length of the number of items in storage. + * + * @property length + * @return {Number} Number of items in storage. + */ + //length:0, + + /** + * Returns the key name by index. + * + * @method key + * @param {Number} index Index of key to return. + * @return {String} Key value or null if it wasn't found. + */ + key: function(index) { + return keys[index]; + }, + + /** + * Returns the value if the specified key or null if it wasn't found. + * + * @method getItem + * @param {String} key Key of item to retrive. + * @return {String} Value of the specified item or null if it wasn't found. + */ + getItem: function(key) { + return key in items ? items[key] : null; + }, + + /** + * Sets the value of the specified item by it's key. + * + * @method setItem + * @param {String} key Key of the item to set. + * @param {String} value Value of the item to set. + */ + setItem: function(key, value) { + items[key] = "" + value; + save(); + }, + + /** + * Removes the specified item by key. + * + * @method removeItem + * @param {String} key Key of item to remove. + */ + removeItem: function(key) { + delete items[key]; + save(); + }, + + /** + * Removes all items. + * + * @method clear + */ + clear: function() { + items = {}; + save(); + } + }; + + load(); + + return LocalStorage; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/util/Observable.js b/lib/tinymce/jscripts/tinymce4/classes/util/Observable.js new file mode 100644 index 00000000..2dad4d81 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/util/Observable.js @@ -0,0 +1,188 @@ +/** + * Observable.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/util/Observable", [ + "tinymce/util/Tools" +], function(Tools) { + var bindingsName = "__bindings"; + var nativeEvents = Tools.makeMap( + "focusin focusout click dblclick mousedown mouseup mousemove mouseover beforepaste paste cut copy" + + " mouseout mouseenter mouseleave keydown keypress keyup contextmenu dragend dragover draggesture dragdrop drop drag", ' ' + ); + + function returnFalse() { + return false; + } + + function returnTrue() { + return true; + } + + return { + fire: function(name, args, bubble) { + var self = this, handlers, i, l, callback, parent; + + name = name.toLowerCase(); + args = args || {}; + args.type = name; + + // Setup target is there isn't one + if (!args.target) { + args.target = self; + } + + // Add event delegation methods if they are missing + if (!args.preventDefault) { + // Add preventDefault method + args.preventDefault = function() { + args.isDefaultPrevented = returnTrue; + }; + + // Add stopPropagation + args.stopPropagation = function() { + args.isPropagationStopped = returnTrue; + }; + + // Add stopImmediatePropagation + args.stopImmediatePropagation = function() { + args.isImmediatePropagationStopped = returnTrue; + }; + + // Add event delegation states + args.isDefaultPrevented = returnFalse; + args.isPropagationStopped = returnFalse; + args.isImmediatePropagationStopped = returnFalse; + } + + //console.log(name, args); + + if (self[bindingsName]) { + handlers = self[bindingsName][name]; + + if (handlers) { + for (i = 0, l = handlers.length; i < l; i++) { + handlers[i] = callback = handlers[i]; + + // Stop immediate propagation if needed + if (args.isImmediatePropagationStopped()) { + break; + } + + // If callback returns false then prevent default and stop all propagation + if (callback.call(self, args) === false) { + args.preventDefault(); + return args; + } + } + } + } + + // Bubble event up to parents + if (bubble !== false && self.parent) { + parent = self.parent(); + while (parent && !args.isPropagationStopped()) { + parent.fire(name, args, false); + parent = parent.parent(); + } + } + + return args; + }, + + on: function(name, callback) { + var self = this, bindings, handlers, names, i; + + if (callback === false) { + callback = function() { + return false; + }; + } + + if (callback) { + names = name.toLowerCase().split(' '); + i = names.length; + while (i--) { + name = names[i]; + + bindings = self[bindingsName]; + if (!bindings) { + bindings = self[bindingsName] = {}; + } + + handlers = bindings[name]; + if (!handlers) { + handlers = bindings[name] = []; + if (self.bindNative && nativeEvents[name]) { + self.bindNative(name); + } + } + + handlers.push(callback); + } + } + + return self; + }, + + off: function(name, callback) { + var self = this, i, bindings = self[bindingsName], handlers, bindingName, names, hi; + + if (bindings) { + if (name) { + names = name.toLowerCase().split(' '); + i = names.length; + while (i--) { + name = names[i]; + handlers = bindings[name]; + + // Unbind all handlers + if (!name) { + for (bindingName in bindings) { + bindings[name].length = 0; + } + + return self; + } + + if (handlers) { + // Unbind all by name + if (!callback) { + handlers.length = 0; + } else { + // Unbind specific ones + hi = handlers.length; + while (hi--) { + if (handlers[hi] === callback) { + handlers.splice(hi, 1); + } + } + } + + if (!handlers.length && self.unbindNative && nativeEvents[name]) { + self.unbindNative(name); + delete bindings[name]; + } + } + } + } else { + if (self.unbindNative) { + for (name in bindings) { + self.unbindNative(name); + } + } + + self[bindingsName] = []; + } + } + + return self; + } + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/util/Quirks.js b/lib/tinymce/jscripts/tinymce4/classes/util/Quirks.js new file mode 100644 index 00000000..4a43a8ee --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/util/Quirks.js @@ -0,0 +1,932 @@ +/** + * Quirks.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This file includes fixes for various browser quirks it's made to make it easy to add/remove browser specific fixes. + * + * @class tinymce.util.Quirks + * @private + */ +define("tinymce/util/Quirks", [ + "tinymce/util/VK", + "tinymce/dom/RangeUtils", + "tinymce/html/Node", + "tinymce/html/Entities", + "tinymce/Env", + "tinymce/util/Tools" +], function(VK, RangeUtils, Node, Entities, Env, Tools) { + return function(editor) { + var each = Tools.each; + var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, + settings = editor.settings, parser = editor.parser, serializer = editor.serializer; + var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit; + + /** + * Executes a command with a specific state this can be to enable/disable browser editing features. + */ + function setEditorCommandState(cmd, state) { + try { + editor.getDoc().execCommand(cmd, false, state); + } catch (ex) { + // Ignore + } + } + + /** + * Returns current IE document mode. + */ + function getDocumentMode() { + var documentMode = editor.getDoc().documentMode; + + return documentMode ? documentMode : 6; + } + + /** + * Returns true/false if the event is prevented or not. + * + * @param {Event} e Event object. + * @return {Boolean} true/false if the event is prevented or not. + */ + function isDefaultPrevented(e) { + return e.isDefaultPrevented(); + } + + /** + * Fixes a WebKit bug when deleting contents using backspace or delete key. + * WebKit will produce a span element if you delete across two block elements. + * + * Example: + *

    a

    |b

    + * + * Will produce this on backspace: + *

    ab

    + * + * This fixes the backspace to produce: + *

    a|b

    + * + * See bug: https://bugs.webkit.org/show_bug.cgi?id=45784 + * + * This code is a bit of a hack and hopefully it will be fixed soon in WebKit. + */ + function cleanupStylesWhenDeleting() { + function removeMergedFormatSpans(isDelete) { + var rng, blockElm, wrapperElm, bookmark, container, offset, elm; + + function isAtStartOrEndOfElm() { + if (container.nodeType == 3) { + if (isDelete && offset == container.length) { + return true; + } + + if (!isDelete && offset === 0) { + return true; + } + } + } + + rng = selection.getRng(); + var tmpRng = [rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset]; + + if (!rng.collapsed) { + isDelete = true; + } + + container = rng[(isDelete ? 'start' : 'end') + 'Container']; + offset = rng[(isDelete ? 'start' : 'end') + 'Offset']; + + if (container.nodeType == 3) { + 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); + } + + if (blockElm && (isAtStartOrEndOfElm() || !rng.collapsed)) { + // Wrap children of block in a EM and let WebKit stick is + // runtime styles junk into that EM + wrapperElm = dom.create('em', {'id': '__mceDel'}); + + each(Tools.grep(blockElm.childNodes), function(node) { + wrapperElm.appendChild(node); + }); + + blockElm.appendChild(wrapperElm); + } + } + + // Do the backspace/delete action + rng = dom.createRng(); + rng.setStart(tmpRng[0], tmpRng[1]); + rng.setEnd(tmpRng[2], tmpRng[3]); + selection.setRng(rng); + editor.getDoc().execCommand(isDelete ? 'ForwardDelete' : 'Delete', false, null); + + // Remove temp wrapper element + if (wrapperElm) { + bookmark = selection.getBookmark(); + + while ((elm = dom.get('__mceDel'))) { + dom.remove(elm, true); + } + + selection.moveToBookmark(bookmark); + } + } + + editor.on('keydown', function(e) { + var isDelete; + + isDelete = e.keyCode == DELETE; + if (!isDefaultPrevented(e) && (isDelete || e.keyCode == BACKSPACE) && !VK.modifierPressed(e)) { + e.preventDefault(); + removeMergedFormatSpans(isDelete); + } + }); + + editor.addCommand('Delete', function() {removeMergedFormatSpans();}); + } + + /** + * Makes sure that the editor body becomes empty when backspace or delete is pressed in empty editors. + * + * For example: + *

    |

    + * + * Or: + *

    |

    + * + * Or: + * [

    ] + */ + 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.on('keydown', function(e) { + var keyCode = e.keyCode, isCollapsed; + + // Empty the editor if it's needed for example backspace at

    |

    + if (!isDefaultPrevented(e) && (keyCode == DELETE || keyCode == BACKSPACE)) { + isCollapsed = editor.selection.isCollapsed(); + + // Selection is collapsed but the editor isn't empty + if (isCollapsed && !dom.isEmpty(editor.getBody())) { + return; + } + + // IE deletes all contents correctly when everything is selected + if (isIE && !isCollapsed) { + return; + } + + // Selection isn't collapsed but not all the contents is selected + if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) { + return; + } + + // Manually empty the editor + e.preventDefault(); + editor.setContent(''); + editor.selection.setCursorLocation(editor.getBody(), 0); + editor.nodeChanged(); + } + }); + } + + /** + * WebKit doesn't select all the nodes in the body when you press Ctrl+A. + * This selects the whole body so that backspace/delete logic will delete everything + */ + function selectAll() { + editor.on('keydown', function(e) { + if (!isDefaultPrevented(e) && e.keyCode == 65 && VK.metaKeyPressed(e)) { + e.preventDefault(); + editor.execCommand('SelectAll'); + } + }); + } + + /** + * WebKit has a weird issue where it some times fails to properly convert keypresses to input method keystrokes. + * The IME on Mac doesn't initialize when it doesn't fire a proper focus event. + * + * This seems to happen when the user manages to click the documentElement element then the window doesn't get proper focus until + * you enter a character into the editor. + * + * It also happens when the first focus in made to the body. + * + * See: https://bugs.webkit.org/show_bug.cgi?id=83566 + */ + function inputMethodFocus() { + if (!editor.settings.content_editable) { + // Case 1 IME doesn't initialize if you focus the document + dom.bind(editor.getDoc(), 'focusin', function() { + selection.setRng(selection.getRng()); + }); + + // Case 2 IME doesn't initialize if you click the documentElement it also doesn't properly fire the focusin event + dom.bind(editor.getDoc(), 'mousedown', function(e) { + if (e.target == editor.getDoc().documentElement) { + editor.getWin().focus(); + selection.setRng(selection.getRng()); + } + }); + } + } + + /** + * Backspacing in FireFox/IE from a paragraph into a horizontal rule results in a floating text node because the + * browser just deletes the paragraph - the browser fails to merge the text node with a horizontal rule so it is + * left there. TinyMCE sees a floating text node and wraps it in a paragraph on the key up event (ForceBlocks.js + * addRootBlocks), meaning the action does nothing. With this code, FireFox/IE matche the behaviour of other + * browsers + */ + function removeHrOnBackspace() { + editor.on('keydown', function(e) { + if (!isDefaultPrevented(e) && 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); + e.preventDefault(); + } + } + } + }); + } + + /** + * Firefox 3.x has an issue where the body element won't get proper focus if you click out + * side it's rectangle. + */ + 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 (!window.Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4 + editor.on('mousedown', function(e) { + if (!isDefaultPrevented(e) && 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); + } + }); + } + } + + /** + * WebKit has a bug where it isn't possible to select image, hr or anchor elements + * by clicking on them so we need to fake that. + */ + function selectControlElements() { + editor.on('click', function(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(); + }); + } + + /** + * Fixes a Gecko bug where the style attribute gets added to the wrong element when deleting between two block elements. + * + * Fixes do backspace/delete on this: + *

    bla[ck

    r]ed

    + * + * Would become: + *

    bla|ed

    + * + * Instead of: + *

    bla|ed

    + */ + 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); + + each(template, function(attr) { + target.setAttributeNode(attr.cloneNode(true)); + }); + } + }; + } + + function isSelectionAcrossElements() { + return !selection.isCollapsed() && + dom.getParent(selection.getStart(), dom.isBlock) != dom.getParent(selection.getEnd(), dom.isBlock); + } + + editor.on('keypress', function(e) { + var applyAttributes; + + if (!isDefaultPrevented(e) && (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 (!isDefaultPrevented(e) && isSelectionAcrossElements()) { + applyAttributes = getAttributeApplyFunction(); + + setTimeout(function() { + applyAttributes(); + }, 0); + } + }); + } + + /** + * Fire a nodeChanged when the selection is changed on WebKit this fixes selection issues on iOS5. It only fires the nodeChange + * event every 50ms since it would other wise update the UI when you type and it hogs the CPU. + */ + function selectionChangeNodeChanged() { + var lastRng, selectionTimer; + + editor.on('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 || !RangeUtils.compareRanges(rng, lastRng)) { + editor.nodeChanged(); + lastRng = rng; + } + }, 50); + }); + } + + /** + * Screen readers on IE needs to have the role application set on the body. + */ + function ensureBodyHasRoleApplication() { + document.body.setAttribute("role", "application"); + } + + /** + * Backspacing into a table behaves differently depending upon browser type. + * Therefore, disable Backspace when cursor immediately follows a table. + */ + function disableBackspaceIntoATable() { + editor.on('keydown', function(e) { + if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { + if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { + var previousSibling = selection.getNode().previousSibling; + if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") { + e.preventDefault(); + return false; + } + } + } + }); + } + + /** + * Old IE versions can't properly render BR elements in PRE tags white in contentEditable mode. So this + * logic adds a \n before the BR so that it will get rendered. + */ + function addNewLinesBeforeBrInPre() { + // IE8+ rendering mode does the right thing with BR in PRE + if (getDocumentMode() > 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); + editor.contentStyles.push('.mceHideBrInPre pre br {display: none}'); + dom.addClass(editor.getBody(), 'mceHideBrInPre'); + + // Adds a \n before all BR elements in PRE to get them visual + parser.addNodeFilter('pre', function(nodes) { + 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 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 + serializer.addNodeFilter('pre', function(nodes) { + 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$/, ''); + } + } + } + }); + } + + /** + * Moves style width/height to attribute width/height when the user resizes an image on IE. + */ + function removePreSerializedStylesWhenSelectingControls() { + dom.bind(editor.getBody(), 'mouseup', function() { + 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', ''); + } + } + }); + } + + /** + * Backspace or delete on WebKit will combine all visual styles in a span if the last character is deleted. + * + * For example backspace on: + *

    x|

    + * + * Will produce: + *

    |

    + * + * When it should produce: + *

    |

    + * + * See: https://bugs.webkit.org/show_bug.cgi?id=81656 + */ + function keepInlineElementOnDeleteBackspace() { + editor.on('keydown', function(e) { + var isDelete, rng, container, offset, brElm, sibling, collapsed, nonEmptyElements; + + isDelete = e.keyCode == DELETE; + if (!isDefaultPrevented(e) && (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)))) { + // Edge case when deleting

    |x

    + sibling = container.previousSibling; + if (sibling && sibling.nodeName == "IMG") { + return; + } + + 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:

    |

    + 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'); + } + } + }); + } + + /** + * Removes a blockquote when backspace is pressed at the beginning of it. + * + * For example: + *

    |x

    + * + * Becomes: + *

    |x

    + */ + function removeBlockQuoteOnBackSpace() { + // Add block quote deletion handler + editor.on('keydown', function(e) { + var rng, container, offset, root, parent; + + if (isDefaultPrevented(e) || 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 && 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 = dom.createRng(); + rng.setStart(container, 0); + rng.setEnd(container, 0); + selection.setRng(rng); + } + }); + } + + /** + * Sets various Gecko editing options on mouse down and before a execCommand to disable inline table editing that is broken etc. + */ + function setGeckoEditingOptions() { + function setOpts() { + editor._refreshContentEditable(); + + setEditorCommandState("StyleWithCSS", false); + setEditorCommandState("enableInlineTableEditing", false); + + if (!settings.object_resizing) { + setEditorCommandState("enableObjectResizing", false); + } + } + + if (!settings.readonly) { + editor.on('BeforeExecCommand MouseDown', setOpts); + } + } + + /** + * Fixes a gecko link bug, when a link is placed at the end of block elements there is + * no way to move the caret behind the link. This fix adds a bogus br element after the link. + * + * For example this: + *

    x

    + * + * Becomes this: + *

    x

    + */ + function addBrAfterLastLinks() { + function fixLinks() { + 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.on('SetContent ExecCommand', function(e) { + if (e.type == "setcontent" || e.command === 'mceInsertLink') { + fixLinks(); + } + }); + } + + /** + * WebKit will produce DIV elements here and there by default. But since TinyMCE uses paragraphs by + * default we want to change that behavior. + */ + function setDefaultBlockType() { + if (settings.forced_root_block) { + editor.on('init', function() { + setEditorCommandState('DefaultParagraphSeparator', settings.forced_root_block); + }); + } + } + + /** + * Removes ghost selections from images/tables on Gecko. + */ + function removeGhostSelection() { + editor.on('Undo Redo SetContent', function(e) { + if (!e.initial) { + editor.execCommand('mceRepaint'); + } + }); + } + + /** + * Deletes the selected image on IE instead of navigating to previous page. + */ + function deleteControlItemOnBackSpace() { + editor.on('keydown', function(e) { + var rng; + + if (!isDefaultPrevented(e) && e.keyCode == BACKSPACE) { + rng = editor.getDoc().selection.createRange(); + if (rng && rng.item) { + e.preventDefault(); + editor.undoManager.beforeChange(); + dom.remove(rng.item(0)); + editor.undoManager.add(); + } + } + }); + } + + /** + * IE10 doesn't properly render block elements with the right height until you add contents to them. + * This fixes that by adding a padding-right to all empty text block elements. + * See: https://connect.microsoft.com/IE/feedback/details/743881 + */ + function renderEmptyBlocksFix() { + var emptyBlocksCSS; + + // IE10+ + if (getDocumentMode() >= 10) { + emptyBlocksCSS = ''; + each('p div h1 h2 h3 h4 h5 h6'.split(' '), function(name, i) { + emptyBlocksCSS += (i > 0 ? ',' : '') + name + ':empty'; + }); + + editor.contentStyles.push(emptyBlocksCSS + '{padding-right: 1px !important}'); + } + } + + /** + * Old IE versions can't retain contents within noscript elements so this logic will store the contents + * as a attribute and the insert that value as it's raw text when the DOM is serialized. + */ + function keepNoScriptContents() { + if (getDocumentMode() < 9) { + parser.addNodeFilter('noscript', function(nodes) { + var i = nodes.length, node, textNode; + + while (i--) { + node = nodes[i]; + textNode = node.firstChild; + + if (textNode) { + node.attr('data-mce-innertext', textNode.value); + } + } + }); + + serializer.addNodeFilter('noscript', function(nodes) { + var i = nodes.length, node, textNode, value; + + while (i--) { + node = nodes[i]; + textNode = nodes[i].firstChild; + + if (textNode) { + textNode.value = Entities.decode(textNode.value); + } else { + // Old IE can't retain noscript value so an attribute is used to store it + value = node.attributes.map['data-mce-innertext']; + if (value) { + node.attr('data-mce-innertext', null); + textNode = new Node('#text', 3); + textNode.value = value; + textNode.raw = true; + node.append(textNode); + } + } + } + }); + } + } + + /** + * IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode. + */ + function fixCaretSelectionOfDocumentElementOnIe() { + var 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(); + } + } + }); + } + + /** + * Fixes selection issues on Gecko where the caret can be placed between two inline elements like a|b + * this fix will lean the caret right into the closest inline element. + */ + function normalizeSelection() { + // Normalize selection for example a|a becomes a|a except for Ctrl+A since it selects everything + editor.on('keyup focusin', function(e) { + if (e.keyCode != 65 || !VK.metaKeyPressed(e)) { + selection.normalize(); + } + }); + } + + // All browsers + disableBackspaceIntoATable(); + removeBlockQuoteOnBackSpace(); + emptyEditorWhenDeleting(); + normalizeSelection(); + + // WebKit + if (isWebKit) { + keepInlineElementOnDeleteBackspace(); + cleanupStylesWhenDeleting(); + inputMethodFocus(); + selectControlElements(); + setDefaultBlockType(); + + // iOS + if (Env.iOS) { + selectionChangeNodeChanged(); + } else { + selectAll(); + } + } + + // IE + if (isIE) { + removeHrOnBackspace(); + ensureBodyHasRoleApplication(); + addNewLinesBeforeBrInPre(); + removePreSerializedStylesWhenSelectingControls(); + deleteControlItemOnBackSpace(); + renderEmptyBlocksFix(); + keepNoScriptContents(); + fixCaretSelectionOfDocumentElementOnIe(); + } + + // Gecko + if (isGecko) { + removeHrOnBackspace(); + focusBody(); + removeStylesWhenDeletingAccrossBlockElements(); + setGeckoEditingOptions(); + addBrAfterLastLinks(); + removeGhostSelection(); + } + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/classes/util/Tools.js b/lib/tinymce/jscripts/tinymce4/classes/util/Tools.js new file mode 100644 index 00000000..66b6b4b6 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/util/Tools.js @@ -0,0 +1,496 @@ +/** + * Quirks.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/util/Tools", [], function() { + /** + * Removes whitespace from the beginning and end of a string. + * + * @method trim + * @param {String} s String to remove whitespace from. + * @return {String} New string with removed whitespace. + */ + var whiteSpaceRegExp = /^\s*|\s*$/g; + var trim = function(str) { + return (str === null || str === undefined) ? '' : ("" + str).replace(whiteSpaceRegExp, ''); + }; + + /** + * Returns true/false if the object is an array or not. + * + * @method isArray + * @param {Object} obj Object to check. + * @return {boolean} true/false state if the object is an array or not. + */ + var isArray = Array.isArray || function(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + + /** + * Checks if a object is of a specific type for example an array. + * + * @method is + * @param {Object} o Object to check type of. + * @param {string} t Optional type to check for. + * @return {Boolean} true/false if the object is of the specified type. + */ + function is(o, t) { + if (!t) { + return o !== undefined; + } + + if (t == 'array' && isArray(o)) { + return true; + } + + return typeof(o) == t; + } + + /** + * Converts the specified object into a real JavaScript array. + * + * @method toArray + * @param {Object} obj Object to convert into array. + * @return {Array} Array object based in input. + */ + function toArray(obj) { + var array = [], i, l; + + for (i = 0, l = obj.length; i < l; i++) { + array[i] = obj[i]; + } + + return array; + } + + /** + * Makes a name/object map out of an array with names. + * + * @method makeMap + * @param {Array/String} items Items to make map out of. + * @param {String} delim Optional delimiter to split string by. + * @param {Object} map Optional map to add items to. + * @return {Object} Name/value map of items. + */ + function makeMap(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; + } + + /** + * Performs an iteration of all items in a collection such as an object or array. This method will execure the + * callback function for each item in the collection, if the callback returns false the iteration will terminate. + * The callback has the following format: cb(value, key_or_index). + * + * @method each + * @param {Object} o Collection to iterate. + * @param {function} cb Callback function to execute for each item. + * @param {Object} s Optional scope to execute the callback in. + * @example + * // Iterate an array + * tinymce.each([1,2,3], function(v, i) { + * console.debug("Value: " + v + ", Index: " + i); + * }); + * + * // Iterate an object + * tinymce.each({a: 1, b: 2, c: 3], function(v, k) { + * console.debug("Value: " + v + ", Key: " + k); + * }); + */ + function each(o, cb, s) { + var n, l; + + if (!o) { + return 0; + } + + s = s || o; + + if (o.length !== undefined) { + // 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; + } + + /** + * Creates a new array by the return value of each iteration function call. This enables you to convert + * one array list into another. + * + * @method map + * @param {Array} a Array of items to iterate. + * @param {function} f Function to call for each item. It's return value will be the new value. + * @return {Array} Array with new values based on function return values. + */ + function map(a, f) { + var o = []; + + each(a, function(v) { + o.push(f(v)); + }); + + return o; + } + + /** + * Filters out items from the input array by calling the specified function for each item. + * If the function returns false the item will be excluded if it returns true it will be included. + * + * @method grep + * @param {Array} a Array of items to loop though. + * @param {function} f Function to call for each item. Include/exclude depends on it's return value. + * @return {Array} New array with values imported and filtered based in input. + * @example + * // Filter out some items, this will return an array with 4 and 5 + * var items = tinymce.grep([1,2,3,4,5], function(v) {return v > 3;}); + */ + function grep(a, f) { + var o = []; + + each(a, function(v) { + if (!f || f(v)) { + o.push(v); + } + }); + + return o; + } + + /** + * Creates a class, subclass or static singleton. + * More details on this method can be found in the Wiki. + * + * @method create + * @param {String} s Class name, inheritage and prefix. + * @param {Object} p Collection of methods to add to the class. + * @param {Object} root Optional root object defaults to the global window object. + * @example + * // Creates a basic class + * tinymce.create('tinymce.somepackage.SomeClass', { + * SomeClass: function() { + * // Class constructor + * }, + * + * method: function() { + * // Some method + * } + * }); + * + * // Creates a basic subclass class + * tinymce.create('tinymce.somepackage.SomeSubClass:tinymce.somepackage.SomeClass', { + * SomeSubClass: function() { + * // Class constructor + * this.parent(); // Call parent constructor + * }, + * + * method: function() { + * // Some method + * this.parent(); // Call parent method + * }, + * + * 'static': { + * staticMethod: function() { + * // Static method + * } + * } + * }); + * + * // Creates a singleton/static class + * tinymce.create('static tinymce.somepackage.SomeSingletonClass', { + * method: function() { + * // Some method + * } + * }); + */ + function create(s, p, root) { + var t = this, sp, ns, cn, scn, c, de = 0; + + // Parse : : + 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 + /*jshint sub:true*/ + t.each(p['static'], function(f, n) { + ns[cn][n] = f; + }); + } + + /** + * Returns the index of a value in an array, this method will return -1 if the item wasn't found. + * + * @method inArray + * @param {Array} a Array/Object to search for value in. + * @param {Object} v Value to check for inside the array. + * @return {Number/String} Index of item inside the array inside an object. Or -1 if it wasn't found. + * @example + * // Get index of value in array this will alert 1 since 2 is at that index + * alert(tinymce.inArray([1,2,3], 2)); + */ + function inArray(a, v) { + var i, l; + + if (a) { + for (i = 0, l = a.length; i < l; i++) { + if (a[i] === v) { + return i; + } + } + } + + return -1; + } + + function extend(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 !== undefined) { + obj[name] = value; + } + } + } + } + + return obj; + } + + /** + * Executed the specified function for each item in a object tree. + * + * @method walk + * @param {Object} o Object tree to walk though. + * @param {function} f Function to call for each item. + * @param {String} n Optional name of collection inside the objects to walk for example childNodes. + * @param {String} s Optional scope to execute the function in. + */ + function walk(o, f, n, s) { + s = s || this; + + if (o) { + if (n) { + o = o[n]; + } + + each(o, function(o, i) { + if (f.call(s, o, i, n) === false) { + return false; + } + + walk(o, f, n, s); + }); + } + } + + /** + * Creates a namespace on a specific object. + * + * @method createNS + * @param {String} n Namespace to create for example a.b.c.d. + * @param {Object} o Optional object to add namespace to, defaults to window. + * @return {Object} New namespace object the last item in path. + * @example + * // Create some namespace + * tinymce.createNS('tinymce.somepackage.subpackage'); + * + * // Add a singleton + * var tinymce.somepackage.subpackage.SomeSingleton = { + * method: function() { + * // Some method + * } + * }; + */ + function createNS(n, o) { + var i, v; + + o = o || window; + + n = n.split('.'); + for (i=0; i= items.length) { + for (i = 0, l = base.length; i < l; i++) { + if (i >= items.length || base[i] != items[i]) { + breakPoint = 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]) { + breakPoint = i + 1; + break; + } + } + } + + if (breakPoint === 1) { + return path; + } + + for (i = 0, l = base.length - (breakPoint - 1); i < l; i++) { + out += "../"; + } + + for (i = breakPoint - 1, l = items.length; i < l; i++) { + if (i != breakPoint - 1) { + out += "/" + items[i]; + } else { + out += items[i]; + } + } + + return out; + }, + + /** + * Converts a relative path into a absolute path. + * + * @method toAbsPath + * @param {String} base Base point to convert the path from. + * @param {String} path Relative path to convert into an absolute path. + */ + 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; + }, + + /** + * Returns the full URI of the internal structure. + * + * @method getURI + * @param {Boolean} noProtoHost Optional no host and protocol part. Defaults to false. + */ + getURI: function(noProtoHost) { + var s, self = this; + + // Rebuild source + if (!self.source || noProtoHost) { + s = ''; + + if (!noProtoHost) { + if (self.protocol) { + s += self.protocol + '://'; + } + + if (self.userInfo) { + s += self.userInfo + '@'; + } + + if (self.host) { + s += self.host; + } + + if (self.port) { + s += ':' + self.port; + } + } + + if (self.path) { + s += self.path; + } + + if (self.query) { + s += '?' + self.query; + } + + if (self.anchor) { + s += '#' + self.anchor; + } + + self.source = s; + } + + return self.source; + } + }; + + return URI; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/util/VK.js b/lib/tinymce/jscripts/tinymce4/classes/util/VK.js new file mode 100644 index 00000000..94b868c9 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/util/VK.js @@ -0,0 +1,37 @@ +/** + * VK.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This file exposes a set of the common KeyCodes for use. Please grow it as needed. + */ +define("tinymce/util/VK", [ + "tinymce/Env" +], function(Env) { + return { + 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; + }, + + metaKeyPressed: function(e) { + // Check if ctrl or meta key is pressed also check if alt is false for Polish users + return Env.mac ? e.metaKey : e.ctrlKey && !e.altKey; + } + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/classes/util/XHR.js b/lib/tinymce/jscripts/tinymce4/classes/util/XHR.js new file mode 100644 index 00000000..7b87fbc4 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/classes/util/XHR.js @@ -0,0 +1,84 @@ +/** + * XHR.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class enables you to send XMLHTTPRequests cross browser. + * @class tinymce.util.XHR + * @static + * @example + * // Sends a low level Ajax request + * tinymce.util.XHR.send({ + * url: 'someurl', + * success: function(text) { + * console.debug(text); + * } + * }); + */ +define("tinymce/util/XHR", [], function() { + return { + /** + * Sends a XMLHTTPRequest. + * Consult the Wiki for details on what settings this method takes. + * + * @method send + * @param {Object} settings Object will target URL, callbacks and other info needed to make the request. + */ + send: function(settings) { + var xhr, count = 0; + + function ready() { + if (!settings.async || xhr.readyState == 4 || count++ > 10000) { + if (settings.success && count < 10000 && xhr.status == 200) { + settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings); + } else if (settings.error) { + settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings); + } + + xhr = null; + } else { + setTimeout(ready, 10); + } + } + + // Default settings + settings.scope = settings.scope || this; + settings.success_scope = settings.success_scope || settings.scope; + settings.error_scope = settings.error_scope || settings.scope; + settings.async = settings.async === false ? false : true; + settings.data = settings.data || ''; + + xhr = new XMLHttpRequest(); + + if (xhr) { + if (xhr.overrideMimeType) { + xhr.overrideMimeType(settings.content_type); + } + + xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async); + + if (settings.content_type) { + xhr.setRequestHeader('Content-Type', settings.content_type); + } + + xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); + + xhr.send(settings.data); + + // Syncronous request + if (!settings.async) { + return ready(); + } + + // Wait for response, onReadyStateChange can not be used since it leaks memory in IE + setTimeout(ready, 10); + } + } + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/jquery.tinymce.min.js b/lib/tinymce/jscripts/tinymce4/jquery.tinymce.min.js new file mode 100644 index 00000000..cfed3a4e --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/jquery.tinymce.min.js @@ -0,0 +1 @@ +(function(t){function e(){function e(t){"remove"===t&&this.each(function(t,e){var n=r(e);n&&n.remove()}),this.find("span.mceEditor,div.mceEditor").each(function(t,e){var n=tinymce.get(e.id.replace(/_parent$/,""));n&&n.remove()})}function i(t){var i,r=this;if(t!==n)e.call(r),r.each(function(e,n){var i;(i=tinymce.get(n.id))&&i.setContent(t)});else if(r.length>0&&(i=tinymce.get(r[0].id)))return i.getContent()}function r(t){var e=null;return t&&t.id&&a.tinymce&&(e=tinymce.get(t.id)),e}function c(t){return!!(t&&t.length&&a.tinymce&&t.is(":tinymce"))}var u={};t.each(["text","html","val"],function(e,a){var o=u[a]=t.fn[a],s="text"===a;t.fn[a]=function(e){var a=this;if(!c(a))return o.apply(a,arguments);if(e!==n)return i.call(a.filter(":tinymce"),e),o.apply(a.not(":tinymce"),arguments),a;var u="",l=arguments;return(s?a:a.eq(0)).each(function(e,n){var i=r(n);u+=i?s?i.getContent().replace(/<(?:"[^"]*"|'[^']*'|[^'">])*>/g,""):i.getContent({save:!0}):o.apply(t(n),l)}),u}}),t.each(["append","prepend"],function(e,i){var a=u[i]=t.fn[i],o="prepend"===i;t.fn[i]=function(t){var e=this;return c(e)?t!==n?(e.filter(":tinymce").each(function(e,n){var i=r(n);i&&i.setContent(o?t+i.getContent():i.getContent()+t)}),a.apply(e.not(":tinymce"),arguments),e):void 0:a.apply(e,arguments)}}),t.each(["remove","replaceWith","replaceAll","empty"],function(n,i){var r=u[i]=t.fn[i];t.fn[i]=function(){return e.call(this,i),r.apply(this,arguments)}}),u.attr=t.fn.attr,t.fn.attr=function(e,a){var o=this,s=arguments;if(!e||"value"!==e||!c(o))return a!==n?u.attr.apply(o,s):u.attr.apply(o,s);if(a!==n)return i.call(o.filter(":tinymce"),a),u.attr.apply(o.not(":tinymce"),s),o;var l=o[0],p=r(l);return p?p.getContent({save:!0}):u.attr.apply(t(l),s)}}var n,i,r=[],a=window;t.fn.tinymce=function(n){function c(){var i=[],r=0;e&&(e(),e=null),l.each(function(t,e){var a,c=e.id,u=n.oninit;c||(e.id=c=tinymce.DOM.uniqueId()),a=new tinymce.Editor(c,n,tinymce.EditorManager),i.push(a),a.on("init",function(){var t,e=u;l.css("visibility",""),u&&++r==i.length&&("string"==typeof e&&(t=-1===e.indexOf(".")?null:tinymce.resolve(e.replace(/\.\w+$/,"")),e=tinymce.resolve(e)),e.apply(t||tinymce,i))})}),t.each(i,function(t,e){e.render()})}var u,o,s,l=this,p="";if(!l.length)return l;if(!n)return tinymce.get(l[0].id);if(l.css("visibility","hidden"),a.tinymce||i||!(u=n.script_url))1===i?r.push(c):c();else{i=1,o=u.substring(0,u.lastIndexOf("/")),-1!=u.indexOf(".min")&&(p=".min"),a.tinymce=a.tinyMCEPreInit||{base:o,suffix:p},-1!=u.indexOf("gzip")&&(s=n.language||"en",u=u+(/\?/.test(u)?"&":"?")+"js=true&core=true&suffix="+escape(p)+"&themes="+escape(n.theme)+"&plugins="+escape(n.plugins)+"&languages="+s,a.tinyMCE_GZ||(a.tinyMCE_GZ={start:function(){function e(t){tinymce.ScriptLoader.markDone(tinymce.baseURI.toAbsolute(t))}e("langs/"+s+".js"),e("themes/"+n.theme+"/theme"+p+".js"),e("themes/"+n.theme+"/langs/"+s+".js"),t.each(n.plugins.split(","),function(t,n){n&&(e("plugins/"+n+"/plugin"+p+".js"),e("plugins/"+n+"/langs/"+s+".js"))})},end:function(){}}));var f=document.createElement("script");f.type="text/javascript",f.onload=f.onreadystatechange=function(e){e=e||event,("load"==e.type||/complete|loaded/.test(f.readyState))&&(tinymce.dom.Event.domLoaded=1,i=2,n.script_loaded&&n.script_loaded(),c(),t.each(r,function(t,e){e()}))},f.src=u,document.body.appendChild(f)}return l},t.extend(t.expr[":"],{tinymce:function(t){return!!(t.id&&"tinymce"in window&&tinymce.get(t.id))}})})(jQuery); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/langs/readme.md b/lib/tinymce/jscripts/tinymce4/langs/readme.md new file mode 100644 index 00000000..403563ca --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/langs/readme.md @@ -0,0 +1 @@ +This is where language files should be placed. \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/license.txt b/lib/tinymce/jscripts/tinymce4/license.txt new file mode 100644 index 00000000..1837b0ac --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/license.txt @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/lib/tinymce/jscripts/tinymce4/plugins/advlist/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/advlist/plugin.js new file mode 100644 index 00000000..665f9aa6 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/advlist/plugin.js @@ -0,0 +1,93 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('advlist', function(editor) { + var olMenuItems, ulMenuItems, lastStyles = {}; + + function buildMenuItems(listName, styleValues) { + var items = []; + + tinymce.each(styleValues.split(/[ ,]/), function(styleValue) { + items.push({ + text: styleValue.replace(/\-/g, ' ').replace(/\b\w/g, function(chr) {return chr.toUpperCase();}), + data: styleValue == 'default' ? '' : styleValue + }); + }); + + return items; + } + + olMenuItems = buildMenuItems('OL', editor.getParam( + "advlist_number_styles", + "default,lower-alpha,lower-greek,lower-roman,upper-alpha,upper-roman" + )); + + ulMenuItems = buildMenuItems('UL', editor.getParam("advlist_bullet_styles", "default,circle,disc,square")); + + function applyListFormat(listName, styleValue) { + var list, dom = editor.dom, sel = editor.selection; + + // Check for existing list element + list = dom.getParent(sel.getNode(), 'ol,ul'); + + // Switch/add list type if needed + if (!list || list.nodeName != listName || styleValue === false) { + editor.execCommand(listName == 'UL' ? 'InsertUnorderedList' : 'InsertOrderedList'); + } + + // Set style + styleValue = styleValue === false ? lastStyles[listName] : styleValue; + lastStyles[listName] = styleValue; + + list = dom.getParent(sel.getNode(), 'ol,ul'); + if (list) { + dom.setStyle(list, 'listStyleType', styleValue); + list.removeAttribute('data-mce-style'); + } + + editor.focus(); + } + + function updateSelection(e) { + var listStyleType = editor.dom.getStyle(editor.dom.getParent(editor.selection.getNode(), 'ol,ul'), 'listStyleType') || ''; + + e.control.items().each(function(ctrl) { + ctrl.active(ctrl.settings.data === listStyleType); + }); + } + + editor.addButton('numlist', { + type: 'splitbutton', + tooltip: 'Numbered list', + menu: olMenuItems, + onshow: updateSelection, + onselect: function(e) { + applyListFormat('OL', e.control.settings.data); + }, + onclick: function() { + applyListFormat('OL', false); + } + }); + + editor.addButton('bullist', { + type: 'splitbutton', + tooltip: 'Bullet list', + menu: ulMenuItems, + onshow: updateSelection, + onselect: function(e) { + applyListFormat('UL', e.control.settings.data); + }, + onclick: function() { + applyListFormat('UL', false); + } + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/advlist/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/advlist/plugin.min.js new file mode 100644 index 00000000..a4db7cca --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/advlist/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("advlist",function(t){function e(t,e){var n=[];return tinymce.each(e.split(/[ ,]/),function(t){n.push({text:t.replace(/\-/g," ").replace(/\b\w/g,function(t){return t.toUpperCase()}),data:"default"==t?"":t})}),n}function n(e,n){var o,l=t.dom,a=t.selection;o=l.getParent(a.getNode(),"ol,ul"),o&&o.nodeName==e&&n!==!1||t.execCommand("UL"==e?"InsertUnorderedList":"InsertOrderedList"),n=n===!1?i[e]:n,i[e]=n,o=l.getParent(a.getNode(),"ol,ul"),o&&(l.setStyle(o,"listStyleType",n),o.removeAttribute("data-mce-style")),t.focus()}function o(e){var n=t.dom.getStyle(t.dom.getParent(t.selection.getNode(),"ol,ul"),"listStyleType")||"";e.control.items().each(function(t){t.active(t.settings.data===n)})}var l,a,i={};l=e("OL",t.getParam("advlist_number_styles","default,lower-alpha,lower-greek,lower-roman,upper-alpha,upper-roman")),a=e("UL",t.getParam("advlist_bullet_styles","default,circle,disc,square")),t.addButton("numlist",{type:"splitbutton",tooltip:"Numbered list",menu:l,onshow:o,onselect:function(t){n("OL",t.control.settings.data)},onclick:function(){n("OL",!1)}}),t.addButton("bullist",{type:"splitbutton",tooltip:"Bullet list",menu:a,onshow:o,onselect:function(t){n("UL",t.control.settings.data)},onclick:function(){n("UL",!1)}})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/anchor/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/anchor/plugin.js new file mode 100644 index 00000000..59dac770 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/anchor/plugin.js @@ -0,0 +1,39 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('anchor', function(editor) { + function showDialog() { + editor.windowManager.open({ + title: 'Insert anchor', + body: {type: 'textbox', name: 'name', size: 40, label: 'Name', value: editor.selection.getNode().id}, + onsubmit: function(e) { + editor.execCommand('mceInsertContent', false, editor.dom.createHTML('a', { + id: e.data.name + })); + } + }); + } + + editor.addButton('anchor', { + icon: 'anchor', + tooltip: 'Insert anchor', + onclick: showDialog, + stateSelector: 'a:not([href])' + }); + + editor.addMenuItem('anchor', { + icon: 'anchor', + text: 'Anchor', + context: 'insert', + onclick: showDialog + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/anchor/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/anchor/plugin.min.js new file mode 100644 index 00000000..e6c14456 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/anchor/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("anchor",function(t){function e(){t.windowManager.open({title:"Insert anchor",body:{type:"textbox",name:"name",size:40,label:"Name",value:t.selection.getNode().id},onsubmit:function(e){t.execCommand("mceInsertContent",!1,t.dom.createHTML("a",{id:e.data.name}))}})}t.addButton("anchor",{icon:"anchor",tooltip:"Insert anchor",onclick:e,stateSelector:"a:not([href])"}),t.addMenuItem("anchor",{icon:"anchor",text:"Anchor",context:"insert",onclick:e})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/autolink/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/autolink/plugin.js new file mode 100644 index 00000000..f4306cb5 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/autolink/plugin.js @@ -0,0 +1,159 @@ +/** + * plugin.js + * + * Copyright 2011, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('autolink', function(editor) { + editor.on("keydown", function(e) { + if (e.keyCode == 13) { + return handleEnter(editor); + } + }); + + // Internet Explorer has built-in automatic linking for most cases + if (tinymce.Env.ie) { + return; + } + + editor.on("keypress", function(e) { + if (e.which == 41) { + return handleEclipse(editor); + } + }); + + editor.on("keyup", function(e) { + if (e.keyCode == 32) { + return handleSpacebar(editor); + } + }); + + function handleEclipse(editor) { + parseCurrentLine(editor, -1, '(', true); + } + + function handleSpacebar(editor) { + parseCurrentLine(editor, 0, '', true); + } + + function handleEnter(editor) { + parseCurrentLine(editor, -1, '', false); + } + + function parseCurrentLine(editor, end_offset, delimiter) { + var rng, end, start, endContainer, bookmark, text, matches, prev, len; + + // We need at least five characters to form a URL, + // hence, at minimum, five characters from the beginning of the line. + rng = editor.selection.getRng(true).cloneRange(); + if (rng.startOffset < 5) { + // During testing, the caret is placed inbetween two text nodes. + // The previous text node contains the URL. + prev = rng.endContainer.previousSibling; + if (!prev) { + if (!rng.endContainer.firstChild || !rng.endContainer.firstChild.nextSibling) { + return; + } + + prev = rng.endContainer.firstChild.nextSibling; + } + + len = prev.length; + rng.setStart(prev, len); + rng.setEnd(prev, len); + + if (rng.endOffset < 5) { + return; + } + + end = rng.endOffset; + endContainer = prev; + } else { + endContainer = rng.endContainer; + + // Get a text node + if (endContainer.nodeType != 3 && endContainer.firstChild) { + while (endContainer.nodeType != 3 && endContainer.firstChild) { + endContainer = endContainer.firstChild; + } + + // Move range to text node + if (endContainer.nodeType == 3) { + rng.setStart(endContainer, 0); + rng.setEnd(endContainer, endContainer.nodeValue.length); + } + } + + if (rng.endOffset == 1) { + end = 2; + } else { + end = rng.endOffset - 1 - end_offset; + } + } + + start = end; + + do { + // Move the selection one character backwards. + rng.setStart(endContainer, end >= 2 ? end - 2 : 0); + rng.setEnd(endContainer, end >= 1 ? end - 1 : 0); + end -= 1; + + // Loop until one of the following is found: a blank space,  , delimeter, (end-2) >= 0 + } while (rng.toString() != ' ' && rng.toString() !== '' && + rng.toString().charCodeAt(0) != 160 && (end -2) >= 0 && rng.toString() != delimiter); + + if (rng.toString() == delimiter || rng.toString().charCodeAt(0) == 160) { + rng.setStart(endContainer, end); + rng.setEnd(endContainer, start); + end += 1; + } else if (rng.startOffset === 0) { + rng.setStart(endContainer, 0); + rng.setEnd(endContainer, start); + } + else { + rng.setStart(endContainer, end); + rng.setEnd(endContainer, start); + } + + // Exclude last . from word like "www.site.com." + text = rng.toString(); + if (text.charAt(text.length - 1) == '.') { + rng.setEnd(endContainer, start - 1); + } + + text = rng.toString(); + matches = text.match(/^(https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.|(?:mailto:)?[A-Z0-9._%+\-]+@)(.+)$/i); + + if (matches) { + if (matches[1] == 'www.') { + matches[1] = 'http://www.'; + } else if (/@$/.test(matches[1]) && !/^mailto:/.test(matches[1])) { + matches[1] = 'mailto:' + matches[1]; + } + + bookmark = editor.selection.getBookmark(); + + editor.selection.setRng(rng); + editor.execCommand('createlink', false, matches[1] + matches[2]); + editor.selection.moveToBookmark(bookmark); + editor.nodeChanged(); + + // TODO: Determine if this is still needed. + if (tinymce.Env.webkit) { + // move the caret to its original position + editor.selection.collapse(false); + var max = Math.min(endContainer.length, start + 1); + rng.setStart(endContainer, max); + rng.setEnd(endContainer, max); + editor.selection.setRng(rng); + } + } + } +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/autolink/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/autolink/plugin.min.js new file mode 100644 index 00000000..dc5f9cd0 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/autolink/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("autolink",function(t){function e(t){i(t,-1,"(",!0)}function n(t){i(t,0,"",!0)}function o(t){i(t,-1,"",!1)}function i(t,e,n){var o,i,a,r,l,s,d,c,u;if(o=t.selection.getRng(!0).cloneRange(),5>o.startOffset){if(c=o.endContainer.previousSibling,!c){if(!o.endContainer.firstChild||!o.endContainer.firstChild.nextSibling)return;c=o.endContainer.firstChild.nextSibling}if(u=c.length,o.setStart(c,u),o.setEnd(c,u),5>o.endOffset)return;i=o.endOffset,r=c}else{if(r=o.endContainer,3!=r.nodeType&&r.firstChild){for(;3!=r.nodeType&&r.firstChild;)r=r.firstChild;3==r.nodeType&&(o.setStart(r,0),o.setEnd(r,r.nodeValue.length))}i=1==o.endOffset?2:o.endOffset-1-e}a=i;do o.setStart(r,i>=2?i-2:0),o.setEnd(r,i>=1?i-1:0),i-=1;while(" "!=""+o&&""!=""+o&&160!=(""+o).charCodeAt(0)&&i-2>=0&&""+o!=n);if(""+o==n||160==(""+o).charCodeAt(0)?(o.setStart(r,i),o.setEnd(r,a),i+=1):0===o.startOffset?(o.setStart(r,0),o.setEnd(r,a)):(o.setStart(r,i),o.setEnd(r,a)),s=""+o,"."==s.charAt(s.length-1)&&o.setEnd(r,a-1),s=""+o,d=s.match(/^(https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.|(?:mailto:)?[A-Z0-9._%+\-]+@)(.+)$/i),d&&("www."==d[1]?d[1]="http://www.":/@$/.test(d[1])&&!/^mailto:/.test(d[1])&&(d[1]="mailto:"+d[1]),l=t.selection.getBookmark(),t.selection.setRng(o),t.execCommand("createlink",!1,d[1]+d[2]),t.selection.moveToBookmark(l),t.nodeChanged(),tinymce.Env.webkit)){t.selection.collapse(!1);var f=Math.min(r.length,a+1);o.setStart(r,f),o.setEnd(r,f),t.selection.setRng(o)}}t.on("keydown",function(e){return 13==e.keyCode?o(t):void 0}),tinymce.Env.ie||(t.on("keypress",function(n){return 41==n.which?e(t):void 0}),t.on("keyup",function(e){return 32==e.keyCode?n(t):void 0}))}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/autoresize/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/autoresize/plugin.js new file mode 100644 index 00000000..3c86568b --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/autoresize/plugin.js @@ -0,0 +1,87 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +/** + * Auto Resize + * + * This plugin automatically resizes the content area to fit its content height. + * It will retain a minimum height, which is the height of the content area when + * it's initialized. + */ +tinymce.PluginManager.add('autoresize', function(editor) { + var settings = editor.settings, oldSize = 0; + + /** + * This method gets executed each time the editor needs to resize. + */ + function resize(e) { + var deltaSize, d = editor.getDoc(), body = d.body, de = d.documentElement, DOM = tinymce.DOM; + var resizeHeight = settings.autoresize_min_height, myHeight; + + if ((e.type == "setcontent" && e.initial) || (editor.plugins.fullscreen && editor.plugins.fullscreen.isFullscreen())) { + return; + } + + // Get height differently depending on the browser used + myHeight = tinymce.Env.ie ? body.scrollHeight : (tinymce.Env.webkit && body.clientHeight === 0 ? 0 : body.offsetHeight); + + // Don't make it smaller than the minimum height + if (myHeight > settings.autoresize_min_height) { + resizeHeight = myHeight; + } + + // If a maximum height has been defined don't exceed this height + if (settings.autoresize_max_height && myHeight > settings.autoresize_max_height) { + resizeHeight = settings.autoresize_max_height; + body.style.overflowY = "auto"; + de.style.overflowY = "auto"; // Old IE + } else { + body.style.overflowY = "hidden"; + de.style.overflowY = "hidden"; // Old IE + body.scrollTop = 0; + } + + // Resize content element + if (resizeHeight !== oldSize) { + deltaSize = resizeHeight - oldSize; + DOM.setStyle(DOM.get(editor.id + '_ifr'), 'height', resizeHeight + 'px'); + oldSize = resizeHeight; + + // WebKit doesn't decrease the size of the body element until the iframe gets resized + // So we need to continue to resize the iframe down until the size gets fixed + if (tinymce.isWebKit && deltaSize < 0) { + resize(e); + } + } + } + + // Define minimum height + settings.autoresize_min_height = parseInt(editor.getParam('autoresize_min_height', editor.getElement().offsetHeight), 10); + + // Define maximum height + settings.autoresize_max_height = parseInt(editor.getParam('autoresize_max_height', 0), 10); + + // Add padding at the bottom for better UX + editor.on("init", function() { + editor.dom.setStyle(editor.getBody(), 'paddingBottom', editor.getParam('autoresize_bottom_margin', 50) + 'px'); + }); + + // Add appropriate listeners for resizing content area + editor.on("change setcontent paste keyup", resize); + + if (editor.getParam('autoresize_on_init', true)) { + editor.on('load', resize); + } + + // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample'); + editor.addCommand('mceAutoResize', resize); +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/autoresize/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/autoresize/plugin.min.js new file mode 100644 index 00000000..e38f0461 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/autoresize/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("autoresize",function(e){function t(i){var a,s,r=e.getDoc(),l=r.body,c=r.documentElement,d=tinymce.DOM,u=n.autoresize_min_height;"setcontent"==i.type&&i.initial||e.plugins.fullscreen&&e.plugins.fullscreen.isFullscreen()||(s=tinymce.Env.ie?l.scrollHeight:tinymce.Env.webkit&&0===l.clientHeight?0:l.offsetHeight,s>n.autoresize_min_height&&(u=s),n.autoresize_max_height&&s>n.autoresize_max_height?(u=n.autoresize_max_height,l.style.overflowY="auto",c.style.overflowY="auto"):(l.style.overflowY="hidden",c.style.overflowY="hidden",l.scrollTop=0),u!==o&&(a=u-o,d.setStyle(d.get(e.id+"_ifr"),"height",u+"px"),o=u,tinymce.isWebKit&&0>a&&t(i)))}var n=e.settings,o=0;n.autoresize_min_height=parseInt(e.getParam("autoresize_min_height",e.getElement().offsetHeight),10),n.autoresize_max_height=parseInt(e.getParam("autoresize_max_height",0),10),e.on("init",function(){e.dom.setStyle(e.getBody(),"paddingBottom",e.getParam("autoresize_bottom_margin",50)+"px")}),e.on("change setcontent paste keyup",t),e.getParam("autoresize_on_init",!0)&&e.on("load",t),e.addCommand("mceAutoResize",t)}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/autosave/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/autosave/plugin.js new file mode 100644 index 00000000..8da83ba3 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/autosave/plugin.js @@ -0,0 +1,127 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('autosave', function(editor) { + var settings = editor.settings, LocalStorage = tinymce.util.LocalStorage, prefix = editor.id, started; + + function parseTime(time, defaultTime) { + var multipels = { + s: 1000, + m: 60000 + }; + + time = /^(\d+)([ms]?)$/.exec('' + (time || defaultTime)); + + return (time[2] ? multipels[time[2]] : 1) * parseInt(time, 10); + } + + function hasDraft() { + var time = parseInt(LocalStorage.getItem(prefix + "autosave.time"), 10) || 0; + + if (new Date().getTime() - time > settings.autosave_retention) { + removeDraft(); + return false; + } + + return true; + } + + function removeDraft() { + LocalStorage.removeItem(prefix + "autosave.draft"); + LocalStorage.removeItem(prefix + "autosave.time"); + } + + function storeDraft() { + if (started && editor.isDirty()) { + LocalStorage.setItem(prefix + "autosave.draft", editor.getContent({format: 'raw', no_events: true})); + LocalStorage.setItem(prefix + "autosave.time", new Date().getTime()); + editor.fire('StoreDraft'); + } + } + + function restoreDraft() { + if (hasDraft()) { + editor.setContent(LocalStorage.getItem(prefix + "autosave.draft"), {format: 'raw'}); + removeDraft(); + editor.fire('RestoreDraft'); + } + } + + function startStoreDraft() { + if (!started) { + setInterval(function() { + if (!editor.removed) { + storeDraft(); + } + }, settings.autosave_interval); + + started = true; + } + } + + settings.autosave_interval = parseTime(settings.autosave_interval, '30s'); + settings.autosave_retention = parseTime(settings.autosave_retention, '20m'); + + function postRender() { + var self = this; + + self.disabled(!hasDraft()); + + editor.on('StoreDraft RestoreDraft', function() { + self.disabled(!hasDraft()); + }); + + startStoreDraft(); + } + + function restoreLastDraft() { + editor.undoManager.beforeChange(); + restoreDraft(); + editor.undoManager.add(); + } + + editor.addButton('restoredraft', { + title: 'Restore draft', + onclick: restoreLastDraft, + onPostRender: postRender + }); + + editor.addMenuItem('restoredraft', { + text: 'Restore last draft', + onclick: restoreLastDraft, + onPostRender: postRender, + context: 'file' + }); + + this.storeDraft = storeDraft; + + // Internal unload handler will be called before the page is unloaded + function beforeUnloadHandler() { + var msg; + + tinymce.each(tinymce.editors, function(editor) { + // Store a draft for each editor instance + if (editor.plugins.autosave) { + editor.plugins.autosave.storeDraft(); + } + + // Setup a return message if the editor is dirty + if (!msg && editor.isDirty() && editor.getParam("autosave_ask_before_unload", true)) { + msg = editor.translate("You have unsaved changes are you sure you want to navigate away?"); + } + }); + + return msg; + } + + window.onbeforeunload = beforeUnloadHandler; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/autosave/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/autosave/plugin.min.js new file mode 100644 index 00000000..c1423ee5 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/autosave/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("autosave",function(e){function t(e,t){var n={s:1e3,m:6e4};return e=/^(\d+)([ms]?)$/.exec(""+(e||t)),(e[2]?n[e[2]]:1)*parseInt(e,10)}function n(){var e=parseInt(f.getItem(m+"autosave.time"),10)||0;return(new Date).getTime()-e>c.autosave_retention?(o(),!1):!0}function o(){f.removeItem(m+"autosave.draft"),f.removeItem(m+"autosave.time")}function a(){d&&e.isDirty()&&(f.setItem(m+"autosave.draft",e.getContent({format:"raw",no_events:!0})),f.setItem(m+"autosave.time",(new Date).getTime()),e.fire("StoreDraft"))}function i(){n()&&(e.setContent(f.getItem(m+"autosave.draft"),{format:"raw"}),o(),e.fire("RestoreDraft"))}function r(){d||(setInterval(function(){e.removed||a()},c.autosave_interval),d=!0)}function s(){var t=this;t.disabled(!n()),e.on("StoreDraft RestoreDraft",function(){t.disabled(!n())}),r()}function l(){e.undoManager.beforeChange(),i(),e.undoManager.add()}function u(){var e;return tinymce.each(tinymce.editors,function(t){t.plugins.autosave&&t.plugins.autosave.storeDraft(),!e&&t.isDirty()&&t.getParam("autosave_ask_before_unload",!0)&&(e=t.translate("You have unsaved changes are you sure you want to navigate away?"))}),e}var d,c=e.settings,f=tinymce.util.LocalStorage,m=e.id;c.autosave_interval=t(c.autosave_interval,"30s"),c.autosave_retention=t(c.autosave_retention,"20m"),e.addButton("restoredraft",{title:"Restore draft",onclick:l,onPostRender:s}),e.addMenuItem("restoredraft",{text:"Restore last draft",onclick:l,onPostRender:s,context:"file"}),this.storeDraft=a,window.onbeforeunload=u}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/bbcode/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/bbcode/plugin.js new file mode 100644 index 00000000..b3ac04b8 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/bbcode/plugin.js @@ -0,0 +1,123 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +(function() { + tinymce.create('tinymce.plugins.BBCodePlugin', { + init : function(ed) { + var t = this, dialect = ed.getParam('bbcode_dialect', 'punbb').toLowerCase(); + + ed.on('beforeSetContent', function(e) { + e.content = t['_' + dialect + '_bbcode2html'](e.content); + }); + + ed.on('postProcess', function(e) { + if (e.set) { + e.content = t['_' + dialect + '_bbcode2html'](e.content); + } + + if (e.get) { + e.content = t['_' + dialect + '_html2bbcode'](e.content); + } + }); + }, + + getInfo: function() { + return { + longname: 'BBCode Plugin', + author: 'Moxiecode Systems AB', + authorurl: 'http://www.tinymce.com', + infourl: 'http://www.tinymce.com/wiki.php/Plugin:bbcode' + }; + }, + + // Private methods + + // HTML -> BBCode in PunBB dialect + _punbb_html2bbcode : function(s) { + s = tinymce.trim(s); + + function rep(re, str) { + s = s.replace(re, str); + } + + // example: to [b] + rep(/(.*?)<\/a>/gi,"[url=$1]$2[/url]"); + rep(/(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]"); + rep(/(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]"); + rep(/(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]"); + rep(/(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]"); + rep(/(.*?)<\/span>/gi,"[color=$1]$2[/color]"); + rep(/(.*?)<\/font>/gi,"[color=$1]$2[/color]"); + rep(/(.*?)<\/span>/gi,"[size=$1]$2[/size]"); + rep(/(.*?)<\/font>/gi,"$1"); + rep(//gi,"[img]$1[/img]"); + rep(/(.*?)<\/span>/gi,"[code]$1[/code]"); + rep(/(.*?)<\/span>/gi,"[quote]$1[/quote]"); + rep(/(.*?)<\/strong>/gi,"[code][b]$1[/b][/code]"); + rep(/(.*?)<\/strong>/gi,"[quote][b]$1[/b][/quote]"); + rep(/(.*?)<\/em>/gi,"[code][i]$1[/i][/code]"); + rep(/(.*?)<\/em>/gi,"[quote][i]$1[/i][/quote]"); + rep(/(.*?)<\/u>/gi,"[code][u]$1[/u][/code]"); + rep(/(.*?)<\/u>/gi,"[quote][u]$1[/u][/quote]"); + rep(/<\/(strong|b)>/gi,"[/b]"); + rep(/<(strong|b)>/gi,"[b]"); + rep(/<\/(em|i)>/gi,"[/i]"); + rep(/<(em|i)>/gi,"[i]"); + rep(/<\/u>/gi,"[/u]"); + rep(/(.*?)<\/span>/gi,"[u]$1[/u]"); + rep(//gi,"[u]"); + rep(/]*>/gi,"[quote]"); + rep(/<\/blockquote>/gi,"[/quote]"); + rep(/
    /gi,"\n"); + rep(//gi,"\n"); + rep(/
    /gi,"\n"); + rep(/

    /gi,""); + rep(/<\/p>/gi,"\n"); + rep(/ |\u00a0/gi," "); + rep(/"/gi,"\""); + rep(/</gi,"<"); + rep(/>/gi,">"); + rep(/&/gi,"&"); + + return s; + }, + + // BBCode -> HTML from PunBB dialect + _punbb_bbcode2html : function(s) { + s = tinymce.trim(s); + + function rep(re, str) { + s = s.replace(re, str); + } + + // example: [b] to + rep(/\n/gi,"
    "); + rep(/\[b\]/gi,""); + rep(/\[\/b\]/gi,""); + rep(/\[i\]/gi,""); + rep(/\[\/i\]/gi,""); + rep(/\[u\]/gi,""); + rep(/\[\/u\]/gi,""); + rep(/\[url=([^\]]+)\](.*?)\[\/url\]/gi,"$2"); + rep(/\[url\](.*?)\[\/url\]/gi,"$1"); + rep(/\[img\](.*?)\[\/img\]/gi,""); + rep(/\[color=(.*?)\](.*?)\[\/color\]/gi,"$2"); + rep(/\[code\](.*?)\[\/code\]/gi,"$1 "); + rep(/\[quote.*?\](.*?)\[\/quote\]/gi,"$1 "); + + return s; + } + }); + + // Register plugin + tinymce.PluginManager.add('bbcode', tinymce.plugins.BBCodePlugin); +})(); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/bbcode/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/bbcode/plugin.min.js new file mode 100644 index 00000000..578e8985 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/bbcode/plugin.min.js @@ -0,0 +1 @@ +(function(){tinymce.create("tinymce.plugins.BBCodePlugin",{init:function(e){var t=this,n=e.getParam("bbcode_dialect","punbb").toLowerCase();e.on("beforeSetContent",function(e){e.content=t["_"+n+"_bbcode2html"](e.content)}),e.on("postProcess",function(e){e.set&&(e.content=t["_"+n+"_bbcode2html"](e.content)),e.get&&(e.content=t["_"+n+"_html2bbcode"](e.content))})},getInfo:function(){return{longname:"BBCode Plugin",author:"Moxiecode Systems AB",authorurl:"http://www.tinymce.com",infourl:"http://www.tinymce.com/wiki.php/Plugin:bbcode"}},_punbb_html2bbcode:function(e){function t(t,n){e=e.replace(t,n)}return e=tinymce.trim(e),t(/(.*?)<\/a>/gi,"[url=$1]$2[/url]"),t(/(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]"),t(/(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]"),t(/(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]"),t(/(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]"),t(/(.*?)<\/span>/gi,"[color=$1]$2[/color]"),t(/(.*?)<\/font>/gi,"[color=$1]$2[/color]"),t(/(.*?)<\/span>/gi,"[size=$1]$2[/size]"),t(/(.*?)<\/font>/gi,"$1"),t(//gi,"[img]$1[/img]"),t(/(.*?)<\/span>/gi,"[code]$1[/code]"),t(/(.*?)<\/span>/gi,"[quote]$1[/quote]"),t(/(.*?)<\/strong>/gi,"[code][b]$1[/b][/code]"),t(/(.*?)<\/strong>/gi,"[quote][b]$1[/b][/quote]"),t(/(.*?)<\/em>/gi,"[code][i]$1[/i][/code]"),t(/(.*?)<\/em>/gi,"[quote][i]$1[/i][/quote]"),t(/(.*?)<\/u>/gi,"[code][u]$1[/u][/code]"),t(/(.*?)<\/u>/gi,"[quote][u]$1[/u][/quote]"),t(/<\/(strong|b)>/gi,"[/b]"),t(/<(strong|b)>/gi,"[b]"),t(/<\/(em|i)>/gi,"[/i]"),t(/<(em|i)>/gi,"[i]"),t(/<\/u>/gi,"[/u]"),t(/(.*?)<\/span>/gi,"[u]$1[/u]"),t(//gi,"[u]"),t(/]*>/gi,"[quote]"),t(/<\/blockquote>/gi,"[/quote]"),t(/
    /gi,"\n"),t(//gi,"\n"),t(/
    /gi,"\n"),t(/

    /gi,""),t(/<\/p>/gi,"\n"),t(/ |\u00a0/gi," "),t(/"/gi,'"'),t(/</gi,"<"),t(/>/gi,">"),t(/&/gi,"&"),e},_punbb_bbcode2html:function(e){function t(t,n){e=e.replace(t,n)}return e=tinymce.trim(e),t(/\n/gi,"
    "),t(/\[b\]/gi,""),t(/\[\/b\]/gi,""),t(/\[i\]/gi,""),t(/\[\/i\]/gi,""),t(/\[u\]/gi,""),t(/\[\/u\]/gi,""),t(/\[url=([^\]]+)\](.*?)\[\/url\]/gi,'$2'),t(/\[url\](.*?)\[\/url\]/gi,'$1'),t(/\[img\](.*?)\[\/img\]/gi,''),t(/\[color=(.*?)\](.*?)\[\/color\]/gi,'$2'),t(/\[code\](.*?)\[\/code\]/gi,'$1 '),t(/\[quote.*?\](.*?)\[\/quote\]/gi,'$1 '),e}}),tinymce.PluginManager.add("bbcode",tinymce.plugins.BBCodePlugin)})(); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/charmap/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/charmap/plugin.js new file mode 100644 index 00000000..b82b671b --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/charmap/plugin.js @@ -0,0 +1,361 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('charmap', function(editor) { + var charmap = [ + ['160', 'no-break space'], + ['38', 'ampersand'], + ['34', 'quotation mark'], + // finance + ['162', 'cent sign'], + ['8364', 'euro sign'], + ['163', 'pound sign'], + ['165', 'yen sign'], + // signs + ['169', 'copyright sign'], + ['174', 'registered sign'], + ['8482', 'trade mark sign'], + ['8240', 'per mille sign'], + ['181', 'micro sign'], + ['183', 'middle dot'], + ['8226', 'bullet'], + ['8230', 'three dot leader'], + ['8242', 'minutes / feet'], + ['8243', 'seconds / inches'], + ['167', 'section sign'], + ['182', 'paragraph sign'], + ['223', 'sharp s / ess-zed'], + // quotations + ['8249', 'single left-pointing angle quotation mark'], + ['8250', 'single right-pointing angle quotation mark'], + ['171', 'left pointing guillemet'], + ['187', 'right pointing guillemet'], + ['8216', 'left single quotation mark'], + ['8217', 'right single quotation mark'], + ['8220', 'left double quotation mark'], + ['8221', 'right double quotation mark'], + ['8218', 'single low-9 quotation mark'], + ['8222', 'double low-9 quotation mark'], + ['60', 'less-than sign'], + ['62', 'greater-than sign'], + ['8804', 'less-than or equal to'], + ['8805', 'greater-than or equal to'], + ['8211', 'en dash'], + ['8212', 'em dash'], + ['175', 'macron'], + ['8254', 'overline'], + ['164', 'currency sign'], + ['166', 'broken bar'], + ['168', 'diaeresis'], + ['161', 'inverted exclamation mark'], + ['191', 'turned question mark'], + ['710', 'circumflex accent'], + ['732', 'small tilde'], + ['176', 'degree sign'], + ['8722', 'minus sign'], + ['177', 'plus-minus sign'], + ['247', 'division sign'], + ['8260', 'fraction slash'], + ['215', 'multiplication sign'], + ['185', 'superscript one'], + ['178', 'superscript two'], + ['179', 'superscript three'], + ['188', 'fraction one quarter'], + ['189', 'fraction one half'], + ['190', 'fraction three quarters'], + // math / logical + ['402', 'function / florin'], + ['8747', 'integral'], + ['8721', 'n-ary sumation'], + ['8734', 'infinity'], + ['8730', 'square root'], + ['8764', 'similar to'], + ['8773', 'approximately equal to'], + ['8776', 'almost equal to'], + ['8800', 'not equal to'], + ['8801', 'identical to'], + ['8712', 'element of'], + ['8713', 'not an element of'], + ['8715', 'contains as member'], + ['8719', 'n-ary product'], + ['8743', 'logical and'], + ['8744', 'logical or'], + ['172', 'not sign'], + ['8745', 'intersection'], + ['8746', 'union'], + ['8706', 'partial differential'], + ['8704', 'for all'], + ['8707', 'there exists'], + ['8709', 'diameter'], + ['8711', 'backward difference'], + ['8727', 'asterisk operator'], + ['8733', 'proportional to'], + ['8736', 'angle'], + // undefined + ['180', 'acute accent'], + ['184', 'cedilla'], + ['170', 'feminine ordinal indicator'], + ['186', 'masculine ordinal indicator'], + ['8224', 'dagger'], + ['8225', 'double dagger'], + // alphabetical special chars + ['192', 'A - grave'], + ['193', 'A - acute'], + ['194', 'A - circumflex'], + ['195', 'A - tilde'], + ['196', 'A - diaeresis'], + ['197', 'A - ring above'], + ['198', 'ligature AE'], + ['199', 'C - cedilla'], + ['200', 'E - grave'], + ['201', 'E - acute'], + ['202', 'E - circumflex'], + ['203', 'E - diaeresis'], + ['204', 'I - grave'], + ['205', 'I - acute'], + ['206', 'I - circumflex'], + ['207', 'I - diaeresis'], + ['208', 'ETH'], + ['209', 'N - tilde'], + ['210', 'O - grave'], + ['211', 'O - acute'], + ['212', 'O - circumflex'], + ['213', 'O - tilde'], + ['214', 'O - diaeresis'], + ['216', 'O - slash'], + ['338', 'ligature OE'], + ['352', 'S - caron'], + ['217', 'U - grave'], + ['218', 'U - acute'], + ['219', 'U - circumflex'], + ['220', 'U - diaeresis'], + ['221', 'Y - acute'], + ['376', 'Y - diaeresis'], + ['222', 'THORN'], + ['224', 'a - grave'], + ['225', 'a - acute'], + ['226', 'a - circumflex'], + ['227', 'a - tilde'], + ['228', 'a - diaeresis'], + ['229', 'a - ring above'], + ['230', 'ligature ae'], + ['231', 'c - cedilla'], + ['232', 'e - grave'], + ['233', 'e - acute'], + ['234', 'e - circumflex'], + ['235', 'e - diaeresis'], + ['236', 'i - grave'], + ['237', 'i - acute'], + ['238', 'i - circumflex'], + ['239', 'i - diaeresis'], + ['240', 'eth'], + ['241', 'n - tilde'], + ['242', 'o - grave'], + ['243', 'o - acute'], + ['244', 'o - circumflex'], + ['245', 'o - tilde'], + ['246', 'o - diaeresis'], + ['248', 'o slash'], + ['339', 'ligature oe'], + ['353', 's - caron'], + ['249', 'u - grave'], + ['250', 'u - acute'], + ['251', 'u - circumflex'], + ['252', 'u - diaeresis'], + ['253', 'y - acute'], + ['254', 'thorn'], + ['255', 'y - diaeresis'], + ['913', 'Alpha'], + ['914', 'Beta'], + ['915', 'Gamma'], + ['916', 'Delta'], + ['917', 'Epsilon'], + ['918', 'Zeta'], + ['919', 'Eta'], + ['920', 'Theta'], + ['921', 'Iota'], + ['922', 'Kappa'], + ['923', 'Lambda'], + ['924', 'Mu'], + ['925', 'Nu'], + ['926', 'Xi'], + ['927', 'Omicron'], + ['928', 'Pi'], + ['929', 'Rho'], + ['931', 'Sigma'], + ['932', 'Tau'], + ['933', 'Upsilon'], + ['934', 'Phi'], + ['935', 'Chi'], + ['936', 'Psi'], + ['937', 'Omega'], + ['945', 'alpha'], + ['946', 'beta'], + ['947', 'gamma'], + ['948', 'delta'], + ['949', 'epsilon'], + ['950', 'zeta'], + ['951', 'eta'], + ['952', 'theta'], + ['953', 'iota'], + ['954', 'kappa'], + ['955', 'lambda'], + ['956', 'mu'], + ['957', 'nu'], + ['958', 'xi'], + ['959', 'omicron'], + ['960', 'pi'], + ['961', 'rho'], + ['962', 'final sigma'], + ['963', 'sigma'], + ['964', 'tau'], + ['965', 'upsilon'], + ['966', 'phi'], + ['967', 'chi'], + ['968', 'psi'], + ['969', 'omega'], + // symbols + ['8501', 'alef symbol'], + ['982', 'pi symbol'], + ['8476', 'real part symbol'], + ['978', 'upsilon - hook symbol'], + ['8472', 'Weierstrass p'], + ['8465', 'imaginary part'], + // arrows + ['8592', 'leftwards arrow'], + ['8593', 'upwards arrow'], + ['8594', 'rightwards arrow'], + ['8595', 'downwards arrow'], + ['8596', 'left right arrow'], + ['8629', 'carriage return'], + ['8656', 'leftwards double arrow'], + ['8657', 'upwards double arrow'], + ['8658', 'rightwards double arrow'], + ['8659', 'downwards double arrow'], + ['8660', 'left right double arrow'], + ['8756', 'therefore'], + ['8834', 'subset of'], + ['8835', 'superset of'], + ['8836', 'not a subset of'], + ['8838', 'subset of or equal to'], + ['8839', 'superset of or equal to'], + ['8853', 'circled plus'], + ['8855', 'circled times'], + ['8869', 'perpendicular'], + ['8901', 'dot operator'], + ['8968', 'left ceiling'], + ['8969', 'right ceiling'], + ['8970', 'left floor'], + ['8971', 'right floor'], + ['9001', 'left-pointing angle bracket'], + ['9002', 'right-pointing angle bracket'], + ['9674', 'lozenge'], + ['9824', 'black spade suit'], + ['9827', 'black club suit'], + ['9829', 'black heart suit'], + ['9830', 'black diamond suit'], + ['8194', 'en space'], + ['8195', 'em space'], + ['8201', 'thin space'], + ['8204', 'zero width non-joiner'], + ['8205', 'zero width joiner'], + ['8206', 'left-to-right mark'], + ['8207', 'right-to-left mark'], + ['173', 'soft hyphen'] + ]; + + function showDialog() { + var gridHtml, x, y, win; + + function getParentTd(elm) { + while (elm) { + if (elm.nodeName == 'TD') { + return elm; + } + + elm = elm.parentNode; + } + } + + gridHtml = ''; + + for (y = 0; y < 10; y++) { + gridHtml += ''; + + for (x = 0; x < 20; x++) { + var chr = charmap[y * 10 + x]; + var id = 'g' + (y * 10 + x); + + gridHtml += ''; + } + + gridHtml += ''; + } + + gridHtml += ''; + + var charMapPanel = { + type: 'container', + html: gridHtml, + onclick: function(e) { + var target = e.target; + if (target.nodeName == 'DIV') { + editor.execCommand('mceInsertContent', false, target.firstChild.nodeValue); + } + }, + onmouseover: function(e) { + var td = getParentTd(e.target); + + if (td) { + win.find('#preview').text(td.firstChild.firstChild.data); + } + } + }; + + win = editor.windowManager.open({ + title: "Special characters", + spacing: 10, + padding: 10, + items: [ + charMapPanel, + { + type: 'label', + name: 'preview', + text: ' ', + style: 'font-size: 40px; text-align: center', + border: 1, + minWidth: 100, + minHeight: 80 + } + ], + buttons: [ + {text: "Close", onclick: function() { + win.close(); + }} + ] + }); + } + + editor.addButton('charmap', { + icon: 'charmap', + tooltip: 'Insert special character', + onclick: showDialog + }); + + editor.addMenuItem('charmap', { + icon: 'charmap', + text: 'Special character', + onclick: showDialog, + context: 'insert' + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/charmap/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/charmap/plugin.min.js new file mode 100644 index 00000000..c491c904 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/charmap/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("charmap",function(e){function t(){function t(e){for(;e;){if("TD"==e.nodeName)return e;e=e.parentNode}}var o,i,a,r;for(o='',a=0;10>a;a++){for(o+="",i=0;20>i;i++){var s=n[10*a+i],l="g"+(10*a+i);o+='"}o+=""}o+="";var c={type:"container",html:o,onclick:function(t){var n=t.target;"DIV"==n.nodeName&&e.execCommand("mceInsertContent",!1,n.firstChild.nodeValue)},onmouseover:function(e){var n=t(e.target);n&&r.find("#preview").text(n.firstChild.firstChild.data)}};r=e.windowManager.open({title:"Special characters",spacing:10,padding:10,items:[c,{type:"label",name:"preview",text:" ",style:"font-size: 40px; text-align: center",border:1,minWidth:100,minHeight:80}],buttons:[{text:"Close",onclick:function(){r.close()}}]})}var n=[["160","no-break space"],["38","ampersand"],["34","quotation mark"],["162","cent sign"],["8364","euro sign"],["163","pound sign"],["165","yen sign"],["169","copyright sign"],["174","registered sign"],["8482","trade mark sign"],["8240","per mille sign"],["181","micro sign"],["183","middle dot"],["8226","bullet"],["8230","three dot leader"],["8242","minutes / feet"],["8243","seconds / inches"],["167","section sign"],["182","paragraph sign"],["223","sharp s / ess-zed"],["8249","single left-pointing angle quotation mark"],["8250","single right-pointing angle quotation mark"],["171","left pointing guillemet"],["187","right pointing guillemet"],["8216","left single quotation mark"],["8217","right single quotation mark"],["8220","left double quotation mark"],["8221","right double quotation mark"],["8218","single low-9 quotation mark"],["8222","double low-9 quotation mark"],["60","less-than sign"],["62","greater-than sign"],["8804","less-than or equal to"],["8805","greater-than or equal to"],["8211","en dash"],["8212","em dash"],["175","macron"],["8254","overline"],["164","currency sign"],["166","broken bar"],["168","diaeresis"],["161","inverted exclamation mark"],["191","turned question mark"],["710","circumflex accent"],["732","small tilde"],["176","degree sign"],["8722","minus sign"],["177","plus-minus sign"],["247","division sign"],["8260","fraction slash"],["215","multiplication sign"],["185","superscript one"],["178","superscript two"],["179","superscript three"],["188","fraction one quarter"],["189","fraction one half"],["190","fraction three quarters"],["402","function / florin"],["8747","integral"],["8721","n-ary sumation"],["8734","infinity"],["8730","square root"],["8764","similar to"],["8773","approximately equal to"],["8776","almost equal to"],["8800","not equal to"],["8801","identical to"],["8712","element of"],["8713","not an element of"],["8715","contains as member"],["8719","n-ary product"],["8743","logical and"],["8744","logical or"],["172","not sign"],["8745","intersection"],["8746","union"],["8706","partial differential"],["8704","for all"],["8707","there exists"],["8709","diameter"],["8711","backward difference"],["8727","asterisk operator"],["8733","proportional to"],["8736","angle"],["180","acute accent"],["184","cedilla"],["170","feminine ordinal indicator"],["186","masculine ordinal indicator"],["8224","dagger"],["8225","double dagger"],["192","A - grave"],["193","A - acute"],["194","A - circumflex"],["195","A - tilde"],["196","A - diaeresis"],["197","A - ring above"],["198","ligature AE"],["199","C - cedilla"],["200","E - grave"],["201","E - acute"],["202","E - circumflex"],["203","E - diaeresis"],["204","I - grave"],["205","I - acute"],["206","I - circumflex"],["207","I - diaeresis"],["208","ETH"],["209","N - tilde"],["210","O - grave"],["211","O - acute"],["212","O - circumflex"],["213","O - tilde"],["214","O - diaeresis"],["216","O - slash"],["338","ligature OE"],["352","S - caron"],["217","U - grave"],["218","U - acute"],["219","U - circumflex"],["220","U - diaeresis"],["221","Y - acute"],["376","Y - diaeresis"],["222","THORN"],["224","a - grave"],["225","a - acute"],["226","a - circumflex"],["227","a - tilde"],["228","a - diaeresis"],["229","a - ring above"],["230","ligature ae"],["231","c - cedilla"],["232","e - grave"],["233","e - acute"],["234","e - circumflex"],["235","e - diaeresis"],["236","i - grave"],["237","i - acute"],["238","i - circumflex"],["239","i - diaeresis"],["240","eth"],["241","n - tilde"],["242","o - grave"],["243","o - acute"],["244","o - circumflex"],["245","o - tilde"],["246","o - diaeresis"],["248","o slash"],["339","ligature oe"],["353","s - caron"],["249","u - grave"],["250","u - acute"],["251","u - circumflex"],["252","u - diaeresis"],["253","y - acute"],["254","thorn"],["255","y - diaeresis"],["913","Alpha"],["914","Beta"],["915","Gamma"],["916","Delta"],["917","Epsilon"],["918","Zeta"],["919","Eta"],["920","Theta"],["921","Iota"],["922","Kappa"],["923","Lambda"],["924","Mu"],["925","Nu"],["926","Xi"],["927","Omicron"],["928","Pi"],["929","Rho"],["931","Sigma"],["932","Tau"],["933","Upsilon"],["934","Phi"],["935","Chi"],["936","Psi"],["937","Omega"],["945","alpha"],["946","beta"],["947","gamma"],["948","delta"],["949","epsilon"],["950","zeta"],["951","eta"],["952","theta"],["953","iota"],["954","kappa"],["955","lambda"],["956","mu"],["957","nu"],["958","xi"],["959","omicron"],["960","pi"],["961","rho"],["962","final sigma"],["963","sigma"],["964","tau"],["965","upsilon"],["966","phi"],["967","chi"],["968","psi"],["969","omega"],["8501","alef symbol"],["982","pi symbol"],["8476","real part symbol"],["978","upsilon - hook symbol"],["8472","Weierstrass p"],["8465","imaginary part"],["8592","leftwards arrow"],["8593","upwards arrow"],["8594","rightwards arrow"],["8595","downwards arrow"],["8596","left right arrow"],["8629","carriage return"],["8656","leftwards double arrow"],["8657","upwards double arrow"],["8658","rightwards double arrow"],["8659","downwards double arrow"],["8660","left right double arrow"],["8756","therefore"],["8834","subset of"],["8835","superset of"],["8836","not a subset of"],["8838","subset of or equal to"],["8839","superset of or equal to"],["8853","circled plus"],["8855","circled times"],["8869","perpendicular"],["8901","dot operator"],["8968","left ceiling"],["8969","right ceiling"],["8970","left floor"],["8971","right floor"],["9001","left-pointing angle bracket"],["9002","right-pointing angle bracket"],["9674","lozenge"],["9824","black spade suit"],["9827","black club suit"],["9829","black heart suit"],["9830","black diamond suit"],["8194","en space"],["8195","em space"],["8201","thin space"],["8204","zero width non-joiner"],["8205","zero width joiner"],["8206","left-to-right mark"],["8207","right-to-left mark"],["173","soft hyphen"]];e.addButton("charmap",{icon:"charmap",tooltip:"Insert special character",onclick:t}),e.addMenuItem("charmap",{icon:"charmap",text:"Special character",onclick:t,context:"insert"})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/chocobo/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/chocobo/plugin.js new file mode 100644 index 00000000..dcec4cbf --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/chocobo/plugin.js @@ -0,0 +1,38 @@ +/*jshint unused:false */ +/*global tinymce:true */ + +tinymce.PluginManager.add('chocobo', function(editor) { + var self = this; + + self.user = { + username: "Curt M", + userId: 6 + }; + + editor.on('init', function(e) { + + }); + + + editor.on('keydown', function(e) { + // handle delete key + if (e.keyCode == 46) { + //e.preventDefault(); + + // get the selection + var c = editor.selection.getContent(); + alert(c); + } + + + // handle backspace key + if(e.keyCode == 8) + { + //e.preventDefault(); + + } + + + }); + +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/chocobo/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/chocobo/plugin.min.js new file mode 100644 index 00000000..1d9c2160 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/chocobo/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("example",function(){}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/code/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/code/plugin.js new file mode 100644 index 00000000..4e2a434e --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/code/plugin.js @@ -0,0 +1,44 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('code', function(editor) { + function showSourceEditor() { + editor.windowManager.open({ + title: "Source code", + body: { + type: 'textbox', + name: 'code', + multiline: true, + minWidth: 600, + minHeight: 500, + value: editor.getContent(), + spellcheck: false + }, + onSubmit: function(e) { + editor.setContent(e.data.code); + } + }); + } + + editor.addButton('code', { + icon: 'code', + tooltip: 'Source code', + onclick: showSourceEditor + }); + + editor.addMenuItem('code', { + icon: 'code', + text: 'Source code', + context: 'tools', + onclick: showSourceEditor + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/code/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/code/plugin.min.js new file mode 100644 index 00000000..ff3fddf1 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/code/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("code",function(e){function t(){e.windowManager.open({title:"Source code",body:{type:"textbox",name:"code",multiline:!0,minWidth:600,minHeight:500,value:e.getContent(),spellcheck:!1},onSubmit:function(t){e.setContent(t.data.code)}})}e.addButton("code",{icon:"code",tooltip:"Source code",onclick:t}),e.addMenuItem("code",{icon:"code",text:"Source code",context:"tools",onclick:t})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/compat3x/editable_selects.js b/lib/tinymce/jscripts/tinymce4/plugins/compat3x/editable_selects.js new file mode 100644 index 00000000..8d30787d --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/compat3x/editable_selects.js @@ -0,0 +1,70 @@ +/** + * editable_selects.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +var TinyMCE_EditableSelects = { + editSelectElm : null, + + init : function() { + var nl = document.getElementsByTagName("select"), i, d = document, o; + + for (i=0; i'; + h += ' '; + + return h; +} + +function updateColor(img_id, form_element_id) { + document.getElementById(img_id).style.backgroundColor = document.forms[0].elements[form_element_id].value; +} + +function setBrowserDisabled(id, state) { + var img = document.getElementById(id); + var lnk = document.getElementById(id + "_link"); + + if (lnk) { + if (state) { + lnk.setAttribute("realhref", lnk.getAttribute("href")); + lnk.removeAttribute("href"); + tinyMCEPopup.dom.addClass(img, 'disabled'); + } else { + if (lnk.getAttribute("realhref")) + lnk.setAttribute("href", lnk.getAttribute("realhref")); + + tinyMCEPopup.dom.removeClass(img, 'disabled'); + } + } +} + +function getBrowserHTML(id, target_form_element, type, prefix) { + var option = prefix + "_" + type + "_browser_callback", cb, html; + + cb = tinyMCEPopup.getParam(option, tinyMCEPopup.getParam("file_browser_callback")); + + if (!cb) + return ""; + + html = ""; + html += ''; + html += ' '; + + return html; +} + +function openBrowser(img_id, target_form_element, type, option) { + var img = document.getElementById(img_id); + + if (img.className != "mceButtonDisabled") + tinyMCEPopup.openBrowser(target_form_element, type, option); +} + +function selectByValue(form_obj, field_name, value, add_custom, ignore_case) { + if (!form_obj || !form_obj.elements[field_name]) + return; + + if (!value) + value = ""; + + var sel = form_obj.elements[field_name]; + + var found = false; + for (var i=0; i/langs/_dlg.js lang pack file. + * + * @method requireLangPack + */ + requireLangPack : function() { + var t = this, u = t.getWindowArg('plugin_url') || t.getWindowArg('theme_url'); + + if (u && t.editor.settings.language && t.features.translate_i18n !== false && t.editor.settings.language_load !== false) { + u += '/langs/' + t.editor.settings.language + '_dlg.js'; + + if (!tinymce.ScriptLoader.isDone(u)) { + document.write(''); + tinymce.ScriptLoader.markDone(u); + } + } + }, + + /** + * Executes a color picker on the specified element id. When the user + * then selects a color it will be set as the value of the specified element. + * + * @method pickColor + * @param {DOMEvent} e DOM event object. + * @param {string} element_id Element id to be filled with the color value from the picker. + */ + pickColor : function(e, element_id) { + this.execCommand('mceColorPicker', true, { + color : document.getElementById(element_id).value, + func : function(c) { + document.getElementById(element_id).value = c; + + try { + document.getElementById(element_id).onchange(); + } catch (ex) { + // Try fire event, ignore errors + } + } + }); + }, + + /** + * Opens a filebrowser/imagebrowser this will set the output value from + * the browser as a value on the specified element. + * + * @method openBrowser + * @param {string} element_id Id of the element to set value in. + * @param {string} type Type of browser to open image/file/flash. + * @param {string} option Option name to get the file_broswer_callback function name from. + */ + openBrowser : function(element_id, type, option) { + tinyMCEPopup.restoreSelection(); + this.editor.execCallback('file_browser_callback', element_id, document.getElementById(element_id).value, type, window); + }, + + /** + * Creates a confirm dialog. Please don't use the blocking behavior of this + * native version use the callback method instead then it can be extended. + * + * @method confirm + * @param {String} t Title for the new confirm dialog. + * @param {function} cb Callback function to be executed after the user has selected ok or cancel. + * @param {Object} s Optional scope to execute the callback in. + */ + confirm : function(t, cb, s) { + this.editor.windowManager.confirm(t, cb, s, window); + }, + + /** + * Creates a alert dialog. Please don't use the blocking behavior of this + * native version use the callback method instead then it can be extended. + * + * @method alert + * @param {String} t Title for the new alert dialog. + * @param {function} cb Callback function to be executed after the user has selected ok. + * @param {Object} s Optional scope to execute the callback in. + */ + alert : function(tx, cb, s) { + this.editor.windowManager.alert(tx, cb, s, window); + }, + + /** + * Closes the current window. + * + * @method close + */ + close : function() { + var t = this; + + // To avoid domain relaxing issue in Opera + function close() { + t.editor.windowManager.close(window); + tinymce = tinyMCE = t.editor = t.params = t.dom = t.dom.doc = null; // Cleanup + }; + + if (tinymce.isOpera) + t.getWin().setTimeout(close, 0); + else + close(); + }, + + // Internal functions + + _restoreSelection : function() { + var e = window.event.srcElement; + + if (e.nodeName == 'INPUT' && (e.type == 'submit' || e.type == 'button')) + tinyMCEPopup.restoreSelection(); + }, + +/* _restoreSelection : function() { + var e = window.event.srcElement; + + // If user focus a non text input or textarea + if ((e.nodeName != 'INPUT' && e.nodeName != 'TEXTAREA') || e.type != 'text') + tinyMCEPopup.restoreSelection(); + },*/ + + _onDOMLoaded : function() { + var t = tinyMCEPopup, ti = document.title, bm, h, nv; + + // Translate page + if (t.features.translate_i18n !== false) { + h = document.body.innerHTML; + + // Replace a=x with a="x" in IE + if (tinymce.isIE) + h = h.replace(/ (value|title|alt)=([^"][^\s>]+)/gi, ' $1="$2"') + + document.dir = t.editor.getParam('directionality',''); + + if ((nv = t.editor.translate(h)) && nv != h) + document.body.innerHTML = nv; + + if ((nv = t.editor.translate(ti)) && nv != ti) + document.title = ti = nv; + } + + if (!t.editor.getParam('browser_preferred_colors', false) || !t.isWindow) + t.dom.addClass(document.body, 'forceColors'); + + document.body.style.display = ''; + + // Restore selection in IE when focus is placed on a non textarea or input element of the type text + if (tinymce.isIE) { + document.attachEvent('onmouseup', tinyMCEPopup._restoreSelection); + + // Add base target element for it since it would fail with modal dialogs + t.dom.add(t.dom.select('head')[0], 'base', {target : '_self'}); + } + + t.restoreSelection(); + t.resizeToInnerSize(); + + // Set inline title + if (!t.isWindow) + t.editor.windowManager.setTitle(window, ti); + else + window.focus(); + + if (!tinymce.isIE && !t.isWindow) { + t.dom.bind(document, 'focus', function() { + t.editor.windowManager.focus(t.id); + }); + } + + // Patch for accessibility + tinymce.each(t.dom.select('select'), function(e) { + e.onkeydown = tinyMCEPopup._accessHandler; + }); + + // Call onInit + // Init must be called before focus so the selection won't get lost by the focus call + tinymce.each(t.listeners, function(o) { + o.func.call(o.scope, t.editor); + }); + + // Move focus to window + if (t.getWindowArg('mce_auto_focus', true)) { + window.focus(); + + // Focus element with mceFocus class + tinymce.each(document.forms, function(f) { + tinymce.each(f.elements, function(e) { + if (t.dom.hasClass(e, 'mceFocus') && !e.disabled) { + e.focus(); + return false; // Break loop + } + }); + }); + } + + document.onkeyup = tinyMCEPopup._closeWinKeyHandler; + }, + + _accessHandler : function(e) { + e = e || window.event; + + if (e.keyCode == 13 || e.keyCode == 32) { + var elm = e.target || e.srcElement; + + if (elm.onchange) + elm.onchange(); + + return tinymce.dom.Event.cancel(e); + } + }, + + _closeWinKeyHandler : function(e) { + e = e || window.event; + + if (e.keyCode == 27) + tinyMCEPopup.close(); + }, + + _eventProxy: function(id) { + return function(evt) { + tinyMCEPopup.dom.events.callNativeHandler(id, evt); + }; + } +}; + +tinyMCEPopup.init(); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/compat3x/validate.js b/lib/tinymce/jscripts/tinymce4/plugins/compat3x/validate.js new file mode 100644 index 00000000..d13aaa1b --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/compat3x/validate.js @@ -0,0 +1,252 @@ +/** + * validate.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + // String validation: + + if (!Validator.isEmail('myemail')) + alert('Invalid email.'); + + // Form validation: + + var f = document.forms['myform']; + + if (!Validator.isEmail(f.myemail)) + alert('Invalid email.'); +*/ + +var Validator = { + isEmail : function(s) { + return this.test(s, '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$'); + }, + + isAbsUrl : function(s) { + return this.test(s, '^(news|telnet|nttp|file|http|ftp|https)://[-A-Za-z0-9\\.]+\\/?.*$'); + }, + + isSize : function(s) { + return this.test(s, '^[0-9.]+(%|in|cm|mm|em|ex|pt|pc|px)?$'); + }, + + isId : function(s) { + return this.test(s, '^[A-Za-z_]([A-Za-z0-9_])*$'); + }, + + isEmpty : function(s) { + var nl, i; + + if (s.nodeName == 'SELECT' && s.selectedIndex < 1) + return true; + + if (s.type == 'checkbox' && !s.checked) + return true; + + if (s.type == 'radio') { + for (i=0, nl = s.form.elements; i parseInt(v)) + st = this.mark(f, n); + } + } + + return st; + }, + + hasClass : function(n, c, d) { + return new RegExp('\\b' + c + (d ? '[0-9]+' : '') + '\\b', 'g').test(n.className); + }, + + getNum : function(n, c) { + c = n.className.match(new RegExp('\\b' + c + '([0-9]+)\\b', 'g'))[0]; + c = c.replace(/[^0-9]/g, ''); + + return c; + }, + + addClass : function(n, c, b) { + var o = this.removeClass(n, c); + n.className = b ? c + (o != '' ? (' ' + o) : '') : (o != '' ? (o + ' ') : '') + c; + }, + + removeClass : function(n, c) { + c = n.className.replace(new RegExp("(^|\\s+)" + c + "(\\s+|$)"), ' '); + return n.className = c != ' ' ? c : ''; + }, + + tags : function(f, s) { + return f.getElementsByTagName(s); + }, + + mark : function(f, n) { + var s = this.settings; + + this.addClass(n, s.invalid_cls); + n.setAttribute('aria-invalid', 'true'); + this.markLabels(f, n, s.invalid_cls); + + return false; + }, + + markLabels : function(f, n, ic) { + var nl, i; + + nl = this.tags(f, "label"); + for (i=0; ia;a++)"|"==i[a].text&&(0===a||a==i.length-1)&&i.splice(a,1);t=new tinymce.ui.Menu({items:i,context:"contextmenu"}),t.renderTo(document.body)}var r=tinymce.DOM.getPos(e.getContentAreaContainer());r.x+=n.clientX,r.y+=n.clientY,t.moveTo(r.x,r.y),e.on("remove",function(){t.remove(),t=null})})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/directionality/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/directionality/plugin.js new file mode 100644 index 00000000..3fd0dabc --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/directionality/plugin.js @@ -0,0 +1,64 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('directionality', function(editor) { + function setDir(dir) { + var dom = editor.dom, curDir, blocks = editor.selection.getSelectedBlocks(); + + if (blocks.length) { + curDir = dom.getAttrib(blocks[0], "dir"); + + tinymce.each(blocks, function(block) { + // Add dir to block if the parent block doesn't already have that dir + if (!dom.getParent(block.parentNode, "*[dir='" + dir + "']", dom.getRoot())) { + if (curDir != dir) { + dom.setAttrib(block, "dir", dir); + } else { + dom.setAttrib(block, "dir", null); + } + } + }); + + editor.nodeChanged(); + } + } + + function generateSelector(dir) { + var selector = []; + + tinymce.each('h1 h2 h3 h4 h5 h6 div p'.split(' '), function(name) { + selector.push(name + '[dir=' + dir + ']'); + }); + + return selector.join(','); + } + + editor.addCommand('mceDirectionLTR', function() { + setDir("ltr"); + }); + + editor.addCommand('mceDirectionRTL', function() { + setDir("rtl"); + }); + + editor.addButton('ltr', { + title: 'Left to right', + cmd: 'mceDirectionLTR', + stateSelector: generateSelector('ltr') + }); + + editor.addButton('rtl', { + title: 'Right to left', + cmd: 'mceDirectionRTL', + stateSelector: generateSelector('rtl') + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/directionality/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/directionality/plugin.min.js new file mode 100644 index 00000000..480a8b7a --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/directionality/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("directionality",function(e){function t(t){var n,o=e.dom,i=e.selection.getSelectedBlocks();i.length&&(n=o.getAttrib(i[0],"dir"),tinymce.each(i,function(e){o.getParent(e.parentNode,"*[dir='"+t+"']",o.getRoot())||(n!=t?o.setAttrib(e,"dir",t):o.setAttrib(e,"dir",null))}),e.nodeChanged())}function n(e){var t=[];return tinymce.each("h1 h2 h3 h4 h5 h6 div p".split(" "),function(n){t.push(n+"[dir="+e+"]")}),t.join(",")}e.addCommand("mceDirectionLTR",function(){t("ltr")}),e.addCommand("mceDirectionRTL",function(){t("rtl")}),e.addButton("ltr",{title:"Left to right",cmd:"mceDirectionLTR",stateSelector:n("ltr")}),e.addButton("rtl",{title:"Right to left",cmd:"mceDirectionRTL",stateSelector:n("rtl")})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-cool.gif b/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-cool.gif new file mode 100644 index 0000000000000000000000000000000000000000..ba90cc36fb0415d0273d1cd206bff63fd9c91fde GIT binary patch literal 354 zcmV-o0iFIwNk%w1VG;lm0Mr!#3ke00dJfFY%i+lrhK7V(RutUQJhPY;?(XfrsZKgL z7WLQ^zPO&zzav{)SL^9nBOw~z(=orMEH5uC-P_gr`uhCnASMa|$-iRw?m_(dUwU8) zq>Kx}s1_F$4FCWDA^8LW0018VEC2ui01^Na000Hw;3tYzX_jM3Qpv$_M?zI9i5=0S zX-{-uv=l3%&P0s%m9Ox_a(m_c|u z01g3U0`Wll5)poVdma=N8y<3f0Sf~hXmTC}2oxMW4FdxUj+z4<0}lrX2nP=qkDRIt z9Ge*(qzMrj3jrIOjvI{`5eWzt3`G_T8yChG8w(a19SkK12@M(+799Zr9n=~PzBCmA z5)BU-)YKUd4H5!D9|!^o9kWIe9SH(WDHRk92}DZ?3})2$P@$55g90f0N)ZA8JID5J Aw*UYD literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-cry.gif b/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-cry.gif new file mode 100644 index 0000000000000000000000000000000000000000..74d897a4f6d22e814e2b054e98b8a75fb464b4be GIT binary patch literal 329 zcmV-P0k-}}Nk%w1VG;lm0Mr-&E)xPSit@9T3%;vR+|V+?t0A(pllJjXrMl7n=_A_a za^B+Su$LjvyC3@TIQZNZa##w=!k(SO^P#bO*w(eU#;{U83XFCU_V)J5wrb+;g2vkN z#>U24qVoOvY5)KLA^8LW0018VEC2ui01^Na000HX;3tY$X_jM3QUfCh%s^o(nF++< zc?Th6v=oL>*by8K!mhvwelUXuuW&&U9iGO3hM@>Njw{l^#0q9mWpcefdI;O$;efnY zkd~@r-o$*74FCWI1%d((4+jDz0va0>69^fI6%`W{8w!gU1pyL>prH>E0R<%k6Aq%H z4ij+^9TEwM5P}eh2@)L<~6+>@EpxfA0YrcPNsSu literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-embarassed.gif b/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-embarassed.gif new file mode 100644 index 0000000000000000000000000000000000000000..963a96b8a7593b1d8bcbab073abe5ee4e539dbf6 GIT binary patch literal 331 zcmV-R0kr-{Nk%w1VG;lm0MrryDh>j~yq&6%75dW~z^P39(NxsGDE{UkxtkIEq(S-a zRKlwv+S=Lr?>hbYY~sQ?c3T&ZcN_Nh_EU3s(>Io6B&>WW`@bsw**)Ocy1bht z{*G6|uwwqUQ2+n{A^8LW0018VEC2ui01^Na000HZ;3tYwX_jM3YQ!c88=*-m*&&bO zILd=`w3KAC;8hxpif*w9ek6oqV-Z0L77fROK$BSR@5BAv-%C>6y>>#+D4e#&nz^qMDItlpp zTG728+|V&?R13PIEBW(C`uh6d*t-1sZ^XQv;oDD}iYLOV7uVO;{`xl4#4tJ{0;h@! z>)kdc3IhA?Hvj+tA^8La0018VEC2ui01^Na06+!P;3tYuX_ljS7!u|-O)I}TzP1q%xT4HOFwMJaO;2ml)!00$)141pU08x3594IX?4 o5YuAA8yXz~76K1c;3^jg77WP185Rf^u}23N0sR5^q(T4yJ1sVN5dZ)H literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-frown.gif b/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-frown.gif new file mode 100644 index 0000000000000000000000000000000000000000..716f55e161bfebb1c3d34f0b0f40c177fc82c30b GIT binary patch literal 340 zcmV-a0jvH;Nk%w1VG;lm0MroxK_>;q#>Sw62=mns-On=0wransPVevT^YK{Dy(0YY zH)vE6x0?;Wqb>gZas1^OT0si>`ugD5y87}*#H$s=yq(wA*8cf7{`y+(+9J7|9QfT7 z`ROHiU=Y&6FaQ7mA^8LW0018VEC2ui01^Na000Hi;3tYvX_jM3N`@u~nju9hSuh^r zIEcp-wA7(NL0~2d#RP+(G!CPPA>o*KJjv_CkucCA5=K?AfF#RG2V*8BU@jL304|4P z2;PGRF@bj$et;Jf2pR_mVsIA<85|n}kQ*Bq42Ovqj*yy>6P0=h3X&9Z01yyk~2N4w%7#RW^55W%`0vQ+-6(y_*2pqz~90*;x9}yM}%$UI(7t#$D mK_3Se1{4HKM+6iG7EmeH6$V631{L5n)#CyC0qx-*Apkoyg?w!Q literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-innocent.gif b/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-innocent.gif new file mode 100644 index 0000000000000000000000000000000000000000..334d49e0e60f2997c9ba24071764f95d9e08a5cc GIT binary patch literal 336 zcmV-W0k8f?Nk%w1VG;lm0MrryI4TI-%dP0m5~*+Y`T~ z7Rth){q{I_X%*S48uRZ|(b3V&wIKTX`u+WJzo<^$#wuY;3W|Cf{O29IkTAcaE&lpe z+P*^H)-tknA^-pYA^8LW0018VEC2ui01^Na000He;3tYwX_n)75QgVvNQ`6#5gcMm zEEG~blgXokptKAJgCU?%JT?yos!R6cPtcQWh2siHlNI2L}ifQhgX02^InZ2?-ktkqVRyZJY^Trk|lv zovp437?1~d46O)?2(1i+2NDYk8<+_Kil!K!3njA^!I#dL8x<729}*B65mC=m5gHH@ iDi9P3f*VjB3KS4HDb_qqRul{0DIT=Nk%w1VG;lm0Mrx!QauaC#>Vb6G=_5=^YB^9wrc376Sb5I-qJGf@9vZ# z5WlKU(!eVB+7tfnDXp0zyB`?BZ5IChalob*`uh6d*t+@dKGHcU+L|83yq*5~IoH?L zy`?Gp<{bX|SpWb4A^8LW0018VEC2ui01^Na000Hg;3tYyX_jM3R?Bl7&r(q;SsVx< zNd$5fv{ZsKA$SlL3&KN~a1tZRf*~1Ltkx9~2uL3&z-yb0WJDRY082|tP literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-laughing.gif b/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-laughing.gif new file mode 100644 index 0000000000000000000000000000000000000000..82c5b182e61d32bd394acae551eff180f1eebd26 GIT binary patch literal 343 zcmV-d0jT~*Nk%w1VG;lm0Q4UK!lp8=s;1-69HWK?p_PpF=Pd8~Ygtcnp*fHAL z**;z>w3iC}`fmL6IkKB1N;3zEa}&zKpsu1;_V)HocR5-{J~BcYvE`YXhBnc@CfU=! za(Ec zG>66zv=rqr;2j)}gKqE$ekcSD?}0=WLB?AWp85)qALd+P=4)6X4oXy{bw2>K^d$ z@6ERvva+(4ib~41YUkTEn1&#?rzrOHT>1I=Y*h`+%*@WtPUPg|!@EEI_d5LgZ>^Og z-qyBKJqy*wF8}}lA^8La0018VEC2ui01^Na06+!6;3tYxX_lj?7+U61R3gAaEg8x< zT>%mSfCwURnWQF&g=Q0ZxH1ulW`QtH0>O!5%iT_X0VBy_@EkOngU8?ye~=H!t21{= z9@Uj3a_UbE88~kh5Eq7rh!7QSBn1c?0|Off1&k^`5*QE<4-gmSR<4C>Dj%C>6W(lWoQPVevT^YB^Fy&h6M z4YZgH{O~qtR1(Ci8T;lQ`uh6d*t-7xar*K{#Jrulo-Wtd*44u?{`oh#n;gQXGXDEo z_}UUC3IeK%0ssI2A^8La0018VEC2ui01^Na06+!R;3tYuX_ljSEE482&%+G^XK%|f zLKbCc4u{4-u|QG~LqamSTo?@JM3OKZAr!|Z2IzP@fY`=CIg$vA3qm46TowfLCt29I z6pDKuvnf~)83+sm9yW#?9s>^(89F=~2?!W44-6Ox2^vNza}fp^9v&G65pp936%Gg+ z6HpTy2o4oGoh+>l3Q)KVQwybl2oo*<4a3D469|nfEii|MH4`}p1_cZp0ssj%2>=2d q41Na?)CpS;4gvxWVpZcR76uLludD?Q1{SnP2NnVU0rZ&)0RTIit8@_n literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-surprised.gif b/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-surprised.gif new file mode 100644 index 0000000000000000000000000000000000000000..0cc9bb71cca4cdeafbb248ce7e07c3708c1cbd64 GIT binary patch literal 338 zcmV-Y0j>T=Nk%w1VG;lm0Q4UK`{WwN#>SnDDC*4*{OcpiwransPVevTQacIr@mkQp zCf(06s)_=>r7UYx48o@u`uh6d*t-7rH~ji<`P&oj;5Wp)o!8ga`SV6TA_BIW5#ZWV z{`*)c32kA}f=futY?#YE7kxGD|7L}4&OEDw$hkm+~<00QS>F_H?J#bz?uEHnl42f5(9 z5O)`6Q9V2o5;YVLUK)Y`7!Nr+4GMq?85s%^2?`BGDRU798Vn2?1`%>22R{iO0u>bk z9tlA?nk*O<3zHJH6&Mp5qALj)E(mxM!Y&vII4dm@1Ov{`f*8pL3xPEVUI>D>1_uxa kNm?`6VH{N6Di;P13m6<67z+;u7qCYM7XkVK^`jvGJD~P?KL7v# literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-tongue-out.gif b/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-tongue-out.gif new file mode 100644 index 0000000000000000000000000000000000000000..2075dc16058f1f17912167675ce5cfb9986fc71d GIT binary patch literal 328 zcmV-O0k{4~Nk%w1VG;lm0Mrx!CJF+^#>SU@3-{U*rx+Q^wrc$ABfqLn@9*x?z8(4X zSW-O=@){bmmI~g|GQXoP);cvj3|f1M8e@{G*!tYaiCEujj1NGxRN#6#tiCETo+{x{Hkzt z5k-kPvcD=V2nbmjCgL6k{uF&2nP-t0s;w<385Nx2oxDb z9T5Pp7qJl?3Kkh9oe2sCr5F$p7zPSlsUH*@54w*83=9Or4;w)r2pcU95(FL|1Th;< aDaRQH4;Tal7#Y$v#?=Au0pHUfApkpvZg^t= literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-undecided.gif b/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-undecided.gif new file mode 100644 index 0000000000000000000000000000000000000000..bef7e257303f8243c89787e7a7f9955dd1f112e2 GIT binary patch literal 337 zcmV-X0j~Z>Nk%w1VG;lm0MroxDi#99#>R?y8~4}{%C>6#>?OadPVevTr-=vi@LATn z4rERY-qJF+n+?CCE&B3D{{3Shh?>WT0o%`b%*Voqm`dL;(4F35y zc485^n;g!+Bme*aA^8LW0018VEC2ui01^Na000Hf;3tYvX_jM3N=AnuogqakNi<9X zK?&0kwA8^tNn{?C$|IAYI1ZzT!2>}iuMddFK#NEkRl!7%6brJAnUs;)XcnA}TNBSP zxQ9;SvEfwYeSaGd2^|LqU~(QF1qBxr3Ii7x84ZVt8wCTKoSYAqc?p`G2onnpk`IOl z1`HLGj}riN2p1K12N4z&8IBDc6tEWs859;JtRB6>lf+xO9}yT19toMv8wnl`7(pKg j7zPv!OGgY81{hE&(iR3pP6ig;HPPS!_yOwPA0Yrc)=Yf3 literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-wink.gif b/lib/tinymce/jscripts/tinymce4/plugins/emoticons/img/smiley-wink.gif new file mode 100644 index 0000000000000000000000000000000000000000..0631c7616ec8624ddeee02b633326f697ee72f80 GIT binary patch literal 350 zcmV-k0ipg!Nk%w1VG;lm0Q4UK(ZVUl#>Sn03F^-g-qAA3wransPV?|t@9*x%vmQ`7 z4E*pcw3rOOq%3t@4*K#({N^40{c-yG`rz2Q!KfI-yq*61HrBop*VoqW<}&{JS@_x# zwwfF$4Fdh~IsgCwA^8La0018VEC2ui01^Na06+!X;3tYwX_ljiFp=e23$zWxW@`*G zN?2ty6iUNT!AMdPLn89IbS7WCB_mWF$+hzY-{PWkp(?(Xf;zbH~P z3jOdj?W+^YwrakfE8fyG&5jTBz!3WS`fgM_;MltQ+c}4GO8)(E`S3`@yq&d~5!ct& z)v79NObo)O7XSbNA^8LW0018VEC2ui01^Na000He;3tYwX_jM3QifI(nn6h_*=Wyk zUB{y}v=qYOIUF#R3dZPhAVv~H;(|a2yN_5FH&J0|$eJ3kw4gj1Y?v5d#>LMV12^6BYy$1)ZKA zga!|m2?POz0R)f>4+aPl8KD{gz`+G_9vLMFQU?RU!8uyH9}*i52|cC+7S0YEK_3Vk i1|APfM-Ltb8&4_H83sg61{vHn(cc000qNZzApkp'; + }); + + emoticonsHtml += ''; + }); + + emoticonsHtml += ''; + + return emoticonsHtml; + } + + editor.addButton('emoticons', { + type: 'panelbutton', + popoverAlign: 'bc-tl', + panel: { + autohide: true, + html: getHtml, + onclick: function(e) { + var linkElm = editor.dom.getParent(e.target, 'a'); + + if (linkElm) { + editor.insertContent(''); + this.hide(); + } + } + }, + tooltip: 'Emoticons' + }); +/* + editor.addButton('emoticons', { + type: 'panelbutton', + popoverAlign: 'bc-tl', + panel: { + layout: 'flex', + spacing: 5, + padding: 5, + autohide: true, + items: [ + {type: 'textbox', label: 'Url'}, + {type: 'button', text: 'OK'} + ] + }, + tooltip: 'Emoticons' + });*/ +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/emoticons/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/emoticons/plugin.min.js new file mode 100644 index 00000000..9ba514a6 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/emoticons/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("emoticons",function(e,t){function n(){var e;return e='',tinymce.each(o,function(n){e+="",tinymce.each(n,function(n){var o=t+"/img/smiley-"+n+".gif";e+=''}),e+=""}),e+=""}var o=[["cool","cry","embarassed","foot-in-mouth"],["frown","innocent","kiss","laughing"],["money-mouth","sealed","smile","surprised"],["tongue-out","undecided","wink","yell"]];e.addButton("emoticons",{type:"panelbutton",popoverAlign:"bc-tl",panel:{autohide:!0,html:n,onclick:function(t){var n=e.dom.getParent(t.target,"a");n&&(e.insertContent(''),this.hide())}},tooltip:"Emoticons"})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/example/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/example/plugin.js new file mode 100644 index 00000000..aeb76530 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/example/plugin.js @@ -0,0 +1,45 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint unused:false */ +/*global tinymce:true */ + +tinymce.PluginManager.add('example', function(editor) { + function showSourceEditor() { + editor.windowManager.open({ + title: "Source code", + body: { + type: 'textbox', + name: 'code', + multiline: true, + minWidth: 600, + minHeight: 500, + value: editor.getContent(), + spellcheck: false + }, + onSubmit: function(e) { + editor.setContent(e.data.code); + } + }); + } + + editor.addButton('code', { + icon: 'code', + tooltip: 'HTML', + onclick: showSourceEditor + }); + + editor.addMenuItem('code', { + icon: 'code', + text: 'hTMl', + context: 'tools', + onclick: showSourceEditor + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/example/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/example/plugin.min.js new file mode 100644 index 00000000..1d9c2160 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/example/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("example",function(){}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/example_dependency/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/example_dependency/plugin.js new file mode 100644 index 00000000..4f1c8efe --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/example_dependency/plugin.js @@ -0,0 +1,22 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint unused:false */ +/*global tinymce:true */ + +/** + * Register the plugin, specifying the list of the plugins that this plugin depends on. They are specified in a list, + * with the list loaded in order. plugins in this list will be initialised when this plugin is initialized. (before the + * init method is called). plugins in a depends list should typically be specified using the short name). If neccesary + * this can be done with an object which has the url to the plugin and the shortname. + */ +tinymce.PluginManager.add('example_dependency', function(editor) { + // Example logic here +}, ['example']); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/example_dependency/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/example_dependency/plugin.min.js new file mode 100644 index 00000000..e61bf473 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/example_dependency/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("example_dependency",function(){},["example"]); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/fullpage/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/fullpage/plugin.js new file mode 100644 index 00000000..0d7c4c76 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/fullpage/plugin.js @@ -0,0 +1,436 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('fullpage', function(editor) { + var each = tinymce.each, Node = tinymce.html.Node; + var head, foot; + + function showDialog() { + var data = htmlToData(); + + editor.windowManager.open({ + title: 'Document properties', + data: data, + defaults: {type: 'textbox', size: 40}, + body: [ + {name: 'title', label: 'Title'}, + {name: 'keywords', label: 'Keywords'}, + {name: 'description', label: 'Description'}, + {name: 'robots', label: 'Robots'}, + {name: 'author', label: 'Author'}, + {name: 'docencoding', label: 'Encoding'} + ], + onSubmit: function(e) { + dataToHtml(tinymce.extend(data, e.data)); + } + }); + } + + function htmlToData() { + var headerFragment = parseHeader(), data = {}, elm, matches; + + function getAttr(elm, name) { + var value = elm.attr(name); + + return value || ''; + } + + // Default some values + data.fontface = editor.getParam("fullpage_default_fontface", ""); + data.fontsize = editor.getParam("fullpage_default_fontsize", ""); + + // Parse XML PI + elm = headerFragment.firstChild; + if (elm.type == 7) { + data.xml_pi = true; + matches = /encoding="([^"]+)"/.exec(elm.value); + if (matches) { + data.docencoding = matches[1]; + } + } + + // Parse doctype + elm = headerFragment.getAll('#doctype')[0]; + if (elm) { + data.doctype = '"; + } + + // Parse title element + elm = headerFragment.getAll('title')[0]; + if (elm && elm.firstChild) { + data.title = elm.firstChild.value; + } + + // Parse meta elements + each(headerFragment.getAll('meta'), function(meta) { + var name = meta.attr('name'), httpEquiv = meta.attr('http-equiv'), matches; + + if (name) { + data[name.toLowerCase()] = meta.attr('content'); + } else if (httpEquiv == "Content-Type") { + matches = /charset\s*=\s*(.*)\s*/gi.exec(meta.attr('content')); + + if (matches) { + data.docencoding = matches[1]; + } + } + }); + + // Parse html attribs + elm = headerFragment.getAll('html')[0]; + if (elm) { + data.langcode = getAttr(elm, 'lang') || getAttr(elm, 'xml:lang'); + } + + // Parse stylesheet + elm = headerFragment.getAll('link')[0]; + if (elm && elm.attr('rel') == 'stylesheet') { + data.stylesheet = elm.attr('href'); + } + + // Parse body parts + elm = headerFragment.getAll('body')[0]; + if (elm) { + data.langdir = getAttr(elm, 'dir'); + data.style = getAttr(elm, 'style'); + data.visited_color = getAttr(elm, 'vlink'); + data.link_color = getAttr(elm, 'link'); + data.active_color = getAttr(elm, 'alink'); + } + + return data; + } + + function dataToHtml(data) { + var headerFragment, headElement, html, elm, value, dom = editor.dom; + + function setAttr(elm, name, value) { + elm.attr(name, value ? value : undefined); + } + + function addHeadNode(node) { + if (headElement.firstChild) { + headElement.insert(node, headElement.firstChild); + } else { + headElement.append(node); + } + } + + headerFragment = parseHeader(); + headElement = headerFragment.getAll('head')[0]; + if (!headElement) { + elm = headerFragment.getAll('html')[0]; + headElement = new Node('head', 1); + + if (elm.firstChild) { + elm.insert(headElement, elm.firstChild, true); + } else { + elm.append(headElement); + } + } + + // Add/update/remove XML-PI + elm = headerFragment.firstChild; + if (data.xml_pi) { + value = 'version="1.0"'; + + if (data.docencoding) { + value += ' encoding="' + data.docencoding + '"'; + } + + if (elm.type != 7) { + elm = new Node('xml', 7); + headerFragment.insert(elm, headerFragment.firstChild, true); + } + + elm.value = value; + } else if (elm && elm.type == 7) { + elm.remove(); + } + + // Add/update/remove doctype + elm = headerFragment.getAll('#doctype')[0]; + if (data.doctype) { + if (!elm) { + elm = new Node('#doctype', 10); + + if (data.xml_pi) { + headerFragment.insert(elm, headerFragment.firstChild); + } else { + addHeadNode(elm); + } + } + + elm.value = data.doctype.substring(9, data.doctype.length - 1); + } else if (elm) { + elm.remove(); + } + + // Add meta encoding + if (data.docencoding) { + elm = null; + each(headerFragment.getAll('meta'), function(meta) { + if (meta.attr('http-equiv') == 'Content-Type') { + elm = meta; + } + }); + + if (!elm) { + elm = new Node('meta', 1); + elm.attr('http-equiv', 'Content-Type'); + elm.shortEnded = true; + addHeadNode(elm); + } + + elm.attr('content', 'text/html; charset=' + data.docencoding); + } + + // Add/update/remove title + elm = headerFragment.getAll('title')[0]; + if (data.title) { + if (!elm) { + elm = new Node('title', 1); + elm.append(new Node('#text', 3)).value = data.title; + addHeadNode(elm); + } + } else if (elm) { + elm.remove(); + } + + // Add/update/remove meta + each('keywords,description,author,copyright,robots'.split(','), function(name) { + var nodes = headerFragment.getAll('meta'), i, meta, value = data[name]; + + for (i = 0; i < nodes.length; i++) { + meta = nodes[i]; + + if (meta.attr('name') == name) { + if (value) { + meta.attr('content', value); + } else { + meta.remove(); + } + + return; + } + } + + if (value) { + elm = new Node('meta', 1); + elm.attr('name', name); + elm.attr('content', value); + elm.shortEnded = true; + + addHeadNode(elm); + } + }); + + // Add/update/delete link + elm = headerFragment.getAll('link')[0]; + if (elm && elm.attr('rel') == 'stylesheet') { + if (data.stylesheet) { + elm.attr('href', data.stylesheet); + } else { + elm.remove(); + } + } else if (data.stylesheet) { + elm = new Node('link', 1); + elm.attr({ + rel : 'stylesheet', + text : 'text/css', + href : data.stylesheet + }); + elm.shortEnded = true; + + addHeadNode(elm); + } + + // Update body attributes + elm = headerFragment.getAll('body')[0]; + if (elm) { + setAttr(elm, 'dir', data.langdir); + setAttr(elm, 'style', data.style); + setAttr(elm, 'vlink', data.visited_color); + setAttr(elm, 'link', data.link_color); + setAttr(elm, 'alink', data.active_color); + + // Update iframe body as well + dom.setAttribs(editor.getBody(), { + style : data.style, + dir : data.dir, + vLink : data.visited_color, + link : data.link_color, + aLink : data.active_color + }); + } + + // Set html attributes + elm = headerFragment.getAll('html')[0]; + if (elm) { + setAttr(elm, 'lang', data.langcode); + setAttr(elm, 'xml:lang', data.langcode); + } + + // No need for a head element + if (!headElement.firstChild) { + headElement.remove(); + } + + // Serialize header fragment and crop away body part + html = new tinymce.html.Serializer({ + validate: false, + indent: true, + apply_source_formatting : true, + indent_before: 'head,html,body,meta,title,script,link,style', + indent_after: 'head,html,body,meta,title,script,link,style' + }).serialize(headerFragment); + + head = html.substring(0, html.indexOf('')); + } + + function parseHeader() { + // Parse the contents with a DOM parser + return new tinymce.html.DomParser({ + validate: false, + root_name: '#document' + }).parse(head); + } + + function setContent(o) { + var startPos, endPos, content = o.content, headerFragment, styles = '', dom = editor.dom, elm; + + function low(s) { + return s.replace(/<\/?[A-Z]+/g, function(a) { + return a.toLowerCase(); + }); + } + + // Ignore raw updated if we already have a head, this will fix issues with undo/redo keeping the head/foot separate + if (o.format == 'raw' && head) { + return; + } + + if (o.source_view && editor.getParam('fullpage_hide_in_source_view')) { + return; + } + + // Parse out head, body and footer + content = content.replace(/<(\/?)BODY/gi, '<$1body'); + startPos = content.indexOf('', startPos); + head = low(content.substring(0, startPos + 1)); + + endPos = content.indexOf('\n'; + } + + header += editor.getParam('fullpage_default_doctype', ''); + header += '\n\n\n'; + + if ((value = editor.getParam('fullpage_default_title'))) { + header += '' + value + '\n'; + } + + if ((value = editor.getParam('fullpage_default_encoding'))) { + header += '\n'; + } + + if ((value = editor.getParam('fullpage_default_font_family'))) { + styles += 'font-family: ' + value + ';'; + } + + if ((value = editor.getParam('fullpage_default_font_size'))) { + styles += 'font-size: ' + value + ';'; + } + + if ((value = editor.getParam('fullpage_default_text_color'))) { + styles += 'color: ' + value + ';'; + } + + header += '\n\n'; + + return header; + } + + function getContent(o) { + if (!o.selection && (!o.source_view || !editor.getParam('fullpage_hide_in_source_view'))) { + o.content = tinymce.trim(head) + '\n' + tinymce.trim(o.content) + '\n' + tinymce.trim(foot); + } + } + + editor.addCommand('mceFullPageProperties', showDialog); + + editor.addButton('fullpage', { + title: 'Document properties', + cmd : 'mceFullPageProperties' + }); + + editor.addMenuItem('fullpage', { + text: 'Document properties', + cmd : 'mceFullPageProperties', + context: 'file' + }); + + editor.on('BeforeSetContent', setContent); + editor.on('GetContent', getContent); +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/fullpage/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/fullpage/plugin.min.js new file mode 100644 index 00000000..5bd47c03 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/fullpage/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("fullpage",function(e){function t(){var t=n();e.windowManager.open({title:"Document properties",data:t,defaults:{type:"textbox",size:40},body:[{name:"title",label:"Title"},{name:"keywords",label:"Keywords"},{name:"description",label:"Description"},{name:"robots",label:"Robots"},{name:"author",label:"Author"},{name:"docencoding",label:"Encoding"}],onSubmit:function(e){i(tinymce.extend(t,e.data))}})}function n(){function t(e,t){var n=e.attr(t);return n||""}var n,i,a=o(),r={};return r.fontface=e.getParam("fullpage_default_fontface",""),r.fontsize=e.getParam("fullpage_default_fontsize",""),n=a.firstChild,7==n.type&&(r.xml_pi=!0,i=/encoding="([^"]+)"/.exec(n.value),i&&(r.docencoding=i[1])),n=a.getAll("#doctype")[0],n&&(r.doctype=""),n=a.getAll("title")[0],n&&n.firstChild&&(r.title=n.firstChild.value),d(a.getAll("meta"),function(e){var t,n=e.attr("name"),i=e.attr("http-equiv");n?r[n.toLowerCase()]=e.attr("content"):"Content-Type"==i&&(t=/charset\s*=\s*(.*)\s*/gi.exec(e.attr("content")),t&&(r.docencoding=t[1]))}),n=a.getAll("html")[0],n&&(r.langcode=t(n,"lang")||t(n,"xml:lang")),n=a.getAll("link")[0],n&&"stylesheet"==n.attr("rel")&&(r.stylesheet=n.attr("href")),n=a.getAll("body")[0],n&&(r.langdir=t(n,"dir"),r.style=t(n,"style"),r.visited_color=t(n,"vlink"),r.link_color=t(n,"link"),r.active_color=t(n,"alink")),r}function i(t){function n(e,t,n){e.attr(t,n?n:void 0)}function i(e){r.firstChild?r.insert(e,r.firstChild):r.append(e)}var a,r,l,s,g,m=e.dom;a=o(),r=a.getAll("head")[0],r||(s=a.getAll("html")[0],r=new u("head",1),s.firstChild?s.insert(r,s.firstChild,!0):s.append(r)),s=a.firstChild,t.xml_pi?(g='version="1.0"',t.docencoding&&(g+=' encoding="'+t.docencoding+'"'),7!=s.type&&(s=new u("xml",7),a.insert(s,a.firstChild,!0)),s.value=g):s&&7==s.type&&s.remove(),s=a.getAll("#doctype")[0],t.doctype?(s||(s=new u("#doctype",10),t.xml_pi?a.insert(s,a.firstChild):i(s)),s.value=t.doctype.substring(9,t.doctype.length-1)):s&&s.remove(),t.docencoding&&(s=null,d(a.getAll("meta"),function(e){"Content-Type"==e.attr("http-equiv")&&(s=e)}),s||(s=new u("meta",1),s.attr("http-equiv","Content-Type"),s.shortEnded=!0,i(s)),s.attr("content","text/html; charset="+t.docencoding)),s=a.getAll("title")[0],t.title?s||(s=new u("title",1),s.append(new u("#text",3)).value=t.title,i(s)):s&&s.remove(),d("keywords,description,author,copyright,robots".split(","),function(e){var n,o,r=a.getAll("meta"),l=t[e];for(n=0;r.length>n;n++)if(o=r[n],o.attr("name")==e)return l?o.attr("content",l):o.remove(),void 0;l&&(s=new u("meta",1),s.attr("name",e),s.attr("content",l),s.shortEnded=!0,i(s))}),s=a.getAll("link")[0],s&&"stylesheet"==s.attr("rel")?t.stylesheet?s.attr("href",t.stylesheet):s.remove():t.stylesheet&&(s=new u("link",1),s.attr({rel:"stylesheet",text:"text/css",href:t.stylesheet}),s.shortEnded=!0,i(s)),s=a.getAll("body")[0],s&&(n(s,"dir",t.langdir),n(s,"style",t.style),n(s,"vlink",t.visited_color),n(s,"link",t.link_color),n(s,"alink",t.active_color),m.setAttribs(e.getBody(),{style:t.style,dir:t.dir,vLink:t.visited_color,link:t.link_color,aLink:t.active_color})),s=a.getAll("html")[0],s&&(n(s,"lang",t.langcode),n(s,"xml:lang",t.langcode)),r.firstChild||r.remove(),l=new tinymce.html.Serializer({validate:!1,indent:!0,apply_source_formatting:!0,indent_before:"head,html,body,meta,title,script,link,style",indent_after:"head,html,body,meta,title,script,link,style"}).serialize(a),c=l.substring(0,l.indexOf(""))}function o(){return new tinymce.html.DomParser({validate:!1,root_name:"#document"}).parse(c)}function a(t){function n(e){return e.replace(/<\/?[A-Z]+/g,function(e){return e.toLowerCase()})}var i,a,l,u,g=t.content,m="",f=e.dom;"raw"==t.format&&c||t.source_view&&e.getParam("fullpage_hide_in_source_view")||(g=g.replace(/<(\/?)BODY/gi,"<$1body"),i=g.indexOf("",i),c=n(g.substring(0,i+1)),a=g.indexOf("\n"),l=o(),d(l.getAll("style"),function(e){e.firstChild&&(m+=e.firstChild.value)}),u=l.getAll("body")[0],u&&f.setAttribs(e.getBody(),{style:u.attr("style")||"",dir:u.attr("dir")||"",vLink:u.attr("vlink")||"",link:u.attr("link")||"",aLink:u.attr("alink")||""}),f.remove("fullpage_styles"),m&&(f.add(e.getDoc().getElementsByTagName("head")[0],"style",{id:"fullpage_styles"},m),u=f.get("fullpage_styles"),u.styleSheet&&(u.styleSheet.cssText=m)))}function r(){var t,n="",i="";return e.getParam("fullpage_default_xml_pi")&&(n+='\n'),n+=e.getParam("fullpage_default_doctype",""),n+="\n\n\n",(t=e.getParam("fullpage_default_title"))&&(n+=""+t+"\n"),(t=e.getParam("fullpage_default_encoding"))&&(n+='\n'),(t=e.getParam("fullpage_default_font_family"))&&(i+="font-family: "+t+";"),(t=e.getParam("fullpage_default_font_size"))&&(i+="font-size: "+t+";"),(t=e.getParam("fullpage_default_text_color"))&&(i+="color: "+t+";"),n+="\n\n"}function l(t){t.selection||t.source_view&&e.getParam("fullpage_hide_in_source_view")||(t.content=tinymce.trim(c)+"\n"+tinymce.trim(t.content)+"\n"+tinymce.trim(s))}var c,s,d=tinymce.each,u=tinymce.html.Node;e.addCommand("mceFullPageProperties",t),e.addButton("fullpage",{title:"Document properties",cmd:"mceFullPageProperties"}),e.addMenuItem("fullpage",{text:"Document properties",cmd:"mceFullPageProperties",context:"file"}),e.on("BeforeSetContent",a),e.on("GetContent",l)}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/fullscreen/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/fullscreen/plugin.js new file mode 100644 index 00000000..24fec649 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/fullscreen/plugin.js @@ -0,0 +1,115 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('fullscreen', function(editor) { + var fullscreenState = false, DOM = tinymce.DOM, deltaHeight, iframeWidth, iframeHeight; + + if (editor.settings.inline) { + return; + } + + function getWindowSize() { + var w, h, win = window, doc = document; + var body = doc.body; + + // Old IE + if (body.offsetWidth) { + w = body.offsetWidth; + h = body.offsetHeight; + } + + // Modern browsers + if (win.innerWidth && win.innerHeight) { + w = win.innerWidth; + h = win.innerHeight; + } + + return {w: w, h: h}; + } + + function toggleFullscreen() { + var body = document.body, documentElement = document.documentElement; + var editorContainer, iframe, iframeStyle; + + function resize() { + DOM.setStyle(iframe, 'height', getWindowSize().h - (editorContainer.clientHeight - iframe.clientHeight)); + } + + fullscreenState = !fullscreenState; + + editorContainer = editor.getContainer().firstChild; + iframe = editor.getContentAreaContainer().firstChild; + iframeStyle = iframe.style; + + if (fullscreenState) { + iframeWidth = iframeStyle.width; + iframeHeight = iframeStyle.height; + deltaHeight = editorContainer.clientHeight - iframe.clientHeight; + iframeStyle.width = iframeStyle.height = '100%'; + + DOM.addClass(body, 'mce-fullscreen'); + DOM.addClass(documentElement, 'mce-fullscreen'); + DOM.addClass(editorContainer, 'mce-fullscreen'); + + DOM.bind(window, 'resize', resize); + resize(); + } else { + iframeStyle.width = iframeWidth; + iframeStyle.height = iframeHeight; + + DOM.removeClass(body, 'mce-fullscreen'); + DOM.removeClass(documentElement, 'mce-fullscreen'); + DOM.removeClass(editorContainer, 'mce-fullscreen'); + DOM.unbind(window, 'resize', resize); + } + + editor.fire('FullscreenStateChanged', {state: fullscreenState}); + } + + editor.on('init', function() { + editor.addShortcut('Ctrl+Alt+F', '', toggleFullscreen); + }); + + editor.addMenuItem('fullscreen', { + text: 'Fullscreen', + shortcut: 'Ctrl+Alt+F', + selectable: true, + onClick: toggleFullscreen, + onPostRender: function() { + var self = this; + + editor.on('FullscreenStateChanged', function(e) { + self.active(e.state); + }); + }, + context: 'view' + }); + + editor.addButton('fullscreen', { + tooltip: 'Fullscreen', + shortcut: 'Ctrl+Alt+F', + onClick: toggleFullscreen, + onPostRender: function() { + var self = this; + + editor.on('FullscreenStateChanged', function(e) { + self.active(e.state); + }); + } + }); + + return { + isFullscreen: function() { + return fullscreenState; + } + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/fullscreen/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/fullscreen/plugin.min.js new file mode 100644 index 00000000..45606f26 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/fullscreen/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("fullscreen",function(e){function t(){var e,t,n=window,i=document,o=i.body;return o.offsetWidth&&(e=o.offsetWidth,t=o.offsetHeight),n.innerWidth&&n.innerHeight&&(e=n.innerWidth,t=n.innerHeight),{w:e,h:t}}function n(){function n(){l.setStyle(s,"height",t().h-(c.clientHeight-s.clientHeight))}var c,s,d,u=document.body,g=document.documentElement;r=!r,c=e.getContainer().firstChild,s=e.getContentAreaContainer().firstChild,d=s.style,r?(o=d.width,a=d.height,i=c.clientHeight-s.clientHeight,d.width=d.height="100%",l.addClass(u,"mce-fullscreen"),l.addClass(g,"mce-fullscreen"),l.addClass(c,"mce-fullscreen"),l.bind(window,"resize",n),n()):(d.width=o,d.height=a,l.removeClass(u,"mce-fullscreen"),l.removeClass(g,"mce-fullscreen"),l.removeClass(c,"mce-fullscreen"),l.unbind(window,"resize",n)),e.fire("FullscreenStateChanged",{state:r})}var i,o,a,r=!1,l=tinymce.DOM;if(!e.settings.inline)return e.on("init",function(){e.addShortcut("Ctrl+Alt+F","",n)}),e.addMenuItem("fullscreen",{text:"Fullscreen",shortcut:"Ctrl+Alt+F",selectable:!0,onClick:n,onPostRender:function(){var t=this;e.on("FullscreenStateChanged",function(e){t.active(e.state)})},context:"view"}),e.addButton("fullscreen",{tooltip:"Fullscreen",shortcut:"Ctrl+Alt+F",onClick:n,onPostRender:function(){var t=this;e.on("FullscreenStateChanged",function(e){t.active(e.state)})}}),{isFullscreen:function(){return r}}}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/hr/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/hr/plugin.js new file mode 100644 index 00000000..cd00cb3e --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/hr/plugin.js @@ -0,0 +1,30 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('hr', function(editor) { + editor.addCommand('InsertHorizontalRule', function() { + editor.execCommand('mceInsertContent', false, '


    '); + }); + + editor.addButton('hr', { + icon: 'hr', + tooltip: 'Insert horizontal ruler', + cmd: 'InsertHorizontalRule' + }); + + editor.addMenuItem('hr', { + icon: 'hr', + text: 'Horizontal line', + cmd: 'InsertHorizontalRule', + context: 'insert' + }); +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/hr/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/hr/plugin.min.js new file mode 100644 index 00000000..f9268ae0 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/hr/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("hr",function(e){e.addCommand("InsertHorizontalRule",function(){e.execCommand("mceInsertContent",!1,"
    ")}),e.addButton("hr",{icon:"hr",tooltip:"Insert horizontal ruler",cmd:"InsertHorizontalRule"}),e.addMenuItem("hr",{icon:"hr",text:"Horizontal line",cmd:"InsertHorizontalRule",context:"insert"})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/ice/css/ice.css b/lib/tinymce/jscripts/tinymce4/plugins/ice/css/ice.css new file mode 100644 index 00000000..76c40a84 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/ice/css/ice.css @@ -0,0 +1,27 @@ +.CT-hide .del, .CT-hide .del { + display: none; +} + +.CT-hide .ins, .CT-hide .ins { + color: #333333; + background: none !important; + border: none !important; +} + +.ins, +.del { + -webkit-border-radius: 3px; + border-radius: 3px; + color: #000; + padding: 1px 0 2px; +} + +.ins { + background-color: #e5ffcd; +} + +.del { + text-decoration: line-through; + color: #555; + background-color: #e8e8e8; +} diff --git a/lib/tinymce/jscripts/tinymce4/plugins/ice/img/accept.gif b/lib/tinymce/jscripts/tinymce4/plugins/ice/img/accept.gif new file mode 100644 index 0000000000000000000000000000000000000000..d3960ddcf7005b7574488598305c9d0397230d4d GIT binary patch literal 197 zcmZ?wbhEHb6k!lyIKsd%WnK3A<8_-(v~D@owSDXA?WZU2JTraQ>DhbFF24L~^0n8q zZoHX)`|Z+4AGg2$c;n;Or$2suW*`M9{$$}~U=U=`0cir+$-wHApwgF;IWJ??x}4XG z4p=jJ{J9jc_Lg9Q4LgIPYxhr?gNkP^2rw{lFBfuU;1S_$of0Z)ux)LYqsD5#`1F}o KXT#bV7_0#j>P1=r literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/ice/img/ice-accept-change.png b/lib/tinymce/jscripts/tinymce4/plugins/ice/img/ice-accept-change.png new file mode 100644 index 0000000000000000000000000000000000000000..535687c6c4ec9896e0dece9ece3935fcf60b73cf GIT binary patch literal 3228 zcmV;N3}f?&P)Oz@Z0f2-7z;ux~O9+4z06=<WDR*FRcSTFz- zW=q650N5=6FiBTtNC2?60Km==3$g$R3;-}uh=nNt1bYBr$Ri_o0EC$U6h`t_Jn<{8 z5a%iY0C<_QJh>z}MS)ugEpZ1|S1ukX&Pf+56gFW3VVXcL!g-k)GJ!M?;PcD?0HBc- z5#WRK{dmp}uFlRjj{U%*%WZ25jX z{P*?XzTzZ-GF^d31o+^>%=Ap99M6&ogks$0k4OBs3;+Bb(;~!4V!2o<6ys46agIcq zjPo+3B8fthDa9qy|77CdEc*jK-!%ZRYCZvbku9iQV*~a}ClFY4z~c7+0P?$U!PF=S z1Au6Q;m>#f??3%Vpd|o+W=WE9003S@Bra6Svp>fO002awfhw>;8}z{#EWidF!3EsG z3;bXU&9EIRU@z1_9W=mEXoiz;4lcq~xDGvV5BgyU zp1~-*fe8db$Osc*A=-!mVv1NJjtCc-h4>-CNCXm#Bp}I%6j35eku^v$Qi@a{RY)E3 zJ#qp$hg?Rwkvqr$GJ^buyhkyVfwECO)C{#lxu`c9ghrwZ&}4KmnvWKso6vH!8a<3Q zq36)6Xb;+tK10Vaz~~qUGsJ8#F2=(`u{bOVlVi)VBCHIn#u~6ztOL7=^<&SmcLWlF zMZgI*1b0FpVIDz9SWH+>*hr`#93(Um+6gxa1B6k+CnA%mOSC4s5&6UzVlpv@SV$}* z))J2sFA#f(L&P^E5{W}HC%KRUNwK6<(h|}}(r!{C=`5+6G)NjFlgZj-YqAG9lq?`C z$c5yc>d>VnA`E_*3F2Qp##d8RZb=H01_mm@+|Cqnc9PsG(F5HIG_C zt)aG3uTh7n6Et<2In9F>NlT@zqLtGcXcuVrX|L#Xx)I%#9!{6gSJKPrN9dR61N3(c z4Tcqi$B1Vr8Jidf7-t!G7_XR2rWwr)$3XQ?}=hpK0&Z&W{| zep&sA23f;Q!%st`QJ}G3cbou<7-yIK2z4nfCCCtN2-XOGSWo##{8Q{ATurxr~;I`ytDs%xbip}RzP zziy}Qn4Z2~fSycmr`~zJ=lUFdFa1>gZThG6M+{g7vkW8#+YHVaJjFF}Z#*3@$J_By zLtVo_L#1JrVVB{Ak-5=4qt!-@Mh}c>#$4kh<88)m#-k<%CLtzEP3leVno>={htGUuD;o7bD)w_sX$S}eAxwzy?UvgBH(S?;#HZiQMoS*2K2 zT3xe7t(~nU*1N5{rxB;QPLocnp4Ml>u<^FZwyC!nu;thW+pe~4wtZn|Vi#w(#jeBd zlf9FDx_yoPJqHbk*$%56S{;6Kv~mM9!g3B(KJ}#RZ#@)!hR|78Dq|Iq-afF%KE1Brn_fm;Im z_u$xr8UFki1L{Ox>G0o)(&RAZ;=|I=wN2l97;cLaHH6leTB-XXa*h%dBOEvi`+x zi?=Txl?TadvyiL>SuF~-LZ;|cS}4~l2eM~nS7yJ>iOM;atDY;(?aZ^v+mJV$@1Ote z62cPUlD4IWOIIx&SmwQ~YB{nzae3Pc;}r!fhE@iwJh+OsDs9zItL;~pu715HdQEGA zUct(O!LkCy1<%NCg+}G`0PgpNm-?d@-hMgNe6^V+j6x$b<6@S<$+<4_1hi}Ti zncS4LsjI}fWY1>OX6feMEuLErma3QLmkw?X+1j)X-&VBk_4Y;EFPF_I+q;9dL%E~B zJh;4Nr^(LEJ3myURP{Rblsw%57T)g973R8o)DE9*xN#~;4_o$q%o z4K@u`jhx2fBXC4{U8Qn{*%*B$Ge=nny$HAYq{=vy|sI0 z_vss+H_qMky?OB#|JK!>IX&II^LlUh#rO5!7TtbwC;iULyV-Xq?ybB}ykGP{?LpZ? z-G|jbTmIbG@7#ZCz;~eY(cDM(28Dyq{*m>M4?_iynUBkc4TkHUI6gT!;y-fz>HMcd z&t%Ugo)`Y2{>!cx7B7DI)$7;J(U{Spm-3gBzioV_{p!H$8L!*M!p0uH$#^p{Ui4P` z?ZJ24cOCDe-w#jZd?0@)|7iKK^;6KN`;!@ylm7$*nDhK&GcDTy000JJOGiWi{{a60 z|De66lK=n!32;bRa{vGf6951U69E94oEQKA00(qQO+^RW1sW0}3v8>FaR2}T&PhZ; zR5;6HV4yN!L>E}HWCA^h((182*cO@n&0bVCUa647V9@8tCim3)jrZ$jI>g<5LDP9tnp3|Nk@m z{`;FDX?X~PhN?76u#+Rh@`Ky|?>T$&3$lI`1Nr&+;X$xs#ftxH-z;Ew{_6>YGP@Ro ztAHQFvNtmr6jVhRTpdjq9)EepuEX!{8XE#qj>k zX9htLUWP|so-wRnaQy9`KYz8*4a4igA3uKZmu|^A{P6#ET}>x31_lNOhF{bI*q>r1{n=XXD3c=h!y!@h;r4$co;V~@))qQK9e zKULzE1imuqR9koV=^YM2>RAXWU}tB)vuV>NBL+T(=gQJ5e@Dv#3;+Pit-p03@YL=A O0000KLZ*U+IBfRsybQWXdwQbLP>6pAqfylh#{fb6;Z(vMMVS~$e@S=j*ftg6;Uhf59&ghTmgWD0l;*T zI709Y^p6lP1rIRMx#05C~cW=H_Aw*bJ-5DT&Z2n+x)QHX^p z00esgV8|mQcmRZ%02D^@S3L16t`O%c004NIvOKvYIYoh62rY33S640`D9%Y2D-rV&neh&#Q1i z007~1e$oCcFS8neI|hJl{-P!B1ZZ9hpmq0)X0i`JwE&>$+E?>%_LC6RbVIkUx0b+_+BaR3cnT7Zv!AJxW zizFb)h!jyGOOZ85F;a?DAXP{m@;!0_IfqH8(HlgRxt7s3}k3K`kFu>>-2Q$QMFfPW!La{h336o>X zu_CMttHv6zR;&ZNiS=X8v3CR#fknUxHUxJ0uoBa_M6WNWeqIg~6QE69c9o#eyhGvpiOA@W-aonk<7r1(?fC{oI5N*U!4 zfg=2N-7=cNnjjOr{yriy6mMFgG#l znCF=fnQv8CDz++o6_Lscl}eQ+l^ZHARH>?_s@|##Rr6KLRFA1%Q+=*RRWnoLsR`7U zt5vFIcfW3@?wFpwUVxrVZ>QdQz32KIeJ}k~{cZZE^+ya? z2D1z#2HOnI7(B%_ac?{wFUQ;QQA1tBKtrWrm0_3Rgps+?Jfqb{jYbcQX~taRB;#$y zZN{S}1|}gUOHJxc?wV3fxuz+mJ4`!F$IZ;mqRrNsHJd##*D~ju=bP7?-?v~|cv>vB zsJ6IeNwVZxrdjT`yl#bBIa#GxRa#xMMy;K#CDyyGyQdMSxlWT#tDe?p!?5wT$+oGt z8L;Kp2HUQ-ZMJ=3XJQv;x5ci*?vuTfeY$;({XGW_huIFR9a(?@3)XSs8O^N5RyOM=TTmp(3=8^+zpz2r)C z^>JO{deZfso3oq3?Wo(Y?l$ge?uXo;%ru`Vo>?<<(8I_>;8Eq#KMS9gFl*neeosSB zfoHYnBQIkwkyowPu(zdms`p{<7e4kra-ZWq<2*OsGTvEV%s0Td$hXT+!*8Bnh2KMe zBmZRodjHV?r+_5^X9J0WL4jKW`}lf%A-|44I@@LTvf1rHjG(ze6+w@Jt%Bvjts!X0 z?2xS?_ve_-kiKB_KiJlZ$9G`c^=E@oNG)mWWaNo-3TIW8)$Hg0Ub-~8?KhvJ>$ z3*&nim@mj(aCxE5!t{lw7O5^0EIO7zOo&c6l<+|iDySBWCGrz@C5{St!X3hAA}`T4 z(TLbXTq+(;@<=L8dXnssyft|w#WSTW<++3>sgS%(4NTpeI-VAqb|7ssJvzNHgOZVu zaYCvgO_R1~>SyL=cFU|~g|hy|Zi}}s9+d~lYqOB71z9Z$wnC=pR9Yz4DhIM>Wmjgu z&56o6maCpC&F##y%G;1PobR9i?GnNg;gYtchD%p19a!eQtZF&3JaKv33gZ<8D~47E ztUS1iwkmDaPpj=$m#%)jCVEY4fnLGNg2A-`YwHVD3gv};>)hAvT~AmqS>Lr``i7kw zJ{5_It`yrBmlc25DBO7E8;5VoznR>Ww5hAaxn$2~(q`%A-YuS64wkBy=9dm`4cXeX z4c}I@?e+FW+b@^RDBHV(wnMq2zdX3SWv9u`%{xC-q*U}&`cyXV(%rRT*Z6MH?i+i& z_B8C(+grT%{XWUQ+f@NoP1R=AW&26{v-dx)iK^-Nmiuj8txj!m?Z*Ss1N{dh4z}01 z)YTo*JycSU)+_5r4#yw9{+;i4Ee$peRgIj+;v;ZGdF1K$3E%e~4LaI(jC-u%2h$&R z9cLXcYC@Xwnns&bn)_Q~Te?roKGD|d-g^8;+aC{{G(1^(O7m37Y1-+6)01cN&y1aw zoqc{T`P^XJqPBbIW6s}d4{z_f5Om?vMgNQEJG?v2T=KYd^0M3I6IZxbny)%vZR&LD zJpPl@Psh8QyPB@KTx+@RdcC!KX7}kEo;S|j^u2lU7XQ}Oo;f|;z4Ll+_r>@1-xl3| zawq-H%e&ckC+@AhPrP6BKT#_XdT7&;F71j}Joy zkC~6lh7E@6o;W@^IpRNZ{ptLtL(gQ-CY~4mqW;US7Zxvm_|@yz&e53Bp_lTPlfP|z zrTyx_>lv@x#=^!PzR7qqF<$gm`|ZJZ+;<)Cqu&ot2z=0000WV@Og>004R=004l4008;_004mL004C`008P>0026e000+nl3&F} z0007|Nkl{j=ktLoSQpE(evae7aoiTe zFaRmtXMX*GO%K6 zXsUj@ywDFIAILCF)@U@s@ApHJq@vFxBG{dFjD)V&9JL}t?MC4`RC`85cn}-Ky7&bRdt2c$ zx^Xvl1NDs+aCNrhb0UK2H-Utd$yf?11fY0EM7VhWG_?B(7rJ{eG5#DAiJPcy(Bp`+ z8LL7VBex#@%4B5AVB2u4C{V3Xh;KsX5{Sw%be?KOJhll_MLE_I5qL&lQ6?iF9Bdno z7VVUr!dy0a;&J&=KVD4Fqou0~FanXyBxc5zaH;vq_cCasJGLGXDGGB*>0n%l{0QUy zlU3Aq=<)7O7`OX8SY2An%Cfw@vU6&@UTOZ6Gf0S4g1+&qW~vMhgXu~^N^%M0rOB&DAJ c`yc!F0N4XOz@Z0f2-7z;ux~O9+4z06=<WDR*FRcSTFz- zW=q650N5=6FiBTtNC2?60Km==3$g$R3;-}uh=nNt1bYBr$Ri_o0EC$U6h`t_Jn<{8 z5a%iY0C<_QJh>z}MS)ugEpZ1|S1ukX&Pf+56gFW3VVXcL!g-k)GJ!M?;PcD?0HBc- z5#WRK{dmp}uFlRjj{U%*%WZ25jX z{P*?XzTzZ-GF^d31o+^>%=Ap99M6&ogks$0k4OBs3;+Bb(;~!4V!2o<6ys46agIcq zjPo+3B8fthDa9qy|77CdEc*jK-!%ZRYCZvbku9iQV*~a}ClFY4z~c7+0P?$U!PF=S z1Au6Q;m>#f??3%Vpd|o+W=WE9003S@Bra6Svp>fO002awfhw>;8}z{#EWidF!3EsG z3;bXU&9EIRU@z1_9W=mEXoiz;4lcq~xDGvV5BgyU zp1~-*fe8db$Osc*A=-!mVv1NJjtCc-h4>-CNCXm#Bp}I%6j35eku^v$Qi@a{RY)E3 zJ#qp$hg?Rwkvqr$GJ^buyhkyVfwECO)C{#lxu`c9ghrwZ&}4KmnvWKso6vH!8a<3Q zq36)6Xb;+tK10Vaz~~qUGsJ8#F2=(`u{bOVlVi)VBCHIn#u~6ztOL7=^<&SmcLWlF zMZgI*1b0FpVIDz9SWH+>*hr`#93(Um+6gxa1B6k+CnA%mOSC4s5&6UzVlpv@SV$}* z))J2sFA#f(L&P^E5{W}HC%KRUNwK6<(h|}}(r!{C=`5+6G)NjFlgZj-YqAG9lq?`C z$c5yc>d>VnA`E_*3F2Qp##d8RZb=H01_mm@+|Cqnc9PsG(F5HIG_C zt)aG3uTh7n6Et<2In9F>NlT@zqLtGcXcuVrX|L#Xx)I%#9!{6gSJKPrN9dR61N3(c z4Tcqi$B1Vr8Jidf7-t!G7_XR2rWwr)$3XQ?}=hpK0&Z&W{| zep&sA23f;Q!%st`QJ}G3cbou<7-yIK2z4nfCCCtN2-XOGSWo##{8Q{ATurxr~;I`ytDs%xbip}RzP zziy}Qn4Z2~fSycmr`~zJ=lUFdFa1>gZThG6M+{g7vkW8#+YHVaJjFF}Z#*3@$J_By zLtVo_L#1JrVVB{Ak-5=4qt!-@Mh}c>#$4kh<88)m#-k<%CLtzEP3leVno>={htGUuD;o7bD)w_sX$S}eAxwzy?UvgBH(S?;#HZiQMoS*2K2 zT3xe7t(~nU*1N5{rxB;QPLocnp4Ml>u<^FZwyC!nu;thW+pe~4wtZn|Vi#w(#jeBd zlf9FDx_yoPJqHbk*$%56S{;6Kv~mM9!g3B(KJ}#RZ#@)!hR|78Dq|Iq-afF%KE1Brn_fm;Im z_u$xr8UFki1L{Ox>G0o)(&RAZ;=|I=wN2l97;cLaHH6leTB-XXa*h%dBOEvi`+x zi?=Txl?TadvyiL>SuF~-LZ;|cS}4~l2eM~nS7yJ>iOM;atDY;(?aZ^v+mJV$@1Ote z62cPUlD4IWOIIx&SmwQ~YB{nzae3Pc;}r!fhE@iwJh+OsDs9zItL;~pu715HdQEGA zUct(O!LkCy1<%NCg+}G`0PgpNm-?d@-hMgNe6^V+j6x$b<6@S<$+<4_1hi}Ti zncS4LsjI}fWY1>OX6feMEuLErma3QLmkw?X+1j)X-&VBk_4Y;EFPF_I+q;9dL%E~B zJh;4Nr^(LEJ3myURP{Rblsw%57T)g973R8o)DE9*xN#~;4_o$q%o z4K@u`jhx2fBXC4{U8Qn{*%*B$Ge=nny$HAYq{=vy|sI0 z_vss+H_qMky?OB#|JK!>IX&II^LlUh#rO5!7TtbwC;iULyV-Xq?ybB}ykGP{?LpZ? z-G|jbTmIbG@7#ZCz;~eY(cDM(28Dyq{*m>M4?_iynUBkc4TkHUI6gT!;y-fz>HMcd z&t%Ugo)`Y2{>!cx7B7DI)$7;J(U{Spm-3gBzioV_{p!H$8L!*M!p0uH$#^p{Ui4P` z?ZJ24cOCDe-w#jZd?0@)|7iKK^;6KN`;!@ylm7$*nDhK&GcDTy000JJOGiWi{{a60 z|De66lK=n!32;bRa{vGf6951U69E94oEQKA00(qQO+^RW1sW0}6_%u{5&!@JXGugs zR5;7+lf6qqaTJD6enKj!MFm2MI3y*uWKdK(SkWN3Lz0Mi zo}g5cB$E-}YSAbGtXQgO?DmOYg|S$S1VQ*F-FCT1p17s_@d=UBNw(7f@z+L&dvmgWg^Q8Mu3>7D3YTFTx6P86%~88pQW?G8 zjXzzl778J$QsI4V73rC2JekcXyIn||Or1NW^5!$A=vP>c$4R5pQTZiH%RRJ(1@C~| P00000NkvXXu0mjfod(wx literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/ice/img/ice-reject.png b/lib/tinymce/jscripts/tinymce4/plugins/ice/img/ice-reject.png new file mode 100644 index 0000000000000000000000000000000000000000..fe1f54daf022699685cfb4aab651b15e22da39fc GIT binary patch literal 3405 zcmV-T4YKlyP)KLZ*U+IBfRsybQWXdwQbLP>6pAqfylh#{fb6;Z(vMMVS~$e@S=j*ftg6;Uhf59&ghTmgWD0l;*T zI709Y^p6lP1rIRMx#05C~cW=H_Aw*bJ-5DT&Z2n+x)QHX^p z00esgV8|mQcmRZ%02D^@S3L16t`O%c004NIvOKvYIYoh62rY33S640`D9%Y2D-rV&neh&#Q1i z007~1e$oCcFS8neI|hJl{-P!B1ZZ9hpmq0)X0i`JwE&>$+E?>%_LC6RbVIkUx0b+_+BaR3cnT7Zv!AJxW zizFb)h!jyGOOZ85F;a?DAXP{m@;!0_IfqH8(HlgRxt7s3}k3K`kFu>>-2Q$QMFfPW!La{h336o>X zu_CMttHv6zR;&ZNiS=X8v3CR#fknUxHUxJ0uoBa_M6WNWeqIg~6QE69c9o#eyhGvpiOA@W-aonk<7r1(?fC{oI5N*U!4 zfg=2N-7=cNnjjOr{yriy6mMFgG#l znCF=fnQv8CDz++o6_Lscl}eQ+l^ZHARH>?_s@|##Rr6KLRFA1%Q+=*RRWnoLsR`7U zt5vFIcfW3@?wFpwUVxrVZ>QdQz32KIeJ}k~{cZZE^+ya? z2D1z#2HOnI7(B%_ac?{wFUQ;QQA1tBKtrWrm0_3Rgps+?Jfqb{jYbcQX~taRB;#$y zZN{S}1|}gUOHJxc?wV3fxuz+mJ4`!F$IZ;mqRrNsHJd##*D~ju=bP7?-?v~|cv>vB zsJ6IeNwVZxrdjT`yl#bBIa#GxRa#xMMy;K#CDyyGyQdMSxlWT#tDe?p!?5wT$+oGt z8L;Kp2HUQ-ZMJ=3XJQv;x5ci*?vuTfeY$;({XGW_huIFR9a(?@3)XSs8O^N5RyOM=TTmp(3=8^+zpz2r)C z^>JO{deZfso3oq3?Wo(Y?l$ge?uXo;%ru`Vo>?<<(8I_>;8Eq#KMS9gFl*neeosSB zfoHYnBQIkwkyowPu(zdms`p{<7e4kra-ZWq<2*OsGTvEV%s0Td$hXT+!*8Bnh2KMe zBmZRodjHV?r+_5^X9J0WL4jKW`}lf%A-|44I@@LTvf1rHjG(ze6+w@Jt%Bvjts!X0 z?2xS?_ve_-kiKB_KiJlZ$9G`c^=E@oNG)mWWaNo-3TIW8)$Hg0Ub-~8?KhvJ>$ z3*&nim@mj(aCxE5!t{lw7O5^0EIO7zOo&c6l<+|iDySBWCGrz@C5{St!X3hAA}`T4 z(TLbXTq+(;@<=L8dXnssyft|w#WSTW<++3>sgS%(4NTpeI-VAqb|7ssJvzNHgOZVu zaYCvgO_R1~>SyL=cFU|~g|hy|Zi}}s9+d~lYqOB71z9Z$wnC=pR9Yz4DhIM>Wmjgu z&56o6maCpC&F##y%G;1PobR9i?GnNg;gYtchD%p19a!eQtZF&3JaKv33gZ<8D~47E ztUS1iwkmDaPpj=$m#%)jCVEY4fnLGNg2A-`YwHVD3gv};>)hAvT~AmqS>Lr``i7kw zJ{5_It`yrBmlc25DBO7E8;5VoznR>Ww5hAaxn$2~(q`%A-YuS64wkBy=9dm`4cXeX z4c}I@?e+FW+b@^RDBHV(wnMq2zdX3SWv9u`%{xC-q*U}&`cyXV(%rRT*Z6MH?i+i& z_B8C(+grT%{XWUQ+f@NoP1R=AW&26{v-dx)iK^-Nmiuj8txj!m?Z*Ss1N{dh4z}01 z)YTo*JycSU)+_5r4#yw9{+;i4Ee$peRgIj+;v;ZGdF1K$3E%e~4LaI(jC-u%2h$&R z9cLXcYC@Xwnns&bn)_Q~Te?roKGD|d-g^8;+aC{{G(1^(O7m37Y1-+6)01cN&y1aw zoqc{T`P^XJqPBbIW6s}d4{z_f5Om?vMgNQEJG?v2T=KYd^0M3I6IZxbny)%vZR&LD zJpPl@Psh8QyPB@KTx+@RdcC!KX7}kEo;S|j^u2lU7XQ}Oo;f|;z4Ll+_r>@1-xl3| zawq-H%e&ckC+@AhPrP6BKT#_XdT7&;F71j}Joy zkC~6lh7E@6o;W@^IpRNZ{ptLtL(gQ-CY~4mqW;US7Zxvm_|@yz&e53Bp_lTPlfP|z zrTyx_>lv@x#=^!PzR7qqF<$gm`|ZJZ+;<)Cqu&ot2z=0000WV@Og>004R=004l4008;_004mL004C`008P>0026e000+nl3&F} z0007bNklTSNED8tIEdezR3#IM;dp&Kl1qvQuPP>zLe*4Tj z*L)c{Vq-EQ%KwHfD2JRS!C2)nCtx!g6*c~TGr2!fDjjP1Jx z##l-A!4Y6_aBm0^-39S(}3 zxDf~hnrdrnK}4vpuZJKAh(@D(6052T0OEllW6bh+JV+*!&~?4yHi-z~a2R4ujcC_Z zJY^z6EEd~~Sr(AbgQ}`vagO}X4y4PM8Vn_~@n(6ssUirVtYFI$h^&Tq^9s!-5 zxG?+}`PZ-5(w(~vXEpt=GB$R4PhX~|r`I+&H_0#zG7N)sT_;V`s8}qLwzWl{T3hMQ z{d@GKql40+tMtL^q3zLUwAj*;O#xxsIW(c2vbnt-zs6pmW#|@u&%Q-q_#sxFJS`R! z<>mUs#Jh@Hjz*&;$i^6B;E@P2kv^YTN}90-CRMVRd{0oN@Sr9c(?7I_FCyCZTCJ%RtjKt1Qbxe}BL80w_KI92tSTt`6&8 z(?D-8vfJB*{Oqhtu&e?ZhO%EmWo~ZHUFi>?fdP0H7pqOLm(;;Q-89W_-#^Q@yHPx#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2ipb; z4+RsZMWHSL00S^dL_t(I%hl9tNK|PU2k`$nbKW!WnKL)X8_sNFF=?%vifCHo(hZCu zk_fR26~V&pm)&(QbhAj1lrB`*1acl7h9T)(@nh?H`vIaJ~GNQ6e= zAL@Fn7Q_OrK82Aa@9o;%dzQaRm~C%t0Fa!BOeW=^zvfz751u|7;*yF2E)j(kQJ0>$ zJaYc4bngO6*z|>2o>O)EoBsUi=N}u(m(2MtD$C{Xjm*?Ci~xbF-e29WITdblGP473wMUc57Ae)Vwz0N?&_w!P_Mw^Fk0 zj1zgk*fGDxo?Cs&S-G!ODco|V9RTL7J4R;o^mOI*D>kkvy^@nVhwtcif@2j>!Xn+M zL7W)S*4aBb<{GlQuGZe14t(d7vods5M5E(xwD%$u3dO0KB#4TEUy@Ye#5gA!OuX9T zt^#oLlL<3c)D@V`nU7P`GT?aL-!gJ_*J=R#f9*-js>T+}Y@0pkdxenCTln&N-II?d zH0t#}$>Tfxa@Z{kR5&*UP4$VA{N3f~{fAJ2QjO^Q?0;=m#r`+xv)@{O`SmY`tU2T< SbAIUn0000EX>4Tx0C?J+Q+HUC_ZB|i_hk=OLfG)Jmu!ImA|tE_$Pihg5Rw34gb)%y#f69p zRumNxoJdu~g4GI0orvO~D7a@qiilc^Ra`jkAKa(4eR}Wh?fcjJyyu+f{LXpL4}cL8 zCXwc%Y5+M>g*-agACFH+#L2yY0u@N$1RxOR%fe>`#Q*^C19^CUbg)1C0k3ZW0swH; zE+i7i;s1lWP$pLZAdvvzA`<5d0gzGv$SzdK6adH=0I*ZDWC{S3003-xd_p1ssto|_ z^hrJi0NAOM+!p}Yq8zCR0F40vnJ7mj0zkU}U{!%qECRs70HCZuA}$2Lt^t5qwlYTo zfV~9(c8*w(4?ti5fSE!p%m5%b0suoE6U_r4Oaq`W(!b!TUvP!ENC5!A%azTSOVTqG zxRuZvck=My;vwR~Y_URN7by^C3FIQ2mzyIKNaq7g&I|wm8u`(|{y0C7=jP<$=4R(? z@ASo@{%i1WB0eGU-~POe0t5gMPS5Y!U*+Z218~Oyuywy{sapWrRsd+<`CT*H37}dE z(0cicc{uz)9-g64$UGe!3JVMEC1RnyFyo6p|1;rl;ER6t{6HT5+j{T-ahgDxt-zy$ z{c&M#cCJ#6=gR~_F>d$gBmT#QfBlXr(c(0*Tr3re@mPttP$EsodAU-NL?OwQ;u7h9 zGVvdl{RxwI4FIf$Pry#L2er#=z<%xl0*ek<(slqqe)BDi8VivC5N9+pdG`PSlfU_o zKq~;2Moa!tiTSO!5zH77Xo1hL_iEAz&sE_ z2IPPo3ZWR5K^auQI@koYumc*P5t`u;w81er4d>tzT!HIw7Y1M$p28Tsh6w~g$Osc* zAv%Z=Vvg7%&IlKojszlMNHmgwq#)^t6j36@$a16tsX}UzT}UJHEpik&ja)$bklV;0 zGK&0)yhkyVfwEBp)B<%txu_o+ipHRG(R4HqU4WLNYtb6C9zB4zqNmYI=yh}eeTt4_ zfYC7yW{lZkT#ScBV2M~7CdU?I?5=ix(HVZgM=}{CnA%mPqZa^68Xe5gFH?u96Et<2 zCC!@_L(8Nsqt(!wX=iEoXfNq>x(VHb9z~bXm(pwK2kGbOgYq4YG!XMxcgB zqf}$J#u<$v7REAV@mNCEa#jQDENhreVq3EL>`ZnA`x|yIdrVV9bE;;nW|3x{=5fsd z4#u(I@HyF>O3oq94bFQl11&!-vDRv>X03j$H`;pIzS?5#a_tuF>)P*iaGgM%ES>c_ zZ94aL3A#4AQM!e?+jYlFJ5+DSzi0S9#6BJCZ5(XZOGfi zTj0IRdtf>~J!SgN=>tB-J_4V5pNGDtz9Qc}z9W9tewls;{GR(e`pf-~_`l(K@)q$< z1z-We0p$U`ff|9c18V~x1epY-2Q>wa1-k|>3_cY?3<(WcA99m#z!&lx`C~KOXDpi0 z70L*m6G6C?@k ziR8rC#65}Qa{}jVnlqf_npBo_W3J`gqPZ95>CVfZcRX1&S&)1jiOPpx423?lIEROmG(H@JAFg?XogQlb;dIZPf{y+kr|S? zBlAsGMAqJ{&)IR=Ejg5&l$@hd4QZCNE7vf$D7Q~$D=U)?Nn}(WA6du22pZOfRS_cv~1-c(_QtNLti0-)8>m`6CO07JR*suu!$(^sg%jf zZm#rNxnmV!m1I@#YM0epR(~oNm0zrItf;Q|utvD%;#W>z)qM4NZQ9!2O1H}G>qzUQ z>u#*~S--DJy=p<#(1!30tsC);y-IHSJr>wyfLop*ExT zdYyk=%U1oZtGB+{Cfe4&-FJKQ4uc&PJKpb5^_C@dOYIJXG+^@gCvI%WcHjN%gI&kHifN$EH?V5MBa9S!3!a?Q1 zC*P)gd*e{(q0YnH!_D8Bf4B7r>qvPk(mKC&tSzH$pgp0z@92!9ogH2sN4~fJe(y2k zV|B+hk5`_cohUu=`Q(C=R&z?UQbnZ;IU-!xL z-sg{9@Vs#JBKKn3CAUkhJ+3`ResKNaNUvLO>t*-L?N>ambo5Q@JJIjcfBI^`)pOVQ z*DhV3dA;w(>>IakCfyvkCA#(acJ}QTcM9%I++BK)c(44v+WqPW`VZ=VwEnSWz-{38 zV8CF{!&wjS4he^z{*?dIhvCvk%tzHDMk9@nogW_?4H~`jWX_Y}r?RIL&&qyQ|9R_k ztLNYS;`>X_Sp3-V3;B!Bzpi3>bZWu&*$(w5Ae^4*&Um&L|hzlMF^n)0O!0Y z!1l!McC423D0V;&(RuEa!7rab4gk3KXqrELHQx!~W_eFJg+iP->kFLr@{#DQ9Er}# zGbi?O;;av$5Z^M;pE6p!o@%PvsbX|IAxFm(5}c#PsgXZrv}_qjBnK~?Jwz|#OOV1! zNnxcXFb+c^V!d&{RD41r?;fq5(08lVZ ztmb}LHFXN9l^XQ5Vmp9{El}ZX_{hNqo?Kc-^GP37s)QY?0$n9IH3xQS3QfHKhP11e z@@wCRZGlExxXIyQPK#@J5}mR#D;X-4lkTjx>JJOP t0Fq-t6PCE~ae5NV3v+-Fe*D+A>L)#5xfY}@^7;S(002ovPDHLkV1iUTLdO6A literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/ice/img/reject.gif b/lib/tinymce/jscripts/tinymce4/plugins/ice/img/reject.gif new file mode 100644 index 0000000000000000000000000000000000000000..dab6c050532f82d907a3cc1a8d103db47b40bbe5 GIT binary patch literal 165 zcmV;W09yY?Nk%w1VH5xq0J8u9x3#OmMn>CcXxn;v+k%4Iii+EikpE_8|8{o&fPnv_ zqyMk3|G2pS%*_Al>Hq)$A^8Le000jFEC2ui02BZe000D1@X1N5y*TU5yMIAIg)5QhVTr3nZU2t-1_yaWacs#7tjR<2!uZP2ZS Td=Fc(hL(sw@VI>bhyVaP`y5B) literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/ice/js/ice.min.js b/lib/tinymce/jscripts/tinymce4/plugins/ice/js/ice.min.js new file mode 100644 index 00000000..c3107046 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/ice/js/ice.min.js @@ -0,0 +1,6 @@ +/** + * Load the ice dev files + */ +(function() { + // Taken care of in the ice_on_mce.html page... +})(); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js new file mode 100644 index 00000000..145093b6 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js @@ -0,0 +1,460 @@ +(function() { + tinymce.create('tinymce.plugins.IcePlugin', { + + /** + * Tinymce initializtion API for ice. An `ice` object is expected + * with any of the following params. + */ + deleteTag: 'span', + insertTag: 'span', + deleteClass: 'del', + insertClass: 'ins', + changeIdAttribute: 'data-cid', + userIdAttribute: 'data-userid', + userNameAttribute: 'data-username', + timeAttribute: 'data-time', + preserveOnPaste: 'p', + user: { name: 'Unknown User', id: Math.random() }, + isTracking: true, + contentEditable: true, + css: 'css/ice.css', + manualInit: false, + scriptVersion: new Date().getTime(), + afterInit: function() {}, + afterClean: function(body) { return body; }, + beforePasteClean: function(body) { return body; }, + afterPasteClean: function(body) { return body; }, + + /** + * Plugin initialization - register buttons, commands, and take care of setup. + */ + init: function(ed, url) { + + var self = this, + changeEditor = null; + + + // make sure only the plugin is handling this event + ed.on('keydown', function(e) { + // prevent the delete key and backspace keys from firing twice + if(e.keyCode == 46 || e.keyCode==8) + e.preventDefault(); + + }); + + /** + * After the editor renders, initialize ice. + */ + ed.on('init', function(e) { + var dom = ed.dom; + + tinymce.extend(self, ed.getParam('ice')); + self.insertSelector = '.' + self.insertClass; + self.deleteSelector = '.' + self.deleteClass; + + // Add insert and delete tag/attribute rules. + // Important: keep `id` in attributes list in case `insertTag` is a `span` - tinymce uses temporary spans with ids. + ed.serializer.addRules(self.insertTag + '[id|class|title|'+self.changeIdAttribute + '|' + self.userIdAttribute + '|' + self.userNameAttribute + '|' + self.timeAttribute + ']'); + ed.serializer.addRules(self.deleteTag + '[id|class|title|'+self.changeIdAttribute + '|' + self.userIdAttribute + '|' + self.userNameAttribute + '|' + self.timeAttribute + ']'); + // Temporary tags to act as placeholders for deletes. + ed.serializer.addRules('tempdel[data-allocation]'); + + dom.loadCSS(self.css.indexOf('://') > 0 ? self.css : (url + '/' + self.css)); + + /** + * TODO/FIXME - Investigate further into why this doesn't work... + * + tinymce.ScriptLoader.load(url + '/js/ice.min.js', function() { + ed.execCommand('initializeice'); + }); + * + * Script load manually, instead. + */ + var startIce = function() { + if(!self.manualInit) ed.execCommand('initializeice'); + }; + var script = document.createElement('script'); + script.type = 'text/javascript'; + if (script.readyState) script.onreadystatechange = function() { startIce(); }; + else script.onload = startIce; + script.src = url + '/js/ice.min.js?version='+self.scriptVersion; + document.getElementsByTagName('head')[0].appendChild(script); + + // Setting the Show/Hide Changes button to active + //ed.controlManager.setActive('ice_toggleshowchanges', true); + //if(self.isTracking) + //ed.controlManager.setActive('ice_togglechanges', true); + }); + + /** + * Instantiates a new ice instance using the given `editor` or the current editor body. + * TODO/FIXME: There is some timing conflict that forces us to initialize ice after a + * timeout (maybe mce isn't completely initialized???). Research further... + */ + ed.addCommand('initializeice', function(editor) { + ed = editor || ed; + tinymce.DOM.win.setTimeout(function() { + changeEditor = new ice.InlineChangeEditor({ + element: ed.getBody(), + isTracking: self.isTracking, + contentEditable: self.contentEditable, + changeIdAttribute: self.changeIdAttribute, + userIdAttribute: self.userIdAttribute, + userNameAttribute: self.userNameAttribute, + timeAttribute: self.timeAttribute, + currentUser: { + id: self.user.id, + name: self.user.name + }, + plugins: [ + 'IceEmdashPlugin', + 'IceAddTitlePlugin', + 'IceSmartQuotesPlugin', + { + name: 'IceCopyPastePlugin', + settings: { + pasteType: 'formattedClean', + preserve: self.preserveOnPaste, + beforePasteClean: self.beforePasteClean, + afterPasteClean: self.afterPasteClean + } + } + ], + changeTypes: { + insertType: {tag: self.insertTag, alias: self.insertClass}, + deleteType: {tag: self.deleteTag, alias: self.deleteClass} + } + }).startTracking(); + + ed.on('mousedown', function(e) { + return changeEditor.handleEvent(e); + }); + + ed.on('keyup', function(e) { + return changeEditor.handleEvent(e); + }); + + ed.on('keydown', function(e) { + return changeEditor.handleEvent(e); + }); + + ed.on('keypress', function(e) { + return changeEditor.handleEvent(e); + }); + + setTimeout(function() { self.afterInit.call(self); }, 10); + }, 500); + }); + + /** + * Re-initializes ice's environment - resets the environment variables for the current page + * and re-initializes the internal ice range. This is useful after tinymce hides/switches + * the current editor, like when toggling to the html source view and back. + */ + ed.addCommand('ice_initenv', function() { + changeEditor.initializeEnvironment(); + changeEditor.initializeRange(); + }); + + /** + * Cleans change tracking tags out of the given, or editor, body. Removes deletes and their + * inner contents; removes insert tags, keeping their inner content in place. + * @param el optional html string or node body. + * @return clean body, void of change tracking tags. + */ + ed.addCommand('icecleanbody', function(el) { + var body = changeEditor.getCleanContent(el || ed.getContent(), self.afterClean, self.beforeClean); + return body; + }); + + /** + * Returns true if delete placeholders are in place; otherwise, false. + */ + ed.addCommand('ice_hasDeletePlaceholders', function() { + return changeEditor.isPlaceholdingDeletes; + }); + + /** + * This command will drop placeholders in place of delete tags in the editor body and + * store away the references which can be reverted back with the `ice_removeDeletePlaceholders`. + */ + ed.addCommand('ice_addDeletePlaceholders', function() { + return changeEditor.placeholdDeletes(); + }); + + /** + * Replaces delete placeholders with their respective delete nodes. + */ + ed.addCommand('ice_removeDeletePlaceholders', function() { + return changeEditor.revertDeletePlaceholders(); + }); + + /** + * Insert content with change tracking tags. + * + * The `insert` object parameter can contain the following properties: + * { `item`, `range` } + * Where `item` is the item to insert (string, or textnode) + * and `range` is an optional range to insert into. + */ + ed.addCommand('iceinsert', function(insert) { + insert = insert || {}; + changeEditor.insert(insert.item, insert.range); + }); + + /** + * Deletes content with change tracking tags. + * + * The `del` object parameter can contain the following properties: + * { `right`, `range` } + * Where `right` is an optional boolean parameter, where true deletes to the right, false to the left + * and `range` is an optional range to delete in. + * + * If the current Selection isn't collapsed then the `right` param is ignored + * and a selection delete is performed. + */ + ed.addCommand('icedelete', function(del) { + del = del || {}; + changeEditor.deleteContents(del.right, del.range); + }); + + /** + * Set the current ice user with the incoming `user`. + */ + ed.addCommand('ice_changeuser', function(user) { + changeEditor.setCurrentUser(user); + }); + + /** + * Uses the given `node` or finds the current node where the selection resides, and in the + * case of a delete tag, removes the node, or in the case of an insert, removes the outer + * insert tag and keeps the contents in place. + */ + ed.addCommand('iceaccept', function(node) { + ed.undoManager.add(); + changeEditor.acceptChange(node || ed.selection.getNode()); + cleanup(); + }); + + /** + * Uses the given `node` or finds the current node where the selection resides, and in the + * case of a delete tag, removes the outer delete tag and keeps the contents in place, or + * in the case of an insert, removes the node. + */ + ed.addCommand('icereject', function(node) { + ed.undoManager.add(); + changeEditor.rejectChange(node || ed.selection.getNode()); + cleanup(); + }); + + /** + * Cleans the editor body of change tags - removes delete nodes, and removes outer insert + * tags keeping the inner content in place. Defers to cleaning technique. + */ + ed.addCommand('iceacceptall', function() { + ed.undoManager.add(); + changeEditor.acceptAll(); + cleanup(); + }); + + /** + * Cleans the editor body of change tags - removes inserts, and removes outer delete tags, + * keeping the inner content in place. + */ + ed.addCommand('icerejectall', function() { + ed.undoManager.add(); + changeEditor.rejectAll(); + cleanup(); + }); + + /** + * Adds a class to the editor body which will toggle, hide or show, track change styling. + */ + ed.addCommand('ice_toggleshowchanges', function() { + var body = ed.getBody(), cm = ed.controlManager, disabled = true; + + if(ed.dom.hasClass(body,'CT-hide')) { + //cm.setActive('ice_toggleshowchanges', true); + ed.dom.removeClass(body, 'CT-hide'); + disabled = false; + } else { + //cm.setActive('ice_toggleshowchanges', false); + ed.dom.addClass(body, 'CT-hide'); + } + + tinymce.each(['iceacceptall','icerejectall'], function(button){ + //cm.setDisabled(button, disabled); + }); + + ed.execCommand('mceRepaint'); + }); + + /** + * Calls the ice smart quotes plugin to convert regular quotes to smart quotes. + */ + ed.addCommand('ice_smartquotes', function(quiet) { + changeEditor.pluginsManager.plugins['IceSmartQuotesPlugin'].convert(ed.getBody()); + if (!quiet) ed.windowManager.alert('Regular quotes have been converted into smart quotes.'); + }); + + /** + * Toggle change tracking on or off. Delegates to ice_enable or ice_disable. + */ + ed.addCommand('ice_togglechanges', function() { + if(changeEditor.isTracking) { + ed.execCommand('ice_disable'); + } else { + ed.execCommand('ice_enable'); + } + }); + + /** + * Turns change tracking on - ice will handle incoming key events. + */ + ed.addCommand('ice_enable', function() { + changeEditor.enableChangeTracking(); + //ed.controlManager.setActive('ice_togglechanges', true); + self.isTracking = true; + }); + + /** + * Turns change tracking off - ice will be present but it won't listen + * or act on events. + */ + ed.addCommand('ice_disable', function() { + changeEditor.disableChangeTracking(); + //ed.controlManager.setActive('ice_togglechanges', false); + self.isTracking = false; + }); + + /** + * Returns 1 if ice is handling events and tracking changes; otherwise, 0. + */ + ed.addCommand('ice_isTracking', function() { + return changeEditor.isTracking ? 1 : 0; + }); + + /** + * Calls the copy-paste ice plugin to strip tags and attributes out of the given `html`. + */ + ed.addCommand('ice_strippaste', function(html) { + return changeEditor.pluginsManager.plugins['IceCopyPastePlugin'].stripPaste(html); + }); + + /** + * Makes a manual call to the paste handler - this feature is only useful when `isTracking` + * is false; otherwise, ice will automatically handle paste events. + */ + ed.addCommand('ice_handlepaste', function(html) { + return changeEditor.pluginsManager.plugins['IceCopyPastePlugin'].handlePaste(); + }); + + /** + * Makes a manual call to the emdash handler - this feature is only useful when `isTracking` + * is false and the emdash plugin is not on; otherwise, ice will handle emdash conversion. + */ + ed.addCommand('ice_handleemdash', function(html) { + return changeEditor.pluginsManager.plugins['IceEmdashPlugin'].convertEmdash() ? 1 : 0; + }); + + /** + * Register Buttons + */ + ed.addButton('iceaccept', { + title : 'Accept Change', + image : url + '/img/accept.gif', + cmd : 'iceaccept' + }); + + ed.addButton('icereject', { + title : 'Reject Change', + image : url + '/img/reject.gif', + cmd : 'icereject' + }); + + ed.addButton('iceacceptall', { + title : 'Accept All Changes', + image : url + '/img/ice-accept.png', + cmd : 'iceacceptall' + }); + + ed.addButton('icerejectall', { + title : 'Reject All Changes', + image : url + '/img/ice-reject.png', + cmd : 'icerejectall' + }); + + ed.addButton('ice_toggleshowchanges', { + title : 'Show/Hide Track Changes', + image : url + '/img/ice-showchanges.png', + cmd : 'ice_toggleshowchanges' + }); + + ed.addButton('ice_smartquotes', { + title : 'Convert quotes to smart quotes', + 'class' : 'mce_blockquote', + cmd : 'ice_smartquotes' + }); + + ed.addButton('ice_togglechanges', { + title : 'Turn On Track Changes ', + image : url + '/img/ice-togglechanges.png', + cmd : 'ice_togglechanges' + }); + + if(ed.plugins.contextmenu) { + ed.plugins.contextmenu.onContextMenu.add(function(th, menu, node) { + if(isInsideChangeTag(node)) { + menu.add({ + title: "Accept Change", + icon: 'accept', + cmd: 'iceaccept' + }); + menu.add({ + title: "Reject Change", + icon: 'reject', + cmd: 'icereject' + }); + } + }); + } + + /** + * Node Change event - watch for node changes and toggle buttons. + */ + ed.on('NodeChange',function(e) { + if (isInsideChangeTag(e.element)) { + //cm.setDisabled('iceaccept', false); + //cm.setDisabled('icereject', false); + } else { + //cm.setDisabled('iceaccept', true); + //cm.setDisabled('icereject', true); + } + cleanup(); + }); + + /** + * Private Methods + */ + + function isInsideChangeTag(n) { + return !!ed.dom.getParent(n, self.insertSelector + ',' + self.deleteSelector); + } + + function cleanup() { + var empty = ed.dom.select(self.insertSelector + ':empty,' + self.deleteSelector + ':empty'); + ed.dom.remove(empty); + // Browsers insert breaks into empty paragraphs as a space holder - clean that up + // Not playing nice with Webkit... + /*tinymce.each(ed.dom.select('br'), function(br, i) { + var p = ed.dom.getParent(br, 'p'); + if(p && (p.innerText || p.textContent) !== '') + ed.dom.remove(br); + });*/ + } + + } + }); + + tinymce.PluginManager.add('ice', tinymce.plugins.IcePlugin); +})(); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/css/searchreplace.css b/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/css/searchreplace.css new file mode 100644 index 00000000..3e2eaf34 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/css/searchreplace.css @@ -0,0 +1,6 @@ +.panel_wrapper {height:85px;} +.panel_wrapper div.current {height:85px;} + +/* IE */ +* html .panel_wrapper {height:100px;} +* html .panel_wrapper div.current {height:100px;} diff --git a/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/editor_plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/editor_plugin.js new file mode 100644 index 00000000..37289376 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/editor_plugin.js @@ -0,0 +1,61 @@ +/** + * editor_plugin_src.js + * + * Copyright 2009, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://tinymce.moxiecode.com/license + * Contributing: http://tinymce.moxiecode.com/contributing + */ + +(function() { + tinymce.create('tinymce.plugins.IceSearchReplacePlugin', { + init : function(ed, url) { + function open(m) { + // Keep IE from writing out the f/r character to the editor + // instance while initializing a new dialog. See: #3131190 + window.focus(); + + ed.windowManager.open({ + file : url + '/searchreplace.htm', + width : 420 + parseInt(ed.getLang('searchreplace.delta_width', 0)), + height : 170 + parseInt(ed.getLang('searchreplace.delta_height', 0)), + inline : 1, + auto_focus : 0 + }, { + mode : m, + search_string : ed.selection.getContent({format : 'text'}), + plugin_url : url + }); + }; + + // Register commands + ed.addCommand('mceSearch', function() { + open('search'); + }); + + ed.addCommand('mceReplace', function() { + open('replace'); + }); + + // Register buttons + ed.addButton('search', {title : 'searchreplace.search_desc', cmd : 'mceSearch'}); + ed.addButton('replace', {title : 'searchreplace.replace_desc', cmd : 'mceReplace'}); + + ed.addShortcut('ctrl+f', 'searchreplace.search_desc', 'mceSearch'); + }, + + getInfo : function() { + return { + longname : 'Ice Search/Replace', + author : 'Moxiecode Systems AB, modified by The New York Times', + authorurl : 'http://tinymce.moxiecode.com', + infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/searchreplace', + version : tinymce.majorVersion + "." + tinymce.minorVersion + }; + } + }); + + // Register plugin + tinymce.PluginManager.add('icesearchreplace', tinymce.plugins.IceSearchReplacePlugin); +})(); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/js/searchreplace.js b/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/js/searchreplace.js new file mode 100644 index 00000000..531e02d8 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/js/searchreplace.js @@ -0,0 +1,160 @@ +tinyMCEPopup.requireLangPack(); + +var SearchReplaceDialog = { + init : function(ed) { + var t = this, f = document.forms[0], m = tinyMCEPopup.getWindowArg("mode"); + + t.switchMode(m); + + f[m + '_panel_searchstring'].value = tinyMCEPopup.getWindowArg("search_string"); + + // Focus input field + f[m + '_panel_searchstring'].focus(); + + mcTabs.onChange.add(function(tab_id, panel_id) { + t.switchMode(tab_id.substring(0, tab_id.indexOf('_'))); + }); + }, + + switchMode : function(m) { + var f, lm = this.lastMode; + + if (lm != m) { + f = document.forms[0]; + + if (lm) { + f[m + '_panel_searchstring'].value = f[lm + '_panel_searchstring'].value; + f[m + '_panel_backwardsu'].checked = f[lm + '_panel_backwardsu'].checked; + f[m + '_panel_backwardsd'].checked = f[lm + '_panel_backwardsd'].checked; + f[m + '_panel_casesensitivebox'].checked = f[lm + '_panel_casesensitivebox'].checked; + } + + mcTabs.displayTab(m + '_tab', m + '_panel'); + document.getElementById("replaceBtn").style.display = (m == "replace") ? "inline" : "none"; + document.getElementById("replaceAllBtn").style.display = (m == "replace") ? "inline" : "none"; + this.lastMode = m; + } + }, + + searchNext : function(a) { + var ed = tinyMCEPopup.editor, se = ed.selection, r = se.getRng(), f, m = this.lastMode, s, b, fl = 0, w = ed.getWin(), wm = ed.windowManager, fo = 0; + + // Get input + f = document.forms[0]; + s = f[m + '_panel_searchstring'].value; + b = f[m + '_panel_backwardsu'].checked; + ca = f[m + '_panel_casesensitivebox'].checked; + rs = f['replace_panel_replacestring'].value; + + if (tinymce.isIE) { + r = ed.getDoc().selection.createRange(); + } + + if (s == '') + return; + + function fix() { + // Correct Firefox graphics glitches + // TODO: Verify if this is actually needed any more, maybe it was for very old FF versions? + r = se.getRng().cloneRange(); + ed.getDoc().execCommand('SelectAll', false, null); + se.setRng(r); + }; + + function replace() { + if(ed.getParam('ice') && ed.execCommand('ice_isTracking')) { + var r = se.getRng().cloneRange(); + var bm = tinyMCE.activeEditor.selection.getBookmark(); + ed.execCommand('iceinsert', { item: rs, range: r }); + tinyMCE.activeEditor.selection.moveToBookmark(bm); + r = se.getRng().cloneRange(); + ed.execCommand('icedelete', { right: null, range: r }); + } else { + ed.selection.setContent(rs); // Needs to be duplicated due to selection bug in IE + } + }; + + // IE flags + if (ca) + fl = fl | 4; + + switch (a) { + case 'all': + // Move caret to beginning of text + ed.execCommand('SelectAll'); + ed.selection.collapse(true); + + if (tinymce.isIE) { + ed.focus(); + r = ed.getDoc().selection.createRange(); + + while (r.findText(s, b ? -1 : 1, fl)) { + ed.execCommand('ice_addDeletePlaceholders'); + r.scrollIntoView(); + r.select(); + replace(); + ed.execCommand('ice_removeDeletePlaceholders'); + ed.execCommand('ice_addDeletePlaceholders'); + fo = 1; + + if (b) { + r.moveEnd("character", -(rs.length)); // Otherwise will loop forever + } + } + ed.execCommand('ice_removeDeletePlaceholders'); + tinyMCEPopup.storeSelection(); + } else { + while (w.find(s, ca, b, false, false, false, false)) { + replace(); + ed.execCommand('ice_removeDeletePlaceholders'); + ed.execCommand('ice_addDeletePlaceholders'); + fo = 1; + } + ed.execCommand('ice_removeDeletePlaceholders'); + } + + if (fo) + tinyMCEPopup.alert(ed.getLang('searchreplace_dlg.allreplaced')); + else + tinyMCEPopup.alert(ed.getLang('searchreplace_dlg.notfound')); + + return; + + case 'current': + ed.execCommand('ice_addDeletePlaceholders'); + if (!ed.selection.isCollapsed()) { + replace(); + } + ed.execCommand('ice_removeDeletePlaceholders'); + + break; + } + + se.collapse(b); + r = se.getRng(); + + // Whats the point + if (!s) + return; + + if (tinymce.isIE) { + ed.focus(); + r = ed.getDoc().selection.createRange(); + + if (r.findText(s, b ? -1 : 1, fl)) { + r.scrollIntoView(); + r.select(); + } else + tinyMCEPopup.alert(ed.getLang('searchreplace_dlg.notfound')); + + tinyMCEPopup.storeSelection(); + } else { + if (!w.find(s, ca, b, false, false, false, false)) + tinyMCEPopup.alert(ed.getLang('searchreplace_dlg.notfound')); + else + fix(); + } + } +}; + +tinyMCEPopup.onInit.add(SearchReplaceDialog.init, SearchReplaceDialog); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/langs/en_dlg.js b/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/langs/en_dlg.js new file mode 100644 index 00000000..3dd3453d --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/langs/en_dlg.js @@ -0,0 +1,16 @@ +tinyMCE.addI18n('en.searchreplace_dlg',{ +searchnext_desc:"Find again", +notfound:"The search has been completed. The search string could not be found.", +search_title:"Find", +replace_title:"Find/Replace", +allreplaced:"All occurrences of the search string were replaced.", +findwhat:"Find what", +replacewith:"Replace with", +direction:"Direction", +up:"Up", +down:"Down", +mcase:"Match case", +findnext:"Find next", +replace:"Replace", +replaceall:"Replace all" +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/plugin.js new file mode 100644 index 00000000..37289376 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/plugin.js @@ -0,0 +1,61 @@ +/** + * editor_plugin_src.js + * + * Copyright 2009, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://tinymce.moxiecode.com/license + * Contributing: http://tinymce.moxiecode.com/contributing + */ + +(function() { + tinymce.create('tinymce.plugins.IceSearchReplacePlugin', { + init : function(ed, url) { + function open(m) { + // Keep IE from writing out the f/r character to the editor + // instance while initializing a new dialog. See: #3131190 + window.focus(); + + ed.windowManager.open({ + file : url + '/searchreplace.htm', + width : 420 + parseInt(ed.getLang('searchreplace.delta_width', 0)), + height : 170 + parseInt(ed.getLang('searchreplace.delta_height', 0)), + inline : 1, + auto_focus : 0 + }, { + mode : m, + search_string : ed.selection.getContent({format : 'text'}), + plugin_url : url + }); + }; + + // Register commands + ed.addCommand('mceSearch', function() { + open('search'); + }); + + ed.addCommand('mceReplace', function() { + open('replace'); + }); + + // Register buttons + ed.addButton('search', {title : 'searchreplace.search_desc', cmd : 'mceSearch'}); + ed.addButton('replace', {title : 'searchreplace.replace_desc', cmd : 'mceReplace'}); + + ed.addShortcut('ctrl+f', 'searchreplace.search_desc', 'mceSearch'); + }, + + getInfo : function() { + return { + longname : 'Ice Search/Replace', + author : 'Moxiecode Systems AB, modified by The New York Times', + authorurl : 'http://tinymce.moxiecode.com', + infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/searchreplace', + version : tinymce.majorVersion + "." + tinymce.minorVersion + }; + } + }); + + // Register plugin + tinymce.PluginManager.add('icesearchreplace', tinymce.plugins.IceSearchReplacePlugin); +})(); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/searchreplace.htm b/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/searchreplace.htm new file mode 100644 index 00000000..bac5a184 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/icesearchreplace/searchreplace.htm @@ -0,0 +1,100 @@ + + + + {#searchreplace_dlg.replace_title} + + + + + + + + +
    + + +
    +
    + + + + + + + + + + + +
    + + + + + + + + + +
    + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + + + + +
    + + + + + + + + + +
    + + + + + +
    +
    +
    + +
    + +
    + + + + +
    +
    + + diff --git a/lib/tinymce/jscripts/tinymce4/plugins/image/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/image/plugin.js new file mode 100644 index 00000000..e2bc7838 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/image/plugin.js @@ -0,0 +1,110 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('image', function(editor) { + function showDialog() { + var win, data, dom = editor.dom, imgElm = editor.selection.getNode(); + var width, height; + + function recalcSize(e) { + var widthCtrl, heightCtrl, newWidth, newHeight; + + widthCtrl = win.find('#width')[0]; + heightCtrl = win.find('#height')[0]; + + newWidth = widthCtrl.value(); + newHeight = heightCtrl.value(); + + if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) { + if (e.control == widthCtrl) { + newHeight = Math.round((newWidth / width) * newHeight); + heightCtrl.value(newHeight); + } else { + newWidth = Math.round((newHeight / height) * newWidth); + widthCtrl.value(newWidth); + } + } + + width = newWidth; + height = newHeight; + } + + width = dom.getAttrib(imgElm, 'width'); + height = dom.getAttrib(imgElm, 'height'); + + if (imgElm.nodeName == "IMG" && !imgElm.getAttribute('data-mce-object')) { + data = { + src: dom.getAttrib(imgElm, 'src'), + alt: dom.getAttrib(imgElm, 'alt'), + width: width, + height: height + }; + } else { + imgElm = null; + } + + win = editor.windowManager.open({ + title: "Edit image", + data: data, + body: [ + {name: 'src', type: 'filepicker', filetype: 'image', label: 'Source', autofocus: true}, + {name: 'alt', type: 'textbox', label: 'Image description'}, + { + type: 'container', + label: 'Dimensions', + layout: 'flex', + direction: 'row', + align: 'center', + spacing: 5, + items: [ + {name: 'width', type: 'textbox', maxLength: 3, size: 3, onchange: recalcSize}, + {type: 'label', text: 'x'}, + {name: 'height', type: 'textbox', maxLength: 3, size: 3, onchange: recalcSize}, + {name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions'} + ] + } + ], + onSubmit: function(e) { + var data = e.data; + + if (data.width === '') { + delete data.width; + } + + if (data.height === '') { + delete data.height; + } + + if (imgElm) { + dom.setAttribs(imgElm, data); + } else { + editor.insertContent(dom.createHTML('img', data)); + } + } + }); + } + + editor.addButton('image', { + icon: 'image', + tooltip: 'Insert/edit image', + onclick: showDialog, + stateSelector: 'img:not([data-mce-object])' + }); + + editor.addMenuItem('image', { + icon: 'image', + text: 'Insert image', + onclick: showDialog, + context: 'insert', + prependToContext: true + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/image/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/image/plugin.min.js new file mode 100644 index 00000000..5b763a55 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/image/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("image",function(e){function t(){function t(e){var t,i,r,l;t=n.find("#width")[0],i=n.find("#height")[0],r=t.value(),l=i.value(),n.find("#constrain")[0].checked()&&o&&a&&r&&l&&(e.control==t?(l=Math.round(r/o*l),i.value(l)):(r=Math.round(l/a*r),t.value(r))),o=r,a=l}var n,i,o,a,r=e.dom,l=e.selection.getNode();o=r.getAttrib(l,"width"),a=r.getAttrib(l,"height"),"IMG"!=l.nodeName||l.getAttribute("data-mce-object")?l=null:i={src:r.getAttrib(l,"src"),alt:r.getAttrib(l,"alt"),width:o,height:a},n=e.windowManager.open({title:"Edit image",data:i,body:[{name:"src",type:"filepicker",filetype:"image",label:"Source",autofocus:!0},{name:"alt",type:"textbox",label:"Image description"},{type:"container",label:"Dimensions",layout:"flex",direction:"row",align:"center",spacing:5,items:[{name:"width",type:"textbox",maxLength:3,size:3,onchange:t},{type:"label",text:"x"},{name:"height",type:"textbox",maxLength:3,size:3,onchange:t},{name:"constrain",type:"checkbox",checked:!0,text:"Constrain proportions"}]}],onSubmit:function(t){var n=t.data;""===n.width&&delete n.width,""===n.height&&delete n.height,l?r.setAttribs(l,n):e.insertContent(r.createHTML("img",n))}})}e.addButton("image",{icon:"image",tooltip:"Insert/edit image",onclick:t,stateSelector:"img:not([data-mce-object])"}),e.addMenuItem("image",{icon:"image",text:"Insert image",onclick:t,context:"insert",prependToContext:!0})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/insertdatetime/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/insertdatetime/plugin.js new file mode 100644 index 00000000..91dbdd4b --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/insertdatetime/plugin.js @@ -0,0 +1,98 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('insertdatetime', function(editor) { + var daysShort = "Sun Mon Tue Wed Thu Fri Sat Sun".split(' '); + var daysLong = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(' '); + var monthsShort = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(' '); + var monthsLong = "January February March April May June July August September October November December".split(' '); + var menuItems = [], lastFormat; + + function getDateTime(fmt, date) { + function addZeros(value, len) { + value = "" + value; + + if (value.length < len) { + for (var i = 0; i < (len - value.length); i++) { + value = "0" + value; + } + } + + return value; + } + + date = date || new Date(); + + fmt = fmt.replace("%D", "%m/%d/%Y"); + fmt = fmt.replace("%r", "%I:%M:%S %p"); + fmt = fmt.replace("%Y", "" + date.getFullYear()); + fmt = fmt.replace("%y", "" + date.getYear()); + fmt = fmt.replace("%m", addZeros(date.getMonth() + 1, 2)); + fmt = fmt.replace("%d", addZeros(date.getDate(), 2)); + fmt = fmt.replace("%H", "" + addZeros(date.getHours(), 2)); + fmt = fmt.replace("%M", "" + addZeros(date.getMinutes(), 2)); + fmt = fmt.replace("%S", "" + addZeros(date.getSeconds(), 2)); + fmt = fmt.replace("%I", "" + ((date.getHours() + 11) % 12 + 1)); + fmt = fmt.replace("%p", "" + (date.getHours() < 12 ? "AM" : "PM")); + fmt = fmt.replace("%B", "" + editor.translate(monthsLong[date.getMonth()])); + fmt = fmt.replace("%b", "" + editor.translate(monthsShort[date.getMonth()])); + fmt = fmt.replace("%A", "" + editor.translate(daysLong[date.getDay()])); + fmt = fmt.replace("%a", "" + editor.translate(daysShort[date.getDay()])); + fmt = fmt.replace("%%", "%"); + + return fmt; + } + + editor.addCommand('mceInsertDate', function() { + var str = getDateTime(editor.getParam("plugin_insertdate_dateFormat", editor.translate("%Y-%m-%d"))); + + editor.execCommand('mceInsertContent', false, str); + }); + + editor.addCommand('mceInsertTime', function() { + var str = getDateTime(editor.getParam("plugin_insertdate_timeFormat", editor.translate('%H:%M:%S'))); + + editor.execCommand('mceInsertContent', false, str); + }); + + editor.addButton('inserttime', { + type: 'splitbutton', + title: 'Insert time', + onclick: function() { + editor.insertContent(getDateTime(lastFormat || "%H:%M:%S")); + }, + menu: menuItems + }); + + // TODO: Add config option here + tinymce.each([ + "%H:%M:%S", + "%Y-%m-%d", + "%I:%M:%S %p", + "%D" + ], function(fmt) { + menuItems.push({ + text: getDateTime(fmt), + onclick: function() { + lastFormat = fmt; + editor.insertContent(getDateTime(fmt)); + } + }); + }); + + editor.addMenuItem('insertdatetime', { + icon: 'date', + text: 'Insert date/time', + menu: menuItems, + context: 'insert' + }); +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/insertdatetime/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/insertdatetime/plugin.min.js new file mode 100644 index 00000000..52c28d89 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/insertdatetime/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("insertdatetime",function(e){function t(t,n){function l(e,t){if(e=""+e,t>e.length)for(var n=0;t-e.length>n;n++)e="0"+e;return e}return n=n||new Date,t=t.replace("%D","%m/%d/%Y"),t=t.replace("%r","%I:%M:%S %p"),t=t.replace("%Y",""+n.getFullYear()),t=t.replace("%y",""+n.getYear()),t=t.replace("%m",l(n.getMonth()+1,2)),t=t.replace("%d",l(n.getDate(),2)),t=t.replace("%H",""+l(n.getHours(),2)),t=t.replace("%M",""+l(n.getMinutes(),2)),t=t.replace("%S",""+l(n.getSeconds(),2)),t=t.replace("%I",""+((n.getHours()+11)%12+1)),t=t.replace("%p",""+(12>n.getHours()?"AM":"PM")),t=t.replace("%B",""+e.translate(r[n.getMonth()])),t=t.replace("%b",""+e.translate(a[n.getMonth()])),t=t.replace("%A",""+e.translate(o[n.getDay()])),t=t.replace("%a",""+e.translate(i[n.getDay()])),t=t.replace("%%","%")}var n,i="Sun Mon Tue Wed Thu Fri Sat Sun".split(" "),o="Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" "),a="Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),r="January February March April May June July August September October November December".split(" "),l=[];e.addCommand("mceInsertDate",function(){var n=t(e.getParam("plugin_insertdate_dateFormat",e.translate("%Y-%m-%d")));e.execCommand("mceInsertContent",!1,n)}),e.addCommand("mceInsertTime",function(){var n=t(e.getParam("plugin_insertdate_timeFormat",e.translate("%H:%M:%S")));e.execCommand("mceInsertContent",!1,n)}),e.addButton("inserttime",{type:"splitbutton",title:"Insert time",onclick:function(){e.insertContent(t(n||"%H:%M:%S"))},menu:l}),tinymce.each(["%H:%M:%S","%Y-%m-%d","%I:%M:%S %p","%D"],function(i){l.push({text:t(i),onclick:function(){n=i,e.insertContent(t(i))}})}),e.addMenuItem("insertdatetime",{icon:"date",text:"Insert date/time",menu:l,context:"insert"})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/layer/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/layer/plugin.js new file mode 100644 index 00000000..5d6d0e40 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/layer/plugin.js @@ -0,0 +1,225 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('layer', function(editor) { + function getParentLayer(node) { + do { + if (node.className && node.className.indexOf('mceItemLayer') != -1) { + return node; + } + } while ((node = node.parentNode)); + } + + function visualAid(e) { + var dom = editor.dom; + + tinymce.each(dom.select('div,p', e), function(e) { + if (/^(absolute|relative|fixed)$/i.test(e.style.position)) { + if (e.hasVisual) { + dom.addClass(e, 'mceItemVisualAid'); + } else { + dom.removeClass(e, 'mceItemVisualAid'); + } + + dom.addClass(e, 'mceItemLayer'); + } + }); + } + + function move(d) { + var i, z = [], le = getParentLayer(editor.selection.getNode()), ci = -1, fi = -1, nl; + + nl = []; + tinymce.walk(editor.getBody(), function(n) { + if (n.nodeType == 1 && /^(absolute|relative|static)$/i.test(n.style.position)) { + nl.push(n); + } + }, 'childNodes'); + + // Find z-indexes + for (i = 0; i < nl.length; i++) { + z[i] = nl[i].style.zIndex ? parseInt(nl[i].style.zIndex, 10) : 0; + + if (ci < 0 && nl[i] == le) { + ci = i; + } + } + + if (d < 0) { + // Move back + + // Try find a lower one + for (i = 0; i < z.length; i++) { + if (z[i] < z[ci]) { + fi = i; + break; + } + } + + if (fi > -1) { + nl[ci].style.zIndex = z[fi]; + nl[fi].style.zIndex = z[ci]; + } else { + if (z[ci] > 0) { + nl[ci].style.zIndex = z[ci] - 1; + } + } + } else { + // Move forward + + // Try find a higher one + for (i = 0; i < z.length; i++) { + if (z[i] > z[ci]) { + fi = i; + break; + } + } + + if (fi > -1) { + nl[ci].style.zIndex = z[fi]; + nl[fi].style.zIndex = z[ci]; + } else { + nl[ci].style.zIndex = z[ci] + 1; + } + } + + editor.execCommand('mceRepaint'); + } + + function insertLayer() { + var dom = editor.dom, p = dom.getPos(dom.getParent(editor.selection.getNode(), '*')); + var body = editor.getBody(); + + editor.dom.add(body, 'div', { + style: { + position: 'absolute', + left: p.x, + top: (p.y > 20 ? p.y : 20), + width: 100, + height: 100 + }, + 'class': 'mceItemVisualAid mceItemLayer' + }, editor.selection.getContent() || editor.getLang('layer.content')); + + // Workaround for IE where it messes up the JS engine if you insert a layer on IE 6,7 + if (tinymce.Env.ie) { + dom.setHTML(body, body.innerHTML); + } + } + + function toggleAbsolute() { + var le = getParentLayer(editor.selection.getNode()); + + if (!le) { + le = editor.dom.getParent(editor.selection.getNode(), 'DIV,P,IMG'); + } + + if (le) { + if (le.style.position.toLowerCase() == "absolute") { + editor.dom.setStyles(le, { + position: '', + left: '', + top: '', + width: '', + height: '' + }); + + editor.dom.removeClass(le, 'mceItemVisualAid'); + editor.dom.removeClass(le, 'mceItemLayer'); + } else { + if (!le.style.left) { + le.style.left = 20 + 'px'; + } + + if (!le.style.top) { + le.style.top = 20 + 'px'; + } + + if (!le.style.width) { + le.style.width = le.width ? (le.width + 'px') : '100px'; + } + + if (!le.style.height) { + le.style.height = le.height ? (le.height + 'px') : '100px'; + } + + le.style.position = "absolute"; + + editor.dom.setAttrib(le, 'data-mce-style', ''); + editor.addVisual(editor.getBody()); + } + + editor.execCommand('mceRepaint'); + editor.nodeChanged(); + } + } + + // Register commands + editor.addCommand('mceInsertLayer', insertLayer); + + editor.addCommand('mceMoveForward', function() { + move(1); + }); + + editor.addCommand('mceMoveBackward', function() { + move(-1); + }); + + editor.addCommand('mceMakeAbsolute', function() { + toggleAbsolute(); + }); + + // Register buttons + editor.addButton('moveforward', {title: 'layer.forward_desc', cmd: 'mceMoveForward'}); + editor.addButton('movebackward', {title: 'layer.backward_desc', cmd: 'mceMoveBackward'}); + editor.addButton('absolute', {title: 'layer.absolute_desc', cmd: 'mceMakeAbsolute'}); + editor.addButton('insertlayer', {title: 'layer.insertlayer_desc', cmd: 'mceInsertLayer'}); + + editor.on('init', function() { + if (tinymce.Env.ie) { + editor.getDoc().execCommand('2D-Position', false, true); + } + }); + + // Remove serialized styles when selecting a layer since it might be changed by a drag operation + editor.on('mouseup', function(e) { + var layer = getParentLayer(e.target); + + if (layer) { + editor.dom.setAttrib(layer, 'data-mce-style', ''); + } + }); + + // Fixes edit focus issues with layers on Gecko + // This will enable designMode while inside a layer and disable it when outside + editor.on('mousedown', function(e) { + var node = e.target, doc = editor.getDoc(), parent; + + if (tinymce.Env.gecko) { + if (getParentLayer(node)) { + if (doc.designMode !== 'on') { + doc.designMode = 'on'; + + // Repaint caret + node = doc.body; + parent = node.parentNode; + parent.removeChild(node); + parent.appendChild(node); + } + } else if (doc.designMode == 'on') { + doc.designMode = 'off'; + } + } + }); + + editor.on('NodeChange', visualAid); +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/layer/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/layer/plugin.min.js new file mode 100644 index 00000000..88621269 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/layer/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("layer",function(e){function t(e){do if(e.className&&-1!=e.className.indexOf("mceItemLayer"))return e;while(e=e.parentNode)}function n(t){var n=e.dom;tinymce.each(n.select("div,p",t),function(e){/^(absolute|relative|fixed)$/i.test(e.style.position)&&(e.hasVisual?n.addClass(e,"mceItemVisualAid"):n.removeClass(e,"mceItemVisualAid"),n.addClass(e,"mceItemLayer"))})}function i(n){var i,o,a=[],r=t(e.selection.getNode()),l=-1,c=-1;for(o=[],tinymce.walk(e.getBody(),function(e){1==e.nodeType&&/^(absolute|relative|static)$/i.test(e.style.position)&&o.push(e)},"childNodes"),i=0;o.length>i;i++)a[i]=o[i].style.zIndex?parseInt(o[i].style.zIndex,10):0,0>l&&o[i]==r&&(l=i);if(0>n){for(i=0;a.length>i;i++)if(a[i]-1?(o[l].style.zIndex=a[c],o[c].style.zIndex=a[l]):a[l]>0&&(o[l].style.zIndex=a[l]-1)}else{for(i=0;a.length>i;i++)if(a[i]>a[l]){c=i;break}c>-1?(o[l].style.zIndex=a[c],o[c].style.zIndex=a[l]):o[l].style.zIndex=a[l]+1}e.execCommand("mceRepaint")}function o(){var t=e.dom,n=t.getPos(t.getParent(e.selection.getNode(),"*")),i=e.getBody();e.dom.add(i,"div",{style:{position:"absolute",left:n.x,top:n.y>20?n.y:20,width:100,height:100},"class":"mceItemVisualAid mceItemLayer"},e.selection.getContent()||e.getLang("layer.content")),tinymce.Env.ie&&t.setHTML(i,i.innerHTML)}function a(){var n=t(e.selection.getNode());n||(n=e.dom.getParent(e.selection.getNode(),"DIV,P,IMG")),n&&("absolute"==n.style.position.toLowerCase()?(e.dom.setStyles(n,{position:"",left:"",top:"",width:"",height:""}),e.dom.removeClass(n,"mceItemVisualAid"),e.dom.removeClass(n,"mceItemLayer")):(n.style.left||(n.style.left="20px"),n.style.top||(n.style.top="20px"),n.style.width||(n.style.width=n.width?n.width+"px":"100px"),n.style.height||(n.style.height=n.height?n.height+"px":"100px"),n.style.position="absolute",e.dom.setAttrib(n,"data-mce-style",""),e.addVisual(e.getBody())),e.execCommand("mceRepaint"),e.nodeChanged())}e.addCommand("mceInsertLayer",o),e.addCommand("mceMoveForward",function(){i(1)}),e.addCommand("mceMoveBackward",function(){i(-1)}),e.addCommand("mceMakeAbsolute",function(){a()}),e.addButton("moveforward",{title:"layer.forward_desc",cmd:"mceMoveForward"}),e.addButton("movebackward",{title:"layer.backward_desc",cmd:"mceMoveBackward"}),e.addButton("absolute",{title:"layer.absolute_desc",cmd:"mceMakeAbsolute"}),e.addButton("insertlayer",{title:"layer.insertlayer_desc",cmd:"mceInsertLayer"}),e.on("init",function(){tinymce.Env.ie&&e.getDoc().execCommand("2D-Position",!1,!0)}),e.on("mouseup",function(n){var i=t(n.target);i&&e.dom.setAttrib(i,"data-mce-style","")}),e.on("mousedown",function(n){var i,o=n.target,a=e.getDoc();tinymce.Env.gecko&&(t(o)?"on"!==a.designMode&&(a.designMode="on",o=a.body,i=o.parentNode,i.removeChild(o),i.appendChild(o)):"on"==a.designMode&&(a.designMode="off"))}),e.on("NodeChange",n)}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/legacyoutput/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/legacyoutput/plugin.js new file mode 100644 index 00000000..20939bd6 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/legacyoutput/plugin.js @@ -0,0 +1,110 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + * + * This plugin will force TinyMCE to produce deprecated legacy output such as font elements, u elements, align + * attributes and so forth. There are a few cases where these old items might be needed for example in email applications or with Flash + * + * However you should NOT use this plugin if you are building some system that produces web contents such as a CMS. All these elements are + * not apart of the newer specifications for HTML and XHTML. + */ + +/*global tinymce:true */ + +(function(tinymce) { + // Override inline_styles setting to force TinyMCE to produce deprecated contents + tinymce.on('AddEditor', function(e) { + e.editor.settings.inline_styles = false; + }); + + tinymce.PluginManager.add('legacyoutput', function(editor) { + editor.on('init', function() { + var alignElements = 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', + fontSizes = tinymce.explode(editor.settings.font_size_style_values), + schema = editor.schema; + + // Override some internal formats to produce legacy elements and attributes + editor.formatter.register({ + // Change alignment formats to use the deprecated align attribute + alignleft: {selector: alignElements, attributes: {align: 'left'}}, + aligncenter: {selector: alignElements, attributes: {align: 'center'}}, + alignright: {selector: alignElements, attributes: {align: 'right'}}, + alignjustify: {selector: alignElements, attributes: {align: 'justify'}}, + + // Change the basic formatting elements to use deprecated element types + bold: [ + {inline: 'b', remove: 'all'}, + {inline: 'strong', remove: 'all'}, + {inline: 'span', styles: {fontWeight: 'bold'}} + ], + italic: [ + {inline: 'i', remove: 'all'}, + {inline: 'em', remove: 'all'}, + {inline: 'span', styles: {fontStyle: 'italic'}} + ], + underline: [ + {inline: 'u', remove: 'all'}, + {inline: 'span', styles: {textDecoration: 'underline'}, exact: true} + ], + strikethrough: [ + {inline: 'strike', remove: 'all'}, + {inline: 'span', styles: {textDecoration: 'line-through'}, exact: true} + ], + + // Change font size and font family to use the deprecated font element + fontname: {inline: 'font', attributes: {face: '%value'}}, + fontsize: { + inline: 'font', + attributes: { + size: function(vars) { + return tinymce.inArray(fontSizes, vars.value) + 1; + } + } + }, + + // Setup font elements for colors as well + forecolor: {inline: 'font', attributes: {color: '%value'}}, + hilitecolor: {inline: 'font', styles: {backgroundColor: '%value'}} + }); + + // Check that deprecated elements are allowed if not add them + tinymce.each('b,i,u,strike'.split(','), function(name) { + schema.addValidElements(name + '[*]'); + }); + + // Add font element if it's missing + if (!schema.getElementRule("font")) { + schema.addValidElements("font[face|size|color|style]"); + } + + // Add the missing and depreacted align attribute for the serialization engine + tinymce.each(alignElements.split(','), function(name) { + var rule = schema.getElementRule(name); + + if (rule) { + if (!rule.attributes.align) { + rule.attributes.align = {}; + rule.attributesOrder.push('align'); + } + } + }); + + // Listen for the onNodeChange event so that we can do special logic for the font size and font name drop boxes + /*editor.on('NodeChange', function() { + var fontElm, fontName, fontSize; + + // Find font element get it's name and size + fontElm = editor.dom.getParent(editor.selection.getNode(), 'font'); + if (fontElm) { + fontName = fontElm.face; + fontSize = fontElm.size; + } + });*/ + }); + }); +})(tinymce); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/legacyoutput/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/legacyoutput/plugin.min.js new file mode 100644 index 00000000..f2fdc1ba --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/legacyoutput/plugin.min.js @@ -0,0 +1 @@ +(function(e){e.on("AddEditor",function(e){e.editor.settings.inline_styles=!1}),e.PluginManager.add("legacyoutput",function(t){t.on("init",function(){var n="p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img",i=e.explode(t.settings.font_size_style_values),o=t.schema;t.formatter.register({alignleft:{selector:n,attributes:{align:"left"}},aligncenter:{selector:n,attributes:{align:"center"}},alignright:{selector:n,attributes:{align:"right"}},alignjustify:{selector:n,attributes:{align:"justify"}},bold:[{inline:"b",remove:"all"},{inline:"strong",remove:"all"},{inline:"span",styles:{fontWeight:"bold"}}],italic:[{inline:"i",remove:"all"},{inline:"em",remove:"all"},{inline:"span",styles:{fontStyle:"italic"}}],underline:[{inline:"u",remove:"all"},{inline:"span",styles:{textDecoration:"underline"},exact:!0}],strikethrough:[{inline:"strike",remove:"all"},{inline:"span",styles:{textDecoration:"line-through"},exact:!0}],fontname:{inline:"font",attributes:{face:"%value"}},fontsize:{inline:"font",attributes:{size:function(t){return e.inArray(i,t.value)+1}}},forecolor:{inline:"font",attributes:{color:"%value"}},hilitecolor:{inline:"font",styles:{backgroundColor:"%value"}}}),e.each("b,i,u,strike".split(","),function(e){o.addValidElements(e+"[*]")}),o.getElementRule("font")||o.addValidElements("font[face|size|color|style]"),e.each(n.split(","),function(e){var t=o.getElementRule(e);t&&(t.attributes.align||(t.attributes.align={},t.attributesOrder.push("align")))})})})})(tinymce); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/link/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/link/plugin.js new file mode 100644 index 00000000..ab701fe2 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/link/plugin.js @@ -0,0 +1,122 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('link', function(editor) { + function showDialog() { + var data = {}, selection = editor.selection, dom = editor.dom, selectedElm, anchorElm, initialText; + + function updateText() { + if (!initialText && data.text.length === 0) { + this.parent().parent().find('#text')[0].value(this.value()); + } + } + + selectedElm = selection.getNode(); + anchorElm = dom.getParent(selectedElm, 'a[href]'); + if (anchorElm) { + selection.select(anchorElm); + } + + data.text = initialText = selection.getContent({format: 'text'}); + data.href = anchorElm ? dom.getAttrib(anchorElm, 'href') : ''; + data.target = anchorElm ? dom.getAttrib(anchorElm, 'target') : ''; + + if (selectedElm.nodeName == "IMG") { + data.text = initialText = " "; + } + + editor.windowManager.open({ + title: 'Insert link', + data: data, + body: [ + {name: 'text', type: 'textbox', size: 40, label: 'Text to display', onchange: function() { + initialText = this.value(); + }}, + { + name: 'href', + type: 'filepicker', + filetype: 'file', + size: 40, + autofocus: true, + label: 'Url', + onchange: updateText, + onkeyup: updateText + }, + {name: 'target', type: 'listbox', label: 'Target', values: [ + {text: 'None', value: ''}, + {text: 'New window', value: '_blank'} + ]} + ], + onSubmit: function(e) { + var data = e.data; + + if (!data.href) { + editor.execCommand('unlink'); + return; + } + + if (data.text != initialText) { + if (anchorElm) { + editor.focus(); + anchorElm.innerHTML = data.text; + + dom.setAttribs(anchorElm, { + href: data.href, + target: data.target + }); + + selection.select(anchorElm); + } else { + editor.insertContent(dom.createHTML('a', { + href: data.href, + target: data.target + }, data.text)); + } + } else { + editor.execCommand('mceInsertLink', false, { + href: data.href, + target: data.target + }); + } + } + }); + } + + editor.addButton('link', { + icon: 'link', + tooltip: 'Insert/edit link', + shortcut: 'Ctrl+K', + onclick: showDialog, + stateSelector: 'a[href]' + }); + + editor.addButton('unlink', { + icon: 'unlink', + tooltip: 'Remove link(s)', + cmd: 'unlink', + stateSelector: 'a[href]' + }); + + editor.addShortcut('Ctrl+K', '', showDialog); + + this.showDialog = showDialog; + + editor.addMenuItem('link', { + icon: 'link', + text: 'Insert link', + shortcut: 'Ctrl+K', + onclick: showDialog, + stateSelector: 'a[href]', + context: 'insert', + prependToContext: true + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/link/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/link/plugin.min.js new file mode 100644 index 00000000..3370a477 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/link/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("link",function(e){function t(){function t(){o||0!==a.text.length||this.parent().parent().find("#text")[0].value(this.value())}var n,i,o,a={},r=e.selection,l=e.dom;n=r.getNode(),i=l.getParent(n,"a[href]"),i&&r.select(i),a.text=o=r.getContent({format:"text"}),a.href=i?l.getAttrib(i,"href"):"",a.target=i?l.getAttrib(i,"target"):"","IMG"==n.nodeName&&(a.text=o=" "),e.windowManager.open({title:"Insert link",data:a,body:[{name:"text",type:"textbox",size:40,label:"Text to display",onchange:function(){o=this.value()}},{name:"href",type:"filepicker",filetype:"file",size:40,autofocus:!0,label:"Url",onchange:t,onkeyup:t},{name:"target",type:"listbox",label:"Target",values:[{text:"None",value:""},{text:"New window",value:"_blank"}]}],onSubmit:function(t){var n=t.data;return n.href?(n.text!=o?i?(e.focus(),i.innerHTML=n.text,l.setAttribs(i,{href:n.href,target:n.target}),r.select(i)):e.insertContent(l.createHTML("a",{href:n.href,target:n.target},n.text)):e.execCommand("mceInsertLink",!1,{href:n.href,target:n.target}),void 0):(e.execCommand("unlink"),void 0)}})}e.addButton("link",{icon:"link",tooltip:"Insert/edit link",shortcut:"Ctrl+K",onclick:t,stateSelector:"a[href]"}),e.addButton("unlink",{icon:"unlink",tooltip:"Remove link(s)",cmd:"unlink",stateSelector:"a[href]"}),e.addShortcut("Ctrl+K","",t),this.showDialog=t,e.addMenuItem("link",{icon:"link",text:"Insert link",shortcut:"Ctrl+K",onclick:t,stateSelector:"a[href]",context:"insert",prependToContext:!0})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/lists/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/lists/plugin.js new file mode 100644 index 00000000..6d41d312 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/lists/plugin.js @@ -0,0 +1,612 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('lists', function(editor) { + var plugin = this; + + editor.on('init', function() { + var dom = editor.dom, selection = editor.selection; + + /** + * Returns a range bookmark. This will convert indexed bookmarks into temporary span elements with + * index 0 so that they can be restored properly after the DOM has been modified. Text bookmarks will be passed out + * as is since this is for operations that doesn't alter text. + * + * So this:

    ||

    + * becomes:

    ||

    + * + * @param {DOMRange} rng DOM Range to get bookmark on. + * @return {Object} Bookmark object. + */ + function createBookmark(rng) { + var bookmark = {}; + + function setupEndPoint(start) { + var offsetNode, container, offset; + + container = rng[start ? 'startContainer' : 'endContainer']; + offset = rng[start ? 'startOffset' : 'endOffset']; + + if (container.nodeType == 1) { + offsetNode = dom.create('span', {'data-mce-type': 'bookmark'}); + + if (container.hasChildNodes()) { + offset = Math.min(offset, container.childNodes.length - 1); + container.insertBefore(offsetNode, container.childNodes[offset]); + } else { + container.appendChild(offsetNode); + } + + container = offsetNode; + offset = 0; + } + + bookmark[start ? 'startContainer' : 'endContainer'] = container; + bookmark[start ? 'startOffset' : 'endOffset'] = offset; + } + + setupEndPoint(true); + setupEndPoint(); + + return bookmark; + } + + /** + * Moves the selection to the current bookmark and removes any selection container wrappers. + * + * @param {Object} bookmark Bookmark object to move selection to. + */ + function moveToBookmark(bookmark) { + function restoreEndPoint(start) { + var container, offset, node; + + function nodeIndex(container) { + var node = container.parentNode.firstChild, idx = 0; + + while (node) { + if (node == container) { + return idx; + } + + // Skip data-mce-type=bookmark nodes + if (node.nodeType != 1 || node.getAttribute('data-mce-type') != 'bookmark') { + idx++; + } + + node = node.nextSibling; + } + + return -1; + } + + container = node = bookmark[start ? 'startContainer' : 'endContainer']; + offset = bookmark[start ? 'startOffset' : 'endOffset']; + + if (container.nodeType == 1) { + if (start) { + offset = nodeIndex(container); + container = container.parentNode; + } else { + offset = nodeIndex(container); + container = container.parentNode; + } + + dom.remove(node); + } + + bookmark[start ? 'startContainer' : 'endContainer'] = container; + bookmark[start ? 'startOffset' : 'endOffset'] = offset; + } + + restoreEndPoint(true); + restoreEndPoint(); + + var rng = dom.createRng(); + + rng.setStart(bookmark.startContainer, bookmark.startOffset); + rng.setEnd(bookmark.endContainer, bookmark.endOffset); + + selection.setRng(rng); + } + + function isListNode(node) { + return node && (/^(OL|UL)$/).test(node.nodeName); + } + + function isFirstChild(node) { + return node.parentNode.firstChild == node; + } + + function isLastChild(node) { + return node.parentNode.lastChild == node; + } + + function isTextBlock(node) { + return node && !!editor.schema.getTextBlockElements()[node.nodeName]; + } + + function createNewTextBlock(contentNode, blockName) { + var node, textBlock; + + if (editor.settings.forced_root_block) { + blockName = blockName || editor.settings.forced_root_block; + } + + if (blockName) { + textBlock = dom.create(blockName); + } else { + textBlock = dom.createFragment(); + } + + if (contentNode) { + while ((node = contentNode.firstChild)) { + textBlock.appendChild(node); + } + } + + if (!editor.settings.forced_root_block) { + textBlock.appendChild(dom.create('br')); + } + + // BR is needed in empty blocks on non IE browsers + if (!textBlock.hasChildNodes() && !tinymce.isIE) { + textBlock.innerHTML = '
    '; + } + + return textBlock; + } + + function getSelectedListItems() { + return tinymce.grep(selection.getSelectedBlocks(), function(block) { + return block.nodeName == 'LI'; + }); + } + + function getSelectedTextBlocks() { + return tinymce.grep(selection.getSelectedBlocks(), isTextBlock); + } + + function splitList(ul, li, newBlock) { + var tmpRng, fragment; + + newBlock = newBlock || createNewTextBlock(li); + tmpRng = dom.createRng(); + tmpRng.setStartAfter(li); + tmpRng.setEndAfter(ul); + fragment = tmpRng.extractContents(); + + if (!dom.isEmpty(fragment)) { + dom.insertAfter(fragment, ul); + } + + if (!dom.isEmpty(newBlock)) { + dom.insertAfter(newBlock, ul); + } + + if (dom.isEmpty(li.parentNode)) { + dom.remove(li.parentNode); + } + + dom.remove(li); + } + + function mergeWithAdjacentLists(listBlock) { + var sibling, node; + + sibling = listBlock.nextSibling; + if (sibling && isListNode(sibling) && sibling.nodeName == listBlock.nodeName) { + while ((node = sibling.firstChild)) { + listBlock.appendChild(node); + } + + dom.remove(sibling); + } + + sibling = listBlock.previousSibling; + if (sibling && isListNode(sibling) && sibling.nodeName == listBlock.nodeName) { + while ((node = sibling.firstChild)) { + listBlock.insertBefore(node, listBlock.firstChild); + } + + dom.remove(sibling); + } + } + + /** + * Normalizes the all lists in the specified element. + */ + function normalizeList(element) { + tinymce.each(tinymce.grep(dom.select('ol,ul', element)), function(ul) { + var sibling, parentNode = ul.parentNode; + + // Move UL/OL to previous LI if it's the only child of a LI + if (parentNode.nodeName == 'LI' && parentNode.firstChild == ul) { + sibling = parentNode.previousSibling; + if (sibling && sibling.nodeName == 'LI') { + sibling.appendChild(ul); + + if (dom.isEmpty(parentNode)) { + dom.remove(parentNode); + } + } + } + + // Append OL/UL to previous LI if it's in a parent OL/UL i.e. old HTML4 + if (isListNode(parentNode)) { + sibling = parentNode.previousSibling; + if (sibling && sibling.nodeName == 'LI') { + sibling.appendChild(ul); + } + } + }); + } + + function indent() { + var state, bookmark = createBookmark(selection.getRng(true)); + + tinymce.each(getSelectedListItems(), function(li) { + var sibling, newList; + + sibling = li.previousSibling; + + if (sibling && sibling.nodeName == 'UL') { + sibling.appendChild(li); + return; + } + + if (sibling && sibling.nodeName == 'LI' && isListNode(sibling.lastChild)) { + sibling.lastChild.appendChild(li); + return; + } + + sibling = li.nextSibling; + + if (sibling && sibling.nodeName == 'UL') { + sibling.insertBefore(li, sibling.firstChild); + return; + } + + if (sibling && sibling.nodeName == 'LI' && isListNode(li.lastChild)) { + return; + } + + sibling = li.previousSibling; + if (sibling && sibling.nodeName == 'LI') { + newList = dom.create(li.parentNode.nodeName); + sibling.appendChild(newList); + newList.appendChild(li); + } + + /*sibling = li.nextSibling; + if (sibling && sibling.nodeName == 'LI') { + newList = dom.create(li.parentNode.nodeName); + sibling.insertBefore(newList, sibling.firstChild); + newList.appendChild(li); + }*/ + + state = true; + }); + + moveToBookmark(bookmark); + + return state; + } + + function outdent() { + var state, bookmark = createBookmark(selection.getRng(true)); + + tinymce.each(getSelectedListItems(), function(li) { + var ul = li.parentNode, ulParent = ul.parentNode, newBlock; + + if (isFirstChild(li) && isLastChild(li)) { + if (ulParent.nodeName == "LI") { + dom.insertAfter(li, ulParent); + } else if (isListNode(ulParent)) { + dom.remove(ul, true); + } else { + return; + } + } else if (isFirstChild(li)) { + if (ulParent.nodeName == "LI") { + dom.insertAfter(li, ulParent); + newBlock = dom.create("LI"); + newBlock.appendChild(ul); + dom.insertAfter(newBlock, li); + } else if (isListNode(ulParent)) { + ulParent.insertBefore(li, ul); + } else { + return; + } + } else if (isLastChild(li)) { + if (ulParent.nodeName == "LI") { + dom.insertAfter(li, ulParent); + } else if (isListNode(ulParent)) { + dom.insertAfter(li, ul); + } else { + return; + } + } else { + if (ulParent.nodeName == 'LI') { + ul = ulParent; + newBlock = createNewTextBlock(li, 'LI'); + } else if (isListNode(ulParent)) { + newBlock = createNewTextBlock(li, 'LI'); + } else { + return; + } + + splitList(ul, li, newBlock); + normalizeList(ul.parentNode); + } + + state = true; + }); + + moveToBookmark(bookmark); + + return state; + } + + function applyList(listName) { + var rng = selection.getRng(true), bookmark = createBookmark(rng), textBlocks = getSelectedTextBlocks(); + + function convertNonBlockLines() { + function getEndPointNode(start) { + var container, offset, root = editor.getBody(); + + container = rng[start ? 'startContainer' : 'endContainer']; + offset = rng[start ? 'startOffset' : 'endOffset']; + + // Resolve node index + if (container.nodeType == 1) { + container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container; + } + + while (container.parentNode != root) { + if (isTextBlock(container)) { + return container; + } + + if (/^(TD|TH)$/.test(container.parentNode.nodeName)) { + return container; + } + + container = container.parentNode; + } + + return container; + } + + function getAllSiblings(node, isForward) { + var sibling, siblings = []; + + if (!isTextBlock(node)) { + // Walk to start/end of line + while (node) { + sibling = node[isForward ? 'previousSibling' : 'nextSibling']; + if (dom.isBlock(sibling) || !sibling) { + break; + } + + node = sibling; + } + + while (node) { + siblings.push(node); + node = node[isForward ? 'nextSibling' : 'previousSibling']; + } + } + + return siblings; + } + + var startNode = getEndPointNode(true); + var endNode = getEndPointNode(); + var block, siblings; + + siblings = getAllSiblings(startNode, true); + + if (startNode != endNode) { + siblings = siblings.concat(getAllSiblings(endNode).reverse()); + } + + tinymce.each(siblings, function(node) { + if (dom.isBlock(node) && node.nodeName != 'BR') { + return; + } + + if (!block || node.nodeName == 'BR') { + if (node.nodeName == 'BR') { + if (!node.nextSibling || (dom.isBlock(node.nextSibling) && node.nextSibling.nodeName != "BR")) { + dom.remove(node); + return false; + } + } + + block = dom.create('p'); + textBlocks.push(block); + node.parentNode.insertBefore(block, node); + } + + if (node.nodeName != 'BR') { + block.appendChild(node); + } else { + dom.remove(node); + } + + if (node == endNode) { + return false; + } + }); + } + + convertNonBlockLines(); + + tinymce.each(textBlocks, function(block) { + var listBlock, sibling; + + sibling = block.previousSibling; + if (sibling && isListNode(sibling) && sibling.nodeName == listName) { + listBlock = sibling; + block = dom.rename(block, 'LI'); + sibling.appendChild(block); + } else { + listBlock = dom.create(listName); + block.parentNode.insertBefore(listBlock, block); + listBlock.appendChild(block); + block = dom.rename(block, 'LI'); + } + + mergeWithAdjacentLists(listBlock); + }); + + moveToBookmark(bookmark); + } + + function removeList() { + var bookmark = createBookmark(selection.getRng(true)); + + tinymce.each(getSelectedListItems(), function(li) { + var node, rootList; + + for (node = li; node; node = node.parentNode) { + if (isListNode(node)) { + rootList = node; + } + } + + splitList(rootList, li); + }); + + moveToBookmark(bookmark); + } + + function toggleList(listName) { + var parentList = dom.getParent(selection.getStart(), 'OL,UL'); + + if (parentList) { + if (parentList.nodeName == listName) { + removeList(listName); + } else { + var bookmark = createBookmark(selection.getRng(true)); + mergeWithAdjacentLists(dom.rename(parentList, listName)); + moveToBookmark(bookmark); + } + } else { + applyList(listName); + } + } + + plugin.backspaceDelete = function(isForward) { + function findNextCaretContainer(rng, isForward) { + var node = rng.startContainer, offset = rng.startOffset; + + if (node.nodeType == 3 && (isForward ? offset < node.data.length : offset > 0)) { + return node; + } + + var walker = new tinymce.dom.TreeWalker(rng.startContainer); + while ((node = walker[isForward ? 'next' : 'prev']())) { + if (node.nodeType == 3 && node.data.length > 0) { + return node; + } + } + } + + function mergeLiElements(fromElm, toElm) { + var node, listNode, ul = fromElm.parentNode; + + if (isListNode(toElm.lastChild)) { + listNode = toElm.lastChild; + } + + node = toElm.lastChild; + if (node && node.nodeName == 'BR' && fromElm.hasChildNodes()) { + dom.remove(node); + } + + while ((node = fromElm.firstChild)) { + toElm.appendChild(node); + } + + if (listNode) { + toElm.appendChild(listNode); + } + + dom.remove(fromElm); + + if (dom.isEmpty(ul)) { + dom.remove(ul); + } + } + + if (selection.isCollapsed()) { + var li = dom.getParent(selection.getStart(), 'LI'); + + if (li) { + var rng = selection.getRng(true); + var otherLi = dom.getParent(findNextCaretContainer(rng, isForward), 'LI'); + + if (otherLi && otherLi != li) { + var bookmark = createBookmark(rng); + + if (isForward) { + mergeLiElements(otherLi, li); + } else { + mergeLiElements(li, otherLi); + } + + moveToBookmark(bookmark); + + return true; + } else if (!otherLi) { + if (!isForward && removeList(li.parentNode.nodeName)) { + return true; + } + } + } + } + }; + + editor.addCommand('Indent', function() { + if (!indent()) { + return true; + } + }); + + editor.addCommand('Outdent', function() { + if (!outdent()) { + return true; + } + }); + + editor.addCommand('InsertUnorderedList', function() { + toggleList('UL'); + }); + + editor.addCommand('InsertOrderedList', function() { + toggleList('OL'); + }); + }); + + editor.on('keydown', function(e) { + if (e.keyCode == tinymce.util.VK.BACKSPACE) { + if (plugin.backspaceDelete()) { + e.preventDefault(); + } + } else if (e.keyCode == tinymce.util.VK.DELETE) { + if (plugin.backspaceDelete(true)) { + e.preventDefault(); + } + } + }); +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/lists/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/lists/plugin.min.js new file mode 100644 index 00000000..41279bed --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/lists/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("lists",function(e){var t=this;e.on("init",function(){function n(e){function t(t){var i,o,a;o=e[t?"startContainer":"endContainer"],a=e[t?"startOffset":"endOffset"],1==o.nodeType&&(i=b.create("span",{"data-mce-type":"bookmark"}),o.hasChildNodes()?(a=Math.min(a,o.childNodes.length-1),o.insertBefore(i,o.childNodes[a])):o.appendChild(i),o=i,a=0),n[t?"startContainer":"endContainer"]=o,n[t?"startOffset":"endOffset"]=a}var n={};return t(!0),t(),n}function i(e){function t(t){function n(e){for(var t=e.parentNode.firstChild,n=0;t;){if(t==e)return n;(1!=t.nodeType||"bookmark"!=t.getAttribute("data-mce-type"))&&n++,t=t.nextSibling}return-1}var i,o,a;i=a=e[t?"startContainer":"endContainer"],o=e[t?"startOffset":"endOffset"],1==i.nodeType&&(t?(o=n(i),i=i.parentNode):(o=n(i),i=i.parentNode),b.remove(a)),e[t?"startContainer":"endContainer"]=i,e[t?"startOffset":"endOffset"]=o}t(!0),t();var n=b.createRng();n.setStart(e.startContainer,e.startOffset),n.setEnd(e.endContainer,e.endOffset),C.setRng(n)}function o(e){return e&&/^(OL|UL)$/.test(e.nodeName)}function a(e){return e.parentNode.firstChild==e}function r(e){return e.parentNode.lastChild==e}function l(t){return t&&!!e.schema.getTextBlockElements()[t.nodeName]}function s(t,n){var i,o;if(e.settings.forced_root_block&&(n=n||e.settings.forced_root_block),o=n?b.create(n):b.createFragment(),t)for(;i=t.firstChild;)o.appendChild(i);return e.settings.forced_root_block||o.appendChild(b.create("br")),o.hasChildNodes()||tinymce.isIE||(o.innerHTML='
    '),o}function c(){return tinymce.grep(C.getSelectedBlocks(),function(e){return"LI"==e.nodeName})}function d(){return tinymce.grep(C.getSelectedBlocks(),l)}function u(e,t,n){var i,o;n=n||s(t),i=b.createRng(),i.setStartAfter(t),i.setEndAfter(e),o=i.extractContents(),b.isEmpty(o)||b.insertAfter(o,e),b.isEmpty(n)||b.insertAfter(n,e),b.isEmpty(t.parentNode)&&b.remove(t.parentNode),b.remove(t)}function m(e){var t,n;if(t=e.nextSibling,t&&o(t)&&t.nodeName==e.nodeName){for(;n=t.firstChild;)e.appendChild(n);b.remove(t)}if(t=e.previousSibling,t&&o(t)&&t.nodeName==e.nodeName){for(;n=t.firstChild;)e.insertBefore(n,e.firstChild);b.remove(t)}}function g(e){tinymce.each(tinymce.grep(b.select("ol,ul",e)),function(e){var t,n=e.parentNode;"LI"==n.nodeName&&n.firstChild==e&&(t=n.previousSibling,t&&"LI"==t.nodeName&&(t.appendChild(e),b.isEmpty(n)&&b.remove(n))),o(n)&&(t=n.previousSibling,t&&"LI"==t.nodeName&&t.appendChild(e))})}function f(){var e,t=n(C.getRng(!0));return tinymce.each(c(),function(t){var n,i;return n=t.previousSibling,n&&"UL"==n.nodeName?(n.appendChild(t),void 0):n&&"LI"==n.nodeName&&o(n.lastChild)?(n.lastChild.appendChild(t),void 0):(n=t.nextSibling,n&&"UL"==n.nodeName?(n.insertBefore(t,n.firstChild),void 0):(n&&"LI"==n.nodeName&&o(t.lastChild)||(n=t.previousSibling,n&&"LI"==n.nodeName&&(i=b.create(t.parentNode.nodeName),n.appendChild(i),i.appendChild(t)),e=!0),void 0))}),i(t),e}function h(){var e,t=n(C.getRng(!0));return tinymce.each(c(),function(t){var n,i=t.parentNode,l=i.parentNode;if(a(t)&&r(t))if("LI"==l.nodeName)b.insertAfter(t,l);else{if(!o(l))return;b.remove(i,!0)}else if(a(t))if("LI"==l.nodeName)b.insertAfter(t,l),n=b.create("LI"),n.appendChild(i),b.insertAfter(n,t);else{if(!o(l))return;l.insertBefore(t,i)}else if(r(t))if("LI"==l.nodeName)b.insertAfter(t,l);else{if(!o(l))return;b.insertAfter(t,i)}else{if("LI"==l.nodeName)i=l,n=s(t,"LI");else{if(!o(l))return;n=s(t,"LI")}u(i,t,n),g(i.parentNode)}e=!0}),i(t),e}function p(t){function a(){function t(t){var n,i,o=e.getBody();for(n=r[t?"startContainer":"endContainer"],i=r[t?"startOffset":"endOffset"],1==n.nodeType&&(n=n.childNodes[Math.min(i,n.childNodes.length-1)]||n);n.parentNode!=o;){if(l(n))return n;if(/^(TD|TH)$/.test(n.parentNode.nodeName))return n;n=n.parentNode}return n}function n(e,t){var n,i=[];if(!l(e)){for(;e&&(n=e[t?"previousSibling":"nextSibling"],!b.isBlock(n)&&n);)e=n;for(;e;)i.push(e),e=e[t?"nextSibling":"previousSibling"]}return i}var i,o,a=t(!0),s=t();o=n(a,!0),a!=s&&(o=o.concat(n(s).reverse())),tinymce.each(o,function(e){if(!b.isBlock(e)||"BR"==e.nodeName){if(!i||"BR"==e.nodeName){if("BR"==e.nodeName&&(!e.nextSibling||b.isBlock(e.nextSibling)&&"BR"!=e.nextSibling.nodeName))return b.remove(e),!1;i=b.create("p"),c.push(i),e.parentNode.insertBefore(i,e)}return"BR"!=e.nodeName?i.appendChild(e):b.remove(e),e==s?!1:void 0}})}var r=C.getRng(!0),s=n(r),c=d();a(),tinymce.each(c,function(e){var n,i;i=e.previousSibling,i&&o(i)&&i.nodeName==t?(n=i,e=b.rename(e,"LI"),i.appendChild(e)):(n=b.create(t),e.parentNode.insertBefore(n,e),n.appendChild(e),e=b.rename(e,"LI")),m(n)}),i(s)}function y(){var e=n(C.getRng(!0));tinymce.each(c(),function(e){var t,n;for(t=e;t;t=t.parentNode)o(t)&&(n=t);u(n,e)}),i(e)}function v(e){var t=b.getParent(C.getStart(),"OL,UL");if(t)if(t.nodeName==e)y(e);else{var o=n(C.getRng(!0));m(b.rename(t,e)),i(o)}else p(e)}var b=e.dom,C=e.selection;t.backspaceDelete=function(e){function t(e,t){var n=e.startContainer,i=e.startOffset;if(3==n.nodeType&&(t?n.data.length>i:i>0))return n;for(var o=new tinymce.dom.TreeWalker(e.startContainer);n=o[t?"next":"prev"]();)if(3==n.nodeType&&n.data.length>0)return n}function a(e,t){var n,i,a=e.parentNode;for(o(t.lastChild)&&(i=t.lastChild),n=t.lastChild,n&&"BR"==n.nodeName&&e.hasChildNodes()&&b.remove(n);n=e.firstChild;)t.appendChild(n);i&&t.appendChild(i),b.remove(e),b.isEmpty(a)&&b.remove(a)}if(C.isCollapsed()){var r=b.getParent(C.getStart(),"LI");if(r){var l=C.getRng(!0),s=b.getParent(t(l,e),"LI");if(s&&s!=r){var c=n(l);return e?a(s,r):a(r,s),i(c),!0}if(!s&&!e&&y(r.parentNode.nodeName))return!0}}},e.addCommand("Indent",function(){return f()?void 0:!0}),e.addCommand("Outdent",function(){return h()?void 0:!0}),e.addCommand("InsertUnorderedList",function(){v("UL")}),e.addCommand("InsertOrderedList",function(){v("OL")})}),e.on("keydown",function(e){e.keyCode==tinymce.util.VK.BACKSPACE?t.backspaceDelete()&&e.preventDefault():e.keyCode==tinymce.util.VK.DELETE&&t.backspaceDelete(!0)&&e.preventDefault()})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/media/moxieplayer.swf b/lib/tinymce/jscripts/tinymce4/plugins/media/moxieplayer.swf new file mode 100644 index 0000000000000000000000000000000000000000..585d772d6d3c23626fddfa58c4220b056783e148 GIT binary patch literal 19980 zcmV)FK)=63S5pccivR$4+TFbgSX0N>I6O1=CN~KI0x05+ilP_+ai@wRfyT`lc5tI?Yn|XIMxcY?Oy z*i4q}Kw8#jSn_Obf`c7YGj%SaIeEEeMlw?urZ?-e^w~CRSmV&fKqyleX|UvGX>C#3 zoE)=Br={e=1~;-AExG}NwE6l*2D8>`Y#mmLNc-4KHnTn|I@6M&4~#SG2M0C{j4tiZ zutgM#oLS0fl-o45w0Ee^k`U0Iu}%y`t=^if?c`GHN;ff3=28;e}f%GP1; zEw-Zu_Ad%`P~GBMqZm?BQu3*SgAJAf@c4KXVn2Q@=bDc{ZCRyLR9pQ>M+>rgjAMHR?_Mj5f$Os~u>w`bz$#y z%KZF}f*Gqu^;+JRQn zP(AEfX4)w?Pw&`z3W}vMT`d$kpe-IdHOK)*Eb0Br+@@Ia#a^ zWdVi~Whs!&xKy&7LsOA)c5fW+=p%0p%sD!^%T$=N*#dI?uLyL*{}sV#vf1=j+rQwn z4ikC(&!#~|*=-(y`6jE$Z9~eLm%H$nKe2K#%FL`>jQ6Kj4pP~9k7gT(Z$9qM4gIXjN7;>V&f&hitYiU6E$4B`A;ndqkYV9#&qTj68!upZi{q81~~f zKR3?ZC;9KYC~Awm9FT5tcFmfVvvVKlp>lWcpRwF`@Sm~X+r@uEEN>_OlSxu09J|!G zbh=Id1HmmvrT*Ijl#5r+5|oQq{vwov`rluMQYG)2ev|U_&xgjK+}ZvMn)_t`1?|1L z{v&32Q>8}4H8YzjORqO;bFBKz+D>Ysl@SkP({R^WZVp+k+0+kuu{9_i}-AMF*aMY)D`)_wl;Apk1SJWrrD)ab>Lv?OO;U5 zmZd7FDd-?;j$RM_ORaerHGCf!LAOo+&kSMHrf#~fS*s7YZS@b9(8;dT95$wOa$&}K zRyR5OZ`ejBLAEq4{_n7p&N;oOa{gtG|66TlM9XIXp~<9jQf77j*O*PwqKLe=bU6V3 z*V>O#U%@fui2r)d|65%K8ap^`C7WZjQkz+xhg4oHRPK!b714dt|BCqDy#EEays2Bw zrc5`xB(9oR>2#2qJ2yF^d^c9?!w$UjkhgT5eQJ}+J?~C)&^X+EF4}Ccdhby->+|(y z7r~ZgMky0xwhC<7#BH+TEdIxiLgTWIf*5W#`ycrTEy}tGE>h(=AOAn`9B78#jI@;x z@Gu~iPmUY)Y{(hse^ZZXm5KSP_IZulX({lbUCh4G^+_xf9V zVUA*SFik!ao)U)|MG_Vn-qHD^x`(nQhvL;bXInT$$olyV&Vd!#^At;RX)l$ zhcq=D{~_tt?$`Hqi#kqdJ}r88`1<(GK1t16wAeUpn!m2{pB{d*lB!1Q6B83dPM<%2 zxJs2O#ZrcefxIz1s5+~Ou9Aqv-|M{_jf)%dHU9OAKedk5nCF& z^|$;!{cU$vZ>@4HFztu)i!aJTUO#`}{WLJSXU}DEGddsaC4ISff4wtt-Fo-#Eq@yL z^v=03&z~?#FPQVupzl()H6gPm`5!K z|2==r?3OX(2JU%z`sQDA23M>Wi6O=C*EihfiCGy0vJ9sl{RsagBxe)-Du?C!=>V@&V1 zwtCtk=*-EsM~@!uVc)o`wU9V3epR)oH-E?E{kkr8tpED7uij2wowg_S_*d^<-ZcNZ zC2QctTZ2I;IyIaYni68|6yd#P$YTQ_OFaBXJ(|?9hPG|Vnm+4<#I@~&oRcIa<6Y7V_s>%qlIZBCAP^lr?%e(g#s-Mf2N{pzy= z0p~o#8{1XSXXTo&|2F8#iI9+x^NqG%+MB)mr6Kqeb)%ST2aV>s=kktyeXv8(wrP_m z`>yZ$T8C(lzVkj3(c%?!7T?lqPtxuzJtDH;*PpH4FWy#=eV}kI!gw;r5x87am1v(DuA;LYssB zp?&K=f%7u7uBm8o{Q5`p*N=Qs;?=6&{^n5~#usPp3?1;9chrl(&#q7Hc^=Nr-Km%S zUvH}to<8iw>cVr$Yi7OiTvYV^+Sz;FKKu2;&%?Pn7Z*nzd-g29Fzo0uzgDMAt!r7* z#`Rn>(7g2V0n6(|SdL@etM3fGnZNPDy`L*q6BqB$XSX)?J9XpMq6txB`qq4#^<=L{ zScTRTYJT}*!K{pNGqhp5p7_3oV>q&T*2TLQT4Y`P{(0-kpQoA*j+>F1@?@v)se;_Y zhaTr`X?<(knBElx$?|gP~ zz@$5Ux0rh`czn3`x1Lp-?{5`$;o$gLr~AEJ)3ZjaJF&VyCRG2Z$LVwaL%;bObV~c9 z+tP~zv^OJ9&1*Yv(eo=`wSBPN{&>QZ*_FmGn{uj3m4i20om)2HlP)i2Z2ozR>5{t5 ztd7@q#(%SZ<;lDT*P>&$=lrpEL=D}=ZKn@E?N)uot?Ibu=YK~>=l=e@&nu|QD}3~% zEkC*1o`mhkXSZs&w$;w(mp{8&x&4=Oe9l!0nL42B$j_!%zWn6LU&XryuF*ujv|QRu z-x;9A(<{Ttda+=2pRK9yu8s}s)U?Z%jAMUP`>kqX+kHzuo<8zL(+gu7RJ!=AwopC0 zPTKlEqYq6wFGOC7i~7@N&e?(24pzVZRY}T%LG>Tz&7XXu4|j0a^G(;roPA1m?Hlzj zd+DIjsk??IfB*U1yI*eK-{w@$&|d3)SB}?Q&+4{4;-lt~A)9`S^{TgR&YSp>`$dsy z3!ZcK*ROy2>8BqTzihdEly3BvJ@V{58H4*J_1*vF{Ax)rT3@L1++=^5aA>l8!_7Zt zSA1}F;oJG`A2&W2zf}L#{#I=lPM+|%&g}=uzT1Odepd16D~!;~h0n*gxV&xAqD9wg z@2XUAdEn95;!HY`oQ#_%=Ukoh=bkr@JYIv29|>}QxTkWvy?LcpFMj#rBgK>5X9I5! z=-)qoP3o>!nlC-;6gIuEIIY^po9?~+J!;JM%R}r##||2B_<4a@qL8|~R)+U`Yi+Vnbo_H6#pQ*+y-T-Y;U z`Qn$cLte~HhH$Aqu{WGs* zbo`WhZ@;~q{POMdD`R(`I5s`Zqp<1LNe@O38(0$mU_$+yLe_vu+^)oP-uD*;?0Gx+ z$xEN>&&PaMb$w0q-vMLpEkEb2o40554<*9k=TB#!>^Cs<{O^rZ+Pru>)pTT0aLu0D zTgz__={5PqZ}%GP-{tje(_7!CyLl>yCG*xjT)n#eS2f!X?_#Wes$RDv%~Cs0c>ZS1 zz%|VWwDF&}`^~Kz(+2cEvf@JRbKAB(-PBUOa{ne-v$WzLOX6P`FFyY0;P#8vZa++$ ze(8G0X5+8+&p5Gj@sN<@_&o#q2K4FHCN!#o1Zpq8QSpkr*+QDivE5zpm=A}vL$Sgt!<#^@>Bgs zE**N}L6u4e4J-SNytZMnHgDg^+uwRtsuFr2D=A^mfY~cg^q6pBS=fWkQ=hJUyib`s z+PeP2?e#C8T)*?p*_6b4-I}ZWC?5W`;KGJk=7F`$(NDL%c=AJJ-sM^oe%=<|yic3Z z-K+W!=wI+n{}oRsH3}VfqQ|LjhxGByV)}PqQ0uvu&x%i)2DMu=Fec;dwX2D``_(^x z(Cls2I{WXd4%a)DyvPS{`}RW)K$JUgXr3xhr%GwohxrOJ)FMsWRl0zwf7%P zy}jwlj)Sr5UvBRA_^-xiW^_LJD!*sF%)S+7t!(R;zO~VGxlg47H*P|>!W;`Bn>PBM5X-m+G z_0dD`d&M#gS}{Sz&@z!v14ndW_)_F{lS6_lFc`NPt+y7 zys(HZ%(+JAHkiL$@^1YK^T3nMza9Gd7n{t>Pd#gJCh3OXfUzFBjb{>XZ&UX)nU+sH zvc|>7&L1Xs|7z+q>FckrCe%6IbLP)KRoI^JYTBp=nPZDIb?g3db>aEGZ>Q--dx=H^2rZPms{rT{w*j=>malERpyd|&y&qxG`(C{c^ zP|aFhqtd*jwN-~Mi5|SrVTAv`{~7k?VcNd7mX3QWj5LXFv<8lQYu~+ zNHrP#^*WnZSG_IKrnTjXINou2W^*FDM_^@HTwXSdL521fi&?MD=1kc(J`WOU*SxF@ z7(!$q(`2PXO52-kS=t<~SC`I;E|xs2zLX=8MUO-lpNrKZatEzV%WLy&7S9eM5s@(o zaMe%mU#5;uM{9z>SRszuPjAVRcc(9cv-_F#lIYxA?GSlVt~T3BKeCW?vjCrp&Ja86 zbK|oO7C*6i<*<>41DcZf%E!UEx&$XHKRv}Rg!96JNj@c>WSQMU^lWVf+ zmEyMu?b+pugC83I%ab69GwIEl9^D)_i|w_!QgPmrM58uGFYTg*ofs?=A5A(4S%X7$ zmR!Aee0O%QuFs7zn_z)_KKR^0Dvqs49AL^8vyvDX8MuWCSahkCRdR!~%v`qKCKuU) zoF{BEtX{UBZKl*}%hhYM7GIGix(hKDIvtx{RazCNHJSC9-oURrf~TV_ zwkk~7CYwoXHVxIQ=!Hl=tdNr(A8lqP6Q<54t4$C4WmQ;pTC<*U&(muYr4h1Dbfwj3 z8RRT@XX;@cEJK{-fYO5#S?1vInINJb9qFME7rm03P(-@bOGP19z0Z_)u0G3>ua7pH zS+zKlv%kAgNev*Y@!0}>X!2}+<#5DXVXHmpes|O6TJ^aRJiWY8P%KdvJ=jgYnD-Jl zBRNMbs>EUk%b;wrLMc{=!l^2KRpdY~y##fTrZ--(;`Nz~<~!>RHjkWAF;_a|rJFWe zZ?2d{HGn1`#M!M@mgcz3lBYREM3&~bk`q`PNE4lZ641|8u+?Q*!GRvOd$F<$S!T0z>J%TJm?#IrJ=g*X4pC9W z)6cY`tKz=^rUyZL$&5=2hne2RPjviD2~>qGwO4zxJLh=FQ03%*d$h}eEDp! zKhhj+E>g4oUO{^5 zw7@~MRpd}*$22*PS*rj!N>pKXnFCLw$(98BD$ZN!C^4f^Nn5^E z@XFF_t$Dfn%ueE5oW-7Wf;>Iro*)|0I$NIBoCx~LL!2cO7(eHlyVr@k90y7t$XJ;! z_bOXgA)aA&E>nqz3TfhU%AHHy%a!Zx%6%&C&Znxh_oRt4+j5nlrC=iL@;$c-)v?i; z`PyuqKC|ptm7H?tGOVKAs`i0(N-H%>UhRk2^voVJ?j4pT&t@`P<*p`w*NT)uu3SE0 zFmD{_LrF3t0=Y<*^L5vyq9Wrmz~G8+6{Hz#_oZnti9Ef8rJf+%xi&Z({rbTHRa(Jr zISZbdjw8Yd`Iq`Fk#2sA%BhN-Y*j5sO*`BC-P+vz0hv>2O2wCy-tQey_ik>wUZA?Z zSC(0pr5(&t*{cYeQ;2VlXjVpD8=CQUdtJ(K#1}3Mr=RFb>g6mm#H_b^i@qkD1hFgyDsYyS zfY1SSdN%z~Q|Zp7gsFP}59}+e_A9fvqM+6Ir?nTGWgucq>SSF(mr;T7an?jSYpS`F zVL2yF5Km4o$FsNN`KgEaWSgLHsij_}+1{nuPaVpPGlO^z0lje z;6xLTqnCT3NeA9!ZPGy@*2P0snq|t(wdBgE=LZtj%bDrzr30rc&!*25d#cJ7n{@DX zmqbxYq~iM}3H1PSd1^d)>SXycwF3v4Ze$EYspMMPvYxHCDH{$U=$iQKOcQ8Yg~{5% zqRV53FV}(TXp%e2)__t!&`FIc4XZLbF)=nNF|B)Sbcfy^TDpl=@M<%MD7tly?wuCX zIX>oNIh}&eY|;(z=oX!v7%SE)n6JdDy}EVRbnG6Rm?*Y*I^~=-diKzCPVNGoIz@Nw z80+wwbf9AT>Al3Jn_=EqyyczQ5cS(ZapPjaqV%z#(JLwlAaF)6xxl6d-=K9wYPj_(kwWEBwP z8sb4_v;8EJo9%Tj$uMSY^B>mL60w`i|G6#dhzm>8^m8bl1bW zSZx)`1l*CLnhPphS$@!5vn*0PT`U$)=|#k<|3aji`#nSCd&bJowazq_k7Iw|z$eA_ zN>XIH%2JRK*g4U8&lMaCAWs^Sqi6HQdI=*g1z)e9&8Vd3H#sSedInaCO(R!@Xe+5L z@YdRF;77UwSSi~LE0>pRmcprpBPL--n+It&N(^R;1r(KDKfo)IDkqmG<7F*V^kKX1 zm^d?K9`t;siRVw5>DC~n=Q6spM;8rMCY@uWd&DZld>2iRSP5)Z?hpm@qM3>CU|G>p zdqsEX5ZfUw2}CL>x?`*i{ID3K$($(z=E2U}tlR+o5Z(k*!RtWK{9Ka^rQT2|jk6U7 z*ENlzRAI;*UY1G1?p}DRpFJ|@3bNhFRIq#!Xlb*;k`4A>OZQ8vV=7tEH8zPdl$4z4 z5!*E>wtHG!_vkLM3Ks8+b6{C<4qTQgTOvB_PWGd1JY5|>G1e^;|9XgZ49({Qx#Mjh z1Tr{RX8LslpOa@b!d{sTJXH`1X89R4Nm6{5*zR5|O>>?X2~$3}5l>I9L{#dc+d>bi zCoBW?aAWdvtzi86bE3^f21oV8-88pHG~4kzK^I8p%PW&!^f8?gynrD9ksQQWsg2E9(&0%`6|czfkI6$pX#dsmsfyA);8S z;57M>ZkELp^dBf$X279D-9J~U0`)k6oEU34I=rXl#E{9uVZYLvriDw`A@X$jSTx#_ zW--&nX)~;@@H(>mpr(S$3ydtacd{&p&m#r3kgL-}^kf8oS+30kPZ`wg5E+OQQ`bDr z@Ht?5c%#J%f^W&S$#P-ys8mBeIOdrw*0SUd;USFG%M1`2F$80}I*8br2r<{GqZ*PyMdV+cixtlu}2 zHo&jg$w{J5YTG(}!%{-}hBW}h296p^gpNh2umT;qPW@0ug4Yk$>tuP^dN6c3deXNc z?uP>f@WISlogUYdzGG_!PZ|@BBCE&Nkb{8OiqAG-#GG)#`xbv_bVV_-bmW=)q z9X)T*-Pp0Ual%jb?XWLAGtF=BABQe)EInh;+2d(8QeU!VH|9tEkLETFLj`M2_q3P=p-5%6h1 ziUb7=$Fh-FHUKXtf;&6ybnk9B_`7?&E;JvHwFH z@EFUU;DE72f@G73Y&m@%hNKd%(zwbgQpHZH6p|`Mq)IWVBKLm_EznlCN)P(1@+ssc zRZ=R2`S0PNxE5C#j;kEx7|wpk!9Z2$Xz;j?tL)^V`XR3J82e%#6Rhx5;_${19!;7y zYu=(|E3c1K;kdP|O_W%~GViu++F@C^Pqd>(<%ipIG2y-)oE4b!48R=~vEh|E#V61* zmVb=HJ6G>gqiZWHQPjoZ8ZIWNTgz4+pVY(Q-DPbOlUlZthlS(h`aK%-Y=!IZ-~~(s z!V8>Kz=D9~0#OLWL%>P_dkWY~z}^B@3B0d>{RC1$koXIHC4sLj@Kpr9svxZ{;2MIo zrXURz_*#NcN8o}4Sv`Rd7UT^CE<}(u6nM2DZ6ruT1x2`k8w-4dpll-Grh>AWplmKE zTL{XQf@h?l{7CR@EhyUvUTpoS^I|C_4$tctM#UC_fgI zodsnVLD^Nn8bR4jP<|pPy9+o;kR=PMo&xSA;NAl6BjCP*UlYNvnSfITE=|Dcf?spN zuZ7^J75p*;Kb_#0DfsCHKZD@cPw+DeekQ@Mzu-4O@G}d3S%P1-;Aav1as;A;(*f5pka#hm;^`06Y%^9Kk~1QGjERKMv22g}@W=I0kppKLD-*Tm$$M;5xt!fSUlf z0R95F4R8nGE--cv3-x*m+ygAse}sjQrvT3Yo&&r9cnR(4EfQ`AblL_%#tC-vMR`z%Wk0!vVeq7zt1S@D0GX0HXj#1B?L}3os5~JSXtqaYFbc zuBt>nfs@E50wha?Hj_CyoL8X@-PtLC2#1?|56`Ip(*UM(LYp{wJy5+fIQe%(CZ9lL zaJHaj7Qk$PIRJA3<^jwHSOBmPU=hG#fF%G+IU!~pz zaq?(6Fbli3gA-zR0_+0V&B=$siI4jkDE$Jk4`4r6RRQOajtSUD;du-IdSFmf_#`J^ z1A1aN_K@#^=ROSP;u4H~nX3v`;|k=i0bJ+g*EuNv1-)(q+yS@?^SuXfAK(GN-%$4u z;1MTpD3$wr$_uev9wM*mCGd}-`UxkWhrQ(KV1=G?Ue7o$`E!8rP&ESJ1>~O+FCpd? z%q?Ar0o4=(YANP56yI?2x6u3!U>NTu|Ba#zE_vf#OVn{`5JCmrth8$-I0DeNN%! zdtppGotICe5_o;Xd3n+2T;Sn57%yf4@VJl{ z!j}QOfJI#e&(*yA2=S6%qjT5*?OOqkWBDBDw+;Huh39%Y=5}8G6O`8h>;RYt_45JJ zvNWDQwz2&)5`2(=|Rdxa0Jpe!RRaHXxe&Fm7FZ4JJa0K8e00>f#W4!zk_K|M@ zaftz;h?xv~bR2L`0G#CIL2`LGw}Uvp%E6e>1R)t#Drtc@3+xje2Vl&7kd$rbkpjyw z1}6#%Qkn>^X5vJl1>OO!9|A=fP@!;ENH8yxE96MVDHIsM9a-erIj9E=O1KZo?mtRe zuXM|}mE>YS3F1AyluCEP-ZW9Ua^7WTOG<0YG-2L@CQ6FnQI;k8lsQ=~=Z8Z+yc{Vw zr80mn1n<_wmo8n|A7A<}hqxnD5GygJEpq1sKUjeBGf4R#;<^a4orVNeq!~z%Kh5~N zvs8&@D!Jj{fBfnB{u(!A1vXW3D3XR<{`?I{o!yLg73@NB;KompH!{n;cTs4|hr%4T()TBuuBwQ_CLi3OiERnEfLUPz5qEL8v z5TzGTAeahI>EKEQC={VE6pm116oF6^rLrjyRw$Z5>fzCxr7b}Cc&;Voz7^=eNQ}6TKvr7A zUbX=ljKWCO7Nd&oF!GPas8V~30%9<#+ySF19FcpY>NuA25?4>ILbbV$l-EwRP+&Yp zwW`I*eNaP^fKl+r7=<*c2Fjp$NN37u7n*cMNQ1gjQTl}O-JS8Bh){KuM3ZEi^q@&k zgaT17n(IxIPZ6qt`p~2=LN!qeLe)?zU9vRFN;=F1b6S>WuvCXorc$XVC{)j(Fats1 z1`aju$DxRR1T`^osHq8~X8kd0I{>40W{je=MW?zLqD5@n}1GFpDzgN`z1js zUven*D}vI7ff7jv&kt#bLoQ=D7>$7#m7uYZa%dc$1^MxKHl*L-InX)*&xLd%o`-GnO5A+B051fZ z^%h|&6^kKVg3(eqc~c?Ese`8BWssi^X&v+f{t@ysAgzOD;^mN^1!)~L8)985!YiR> z4#d25&|HXkYomFP))Kw1Ya#A_hG2+}$*)LO_dfwT^cw+`~lAgzOb#Oooy z9MU>y1>OMpm5|m!s~`#oas3J7O)!_$kaB1ZMB)Ukg;<=Rbr6kXv>sw`j5grykZ#0) zj5gsNkZ#61A>D#^!Mx>_(RPe><2_hj72N!t82t>vm+?7Bui*2L{*Es|`Uk!U=~etIq}T8zNdLsYL3$luhV%x$0_jcsJEXVp zACUfquR?koUxV}x{u9!>_&TKbaOMpxuZRA|+)eCIFAp*3mq+*(UCChdly;WL8=yCs zN{$3ABlT~?qLkpw5;U8BNWMhkqbGlKmk3Ae{URinW2@ znUujz1ka)jZXtL!WpEq8XD~XC(XSXiz~~7^FR;W(cMgmQzR6r5{1VRt!msdrAp9D? z!)Q62Yl5m&#dX1ls)0EkTmc*h?v5H);}O>xH{lVl!B!qg60wa((%v|qN5W)`hww-S z3Sl02lX6f4yJ#@A3&SLM_{X}pOj{@La zV=R+%_HeMy;DN{$FR?v5aM(g}CUDpya@L-{3mb#&=|5v*1A9D5Urf@M5W`ZUT}B`u zto@Nb(w7s%3Zh*}(pM3~YGPPJ?1qpy7$`r)7hL=XZq*H0weJ{&QWlbgg>V94q(Z|w zl1>ckp}m!+6Jf;-#IO;{k+ht$sg$x|Gf9B$(?sKxMI>Pn5CATV(zg)9R-)ZTiX3!4 zf__C#BCTnm43X_lA}Sd|c1X&w0P6GR;881P)yR>gS60sx8XENkAVW9s04{Z`90^{=D>n1 z0_iYG7AHP<@gZSNQYHs_>=HK-A^jI;%^4CmjbO1i)PlHh>W6eS+T+ zN)sxnAVDBGFk{16I&Z@{lF&qAjIbLb(mBIe(oTRS5DVi-JDIC6p0ty@3g3}-3RhtQ zY3Jc8OeF1;uEHeJ&eK(xOxk%l3dC@pwDT4Vc0)_8o;_Q@mf8)?d?5savc`g_q|sb9 zO1VH$H5aJRNH4;{;br(&(9=A+1eQU94ni0#LBGLqlAy~3NkLEY5MBDFN2InaG+ZGe zXN@h3WJIfnz4fIcRIAYNJ2Cu0)UQYdknq&z^^DEaLqV!QF4H44CVD3PC}N{R!&Tzz z1BW0={f59%N{P|LAe9%ZphqkH8qtgZk#8DoYzmz!P~i$rX{Tw2(wqBKg`*OY9%}fL zXbmiLoj`JfEDFk8sO<;n6*;0%Mp8LDLr-QIFS3wk2e;(A-MNs1P&%miR+y<+@Cd5a=^h48prXJwH(=5OLU{dPkPEmBF#MJW$i<{_xaKw|_DsY<|d*0qQ0 zQMx2N{Ui=g_YF^fM8eZ6gs0bo-(ILX`!Uu94IL)Ja6Wlo%(G)X7Bs zBQZ{|OmqZ8WIYR6RSi%}DSyL?bSyMHA%>@}+%rO# zY%eY>s(7iS#NGoLI|7y31Qy%_#-U~KBcQ4dUA}tu@RaA|AJ&gJ)-MjQgD?;fd9KT0 z4-ZxP3j)7}mn00&*S@5j)+10~2`YmyRHVNmn%8g)Uy(rVE7}|^;XFL8P7Pjbgs8!9 zV5)>cU8lbx>}=?OnSpZ|0+ZnLOgb`}l(>sd6!Sm7asePvs!hAowcz?P2S%H7g9`0d42cWi4l=+TJw z7q>MOV-F=IWk~OYP#8}KT4b~^0>Rx!Nf8gxU5SIhn|238Ba94jV z^lvQXJe0$!7CZ|iw06U%)Q^FOy%4%U4N&Dp-dVe$tNJun&%j0MnV43t#BhwxVY*cjQkY2$n@Prdq(dl$uIe+i zCv}OaBLv=#W3&%RHE~Tb1E$y%1L0b&tE5{uD?zQ99B;!v!~y}#?JQiW7yaQb{S^T z&7PtuDo)T4V^`qbUYNmWNHk|LZ`brkDfJTSp<(qxbh3KdZ@COvuyz!rhS6LQ3ek+= zh%?XnjOBP%){Ns&hKw;}Hw>T_?LHu;kLRXPoe$i#pqJ~?)YN*$R4BD{l!95Qm6Rxz z^-{j$QaI+6FxPSdmrj?ET2;EH2^`UU$I*F4@_=2@iTxe*LQ5Mz;-E1)y_;HAAsB2z zaOtAy(pmm0>1TUxan0#aXT*?YUg+nQS*C`+8E|k{R)KA2|_LhzLFGh8`k94-uiY6XA_G zyIyufFA<@ah|tD~uu`PZ+ivJBBJ>s!qMQh;M1)VNdXh8sq+ZQY6+|1?h>d-yrjm=A zYAwff9hm~EScbmm5RsvFgovlxkZ1rKMllODW~`F13_IP?9H0aM3iX^FA~V)aWZJvh zEw1))ZtXE(law{-5J|pFvm{X|rrXX+iB!G;t-}Xs!DZ0uiDUg3TUXsf~!8XrYtMw8mRAhgz3#iAzG#6{x~DjxXT$c<2M z;^x!fYCc0YgOT>COfj9fBpSbmBI$&r(_p)lXgX|{68*p-PKjo4^flc~4#Isji$hWw z>PQVV&BhO!-*zG1c(#bhQS#UqTqVfp}KvP6_D( zD_3Ms>PgTCXz@U!PUQ`ibUnHzIAa!jN@iWVcMwj;&nk8$dfbksWnFTa=9xg3R>y}sWUh!xPH`5;mVoX$m6CWabuO3w7q-XECD=HZ zqg!VW&*15mk50nwe5%VN9dX?zE#`512sa-V%}1$R08+sR;DsO-a)qKh!Ga8!Vsz#a z3@0HG_>@)$J{P%9(-VGsN!hGyz-5wiR=u6GS_rcejQLRYDSf3(+a_aY;{s@u8HYgK z6ii2aZ_eLCtRj==P;X!{r{f_OD30gSzbAne8q!#aGc4ht0Tx8Pmy27SwT;WgL#HkG0O(ZMj%h@Qx|V}E_z8=#>r~)ICa+F6 zd@&BJKy?|v6z8!^I;b(+#(A(J(=Z`2xtd}v#f25vg_jGzP_h)OJVpFM?QLw=?8H=B zrk6u{nH%XljPwtsq?eULdYK#PJ1){Q$|3!u8|k}@^vqJyKbAxKM>o=UU8HAW2`7^$ z(VYl5Bcjt&!Y{|2(x(zJcAZK>&Z>{lH7#Pp-Gd{x0;jLw3@f>4PDY?-AvFty2D+4v z?v$h1m;;VJrW`FVhoj|KrFL>eX)XrXf`gEs2lI%x;6-^V4k9y@r+wmLc+NjCyz+m< z@G>XED;dLc8N;0@!z;^ScqLXfpc&%|2e+F`x!vr>?Nb-G^UB$|Rc<@?kPSP(bmvx; zGwdq2oqOmay`UV@tKCRHVx$+Al3ra7>D6weAGt^`Du?tMH`0$8>BXg_*OWtgjT`C5 zF49ZNA-(nk(o0K8uPul4+Hy%RD~I$tH_}fS=^xn^x1(6=$|1cDt7wS$v74avUO~c&Pt~s1bx?))3)5vwjS(+Eut@K@3bjkIy-2%^8nun3wZ`R8Yg|cdH-Vv( z$z{}~71w1m<^io3i#F{{;IJhaqV`3w`d!^j+L=Q2anYht2PLIGD~jgKxCm1PRsm*L zs6HVg`GMJ+N+{Y1m(`m}7+F695J*^r5gn+A3Ny%S5tT9!q#`N-u*pSKp@7aPqNg7Y zco98MaAb<8VFTM$M6D1Qnj&g4z$z3`MNMU#>OU%fMX*vZxh+ioS~%p-uc1TiUShVk z{0fd0OR#n=M=z>fHSe%?CA~V?N*x2CHaG_B-t#eR@Y_o+dQbD{P}^|n<>7WrFXddf zKR;0_vid+}{fAWMVG6wz4o_?srL_aoOVRgykDc^;QmKpRE=rUKc~9BEi0;7@dU*hi z-IT^|hA#562l7(E)%9oERZ?LsgFpv@TDNb$Y z)PeHP145vQJsn2oh^PKtur@lzv*r+H! zna`xv|6HJx+S!z?5F%~mFdguBPW=bho~W;Kaoadj0HXUR7q^`beXiK>3-JMCmyF0CIPt& zNrtrIrjn8(;B-GIP>yd1`pAdC$>_u)ILh8lSPwO(tkKdfR|)zYfHmhOu6;U4_lZ+E zuc{@zJgXajp?h-(mtOiF#ynPdG=)9^%ndX0>|3@5~H*o&RFJUcjSJODKZa8RZf z4Hbei9c38s2?r1dr@Cw&_LR7UIAq+59hrUD&faR-4Tl`Q?J;1&!=qa2LF~MuD$D&r zO7b`sI1kU!t{08KDUCJggA*UT_;7~5&ed3s>3b8P!|)mRE7^SDvDz2p&xyFw*|@;j zL3E33?jw}#zt+{?z4pWY5_?L;AR0DH9INNxj7CTc7SQ^Hio9_@qfV~}>65l;#jT`4 z6npElSG?wFcTBwZ+2=ss$KH7|WR{gM2l@qqcMr4|f_D#eg2_N6H8e*s zDl?qxMUrDY_9hAFgRoHQ@DStJlT126v`b$*9i`kkWo`yk9K;T>qg{jThW%KxkE2p` ziggaBsvl_X=TI3UFr<^pYWF6-I;Z2s0W07hC`map;i5y%4=S3n_i5wIfPf?3*r!;>9 zH%}sEcWI|_A^m1Xyg-D4;RrWE1-dqH1ZcL)nD>y%#}alwArW5%(T@;@dAYtqa9&o> zj|k}5HiORK497U_adv;f8H+G|@SL&%V8k8ssx3Yk1YCioPWl*nW8B&~s`xa!--I@HgMFR84dSlAG;5!9_Nd5u-l+>e*(}D%lg=9-=cT54|h%EBK_fQP8x{OV*6IRu%Lodn5 zH8#gTVUBWi6-y=J+`tnG999+lq5vIlSC8a_B9gJakS?3JWM@+Xz+4p>u5(3(8ywiF z`ShJ9tGWqQw_H^T0ff>>shYtT8UErDsuCb;FD{}hTul3ewJD~Zz|<7O+^%6xCXtQ@ zkr5ZxOD9RGmQW21t9Di#f0zWEuiGrTvKJLoGF0XZodQq4t#^n!9M|_{y%KcFkT5w1 zw=B3a5Gl&wsg|MgyS$Q?Qf7+m>Th^(NkJ~O zcQ`1Ga+dDW(imsy9xaV?mhN-!k5X)Szy()(GZw?Lnn>(kTz^fPg^AsweY79_lH4uzD{^f5;ggaq4M&aIzGHlDB8@?%M{A zDmbT)IqegUW}b4|XDsua)4pJtmz?$$%e)4jNKvu&4OaxEx19DJSCn4D8HVxN;e1j0 z2;T5DuN}$LMsXUD5myT`H#qHbwrn>*QYF%EPJya<&be%7Q)(vEM6^N_1uE-m5O>h| zAm^-f21+MrsXQ^c$@U||NjT7ra9~0pq7@Fp#o!Rw3k?Ol>)<=8_tENa%2t;*)Gf@x zHhcuTP%EJp8deJywV0X+SI1!zkTiM>v^T(gr^2tj#o5{WS0D*z7SZpcWm5Us(y!a7 z(h-daCq8(`5vDCWCb& zYk1!MP_Z)PVLbZT+bQw0H<1kfe@lj9s^{@ctHq7wk$NVM`x6tbsH4^M-CAapX_u!%g>GZ1LL$8_rPktHU;!w!0-b~gn^G2RQa7Lw?7zyN6U}~&f^&t%Kp!ww!!eC$ z)#FHoTA&nYL?bc`nzc~WxeM4=T-Q0uTTzNKgO5|P;$ed1MGkC7^#WSIjxdUg_)?1V zToiAWQoLD~A{6sQiu1})g!)ukU(9TisyoX&J3&RXSm6OfF6Pxscp96=d9bE>j1yQ3 z8o4gz+hb75-|^VDG9A_o~ zPejj-qv)*yRRsd?D5_Mgpg7-&>_g8nh=8N$tEvjcy~I)Uqt}V_>(QVJ)O8N3Ad^?! z{jQ`!`?n>Zzb*OxZOO^EB{$gbBj+#ouB67hl61FUo7?ZOcO}rDy1CchFgLeIJ&7Gn z`XP2v5CVZNQco^Z1D*#=;11@&gUF^wPA8$hK@s%}G!DO@22^J74&6s>)e$aTw$Yc~ z&VXty_Jv6mf-p`7VN|lLh(m?qy)yL}R)`)$Aq;z$`MNVWr>|T3D!tU(1!d(>dg^p~ z2JPw%yhBql)veyhi|@fV@gt~r*hzfp&J+zezOO?Npzr{cH&?B=l2Z7 zf8{^_!m$rV*Y=JtUTTMmP^&dGSET-hpMSO}Wex$C(*WtuVA3Su?#&_e;LZm<^a?yphn%V2qf#^q`HtEof~@5OX}?EEEutJ+s8Oy5qwi zUcHxMOVs=LxRpGfuRg%fpI_k68zhivGm2I~-@P#WgFO90h|Di2aD0M9ITzQ!%mr5P zD=AT_-V2Xik#XJmWHDLA?;(=aJi@+c4Nn!uT2L6iXdNgF9<2w3;g4R^*BX3Vb`wyT z&TnMjTBY;f7M!KuTK$I`4m}CC1c3JO3-^cLcZGFY+#=ofWy~ECLP<|xzI};^+ z@xll8@;5G_mCH%#r@ku)$BAEx#UsZz&Gtg$Fk(-+frBCvZeVO2PQ`R3pf8m9BIc!{6w4|{QLwP5nv3WpNINQWdDu_My3A-dg%NAz&|4B-~J;6 b==_iWodI83J<=N literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/media/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/media/plugin.js new file mode 100644 index 00000000..ee79aaa5 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/media/plugin.js @@ -0,0 +1,550 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint maxlen:255 */ +/*global tinymce:true */ + +tinymce.PluginManager.add('media', function(editor, url) { + var urlPatterns = [ + {regex: /youtu\.be\/([a-z1-9.-_]+)/, type: 'iframe', w: 425, h: 350, url: 'http://www.youtube.com/embed/$1'}, + {regex: /youtube\.com(.+)v=([^&]+)/, type: 'iframe', w: 425, h: 350, url: 'http://www.youtube.com/embed/$2'}, + {regex: /vimeo\.com\/([0-9]+)/, type: 'iframe', w: 425, h: 350, url: 'http://player.vimeo.com/video/$1?title=0&byline=0&portrait=0&color=8dc7dc'}, + {regex: /maps\.google\.([a-z]{2,3})\/maps\/(.+)msid=(.+)/, type: 'iframe', w: 425, h: 350, url: 'http://maps.google.com/maps/ms?msid=$2&output=embed"'} + ]; + + function guessMime(url) { + if (url.indexOf('.mp3') != -1) { + return 'audio/mpeg'; + } + + if (url.indexOf('.wav') != -1) { + return 'audio/wav'; + } + + if (url.indexOf('.mp4') != -1) { + return 'video/mp4'; + } + + if (url.indexOf('.webm') != -1) { + return 'video/webm'; + } + + if (url.indexOf('.ogg') != -1) { + return 'video/ogg'; + } + + return ''; + } + + function showDialog() { + var win, width, height, data; + + function recalcSize(e) { + var widthCtrl, heightCtrl, newWidth, newHeight; + + widthCtrl = win.find('#width')[0]; + heightCtrl = win.find('#height')[0]; + + newWidth = widthCtrl.value(); + newHeight = heightCtrl.value(); + + if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) { + if (e.control == widthCtrl) { + newHeight = Math.round((newWidth / width) * newHeight); + heightCtrl.value(newHeight); + } else { + newWidth = Math.round((newHeight / height) * newWidth); + widthCtrl.value(newWidth); + } + } + + width = newWidth; + height = newHeight; + } + + data = getData(editor.selection.getNode()); + width = data.width; + height = data.height; + + win = editor.windowManager.open({ + title: 'Insert media', + data: data, + bodyType: 'tabpanel', + body: [ + { + title: 'General', + type: "form", + onShowTab: function() { + this.fromJSON(htmlToData(this.next().find('#embed').value())); + }, + items: [ + {name: 'source1', type: 'filepicker', filetype: 'image', size: 40, autofocus: true, label: 'Source'}, + {name: 'source2', type: 'filepicker', filetype: 'image', size: 40, label: 'Alternative source'}, + {name: 'poster', type: 'filepicker', filetype: 'image', size: 40, label: 'Poster'}, + { + type: 'container', + label: 'Dimensions', + layout: 'flex', + direction: 'row', + align: 'center', + spacing: 5, + items: [ + {name: 'width', type: 'textbox', maxLength: 3, size: 3, onchange: recalcSize}, + {type: 'label', text: 'x'}, + {name: 'height', type: 'textbox', maxLength: 3, size: 3, onchange: recalcSize}, + {name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions'} + ] + } + ] + }, + + { + title: 'Embed', + type: "panel", + layout: 'flex', + direction: 'column', + align: 'stretch', + padding: 10, + spacing: 10, + onShowTab: function() { + this.find('#embed').value(dataToHtml(this.parent().toJSON())); + }, + items: [ + { + type: 'label', + text: 'Paste your embed code below:' + }, + { + type: 'textbox', + flex: 1, + name: 'embed', + value: getSource(), + multiline: true, + label: 'Source' + } + ] + } + ], + onSubmit: function() { + editor.insertContent(dataToHtml(this.toJSON())); + } + }); + } + + function getSource() { + var elm = editor.selection.getNode(); + + if (elm.getAttribute('data-mce-object')) { + return editor.selection.getContent(); + } + } + + function dataToHtml(data) { + var html = ''; + + if (!data.source1) { + tinymce.extend(data, htmlToData(data.embed)); + if (!data.source1) { + return ''; + } + } + + data.source1 = editor.convertURL(data.source1, "source"); + data.source2 = editor.convertURL(data.source2, "source"); + data.source1mime = guessMime(data.source1); + data.source2mime = guessMime(data.source2); + data.poster = editor.convertURL(data.poster, "poster"); + data.flashPlayerUrl = editor.convertURL(url + '/moxieplayer.swf', "movie"); + + if (data.embed) { + html = updateHtml(data.embed, data, true); + } else { + tinymce.each(urlPatterns, function(pattern) { + var match, i, url; + + if ((match = pattern.regex.exec(data.source1))) { + url = pattern.url; + + for (i = 0; match[i]; i++) { + /*jshint loopfunc:true*/ + url = url.replace('$' + i, function() { + return match[i]; + }); + } + + data.source1 = url; + data.type = pattern.type; + data.width = pattern.w; + data.height = pattern.h; + } + }); + + data.width = data.width || 300; + data.height = data.height || 150; + + tinymce.each(data, function(value, key) { + data[key] = editor.dom.encode(value); + }); + + if (data.type == "iframe") { + html += ''; + } else if (data.source1mime.indexOf('audio') != -1) { + if (editor.settings.audio_template_callback) { + html = editor.settings.audio_template_callback(data); + } else { + html += ( + '' + ); + } + } else { + if (editor.settings.video_template_callback) { + html = editor.settings.video_template_callback(data); + } else { + html = ( + '' + ); + } + } + } + + return html; + } + + function htmlToData(html) { + var data = {}; + + new tinymce.html.SaxParser({ + validate: false, + special: 'script,noscript', + start: function(name, attrs) { + if (!data.source1 && name == "param") { + data.source1 = attrs.map.movie; + } + + if (name == "iframe" || name == "object" || name == "embed" || name == "video" || name == "audio") { + data = tinymce.extend(attrs.map, data); + } + + if (name == "source") { + if (!data.source1) { + data.source1 = attrs.map.src; + } else if (!data.source2) { + data.source2 = attrs.map.src; + } + } + } + }).parse(html); + + data.source1 = data.source1 || data.src || data.data; + data.source2 = data.source2 || ''; + data.poster = data.poster || ''; + + return data; + } + + function getData(element) { + if (element.getAttribute('data-mce-object')) { + return htmlToData(editor.serializer.serialize(element, {selection: true})); + } + + return {}; + } + + function updateHtml(html, data, updateAll) { + var writer = new tinymce.html.Writer(); + var sourceCount = 0; + + function setAttributes(attrs, updatedAttrs) { + var name, i, value, attr; + + for (name in updatedAttrs) { + value = "" + updatedAttrs[name]; + + if (attrs.map[name]) { + i = attrs.length; + while (i--) { + attr = attrs[i]; + + if (attr.name == name) { + if (value) { + attrs.map[name] = value; + attr.value = value; + } else { + delete attrs.map[name]; + attrs.splice(i, 1); + } + } + } + } else if (value) { + attrs.push({ + name: name, + value: value + }); + + attrs.map[name] = value; + } + } + } + + new tinymce.html.SaxParser({ + validate: false, + special: 'script,noscript', + + comment: function(text) { + writer.comment(text); + }, + + cdata: function(text) { + writer.cdata(text); + }, + + text: function(text, raw) { + writer.text(text, raw); + }, + + start: function(name, attrs, empty) { + switch (name) { + case "video": + case "object": + case "img": + case "iframe": + setAttributes(attrs, { + width: data.width, + height: data.height + }); + break; + } + + if (updateAll) { + switch (name) { + case "video": + setAttributes(attrs, { + poster: data.poster, + src: "" + }); + + if (data.source2) { + setAttributes(attrs, { + src: "" + }); + } + break; + + case "iframe": + setAttributes(attrs, { + src: data.source1 + }); + break; + + case "source": + sourceCount++; + + if (sourceCount <= 2) { + setAttributes(attrs, { + src: data["source" + sourceCount], + type: data["source" + sourceCount + "mime"] + }); + + if (!data["source" + sourceCount]) { + return; + } + } + break; + } + } + + writer.start(name, attrs, empty); + }, + + end: function(name) { + if (name == "video" && updateAll) { + for (var index = 1; index <= 2; index++) { + if (data["source" + index]) { + var attrs = []; + attrs.map = {}; + + if (sourceCount < index) { + setAttributes(attrs, { + src: data["source" + index], + type: data["source" + index + "mime"] + }); + + writer.start("source", attrs, true); + } + } + } + } + + writer.end(name); + } + }, new tinymce.html.Schema({})).parse(html); + + return writer.getContent(); + } + + editor.on('ResolveName', function(e) { + var name; + + if ((name = e.target.getAttribute("data-mce-object"))) { + e.name = name; + } + }); + + editor.on('preInit', function() { + // Make sure that any messy HTML is retained inside these + var specialElements = editor.schema.getSpecialElements(); + tinymce.each('video audio iframe object'.split(' '), function(name) { + specialElements[name] = new RegExp('<\/' + name + '[^>]*>','gi'); + }); + + // Allow elements + editor.schema.addValidElements('object[id|style|width|height|classid|codebase|*],embed[id|style|width|height|type|src|*],video[*],audio[*]'); + + // Set allowFullscreen attribs as boolean + var boolAttrs = editor.schema.getBoolAttrs(); + tinymce.each('webkitallowfullscreen mozallowfullscreen allowfullscreen'.split(' '), function(name) { + boolAttrs[name] = {}; + }); + + // Converts iframe, video etc into placeholder images + editor.parser.addNodeFilter('iframe,video,audio,object,embed', function(nodes, name) { + var i = nodes.length, ai, node, placeHolder, attrName, attrValue, attribs, innerHtml; + + while (i--) { + node = nodes[i]; + placeHolder = new tinymce.html.Node('img', 1); + placeHolder.shortEnded = true; + + // Prefix all attributes except width, height and style since we + // will add these to the placeholder + attribs = node.attributes; + ai = attribs.length; + while (ai--) { + attrName = attribs[ai].name; + attrValue = attribs[ai].value; + + if (attrName !== "width" && attrName !== "height" && attrName !== "style") { + if (attrName == "data" || attrName == "src") { + attrValue = editor.convertURL(attrValue, attrName); + } + + placeHolder.attr('data-mce-p-' + attrName, attrValue); + } + } + + // Place the inner HTML contents inside an escaped attribute + // This enables us to copy/paste the fake object + innerHtml = node.firstChild && node.firstChild.value; + if (innerHtml) { + placeHolder.attr("data-mce-html", escape(innerHtml)); + placeHolder.firstChild = null; + } + + placeHolder.attr({ + width: node.attr('width') || "300", + height: node.attr('height') || (name == "audio" ? "30" : "150"), + style: node.attr('style'), + src: tinymce.Env.transparentSrc, + "data-mce-object": name, + "class": "mce-object mce-object-" + name + }); + + node.replace(placeHolder); + } + }); + + // Replaces placeholder images with real elements for video, object, iframe etc + editor.serializer.addAttributeFilter('data-mce-object', function(nodes, name) { + var i = nodes.length, node, realElm, ai, attribs, innerHtml, innerNode; + + while (i--) { + node = nodes[i]; + realElm = new tinymce.html.Node(node.attr(name), 1); + + // Add width/height to everything but audio + if (node.attr(name) != "audio") { + realElm.attr({ + width: node.attr('width'), + height: node.attr('height') + }); + } + + realElm.attr({ + style: node.attr('style') + }); + + // Unprefix all placeholder attributes + attribs = node.attributes; + ai = attribs.length; + while (ai--) { + var attrName = attribs[ai].name; + + if (attrName.indexOf('data-mce-p-') === 0) { + realElm.attr(attrName.substr(11), attribs[ai].value); + } + } + + // Inject innerhtml + innerHtml = node.attr('data-mce-html'); + if (innerHtml) { + innerNode = new tinymce.html.Node('#text', 3); + innerNode.raw = true; + innerNode.value = unescape(innerHtml); + realElm.append(innerNode); + } + + node.replace(realElm); + } + }); + + }); + + editor.on('ObjectSelected', function(e) { + if (e.target.getAttribute('data-mce-object') == "audio") { + e.preventDefault(); + } + }); + + editor.on('objectResized', function(e) { + var target = e.target, html; + + if (target.getAttribute('data-mce-object')) { + html = target.getAttribute('data-mce-html'); + if (html) { + html = unescape(html); + target.setAttribute('data-mce-html', escape( + updateHtml(html, { + width: e.width, + height: e.height + }) + )); + } + } + }); + + editor.addButton('media', { + tooltip: 'Insert/edit video', + onclick: showDialog, + stateSelector: 'img[data-mce-object=video]' + }); + + editor.addMenuItem('media', { + icon: 'media', + text: 'Insert video', + onclick: showDialog, + context: 'insert', + prependToContext: true + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/media/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/media/plugin.min.js new file mode 100644 index 00000000..02b3407f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/media/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("media",function(e,t){function n(e){return-1!=e.indexOf(".mp3")?"audio/mpeg":-1!=e.indexOf(".wav")?"audio/wav":-1!=e.indexOf(".mp4")?"video/mp4":-1!=e.indexOf(".webm")?"video/webm":-1!=e.indexOf(".ogg")?"video/ogg":""}function i(){function t(e){var t,o,a,r;t=n.find("#width")[0],o=n.find("#height")[0],a=t.value(),r=o.value(),n.find("#constrain")[0].checked()&&i&&c&&a&&r&&(e.control==t?(r=Math.round(a/i*r),o.value(r)):(a=Math.round(r/c*a),t.value(a))),i=a,c=r}var n,i,c,s;s=l(e.selection.getNode()),i=s.width,c=s.height,n=e.windowManager.open({title:"Insert media",data:s,bodyType:"tabpanel",body:[{title:"General",type:"form",onShowTab:function(){this.fromJSON(r(this.next().find("#embed").value()))},items:[{name:"source1",type:"filepicker",filetype:"image",size:40,autofocus:!0,label:"Source"},{name:"source2",type:"filepicker",filetype:"image",size:40,label:"Alternative source"},{name:"poster",type:"filepicker",filetype:"image",size:40,label:"Poster"},{type:"container",label:"Dimensions",layout:"flex",direction:"row",align:"center",spacing:5,items:[{name:"width",type:"textbox",maxLength:3,size:3,onchange:t},{type:"label",text:"x"},{name:"height",type:"textbox",maxLength:3,size:3,onchange:t},{name:"constrain",type:"checkbox",checked:!0,text:"Constrain proportions"}]}]},{title:"Embed",type:"panel",layout:"flex",direction:"column",align:"stretch",padding:10,spacing:10,onShowTab:function(){this.find("#embed").value(a(this.parent().toJSON()))},items:[{type:"label",text:"Paste your embed code below:"},{type:"textbox",flex:1,name:"embed",value:o(),multiline:!0,label:"Source"}]}],onSubmit:function(){e.insertContent(a(this.toJSON()))}})}function o(){var t=e.selection.getNode();return t.getAttribute("data-mce-object")?e.selection.getContent():void 0}function a(i){var o="";return i.source1||(tinymce.extend(i,r(i.embed)),i.source1)?(i.source1=e.convertURL(i.source1,"source"),i.source2=e.convertURL(i.source2,"source"),i.source1mime=n(i.source1),i.source2mime=n(i.source2),i.poster=e.convertURL(i.poster,"poster"),i.flashPlayerUrl=e.convertURL(t+"/moxieplayer.swf","movie"),i.embed?o=c(i.embed,i,!0):(tinymce.each(s,function(e){var t,n,o;if(t=e.regex.exec(i.source1)){for(o=e.url,n=0;t[n];n++)o=o.replace("$"+n,function(){return t[n]});i.source1=o,i.type=e.type,i.width=e.w,i.height=e.h}}),i.width=i.width||300,i.height=i.height||150,tinymce.each(i,function(t,n){i[n]=e.dom.encode(t)}),"iframe"==i.type?o+='':-1!=i.source1mime.indexOf("audio")?e.settings.audio_template_callback?o=e.settings.audio_template_callback(i):o+='":o=e.settings.video_template_callback?e.settings.video_template_callback(i):'"),o):""}function r(e){var t={};return new tinymce.html.SaxParser({validate:!1,special:"script,noscript",start:function(e,n){t.source1||"param"!=e||(t.source1=n.map.movie),("iframe"==e||"object"==e||"embed"==e||"video"==e||"audio"==e)&&(t=tinymce.extend(n.map,t)),"source"==e&&(t.source1?t.source2||(t.source2=n.map.src):t.source1=n.map.src)}}).parse(e),t.source1=t.source1||t.src||t.data,t.source2=t.source2||"",t.poster=t.poster||"",t}function l(t){return t.getAttribute("data-mce-object")?r(e.serializer.serialize(t,{selection:!0})):{}}function c(e,t,n){function i(e,t){var n,i,o,a;for(n in t)if(o=""+t[n],e.map[n])for(i=e.length;i--;)a=e[i],a.name==n&&(o?(e.map[n]=o,a.value=o):(delete e.map[n],e.splice(i,1)));else o&&(e.push({name:n,value:o}),e.map[n]=o)}var o=new tinymce.html.Writer,a=0;return new tinymce.html.SaxParser({validate:!1,special:"script,noscript",comment:function(e){o.comment(e)},cdata:function(e){o.cdata(e)},text:function(e,t){o.text(e,t)},start:function(e,r,l){switch(e){case"video":case"object":case"img":case"iframe":i(r,{width:t.width,height:t.height})}if(n)switch(e){case"video":i(r,{poster:t.poster,src:""}),t.source2&&i(r,{src:""});break;case"iframe":i(r,{src:t.source1});break;case"source":if(a++,2>=a&&(i(r,{src:t["source"+a],type:t["source"+a+"mime"]}),!t["source"+a]))return}o.start(e,r,l)},end:function(e){if("video"==e&&n)for(var r=1;2>=r;r++)if(t["source"+r]){var l=[];l.map={},r>a&&(i(l,{src:t["source"+r],type:t["source"+r+"mime"]}),o.start("source",l,!0))}o.end(e)}},new tinymce.html.Schema({})).parse(e),o.getContent()}var s=[{regex:/youtu\.be\/([a-z1-9.-_]+)/,type:"iframe",w:425,h:350,url:"http://www.youtube.com/embed/$1"},{regex:/youtube\.com(.+)v=([^&]+)/,type:"iframe",w:425,h:350,url:"http://www.youtube.com/embed/$2"},{regex:/vimeo\.com\/([0-9]+)/,type:"iframe",w:425,h:350,url:"http://player.vimeo.com/video/$1?title=0&byline=0&portrait=0&color=8dc7dc"},{regex:/maps\.google\.([a-z]{2,3})\/maps\/(.+)msid=(.+)/,type:"iframe",w:425,h:350,url:'http://maps.google.com/maps/ms?msid=$2&output=embed"'}];e.on("ResolveName",function(e){var t;(t=e.target.getAttribute("data-mce-object"))&&(e.name=t)}),e.on("preInit",function(){var t=e.schema.getSpecialElements();tinymce.each("video audio iframe object".split(" "),function(e){t[e]=RegExp("]*>","gi")}),e.schema.addValidElements("object[id|style|width|height|classid|codebase|*],embed[id|style|width|height|type|src|*],video[*],audio[*]");var n=e.schema.getBoolAttrs();tinymce.each("webkitallowfullscreen mozallowfullscreen allowfullscreen".split(" "),function(e){n[e]={}}),e.parser.addNodeFilter("iframe,video,audio,object,embed",function(t,n){for(var i,o,a,r,l,c,s,d=t.length;d--;){for(o=t[d],a=new tinymce.html.Node("img",1),a.shortEnded=!0,c=o.attributes,i=c.length;i--;)r=c[i].name,l=c[i].value,"width"!==r&&"height"!==r&&"style"!==r&&(("data"==r||"src"==r)&&(l=e.convertURL(l,r)),a.attr("data-mce-p-"+r,l));s=o.firstChild&&o.firstChild.value,s&&(a.attr("data-mce-html",escape(s)),a.firstChild=null),a.attr({width:o.attr("width")||"300",height:o.attr("height")||("audio"==n?"30":"150"),style:o.attr("style"),src:tinymce.Env.transparentSrc,"data-mce-object":n,"class":"mce-object mce-object-"+n}),o.replace(a)}}),e.serializer.addAttributeFilter("data-mce-object",function(e,t){for(var n,i,o,a,r,l,c=e.length;c--;){for(n=e[c],i=new tinymce.html.Node(n.attr(t),1),"audio"!=n.attr(t)&&i.attr({width:n.attr("width"),height:n.attr("height")}),i.attr({style:n.attr("style")}),a=n.attributes,o=a.length;o--;){var s=a[o].name;0===s.indexOf("data-mce-p-")&&i.attr(s.substr(11),a[o].value)}r=n.attr("data-mce-html"),r&&(l=new tinymce.html.Node("#text",3),l.raw=!0,l.value=unescape(r),i.append(l)),n.replace(i)}})}),e.on("ObjectSelected",function(e){"audio"==e.target.getAttribute("data-mce-object")&&e.preventDefault()}),e.on("objectResized",function(e){var t,n=e.target;n.getAttribute("data-mce-object")&&(t=n.getAttribute("data-mce-html"),t&&(t=unescape(t),n.setAttribute("data-mce-html",escape(c(t,{width:e.width,height:e.height})))))}),e.addButton("media",{tooltip:"Insert/edit video",onclick:i,stateSelector:"img[data-mce-object=video]"}),e.addMenuItem("media",{icon:"media",text:"Insert video",onclick:i,context:"insert",prependToContext:!0})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/nonbreaking/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/nonbreaking/plugin.js new file mode 100644 index 00000000..9e4a4c96 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/nonbreaking/plugin.js @@ -0,0 +1,43 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('nonbreaking', function(editor) { + editor.addCommand('mceNonBreaking', function() { + editor.insertContent( + (editor.plugins.visualchars && editor.plugins.visualchars.state) ? + ' ' : ' ' + ); + }); + + editor.addButton('nonbreaking', { + title: 'Insert nonbreaking space', + cmd: 'mceNonBreaking' + }); + + editor.addMenuItem('nonbreaking', { + text: 'Nonbreaking space', + cmd: 'mceNonBreaking', + context: 'insert' + }); + + if (editor.getParam('nonbreaking_force_tab')) { + editor.on('keydown', function(e) { + if (e.keyCode == 9) { + e.preventDefault(); + + editor.execCommand('mceNonBreaking'); + editor.execCommand('mceNonBreaking'); + editor.execCommand('mceNonBreaking'); + } + }); + } +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/nonbreaking/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/nonbreaking/plugin.min.js new file mode 100644 index 00000000..23e653e9 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/nonbreaking/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("nonbreaking",function(e){e.addCommand("mceNonBreaking",function(){e.insertContent(e.plugins.visualchars&&e.plugins.visualchars.state?' ':" ")}),e.addButton("nonbreaking",{title:"Insert nonbreaking space",cmd:"mceNonBreaking"}),e.addMenuItem("nonbreaking",{text:"Nonbreaking space",cmd:"mceNonBreaking",context:"insert"}),e.getParam("nonbreaking_force_tab")&&e.on("keydown",function(t){9==t.keyCode&&(t.preventDefault(),e.execCommand("mceNonBreaking"),e.execCommand("mceNonBreaking"),e.execCommand("mceNonBreaking"))})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/noneditable/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/noneditable/plugin.js new file mode 100644 index 00000000..c87f09d2 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/noneditable/plugin.js @@ -0,0 +1,533 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint loopfunc:true */ +/*global tinymce:true */ + +tinymce.PluginManager.add('noneditable', function(editor) { + var TreeWalker = tinymce.dom.TreeWalker; + var externalName = 'contenteditable', internalName = 'data-mce-' + externalName; + var VK = tinymce.util.VK; + + function handleContentEditableSelection() { + var dom = editor.dom, selection = editor.selection, caretContainerId = 'mce_noneditablecaret', invisibleChar = '\uFEFF'; + + // Returns the content editable state of a node "true/false" or null + function getContentEditable(node) { + var contentEditable; + + // Ignore non elements + if (node.nodeType === 1) { + // Check for fake content editable + contentEditable = node.getAttribute(internalName); + if (contentEditable && contentEditable !== "inherit") { + return contentEditable; + } + + // Check for real content editable + contentEditable = node.contentEditable; + if (contentEditable !== "inherit") { + return contentEditable; + } + } + + return null; + } + + // Returns the noneditable parent or null if there is a editable before it or if it wasn't found + function getNonEditableParent(node) { + var state; + + while (node) { + state = getContentEditable(node); + if (state) { + return state === "false" ? node : null; + } + + node = node.parentNode; + } + } + + // Get caret container parent for the specified node + 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; + } + } + } + } + + // Insert caret container before/after target or expand selection to include block + function insertCaretContainerOrExpandToBlock(target, before) { + var caretContainer, rng; + + // Select block + if (getContentEditable(target) === "false") { + if (dom.isBlock(target)) { + selection.select(target); + return; + } + } + + rng = dom.createRng(); + + if (getContentEditable(target) === "true") { + if (!target.firstChild) { + target.appendChild(editor.getDoc().createTextNode('\u00a0')); + } + + target = target.firstChild; + before = true; + } + + /* + caretContainer = dom.create('span', { + id: caretContainerId, + 'data-mce-bogus': true, + style:'border: 1px solid red' + }, invisibleChar); + */ + + caretContainer = dom.create('span', {id: caretContainerId, 'data-mce-bogus': true}, invisibleChar); + + if (before) { + target.parentNode.insertBefore(caretContainer, target); + } else { + dom.insertAfter(caretContainer, target); + } + + rng.setStart(caretContainer.firstChild, 1); + rng.collapse(true); + selection.setRng(rng); + + return caretContainer; + } + + // Removes any caret container except the one we might be in + function removeCaretContainer(caretContainer) { + var rng, child, currentCaretContainer, lastContainer; + + if (caretContainer) { + rng = selection.getRng(true); + rng.setStartBefore(caretContainer); + rng.setEndBefore(caretContainer); + + child = findFirstTextNode(caretContainer); + if (child && child.nodeValue.charAt(0) == invisibleChar) { + child = child.deleteData(0, 1); + } + + dom.remove(caretContainer, true); + + selection.setRng(rng); + } else { + currentCaretContainer = getParentCaretContainer(selection.getStart()); + while ((caretContainer = dom.get(caretContainerId)) && caretContainer !== lastContainer) { + if (currentCaretContainer !== caretContainer) { + child = findFirstTextNode(caretContainer); + if (child && child.nodeValue.charAt(0) == invisibleChar) { + child = child.deleteData(0, 1); + } + + dom.remove(caretContainer, true); + } + + lastContainer = caretContainer; + } + } + } + + // Modifies the selection to include contentEditable false elements or insert caret containers + function moveSelection() { + var nonEditableStart, nonEditableEnd, isCollapsed, rng, element; + + // Checks if there is any contents to the left/right side of caret returns the noneditable element or + // any editable element if it finds one inside + function hasSideContent(element, left) { + var container, offset, walker, node, len; + + container = rng.startContainer; + offset = rng.startOffset; + + // If endpoint is in middle of text node then expand to beginning/end of element + if (container.nodeType == 3) { + len = container.nodeValue.length; + if ((offset > 0 && offset < len) || (left ? offset == len : offset === 0)) { + return; + } + } else { + // Can we resolve the node by index + if (offset < container.childNodes.length) { + // Browser represents caret position as the offset at the start of an element. When moving right + // this is the element we are moving into so we consider our container to be child node at offset-1 + var pos = !left && offset > 0 ? offset-1 : offset; + container = container.childNodes[pos]; + if (container.hasChildNodes()) { + container = container.firstChild; + } + } else { + // If not then the caret is at the last position in it's container and the caret container + // should be inserted after the noneditable element + return !left ? element : null; + } + } + + // Walk left/right to look for contents + walker = new TreeWalker(container, element); + while ((node = walker[left ? 'prev' : 'next']())) { + if (node.nodeType === 3 && node.nodeValue.length > 0) { + return; + } else if (getContentEditable(node) === "true") { + // Found contentEditable=true element return this one to we can move the caret inside it + return node; + } + } + + return element; + } + + // Remove any existing caret containers + removeCaretContainer(); + + // Get noneditable start/end elements + isCollapsed = selection.isCollapsed(); + nonEditableStart = getNonEditableParent(selection.getStart()); + nonEditableEnd = getNonEditableParent(selection.getEnd()); + + // Is any fo the range endpoints noneditable + if (nonEditableStart || nonEditableEnd) { + rng = selection.getRng(true); + + // If it's a caret selection then look left/right to see if we need to move the caret out side or expand + if (isCollapsed) { + nonEditableStart = nonEditableStart || nonEditableEnd; + + if ((element = hasSideContent(nonEditableStart, true))) { + // We have no contents to the left of the caret then insert a caret container before the noneditable element + insertCaretContainerOrExpandToBlock(element, true); + } else if ((element = hasSideContent(nonEditableStart, false))) { + // We have no contents to the right of the caret then insert a caret container after the noneditable element + insertCaretContainerOrExpandToBlock(element, false); + } else { + // We are in the middle of a noneditable so expand to select it + selection.select(nonEditableStart); + } + } else { + rng = selection.getRng(true); + + // Expand selection to include start non editable element + if (nonEditableStart) { + rng.setStartBefore(nonEditableStart); + } + + // Expand selection to include end non editable element + if (nonEditableEnd) { + rng.setEndAfter(nonEditableEnd); + } + + selection.setRng(rng); + } + } + } + + function handleKey(e) { + var keyCode = e.keyCode, nonEditableParent, caretContainer, startElement, endElement; + + function getNonEmptyTextNodeSibling(node, prev) { + while ((node = node[prev ? 'previousSibling' : 'nextSibling'])) { + if (node.nodeType !== 3 || node.nodeValue.length > 0) { + return node; + } + } + } + + function positionCaretOnElement(element, start) { + selection.select(element); + selection.collapse(start); + } + + function canDelete(backspace) { + var rng, container, offset, nonEditableParent; + + function removeNodeIfNotParent(node) { + var parent = container; + + while (parent) { + if (parent === node) { + return; + } + + parent = parent.parentNode; + } + + dom.remove(node); + moveSelection(); + } + + function isNextPrevTreeNodeNonEditable() { + var node, walker, nonEmptyElements = editor.schema.getNonEmptyElements(); + + walker = new tinymce.dom.TreeWalker(container, editor.getBody()); + while ((node = (backspace ? walker.prev() : walker.next()))) { + // Found IMG/INPUT etc + if (nonEmptyElements[node.nodeName.toLowerCase()]) { + break; + } + + // Found text node with contents + if (node.nodeType === 3 && tinymce.trim(node.nodeValue).length > 0) { + break; + } + + // Found non editable node + if (getContentEditable(node) === "false") { + removeNodeIfNotParent(node); + return true; + } + } + + // Check if the content node is within a non editable parent + if (getNonEditableParent(node)) { + return true; + } + + return false; + } + + if (selection.isCollapsed()) { + rng = selection.getRng(true); + container = rng.startContainer; + offset = rng.startOffset; + container = getParentCaretContainer(container) || container; + + // Is in noneditable parent + if ((nonEditableParent = getNonEditableParent(container))) { + removeNodeIfNotParent(nonEditableParent); + return false; + } + + // Check if the caret is in the middle of a text node + if (container.nodeType == 3 && (backspace ? offset > 0 : offset < container.nodeValue.length)) { + return true; + } + + // Resolve container index + if (container.nodeType == 1) { + container = container.childNodes[offset] || container; + } + + // Check if previous or next tree node is non editable then block the event + if (isNextPrevTreeNodeNonEditable()) { + return false; + } + } + + return true; + } + + startElement = selection.getStart(); + endElement = selection.getEnd(); + + // Disable all key presses in contentEditable=false except delete or backspace + nonEditableParent = getNonEditableParent(startElement) || getNonEditableParent(endElement); + if (nonEditableParent && (keyCode < 112 || keyCode > 124) && keyCode != VK.DELETE && keyCode != VK.BACKSPACE) { + // Is Ctrl+c, Ctrl+v or Ctrl+x then use default browser behavior + if ((tinymce.isMac ? e.metaKey : e.ctrlKey) && (keyCode == 67 || keyCode == 88 || keyCode == 86)) { + return; + } + + e.preventDefault(); + + // Arrow left/right select the element and collapse left/right + if (keyCode == VK.LEFT || keyCode == VK.RIGHT) { + var left = keyCode == VK.LEFT; + // If a block element find previous or next element to position the caret + if (editor.dom.isBlock(nonEditableParent)) { + var targetElement = left ? nonEditableParent.previousSibling : nonEditableParent.nextSibling; + var walker = new TreeWalker(targetElement, targetElement); + var caretElement = left ? walker.prev() : walker.next(); + positionCaretOnElement(caretElement, !left); + } else { + positionCaretOnElement(nonEditableParent, left); + } + } + } else { + // Is arrow left/right, backspace or delete + if (keyCode == VK.LEFT || keyCode == VK.RIGHT || keyCode == VK.BACKSPACE || keyCode == VK.DELETE) { + caretContainer = getParentCaretContainer(startElement); + if (caretContainer) { + // Arrow left or backspace + if (keyCode == VK.LEFT || keyCode == VK.BACKSPACE) { + nonEditableParent = getNonEmptyTextNodeSibling(caretContainer, true); + + if (nonEditableParent && getContentEditable(nonEditableParent) === "false") { + e.preventDefault(); + + if (keyCode == VK.LEFT) { + positionCaretOnElement(nonEditableParent, true); + } else { + dom.remove(nonEditableParent); + return; + } + } else { + removeCaretContainer(caretContainer); + } + } + + // Arrow right or delete + if (keyCode == VK.RIGHT || keyCode == VK.DELETE) { + nonEditableParent = getNonEmptyTextNodeSibling(caretContainer); + + if (nonEditableParent && getContentEditable(nonEditableParent) === "false") { + e.preventDefault(); + + if (keyCode == VK.RIGHT) { + positionCaretOnElement(nonEditableParent, false); + } else { + dom.remove(nonEditableParent); + return; + } + } else { + removeCaretContainer(caretContainer); + } + } + } + + if ((keyCode == VK.BACKSPACE || keyCode == VK.DELETE) && !canDelete(keyCode == VK.BACKSPACE)) { + e.preventDefault(); + return false; + } + } + } + } + + editor.on('mousedown', function(e) { + var node = editor.selection.getNode(); + + if (getContentEditable(node) === "false" && node == e.target) { + // Expand selection on mouse down we can't block the default event since it's used for drag/drop + moveSelection(); + } + }); + + editor.on('mouseup keyup', moveSelection); + editor.on('keydown', handleKey); + } + + var editClass, nonEditClass, nonEditableRegExps; + + // Converts configured regexps to noneditable span items + function convertRegExpsToNonEditable(e) { + var i = nonEditableRegExps.length, content = e.content, cls = tinymce.trim(nonEditClass); + + // Don't replace the variables when raw is used for example on undo/redo + if (e.format == "raw") { + return; + } + + while (i--) { + content = content.replace(nonEditableRegExps[i], function(match) { + var args = arguments, index = args[args.length - 2]; + + // Is value inside an attribute then don't replace + if (index > 0 && content.charAt(index - 1) == '"') { + return match; + } + + return ( + '' + + editor.dom.encode(typeof(args[1]) === "string" ? args[1] : args[0]) + '' + ); + }); + } + + e.content = content; + } + + editClass = " " + tinymce.trim(editor.getParam("noneditable_editable_class", "mceEditable")) + " "; + nonEditClass = " " + tinymce.trim(editor.getParam("noneditable_noneditable_class", "mceNonEditable")) + " "; + + // Setup noneditable regexps array + nonEditableRegExps = editor.getParam("noneditable_regexp"); + if (nonEditableRegExps && !nonEditableRegExps.length) { + nonEditableRegExps = [nonEditableRegExps]; + } + + editor.on('PreInit', function() { + handleContentEditableSelection(); + + if (nonEditableRegExps) { + editor.on('BeforeSetContent', convertRegExpsToNonEditable); + } + + // Apply contentEditable true/false on elements with the noneditable/editable classes + editor.parser.addAttributeFilter('class', function(nodes) { + var i = nodes.length, className, node; + + while (i--) { + node = nodes[i]; + className = " " + node.attr("class") + " "; + + if (className.indexOf(editClass) !== -1) { + node.attr(internalName, "true"); + } else if (className.indexOf(nonEditClass) !== -1) { + node.attr(internalName, "false"); + } + } + }); + + // Remove internal name + editor.serializer.addAttributeFilter(internalName, function(nodes) { + var i = nodes.length, node; + + while (i--) { + node = nodes[i]; + + if (nonEditableRegExps && node.attr('data-mce-content')) { + node.name = "#text"; + node.type = 3; + node.raw = true; + node.value = node.attr('data-mce-content'); + } else { + node.attr(externalName, null); + node.attr(internalName, null); + } + } + }); + + // Convert external name into internal name + editor.parser.addAttributeFilter(externalName, function(nodes) { + var i = nodes.length, node; + + while (i--) { + node = nodes[i]; + node.attr(internalName, node.attr(externalName)); + node.attr(externalName, null); + } + }); + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/noneditable/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/noneditable/plugin.min.js new file mode 100644 index 00000000..5f9819e8 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/noneditable/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("noneditable",function(e){function t(){function t(e){var t;if(1===e.nodeType){if(t=e.getAttribute(c),t&&"inherit"!==t)return t;if(t=e.contentEditable,"inherit"!==t)return t}return null}function n(e){for(var n;e;){if(n=t(e))return"false"===n?e:null;e=e.parentNode}}function i(e){for(;e;){if(e.id===g)return e;e=e.parentNode}}function o(e){var t;if(e)for(t=new r(e,e),e=t.current();e;e=t.next())if(3===e.nodeType)return e}function a(n,i){var o,a;return"false"===t(n)&&m.isBlock(n)?(f.select(n),void 0):(a=m.createRng(),"true"===t(n)&&(n.firstChild||n.appendChild(e.getDoc().createTextNode(" ")),n=n.firstChild,i=!0),o=m.create("span",{id:g,"data-mce-bogus":!0},h),i?n.parentNode.insertBefore(o,n):m.insertAfter(o,n),a.setStart(o.firstChild,1),a.collapse(!0),f.setRng(a),o)}function l(e){var t,n,a,r;if(e)t=f.getRng(!0),t.setStartBefore(e),t.setEndBefore(e),n=o(e),n&&n.nodeValue.charAt(0)==h&&(n=n.deleteData(0,1)),m.remove(e,!0),f.setRng(t);else for(a=i(f.getStart());(e=m.get(g))&&e!==r;)a!==e&&(n=o(e),n&&n.nodeValue.charAt(0)==h&&(n=n.deleteData(0,1)),m.remove(e,!0)),r=e}function d(){function e(e,n){var i,o,a,l,c;if(i=s.startContainer,o=s.startOffset,3==i.nodeType){if(c=i.nodeValue.length,o>0&&c>o||(n?o==c:0===o))return}else{if(!(i.childNodes.length>o))return n?null:e;var d=!n&&o>0?o-1:o;i=i.childNodes[d],i.hasChildNodes()&&(i=i.firstChild)}for(a=new r(i,e);l=a[n?"prev":"next"]();){if(3===l.nodeType&&l.nodeValue.length>0)return;if("true"===t(l))return l}return e}var i,o,c,s,d;l(),c=f.isCollapsed(),i=n(f.getStart()),o=n(f.getEnd()),(i||o)&&(s=f.getRng(!0),c?(i=i||o,(d=e(i,!0))?a(d,!0):(d=e(i,!1))?a(d,!1):f.select(i)):(s=f.getRng(!0),i&&s.setStartBefore(i),o&&s.setEndAfter(o),f.setRng(s)))}function u(o){function a(e,t){for(;e=e[t?"previousSibling":"nextSibling"];)if(3!==e.nodeType||e.nodeValue.length>0)return e}function c(e,t){f.select(e),f.collapse(t)}function u(o){function a(e){for(var t=c;t;){if(t===e)return;t=t.parentNode}m.remove(e),d()}function r(){var i,r,l=e.schema.getNonEmptyElements();for(r=new tinymce.dom.TreeWalker(c,e.getBody());(i=o?r.prev():r.next())&&!l[i.nodeName.toLowerCase()]&&!(3===i.nodeType&&tinymce.trim(i.nodeValue).length>0);)if("false"===t(i))return a(i),!0;return n(i)?!0:!1}var l,c,s,u;if(f.isCollapsed()){if(l=f.getRng(!0),c=l.startContainer,s=l.startOffset,c=i(c)||c,u=n(c))return a(u),!1;if(3==c.nodeType&&(o?s>0:c.nodeValue.length>s))return!0;if(1==c.nodeType&&(c=c.childNodes[s]||c),r())return!1}return!0}var g,h,p,y,v=o.keyCode;if(p=f.getStart(),y=f.getEnd(),g=n(p)||n(y),g&&(112>v||v>124)&&v!=s.DELETE&&v!=s.BACKSPACE){if((tinymce.isMac?o.metaKey:o.ctrlKey)&&(67==v||88==v||86==v))return;if(o.preventDefault(),v==s.LEFT||v==s.RIGHT){var b=v==s.LEFT;if(e.dom.isBlock(g)){var x=b?g.previousSibling:g.nextSibling,C=new r(x,x),w=b?C.prev():C.next();c(w,!b)}else c(g,b)}}else if(v==s.LEFT||v==s.RIGHT||v==s.BACKSPACE||v==s.DELETE){if(h=i(p)){if(v==s.LEFT||v==s.BACKSPACE)if(g=a(h,!0),g&&"false"===t(g)){if(o.preventDefault(),v!=s.LEFT)return m.remove(g),void 0;c(g,!0)}else l(h);if(v==s.RIGHT||v==s.DELETE)if(g=a(h),g&&"false"===t(g)){if(o.preventDefault(),v!=s.RIGHT)return m.remove(g),void 0;c(g,!1)}else l(h)}if((v==s.BACKSPACE||v==s.DELETE)&&!u(v==s.BACKSPACE))return o.preventDefault(),!1}}var m=e.dom,f=e.selection,g="mce_noneditablecaret",h="";e.on("mousedown",function(n){var i=e.selection.getNode();"false"===t(i)&&i==n.target&&d()}),e.on("mouseup keyup",d),e.on("keydown",u)}function n(t){var n=a.length,i=t.content,r=tinymce.trim(o);if("raw"!=t.format){for(;n--;)i=i.replace(a[n],function(t){var n=arguments,o=n[n.length-2];return o>0&&'"'==i.charAt(o-1)?t:''+e.dom.encode("string"==typeof n[1]?n[1]:n[0])+""});t.content=i}}var i,o,a,r=tinymce.dom.TreeWalker,l="contenteditable",c="data-mce-"+l,s=tinymce.util.VK;i=" "+tinymce.trim(e.getParam("noneditable_editable_class","mceEditable"))+" ",o=" "+tinymce.trim(e.getParam("noneditable_noneditable_class","mceNonEditable"))+" ",a=e.getParam("noneditable_regexp"),a&&!a.length&&(a=[a]),e.on("PreInit",function(){t(),a&&e.on("BeforeSetContent",n),e.parser.addAttributeFilter("class",function(e){for(var t,n,a=e.length;a--;)n=e[a],t=" "+n.attr("class")+" ",-1!==t.indexOf(i)?n.attr(c,"true"):-1!==t.indexOf(o)&&n.attr(c,"false")}),e.serializer.addAttributeFilter(c,function(e){for(var t,n=e.length;n--;)t=e[n],a&&t.attr("data-mce-content")?(t.name="#text",t.type=3,t.raw=!0,t.value=t.attr("data-mce-content")):(t.attr(l,null),t.attr(c,null))}),e.parser.addAttributeFilter(l,function(e){for(var t,n=e.length;n--;)t=e[n],t.attr(c,t.attr(l)),t.attr(l,null)})})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/pagebreak/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/pagebreak/plugin.js new file mode 100644 index 00000000..c6b24f77 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/pagebreak/plugin.js @@ -0,0 +1,86 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('pagebreak', function(editor) { + var cls = 'mce-pagebreak', sep = editor.getParam('pagebreak_separator', ''), pbRE; + var pb = ''; + + pbRE = new RegExp(sep.replace(/[\?\.\*\[\]\(\)\{\}\+\^\$\:]/g, function(a) { + return '\\' + a; + }), 'g'); + + // Register commands + editor.addCommand('mcePageBreak', function() { + editor.execCommand('mceInsertContent', 0, pb); + }); + + // Register buttons + editor.addButton('pagebreak', { + title: 'Page break', + cmd: 'mcePageBreak' + }); + + editor.addMenuItem('pagebreak', { + text: 'Page break', + icon: 'pagebreak', + cmd: 'mcePageBreak', + context: 'insert' + }); + + editor.on('ResolveName', function(e) { + if (e.target.nodeName == 'IMG' && editor.dom.hasClass(e.target, cls)) { + e.name = 'pagebreak'; + } + }); + + editor.on('click', function(e) { + e = e.target; + + if (e.nodeName === 'IMG' && editor.dom.hasClass(e, cls)) { + editor.selection.select(e); + } + }); + + editor.on('PreInit', function() { + editor.parser.addNodeFilter('#comment', function(nodes) { + var i = nodes.length, node, img; + + while (i--) { + node = nodes[i]; + if (node.value.indexOf('pagebreak') !== -1) { + img = new tinymce.html.Node('img', 1); + + img.attr({ + src: tinymce.Env.transparentSrc, + 'class': 'mce-pagebreak', + 'data-mce-resize': 'false' + }); + + node.replace(img); + } + } + }); + + editor.serializer.addNodeFilter('img', function(nodes) { + var i = nodes.length, node, className; + + while (i--) { + node = nodes[i]; + className = node.attr('class'); + if (className && className.indexOf('mce-pagebreak') !== -1) { + node.type = 8; + node.value = 'pagebreak'; + } + } + }); + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/pagebreak/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/pagebreak/plugin.min.js new file mode 100644 index 00000000..bfbec8c2 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/pagebreak/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("pagebreak",function(e){var t,n="mce-pagebreak",i=e.getParam("pagebreak_separator",""),a='';t=RegExp(i.replace(/[\?\.\*\[\]\(\)\{\}\+\^\$\:]/g,function(e){return"\\"+e}),"g"),e.addCommand("mcePageBreak",function(){e.execCommand("mceInsertContent",0,a)}),e.addButton("pagebreak",{title:"Page break",cmd:"mcePageBreak"}),e.addMenuItem("pagebreak",{text:"Page break",icon:"pagebreak",cmd:"mcePageBreak",context:"insert"}),e.on("ResolveName",function(t){"IMG"==t.target.nodeName&&e.dom.hasClass(t.target,n)&&(t.name="pagebreak")}),e.on("click",function(t){t=t.target,"IMG"===t.nodeName&&e.dom.hasClass(t,n)&&e.selection.select(t)}),e.on("PreInit",function(){e.parser.addNodeFilter("#comment",function(e){for(var t,n,i=e.length;i--;)t=e[i],-1!==t.value.indexOf("pagebreak")&&(n=new tinymce.html.Node("img",1),n.attr({src:tinymce.Env.transparentSrc,"class":"mce-pagebreak","data-mce-resize":"false"}),t.replace(n))}),e.serializer.addNodeFilter("img",function(e){for(var t,n,i=e.length;i--;)t=e[i],n=t.attr("class"),n&&-1!==n.indexOf("mce-pagebreak")&&(t.type=8,t.value="pagebreak")})})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/paste/classes/Clipboard.js b/lib/tinymce/jscripts/tinymce4/plugins/paste/classes/Clipboard.js new file mode 100644 index 00000000..6c18b5e8 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/paste/classes/Clipboard.js @@ -0,0 +1,216 @@ +/** + * Clipboard.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class contains logic for getting HTML contents out of the clipboard. + * + * @class tinymce.pasteplugin.Clipboard + * @private + */ +define("tinymce/pasteplugin/Clipboard", [ + "tinymce/Env", + "tinymce/util/Tools", + "tinymce/util/VK" +], function(Env, Tools, VK) { + function hasClipboardData() { + // Gecko is excluded until the fix: https://bugzilla.mozilla.org/show_bug.cgi?id=850663 + return !Env.gecko && (("ClipboardEvent" in window) || (Env.webkit && "FocusEvent" in window)); + } + + return function(editor) { + var plainTextPasteTime; + + function shouldPasteAsPlainText() { + return new Date().getTime() - plainTextPasteTime < 100; + } + + // TODO: Move this to a class? + function process(content, items) { + Tools.each(items, function(v) { + if (v.constructor == RegExp) { + content = content.replace(v, ''); + } else { + content = content.replace(v[0], v[1]); + } + }); + + return content; + } + + function processHtml(html) { + var args = editor.fire('PastePreProcess', {content: html}); + + if (editor.settings.paste_remove_styles || (editor.settings.paste_remove_styles_if_webkit !== false && Env.webkit)) { + args.content = args.content.replace(/ style=\"[^\"]+\"/g, ''); + } + + if (!args.isDefaultPrevented()) { + editor.insertContent(args.content); + } + } + + function processText(text) { + text = editor.dom.encode(text); + + text = process(text, [ + [/\n\n/g, "

    "], + [/^(.*<\/p>)(

    )$/, '

    $1'], + [/\n/g, "
    "] + ]); + + var args = editor.fire('PastePreProcess', {content: text}); + + if (!args.isDefaultPrevented()) { + editor.insertContent(args.content); + } + } + + function createPasteBin() { + var scrollTop = (editor.inline ? editor.getBody() : editor.getDoc().documentElement).scrollTop; + + // Create a pastebin and move the selection into the bin + var pastebinElm = editor.dom.add(editor.getBody(), 'div', { + id: 'mcePasteBin', + contentEditable: false, + style: 'position: absolute; top: ' + scrollTop + 'px; left: 0; background: red; width: 1px; height: 1px; overflow: hidden' + }, '

    X
    '); + + return pastebinElm; + } + + function removePasteBin() { + var pastebinElm = editor.dom.get('mcePasteBin'); + + editor.dom.unbind(pastebinElm); + editor.dom.remove(pastebinElm); + } + + editor.on('keydown', function(e) { + // Shift+Ctrl+V + if (e.shiftKey && e.keyCode == 86) { + plainTextPasteTime = new Date().getTime(); + } + }); + + // Use Clipboard API if it's available + if (hasClipboardData()) { + editor.on('paste', function(e) { + var clipboardData = e.clipboardData; + + function processByContentType(contentType, processFunc) { + for (var ti = 0; ti < clipboardData.types.length; ti++) { + if (clipboardData.types[ti] == contentType) { + processFunc(clipboardData.getData(contentType)); + //clipboardData.items[ti].getAsString(processFunc); + return true; + } + } + } + + if (clipboardData) { + e.preventDefault(); + + if (shouldPasteAsPlainText()) { + // First look for HTML then look for plain text + if (!processByContentType('text/plain', processText)) { + processByContentType('text/html', processHtml); + } + } else { + // First look for HTML then look for plain text + if (!processByContentType('text/html', processHtml)) { + processByContentType('text/plain', processText); + } + } + } + }); + } else { + if (Env.ie) { + // Explorer fallback + editor.on('init', function() { + var dom = editor.dom; + + editor.dom.bind(editor.getBody(), 'paste', function(e) { + var gotPasteEvent; + + e.preventDefault(); + + if (shouldPasteAsPlainText() && dom.doc.dataTransfer) { + processText(dom.doc.dataTransfer.getData('Text')); + return; + } + + var pastebinElm = createPasteBin(); + + dom.bind(pastebinElm, 'paste', function(e) { + e.stopPropagation(); + gotPasteEvent = true; + }); + + var lastRng = editor.selection.getRng(); + + // Select the container + var rng = dom.doc.body.createTextRange(); + rng.moveToElementText(pastebinElm.firstChild); + rng.execCommand('Paste'); + removePasteBin(); + + if (!gotPasteEvent) { + editor.windowManager.alert('Clipboard access not possible.'); + return; + } + + var html = pastebinElm.firstChild.innerHTML; + editor.selection.setRng(lastRng); + processHtml(html); + }); + }); + } else { + editor.on('init', function() { + editor.dom.bind(editor.getBody(), 'paste', function(e) { + e.preventDefault(); + editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.'); + }); + }); + + // Old Gecko/WebKit/Opera fallback + editor.on('keydown', function(e) { + if (VK.metaKeyPressed(e) && e.keyCode == 86 && !e.isDefaultPrevented()) { + var pastebinElm = createPasteBin(); + var lastRng = editor.selection.getRng(); + + editor.selection.select(pastebinElm, true); + + editor.dom.bind(pastebinElm, 'paste', function(e) { + e.stopPropagation(); + + setTimeout(function() { + removePasteBin(); + editor.lastRng = lastRng; + editor.selection.setRng(lastRng); + processHtml(pastebinElm.firstChild.innerHTML); + }, 0); + }); + } + }); + } + } + + // Block all drag/drop events + if (editor.paste_block_drop) { + editor.on('dragend dragover draggesture dragdrop drop drag', function(e) { + e.preventDefault(); + e.stopPropagation(); + }); + } + + this.paste = processHtml; + this.pasteText = processText; + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/paste/classes/Plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/paste/classes/Plugin.js new file mode 100644 index 00000000..63d3f0a8 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/paste/classes/Plugin.js @@ -0,0 +1,40 @@ +/** + * Plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class contains the tinymce plugin logic for the paste plugin. + * + * @class tinymce.pasteplugin.Plugin + * @private + */ +define("tinymce/pasteplugin/Plugin", [ + "tinymce/PluginManager", + "tinymce/pasteplugin/Clipboard", + "tinymce/pasteplugin/WordFilter", + "tinymce/pasteplugin/Quirks" +], function(PluginManager, Clipboard, WordFilter, Quirks) { + PluginManager.add('paste', function(editor) { + var self = this; + + self.clipboard = new Clipboard(editor); + self.quirks = new Quirks(editor); + self.wordFilter = new WordFilter(editor); + + editor.addCommand('mceInsertClipboardContent', function(ui, value) { + if (value.content) { + self.clipboard.paste(value.content); + } + + if (value.text) { + self.clipboard.pasteText(value.text); + } + }); + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/paste/classes/Quirks.js b/lib/tinymce/jscripts/tinymce4/plugins/paste/classes/Quirks.js new file mode 100644 index 00000000..0b52b9c7 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/paste/classes/Quirks.js @@ -0,0 +1,110 @@ +/** + * Quirks.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class contains various fixes for browsers. These issues can not be feature + * detected since we have no direct control over the clipboard. However we might be able + * to remove some of these fixes once the browsers gets updated/fixed. + * + * @class tinymce.pasteplugin.Quirks + * @private + */ +define("tinymce/pasteplugin/Quirks", [ + "tinymce/Env", + "tinymce/util/Tools" +], function(Env, Tools) { + return function(editor) { + function addPreProcessFilter(filterFunc) { + editor.on('PastePreProcess', function(e) { + e.content = filterFunc(e.content); + }); + } + + function process(content, items) { + Tools.each(items, function(v) { + if (v.constructor == RegExp) { + content = content.replace(v, ''); + } else { + content = content.replace(v[0], v[1]); + } + }); + + return content; + } + + /** + * Removes WebKit fragment comments and converted-space spans. + * + * This: + * a b + * + * Becomes: + * a b + */ + function removeWebKitFragments(html) { + html = process(html, [ + /^[\s\S]*|[\s\S]*$/g, // WebKit fragment + [/\u00a0<\/span>/g, '\u00a0'], // WebKit   + /
    $/ // Traling BR elements + ]); + + return html; + } + + /** + * Removes BR elements after block elements. IE9 has a nasty bug where it puts a BR element after each + * block element when pasting from word. This removes those elements. + * + * This: + *

    a


    b

    + * + * Becomes: + *

    a

    b

    + */ + function removeExplorerBrElementsAfterBlocks(html) { + // Produce block regexp based on the block elements in schema + if (!this.explorerBlocksRegExp) { + var blockElements = []; + + Tools.each(editor.schema.getBlockElements(), function(block, blockName) { + blockElements.push(blockName); + }); + + this.explorerBlocksRegExp = new RegExp( + '(?:
     [\\s\\r\\n]+|
    )*(<\/?(' + blockElements.join('|') + ')[^>]*>)(?:
     [\\s\\r\\n]+|
    )*', + 'g' + ); + } + + // Remove BR:s from: X
    + html = process(html, [ + [this.explorerBlocksRegExp, '$1'] + ]); + + // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break + html = process(html, [ + [/

    /g, '

    '], // Replace multiple BR elements with uppercase BR to keep them intact + [/
    /g, ' '], // Replace single br elements with space since they are word wrap BR:s + [/

    /g, '
    '] // Replace back the double brs but into a single BR + ]); + + return html; + } + + // Sniff browsers and apply fixes since we can't feature detect + if (Env.webkit) { + addPreProcessFilter(removeWebKitFragments); + } + + if (Env.ie) { + addPreProcessFilter(removeExplorerBrElementsAfterBlocks); + } + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/paste/classes/WordFilter.js b/lib/tinymce/jscripts/tinymce4/plugins/paste/classes/WordFilter.js new file mode 100644 index 00000000..576c711a --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/paste/classes/WordFilter.js @@ -0,0 +1,259 @@ +/** + * WordFilter.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class parses word HTML into proper TinyMCE markup. + * + * @class tinymce.pasteplugin.Quirks + * @private + */ +define("tinymce/pasteplugin/WordFilter", [ + "tinymce/util/Tools", + "tinymce/html/DomParser", + "tinymce/html/Schema", + "tinymce/html/Serializer", + "tinymce/html/Node" +], function(Tools, DomParser, Schema, Serializer, Node) { + return function(editor) { + var each = Tools.each; + + editor.on('PastePreProcess', function(e) { + var content = e.content, retainStyleProperties, validStyles; + + retainStyleProperties = editor.settings.paste_retain_style_properties; + if (retainStyleProperties) { + validStyles = Tools.makeMap(retainStyleProperties); + } + + function process(items) { + each(items, function(v) { + if (v.constructor == RegExp) { + content = content.replace(v, ''); + } else { + content = content.replace(v[0], v[1]); + } + }); + } + + /** + * Converts fake bullet and numbered lists to real semantic OL/UL. + * + * @param {tinymce.html.Node} node Root node to convert children of. + */ + function convertFakeListsToProperLists(node) { + var currentListNode, prevListNode, lastLevel = 1; + + function convertParagraphToLi(paragraphNode, listStartTextNode, listName, start) { + var level = paragraphNode._listLevel || lastLevel; + + // Handle list nesting + if (level != lastLevel) { + if (level < lastLevel) { + // Move to parent list + if (currentListNode) { + currentListNode = currentListNode.parent.parent; + } + } else { + // Create new list + prevListNode = currentListNode; + currentListNode = null; + } + } + + if (!currentListNode || currentListNode.name != listName) { + prevListNode = prevListNode || currentListNode; + currentListNode = new Node(listName, 1); + + if (start > 1) { + currentListNode.attr('start', '' + start); + } + + paragraphNode.wrap(currentListNode); + } else { + currentListNode.append(paragraphNode); + } + + paragraphNode.name = 'li'; + listStartTextNode.value = ''; + + var nextNode = listStartTextNode.next; + if (nextNode && nextNode.type == 3) { + nextNode.value = nextNode.value.replace(/^\u00a0+/, ''); + } + + // Append list to previous list + if (level > lastLevel) { + prevListNode.lastChild.append(currentListNode); + } + + lastLevel = level; + } + + var paragraphs = node.getAll('p'); + + for (var i = 0; i < paragraphs.length; i++) { + node = paragraphs[i]; + + if (node.name == 'p' && node.firstChild) { + // Find first text node in paragraph + var nodeText = ''; + var listStartTextNode = node.firstChild; + + while (listStartTextNode) { + nodeText = listStartTextNode.value; + if (nodeText) { + break; + } + + listStartTextNode = listStartTextNode.firstChild; + } + + // Detect unordered lists look for bullets + if (/^\s*[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*$/.test(nodeText)) { + convertParagraphToLi(node, listStartTextNode, 'ul'); + continue; + } + + // Detect ordered lists 1., a. or ixv. + if (/^\s*\w+\./.test(nodeText)) { + // Parse OL start number + var matches = /([0-9])\./.exec(nodeText); + var start = 1; + if (matches) { + start = parseInt(matches[1], 10); + } + + convertParagraphToLi(node, listStartTextNode, 'ol', start); + continue; + } + + currentListNode = null; + } + } + } + + function filterStyles(node, styleValue) { + // Parse out list indent level for lists + if (node.name === 'p') { + var matches = /mso-list:\w+ \w+([0-9]+)/.exec(styleValue); + + if (matches) { + node._listLevel = parseInt(matches[1], 10); + } + } + + if (editor.getParam("paste_retain_style_properties", "none")) { + var outputStyle = ""; + + Tools.each(editor.dom.parseStyle(styleValue), function(value, name) { + // Convert various MS styles to W3C styles + switch (name) { + case "horiz-align": + name = "text-align"; + return; + + case "vert-align": + name = "vertical-align"; + return; + + case "font-color": + case "mso-foreground": + name = "color"; + return; + + case "mso-background": + case "mso-highlight": + name = "background"; + break; + } + + // Output only valid styles + if (retainStyleProperties == "all" || (validStyles && validStyles[name])) { + outputStyle += name + ':' + value + ';'; + } + }); + + if (outputStyle) { + return outputStyle; + } + } + + return null; + } + + if (editor.settings.paste_enable_default_filters === false) { + return; + } + + // Detect is the contents is Word junk HTML + if (/class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i.test(e.content)) { + e.wordContent = true; // Mark it for other processors + + // Remove basic Word junk + process([ + // Word comments like conditional comments etc + //gi, + + // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, + // MS Office namespaced tags, and a few other tags + /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, + + // Convert into for line-though + [/<(\/?)s>/gi, "<$1strike>"], + + // Replace nsbp entites to char since it's easier to handle + [/ /gi, "\u00a0"], + + // Convert ___ to string of alternating + // breaking/non-breaking spaces of same length + [/([\s\u00a0]*)<\/span>/gi, + function(str, spaces) { + return (spaces.length > 0) ? + spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : ""; + } + ] + ]); + + // Setup strict schema + var schema = new Schema({ + valid_elements: '@[style],-strong/b,-em/i,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,-table,' + + '-tr,-td[colspan|rowspan],-th,-thead,-tfoot,-tbody,-a[!href]' + }); + + // Parse HTML into DOM structure + var domParser = new DomParser({}, schema); + + // Filte element style attributes + domParser.addAttributeFilter('style', function(nodes) { + var i = nodes.length, node; + + while (i--) { + node = nodes[i]; + node.attr('style', filterStyles(node, node.attr('style'))); + + // Remove pointess spans + if (node.name == 'span' && !node.attributes.length) { + node.unwrap(); + } + } + }); + + // Parse into DOM structure + var rootNode = domParser.parse(content); + + // Process DOM + convertFakeListsToProperLists(rootNode); + + // Serialize DOM back to HTML + e.content = new Serializer({}, schema).serialize(rootNode); + } + }); + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/paste/plugin.dev.js b/lib/tinymce/jscripts/tinymce4/plugins/paste/plugin.dev.js new file mode 100644 index 00000000..46b8518f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/paste/plugin.dev.js @@ -0,0 +1,119 @@ +/** + * Inline development version. Only to be used while developing since it uses document.write to load scripts. + */ + +/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ +/*globals $code */ + +(function(exports) { + "use strict"; + + var html = "", baseDir; + var modules = {}, exposedModules = [], moduleCount = 0; + + var scripts = document.getElementsByTagName('script'); + for (var i = 0; i < scripts.length; i++) { + var src = scripts[i].src; + + if (src.indexOf('/plugin.dev.js') != -1) { + baseDir = src.substring(0, src.lastIndexOf('/')); + } + } + + function require(ids, callback) { + var module, defs = []; + + for (var i = 0; i < ids.length; ++i) { + module = modules[ids[i]] || resolve(ids[i]); + if (!module) { + throw 'module definition dependecy not found: ' + ids[i]; + } + + defs.push(module); + } + + callback.apply(null, defs); + } + + function resolve(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length; ++fi) { + if (!target[fragments[fi]]) { + return; + } + + target = target[fragments[fi]]; + } + + return target; + } + + function register(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length - 1; ++fi) { + if (target[fragments[fi]] === undefined) { + target[fragments[fi]] = {}; + } + + target = target[fragments[fi]]; + } + + target[fragments[fragments.length - 1]] = modules[id]; + } + + function define(id, dependencies, definition) { + if (typeof id !== 'string') { + throw 'invalid module definition, module id must be defined and be a string'; + } + + if (dependencies === undefined) { + throw 'invalid module definition, dependencies must be specified'; + } + + if (definition === undefined) { + throw 'invalid module definition, definition function must be specified'; + } + + require(dependencies, function() { + modules[id] = definition.apply(null, arguments); + }); + + if (--moduleCount === 0) { + for (var i = 0; i < exposedModules.length; i++) { + register(exposedModules[i]); + } + } + } + + function expose(ids) { + exposedModules = ids; + } + + function writeScripts() { + document.write(html); + } + + function load(path) { + html += '\n'; + moduleCount++; + } + + // Expose globally + exports.define = define; + exports.require = require; + + expose(["tinymce/pasteplugin/Clipboard","tinymce/pasteplugin/WordFilter","tinymce/pasteplugin/Quirks","tinymce/pasteplugin/Plugin"]); + + load('classes/Clipboard.js'); + load('classes/WordFilter.js'); + load('classes/Quirks.js'); + load('classes/Plugin.js'); + + writeScripts(); +})(this); + +// $hash: 85a116a5099f2fb1f017e02daac61c63 \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/paste/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/paste/plugin.js new file mode 100644 index 00000000..53d02d2f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/paste/plugin.js @@ -0,0 +1,721 @@ +/** + * Compiled inline version. (Library mode) + */ + +/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ +/*globals $code */ + +(function(exports, undefined) { + "use strict"; + + var modules = {}; + + function require(ids, callback) { + var module, defs = []; + + for (var i = 0; i < ids.length; ++i) { + module = modules[ids[i]] || resolve(ids[i]); + if (!module) { + throw 'module definition dependecy not found: ' + ids[i]; + } + + defs.push(module); + } + + callback.apply(null, defs); + } + + function define(id, dependencies, definition) { + if (typeof id !== 'string') { + throw 'invalid module definition, module id must be defined and be a string'; + } + + if (dependencies === undefined) { + throw 'invalid module definition, dependencies must be specified'; + } + + if (definition === undefined) { + throw 'invalid module definition, definition function must be specified'; + } + + require(dependencies, function() { + modules[id] = definition.apply(null, arguments); + }); + } + + function defined(id) { + return !!modules[id]; + } + + function resolve(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length; ++fi) { + if (!target[fragments[fi]]) { + return; + } + + target = target[fragments[fi]]; + } + + return target; + } + + function expose(ids) { + for (var i = 0; i < ids.length; i++) { + var target = exports; + var id = ids[i]; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length - 1; ++fi) { + if (target[fragments[fi]] === undefined) { + target[fragments[fi]] = {}; + } + + target = target[fragments[fi]]; + } + + target[fragments[fragments.length - 1]] = modules[id]; + } + } + +// Included from: js/tinymce/plugins/paste/classes/Clipboard.js + +/** + * Clipboard.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class contains logic for getting HTML contents out of the clipboard. + * + * @class tinymce.pasteplugin.Clipboard + * @private + */ +define("tinymce/pasteplugin/Clipboard", [ + "tinymce/Env", + "tinymce/util/Tools", + "tinymce/util/VK" +], function(Env, Tools, VK) { + function hasClipboardData() { + // Gecko is excluded until the fix: https://bugzilla.mozilla.org/show_bug.cgi?id=850663 + return !Env.gecko && (("ClipboardEvent" in window) || (Env.webkit && "FocusEvent" in window)); + } + + return function(editor) { + var plainTextPasteTime; + + function shouldPasteAsPlainText() { + return new Date().getTime() - plainTextPasteTime < 100; + } + + // TODO: Move this to a class? + function process(content, items) { + Tools.each(items, function(v) { + if (v.constructor == RegExp) { + content = content.replace(v, ''); + } else { + content = content.replace(v[0], v[1]); + } + }); + + return content; + } + + function processHtml(html) { + var args = editor.fire('PastePreProcess', {content: html}); + + if (editor.settings.paste_remove_styles || (editor.settings.paste_remove_styles_if_webkit !== false && Env.webkit)) { + args.content = args.content.replace(/ style=\"[^\"]+\"/g, ''); + } + + if (!args.isDefaultPrevented()) { + editor.insertContent(args.content); + } + } + + function processText(text) { + text = editor.dom.encode(text); + + text = process(text, [ + [/\n\n/g, "

    "], + [/^(.*<\/p>)(

    )$/, '

    $1'], + [/\n/g, "
    "] + ]); + + var args = editor.fire('PastePreProcess', {content: text}); + + if (!args.isDefaultPrevented()) { + editor.insertContent(args.content); + } + } + + function createPasteBin() { + var scrollTop = (editor.inline ? editor.getBody() : editor.getDoc().documentElement).scrollTop; + + // Create a pastebin and move the selection into the bin + var pastebinElm = editor.dom.add(editor.getBody(), 'div', { + id: 'mcePasteBin', + contentEditable: false, + style: 'position: absolute; top: ' + scrollTop + 'px; left: 0; background: red; width: 1px; height: 1px; overflow: hidden' + }, '

    X
    '); + + return pastebinElm; + } + + function removePasteBin() { + var pastebinElm = editor.dom.get('mcePasteBin'); + + editor.dom.unbind(pastebinElm); + editor.dom.remove(pastebinElm); + } + + editor.on('keydown', function(e) { + // Shift+Ctrl+V + if (e.shiftKey && e.keyCode == 86) { + plainTextPasteTime = new Date().getTime(); + } + }); + + // Use Clipboard API if it's available + if (hasClipboardData()) { + editor.on('paste', function(e) { + var clipboardData = e.clipboardData; + + function processByContentType(contentType, processFunc) { + for (var ti = 0; ti < clipboardData.types.length; ti++) { + if (clipboardData.types[ti] == contentType) { + processFunc(clipboardData.getData(contentType)); + //clipboardData.items[ti].getAsString(processFunc); + return true; + } + } + } + + if (clipboardData) { + e.preventDefault(); + + if (shouldPasteAsPlainText()) { + // First look for HTML then look for plain text + if (!processByContentType('text/plain', processText)) { + processByContentType('text/html', processHtml); + } + } else { + // First look for HTML then look for plain text + if (!processByContentType('text/html', processHtml)) { + processByContentType('text/plain', processText); + } + } + } + }); + } else { + if (Env.ie) { + // Explorer fallback + editor.on('init', function() { + var dom = editor.dom; + + editor.dom.bind(editor.getBody(), 'paste', function(e) { + var gotPasteEvent; + + e.preventDefault(); + + if (shouldPasteAsPlainText() && dom.doc.dataTransfer) { + processText(dom.doc.dataTransfer.getData('Text')); + return; + } + + var pastebinElm = createPasteBin(); + + dom.bind(pastebinElm, 'paste', function(e) { + e.stopPropagation(); + gotPasteEvent = true; + }); + + var lastRng = editor.selection.getRng(); + + // Select the container + var rng = dom.doc.body.createTextRange(); + rng.moveToElementText(pastebinElm.firstChild); + rng.execCommand('Paste'); + removePasteBin(); + + if (!gotPasteEvent) { + editor.windowManager.alert('Clipboard access not possible.'); + return; + } + + var html = pastebinElm.firstChild.innerHTML; + editor.selection.setRng(lastRng); + processHtml(html); + }); + }); + } else { + editor.on('init', function() { + editor.dom.bind(editor.getBody(), 'paste', function(e) { + e.preventDefault(); + editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.'); + }); + }); + + // Old Gecko/WebKit/Opera fallback + editor.on('keydown', function(e) { + if (VK.metaKeyPressed(e) && e.keyCode == 86 && !e.isDefaultPrevented()) { + var pastebinElm = createPasteBin(); + var lastRng = editor.selection.getRng(); + + editor.selection.select(pastebinElm, true); + + editor.dom.bind(pastebinElm, 'paste', function(e) { + e.stopPropagation(); + + setTimeout(function() { + removePasteBin(); + editor.lastRng = lastRng; + editor.selection.setRng(lastRng); + processHtml(pastebinElm.firstChild.innerHTML); + }, 0); + }); + } + }); + } + } + + // Block all drag/drop events + if (editor.paste_block_drop) { + editor.on('dragend dragover draggesture dragdrop drop drag', function(e) { + e.preventDefault(); + e.stopPropagation(); + }); + } + + this.paste = processHtml; + this.pasteText = processText; + }; +}); + +// Included from: js/tinymce/plugins/paste/classes/WordFilter.js + +/** + * WordFilter.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class parses word HTML into proper TinyMCE markup. + * + * @class tinymce.pasteplugin.Quirks + * @private + */ +define("tinymce/pasteplugin/WordFilter", [ + "tinymce/util/Tools", + "tinymce/html/DomParser", + "tinymce/html/Schema", + "tinymce/html/Serializer", + "tinymce/html/Node" +], function(Tools, DomParser, Schema, Serializer, Node) { + return function(editor) { + var each = Tools.each; + + editor.on('PastePreProcess', function(e) { + var content = e.content, retainStyleProperties, validStyles; + + retainStyleProperties = editor.settings.paste_retain_style_properties; + if (retainStyleProperties) { + validStyles = Tools.makeMap(retainStyleProperties); + } + + function process(items) { + each(items, function(v) { + if (v.constructor == RegExp) { + content = content.replace(v, ''); + } else { + content = content.replace(v[0], v[1]); + } + }); + } + + /** + * Converts fake bullet and numbered lists to real semantic OL/UL. + * + * @param {tinymce.html.Node} node Root node to convert children of. + */ + function convertFakeListsToProperLists(node) { + var currentListNode, prevListNode, lastLevel = 1; + + function convertParagraphToLi(paragraphNode, listStartTextNode, listName, start) { + var level = paragraphNode._listLevel || lastLevel; + + // Handle list nesting + if (level != lastLevel) { + if (level < lastLevel) { + // Move to parent list + if (currentListNode) { + currentListNode = currentListNode.parent.parent; + } + } else { + // Create new list + prevListNode = currentListNode; + currentListNode = null; + } + } + + if (!currentListNode || currentListNode.name != listName) { + prevListNode = prevListNode || currentListNode; + currentListNode = new Node(listName, 1); + + if (start > 1) { + currentListNode.attr('start', '' + start); + } + + paragraphNode.wrap(currentListNode); + } else { + currentListNode.append(paragraphNode); + } + + paragraphNode.name = 'li'; + listStartTextNode.value = ''; + + var nextNode = listStartTextNode.next; + if (nextNode && nextNode.type == 3) { + nextNode.value = nextNode.value.replace(/^\u00a0+/, ''); + } + + // Append list to previous list + if (level > lastLevel) { + prevListNode.lastChild.append(currentListNode); + } + + lastLevel = level; + } + + var paragraphs = node.getAll('p'); + + for (var i = 0; i < paragraphs.length; i++) { + node = paragraphs[i]; + + if (node.name == 'p' && node.firstChild) { + // Find first text node in paragraph + var nodeText = ''; + var listStartTextNode = node.firstChild; + + while (listStartTextNode) { + nodeText = listStartTextNode.value; + if (nodeText) { + break; + } + + listStartTextNode = listStartTextNode.firstChild; + } + + // Detect unordered lists look for bullets + if (/^\s*[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*$/.test(nodeText)) { + convertParagraphToLi(node, listStartTextNode, 'ul'); + continue; + } + + // Detect ordered lists 1., a. or ixv. + if (/^\s*\w+\./.test(nodeText)) { + // Parse OL start number + var matches = /([0-9])\./.exec(nodeText); + var start = 1; + if (matches) { + start = parseInt(matches[1], 10); + } + + convertParagraphToLi(node, listStartTextNode, 'ol', start); + continue; + } + + currentListNode = null; + } + } + } + + function filterStyles(node, styleValue) { + // Parse out list indent level for lists + if (node.name === 'p') { + var matches = /mso-list:\w+ \w+([0-9]+)/.exec(styleValue); + + if (matches) { + node._listLevel = parseInt(matches[1], 10); + } + } + + if (editor.getParam("paste_retain_style_properties", "none")) { + var outputStyle = ""; + + Tools.each(editor.dom.parseStyle(styleValue), function(value, name) { + // Convert various MS styles to W3C styles + switch (name) { + case "horiz-align": + name = "text-align"; + return; + + case "vert-align": + name = "vertical-align"; + return; + + case "font-color": + case "mso-foreground": + name = "color"; + return; + + case "mso-background": + case "mso-highlight": + name = "background"; + break; + } + + // Output only valid styles + if (retainStyleProperties == "all" || (validStyles && validStyles[name])) { + outputStyle += name + ':' + value + ';'; + } + }); + + if (outputStyle) { + return outputStyle; + } + } + + return null; + } + + if (editor.settings.paste_enable_default_filters === false) { + return; + } + + // Detect is the contents is Word junk HTML + if (/class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i.test(e.content)) { + e.wordContent = true; // Mark it for other processors + + // Remove basic Word junk + process([ + // Word comments like conditional comments etc + //gi, + + // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, + // MS Office namespaced tags, and a few other tags + /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, + + // Convert into for line-though + [/<(\/?)s>/gi, "<$1strike>"], + + // Replace nsbp entites to char since it's easier to handle + [/ /gi, "\u00a0"], + + // Convert ___ to string of alternating + // breaking/non-breaking spaces of same length + [/([\s\u00a0]*)<\/span>/gi, + function(str, spaces) { + return (spaces.length > 0) ? + spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : ""; + } + ] + ]); + + // Setup strict schema + var schema = new Schema({ + valid_elements: '@[style],-strong/b,-em/i,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,-table,' + + '-tr,-td[colspan|rowspan],-th,-thead,-tfoot,-tbody,-a[!href]' + }); + + // Parse HTML into DOM structure + var domParser = new DomParser({}, schema); + + // Filte element style attributes + domParser.addAttributeFilter('style', function(nodes) { + var i = nodes.length, node; + + while (i--) { + node = nodes[i]; + node.attr('style', filterStyles(node, node.attr('style'))); + + // Remove pointess spans + if (node.name == 'span' && !node.attributes.length) { + node.unwrap(); + } + } + }); + + // Parse into DOM structure + var rootNode = domParser.parse(content); + + // Process DOM + convertFakeListsToProperLists(rootNode); + + // Serialize DOM back to HTML + e.content = new Serializer({}, schema).serialize(rootNode); + } + }); + }; +}); + +// Included from: js/tinymce/plugins/paste/classes/Quirks.js + +/** + * Quirks.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class contains various fixes for browsers. These issues can not be feature + * detected since we have no direct control over the clipboard. However we might be able + * to remove some of these fixes once the browsers gets updated/fixed. + * + * @class tinymce.pasteplugin.Quirks + * @private + */ +define("tinymce/pasteplugin/Quirks", [ + "tinymce/Env", + "tinymce/util/Tools" +], function(Env, Tools) { + return function(editor) { + function addPreProcessFilter(filterFunc) { + editor.on('PastePreProcess', function(e) { + e.content = filterFunc(e.content); + }); + } + + function process(content, items) { + Tools.each(items, function(v) { + if (v.constructor == RegExp) { + content = content.replace(v, ''); + } else { + content = content.replace(v[0], v[1]); + } + }); + + return content; + } + + /** + * Removes WebKit fragment comments and converted-space spans. + * + * This: + * a b + * + * Becomes: + * a b + */ + function removeWebKitFragments(html) { + html = process(html, [ + /^[\s\S]*|[\s\S]*$/g, // WebKit fragment + [/\u00a0<\/span>/g, '\u00a0'], // WebKit   + /
    $/ // Traling BR elements + ]); + + return html; + } + + /** + * Removes BR elements after block elements. IE9 has a nasty bug where it puts a BR element after each + * block element when pasting from word. This removes those elements. + * + * This: + *

    a


    b

    + * + * Becomes: + *

    a

    b

    + */ + function removeExplorerBrElementsAfterBlocks(html) { + // Produce block regexp based on the block elements in schema + if (!this.explorerBlocksRegExp) { + var blockElements = []; + + Tools.each(editor.schema.getBlockElements(), function(block, blockName) { + blockElements.push(blockName); + }); + + this.explorerBlocksRegExp = new RegExp( + '(?:
     [\\s\\r\\n]+|
    )*(<\/?(' + blockElements.join('|') + ')[^>]*>)(?:
     [\\s\\r\\n]+|
    )*', + 'g' + ); + } + + // Remove BR:s from: X
    + html = process(html, [ + [this.explorerBlocksRegExp, '$1'] + ]); + + // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break + html = process(html, [ + [/

    /g, '

    '], // Replace multiple BR elements with uppercase BR to keep them intact + [/
    /g, ' '], // Replace single br elements with space since they are word wrap BR:s + [/

    /g, '
    '] // Replace back the double brs but into a single BR + ]); + + return html; + } + + // Sniff browsers and apply fixes since we can't feature detect + if (Env.webkit) { + addPreProcessFilter(removeWebKitFragments); + } + + if (Env.ie) { + addPreProcessFilter(removeExplorerBrElementsAfterBlocks); + } + }; +}); + +// Included from: js/tinymce/plugins/paste/classes/Plugin.js + +/** + * Plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class contains the tinymce plugin logic for the paste plugin. + * + * @class tinymce.pasteplugin.Plugin + * @private + */ +define("tinymce/pasteplugin/Plugin", [ + "tinymce/PluginManager", + "tinymce/pasteplugin/Clipboard", + "tinymce/pasteplugin/WordFilter", + "tinymce/pasteplugin/Quirks" +], function(PluginManager, Clipboard, WordFilter, Quirks) { + PluginManager.add('paste', function(editor) { + var self = this; + + self.clipboard = new Clipboard(editor); + self.quirks = new Quirks(editor); + self.wordFilter = new WordFilter(editor); + + editor.addCommand('mceInsertClipboardContent', function(ui, value) { + if (value.content) { + self.clipboard.paste(value.content); + } + + if (value.text) { + self.clipboard.pasteText(value.text); + } + }); + }); +}); + +expose(["tinymce/pasteplugin/Clipboard","tinymce/pasteplugin/WordFilter","tinymce/pasteplugin/Quirks","tinymce/pasteplugin/Plugin"]); +})(this); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/paste/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/paste/plugin.min.js new file mode 100644 index 00000000..a99a1322 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/paste/plugin.min.js @@ -0,0 +1 @@ +(function(e,t){"use strict";function n(e,t){for(var n,i=[],r=0;e.length>r;++r){if(n=s[e[r]]||o(e[r]),!n)throw"module definition dependecy not found: "+e[r];i.push(n)}t.apply(null,i)}function i(e,i,r){if("string"!=typeof e)throw"invalid module definition, module id must be defined and be a string";if(i===t)throw"invalid module definition, dependencies must be specified";if(r===t)throw"invalid module definition, definition function must be specified";n(i,function(){s[e]=r.apply(null,arguments)})}function r(e){return!!s[e]}function o(t){for(var n=e,i=t.split(/[.\/]/),r=0;i.length>r;++r){if(!n[i[r]])return;n=n[i[r]]}return n}function a(n){for(var i=0;n.length>i;i++){for(var r=e,o=n[i],a=o.split(/[.\/]/),l=0;a.length-1>l;++l)r[a[l]]===t&&(r[a[l]]={}),r=r[a[l]];r[a[a.length-1]]=s[o]}}var s={},l="tinymce/pasteplugin/Clipboard",c="tinymce/Env",u="tinymce/util/Tools",p="tinymce/util/VK",d="tinymce/pasteplugin/WordFilter",f="tinymce/html/DomParser",g="tinymce/html/Schema",m="tinymce/html/Serializer",h="tinymce/html/Node",v="tinymce/pasteplugin/Quirks",b="tinymce/pasteplugin/Plugin",y="tinymce/PluginManager";i(l,[c,u,p],function(e,n,i){function r(){return!e.gecko&&("ClipboardEvent"in window||e.webkit&&"FocusEvent"in window)}return function(o){function a(){return 100>(new Date).getTime()-d}function s(e,t){return n.each(t,function(t){e=t.constructor==RegExp?e.replace(t,""):e.replace(t[0],t[1])}),e}function l(t){var n=o.fire("PastePreProcess",{content:t});(o.settings.paste_remove_styles||o.settings.paste_remove_styles_if_webkit!==!1&&e.webkit)&&(n.content=n.content.replace(/ style=\"[^\"]+\"/g,"")),n.isDefaultPrevented()||o.insertContent(n.content)}function c(e){e=o.dom.encode(e),e=s(e,[[/\n\n/g,"

    "],[/^(.*<\/p>)(

    )$/,"

    $1"],[/\n/g,"
    "]]);var t=o.fire("PastePreProcess",{content:e});t.isDefaultPrevented()||o.insertContent(t.content)}function u(){var e=(o.inline?o.getBody():o.getDoc().documentElement).scrollTop,t=o.dom.add(o.getBody(),"div",{id:"mcePasteBin",contentEditable:!1,style:"position: absolute; top: "+e+"px; left: 0; background: red; width: 1px; height: 1px; overflow: hidden"},'

    X
    ');return t}function p(){var e=o.dom.get("mcePasteBin");o.dom.unbind(e),o.dom.remove(e)}var d;o.on("keydown",function(e){e.shiftKey&&86==e.keyCode&&(d=(new Date).getTime())}),r()?o.on("paste",function(e){function t(e,t){for(var i=0;n.types.length>i;i++)if(n.types[i]==e)return t(n.getData(e)),!0}var n=e.clipboardData;n&&(e.preventDefault(),a()?t("text/plain",c)||t("text/html",l):t("text/html",l)||t("text/plain",c))}):e.ie?o.on("init",function(){var e=o.dom;o.dom.bind(o.getBody(),"paste",function(n){var i;if(n.preventDefault(),a()&&e.doc.dataTransfer)return c(e.doc.dataTransfer.getData("Text")),t;var r=u();e.bind(r,"paste",function(e){e.stopPropagation(),i=!0});var s=o.selection.getRng(),d=e.doc.body.createTextRange();if(d.moveToElementText(r.firstChild),d.execCommand("Paste"),p(),!i)return o.windowManager.alert("Clipboard access not possible."),t;var f=r.firstChild.innerHTML;o.selection.setRng(s),l(f)})}):(o.on("init",function(){o.dom.bind(o.getBody(),"paste",function(e){e.preventDefault(),o.windowManager.alert("Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.")})}),o.on("keydown",function(e){if(i.metaKeyPressed(e)&&86==e.keyCode&&!e.isDefaultPrevented()){var t=u(),n=o.selection.getRng();o.selection.select(t,!0),o.dom.bind(t,"paste",function(e){e.stopPropagation(),setTimeout(function(){p(),o.lastRng=n,o.selection.setRng(n),l(t.firstChild.innerHTML)},0)})}})),o.paste_block_drop&&o.on("dragend dragover draggesture dragdrop drop drag",function(e){e.preventDefault(),e.stopPropagation()}),this.paste=l,this.pasteText=c}}),i(d,[u,f,g,m,h],function(e,n,i,r,o){return function(a){var s=e.each;a.on("PastePreProcess",function(l){function c(e){s(e,function(e){d=e.constructor==RegExp?d.replace(e,""):d.replace(e[0],e[1])})}function u(e){function t(e,t,a,s){var l=e._listLevel||r;l!=r&&(r>l?n&&(n=n.parent.parent):(i=n,n=null)),n&&n.name==a?n.append(e):(i=i||n,n=new o(a,1),s>1&&n.attr("start",""+s),e.wrap(n)),e.name="li",t.value="";var c=t.next;c&&3==c.type&&(c.value=c.value.replace(/^\u00a0+/,"")),l>r&&i.lastChild.append(n),r=l}for(var n,i,r=1,a=e.getAll("p"),s=0;a.length>s;s++)if(e=a[s],"p"==e.name&&e.firstChild){for(var l="",c=e.firstChild;c&&!(l=c.value);)c=c.firstChild;if(/^\s*[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*$/.test(l)){t(e,c,"ul");continue}if(/^\s*\w+\./.test(l)){var u=/([0-9])\./.exec(l),p=1;u&&(p=parseInt(u[1],10)),t(e,c,"ol",p);continue}n=null}}function p(n,i){if("p"===n.name){var r=/mso-list:\w+ \w+([0-9]+)/.exec(i);r&&(n._listLevel=parseInt(r[1],10))}if(a.getParam("paste_retain_style_properties","none")){var o="";if(e.each(a.dom.parseStyle(i),function(e,n){switch(n){case"horiz-align":return n="text-align",t;case"vert-align":return n="vertical-align",t;case"font-color":case"mso-foreground":return n="color",t;case"mso-background":case"mso-highlight":n="background"}("all"==f||g&&g[n])&&(o+=n+":"+e+";")}),o)return o}return null}var d=l.content,f,g;if(f=a.settings.paste_retain_style_properties,f&&(g=e.makeMap(f)),a.settings.paste_enable_default_filters!==!1&&/class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i.test(l.content)){l.wordContent=!0,c([//gi,/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,[/<(\/?)s>/gi,"<$1strike>"],[/ /gi,"\u00a0"],[/([\s\u00a0]*)<\/span>/gi,function(e,t){return t.length>0?t.replace(/./," ").slice(Math.floor(t.length/2)).split("").join("\u00a0"):""}]]);var m=new i({valid_elements:"@[style],-strong/b,-em/i,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,-table,-tr,-td[colspan|rowspan],-th,-thead,-tfoot,-tbody,-a[!href]"}),h=new n({},m);h.addAttributeFilter("style",function(e){for(var t=e.length,n;t--;)n=e[t],n.attr("style",p(n,n.attr("style"))),"span"!=n.name||n.attributes.length||n.unwrap()});var v=h.parse(d);u(v),l.content=new r({},m).serialize(v)}})}}),i(v,[c,u],function(e,t){return function(n){function i(e){n.on("PastePreProcess",function(t){t.content=e(t.content)})}function r(e,n){return t.each(n,function(t){e=t.constructor==RegExp?e.replace(t,""):e.replace(t[0],t[1])}),e}function o(e){return e=r(e,[/^[\s\S]*|[\s\S]*$/g,[/\u00a0<\/span>/g,"\u00a0"],/
    $/])}function a(e){if(!this.explorerBlocksRegExp){var i=[];t.each(n.schema.getBlockElements(),function(e,t){i.push(t)}),this.explorerBlocksRegExp=RegExp("(?:
     [\\s\\r\\n]+|
    )*(]*>)(?:
     [\\s\\r\\n]+|
    )*","g")}return e=r(e,[[this.explorerBlocksRegExp,"$1"]]),e=r(e,[[/

    /g,"

    "],[/
    /g," "],[/

    /g,"
    "]])}e.webkit&&i(o),e.ie&&i(a)}}),i(b,[y,l,d,v],function(e,t,n,i){e.add("paste",function(e){var r=this;r.clipboard=new t(e),r.quirks=new i(e),r.wordFilter=new n(e),e.addCommand("mceInsertClipboardContent",function(e,t){t.content&&r.clipboard.paste(t.content),t.text&&r.clipboard.pasteText(t.text)})})}),a([l,d,v,b])})(this); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/preview/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/preview/plugin.js new file mode 100644 index 00000000..42b28fb0 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/preview/plugin.js @@ -0,0 +1,62 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('preview', function(editor) { + editor.addCommand('mcePreview', function() { + editor.windowManager.open({ + title: 'Preview', + width : parseInt(editor.getParam("plugin_preview_width", "650"), 10), + height : parseInt(editor.getParam("plugin_preview_height", "500"), 10), + html: '', + buttons: { + text: 'Close', + onclick: function() { + this.parent().parent().close(); + } + }, + onPostRender: function() { + var doc = this.getEl('body').firstChild.contentWindow.document, previewHtml, headHtml = ''; + + tinymce.each(tinymce.explode(editor.settings.content_css), function(url) { + headHtml += ''; + }); + + previewHtml = ( + '' + + '' + + '' + + headHtml + + '' + + '' + + editor.getContent() + + '' + + '' + ); + + doc.open(); + doc.write(previewHtml); + doc.close(); + } + }); + }); + + editor.addButton('preview', { + title : 'Preview', + cmd : 'mcePreview' + }); + + editor.addMenuItem('preview', { + text : 'Preview', + cmd : 'mcePreview', + context: 'view' + }); +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/preview/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/preview/plugin.min.js new file mode 100644 index 00000000..a16b2593 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/preview/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("preview",function(e){e.addCommand("mcePreview",function(){e.windowManager.open({title:"Preview",width:parseInt(e.getParam("plugin_preview_width","650"),10),height:parseInt(e.getParam("plugin_preview_height","500"),10),html:"",buttons:{text:"Close",onclick:function(){this.parent().parent().close()}},onPostRender:function(){var t,n=this.getEl("body").firstChild.contentWindow.document,i="";tinymce.each(tinymce.explode(e.settings.content_css),function(t){i+=''}),t=""+i+""+""+e.getContent()+""+"",n.open(),n.write(t),n.close()}})}),e.addButton("preview",{title:"Preview",cmd:"mcePreview"}),e.addMenuItem("preview",{text:"Preview",cmd:"mcePreview",context:"view"})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/print/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/print/plugin.js new file mode 100644 index 00000000..54c23d07 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/print/plugin.js @@ -0,0 +1,27 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('print',function(editor) { + editor.addCommand('mcePrint', function() { + editor.getWin().print(); + }); + + editor.addButton('print', {title: 'Print', cmd: 'mcePrint'}); + + editor.addMenuItem('print', { + text: 'Print', + cmd: 'mcePrint', + icon: 'print', + shortcut: 'Ctrl+P', + context: 'file' + }); +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/print/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/print/plugin.min.js new file mode 100644 index 00000000..0b520b87 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/print/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("print",function(e){e.addCommand("mcePrint",function(){e.getWin().print()}),e.addButton("print",{title:"Print",cmd:"mcePrint"}),e.addMenuItem("print",{text:"Print",cmd:"mcePrint",icon:"print",shortcut:"Ctrl+P",context:"file"})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/save/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/save/plugin.js new file mode 100644 index 00000000..80ff998a --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/save/plugin.js @@ -0,0 +1,93 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('save', function(editor) { + function save() { + var formObj, os; + + formObj = tinymce.DOM.getParent(editor.id, 'form'); + + if (editor.getParam("save_enablewhendirty") && !editor.isDirty()) { + return; + } + + tinymce.triggerSave(); + + // Use callback instead + if ((os = editor.getParam("save_onsavecallback"))) { + if (editor.execCallback('save_onsavecallback', editor)) { + editor.startContent = tinymce.trim(editor.getContent({format: 'raw'})); + editor.nodeChanged(); + } + + return; + } + + if (formObj) { + editor.isNotDirty = true; + + if (!formObj.onsubmit || formObj.onsubmit()) { + if (typeof(formObj.submit) == "function") { + formObj.submit(); + } else { + editor.windowManager.alert("Error: Form submit field collision."); + } + } + + editor.nodeChanged(); + } else { + editor.windowManager.alert("Error: No form element found."); + } + } + + function cancel() { + var os, h = tinymce.trim(editor.startContent); + + // Use callback instead + if ((os = editor.getParam("save_oncancelcallback"))) { + editor.execCallback('save_oncancelcallback', editor); + return; + } + + editor.setContent(h); + editor.undoManager.clear(); + editor.nodeChanged(); + } + + function stateToggle() { + var self = this; + + editor.on('nodeChange', function() { + self.disabled(!editor.isDirty()); + }); + } + + editor.addCommand('mceSave', save); + editor.addCommand('mceCancel', cancel); + + editor.addButton('save', { + text: 'Save', + cmd: 'mceSave', + disabled: true, + onPostRender: stateToggle + }); + + editor.addButton('cancel', { + text: 'Cancel', + icon: false, + cmd: 'mceCancel', + disabled: true, + onPostRender: stateToggle + }); + + editor.addShortcut('ctrl+s', '', 'mceSave'); +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/save/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/save/plugin.min.js new file mode 100644 index 00000000..949dd59a --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/save/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("save",function(e){function t(){var t,n;return t=tinymce.DOM.getParent(e.id,"form"),!e.getParam("save_enablewhendirty")||e.isDirty()?(tinymce.triggerSave(),(n=e.getParam("save_onsavecallback"))?(e.execCallback("save_onsavecallback",e)&&(e.startContent=tinymce.trim(e.getContent({format:"raw"})),e.nodeChanged()),void 0):(t?(e.isNotDirty=!0,(!t.onsubmit||t.onsubmit())&&("function"==typeof t.submit?t.submit():e.windowManager.alert("Error: Form submit field collision.")),e.nodeChanged()):e.windowManager.alert("Error: No form element found."),void 0)):void 0}function n(){var t,n=tinymce.trim(e.startContent);return(t=e.getParam("save_oncancelcallback"))?(e.execCallback("save_oncancelcallback",e),void 0):(e.setContent(n),e.undoManager.clear(),e.nodeChanged(),void 0)}function i(){var t=this;e.on("nodeChange",function(){t.disabled(!e.isDirty())})}e.addCommand("mceSave",t),e.addCommand("mceCancel",n),e.addButton("save",{text:"Save",cmd:"mceSave",disabled:!0,onPostRender:i}),e.addButton("cancel",{text:"Cancel",icon:!1,cmd:"mceCancel",disabled:!0,onPostRender:i}),e.addShortcut("ctrl+s","","mceSave")}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/searchreplace/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/searchreplace/plugin.js new file mode 100644 index 00000000..f3ede6be --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/searchreplace/plugin.js @@ -0,0 +1,533 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint smarttabs:true, undef:true, unused:true, latedef:true, curly:true, bitwise:true */ +/*global tinymce:true */ + +(function() { + // Based on work developed by: James Padolsey http://james.padolsey.com + // released under UNLICENSE that is compatible with LGPL + // TODO: Handle contentEditable edgecase: + //

    texttexttexttexttext

    + function findAndReplaceDOMText(regex, node, replacementNode, captureGroup, schema) { + var m, matches = [], text, count = 0, doc; + var blockElementsMap, hiddenTextElementsMap, shortEndedElementsMap; + + doc = node.ownerDocument; + blockElementsMap = schema.getBlockElements(); // H1-H6, P, TD etc + hiddenTextElementsMap = schema.getWhiteSpaceElements(); // TEXTAREA, PRE, STYLE, SCRIPT + shortEndedElementsMap = schema.getShortEndedElements(); // BR, IMG, INPUT + + function getMatchIndexes(m, captureGroup) { + captureGroup = captureGroup || 0; + + if (!m[0]) { + throw 'findAndReplaceDOMText cannot handle zero-length matches'; + } + + var index = m.index; + + if (captureGroup > 0) { + var cg = m[captureGroup]; + + if (!cg) { + throw 'Invalid capture group'; + } + + index += m[0].indexOf(cg); + m[0] = cg; + } + + return [index, index + m[0].length, [m[0]]]; + } + + function getText(node) { + var txt; + + if (node.nodeType === 3) { + return node.data; + } + + if (hiddenTextElementsMap[node.nodeName]) { + return ''; + } + + txt = ''; + + if (blockElementsMap[node.nodeName] || shortEndedElementsMap[node.nodeName]) { + txt += '\n'; + } + + if ((node = node.firstChild)) { + do { + txt += getText(node); + } while ((node = node.nextSibling)); + } + + return txt; + } + + function stepThroughMatches(node, matches, replaceFn) { + var startNode, endNode, startNodeIndex, + endNodeIndex, innerNodes = [], atIndex = 0, curNode = node, + matchLocation = matches.shift(), matchIndex = 0; + + out: while (true) { + if (blockElementsMap[curNode.nodeName] || shortEndedElementsMap[curNode.nodeName]) { + atIndex++; + } + + if (curNode.nodeType === 3) { + if (!endNode && curNode.length + atIndex >= matchLocation[1]) { + // We've found the ending + endNode = curNode; + endNodeIndex = matchLocation[1] - atIndex; + } else if (startNode) { + // Intersecting node + innerNodes.push(curNode); + } + + if (!startNode && curNode.length + atIndex > matchLocation[0]) { + // We've found the match start + startNode = curNode; + startNodeIndex = matchLocation[0] - atIndex; + } + + atIndex += curNode.length; + } + + if (startNode && endNode) { + curNode = replaceFn({ + startNode: startNode, + startNodeIndex: startNodeIndex, + endNode: endNode, + endNodeIndex: endNodeIndex, + innerNodes: innerNodes, + match: matchLocation[2], + matchIndex: matchIndex + }); + + // replaceFn has to return the node that replaced the endNode + // and then we step back so we can continue from the end of the + // match: + atIndex -= (endNode.length - endNodeIndex); + startNode = null; + endNode = null; + innerNodes = []; + matchLocation = matches.shift(); + matchIndex++; + + if (!matchLocation) { + break; // no more matches + } + } else if (!hiddenTextElementsMap[curNode.nodeName] && curNode.firstChild) { + // Move down + curNode = curNode.firstChild; + continue; + } else if (curNode.nextSibling) { + // Move forward: + curNode = curNode.nextSibling; + continue; + } + + // Move forward or up: + while (true) { + if (curNode.nextSibling) { + curNode = curNode.nextSibling; + break; + } else if (curNode.parentNode !== node) { + curNode = curNode.parentNode; + } else { + break out; + } + } + } + } + + /** + * Generates the actual replaceFn which splits up text nodes + * and inserts the replacement element. + */ + function genReplacer(nodeName) { + var makeReplacementNode; + + if (typeof nodeName != 'function') { + var stencilNode = nodeName.nodeType ? nodeName : doc.createElement(nodeName); + + makeReplacementNode = function(fill, matchIndex) { + var clone = stencilNode.cloneNode(false); + + clone.setAttribute('data-mce-index', matchIndex); + + if (fill) { + clone.appendChild(doc.createTextNode(fill)); + } + + return clone; + }; + } else { + makeReplacementNode = nodeName; + } + + return function replace(range) { + var before, after, parentNode, startNode = range.startNode, + endNode = range.endNode, matchIndex = range.matchIndex; + + if (startNode === endNode) { + var node = startNode; + + parentNode = node.parentNode; + if (range.startNodeIndex > 0) { + // Add `before` text node (before the match) + before = doc.createTextNode(node.data.substring(0, range.startNodeIndex)); + parentNode.insertBefore(before, node); + } + + // Create the replacement node: + var el = makeReplacementNode(range.match[0], matchIndex); + parentNode.insertBefore(el, node); + if (range.endNodeIndex < node.length) { + // Add `after` text node (after the match) + after = doc.createTextNode(node.data.substring(range.endNodeIndex)); + parentNode.insertBefore(after, node); + } + + node.parentNode.removeChild(node); + + return el; + } else { + // Replace startNode -> [innerNodes...] -> endNode (in that order) + before = doc.createTextNode(startNode.data.substring(0, range.startNodeIndex)); + after = doc.createTextNode(endNode.data.substring(range.endNodeIndex)); + var elA = makeReplacementNode(startNode.data.substring(range.startNodeIndex), matchIndex); + var innerEls = []; + + for (var i = 0, l = range.innerNodes.length; i < l; ++i) { + var innerNode = range.innerNodes[i]; + var innerEl = makeReplacementNode(innerNode.data, matchIndex); + innerNode.parentNode.replaceChild(innerEl, innerNode); + innerEls.push(innerEl); + } + + var elB = makeReplacementNode(endNode.data.substring(0, range.endNodeIndex), matchIndex); + + parentNode = startNode.parentNode; + parentNode.insertBefore(before, startNode); + parentNode.insertBefore(elA, startNode); + parentNode.removeChild(startNode); + + parentNode = endNode.parentNode; + parentNode.insertBefore(elB, endNode); + parentNode.insertBefore(after, endNode); + parentNode.removeChild(endNode); + + return elB; + } + }; + } + + text = getText(node); + if (!text) { + return; + } + + if (regex.global) { + while ((m = regex.exec(text))) { + matches.push(getMatchIndexes(m, captureGroup)); + } + } else { + m = text.match(regex); + matches.push(getMatchIndexes(m, captureGroup)); + } + + if (matches.length) { + count = matches.length; + stepThroughMatches(node, matches, genReplacer(replacementNode)); + } + + return count; + } + + function Plugin(editor) { + var self = this, currentIndex = -1, spellcheckerEnabled; + + function showDialog() { + var win = tinymce.ui.Factory.create({ + type: 'window', + layout: "flex", + pack: "center", + align: "center", + onClose: function() { + editor.focus(); + spellcheckerEnabled = false; + self.unmarkAllMatches(); + }, + buttons: [ + {text: "Find", onclick: function() { + win.find('form')[0].submit(); + }}, + {text: "Replace", disabled: true, onclick: function() { + if (!self.replace(win.find('#replace').value())) { + win.statusbar.items().slice(1).disabled(true); + } + }}, + {text: "Replace all", disabled: true, onclick: function() { + self.replaceAll(win.find('#replace').value()); + win.statusbar.items().slice(1).disabled(true); + }}, + {type: "spacer", flex: 1}, + {text: "Prev", disabled: true, onclick: function() { + self.prev(); + }}, + {text: "Next", disabled: true, onclick: function() { + self.next(); + }} + ], + title: "Find and replace", + items: { + type: "form", + padding: 20, + labelGap: 30, + spacing: 10, + onsubmit: function(e) { + var count, regEx, caseState, text, wholeWord; + + e.preventDefault(); + + caseState = win.find('#case').checked(); + wholeWord = win.find('#words').checked(); + + text = win.find('#find').value(); + if (!text.length) { + self.unmarkAllMatches(); + win.statusbar.items().slice(1).disabled(true); + return; + } + + text = text.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); + text = wholeWord ? '\\b' + text + '\\b' : text; + regEx = new RegExp(text, caseState ? 'g' : 'gi'); + count = self.markAllMatches(regEx); + + if (count) { + self.first(); + } else { + tinymce.ui.MessageBox.alert('Could not find the specified string.'); + } + + win.statusbar.items().slice(1).disabled(count === 0); + }, + items: [ + {type: 'textbox', name: 'find', size: 40, label: 'Find', value: editor.selection.getNode().src}, + {type: 'textbox', name: 'replace', size: 40, label: 'Replace with'}, + {type: 'checkbox', name: 'case', text: 'Match case', label: ' '}, + {type: 'checkbox', name: 'words', text: 'Whole words', label: ' '} + ] + } + }).renderTo().reflow(); + + spellcheckerEnabled = true; + } + + self.init = function(ed) { + ed.addMenuItem('searchreplace', { + text: 'Find and replace', + shortcut: 'Ctrl+F', + onclick: showDialog, + separator: 'before', + context: 'edit' + }); + + ed.addButton('searchreplace', { + tooltip: 'Find and replace', + shortcut: 'Ctrl+F', + onclick: showDialog + }); + + ed.shortcuts.add('Ctrl+F', '', showDialog); + }; + + self.markAllMatches = function(regex) { + var node, marker; + + marker = editor.dom.create('span', { + "class": 'mce-match-marker', + "data-mce-bogus": 1 + }); + + node = editor.getBody(); + + self.unmarkAllMatches(node); + + return findAndReplaceDOMText(regex, node, marker, false, editor.schema); + }; + + function unwrap(node) { + var parentNode = node.parentNode; + parentNode.insertBefore(node.firstChild, node); + node.parentNode.removeChild(node); + } + + function moveSelection(forward, fromStart) { + var selection = editor.selection, rng = selection.getRng(true), currentIndex = -1, + startContainer, endContainer; + + forward = forward !== false; + + function walkToIndex() { + var node, walker; + + if (fromStart) { + node = editor.getBody()[forward ? 'firstChild' : 'lastChild']; + } else { + node = rng[forward ? 'endContainer' : 'startContainer']; + } + + walker = new tinymce.dom.TreeWalker(node, editor.getBody()); + + while ((node = walker.current())) { + if (node.nodeType == 1 && node.nodeName == "SPAN" && node.getAttribute('data-mce-index') !== null) { + currentIndex = node.getAttribute('data-mce-index'); + startContainer = node.firstChild; + + while ((node = walker.current())) { + if (node.nodeType == 1 && node.nodeName == "SPAN" && node.getAttribute('data-mce-index') !== null) { + if (node.getAttribute('data-mce-index') === currentIndex) { + endContainer = node.firstChild; + } else { + return; + } + } + + walker[forward ? 'next' : 'prev'](); + } + } + + walker[forward ? 'next' : 'prev'](); + } + } + + walkToIndex(); + + if (startContainer && endContainer) { + editor.focus(); + + if (forward) { + rng.setStart(startContainer, 0); + rng.setEnd(endContainer, endContainer.length); + } else { + rng.setStart(endContainer, 0); + rng.setEnd(startContainer, startContainer.length); + } + + selection.scrollIntoView(startContainer.parentNode); + selection.setRng(rng); + } + + return currentIndex; + } + + function removeNode(node) { + node.parentNode.removeChild(node); + } + + self.first = function() { + currentIndex = moveSelection(true, true); + return currentIndex !== -1; + }; + + self.next = function() { + currentIndex = moveSelection(true); + return currentIndex !== -1; + }; + + self.prev = function() { + currentIndex = moveSelection(false); + return currentIndex !== -1; + }; + + self.replace = function(text, forward, all) { + var i, nodes, node, matchIndex, currentMatchIndex, nextIndex; + + if (currentIndex === -1) { + currentIndex = moveSelection(forward); + } + + nextIndex = moveSelection(forward); + + node = editor.getBody(); + nodes = tinymce.toArray(node.getElementsByTagName('span')); + if (nodes.length) { + for (i = 0; i < nodes.length; i++) { + matchIndex = currentMatchIndex = nodes[i].getAttribute('data-mce-index'); + if (all || matchIndex === currentIndex) { + if (text.length) { + nodes[i].firstChild.nodeValue = text; + unwrap(nodes[i]); + } else { + removeNode(nodes[i]); + } + + while (nodes[++i]) { + matchIndex = nodes[i].getAttribute('data-mce-index'); + if (matchIndex === currentMatchIndex) { + removeNode(nodes[i]); + } else { + i--; + break; + } + } + } + } + } + + if (nextIndex == -1) { + nextIndex = moveSelection(forward, true); + } + + currentIndex = nextIndex; + + if (all) { + editor.selection.setCursorLocation(editor.getBody(), 0); + } + + editor.undoManager.add(); + + return currentIndex !== -1; + }; + + self.replaceAll = function(text) { + self.replace(text, true, true); + }; + + self.unmarkAllMatches = function() { + var i, nodes, node; + + node = editor.getBody(); + nodes = node.getElementsByTagName('span'); + i = nodes.length; + while (i--) { + node = nodes[i]; + if (node.getAttribute('data-mce-index')) { + unwrap(node); + } + } + }; + + editor.on('beforeaddundo keydown', function(e) { + if (spellcheckerEnabled) { + e.preventDefault(); + return false; + } + }); + } + + tinymce.PluginManager.add('searchreplace', Plugin); +})(); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/searchreplace/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/searchreplace/plugin.min.js new file mode 100644 index 00000000..5d4436fe --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/searchreplace/plugin.min.js @@ -0,0 +1 @@ +(function(){function e(e,t,n,i,a){function o(e,t){if(t=t||0,!e[0])throw"findAndReplaceDOMText cannot handle zero-length matches";var n=e.index;if(t>0){var i=e[t];if(!i)throw"Invalid capture group";n+=e[0].indexOf(i),e[0]=i}return[n,n+e[0].length,[e[0]]]}function r(e){var t;if(3===e.nodeType)return e.data;if(f[e.nodeName])return"";if(t="",(m[e.nodeName]||g[e.nodeName])&&(t+="\n"),e=e.firstChild)do t+=r(e);while(e=e.nextSibling);return t}function l(e,t,n){var i,a,o,r,l=[],c=0,s=e,d=t.shift(),u=0;e:for(;;){if((m[s.nodeName]||g[s.nodeName])&&c++,3===s.nodeType&&(!a&&s.length+c>=d[1]?(a=s,r=d[1]-c):i&&l.push(s),!i&&s.length+c>d[0]&&(i=s,o=d[0]-c),c+=s.length),i&&a){if(s=n({startNode:i,startNodeIndex:o,endNode:a,endNodeIndex:r,innerNodes:l,match:d[2],matchIndex:u}),c-=a.length-r,i=null,a=null,l=[],d=t.shift(),u++,!d)break}else{if(!f[s.nodeName]&&s.firstChild){s=s.firstChild;continue}if(s.nextSibling){s=s.nextSibling;continue}}for(;;){if(s.nextSibling){s=s.nextSibling;break}if(s.parentNode===e)break e;s=s.parentNode}}}function c(e){var t;if("function"!=typeof e){var n=e.nodeType?e:u.createElement(e);t=function(e,t){var i=n.cloneNode(!1);return i.setAttribute("data-mce-index",t),e&&i.appendChild(u.createTextNode(e)),i}}else t=e;return function(e){var n,i,a,o=e.startNode,r=e.endNode,l=e.matchIndex;if(o===r){var c=o;a=c.parentNode,e.startNodeIndex>0&&(n=u.createTextNode(c.data.substring(0,e.startNodeIndex)),a.insertBefore(n,c));var s=t(e.match[0],l);return a.insertBefore(s,c),e.endNodeIndexf;++f){var p=e.innerNodes[f],h=t(p.data,l);p.parentNode.replaceChild(h,p),m.push(h)}var y=t(r.data.substring(0,e.endNodeIndex),l);return a=o.parentNode,a.insertBefore(n,o),a.insertBefore(d,o),a.removeChild(o),a=r.parentNode,a.insertBefore(y,r),a.insertBefore(i,r),a.removeChild(r),y}}var s,d,u,m,f,g,p=[],h=0;if(u=t.ownerDocument,m=a.getBlockElements(),f=a.getWhiteSpaceElements(),g=a.getShortEndedElements(),d=r(t)){if(e.global)for(;s=e.exec(d);)p.push(o(s,i));else s=d.match(e),p.push(o(s,i));return p.length&&(h=p.length,l(t,p,c(n))),h}}function t(t){function n(){var e=tinymce.ui.Factory.create({type:"window",layout:"flex",pack:"center",align:"center",onClose:function(){t.focus(),r=!1,l.unmarkAllMatches()},buttons:[{text:"Find",onclick:function(){e.find("form")[0].submit()}},{text:"Replace",disabled:!0,onclick:function(){l.replace(e.find("#replace").value())||e.statusbar.items().slice(1).disabled(!0)}},{text:"Replace all",disabled:!0,onclick:function(){l.replaceAll(e.find("#replace").value()),e.statusbar.items().slice(1).disabled(!0)}},{type:"spacer",flex:1},{text:"Prev",disabled:!0,onclick:function(){l.prev()}},{text:"Next",disabled:!0,onclick:function(){l.next()}}],title:"Find and replace",items:{type:"form",padding:20,labelGap:30,spacing:10,onsubmit:function(t){var n,i,a,o,r;return t.preventDefault(),a=e.find("#case").checked(),r=e.find("#words").checked(),o=e.find("#find").value(),o.length?(o=o.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),o=r?"\\b"+o+"\\b":o,i=RegExp(o,a?"g":"gi"),n=l.markAllMatches(i),n?l.first():tinymce.ui.MessageBox.alert("Could not find the specified string."),e.statusbar.items().slice(1).disabled(0===n),void 0):(l.unmarkAllMatches(),e.statusbar.items().slice(1).disabled(!0),void 0)},items:[{type:"textbox",name:"find",size:40,label:"Find",value:t.selection.getNode().src},{type:"textbox",name:"replace",size:40,label:"Replace with"},{type:"checkbox",name:"case",text:"Match case",label:" "},{type:"checkbox",name:"words",text:"Whole words",label:" "}]}}).renderTo().reflow();r=!0}function i(e){var t=e.parentNode;t.insertBefore(e.firstChild,e),e.parentNode.removeChild(e)}function a(e,n){function i(){var i,r;for(i=n?t.getBody()[e?"firstChild":"lastChild"]:l[e?"endContainer":"startContainer"],r=new tinymce.dom.TreeWalker(i,t.getBody());i=r.current();){if(1==i.nodeType&&"SPAN"==i.nodeName&&null!==i.getAttribute("data-mce-index"))for(c=i.getAttribute("data-mce-index"),a=i.firstChild;i=r.current();){if(1==i.nodeType&&"SPAN"==i.nodeName&&null!==i.getAttribute("data-mce-index")){if(i.getAttribute("data-mce-index")!==c)return;o=i.firstChild}r[e?"next":"prev"]()}r[e?"next":"prev"]()}}var a,o,r=t.selection,l=r.getRng(!0),c=-1;return e=e!==!1,i(),a&&o&&(t.focus(),e?(l.setStart(a,0),l.setEnd(o,o.length)):(l.setStart(o,0),l.setEnd(a,a.length)),r.scrollIntoView(a.parentNode),r.setRng(l)),c}function o(e){e.parentNode.removeChild(e)}var r,l=this,c=-1;l.init=function(e){e.addMenuItem("searchreplace",{text:"Find and replace",shortcut:"Ctrl+F",onclick:n,separator:"before",context:"edit"}),e.addButton("searchreplace",{tooltip:"Find and replace",shortcut:"Ctrl+F",onclick:n}),e.shortcuts.add("Ctrl+F","",n)},l.markAllMatches=function(n){var i,a;return a=t.dom.create("span",{"class":"mce-match-marker","data-mce-bogus":1}),i=t.getBody(),l.unmarkAllMatches(i),e(n,i,a,!1,t.schema)},l.first=function(){return c=a(!0,!0),-1!==c},l.next=function(){return c=a(!0),-1!==c},l.prev=function(){return c=a(!1),-1!==c},l.replace=function(e,n,r){var l,s,d,u,m,f;if(-1===c&&(c=a(n)),f=a(n),d=t.getBody(),s=tinymce.toArray(d.getElementsByTagName("span")),s.length)for(l=0;s.length>l;l++)if(u=m=s[l].getAttribute("data-mce-index"),r||u===c)for(e.length?(s[l].firstChild.nodeValue=e,i(s[l])):o(s[l]);s[++l];){if(u=s[l].getAttribute("data-mce-index"),u!==m){l--;break}o(s[l])}return-1==f&&(f=a(n,!0)),c=f,r&&t.selection.setCursorLocation(t.getBody(),0),t.undoManager.add(),-1!==c},l.replaceAll=function(e){l.replace(e,!0,!0)},l.unmarkAllMatches=function(){var e,n,a;for(a=t.getBody(),n=a.getElementsByTagName("span"),e=n.length;e--;)a=n[e],a.getAttribute("data-mce-index")&&i(a)},t.on("beforeaddundo keydown",function(e){return r?(e.preventDefault(),!1):void 0})}tinymce.PluginManager.add("searchreplace",t)})(); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/classes/DomTextMatcher.js b/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/classes/DomTextMatcher.js new file mode 100644 index 00000000..dd75823b --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/classes/DomTextMatcher.js @@ -0,0 +1,278 @@ +/** + * DomTextMatcher.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class logic for filtering text and matching words. + * + * @class tinymce.spellcheckerplugin.TextFilter + * @private + */ +define("tinymce/spellcheckerplugin/DomTextMatcher", [], function() { + // Based on work developed by: James Padolsey http://james.padolsey.com + // released under UNLICENSE that is compatible with LGPL + // TODO: Handle contentEditable edgecase: + //

    texttexttexttexttext

    + return function(regex, node, schema) { + var m, matches = [], text, count = 0, doc; + var blockElementsMap, hiddenTextElementsMap, shortEndedElementsMap; + + doc = node.ownerDocument; + blockElementsMap = schema.getBlockElements(); // H1-H6, P, TD etc + hiddenTextElementsMap = schema.getWhiteSpaceElements(); // TEXTAREA, PRE, STYLE, SCRIPT + shortEndedElementsMap = schema.getShortEndedElements(); // BR, IMG, INPUT + + function getMatchIndexes(m) { + if (!m[0]) { + throw 'findAndReplaceDOMText cannot handle zero-length matches'; + } + + var index = m.index; + + return [index, index + m[0].length, [m[0]]]; + } + + function getText(node) { + var txt; + + if (node.nodeType === 3) { + return node.data; + } + + if (hiddenTextElementsMap[node.nodeName]) { + return ''; + } + + txt = ''; + + if (blockElementsMap[node.nodeName] || shortEndedElementsMap[node.nodeName]) { + txt += '\n'; + } + + if ((node = node.firstChild)) { + do { + txt += getText(node); + } while ((node = node.nextSibling)); + } + + return txt; + } + + function stepThroughMatches(node, matches, replaceFn) { + var startNode, endNode, startNodeIndex, + endNodeIndex, innerNodes = [], atIndex = 0, curNode = node, + matchLocation = matches.shift(), matchIndex = 0; + + out: while (true) { + if (blockElementsMap[curNode.nodeName] || shortEndedElementsMap[curNode.nodeName]) { + atIndex++; + } + + if (curNode.nodeType === 3) { + if (!endNode && curNode.length + atIndex >= matchLocation[1]) { + // We've found the ending + endNode = curNode; + endNodeIndex = matchLocation[1] - atIndex; + } else if (startNode) { + // Intersecting node + innerNodes.push(curNode); + } + + if (!startNode && curNode.length + atIndex > matchLocation[0]) { + // We've found the match start + startNode = curNode; + startNodeIndex = matchLocation[0] - atIndex; + } + + atIndex += curNode.length; + } + + if (startNode && endNode) { + curNode = replaceFn({ + startNode: startNode, + startNodeIndex: startNodeIndex, + endNode: endNode, + endNodeIndex: endNodeIndex, + innerNodes: innerNodes, + match: matchLocation[2], + matchIndex: matchIndex + }); + + // replaceFn has to return the node that replaced the endNode + // and then we step back so we can continue from the end of the + // match: + atIndex -= (endNode.length - endNodeIndex); + startNode = null; + endNode = null; + innerNodes = []; + matchLocation = matches.shift(); + matchIndex++; + + if (!matchLocation) { + break; // no more matches + } + } else if (!hiddenTextElementsMap[curNode.nodeName] && curNode.firstChild) { + // Move down + curNode = curNode.firstChild; + continue; + } else if (curNode.nextSibling) { + // Move forward: + curNode = curNode.nextSibling; + continue; + } + + // Move forward or up: + while (true) { + if (curNode.nextSibling) { + curNode = curNode.nextSibling; + break; + } else if (curNode.parentNode !== node) { + curNode = curNode.parentNode; + } else { + break out; + } + } + } + } + + /** + * Generates the actual replaceFn which splits up text nodes + * and inserts the replacement element. + */ + function genReplacer(nodeName) { + var makeReplacementNode; + + if (typeof nodeName != 'function') { + var stencilNode = nodeName.nodeType ? nodeName : doc.createElement(nodeName); + + makeReplacementNode = function(fill, matchIndex) { + var clone = stencilNode.cloneNode(false); + + clone.setAttribute('data-mce-index', matchIndex); + + if (fill) { + clone.appendChild(doc.createTextNode(fill)); + } + + return clone; + }; + } else { + makeReplacementNode = nodeName; + } + + return function replace(range) { + var before, after, parentNode, startNode = range.startNode, + endNode = range.endNode, matchIndex = range.matchIndex; + + if (startNode === endNode) { + var node = startNode; + + parentNode = node.parentNode; + if (range.startNodeIndex > 0) { + // Add `before` text node (before the match) + before = doc.createTextNode(node.data.substring(0, range.startNodeIndex)); + parentNode.insertBefore(before, node); + } + + // Create the replacement node: + var el = makeReplacementNode(range.match[0], matchIndex); + parentNode.insertBefore(el, node); + if (range.endNodeIndex < node.length) { + // Add `after` text node (after the match) + after = doc.createTextNode(node.data.substring(range.endNodeIndex)); + parentNode.insertBefore(after, node); + } + + node.parentNode.removeChild(node); + + return el; + } else { + // Replace startNode -> [innerNodes...] -> endNode (in that order) + before = doc.createTextNode(startNode.data.substring(0, range.startNodeIndex)); + after = doc.createTextNode(endNode.data.substring(range.endNodeIndex)); + var elA = makeReplacementNode(startNode.data.substring(range.startNodeIndex), matchIndex); + var innerEls = []; + + for (var i = 0, l = range.innerNodes.length; i < l; ++i) { + var innerNode = range.innerNodes[i]; + var innerEl = makeReplacementNode(innerNode.data, matchIndex); + innerNode.parentNode.replaceChild(innerEl, innerNode); + innerEls.push(innerEl); + } + + var elB = makeReplacementNode(endNode.data.substring(0, range.endNodeIndex), matchIndex); + + parentNode = startNode.parentNode; + parentNode.insertBefore(before, startNode); + parentNode.insertBefore(elA, startNode); + parentNode.removeChild(startNode); + + parentNode = endNode.parentNode; + parentNode.insertBefore(elB, endNode); + parentNode.insertBefore(after, endNode); + parentNode.removeChild(endNode); + + return elB; + } + }; + } + + text = getText(node); + if (text && regex.global) { + while ((m = regex.exec(text))) { + matches.push(getMatchIndexes(m)); + } + } + + function filter(callback) { + var filteredMatches = []; + + each(function(match, i) { + if (callback(match, i)) { + filteredMatches.push(match); + } + }); + + matches = filteredMatches; + + /*jshint validthis:true*/ + return this; + } + + function each(callback) { + for (var i = 0, l = matches.length; i < l; i++) { + if (callback(matches[i], i) === false) { + break; + } + } + + /*jshint validthis:true*/ + return this; + } + + function mark(replacementNode) { + if (matches.length) { + count = matches.length; + stepThroughMatches(node, matches, genReplacer(replacementNode)); + } + + /*jshint validthis:true*/ + return this; + } + + return { + text: text, + count: count, + matches: matches, + each: each, + filter: filter, + mark: mark + }; + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/classes/Plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/classes/Plugin.js new file mode 100644 index 00000000..80007448 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/classes/Plugin.js @@ -0,0 +1,262 @@ +/** + * Plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint camelcase:false */ + +/** + * This class contains all core logic for the spellchecker plugin. + * + * @class tinymce.spellcheckerplugin.Plugin + * @private + */ +define("tinymce/spellcheckerplugin/Plugin", [ + "tinymce/spellcheckerplugin/DomTextMatcher", + "tinymce/PluginManager", + "tinymce/util/Tools", + "tinymce/ui/Menu", + "tinymce/dom/DOMUtils", + "tinymce/util/JSONRequest" +], function(DomTextMatcher, PluginManager, Tools, Menu, DOMUtils, JSONRequest) { + PluginManager.add('spellchecker', function(editor) { + var lastSuggestions, started; + + function isEmpty(obj) { + /*jshint unused:false*/ + for (var name in obj) { + return false; + } + + return true; + } + + function showSuggestions(target, word) { + var items = [], suggestions = lastSuggestions[word]; + + Tools.each(suggestions, function(suggestion) { + items.push({ + text: suggestion, + onclick: function() { + editor.insertContent(suggestion); + checkIfFinished(); + } + }); + }); + + items.push.apply(items, [ + {text: '-'}, + + {text: 'Ignore', onclick: function() { + ignoreWord(target, word); + }}, + + {text: 'Ignore all', onclick: function() { + ignoreWord(target, word, true); + }}, + + {text: 'Finish', onclick: finish} + ]); + + // Render menu + var menu = new Menu({ + items: items, + context: 'contextmenu', + onhide: function() { + menu.remove(); + } + }); + + menu.renderTo(document.body); + + // Position menu + var pos = DOMUtils.DOM.getPos(editor.getContentAreaContainer()); + var targetPos = editor.dom.getPos(target); + + pos.x += targetPos.x; + pos.y += targetPos.y; + + menu.moveTo(pos.x, pos.y + target.offsetHeight); + } + + function spellcheck() { + var textFilter, words = [], uniqueWords = {}; + + if (started) { + finish(); + return; + } + + started = true; + + function doneCallback(suggestions) { + editor.setProgressState(false); + + if (isEmpty(suggestions)) { + editor.windowManager.alert('No misspellings found'); + return; + } + + lastSuggestions = suggestions; + + textFilter.filter(function(match) { + return !!suggestions[match[2][0]]; + }).mark(editor.dom.create('span', { + "class": 'mce-spellchecker-word', + "data-mce-bogus": 1 + })); + + textFilter = null; + editor.fire('SpellcheckStart'); + } + + // Find all words and make an unique words array + textFilter = new DomTextMatcher(/\w+/g, editor.getBody(), editor.schema).each(function(match) { + if (!uniqueWords[match[2][0]]) { + words.push(match[2][0]); + uniqueWords[match[2][0]] = true; + } + }); + + editor.settings.spellcheck_callback = function(method, words, doneCallback) { + JSONRequest.sendRPC({ + url: editor.settings.spellchecker_rpc_url, + method: method, + params: { + lang: "en", + words: words + }, + success: function(result) { + doneCallback(result); + }, + error: function(result, xhr) { + editor.windowManager.alert("Error: " + result + "\nData:" + xhr.responseText); + editor.setProgressState(false); + textFilter = null; + } + }); + }; + + editor.setProgressState(true); + editor.settings.spellcheck_callback("spellcheck", words, doneCallback); + } + + function checkIfFinished() { + if (!editor.dom.select('span.mce-spellchecker-word').length) { + finish(); + } + } + + function unwrap(node) { + var parentNode = node.parentNode; + parentNode.insertBefore(node.firstChild, node); + node.parentNode.removeChild(node); + } + + function ignoreWord(target, word, all) { + if (all) { + Tools.each(editor.dom.select('span.mce-spellchecker-word'), function(item) { + var text = item.innerText || item.textContent; + + if (text == word) { + unwrap(item); + } + }); + } else { + unwrap(target); + } + + checkIfFinished(); + } + + function finish() { + var i, nodes, node; + + started = false; + node = editor.getBody(); + nodes = node.getElementsByTagName('span'); + i = nodes.length; + while (i--) { + node = nodes[i]; + if (node.getAttribute('data-mce-index')) { + unwrap(node); + } + } + + editor.fire('SpellcheckEnd'); + } + + function selectMatch(index) { + var nodes, i, spanElm, spanIndex = -1, startContainer, endContainer; + + index = "" + index; + nodes = editor.getBody().getElementsByTagName("span"); + for (i = 0; i < nodes.length; i++) { + spanElm = nodes[i]; + if (spanElm.className == "mce-spellchecker-word") { + spanIndex = spanElm.getAttribute('data-mce-index'); + if (spanIndex === index) { + spanIndex = index; + + if (!startContainer) { + startContainer = spanElm.firstChild; + } + + endContainer = spanElm.firstChild; + } + + if (spanIndex !== index && endContainer) { + break; + } + } + } + + var rng = editor.dom.createRng(); + rng.setStart(startContainer, 0); + rng.setEnd(endContainer, endContainer.length); + editor.selection.setRng(rng); + + return rng; + } + + editor.on('click', function(e) { + if (e.target.className == "mce-spellchecker-word") { + e.preventDefault(); + + var rng = selectMatch(e.target.getAttribute('data-mce-index')); + showSuggestions(e.target, rng.toString()); + } + }); + + editor.addMenuItem('spellchecker', { + text: 'Spellcheck', + context: 'tools', + onclick: spellcheck, + selectable: true, + onPostRender: function() { + var self = this; + + editor.on('SpellcheckStart SpellcheckEnd', function() { + self.active(started); + }); + } + }); + + editor.addButton('spellchecker', { + tooltip: 'Spellcheck', + onclick: spellcheck, + onPostRender: function() { + var self = this; + + editor.on('SpellcheckStart SpellcheckEnd', function() { + self.active(started); + }); + } + }); + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/plugin.dev.js b/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/plugin.dev.js new file mode 100644 index 00000000..25a36fbd --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/plugin.dev.js @@ -0,0 +1,117 @@ +/** + * Inline development version. Only to be used while developing since it uses document.write to load scripts. + */ + +/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ +/*globals $code */ + +(function(exports) { + "use strict"; + + var html = "", baseDir; + var modules = {}, exposedModules = [], moduleCount = 0; + + var scripts = document.getElementsByTagName('script'); + for (var i = 0; i < scripts.length; i++) { + var src = scripts[i].src; + + if (src.indexOf('/plugin.dev.js') != -1) { + baseDir = src.substring(0, src.lastIndexOf('/')); + } + } + + function require(ids, callback) { + var module, defs = []; + + for (var i = 0; i < ids.length; ++i) { + module = modules[ids[i]] || resolve(ids[i]); + if (!module) { + throw 'module definition dependecy not found: ' + ids[i]; + } + + defs.push(module); + } + + callback.apply(null, defs); + } + + function resolve(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length; ++fi) { + if (!target[fragments[fi]]) { + return; + } + + target = target[fragments[fi]]; + } + + return target; + } + + function register(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length - 1; ++fi) { + if (target[fragments[fi]] === undefined) { + target[fragments[fi]] = {}; + } + + target = target[fragments[fi]]; + } + + target[fragments[fragments.length - 1]] = modules[id]; + } + + function define(id, dependencies, definition) { + if (typeof id !== 'string') { + throw 'invalid module definition, module id must be defined and be a string'; + } + + if (dependencies === undefined) { + throw 'invalid module definition, dependencies must be specified'; + } + + if (definition === undefined) { + throw 'invalid module definition, definition function must be specified'; + } + + require(dependencies, function() { + modules[id] = definition.apply(null, arguments); + }); + + if (--moduleCount === 0) { + for (var i = 0; i < exposedModules.length; i++) { + register(exposedModules[i]); + } + } + } + + function expose(ids) { + exposedModules = ids; + } + + function writeScripts() { + document.write(html); + } + + function load(path) { + html += '\n'; + moduleCount++; + } + + // Expose globally + exports.define = define; + exports.require = require; + + expose(["tinymce/spellcheckerplugin/DomTextMatcher","tinymce/spellcheckerplugin/Plugin"]); + + load('classes/DomTextMatcher.js'); + load('classes/Plugin.js'); + + writeScripts(); +})(this); + +// $hash: b7c8d0a3a68383a9664606d506fd504a \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/plugin.js new file mode 100644 index 00000000..f3c46ef1 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/plugin.js @@ -0,0 +1,630 @@ +/** + * Compiled inline version. (Library mode) + */ + +/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ +/*globals $code */ + +(function(exports, undefined) { + "use strict"; + + var modules = {}; + + function require(ids, callback) { + var module, defs = []; + + for (var i = 0; i < ids.length; ++i) { + module = modules[ids[i]] || resolve(ids[i]); + if (!module) { + throw 'module definition dependecy not found: ' + ids[i]; + } + + defs.push(module); + } + + callback.apply(null, defs); + } + + function define(id, dependencies, definition) { + if (typeof id !== 'string') { + throw 'invalid module definition, module id must be defined and be a string'; + } + + if (dependencies === undefined) { + throw 'invalid module definition, dependencies must be specified'; + } + + if (definition === undefined) { + throw 'invalid module definition, definition function must be specified'; + } + + require(dependencies, function() { + modules[id] = definition.apply(null, arguments); + }); + } + + function defined(id) { + return !!modules[id]; + } + + function resolve(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length; ++fi) { + if (!target[fragments[fi]]) { + return; + } + + target = target[fragments[fi]]; + } + + return target; + } + + function expose(ids) { + for (var i = 0; i < ids.length; i++) { + var target = exports; + var id = ids[i]; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length - 1; ++fi) { + if (target[fragments[fi]] === undefined) { + target[fragments[fi]] = {}; + } + + target = target[fragments[fi]]; + } + + target[fragments[fragments.length - 1]] = modules[id]; + } + } + +// Included from: js/tinymce/plugins/spellchecker/classes/DomTextMatcher.js + +/** + * DomTextMatcher.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class logic for filtering text and matching words. + * + * @class tinymce.spellcheckerplugin.TextFilter + * @private + */ +define("tinymce/spellcheckerplugin/DomTextMatcher", [], function() { + // Based on work developed by: James Padolsey http://james.padolsey.com + // released under UNLICENSE that is compatible with LGPL + // TODO: Handle contentEditable edgecase: + //

    texttexttexttexttext

    + return function(regex, node, schema) { + var m, matches = [], text, count = 0, doc; + var blockElementsMap, hiddenTextElementsMap, shortEndedElementsMap; + + doc = node.ownerDocument; + blockElementsMap = schema.getBlockElements(); // H1-H6, P, TD etc + hiddenTextElementsMap = schema.getWhiteSpaceElements(); // TEXTAREA, PRE, STYLE, SCRIPT + shortEndedElementsMap = schema.getShortEndedElements(); // BR, IMG, INPUT + + function getMatchIndexes(m) { + if (!m[0]) { + throw 'findAndReplaceDOMText cannot handle zero-length matches'; + } + + var index = m.index; + + return [index, index + m[0].length, [m[0]]]; + } + + function getText(node) { + var txt; + + if (node.nodeType === 3) { + return node.data; + } + + if (hiddenTextElementsMap[node.nodeName]) { + return ''; + } + + txt = ''; + + if (blockElementsMap[node.nodeName] || shortEndedElementsMap[node.nodeName]) { + txt += '\n'; + } + + if ((node = node.firstChild)) { + do { + txt += getText(node); + } while ((node = node.nextSibling)); + } + + return txt; + } + + function stepThroughMatches(node, matches, replaceFn) { + var startNode, endNode, startNodeIndex, + endNodeIndex, innerNodes = [], atIndex = 0, curNode = node, + matchLocation = matches.shift(), matchIndex = 0; + + out: while (true) { + if (blockElementsMap[curNode.nodeName] || shortEndedElementsMap[curNode.nodeName]) { + atIndex++; + } + + if (curNode.nodeType === 3) { + if (!endNode && curNode.length + atIndex >= matchLocation[1]) { + // We've found the ending + endNode = curNode; + endNodeIndex = matchLocation[1] - atIndex; + } else if (startNode) { + // Intersecting node + innerNodes.push(curNode); + } + + if (!startNode && curNode.length + atIndex > matchLocation[0]) { + // We've found the match start + startNode = curNode; + startNodeIndex = matchLocation[0] - atIndex; + } + + atIndex += curNode.length; + } + + if (startNode && endNode) { + curNode = replaceFn({ + startNode: startNode, + startNodeIndex: startNodeIndex, + endNode: endNode, + endNodeIndex: endNodeIndex, + innerNodes: innerNodes, + match: matchLocation[2], + matchIndex: matchIndex + }); + + // replaceFn has to return the node that replaced the endNode + // and then we step back so we can continue from the end of the + // match: + atIndex -= (endNode.length - endNodeIndex); + startNode = null; + endNode = null; + innerNodes = []; + matchLocation = matches.shift(); + matchIndex++; + + if (!matchLocation) { + break; // no more matches + } + } else if (!hiddenTextElementsMap[curNode.nodeName] && curNode.firstChild) { + // Move down + curNode = curNode.firstChild; + continue; + } else if (curNode.nextSibling) { + // Move forward: + curNode = curNode.nextSibling; + continue; + } + + // Move forward or up: + while (true) { + if (curNode.nextSibling) { + curNode = curNode.nextSibling; + break; + } else if (curNode.parentNode !== node) { + curNode = curNode.parentNode; + } else { + break out; + } + } + } + } + + /** + * Generates the actual replaceFn which splits up text nodes + * and inserts the replacement element. + */ + function genReplacer(nodeName) { + var makeReplacementNode; + + if (typeof nodeName != 'function') { + var stencilNode = nodeName.nodeType ? nodeName : doc.createElement(nodeName); + + makeReplacementNode = function(fill, matchIndex) { + var clone = stencilNode.cloneNode(false); + + clone.setAttribute('data-mce-index', matchIndex); + + if (fill) { + clone.appendChild(doc.createTextNode(fill)); + } + + return clone; + }; + } else { + makeReplacementNode = nodeName; + } + + return function replace(range) { + var before, after, parentNode, startNode = range.startNode, + endNode = range.endNode, matchIndex = range.matchIndex; + + if (startNode === endNode) { + var node = startNode; + + parentNode = node.parentNode; + if (range.startNodeIndex > 0) { + // Add `before` text node (before the match) + before = doc.createTextNode(node.data.substring(0, range.startNodeIndex)); + parentNode.insertBefore(before, node); + } + + // Create the replacement node: + var el = makeReplacementNode(range.match[0], matchIndex); + parentNode.insertBefore(el, node); + if (range.endNodeIndex < node.length) { + // Add `after` text node (after the match) + after = doc.createTextNode(node.data.substring(range.endNodeIndex)); + parentNode.insertBefore(after, node); + } + + node.parentNode.removeChild(node); + + return el; + } else { + // Replace startNode -> [innerNodes...] -> endNode (in that order) + before = doc.createTextNode(startNode.data.substring(0, range.startNodeIndex)); + after = doc.createTextNode(endNode.data.substring(range.endNodeIndex)); + var elA = makeReplacementNode(startNode.data.substring(range.startNodeIndex), matchIndex); + var innerEls = []; + + for (var i = 0, l = range.innerNodes.length; i < l; ++i) { + var innerNode = range.innerNodes[i]; + var innerEl = makeReplacementNode(innerNode.data, matchIndex); + innerNode.parentNode.replaceChild(innerEl, innerNode); + innerEls.push(innerEl); + } + + var elB = makeReplacementNode(endNode.data.substring(0, range.endNodeIndex), matchIndex); + + parentNode = startNode.parentNode; + parentNode.insertBefore(before, startNode); + parentNode.insertBefore(elA, startNode); + parentNode.removeChild(startNode); + + parentNode = endNode.parentNode; + parentNode.insertBefore(elB, endNode); + parentNode.insertBefore(after, endNode); + parentNode.removeChild(endNode); + + return elB; + } + }; + } + + text = getText(node); + if (text && regex.global) { + while ((m = regex.exec(text))) { + matches.push(getMatchIndexes(m)); + } + } + + function filter(callback) { + var filteredMatches = []; + + each(function(match, i) { + if (callback(match, i)) { + filteredMatches.push(match); + } + }); + + matches = filteredMatches; + + /*jshint validthis:true*/ + return this; + } + + function each(callback) { + for (var i = 0, l = matches.length; i < l; i++) { + if (callback(matches[i], i) === false) { + break; + } + } + + /*jshint validthis:true*/ + return this; + } + + function mark(replacementNode) { + if (matches.length) { + count = matches.length; + stepThroughMatches(node, matches, genReplacer(replacementNode)); + } + + /*jshint validthis:true*/ + return this; + } + + return { + text: text, + count: count, + matches: matches, + each: each, + filter: filter, + mark: mark + }; + }; +}); + +// Included from: js/tinymce/plugins/spellchecker/classes/Plugin.js + +/** + * Plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint camelcase:false */ + +/** + * This class contains all core logic for the spellchecker plugin. + * + * @class tinymce.spellcheckerplugin.Plugin + * @private + */ +define("tinymce/spellcheckerplugin/Plugin", [ + "tinymce/spellcheckerplugin/DomTextMatcher", + "tinymce/PluginManager", + "tinymce/util/Tools", + "tinymce/ui/Menu", + "tinymce/dom/DOMUtils", + "tinymce/util/JSONRequest" +], function(DomTextMatcher, PluginManager, Tools, Menu, DOMUtils, JSONRequest) { + PluginManager.add('spellchecker', function(editor) { + var lastSuggestions, started; + + function isEmpty(obj) { + /*jshint unused:false*/ + for (var name in obj) { + return false; + } + + return true; + } + + function showSuggestions(target, word) { + var items = [], suggestions = lastSuggestions[word]; + + Tools.each(suggestions, function(suggestion) { + items.push({ + text: suggestion, + onclick: function() { + editor.insertContent(suggestion); + checkIfFinished(); + } + }); + }); + + items.push.apply(items, [ + {text: '-'}, + + {text: 'Ignore', onclick: function() { + ignoreWord(target, word); + }}, + + {text: 'Ignore all', onclick: function() { + ignoreWord(target, word, true); + }}, + + {text: 'Finish', onclick: finish} + ]); + + // Render menu + var menu = new Menu({ + items: items, + context: 'contextmenu', + onhide: function() { + menu.remove(); + } + }); + + menu.renderTo(document.body); + + // Position menu + var pos = DOMUtils.DOM.getPos(editor.getContentAreaContainer()); + var targetPos = editor.dom.getPos(target); + + pos.x += targetPos.x; + pos.y += targetPos.y; + + menu.moveTo(pos.x, pos.y + target.offsetHeight); + } + + function spellcheck() { + var textFilter, words = [], uniqueWords = {}; + + if (started) { + finish(); + return; + } + + started = true; + + function doneCallback(suggestions) { + editor.setProgressState(false); + + if (isEmpty(suggestions)) { + editor.windowManager.alert('No misspellings found'); + return; + } + + lastSuggestions = suggestions; + + textFilter.filter(function(match) { + return !!suggestions[match[2][0]]; + }).mark(editor.dom.create('span', { + "class": 'mce-spellchecker-word', + "data-mce-bogus": 1 + })); + + textFilter = null; + editor.fire('SpellcheckStart'); + } + + // Find all words and make an unique words array + textFilter = new DomTextMatcher(/\w+/g, editor.getBody(), editor.schema).each(function(match) { + if (!uniqueWords[match[2][0]]) { + words.push(match[2][0]); + uniqueWords[match[2][0]] = true; + } + }); + + editor.settings.spellcheck_callback = function(method, words, doneCallback) { + JSONRequest.sendRPC({ + url: editor.settings.spellchecker_rpc_url, + method: method, + params: { + lang: "en", + words: words + }, + success: function(result) { + doneCallback(result); + }, + error: function(result, xhr) { + editor.windowManager.alert("Error: " + result + "\nData:" + xhr.responseText); + editor.setProgressState(false); + textFilter = null; + } + }); + }; + + editor.setProgressState(true); + editor.settings.spellcheck_callback("spellcheck", words, doneCallback); + } + + function checkIfFinished() { + if (!editor.dom.select('span.mce-spellchecker-word').length) { + finish(); + } + } + + function unwrap(node) { + var parentNode = node.parentNode; + parentNode.insertBefore(node.firstChild, node); + node.parentNode.removeChild(node); + } + + function ignoreWord(target, word, all) { + if (all) { + Tools.each(editor.dom.select('span.mce-spellchecker-word'), function(item) { + var text = item.innerText || item.textContent; + + if (text == word) { + unwrap(item); + } + }); + } else { + unwrap(target); + } + + checkIfFinished(); + } + + function finish() { + var i, nodes, node; + + started = false; + node = editor.getBody(); + nodes = node.getElementsByTagName('span'); + i = nodes.length; + while (i--) { + node = nodes[i]; + if (node.getAttribute('data-mce-index')) { + unwrap(node); + } + } + + editor.fire('SpellcheckEnd'); + } + + function selectMatch(index) { + var nodes, i, spanElm, spanIndex = -1, startContainer, endContainer; + + index = "" + index; + nodes = editor.getBody().getElementsByTagName("span"); + for (i = 0; i < nodes.length; i++) { + spanElm = nodes[i]; + if (spanElm.className == "mce-spellchecker-word") { + spanIndex = spanElm.getAttribute('data-mce-index'); + if (spanIndex === index) { + spanIndex = index; + + if (!startContainer) { + startContainer = spanElm.firstChild; + } + + endContainer = spanElm.firstChild; + } + + if (spanIndex !== index && endContainer) { + break; + } + } + } + + var rng = editor.dom.createRng(); + rng.setStart(startContainer, 0); + rng.setEnd(endContainer, endContainer.length); + editor.selection.setRng(rng); + + return rng; + } + + editor.on('click', function(e) { + if (e.target.className == "mce-spellchecker-word") { + e.preventDefault(); + + var rng = selectMatch(e.target.getAttribute('data-mce-index')); + showSuggestions(e.target, rng.toString()); + } + }); + + editor.addMenuItem('spellchecker', { + text: 'Spellcheck', + context: 'tools', + onclick: spellcheck, + selectable: true, + onPostRender: function() { + var self = this; + + editor.on('SpellcheckStart SpellcheckEnd', function() { + self.active(started); + }); + } + }); + + editor.addButton('spellchecker', { + tooltip: 'Spellcheck', + onclick: spellcheck, + onPostRender: function() { + var self = this; + + editor.on('SpellcheckStart SpellcheckEnd', function() { + self.active(started); + }); + } + }); + }); +}); + +expose(["tinymce/spellcheckerplugin/DomTextMatcher","tinymce/spellcheckerplugin/Plugin"]); +})(this); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/plugin.min.js new file mode 100644 index 00000000..88cecedf --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/spellchecker/plugin.min.js @@ -0,0 +1 @@ +(function(e,t){"use strict";function n(e,t){for(var n,r=[],i=0;e.length>i;++i){if(n=s[e[i]]||o(e[i]),!n)throw"module definition dependecy not found: "+e[i];r.push(n)}t.apply(null,r)}function r(e,r,i){if("string"!=typeof e)throw"invalid module definition, module id must be defined and be a string";if(r===t)throw"invalid module definition, dependencies must be specified";if(i===t)throw"invalid module definition, definition function must be specified";n(r,function(){s[e]=i.apply(null,arguments)})}function i(e){return!!s[e]}function o(t){for(var n=e,r=t.split(/[.\/]/),i=0;r.length>i;++i){if(!n[r[i]])return;n=n[r[i]]}return n}function a(n){for(var r=0;n.length>r;r++){for(var i=e,o=n[r],a=o.split(/[.\/]/),l=0;a.length-1>l;++l)i[a[l]]===t&&(i[a[l]]={}),i=i[a[l]];i[a[a.length-1]]=s[o]}}var s={},l="tinymce/spellcheckerplugin/DomTextMatcher",c="tinymce/spellcheckerplugin/Plugin",u="tinymce/PluginManager",d="tinymce/util/Tools",f="tinymce/ui/Menu",p="tinymce/dom/DOMUtils",h="tinymce/util/JSONRequest";r(l,[],function(){return function(e,t,n){function r(e){if(!e[0])throw"findAndReplaceDOMText cannot handle zero-length matches";var t=e.index;return[t,t+e[0].length,[e[0]]]}function i(e){var t;if(3===e.nodeType)return e.data;if(g[e.nodeName])return"";if(t="",(m[e.nodeName]||v[e.nodeName])&&(t+="\n"),e=e.firstChild)do t+=i(e);while(e=e.nextSibling);return t}function o(e,t,n){var r,i,o,a,s=[],l=0,c=e,u=t.shift(),d=0;e:for(;;){if((m[c.nodeName]||v[c.nodeName])&&l++,3===c.nodeType&&(!i&&c.length+l>=u[1]?(i=c,a=u[1]-l):r&&s.push(c),!r&&c.length+l>u[0]&&(r=c,o=u[0]-l),l+=c.length),r&&i){if(c=n({startNode:r,startNodeIndex:o,endNode:i,endNodeIndex:a,innerNodes:s,match:u[2],matchIndex:d}),l-=i.length-a,r=null,i=null,s=[],u=t.shift(),d++,!u)break}else{if(!g[c.nodeName]&&c.firstChild){c=c.firstChild;continue}if(c.nextSibling){c=c.nextSibling;continue}}for(;;){if(c.nextSibling){c=c.nextSibling;break}if(c.parentNode===e)break e;c=c.parentNode}}}function a(e){var t;if("function"!=typeof e){var n=e.nodeType?e:h.createElement(e);t=function(e,t){var r=n.cloneNode(!1);return r.setAttribute("data-mce-index",t),e&&r.appendChild(h.createTextNode(e)),r}}else t=e;return function r(e){var n,r,i,o=e.startNode,a=e.endNode,s=e.matchIndex;if(o===a){var l=o;i=l.parentNode,e.startNodeIndex>0&&(n=h.createTextNode(l.data.substring(0,e.startNodeIndex)),i.insertBefore(n,l));var c=t(e.match[0],s);return i.insertBefore(c,l),e.endNodeIndexf;++f){var m=e.innerNodes[f],g=t(m.data,s);m.parentNode.replaceChild(g,m),d.push(g)}var v=t(a.data.substring(0,e.endNodeIndex),s);return i=o.parentNode,i.insertBefore(n,o),i.insertBefore(u,o),i.removeChild(o),i=a.parentNode,i.insertBefore(v,a),i.insertBefore(r,a),i.removeChild(a),v}}function s(e){var t=[];return l(function(n,r){e(n,r)&&t.push(n)}),d=t,this}function l(e){for(var t=0,n=d.length;n>t&&e(d[t],t)!==!1;t++);return this}function c(e){return d.length&&(p=d.length,o(t,d,a(e))),this}var u,d=[],f,p=0,h,m,g,v;if(h=t.ownerDocument,m=n.getBlockElements(),g=n.getWhiteSpaceElements(),v=n.getShortEndedElements(),f=i(t),f&&e.global)for(;u=e.exec(f);)d.push(r(u));return{text:f,count:p,matches:d,each:l,filter:s,mark:c}}}),r(c,[l,u,d,f,p,h],function(e,n,r,i,o,a){n.add("spellchecker",function(n){function s(e){for(var t in e)return!1;return!0}function l(e,t){var a=[],s=m[t];r.each(s,function(e){a.push({text:e,onclick:function(){n.insertContent(e),u()}})}),a.push.apply(a,[{text:"-"},{text:"Ignore",onclick:function(){f(e,t)}},{text:"Ignore all",onclick:function(){f(e,t,!0)}},{text:"Finish",onclick:p}]);var l=new i({items:a,context:"contextmenu",onhide:function(){l.remove()}});l.renderTo(document.body);var c=o.DOM.getPos(n.getContentAreaContainer()),d=n.dom.getPos(e);c.x+=d.x,c.y+=d.y,l.moveTo(c.x,c.y+e.offsetHeight)}function c(){function r(e){return n.setProgressState(!1),s(e)?(n.windowManager.alert("No misspellings found"),t):(m=e,i.filter(function(t){return!!e[t[2][0]]}).mark(n.dom.create("span",{"class":"mce-spellchecker-word","data-mce-bogus":1})),i=null,n.fire("SpellcheckStart"),t)}var i,o=[],l={};return g?(p(),t):(g=!0,i=new e(/\w+/g,n.getBody(),n.schema).each(function(e){l[e[2][0]]||(o.push(e[2][0]),l[e[2][0]]=!0)}),n.settings.spellcheck_callback=function(e,t,r){a.sendRPC({url:n.settings.spellchecker_rpc_url,method:e,params:{lang:"en",words:t},success:function(e){r(e)},error:function(e,t){n.windowManager.alert("Error: "+e+"\nData:"+t.responseText),n.setProgressState(!1),i=null}})},n.setProgressState(!0),n.settings.spellcheck_callback("spellcheck",o,r),t)}function u(){n.dom.select("span.mce-spellchecker-word").length||p()}function d(e){var t=e.parentNode;t.insertBefore(e.firstChild,e),e.parentNode.removeChild(e)}function f(e,t,i){i?r.each(n.dom.select("span.mce-spellchecker-word"),function(e){var n=e.innerText||e.textContent;n==t&&d(e)}):d(e),u()}function p(){var e,t,r;for(g=!1,r=n.getBody(),t=r.getElementsByTagName("span"),e=t.length;e--;)r=t[e],r.getAttribute("data-mce-index")&&d(r);n.fire("SpellcheckEnd")}function h(e){var t,r,i,o=-1,a,s;for(e=""+e,t=n.getBody().getElementsByTagName("span"),r=0;t.length>r&&(i=t[r],"mce-spellchecker-word"!=i.className||(o=i.getAttribute("data-mce-index"),o===e&&(o=e,a||(a=i.firstChild),s=i.firstChild),o===e||!s));r++);var l=n.dom.createRng();return l.setStart(a,0),l.setEnd(s,s.length),n.selection.setRng(l),l}var m,g;n.on("click",function(e){if("mce-spellchecker-word"==e.target.className){e.preventDefault();var t=h(e.target.getAttribute("data-mce-index"));l(e.target,""+t)}}),n.addMenuItem("spellchecker",{text:"Spellcheck",context:"tools",onclick:c,selectable:!0,onPostRender:function(){var e=this;n.on("SpellcheckStart SpellcheckEnd",function(){e.active(g)})}}),n.addButton("spellchecker",{tooltip:"Spellcheck",onclick:c,onPostRender:function(){var e=this;n.on("SpellcheckStart SpellcheckEnd",function(){e.active(g)})}})})}),a([l,c])})(this); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/tabfocus/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/tabfocus/plugin.js new file mode 100644 index 00000000..42901f8e --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/tabfocus/plugin.js @@ -0,0 +1,112 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('tabfocus', function(editor) { + var DOM = tinymce.DOM, each = tinymce.each, explode = tinymce.explode; + + function tabCancel(e) { + if (e.keyCode === 9) { + e.preventDefault(); + } + } + + function tabHandler(e) { + var x, el, v, i; + + function find(d) { + el = DOM.select(':input:enabled,*[tabindex]:not(iframe)'); + + function canSelectRecursive(e) { + return e.nodeName==="BODY" || (e.type != 'hidden' && + e.style.display != "none" && + e.style.visibility != "hidden" && canSelectRecursive(e.parentNode)); + } + function canSelectInOldIe(el) { + return el.attributes.tabIndex.specified || el.nodeName == "INPUT" || el.nodeName == "TEXTAREA"; + } + + function canSelect(el) { + return ((!canSelectInOldIe(el))) && el.getAttribute("tabindex") != '-1' && canSelectRecursive(el); + } + + each(el, function(e, i) { + if (e.id == editor.id) { + x = i; + return false; + } + }); + if (d > 0) { + for (i = x + 1; i < el.length; i++) { + if (canSelect(el[i])) { + return el[i]; + } + } + } else { + for (i = x - 1; i >= 0; i--) { + if (canSelect(el[i])) { + return el[i]; + } + } + } + + return null; + } + + if (e.keyCode === 9) { + v = explode(editor.getParam('tab_focus', editor.getParam('tabfocus_elements', ':prev,:next'))); + + if (v.length == 1) { + v[1] = v[0]; + v[0] = ':prev'; + } + + // Find element to focus + if (e.shiftKey) { + if (v[0] == ':prev') { + el = find(-1); + } else { + el = DOM.get(v[0]); + } + } else { + if (v[1] == ':next') { + el = find(1); + } else { + el = DOM.get(v[1]); + } + } + + if (el) { + if (el.id && (editor = tinymce.get(el.id || el.name))) { + editor.focus(); + } else { + window.setTimeout(function() { + if (!tinymce.Env.webkit) { + window.focus(); + } + + el.focus(); + }, 10); + } + + e.preventDefault(); + } + } + } + + editor.on('keyup', tabCancel); + + if (tinymce.Env.gecko) { + editor.on('keypress keydown', tabHandler); + } else { + editor.on('keydown', tabHandler); + } +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/tabfocus/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/tabfocus/plugin.min.js new file mode 100644 index 00000000..68e9223c --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/tabfocus/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("tabfocus",function(e){function t(e){9===e.keyCode&&e.preventDefault()}function n(t){function n(t){function n(e){return"BODY"===e.nodeName||"hidden"!=e.type&&"none"!=e.style.display&&"hidden"!=e.style.visibility&&n(e.parentNode)}function o(e){return e.attributes.tabIndex.specified||"INPUT"==e.nodeName||"TEXTAREA"==e.nodeName}function c(e){return!o(e)&&"-1"!=e.getAttribute("tabindex")&&n(e)}if(l=i.select(":input:enabled,*[tabindex]:not(iframe)"),a(l,function(t,n){return t.id==e.id?(r=n,!1):void 0}),t>0){for(s=r+1;l.length>s;s++)if(c(l[s]))return l[s]}else for(s=r-1;s>=0;s--)if(c(l[s]))return l[s];return null}var r,l,c,s;9===t.keyCode&&(c=o(e.getParam("tab_focus",e.getParam("tabfocus_elements",":prev,:next"))),1==c.length&&(c[1]=c[0],c[0]=":prev"),l=t.shiftKey?":prev"==c[0]?n(-1):i.get(c[0]):":next"==c[1]?n(1):i.get(c[1]),l&&(l.id&&(e=tinymce.get(l.id||l.name))?e.focus():window.setTimeout(function(){tinymce.Env.webkit||window.focus(),l.focus()},10),t.preventDefault()))}var i=tinymce.DOM,a=tinymce.each,o=tinymce.explode;e.on("keyup",t),tinymce.Env.gecko?e.on("keypress keydown",n):e.on("keydown",n)}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/table/classes/CellSelection.js b/lib/tinymce/jscripts/tinymce4/plugins/table/classes/CellSelection.js new file mode 100644 index 00000000..24cc482f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/table/classes/CellSelection.js @@ -0,0 +1,161 @@ +/** + * CellSelection.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles table cell selection by faking it using a css class that gets applied + * to cells when dragging the mouse from one cell to another. + * + * @class tinymce.tableplugin.CellSelection + * @private + */ +define("tinymce/tableplugin/CellSelection", [ + "tinymce/tableplugin/TableGrid", + "tinymce/dom/TreeWalker", + "tinymce/util/Tools" +], function(TableGrid, TreeWalker, Tools) { + return function(editor) { + var dom = editor.dom, tableGrid, startCell, startTable, hasCellSelection = true; + + function clear() { + // Restore selection possibilities + editor.getBody().style.webkitUserSelect = ''; + + if (hasCellSelection) { + editor.dom.removeClass( + editor.dom.select('td.mce-item-selected,th.mce-item-selected'), + 'mce-item-selected' + ); + + hasCellSelection = false; + } + } + + // Add cell selection logic + editor.on('MouseDown', function(e) { + if (e.button != 2) { + clear(); + + startCell = dom.getParent(e.target, 'td,th'); + startTable = dom.getParent(startCell, 'table'); + } + }); + + dom.bind(editor.getDoc(), 'mouseover', function(e) { + var sel, table, target = e.target; + + if (startCell && (tableGrid || target != startCell) && (target.nodeName == 'TD' || target.nodeName == 'TH')) { + table = dom.getParent(target, 'table'); + if (table == startTable) { + if (!tableGrid) { + tableGrid = new TableGrid(editor.selection, table); + tableGrid.setStartCell(startCell); + + editor.getBody().style.webkitUserSelect = 'none'; + } + + tableGrid.setEndCell(target); + hasCellSelection = true; + } + + // Remove current selection + sel = editor.selection.getSel(); + + try { + if (sel.removeAllRanges) { + sel.removeAllRanges(); + } else { + sel.empty(); + } + } catch (ex) { + // IE9 might throw errors here + } + + e.preventDefault(); + } + }); + + editor.on('MouseUp', function() { + var rng, sel = editor.selection, selectedCells, walker, node, lastNode, endNode; + + function setPoint(node, start) { + var walker = new TreeWalker(node, node); + + do { + // Text node + if (node.nodeType == 3 && Tools.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()))); + } + + // Move selection to startCell + if (startCell) { + if (tableGrid) { + editor.getBody().style.webkitUserSelect = ''; + } + + // Try to expand text selection as much as we can only Gecko supports cell selection + selectedCells = dom.select('td.mce-item-selected,th.mce-item-selected'); + if (selectedCells.length > 0) { + rng = dom.createRng(); + node = selectedCells[0]; + endNode = selectedCells[selectedCells.length - 1]; + rng.setStartBefore(node); + rng.setEndAfter(node); + + setPoint(node, 1); + walker = new TreeWalker(node, dom.getParent(selectedCells[0], 'table')); + + do { + if (node.nodeName == 'TD' || node.nodeName == 'TH') { + if (!dom.hasClass(node, 'mce-item-selected')) { + break; + } + + lastNode = node; + } + } while ((node = walker.next())); + + setPoint(lastNode); + + sel.setRng(rng); + } + + editor.nodeChanged(); + startCell = tableGrid = startTable = null; + } + }); + + editor.on('KeyUp', function() { + clear(); + }); + + return { + clear: clear + }; + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/table/classes/Plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/table/classes/Plugin.js new file mode 100644 index 00000000..66e4d704 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/table/classes/Plugin.js @@ -0,0 +1,706 @@ +/** + * Plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class contains all core logic for the table plugin. + * + * @class tinymce.tableplugin.Plugin + * @private + */ +define("tinymce/tableplugin/Plugin", [ + "tinymce/tableplugin/TableGrid", + "tinymce/tableplugin/Quirks", + "tinymce/tableplugin/CellSelection", + "tinymce/util/Tools", + "tinymce/dom/TreeWalker", + "tinymce/Env", + "tinymce/PluginManager" +], function(TableGrid, Quirks, CellSelection, Tools, TreeWalker, Env, PluginManager) { + var each = Tools.each; + + function Plugin(editor) { + var winMan, clipboardRows, self = this; // Might be selected cells on reload + + function removePxSuffix(size) { + return size ? size.replace(/px$/, '') : ""; + } + + function addSizeSuffix(size) { + if (/^[0-9]+$/.test(size)) { + size += "px"; + } + + return size; + } + + function tableDialog() { + var dom = editor.dom, tableElm, data; + + tableElm = editor.dom.getParent(editor.selection.getNode(), 'table'); + + data = { + width: removePxSuffix(dom.getStyle(tableElm, 'width') || dom.getAttrib(tableElm, 'width')), + height: removePxSuffix(dom.getStyle(tableElm, 'height') || dom.getAttrib(tableElm, 'height')), + cellspacing: dom.getAttrib(tableElm, 'cellspacing'), + cellpadding: dom.getAttrib(tableElm, 'cellpadding'), + border: dom.getAttrib(tableElm, 'border'), + caption: !!dom.select('caption', tableElm)[0] + }; + + each('left center right'.split(' '), function(name) { + if (editor.formatter.matchNode(tableElm, 'align' + name)) { + data.align = name; + } + }); + + editor.windowManager.open({ + title: "Table properties", + items: { + type: 'form', + layout: 'grid', + columns: 2, + data: data, + defaults: { + type: 'textbox', + maxWidth: 50 + }, + items: [ + {label: 'Cols', name: 'cols'}, + {label: 'Rows', name: 'rows'}, + {label: 'Width', name: 'width'}, + {label: 'Height', name: 'height'}, + {label: 'Cell spacing', name: 'cellspacing'}, + {label: 'Cell padding', name: 'cellpadding'}, + {label: 'Border', name: 'border'}, + {label: 'Caption', name: 'caption', type: 'checkbox'}, + { + label: 'Alignment', + minWidth: 90, + name: 'align', + type: 'listbox', + text: 'None', + maxWidth: null, + values: [ + {text: 'None', value: ''}, + {text: 'Left', value: 'left'}, + {text: 'Center', value: 'center'}, + {text: 'Right', value: 'right'} + ] + } + ] + }, + + onsubmit: function() { + var data = this.toJSON(), captionElm; + + editor.undoManager.transact(function() { + editor.dom.setAttribs(tableElm, { + cellspacing: data.cellspacing, + cellpadding: data.cellpadding, + border: data.border + }); + + editor.dom.setStyles(tableElm, { + width: addSizeSuffix(data.width), + height: addSizeSuffix(data.height) + }); + + // Toggle caption on/off + captionElm = dom.select('caption', tableElm)[0]; + + if (captionElm && !data.caption) { + dom.remove(captionElm); + } + + if (!captionElm && data.caption) { + captionElm = dom.create('caption'); + + if (!Env.ie) { + captionElm.innerHTML = '
    '; + } + + tableElm.insertBefore(captionElm, tableElm.firstChild); + } + + // Apply/remove alignment + if (data.align) { + editor.formatter.apply('align' + data.align, {}, tableElm); + } else { + each('left center right'.split(' '), function(name) { + editor.formatter.remove('align' + name, {}, tableElm); + }); + } + + editor.focus(); + editor.addVisual(); + }); + } + }); + } + + function mergeDialog(grid, cell) { + editor.windowManager.open({ + title: "Merge cells", + body: [ + {label: 'Columns', name: 'cols', type: 'textbox', size: 5}, + {label: 'Rows', name: 'rows', type: 'textbox', size: 5} + ], + onsubmit: function() { + var data = this.toJSON(); + + editor.undoManager.transact(function() { + grid.merge(cell, data.cols, data.rows); + }); + } + }); + } + + function cellDialog() { + var dom = editor.dom, cellElm, data, cells = []; + + // Get selected cells or the current cell + cells = editor.dom.select('td.mce-item-selected,th.mce-item-selected'); + cellElm = editor.dom.getParent(editor.selection.getNode(), 'td,th'); + if (!cells.length && cellElm) { + cells.push(cellElm); + } + + cellElm = cellElm || cells[0]; + + data = { + width: removePxSuffix(dom.getStyle(cellElm, 'width') || dom.getAttrib(cellElm, 'width')), + height: removePxSuffix(dom.getStyle(cellElm, 'height') || dom.getAttrib(cellElm, 'height')), + scope: dom.getAttrib(cellElm, 'scope') + }; + + data.type = cellElm.nodeName.toLowerCase(); + + each('left center right'.split(' '), function(name) { + if (editor.formatter.matchNode(cellElm, 'align' + name)) { + data.align = name; + } + }); + + editor.windowManager.open({ + title: "Cell properties", + items: { + type: 'form', + data: data, + layout: 'grid', + columns: 2, + defaults: { + type: 'textbox', + maxWidth: 50 + }, + items: [ + {label: 'Width', name: 'width'}, + {label: 'Height', name: 'height'}, + { + label: 'Cell type', + name: 'type', + type: 'listbox', + text: 'None', + minWidth: 90, + maxWidth: null, + menu: [ + {text: 'Cell', value: 'td'}, + {text: 'Header cell', value: 'th'} + ] + }, + { + label: 'Scope', + name: 'scope', + type: 'listbox', + text: 'None', + minWidth: 90, + maxWidth: null, + menu: [ + {text: 'None', value: ''}, + {text: 'Row', value: 'row'}, + {text: 'Column', value: 'col'}, + {text: 'Row group', value: 'rowgroup'}, + {text: 'Column group', value: 'colgroup'} + ] + }, + { + label: 'Alignment', + name: 'align', + type: 'listbox', + text: 'None', + minWidth: 90, + maxWidth: null, + values: [ + {text: 'None', value: ''}, + {text: 'Left', value: 'left'}, + {text: 'Center', value: 'center'}, + {text: 'Right', value: 'right'} + ] + } + ] + }, + + onsubmit: function() { + var data = this.toJSON(); + + editor.undoManager.transact(function() { + each(cells, function(cellElm) { + editor.dom.setAttrib(cellElm, 'scope', data.scope); + + editor.dom.setStyles(cellElm, { + width: addSizeSuffix(data.width), + height: addSizeSuffix(data.height) + }); + + // Switch cell type + if (data.type && cellElm.nodeName.toLowerCase() != data.type) { + cellElm = dom.rename(cellElm, data.type); + } + + // Apply/remove alignment + if (data.align) { + editor.formatter.apply('align' + data.align, {}, cellElm); + } else { + each('left center right'.split(' '), function(name) { + editor.formatter.remove('align' + name, {}, cellElm); + }); + } + }); + + editor.focus(); + }); + } + }); + } + + function rowDialog() { + var dom = editor.dom, tableElm, cellElm, rowElm, data, rows = []; + + tableElm = editor.dom.getParent(editor.selection.getNode(), 'table'); + cellElm = editor.dom.getParent(editor.selection.getNode(), 'td,th'); + + each(tableElm.rows, function(row) { + each(row.cells, function(cell) { + if (dom.hasClass(cell, 'mce-item-selected') || cell == cellElm) { + rows.push(row); + return false; + } + }); + }); + + rowElm = rows[0]; + + data = { + height: removePxSuffix(dom.getStyle(rowElm, 'height') || dom.getAttrib(rowElm, 'height')), + scope: dom.getAttrib(rowElm, 'scope') + }; + + data.type = rowElm.parentNode.nodeName.toLowerCase(); + + each('left center right'.split(' '), function(name) { + if (editor.formatter.matchNode(rowElm, 'align' + name)) { + data.align = name; + } + }); + + editor.windowManager.open({ + title: "Row properties", + items: { + type: 'form', + data: data, + columns: 2, + defaults: { + type: 'textbox' + }, + items: [ + { + type: 'listbox', + name: 'type', + label: 'Row type', + text: 'None', + maxWidth: null, + menu: [ + {text: 'header', value: 'thead'}, + {text: 'body', value: 'tbody'}, + {text: 'footer', value: 'tfoot'} + ] + }, + { + type: 'listbox', + name: 'align', + label: 'Alignment', + text: 'None', + maxWidth: null, + menu: [ + {text: 'None', value: ''}, + {text: 'Left', value: 'left'}, + {text: 'Center', value: 'center'}, + {text: 'Right', value: 'right'} + ] + }, + {label: 'Height', name: 'height'} + ] + }, + + onsubmit: function() { + var data = this.toJSON(), tableElm, oldParentElm, parentElm; + + editor.undoManager.transact(function() { + each(rows, function(rowElm) { + editor.dom.setAttrib(rowElm, 'scope', data.scope); + + editor.dom.setStyles(rowElm, { + height: addSizeSuffix(data.height) + }); + + if (data.type != rowElm.parentNode.nodeName.toLowerCase()) { + tableElm = dom.getParent(rowElm, 'table'); + + oldParentElm = rowElm.parentNode; + parentElm = dom.select(tableElm, data.type)[0]; + if (!parentElm) { + parentElm = dom.create(data.type); + if (tableElm.firstChild) { + tableElm.insertBefore(parentElm, tableElm.firstChild); + } else { + tableElm.appendChild(parentElm); + } + } + + parentElm.insertBefore(rowElm, parentElm.firstChild); + + if (!oldParentElm.hasChildNodes()) { + dom.remove(oldParentElm); + } + } + + // Apply/remove alignment + if (data.align) { + editor.formatter.apply('align' + data.align, {}, rowElm); + } else { + each('left center right'.split(' '), function(name) { + editor.formatter.remove('align' + name, {}, rowElm); + }); + } + }); + + editor.focus(); + }); + } + }); + } + + function cmd(command) { + return function() { + editor.execCommand(command); + }; + } + + function insertTable(cols, rows) { + var y, x, html; + + html = ''; + + for (y = 0; y < rows; y++) { + html += ''; + + for (x = 0; x < cols; x++) { + html += ''; + } + + html += ''; + } + + html += '
    ' + (Env.ie ? " " : '
    ') + '
    '; + + editor.insertContent(html); + } + + function postRender() { + /*jshint validthis:true*/ + var self = this; + + function bindStateListener() { + self.disabled(!editor.dom.getParent(editor.selection.getNode(), 'table')); + + editor.selection.selectorChanged('table', function(state) { + self.disabled(!state); + }); + } + + if (editor.initialized) { + bindStateListener(); + } else { + editor.on('init', bindStateListener); + } + } + + // Register buttons + each([ + ['table', 'Insert/edit table', 'mceInsertTable'], + ['delete_table', 'Delete table', 'mceTableDelete'], + ['delete_col', 'Delete column', 'mceTableDeleteCol'], + ['delete_row', 'Delete row', 'mceTableDeleteRow'], + ['col_after', 'Insert column after', 'mceTableInsertColAfter'], + ['col_before', 'Insert column before', 'mceTableInsertColBefore'], + ['row_after', 'Insert row after', 'mceTableInsertRowAfter'], + ['row_before', 'Insert row before', 'mceTableInsertRowBefore'], + ['row_props', 'Row properties', 'mceTableRowProps'], + ['cell_props', 'Cell properties', 'mceTableCellProps'], + ['split_cells', 'Split cells', 'mceTableSplitCells'], + ['merge_cells', 'Merge cells', 'mceTableMergeCells'] + ], function(c) { + editor.addButton(c[0], { + title : c[1], + cmd : c[2], + onPostRender: postRender + }); + }); + + function generateTableGrid() { + var html = ''; + + html = ''; + + for (var y = 0; y < 10; y++) { + html += ''; + + for (var x = 0; x < 10; x++) { + html += ''; + } + + html += ''; + } + + html += ''; + + html += '
    0 x 0
    '; + + return html; + } + + editor.addMenuItem('inserttable', { + text: 'Insert table', + icon: 'table', + context: 'table', + onhide: function() { + editor.dom.removeClass(this.menu.items()[0].getEl().getElementsByTagName('a'), 'mce-active'); + }, + menu: [ + { + type: 'container', + html: generateTableGrid(), + + onmousemove: function(e) { + var target = e.target; + + if (target.nodeName == 'A') { + var table = editor.dom.getParent(target, 'table'); + var pos = target.getAttribute('data-mce-index'); + + if (pos != this.lastPos) { + pos = pos.split(','); + + pos[0] = parseInt(pos[0], 10); + pos[1] = parseInt(pos[1], 10); + + for (var y = 0; y < 10; y++) { + for (var x = 0; x < 10; x++) { + editor.dom.toggleClass( + table.rows[y].childNodes[x].firstChild, + 'mce-active', + x <= pos[0] && y <= pos[1] + ); + } + } + + table.nextSibling.innerHTML = (pos[0] + 1) + ' x '+ (pos[1] + 1); + this.lastPos = pos; + } + } + }, + + onclick: function(e) { + if (e.target.nodeName == 'A' && this.lastPos) { + e.preventDefault(); + + insertTable(this.lastPos[0] + 1, this.lastPos[1] + 1); + + // TODO: Maybe rework this? + this.parent().cancel(); // Close parent menu as if it was a click + } + } + } + ] + }); + + editor.addMenuItem('tableprops', { + text: 'Table properties', + context: 'table', + onPostRender: postRender, + onclick: tableDialog + }); + + editor.addMenuItem('deletetable', { + text: 'Delete table', + context: 'table', + onPostRender: postRender, + cmd: 'mceTableDelete' + }); + + editor.addMenuItem('cell', { + separator: 'before', + text: 'Cell', + context: 'table', + menu: [ + {text: 'Cell properties', onclick: cmd('mceTableCellProps'), onPostRender: postRender}, + {text: 'Merge cells', onclick: cmd('mceTableMergeCells'), onPostRender: postRender}, + {text: 'Split cell', onclick: cmd('mceTableSplitCells'), onPostRender: postRender} + ] + }); + + editor.addMenuItem('row', { + text: 'Row', + context: 'table', + menu: [ + {text: 'Insert row before', onclick: cmd('mceTableInsertRowBefore'), onPostRender: postRender}, + {text: 'Insert row after', onclick: cmd('mceTableInsertRowAfter'), onPostRender: postRender}, + {text: 'Delete row', onclick: cmd('mceTableDeleteRow'), onPostRender: postRender}, + {text: 'Row properties', onclick: cmd('mceTableRowProps'), onPostRender: postRender}, + {text: '-'}, + {text: 'Cut row', onclick: cmd('mceTableCutRow'), onPostRender: postRender}, + {text: 'Copy row', onclick: cmd('mceTableCopyRow'), onPostRender: postRender}, + {text: 'Paste row before', onclick: cmd('mceTablePasteRowBefore'), onPostRender: postRender}, + {text: 'Paste row after', onclick: cmd('mceTablePasteRowAfter'), onPostRender: postRender} + ] + }); + + editor.addMenuItem('column', { + text: 'Column', + context: 'table', + menu: [ + {text: 'Insert column before', onclick: cmd('mceTableInsertColBefore'), onPostRender: postRender}, + {text: 'Insert column after', onclick: cmd('mceTableInsertColAfter'), onPostRender: postRender}, + {text: 'Delete column', onclick: cmd('mceTableDeleteCol'), onPostRender: postRender} + ] + }); + + // Select whole table is a table border is clicked + if (!Env.isIE) { + editor.on('click', function(e) { + e = e.target; + + if (e.nodeName === 'TABLE') { + editor.selection.select(e); + editor.nodeChanged(); + } + }); + } + + self.quirks = new Quirks(editor); + + editor.on('Init', function() { + winMan = editor.windowManager; + self.cellSelection = new CellSelection(editor); + }); + + // Register action commands + each({ + mceTableSplitCells: function(grid) { + grid.split(); + }, + + mceTableMergeCells: function(grid) { + var rowSpan, colSpan, cell; + + cell = editor.dom.getParent(editor.selection.getNode(), 'th,td'); + if (cell) { + rowSpan = cell.rowSpan; + colSpan = cell.colSpan; + } + + if (!editor.dom.select('td.mce-item-selected,th.mce-item-selected').length) { + mergeDialog(grid, cell); + } else { + grid.merge(); + } + }, + + mceTableInsertRowBefore: function(grid) { + grid.insertRow(true); + }, + + mceTableInsertRowAfter: function(grid) { + grid.insertRow(); + }, + + mceTableInsertColBefore: function(grid) { + grid.insertCol(true); + }, + + mceTableInsertColAfter: function(grid) { + grid.insertCol(); + }, + + mceTableDeleteCol: function(grid) { + grid.deleteCols(); + }, + + mceTableDeleteRow: function(grid) { + grid.deleteRows(); + }, + + mceTableCutRow: function(grid) { + clipboardRows = grid.cutRows(); + }, + + mceTableCopyRow: function(grid) { + clipboardRows = grid.copyRows(); + }, + + mceTablePasteRowBefore: function(grid) { + grid.pasteRows(clipboardRows, true); + }, + + mceTablePasteRowAfter: function(grid) { + grid.pasteRows(clipboardRows); + }, + + mceTableDelete: function(grid) { + grid.deleteTable(); + } + }, function(func, name) { + editor.addCommand(name, function() { + var grid = new TableGrid(editor.selection); + + if (grid) { + func(grid); + editor.execCommand('mceRepaint'); + self.cellSelection.clear(); + } + }); + }); + + // Register dialog commands + each({ + mceInsertTable: function() { + tableDialog(); + }, + + mceTableRowProps: rowDialog, + mceTableCellProps: cellDialog + }, function(func, name) { + editor.addCommand(name, function(ui, val) { + func(val); + }); + }); + } + + PluginManager.add('table', Plugin); +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/table/classes/Quirks.js b/lib/tinymce/jscripts/tinymce4/plugins/table/classes/Quirks.js new file mode 100644 index 00000000..dec47aff --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/table/classes/Quirks.js @@ -0,0 +1,340 @@ +/** + * Quirks.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class includes fixes for various browser quirks. + * + * @class tinymce.tableplugin.Quirks + * @private + */ +define("tinymce/tableplugin/Quirks", [ + "tinymce/util/VK", + "tinymce/Env", + "tinymce/util/Tools" +], function(VK, Env, Tools) { + var each = Tools.each; + + function getSpanVal(td, name) { + return parseInt(td.getAttribute(name) || 1, 10); + } + + return function(editor) { + /** + * Fixed caret movement around tables on WebKit. + */ + function moveWebKitSelection() { + function eventHandler(e) { + var key = e.keyCode; + + function handle(upBool, sourceNode) { + var siblingDirection = upBool ? 'previousSibling' : 'nextSibling'; + var currentRow = editor.dom.getParent(sourceNode, 'tr'); + var siblingRow = currentRow[siblingDirection]; + + if (siblingRow) { + moveCursorToRow(editor, sourceNode, siblingRow, upBool); + e.preventDefault(); + return true; + } else { + var tableNode = editor.dom.getParent(currentRow, 'table'); + var middleNode = currentRow.parentNode; + var parentNodeName = middleNode.nodeName.toLowerCase(); + if (parentNodeName === 'tbody' || parentNodeName === (upBool ? 'tfoot' : 'thead')) { + var targetParent = getTargetParent(upBool, tableNode, middleNode, 'tbody'); + if (targetParent !== null) { + return moveToRowInTarget(upBool, targetParent, sourceNode); + } + } + return escapeTable(upBool, currentRow, siblingDirection, tableNode); + } + } + + function getTargetParent(upBool, topNode, secondNode, nodeName) { + var tbodies = editor.dom.select('>' + nodeName, topNode); + var position = tbodies.indexOf(secondNode); + if (upBool && position === 0 || !upBool && position === tbodies.length - 1) { + return getFirstHeadOrFoot(upBool, topNode); + } else if (position === -1) { + var topOrBottom = secondNode.tagName.toLowerCase() === 'thead' ? 0 : tbodies.length - 1; + return tbodies[topOrBottom]; + } else { + return tbodies[position + (upBool ? -1 : 1)]; + } + } + + function getFirstHeadOrFoot(upBool, parent) { + var tagName = upBool ? 'thead' : 'tfoot'; + var headOrFoot = editor.dom.select('>' + tagName, parent); + return headOrFoot.length !== 0 ? headOrFoot[0] : null; + } + + function moveToRowInTarget(upBool, targetParent, sourceNode) { + var targetRow = getChildForDirection(targetParent, upBool); + + if (targetRow) { + moveCursorToRow(editor, sourceNode, targetRow, upBool); + } + + e.preventDefault(); + return true; + } + + function escapeTable(upBool, currentRow, siblingDirection, table) { + var tableSibling = table[siblingDirection]; + + if (tableSibling) { + moveCursorToStartOfElement(tableSibling); + return true; + } else { + var parentCell = editor.dom.getParent(table, 'td,th'); + if (parentCell) { + return handle(upBool, parentCell, e); + } else { + var backUpSibling = getChildForDirection(currentRow, !upBool); + moveCursorToStartOfElement(backUpSibling); + e.preventDefault(); + return false; + } + } + } + + function getChildForDirection(parent, up) { + var child = parent && parent[up ? 'lastChild' : 'firstChild']; + // BR is not a valid table child to return in this case we return the table cell + return child && child.nodeName === 'BR' ? editor.dom.getParent(child, 'td,th') : child; + } + + function moveCursorToStartOfElement(n) { + editor.selection.setCursorLocation(n, 0); + } + + function isVerticalMovement() { + return key == VK.UP || key == VK.DOWN; + } + + function isInTable(editor) { + var node = editor.selection.getNode(); + var currentRow = editor.dom.getParent(node, 'tr'); + return currentRow !== null; + } + + function columnIndex(column) { + var colIndex = 0; + var c = column; + while (c.previousSibling) { + c = c.previousSibling; + colIndex = colIndex + getSpanVal(c, "colspan"); + } + return colIndex; + } + + function findColumn(rowElement, columnIndex) { + var c = 0, r = 0; + + each(rowElement.children, function(cell, i) { + c = c + getSpanVal(cell, "colspan"); + r = i; + if (c > columnIndex) { + return false; + } + }); + return r; + } + + function moveCursorToRow(ed, node, row, upBool) { + var srcColumnIndex = columnIndex(editor.dom.getParent(node, 'td,th')); + var tgtColumnIndex = findColumn(row, srcColumnIndex); + var tgtNode = row.childNodes[tgtColumnIndex]; + var rowCellTarget = getChildForDirection(tgtNode, upBool); + moveCursorToStartOfElement(rowCellTarget || tgtNode); + } + + function shouldFixCaret(preBrowserNode) { + var newNode = editor.selection.getNode(); + var newParent = editor.dom.getParent(newNode, 'td,th'); + var oldParent = editor.dom.getParent(preBrowserNode, 'td,th'); + + return newParent && newParent !== oldParent && checkSameParentTable(newParent, oldParent); + } + + function checkSameParentTable(nodeOne, NodeTwo) { + return editor.dom.getParent(nodeOne, 'TABLE') === editor.dom.getParent(NodeTwo, 'TABLE'); + } + + if (isVerticalMovement() && isInTable(editor)) { + var preBrowserNode = editor.selection.getNode(); + setTimeout(function() { + if (shouldFixCaret(preBrowserNode)) { + handle(!e.shiftKey && key === VK.UP, preBrowserNode, e); + } + }, 0); + } + } + + editor.on('KeyDown', function(e) { + eventHandler(e); + }); + } + + function fixBeforeTableCaretBug() { + // Checks if the selection/caret is at the start of the specified block element + function isAtStart(rng, par) { + var doc = par.ownerDocument, rng2 = doc.createRange(), elm; + + rng2.setStartBefore(par); + rng2.setEnd(rng.endContainer, rng.endOffset); + + elm = doc.createElement('body'); + elm.appendChild(rng2.cloneContents()); + + // Check for text characters of other elements that should be treated as content + return elm.innerHTML.replace(/<(br|img|object|embed|input|textarea)[^>]*>/gi, '-').replace(/<[^>]+>/g, '').length === 0; + } + + // Fixes an bug where it's impossible to place the caret before a table in Gecko + // this fix solves it by detecting when the caret is at the beginning of such a table + // and then manually moves the caret infront of the table + editor.on('KeyDown', function(e) { + var rng, table, dom = editor.dom; + + // On gecko it's not possible to place the caret before a table + if (e.keyCode == 37 || e.keyCode == 38) { + rng = editor.selection.getRng(); + table = dom.getParent(rng.startContainer, 'table'); + + if (table && editor.getBody().firstChild == table) { + if (isAtStart(rng, table)) { + rng = dom.createRng(); + + rng.setStartBefore(table); + rng.setEndBefore(table); + + editor.selection.setRng(rng); + + e.preventDefault(); + } + } + } + }); + } + + // Fixes an issue on Gecko where it's impossible to place the caret behind a table + // This fix will force a paragraph element after the table but only when the forced_root_block setting is enabled + function fixTableCaretPos() { + editor.on('KeyDown SetContent VisualAid', function() { + var last; + + // Skip empty text nodes from the end + for (last = editor.getBody().lastChild; last; last = last.previousSibling) { + if (last.nodeType == 3) { + if (last.nodeValue.length > 0) { + break; + } + } else if (last.nodeType == 1 && !last.getAttribute('data-mce-bogus')) { + break; + } + } + + if (last && last.nodeName == 'TABLE') { + if (editor.settings.forced_root_block) { + editor.dom.add( + editor.getBody(), + editor.settings.forced_root_block, + null, + Env.ie ? ' ' : '
    ' + ); + } else { + editor.dom.add(editor.getBody(), 'br', {'data-mce-bogus': '1'}); + } + } + }); + + editor.on('PreProcess', function(o) { + var last = o.node.lastChild; + + if (last && (last.nodeName == "BR" || (last.childNodes.length == 1 && + (last.firstChild.nodeName == 'BR' || last.firstChild.nodeValue == '\u00a0'))) && + last.previousSibling && last.previousSibling.nodeName == "TABLE") { + editor.dom.remove(last); + } + }); + } + + // this nasty hack is here to work around some WebKit selection bugs. + function fixTableCellSelection() { + function tableCellSelected(ed, rng, n, currentCell) { + // The decision of when a table cell is selected is somewhat involved. The fact that this code is + // required is actually a pointer to the root cause of this bug. A cell is selected when the start + // and end offsets are 0, the start container is a text, and the selection node is either a TR (most cases) + // or the parent of the table (in the case of the selection containing the last cell of a table). + var TEXT_NODE = 3, table = ed.dom.getParent(rng.startContainer, 'TABLE'); + var tableParent, allOfCellSelected, tableCellSelection; + + if (table) { + tableParent = table.parentNode; + } + + allOfCellSelected =rng.startContainer.nodeType == TEXT_NODE && + rng.startOffset === 0 && + rng.endOffset === 0 && + currentCell && + (n.nodeName == "TR" || n == tableParent); + + tableCellSelection = (n.nodeName == "TD" || n.nodeName == "TH") && !currentCell; + + return allOfCellSelected || tableCellSelection; + } + + function fixSelection() { + var rng = editor.selection.getRng(); + var n = editor.selection.getNode(); + var currentCell = editor.dom.getParent(rng.startContainer, 'TD,TH'); + + if (!tableCellSelected(editor, rng, n, currentCell)) { + return; + } + + if (!currentCell) { + currentCell=n; + } + + // Get the very last node inside the table cell + var end = currentCell.lastChild; + while (end.lastChild) { + end = end.lastChild; + } + + // Select the entire table cell. Nothing outside of the table cell should be selected. + rng.setEnd(end, end.nodeValue.length); + editor.selection.setRng(rng); + } + + editor.on('KeyDown', function() { + fixSelection(); + }); + + editor.on('MouseDown', function(e) { + if (e.button != 2) { + fixSelection(); + } + }); + } + + if (Env.webkit) { + moveWebKitSelection(); + fixTableCellSelection(); + } + + if (Env.gecko) { + fixBeforeTableCaretBug(); + fixTableCaretPos(); + } + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/table/classes/TableGrid.js b/lib/tinymce/jscripts/tinymce4/plugins/table/classes/TableGrid.js new file mode 100644 index 00000000..40950fa2 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/table/classes/TableGrid.js @@ -0,0 +1,811 @@ +/** + * TableGrid.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class creates a grid out of a table element. This + * makes it a whole lot easier to handle complex tables with + * col/row spans. + * + * @class tinymce.tableplugin.TableGrid + * @private + */ +define("tinymce/tableplugin/TableGrid", [ + "tinymce/util/Tools", + "tinymce/Env" +], function(Tools, Env) { + var each = Tools.each; + + function getSpanVal(td, name) { + return parseInt(td.getAttribute(name) || 1, 10); + } + + return function(selection, table) { + var grid, startPos, endPos, selectedCell, dom = selection.dom; + + function buildGrid() { + var startY = 0; + + grid = []; + + each(['thead', 'tbody', 'tfoot'], function(part) { + var rows = dom.select('> ' + part + ' tr', table); + + each(rows, function(tr, y) { + y += startY; + + each(dom.select('> td, > th', tr), function(td, x) { + var x2, y2, rowspan, colspan; + + // Skip over existing cells produced by rowspan + if (grid[y]) { + while (grid[y][x]) { + x++; + } + } + + // Get col/rowspan from cell + rowspan = getSpanVal(td, 'rowspan'); + colspan = getSpanVal(td, 'colspan'); + + // Fill out rowspan/colspan right and down + for (y2 = y; y2 < y + rowspan; y2++) { + if (!grid[y2]) { + grid[y2] = []; + } + + for (x2 = x; x2 < x + colspan; x2++) { + grid[y2][x2] = { + part: part, + real: y2 == y && x2 == x, + elm: td, + rowspan: rowspan, + colspan: colspan + }; + } + } + }); + }); + + startY += rows.length; + }); + } + + function cloneNode(node, children) { + node = node.cloneNode(children); + node.removeAttribute('id'); + + return node; + } + + function getCell(x, y) { + var row; + + row = grid[y]; + if (row) { + return row[x]; + } + } + + function setSpanVal(td, name, val) { + if (td) { + val = parseInt(val, 10); + + if (val === 1) { + td.removeAttribute(name, 1); + } else { + td.setAttribute(name, val, 1); + } + } + } + + function isCellSelected(cell) { + return cell && (dom.hasClass(cell.elm, 'mce-item-selected') || cell == selectedCell); + } + + function getSelectedRows() { + var rows = []; + + each(table.rows, function(row) { + each(row.cells, function(cell) { + if (dom.hasClass(cell, 'mce-item-selected') || cell == selectedCell.elm) { + rows.push(row); + return false; + } + }); + }); + + return rows; + } + + function deleteTable() { + var rng = dom.createRng(); + + rng.setStartAfter(table); + rng.setEndAfter(table); + + selection.setRng(rng); + + dom.remove(table); + } + + function cloneCell(cell) { + var formatNode; + + // Clone formats + Tools.walk(cell, function(node) { + var curNode; + + if (node.nodeType == 3) { + each(dom.getParents(node.parentNode, null, cell).reverse(), function(node) { + node = cloneNode(node, false); + + if (!formatNode) { + formatNode = curNode = node; + } else if (curNode) { + curNode.appendChild(node); + } + + curNode = node; + }); + + // Add something to the inner node + if (curNode) { + curNode.innerHTML = Env.ie ? ' ' : '
    '; + } + + return false; + } + }, 'childNodes'); + + cell = cloneNode(cell, false); + setSpanVal(cell, 'rowSpan', 1); + setSpanVal(cell, 'colSpan', 1); + + if (formatNode) { + cell.appendChild(formatNode); + } else { + if (!Env.ie) { + cell.innerHTML = '
    '; + } + } + + return cell; + } + + function cleanup() { + var rng = dom.createRng(), row; + + // Empty rows + each(dom.select('tr', table), function(tr) { + if (tr.cells.length === 0) { + dom.remove(tr); + } + }); + + // Empty table + if (dom.select('tr', table).length === 0) { + rng.setStartAfter(table); + rng.setEndAfter(table); + selection.setRng(rng); + dom.remove(table); + return; + } + + // Empty header/body/footer + each(dom.select('thead,tbody,tfoot', table), function(part) { + if (part.rows.length === 0) { + dom.remove(part); + } + }); + + // Restore selection to start position if it still exists + buildGrid(); + + // Restore the selection to the closest table position + row = grid[Math.min(grid.length - 1, startPos.y)]; + if (row) { + selection.select(row[Math.min(row.length - 1, startPos.x)].elm, true); + selection.collapse(true); + } + } + + function fillLeftDown(x, y, rows, cols) { + var tr, x2, r, c, cell; + + tr = grid[y][x].elm.parentNode; + for (r = 1; r <= rows; r++) { + tr = dom.getNext(tr, 'tr'); + + if (tr) { + // Loop left to find real cell + for (x2 = x; x2 >= 0; x2--) { + cell = grid[y + r][x2].elm; + + if (cell.parentNode == tr) { + // Append clones after + for (c = 1; c <= cols; c++) { + dom.insertAfter(cloneCell(cell), cell); + } + + break; + } + } + + if (x2 == -1) { + // Insert nodes before first cell + for (c = 1; c <= cols; c++) { + tr.insertBefore(cloneCell(tr.cells[0]), tr.cells[0]); + } + } + } + } + } + + function split() { + each(grid, function(row, y) { + each(row, function(cell, x) { + var colSpan, rowSpan, i; + + if (isCellSelected(cell)) { + cell = cell.elm; + colSpan = getSpanVal(cell, 'colspan'); + rowSpan = getSpanVal(cell, 'rowspan'); + + if (colSpan > 1 || rowSpan > 1) { + setSpanVal(cell, 'rowSpan', 1); + setSpanVal(cell, 'colSpan', 1); + + // Insert cells right + for (i = 0; i < colSpan - 1; i++) { + dom.insertAfter(cloneCell(cell), cell); + } + + fillLeftDown(x, y, rowSpan - 1, colSpan); + } + } + }); + }); + } + + function merge(cell, cols, rows) { + var pos, startX, startY, endX, endY, x, y, startCell, endCell, children, count; + + // Use specified cell and cols/rows + if (cell) { + pos = getPos(cell); + startX = pos.x; + startY = pos.y; + endX = startX + (cols - 1); + endY = startY + (rows - 1); + } else { + startPos = endPos = null; + + // Calculate start/end pos by checking for selected cells in grid works better with context menu + each(grid, function(row, y) { + each(row, function(cell, x) { + if (isCellSelected(cell)) { + if (!startPos) { + startPos = {x: x, y: y}; + } + + endPos = {x: x, y: y}; + } + }); + }); + + // Use selection + startX = startPos.x; + startY = startPos.y; + endX = endPos.x; + endY = endPos.y; + } + + // Find start/end cells + startCell = getCell(startX, startY); + endCell = getCell(endX, endY); + + // Check if the cells exists and if they are of the same part for example tbody = tbody + if (startCell && endCell && startCell.part == endCell.part) { + // Split and rebuild grid + split(); + buildGrid(); + + // Set row/col span to start cell + startCell = getCell(startX, startY).elm; + setSpanVal(startCell, 'colSpan', (endX - startX) + 1); + setSpanVal(startCell, 'rowSpan', (endY - startY) + 1); + + // Remove other cells and add it's contents to the start cell + for (y = startY; y <= endY; y++) { + for (x = startX; x <= endX; x++) { + if (!grid[y] || !grid[y][x]) { + continue; + } + + cell = grid[y][x].elm; + + /*jshint loopfunc:true */ + if (cell != startCell) { + // Move children to startCell + children = Tools.grep(cell.childNodes); + each(children, function(node) { + startCell.appendChild(node); + }); + + // Remove bogus nodes if there is children in the target cell + if (children.length) { + children = Tools.grep(startCell.childNodes); + count = 0; + each(children, function(node) { + if (node.nodeName == 'BR' && dom.getAttrib(node, 'data-mce-bogus') && count++ < children.length - 1) { + startCell.removeChild(node); + } + }); + } + + dom.remove(cell); + } + } + } + + // Remove empty rows etc and restore caret location + cleanup(); + } + } + + function insertRow(before) { + var posY, cell, lastCell, x, rowElm, newRow, newCell, otherCell, rowSpan; + + // Find first/last row + each(grid, function(row, y) { + each(row, function(cell) { + if (isCellSelected(cell)) { + cell = cell.elm; + rowElm = cell.parentNode; + newRow = cloneNode(rowElm, false); + posY = y; + + if (before) { + return false; + } + } + }); + + if (before) { + return !posY; + } + }); + + for (x = 0; x < grid[0].length; x++) { + // Cell not found could be because of an invalid table structure + if (!grid[posY][x]) { + continue; + } + + cell = grid[posY][x].elm; + + if (cell != lastCell) { + if (!before) { + rowSpan = getSpanVal(cell, 'rowspan'); + if (rowSpan > 1) { + setSpanVal(cell, 'rowSpan', rowSpan + 1); + continue; + } + } else { + // Check if cell above can be expanded + if (posY > 0 && grid[posY - 1][x]) { + otherCell = grid[posY - 1][x].elm; + rowSpan = getSpanVal(otherCell, 'rowSpan'); + if (rowSpan > 1) { + setSpanVal(otherCell, 'rowSpan', rowSpan + 1); + continue; + } + } + } + + // Insert new cell into new row + newCell = cloneCell(cell); + setSpanVal(newCell, 'colSpan', cell.colSpan); + + newRow.appendChild(newCell); + + lastCell = cell; + } + } + + if (newRow.hasChildNodes()) { + if (!before) { + dom.insertAfter(newRow, rowElm); + } else { + rowElm.parentNode.insertBefore(newRow, rowElm); + } + } + } + + function insertCol(before) { + var posX, lastCell; + + // Find first/last column + each(grid, function(row) { + each(row, function(cell, x) { + if (isCellSelected(cell)) { + posX = x; + + if (before) { + return false; + } + } + }); + + if (before) { + return !posX; + } + }); + + each(grid, function(row, y) { + var cell, rowSpan, colSpan; + + if (!row[posX]) { + return; + } + + cell = row[posX].elm; + if (cell != lastCell) { + colSpan = getSpanVal(cell, 'colspan'); + rowSpan = getSpanVal(cell, 'rowspan'); + + if (colSpan == 1) { + if (!before) { + dom.insertAfter(cloneCell(cell), cell); + fillLeftDown(posX, y, rowSpan - 1, colSpan); + } else { + cell.parentNode.insertBefore(cloneCell(cell), cell); + fillLeftDown(posX, y, rowSpan - 1, colSpan); + } + } else { + setSpanVal(cell, 'colSpan', cell.colSpan + 1); + } + + lastCell = cell; + } + }); + } + + function deleteCols() { + var cols = []; + + // Get selected column indexes + each(grid, function(row) { + each(row, function(cell, x) { + if (isCellSelected(cell) && Tools.inArray(cols, x) === -1) { + each(grid, function(row) { + var cell = row[x].elm, colSpan; + + colSpan = getSpanVal(cell, 'colSpan'); + + if (colSpan > 1) { + setSpanVal(cell, 'colSpan', colSpan - 1); + } else { + dom.remove(cell); + } + }); + + cols.push(x); + } + }); + }); + + cleanup(); + } + + function deleteRows() { + var rows; + + function deleteRow(tr) { + var nextTr, pos, lastCell; + + nextTr = dom.getNext(tr, 'tr'); + + // Move down row spanned cells + each(tr.cells, function(cell) { + var rowSpan = getSpanVal(cell, 'rowSpan'); + + if (rowSpan > 1) { + setSpanVal(cell, 'rowSpan', rowSpan - 1); + pos = getPos(cell); + fillLeftDown(pos.x, pos.y, 1, 1); + } + }); + + // Delete cells + pos = getPos(tr.cells[0]); + each(grid[pos.y], function(cell) { + var rowSpan; + + cell = cell.elm; + + if (cell != lastCell) { + rowSpan = getSpanVal(cell, 'rowSpan'); + + if (rowSpan <= 1) { + dom.remove(cell); + } else { + setSpanVal(cell, 'rowSpan', rowSpan - 1); + } + + lastCell = cell; + } + }); + } + + // Get selected rows and move selection out of scope + rows = getSelectedRows(); + + // Delete all selected rows + each(rows.reverse(), function(tr) { + deleteRow(tr); + }); + + cleanup(); + } + + function cutRows() { + var rows = getSelectedRows(); + + dom.remove(rows); + cleanup(); + + return rows; + } + + function copyRows() { + var rows = getSelectedRows(); + + each(rows, function(row, i) { + rows[i] = cloneNode(row, true); + }); + + return rows; + } + + function pasteRows(rows, before) { + var selectedRows = getSelectedRows(), + targetRow = selectedRows[before ? 0 : selectedRows.length - 1], + targetCellCount = targetRow.cells.length; + + // Nothing to paste + if (!rows) { + return; + } + + // Calc target cell count + each(grid, function(row) { + var match; + + targetCellCount = 0; + each(row, function(cell) { + if (cell.real) { + targetCellCount += cell.colspan; + } + + if (cell.elm.parentNode == targetRow) { + match = 1; + } + }); + + if (match) { + return false; + } + }); + + if (!before) { + rows.reverse(); + } + + each(rows, function(row) { + var i, cellCount = row.cells.length, cell; + + // Remove col/rowspans + for (i = 0; i < cellCount; i++) { + cell = row.cells[i]; + setSpanVal(cell, 'colSpan', 1); + setSpanVal(cell, 'rowSpan', 1); + } + + // Needs more cells + for (i = cellCount; i < targetCellCount; i++) { + row.appendChild(cloneCell(row.cells[cellCount - 1])); + } + + // Needs less cells + for (i = targetCellCount; i < cellCount; i++) { + dom.remove(row.cells[i]); + } + + // Add before/after + if (before) { + targetRow.parentNode.insertBefore(row, targetRow); + } else { + dom.insertAfter(row, targetRow); + } + }); + + // Remove current selection + dom.removeClass(dom.select('td.mce-item-selected,th.mce-item-selected'), 'mce-item-selected'); + } + + function getPos(target) { + var pos; + + each(grid, function(row, y) { + each(row, function(cell, x) { + if (cell.elm == target) { + pos = {x : x, y : y}; + return false; + } + }); + + return !pos; + }); + + return pos; + } + + function setStartCell(cell) { + startPos = getPos(cell); + } + + function findEndPos() { + var maxX, maxY; + + maxX = maxY = 0; + + each(grid, function(row, y) { + each(row, function(cell, x) { + var colSpan, rowSpan; + + if (isCellSelected(cell)) { + cell = grid[y][x]; + + if (x > maxX) { + maxX = x; + } + + if (y > maxY) { + maxY = y; + } + + if (cell.real) { + colSpan = cell.colspan - 1; + rowSpan = cell.rowspan - 1; + + if (colSpan) { + if (x + colSpan > maxX) { + maxX = x + colSpan; + } + } + + if (rowSpan) { + if (y + rowSpan > maxY) { + maxY = y + rowSpan; + } + } + } + } + }); + }); + + return {x : maxX, y : maxY}; + } + + function setEndCell(cell) { + var startX, startY, endX, endY, maxX, maxY, colSpan, rowSpan, x, y; + + endPos = getPos(cell); + + if (startPos && endPos) { + // Get start/end positions + startX = Math.min(startPos.x, endPos.x); + startY = Math.min(startPos.y, endPos.y); + endX = Math.max(startPos.x, endPos.x); + endY = Math.max(startPos.y, endPos.y); + + // Expand end positon to include spans + maxX = endX; + maxY = endY; + + // Expand startX + for (y = startY; y <= maxY; y++) { + cell = grid[y][startX]; + + if (!cell.real) { + if (startX - (cell.colspan - 1) < startX) { + startX -= cell.colspan - 1; + } + } + } + + // Expand startY + for (x = startX; x <= maxX; x++) { + cell = grid[startY][x]; + + if (!cell.real) { + if (startY - (cell.rowspan - 1) < startY) { + startY -= cell.rowspan - 1; + } + } + } + + // Find max X, Y + for (y = startY; y <= endY; y++) { + for (x = startX; x <= endX; x++) { + cell = grid[y][x]; + + if (cell.real) { + colSpan = cell.colspan - 1; + rowSpan = cell.rowspan - 1; + + if (colSpan) { + if (x + colSpan > maxX) { + maxX = x + colSpan; + } + } + + if (rowSpan) { + if (y + rowSpan > maxY) { + maxY = y + rowSpan; + } + } + } + } + } + + // Remove current selection + dom.removeClass(dom.select('td.mce-item-selected,th.mce-item-selected'), 'mce-item-selected'); + + // Add new selection + for (y = startY; y <= maxY; y++) { + for (x = startX; x <= maxX; x++) { + if (grid[y][x]) { + dom.addClass(grid[y][x].elm, 'mce-item-selected'); + } + } + } + } + } + + table = table || dom.getParent(selection.getNode(), 'table'); + + buildGrid(); + + selectedCell = dom.getParent(selection.getStart(), 'th,td'); + if (selectedCell) { + startPos = getPos(selectedCell); + endPos = findEndPos(); + selectedCell = getCell(startPos.x, startPos.y); + } + + Tools.extend(this, { + deleteTable: deleteTable, + split: split, + merge: merge, + insertRow: insertRow, + insertCol: insertCol, + deleteCols: deleteCols, + deleteRows: deleteRows, + cutRows: cutRows, + copyRows: copyRows, + pasteRows: pasteRows, + getPos: getPos, + setStartCell: setStartCell, + setEndCell: setEndCell + }); + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/table/plugin.dev.js b/lib/tinymce/jscripts/tinymce4/plugins/table/plugin.dev.js new file mode 100644 index 00000000..83da5cea --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/table/plugin.dev.js @@ -0,0 +1,119 @@ +/** + * Inline development version. Only to be used while developing since it uses document.write to load scripts. + */ + +/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ +/*globals $code */ + +(function(exports) { + "use strict"; + + var html = "", baseDir; + var modules = {}, exposedModules = [], moduleCount = 0; + + var scripts = document.getElementsByTagName('script'); + for (var i = 0; i < scripts.length; i++) { + var src = scripts[i].src; + + if (src.indexOf('/plugin.dev.js') != -1) { + baseDir = src.substring(0, src.lastIndexOf('/')); + } + } + + function require(ids, callback) { + var module, defs = []; + + for (var i = 0; i < ids.length; ++i) { + module = modules[ids[i]] || resolve(ids[i]); + if (!module) { + throw 'module definition dependecy not found: ' + ids[i]; + } + + defs.push(module); + } + + callback.apply(null, defs); + } + + function resolve(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length; ++fi) { + if (!target[fragments[fi]]) { + return; + } + + target = target[fragments[fi]]; + } + + return target; + } + + function register(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length - 1; ++fi) { + if (target[fragments[fi]] === undefined) { + target[fragments[fi]] = {}; + } + + target = target[fragments[fi]]; + } + + target[fragments[fragments.length - 1]] = modules[id]; + } + + function define(id, dependencies, definition) { + if (typeof id !== 'string') { + throw 'invalid module definition, module id must be defined and be a string'; + } + + if (dependencies === undefined) { + throw 'invalid module definition, dependencies must be specified'; + } + + if (definition === undefined) { + throw 'invalid module definition, definition function must be specified'; + } + + require(dependencies, function() { + modules[id] = definition.apply(null, arguments); + }); + + if (--moduleCount === 0) { + for (var i = 0; i < exposedModules.length; i++) { + register(exposedModules[i]); + } + } + } + + function expose(ids) { + exposedModules = ids; + } + + function writeScripts() { + document.write(html); + } + + function load(path) { + html += '\n'; + moduleCount++; + } + + // Expose globally + exports.define = define; + exports.require = require; + + expose(["tinymce/tableplugin/TableGrid","tinymce/tableplugin/Quirks","tinymce/tableplugin/CellSelection","tinymce/tableplugin/Plugin"]); + + load('classes/TableGrid.js'); + load('classes/Quirks.js'); + load('classes/CellSelection.js'); + load('classes/Plugin.js'); + + writeScripts(); +})(this); + +// $hash: e4bdae6ca54498d0dabca12fdf4a2caf \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/table/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/table/plugin.js new file mode 100644 index 00000000..e7bbfe4d --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/table/plugin.js @@ -0,0 +1,2114 @@ +/** + * Compiled inline version. (Library mode) + */ + +/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ +/*globals $code */ + +(function(exports, undefined) { + "use strict"; + + var modules = {}; + + function require(ids, callback) { + var module, defs = []; + + for (var i = 0; i < ids.length; ++i) { + module = modules[ids[i]] || resolve(ids[i]); + if (!module) { + throw 'module definition dependecy not found: ' + ids[i]; + } + + defs.push(module); + } + + callback.apply(null, defs); + } + + function define(id, dependencies, definition) { + if (typeof id !== 'string') { + throw 'invalid module definition, module id must be defined and be a string'; + } + + if (dependencies === undefined) { + throw 'invalid module definition, dependencies must be specified'; + } + + if (definition === undefined) { + throw 'invalid module definition, definition function must be specified'; + } + + require(dependencies, function() { + modules[id] = definition.apply(null, arguments); + }); + } + + function defined(id) { + return !!modules[id]; + } + + function resolve(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length; ++fi) { + if (!target[fragments[fi]]) { + return; + } + + target = target[fragments[fi]]; + } + + return target; + } + + function expose(ids) { + for (var i = 0; i < ids.length; i++) { + var target = exports; + var id = ids[i]; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length - 1; ++fi) { + if (target[fragments[fi]] === undefined) { + target[fragments[fi]] = {}; + } + + target = target[fragments[fi]]; + } + + target[fragments[fragments.length - 1]] = modules[id]; + } + } + +// Included from: js/tinymce/plugins/table/classes/TableGrid.js + +/** + * TableGrid.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class creates a grid out of a table element. This + * makes it a whole lot easier to handle complex tables with + * col/row spans. + * + * @class tinymce.tableplugin.TableGrid + * @private + */ +define("tinymce/tableplugin/TableGrid", [ + "tinymce/util/Tools", + "tinymce/Env" +], function(Tools, Env) { + var each = Tools.each; + + function getSpanVal(td, name) { + return parseInt(td.getAttribute(name) || 1, 10); + } + + return function(selection, table) { + var grid, startPos, endPos, selectedCell, dom = selection.dom; + + function buildGrid() { + var startY = 0; + + grid = []; + + each(['thead', 'tbody', 'tfoot'], function(part) { + var rows = dom.select('> ' + part + ' tr', table); + + each(rows, function(tr, y) { + y += startY; + + each(dom.select('> td, > th', tr), function(td, x) { + var x2, y2, rowspan, colspan; + + // Skip over existing cells produced by rowspan + if (grid[y]) { + while (grid[y][x]) { + x++; + } + } + + // Get col/rowspan from cell + rowspan = getSpanVal(td, 'rowspan'); + colspan = getSpanVal(td, 'colspan'); + + // Fill out rowspan/colspan right and down + for (y2 = y; y2 < y + rowspan; y2++) { + if (!grid[y2]) { + grid[y2] = []; + } + + for (x2 = x; x2 < x + colspan; x2++) { + grid[y2][x2] = { + part: part, + real: y2 == y && x2 == x, + elm: td, + rowspan: rowspan, + colspan: colspan + }; + } + } + }); + }); + + startY += rows.length; + }); + } + + function cloneNode(node, children) { + node = node.cloneNode(children); + node.removeAttribute('id'); + + return node; + } + + function getCell(x, y) { + var row; + + row = grid[y]; + if (row) { + return row[x]; + } + } + + function setSpanVal(td, name, val) { + if (td) { + val = parseInt(val, 10); + + if (val === 1) { + td.removeAttribute(name, 1); + } else { + td.setAttribute(name, val, 1); + } + } + } + + function isCellSelected(cell) { + return cell && (dom.hasClass(cell.elm, 'mce-item-selected') || cell == selectedCell); + } + + function getSelectedRows() { + var rows = []; + + each(table.rows, function(row) { + each(row.cells, function(cell) { + if (dom.hasClass(cell, 'mce-item-selected') || cell == selectedCell.elm) { + rows.push(row); + return false; + } + }); + }); + + return rows; + } + + function deleteTable() { + var rng = dom.createRng(); + + rng.setStartAfter(table); + rng.setEndAfter(table); + + selection.setRng(rng); + + dom.remove(table); + } + + function cloneCell(cell) { + var formatNode; + + // Clone formats + Tools.walk(cell, function(node) { + var curNode; + + if (node.nodeType == 3) { + each(dom.getParents(node.parentNode, null, cell).reverse(), function(node) { + node = cloneNode(node, false); + + if (!formatNode) { + formatNode = curNode = node; + } else if (curNode) { + curNode.appendChild(node); + } + + curNode = node; + }); + + // Add something to the inner node + if (curNode) { + curNode.innerHTML = Env.ie ? ' ' : '
    '; + } + + return false; + } + }, 'childNodes'); + + cell = cloneNode(cell, false); + setSpanVal(cell, 'rowSpan', 1); + setSpanVal(cell, 'colSpan', 1); + + if (formatNode) { + cell.appendChild(formatNode); + } else { + if (!Env.ie) { + cell.innerHTML = '
    '; + } + } + + return cell; + } + + function cleanup() { + var rng = dom.createRng(), row; + + // Empty rows + each(dom.select('tr', table), function(tr) { + if (tr.cells.length === 0) { + dom.remove(tr); + } + }); + + // Empty table + if (dom.select('tr', table).length === 0) { + rng.setStartAfter(table); + rng.setEndAfter(table); + selection.setRng(rng); + dom.remove(table); + return; + } + + // Empty header/body/footer + each(dom.select('thead,tbody,tfoot', table), function(part) { + if (part.rows.length === 0) { + dom.remove(part); + } + }); + + // Restore selection to start position if it still exists + buildGrid(); + + // Restore the selection to the closest table position + row = grid[Math.min(grid.length - 1, startPos.y)]; + if (row) { + selection.select(row[Math.min(row.length - 1, startPos.x)].elm, true); + selection.collapse(true); + } + } + + function fillLeftDown(x, y, rows, cols) { + var tr, x2, r, c, cell; + + tr = grid[y][x].elm.parentNode; + for (r = 1; r <= rows; r++) { + tr = dom.getNext(tr, 'tr'); + + if (tr) { + // Loop left to find real cell + for (x2 = x; x2 >= 0; x2--) { + cell = grid[y + r][x2].elm; + + if (cell.parentNode == tr) { + // Append clones after + for (c = 1; c <= cols; c++) { + dom.insertAfter(cloneCell(cell), cell); + } + + break; + } + } + + if (x2 == -1) { + // Insert nodes before first cell + for (c = 1; c <= cols; c++) { + tr.insertBefore(cloneCell(tr.cells[0]), tr.cells[0]); + } + } + } + } + } + + function split() { + each(grid, function(row, y) { + each(row, function(cell, x) { + var colSpan, rowSpan, i; + + if (isCellSelected(cell)) { + cell = cell.elm; + colSpan = getSpanVal(cell, 'colspan'); + rowSpan = getSpanVal(cell, 'rowspan'); + + if (colSpan > 1 || rowSpan > 1) { + setSpanVal(cell, 'rowSpan', 1); + setSpanVal(cell, 'colSpan', 1); + + // Insert cells right + for (i = 0; i < colSpan - 1; i++) { + dom.insertAfter(cloneCell(cell), cell); + } + + fillLeftDown(x, y, rowSpan - 1, colSpan); + } + } + }); + }); + } + + function merge(cell, cols, rows) { + var pos, startX, startY, endX, endY, x, y, startCell, endCell, children, count; + + // Use specified cell and cols/rows + if (cell) { + pos = getPos(cell); + startX = pos.x; + startY = pos.y; + endX = startX + (cols - 1); + endY = startY + (rows - 1); + } else { + startPos = endPos = null; + + // Calculate start/end pos by checking for selected cells in grid works better with context menu + each(grid, function(row, y) { + each(row, function(cell, x) { + if (isCellSelected(cell)) { + if (!startPos) { + startPos = {x: x, y: y}; + } + + endPos = {x: x, y: y}; + } + }); + }); + + // Use selection + startX = startPos.x; + startY = startPos.y; + endX = endPos.x; + endY = endPos.y; + } + + // Find start/end cells + startCell = getCell(startX, startY); + endCell = getCell(endX, endY); + + // Check if the cells exists and if they are of the same part for example tbody = tbody + if (startCell && endCell && startCell.part == endCell.part) { + // Split and rebuild grid + split(); + buildGrid(); + + // Set row/col span to start cell + startCell = getCell(startX, startY).elm; + setSpanVal(startCell, 'colSpan', (endX - startX) + 1); + setSpanVal(startCell, 'rowSpan', (endY - startY) + 1); + + // Remove other cells and add it's contents to the start cell + for (y = startY; y <= endY; y++) { + for (x = startX; x <= endX; x++) { + if (!grid[y] || !grid[y][x]) { + continue; + } + + cell = grid[y][x].elm; + + /*jshint loopfunc:true */ + if (cell != startCell) { + // Move children to startCell + children = Tools.grep(cell.childNodes); + each(children, function(node) { + startCell.appendChild(node); + }); + + // Remove bogus nodes if there is children in the target cell + if (children.length) { + children = Tools.grep(startCell.childNodes); + count = 0; + each(children, function(node) { + if (node.nodeName == 'BR' && dom.getAttrib(node, 'data-mce-bogus') && count++ < children.length - 1) { + startCell.removeChild(node); + } + }); + } + + dom.remove(cell); + } + } + } + + // Remove empty rows etc and restore caret location + cleanup(); + } + } + + function insertRow(before) { + var posY, cell, lastCell, x, rowElm, newRow, newCell, otherCell, rowSpan; + + // Find first/last row + each(grid, function(row, y) { + each(row, function(cell) { + if (isCellSelected(cell)) { + cell = cell.elm; + rowElm = cell.parentNode; + newRow = cloneNode(rowElm, false); + posY = y; + + if (before) { + return false; + } + } + }); + + if (before) { + return !posY; + } + }); + + for (x = 0; x < grid[0].length; x++) { + // Cell not found could be because of an invalid table structure + if (!grid[posY][x]) { + continue; + } + + cell = grid[posY][x].elm; + + if (cell != lastCell) { + if (!before) { + rowSpan = getSpanVal(cell, 'rowspan'); + if (rowSpan > 1) { + setSpanVal(cell, 'rowSpan', rowSpan + 1); + continue; + } + } else { + // Check if cell above can be expanded + if (posY > 0 && grid[posY - 1][x]) { + otherCell = grid[posY - 1][x].elm; + rowSpan = getSpanVal(otherCell, 'rowSpan'); + if (rowSpan > 1) { + setSpanVal(otherCell, 'rowSpan', rowSpan + 1); + continue; + } + } + } + + // Insert new cell into new row + newCell = cloneCell(cell); + setSpanVal(newCell, 'colSpan', cell.colSpan); + + newRow.appendChild(newCell); + + lastCell = cell; + } + } + + if (newRow.hasChildNodes()) { + if (!before) { + dom.insertAfter(newRow, rowElm); + } else { + rowElm.parentNode.insertBefore(newRow, rowElm); + } + } + } + + function insertCol(before) { + var posX, lastCell; + + // Find first/last column + each(grid, function(row) { + each(row, function(cell, x) { + if (isCellSelected(cell)) { + posX = x; + + if (before) { + return false; + } + } + }); + + if (before) { + return !posX; + } + }); + + each(grid, function(row, y) { + var cell, rowSpan, colSpan; + + if (!row[posX]) { + return; + } + + cell = row[posX].elm; + if (cell != lastCell) { + colSpan = getSpanVal(cell, 'colspan'); + rowSpan = getSpanVal(cell, 'rowspan'); + + if (colSpan == 1) { + if (!before) { + dom.insertAfter(cloneCell(cell), cell); + fillLeftDown(posX, y, rowSpan - 1, colSpan); + } else { + cell.parentNode.insertBefore(cloneCell(cell), cell); + fillLeftDown(posX, y, rowSpan - 1, colSpan); + } + } else { + setSpanVal(cell, 'colSpan', cell.colSpan + 1); + } + + lastCell = cell; + } + }); + } + + function deleteCols() { + var cols = []; + + // Get selected column indexes + each(grid, function(row) { + each(row, function(cell, x) { + if (isCellSelected(cell) && Tools.inArray(cols, x) === -1) { + each(grid, function(row) { + var cell = row[x].elm, colSpan; + + colSpan = getSpanVal(cell, 'colSpan'); + + if (colSpan > 1) { + setSpanVal(cell, 'colSpan', colSpan - 1); + } else { + dom.remove(cell); + } + }); + + cols.push(x); + } + }); + }); + + cleanup(); + } + + function deleteRows() { + var rows; + + function deleteRow(tr) { + var nextTr, pos, lastCell; + + nextTr = dom.getNext(tr, 'tr'); + + // Move down row spanned cells + each(tr.cells, function(cell) { + var rowSpan = getSpanVal(cell, 'rowSpan'); + + if (rowSpan > 1) { + setSpanVal(cell, 'rowSpan', rowSpan - 1); + pos = getPos(cell); + fillLeftDown(pos.x, pos.y, 1, 1); + } + }); + + // Delete cells + pos = getPos(tr.cells[0]); + each(grid[pos.y], function(cell) { + var rowSpan; + + cell = cell.elm; + + if (cell != lastCell) { + rowSpan = getSpanVal(cell, 'rowSpan'); + + if (rowSpan <= 1) { + dom.remove(cell); + } else { + setSpanVal(cell, 'rowSpan', rowSpan - 1); + } + + lastCell = cell; + } + }); + } + + // Get selected rows and move selection out of scope + rows = getSelectedRows(); + + // Delete all selected rows + each(rows.reverse(), function(tr) { + deleteRow(tr); + }); + + cleanup(); + } + + function cutRows() { + var rows = getSelectedRows(); + + dom.remove(rows); + cleanup(); + + return rows; + } + + function copyRows() { + var rows = getSelectedRows(); + + each(rows, function(row, i) { + rows[i] = cloneNode(row, true); + }); + + return rows; + } + + function pasteRows(rows, before) { + var selectedRows = getSelectedRows(), + targetRow = selectedRows[before ? 0 : selectedRows.length - 1], + targetCellCount = targetRow.cells.length; + + // Nothing to paste + if (!rows) { + return; + } + + // Calc target cell count + each(grid, function(row) { + var match; + + targetCellCount = 0; + each(row, function(cell) { + if (cell.real) { + targetCellCount += cell.colspan; + } + + if (cell.elm.parentNode == targetRow) { + match = 1; + } + }); + + if (match) { + return false; + } + }); + + if (!before) { + rows.reverse(); + } + + each(rows, function(row) { + var i, cellCount = row.cells.length, cell; + + // Remove col/rowspans + for (i = 0; i < cellCount; i++) { + cell = row.cells[i]; + setSpanVal(cell, 'colSpan', 1); + setSpanVal(cell, 'rowSpan', 1); + } + + // Needs more cells + for (i = cellCount; i < targetCellCount; i++) { + row.appendChild(cloneCell(row.cells[cellCount - 1])); + } + + // Needs less cells + for (i = targetCellCount; i < cellCount; i++) { + dom.remove(row.cells[i]); + } + + // Add before/after + if (before) { + targetRow.parentNode.insertBefore(row, targetRow); + } else { + dom.insertAfter(row, targetRow); + } + }); + + // Remove current selection + dom.removeClass(dom.select('td.mce-item-selected,th.mce-item-selected'), 'mce-item-selected'); + } + + function getPos(target) { + var pos; + + each(grid, function(row, y) { + each(row, function(cell, x) { + if (cell.elm == target) { + pos = {x : x, y : y}; + return false; + } + }); + + return !pos; + }); + + return pos; + } + + function setStartCell(cell) { + startPos = getPos(cell); + } + + function findEndPos() { + var maxX, maxY; + + maxX = maxY = 0; + + each(grid, function(row, y) { + each(row, function(cell, x) { + var colSpan, rowSpan; + + if (isCellSelected(cell)) { + cell = grid[y][x]; + + if (x > maxX) { + maxX = x; + } + + if (y > maxY) { + maxY = y; + } + + if (cell.real) { + colSpan = cell.colspan - 1; + rowSpan = cell.rowspan - 1; + + if (colSpan) { + if (x + colSpan > maxX) { + maxX = x + colSpan; + } + } + + if (rowSpan) { + if (y + rowSpan > maxY) { + maxY = y + rowSpan; + } + } + } + } + }); + }); + + return {x : maxX, y : maxY}; + } + + function setEndCell(cell) { + var startX, startY, endX, endY, maxX, maxY, colSpan, rowSpan, x, y; + + endPos = getPos(cell); + + if (startPos && endPos) { + // Get start/end positions + startX = Math.min(startPos.x, endPos.x); + startY = Math.min(startPos.y, endPos.y); + endX = Math.max(startPos.x, endPos.x); + endY = Math.max(startPos.y, endPos.y); + + // Expand end positon to include spans + maxX = endX; + maxY = endY; + + // Expand startX + for (y = startY; y <= maxY; y++) { + cell = grid[y][startX]; + + if (!cell.real) { + if (startX - (cell.colspan - 1) < startX) { + startX -= cell.colspan - 1; + } + } + } + + // Expand startY + for (x = startX; x <= maxX; x++) { + cell = grid[startY][x]; + + if (!cell.real) { + if (startY - (cell.rowspan - 1) < startY) { + startY -= cell.rowspan - 1; + } + } + } + + // Find max X, Y + for (y = startY; y <= endY; y++) { + for (x = startX; x <= endX; x++) { + cell = grid[y][x]; + + if (cell.real) { + colSpan = cell.colspan - 1; + rowSpan = cell.rowspan - 1; + + if (colSpan) { + if (x + colSpan > maxX) { + maxX = x + colSpan; + } + } + + if (rowSpan) { + if (y + rowSpan > maxY) { + maxY = y + rowSpan; + } + } + } + } + } + + // Remove current selection + dom.removeClass(dom.select('td.mce-item-selected,th.mce-item-selected'), 'mce-item-selected'); + + // Add new selection + for (y = startY; y <= maxY; y++) { + for (x = startX; x <= maxX; x++) { + if (grid[y][x]) { + dom.addClass(grid[y][x].elm, 'mce-item-selected'); + } + } + } + } + } + + table = table || dom.getParent(selection.getNode(), 'table'); + + buildGrid(); + + selectedCell = dom.getParent(selection.getStart(), 'th,td'); + if (selectedCell) { + startPos = getPos(selectedCell); + endPos = findEndPos(); + selectedCell = getCell(startPos.x, startPos.y); + } + + Tools.extend(this, { + deleteTable: deleteTable, + split: split, + merge: merge, + insertRow: insertRow, + insertCol: insertCol, + deleteCols: deleteCols, + deleteRows: deleteRows, + cutRows: cutRows, + copyRows: copyRows, + pasteRows: pasteRows, + getPos: getPos, + setStartCell: setStartCell, + setEndCell: setEndCell + }); + }; +}); + +// Included from: js/tinymce/plugins/table/classes/Quirks.js + +/** + * Quirks.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class includes fixes for various browser quirks. + * + * @class tinymce.tableplugin.Quirks + * @private + */ +define("tinymce/tableplugin/Quirks", [ + "tinymce/util/VK", + "tinymce/Env", + "tinymce/util/Tools" +], function(VK, Env, Tools) { + var each = Tools.each; + + function getSpanVal(td, name) { + return parseInt(td.getAttribute(name) || 1, 10); + } + + return function(editor) { + /** + * Fixed caret movement around tables on WebKit. + */ + function moveWebKitSelection() { + function eventHandler(e) { + var key = e.keyCode; + + function handle(upBool, sourceNode) { + var siblingDirection = upBool ? 'previousSibling' : 'nextSibling'; + var currentRow = editor.dom.getParent(sourceNode, 'tr'); + var siblingRow = currentRow[siblingDirection]; + + if (siblingRow) { + moveCursorToRow(editor, sourceNode, siblingRow, upBool); + e.preventDefault(); + return true; + } else { + var tableNode = editor.dom.getParent(currentRow, 'table'); + var middleNode = currentRow.parentNode; + var parentNodeName = middleNode.nodeName.toLowerCase(); + if (parentNodeName === 'tbody' || parentNodeName === (upBool ? 'tfoot' : 'thead')) { + var targetParent = getTargetParent(upBool, tableNode, middleNode, 'tbody'); + if (targetParent !== null) { + return moveToRowInTarget(upBool, targetParent, sourceNode); + } + } + return escapeTable(upBool, currentRow, siblingDirection, tableNode); + } + } + + function getTargetParent(upBool, topNode, secondNode, nodeName) { + var tbodies = editor.dom.select('>' + nodeName, topNode); + var position = tbodies.indexOf(secondNode); + if (upBool && position === 0 || !upBool && position === tbodies.length - 1) { + return getFirstHeadOrFoot(upBool, topNode); + } else if (position === -1) { + var topOrBottom = secondNode.tagName.toLowerCase() === 'thead' ? 0 : tbodies.length - 1; + return tbodies[topOrBottom]; + } else { + return tbodies[position + (upBool ? -1 : 1)]; + } + } + + function getFirstHeadOrFoot(upBool, parent) { + var tagName = upBool ? 'thead' : 'tfoot'; + var headOrFoot = editor.dom.select('>' + tagName, parent); + return headOrFoot.length !== 0 ? headOrFoot[0] : null; + } + + function moveToRowInTarget(upBool, targetParent, sourceNode) { + var targetRow = getChildForDirection(targetParent, upBool); + + if (targetRow) { + moveCursorToRow(editor, sourceNode, targetRow, upBool); + } + + e.preventDefault(); + return true; + } + + function escapeTable(upBool, currentRow, siblingDirection, table) { + var tableSibling = table[siblingDirection]; + + if (tableSibling) { + moveCursorToStartOfElement(tableSibling); + return true; + } else { + var parentCell = editor.dom.getParent(table, 'td,th'); + if (parentCell) { + return handle(upBool, parentCell, e); + } else { + var backUpSibling = getChildForDirection(currentRow, !upBool); + moveCursorToStartOfElement(backUpSibling); + e.preventDefault(); + return false; + } + } + } + + function getChildForDirection(parent, up) { + var child = parent && parent[up ? 'lastChild' : 'firstChild']; + // BR is not a valid table child to return in this case we return the table cell + return child && child.nodeName === 'BR' ? editor.dom.getParent(child, 'td,th') : child; + } + + function moveCursorToStartOfElement(n) { + editor.selection.setCursorLocation(n, 0); + } + + function isVerticalMovement() { + return key == VK.UP || key == VK.DOWN; + } + + function isInTable(editor) { + var node = editor.selection.getNode(); + var currentRow = editor.dom.getParent(node, 'tr'); + return currentRow !== null; + } + + function columnIndex(column) { + var colIndex = 0; + var c = column; + while (c.previousSibling) { + c = c.previousSibling; + colIndex = colIndex + getSpanVal(c, "colspan"); + } + return colIndex; + } + + function findColumn(rowElement, columnIndex) { + var c = 0, r = 0; + + each(rowElement.children, function(cell, i) { + c = c + getSpanVal(cell, "colspan"); + r = i; + if (c > columnIndex) { + return false; + } + }); + return r; + } + + function moveCursorToRow(ed, node, row, upBool) { + var srcColumnIndex = columnIndex(editor.dom.getParent(node, 'td,th')); + var tgtColumnIndex = findColumn(row, srcColumnIndex); + var tgtNode = row.childNodes[tgtColumnIndex]; + var rowCellTarget = getChildForDirection(tgtNode, upBool); + moveCursorToStartOfElement(rowCellTarget || tgtNode); + } + + function shouldFixCaret(preBrowserNode) { + var newNode = editor.selection.getNode(); + var newParent = editor.dom.getParent(newNode, 'td,th'); + var oldParent = editor.dom.getParent(preBrowserNode, 'td,th'); + + return newParent && newParent !== oldParent && checkSameParentTable(newParent, oldParent); + } + + function checkSameParentTable(nodeOne, NodeTwo) { + return editor.dom.getParent(nodeOne, 'TABLE') === editor.dom.getParent(NodeTwo, 'TABLE'); + } + + if (isVerticalMovement() && isInTable(editor)) { + var preBrowserNode = editor.selection.getNode(); + setTimeout(function() { + if (shouldFixCaret(preBrowserNode)) { + handle(!e.shiftKey && key === VK.UP, preBrowserNode, e); + } + }, 0); + } + } + + editor.on('KeyDown', function(e) { + eventHandler(e); + }); + } + + function fixBeforeTableCaretBug() { + // Checks if the selection/caret is at the start of the specified block element + function isAtStart(rng, par) { + var doc = par.ownerDocument, rng2 = doc.createRange(), elm; + + rng2.setStartBefore(par); + rng2.setEnd(rng.endContainer, rng.endOffset); + + elm = doc.createElement('body'); + elm.appendChild(rng2.cloneContents()); + + // Check for text characters of other elements that should be treated as content + return elm.innerHTML.replace(/<(br|img|object|embed|input|textarea)[^>]*>/gi, '-').replace(/<[^>]+>/g, '').length === 0; + } + + // Fixes an bug where it's impossible to place the caret before a table in Gecko + // this fix solves it by detecting when the caret is at the beginning of such a table + // and then manually moves the caret infront of the table + editor.on('KeyDown', function(e) { + var rng, table, dom = editor.dom; + + // On gecko it's not possible to place the caret before a table + if (e.keyCode == 37 || e.keyCode == 38) { + rng = editor.selection.getRng(); + table = dom.getParent(rng.startContainer, 'table'); + + if (table && editor.getBody().firstChild == table) { + if (isAtStart(rng, table)) { + rng = dom.createRng(); + + rng.setStartBefore(table); + rng.setEndBefore(table); + + editor.selection.setRng(rng); + + e.preventDefault(); + } + } + } + }); + } + + // Fixes an issue on Gecko where it's impossible to place the caret behind a table + // This fix will force a paragraph element after the table but only when the forced_root_block setting is enabled + function fixTableCaretPos() { + editor.on('KeyDown SetContent VisualAid', function() { + var last; + + // Skip empty text nodes from the end + for (last = editor.getBody().lastChild; last; last = last.previousSibling) { + if (last.nodeType == 3) { + if (last.nodeValue.length > 0) { + break; + } + } else if (last.nodeType == 1 && !last.getAttribute('data-mce-bogus')) { + break; + } + } + + if (last && last.nodeName == 'TABLE') { + if (editor.settings.forced_root_block) { + editor.dom.add( + editor.getBody(), + editor.settings.forced_root_block, + null, + Env.ie ? ' ' : '
    ' + ); + } else { + editor.dom.add(editor.getBody(), 'br', {'data-mce-bogus': '1'}); + } + } + }); + + editor.on('PreProcess', function(o) { + var last = o.node.lastChild; + + if (last && (last.nodeName == "BR" || (last.childNodes.length == 1 && + (last.firstChild.nodeName == 'BR' || last.firstChild.nodeValue == '\u00a0'))) && + last.previousSibling && last.previousSibling.nodeName == "TABLE") { + editor.dom.remove(last); + } + }); + } + + // this nasty hack is here to work around some WebKit selection bugs. + function fixTableCellSelection() { + function tableCellSelected(ed, rng, n, currentCell) { + // The decision of when a table cell is selected is somewhat involved. The fact that this code is + // required is actually a pointer to the root cause of this bug. A cell is selected when the start + // and end offsets are 0, the start container is a text, and the selection node is either a TR (most cases) + // or the parent of the table (in the case of the selection containing the last cell of a table). + var TEXT_NODE = 3, table = ed.dom.getParent(rng.startContainer, 'TABLE'); + var tableParent, allOfCellSelected, tableCellSelection; + + if (table) { + tableParent = table.parentNode; + } + + allOfCellSelected =rng.startContainer.nodeType == TEXT_NODE && + rng.startOffset === 0 && + rng.endOffset === 0 && + currentCell && + (n.nodeName == "TR" || n == tableParent); + + tableCellSelection = (n.nodeName == "TD" || n.nodeName == "TH") && !currentCell; + + return allOfCellSelected || tableCellSelection; + } + + function fixSelection() { + var rng = editor.selection.getRng(); + var n = editor.selection.getNode(); + var currentCell = editor.dom.getParent(rng.startContainer, 'TD,TH'); + + if (!tableCellSelected(editor, rng, n, currentCell)) { + return; + } + + if (!currentCell) { + currentCell=n; + } + + // Get the very last node inside the table cell + var end = currentCell.lastChild; + while (end.lastChild) { + end = end.lastChild; + } + + // Select the entire table cell. Nothing outside of the table cell should be selected. + rng.setEnd(end, end.nodeValue.length); + editor.selection.setRng(rng); + } + + editor.on('KeyDown', function() { + fixSelection(); + }); + + editor.on('MouseDown', function(e) { + if (e.button != 2) { + fixSelection(); + } + }); + } + + if (Env.webkit) { + moveWebKitSelection(); + fixTableCellSelection(); + } + + if (Env.gecko) { + fixBeforeTableCaretBug(); + fixTableCaretPos(); + } + }; +}); + +// Included from: js/tinymce/plugins/table/classes/CellSelection.js + +/** + * CellSelection.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles table cell selection by faking it using a css class that gets applied + * to cells when dragging the mouse from one cell to another. + * + * @class tinymce.tableplugin.CellSelection + * @private + */ +define("tinymce/tableplugin/CellSelection", [ + "tinymce/tableplugin/TableGrid", + "tinymce/dom/TreeWalker", + "tinymce/util/Tools" +], function(TableGrid, TreeWalker, Tools) { + return function(editor) { + var dom = editor.dom, tableGrid, startCell, startTable, hasCellSelection = true; + + function clear() { + // Restore selection possibilities + editor.getBody().style.webkitUserSelect = ''; + + if (hasCellSelection) { + editor.dom.removeClass( + editor.dom.select('td.mce-item-selected,th.mce-item-selected'), + 'mce-item-selected' + ); + + hasCellSelection = false; + } + } + + // Add cell selection logic + editor.on('MouseDown', function(e) { + if (e.button != 2) { + clear(); + + startCell = dom.getParent(e.target, 'td,th'); + startTable = dom.getParent(startCell, 'table'); + } + }); + + dom.bind(editor.getDoc(), 'mouseover', function(e) { + var sel, table, target = e.target; + + if (startCell && (tableGrid || target != startCell) && (target.nodeName == 'TD' || target.nodeName == 'TH')) { + table = dom.getParent(target, 'table'); + if (table == startTable) { + if (!tableGrid) { + tableGrid = new TableGrid(editor.selection, table); + tableGrid.setStartCell(startCell); + + editor.getBody().style.webkitUserSelect = 'none'; + } + + tableGrid.setEndCell(target); + hasCellSelection = true; + } + + // Remove current selection + sel = editor.selection.getSel(); + + try { + if (sel.removeAllRanges) { + sel.removeAllRanges(); + } else { + sel.empty(); + } + } catch (ex) { + // IE9 might throw errors here + } + + e.preventDefault(); + } + }); + + editor.on('MouseUp', function() { + var rng, sel = editor.selection, selectedCells, walker, node, lastNode, endNode; + + function setPoint(node, start) { + var walker = new TreeWalker(node, node); + + do { + // Text node + if (node.nodeType == 3 && Tools.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()))); + } + + // Move selection to startCell + if (startCell) { + if (tableGrid) { + editor.getBody().style.webkitUserSelect = ''; + } + + // Try to expand text selection as much as we can only Gecko supports cell selection + selectedCells = dom.select('td.mce-item-selected,th.mce-item-selected'); + if (selectedCells.length > 0) { + rng = dom.createRng(); + node = selectedCells[0]; + endNode = selectedCells[selectedCells.length - 1]; + rng.setStartBefore(node); + rng.setEndAfter(node); + + setPoint(node, 1); + walker = new TreeWalker(node, dom.getParent(selectedCells[0], 'table')); + + do { + if (node.nodeName == 'TD' || node.nodeName == 'TH') { + if (!dom.hasClass(node, 'mce-item-selected')) { + break; + } + + lastNode = node; + } + } while ((node = walker.next())); + + setPoint(lastNode); + + sel.setRng(rng); + } + + editor.nodeChanged(); + startCell = tableGrid = startTable = null; + } + }); + + editor.on('KeyUp', function() { + clear(); + }); + + return { + clear: clear + }; + }; +}); + +// Included from: js/tinymce/plugins/table/classes/Plugin.js + +/** + * Plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class contains all core logic for the table plugin. + * + * @class tinymce.tableplugin.Plugin + * @private + */ +define("tinymce/tableplugin/Plugin", [ + "tinymce/tableplugin/TableGrid", + "tinymce/tableplugin/Quirks", + "tinymce/tableplugin/CellSelection", + "tinymce/util/Tools", + "tinymce/dom/TreeWalker", + "tinymce/Env", + "tinymce/PluginManager" +], function(TableGrid, Quirks, CellSelection, Tools, TreeWalker, Env, PluginManager) { + var each = Tools.each; + + function Plugin(editor) { + var winMan, clipboardRows, self = this; // Might be selected cells on reload + + function removePxSuffix(size) { + return size ? size.replace(/px$/, '') : ""; + } + + function addSizeSuffix(size) { + if (/^[0-9]+$/.test(size)) { + size += "px"; + } + + return size; + } + + function tableDialog() { + var dom = editor.dom, tableElm, data; + + tableElm = editor.dom.getParent(editor.selection.getNode(), 'table'); + + data = { + width: removePxSuffix(dom.getStyle(tableElm, 'width') || dom.getAttrib(tableElm, 'width')), + height: removePxSuffix(dom.getStyle(tableElm, 'height') || dom.getAttrib(tableElm, 'height')), + cellspacing: dom.getAttrib(tableElm, 'cellspacing'), + cellpadding: dom.getAttrib(tableElm, 'cellpadding'), + border: dom.getAttrib(tableElm, 'border'), + caption: !!dom.select('caption', tableElm)[0] + }; + + each('left center right'.split(' '), function(name) { + if (editor.formatter.matchNode(tableElm, 'align' + name)) { + data.align = name; + } + }); + + editor.windowManager.open({ + title: "Table properties", + items: { + type: 'form', + layout: 'grid', + columns: 2, + data: data, + defaults: { + type: 'textbox', + maxWidth: 50 + }, + items: [ + {label: 'Cols', name: 'cols'}, + {label: 'Rows', name: 'rows'}, + {label: 'Width', name: 'width'}, + {label: 'Height', name: 'height'}, + {label: 'Cell spacing', name: 'cellspacing'}, + {label: 'Cell padding', name: 'cellpadding'}, + {label: 'Border', name: 'border'}, + {label: 'Caption', name: 'caption', type: 'checkbox'}, + { + label: 'Alignment', + minWidth: 90, + name: 'align', + type: 'listbox', + text: 'None', + maxWidth: null, + values: [ + {text: 'None', value: ''}, + {text: 'Left', value: 'left'}, + {text: 'Center', value: 'center'}, + {text: 'Right', value: 'right'} + ] + } + ] + }, + + onsubmit: function() { + var data = this.toJSON(), captionElm; + + editor.undoManager.transact(function() { + editor.dom.setAttribs(tableElm, { + cellspacing: data.cellspacing, + cellpadding: data.cellpadding, + border: data.border + }); + + editor.dom.setStyles(tableElm, { + width: addSizeSuffix(data.width), + height: addSizeSuffix(data.height) + }); + + // Toggle caption on/off + captionElm = dom.select('caption', tableElm)[0]; + + if (captionElm && !data.caption) { + dom.remove(captionElm); + } + + if (!captionElm && data.caption) { + captionElm = dom.create('caption'); + + if (!Env.ie) { + captionElm.innerHTML = '
    '; + } + + tableElm.insertBefore(captionElm, tableElm.firstChild); + } + + // Apply/remove alignment + if (data.align) { + editor.formatter.apply('align' + data.align, {}, tableElm); + } else { + each('left center right'.split(' '), function(name) { + editor.formatter.remove('align' + name, {}, tableElm); + }); + } + + editor.focus(); + editor.addVisual(); + }); + } + }); + } + + function mergeDialog(grid, cell) { + editor.windowManager.open({ + title: "Merge cells", + body: [ + {label: 'Columns', name: 'cols', type: 'textbox', size: 5}, + {label: 'Rows', name: 'rows', type: 'textbox', size: 5} + ], + onsubmit: function() { + var data = this.toJSON(); + + editor.undoManager.transact(function() { + grid.merge(cell, data.cols, data.rows); + }); + } + }); + } + + function cellDialog() { + var dom = editor.dom, cellElm, data, cells = []; + + // Get selected cells or the current cell + cells = editor.dom.select('td.mce-item-selected,th.mce-item-selected'); + cellElm = editor.dom.getParent(editor.selection.getNode(), 'td,th'); + if (!cells.length && cellElm) { + cells.push(cellElm); + } + + cellElm = cellElm || cells[0]; + + data = { + width: removePxSuffix(dom.getStyle(cellElm, 'width') || dom.getAttrib(cellElm, 'width')), + height: removePxSuffix(dom.getStyle(cellElm, 'height') || dom.getAttrib(cellElm, 'height')), + scope: dom.getAttrib(cellElm, 'scope') + }; + + data.type = cellElm.nodeName.toLowerCase(); + + each('left center right'.split(' '), function(name) { + if (editor.formatter.matchNode(cellElm, 'align' + name)) { + data.align = name; + } + }); + + editor.windowManager.open({ + title: "Cell properties", + items: { + type: 'form', + data: data, + layout: 'grid', + columns: 2, + defaults: { + type: 'textbox', + maxWidth: 50 + }, + items: [ + {label: 'Width', name: 'width'}, + {label: 'Height', name: 'height'}, + { + label: 'Cell type', + name: 'type', + type: 'listbox', + text: 'None', + minWidth: 90, + maxWidth: null, + menu: [ + {text: 'Cell', value: 'td'}, + {text: 'Header cell', value: 'th'} + ] + }, + { + label: 'Scope', + name: 'scope', + type: 'listbox', + text: 'None', + minWidth: 90, + maxWidth: null, + menu: [ + {text: 'None', value: ''}, + {text: 'Row', value: 'row'}, + {text: 'Column', value: 'col'}, + {text: 'Row group', value: 'rowgroup'}, + {text: 'Column group', value: 'colgroup'} + ] + }, + { + label: 'Alignment', + name: 'align', + type: 'listbox', + text: 'None', + minWidth: 90, + maxWidth: null, + values: [ + {text: 'None', value: ''}, + {text: 'Left', value: 'left'}, + {text: 'Center', value: 'center'}, + {text: 'Right', value: 'right'} + ] + } + ] + }, + + onsubmit: function() { + var data = this.toJSON(); + + editor.undoManager.transact(function() { + each(cells, function(cellElm) { + editor.dom.setAttrib(cellElm, 'scope', data.scope); + + editor.dom.setStyles(cellElm, { + width: addSizeSuffix(data.width), + height: addSizeSuffix(data.height) + }); + + // Switch cell type + if (data.type && cellElm.nodeName.toLowerCase() != data.type) { + cellElm = dom.rename(cellElm, data.type); + } + + // Apply/remove alignment + if (data.align) { + editor.formatter.apply('align' + data.align, {}, cellElm); + } else { + each('left center right'.split(' '), function(name) { + editor.formatter.remove('align' + name, {}, cellElm); + }); + } + }); + + editor.focus(); + }); + } + }); + } + + function rowDialog() { + var dom = editor.dom, tableElm, cellElm, rowElm, data, rows = []; + + tableElm = editor.dom.getParent(editor.selection.getNode(), 'table'); + cellElm = editor.dom.getParent(editor.selection.getNode(), 'td,th'); + + each(tableElm.rows, function(row) { + each(row.cells, function(cell) { + if (dom.hasClass(cell, 'mce-item-selected') || cell == cellElm) { + rows.push(row); + return false; + } + }); + }); + + rowElm = rows[0]; + + data = { + height: removePxSuffix(dom.getStyle(rowElm, 'height') || dom.getAttrib(rowElm, 'height')), + scope: dom.getAttrib(rowElm, 'scope') + }; + + data.type = rowElm.parentNode.nodeName.toLowerCase(); + + each('left center right'.split(' '), function(name) { + if (editor.formatter.matchNode(rowElm, 'align' + name)) { + data.align = name; + } + }); + + editor.windowManager.open({ + title: "Row properties", + items: { + type: 'form', + data: data, + columns: 2, + defaults: { + type: 'textbox' + }, + items: [ + { + type: 'listbox', + name: 'type', + label: 'Row type', + text: 'None', + maxWidth: null, + menu: [ + {text: 'header', value: 'thead'}, + {text: 'body', value: 'tbody'}, + {text: 'footer', value: 'tfoot'} + ] + }, + { + type: 'listbox', + name: 'align', + label: 'Alignment', + text: 'None', + maxWidth: null, + menu: [ + {text: 'None', value: ''}, + {text: 'Left', value: 'left'}, + {text: 'Center', value: 'center'}, + {text: 'Right', value: 'right'} + ] + }, + {label: 'Height', name: 'height'} + ] + }, + + onsubmit: function() { + var data = this.toJSON(), tableElm, oldParentElm, parentElm; + + editor.undoManager.transact(function() { + each(rows, function(rowElm) { + editor.dom.setAttrib(rowElm, 'scope', data.scope); + + editor.dom.setStyles(rowElm, { + height: addSizeSuffix(data.height) + }); + + if (data.type != rowElm.parentNode.nodeName.toLowerCase()) { + tableElm = dom.getParent(rowElm, 'table'); + + oldParentElm = rowElm.parentNode; + parentElm = dom.select(tableElm, data.type)[0]; + if (!parentElm) { + parentElm = dom.create(data.type); + if (tableElm.firstChild) { + tableElm.insertBefore(parentElm, tableElm.firstChild); + } else { + tableElm.appendChild(parentElm); + } + } + + parentElm.insertBefore(rowElm, parentElm.firstChild); + + if (!oldParentElm.hasChildNodes()) { + dom.remove(oldParentElm); + } + } + + // Apply/remove alignment + if (data.align) { + editor.formatter.apply('align' + data.align, {}, rowElm); + } else { + each('left center right'.split(' '), function(name) { + editor.formatter.remove('align' + name, {}, rowElm); + }); + } + }); + + editor.focus(); + }); + } + }); + } + + function cmd(command) { + return function() { + editor.execCommand(command); + }; + } + + function insertTable(cols, rows) { + var y, x, html; + + html = ''; + + for (y = 0; y < rows; y++) { + html += ''; + + for (x = 0; x < cols; x++) { + html += ''; + } + + html += ''; + } + + html += '
    ' + (Env.ie ? " " : '
    ') + '
    '; + + editor.insertContent(html); + } + + function postRender() { + /*jshint validthis:true*/ + var self = this; + + function bindStateListener() { + self.disabled(!editor.dom.getParent(editor.selection.getNode(), 'table')); + + editor.selection.selectorChanged('table', function(state) { + self.disabled(!state); + }); + } + + if (editor.initialized) { + bindStateListener(); + } else { + editor.on('init', bindStateListener); + } + } + + // Register buttons + each([ + ['table', 'Insert/edit table', 'mceInsertTable'], + ['delete_table', 'Delete table', 'mceTableDelete'], + ['delete_col', 'Delete column', 'mceTableDeleteCol'], + ['delete_row', 'Delete row', 'mceTableDeleteRow'], + ['col_after', 'Insert column after', 'mceTableInsertColAfter'], + ['col_before', 'Insert column before', 'mceTableInsertColBefore'], + ['row_after', 'Insert row after', 'mceTableInsertRowAfter'], + ['row_before', 'Insert row before', 'mceTableInsertRowBefore'], + ['row_props', 'Row properties', 'mceTableRowProps'], + ['cell_props', 'Cell properties', 'mceTableCellProps'], + ['split_cells', 'Split cells', 'mceTableSplitCells'], + ['merge_cells', 'Merge cells', 'mceTableMergeCells'] + ], function(c) { + editor.addButton(c[0], { + title : c[1], + cmd : c[2], + onPostRender: postRender + }); + }); + + function generateTableGrid() { + var html = ''; + + html = ''; + + for (var y = 0; y < 10; y++) { + html += ''; + + for (var x = 0; x < 10; x++) { + html += ''; + } + + html += ''; + } + + html += ''; + + html += '
    0 x 0
    '; + + return html; + } + + editor.addMenuItem('inserttable', { + text: 'Insert table', + icon: 'table', + context: 'table', + onhide: function() { + editor.dom.removeClass(this.menu.items()[0].getEl().getElementsByTagName('a'), 'mce-active'); + }, + menu: [ + { + type: 'container', + html: generateTableGrid(), + + onmousemove: function(e) { + var target = e.target; + + if (target.nodeName == 'A') { + var table = editor.dom.getParent(target, 'table'); + var pos = target.getAttribute('data-mce-index'); + + if (pos != this.lastPos) { + pos = pos.split(','); + + pos[0] = parseInt(pos[0], 10); + pos[1] = parseInt(pos[1], 10); + + for (var y = 0; y < 10; y++) { + for (var x = 0; x < 10; x++) { + editor.dom.toggleClass( + table.rows[y].childNodes[x].firstChild, + 'mce-active', + x <= pos[0] && y <= pos[1] + ); + } + } + + table.nextSibling.innerHTML = (pos[0] + 1) + ' x '+ (pos[1] + 1); + this.lastPos = pos; + } + } + }, + + onclick: function(e) { + if (e.target.nodeName == 'A' && this.lastPos) { + e.preventDefault(); + + insertTable(this.lastPos[0] + 1, this.lastPos[1] + 1); + + // TODO: Maybe rework this? + this.parent().cancel(); // Close parent menu as if it was a click + } + } + } + ] + }); + + editor.addMenuItem('tableprops', { + text: 'Table properties', + context: 'table', + onPostRender: postRender, + onclick: tableDialog + }); + + editor.addMenuItem('deletetable', { + text: 'Delete table', + context: 'table', + onPostRender: postRender, + cmd: 'mceTableDelete' + }); + + editor.addMenuItem('cell', { + separator: 'before', + text: 'Cell', + context: 'table', + menu: [ + {text: 'Cell properties', onclick: cmd('mceTableCellProps'), onPostRender: postRender}, + {text: 'Merge cells', onclick: cmd('mceTableMergeCells'), onPostRender: postRender}, + {text: 'Split cell', onclick: cmd('mceTableSplitCells'), onPostRender: postRender} + ] + }); + + editor.addMenuItem('row', { + text: 'Row', + context: 'table', + menu: [ + {text: 'Insert row before', onclick: cmd('mceTableInsertRowBefore'), onPostRender: postRender}, + {text: 'Insert row after', onclick: cmd('mceTableInsertRowAfter'), onPostRender: postRender}, + {text: 'Delete row', onclick: cmd('mceTableDeleteRow'), onPostRender: postRender}, + {text: 'Row properties', onclick: cmd('mceTableRowProps'), onPostRender: postRender}, + {text: '-'}, + {text: 'Cut row', onclick: cmd('mceTableCutRow'), onPostRender: postRender}, + {text: 'Copy row', onclick: cmd('mceTableCopyRow'), onPostRender: postRender}, + {text: 'Paste row before', onclick: cmd('mceTablePasteRowBefore'), onPostRender: postRender}, + {text: 'Paste row after', onclick: cmd('mceTablePasteRowAfter'), onPostRender: postRender} + ] + }); + + editor.addMenuItem('column', { + text: 'Column', + context: 'table', + menu: [ + {text: 'Insert column before', onclick: cmd('mceTableInsertColBefore'), onPostRender: postRender}, + {text: 'Insert column after', onclick: cmd('mceTableInsertColAfter'), onPostRender: postRender}, + {text: 'Delete column', onclick: cmd('mceTableDeleteCol'), onPostRender: postRender} + ] + }); + + // Select whole table is a table border is clicked + if (!Env.isIE) { + editor.on('click', function(e) { + e = e.target; + + if (e.nodeName === 'TABLE') { + editor.selection.select(e); + editor.nodeChanged(); + } + }); + } + + self.quirks = new Quirks(editor); + + editor.on('Init', function() { + winMan = editor.windowManager; + self.cellSelection = new CellSelection(editor); + }); + + // Register action commands + each({ + mceTableSplitCells: function(grid) { + grid.split(); + }, + + mceTableMergeCells: function(grid) { + var rowSpan, colSpan, cell; + + cell = editor.dom.getParent(editor.selection.getNode(), 'th,td'); + if (cell) { + rowSpan = cell.rowSpan; + colSpan = cell.colSpan; + } + + if (!editor.dom.select('td.mce-item-selected,th.mce-item-selected').length) { + mergeDialog(grid, cell); + } else { + grid.merge(); + } + }, + + mceTableInsertRowBefore: function(grid) { + grid.insertRow(true); + }, + + mceTableInsertRowAfter: function(grid) { + grid.insertRow(); + }, + + mceTableInsertColBefore: function(grid) { + grid.insertCol(true); + }, + + mceTableInsertColAfter: function(grid) { + grid.insertCol(); + }, + + mceTableDeleteCol: function(grid) { + grid.deleteCols(); + }, + + mceTableDeleteRow: function(grid) { + grid.deleteRows(); + }, + + mceTableCutRow: function(grid) { + clipboardRows = grid.cutRows(); + }, + + mceTableCopyRow: function(grid) { + clipboardRows = grid.copyRows(); + }, + + mceTablePasteRowBefore: function(grid) { + grid.pasteRows(clipboardRows, true); + }, + + mceTablePasteRowAfter: function(grid) { + grid.pasteRows(clipboardRows); + }, + + mceTableDelete: function(grid) { + grid.deleteTable(); + } + }, function(func, name) { + editor.addCommand(name, function() { + var grid = new TableGrid(editor.selection); + + if (grid) { + func(grid); + editor.execCommand('mceRepaint'); + self.cellSelection.clear(); + } + }); + }); + + // Register dialog commands + each({ + mceInsertTable: function() { + tableDialog(); + }, + + mceTableRowProps: rowDialog, + mceTableCellProps: cellDialog + }, function(func, name) { + editor.addCommand(name, function(ui, val) { + func(val); + }); + }); + } + + PluginManager.add('table', Plugin); +}); + +expose(["tinymce/tableplugin/TableGrid","tinymce/tableplugin/Quirks","tinymce/tableplugin/CellSelection","tinymce/tableplugin/Plugin"]); +})(this); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/table/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/table/plugin.min.js new file mode 100644 index 00000000..fb6152f9 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/table/plugin.min.js @@ -0,0 +1 @@ +(function(e,t){"use strict";function n(e,t){for(var n,o=[],r=0;e.length>r;++r){if(n=i[e[r]]||l(e[r]),!n)throw"module definition dependecy not found: "+e[r];o.push(n)}t.apply(null,o)}function o(e,o,r){if("string"!=typeof e)throw"invalid module definition, module id must be defined and be a string";if(o===t)throw"invalid module definition, dependencies must be specified";if(r===t)throw"invalid module definition, definition function must be specified";n(o,function(){i[e]=r.apply(null,arguments)})}function r(e){return!!i[e]}function l(t){for(var n=e,o=t.split(/[.\/]/),r=0;o.length>r;++r){if(!n[o[r]])return;n=n[o[r]]}return n}function a(n){for(var o=0;n.length>o;o++){for(var r=e,l=n[o],a=l.split(/[.\/]/),c=0;a.length-1>c;++c)r[a[c]]===t&&(r[a[c]]={}),r=r[a[c]];r[a[a.length-1]]=i[l]}}var i={},c="tinymce/tableplugin/TableGrid",s="tinymce/util/Tools",d="tinymce/Env",u="tinymce/tableplugin/Quirks",f="tinymce/util/VK",m="tinymce/tableplugin/CellSelection",g="tinymce/dom/TreeWalker",p="tinymce/tableplugin/Plugin",h="tinymce/PluginManager";o(c,[s,d],function(e,n){function o(e,t){return parseInt(e.getAttribute(t)||1,10)}var r=e.each;return function(l,a){function i(){var e=0;I=[],r(["thead","tbody","tfoot"],function(t){var n=E.select("> "+t+" tr",a);r(n,function(n,l){l+=e,r(E.select("> td, > th",n),function(e,n){var r,a,i,c;if(I[l])for(;I[l][n];)n++;for(i=o(e,"rowspan"),c=o(e,"colspan"),a=l;l+i>a;a++)for(I[a]||(I[a]=[]),r=n;n+c>r;r++)I[a][r]={part:t,real:a==l&&r==n,elm:e,rowspan:i,colspan:c}})}),e+=n.length})}function c(e,t){return e=e.cloneNode(t),e.removeAttribute("id"),e}function s(e,n){var o;return o=I[n],o?o[e]:t}function d(e,t,n){e&&(n=parseInt(n,10),1===n?e.removeAttribute(t,1):e.setAttribute(t,n,1))}function u(e){return e&&(E.hasClass(e.elm,"mce-item-selected")||e==D)}function f(){var e=[];return r(a.rows,function(n){r(n.cells,function(o){return E.hasClass(o,"mce-item-selected")||o==D.elm?(e.push(n),!1):t})}),e}function m(){var e=E.createRng();e.setStartAfter(a),e.setEndAfter(a),l.setRng(e),E.remove(a)}function g(o){var l;return e.walk(o,function(e){var a;return 3==e.nodeType?(r(E.getParents(e.parentNode,null,o).reverse(),function(e){e=c(e,!1),l?a&&a.appendChild(e):l=a=e,a=e}),a&&(a.innerHTML=n.ie?" ":'
    '),!1):t},"childNodes"),o=c(o,!1),d(o,"rowSpan",1),d(o,"colSpan",1),l?o.appendChild(l):n.ie||(o.innerHTML='
    '),o}function p(){var e=E.createRng(),n;return r(E.select("tr",a),function(e){0===e.cells.length&&E.remove(e)}),0===E.select("tr",a).length?(e.setStartAfter(a),e.setEndAfter(a),l.setRng(e),E.remove(a),t):(r(E.select("thead,tbody,tfoot",a),function(e){0===e.rows.length&&E.remove(e)}),i(),n=I[Math.min(I.length-1,k.y)],n&&(l.select(n[Math.min(n.length-1,k.x)].elm,!0),l.collapse(!0)),t)}function h(e,t,n,o){var r,l,a,i,c;for(r=I[t][e].elm.parentNode,a=1;n>=a;a++)if(r=E.getNext(r,"tr")){for(l=e;l>=0;l--)if(c=I[t+a][l].elm,c.parentNode==r){for(i=1;o>=i;i++)E.insertAfter(g(c),c);break}if(-1==l)for(i=1;o>=i;i++)r.insertBefore(g(r.cells[0]),r.cells[0])}}function b(){r(I,function(e,t){r(e,function(e,n){var r,l,a;if(u(e)&&(e=e.elm,r=o(e,"colspan"),l=o(e,"rowspan"),r>1||l>1)){for(d(e,"rowSpan",1),d(e,"colSpan",1),a=0;r-1>a;a++)E.insertAfter(g(e),e);h(n,t,l-1,r)}})})}function v(t,n,o){var l,a,c,f,m,g,h,v,w,x,y;if(t?(l=P(t),a=l.x,c=l.y,f=a+(n-1),m=c+(o-1)):(k=M=null,r(I,function(e,t){r(e,function(e,n){u(e)&&(k||(k={x:n,y:t}),M={x:n,y:t})})}),a=k.x,c=k.y,f=M.x,m=M.y),v=s(a,c),w=s(f,m),v&&w&&v.part==w.part){for(b(),i(),v=s(a,c).elm,d(v,"colSpan",f-a+1),d(v,"rowSpan",m-c+1),h=c;m>=h;h++)for(g=a;f>=g;g++)I[h]&&I[h][g]&&(t=I[h][g].elm,t!=v&&(x=e.grep(t.childNodes),r(x,function(e){v.appendChild(e)}),x.length&&(x=e.grep(v.childNodes),y=0,r(x,function(e){"BR"==e.nodeName&&E.getAttrib(e,"data-mce-bogus")&&y++i;i++)if(I[n][i]&&(l=I[n][i].elm,l!=a)){if(e){if(n>0&&I[n-1][i]&&(p=I[n-1][i].elm,h=o(p,"rowSpan"),h>1)){d(p,"rowSpan",h+1);continue}}else if(h=o(l,"rowspan"),h>1){d(l,"rowSpan",h+1);continue}m=g(l),d(m,"colSpan",l.colSpan),f.appendChild(m),a=l}f.hasChildNodes()&&(e?s.parentNode.insertBefore(f,s):E.insertAfter(f,s))}function x(e){var n,l;r(I,function(o){return r(o,function(o,r){return u(o)&&(n=r,e)?!1:t}),e?!n:t}),r(I,function(t,r){var a,i,c;t[n]&&(a=t[n].elm,a!=l&&(c=o(a,"colspan"),i=o(a,"rowspan"),1==c?e?(a.parentNode.insertBefore(g(a),a),h(n,r,i-1,c)):(E.insertAfter(g(a),a),h(n,r,i-1,c)):d(a,"colSpan",a.colSpan+1),l=a))})}function y(){var t=[];r(I,function(n){r(n,function(n,l){u(n)&&-1===e.inArray(t,l)&&(r(I,function(e){var t=e[l].elm,n;n=o(t,"colSpan"),n>1?d(t,"colSpan",n-1):E.remove(t)}),t.push(l))})}),p()}function C(){function e(e){var t,n,l;t=E.getNext(e,"tr"),r(e.cells,function(e){var t=o(e,"rowSpan");t>1&&(d(e,"rowSpan",t-1),n=P(e),h(n.x,n.y,1,1))}),n=P(e.cells[0]),r(I[n.y],function(e){var t;e=e.elm,e!=l&&(t=o(e,"rowSpan"),1>=t?E.remove(e):d(e,"rowSpan",t-1),l=e)})}var t;t=f(),r(t.reverse(),function(t){e(t)}),p()}function R(){var e=f();return E.remove(e),p(),e}function N(){var e=f();return r(e,function(t,n){e[n]=c(t,!0)}),e}function T(e,n){var o=f(),l=o[n?0:o.length-1],a=l.cells.length;e&&(r(I,function(e){var n;return a=0,r(e,function(e){e.real&&(a+=e.colspan),e.elm.parentNode==l&&(n=1)}),n?!1:t}),n||e.reverse(),r(e,function(e){var t,o=e.cells.length,r;for(t=0;o>t;t++)r=e.cells[t],d(r,"colSpan",1),d(r,"rowSpan",1);for(t=o;a>t;t++)e.appendChild(g(e.cells[o-1]));for(t=a;o>t;t++)E.remove(e.cells[t]);n?l.parentNode.insertBefore(e,l):E.insertAfter(e,l)}),E.removeClass(E.select("td.mce-item-selected,th.mce-item-selected"),"mce-item-selected"))}function P(e){var n;return r(I,function(o,l){return r(o,function(o,r){return o.elm==e?(n={x:r,y:l},!1):t}),!n}),n}function S(e){k=P(e)}function A(){var e,t;return e=t=0,r(I,function(n,o){r(n,function(n,r){var l,a;u(n)&&(n=I[o][r],r>e&&(e=r),o>t&&(t=o),n.real&&(l=n.colspan-1,a=n.rowspan-1,l&&r+l>e&&(e=r+l),a&&o+a>t&&(t=o+a)))})}),{x:e,y:t}}function B(e){var t,n,o,r,l,a,i,c,s,d;if(M=P(e),k&&M){for(t=Math.min(k.x,M.x),n=Math.min(k.y,M.y),o=Math.max(k.x,M.x),r=Math.max(k.y,M.y),l=o,a=r,d=n;a>=d;d++)e=I[d][t],e.real||t>t-(e.colspan-1)&&(t-=e.colspan-1);for(s=t;l>=s;s++)e=I[n][s],e.real||n>n-(e.rowspan-1)&&(n-=e.rowspan-1);for(d=n;r>=d;d++)for(s=t;o>=s;s++)e=I[d][s],e.real&&(i=e.colspan-1,c=e.rowspan-1,i&&s+i>l&&(l=s+i),c&&d+c>a&&(a=d+c));for(E.removeClass(E.select("td.mce-item-selected,th.mce-item-selected"),"mce-item-selected"),d=n;a>=d;d++)for(s=t;l>=s;s++)I[d][s]&&E.addClass(I[d][s].elm,"mce-item-selected")}}var I,k,M,D,E=l.dom;a=a||E.getParent(l.getNode(),"table"),i(),D=E.getParent(l.getStart(),"th,td"),D&&(k=P(D),M=A(),D=s(k.x,k.y)),e.extend(this,{deleteTable:m,split:b,merge:v,insertRow:w,insertCol:x,deleteCols:y,deleteRows:C,cutRows:R,copyRows:N,pasteRows:T,getPos:P,setStartCell:S,setEndCell:B})}}),o(u,[f,d,s],function(e,n,o){function r(e,t){return parseInt(e.getAttribute(t)||1,10)}var l=o.each;return function(o){function a(){function n(n){function a(e,t){var r=e?"previousSibling":"nextSibling",l=o.dom.getParent(t,"tr"),a=l[r];if(a)return b(o,t,a,e),n.preventDefault(),!0;var c=o.dom.getParent(l,"table"),u=l.parentNode,f=u.nodeName.toLowerCase();if("tbody"===f||f===(e?"tfoot":"thead")){var m=i(e,c,u,"tbody");if(null!==m)return s(e,m,t)}return d(e,l,r,c)}function i(e,t,n,r){var l=o.dom.select(">"+r,t),a=l.indexOf(n);if(e&&0===a||!e&&a===l.length-1)return c(e,t);if(-1===a){var i="thead"===n.tagName.toLowerCase()?0:l.length-1;return l[i]}return l[a+(e?-1:1)]}function c(e,t){var n=e?"thead":"tfoot",r=o.dom.select(">"+n,t);return 0!==r.length?r[0]:null}function s(e,t,r){var l=u(t,e);return l&&b(o,r,l,e),n.preventDefault(),!0}function d(e,t,r,l){var i=l[r];if(i)return f(i),!0;var c=o.dom.getParent(l,"td,th");if(c)return a(e,c,n);var s=u(t,!e);return f(s),n.preventDefault(),!1}function u(e,t){var n=e&&e[t?"lastChild":"firstChild"];return n&&"BR"===n.nodeName?o.dom.getParent(n,"td,th"):n}function f(e){o.selection.setCursorLocation(e,0)}function m(){return x==e.UP||x==e.DOWN}function g(e){var t=e.selection.getNode(),n=e.dom.getParent(t,"tr");return null!==n}function p(e){for(var t=0,n=e;n.previousSibling;)n=n.previousSibling,t+=r(n,"colspan");return t}function h(e,n){var o=0,a=0;return l(e.children,function(e,l){return o+=r(e,"colspan"),a=l,o>n?!1:t}),a}function b(e,t,n,r){var l=p(o.dom.getParent(t,"td,th")),a=h(n,l),i=n.childNodes[a],c=u(i,r);f(c||i)}function v(e){var t=o.selection.getNode(),n=o.dom.getParent(t,"td,th"),r=o.dom.getParent(e,"td,th");return n&&n!==r&&w(n,r)}function w(e,t){return o.dom.getParent(e,"TABLE")===o.dom.getParent(t,"TABLE")}var x=n.keyCode;if(m()&&g(o)){var y=o.selection.getNode();setTimeout(function(){v(y)&&a(!n.shiftKey&&x===e.UP,y,n)},0)}}o.on("KeyDown",function(e){n(e)})}function i(){function e(e,t){var n=t.ownerDocument,o=n.createRange(),r;return o.setStartBefore(t),o.setEnd(e.endContainer,e.endOffset),r=n.createElement("body"),r.appendChild(o.cloneContents()),0===r.innerHTML.replace(/<(br|img|object|embed|input|textarea)[^>]*>/gi,"-").replace(/<[^>]+>/g,"").length}o.on("KeyDown",function(t){var n,r,l=o.dom;(37==t.keyCode||38==t.keyCode)&&(n=o.selection.getRng(),r=l.getParent(n.startContainer,"table"),r&&o.getBody().firstChild==r&&e(n,r)&&(n=l.createRng(),n.setStartBefore(r),n.setEndBefore(r),o.selection.setRng(n),t.preventDefault()))})}function c(){o.on("KeyDown SetContent VisualAid",function(){var e;for(e=o.getBody().lastChild;e;e=e.previousSibling)if(3==e.nodeType){if(e.nodeValue.length>0)break}else if(1==e.nodeType&&!e.getAttribute("data-mce-bogus"))break;e&&"TABLE"==e.nodeName&&(o.settings.forced_root_block?o.dom.add(o.getBody(),o.settings.forced_root_block,null,n.ie?" ":'
    '):o.dom.add(o.getBody(),"br",{"data-mce-bogus":"1"}))}),o.on("PreProcess",function(e){var t=e.node.lastChild;t&&("BR"==t.nodeName||1==t.childNodes.length&&("BR"==t.firstChild.nodeName||"\u00a0"==t.firstChild.nodeValue))&&t.previousSibling&&"TABLE"==t.previousSibling.nodeName&&o.dom.remove(t)})}function s(){function e(e,t,n,o){var r=3,l=e.dom.getParent(t.startContainer,"TABLE"),a,i,c;return l&&(a=l.parentNode),i=t.startContainer.nodeType==r&&0===t.startOffset&&0===t.endOffset&&o&&("TR"==n.nodeName||n==a),c=("TD"==n.nodeName||"TH"==n.nodeName)&&!o,i||c}function t(){var t=o.selection.getRng(),n=o.selection.getNode(),r=o.dom.getParent(t.startContainer,"TD,TH");if(e(o,t,n,r)){r||(r=n);for(var l=r.lastChild;l.lastChild;)l=l.lastChild;t.setEnd(l,l.nodeValue.length),o.selection.setRng(t)}}o.on("KeyDown",function(){t()}),o.on("MouseDown",function(e){2!=e.button&&t()})}n.webkit&&(a(),s()),n.gecko&&(i(),c())}}),o(m,[c,g,s],function(e,n,o){return function(r){function l(){r.getBody().style.webkitUserSelect="",d&&(r.dom.removeClass(r.dom.select("td.mce-item-selected,th.mce-item-selected"),"mce-item-selected"),d=!1)}var a=r.dom,i,c,s,d=!0;return r.on("MouseDown",function(e){2!=e.button&&(l(),c=a.getParent(e.target,"td,th"),s=a.getParent(c,"table"))}),a.bind(r.getDoc(),"mouseover",function(t){var n,o,l=t.target;if(c&&(i||l!=c)&&("TD"==l.nodeName||"TH"==l.nodeName)){o=a.getParent(l,"table"),o==s&&(i||(i=new e(r.selection,o),i.setStartCell(c),r.getBody().style.webkitUserSelect="none"),i.setEndCell(l),d=!0),n=r.selection.getSel();try{n.removeAllRanges?n.removeAllRanges():n.empty()}catch(u){}t.preventDefault()}}),r.on("MouseUp",function(){function e(e,r){var a=new n(e,e);do{if(3==e.nodeType&&0!==o.trim(e.nodeValue).length)return r?l.setStart(e,0):l.setEnd(e,e.nodeValue.length),t;if("BR"==e.nodeName)return r?l.setStartBefore(e):l.setEndBefore(e),t}while(e=r?a.next():a.prev())}var l,d=r.selection,u,f,m,g,p;if(c){if(i&&(r.getBody().style.webkitUserSelect=""),u=a.select("td.mce-item-selected,th.mce-item-selected"),u.length>0){l=a.createRng(),m=u[0],p=u[u.length-1],l.setStartBefore(m),l.setEndAfter(m),e(m,1),f=new n(m,a.getParent(u[0],"table"));do if("TD"==m.nodeName||"TH"==m.nodeName){if(!a.hasClass(m,"mce-item-selected"))break;g=m}while(m=f.next());e(g),d.setRng(l)}r.nodeChanged(),c=i=s=null}}),r.on("KeyUp",function(){l()}),{clear:l}}}),o(p,[c,u,m,s,g,d,h],function(e,n,o,r,l,a,i){function c(r){function l(e){return e?e.replace(/px$/,""):""}function i(e){return/^[0-9]+$/.test(e)&&(e+="px"),e}function c(){var e=r.dom,t,n;t=r.dom.getParent(r.selection.getNode(),"table"),n={width:l(e.getStyle(t,"width")||e.getAttrib(t,"width")),height:l(e.getStyle(t,"height")||e.getAttrib(t,"height")),cellspacing:e.getAttrib(t,"cellspacing"),cellpadding:e.getAttrib(t,"cellpadding"),border:e.getAttrib(t,"border"),caption:!!e.select("caption",t)[0]},s("left center right".split(" "),function(e){r.formatter.matchNode(t,"align"+e)&&(n.align=e)}),r.windowManager.open({title:"Table properties",items:{type:"form",layout:"grid",columns:2,data:n,defaults:{type:"textbox",maxWidth:50},items:[{label:"Cols",name:"cols"},{label:"Rows",name:"rows"},{label:"Width",name:"width"},{label:"Height",name:"height"},{label:"Cell spacing",name:"cellspacing"},{label:"Cell padding",name:"cellpadding"},{label:"Border",name:"border"},{label:"Caption",name:"caption",type:"checkbox"},{label:"Alignment",minWidth:90,name:"align",type:"listbox",text:"None",maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]}]},onsubmit:function(){var n=this.toJSON(),o;r.undoManager.transact(function(){r.dom.setAttribs(t,{cellspacing:n.cellspacing,cellpadding:n.cellpadding,border:n.border}),r.dom.setStyles(t,{width:i(n.width),height:i(n.height)}),o=e.select("caption",t)[0],o&&!n.caption&&e.remove(o),!o&&n.caption&&(o=e.create("caption"),a.ie||(o.innerHTML='
    '),t.insertBefore(o,t.firstChild)),n.align?r.formatter.apply("align"+n.align,{},t):s("left center right".split(" "),function(e){r.formatter.remove("align"+e,{},t)}),r.focus(),r.addVisual()})}})}function d(e,t){r.windowManager.open({title:"Merge cells",body:[{label:"Columns",name:"cols",type:"textbox",size:5},{label:"Rows",name:"rows",type:"textbox",size:5}],onsubmit:function(){var n=this.toJSON();r.undoManager.transact(function(){e.merge(t,n.cols,n.rows)})}})}function u(){var e=r.dom,t,n,o=[];o=r.dom.select("td.mce-item-selected,th.mce-item-selected"),t=r.dom.getParent(r.selection.getNode(),"td,th"),!o.length&&t&&o.push(t),t=t||o[0],n={width:l(e.getStyle(t,"width")||e.getAttrib(t,"width")),height:l(e.getStyle(t,"height")||e.getAttrib(t,"height")),scope:e.getAttrib(t,"scope")},n.type=t.nodeName.toLowerCase(),s("left center right".split(" "),function(e){r.formatter.matchNode(t,"align"+e)&&(n.align=e)}),r.windowManager.open({title:"Cell properties",items:{type:"form",data:n,layout:"grid",columns:2,defaults:{type:"textbox",maxWidth:50},items:[{label:"Width",name:"width"},{label:"Height",name:"height"},{label:"Cell type",name:"type",type:"listbox",text:"None",minWidth:90,maxWidth:null,menu:[{text:"Cell",value:"td"},{text:"Header cell",value:"th"}]},{label:"Scope",name:"scope",type:"listbox",text:"None",minWidth:90,maxWidth:null,menu:[{text:"None",value:""},{text:"Row",value:"row"},{text:"Column",value:"col"},{text:"Row group",value:"rowgroup"},{text:"Column group",value:"colgroup"}]},{label:"Alignment",name:"align",type:"listbox",text:"None",minWidth:90,maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]}]},onsubmit:function(){var t=this.toJSON();r.undoManager.transact(function(){s(o,function(n){r.dom.setAttrib(n,"scope",t.scope),r.dom.setStyles(n,{width:i(t.width),height:i(t.height)}),t.type&&n.nodeName.toLowerCase()!=t.type&&(n=e.rename(n,t.type)),t.align?r.formatter.apply("align"+t.align,{},n):s("left center right".split(" "),function(e){r.formatter.remove("align"+e,{},n)})}),r.focus()})}})}function f(){var e=r.dom,n,o,a,c,d=[];n=r.dom.getParent(r.selection.getNode(),"table"),o=r.dom.getParent(r.selection.getNode(),"td,th"),s(n.rows,function(n){s(n.cells,function(r){return e.hasClass(r,"mce-item-selected")||r==o?(d.push(n),!1):t})}),a=d[0],c={height:l(e.getStyle(a,"height")||e.getAttrib(a,"height")),scope:e.getAttrib(a,"scope")},c.type=a.parentNode.nodeName.toLowerCase(),s("left center right".split(" "),function(e){r.formatter.matchNode(a,"align"+e)&&(c.align=e)}),r.windowManager.open({title:"Row properties",items:{type:"form",data:c,columns:2,defaults:{type:"textbox"},items:[{type:"listbox",name:"type",label:"Row type",text:"None",maxWidth:null,menu:[{text:"header",value:"thead"},{text:"body",value:"tbody"},{text:"footer",value:"tfoot"}]},{type:"listbox",name:"align",label:"Alignment",text:"None",maxWidth:null,menu:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]},{label:"Height",name:"height"}]},onsubmit:function(){var t=this.toJSON(),n,o,l;r.undoManager.transact(function(){s(d,function(a){r.dom.setAttrib(a,"scope",t.scope),r.dom.setStyles(a,{height:i(t.height)}),t.type!=a.parentNode.nodeName.toLowerCase()&&(n=e.getParent(a,"table"),o=a.parentNode,l=e.select(n,t.type)[0],l||(l=e.create(t.type),n.firstChild?n.insertBefore(l,n.firstChild):n.appendChild(l)),l.insertBefore(a,l.firstChild),o.hasChildNodes()||e.remove(o)),t.align?r.formatter.apply("align"+t.align,{},a):s("left center right".split(" "),function(e){r.formatter.remove("align"+e,{},a)})}),r.focus()})}})}function m(e){return function(){r.execCommand(e)}}function g(e,t){var n,o,l;for(l="",n=0;t>n;n++){for(l+="",o=0;e>o;o++)l+="";l+=""}l+="
    "+(a.ie?" ":"
    ")+"
    ",r.insertContent(l)}function p(){function e(){t.disabled(!r.dom.getParent(r.selection.getNode(),"table")),r.selection.selectorChanged("table",function(e){t.disabled(!e)})}var t=this;r.initialized?e():r.on("init",e)}function h(){var e="";e='';for(var t=0;10>t;t++){e+="";for(var n=0;10>n;n++)e+='';e+=""}return e+="",e+='
    0 x 0
    '}var b,v,w=this;s([["table","Insert/edit table","mceInsertTable"],["delete_table","Delete table","mceTableDelete"],["delete_col","Delete column","mceTableDeleteCol"],["delete_row","Delete row","mceTableDeleteRow"],["col_after","Insert column after","mceTableInsertColAfter"],["col_before","Insert column before","mceTableInsertColBefore"],["row_after","Insert row after","mceTableInsertRowAfter"],["row_before","Insert row before","mceTableInsertRowBefore"],["row_props","Row properties","mceTableRowProps"],["cell_props","Cell properties","mceTableCellProps"],["split_cells","Split cells","mceTableSplitCells"],["merge_cells","Merge cells","mceTableMergeCells"]],function(e){r.addButton(e[0],{title:e[1],cmd:e[2],onPostRender:p})}),r.addMenuItem("inserttable",{text:"Insert table",icon:"table",context:"table",onhide:function(){r.dom.removeClass(this.menu.items()[0].getEl().getElementsByTagName("a"),"mce-active")},menu:[{type:"container",html:h(),onmousemove:function(e){var t=e.target;if("A"==t.nodeName){var n=r.dom.getParent(t,"table"),o=t.getAttribute("data-mce-index");if(o!=this.lastPos){o=o.split(","),o[0]=parseInt(o[0],10),o[1]=parseInt(o[1],10);for(var l=0;10>l;l++)for(var a=0;10>a;a++)r.dom.toggleClass(n.rows[l].childNodes[a].firstChild,"mce-active",o[0]>=a&&o[1]>=l);n.nextSibling.innerHTML=o[0]+1+" x "+(o[1]+1),this.lastPos=o}}},onclick:function(e){"A"==e.target.nodeName&&this.lastPos&&(e.preventDefault(),g(this.lastPos[0]+1,this.lastPos[1]+1),this.parent().cancel())}}]}),r.addMenuItem("tableprops",{text:"Table properties",context:"table",onPostRender:p,onclick:c}),r.addMenuItem("deletetable",{text:"Delete table",context:"table",onPostRender:p,cmd:"mceTableDelete"}),r.addMenuItem("cell",{separator:"before",text:"Cell",context:"table",menu:[{text:"Cell properties",onclick:m("mceTableCellProps"),onPostRender:p},{text:"Merge cells",onclick:m("mceTableMergeCells"),onPostRender:p},{text:"Split cell",onclick:m("mceTableSplitCells"),onPostRender:p}]}),r.addMenuItem("row",{text:"Row",context:"table",menu:[{text:"Insert row before",onclick:m("mceTableInsertRowBefore"),onPostRender:p},{text:"Insert row after",onclick:m("mceTableInsertRowAfter"),onPostRender:p},{text:"Delete row",onclick:m("mceTableDeleteRow"),onPostRender:p},{text:"Row properties",onclick:m("mceTableRowProps"),onPostRender:p},{text:"-"},{text:"Cut row",onclick:m("mceTableCutRow"),onPostRender:p},{text:"Copy row",onclick:m("mceTableCopyRow"),onPostRender:p},{text:"Paste row before",onclick:m("mceTablePasteRowBefore"),onPostRender:p},{text:"Paste row after",onclick:m("mceTablePasteRowAfter"),onPostRender:p}]}),r.addMenuItem("column",{text:"Column",context:"table",menu:[{text:"Insert column before",onclick:m("mceTableInsertColBefore"),onPostRender:p},{text:"Insert column after",onclick:m("mceTableInsertColAfter"),onPostRender:p},{text:"Delete column",onclick:m("mceTableDeleteCol"),onPostRender:p}]}),a.isIE||r.on("click",function(e){e=e.target,"TABLE"===e.nodeName&&(r.selection.select(e),r.nodeChanged())}),w.quirks=new n(r),r.on("Init",function(){b=r.windowManager,w.cellSelection=new o(r)}),s({mceTableSplitCells:function(e){e.split()},mceTableMergeCells:function(e){var t,n,o;o=r.dom.getParent(r.selection.getNode(),"th,td"),o&&(t=o.rowSpan,n=o.colSpan),r.dom.select("td.mce-item-selected,th.mce-item-selected").length?e.merge():d(e,o)},mceTableInsertRowBefore:function(e){e.insertRow(!0)},mceTableInsertRowAfter:function(e){e.insertRow()},mceTableInsertColBefore:function(e){e.insertCol(!0)},mceTableInsertColAfter:function(e){e.insertCol()},mceTableDeleteCol:function(e){e.deleteCols()},mceTableDeleteRow:function(e){e.deleteRows()},mceTableCutRow:function(e){v=e.cutRows()},mceTableCopyRow:function(e){v=e.copyRows()},mceTablePasteRowBefore:function(e){e.pasteRows(v,!0)},mceTablePasteRowAfter:function(e){e.pasteRows(v)},mceTableDelete:function(e){e.deleteTable()}},function(t,n){r.addCommand(n,function(){var n=new e(r.selection);n&&(t(n),r.execCommand("mceRepaint"),w.cellSelection.clear())})}),s({mceInsertTable:function(){c()},mceTableRowProps:f,mceTableCellProps:u},function(e,t){r.addCommand(t,function(t,n){e(n)})})}var s=r.each;i.add("table",c)}),a([c,u,m,p])})(this); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/template/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/template/plugin.js new file mode 100644 index 00000000..7afdb299 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/template/plugin.js @@ -0,0 +1,196 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('template', function(editor) { + var each = tinymce.each; + + function showDialog() { + var win, values = [], templateHtml; + + if (!editor.settings.templates) { + editor.windowManager.alert('No templates defined'); + return; + } + + tinymce.each(editor.settings.templates, function(template) { + values.push({ + text: template.title, + value: { + url: template.url, + content: template.content, + description: template.description + } + }); + }); + + function onSelectTemplate(e) { + var value = e.control.value(); + + if (value.url) { + tinymce.util.XHR.send({ + url: value.url, + success: function(html) { + templateHtml = html; + win.find('iframe')[0].html(html); + } + }); + } else { + templateHtml = value.content; + win.find('iframe')[0].html(value.content); + } + + win.find('#description')[0].text(e.control.value().description); + } + + win = editor.windowManager.open({ + title: 'Insert template', + + body: [ + {type: 'listbox', name: 'template', flex: 0, label: 'Templates', values: values, onselect: onSelectTemplate}, + {type: 'label', name: 'description', label: 'Description', text: ''}, + {type: 'iframe', minWidth: 600, minHeight: 400, border: 1} + ], + + onsubmit: function() { + insertTemplate(false, templateHtml); + } + }); + } + + function getDateTime(fmt, date) { + var daysShort = "Sun Mon Tue Wed Thu Fri Sat Sun".split(' '); + var daysLong = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(' '); + var monthsShort = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(' '); + var monthsLong = "January February March April May June July August September October November December".split(' '); + + function addZeros(value, len) { + value = "" + value; + + if (value.length < len) { + for (var i = 0; i < (len - value.length); i++) { + value = "0" + value; + } + } + + return value; + } + + date = date || new Date(); + + fmt = fmt.replace("%D", "%m/%d/%Y"); + fmt = fmt.replace("%r", "%I:%M:%S %p"); + fmt = fmt.replace("%Y", "" + date.getFullYear()); + fmt = fmt.replace("%y", "" + date.getYear()); + fmt = fmt.replace("%m", addZeros(date.getMonth() + 1, 2)); + fmt = fmt.replace("%d", addZeros(date.getDate(), 2)); + fmt = fmt.replace("%H", "" + addZeros(date.getHours(), 2)); + fmt = fmt.replace("%M", "" + addZeros(date.getMinutes(), 2)); + fmt = fmt.replace("%S", "" + addZeros(date.getSeconds(), 2)); + fmt = fmt.replace("%I", "" + ((date.getHours() + 11) % 12 + 1)); + fmt = fmt.replace("%p", "" + (date.getHours() < 12 ? "AM" : "PM")); + fmt = fmt.replace("%B", "" + editor.translate(monthsLong[date.getMonth()])); + fmt = fmt.replace("%b", "" + editor.translate(monthsShort[date.getMonth()])); + fmt = fmt.replace("%A", "" + editor.translate(daysLong[date.getDay()])); + fmt = fmt.replace("%a", "" + editor.translate(daysShort[date.getDay()])); + fmt = fmt.replace("%%", "%"); + + return fmt; + } + + function replaceVals(e) { + var dom = editor.dom, vl = editor.getParam('template_replace_values'); + + each(dom.select('*', e), function(e) { + each(vl, function(v, k) { + if (dom.hasClass(e, k)) { + if (typeof(vl[k]) == 'function') { + vl[k](e); + } + } + }); + }); + } + + function insertTemplate(ui, html) { + var el, n, dom = editor.dom, sel = editor.selection.getContent(); + + each(editor.getParam('template_replace_values'), function(v, k) { + if (typeof(v) != 'function') { + html = html.replace(new RegExp('\\{\\$' + k + '\\}', 'g'), v); + } + }); + + el = dom.create('div', null, html); + + // Find template element within div + n = dom.select('.mceTmpl', el); + if (n && n.length > 0) { + el = dom.create('div', null); + el.appendChild(n[0].cloneNode(true)); + } + + function hasClass(n, c) { + return new RegExp('\\b' + c + '\\b', 'g').test(n.className); + } + + each(dom.select('*', el), function(n) { + // Replace cdate + if (hasClass(n, editor.getParam('template_cdate_classes', 'cdate').replace(/\s+/g, '|'))) { + n.innerHTML = getDateTime(editor.getParam("template_cdate_format", editor.getLang("template.cdate_format"))); + } + + // Replace mdate + if (hasClass(n, editor.getParam('template_mdate_classes', 'mdate').replace(/\s+/g, '|'))) { + n.innerHTML = getDateTime(editor.getParam("template_mdate_format", editor.getLang("template.mdate_format"))); + } + + // Replace selection + if (hasClass(n, editor.getParam('template_selected_content_classes', 'selcontent').replace(/\s+/g, '|'))) { + n.innerHTML = sel; + } + }); + + replaceVals(el); + + editor.execCommand('mceInsertContent', false, el.innerHTML); + editor.addVisual(); + } + + editor.addCommand('mceInsertTemplate', insertTemplate); + + editor.addButton('template', { + title: 'Insert template', + onclick: showDialog + }); + + editor.addMenuItem('image', { + text: 'Insert template', + onclick: showDialog, + context: 'insert' + }); + + editor.on('PreProcess', function(o) { + var dom = editor.dom; + + each(dom.select('div', o.node), function(e) { + if (dom.hasClass(e, 'mceTmpl')) { + each(dom.select('*', e), function(e) { + if (dom.hasClass(e, editor.getParam('template_mdate_classes', 'mdate').replace(/\s+/g, '|'))) { + e.innerHTML = getDateTime(editor.getParam("template_mdate_format", editor.getLang("template.mdate_format"))); + } + }); + + replaceVals(e); + } + }); + }); +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/template/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/template/plugin.min.js new file mode 100644 index 00000000..bde4dbb4 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/template/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("template",function(e){function t(){function t(e){var t=e.control.value();t.url?tinymce.util.XHR.send({url:t.url,success:function(e){a=e,n.find("iframe")[0].html(e)}}):(a=t.content,n.find("iframe")[0].html(t.content)),n.find("#description")[0].text(e.control.value().description)}var n,a,r=[];return e.settings.templates?(tinymce.each(e.settings.templates,function(e){r.push({text:e.title,value:{url:e.url,content:e.content,description:e.description}})}),n=e.windowManager.open({title:"Insert template",body:[{type:"listbox",name:"template",flex:0,label:"Templates",values:r,onselect:t},{type:"label",name:"description",label:"Description",text:""},{type:"iframe",minWidth:600,minHeight:400,border:1}],onsubmit:function(){i(!1,a)}}),void 0):(e.windowManager.alert("No templates defined"),void 0)}function n(t,n){function a(e,t){if(e=""+e,t>e.length)for(var n=0;t-e.length>n;n++)e="0"+e;return e}var i="Sun Mon Tue Wed Thu Fri Sat Sun".split(" "),r="Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" "),o="Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),l="January February March April May June July August September October November December".split(" ");return n=n||new Date,t=t.replace("%D","%m/%d/%Y"),t=t.replace("%r","%I:%M:%S %p"),t=t.replace("%Y",""+n.getFullYear()),t=t.replace("%y",""+n.getYear()),t=t.replace("%m",a(n.getMonth()+1,2)),t=t.replace("%d",a(n.getDate(),2)),t=t.replace("%H",""+a(n.getHours(),2)),t=t.replace("%M",""+a(n.getMinutes(),2)),t=t.replace("%S",""+a(n.getSeconds(),2)),t=t.replace("%I",""+((n.getHours()+11)%12+1)),t=t.replace("%p",""+(12>n.getHours()?"AM":"PM")),t=t.replace("%B",""+e.translate(l[n.getMonth()])),t=t.replace("%b",""+e.translate(o[n.getMonth()])),t=t.replace("%A",""+e.translate(r[n.getDay()])),t=t.replace("%a",""+e.translate(i[n.getDay()])),t=t.replace("%%","%")}function a(t){var n=e.dom,a=e.getParam("template_replace_values");r(n.select("*",t),function(e){r(a,function(t,i){n.hasClass(e,i)&&"function"==typeof a[i]&&a[i](e)})})}function i(t,i){function o(e,t){return RegExp("\\b"+t+"\\b","g").test(e.className)}var l,c,s=e.dom,d=e.selection.getContent();r(e.getParam("template_replace_values"),function(e,t){"function"!=typeof e&&(i=i.replace(RegExp("\\{\\$"+t+"\\}","g"),e))}),l=s.create("div",null,i),c=s.select(".mceTmpl",l),c&&c.length>0&&(l=s.create("div",null),l.appendChild(c[0].cloneNode(!0))),r(s.select("*",l),function(t){o(t,e.getParam("template_cdate_classes","cdate").replace(/\s+/g,"|"))&&(t.innerHTML=n(e.getParam("template_cdate_format",e.getLang("template.cdate_format")))),o(t,e.getParam("template_mdate_classes","mdate").replace(/\s+/g,"|"))&&(t.innerHTML=n(e.getParam("template_mdate_format",e.getLang("template.mdate_format")))),o(t,e.getParam("template_selected_content_classes","selcontent").replace(/\s+/g,"|"))&&(t.innerHTML=d)}),a(l),e.execCommand("mceInsertContent",!1,l.innerHTML),e.addVisual()}var r=tinymce.each;e.addCommand("mceInsertTemplate",i),e.addButton("template",{title:"Insert template",onclick:t}),e.addMenuItem("image",{text:"Insert template",onclick:t,context:"insert"}),e.on("PreProcess",function(t){var i=e.dom;r(i.select("div",t.node),function(t){i.hasClass(t,"mceTmpl")&&(r(i.select("*",t),function(t){i.hasClass(t,e.getParam("template_mdate_classes","mdate").replace(/\s+/g,"|"))&&(t.innerHTML=n(e.getParam("template_mdate_format",e.getLang("template.mdate_format"))))}),a(t))})})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/css/visualblocks.css b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/css/visualblocks.css new file mode 100644 index 00000000..7a3a47a3 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/css/visualblocks.css @@ -0,0 +1,114 @@ +.mce-visualblocks p { + padding-top: 10px; + border: 1px dashed #BBB; + margin-left: 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhCQAJAJEAAAAAAP///7u7u////yH5BAEAAAMALAAAAAAJAAkAAAIQnG+CqCN/mlyvsRUpThG6AgA7); +} + +.mce-visualblocks h1 { + padding-top: 10px; + border: 1px dashed #BBB; + margin-left: 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhDQAKAIABALu7u////yH5BAEAAAEALAAAAAANAAoAAAIXjI8GybGu1JuxHoAfRNRW3TWXyF2YiRUAOw==); +} + +.mce-visualblocks h2 { + padding-top: 10px; + border: 1px dashed #BBB; + margin-left: 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhDgAKAIABALu7u////yH5BAEAAAEALAAAAAAOAAoAAAIajI8Hybbx4oOuqgTynJd6bGlWg3DkJzoaUAAAOw==); +} + +.mce-visualblocks h3 { + padding-top: 10px; + border: 1px dashed #BBB; + margin-left: 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhDgAKAIABALu7u////yH5BAEAAAEALAAAAAAOAAoAAAIZjI8Hybbx4oOuqgTynJf2Ln2NOHpQpmhAAQA7); +} + +.mce-visualblocks h4 { + padding-top: 10px; + border: 1px dashed #BBB; + margin-left: 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhDgAKAIABALu7u////yH5BAEAAAEALAAAAAAOAAoAAAIajI8HybbxInR0zqeAdhtJlXwV1oCll2HaWgAAOw==); +} + +.mce-visualblocks h5 { + padding-top: 10px; + border: 1px dashed #BBB; + margin-left: 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhDgAKAIABALu7u////yH5BAEAAAEALAAAAAAOAAoAAAIajI8HybbxIoiuwjane4iq5GlW05GgIkIZUAAAOw==); +} + +.mce-visualblocks h6 { + padding-top: 10px; + border: 1px dashed #BBB; + margin-left: 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhDgAKAIABALu7u////yH5BAEAAAEALAAAAAAOAAoAAAIajI8HybbxIoiuwjan04jep1iZ1XRlAo5bVgAAOw==); +} + +.mce-visualblocks div { + padding-top: 10px; + border: 1px dashed #BBB; + margin-left: 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhEgAKAIABALu7u////yH5BAEAAAEALAAAAAASAAoAAAIfjI9poI0cgDywrhuxfbrzDEbQM2Ei5aRjmoySW4pAAQA7); +} + +.mce-visualblocks section { + padding-top: 10px; + border: 1px dashed #BBB; + margin: 0 0 1em 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhKAAKAIABALu7u////yH5BAEAAAEALAAAAAAoAAoAAAI5jI+pywcNY3sBWHdNrplytD2ellDeSVbp+GmWqaDqDMepc8t17Y4vBsK5hDyJMcI6KkuYU+jpjLoKADs=); +} + +.mce-visualblocks article { + padding-top: 10px; + border: 1px dashed #BBB; + margin: 0 0 1em 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhKgAKAIABALu7u////yH5BAEAAAEALAAAAAAqAAoAAAI6jI+pywkNY3wG0GBvrsd2tXGYSGnfiF7ikpXemTpOiJScasYoDJJrjsG9gkCJ0ag6KhmaIe3pjDYBBQA7); +} + +.mce-visualblocks blockquote { + padding-top: 10px; + border: 1px dashed #BBB; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhPgAKAIABALu7u////yH5BAEAAAEALAAAAAA+AAoAAAJPjI+py+0Knpz0xQDyuUhvfoGgIX5iSKZYgq5uNL5q69asZ8s5rrf0yZmpNkJZzFesBTu8TOlDVAabUyatguVhWduud3EyiUk45xhTTgMBBQA7); +} + +.mce-visualblocks address { + padding-top: 10px; + border: 1px dashed #BBB; + margin: 0 0 1em 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhLQAKAIABALu7u////yH5BAEAAAEALAAAAAAtAAoAAAI/jI+pywwNozSP1gDyyZcjb3UaRpXkWaXmZW4OqKLhBmLs+K263DkJK7OJeifh7FicKD9A1/IpGdKkyFpNmCkAADs=); +} + +.mce-visualblocks pre { + padding-top: 10px; + border: 1px dashed #BBB; + margin-left: 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhFQAKAIABALu7uwAAACH5BAEAAAEALAAAAAAVAAoAAAIjjI+ZoN0cgDwSmnpz1NCueYERhnibZVKLNnbOq8IvKpJtVQAAOw==); +} + +.mce-visualblocks figure { + padding-top: 10px; + border: 1px dashed #BBB; + margin: 0 0 1em 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhJAAKAIAAALu7u////yH5BAEAAAEALAAAAAAkAAoAAAI0jI+py+2fwAHUSFvD3RlvG4HIp4nX5JFSpnZUJ6LlrM52OE7uSWosBHScgkSZj7dDKnWAAgA7); +} + +.mce-visualblocks hgroup { + padding-top: 10px; + border: 1px dashed #BBB; + margin: 0 0 1em 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhJwAKAIABALu7uwAAACH5BAEAAAEALAAAAAAnAAoAAAI3jI+pywYNI3uB0gpsRtt5fFnfNZaVSYJil4Wo03Hv6Z62uOCgiXH1kZIIJ8NiIxRrAZNMZAtQAAA7); +} + +.mce-visualblocks aside { + padding-top: 10px; + border: 1px dashed #BBB; + margin: 0 0 1em 3px; + background: transparent no-repeat url(data:image/gif;base64,R0lGODlhHgAKAIABAKqqqv///yH5BAEAAAEALAAAAAAeAAoAAAItjI+pG8APjZOTzgtqy7I3f1yehmQcFY4WKZbqByutmW4aHUd6vfcVbgudgpYCADs=); +} + +.mce-visualblocks figcaption { + border: 1px dashed #BBB; +} diff --git a/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/address.gif b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/address.gif new file mode 100644 index 0000000000000000000000000000000000000000..87c4bff976c0d8cf3cd1bf08652be555618764ef GIT binary patch literal 104 zcmZ?wbhEHb)MemeXkcX6y?gin|Nj+#vM@3*Ff!;c00Bsbfyut7f8}W&-o+;U*BCyX zoUWW-D&;oyN#xRJsd;=W7CmH3dh=uLt~-{T+M7G8)E~Zyn4@9uaQ%~}|Nj+#vM@3*Ff!;c00Bsbfl0Tgf2H&R{@%%x&v9p+ o-eg`MGp{X0Mzl{%bJ{C*?X@%Wq-5Qz_I?-5HW;{wIHB#&hgP3!VZ_GP`kwkG|w<+|-(PR?9u<`j7*d=0Dh9-o)aA#AgQ)z&sW YO^m#~uDsBw)6?R)M6e$-BP)Y70M4y2T>t<8 literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/div.gif b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/div.gif new file mode 100644 index 0000000000000000000000000000000000000000..41754ae46091d38c2273b0137d81f967fed49122 GIT binary patch literal 72 zcmZ?wbhEHb6k_0FXkcX6y?gin|Nj+#vM@3*Ff!;c00Bsbfl0onKXXB^OoPpabrW;IEh`IAU-Wd%xiSmCcb-`~EG2WATxRxfch)LxU}CTa0Qf~Cn*aa+ literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h1.gif b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h1.gif new file mode 100644 index 0000000000000000000000000000000000000000..a05071017a6491348a28d09a07af9f8643b5b2ec GIT binary patch literal 64 zcmZ?wbhEHbTpZ(;vkB^$ytz!8! UXL?mmW>|B<6Ll-800stY0JmEe>Hq)$ literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h3.gif b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h3.gif new file mode 100644 index 0000000000000000000000000000000000000000..11a1054bd5b5e52f66ca754a9d39145c7123bb32 GIT binary patch literal 66 zcmZ?wbhEHbTpZ(;vk4hya=ax5= UNqbJM5xv&1bb8{gC=0Hr(?;{X5v literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h5.gif b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h5.gif new file mode 100644 index 0000000000000000000000000000000000000000..e2cc8c7473d0406eab408798dada39ad77ccb695 GIT binary patch literal 67 zcmZ?wbhEHbTpZ(;vk4hcu4w)^l U?pXCCGwkxj1xikm0SpY*0I!V|)c^nh literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h6.gif b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/h6.gif new file mode 100644 index 0000000000000000000000000000000000000000..5ea288fb6435f958333143a256ba0ce103285bbd GIT binary patch literal 67 zcmZ?wbhEHbTpZ(;vk4hcu4w)^# U+;MMt#LTNDsZ4#*VGIn`0JdTlbN~PV literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/hgroup.gif b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/hgroup.gif new file mode 100644 index 0000000000000000000000000000000000000000..7151919082cc43b5dd3a857f0c74d0c58e844c1e GIT binary patch literal 96 zcmZ?wbhEHbRA=B~XkcX6y?ZwU1B2pE7DfgJMg|=qn*k)lz+~Rjzw$I2uX1(cC9WK| z+m$tu_f4lw^=wL--n!y);ro~Kw(WSZptJDn#7P|Lhm({=vKc4)q;Ll?FjxZsI3gf) literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/p.gif b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/img/p.gif new file mode 100644 index 0000000000000000000000000000000000000000..04645bf4ceb8162936ec90e2c9c07279f8e4e945 GIT binary patch literal 63 zcmZ?wbhEHbDxYiwnIBxY&s1OS!sFC2!8RhXBQWPH2`nY BCMy5{ literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/plugin.js new file mode 100644 index 00000000..9edf59c5 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/plugin.js @@ -0,0 +1,72 @@ +/** + * plugin.js + * + * Copyright 2012, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('visualblocks', function(editor, url) { + var cssId, visualBlocksMenuItem, enabled; + + // We don't support older browsers like IE6/7 and they don't provide prototypes for DOM objects + if (!window.NodeList) { + return; + } + + editor.addCommand('mceVisualBlocks', function() { + var dom = editor.dom, linkElm; + + if (!cssId) { + cssId = dom.uniqueId(); + linkElm = dom.create('link', { + id: cssId, + rel: 'stylesheet', + href: url + '/css/visualblocks.css' + }); + + editor.getDoc().getElementsByTagName('head')[0].appendChild(linkElm); + } + + // Toggle on/off visual blocks while computing previews + editor.on("PreviewFormats AfterPreviewFormats", function(e) { + if (enabled) { + dom.toggleClass(editor.getBody(), 'mce-visualblocks', e.type == "afterpreviewformats"); + } + }); + + dom.toggleClass(editor.getBody(), 'mce-visualblocks'); + enabled = editor.dom.hasClass(editor.getBody(), 'mce-visualblocks'); + + if (visualBlocksMenuItem) { + visualBlocksMenuItem.active(dom.hasClass(editor.getBody(), 'mce-visualblocks')); + } + }); + + editor.addButton('visualblocks', { + title: 'visualblocks.desc', + cmd: 'mceVisualBlocks' + }); + + editor.addMenuItem('visualblocks', { + text: 'Show blocks', + cmd: 'mceVisualBlocks', + onPostRender: function() { + visualBlocksMenuItem = this; + visualBlocksMenuItem.active(editor.dom.hasClass(editor.getBody(), 'mce-visualblocks')); + }, + selectable: true, + context: 'view', + prependToContext: true + }); + + editor.on('init', function() { + if (editor.settings.visualblocks_default_state) { + editor.execCommand('mceVisualBlocks', false, null, {skip_focus: true}); + } + }); +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/plugin.min.js new file mode 100644 index 00000000..ced2d5a3 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/visualblocks/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("visualblocks",function(e,t){var n,a,i;window.NodeList&&(e.addCommand("mceVisualBlocks",function(){var o,r=e.dom;n||(n=r.uniqueId(),o=r.create("link",{id:n,rel:"stylesheet",href:t+"/css/visualblocks.css"}),e.getDoc().getElementsByTagName("head")[0].appendChild(o)),e.on("PreviewFormats AfterPreviewFormats",function(t){i&&r.toggleClass(e.getBody(),"mce-visualblocks","afterpreviewformats"==t.type)}),r.toggleClass(e.getBody(),"mce-visualblocks"),i=e.dom.hasClass(e.getBody(),"mce-visualblocks"),a&&a.active(r.hasClass(e.getBody(),"mce-visualblocks"))}),e.addButton("visualblocks",{title:"visualblocks.desc",cmd:"mceVisualBlocks"}),e.addMenuItem("visualblocks",{text:"Show blocks",cmd:"mceVisualBlocks",onPostRender:function(){a=this,a.active(e.dom.hasClass(e.getBody(),"mce-visualblocks"))},selectable:!0,context:"view",prependToContext:!0}),e.on("init",function(){e.settings.visualblocks_default_state&&e.execCommand("mceVisualBlocks",!1,null,{skip_focus:!0})}))}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/visualchars/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/visualchars/plugin.js new file mode 100644 index 00000000..77f9413e --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/visualchars/plugin.js @@ -0,0 +1,80 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('visualchars', function(editor) { + var state, visualCharsMenuItem; + + function toggleVisualChars(addBookmark) { + var node, nodeList, i, body = editor.getBody(), nodeValue, selection = editor.selection, div, bookmark; + + state = !state; + visualCharsMenuItem.active(state); + + if (addBookmark) { + bookmark = selection.getBookmark(); + } + + if (state) { + nodeList = []; + tinymce.walk(body, function(n) { + if (n.nodeType == 3 && n.nodeValue && n.nodeValue.indexOf('\u00a0') != -1) { + nodeList.push(n); + } + }, 'childNodes'); + + for (i = 0; i < nodeList.length; i++) { + nodeValue = nodeList[i].nodeValue; + nodeValue = nodeValue.replace(/(\u00a0)/g, '$1'); + + div = editor.dom.create('div', null, nodeValue); + while ((node = div.lastChild)) { + editor.dom.insertAfter(node, nodeList[i]); + } + + editor.dom.remove(nodeList[i]); + } + } else { + nodeList = editor.dom.select('span.mce-nbsp', body); + + for (i = nodeList.length - 1; i >= 0; i--) { + editor.dom.remove(nodeList[i], 1); + } + } + + selection.moveToBookmark(bookmark); + } + + editor.addCommand('mceVisualChars', toggleVisualChars); + + editor.addButton('visualchars', { + title: 'Show invisible characters', + cmd: 'mceVisualChars' + }); + + editor.addMenuItem('visualchars', { + text: 'Show invisible characters', + cmd: 'mceVisualChars', + onPostRender: function() { + visualCharsMenuItem = this; + }, + selectable: true, + context: 'view', + prependToContext: true + }); + + editor.on('beforegetcontent', function(e) { + if (state && e.format != 'raw' && !e.draft) { + state = true; + toggleVisualChars(false); + } + }); +}); diff --git a/lib/tinymce/jscripts/tinymce4/plugins/visualchars/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/visualchars/plugin.min.js new file mode 100644 index 00000000..64cb837e --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/visualchars/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("visualchars",function(e){function t(t){var i,o,r,l,c,s,d=e.getBody(),u=e.selection;if(n=!n,a.active(n),t&&(s=u.getBookmark()),n)for(o=[],tinymce.walk(d,function(e){3==e.nodeType&&e.nodeValue&&-1!=e.nodeValue.indexOf(" ")&&o.push(e)},"childNodes"),r=0;o.length>r;r++){for(l=o[r].nodeValue,l=l.replace(/(\u00a0)/g,'$1'),c=e.dom.create("div",null,l);i=c.lastChild;)e.dom.insertAfter(i,o[r]);e.dom.remove(o[r])}else for(o=e.dom.select("span.mce-nbsp",d),r=o.length-1;r>=0;r--)e.dom.remove(o[r],1);u.moveToBookmark(s)}var n,a;e.addCommand("mceVisualChars",t),e.addButton("visualchars",{title:"Show invisible characters",cmd:"mceVisualChars"}),e.addMenuItem("visualchars",{text:"Show invisible characters",cmd:"mceVisualChars",onPostRender:function(){a=this},selectable:!0,context:"view",prependToContext:!0}),e.on("beforegetcontent",function(e){n&&"raw"!=e.format&&!e.draft&&(n=!0,t(!1))})}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/wordcount/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/wordcount/plugin.js new file mode 100644 index 00000000..b11bf38d --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/wordcount/plugin.js @@ -0,0 +1,64 @@ +/** + * plugin.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.PluginManager.add('wordcount', function(editor) { + var self = this, countre, cleanre; + + countre = editor.getParam('wordcount_countregex', /[\w\u2019\x27\-]+/g); // u2019 == ’ + cleanre = editor.getParam('wordcount_cleanregex', /[0-9.(),;:!?%#$?\x27\x22_+=\\\/\-]*/g); + + function update() { + editor.theme.panel.find('#wordcount').text(['Words: %d', self.getCount()]); + } + + editor.on('init', function() { + var statusbar = editor.theme.panel && editor.theme.panel.find('#statusbar')[0]; + + if (statusbar) { + statusbar.insert({ + type: 'label', + name: 'wordcount', + text: ['Words: %d', self.getCount()], + classes: 'wordcount' + }, 0); + + editor.on('setcontent beforeaddundo', update); + + editor.on('keyup', function(e) { + if (e.keyCode == 32) { + update(); + } + }); + } + }); + + self.getCount = function() { + var tx = editor.getContent({format: 'raw'}); + var tc = 0; + + if (tx) { + tx = tx.replace(/\.\.\./g, ' '); // convert ellipses to spaces + tx = tx.replace(/<.[^<>]*?>/g, ' ').replace(/ | /gi, ' '); // remove html tags and space chars + + // deal with html entities + tx = tx.replace(/(\w+)(&.+?;)+(\w+)/, "$1$3").replace(/&.+?;/g, ' '); + tx = tx.replace(cleanre, ''); // remove numbers and punctuation + + var wordArray = tx.match(countre); + if (wordArray) { + tc = wordArray.length; + } + } + + return tc; + }; +}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/plugins/wordcount/plugin.min.js b/lib/tinymce/jscripts/tinymce4/plugins/wordcount/plugin.min.js new file mode 100644 index 00000000..7b2386cc --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/plugins/wordcount/plugin.min.js @@ -0,0 +1 @@ +tinymce.PluginManager.add("wordcount",function(e){function t(){e.theme.panel.find("#wordcount").text(["Words: %d",i.getCount()])}var n,a,i=this;n=e.getParam("wordcount_countregex",/[\w\u2019\x27\-]+/g),a=e.getParam("wordcount_cleanregex",/[0-9.(),;:!?%#$?\x27\x22_+=\\\/\-]*/g),e.on("init",function(){var n=e.theme.panel&&e.theme.panel.find("#statusbar")[0];n&&(n.insert({type:"label",name:"wordcount",text:["Words: %d",i.getCount()],classes:"wordcount"},0),e.on("setcontent beforeaddundo",t),e.on("keyup",function(e){32==e.keyCode&&t()}))}),i.getCount=function(){var t=e.getContent({format:"raw"}),i=0;if(t){t=t.replace(/\.\.\./g," "),t=t.replace(/<.[^<>]*?>/g," ").replace(/ | /gi," "),t=t.replace(/(\w+)(&.+?;)+(\w+)/,"$1$3").replace(/&.+?;/g," "),t=t.replace(a,"");var o=t.match(n);o&&(i=o.length)}return i}}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/AbsoluteLayout.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/AbsoluteLayout.less new file mode 100644 index 00000000..5b030970 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/AbsoluteLayout.less @@ -0,0 +1,17 @@ +// AbsoluteLayout + +.mce-abs-layout { + position: relative; +} + +body .mce-abs-layout-item, .mce-abs-end { + position: absolute; +} + +.mce-abs-end { + width: 1px; height: 1px; +} + +.mce-container-body.mce-abs-layout { + overflow: hidden; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Animations.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Animations.less new file mode 100644 index 00000000..4b38cf15 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Animations.less @@ -0,0 +1,10 @@ +// Animations + +.mce-fade { + opacity: 0; + .transition(opacity .15s linear); + + &.mce-in { + opacity: 1; + } +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Button.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Button.less new file mode 100644 index 00000000..fc941015 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Button.less @@ -0,0 +1,115 @@ +// Button + +.mce-btn { + border: 1px solid @btn-border-color; + position: relative; + text-shadow: @textShadow; + .button-background(@btn-background, @btn-background-highlight, @btn-text-color, 0 1px 1px rgba(255, 255, 255, .75)); + .inline-block(); + + .border-radius(3px); + .box-shadow(inset 0 1px 0 rgba(255, 255, 255, .2), 0 1px 2px rgba(0, 0, 0, .05)); + + &:hover, &:focus { + color: @btn-text-color; + text-decoration: none; + .button-background(darken(@btn-background, 5%), darken(@btn-background-highlight, 5%), @btn-text-color, 0 1px 1px rgba(255, 255, 255, .75)); + } + + &.mce-disabled, &.mce-disabled:hover { + cursor: default; + background-image: none; + .box-shadow(none); + .opacity(0.65); + } + + &.mce-active, &.mce-active:hover { + .button-background(darken(@btn-background, 10%), darken(@btn-background-highlight, 10%), @btn-text-color, 0 1px 1px rgba(255, 255, 255, .75)); + .box-shadow(inset 0 2px 4px rgba(0, 0, 0, .15), 0 1px 2px rgba(0, 0, 0 ,.05)); + } +} + +.mce-btn button { + padding: 4px 10px; + font-size: @font-size; + line-height: @line-height; + *line-height: @line-height - 4px; + cursor: pointer; + color: @btn-text-color; + + // Fixes for default inner padding of button + overflow: visible; // IE7 + -webkit-appearance: none; // WebKit + &::-moz-focus-inner { // Gecko + border: 0; + padding: 0; + } +} + +.mce-btn i { + text-shadow: 1px 1px @btn-text-shadow; +} + +.mce-primary { + .button-background(@btn-background-primary, @btn-background-primary-highlight, white, 0 1px 1px rgba(255, 255, 255, .75)); + + &:hover, &:focus { + .button-background(darken(#0088cc, 5%), darken(#0044cc, 5%), white, 0 1px 1px rgba(255, 255, 255, .75)); + } +} + +.mce-primary button { + color: @btn-text-color-primary; +} + +.mce-btn-large button { + padding: 9px 14px; + font-size: @font-size + 2px; + line-height: normal; + .border-radius(5px); +} + +.mce-btn-large i { + margin-top: 2px; +} + +.mce-btn-small button { + padding: 3px 5px; + font-size: @font-size - 2px; + line-height: @line-height - 5px; +} + +.mce-btn-small i { + margin-top: 0; +} + +.mce-btn .mce-caret { + margin-top: 8px; + *margin-top: 6px; + margin-left: 0; +} + +.mce-btn-small .mce-caret { + margin-top: 6px; + *margin-top: 4px; + margin-left: 0; +} + +.mce-caret { + .inline-block(); + width: 0; height: 0; + vertical-align: top; + border-top: 4px solid @btn-caret-color; + border-right: 4px solid transparent; + border-left: 4px solid transparent; + content: ""; +} + +.mce-disabled .mce-caret { + border-top-color: @text-color-disabled; +} + +.mce-caret.mce-up { + border-bottom: 4px solid @btn-caret-color; + border-top: 0; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/ButtonGroup.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/ButtonGroup.less new file mode 100644 index 00000000..c8852d12 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/ButtonGroup.less @@ -0,0 +1,44 @@ +// ButtonGroup + +.mce-btn-group .mce-btn { + border-width: 1px 0 1px 0; + margin: 0; + .border-radius(0); + + &:hover, &:focus { + .button-background(darken(@btn-background, 5%), darken(@btn-background-highlight, 5%), @btn-text-color, 0 1px 1px rgba(255, 255, 255, .75)); + } + + &.mce-disabled, &.mce-disabled:hover { + .box-shadow(inset 0 1px 0 rgba(255, 255, 255, .2), 0 1px 2px rgba(0, 0, 0, .05)); + .button-background(@btn-background, @btn-background-highlight, @btn-text-color, 0 1px 1px rgba(255, 255, 255, .75)); + .opacity(1); + } + + &.mce-active, &.mce-active:hover, &:active { + .button-background(darken(@btn-background, 10%), darken(@btn-background-highlight, 10%), @btn-text-color, 0 1px 1px rgba(255, 255, 255, .75)); + .box-shadow(inset 0 2px 4px rgba(0, 0, 0, .15), 0 1px 2px rgba(0, 0, 0 ,.05)); + } + + &.mce-disabled button { + .opacity(0.65); + } +} + +.mce-btn-group .mce-first { + border-left: 1px solid @btn-border-color; + .border-radius(3px 0 0 3px); +} + +.mce-btn-group .mce-last { + border-right: 1px solid @btn-border-color; + .border-radius(0 3px 3px 0); +} + +.mce-btn-group .mce-first.mce-last { + .border-radius(3px); +} + +.mce-btn-group .mce-btn.mce-flow-layout-item { + margin: 0; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Checkbox.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Checkbox.less new file mode 100644 index 00000000..484e4c01 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Checkbox.less @@ -0,0 +1,27 @@ +// Checkbox + +.mce-checkbox { + cursor: pointer; +} + +i.mce-i-checkbox { + margin: 0 3px 0 0; + border: 1px solid @btn-border-color; + .border-radius(3px); + .box-shadow(inset 0 1px 0 rgba(255, 255, 255, .2), 0 1px 2px rgba(0, 0, 0, .05)); + .vertical-gradient; + font-size: 0; + line-height: 0; +} + +.mce-checked i.mce-i-checkbox { + color: @text-color; + font-size: 16px; + line-height: 16px; +} + +.mce-checkbox:focus i.mce-i-checkbox { + border: 1px solid red; + border: 1px solid rgba(82, 168, 236, .8); + .box-shadow(inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(82, 168, 236, .6)); +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/ColorButton.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/ColorButton.less new file mode 100644 index 00000000..86e09cca --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/ColorButton.less @@ -0,0 +1,44 @@ +// ColorButton + +.mce-colorbutton .mce-ico { + position: relative; +} + +.mce-colorpicker { + background: #FFF; +} + +.mce-colorbutton-grid { + margin: 4px; +} + +.mce-grid td div { + border: 1px solid #808080; + width: 12px; height: 12px; + margin: 2px; + cursor: pointer; + &:hover { + border-color: black; + } + &:focus { + border-color: red; + outline: 1px solid rgba(82, 168, 236, .8); + border-color: rgba(82, 168, 236, .8) + } +} + +.mce-colorbutton { + position: relative; +} + +.mce-colorbutton .mce-preview { + display: block; + position: absolute; + left: 50%; top: 50%; + margin-left: -8px; + margin-top: 7px; + background: gray; + width: 16px; + height: 2px; + overflow: hidden; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/ComboBox.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/ComboBox.less new file mode 100644 index 00000000..65c6bc1b --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/ComboBox.less @@ -0,0 +1,34 @@ +// ComboBox + +.mce-combobox { + .inline-block(); + .border-radius(); + width: 100px; + .box-shadow(inset 0 1px 0 rgba(255, 255, 255, .2), 0 1px 2px rgba(0, 0, 0, .05)); +} + +.mce-combobox input { + border-color: 1px solid @btn-border-color; + border-right-color: rgba(0, 0, 0, .15); + height: 28px; +} + +.mce-combobox.mce-has-open input { + .border-radius(4px 0 0 4px); +} + +.mce-combobox .mce-btn { + border-left: 0; + .border-radius(0 4px 4px 0); +} + +.mce-combobox button { + padding-right: 8px; + padding-left: 8px; +} + +.mce-combobox *:focus { + border-color: red; + border-color: rgba(82, 168, 236, .8); + .box-shadow(inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(82, 168, 236, .6)); +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Container.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Container.less new file mode 100644 index 00000000..55cc7923 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Container.less @@ -0,0 +1,9 @@ +// Container + +.mce-container, .mce-container-body { + display: block; +} + +.mce-autoscroll { + overflow: hidden; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Content.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Content.less new file mode 100644 index 00000000..f587864f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Content.less @@ -0,0 +1,81 @@ +/* Content.less */ + +@font-family: Verdana, Arial, Helvetica, sans-serif; +@font-size: 11px; + +body.mce-content-body { + background-color: #FFFFFF; + font-family: @font-family; + font-size: @font-size; + scrollbar-3dlight-color: #F0F0EE; + scrollbar-arrow-color: #676662; + scrollbar-base-color: #F0F0EE; + scrollbar-darkshadow-color: #DDDDDD; + scrollbar-face-color: #E0E0DD; + scrollbar-highlight-color: #F0F0EE; + scrollbar-shadow-color: #F0F0EE; + scrollbar-track-color: #F5F5F5; +} + +td, th { + font-family: @font-family; + font-size: @font-size; +} + +.mce-object { + border: 1px dotted #3A3A3A; + background: #D5D5D5 url(img/object.gif) no-repeat center; +} + +.mce-pagebreak { + cursor: default; + display: block; + border: 0; + width: 100%; + height: 5px; + border: 1px dashed #666; + margin-top: 15px; +} + +.mce-item-anchor { + cursor: default; + display: inline-block; + -webkit-user-select: all; + -webkit-user-modify: read-only; + -moz-user-select: all; + -moz-user-modify: read-only; + width: 9px !important; + height: 9px !important; + border: 1px dotted #3A3A3A; + background: #D5D5D5 url(img/anchor.gif) no-repeat center; +} + +.mce-nbsp { + background: #AAA; +} + +hr { + cursor: default; +} + +.mce-match-marker { + background: green; + color: #fff; +} + +.mce-spellchecker-word { + background: url(img/wline.gif) repeat-x bottom left; + cursor: default; +} + +.mce-item-table, .mce-item-table td, .mce-item-table th, .mce-item-table caption { + border: 1px dashed #BBB; +} + +td.mce-item-selected, th.mce-item-selected { + background-color: #3399ff !important; +} + +.mce-edit-focus { + outline: 1px dotted #333; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/FieldSet.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/FieldSet.less new file mode 100644 index 00000000..2844eb77 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/FieldSet.less @@ -0,0 +1,15 @@ +// FieldSet + +.mce-fieldset { + border: 0 solid #9E9E9E; + .border-radius(3px); +} + +.mce-fieldset > .mce-container-body { + margin-top: -15px; +} + +.mce-fieldset-title { + margin-left: 5px; + padding: 0 5px 0 5px; +} \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/FitLayout.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/FitLayout.less new file mode 100644 index 00000000..f2c0f66f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/FitLayout.less @@ -0,0 +1,9 @@ +// FitLayout + +.mce-fit-layout { + .inline-block(); +} + +.mce-fit-layout-item { + position: absolute; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/FloatPanel.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/FloatPanel.less new file mode 100644 index 00000000..2e731edb --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/FloatPanel.less @@ -0,0 +1,67 @@ +// FloatPanel + +.mce-floatpanel { + position: absolute; + .box-shadow(#ccc 5px 5px 5px); +} + +// Popover panel + +.mce-floatpanel .mce-arrow, +.mce-floatpanel .mce-arrow:after { + position: absolute; + display: block; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; +} + +.mce-floatpanel .mce-arrow { + border-width: @popover-arrow-outer-width; +} + +.mce-floatpanel .mce-arrow:after { + border-width: @popover-arrow-width; + content: ""; +} + +.mce-floatpanel.mce-popover { + position: absolute; + top: 0; + left: 0; + background: @popover-background; + -webkit-background-clip: padding-box; + -moz-background-clip: padding; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0,0,0,.2); + .border-radius(6px); + .box-shadow(0 5px 10px rgba(0,0,0,.2)); + + &.mce-bottom { + margin-top: 10px; + + & > .mce-arrow { + left: 50%; + margin-left: -@popover-arrow-outer-width; + border-top-width: 0; + border-bottom-color: #999; // IE8 fallback + border-bottom-color: @popover-arrow-outer-color; + top: -@popover-arrow-outer-width; + + &:after { + top: 1px; + margin-left: -@popover-arrow-width; + border-top-width: 0; + border-bottom-color: @popover-arrow-color; + } + } + + &.mce-start { margin-left: -22px; } + &.mce-start > .mce-arrow { left: 20px; } + + &.mce-end { margin-left: 22px; } + &.mce-end > .mce-arrow { right: 10px; left: auto; } + } +} \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/FlowLayout.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/FlowLayout.less new file mode 100644 index 00000000..ca54fb16 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/FlowLayout.less @@ -0,0 +1,17 @@ +// FlowLayout + +.mce-flow-layout-item { + .inline-block(); +} + +.mce-flow-layout-item { + margin: 2px 0 2px 2px; +} + +.mce-flow-layout-item.mce-last { + margin-right: 2px; +} + +.mce-flow-layout { + white-space: normal; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Icons.Ie7.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Icons.Ie7.less new file mode 100644 index 00000000..2485466f --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Icons.Ie7.less @@ -0,0 +1,97 @@ +/* Icons IE7 */ + +@font-face { + font-family: 'icomoon'; + src:url('fonts/icomoon.eot'); + src:url('fonts/icomoon.eot?#iefix') format('embedded-opentype'), + url('fonts/icomoon.svg#icomoon') format('svg'), + url('fonts/icomoon.woff') format('woff'), + url('fonts/icomoon.ttf') format('truetype'); + font-weight: normal; + font-style: normal; +} + +@iconSize: 16px; + +.mce-ico { + font-family: 'icomoon'; + font-style: normal; + font-weight: normal; + font-size: @iconSize; + line-height: 16px; + vertical-align: text-top; + -webkit-font-smoothing: antialiased; + + display: inline-block; + background: transparent center center; + width: 16px; + height: 16px; + color: #333; + -ie7-icon: ' '; +} + +// .mce-i-checkbox needs to have zoom overridden since it's set by the gradient mixin +.mce-ico, i.mce-i-checkbox { + zoom: ~"expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = this.currentStyle['-ie7-icon'].substr(1, 1) + ' ')"; +} + +.mce-i-save { -ie7-icon: "\e000"; } +.mce-i-newdocument { -ie7-icon: "\e001"; } +.mce-i-fullpage { -ie7-icon: "\e002"; } +.mce-i-alignleft { -ie7-icon: "\e003"; } +.mce-i-aligncenter { -ie7-icon: "\e004"; } +.mce-i-alignright { -ie7-icon: "\e005"; } +.mce-i-alignjustify { -ie7-icon: "\e006"; } +.mce-i-cut { -ie7-icon: "\e007"; } +.mce-i-paste { -ie7-icon: "\e008"; } +.mce-i-searchreplace { -ie7-icon: "\e009"; } +.mce-i-bullist { -ie7-icon: "\e00a"; } +.mce-i-numlist { -ie7-icon: "\e00b"; } +.mce-i-indent { -ie7-icon: "\e00c"; } +.mce-i-outdent { -ie7-icon: "\e00d"; } +.mce-i-blockquote { -ie7-icon: "\e00e"; } +.mce-i-undo { -ie7-icon: "\e00f"; } +.mce-i-redo { -ie7-icon: "\e010"; } +.mce-i-link { -ie7-icon: "\e011"; } +.mce-i-unlink { -ie7-icon: "\e012"; } +.mce-i-anchor { -ie7-icon: "\e013"; } +.mce-i-image { -ie7-icon: "\e014"; } +.mce-i-media { -ie7-icon: "\e015"; } +.mce-i-help { -ie7-icon: "\e016"; } +.mce-i-code { -ie7-icon: "\e017"; } +.mce-i-inserttime { -ie7-icon: "\e018"; } +.mce-i-preview { -ie7-icon: "\e019"; } +.mce-i-forecolor { -ie7-icon: "\e01a"; } +.mce-i-backcolor { -ie7-icon: "\e01a"; } +.mce-i-table { -ie7-icon: "\e01b"; } +.mce-i-hr { -ie7-icon: "\e01c"; } +.mce-i-removeformat { -ie7-icon: "\e01d"; } +.mce-i-subscript { -ie7-icon: "\e01e"; } +.mce-i-superscript { -ie7-icon: "\e01f"; } +.mce-i-charmap { -ie7-icon: "\e020"; } +.mce-i-emoticons { -ie7-icon: "\e021"; } +.mce-i-print { -ie7-icon: "\e022"; } +.mce-i-fullscreen { -ie7-icon: "\e023"; } +.mce-i-spellchecker { -ie7-icon: "\e024"; } +.mce-i-nonbreaking { -ie7-icon: "\e025"; } +.mce-i-template { -ie7-icon: "\e026"; } +.mce-i-pagebreak { -ie7-icon: "\e027"; } +.mce-i-restoredraft { -ie7-icon: "\e028"; } +.mce-i-untitled { -ie7-icon: "\e029"; } +.mce-i-bold { -ie7-icon: "\e02a"; } +.mce-i-italic { -ie7-icon: "\e02b"; } +.mce-i-underline { -ie7-icon: "\e02c"; } +.mce-i-strikethrough { -ie7-icon: "\e02d"; } +.mce-i-visualchars { -ie7-icon: "\e02e"; } +.mce-i-ltr { -ie7-icon: "\e02f"; } +.mce-i-rtl { -ie7-icon: "\e030"; } +.mce-i-copy { -ie7-icon: "\e031"; } +.mce-i-resize { -ie7-icon: "\e032"; } +.mce-i-browse { -ie7-icon: "\e034"; } + +.mce-i-checkbox, .mce-i-selected { + -ie7-icon: "\e033"; +} + +.mce-i-selected { visibility: hidden; } +.mce-i-backcolor { background: #BBB; } diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Icons.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Icons.less new file mode 100644 index 00000000..75e17ef9 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Icons.less @@ -0,0 +1,91 @@ +/* Icons */ + +@font-face { + font-family: 'tinymce'; + src:url('fonts/icomoon.eot'); + src:url('fonts/icomoon.eot?#iefix') format('embedded-opentype'), + url('fonts/icomoon.svg#icomoon') format('svg'), + url('fonts/icomoon.woff') format('woff'), + url('fonts/icomoon.ttf') format('truetype'); + font-weight: normal; + font-style: normal; +} + +@iconSize: 16px; + +.mce-ico { + font-family: 'tinymce', Arial; + font-style: normal; + font-weight: normal; + font-size: @iconSize; + line-height: 16px; + vertical-align: text-top; + -webkit-font-smoothing: antialiased; + + display: inline-block; + background: transparent center center; + width: 16px; + height: 16px; + color: @btn-text-color; +} + +.mce-i-save:before { content: "\e000"; } +.mce-i-newdocument:before { content: "\e001"; } +.mce-i-fullpage:before { content: "\e002"; } +.mce-i-alignleft:before { content: "\e003"; } +.mce-i-aligncenter:before { content: "\e004"; } +.mce-i-alignright:before { content: "\e005"; } +.mce-i-alignjustify:before { content: "\e006"; } +.mce-i-cut:before { content: "\e007"; } +.mce-i-paste:before { content: "\e008"; } +.mce-i-searchreplace:before { content: "\e009"; } +.mce-i-bullist:before { content: "\e00a"; } +.mce-i-numlist:before { content: "\e00b"; } +.mce-i-indent:before { content: "\e00c"; } +.mce-i-outdent:before { content: "\e00d"; } +.mce-i-blockquote:before { content: "\e00e"; } +.mce-i-undo:before { content: "\e00f"; } +.mce-i-redo:before { content: "\e010"; } +.mce-i-link:before { content: "\e011"; } +.mce-i-unlink:before { content: "\e012"; } +.mce-i-anchor:before { content: "\e013"; } +.mce-i-image:before { content: "\e014"; } +.mce-i-media:before { content: "\e015"; } +.mce-i-help:before { content: "\e016"; } +.mce-i-code:before { content: "\e017"; } +.mce-i-inserttime:before { content: "\e018"; } +.mce-i-preview:before { content: "\e019"; } +.mce-i-forecolor:before { content: "\e01a"; } +.mce-i-backcolor:before { content: "\e01a"; } +.mce-i-table:before { content: "\e01b"; } +.mce-i-hr:before { content: "\e01c"; } +.mce-i-removeformat:before { content: "\e01d"; } +.mce-i-subscript:before { content: "\e01e"; } +.mce-i-superscript:before { content: "\e01f"; } +.mce-i-charmap:before { content: "\e020"; } +.mce-i-emoticons:before { content: "\e021"; } +.mce-i-print:before { content: "\e022"; } +.mce-i-fullscreen:before { content: "\e023"; } +.mce-i-spellchecker:before { content: "\e024"; } +.mce-i-nonbreaking:before { content: "\e025"; } +.mce-i-template:before { content: "\e026"; } +.mce-i-pagebreak:before { content: "\e027"; } +.mce-i-restoredraft:before { content: "\e028"; } +.mce-i-untitled:before { content: "\e029"; } +.mce-i-bold:before { content: "\e02a"; } +.mce-i-italic:before { content: "\e02b"; } +.mce-i-underline:before { content: "\e02c"; } +.mce-i-strikethrough:before { content: "\e02d"; } +.mce-i-visualchars:before { content: "\e02e"; } +.mce-i-ltr:before { content: "\e02f"; } +.mce-i-rtl:before { content: "\e030"; } +.mce-i-copy:before { content: "\e031"; } +.mce-i-resize:before { content: "\e032"; } +.mce-i-browse:before { content: "\e034"; } + +.mce-i-checkbox:before, .mce-i-selected:before { + content: "\e033"; +} + +.mce-i-selected { visibility: hidden; } +i.mce-i-backcolor { text-shadow: none; background: #BBB; } diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Iframe.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Iframe.less new file mode 100644 index 00000000..5338f6e1 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Iframe.less @@ -0,0 +1,6 @@ +// Iframe + +.mce-iframe { + border: 0 solid @btn-border-color; + width: 100%; height: 100%; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Label.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Label.less new file mode 100644 index 00000000..c9aa6fbe --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Label.less @@ -0,0 +1,20 @@ +// Label + +.mce-label { + .inline-block(); + text-shadow: @textShadow; + border: 0 solid @btn-border-color; + overflow: hidden; +} + +.mce-label.mce-autoscroll { + overflow: auto; +} + +.mce-label-disabled .mce-text { + color: @text-color-disabled; +} + +.mce-label.mce-multiline { + white-space: pre-wrap; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/ListBox.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/ListBox.less new file mode 100644 index 00000000..877840cb --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/ListBox.less @@ -0,0 +1,20 @@ +// ListBox + +.mce-listbox button { + text-align: left; + padding-right: 20px; + position: relative +} + +.mce-listbox .mce-caret { + position: absolute; + margin-top: -2px; + right: 8px; + top: 50%; +} + +.mce-listbox span { + width: 100%; + display: block; + overflow: hidden; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Menu.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Menu.less new file mode 100644 index 00000000..80c977ea --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Menu.less @@ -0,0 +1,29 @@ +// Menu + +.mce-menu { + .reset-gradient(); + z-index: 1000; + padding: 5px 0 5px 0; + margin: 2px 0 0; + min-width: 160px; + background: #FFF; + border: 1px solid #CCC; + border: 1px solid rgba(0, 0, 0, 0.2); + z-index: 1002; + .border-radius(6px); + .box-shadow(0 5px 10px rgba(0,0,0,.2)); +} + +.mce-menu i { + display: none; +} + +.mce-menu-has-icons i { + .inline-block(); +} + +.mce-menu-sub { + margin-top: -6px; + margin-left: -1px; + .border-radius(0 6px 6px 6px); +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/MenuBar.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/MenuBar.less new file mode 100644 index 00000000..0a4d09f7 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/MenuBar.less @@ -0,0 +1,23 @@ +/* MenuBar */ + +.mce-menubar .mce-menubtn { + border-color: transparent; + background: transparent; + .border-radius(0); + .box-shadow(none); + filter: none; +} + +.mce-menubar { + border: 1px solid @menubar-border; +} + +.mce-menubar .mce-menubtn button { + color: @text-color; +} + +.mce-menubar .mce-menubtn:hover, .mce-menubar .mce-menubtn.mce-active, .mce-menubtn:focus { + border-color: transparent; + background: @menubar-background-active; + filter: none; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/MenuButton.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/MenuButton.less new file mode 100644 index 00000000..80123995 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/MenuButton.less @@ -0,0 +1,5 @@ +/* MenuButton */ + +.mce-menubtn.mce-disabled span { + color: @text-color-disabled; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/MenuItem.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/MenuItem.less new file mode 100644 index 00000000..c0beffe7 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/MenuItem.less @@ -0,0 +1,89 @@ +// MenuItem + +.mce-menu-item { + display: block; + padding: 6px 20px; + clear: both; + font-weight: normal; + line-height: 20px; + color: @btn-text-color; + white-space: nowrap; + cursor: pointer; + line-height: normal; +} + +.mce-menu-item.mce-disabled .mce-text { + color: @text-color-disabled; +} + +.mce-menu-item:hover, .mce-menu-item.mce-selected, .mce-menu-item:focus { + text-decoration: none; + color: @text-color-inverse; + background-color: @menuitem-background-hover; + .vertical-gradient(#08C, #0077B3); +} + +.mce-menu-item:hover .mce-text, .mce-menu-item.mce-selected .mce-text { + color: @text-color-inverse; +} + +.mce-menu-item:hover .mce-ico, .mce-menu-item.mce-selected .mce-ico, .mce-menu-item:focus .mce-ico { + color: white; +} + +.mce-menu-shortcut { + display: inline-block; + color: @text-color-disabled; +} + +.mce-menu-shortcut { + .inline-block(); + padding: 0 20px 0 20px; +} + +.mce-menu-item .mce-caret { + margin-top: 6px; + *margin-top: 3px; + margin-right: 6px; + border-top: 4px solid transparent; + border-bottom: 4px solid transparent; + border-left: 4px solid #666; +} + +.mce-menu-item.mce-selected .mce-caret, .mce-menu-item:focus .mce-caret { + border-left-color: #FFF; +} + +.mce-menu-align .mce-menu-shortcut { + *margin-top: -2px; +} + +.mce-menu-align .mce-menu-shortcut, .mce-menu-align .mce-caret { + position: absolute; + right: 0; +} + +.mce-menu-item-sep, .mce-menu-item-sep:hover { + padding: 0; + height: 1px; + margin: 9px 1px; + overflow: hidden; + background: #E5E5E5; + border-bottom: 1px solid white; + cursor: default; + filter: none; +} + +.mce-menu-item.mce-active i { + visibility: visible; +} + +.mce-menu-item.mce-active { + background-color: #C8DEF4; + outline: 1px solid @btn-border-color; +} + +.mce-menu-item-checkbox.mce-active { + background-color: #FFF; + outline: 0; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Mixins.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Mixins.less new file mode 100644 index 00000000..bff6c495 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Mixins.less @@ -0,0 +1,60 @@ +// Mixins + +.opacity(@opacity:0.5) { + opacity: @opacity; + @opacityie: @opacity * 100; + filter: ~"alpha(opacity=@{opacityie})"; + zoom: 1; +} + +.vertical-gradient(@startColor: #FDFDFD, @endColor: #DDD) { + background-color: mix(@startColor, @endColor, 60%); + background-image: -moz-linear-gradient(top, @startColor, @endColor); // FF 3.6+ + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+ + background-image: -webkit-linear-gradient(top, @startColor, @endColor); // Safari 5.1+, Chrome 10+ + background-image: -o-linear-gradient(top, @startColor, @endColor); // Opera 11.10 + background-image: linear-gradient(to bottom, @startColor, @endColor); // Standard, IE10 + background-repeat: repeat-x; + filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@startColor),argb(@endColor))); + zoom: 1; +} + +.border-radius(@radius:3px) { + -webkit-border-radius: @radius; + -moz-border-radius: @radius; + border-radius: @radius; +} + +.box-shadow(@shadowA:#ccc 5px 5px 5px, @shadowB:X, ...){ + // Multiple shadow solution from http://toekneestuck.com/blog/2012/05/15/less-css-arguments-variable/ + @props: ~`"@{arguments}".replace(/[\[\]]|\,\sX/g, '')`; + -webkit-box-shadow: @props; + -moz-box-shadow: @props; + box-shadow: @props; +} + +.transition(@transition) { + -webkit-transition: @transition; + transition: @transition; +} + +.inline-block() { + display: inline-block; + + // IE7 + *display: inline; + *zoom: 1; +} + +.reset-gradient() { + filter: e(%("progid:DXImageTransform.Microsoft.gradient(enabled = false)")); + background: transparent; +} + +.button-background(@startColor, @endColor, @textColor: #fff, @textShadow: 0 -1px 0 rgba(0,0,0,.25)) { + color: @textColor; + text-shadow: @textShadow; + .vertical-gradient(@startColor, @endColor); + border-color: @endColor @endColor darken(@endColor, 15%); + border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) fadein(rgba(0,0,0,.1), 15%); +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Panel.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Panel.less new file mode 100644 index 00000000..d5fc6da4 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Panel.less @@ -0,0 +1,6 @@ +// Panel + +.mce-panel { + border: 0 solid @panel-border; + .vertical-gradient(@panel-background, @panel-background-highlight); +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Path.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Path.less new file mode 100644 index 00000000..9a9a1f12 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Path.less @@ -0,0 +1,39 @@ +// Path + +.mce-path { + .inline-block(); + padding: 8px; + white-space: normal; +} + +.mce-path .mce-txt { + display: inline-block; + padding-right: 3px; +} + +.mce-path .mce-path-body { + display: inline-block; +} + +.mce-path-item { + .inline-block(); + cursor: pointer; + color: @text-color; +} + +.mce-path .mce-last { + //color: @text-color-disabled; +} + +.mce-path-item:hover { + text-decoration: underline; +} + +.mce-path-item:focus { + background: gray; + color: white; +} + +.mce-path .mce-divider { + display: inline; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Radio.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Radio.less new file mode 100644 index 00000000..8b085710 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Radio.less @@ -0,0 +1,19 @@ +// Radio + +i.mce-radio { + padding: 1px; + margin: 0 3px 0 0; + background-color: #fafafa; + border: 1px solid #cacece; + + .border-radius(8px); + .box-shadow(inset 0 1px 0 rgba(255, 255, 255, .2), 0 1px 2px rgba(0, 0, 0, .05)); + .vertical-gradient; +} + +i.mce-radio:after { + font-family: Arial; + font-size: 12px; + color: @text-color; + content: '\25cf'; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Reset.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Reset.less new file mode 100644 index 00000000..6c4e0ecd --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Reset.less @@ -0,0 +1,36 @@ +// Reset + +.mce-container, .mce-container *, .mce-widget, .mce-widget * { + margin: 0; padding: 0; border: 0; outline: 0; + vertical-align: top; background: transparent; + text-decoration: none; color: @text-color; + font-family: @font-family; + font-size: @font-size; text-shadow: none; float: none; + position: static; width: auto; height: auto; + white-space: nowrap; cursor: inherit; + -webkit-tap-highlight-color: transparent; + line-height: normal; +} + +.mce-container *[unselectable] { + -moz-user-select: none; + -webkit-user-select: none; + -o-user-select: none; + user-select: none; +} + +.mce-container ::-webkit-scrollbar { + width: 8px; height: 8px; + -webkit-border-radius: 4px; +} + +.mce-container ::-webkit-scrollbar-track, +.mce-container ::-webkit-scrollbar-track-piece { + background-color:transparent; +} + +.mce-container ::-webkit-scrollbar-thumb { + background-color: rgba(053, 057, 071, 0.3); + width: 6px; height: 6px; + -webkit-border-radius: 4px; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/ResizeHandle.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/ResizeHandle.less new file mode 100644 index 00000000..54ae025e --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/ResizeHandle.less @@ -0,0 +1,18 @@ +.mce-container-body .mce-resizehandle { + position: absolute; + right: 0; + bottom: 0; + width: 16px; + height: 16px; + visibility: visible; + cursor: s-resize; + margin: 0; +} + +.mce-resizehandle-both { + cursor: se-resize; +} + +i.mce-i-resize { + color: @text-color; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Scrollable.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Scrollable.less new file mode 100644 index 00000000..d627eb8c --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Scrollable.less @@ -0,0 +1,44 @@ +// Scrollbar + +.mce-scrollbar { + position: absolute; + width: 7px; + height: 100%; + top: 2px; + right: 2px; + .opacity(0.4); +} + +.mce-scrollbar-h { + top: auto; + right: auto; + left: 2px; + bottom: 2px; + width: 100%; + height: 7px; +} + +.mce-scrollbar-thumb { + position: absolute; + background-color: #000; + border: 1px solid #888; + border-color: rgba(85, 85, 85, .6); + width: 5px; + height: 100%; + .border-radius(7px); +} + +.mce-scrollbar-h .mce-scrollbar-thumb { + width: 100%; + height: 5px; +} + +.mce-scrollbar:hover, .mce-scrollbar.mce-active { + background-color: #AAA; + .opacity(0.6); + .border-radius(7px); +} + +.mce-scroll { + position: relative; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Select.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Select.less new file mode 100644 index 00000000..22be7295 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Select.less @@ -0,0 +1,6 @@ +/* Select */ + +.mce-select { + border: 1px solid #AAA; + height: 30px; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Spacer.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Spacer.less new file mode 100644 index 00000000..0871105c --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Spacer.less @@ -0,0 +1,5 @@ +// Spacer + +.mce-spacer { + visibility: hidden; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/SplitButton.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/SplitButton.less new file mode 100644 index 00000000..c1ee3e4d --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/SplitButton.less @@ -0,0 +1,23 @@ +// SplitButton + +.mce-splitbtn .mce-open { + border-left: 1px solid transparent; + border-right: 1px solid transparent; +} + +.mce-splitbtn:hover .mce-open { + border-left-color: @btn-border-color; + border-right-color: @btn-border-color; +} + +.mce-splitbtn button { + padding-right: 4px; +} + +.mce-splitbtn .mce-open { + padding-left: 4px; +} + +.mce-splitbtn .mce-open.mce-active { + .box-shadow(inset 0 2px 4px rgba(0, 0, 0, .15), 0 1px 2px rgba(0, 0, 0 ,.05)); +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/StackLayout.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/StackLayout.less new file mode 100644 index 00000000..dff0a08e --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/StackLayout.less @@ -0,0 +1,5 @@ +// StackLayout + +.mce-stack-layout-item { + display: block; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/TabPanel.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/TabPanel.less new file mode 100644 index 00000000..12743ad3 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/TabPanel.less @@ -0,0 +1,28 @@ +// TabPanel + +.mce-tabs { + display: block; + border-bottom: 1px solid @tab-border; +} + +.mce-tab { + .inline-block(); + border: 1px solid @tab-border; + border-width: 1px 1px 0 0; + background: @tab-background; + padding: 8px; + text-shadow: @textShadow; + height: 13px; + cursor: pointer; +} + +.mce-tab:hover { + background: @tab-background-hover; +} + +.mce-tab.mce-active { + background: @tab-background-active; + border-bottom-color: transparent; + margin-bottom: -1px; + height: 14px; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/TextBox.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/TextBox.less new file mode 100644 index 00000000..49cbcf42 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/TextBox.less @@ -0,0 +1,28 @@ +// TextBox + +.mce-textbox { + background: #FFF; + border: 1px solid @btn-border-color; + .border-radius(); + .box-shadow(inset 0 1px 1px rgba(0, 0, 0, 0.075)); + display: inline-block; + .transition(~"border linear .2s, box-shadow linear .2s"); + height: 28px; + resize: none; + padding: 0 4px 0 4px; + white-space: normal; + color: @black; +} + +.mce-textbox:focus { + border-color: rgba(82, 168, 236, .8); + .box-shadow(inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(82, 168, 236, .6)); +} + +.mce-placeholder .mce-textbox { + color: #aaa; +} + +.mce-textbox.mce-multiline { + padding: 4px; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Throbber.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Throbber.less new file mode 100644 index 00000000..d9a8752c --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Throbber.less @@ -0,0 +1,9 @@ +// Throbber + +.mce-throbber { + position: absolute; + top: 0; left: 0; + width: 100%; height: 100%; + .opacity(0.6); + background: #FFFFFF url('img/loader.gif') no-repeat center center; +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/TinyMCE.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/TinyMCE.less new file mode 100644 index 00000000..12a8af31 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/TinyMCE.less @@ -0,0 +1,105 @@ +.mce-tinymce { + // Avoid FOUC + visibility: visible !important; + position: relative; +} + +.mce-fullscreen { + border: 0; padding: 0; margin: 0; + overflow: hidden; + background: #FFF; + height: 100%; + z-index: 100; +} + +div.mce-fullscreen { + position: fixed; + top: 0; left: 0; + width: 100%; + height: auto; +} + +.mce-tinymce { + display: block; + border-radius: 2px; +} + +.mce-wordcount { + float: right; + padding: 8px; +} + +.mce-edit-area { + background: #FFF; + filter: none; +} + +.mce-statusbar { + position: relative; +} + +.mce-statusbar .mce-container-body { + position: relative; +} + +.mce-fullscreen .mce-resizehandle { + display: none; +} + +// Charmap + +.mce-charmap { + border-collapse: collapse; +} + +.mce-charmap td { + cursor: default; + border: 1px solid @btn-border-color; + width: 20px; + height: 20px; + line-height: 20px; + text-align: center; + vertical-align: center; + padding: 2px; +} + +.mce-charmap td:hover { + background: @btn-background-highlight; +} + +.mce-grid { + border-spacing: 2px; + border-collapse: separate; + + a { + display: block; + border: 1px solid transparent; + + &:hover { + border-color: @btn-border-color; + } + } +} + +.mce-grid-border { + margin: 0 4px 0 4px; + + a { + border-color: #e8e8e8; + width: 13px; height: 13px; + } + + a:hover, a.mce-active { + border-color: #c4daff; + background: #deeafa; + } +} + +.mce-text-center { + text-align: center; +} + +div.mce-tinymce-inline { + width: 100%; + .box-shadow(none); +} diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/ToolTip.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/ToolTip.less new file mode 100644 index 00000000..da83202d --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/ToolTip.less @@ -0,0 +1,135 @@ +// Tooltip + +.mce-tooltip { + position: absolute; + padding: 5px; + .opacity(0.8); +} + +.mce-tooltip-inner { + font-size: 11px; + background-color: @tooltip-background; + color: @tooltip-text-color; + max-width: 200px; + padding: 5px 8px 4px 8px; + text-align: center; + white-space: normal; +} + +.mce-tooltip-inner { + .border-radius(3px); +} + +.mce-tooltip-inner { + .box-shadow(0 0 5px @tooltip-background); +} + +.mce-tooltip-arrow { + position: absolute; + width: 0; + height: 0; + line-height: 0; + border: 5px dashed @tooltip-background; +} + +.mce-tooltip-arrow-n { + border-bottom-color: @tooltip-background; +} + +.mce-tooltip-arrow-s { + border-top-color: @tooltip-background; +} + +.mce-tooltip-arrow-e { + border-left-color: @tooltip-background; +} + +.mce-tooltip-arrow-w { + border-right-color: @tooltip-background; +} + +.mce-tooltip-n .mce-tooltip-arrow { + top: 0px; + left: 50%; + margin-left: -5px; + border-bottom-style: solid; + border-top: none; + border-left-color: transparent; + border-right-color: transparent; +} + +.mce-tooltip-nw .mce-tooltip-arrow { + top: 0; + left: 10px; + border-bottom-style: solid; + border-top: none; + border-left-color: transparent; + border-right-color: transparent; +} + +.mce-tooltip-ne .mce-tooltip-arrow { + top: 0; + right: 10px; + border-bottom-style: solid; + border-top: none; + border-left-color: transparent; + border-right-color: transparent; +} + +.mce-tooltip-s .mce-tooltip-arrow { + bottom: 0; + left: 50%; + margin-left: -5px; + border-top-style: solid; + border-bottom: none; + border-left-color: transparent; + border-right-color: transparent; +} + +.mce-tooltip-sw .mce-tooltip-arrow { + bottom: 0; + left: 10px; + border-top-style: solid; + border-bottom: none; + border-left-color: transparent; + border-right-color: transparent; +} + +.mce-tooltip-se .mce-tooltip-arrow { + bottom: 0; + right: 10px; + border-top-style: solid; + border-bottom: none; + border-left-color: transparent; + border-right-color: transparent; +} + +.mce-tooltip-e .mce-tooltip-arrow { + right: 0; + top: 50%; + margin-top: -5px; + border-left-style: solid; + border-right: none; + border-top-color: transparent; + border-bottom-color: transparent; +} + +.mce-tooltip-w .mce-tooltip-arrow { + left: 0; + top: 50%; + margin-top: -5px; + border-right-style: solid; + border-left: none; + border-top-color: transparent; + border-bottom-color: transparent; +} + +// Invalid field tooltip +/* +.mce-tooltip-inner { background: #aa0000; } +.mce-tooltip-arrow-n { border-bottom-color: #aa0000; } +.mce-tooltip-arrow-s { border-top-color: #aa0000; } +.mce-tooltip-arrow-e { border-left-color: #aa0000; } +.mce-tooltip-arrow-w { border-right-color: #aa0000; } +.mce-tooltip-arrow { border: 5px dashed #aa0000; } +*/ diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Variables.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Variables.less new file mode 100644 index 00000000..3a8d9189 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Variables.less @@ -0,0 +1,123 @@ +// Variables + +@black: #000; +@white: #fff; +@grayDark: #333; +@gray: #aaa; + +// Default font +@font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; +@font-size: 14px; +@line-height: 20px; + +// Text colors +@text-color: @black; +@text-color-inverse: @white; +@text-color-disabled: lighten(@text-color, 60%); + +@textShadow: 0 1px 1px hsla(hue(@text-color-inverse), saturation(@text-color-inverse), lightness(@text-color-inverse), 0.75); +@invertedTextShadow: 0 1px 1px hsla(hue(@text-color), saturation(@text-color), lightness(@text-color), 0.75); + +// Button +@btn-text-color: #333; +@btn-text-shadow: #fff; +@btn-border-color: #c5c5c5; +@btn-caret-color: #444; +@btn-text-color-disabled: @text-color-disabled; + +@btn-background: @white; +@btn-background-highlight: darken(@white, 15%); +@btn-background-hover: darken(@btn-background, 5%); +@btn-background-highlight-hover: darken(@btn-background-highlight, 5%); + +@btn-background-primary: #0088cc; +@btn-background-primary-highlight: #0044cc; +@btn-background-primary-hover: darken(#0088cc, 5%); +@btn-background-primary-highlight-hover: darken(#0044cc, 5%); +@btn-text-color-primary: #fff; + +// Menu +@menubar-border: #ddd; +@menubar-background-active: #ddd; +@menuitem-background-hover: #0081C2; + +// Panel +@panel-border: #9E9E9E; +@panel-background: #FDFDFD; +@panel-background-highlight: #DDD; + +// Tabs +@tab-border: #ccc; +@tab-background: #e3e3e3; +@tab-background-hover: #FDFDFD; +@tab-background-active: #FDFDFD; + +// Tooltip +@tooltip-background: #000; +@tooltip-text-color: @white; + +// Popover +@popover-background: @white; +@popover-arrow-width: 10px; +@popover-arrow-color: @white; +@popover-arrow-outer-width: @popover-arrow-width + 1; +@popover-arrow-outer-color: rgba(0, 0, 0, 0.25); + +// ------ +/* +@black: #000; +@white: #fff; +@grayDark: #333; +@gray: #aaa; + +// Default font +@font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; +@font-size: 14px; +@line-height: 20px; + +// Text colors +@text-color: #aaa; +@text-color-inverse: @black; +@text-color-disabled: lighten(@text-color, 50%); + +@textShadow: 0 1px 1px hsla(hue(@text-color-inverse), saturation(@text-color-inverse), lightness(@text-color-inverse), 0.75); +@invertedTextShadow: 0 1px 1px hsla(hue(@text-color), saturation(@text-color), lightness(@text-color), 0.75); + +// Button +@btn-text-color: #333; +@btn-text-shadow: #aaa; +@btn-text-color-disabled: #888; +@btn-border-color: #666; +@btn-caret-color: #444; + +@btn-background: #ddd; +@btn-background-highlight: #888; +@btn-background-hover: #eee; +@btn-background-highlight-hover: #777; + +@btn-background-primary: #0088cc; +@btn-background-primary-highlight: #0044cc; +@btn-background-primary-hover: #0088cc; +@btn-background-primary-highlight-hover: #0044cc; +@btn-text-color-primary: #fff; + +// Menu +@menubar-border: #333; +@menubar-background-active: #333; +@menuitem-background-hover: #0081C2; + +// Panel +@panel-border: #9E9E9E; +@panel-background: #777; +@panel-background-highlight: #444; + +// Tabs +@tab-border: #ccc; +@tab-background: #e3e3e3; +@tab-background-hover: #FDFDFD; +@tab-background-active: #FDFDFD; + +// Tooltip +@tooltip-background: #000; +@tooltip-text-color: @white; +*/ \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/Window.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Window.less new file mode 100644 index 00000000..867f3dc4 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/Window.less @@ -0,0 +1,108 @@ +// Window + +.mce-fullscreen { + border: 0; padding: 0; margin: 0; + overflow: hidden; + background: #FFF; + height: 100%; +} + +div.mce-fullscreen { + position: fixed; + top: 0; left: 0; +} + +#mce-modal-block { + .opacity(0); + position: fixed; + left: 0; top: 0; + width: 100%; height: 100%; + background: #000; +} + +#mce-modal-block.mce-in { + .opacity(0.3); +} + +.mce-window-move { + cursor: move; +} + +.mce-window { + .border-radius(6px); + .box-shadow(0 3px 7px rgba(0,0,0,0.3)); + .reset-gradient(); + background: #FFF; + position: fixed; + top: 0; left: 0; + opacity: 0; + .transition(opacity 150ms ease-in); +} + +.mce-window.mce-in { + opacity: 1; +} + +.mce-window-head { + padding: 9px 15px; + border-bottom: 1px solid #EEE; + position: relative; +} + +.mce-window-head .mce-close { + position: absolute; + right: 15px; + top: 9px; + font-size: 20px; + font-weight: bold; + line-height: 20px; + color: #CCC; + text-shadow: 0 1px 0 white; + cursor: pointer; + + // IE7 + height: 20px; + overflow: hidden; +} + +.mce-close:hover { + color: #AAA; +} + +.mce-window-head .mce-title { + .inline-block(); + line-height: 20px; + font-size: 20px; + font-weight: bold; + text-rendering: optimizelegibility; + padding-right: 10px; +} + +.mce-window .mce-container-body { + display: block; +} + +.mce-foot { + display: block; + background-color: whiteSmoke; + border-top: 1px solid #DDD; + .border-radius(0 0 6px 6px); + .box-shadow(inset 0 1px 0 white); +} + +.mce-window-head .mce-dragh { + position: absolute; + top: 0; left: 0; + cursor: move; + width: 90%; + height: 100%; +} + +.mce-window iframe { + width: 100%; + height: 100%; +} + +.mce-window.mce-fullscreen, .mce-window.mce-fullscreen .mce-foot { + .border-radius(0); +} \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/content.min.css b/lib/tinymce/jscripts/tinymce4/skins/lightgray/content.min.css new file mode 100644 index 00000000..0b272601 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/content.min.css @@ -0,0 +1 @@ +body.mce-content-body{background-color:#fff;font-family:Verdana,Arial,Helvetica,sans-serif;font-size:11px;scrollbar-3dlight-color:#f0f0ee;scrollbar-arrow-color:#676662;scrollbar-base-color:#f0f0ee;scrollbar-darkshadow-color:#ddd;scrollbar-face-color:#e0e0dd;scrollbar-highlight-color:#f0f0ee;scrollbar-shadow-color:#f0f0ee;scrollbar-track-color:#f5f5f5}td,th{font-family:Verdana,Arial,Helvetica,sans-serif;font-size:11px}.mce-object{border:1px dotted #3a3a3a;background:#d5d5d5 url(img/object.gif) no-repeat center}.mce-pagebreak{cursor:default;display:block;border:0;width:100%;height:5px;border:1px dashed #666;margin-top:15px}.mce-item-anchor{cursor:default;display:inline-block;-webkit-user-select:all;-webkit-user-modify:read-only;-moz-user-select:all;-moz-user-modify:read-only;width:9px!important;height:9px!important;border:1px dotted #3a3a3a;background:#d5d5d5 url(img/anchor.gif) no-repeat center}.mce-nbsp{background:#AAA}hr{cursor:default}.mce-match-marker{background:green;color:#fff}.mce-spellchecker-word{background:url(img/wline.gif) repeat-x bottom left;cursor:default}.mce-item-table,.mce-item-table td,.mce-item-table th,.mce-item-table caption{border:1px dashed #BBB}td.mce-item-selected,th.mce-item-selected{background-color:#39f!important}.mce-edit-focus{outline:1px dotted #333} \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.dev.svg b/lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.dev.svg new file mode 100644 index 00000000..262c21e2 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.dev.svg @@ -0,0 +1,150 @@ + + + + +This is a custom SVG font generated by IcoMoon. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.eot b/lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.eot new file mode 100644 index 0000000000000000000000000000000000000000..0350809a8c6b0e7570cbd2d40678b9b8d2f35dd9 GIT binary patch literal 8196 zcmds6eQaCTb-#ySkJKj_emseirT6$GQnD?HlAAamwCmVQI(yG{Y$vX5 z5l(_7ZW2GhK^kmbXQXY~WyQv2Lsz63V5CJhbXoC+cKKuIRs+q3qR0^bF%;gg1;&N~ z-3n0qoy$u_a-1v$_SYVH@427n+;i{wy6=SyA>45xNCX5w0TB+$0$Q#Tm+q-|>LRWn zdW6U2Oxv9Aw!IGr#G~S*SQY1yR>cK$42Xl`lsF@v5a+~kagk?=!)UoE9>Z83V~CQN z6-7Dr*4b#}b@YQ~P}Eme4&8hDbKl-B#Q0vcj_%vLydqAE2k%-`obfpjz9d% z`wk4D?;WJ-BWMT(#4zTjP@j0@{Nqoa`&Q@=QNM=zKc8DYdHk!9uRn|VyibpxKmKGx z{1(_0w1B#C;rRJe_y6=iZwN7hetN#K`q<-lkNMo#z#1LuirfL@o8n@KBeL$t|7>19iaaq7y=eVkm$CYl=zi~X5 zH`aMhH+9<`H1WfF!f6z{%Fi39acNY9#LIxu?rF8=Zwkm99^SD|DZU`bLT>R?MMcaD zTa=*&MKK3em=W8>HnCMqiz!hMc`+#_ge7vq6owcVV`2-ajEF4GX-Mc$r?g0kq_{&Q za7=?xxPH+mdPR?jVGSCzBaAiGc(nwIo#g^{nUjl9S+{dz+yB?{J>pNqKZ;+_5S8fy zeVJaPcj&(Z`M`<5-v<6QxEO2%zZv|u&{$}1=xpfa&^JRj!h!I^;a9?MhTn^9jU0-c zi~K^nsJ*DYuHA^HqKnZ>(Klj7>_n{96Y1IBbFk;hp0|1toE@5+3v$?)6fO%WTjvw?6jFE z=obHNtilYN6}y5GHC?ymljGX9kAKr$!!fK0*KtA5ZF?RWw*76}aa*3-azP`&#*SJz zs{v?~NSbLYA%7J<2rAS(5)Pi(J$vYjnC?4mkG!_m+Vkss+HRu(6u@D81P)EtTI)Do zyak2N7)aES`Em`nuE1ZPx`{MsO2U}KXD22zDJ_yKZdp+TiW_u0w}*UB5oAXS4eFH3zE)-vE;DUcj^! zgeX<)q*Vc{O{axKzR~s!12V?4yI!xS$H(8Z<|_N!&i+bn=O2Sj-$TZ{t+nKOf-Ds*>B(|t3u#zZ ztzuSu*S($^ZMw}h0eNbTrmnhAvsu{>vi*JwCzRXQF5Z~W|X+t_MmYezVDeT*rpB zq^;;!ijJM=ScyBuC&fPKOLqm#TE(hps$PInGPC;s(obf>OeV~Pk3~9Q*)dw3lHs_< zZQ3A9*eatf*vuG)XE@S+V4i0*KhQ!3Mz;_#@zHenabfom0oHiAY&op7HJOI-Kx*+> zx(+4@hdiIluH*ZjC-7*(fNbCgf17~CoP`Ikid}LCY?eaGMYa&*v?ePSms6RY#5*E8 z({{PKo93;u*4ZaJsTFE^4Z@l1clwiH6_%?%nd}Eq&ia#?3>qEByWW`Ica2=v=U(5J zGn$yuEEfBdtz>`Es5{aDT($20DnirsbBkc5DOh)CRsqBcutNn6>Q#fx6l#O4C3-C& zmd{qtF8>W@{x6q()Xt%_e3n{VKD#V4zx_Gc#eVLFKU(V9fI*X#34e+};mT@B0A_UO>n0 zPotInCiE+y9Oi_g0=<(hk#e;*K)HM&LucQ9>7}<{`qS4hUw-{^`$jUGOlE&9^XBQp zndn289*SnDg%K~k-ToeiTz>s69-{tlO=Opj99e=+!(MfDf^CnDjjSxfm&1dnQyErn z-L9-V_lQQWXZYns==5UQH@tlhg2aRS49ELy=EUy$>S}%WiOgp`C!TGrutivDFpU5- z&xH+YK~8l(JJzEbUCpc;ncap8!K`WTFb?c9|Jhx?s+i;(s*mBIlbO)|Z@Fdm|aEm)v4EAD1>_$Bo z(Z&d3nV(?q04dcY(rFj+g=(!@V<}=kR>CyG87VA9`odro&*1RX z)No&PXba-RsVzg%KGgqy>()%JHZz*fkIvL`ST6LAJ=xFb8{nIxFX?x>ddIrOk?I^p zG`$+G49zedoqi^Z$#>;yU9a$qxl8y zKJ={YSd^o7y3vp`1hX0t2K1msE>?j(PiheQnk~h@>3Mv7NH{zfC4P9lQbw`oETbJe zvB8ITw5Y1AM)w3-j^p(wVd$H0ymsl*YnR$@Nn7DL1Z(8Nuo_Ms&6i$#RoVxE(-eGb zq$X%=j-jz-QWBMcXO)%SZ9_erhQVz^arq$w)=;>z?6g}RHDzSklnoFgh*GD|cR`co z37ewm4#KiaYC-tVh`caFa=MvhgU&wB_eQ5iN2m6-J-B}$b|rH6VQw6Sgf@#EbS~^e z6Z;inzLJTWo(LASgy}Y$hUei00(@t)i6!5Q+Lv&@6nHzq`v z_<&(}uKUGEbO7jpbOaz|#({AOD1mXO{x1rew;Qw_IG%vD_zGa!Z5faRf%_g|UwRQ2 z9Ka<%Q)QO(5wM2{{QqEQes3VD{eea@KXh9zKkjaPet>`}Df7PDvG=j|0Fql;dsoIo zh?J?KYnA*!AfwL)76W7;OgTKMCGW7NdxsZJ(8Evr{$(;MD|^k!2ag=sWkL8z##2AS zo?(7?k!Ay0x=>43#{vUH&)kvJCJ!U_S~{^X+&gWUdsiw3UH1K_$=Y?`$b(W91oV(# zlM@2?5T~<6MTk|k(;RVE%@4FR=9ZR@?zwVw&sD2%%$q$ymQ>tn-t$YYFC5tC;Cz#jb(Xgh|bq){r-g2CwOA%VlTc z;_&Q#w+X}U)U}wwakvrF+P)TpX%rqr(`f&hZMbB>BS4Oz-+wJ8#SZN01Bf3%zfh~r zBh+KFu30$^)|}s6RbjVb=(v;*!?M7p!^YPZsRmB~`&aFR3aJbm`&q(k3aDvWAH(c4 z{Z(#e!0?8Ke1B-jGX`dI9io`5AfUy4Ge1WbEHN&g@Platv6^1X zjFXK}SFa)BE#MtR1@9{Yq8{m;UvN@-v>w${&cb|eq<)*Gjt%;Yj~vsT7MFvu|3M|k zE!_IEc*`yb0?3zjwg$F|cpElA%fL=#^km91bEv}@=xH0G`GZgOPRDP?hlb+Rhz})l zf#AVl@S$k?YBYK?6uM0G^rw0gL-BT94k;$4dV?4dXn!UerE5{T914MccW*+7pYVo} zW5R?9g-x3L7PDgOd;!7t5aBpJUUrc&Il^%lVmQQyUb8tOptdl)J~ddHc<;1=bM>Zk zt$tnR=x) z+)yZn7Q7u&WxlTtsd7-P;9YlTObG2?SLHCiT6{;9BWVB0t)C4aJ-K>*brs(aZ~1t5 z@YIe?~OKCy+LONbIzg!~*VJC8RROmGEv`tgK#m zd}a0GnNvo2wrG69P;^l$EzFc=%Eb}}ZN??m*Y+WwF%O@*_}HVX7mU&@V(Jf@D|JMk z!G~o#s2#wMf8l!PC z$fO)uG(nS;rvgpUG;M{jZ>JfWr8z26312^Knx_g?sir+~;nC%yJ+EL{!IFZ-4lJ)I zxUAq_1wX0a9tD>a+@autf{ISLs_GR572UF}>WY3@(Jw3dB}Koa=$91zlA>Qy^h=6< zNzpGU`Xxobr0ACv{gR?zQuIrTeo4_UDf&f4zo_UJ75$>3UsUvqihfbiFDm*)MZc)% z7Zv@YqF+?>i;8|x(Jw0cw(MUi7Wv9X_@ap54kgw={&FoH6?AI>t$as>1;E22#1D7B L@*{>Dzc2p}lK$2K literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.svg b/lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.svg new file mode 100644 index 00000000..fa1d05f6 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.svg @@ -0,0 +1,150 @@ + + + + +This is a custom SVG font generated by IcoMoon. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.ttf b/lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/icomoon.ttf new file mode 100644 index 0000000000000000000000000000000000000000..4529badb8748c5a7310bf7e835e51fe8a0fe277a GIT binary patch literal 8032 zcmds6eQaCTbw7t+kNPIVk0(*G^vEZXl5I&OpGeBJtvtDw+{F2yQ^#J?*?YEQJ8^A` za1tzWllTD+(qQX4BW=?zD>g10x+2X0BQ3I_%ZfL&%O69x8fZ2YMTYQ?q40(+Fg6tE zR)E^?Ts}Hd;$$hXzxMd^MCpF1QGul>W5C8JJ$Hw({Fu?DDY*py>a^3qmA`-V4{gJ^hZyh zee#s~ay>y5`T_RufyIWUaAw~?w3qahTa5zI}ZKKbyu$DTO*t!(&8 zBD+O52y1B39M+a~)tY2bcZu{$r;NHQZAdXB1F7!U9Y7mNAkz8`zny$&yss|pgMR9c z5%{n_E(7@fIgZ~a<4U*a-#A{%8|yNso4V~bn&c7QNE!oI<#`=7DUDHxUIL7EPph?X zgCKKwgkzmjY*CGc+~TQHg%-%7GL@)E^E5}Zw4JumR+^z{Do~!LXp&6IQI-svpmEv) zDx;LaISrFeX-ZL&5_B8IDTdP?gtqikAN5iX)}TQM?RqpBU5Z|ezTRW>9PerMMtZmR-q-s?@0)#* zzUjWjzE$v_)?3gw4`-3YsTRS1vtVl3pjFEztU0bMRLkj9QZH013;A3mnYPL`Jzc(? ztElFsGs)Mk#jYCcjpfsAGX7(_TyNB8PYf>B7Z;~T^~2FjPq6133zL%zliW1yb!xS} z!PV`H_4;D$$;0~S^dd$Mp6J7<%%?GEasdZBL@wFfWCzlrL1u;^M>=F{0`gXX49-I? zYqS%qwNj>rl=4$y1FUUmmwxHnnAkN8+fa`J$UId;hVspq9W=<}sJyB2_cD>gu+PU9 zWV;`$O+gpH$x6YDTd8ckpquhqSVcCRtymS5xal}8k8Q`YJiJY39mlXvj_rV+({^1p zEbH5r?X+B{<$y*2S_I36vl@g(Q6if%~z)}CMA z({>sSpa2fzBXDTC*1Cz~h4-QG1OrnYnWxt9{uOvPr*0w*nu;*y$l1|UI;ll+g?z>_**;JO#m&*QOg;}h z8!HC386XF1ZGvtb=OL1kjO6mW1ww*r)rz9x*hil|YG=j{j%9EFb{l)Uw(H=*UDvKn z=$VW@an;7^v2Osi?>@kk8H6ZRtb|#?R-1MUi9Mt38U|!a#s@dh9-%CDE&8)97~dHv zOQ~Q%aU$DT2No&u@$vl?+cpf_sqD{v&q|Gtr>uIto|>3=*PO5HZ`=DTxt)KEZF(*; z+1q+cttTi_A(Eabr?;?%Wz{O#isv}jl4DJ$xlWL$)>!h2V>@_dZGrV0!W{4=30qAp z^v#MKMNW%omR7KqSeNak*f?_e@{v1EpMJqA^d4z6?(2W%J1%y5`MZ~kr(Za|kgvM# zedoaeg;%?&1MlhVD9)UK$&?jtOhG+cvyixu)l4KC%X8dr9*wr$Xe`QhwB3xd6x&|3 zWpp1lS}o6Oljk*?@VuMob}U85PIRoq?et072Yu>eV( znk-i=hnX^`QZOD!Ejdfa#w4=Y^`z|Bp69xRM76VbQJpEPT;0tJW?Ad-$x3L2nqGr&CI;+*1hxvxHIPUQfT&~xiF6u` zw(VYP%CJPCV5Lb|cW71t#0s!O z1r6#|gUl3aL!u>mEkG-0s%KXIMl$c0D;{cRQCc~}Eh(Q_QJL5Noa&N6D`$j;FY7_& zKOl{;o3O#%Z3{!ye)BunfM*g`}{z1U?2&V2P?2K*HxhH zH7`p007$*(2Q+vA9o(NmtN2amSHO3elRg#boob1ctF=MS) zfMI(qFtV})Uk(qRN~T4*b*pmIxkog1T*E6bL8q6>p5g9$03;sRXV~s%)5mw$*VgL0 zkEcKD+ObSyRV>14Ludq`c@At)3v#N<*@+(2AV*e8Gqr-LYgSFS3hY8QZRh;nqeu6; zuFCnz5#x?=q}tJ=u8SnNlsyxf2d=3NxPl*zYs5#zGhJLtuJ{Jl)v-gsSHYRfxsS3Q z3@Z_XMC+Ok1!_4s=jOIkOUF61ygbo;4Ld+~yUEYT+Rr=PM)Y=gOI|=&93+YZtGFT- z2SJE!@u1K1X>X2OXaq)tE7q2PSxJCd(CCWnbP7rQQW#Ja90;Myu4^E%jjW9f1@^?G zV9Ac*IFL#_ZYMPXI;0g_pSAN?B-@h$? zS9hFen5A=@qmU;mOqmgVXlhqICdP!f_52Ql3{j^)i z-f~>~aVPCma1DWe{x*vD8;0vRUyMWtfeuJV0YcdrFfIcnFz(d<#fRBj4cZPIkHcDg z1u*5b3`hduzQ^E8AL4=oxa6m+vgLdP+d~BYf54gF8%$__ps~si-g1{8mm8lSWME3D zy#H3)`&c}HvMsn02>HX4ozu^+sv81k;UWu&{LjwiH*wY z-t5!^hY##BA$+XjsULx7m>*u^xqy}`)Kb;)z##L}we!LE+5%5-=p>L^rjl& zI=5#ocI2`>-_ygJDnyZvvTX7{>5iAu;i=v~mX# zwTd&GjwNEU@xnbC?f>#4gx_ppjA00mHqlLVyoJOE-Cw}BQ(b%2g_}rvxQK0ju|XJm zo1ar1FKx)>ST@t0!Pm8A*d=u@kpKWeuEYaK2-4ybl1p5Q%c?3>;tP2;#gCyK0#w^j z);E+P&`h59#uyyU*ib4p^tGXst@2d+`%h_oeVSySF|?i@O|n0~*~Tp}2eVu^HPpT? zQ{Q+)avmN^wY{Ff9=xqh0DB7GJj2ennLNG_LdWEiar35eb3ZAo7MGoBm24_ev1-_A zJj=}m_~9TnnwH2EW=>~9szO$ z{r+p3q8;Gr{fHkyzfh|#Ak-7Hu9-Ov)?B__RbjVb=%kbn!?M7p!^YQ^xCT!E`&aFR z3dyt>`#HvE3aDvWAIIzz|5a{w&~S%`J#To}H3nyM6WWNL+iuQ8v)Sm3xjmDqV<#f%D(_P`m!`0mz#7X_sD(p@?a!X9Ys;=%A@C}isDhOzC z-^|am2}_KNC;VUvL9C|N(i3bU)YWT2d+V{~=`C9zJ%lF*Pc27h*WXhiE!EUXL3hO~N~^U|+dmU#(wLIr_Uaa1wFOsv`r6&eKmX$_PA68oX_%96)*6F9+d4 zpYY2ew7=??CG!5EUyh*tI(EaM9<<==kYASj>abr9(ki}ncgBR!{&l|`#=jQd@yijk z|AZc)6SPL>kk;rt(IY3;&aJJXa37td)ATrKfDjiX0@L|~wbv^+OaF9bB<_K#X z++on*5*UKJ1PMMsa19#V-GUG94#C|mg9J;E;O+!pe*fCq zFZ*G)t4_T>=iR#ZzT5qwyYBN)k&{!=)KmcgXp#XKfY%|22|)Po`F{^-IXM~t009*M zpg05oc(832_!i~lG(Q3Wlvl6TWUrvG^l4y|mywkN0H|rMj>DH5Opi4gr{LZ|eE#k2>#_BmWNsQ~?gA_7<;N=_~*98Y5I?`Et+k zi;L@PTH&u6<|}9bhyZ|RR;NCSC&7G6H-0l-Ur;T%Vjl-EzMh6TiZ8{CsZG)7XG!S? ze7$(HGnKShK~&Tzx{nev3`}@1x{orMm6Cy|aA`FA1hRDghOMr(43Ty;)Kj0A)0fU$ zq^VWs6QSE2mlI}QR_cW+7#C>Bl{IZd_iiA)3g=yY>%i6|p{_=Osp+<^XvL5%H!;LwQkQih z$IX1Yj;d0CyeG6C?}!qd(mDNTM{6+EWukZF(;RYa(p`^ugeo$~QCo2YZl@gOGD`=r^`%>))I=FNo4_v$MV z@&@N0h~pRsVKJVKL~)jzKQ%=&!-rv;KXpZcusObS+(&h!Zp~g!*)s^3XNztb^fGBXIVY1X6&i|g3WeZ?qnwjT zV##8OI}mCJMqvn?&Ze$W=3Yjhg*_=1lB>vCI9-?m--Wa6W7sq$Ggl>aC3ht*DC)s~ z!G-t9nGNo>@0IUA>2p5O*vEqvzw6@HH<8#tl(N%*ayOW14^(n1ae=wSpx%9aeWLSU zM=m-nH1}IRAEuc)t&CN(x7Qsx9ClZJuJYO@(&v}%>i>TPv zF=Mr5*A6YuwBKd3yx^WPL)mczx#&Us{E3k`{6z4JoUf6uRkYM{E)F2YL`?F(qxe(#AYh$~_8}GO5qLK`?I$Z~s zfmzoMLPY7m)_j6oijMWBYErZNy-ZE%z)3Ae$O}1Aj?evj>y>^R%u{6K*}|o95hLl+ zDA!2!NvYY+V>0Gp$|trxq7@)PGOEw4+8L`i z)99?n+#%%|`Z`3j`_NL^q7xUQXdpd!7%76#o>}oP1yg6H(mbrw-PUUkGi}^X%Z|3D zQ_ha-sCis5)K&vat|Bo%CZx0c7e@tY?Jnu`3llxa!YLVTNcCkLaujC}F z8*qBTDA+!m_M;L5DvH2eF+2HWg%DRsSF*Y&<&5|`P^??i15-56%++ruJSZpcbp zXPMI8lDQcgb>&h-yIys1PTI_K*S(@>?rAozh(R zYalDf?Nj9}Fik^ob`)y6m0+il_=qmu@o%)hFpefOM#4Vm3j|-CBy7Z#VvZYl{>&=L zr5UatIl;Iy)l)=BuDId;{G}Hn?&S9{=hHgq8d!tvOQKVX{y1cO>LJ&{=`iP|A)ZGe zH0b4*g5(T@GqD=2FmvhMA-Q6NEo@A9JG>@8r8jtmznC)l2VQV>9zeOPN5A8|;CIJ1 z<(~x(Zy^3erD#GKvteCj-8|bUiCq+@H;J`!q)@kjyOf`~fswB1vAC14(avKoG)vEV z63 z?Y4i}+*o=04N8gg%8pZnAcavHNen6h#&%AU(dP}JV`q*L1{s-A?{%Qf0NdrIIFLVR zbr@-#*g9zF-+uNJ&2HtnQd5Q_FQU5+uFeW>{nGp~$KYw8onbvI(>TH)WpawXpu&7a zI93`U-S-H0&+Z5}OlvfhO(<8(3KzTSF$$Db3NIzAH#b|jeFAjkcX_fM{fWrPp? z#^3jMZoEk{;|T1nu)cQS6wa3GK&W4Lk`mWf*}TtJh=JIu+IdkYfmut!=_X4747~c$AxDaWD=9CIEbnSj9XE|x@*&_4rPe!%U` zODztBapYbg>PWN=?H$;NEREdo_292_n+;3CK~@4@ksF zD{M8rl89d}`H@0sLVoMxHuZ&Fjw1FLtHrTFEeG3yU0-?~-Ax4*Ku|+6n_Abpc41u^ zqzn0cCS8a&_2(1`57Pkiu6ym!V=9bY8I~D& z)GZqB_r5_MZ&BvA>l^MYe>za4pg(Z~K$edP_RV8(07SWs@0&3TdsH+tzT^X<_Ei4v z`X&ln_ckx^RLZj+!I2H*=aDoD+l+~WXWtn$pWjz^*odUv@mOGqZ=E^f$tXv=)B-<08t zK&pmz8_sJiMLkDg5K33TpiZ$QfR9&VbZg8t-!!Y>c+H^T6GP!m6ey1l4?o zM5cY{Po&GsiQVSCg*KLc+}jLKQq!N7`_Bf7zgfEtw8ej*lV4e5jPSN1~s zX2Q8(a#_aNb+vj#%lQf;cu+tF@$sEEzdDqnXu;{IM8_=x@`B#i)2yWw(s2-ir>sKd z7f7syJ_Hy?Lx2Xne5lg4Vo3&w#_9iDGE)_0Rc$Mr`MdNhZd!&chyRqfJO+ z;WM-@^tv^afZyspD){tA_NCh~c^>>}i@R~zX!CK_`Akwsd;pew{8bs0&N;iMP-w}g zl76H&0j*eSkSQ7F_dM5}K?nmb1tlJd|5(0tAso3%J$>JIC&CFz9AfMPkL#2HS7e>0 zHuwFs3qjMVHnY)rtBt1noTk~8-14bS_n zNdNZKTwS+)*uDT2v|CYJz%G-wjB;or?Pl)!9qH6XD-?jX@Wu1ZK62t9t*=nQDtTo6 z{0qZ^2w+VXEdF1fH**Im-Jc?%m+#e=^Q$7ND?8@Pe^p(XPsL|zz&yVjhWFV{X^sbe z_uYZ^ss`fX%)s4@qozbvrC6yC350)yg^(jyz7KdYT|*mpUJx8Ku?EF|l2m!&OS~(t z^nB`Jc{ix0rOk|{M_<8kENRhD6tAjQMC!}k_(-E)b&IPo(w{Y}S8H0wKf?M$yL$6z zl@rEvD`&F#OEb9)4VEfpz5S5qtb54{_Hsf5-a^(a!mF)1DD!KjH%uk zLG}uy?&+p(LAkP^M#$$V6>t(61hsBpfdPkLIN1359BQ$*F<5f(OkveV63GfYl z5FKrHeJ=U zm6NgG#GczAphbydwbhuztrx0eHR`$VTFt7fO&c?arCGkQ=nL~j{aMrP_A|YAPg2}1IZ^dTs+?xzyd-Sj6_8*i#*yrW4yh@*yn*+IX zf$YXvw7h%M46pg3Dcxc1ZKl_{PPX72|_!Y+Zo&tr&dCk1fthu9&Rlum5QkJtOO51;Awh^gdNs&VSdJEWw zq|i~kb+w2{X8%;|POY?J^!erhNskTI4`#C!+`4ZW1!IA=5V4duK-0n#KmIiI#)te; z(sL$c+^HC0A%PLKyHbMSPTN4zOxfb;OU9n=WrTl4PL5?-upX-axgwA``wdvJ-+ z+}v(w=D9Zc;ObL__f8U5v0}fYuX2oxYG;F$=q^h0@o-Z$K?TBUaEdVsM zijrT$@+tETLaKL@P|PQpsrAPMu8a`uRw)sd&UGgTJel;OB@7whQi8=7kBoH};P)qD zJTE1aw@hL$=&-yor4hHlxi@R=F6BtnDE<~sI-%8YCQ6A>vG&f$a11s8)5n4 zd_Z_K?X_qnvx3Irl$MM+ovHG|Ow*;#d;oX(12_mDFM%G2E>InvK6yQEu825VNUN{5!nwo z*}C%&g52sMCj<9sGZ#gr`0YC5FKfzdpv{5x>SrD0iAY14gC`$O5l)u$H`EsBcWQ~W zK^Lv#G-7|>B~Luk2G@ibVZ(*)vn^)p9wcneu5x4eYJRkct2jpZ}nuZ>mfGKTsC$rNHh z1o;!KH5>@5Eb_A)K$96a>U;rjR#o$bwMMyS;KXvf&=b4SmKJ5?dvH!nC|&cs@RS}4 zU|L8YU)GACP!4p(eeY13UkGoJVsl|y;;NCFeP`c~0waGu5F=NPc4+l??KgsvH$Od) zS09Jl{Ts2NoLLkHvw^Jpn<%lpt+Yk7C*78kPJ&Fk$3KaH?Y<#55?dr2zQmk*HRcq9F|x1dALcKe7+Vc=_R1`4!5ZWz!v%c$ zIe#^UedeYHAwH5V#fNHir^ zJiuDt(T%zjN-=aXr@m5@UWtA;e4vV%@l!?BcUnd)o2~RFFV0GA(1gQ@<`}rVGmkk% zW+ZRXe_45{79v=48)p4unV1Mtb0FB6`dJR8DHXm*=h;^^zmQ?Qj^B4Aodl}M7;~b}IvBoTSO*F@bGe=zS z$->+~A@aK)X*APlp3g_aC;nn__BmecO+wwu5O)j)CqRX#d<>QM=MPqbU+z5K*-A1P zOme`|cNwD=K1YeeYnrUzU$e^)UN4HwSOLr81wBey{-U9UuSF{~wx|iR``X2cpHV8T zl8#+u3(K}dS|77;N`jlJDP98uLS49FMB7L1;&%Xwz>ItI2+1QWTNZ~XSLBZr2{mdv6A96!F}i$ z#_1SGHC*KS0wn9u;7Qyk&-}ByPKl-14|sn6+!`yxoR-g&Xjm3WIc+@wRr7x%bS_m; zm4k)~YfPan_dP!hs1D-p$n~s$3Z;B)z0$2ODzMs>naig2{(f-^fc%MqVD ziPa1LoAVScjzt-93ma@m)B8JG8^j1%3*{xP?SgJoM-lHxQok;xXzU=@oplg(n>l#5 zjHtdTpfrel8h?;(AbVoFHW5vPGhvn$huvUIfB&pPL7FuJtDfjG{oYm1F`)J)NgIoy zhrV#1onbzV+r2Y3o)23ssZhmTqFWfv_nMK?9c)uZlz9JuBRqFp)VWFj*#} zB_svu90hm1p^w8$8JuWr0}ms?GinsqF*&kM^JHz7ATNTB4*PL1oVW-2EFF5HuJ7KDl|CtAlQ8pJl;t)E0-tAb^;vre% z#|gW5!cOiJg~k&yM)?Mz7h)`3RnemD!VLUJ) z58%NG@u7I$oNSNh+;j*w#;~;2gAjr}1{vfuerxPq=-P^6WcU->jmR!?3dI#fQM$+q z2(e^1b^h!DE)+Oq2q7RhCkwdZORe0WTQ=jYw5Ux^&;{jhLV1#O=~DF#j%Re~px~QE zTu7T7lB}wB9f^n?gQ}5lI++T(*k%g3<@>WSUfNV@^xx=G*YTv;9`^GrxUxY~ za##^FX{f0*8wiFOvKyMcuQ*x~VXZ1RYGoWZa%FE1*U+fJpMK@n@zrEqU^OemV zS;~tO`6o$1=!yoFgIde?us8~#RXlKdXq;ik1gW9`r$L8jhIEFVerS>)>ZRq%_FzRX znA8nq?0!taX8VMKCfg-WP@rersoAG+nBF#NF73*RD2n6%-5*z~@~WCo#a%CSu^xR zF&Gn6MLUEf@k>GcX}ngt^{P%kRoV}>c}w#Xn+e=thOu(QlXf3#B;RchDPC)L+j<-s zShLV`t5~Y9Z1t_DXeO;fD2jWJE4VDBpaVywa;q0!vQCjEMZTX;CKZ?mtq>0ng6dl% zC#1xIoa4(pIERy^3{4A0uw7tnj7g8- z5NzuWa#y^I5sxo^LYNowsD04#G)asF-J0(5I2I?^Zc*%BYg^#XtUro4#zK_VKfsgP z0P&-Z_=eal7J3;eQba<;CU;-~Ep=27ZvxtZ@R+0aJ;g~@h;6kG+%5#v2)uVsK~iq& zP=JP?`&`=Tb6(iRyQJQI>F*Nz`r7OKY+_~Gs)`d8SClY>rWr*=~>4v>gM^t z)5yie#a+w8+Y<-~8pVy@$?RJ{3)nzJ{QK<%hvbTcnv03=)uNA(2|!B^z?H(Je)Y8- z8-~{>feF0j7Rt=x7P7(|R7bs5eM6c4aI1<0w{|5{Xh88C;O{Z{TQu4#G^+8wLTPbO zOaPp(4vvZ3Ky_wyu|6dHtCLGKE^W6ZmIv*vc^GC2TX=?_F#CoM@ z7*+K1%f<^L2zdxaf&&Fn_qEMEfd1xx*Xiro3&J-l{Qei57n1Y_E&oe3cxlapbjw^dGm!j9oL&A&z5wCi<*Ew%0j}1na%rc{35dM7U9g| zh3=7z_Aa211hChNg7#W)fGPkW@LzszvD~(Z+_q5cLe{0+aJ-qB;;v3>q?n~7)Ze|=1iFeEhpzxP$o>kkON0O0=u`NyuK literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/readme.md b/lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/readme.md new file mode 100644 index 00000000..fa5d6394 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/fonts/readme.md @@ -0,0 +1 @@ +Icons are generated and provided by the http://icomoon.io service. diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/img/anchor.gif b/lib/tinymce/jscripts/tinymce4/skins/lightgray/img/anchor.gif new file mode 100644 index 0000000000000000000000000000000000000000..606348c7f53dba169a9aca7279a2a973f4b07bdb GIT binary patch literal 53 zcmZ?wbhEHbWM^P!XkcUjg8%>jEB<5wG8q|kKzxu40~1eAV&{y5e`l1KFoiKNSOWkz C+YCGa literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/img/loader.gif b/lib/tinymce/jscripts/tinymce4/skins/lightgray/img/loader.gif new file mode 100644 index 0000000000000000000000000000000000000000..c69e937232b24ea30f01c68bbd2ebc798dcecfcb GIT binary patch literal 2608 zcmdVcdr(tX9tZGC9yiG~=H_*Q-0%n(kWqP*D#hw{AQu8;1%gl-Hrf&{2?48KX;hHy z3Ze*zEz4t3XdUFyLbNPUYlA`|B}P=N1fqtL1*}S;87#|-W9v<#G;ul(e%d3)N(^9c$d2Dz{7}?ErjNd;{EMKkCsk21~b9Gvg zDo<7L=3Z5HNbVlZUcm1eg#o#CZCJU`3IYHwM->zCd?uYrF3vKFeM}v?f+%s?E>ly|3W25ry9#NNbTx-}0ON58dTrs^ix{_1O0Wh~SVSBlH)Ajn zPn^Gbjz}PCtN@#keR&hK&Dhl-b$kZ8^S)x#dh0{7X=X%CCJk7P1PSO>T&S8I4{#Lg zb5#)o=;!ZP*1nM{cI4@(x7o27*SA()NHmrn67aN@Pmi~(i_SnrjYnwh36aG%!@i0d zqbvfa44f|?OG4ntP|nbjhEl1)Yp6ZN@yjy zy4==QmLy%t;ps3R?~f2KfTTI|2?q8dFd6^z5GF+Xa&Y)sjG)hxit80pPcOP zJ z*LW{SyGHD%hUotV+W%I}fBLAIx!8|7#}$;clKQ+{&FjDqGQ2ZNx(lYM3*%~}ILnao zM`aui55~ZFJlu^!5rdA9Q_7H68H_;##u{x(Yn-vSfIRCb^Nqsg zGRS!Egm>h+o<}LeV4&CLReo9FrDjDvs}8?JwC)#Qs|ie=r?~xUh)&*d`Fx>FG}%X# zNdtDHBKhLPC0wpooFDAQKL%*6T|ULH$=wX!NhcasgD3d;-d$I6yRK3yN+E~C1335_iLOt+*9uvSZ`>*KA}vm}08wRq=>5l|t*Na&jR z-C1&C`nkEk#sB|@yyt-#fXngP04My zm7u$Q%EJbHp`>~`5W&L{W!6`y&}LMS;jfUpgO~7TLVMRZ9IC)IZp0A${`yp0{&wco z#1nx@XMkhqeK%7?RE7JdLr1^nwFfaJ0Q&Lv?WNJ%9}VSJsNY2+UYs2%EU0J~ayFXv zi*?7KCXQHkD)O6!0Q%4N+HTODHxJ{kQSuQX$l-rSwkwh(zMkdfzxyGwl@yHC)C4p< z&n2%8#M?)Q@mgHL1ot8`SFdSEj9ye|jHy+U8#@HoUExG=@AVkRAe_qYm4EpzK6L*& zh`)26?V#f4#_h^P9G^%>h2-H3)$QP zQovu6J9qDvsxqweDdNNa!Lb?L4_UF{tLX_nN7r0U_vF14YKcGR-*Gl} zx3oG)bzf|65dBxD-;2ZCp??K;+TuQ9onnK?==5hzbkb^r_g>z4#D8mcv8(+XdoszA zCx-qhdgxMNMotj}SiL_6V(tLcsK7(M(r(%u<}QrVfOvyK6_;~NOTlPGfX@M7S5YQF z&*$(ylJMHJt^_aQeu{C6NaTE$G3HNN@_SnN8YcaKn%`)F@~L1x+ah7-gEJPpc6w%3 zyX}r+Qk$4RHZzfH){e~F*qJ{d*L8a6n4;U?+{de0-t)mal#TVxe)3F}^UBh+zd T)6_**#cgp_+?JL9(ew3BlNF>u literal 0 HcmV?d00001 diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/img/object.gif b/lib/tinymce/jscripts/tinymce4/skins/lightgray/img/object.gif new file mode 100644 index 0000000000000000000000000000000000000000..cccd7f023fb80908cb33bb7d9604236cd21b7ae7 GIT binary patch literal 152 zcmV;J0B8S4Nk%w1VG#fg0J9GO<>lo+KR<78Z?v?uS65g4{r%Y3*xlXT%F4>`@9+2b z_ww@cot>Tk|Nk>HGXMYpA^8LW000jFEC2ui01*HU000C<(8)=wd#<&tyXIMjHBV`d zBSi|xsj3(;nD0kQ0aJq8eLH~x02P|t2!_J&Wqb%0io?#xD.mce-arrow{left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);top:-11px}.mce-floatpanel.mce-popover.mce-bottom>.mce-arrow:after{top:1px;margin-left:-10px;border-top-width:0;border-bottom-color:#fff}.mce-floatpanel.mce-popover.mce-bottom.mce-start{margin-left:-22px}.mce-floatpanel.mce-popover.mce-bottom.mce-start>.mce-arrow{left:20px}.mce-floatpanel.mce-popover.mce-bottom.mce-end{margin-left:22px}.mce-floatpanel.mce-popover.mce-bottom.mce-end>.mce-arrow{right:10px;left:auto}.mce-fullscreen{border:0;padding:0;margin:0;overflow:hidden;background:#FFF;height:100%}div.mce-fullscreen{position:fixed;top:0;left:0}#mce-modal-block{opacity:0;filter:alpha(opacity=0);zoom:1;position:fixed;left:0;top:0;width:100%;height:100%;background:#000}#mce-modal-block.mce-in{opacity:.3;filter:alpha(opacity=30);zoom:1}.mce-window-move{cursor:move}.mce-window{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 3px 7px rgba(0,0,0,0.3);-moz-box-shadow:0 3px 7px rgba(0,0,0,0.3);box-shadow:0 3px 7px rgba(0,0,0,0.3);filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);background:transparent;background:#FFF;position:fixed;top:0;left:0;opacity:0;-webkit-transition:opacity 150ms ease-in;transition:opacity 150ms ease-in}.mce-window.mce-in{opacity:1}.mce-window-head{padding:9px 15px;border-bottom:1px solid #EEE;position:relative}.mce-window-head .mce-close{position:absolute;right:15px;top:9px;font-size:20px;font-weight:bold;line-height:20px;color:#CCC;text-shadow:0 1px 0 white;cursor:pointer;height:20px;overflow:hidden}.mce-close:hover{color:#AAA}.mce-window-head .mce-title{display:inline-block;*display:inline;*zoom:1;line-height:20px;font-size:20px;font-weight:bold;text-rendering:optimizelegibility;padding-right:10px}.mce-window .mce-container-body{display:block}.mce-foot{display:block;background-color:whiteSmoke;border-top:1px solid #DDD;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;-webkit-box-shadow:inset 0 1px 0 #fff;-moz-box-shadow:inset 0 1px 0 #fff;box-shadow:inset 0 1px 0 #fff}.mce-window-head .mce-dragh{position:absolute;top:0;left:0;cursor:move;width:90%;height:100%}.mce-window iframe{width:100%;height:100%}.mce-window.mce-fullscreen,.mce-window.mce-fullscreen .mce-foot{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.mce-abs-layout{position:relative}body .mce-abs-layout-item,.mce-abs-end{position:absolute}.mce-abs-end{width:1px;height:1px}.mce-container-body.mce-abs-layout{overflow:hidden}.mce-tooltip{position:absolute;padding:5px;opacity:.8;filter:alpha(opacity=80);zoom:1}.mce-tooltip-inner{font-size:11px;background-color:#000;color:#fff;max-width:200px;padding:5px 8px 4px 8px;text-align:center;white-space:normal}.mce-tooltip-inner{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.mce-tooltip-inner{-webkit-box-shadow:0 0 5px #000;-moz-box-shadow:0 0 5px #000;box-shadow:0 0 5px #000}.mce-tooltip-arrow{position:absolute;width:0;height:0;line-height:0;border:5px dashed #000}.mce-tooltip-arrow-n{border-bottom-color:#000}.mce-tooltip-arrow-s{border-top-color:#000}.mce-tooltip-arrow-e{border-left-color:#000}.mce-tooltip-arrow-w{border-right-color:#000}.mce-tooltip-n .mce-tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-style:solid;border-top:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-nw .mce-tooltip-arrow{top:0;left:10px;border-bottom-style:solid;border-top:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-ne .mce-tooltip-arrow{top:0;right:10px;border-bottom-style:solid;border-top:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-s .mce-tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-style:solid;border-bottom:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-sw .mce-tooltip-arrow{bottom:0;left:10px;border-top-style:solid;border-bottom:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-se .mce-tooltip-arrow{bottom:0;right:10px;border-top-style:solid;border-bottom:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-e .mce-tooltip-arrow{right:0;top:50%;margin-top:-5px;border-left-style:solid;border-right:0;border-top-color:transparent;border-bottom-color:transparent}.mce-tooltip-w .mce-tooltip-arrow{left:0;top:50%;margin-top:-5px;border-right-style:solid;border-left:none;border-top-color:transparent;border-bottom-color:transparent}.mce-btn{border:1px solid #c5c5c5;position:relative;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fff,#d9d9d9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#d9d9d9));background-image:-webkit-linear-gradient(top,#fff,#d9d9d9);background-image:-o-linear-gradient(top,#fff,#d9d9d9);background-image:linear-gradient(to bottom,#fff,#d9d9d9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffd9d9d9',GradientType=0);zoom:1;border-color:#d9d9d9 #d9d9d9 #b3b3b3;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);display:inline-block;*display:inline;*zoom:1;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.mce-btn:hover,.mce-btn:focus{text-decoration:none;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#e3e3e3;background-image:-moz-linear-gradient(top,#f2f2f2,#ccc);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f2f2f2),to(#ccc));background-image:-webkit-linear-gradient(top,#f2f2f2,#ccc);background-image:-o-linear-gradient(top,#f2f2f2,#ccc);background-image:linear-gradient(to bottom,#f2f2f2,#ccc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2',endColorstr='#ffcccccc',GradientType=0);zoom:1;border-color:#ccc #ccc #a6a6a6;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25)}.mce-btn.mce-disabled,.mce-btn.mce-disabled:hover{cursor:default;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;opacity:.65;filter:alpha(opacity=65);zoom:1}.mce-btn.mce-active,.mce-btn.mce-active:hover{color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#d6d6d6;background-image:-moz-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:-webkit-gradient(linear,0 0,0 100%,from(#e6e6e6),to(#bfbfbf));background-image:-webkit-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:-o-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:linear-gradient(to bottom,#e6e6e6,#bfbfbf);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe6e6e6',endColorstr='#ffbfbfbf',GradientType=0);zoom:1;border-color:#bfbfbf #bfbfbf #999;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.mce-btn button{padding:4px 10px;font-size:14px;line-height:20px;*line-height:16px;cursor:pointer;color:#333;overflow:visible;-webkit-appearance:none}.mce-btn button::-moz-focus-inner{border:0;padding:0}.mce-btn i{text-shadow:1px 1px #fff}.mce-primary{color:#fff;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);zoom:1;border-color:#04c #04c #002b80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25)}.mce-primary:hover,.mce-primary:focus{color:#fff;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#005fb3;background-image:-moz-linear-gradient(top,#0077b3,#003cb3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#0077b3),to(#003cb3));background-image:-webkit-linear-gradient(top,#0077b3,#003cb3);background-image:-o-linear-gradient(top,#0077b3,#003cb3);background-image:linear-gradient(to bottom,#0077b3,#003cb3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0077b3',endColorstr='#ff003cb3',GradientType=0);zoom:1;border-color:#003cb3 #003cb3 #026;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25)}.mce-primary button{color:#fff}.mce-btn-large button{padding:9px 14px;font-size:16px;line-height:normal;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.mce-btn-large i{margin-top:2px}.mce-btn-small button{padding:3px 5px;font-size:12px;line-height:15px}.mce-btn-small i{margin-top:0}.mce-btn .mce-caret{margin-top:8px;*margin-top:6px;margin-left:0}.mce-btn-small .mce-caret{margin-top:6px;*margin-top:4px;margin-left:0}.mce-caret{display:inline-block;*display:inline;*zoom:1;width:0;height:0;vertical-align:top;border-top:4px solid #444;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.mce-disabled .mce-caret{border-top-color:#999}.mce-caret.mce-up{border-bottom:4px solid #444;border-top:0}.mce-btn-group .mce-btn{border-width:1px 0 1px 0;margin:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.mce-btn-group .mce-btn:hover,.mce-btn-group .mce-btn:focus{color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#e3e3e3;background-image:-moz-linear-gradient(top,#f2f2f2,#ccc);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f2f2f2),to(#ccc));background-image:-webkit-linear-gradient(top,#f2f2f2,#ccc);background-image:-o-linear-gradient(top,#f2f2f2,#ccc);background-image:linear-gradient(to bottom,#f2f2f2,#ccc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2',endColorstr='#ffcccccc',GradientType=0);zoom:1;border-color:#ccc #ccc #a6a6a6;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25)}.mce-btn-group .mce-btn.mce-disabled,.mce-btn-group .mce-btn.mce-disabled:hover{-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fff,#d9d9d9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#d9d9d9));background-image:-webkit-linear-gradient(top,#fff,#d9d9d9);background-image:-o-linear-gradient(top,#fff,#d9d9d9);background-image:linear-gradient(to bottom,#fff,#d9d9d9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffd9d9d9',GradientType=0);border-color:#d9d9d9 #d9d9d9 #b3b3b3;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);opacity:1;filter:alpha(opacity=100);zoom:1}.mce-btn-group .mce-btn.mce-active,.mce-btn-group .mce-btn.mce-active:hover,.mce-btn-group .mce-btn:active{color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#d6d6d6;background-image:-moz-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:-webkit-gradient(linear,0 0,0 100%,from(#e6e6e6),to(#bfbfbf));background-image:-webkit-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:-o-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:linear-gradient(to bottom,#e6e6e6,#bfbfbf);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe6e6e6',endColorstr='#ffbfbfbf',GradientType=0);zoom:1;border-color:#bfbfbf #bfbfbf #999;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.mce-btn-group .mce-btn.mce-disabled button{opacity:.65;filter:alpha(opacity=65);zoom:1}.mce-btn-group .mce-first{border-left:1px solid #c5c5c5;-webkit-border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;border-radius:3px 0 0 3px}.mce-btn-group .mce-last{border-right:1px solid #c5c5c5;-webkit-border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;border-radius:0 3px 3px 0}.mce-btn-group .mce-first.mce-last{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.mce-btn-group .mce-btn.mce-flow-layout-item{margin:0}.mce-checkbox{cursor:pointer}i.mce-i-checkbox{margin:0 3px 0 0;border:1px solid #c5c5c5;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fdfdfd,#ddd);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fdfdfd),to(#ddd));background-image:-webkit-linear-gradient(top,#fdfdfd,#ddd);background-image:-o-linear-gradient(top,#fdfdfd,#ddd);background-image:linear-gradient(to bottom,#fdfdfd,#ddd);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffdfdfd',endColorstr='#ffdddddd',GradientType=0);zoom:1;font-size:0;line-height:0}.mce-checked i.mce-i-checkbox{color:#000;font-size:16px;line-height:16px}.mce-checkbox:focus i.mce-i-checkbox{border:1px solid red;border:1px solid rgba(82,168,236,0.8);-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.mce-colorbutton .mce-ico{position:relative}.mce-colorpicker{background:#FFF}.mce-colorbutton-grid{margin:4px}.mce-grid td div{border:1px solid #808080;width:12px;height:12px;margin:2px;cursor:pointer}.mce-grid td div:hover{border-color:black}.mce-grid td div:focus{border-color:red;outline:1px solid rgba(82,168,236,0.8);border-color:rgba(82,168,236,0.8)}.mce-colorbutton{position:relative}.mce-colorbutton .mce-preview{display:block;position:absolute;left:50%;top:50%;margin-left:-8px;margin-top:7px;background:gray;width:16px;height:2px;overflow:hidden}.mce-combobox{display:inline-block;*display:inline;*zoom:1;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;width:100px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.mce-combobox input{border-color:1px solid #c5c5c5;border-right-color:rgba(0,0,0,0.15);height:28px}.mce-combobox.mce-has-open input{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.mce-combobox .mce-btn{border-left:0;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.mce-combobox button{padding-right:8px;padding-left:8px}.mce-combobox *:focus{border-color:red;border-color:rgba(82,168,236,0.8);-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.mce-path{display:inline-block;*display:inline;*zoom:1;padding:8px;white-space:normal}.mce-path .mce-txt{display:inline-block;padding-right:3px}.mce-path .mce-path-body{display:inline-block}.mce-path-item{display:inline-block;*display:inline;*zoom:1;cursor:pointer;color:#000}.mce-path-item:hover{text-decoration:underline}.mce-path-item:focus{background:gray;color:white}.mce-path .mce-divider{display:inline}.mce-fieldset{border:0 solid #9e9e9e;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.mce-fieldset>.mce-container-body{margin-top:-15px}.mce-fieldset-title{margin-left:5px;padding:0 5px 0 5px}.mce-fit-layout{display:inline-block;*display:inline;*zoom:1}.mce-fit-layout-item{position:absolute}.mce-flow-layout-item{display:inline-block;*display:inline;*zoom:1}.mce-flow-layout-item{margin:2px 0 2px 2px}.mce-flow-layout-item.mce-last{margin-right:2px}.mce-flow-layout{white-space:normal}.mce-iframe{border:0 solid #c5c5c5;width:100%;height:100%}.mce-label{display:inline-block;*display:inline;*zoom:1;text-shadow:0 1px 1px rgba(255,255,255,0.75);border:0 solid #c5c5c5;overflow:hidden}.mce-label.mce-autoscroll{overflow:auto}.mce-label-disabled .mce-text{color:#999}.mce-label.mce-multiline{white-space:pre-wrap}.mce-menubar .mce-menubtn{border-color:transparent;background:transparent;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;filter:none}.mce-menubar{border:1px solid #ddd}.mce-menubar .mce-menubtn button{color:#000}.mce-menubar .mce-menubtn:hover,.mce-menubar .mce-menubtn.mce-active,.mce-menubtn:focus{border-color:transparent;background:#ddd;filter:none}.mce-menubtn.mce-disabled span{color:#999}.mce-listbox button{text-align:left;padding-right:20px;position:relative}.mce-listbox .mce-caret{position:absolute;margin-top:-2px;right:8px;top:50%}.mce-listbox span{width:100%;display:block;overflow:hidden}.mce-menu-item{display:block;padding:6px 20px;clear:both;font-weight:normal;line-height:20px;color:#333;white-space:nowrap;cursor:pointer;line-height:normal}.mce-menu-item.mce-disabled .mce-text{color:#999}.mce-menu-item:hover,.mce-menu-item.mce-selected,.mce-menu-item:focus{text-decoration:none;color:#fff;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0);zoom:1}.mce-menu-item:hover .mce-text,.mce-menu-item.mce-selected .mce-text{color:#fff}.mce-menu-item:hover .mce-ico,.mce-menu-item.mce-selected .mce-ico,.mce-menu-item:focus .mce-ico{color:white}.mce-menu-shortcut{display:inline-block;color:#999}.mce-menu-shortcut{display:inline-block;*display:inline;*zoom:1;padding:0 20px 0 20px}.mce-menu-item .mce-caret{margin-top:6px;*margin-top:3px;margin-right:6px;border-top:4px solid transparent;border-bottom:4px solid transparent;border-left:4px solid #666}.mce-menu-item.mce-selected .mce-caret,.mce-menu-item:focus .mce-caret{border-left-color:#FFF}.mce-menu-align .mce-menu-shortcut{*margin-top:-2px}.mce-menu-align .mce-menu-shortcut,.mce-menu-align .mce-caret{position:absolute;right:0}.mce-menu-item-sep,.mce-menu-item-sep:hover{padding:0;height:1px;margin:9px 1px;overflow:hidden;background:#e5e5e5;border-bottom:1px solid white;cursor:default;filter:none}.mce-menu-item.mce-active i{visibility:visible}.mce-menu-item.mce-active{background-color:#c8def4;outline:1px solid #c5c5c5}.mce-menu-item-checkbox.mce-active{background-color:#FFF;outline:0}.mce-menu{filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);background:transparent;z-index:1000;padding:5px 0 5px 0;margin:2px 0 0;min-width:160px;background:#FFF;border:1px solid #CCC;border:1px solid rgba(0,0,0,0.2);z-index:1002;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2)}.mce-menu i{display:none}.mce-menu-has-icons i{display:inline-block;*display:inline;*zoom:1}.mce-menu-sub{margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px}i.mce-radio{padding:1px;margin:0 3px 0 0;background-color:#fafafa;border:1px solid #cacece;-webkit-border-radius:8px;-moz-border-radius:8px;border-radius:8px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fdfdfd,#ddd);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fdfdfd),to(#ddd));background-image:-webkit-linear-gradient(top,#fdfdfd,#ddd);background-image:-o-linear-gradient(top,#fdfdfd,#ddd);background-image:linear-gradient(to bottom,#fdfdfd,#ddd);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffdfdfd',endColorstr='#ffdddddd',GradientType=0);zoom:1}i.mce-radio:after{font-family:Arial;font-size:12px;color:#000;content:'\25cf'}.mce-container-body .mce-resizehandle{position:absolute;right:0;bottom:0;width:16px;height:16px;visibility:visible;cursor:s-resize;margin:0}.mce-resizehandle-both{cursor:se-resize}i.mce-i-resize{color:#000}.mce-spacer{visibility:hidden}.mce-splitbtn .mce-open{border-left:1px solid transparent;border-right:1px solid transparent}.mce-splitbtn:hover .mce-open{border-left-color:#c5c5c5;border-right-color:#c5c5c5}.mce-splitbtn button{padding-right:4px}.mce-splitbtn .mce-open{padding-left:4px}.mce-splitbtn .mce-open.mce-active{-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.mce-stack-layout-item{display:block}.mce-tabs{display:block;border-bottom:1px solid #ccc}.mce-tab{display:inline-block;*display:inline;*zoom:1;border:1px solid #ccc;border-width:1px 1px 0 0;background:#e3e3e3;padding:8px;text-shadow:0 1px 1px rgba(255,255,255,0.75);height:13px;cursor:pointer}.mce-tab:hover{background:#fdfdfd}.mce-tab.mce-active{background:#fdfdfd;border-bottom-color:transparent;margin-bottom:-1px;height:14px}.mce-textbox{background:#FFF;border:1px solid #c5c5c5;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);display:inline-block;-webkit-transition:border linear .2s,box-shadow linear .2s;transition:border linear .2s,box-shadow linear .2s;height:28px;resize:none;padding:0 4px 0 4px;white-space:normal;color:#000}.mce-textbox:focus{border-color:rgba(82,168,236,0.8);-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.mce-placeholder .mce-textbox{color:#aaa}.mce-textbox.mce-multiline{padding:4px}.mce-throbber{position:absolute;top:0;left:0;width:100%;height:100%;opacity:.6;filter:alpha(opacity=60);zoom:1;background:#fff url('img/loader.gif') no-repeat center center}@font-face{font-family:'tinymce';src:url('fonts/icomoon.eot');src:url('fonts/icomoon.eot?#iefix') format('embedded-opentype'),url('fonts/icomoon.svg#icomoon') format('svg'),url('fonts/icomoon.woff') format('woff'),url('fonts/icomoon.ttf') format('truetype');font-weight:normal;font-style:normal}.mce-ico{font-family:'tinymce',Arial;font-style:normal;font-weight:normal;font-size:16px;line-height:16px;vertical-align:text-top;-webkit-font-smoothing:antialiased;display:inline-block;background:transparent center center;width:16px;height:16px;color:#333}.mce-i-save:before{content:"\e000"}.mce-i-newdocument:before{content:"\e001"}.mce-i-fullpage:before{content:"\e002"}.mce-i-alignleft:before{content:"\e003"}.mce-i-aligncenter:before{content:"\e004"}.mce-i-alignright:before{content:"\e005"}.mce-i-alignjustify:before{content:"\e006"}.mce-i-cut:before{content:"\e007"}.mce-i-paste:before{content:"\e008"}.mce-i-searchreplace:before{content:"\e009"}.mce-i-bullist:before{content:"\e00a"}.mce-i-numlist:before{content:"\e00b"}.mce-i-indent:before{content:"\e00c"}.mce-i-outdent:before{content:"\e00d"}.mce-i-blockquote:before{content:"\e00e"}.mce-i-undo:before{content:"\e00f"}.mce-i-redo:before{content:"\e010"}.mce-i-link:before{content:"\e011"}.mce-i-unlink:before{content:"\e012"}.mce-i-anchor:before{content:"\e013"}.mce-i-image:before{content:"\e014"}.mce-i-media:before{content:"\e015"}.mce-i-help:before{content:"\e016"}.mce-i-code:before{content:"\e017"}.mce-i-inserttime:before{content:"\e018"}.mce-i-preview:before{content:"\e019"}.mce-i-forecolor:before{content:"\e01a"}.mce-i-backcolor:before{content:"\e01a"}.mce-i-table:before{content:"\e01b"}.mce-i-hr:before{content:"\e01c"}.mce-i-removeformat:before{content:"\e01d"}.mce-i-subscript:before{content:"\e01e"}.mce-i-superscript:before{content:"\e01f"}.mce-i-charmap:before{content:"\e020"}.mce-i-emoticons:before{content:"\e021"}.mce-i-print:before{content:"\e022"}.mce-i-fullscreen:before{content:"\e023"}.mce-i-spellchecker:before{content:"\e024"}.mce-i-nonbreaking:before{content:"\e025"}.mce-i-template:before{content:"\e026"}.mce-i-pagebreak:before{content:"\e027"}.mce-i-restoredraft:before{content:"\e028"}.mce-i-untitled:before{content:"\e029"}.mce-i-bold:before{content:"\e02a"}.mce-i-italic:before{content:"\e02b"}.mce-i-underline:before{content:"\e02c"}.mce-i-strikethrough:before{content:"\e02d"}.mce-i-visualchars:before{content:"\e02e"}.mce-i-ltr:before{content:"\e02f"}.mce-i-rtl:before{content:"\e030"}.mce-i-copy:before{content:"\e031"}.mce-i-resize:before{content:"\e032"}.mce-i-browse:before{content:"\e034"}.mce-i-checkbox:before,.mce-i-selected:before{content:"\e033"}.mce-i-selected{visibility:hidden}i.mce-i-backcolor{text-shadow:none;background:#BBB} \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/skin.ie7.min.css b/lib/tinymce/jscripts/tinymce4/skins/lightgray/skin.ie7.min.css new file mode 100644 index 00000000..8a845d58 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/skin.ie7.min.css @@ -0,0 +1 @@ +.mce-container,.mce-container *,.mce-widget,.mce-widget *{margin:0;padding:0;border:0;outline:0;vertical-align:top;background:transparent;text-decoration:none;color:#000;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;text-shadow:none;float:none;position:static;width:auto;height:auto;white-space:nowrap;cursor:inherit;-webkit-tap-highlight-color:transparent;line-height:normal}.mce-container *[unselectable]{-moz-user-select:none;-webkit-user-select:none;-o-user-select:none;user-select:none}.mce-container ::-webkit-scrollbar{width:8px;height:8px;-webkit-border-radius:4px}.mce-container ::-webkit-scrollbar-track,.mce-container ::-webkit-scrollbar-track-piece{background-color:transparent}.mce-container ::-webkit-scrollbar-thumb{background-color:rgba(53,57,71,0.3);width:6px;height:6px;-webkit-border-radius:4px}.mce-fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.mce-fade.mce-in{opacity:1}.mce-tinymce{visibility:visible!important;position:relative}.mce-fullscreen{border:0;padding:0;margin:0;overflow:hidden;background:#FFF;height:100%;z-index:100}div.mce-fullscreen{position:fixed;top:0;left:0;width:100%;height:auto}.mce-tinymce{display:block;border-radius:2px}.mce-wordcount{float:right;padding:8px}.mce-edit-area{background:#FFF;filter:none}.mce-statusbar{position:relative}.mce-statusbar .mce-container-body{position:relative}.mce-fullscreen .mce-resizehandle{display:none}.mce-charmap{border-collapse:collapse}.mce-charmap td{cursor:default;border:1px solid #c5c5c5;width:20px;height:20px;line-height:20px;text-align:center;vertical-align:center;padding:2px}.mce-charmap td:hover{background:#d9d9d9}.mce-grid{border-spacing:2px;border-collapse:separate}.mce-grid a{display:block;border:1px solid transparent}.mce-grid a:hover{border-color:#c5c5c5}.mce-grid-border{margin:0 4px 0 4px}.mce-grid-border a{border-color:#e8e8e8;width:13px;height:13px}.mce-grid-border a:hover,.mce-grid-border a.mce-active{border-color:#c4daff;background:#deeafa}.mce-text-center{text-align:center}div.mce-tinymce-inline{width:100%;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.mce-container,.mce-container-body{display:block}.mce-autoscroll{overflow:hidden}.mce-scrollbar{position:absolute;width:7px;height:100%;top:2px;right:2px;opacity:.4;filter:alpha(opacity=40);zoom:1}.mce-scrollbar-h{top:auto;right:auto;left:2px;bottom:2px;width:100%;height:7px}.mce-scrollbar-thumb{position:absolute;background-color:#000;border:1px solid #888;border-color:rgba(85,85,85,0.6);width:5px;height:100%;-webkit-border-radius:7px;-moz-border-radius:7px;border-radius:7px}.mce-scrollbar-h .mce-scrollbar-thumb{width:100%;height:5px}.mce-scrollbar:hover,.mce-scrollbar.mce-active{background-color:#AAA;opacity:.6;filter:alpha(opacity=60);zoom:1;-webkit-border-radius:7px;-moz-border-radius:7px;border-radius:7px}.mce-scroll{position:relative}.mce-panel{border:0 solid #9e9e9e;background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fdfdfd,#ddd);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fdfdfd),to(#ddd));background-image:-webkit-linear-gradient(top,#fdfdfd,#ddd);background-image:-o-linear-gradient(top,#fdfdfd,#ddd);background-image:linear-gradient(to bottom,#fdfdfd,#ddd);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffdfdfd',endColorstr='#ffdddddd',GradientType=0);zoom:1}.mce-floatpanel{position:absolute;-webkit-box-shadow:#ccc 5px 5px 5px;-moz-box-shadow:#ccc 5px 5px 5px;box-shadow:#ccc 5px 5px 5px}.mce-floatpanel .mce-arrow,.mce-floatpanel .mce-arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.mce-floatpanel .mce-arrow{border-width:11px}.mce-floatpanel .mce-arrow:after{border-width:10px;content:""}.mce-floatpanel.mce-popover{position:absolute;top:0;left:0;background:#fff;-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2)}.mce-floatpanel.mce-popover.mce-bottom{margin-top:10px}.mce-floatpanel.mce-popover.mce-bottom>.mce-arrow{left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);top:-11px}.mce-floatpanel.mce-popover.mce-bottom>.mce-arrow:after{top:1px;margin-left:-10px;border-top-width:0;border-bottom-color:#fff}.mce-floatpanel.mce-popover.mce-bottom.mce-start{margin-left:-22px}.mce-floatpanel.mce-popover.mce-bottom.mce-start>.mce-arrow{left:20px}.mce-floatpanel.mce-popover.mce-bottom.mce-end{margin-left:22px}.mce-floatpanel.mce-popover.mce-bottom.mce-end>.mce-arrow{right:10px;left:auto}.mce-fullscreen{border:0;padding:0;margin:0;overflow:hidden;background:#FFF;height:100%}div.mce-fullscreen{position:fixed;top:0;left:0}#mce-modal-block{opacity:0;filter:alpha(opacity=0);zoom:1;position:fixed;left:0;top:0;width:100%;height:100%;background:#000}#mce-modal-block.mce-in{opacity:.3;filter:alpha(opacity=30);zoom:1}.mce-window-move{cursor:move}.mce-window{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 3px 7px rgba(0,0,0,0.3);-moz-box-shadow:0 3px 7px rgba(0,0,0,0.3);box-shadow:0 3px 7px rgba(0,0,0,0.3);filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);background:transparent;background:#FFF;position:fixed;top:0;left:0;opacity:0;-webkit-transition:opacity 150ms ease-in;transition:opacity 150ms ease-in}.mce-window.mce-in{opacity:1}.mce-window-head{padding:9px 15px;border-bottom:1px solid #EEE;position:relative}.mce-window-head .mce-close{position:absolute;right:15px;top:9px;font-size:20px;font-weight:bold;line-height:20px;color:#CCC;text-shadow:0 1px 0 white;cursor:pointer;height:20px;overflow:hidden}.mce-close:hover{color:#AAA}.mce-window-head .mce-title{display:inline-block;*display:inline;*zoom:1;line-height:20px;font-size:20px;font-weight:bold;text-rendering:optimizelegibility;padding-right:10px}.mce-window .mce-container-body{display:block}.mce-foot{display:block;background-color:whiteSmoke;border-top:1px solid #DDD;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;-webkit-box-shadow:inset 0 1px 0 #fff;-moz-box-shadow:inset 0 1px 0 #fff;box-shadow:inset 0 1px 0 #fff}.mce-window-head .mce-dragh{position:absolute;top:0;left:0;cursor:move;width:90%;height:100%}.mce-window iframe{width:100%;height:100%}.mce-window.mce-fullscreen,.mce-window.mce-fullscreen .mce-foot{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.mce-abs-layout{position:relative}body .mce-abs-layout-item,.mce-abs-end{position:absolute}.mce-abs-end{width:1px;height:1px}.mce-container-body.mce-abs-layout{overflow:hidden}.mce-tooltip{position:absolute;padding:5px;opacity:.8;filter:alpha(opacity=80);zoom:1}.mce-tooltip-inner{font-size:11px;background-color:#000;color:#fff;max-width:200px;padding:5px 8px 4px 8px;text-align:center;white-space:normal}.mce-tooltip-inner{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.mce-tooltip-inner{-webkit-box-shadow:0 0 5px #000;-moz-box-shadow:0 0 5px #000;box-shadow:0 0 5px #000}.mce-tooltip-arrow{position:absolute;width:0;height:0;line-height:0;border:5px dashed #000}.mce-tooltip-arrow-n{border-bottom-color:#000}.mce-tooltip-arrow-s{border-top-color:#000}.mce-tooltip-arrow-e{border-left-color:#000}.mce-tooltip-arrow-w{border-right-color:#000}.mce-tooltip-n .mce-tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-style:solid;border-top:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-nw .mce-tooltip-arrow{top:0;left:10px;border-bottom-style:solid;border-top:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-ne .mce-tooltip-arrow{top:0;right:10px;border-bottom-style:solid;border-top:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-s .mce-tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-style:solid;border-bottom:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-sw .mce-tooltip-arrow{bottom:0;left:10px;border-top-style:solid;border-bottom:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-se .mce-tooltip-arrow{bottom:0;right:10px;border-top-style:solid;border-bottom:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-e .mce-tooltip-arrow{right:0;top:50%;margin-top:-5px;border-left-style:solid;border-right:0;border-top-color:transparent;border-bottom-color:transparent}.mce-tooltip-w .mce-tooltip-arrow{left:0;top:50%;margin-top:-5px;border-right-style:solid;border-left:none;border-top-color:transparent;border-bottom-color:transparent}.mce-btn{border:1px solid #c5c5c5;position:relative;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fff,#d9d9d9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#d9d9d9));background-image:-webkit-linear-gradient(top,#fff,#d9d9d9);background-image:-o-linear-gradient(top,#fff,#d9d9d9);background-image:linear-gradient(to bottom,#fff,#d9d9d9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffd9d9d9',GradientType=0);zoom:1;border-color:#d9d9d9 #d9d9d9 #b3b3b3;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);display:inline-block;*display:inline;*zoom:1;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.mce-btn:hover,.mce-btn:focus{text-decoration:none;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#e3e3e3;background-image:-moz-linear-gradient(top,#f2f2f2,#ccc);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f2f2f2),to(#ccc));background-image:-webkit-linear-gradient(top,#f2f2f2,#ccc);background-image:-o-linear-gradient(top,#f2f2f2,#ccc);background-image:linear-gradient(to bottom,#f2f2f2,#ccc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2',endColorstr='#ffcccccc',GradientType=0);zoom:1;border-color:#ccc #ccc #a6a6a6;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25)}.mce-btn.mce-disabled,.mce-btn.mce-disabled:hover{cursor:default;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;opacity:.65;filter:alpha(opacity=65);zoom:1}.mce-btn.mce-active,.mce-btn.mce-active:hover{color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#d6d6d6;background-image:-moz-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:-webkit-gradient(linear,0 0,0 100%,from(#e6e6e6),to(#bfbfbf));background-image:-webkit-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:-o-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:linear-gradient(to bottom,#e6e6e6,#bfbfbf);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe6e6e6',endColorstr='#ffbfbfbf',GradientType=0);zoom:1;border-color:#bfbfbf #bfbfbf #999;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.mce-btn button{padding:4px 10px;font-size:14px;line-height:20px;*line-height:16px;cursor:pointer;color:#333;overflow:visible;-webkit-appearance:none}.mce-btn button::-moz-focus-inner{border:0;padding:0}.mce-btn i{text-shadow:1px 1px #fff}.mce-primary{color:#fff;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);zoom:1;border-color:#04c #04c #002b80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25)}.mce-primary:hover,.mce-primary:focus{color:#fff;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#005fb3;background-image:-moz-linear-gradient(top,#0077b3,#003cb3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#0077b3),to(#003cb3));background-image:-webkit-linear-gradient(top,#0077b3,#003cb3);background-image:-o-linear-gradient(top,#0077b3,#003cb3);background-image:linear-gradient(to bottom,#0077b3,#003cb3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0077b3',endColorstr='#ff003cb3',GradientType=0);zoom:1;border-color:#003cb3 #003cb3 #026;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25)}.mce-primary button{color:#fff}.mce-btn-large button{padding:9px 14px;font-size:16px;line-height:normal;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.mce-btn-large i{margin-top:2px}.mce-btn-small button{padding:3px 5px;font-size:12px;line-height:15px}.mce-btn-small i{margin-top:0}.mce-btn .mce-caret{margin-top:8px;*margin-top:6px;margin-left:0}.mce-btn-small .mce-caret{margin-top:6px;*margin-top:4px;margin-left:0}.mce-caret{display:inline-block;*display:inline;*zoom:1;width:0;height:0;vertical-align:top;border-top:4px solid #444;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.mce-disabled .mce-caret{border-top-color:#999}.mce-caret.mce-up{border-bottom:4px solid #444;border-top:0}.mce-btn-group .mce-btn{border-width:1px 0 1px 0;margin:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.mce-btn-group .mce-btn:hover,.mce-btn-group .mce-btn:focus{color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#e3e3e3;background-image:-moz-linear-gradient(top,#f2f2f2,#ccc);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f2f2f2),to(#ccc));background-image:-webkit-linear-gradient(top,#f2f2f2,#ccc);background-image:-o-linear-gradient(top,#f2f2f2,#ccc);background-image:linear-gradient(to bottom,#f2f2f2,#ccc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2',endColorstr='#ffcccccc',GradientType=0);zoom:1;border-color:#ccc #ccc #a6a6a6;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25)}.mce-btn-group .mce-btn.mce-disabled,.mce-btn-group .mce-btn.mce-disabled:hover{-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fff,#d9d9d9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#d9d9d9));background-image:-webkit-linear-gradient(top,#fff,#d9d9d9);background-image:-o-linear-gradient(top,#fff,#d9d9d9);background-image:linear-gradient(to bottom,#fff,#d9d9d9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffd9d9d9',GradientType=0);border-color:#d9d9d9 #d9d9d9 #b3b3b3;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);opacity:1;filter:alpha(opacity=100);zoom:1}.mce-btn-group .mce-btn.mce-active,.mce-btn-group .mce-btn.mce-active:hover,.mce-btn-group .mce-btn:active{color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#d6d6d6;background-image:-moz-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:-webkit-gradient(linear,0 0,0 100%,from(#e6e6e6),to(#bfbfbf));background-image:-webkit-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:-o-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:linear-gradient(to bottom,#e6e6e6,#bfbfbf);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe6e6e6',endColorstr='#ffbfbfbf',GradientType=0);zoom:1;border-color:#bfbfbf #bfbfbf #999;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.mce-btn-group .mce-btn.mce-disabled button{opacity:.65;filter:alpha(opacity=65);zoom:1}.mce-btn-group .mce-first{border-left:1px solid #c5c5c5;-webkit-border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;border-radius:3px 0 0 3px}.mce-btn-group .mce-last{border-right:1px solid #c5c5c5;-webkit-border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;border-radius:0 3px 3px 0}.mce-btn-group .mce-first.mce-last{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.mce-btn-group .mce-btn.mce-flow-layout-item{margin:0}.mce-checkbox{cursor:pointer}i.mce-i-checkbox{margin:0 3px 0 0;border:1px solid #c5c5c5;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fdfdfd,#ddd);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fdfdfd),to(#ddd));background-image:-webkit-linear-gradient(top,#fdfdfd,#ddd);background-image:-o-linear-gradient(top,#fdfdfd,#ddd);background-image:linear-gradient(to bottom,#fdfdfd,#ddd);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffdfdfd',endColorstr='#ffdddddd',GradientType=0);zoom:1;font-size:0;line-height:0}.mce-checked i.mce-i-checkbox{color:#000;font-size:16px;line-height:16px}.mce-checkbox:focus i.mce-i-checkbox{border:1px solid red;border:1px solid rgba(82,168,236,0.8);-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.mce-colorbutton .mce-ico{position:relative}.mce-colorpicker{background:#FFF}.mce-colorbutton-grid{margin:4px}.mce-grid td div{border:1px solid #808080;width:12px;height:12px;margin:2px;cursor:pointer}.mce-grid td div:hover{border-color:black}.mce-grid td div:focus{border-color:red;outline:1px solid rgba(82,168,236,0.8);border-color:rgba(82,168,236,0.8)}.mce-colorbutton{position:relative}.mce-colorbutton .mce-preview{display:block;position:absolute;left:50%;top:50%;margin-left:-8px;margin-top:7px;background:gray;width:16px;height:2px;overflow:hidden}.mce-combobox{display:inline-block;*display:inline;*zoom:1;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;width:100px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.mce-combobox input{border-color:1px solid #c5c5c5;border-right-color:rgba(0,0,0,0.15);height:28px}.mce-combobox.mce-has-open input{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.mce-combobox .mce-btn{border-left:0;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.mce-combobox button{padding-right:8px;padding-left:8px}.mce-combobox *:focus{border-color:red;border-color:rgba(82,168,236,0.8);-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.mce-path{display:inline-block;*display:inline;*zoom:1;padding:8px;white-space:normal}.mce-path .mce-txt{display:inline-block;padding-right:3px}.mce-path .mce-path-body{display:inline-block}.mce-path-item{display:inline-block;*display:inline;*zoom:1;cursor:pointer;color:#000}.mce-path-item:hover{text-decoration:underline}.mce-path-item:focus{background:gray;color:white}.mce-path .mce-divider{display:inline}.mce-fieldset{border:0 solid #9e9e9e;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.mce-fieldset>.mce-container-body{margin-top:-15px}.mce-fieldset-title{margin-left:5px;padding:0 5px 0 5px}.mce-fit-layout{display:inline-block;*display:inline;*zoom:1}.mce-fit-layout-item{position:absolute}.mce-flow-layout-item{display:inline-block;*display:inline;*zoom:1}.mce-flow-layout-item{margin:2px 0 2px 2px}.mce-flow-layout-item.mce-last{margin-right:2px}.mce-flow-layout{white-space:normal}.mce-iframe{border:0 solid #c5c5c5;width:100%;height:100%}.mce-label{display:inline-block;*display:inline;*zoom:1;text-shadow:0 1px 1px rgba(255,255,255,0.75);border:0 solid #c5c5c5;overflow:hidden}.mce-label.mce-autoscroll{overflow:auto}.mce-label-disabled .mce-text{color:#999}.mce-label.mce-multiline{white-space:pre-wrap}.mce-menubar .mce-menubtn{border-color:transparent;background:transparent;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;filter:none}.mce-menubar{border:1px solid #ddd}.mce-menubar .mce-menubtn button{color:#000}.mce-menubar .mce-menubtn:hover,.mce-menubar .mce-menubtn.mce-active,.mce-menubtn:focus{border-color:transparent;background:#ddd;filter:none}.mce-menubtn.mce-disabled span{color:#999}.mce-listbox button{text-align:left;padding-right:20px;position:relative}.mce-listbox .mce-caret{position:absolute;margin-top:-2px;right:8px;top:50%}.mce-listbox span{width:100%;display:block;overflow:hidden}.mce-menu-item{display:block;padding:6px 20px;clear:both;font-weight:normal;line-height:20px;color:#333;white-space:nowrap;cursor:pointer;line-height:normal}.mce-menu-item.mce-disabled .mce-text{color:#999}.mce-menu-item:hover,.mce-menu-item.mce-selected,.mce-menu-item:focus{text-decoration:none;color:#fff;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0);zoom:1}.mce-menu-item:hover .mce-text,.mce-menu-item.mce-selected .mce-text{color:#fff}.mce-menu-item:hover .mce-ico,.mce-menu-item.mce-selected .mce-ico,.mce-menu-item:focus .mce-ico{color:white}.mce-menu-shortcut{display:inline-block;color:#999}.mce-menu-shortcut{display:inline-block;*display:inline;*zoom:1;padding:0 20px 0 20px}.mce-menu-item .mce-caret{margin-top:6px;*margin-top:3px;margin-right:6px;border-top:4px solid transparent;border-bottom:4px solid transparent;border-left:4px solid #666}.mce-menu-item.mce-selected .mce-caret,.mce-menu-item:focus .mce-caret{border-left-color:#FFF}.mce-menu-align .mce-menu-shortcut{*margin-top:-2px}.mce-menu-align .mce-menu-shortcut,.mce-menu-align .mce-caret{position:absolute;right:0}.mce-menu-item-sep,.mce-menu-item-sep:hover{padding:0;height:1px;margin:9px 1px;overflow:hidden;background:#e5e5e5;border-bottom:1px solid white;cursor:default;filter:none}.mce-menu-item.mce-active i{visibility:visible}.mce-menu-item.mce-active{background-color:#c8def4;outline:1px solid #c5c5c5}.mce-menu-item-checkbox.mce-active{background-color:#FFF;outline:0}.mce-menu{filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);background:transparent;z-index:1000;padding:5px 0 5px 0;margin:2px 0 0;min-width:160px;background:#FFF;border:1px solid #CCC;border:1px solid rgba(0,0,0,0.2);z-index:1002;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2)}.mce-menu i{display:none}.mce-menu-has-icons i{display:inline-block;*display:inline;*zoom:1}.mce-menu-sub{margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px}i.mce-radio{padding:1px;margin:0 3px 0 0;background-color:#fafafa;border:1px solid #cacece;-webkit-border-radius:8px;-moz-border-radius:8px;border-radius:8px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fdfdfd,#ddd);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fdfdfd),to(#ddd));background-image:-webkit-linear-gradient(top,#fdfdfd,#ddd);background-image:-o-linear-gradient(top,#fdfdfd,#ddd);background-image:linear-gradient(to bottom,#fdfdfd,#ddd);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffdfdfd',endColorstr='#ffdddddd',GradientType=0);zoom:1}i.mce-radio:after{font-family:Arial;font-size:12px;color:#000;content:'\25cf'}.mce-container-body .mce-resizehandle{position:absolute;right:0;bottom:0;width:16px;height:16px;visibility:visible;cursor:s-resize;margin:0}.mce-resizehandle-both{cursor:se-resize}i.mce-i-resize{color:#000}.mce-spacer{visibility:hidden}.mce-splitbtn .mce-open{border-left:1px solid transparent;border-right:1px solid transparent}.mce-splitbtn:hover .mce-open{border-left-color:#c5c5c5;border-right-color:#c5c5c5}.mce-splitbtn button{padding-right:4px}.mce-splitbtn .mce-open{padding-left:4px}.mce-splitbtn .mce-open.mce-active{-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.mce-stack-layout-item{display:block}.mce-tabs{display:block;border-bottom:1px solid #ccc}.mce-tab{display:inline-block;*display:inline;*zoom:1;border:1px solid #ccc;border-width:1px 1px 0 0;background:#e3e3e3;padding:8px;text-shadow:0 1px 1px rgba(255,255,255,0.75);height:13px;cursor:pointer}.mce-tab:hover{background:#fdfdfd}.mce-tab.mce-active{background:#fdfdfd;border-bottom-color:transparent;margin-bottom:-1px;height:14px}.mce-textbox{background:#FFF;border:1px solid #c5c5c5;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);display:inline-block;-webkit-transition:border linear .2s,box-shadow linear .2s;transition:border linear .2s,box-shadow linear .2s;height:28px;resize:none;padding:0 4px 0 4px;white-space:normal;color:#000}.mce-textbox:focus{border-color:rgba(82,168,236,0.8);-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.mce-placeholder .mce-textbox{color:#aaa}.mce-textbox.mce-multiline{padding:4px}.mce-throbber{position:absolute;top:0;left:0;width:100%;height:100%;opacity:.6;filter:alpha(opacity=60);zoom:1;background:#fff url('img/loader.gif') no-repeat center center}@font-face{font-family:'icomoon';src:url('fonts/icomoon.eot');src:url('fonts/icomoon.eot?#iefix') format('embedded-opentype'),url('fonts/icomoon.svg#icomoon') format('svg'),url('fonts/icomoon.woff') format('woff'),url('fonts/icomoon.ttf') format('truetype');font-weight:normal;font-style:normal}.mce-ico{font-family:'icomoon';font-style:normal;font-weight:normal;font-size:16px;line-height:16px;vertical-align:text-top;-webkit-font-smoothing:antialiased;display:inline-block;background:transparent center center;width:16px;height:16px;color:#333;-ie7-icon:' '}.mce-ico,i.mce-i-checkbox{zoom:expression(this.runtimeStyle['zoom'] = '1',this.innerHTML = this.currentStyle['-ie7-icon'].substr(1,1)+' ')}.mce-i-save{-ie7-icon:"\e000"}.mce-i-newdocument{-ie7-icon:"\e001"}.mce-i-fullpage{-ie7-icon:"\e002"}.mce-i-alignleft{-ie7-icon:"\e003"}.mce-i-aligncenter{-ie7-icon:"\e004"}.mce-i-alignright{-ie7-icon:"\e005"}.mce-i-alignjustify{-ie7-icon:"\e006"}.mce-i-cut{-ie7-icon:"\e007"}.mce-i-paste{-ie7-icon:"\e008"}.mce-i-searchreplace{-ie7-icon:"\e009"}.mce-i-bullist{-ie7-icon:"\e00a"}.mce-i-numlist{-ie7-icon:"\e00b"}.mce-i-indent{-ie7-icon:"\e00c"}.mce-i-outdent{-ie7-icon:"\e00d"}.mce-i-blockquote{-ie7-icon:"\e00e"}.mce-i-undo{-ie7-icon:"\e00f"}.mce-i-redo{-ie7-icon:"\e010"}.mce-i-link{-ie7-icon:"\e011"}.mce-i-unlink{-ie7-icon:"\e012"}.mce-i-anchor{-ie7-icon:"\e013"}.mce-i-image{-ie7-icon:"\e014"}.mce-i-media{-ie7-icon:"\e015"}.mce-i-help{-ie7-icon:"\e016"}.mce-i-code{-ie7-icon:"\e017"}.mce-i-inserttime{-ie7-icon:"\e018"}.mce-i-preview{-ie7-icon:"\e019"}.mce-i-forecolor{-ie7-icon:"\e01a"}.mce-i-backcolor{-ie7-icon:"\e01a"}.mce-i-table{-ie7-icon:"\e01b"}.mce-i-hr{-ie7-icon:"\e01c"}.mce-i-removeformat{-ie7-icon:"\e01d"}.mce-i-subscript{-ie7-icon:"\e01e"}.mce-i-superscript{-ie7-icon:"\e01f"}.mce-i-charmap{-ie7-icon:"\e020"}.mce-i-emoticons{-ie7-icon:"\e021"}.mce-i-print{-ie7-icon:"\e022"}.mce-i-fullscreen{-ie7-icon:"\e023"}.mce-i-spellchecker{-ie7-icon:"\e024"}.mce-i-nonbreaking{-ie7-icon:"\e025"}.mce-i-template{-ie7-icon:"\e026"}.mce-i-pagebreak{-ie7-icon:"\e027"}.mce-i-restoredraft{-ie7-icon:"\e028"}.mce-i-untitled{-ie7-icon:"\e029"}.mce-i-bold{-ie7-icon:"\e02a"}.mce-i-italic{-ie7-icon:"\e02b"}.mce-i-underline{-ie7-icon:"\e02c"}.mce-i-strikethrough{-ie7-icon:"\e02d"}.mce-i-visualchars{-ie7-icon:"\e02e"}.mce-i-ltr{-ie7-icon:"\e02f"}.mce-i-rtl{-ie7-icon:"\e030"}.mce-i-copy{-ie7-icon:"\e031"}.mce-i-resize{-ie7-icon:"\e032"}.mce-i-browse{-ie7-icon:"\e034"}.mce-i-checkbox,.mce-i-selected{-ie7-icon:"\e033"}.mce-i-selected{visibility:hidden}.mce-i-backcolor{background:#BBB} \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/skin.less b/lib/tinymce/jscripts/tinymce4/skins/lightgray/skin.less new file mode 100644 index 00000000..fc54c090 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/skin.less @@ -0,0 +1,37 @@ +@import "Reset.less"; +@import "Variables.less"; +@import "Mixins.less"; +@import "Animations.less"; +@import "TinyMCE.less"; +@import "Container.less"; +@import "Scrollable.less"; +@import "Panel.less"; +@import "FloatPanel.less"; +@import "Window.less"; +@import "AbsoluteLayout.less"; +@import "ToolTip.less"; +@import "Button.less"; +@import "ButtonGroup.less"; +@import "Checkbox.less"; +@import "ColorButton.less"; +@import "ComboBox.less"; +@import "Path.less"; +@import "FieldSet.less"; +@import "FitLayout.less"; +@import "FlowLayout.less"; +@import "Iframe.less"; +@import "Label.less"; +@import "MenuBar.less"; +@import "MenuButton.less"; +@import "ListBox.less"; +@import "MenuItem.less"; +@import "Menu.less"; +@import "Radio.less"; +@import "ResizeHandle.less"; +@import "Spacer.less"; +@import "SplitButton.less"; +@import "StackLayout.less"; +@import "TabPanel.less"; +@import "TextBox.less"; +@import "Throbber.less"; +@import "Icons.less"; diff --git a/lib/tinymce/jscripts/tinymce4/skins/lightgray/skin.min.css b/lib/tinymce/jscripts/tinymce4/skins/lightgray/skin.min.css new file mode 100644 index 00000000..d5c50b76 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/skins/lightgray/skin.min.css @@ -0,0 +1 @@ +.mce-container,.mce-container *,.mce-widget,.mce-widget *{margin:0;padding:0;border:0;outline:0;vertical-align:top;background:transparent;text-decoration:none;color:#000;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;text-shadow:none;float:none;position:static;width:auto;height:auto;white-space:nowrap;cursor:inherit;-webkit-tap-highlight-color:transparent;line-height:normal}.mce-container *[unselectable]{-moz-user-select:none;-webkit-user-select:none;-o-user-select:none;user-select:none}.mce-container ::-webkit-scrollbar{width:8px;height:8px;-webkit-border-radius:4px}.mce-container ::-webkit-scrollbar-track,.mce-container ::-webkit-scrollbar-track-piece{background-color:transparent}.mce-container ::-webkit-scrollbar-thumb{background-color:rgba(53,57,71,0.3);width:6px;height:6px;-webkit-border-radius:4px}.mce-fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.mce-fade.mce-in{opacity:1}.mce-tinymce{visibility:visible!important;position:relative}.mce-fullscreen{border:0;padding:0;margin:0;overflow:hidden;background:#FFF;height:100%;z-index:100}div.mce-fullscreen{position:fixed;top:0;left:0;width:100%;height:auto}.mce-tinymce{display:block;border-radius:2px}.mce-wordcount{float:right;padding:8px}.mce-edit-area{background:#FFF;filter:none}.mce-statusbar{position:relative}.mce-statusbar .mce-container-body{position:relative}.mce-fullscreen .mce-resizehandle{display:none}.mce-charmap{border-collapse:collapse}.mce-charmap td{cursor:default;border:1px solid #c5c5c5;width:20px;height:20px;line-height:20px;text-align:center;vertical-align:center;padding:2px}.mce-charmap td:hover{background:#d9d9d9}.mce-grid{border-spacing:2px;border-collapse:separate}.mce-grid a{display:block;border:1px solid transparent}.mce-grid a:hover{border-color:#c5c5c5}.mce-grid-border{margin:0 4px 0 4px}.mce-grid-border a{border-color:#e8e8e8;width:13px;height:13px}.mce-grid-border a:hover,.mce-grid-border a.mce-active{border-color:#c4daff;background:#deeafa}.mce-text-center{text-align:center}div.mce-tinymce-inline{width:100%;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.mce-container,.mce-container-body{display:block}.mce-autoscroll{overflow:hidden}.mce-scrollbar{position:absolute;width:7px;height:100%;top:2px;right:2px;opacity:.4;filter:alpha(opacity=40);zoom:1}.mce-scrollbar-h{top:auto;right:auto;left:2px;bottom:2px;width:100%;height:7px}.mce-scrollbar-thumb{position:absolute;background-color:#000;border:1px solid #888;border-color:rgba(85,85,85,0.6);width:5px;height:100%;-webkit-border-radius:7px;-moz-border-radius:7px;border-radius:7px}.mce-scrollbar-h .mce-scrollbar-thumb{width:100%;height:5px}.mce-scrollbar:hover,.mce-scrollbar.mce-active{background-color:#AAA;opacity:.6;filter:alpha(opacity=60);zoom:1;-webkit-border-radius:7px;-moz-border-radius:7px;border-radius:7px}.mce-scroll{position:relative}.mce-panel{border:0 solid #9e9e9e;background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fdfdfd,#ddd);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fdfdfd),to(#ddd));background-image:-webkit-linear-gradient(top,#fdfdfd,#ddd);background-image:-o-linear-gradient(top,#fdfdfd,#ddd);background-image:linear-gradient(to bottom,#fdfdfd,#ddd);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffdfdfd',endColorstr='#ffdddddd',GradientType=0);zoom:1}.mce-floatpanel{position:absolute;-webkit-box-shadow:#ccc 5px 5px 5px;-moz-box-shadow:#ccc 5px 5px 5px;box-shadow:#ccc 5px 5px 5px}.mce-floatpanel .mce-arrow,.mce-floatpanel .mce-arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.mce-floatpanel .mce-arrow{border-width:11px}.mce-floatpanel .mce-arrow:after{border-width:10px;content:""}.mce-floatpanel.mce-popover{position:absolute;top:0;left:0;background:#fff;-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2)}.mce-floatpanel.mce-popover.mce-bottom{margin-top:10px}.mce-floatpanel.mce-popover.mce-bottom>.mce-arrow{left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);top:-11px}.mce-floatpanel.mce-popover.mce-bottom>.mce-arrow:after{top:1px;margin-left:-10px;border-top-width:0;border-bottom-color:#fff}.mce-floatpanel.mce-popover.mce-bottom.mce-start{margin-left:-22px}.mce-floatpanel.mce-popover.mce-bottom.mce-start>.mce-arrow{left:20px}.mce-floatpanel.mce-popover.mce-bottom.mce-end{margin-left:22px}.mce-floatpanel.mce-popover.mce-bottom.mce-end>.mce-arrow{right:10px;left:auto}.mce-fullscreen{border:0;padding:0;margin:0;overflow:hidden;background:#FFF;height:100%}div.mce-fullscreen{position:fixed;top:0;left:0}#mce-modal-block{opacity:0;filter:alpha(opacity=0);zoom:1;position:fixed;left:0;top:0;width:100%;height:100%;background:#000}#mce-modal-block.mce-in{opacity:.3;filter:alpha(opacity=30);zoom:1}.mce-window-move{cursor:move}.mce-window{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 3px 7px rgba(0,0,0,0.3);-moz-box-shadow:0 3px 7px rgba(0,0,0,0.3);box-shadow:0 3px 7px rgba(0,0,0,0.3);filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);background:transparent;background:#FFF;position:fixed;top:0;left:0;opacity:0;-webkit-transition:opacity 150ms ease-in;transition:opacity 150ms ease-in}.mce-window.mce-in{opacity:1}.mce-window-head{padding:9px 15px;border-bottom:1px solid #EEE;position:relative}.mce-window-head .mce-close{position:absolute;right:15px;top:9px;font-size:20px;font-weight:bold;line-height:20px;color:#CCC;text-shadow:0 1px 0 white;cursor:pointer;height:20px;overflow:hidden}.mce-close:hover{color:#AAA}.mce-window-head .mce-title{display:inline-block;*display:inline;*zoom:1;line-height:20px;font-size:20px;font-weight:bold;text-rendering:optimizelegibility;padding-right:10px}.mce-window .mce-container-body{display:block}.mce-foot{display:block;background-color:whiteSmoke;border-top:1px solid #DDD;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;-webkit-box-shadow:inset 0 1px 0 #fff;-moz-box-shadow:inset 0 1px 0 #fff;box-shadow:inset 0 1px 0 #fff}.mce-window-head .mce-dragh{position:absolute;top:0;left:0;cursor:move;width:90%;height:100%}.mce-window iframe{width:100%;height:100%}.mce-window.mce-fullscreen,.mce-window.mce-fullscreen .mce-foot{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.mce-abs-layout{position:relative}body .mce-abs-layout-item,.mce-abs-end{position:absolute}.mce-abs-end{width:1px;height:1px}.mce-container-body.mce-abs-layout{overflow:hidden}.mce-tooltip{position:absolute;padding:5px;opacity:.8;filter:alpha(opacity=80);zoom:1}.mce-tooltip-inner{font-size:11px;background-color:#000;color:#fff;max-width:200px;padding:5px 8px 4px 8px;text-align:center;white-space:normal}.mce-tooltip-inner{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.mce-tooltip-inner{-webkit-box-shadow:0 0 5px #000;-moz-box-shadow:0 0 5px #000;box-shadow:0 0 5px #000}.mce-tooltip-arrow{position:absolute;width:0;height:0;line-height:0;border:5px dashed #000}.mce-tooltip-arrow-n{border-bottom-color:#000}.mce-tooltip-arrow-s{border-top-color:#000}.mce-tooltip-arrow-e{border-left-color:#000}.mce-tooltip-arrow-w{border-right-color:#000}.mce-tooltip-n .mce-tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-style:solid;border-top:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-nw .mce-tooltip-arrow{top:0;left:10px;border-bottom-style:solid;border-top:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-ne .mce-tooltip-arrow{top:0;right:10px;border-bottom-style:solid;border-top:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-s .mce-tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-style:solid;border-bottom:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-sw .mce-tooltip-arrow{bottom:0;left:10px;border-top-style:solid;border-bottom:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-se .mce-tooltip-arrow{bottom:0;right:10px;border-top-style:solid;border-bottom:0;border-left-color:transparent;border-right-color:transparent}.mce-tooltip-e .mce-tooltip-arrow{right:0;top:50%;margin-top:-5px;border-left-style:solid;border-right:0;border-top-color:transparent;border-bottom-color:transparent}.mce-tooltip-w .mce-tooltip-arrow{left:0;top:50%;margin-top:-5px;border-right-style:solid;border-left:none;border-top-color:transparent;border-bottom-color:transparent}.mce-btn{border:1px solid #c5c5c5;position:relative;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fff,#d9d9d9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#d9d9d9));background-image:-webkit-linear-gradient(top,#fff,#d9d9d9);background-image:-o-linear-gradient(top,#fff,#d9d9d9);background-image:linear-gradient(to bottom,#fff,#d9d9d9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffd9d9d9',GradientType=0);zoom:1;border-color:#d9d9d9 #d9d9d9 #b3b3b3;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);display:inline-block;*display:inline;*zoom:1;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.mce-btn:hover,.mce-btn:focus{text-decoration:none;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#e3e3e3;background-image:-moz-linear-gradient(top,#f2f2f2,#ccc);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f2f2f2),to(#ccc));background-image:-webkit-linear-gradient(top,#f2f2f2,#ccc);background-image:-o-linear-gradient(top,#f2f2f2,#ccc);background-image:linear-gradient(to bottom,#f2f2f2,#ccc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2',endColorstr='#ffcccccc',GradientType=0);zoom:1;border-color:#ccc #ccc #a6a6a6;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25)}.mce-btn.mce-disabled,.mce-btn.mce-disabled:hover{cursor:default;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;opacity:.65;filter:alpha(opacity=65);zoom:1}.mce-btn.mce-active,.mce-btn.mce-active:hover{color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#d6d6d6;background-image:-moz-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:-webkit-gradient(linear,0 0,0 100%,from(#e6e6e6),to(#bfbfbf));background-image:-webkit-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:-o-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:linear-gradient(to bottom,#e6e6e6,#bfbfbf);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe6e6e6',endColorstr='#ffbfbfbf',GradientType=0);zoom:1;border-color:#bfbfbf #bfbfbf #999;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.mce-btn button{padding:4px 10px;font-size:14px;line-height:20px;*line-height:16px;cursor:pointer;color:#333;overflow:visible;-webkit-appearance:none}.mce-btn button::-moz-focus-inner{border:0;padding:0}.mce-btn i{text-shadow:1px 1px #fff}.mce-primary{color:#fff;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);zoom:1;border-color:#04c #04c #002b80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25)}.mce-primary:hover,.mce-primary:focus{color:#fff;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#005fb3;background-image:-moz-linear-gradient(top,#0077b3,#003cb3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#0077b3),to(#003cb3));background-image:-webkit-linear-gradient(top,#0077b3,#003cb3);background-image:-o-linear-gradient(top,#0077b3,#003cb3);background-image:linear-gradient(to bottom,#0077b3,#003cb3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0077b3',endColorstr='#ff003cb3',GradientType=0);zoom:1;border-color:#003cb3 #003cb3 #026;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25)}.mce-primary button{color:#fff}.mce-btn-large button{padding:9px 14px;font-size:16px;line-height:normal;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.mce-btn-large i{margin-top:2px}.mce-btn-small button{padding:3px 5px;font-size:12px;line-height:15px}.mce-btn-small i{margin-top:0}.mce-btn .mce-caret{margin-top:8px;*margin-top:6px;margin-left:0}.mce-btn-small .mce-caret{margin-top:6px;*margin-top:4px;margin-left:0}.mce-caret{display:inline-block;*display:inline;*zoom:1;width:0;height:0;vertical-align:top;border-top:4px solid #444;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.mce-disabled .mce-caret{border-top-color:#999}.mce-caret.mce-up{border-bottom:4px solid #444;border-top:0}.mce-btn-group .mce-btn{border-width:1px 0 1px 0;margin:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.mce-btn-group .mce-btn:hover,.mce-btn-group .mce-btn:focus{color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#e3e3e3;background-image:-moz-linear-gradient(top,#f2f2f2,#ccc);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f2f2f2),to(#ccc));background-image:-webkit-linear-gradient(top,#f2f2f2,#ccc);background-image:-o-linear-gradient(top,#f2f2f2,#ccc);background-image:linear-gradient(to bottom,#f2f2f2,#ccc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2',endColorstr='#ffcccccc',GradientType=0);zoom:1;border-color:#ccc #ccc #a6a6a6;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25)}.mce-btn-group .mce-btn.mce-disabled,.mce-btn-group .mce-btn.mce-disabled:hover{-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fff,#d9d9d9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#d9d9d9));background-image:-webkit-linear-gradient(top,#fff,#d9d9d9);background-image:-o-linear-gradient(top,#fff,#d9d9d9);background-image:linear-gradient(to bottom,#fff,#d9d9d9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffd9d9d9',GradientType=0);border-color:#d9d9d9 #d9d9d9 #b3b3b3;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);opacity:1;filter:alpha(opacity=100);zoom:1}.mce-btn-group .mce-btn.mce-active,.mce-btn-group .mce-btn.mce-active:hover,.mce-btn-group .mce-btn:active{color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#d6d6d6;background-image:-moz-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:-webkit-gradient(linear,0 0,0 100%,from(#e6e6e6),to(#bfbfbf));background-image:-webkit-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:-o-linear-gradient(top,#e6e6e6,#bfbfbf);background-image:linear-gradient(to bottom,#e6e6e6,#bfbfbf);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe6e6e6',endColorstr='#ffbfbfbf',GradientType=0);zoom:1;border-color:#bfbfbf #bfbfbf #999;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.mce-btn-group .mce-btn.mce-disabled button{opacity:.65;filter:alpha(opacity=65);zoom:1}.mce-btn-group .mce-first{border-left:1px solid #c5c5c5;-webkit-border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;border-radius:3px 0 0 3px}.mce-btn-group .mce-last{border-right:1px solid #c5c5c5;-webkit-border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;border-radius:0 3px 3px 0}.mce-btn-group .mce-first.mce-last{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.mce-btn-group .mce-btn.mce-flow-layout-item{margin:0}.mce-checkbox{cursor:pointer}i.mce-i-checkbox{margin:0 3px 0 0;border:1px solid #c5c5c5;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fdfdfd,#ddd);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fdfdfd),to(#ddd));background-image:-webkit-linear-gradient(top,#fdfdfd,#ddd);background-image:-o-linear-gradient(top,#fdfdfd,#ddd);background-image:linear-gradient(to bottom,#fdfdfd,#ddd);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffdfdfd',endColorstr='#ffdddddd',GradientType=0);zoom:1;font-size:0;line-height:0}.mce-checked i.mce-i-checkbox{color:#000;font-size:16px;line-height:16px}.mce-checkbox:focus i.mce-i-checkbox{border:1px solid red;border:1px solid rgba(82,168,236,0.8);-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.mce-colorbutton .mce-ico{position:relative}.mce-colorpicker{background:#FFF}.mce-colorbutton-grid{margin:4px}.mce-grid td div{border:1px solid #808080;width:12px;height:12px;margin:2px;cursor:pointer}.mce-grid td div:hover{border-color:black}.mce-grid td div:focus{border-color:red;outline:1px solid rgba(82,168,236,0.8);border-color:rgba(82,168,236,0.8)}.mce-colorbutton{position:relative}.mce-colorbutton .mce-preview{display:block;position:absolute;left:50%;top:50%;margin-left:-8px;margin-top:7px;background:gray;width:16px;height:2px;overflow:hidden}.mce-combobox{display:inline-block;*display:inline;*zoom:1;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;width:100px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.mce-combobox input{border-color:1px solid #c5c5c5;border-right-color:rgba(0,0,0,0.15);height:28px}.mce-combobox.mce-has-open input{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.mce-combobox .mce-btn{border-left:0;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.mce-combobox button{padding-right:8px;padding-left:8px}.mce-combobox *:focus{border-color:red;border-color:rgba(82,168,236,0.8);-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.mce-path{display:inline-block;*display:inline;*zoom:1;padding:8px;white-space:normal}.mce-path .mce-txt{display:inline-block;padding-right:3px}.mce-path .mce-path-body{display:inline-block}.mce-path-item{display:inline-block;*display:inline;*zoom:1;cursor:pointer;color:#000}.mce-path-item:hover{text-decoration:underline}.mce-path-item:focus{background:gray;color:white}.mce-path .mce-divider{display:inline}.mce-fieldset{border:0 solid #9e9e9e;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.mce-fieldset>.mce-container-body{margin-top:-15px}.mce-fieldset-title{margin-left:5px;padding:0 5px 0 5px}.mce-fit-layout{display:inline-block;*display:inline;*zoom:1}.mce-fit-layout-item{position:absolute}.mce-flow-layout-item{display:inline-block;*display:inline;*zoom:1}.mce-flow-layout-item{margin:2px 0 2px 2px}.mce-flow-layout-item.mce-last{margin-right:2px}.mce-flow-layout{white-space:normal}.mce-iframe{border:0 solid #c5c5c5;width:100%;height:100%}.mce-label{display:inline-block;*display:inline;*zoom:1;text-shadow:0 1px 1px rgba(255,255,255,0.75);border:0 solid #c5c5c5;overflow:hidden}.mce-label.mce-autoscroll{overflow:auto}.mce-label-disabled .mce-text{color:#999}.mce-label.mce-multiline{white-space:pre-wrap}.mce-menubar .mce-menubtn{border-color:transparent;background:transparent;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;filter:none}.mce-menubar{border:1px solid #ddd}.mce-menubar .mce-menubtn button{color:#000}.mce-menubar .mce-menubtn:hover,.mce-menubar .mce-menubtn.mce-active,.mce-menubtn:focus{border-color:transparent;background:#ddd;filter:none}.mce-menubtn.mce-disabled span{color:#999}.mce-listbox button{text-align:left;padding-right:20px;position:relative}.mce-listbox .mce-caret{position:absolute;margin-top:-2px;right:8px;top:50%}.mce-listbox span{width:100%;display:block;overflow:hidden}.mce-menu-item{display:block;padding:6px 20px;clear:both;font-weight:normal;line-height:20px;color:#333;white-space:nowrap;cursor:pointer;line-height:normal}.mce-menu-item.mce-disabled .mce-text{color:#999}.mce-menu-item:hover,.mce-menu-item.mce-selected,.mce-menu-item:focus{text-decoration:none;color:#fff;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0);zoom:1}.mce-menu-item:hover .mce-text,.mce-menu-item.mce-selected .mce-text{color:#fff}.mce-menu-item:hover .mce-ico,.mce-menu-item.mce-selected .mce-ico,.mce-menu-item:focus .mce-ico{color:white}.mce-menu-shortcut{display:inline-block;color:#999}.mce-menu-shortcut{display:inline-block;*display:inline;*zoom:1;padding:0 20px 0 20px}.mce-menu-item .mce-caret{margin-top:6px;*margin-top:3px;margin-right:6px;border-top:4px solid transparent;border-bottom:4px solid transparent;border-left:4px solid #666}.mce-menu-item.mce-selected .mce-caret,.mce-menu-item:focus .mce-caret{border-left-color:#FFF}.mce-menu-align .mce-menu-shortcut{*margin-top:-2px}.mce-menu-align .mce-menu-shortcut,.mce-menu-align .mce-caret{position:absolute;right:0}.mce-menu-item-sep,.mce-menu-item-sep:hover{padding:0;height:1px;margin:9px 1px;overflow:hidden;background:#e5e5e5;border-bottom:1px solid white;cursor:default;filter:none}.mce-menu-item.mce-active i{visibility:visible}.mce-menu-item.mce-active{background-color:#c8def4;outline:1px solid #c5c5c5}.mce-menu-item-checkbox.mce-active{background-color:#FFF;outline:0}.mce-menu{filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);background:transparent;z-index:1000;padding:5px 0 5px 0;margin:2px 0 0;min-width:160px;background:#FFF;border:1px solid #CCC;border:1px solid rgba(0,0,0,0.2);z-index:1002;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2)}.mce-menu i{display:none}.mce-menu-has-icons i{display:inline-block;*display:inline;*zoom:1}.mce-menu-sub{margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px}i.mce-radio{padding:1px;margin:0 3px 0 0;background-color:#fafafa;border:1px solid #cacece;-webkit-border-radius:8px;-moz-border-radius:8px;border-radius:8px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);background-color:#f0f0f0;background-image:-moz-linear-gradient(top,#fdfdfd,#ddd);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fdfdfd),to(#ddd));background-image:-webkit-linear-gradient(top,#fdfdfd,#ddd);background-image:-o-linear-gradient(top,#fdfdfd,#ddd);background-image:linear-gradient(to bottom,#fdfdfd,#ddd);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffdfdfd',endColorstr='#ffdddddd',GradientType=0);zoom:1}i.mce-radio:after{font-family:Arial;font-size:12px;color:#000;content:'\25cf'}.mce-container-body .mce-resizehandle{position:absolute;right:0;bottom:0;width:16px;height:16px;visibility:visible;cursor:s-resize;margin:0}.mce-resizehandle-both{cursor:se-resize}i.mce-i-resize{color:#000}.mce-spacer{visibility:hidden}.mce-splitbtn .mce-open{border-left:1px solid transparent;border-right:1px solid transparent}.mce-splitbtn:hover .mce-open{border-left-color:#c5c5c5;border-right-color:#c5c5c5}.mce-splitbtn button{padding-right:4px}.mce-splitbtn .mce-open{padding-left:4px}.mce-splitbtn .mce-open.mce-active{-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.mce-stack-layout-item{display:block}.mce-tabs{display:block;border-bottom:1px solid #ccc}.mce-tab{display:inline-block;*display:inline;*zoom:1;border:1px solid #ccc;border-width:1px 1px 0 0;background:#e3e3e3;padding:8px;text-shadow:0 1px 1px rgba(255,255,255,0.75);height:13px;cursor:pointer}.mce-tab:hover{background:#fdfdfd}.mce-tab.mce-active{background:#fdfdfd;border-bottom-color:transparent;margin-bottom:-1px;height:14px}.mce-textbox{background:#FFF;border:1px solid #c5c5c5;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);display:inline-block;-webkit-transition:border linear .2s,box-shadow linear .2s;transition:border linear .2s,box-shadow linear .2s;height:28px;resize:none;padding:0 4px 0 4px;white-space:normal;color:#000}.mce-textbox:focus{border-color:rgba(82,168,236,0.8);-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.mce-placeholder .mce-textbox{color:#aaa}.mce-textbox.mce-multiline{padding:4px}.mce-throbber{position:absolute;top:0;left:0;width:100%;height:100%;opacity:.6;filter:alpha(opacity=60);zoom:1;background:#fff url('img/loader.gif') no-repeat center center}@font-face{font-family:'tinymce';src:url('fonts/icomoon.eot');src:url('fonts/icomoon.eot?#iefix') format('embedded-opentype'),url('fonts/icomoon.svg#icomoon') format('svg'),url('fonts/icomoon.woff') format('woff'),url('fonts/icomoon.ttf') format('truetype');font-weight:normal;font-style:normal}.mce-ico{font-family:'tinymce',Arial;font-style:normal;font-weight:normal;font-size:16px;line-height:16px;vertical-align:text-top;-webkit-font-smoothing:antialiased;display:inline-block;background:transparent center center;width:16px;height:16px;color:#333}.mce-i-save:before{content:"\e000"}.mce-i-newdocument:before{content:"\e001"}.mce-i-fullpage:before{content:"\e002"}.mce-i-alignleft:before{content:"\e003"}.mce-i-aligncenter:before{content:"\e004"}.mce-i-alignright:before{content:"\e005"}.mce-i-alignjustify:before{content:"\e006"}.mce-i-cut:before{content:"\e007"}.mce-i-paste:before{content:"\e008"}.mce-i-searchreplace:before{content:"\e009"}.mce-i-bullist:before{content:"\e00a"}.mce-i-numlist:before{content:"\e00b"}.mce-i-indent:before{content:"\e00c"}.mce-i-outdent:before{content:"\e00d"}.mce-i-blockquote:before{content:"\e00e"}.mce-i-undo:before{content:"\e00f"}.mce-i-redo:before{content:"\e010"}.mce-i-link:before{content:"\e011"}.mce-i-unlink:before{content:"\e012"}.mce-i-anchor:before{content:"\e013"}.mce-i-image:before{content:"\e014"}.mce-i-media:before{content:"\e015"}.mce-i-help:before{content:"\e016"}.mce-i-code:before{content:"\e017"}.mce-i-inserttime:before{content:"\e018"}.mce-i-preview:before{content:"\e019"}.mce-i-forecolor:before{content:"\e01a"}.mce-i-backcolor:before{content:"\e01a"}.mce-i-table:before{content:"\e01b"}.mce-i-hr:before{content:"\e01c"}.mce-i-removeformat:before{content:"\e01d"}.mce-i-subscript:before{content:"\e01e"}.mce-i-superscript:before{content:"\e01f"}.mce-i-charmap:before{content:"\e020"}.mce-i-emoticons:before{content:"\e021"}.mce-i-print:before{content:"\e022"}.mce-i-fullscreen:before{content:"\e023"}.mce-i-spellchecker:before{content:"\e024"}.mce-i-nonbreaking:before{content:"\e025"}.mce-i-template:before{content:"\e026"}.mce-i-pagebreak:before{content:"\e027"}.mce-i-restoredraft:before{content:"\e028"}.mce-i-untitled:before{content:"\e029"}.mce-i-bold:before{content:"\e02a"}.mce-i-italic:before{content:"\e02b"}.mce-i-underline:before{content:"\e02c"}.mce-i-strikethrough:before{content:"\e02d"}.mce-i-visualchars:before{content:"\e02e"}.mce-i-ltr:before{content:"\e02f"}.mce-i-rtl:before{content:"\e030"}.mce-i-copy:before{content:"\e031"}.mce-i-resize:before{content:"\e032"}.mce-i-browse:before{content:"\e034"}.mce-i-checkbox:before,.mce-i-selected:before{content:"\e033"}.mce-i-selected{visibility:hidden}i.mce-i-backcolor{text-shadow:none;background:#BBB} \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/themes/modern/theme.js b/lib/tinymce/jscripts/tinymce4/themes/modern/theme.js new file mode 100644 index 00000000..98c9e23d --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/themes/modern/theme.js @@ -0,0 +1,479 @@ +/** + * theme.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*global tinymce:true */ + +tinymce.ThemeManager.add('modern', function(editor) { + var self = this, settings = editor.settings, Factory = tinymce.ui.Factory, each = tinymce.each, DOM = tinymce.DOM; + + // Default menus + var defaultMenus = { + file: {title: 'File', items: 'newdocument'}, + edit: {title: 'Edit', items: 'undo redo | cut copy paste | selectall'}, + insert: {title: 'Insert', items: '|'}, + view: {title: 'View', items: 'visualaid |'}, + format: {title: 'Format', items: 'bold italic underline strikethrough superscript subscript | formats | removeformat'}, + table: {title: 'Table'}, + tools: {title: 'Tools'} + }; + + var defaultToolbar = "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | " + + "bullist numlist outdent indent | link image"; + + /** + * Creates the toolbars from config and returns a toolbar array. + * + * @return {Array} Array with toolbars. + */ + function createToolbars() { + var toolbars = []; + + function addToolbar(items) { + var toolbarItems = [], buttonGroup; + + if (!items) { + return; + } + + each(items.split(/[ ,]/), function(item) { + var itemName; + + function bindSelectorChanged() { + var selection = editor.selection; + + if (itemName == "bullist") { + selection.selectorChanged('ul > li', function(state, args) { + var nodeName, i = args.parents.length; + + while (i--) { + nodeName = args.parents[i].nodeName; + if (nodeName == "OL" || nodeName == "UL") { + break; + } + } + + item.active(nodeName == "UL"); + }); + } + + if (itemName == "numlist") { + selection.selectorChanged('ol > li', function(state, args) { + var nodeName, i = args.parents.length; + + while (i--) { + nodeName = args.parents[i].nodeName; + if (nodeName == "OL" || nodeName == "UL") { + break; + } + } + + item.active(nodeName == "OL"); + }); + } + + if (item.settings.stateSelector) { + selection.selectorChanged(item.settings.stateSelector, function(state) { + item.active(state); + }, true); + } + + if (item.settings.disabledStateSelector) { + selection.selectorChanged(item.settings.disabledStateSelector, function(state) { + item.disabled(state); + }); + } + } + + if (item == "|") { + buttonGroup = null; + } else { + if (Factory.has(item)) { + item = {type: item}; + + if (settings.toolbar_items_size) { + item.size = settings.toolbar_items_size; + } + + toolbarItems.push(item); + buttonGroup = null; + } else { + if (!buttonGroup) { + buttonGroup = {type: 'buttongroup', items: []}; + toolbarItems.push(buttonGroup); + } + + if (editor.buttons[item]) { + itemName = item; + item = editor.buttons[itemName]; + item.type = item.type || 'button'; + + if (settings.toolbar_items_size) { + item.size = settings.toolbar_items_size; + } + + item = Factory.create(item); + buttonGroup.items.push(item); + + if (editor.initialized) { + bindSelectorChanged(); + } else { + editor.on('init', bindSelectorChanged); + } + } + } + } + }); + + toolbars.push({type: 'toolbar', layout: 'flow', items: toolbarItems}); + + return true; + } + + // Generate toolbar + for (var i = 1; i < 10; i++) { + if (!addToolbar(settings["toolbar" + i])) { + break; + } + } + + // Generate toolbar or default toolbar + if (!toolbars.length) { + addToolbar(settings.toolbar || defaultToolbar); + } + + return toolbars; + } + + /** + * Creates the menu buttons based on config. + * + * @return {Array} Menu buttons array. + */ + function createMenuButtons() { + var menuButtons = []; + + function createMenuItem(name) { + var menuItem; + + if (name == '|') { + return {text: '|'}; + } + + menuItem = editor.menuItems[name]; + + return menuItem; + } + + function createMenu(context) { + var menuButton, menu, menuItems, isUserDefined; + + // User defined menu + if (settings.menu) { + menu = settings.menu[context]; + isUserDefined = true; + } else { + menu = defaultMenus[context]; + } + + if (menu) { + menuButton = {text: menu.title}; + menuItems = []; + + // Default/user defined items + each((menu.items || '').split(/[ ,]/), function(item) { + var menuItem = createMenuItem(item); + + if (menuItem) { + menuItems.push(createMenuItem(item)); + } + }); + + // Added though context + if (!isUserDefined) { + each(editor.menuItems, function(menuItem) { + if (menuItem.context == context) { + if (menuItem.separator == 'before') { + menuItems.push({text: '|'}); + } + + if (menuItem.prependToContext) { + menuItems.unshift(menuItem); + } else { + menuItems.push(menuItem); + } + + if (menuItem.separator == 'after') { + menuItems.push({text: '|'}); + } + } + }); + } + + for (var i = 0; i < menuItems.length; i++) { + if (menuItems[i].text == '|') { + if (i === 0 || i == menuItems.length - 1) { + menuItems.splice(i, 1); + } + } + } + + menuButton.menu = menuItems; + + if (!menuButton.menu.length) { + return null; + } + } + + return menuButton; + } + + var enabledMenuNames = settings.menubar ? tinymce.makeMap(settings.menubar, /[ ,]/) : false; + for (var menu in defaultMenus) { + if (!enabledMenuNames || enabledMenuNames[menu]) { + menu = createMenu(menu); + + if (menu) { + menuButtons.push(menu); + } + } + } + + return menuButtons; + } + + /** + * Adds accessibility shortcut keys to panel. + * + * @param {tinymce.ui.Panel} panel Panel to add focus to. + */ + function addAccessibilityKeys(panel) { + function focus(type) { + var item = panel.find(type)[0]; + + if (item) { + item.focus(); + } + } + + editor.shortcuts.add('Alt+F9', '', function() { + focus('menubar'); + }); + + editor.shortcuts.add('Alt+F10', '', function() { + focus('toolbar'); + }); + + editor.shortcuts.add('Alt+F11', '', function() { + focus('elementpath'); + }); + + panel.on('cancel', function() { + editor.focus(); + }); + } + + /** + * Renders the inline editor UI. + * + * @return {Object} Name/value object with theme data. + */ + function renderInlineUI() { + var panel; + + function reposition() { + if (panel && panel.visible()) { + var pos = DOM.getPos(editor.getBody()); + panel.moveTo(pos.x, pos.y - panel.layoutRect().h); + } + } + + function show() { + if (panel) { + panel.show(); + reposition(); + DOM.addClass(editor.getBody(), 'mce-edit-focus'); + } + } + + function hide() { + if (panel) { + panel.hide(); + DOM.removeClass(editor.getBody(), 'mce-edit-focus'); + + if (document.activeElement && document.activeElement.className.indexOf('mce-content-body') == -1) { + DOM.setStyle(document.body, 'padding-top', 0); + } + } + } + + function render() { + if (panel) { + if (!panel.visible()) { + show(); + } + + editor.focus(); + return; + } + + panel = self.panel = Factory.create({ + type: 'floatpanel', + classes: 'tinymce tinymce-inline', + layout: 'flex', + direction: 'column', + autohide: false, + border: 1, + items: [ + settings.menubar === false ? null : {type: 'menubar', border: '0 0 1 0', items: createMenuButtons()}, + {type: 'panel', name: 'toolbar', layout: 'stack', items: createToolbars()} + ] + }); + + // Add statusbar + /*if (settings.statusbar !== false) { + panel.add({type: 'panel', classes: 'statusbar', layout: 'flow', border: '1 0 0 0', items: [ + {type: 'elementpath'} + ]}); + }*/ + + panel.renderTo(document.body).reflow(); + + addAccessibilityKeys(panel); + show(); + + editor.on('nodeChange', reposition); + editor.on('activate', show); + editor.on('deactivate', hide); + + editor.on('focusout', function() { + setTimeout(function() { + // TODO: Fix this, hack to see if focus is within a editor element or not + var activeElm = document.activeElement; + + while (activeElm) { + if (activeElm.nodeType == 1 && activeElm.className.indexOf('mce-') != -1 && + activeElm.className.indexOf('mce-content-body') === -1) { + return; + } + + activeElm = activeElm.parentNode; + } + + hide(); + }, 0); + }); + + editor.focus(); + } + + settings.content_editable = true; + + editor.on('focusin', render); + + // Remove the panel when the editor is removed + editor.on('remove', function() { + panel.remove(); + panel = null; + }); + + return {}; + } + + /** + * Renders the iframe editor UI. + * + * @param {Object} args Details about target element etc. + * @return {Object} Name/value object with theme data. + */ + function renderIframeUI(args) { + var panel; + + // Basic UI layout + panel = self.panel = Factory.create({ + type: 'panel', + classes: 'tinymce', + style: 'visibility: hidden', + layout: 'stack', + border: 1, + items: [ + settings.menubar === false ? null : {type: 'menubar', border: '0 0 1 0', items: createMenuButtons()}, + {type: 'panel', layout: 'stack', items: createToolbars()}, + {type: 'panel', name: 'iframe', layout: 'stack', classes: 'edit-area', html: '', border: '1 0 0 0'} + ] + }); + + // Add statusbar if needed + if (settings.statusbar !== false) { + panel.add({type: 'panel', name: 'statusbar', classes: 'statusbar', layout: 'flow', border: '1 0 0 0', items: [ + {type: 'elementpath'}, + settings.resize !== false ? ({type: 'resizehandle', editor: editor}) : null + ]}); + } + + // Render before the target textarea/div + panel.renderBefore(args.targetNode).reflow(); + + // Remove the panel when the editor is removed + editor.on('remove', function() { + panel.remove(); + panel = null; + }); + + // Add accesibility shortkuts + addAccessibilityKeys(panel); + + return { + iframeContainer: panel.find('#iframe')[0].getEl(), + editorContainer: panel.getEl() + }; + } + + /** + * Renders the UI for the theme. This gets called by the editor. + * + * @param {Object} args Details about target element etc. + * @return {Object} Theme UI data items. + */ + self.renderUI = function(args) { + var skin = settings.skin !== false ? settings.skin || 'lightgray' : false; + + if (skin) { + // Load special skin for IE7 + // TODO: Remove this when we drop IE7 support + if (tinymce.Env.ie && tinymce.Env.ie <= 7) { + tinymce.DOM.loadCSS(tinymce.baseURL + '/skins/' + skin + '/skin.ie7.min.css'); + } else { + tinymce.DOM.loadCSS(tinymce.baseURL + '/skins/' + skin + '/skin.min.css'); + } + + // Load content_css + editor.contentCSS.push(tinymce.baseURL + '/skins/' + skin + '/content.min.css'); + } + + // Handle editor setProgressState change + editor.on('ProgressState', function(e) { + self.throbber = self.throbber || new tinymce.ui.Throbber(self.panel.getEl('body')); + + if (e.state) { + self.throbber.show(e.time); + } else { + self.throbber.hide(); + } + }); + + // Render inline UI + if (settings.inline) { + return renderInlineUI(args); + } + + // Render iframe UI + return renderIframeUI(args); + }; +}); diff --git a/lib/tinymce/jscripts/tinymce4/themes/modern/theme.min.js b/lib/tinymce/jscripts/tinymce4/themes/modern/theme.min.js new file mode 100644 index 00000000..b8795366 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/themes/modern/theme.min.js @@ -0,0 +1 @@ +tinymce.ThemeManager.add("modern",function(e){function t(){function t(t){var i,a=[];if(t)return l(t.split(/[ ,]/),function(t){function n(){var n=e.selection;"bullist"==r&&n.selectorChanged("ul > li",function(e,n){for(var i,a=n.parents.length;a--&&(i=n.parents[a].nodeName,"OL"!=i&&"UL"!=i););t.active("UL"==i)}),"numlist"==r&&n.selectorChanged("ol > li",function(e,n){for(var i,a=n.parents.length;a--&&(i=n.parents[a].nodeName,"OL"!=i&&"UL"!=i););t.active("OL"==i)}),t.settings.stateSelector&&n.selectorChanged(t.settings.stateSelector,function(e){t.active(e)},!0),t.settings.disabledStateSelector&&n.selectorChanged(t.settings.disabledStateSelector,function(e){t.disabled(e)})}var r;"|"==t?i=null:c.has(t)?(t={type:t},s.toolbar_items_size&&(t.size=s.toolbar_items_size),a.push(t),i=null):(i||(i={type:"buttongroup",items:[]},a.push(i)),e.buttons[t]&&(r=t,t=e.buttons[r],t.type=t.type||"button",s.toolbar_items_size&&(t.size=s.toolbar_items_size),t=c.create(t),i.items.push(t),e.initialized?n():e.on("init",n)))}),n.push({type:"toolbar",layout:"flow",items:a}),!0}for(var n=[],i=1;10>i&&t(s["toolbar"+i]);i++);return n.length||t(s.toolbar||d),n}function n(){function t(t){var n;return"|"==t?{text:"|"}:n=e.menuItems[t]}function n(n){var i,a,r,o;if(s.menu?(a=s.menu[n],o=!0):a=m[n],a){i={text:a.title},r=[],l((a.items||"").split(/[ ,]/),function(e){var n=t(e);n&&r.push(t(e))}),o||l(e.menuItems,function(e){e.context==n&&("before"==e.separator&&r.push({text:"|"}),e.prependToContext?r.unshift(e):r.push(e),"after"==e.separator&&r.push({text:"|"}))});for(var c=0;r.length>c;c++)"|"==r[c].text&&(0===c||c==r.length-1)&&r.splice(c,1);if(i.menu=r,!i.menu.length)return null}return i}var i=[],a=s.menubar?tinymce.makeMap(s.menubar,/[ ,]/):!1;for(var r in m)(!a||a[r])&&(r=n(r),r&&i.push(r));return i}function i(t){function n(e){var n=t.find(e)[0];n&&n.focus()}e.shortcuts.add("Alt+F9","",function(){n("menubar")}),e.shortcuts.add("Alt+F10","",function(){n("toolbar")}),e.shortcuts.add("Alt+F11","",function(){n("elementpath")}),t.on("cancel",function(){e.focus()})}function a(){function a(){if(d&&d.visible()){var t=u.getPos(e.getBody());d.moveTo(t.x,t.y-d.layoutRect().h)}}function r(){d&&(d.show(),a(),u.addClass(e.getBody(),"mce-edit-focus"))}function l(){d&&(d.hide(),u.removeClass(e.getBody(),"mce-edit-focus"),document.activeElement&&-1==document.activeElement.className.indexOf("mce-content-body")&&u.setStyle(document.body,"padding-top",0))}function m(){return d?(d.visible()||r(),e.focus(),void 0):(d=o.panel=c.create({type:"floatpanel",classes:"tinymce tinymce-inline",layout:"flex",direction:"column",autohide:!1,border:1,items:[s.menubar===!1?null:{type:"menubar",border:"0 0 1 0",items:n()},{type:"panel",name:"toolbar",layout:"stack",items:t()}]}),d.renderTo(document.body).reflow(),i(d),r(),e.on("nodeChange",a),e.on("activate",r),e.on("deactivate",l),e.on("focusout",function(){setTimeout(function(){for(var e=document.activeElement;e;){if(1==e.nodeType&&-1!=e.className.indexOf("mce-")&&-1===e.className.indexOf("mce-content-body"))return;e=e.parentNode}l()},0)}),e.focus(),void 0)}var d;return s.content_editable=!0,e.on("focusin",m),e.on("remove",function(){d.remove(),d=null}),{}}function r(a){var r;return r=o.panel=c.create({type:"panel",classes:"tinymce",style:"visibility: hidden",layout:"stack",border:1,items:[s.menubar===!1?null:{type:"menubar",border:"0 0 1 0",items:n()},{type:"panel",layout:"stack",items:t()},{type:"panel",name:"iframe",layout:"stack",classes:"edit-area",html:"",border:"1 0 0 0"}]}),s.statusbar!==!1&&r.add({type:"panel",name:"statusbar",classes:"statusbar",layout:"flow",border:"1 0 0 0",items:[{type:"elementpath"},s.resize!==!1?{type:"resizehandle",editor:e}:null]}),r.renderBefore(a.targetNode).reflow(),e.on("remove",function(){r.remove(),r=null}),i(r),{iframeContainer:r.find("#iframe")[0].getEl(),editorContainer:r.getEl()}}var o=this,s=e.settings,c=tinymce.ui.Factory,l=tinymce.each,u=tinymce.DOM,m={file:{title:"File",items:"newdocument"},edit:{title:"Edit",items:"undo redo | cut copy paste | selectall"},insert:{title:"Insert",items:"|"},view:{title:"View",items:"visualaid |"},format:{title:"Format",items:"bold italic underline strikethrough superscript subscript | formats | removeformat"},table:{title:"Table"},tools:{title:"Tools"}},d="undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image";o.renderUI=function(t){var n=s.skin!==!1?s.skin||"lightgray":!1;return n&&(tinymce.Env.ie&&7>=tinymce.Env.ie?tinymce.DOM.loadCSS(tinymce.baseURL+"/skins/"+n+"/skin.ie7.min.css"):tinymce.DOM.loadCSS(tinymce.baseURL+"/skins/"+n+"/skin.min.css"),e.contentCSS.push(tinymce.baseURL+"/skins/"+n+"/content.min.css")),e.on("ProgressState",function(e){o.throbber=o.throbber||new tinymce.ui.Throbber(o.panel.getEl("body")),e.state?o.throbber.show(e.time):o.throbber.hide()}),s.inline?a(t):r(t)}}); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/tinymce.dev.js b/lib/tinymce/jscripts/tinymce4/tinymce.dev.js new file mode 100644 index 00000000..09bb7df2 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/tinymce.dev.js @@ -0,0 +1,213 @@ +/** + * Inline development version. Only to be used while developing since it uses document.write to load scripts. + */ + +/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ +/*globals $code */ + +(function(exports) { + "use strict"; + + var html = "", baseDir; + var modules = {}, exposedModules = [], moduleCount = 0; + + var scripts = document.getElementsByTagName('script'); + for (var i = 0; i < scripts.length; i++) { + var src = scripts[i].src; + + if (src.indexOf('/tinymce.dev.js') != -1) { + baseDir = src.substring(0, src.lastIndexOf('/')); + } + } + + function require(ids, callback) { + var module, defs = []; + + for (var i = 0; i < ids.length; ++i) { + module = modules[ids[i]] || resolve(ids[i]); + if (!module) { + throw 'module definition dependecy not found: ' + ids[i]; + } + + defs.push(module); + } + + callback.apply(null, defs); + } + + function resolve(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length; ++fi) { + if (!target[fragments[fi]]) { + return; + } + + target = target[fragments[fi]]; + } + + return target; + } + + function register(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length - 1; ++fi) { + if (target[fragments[fi]] === undefined) { + target[fragments[fi]] = {}; + } + + target = target[fragments[fi]]; + } + + target[fragments[fragments.length - 1]] = modules[id]; + } + + function define(id, dependencies, definition) { + if (typeof id !== 'string') { + throw 'invalid module definition, module id must be defined and be a string'; + } + + if (dependencies === undefined) { + throw 'invalid module definition, dependencies must be specified'; + } + + if (definition === undefined) { + throw 'invalid module definition, definition function must be specified'; + } + + require(dependencies, function() { + modules[id] = definition.apply(null, arguments); + }); + + if (--moduleCount === 0) { + for (var i = 0; i < exposedModules.length; i++) { + register(exposedModules[i]); + } + } + } + + function expose(ids) { + exposedModules = ids; + } + + function writeScripts() { + document.write(html); + } + + function load(path) { + html += '\n'; + moduleCount++; + } + + // Expose globally + exports.define = define; + exports.require = require; + + expose(["tinymce/dom/EventUtils","tinymce/dom/Sizzle","tinymce/dom/DomQuery","tinymce/html/Styles","tinymce/dom/TreeWalker","tinymce/util/Tools","tinymce/dom/Range","tinymce/html/Entities","tinymce/Env","tinymce/dom/DOMUtils","tinymce/dom/ScriptLoader","tinymce/AddOnManager","tinymce/html/Node","tinymce/html/Schema","tinymce/html/SaxParser","tinymce/html/DomParser","tinymce/html/Writer","tinymce/html/Serializer","tinymce/dom/Serializer","tinymce/dom/TridentSelection","tinymce/util/VK","tinymce/dom/ControlSelection","tinymce/dom/Selection","tinymce/dom/RangeUtils","tinymce/Formatter","tinymce/UndoManager","tinymce/EnterKey","tinymce/ForceBlocks","tinymce/EditorCommands","tinymce/util/URI","tinymce/util/Class","tinymce/ui/Selector","tinymce/ui/Collection","tinymce/ui/DomUtils","tinymce/ui/Control","tinymce/ui/Factory","tinymce/ui/Container","tinymce/ui/DragHelper","tinymce/ui/Scrollable","tinymce/ui/Panel","tinymce/ui/Movable","tinymce/ui/Resizable","tinymce/ui/FloatPanel","tinymce/ui/KeyboardNavigation","tinymce/ui/Window","tinymce/ui/MessageBox","tinymce/WindowManager","tinymce/util/Quirks","tinymce/util/Observable","tinymce/Shortcuts","tinymce/Editor","tinymce/EditorManager","tinymce/LegacyInput","tinymce/util/XHR","tinymce/util/JSON","tinymce/util/JSONRequest","tinymce/util/JSONP","tinymce/util/LocalStorage","tinymce/Compat","tinymce/ui/Layout","tinymce/ui/AbsoluteLayout","tinymce/ui/Tooltip","tinymce/ui/Widget","tinymce/ui/Button","tinymce/ui/ButtonGroup","tinymce/ui/Checkbox","tinymce/ui/CheckboxGroup","tinymce/ui/ColorButton","tinymce/ui/ComboBox","tinymce/ui/Path","tinymce/ui/ElementPath","tinymce/ui/FormItem","tinymce/ui/Form","tinymce/ui/FieldSet","tinymce/ui/FilePicker","tinymce/ui/FitLayout","tinymce/ui/FlexLayout","tinymce/ui/FlowLayout","tinymce/ui/FormatControls","tinymce/ui/GridLayout","tinymce/ui/Iframe","tinymce/ui/Label","tinymce/ui/Toolbar","tinymce/ui/MenuBar","tinymce/ui/MenuButton","tinymce/ui/ListBox","tinymce/ui/MenuItem","tinymce/ui/Menu","tinymce/ui/PanelButton","tinymce/ui/Radio","tinymce/ui/RadioGroup","tinymce/ui/ResizeHandle","tinymce/ui/Spacer","tinymce/ui/SplitButton","tinymce/ui/StackLayout","tinymce/ui/TabPanel","tinymce/ui/TextBox","tinymce/ui/Throbber"]); + + load('classes/dom/EventUtils.js'); + load('classes/dom/Sizzle.js'); + load('classes/dom/DomQuery.js'); + load('classes/html/Styles.js'); + load('classes/dom/TreeWalker.js'); + load('classes/util/Tools.js'); + load('classes/dom/Range.js'); + load('classes/html/Entities.js'); + load('classes/Env.js'); + load('classes/dom/DOMUtils.js'); + load('classes/dom/ScriptLoader.js'); + load('classes/AddOnManager.js'); + load('classes/html/Node.js'); + load('classes/html/Schema.js'); + load('classes/html/SaxParser.js'); + load('classes/html/DomParser.js'); + load('classes/html/Writer.js'); + load('classes/html/Serializer.js'); + load('classes/dom/Serializer.js'); + load('classes/dom/TridentSelection.js'); + load('classes/util/VK.js'); + load('classes/dom/ControlSelection.js'); + load('classes/dom/Selection.js'); + load('classes/dom/RangeUtils.js'); + load('classes/Formatter.js'); + load('classes/UndoManager.js'); + load('classes/EnterKey.js'); + load('classes/ForceBlocks.js'); + load('classes/EditorCommands.js'); + load('classes/util/URI.js'); + load('classes/util/Class.js'); + load('classes/ui/Selector.js'); + load('classes/ui/Collection.js'); + load('classes/ui/DomUtils.js'); + load('classes/ui/Control.js'); + load('classes/ui/Factory.js'); + load('classes/ui/Container.js'); + load('classes/ui/DragHelper.js'); + load('classes/ui/Scrollable.js'); + load('classes/ui/Panel.js'); + load('classes/ui/Movable.js'); + load('classes/ui/Resizable.js'); + load('classes/ui/FloatPanel.js'); + load('classes/ui/KeyboardNavigation.js'); + load('classes/ui/Window.js'); + load('classes/ui/MessageBox.js'); + load('classes/WindowManager.js'); + load('classes/util/Quirks.js'); + load('classes/util/Observable.js'); + load('classes/Shortcuts.js'); + load('classes/Editor.js'); + load('classes/EditorManager.js'); + load('classes/LegacyInput.js'); + load('classes/util/XHR.js'); + load('classes/util/JSON.js'); + load('classes/util/JSONRequest.js'); + load('classes/util/JSONP.js'); + load('classes/util/LocalStorage.js'); + load('classes/Compat.js'); + load('classes/ui/Layout.js'); + load('classes/ui/AbsoluteLayout.js'); + load('classes/ui/Tooltip.js'); + load('classes/ui/Widget.js'); + load('classes/ui/Button.js'); + load('classes/ui/ButtonGroup.js'); + load('classes/ui/Checkbox.js'); + load('classes/ui/CheckboxGroup.js'); + load('classes/ui/ColorButton.js'); + load('classes/ui/ComboBox.js'); + load('classes/ui/Path.js'); + load('classes/ui/ElementPath.js'); + load('classes/ui/FormItem.js'); + load('classes/ui/Form.js'); + load('classes/ui/FieldSet.js'); + load('classes/ui/FilePicker.js'); + load('classes/ui/FitLayout.js'); + load('classes/ui/FlexLayout.js'); + load('classes/ui/FlowLayout.js'); + load('classes/ui/FormatControls.js'); + load('classes/ui/GridLayout.js'); + load('classes/ui/Iframe.js'); + load('classes/ui/Label.js'); + load('classes/ui/Toolbar.js'); + load('classes/ui/MenuBar.js'); + load('classes/ui/MenuButton.js'); + load('classes/ui/ListBox.js'); + load('classes/ui/MenuItem.js'); + load('classes/ui/Menu.js'); + load('classes/ui/PanelButton.js'); + load('classes/ui/Radio.js'); + load('classes/ui/RadioGroup.js'); + load('classes/ui/ResizeHandle.js'); + load('classes/ui/Spacer.js'); + load('classes/ui/SplitButton.js'); + load('classes/ui/StackLayout.js'); + load('classes/ui/TabPanel.js'); + load('classes/ui/TextBox.js'); + load('classes/ui/Throbber.js'); + + writeScripts(); +})(this); + +// $hash: 0ce0964377180ff5bfc4ea91a73683dd \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/tinymce.jquery.dev.js b/lib/tinymce/jscripts/tinymce4/tinymce.jquery.dev.js new file mode 100644 index 00000000..ad0237c1 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/tinymce.jquery.dev.js @@ -0,0 +1,212 @@ +/** + * Inline development version. Only to be used while developing since it uses document.write to load scripts. + */ + +/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ +/*globals $code */ + +(function(exports) { + "use strict"; + + var html = "", baseDir; + var modules = {}, exposedModules = [], moduleCount = 0; + + var scripts = document.getElementsByTagName('script'); + for (var i = 0; i < scripts.length; i++) { + var src = scripts[i].src; + + if (src.indexOf('/tinymce.jquery.dev.js') != -1) { + baseDir = src.substring(0, src.lastIndexOf('/')); + } + } + + function require(ids, callback) { + var module, defs = []; + + for (var i = 0; i < ids.length; ++i) { + module = modules[ids[i]] || resolve(ids[i]); + if (!module) { + throw 'module definition dependecy not found: ' + ids[i]; + } + + defs.push(module); + } + + callback.apply(null, defs); + } + + function resolve(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length; ++fi) { + if (!target[fragments[fi]]) { + return; + } + + target = target[fragments[fi]]; + } + + return target; + } + + function register(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length - 1; ++fi) { + if (target[fragments[fi]] === undefined) { + target[fragments[fi]] = {}; + } + + target = target[fragments[fi]]; + } + + target[fragments[fragments.length - 1]] = modules[id]; + } + + function define(id, dependencies, definition) { + if (typeof id !== 'string') { + throw 'invalid module definition, module id must be defined and be a string'; + } + + if (dependencies === undefined) { + throw 'invalid module definition, dependencies must be specified'; + } + + if (definition === undefined) { + throw 'invalid module definition, definition function must be specified'; + } + + require(dependencies, function() { + modules[id] = definition.apply(null, arguments); + }); + + if (--moduleCount === 0) { + for (var i = 0; i < exposedModules.length; i++) { + register(exposedModules[i]); + } + } + } + + function expose(ids) { + exposedModules = ids; + } + + function writeScripts() { + document.write(html); + } + + function load(path) { + html += '\n'; + moduleCount++; + } + + // Expose globally + exports.define = define; + exports.require = require; + + expose(["tinymce/dom/Sizzle","tinymce/html/Styles","tinymce/dom/EventUtils","tinymce/dom/TreeWalker","tinymce/util/Tools","tinymce/dom/Range","tinymce/html/Entities","tinymce/Env","tinymce/dom/DOMUtils","tinymce/dom/ScriptLoader","tinymce/AddOnManager","tinymce/html/Node","tinymce/html/Schema","tinymce/html/SaxParser","tinymce/html/DomParser","tinymce/html/Writer","tinymce/html/Serializer","tinymce/dom/Serializer","tinymce/dom/TridentSelection","tinymce/util/VK","tinymce/dom/ControlSelection","tinymce/dom/Selection","tinymce/dom/RangeUtils","tinymce/Formatter","tinymce/UndoManager","tinymce/EnterKey","tinymce/ForceBlocks","tinymce/EditorCommands","tinymce/util/URI","tinymce/util/Class","tinymce/ui/Selector","tinymce/ui/Collection","tinymce/ui/DomUtils","tinymce/ui/Control","tinymce/ui/Factory","tinymce/ui/Container","tinymce/ui/DragHelper","tinymce/ui/Scrollable","tinymce/ui/Panel","tinymce/ui/Movable","tinymce/ui/Resizable","tinymce/ui/FloatPanel","tinymce/ui/KeyboardNavigation","tinymce/ui/Window","tinymce/ui/MessageBox","tinymce/WindowManager","tinymce/util/Quirks","tinymce/util/Observable","tinymce/Shortcuts","tinymce/Editor","tinymce/EditorManager","tinymce/LegacyInput","tinymce/util/XHR","tinymce/util/JSON","tinymce/util/JSONRequest","tinymce/util/JSONP","tinymce/util/LocalStorage","tinymce/Compat","tinymce/ui/Layout","tinymce/ui/AbsoluteLayout","tinymce/ui/Tooltip","tinymce/ui/Widget","tinymce/ui/Button","tinymce/ui/ButtonGroup","tinymce/ui/Checkbox","tinymce/ui/CheckboxGroup","tinymce/ui/ColorButton","tinymce/ui/ComboBox","tinymce/ui/Path","tinymce/ui/ElementPath","tinymce/ui/FormItem","tinymce/ui/Form","tinymce/ui/FieldSet","tinymce/ui/FilePicker","tinymce/ui/FitLayout","tinymce/ui/FlexLayout","tinymce/ui/FlowLayout","tinymce/ui/FormatControls","tinymce/ui/GridLayout","tinymce/ui/Iframe","tinymce/ui/Label","tinymce/ui/Toolbar","tinymce/ui/MenuBar","tinymce/ui/MenuButton","tinymce/ui/ListBox","tinymce/ui/MenuItem","tinymce/ui/Menu","tinymce/ui/PanelButton","tinymce/ui/Radio","tinymce/ui/RadioGroup","tinymce/ui/ResizeHandle","tinymce/ui/Spacer","tinymce/ui/SplitButton","tinymce/ui/StackLayout","tinymce/ui/TabPanel","tinymce/ui/TextBox","tinymce/ui/Throbber"]); + + load('classes/dom/Sizzle.js'); + load('classes/html/Styles.js'); + load('classes/dom/EventUtils.js'); + load('classes/dom/TreeWalker.js'); + load('classes/util/Tools.js'); + load('classes/dom/Range.js'); + load('classes/html/Entities.js'); + load('classes/Env.js'); + load('classes/dom/DOMUtils.js'); + load('classes/dom/ScriptLoader.js'); + load('classes/AddOnManager.js'); + load('classes/html/Node.js'); + load('classes/html/Schema.js'); + load('classes/html/SaxParser.js'); + load('classes/html/DomParser.js'); + load('classes/html/Writer.js'); + load('classes/html/Serializer.js'); + load('classes/dom/Serializer.js'); + load('classes/dom/TridentSelection.js'); + load('classes/util/VK.js'); + load('classes/dom/ControlSelection.js'); + load('classes/dom/Selection.js'); + load('classes/dom/RangeUtils.js'); + load('classes/Formatter.js'); + load('classes/UndoManager.js'); + load('classes/EnterKey.js'); + load('classes/ForceBlocks.js'); + load('classes/EditorCommands.js'); + load('classes/util/URI.js'); + load('classes/util/Class.js'); + load('classes/ui/Selector.js'); + load('classes/ui/Collection.js'); + load('classes/ui/DomUtils.js'); + load('classes/ui/Control.js'); + load('classes/ui/Factory.js'); + load('classes/ui/Container.js'); + load('classes/ui/DragHelper.js'); + load('classes/ui/Scrollable.js'); + load('classes/ui/Panel.js'); + load('classes/ui/Movable.js'); + load('classes/ui/Resizable.js'); + load('classes/ui/FloatPanel.js'); + load('classes/ui/KeyboardNavigation.js'); + load('classes/ui/Window.js'); + load('classes/ui/MessageBox.js'); + load('classes/WindowManager.js'); + load('classes/util/Quirks.js'); + load('classes/util/Observable.js'); + load('classes/Shortcuts.js'); + load('classes/Editor.js'); + load('classes/EditorManager.js'); + load('classes/LegacyInput.js'); + load('classes/util/XHR.js'); + load('classes/util/JSON.js'); + load('classes/util/JSONRequest.js'); + load('classes/util/JSONP.js'); + load('classes/util/LocalStorage.js'); + load('classes/Compat.js'); + load('classes/ui/Layout.js'); + load('classes/ui/AbsoluteLayout.js'); + load('classes/ui/Tooltip.js'); + load('classes/ui/Widget.js'); + load('classes/ui/Button.js'); + load('classes/ui/ButtonGroup.js'); + load('classes/ui/Checkbox.js'); + load('classes/ui/CheckboxGroup.js'); + load('classes/ui/ColorButton.js'); + load('classes/ui/ComboBox.js'); + load('classes/ui/Path.js'); + load('classes/ui/ElementPath.js'); + load('classes/ui/FormItem.js'); + load('classes/ui/Form.js'); + load('classes/ui/FieldSet.js'); + load('classes/ui/FilePicker.js'); + load('classes/ui/FitLayout.js'); + load('classes/ui/FlexLayout.js'); + load('classes/ui/FlowLayout.js'); + load('classes/ui/FormatControls.js'); + load('classes/ui/GridLayout.js'); + load('classes/ui/Iframe.js'); + load('classes/ui/Label.js'); + load('classes/ui/Toolbar.js'); + load('classes/ui/MenuBar.js'); + load('classes/ui/MenuButton.js'); + load('classes/ui/ListBox.js'); + load('classes/ui/MenuItem.js'); + load('classes/ui/Menu.js'); + load('classes/ui/PanelButton.js'); + load('classes/ui/Radio.js'); + load('classes/ui/RadioGroup.js'); + load('classes/ui/ResizeHandle.js'); + load('classes/ui/Spacer.js'); + load('classes/ui/SplitButton.js'); + load('classes/ui/StackLayout.js'); + load('classes/ui/TabPanel.js'); + load('classes/ui/TextBox.js'); + load('classes/ui/Throbber.js'); + + writeScripts(); +})(this); + +// $hash: 0672c9775ec3aedc6dede9095596d5db \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/tinymce.jquery.js b/lib/tinymce/jscripts/tinymce4/tinymce.jquery.js new file mode 100644 index 00000000..5e8ff5ef --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/tinymce.jquery.js @@ -0,0 +1,30495 @@ +// 4.0b1 (2013-04-11) + +/** + * Compiled inline version. (Library mode) + */ + +/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ +/*globals $code */ + +(function(exports, undefined) { + "use strict"; + + var modules = {}; + + function require(ids, callback) { + var module, defs = []; + + for (var i = 0; i < ids.length; ++i) { + module = modules[ids[i]] || resolve(ids[i]); + if (!module) { + throw 'module definition dependecy not found: ' + ids[i]; + } + + defs.push(module); + } + + callback.apply(null, defs); + } + + function define(id, dependencies, definition) { + if (typeof id !== 'string') { + throw 'invalid module definition, module id must be defined and be a string'; + } + + if (dependencies === undefined) { + throw 'invalid module definition, dependencies must be specified'; + } + + if (definition === undefined) { + throw 'invalid module definition, definition function must be specified'; + } + + require(dependencies, function() { + modules[id] = definition.apply(null, arguments); + }); + } + + function defined(id) { + return !!modules[id]; + } + + function resolve(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length; ++fi) { + if (!target[fragments[fi]]) { + return; + } + + target = target[fragments[fi]]; + } + + return target; + } + + function expose(ids) { + for (var i = 0; i < ids.length; i++) { + var target = exports; + var id = ids[i]; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length - 1; ++fi) { + if (target[fragments[fi]] === undefined) { + target[fragments[fi]] = {}; + } + + target = target[fragments[fi]]; + } + + target[fragments[fragments.length - 1]] = modules[id]; + } + } + +// Included from: js/tinymce/classes/dom/Sizzle.js + +/** + * Sizzle.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint bitwise:false, expr:true, noempty:false, sub:true, eqnull:true, latedef:false, maxlen:255 */ + +/* + * Sizzle CSS Selector Engine + * Copyright, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +define("tinymce/dom/Sizzle", [], function() { +var i, + cachedruns, + Expr, + getText, + isXML, + compile, + outermostContext, + recompare, + sortInput, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + -(new Date()), + preferredDoc = window.document, + support = {}, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + hasDuplicate = false, + sortOrder = function() { return 0; }, + + // General-purpose constants + strundefined = typeof undefined, + MAX_NEGATIVE = 1 << 31, + + // Array methods + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf if we can't use a native one + indexOf = arr.indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + + // 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/, + + // 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 ); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +/** + * 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 = []; + + 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() ]; + } + cache[ key ] = value; + return value; + }; + + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // 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 ( documentIsHTML && !seed ) { + + // Shortcuts + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // QSA path + if ( support.qsa && !rbuggyQSA.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, + newContext.querySelectorAll( newSelector ) + ); + 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 + documentIsHTML = !isXML( doc ); + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = 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 = ""; + 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.getElementsByClassName = assert(function( div ) { + // Opera can't find a second classname (in 9.6) + div.innerHTML = ""; + 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 getElementsByName privileges form controls or returns elements by ID + // If so, assume (for broader support) that getElementById returns elements by name + support.getByName = assert(function( div ) { + // Inject content + div.id = expando + 0; + // Support: Windows 8 Native Apps + // Assigning innerHTML with "name" attributes throws uncatchable exceptions + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx + div.appendChild( document.createElement("a") ).setAttribute( "name", expando ); + div.appendChild( document.createElement("i") ).setAttribute( "name", expando ); + docElem.appendChild( div ); + + // 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; + + // Cleanup + docElem.removeChild( div ); + + return pass; + }); + + // Support: Webkit<537.32 + // Detached nodes confoundingly follow *each other* + support.sortDetached = assert(function( div1 ) { + return div1.compareDocumentPosition && + // Should return 1, but Webkit returns 4 (following) + (div1.compareDocumentPosition( document.createElement("div") ) & 1); + }); + + // IE6/7 return modified attributes + Expr.attrHandle = assert(function( div ) { + div.innerHTML = ""; + 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.getByName ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + 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.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var elem, + tmp = [], + i = 0, + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Name + Expr.find["NAME"] = support.getByName && function( tag, context ) { + if ( typeof context.getElementsByName !== strundefined ) { + return context.getElementsByName( name ); + } + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { + 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 explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // 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 = ""; + 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 = rbuggyMatches.length && 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 ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); + + if ( compare ) { + // Disconnected nodes + if ( compare & 1 || + (recompare && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === doc || contains(preferredDoc, a) ) { + return -1; + } + if ( b === doc || contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } + + // Not directly comparable, sort on existence of method + return a.compareDocumentPosition ? -1 : 1; + } : + function( a, b ) { + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Parentless nodes are either documents or disconnected + } else if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return 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 && documentIsHTML && (!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 ( documentIsHTML ) { + name = name.toLowerCase(); + } + if ( (val = Expr.attrHandle[ name ]) ) { + return val( elem ); + } + if ( !documentIsHTML || 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 = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + // Compensate for sort limitations + recompare = !support.sortDetached; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + return results; +}; + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns Returns -1 if a precedes b, 1 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +// Returns a function to use in pseudos for input types +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.slice( -check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), + // not comment, processing instructions, or others + // Thanks to Diego Perini for the nodeName shortcut + // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +// 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 && 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 ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); + + if ( outermost ) { + outermostContext = context !== document && context; + cachedruns = matcherCachedRuns; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + for ( ; (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + cachedruns = ++matcherCachedRuns; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !group ) { + group = tokenize( selector ); + } + i = group.length; + while ( i-- ) { + cached = matcherFromTokens( group[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + } + return cached; +}; + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function select( selector, context, results, seed ) { + var i, tokens, token, type, find, + match = tokenize( selector ); + + if ( !seed ) { + // Try to minimize operations if there is only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && context.parentNode || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + } + + // Compile and execute a filtering function + // Provide `match` to avoid retokenization if we modified the selector above + compile( selector, match )( + seed, + context, + !documentIsHTML, + results, + rsibling.test( selector ) + ); + return results; +} + +// Deprecated +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +// Check sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Initialize with the default document +setDocument(); + +// Always assume the presence of duplicates if sort doesn't +// pass them to our comparison function (as in Google Chrome). +[0, 0].sort( sortOrder ); +support.detectDuplicates = hasDuplicate; + +// EXPOSE +if ( typeof define === "function" && define.amd ) { + define(function() { return Sizzle; }); +} else { + window.Sizzle = Sizzle; +} + +// EXPOSE +return Sizzle; +}); + +// Included from: js/tinymce/classes/html/Styles.js + +/** + * Styles.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is used to parse CSS styles it also compresses styles to reduce the output size. + * + * @example + * var Styles = new tinymce.html.Styles({ + * url_converter: function(url) { + * return url; + * } + * }); + * + * styles = Styles.parse('border: 1px solid red'); + * styles.color = 'red'; + * + * console.log(new tinymce.html.StyleSerializer().serialize(styles)); + * + * @class tinymce.html.Styles + * @version 3.4 + */ +define("tinymce/html/Styles", [], function() { + return function(settings, schema) { + /*jshint maxlen:255 */ + 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+$/, + undef, i, encodingLookup = {}, encodingItems, invisibleChar = '\uFEFF'; + + settings = settings || {}; + + encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' '); + for (i = 0; i < encodingItems.length; i++) { + encodingLookup[encodingItems[i]] = invisibleChar + i; + encodingLookup[invisibleChar + i] = encodingItems[i]; + } + + function toHex(match, r, g, b) { + function hex(val) { + val = parseInt(val, 10).toString(16); + + return val.length > 1 ? val : '0' + val; // 0 -> 00 + } + + return '#' + hex(r) + hex(g) + hex(b); + } + + return { + /** + * Parses the specified RGB color value and returns a hex version of that color. + * + * @method toHex + * @param {String} color RGB string value like rgb(1,2,3) + * @return {String} Hex version of that RGB value like #FF00FF. + */ + toHex: function(color) { + return color.replace(rgbRegExp, toHex); + }, + + /** + * Parses the specified style value into an object collection. This parser will also + * merge and remove any redundant items that browsers might have added. It will also convert non hex + * colors to hex values. Urls inside the styles will also be converted to absolute/relative based on settings. + * + * @method parse + * @param {String} css Style value to parse for example: border:1px solid red;. + * @return {Object} Object representation of that style like {border: '1px solid red'} + */ + 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]; + } + + /** + * Checks if the specific style can be compressed in other words if all border-width are equal. + */ + 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; + } + + /** + * Compresses multiple styles into one style. + */ + 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 _ + function encode(str) { + isEncoded = true; + + return encodingLookup[str]; + } + + // Decodes the specified string by replacing all _ 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; + }, + + /** + * Serializes the specified style object into a string. + * + * @method serialize + * @param {Object} styles Object to serialize as string for example: {border: '1px solid red'} + * @param {String} element_name Optional element name, if specified only the styles that matches the schema will be serialized. + * @return {String} String representation of the style object for example: border: 1px solid red. + */ + 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; + } + }; + }; +}); + +// Included from: js/tinymce/classes/dom/EventUtils.js + +/** + * EventUtils.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint loopfunc:true*/ + +define("tinymce/dom/EventUtils", [], function() { + "use strict"; + + var eventExpandoPrefix = "mce-data-"; + + /** + * Binds a native event to a callback on the speified target. + */ + function addEvent(target, name, callback, capture) { + if (target.addEventListener) { + target.addEventListener(name, callback, capture || false); + } else if (target.attachEvent) { + target.attachEvent('on' + name, callback); + } + } + + /** + * Unbinds a native event callback on the specified target. + */ + function removeEvent(target, name, callback, capture) { + if (target.removeEventListener) { + target.removeEventListener(name, callback, capture || false); + } else if (target.detachEvent) { + target.detachEvent('on' + name, callback); + } + } + + /** + * Normalizes a native event object or just adds the event specific methods on a custom event. + */ + function fix(originalEvent, 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 originalEvent) { + // layerX/layerY is deprecated in Chrome and produces a warning + if (name !== "layerX" && name !== "layerY") { + event[name] = originalEvent[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 (originalEvent) { + if (originalEvent.preventDefault) { + originalEvent.preventDefault(); + } else { + originalEvent.returnValue = false; // IE + } + } + }; + + // Add stopPropagation + event.stopPropagation = function() { + event.isPropagationStopped = returnTrue; + + // Execute stopPropagation on the original event object + if (originalEvent) { + if (originalEvent.stopPropagation) { + originalEvent.stopPropagation(); + } else { + originalEvent.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; + } + + /** + * Bind a DOMContentLoaded event across browsers and executes the callback once the page DOM is initialized. + * It will also set/check the domLoaded state of the event_utils instance so ready isn't called multiple times. + */ + function bindOnReady(win, callback, eventUtils) { + var doc = win.document, event = {type: 'ready'}; + + if (eventUtils.domLoaded) { + callback(event); + return; + } + + // Gets called when the DOM is ready + function readyHandler() { + if (!eventUtils.domLoaded) { + eventUtils.domLoaded = true; + callback(event); + } + } + + function waitForDomLoaded() { + if (doc.readyState === "complete") { + removeEvent(doc, "readystatechange", waitForDomLoaded); + readyHandler(); + } + } + + function tryScroll() { + 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(tryScroll, 0); + return; + } + + readyHandler(); + } + + // Use W3C method + if (doc.addEventListener) { + addEvent(win, 'DOMContentLoaded', readyHandler); + } else { + // Use IE method + addEvent(doc, "readystatechange", waitForDomLoaded); + + // Wait until we can scroll, when we can the DOM is initialized + if (doc.documentElement.doScroll && win === win.top) { + tryScroll(); + } + } + + // Fallback if any of the above methods should fail for some odd reason + addEvent(win, 'load', readyHandler); + } + + /** + * This class enables you to bind/unbind native events to elements and normalize it's behavior across browsers. + */ + function EventUtils() { + var self = this, events = {}, count, expando, hasFocusIn, hasMouseEnterLeave, mouseEnterLeave; + + expando = eventExpandoPrefix + (+new Date()).toString(32); + 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; + + /** + * Executes all event handler callbacks for a specific event. + * + * @param {Event} evt Event object. + * @param {String} id Expando id value to look for. + */ + 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; + } + } + } + } + + /** + * Binds a callback to an event on the specified target. + * + * @method bind + * @param {Object} target Target node/window or custom object. + * @param {String} names Name of the event to bind. + * @param {function} callback Callback function to execute when the event occurs. + * @param {Object} scope Scope to call the callback function on, defaults to target. + * @return {function} Callback function that got bound. + */ + 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]; + } + + // 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 && name === "ready" && target.readyState == 'complete') { + 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; + + // Check if the target has native events support + + if (name === "ready") { + bindOnReady(target, nativeHandler, self); + } else { + addEvent(target, fakeName || name, nativeHandler, capture); + } + } else { + if (name === "ready" && self.domLoaded) { + callback({type: name}); + } 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; + }; + + /** + * Unbinds the specified event by name, name and callback or all events on the target. + * + * @method unbind + * @param {Object} target Target node/window or custom object. + * @param {String} names Optional event name to unbind. + * @param {function} callback Optional callback function to unbind. + * @return {EventUtils} Event utils instance. + */ + 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, callbackList.nativeHandler, callbackList.capture); + } + } + } + } else { + // All events for a specific element + for (name in eventMap) { + callbackList = eventMap[name]; + removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, 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; + }; + + /** + * Fires the specified event on the specified target. + * + * @method fire + * @param {Object} target Target node/window or custom object. + * @param {String} name Event name to fire. + * @param {Object} args Optional arguments to send to the observers. + * @return {EventUtils} Event utils instance. + */ + self.fire = function(target, name, args) { + var id; + + // 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 + args = fix(null, args); + args.type = name; + args.target = target; + + do { + // Found an expando that means there is listeners to execute + id = target[expando]; + if (id) { + executeHandlers(args, id); + } + + // Walk up the DOM + target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow; + } while (target && !args.isPropagationStopped()); + + return self; + }; + + /** + * Removes all bound event listeners for the specified target. This will also remove any bound + * listeners to child nodes within that target. + * + * @method clean + * @param {Object} target Target node/window object. + * @return {EventUtils} Event utils instance. + */ + 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; + }; + + /** + * Destroys the event object. Call this on IE to remove memory leaks. + */ + self.destory = function() { + events = {}; + }; + + // Legacy function for canceling events + self.cancel = function(e) { + if (e) { + e.preventDefault(); + e.stopImmediatePropagation(); + } + + return false; + }; + } + + EventUtils.Event = new EventUtils(); + EventUtils.Event.bind(window, 'ready', function() {}); + + return EventUtils; +}); + +// Included from: js/tinymce/classes/dom/TreeWalker.js + +/** + * TreeWalker.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/dom/TreeWalker", [], function() { + return 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; + } + } + } + } + } + + /** + * Returns the current node. + * + * @return {Node} Current node where the walker is. + */ + this.current = function() { + return node; + }; + + /** + * Walks to the next node in tree. + * + * @return {Node} Current node where the walker is after moving to the next node. + */ + this.next = function(shallow) { + node = findSibling(node, 'firstChild', 'nextSibling', shallow); + return node; + }; + + /** + * Walks to the previous node in tree. + * + * @return {Node} Current node where the walker is after moving to the previous node. + */ + this.prev = function(shallow) { + node = findSibling(node, 'lastChild', 'previousSibling', shallow); + return node; + }; + }; +}); + +// Included from: js/tinymce/classes/util/Tools.js + +/** + * Quirks.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/util/Tools", [], function() { + /** + * Removes whitespace from the beginning and end of a string. + * + * @method trim + * @param {String} s String to remove whitespace from. + * @return {String} New string with removed whitespace. + */ + var whiteSpaceRegExp = /^\s*|\s*$/g; + var trim = function(str) { + return (str === null || str === undefined) ? '' : ("" + str).replace(whiteSpaceRegExp, ''); + }; + + /** + * Returns true/false if the object is an array or not. + * + * @method isArray + * @param {Object} obj Object to check. + * @return {boolean} true/false state if the object is an array or not. + */ + var isArray = Array.isArray || function(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + + /** + * Checks if a object is of a specific type for example an array. + * + * @method is + * @param {Object} o Object to check type of. + * @param {string} t Optional type to check for. + * @return {Boolean} true/false if the object is of the specified type. + */ + function is(o, t) { + if (!t) { + return o !== undefined; + } + + if (t == 'array' && isArray(o)) { + return true; + } + + return typeof(o) == t; + } + + /** + * Converts the specified object into a real JavaScript array. + * + * @method toArray + * @param {Object} obj Object to convert into array. + * @return {Array} Array object based in input. + */ + function toArray(obj) { + var array = [], i, l; + + for (i = 0, l = obj.length; i < l; i++) { + array[i] = obj[i]; + } + + return array; + } + + /** + * Makes a name/object map out of an array with names. + * + * @method makeMap + * @param {Array/String} items Items to make map out of. + * @param {String} delim Optional delimiter to split string by. + * @param {Object} map Optional map to add items to. + * @return {Object} Name/value map of items. + */ + function makeMap(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; + } + + /** + * Performs an iteration of all items in a collection such as an object or array. This method will execure the + * callback function for each item in the collection, if the callback returns false the iteration will terminate. + * The callback has the following format: cb(value, key_or_index). + * + * @method each + * @param {Object} o Collection to iterate. + * @param {function} cb Callback function to execute for each item. + * @param {Object} s Optional scope to execute the callback in. + * @example + * // Iterate an array + * tinymce.each([1,2,3], function(v, i) { + * console.debug("Value: " + v + ", Index: " + i); + * }); + * + * // Iterate an object + * tinymce.each({a: 1, b: 2, c: 3], function(v, k) { + * console.debug("Value: " + v + ", Key: " + k); + * }); + */ + function each(o, cb, s) { + var n, l; + + if (!o) { + return 0; + } + + s = s || o; + + if (o.length !== undefined) { + // 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; + } + + /** + * Creates a new array by the return value of each iteration function call. This enables you to convert + * one array list into another. + * + * @method map + * @param {Array} a Array of items to iterate. + * @param {function} f Function to call for each item. It's return value will be the new value. + * @return {Array} Array with new values based on function return values. + */ + function map(a, f) { + var o = []; + + each(a, function(v) { + o.push(f(v)); + }); + + return o; + } + + /** + * Filters out items from the input array by calling the specified function for each item. + * If the function returns false the item will be excluded if it returns true it will be included. + * + * @method grep + * @param {Array} a Array of items to loop though. + * @param {function} f Function to call for each item. Include/exclude depends on it's return value. + * @return {Array} New array with values imported and filtered based in input. + * @example + * // Filter out some items, this will return an array with 4 and 5 + * var items = tinymce.grep([1,2,3,4,5], function(v) {return v > 3;}); + */ + function grep(a, f) { + var o = []; + + each(a, function(v) { + if (!f || f(v)) { + o.push(v); + } + }); + + return o; + } + + /** + * Creates a class, subclass or static singleton. + * More details on this method can be found in the Wiki. + * + * @method create + * @param {String} s Class name, inheritage and prefix. + * @param {Object} p Collection of methods to add to the class. + * @param {Object} root Optional root object defaults to the global window object. + * @example + * // Creates a basic class + * tinymce.create('tinymce.somepackage.SomeClass', { + * SomeClass: function() { + * // Class constructor + * }, + * + * method: function() { + * // Some method + * } + * }); + * + * // Creates a basic subclass class + * tinymce.create('tinymce.somepackage.SomeSubClass:tinymce.somepackage.SomeClass', { + * SomeSubClass: function() { + * // Class constructor + * this.parent(); // Call parent constructor + * }, + * + * method: function() { + * // Some method + * this.parent(); // Call parent method + * }, + * + * 'static': { + * staticMethod: function() { + * // Static method + * } + * } + * }); + * + * // Creates a singleton/static class + * tinymce.create('static tinymce.somepackage.SomeSingletonClass', { + * method: function() { + * // Some method + * } + * }); + */ + function create(s, p, root) { + var t = this, sp, ns, cn, scn, c, de = 0; + + // Parse : : + 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 + /*jshint sub:true*/ + t.each(p['static'], function(f, n) { + ns[cn][n] = f; + }); + } + + /** + * Returns the index of a value in an array, this method will return -1 if the item wasn't found. + * + * @method inArray + * @param {Array} a Array/Object to search for value in. + * @param {Object} v Value to check for inside the array. + * @return {Number/String} Index of item inside the array inside an object. Or -1 if it wasn't found. + * @example + * // Get index of value in array this will alert 1 since 2 is at that index + * alert(tinymce.inArray([1,2,3], 2)); + */ + function inArray(a, v) { + var i, l; + + if (a) { + for (i = 0, l = a.length; i < l; i++) { + if (a[i] === v) { + return i; + } + } + } + + return -1; + } + + function extend(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 !== undefined) { + obj[name] = value; + } + } + } + } + + return obj; + } + + /** + * Executed the specified function for each item in a object tree. + * + * @method walk + * @param {Object} o Object tree to walk though. + * @param {function} f Function to call for each item. + * @param {String} n Optional name of collection inside the objects to walk for example childNodes. + * @param {String} s Optional scope to execute the function in. + */ + function walk(o, f, n, s) { + s = s || this; + + if (o) { + if (n) { + o = o[n]; + } + + each(o, function(o, i) { + if (f.call(s, o, i, n) === false) { + return false; + } + + walk(o, f, n, s); + }); + } + } + + /** + * Creates a namespace on a specific object. + * + * @method createNS + * @param {String} n Namespace to create for example a.b.c.d. + * @param {Object} o Optional object to add namespace to, defaults to window. + * @return {Object} New namespace object the last item in path. + * @example + * // Create some namespace + * tinymce.createNS('tinymce.somepackage.subpackage'); + * + * // Add a singleton + * var tinymce.somepackage.subpackage.SomeSingleton = { + * method: function() { + * // Some method + * } + * }; + */ + function createNS(n, o) { + var i, v; + + o = o || window; + + n = n.split('.'); + for (i=0; i= 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; + var 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]; + var 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); + } + + function toStringIE() { + return dom.create('body', null, cloneContents()).outerText; + } + + 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, + toStringIE: toStringIE + }); + + return t; + } + + // Older IE versions doesn't let you override toString by it's constructor so we have to stick it in the prototype + Range.prototype.toString = function() { + return this.toStringIE(); + }; + + return Range; +}); + +// Included from: js/tinymce/classes/html/Entities.js + +/** + * Entities.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint bitwise:false */ + +/** + * Entity encoder class. + * + * @class tinymce.html.Entities + * @static + * @version 3.4 + */ +define("tinymce/html/Entities", [ + "tinymce/util/Tools" +], function(Tools) { + var makeMap = Tools.makeMap; + + 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 = { + '\"': '"', // Needs to be escaped since the YUI compressor would otherwise break the code + "'": ''', + '<': '<', + '>': '>', + '&': '&' + }; + + // Reverse lookup table for raw entities + reverseEntities = { + '<': '<', + '>': '>', + '&': '&', + '"': '"', + ''': "'" + }; + + // 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); + + var Entities = { + /** + * Encodes the specified string using raw entities. This means only the required XML base entities will be endoded. + * + * @method encodeRaw + * @param {String} text Text to encode. + * @param {Boolean} attr Optional flag to specify if the text is attribute contents. + * @return {String} Entity encoded text. + */ + encodeRaw: function(text, attr) { + return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { + return baseEntities[chr] || chr; + }); + }, + + /** + * Encoded the specified text with both the attributes and text entities. This function will produce larger text contents + * since it doesn't know if the context is within a attribute or text node. This was added for compatibility + * and is exposed as the DOMUtils.encode function. + * + * @method encodeAllRaw + * @param {String} text Text to encode. + * @return {String} Entity encoded text. + */ + encodeAllRaw: function(text) { + return ('' + text).replace(rawCharsRegExp, function(chr) { + return baseEntities[chr] || chr; + }); + }, + + /** + * Encodes the specified string using numeric entities. The core entities will be + * encoded as named ones but all non lower ascii characters will be encoded into numeric entities. + * + * @method encodeNumeric + * @param {String} text Text to encode. + * @param {Boolean} attr Optional flag to specify if the text is attribute contents. + * @return {String} Entity encoded text. + */ + 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) + ';'; + }); + }, + + /** + * Encodes the specified string using named entities. The core entities will be encoded + * as named ones but all non lower ascii characters will be encoded into named entities. + * + * @method encodeNamed + * @param {String} text Text to encode. + * @param {Boolean} attr Optional flag to specify if the text is attribute contents. + * @param {Object} entities Optional parameter with entities to use. + * @return {String} Entity encoded text. + */ + encodeNamed: function(text, attr, entities) { + entities = entities || namedEntities; + + return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { + return baseEntities[chr] || entities[chr] || chr; + }); + }, + + /** + * Returns an encode function based on the name(s) and it's optional entities. + * + * @method getEncodeFunc + * @param {String} name Comma separated list of encoders for example named,numeric. + * @param {String} entities Optional parameter with entities to use instead of the built in set. + * @return {function} Encode function to be used. + */ + getEncodeFunc: function(name, 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 = 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; + }, + + /** + * Decodes the specified string, this will replace entities with raw UTF characters. + * + * @param {String} text Text to entity decode. + * @return {String} Entity decoded string. + */ + 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); + }); + } + }; + + return Entities; +}); + +// Included from: js/tinymce/classes/Env.js + +/** + * Env.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/Env", [], function() { + var nav = navigator, userAgent = nav.userAgent; + var opera, webkit, ie, gecko, mac, iDevice; + + opera = window.opera && window.opera.buildNumber; + webkit = /WebKit/.test(userAgent); + ie = !webkit && !opera && (/MSIE/gi).test(userAgent) && (/Explorer/gi).test(nav.appName); + ie = ie && /MSIE (\w+)\./.exec(userAgent)[1]; + gecko = !webkit && /Gecko/.test(userAgent); + mac = userAgent.indexOf('Mac') != -1; + iDevice = /(iPad|iPhone)/.test(userAgent); + + // Is a iPad/iPhone and not on iOS5 sniff the WebKit version since older iOS WebKit versions + // says it has contentEditable support but there is no visible caret. + var contentEditable = !iDevice || userAgent.match(/AppleWebKit\/(\d*)/)[1] >= 534; + + return { + /** + * Constant that is true if the browser is Opera. + * + * @property opera + * @type Boolean + * @final + */ + opera: opera, + + /** + * Constant that is true if the browser is WebKit (Safari/Chrome). + * + * @property webKit + * @type Boolean + * @final + */ + webkit: webkit, + + /** + * Constant that is more than zero if the browser is IE. + * + * @property ie + * @type Boolean + * @final + */ + ie: ie, + + /** + * Constant that is true if the browser is Gecko. + * + * @property gecko + * @type Boolean + * @final + */ + gecko: gecko, + + /** + * Constant that is true if the os is Mac OS. + * + * @property mac + * @type Boolean + * @final + */ + mac: mac, + + /** + * Constant that is true if the os is iOS. + * + * @property iOS + * @type Boolean + * @final + */ + iOS: iDevice, + + /** + * Constant that is true if the browser supports editing. + * + * @property contentEditable + * @type Boolean + * @final + */ + contentEditable: contentEditable, + + /** + * Transparent image data url. + * + * @property transparentSrc + * @type Boolean + * @final + */ + transparentSrc: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", + + /** + * Returns true/false if the browser can or can't place the caret after a inline block like an image. + * + * @property noCaretAfter + * @type Boolean + * @final + */ + caretAfter: ie != 8, + + /** + * Constant that is true if the browser supports native DOM Ranges. IE 9+. + * + * @property range + * @type Boolean + */ + range: window.getSelection && "Range" in window + }; +}); + +// Included from: js/tinymce/classes/dom/DOMUtils.js + +/** + * DOMUtils.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Utility class for various DOM manipulation and retrival functions. + * + * @class tinymce.dom.DOMUtils + * @example + * // Add a class to an element by id in the page + * tinymce.DOM.addClass('someid', 'someclass'); + * + * // Add a class to an element by id inside the editor + * tinymce.activeEditor.dom.addClass('someid', 'someclass'); + */ +define("tinymce/dom/DOMUtils", [ + "tinymce/dom/Sizzle", + "tinymce/html/Styles", + "tinymce/dom/EventUtils", + "tinymce/dom/TreeWalker", + "tinymce/dom/Range", + "tinymce/html/Entities", + "tinymce/Env", + "tinymce/util/Tools" +], function(Sizzle, Styles, EventUtils, TreeWalker, Range, Entities, Env, Tools) { + // Shorten names + var each = Tools.each, is = Tools.is, grep = Tools.grep, trim = Tools.trim, extend = Tools.extend; + var isWebKit = Env.webkit, isIE = Env.ie; + var simpleSelectorRe = /^([a-z0-9],?)+$/i; + var whiteSpaceRegExp = /^[ \t\r\n]*$/; + var numericCssMap = Tools.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' '); + + /** + * Constructs a new DOMUtils instance. Consult the Wiki for more details on settings etc for this class. + * + * @constructor + * @method DOMUtils + * @param {Document} d Document reference to bind the utility class to. + * @param {settings} s Optional settings collection. + */ + function DOMUtils(doc, settings) { + var self = this, blockElementsMap; + + self.doc = doc; + self.win = window; + self.files = {}; + self.counter = 0; + self.stdMode = !isIE || doc.documentMode >= 8; + self.boxModel = !isIE || doc.compatMode == "CSS1Compat" || self.stdMode; + self.hasOuterHTML = "outerHTML" in doc.createElement("a"); + + self.settings = settings = extend({ + keep_values: false, + hex_colors: 1 + }, settings); + + self.schema = settings.schema; + self.styles = new Styles({ + url_converter: settings.url_converter, + url_converter_scope: settings.url_converter_scope + }, settings.schema); + + self.fixDoc(doc); + self.events = settings.ownEvents ? new EventUtils(settings.proxy) : EventUtils.Event; + blockElementsMap = settings.schema ? settings.schema.getBlockElements() : {}; + + /** + * Returns true/false if the specified element is a block element or not. + * + * @method isBlock + * @param {Node/String} node Element/Node to check. + * @return {Boolean} True/False state if the node is a block element or not. + */ + self.isBlock = function(node) { + // Fix for #5446 + if (!node) { + return false; + } + + // 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]; + }; + } + + DOMUtils.prototype = { + root: null, + 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" + }, + + 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; + }, + + /** + * Returns the root node of the document this is normally the body but might be a DIV. Parents like getParent will not + * go above the point of this root node. + * + * @method getRoot + * @return {Element} Root element for the utility class. + */ + getRoot: function() { + var self = this; + + return self.get(self.settings.root_element) || self.doc.body; + }, + + /** + * Returns the viewport of the window. + * + * @method getViewPort + * @param {Window} win Optional window to get viewport of. + * @return {Object} Viewport object with fields x, y, w and h. + */ + getViewPort: function(win) { + var doc, rootElm; + + win = !win ? this.win : win; + doc = win.document; + rootElm = this.boxModel ? doc.documentElement : doc.body; + + // Returns viewport size excluding scrollbars + return { + x: win.pageXOffset || rootElm.scrollLeft, + y: win.pageYOffset || rootElm.scrollTop, + w: win.innerWidth || rootElm.clientWidth, + h: win.innerHeight || rootElm.clientHeight + }; + }, + + /** + * Returns the rectangle for a specific element. + * + * @method getRect + * @param {Element/String} elm Element object or element ID to get rectange from. + * @return {object} Rectange for specified element object with x, y, w, h fields. + */ + getRect: function(elm) { + var self = this, pos, size; + + elm = self.get(elm); + pos = self.getPos(elm); + size = self.getSize(elm); + + return { + x: pos.x, y: pos.y, + w: size.w, h: size.h + }; + }, + + /** + * Returns the size dimensions of the specified element. + * + * @method getSize + * @param {Element/String} elm Element object or element ID to get rectange from. + * @return {object} Rectange for specified element object with w, h fields. + */ + getSize: function(elm) { + var self = this, w, h; + + elm = self.get(elm); + w = self.getStyle(elm, 'width'); + h = self.getStyle(elm, '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) || elm.offsetWidth || elm.clientWidth, + h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight + }; + }, + + /** + * Returns a node by the specified selector function. This function will + * loop through all parent nodes and call the specified function for each node. + * If the function then returns true indicating that it has found what it was looking for, the loop execution will then end + * and the node it found will be returned. + * + * @method getParent + * @param {Node/String} node DOM node to search parents on or ID string. + * @param {function} selector Selection function or CSS selector to execute on each node. + * @param {Node} root Optional root element, never go below this point. + * @return {Node} DOM Node or null if it wasn't found. + */ + getParent: function(node, selector, root) { + return this.getParents(node, selector, root, false); + }, + + /** + * Returns a node list of all parents matching the specified selector function or pattern. + * If the function then returns true indicating that it has found what it was looking for and that node will be collected. + * + * @method getParents + * @param {Node/String} node DOM node to search parents on or ID string. + * @param {function} selector Selection function to execute on each node or CSS pattern. + * @param {Node} root Optional root element, never go below this point. + * @return {Array} Array of nodes or null if it wasn't found. + */ + getParents: function(node, selector, root, collect) { + var self = this, selectorVal, result = []; + + node = self.get(node); + collect = collect === undefined; + + // Wrap node name as func + if (is(selector, 'string')) { + selectorVal = selector; + + if (selector === '*') { + selector = function(node) {return node.nodeType == 1;}; + } else { + selector = function(node) { + return self.is(node, selectorVal); + }; + } + } + + while (node) { + if (node == root || !node.nodeType || node.nodeType === 9) { + break; + } + + if (!selector || selector(node)) { + if (collect) { + result.push(node); + } else { + return node; + } + } + + node = node.parentNode; + } + + return collect ? result : null; + }, + + /** + * Returns the specified element by ID or the input element if it isn't a string. + * + * @method get + * @param {String/Element} n Element id to look for or element to just pass though. + * @return {Element} Element matching the specified id or null if it wasn't found. + */ + get: function(elm) { + var name; + + if (elm && this.doc && typeof(elm) == 'string') { + name = elm; + elm = this.doc.getElementById(elm); + + // IE and Opera returns meta elements when they match the specified input ID, but getElementsByName seems to do the trick + if (elm && elm.id !== name) { + return this.doc.getElementsByName(name)[1]; + } + } + + return elm; + }, + + /** + * Returns the next node that matches selector or function + * + * @method getNext + * @param {Node} node Node to find siblings from. + * @param {String/function} selector Selector CSS expression or function. + * @return {Node} Next node item matching the selector or null if it wasn't found. + */ + getNext: function(node, selector) { + return this._findSib(node, selector, 'nextSibling'); + }, + + /** + * Returns the previous node that matches selector or function + * + * @method getPrev + * @param {Node} node Node to find siblings from. + * @param {String/function} selector Selector CSS expression or function. + * @return {Node} Previous node item matching the selector or null if it wasn't found. + */ + getPrev: function(node, selector) { + return this._findSib(node, selector, 'previousSibling'); + }, + + // #ifndef jquery + + /** + * Selects specific elements by a CSS level 3 pattern. For example "div#a1 p.test". + * This function is optimized for the most common patterns needed in TinyMCE but it also performes good enough + * on more complex patterns. + * + * @method select + * @param {String} selector CSS level 3 pattern to select/find elements by. + * @param {Object} scope Optional root element/scope element to search in. + * @return {Array} Array with all matched elements. + * @example + * // Adds a class to all paragraphs in the currently active editor + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass'); + * + * // Adds a class to all spans that has the test class in the currently active editor + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('span.test'), 'someclass') + */ + select: function(selector, scope) { + var self = this; + + //Sizzle.selectors.cacheLength = 0; + return Sizzle(selector, self.get(scope) || self.get(self.settings.root_element) || self.doc, []); + }, + + /** + * Returns true/false if the specified element matches the specified css pattern. + * + * @method is + * @param {Node/NodeList} elm DOM node to match or an array of nodes to match. + * @param {String} selector CSS pattern to match the element agains. + */ + is: function(elm, selector) { + var i; + + // If it isn't an array then try to do some simple selectors instead of Sizzle for to boost performance + if (elm.length === undefined) { + // Simple all selector + if (selector === '*') { + return elm.nodeType == 1; + } + + // Simple selector just elements + if (simpleSelectorRe.test(selector)) { + selector = selector.toLowerCase().split(/,/); + elm = elm.nodeName.toLowerCase(); + + for (i = selector.length - 1; i >= 0; i--) { + if (selector[i] == elm) { + return true; + } + } + + return false; + } + } + + return Sizzle.matches(selector, elm.nodeType ? [elm] : elm).length > 0; + }, + + // #endif + + /** + * Adds the specified element to another element or elements. + * + * @method add + * @param {String/Element/Array} parentElm Element id string, DOM node element or array of id's or elements to add to. + * @param {String/Element} name Name of new element to add or existing element to add. + * @param {Object} attrs Optional object collection with arguments to add to the new element(s). + * @param {String} html Optional inner HTML contents to add for each element. + * @return {Element/Array} Element that got created or array with elements if multiple elements where passed. + * @example + * // Adds a new paragraph to the end of the active editor + * tinymce.activeEditor.dom.add(tinymce.activeEditor.getBody(), 'p', {title: 'my title'}, 'Some content'); + */ + add: function(parentElm, name, attrs, html, create) { + var self = this; + + return this.run(parentElm, function(parentElm) { + var newElm; + + newElm = is(name, 'string') ? self.doc.createElement(name) : name; + self.setAttribs(newElm, attrs); + + if (html) { + if (html.nodeType) { + newElm.appendChild(html); + } else { + self.setHTML(newElm, html); + } + } + + return !create ? parentElm.appendChild(newElm) : newElm; + }); + }, + + /** + * Creates a new element. + * + * @method create + * @param {String} name Name of new element. + * @param {Object} attrs Optional object name/value collection with element attributes. + * @param {String} html Optional HTML string to set as inner HTML of the element. + * @return {Element} HTML DOM node element that got created. + * @example + * // Adds an element where the caret/selection is in the active editor + * var el = tinymce.activeEditor.dom.create('div', {id: 'test', 'class': 'myclass'}, 'some content'); + * tinymce.activeEditor.selection.setNode(el); + */ + create: function(name, attrs, html) { + return this.add(this.doc.createElement(name), name, attrs, html, 1); + }, + + /** + * Create HTML string for element. The element will be closed unless an empty inner HTML string is passed. + * + * @method createHTML + * @param {String} name Name of new element. + * @param {Object} attrs Optional object name/value collection with element attributes. + * @param {String} html Optional HTML string to set as inner HTML of the element. + * @return {String} String with new HTML element like for example: test. + * @example + * // Creates a html chunk and inserts it at the current selection/caret location + * tinymce.activeEditor.selection.setContent(tinymce.activeEditor.dom.createHTML('a', {href: 'test.html'}, 'some line')); + */ + createHTML: function(name, attrs, html) { + var outHtml = '', key; + + outHtml += '<' + name; + + for (key in attrs) { + if (attrs.hasOwnProperty(key)) { + outHtml += ' ' + key + '="' + this.encode(attrs[key]) + '"'; + } + } + + // A call to tinymce.is doesn't work for some odd reason on IE9 possible bug inside their JS runtime + if (typeof(html) != "undefined") { + return outHtml + '>' + html + ''; + } + + return outHtml + ' />'; + }, + + /** + * Creates a document fragment out of the specified HTML string. + * + * @method createFragment + * @param {String} html Html string to create fragment from. + * @return {DocumentFragment} Document fragment node. + */ + createFragment: function(html) { + var frag, node, doc = this.doc, container; + + container = doc.createElement("div"); + frag = doc.createDocumentFragment(); + + if (html) { + container.innerHTML = html; + } + + while ((node = container.firstChild)) { + frag.appendChild(node); + } + + return frag; + }, + + /** + * Removes/deletes the specified element(s) from the DOM. + * + * @method remove + * @param {String/Element/Array} node ID of element or DOM element object or array containing multiple elements/ids. + * @param {Boolean} keep_children Optional state to keep children or not. If set to true all children will be + * placed at the location of the removed element. + * @return {Element/Array} HTML DOM element that got removed or array of elements depending on input. + * @example + * // Removes all paragraphs in the active editor + * tinymce.activeEditor.dom.remove(tinymce.activeEditor.dom.select('p')); + * + * // Removes a element by id in the document + * tinymce.DOM.remove('mydiv'); + */ + 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 (!isIE || child.nodeType !== 3 || child.nodeValue) { + parent.insertBefore(child, node); + } else { + node.removeChild(child); + } + } + } + + return parent.removeChild(node); + }); + }, + + /** + * Sets the CSS style value on a HTML element. The name can be a camelcase string + * or the CSS style name like background-color. + * + * @method setStyle + * @param {String/Element/Array} n HTML element/Element ID or Array of elements/ids to set CSS style value on. + * @param {String} na Name of the style value to set. + * @param {String} v Value to set on the style. + * @example + * // Sets a style value on all paragraphs in the currently active editor + * tinymce.activeEditor.dom.setStyle(tinymce.activeEditor.dom.select('p'), 'background-color', 'red'); + * + * // Sets a style value to an element by id in the current document + * tinymce.DOM.setStyle('mydiv', 'background-color', 'red'); + */ + setStyle: function(elm, name, value) { + return this.run(elm, function(elm) { + var self = this, style, key; + + if (name) { + if (typeof(name) === 'string') { + style = elm.style; + + // Camelcase it, if needed + name = name.replace(/-(\D)/g, function(a, b) { + return b.toUpperCase(); + }); + + // Default px suffix on these + if (typeof(value) === 'number' && !numericCssMap[name]) { + value += 'px'; + } + + // IE specific opacity + if (name === "opacity" && elm.runtimeStyle && typeof(elm.runtimeStyle.opacity) === "undefined") { + style.filter = value === '' ? '' : "alpha(opacity=" + (value * 100) + ")"; + } + + try { + style[name] = value; + } catch (ex) { + // Ignore IE errors + } + + // Force update of the style data + if (self.settings.update_styles) { + elm.removeAttribute('data-mce-style'); + } + } else { + for (key in name) { + self.setStyle(elm, key, name[key]); + } + } + } + }); + }, + + /** + * Returns the current style or runtime/computed value of a element. + * + * @method getStyle + * @param {String/Element} elm HTML element or element id string to get style from. + * @param {String} name Style name to return. + * @param {Boolean} computed Computed style. + * @return {String} Current style or computed style value of a element. + */ + getStyle: function(elm, name, computed) { + elm = this.get(elm); + + if (!elm) { + return; + } + + // W3C + if (this.doc.defaultView && computed) { + // Remove camelcase + name = name.replace(/[A-Z]/g, function(a){ + return '-' + a; + }); + + try { + return this.doc.defaultView.getComputedStyle(elm, null).getPropertyValue(name); + } catch (ex) { + // Old safari might fail + return null; + } + } + + // Camelcase it, if needed + name = name.replace(/-(\D)/g, function(a, b) { + return b.toUpperCase(); + }); + + if (name == 'float') { + name = isIE ? 'styleFloat' : 'cssFloat'; + } + + // IE & Opera + if (name.currentStyle && computed) { + return elm.currentStyle[name]; + } + + return elm.style ? elm.style[name] : undefined; + }, + + /** + * Sets multiple styles on the specified element(s). + * + * @method setStyles + * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to set styles on. + * @param {Object} o Name/Value collection of style items to add to the element(s). + * @example + * // Sets styles on all paragraphs in the currently active editor + * tinymce.activeEditor.dom.setStyles(tinymce.activeEditor.dom.select('p'), {'background-color': 'red', 'color': 'green'}); + * + * // Sets styles to an element by id in the current document + * tinymce.DOM.setStyles('mydiv', {'background-color': 'red', 'color': 'green'}); + */ + setStyles: function(elm, styles) { + this.setStyle(elm, styles); + }, + + css: function(elm, name, value) { + this.setStyle(elm, name, value); + }, + + /** + * Removes all attributes from an element or elements. + * + * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to remove attributes from. + */ + 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)); + } + }); + }, + + /** + * Sets the specified attributes value of a element or elements. + * + * @method setAttrib + * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to set attribute on. + * @param {String} n Name of attribute to set. + * @param {String} v Value to set on the attribute of this value is falsy like null 0 or '' it will remove the attribute instead. + * @example + * // Sets an attribute to all paragraphs in the active editor + * tinymce.activeEditor.dom.setAttrib(tinymce.activeEditor.dom.select('p'), 'class', 'myclass'); + * + * // Sets an attribute to a specific element in the current page + * tinymce.dom.setAttrib('mydiv', 'class', 'myclass'); + */ + setAttrib: function(e, n, v) { + var t = this; + + // Whats the point + if (!e || !n) { + return; + } + + 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) { + 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 (originalValue != v && s.onSetAttrib) { + s.onSetAttrib({attrElm: e, attrName: n, attrValue: v}); + } + }); + }, + + /** + * Sets the specified attributes of a element or elements. + * + * @method setAttribs + * @param {Element/String/Array} elm DOM element, element id string or array of elements/ids to set attributes on. + * @param {Object} attrs Name/Value collection of attribute items to add to the element(s). + * @example + * // Sets some attributes to all paragraphs in the active editor + * tinymce.activeEditor.dom.setAttribs(tinymce.activeEditor.dom.select('p'), {'class': 'myclass', title: 'some title'}); + * + * // Sets some attributes to a specific element in the current page + * tinymce.DOM.setAttribs('mydiv', {'class': 'myclass', title: 'some title'}); + */ + setAttribs: function(elm, attrs) { + var self = this; + + return this.run(elm, function(elm) { + each(attrs, function(value, name) { + self.setAttrib(elm, name, value); + }); + }); + }, + + /** + * Returns the specified attribute by name. + * + * @method getAttrib + * @param {String/Element} elm Element string id or DOM element to get attribute from. + * @param {String} name Name of attribute to get. + * @param {String} defaultVal Optional default value to return if the attribute didn't exist. + * @return {String} Attribute value string, default value or null if the attribute wasn't found. + */ + getAttrib: function(elm, name, defaultVal) { + var value, self = this, undef; + + elm = self.get(elm); + + if (!elm || elm.nodeType !== 1) { + return defaultVal === undef ? false : defaultVal; + } + + if (!is(defaultVal)) { + defaultVal = ''; + } + + // Try the mce variant for these + if (/^(src|href|style|coords|shape)$/.test(name)) { + value = elm.getAttribute("data-mce-" + name); + + if (value) { + return value; + } + } + + if (isIE && self.props[name]) { + value = elm[self.props[name]]; + value = value && value.nodeValue ? value.nodeValue : value; + } + + if (!value) { + value = elm.getAttribute(name, 2); + } + + // Check boolean attribs + if (/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noshade|nowrap|readonly|selected)$/.test(name)) { + if (elm[self.props[name]] === true && value === '') { + return name; + } + + return value ? name : ''; + } + + // Inner input elements will override attributes on form elements + if (elm.nodeName === "FORM" && elm.getAttributeNode(name)) { + return elm.getAttributeNode(name).nodeValue; + } + + if (name === 'style') { + value = value || elm.style.cssText; + + if (value) { + value = self.serializeStyle(self.parseStyle(value), elm.nodeName); + + if (self.settings.keep_values) { + elm.setAttribute('data-mce-style', value); + } + } + } + + // Remove Apple and WebKit stuff + if (isWebKit && name === "class" && value) { + value = value.replace(/(apple|webkit)\-[a-z\-]+/gi, ''); + } + + // Handle IE issues + if (isIE) { + switch (name) { + case 'rowspan': + case 'colspan': + // IE returns 1 as default value + if (value === 1) { + value = ''; + } + + break; + + case 'size': + // IE returns +0 as default value for size + if (value === '+0' || value === 20 || value === 0) { + value = ''; + } + + break; + + case 'width': + case 'height': + case 'vspace': + case 'checked': + case 'disabled': + case 'readonly': + if (value === 0) { + value = ''; + } + + break; + + case 'hspace': + // IE returns -1 as default value + if (value === -1) { + value = ''; + } + + break; + + case 'maxlength': + case 'tabindex': + // IE returns default value + if (value === 32768 || value === 2147483647 || value === '32768') { + value = ''; + } + + break; + + case 'multiple': + case 'compact': + case 'noshade': + case 'nowrap': + if (value === 65535) { + return name; + } + + return defaultVal; + + case 'shape': + value = value.toLowerCase(); + break; + + default: + // IE has odd anonymous function for event attributes + if (name.indexOf('on') === 0 && value) { + value = ('' + value).replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/, '$1'); + } + } + } + + return (value !== undef && value !== null && value !== '') ? '' + value : defaultVal; + }, + + /** + * Returns the absolute x, y position of a node. The position will be returned in a object with x, y fields. + * + * @method getPos + * @param {Element/String} n HTML element or element id to get x, y position from. + * @param {Element} ro Optional root element to stop calculations at. + * @return {object} Absolute position of the specified element object with x, y fields. + */ + getPos: function(elm, rootElm) { + var self = this, x = 0, y = 0, offsetParent, doc = self.doc, pos; + + elm = self.get(elm); + rootElm = rootElm || doc.body; + + if (elm) { + // Use getBoundingClientRect if it exists since it's faster than looping offset nodes + if (rootElm === doc.body && elm.getBoundingClientRect) { + pos = elm.getBoundingClientRect(); + rootElm = self.boxModel ? doc.documentElement : doc.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 = pos.left + (doc.documentElement.scrollLeft || doc.body.scrollLeft) - rootElm.clientTop; + y = pos.top + (doc.documentElement.scrollTop || doc.body.scrollTop) - rootElm.clientLeft; + + return {x: x, y: y}; + } + + offsetParent = elm; + while (offsetParent && offsetParent != rootElm && offsetParent.nodeType) { + x += offsetParent.offsetLeft || 0; + y += offsetParent.offsetTop || 0; + offsetParent = offsetParent.offsetParent; + } + + offsetParent = elm.parentNode; + while (offsetParent && offsetParent != rootElm && offsetParent.nodeType) { + x -= offsetParent.scrollLeft || 0; + y -= offsetParent.scrollTop || 0; + offsetParent = offsetParent.parentNode; + } + } + + return {x: x, y: y}; + }, + + /** + * Parses the specified style value into an object collection. This parser will also + * merge and remove any redundant items that browsers might have added. It will also convert non hex + * colors to hex values. Urls inside the styles will also be converted to absolute/relative based on settings. + * + * @method parseStyle + * @param {String} cssText Style value to parse for example: border:1px solid red;. + * @return {Object} Object representation of that style like {border: '1px solid red'} + */ + parseStyle: function(cssText) { + return this.styles.parse(cssText); + }, + + /** + * Serializes the specified style object into a string. + * + * @method serializeStyle + * @param {Object} styles Object to serialize as string for example: {border: '1px solid red'} + * @param {String} name Optional element name. + * @return {String} String representation of the style object for example: border: 1px solid red. + */ + serializeStyle: function(styles, name) { + return this.styles.serialize(styles, name); + }, + + /** + * Adds a style element at the top of the document with the specified cssText content. + * + * @method addStyle + * @param {String} cssText CSS Text style to add to top of head of document. + */ + addStyle: function(cssText) { + var self = this, doc = self.doc, head, styleElm; + + // Prevent inline from loading the same styles twice + if (self !== DOMUtils.DOM && doc === document) { + var addedStyles = DOMUtils.DOM.addedStyles; + + addedStyles = addedStyles || []; + if (addedStyles[cssText]) { + return; + } + + addedStyles[cssText] = true; + DOMUtils.DOM.addedStyles = addedStyles; + } + + // Create style element if needed + styleElm = doc.getElementById('mceDefaultStyles'); + if (!styleElm) { + styleElm = doc.createElement('style'), + styleElm.id = 'mceDefaultStyles'; + styleElm.type = 'text/css'; + + head = doc.getElementsByTagName('head')[0]; + if (head.firstChild) { + head.insertBefore(styleElm, head.firstChild); + } else { + head.appendChild(styleElm); + } + } + + // Append style data to old or new style element + if (styleElm.styleSheet) { + styleElm.styleSheet.cssText += cssText; + } else { + styleElm.appendChild(doc.createTextNode(cssText)); + } + }, + + /** + * Imports/loads the specified CSS file into the document bound to the class. + * + * @method loadCSS + * @param {String} u URL to CSS file to load. + * @example + * // Loads a CSS file dynamically into the current document + * tinymce.DOM.loadCSS('somepath/some.css'); + * + * // Loads a CSS file into the currently active editor instance + * tinymce.activeEditor.dom.loadCSS('somepath/some.css'); + * + * // Loads a CSS file into an editor instance by id + * tinymce.get('someid').dom.loadCSS('somepath/some.css'); + * + * // Loads multiple CSS files into the current document + * tinymce.DOM.loadCSS('somepath/some.css,somepath/someother.css'); + */ + loadCSS: function(url) { + var self = this, doc = self.doc, head; + + // Prevent inline from loading the same CSS file twice + if (self !== DOMUtils.DOM && doc === document) { + DOMUtils.DOM.loadCSS(url); + return; + } + + if (!url) { + url = ''; + } + + head = doc.getElementsByTagName('head')[0]; + + each(url.split(','), function(url) { + var link; + + if (self.files[url]) { + return; + } + + self.files[url] = true; + link = self.create('link', {rel: 'stylesheet', href: url}); + + // 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 && doc.documentMode && doc.recalc) { + link.onload = function() { + if (doc.recalc) { + doc.recalc(); + } + + link.onload = null; + }; + } + + head.appendChild(link); + }); + }, + + /** + * Adds a class to the specified element or elements. + * + * @method addClass + * @param {String/Element/Array} elm Element ID string or DOM element or array with elements or IDs. + * @param {String} cls Class name to add to each element. + * @return {String/Array} String with new class value or array with new class values for all elements. + * @example + * // Adds a class to all paragraphs in the active editor + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'myclass'); + * + * // Adds a class to a specific element in the current page + * tinymce.DOM.addClass('mydiv', 'myclass'); + */ + addClass: function(elm, cls) { + return this.run(elm, function(elm) { + var clsVal; + + if (!cls) { + return 0; + } + + if (this.hasClass(elm, cls)) { + return elm.className; + } + + clsVal = this.removeClass(elm, cls); + elm.className = clsVal = (clsVal !== '' ? (clsVal + ' ') : '') + cls; + + return clsVal; + }); + }, + + /** + * Removes a class from the specified element or elements. + * + * @method removeClass + * @param {String/Element/Array} elm Element ID string or DOM element or array with elements or IDs. + * @param {String} cls Class name to remove to each element. + * @return {String/Array} String with new class value or array with new class values for all elements. + * @example + * // Removes a class from all paragraphs in the active editor + * tinymce.activeEditor.dom.removeClass(tinymce.activeEditor.dom.select('p'), 'myclass'); + * + * // Removes a class from a specific element in the current page + * tinymce.DOM.removeClass('mydiv', 'myclass'); + */ + removeClass: function(elm, cls) { + var self = this, re; + + return self.run(elm, function(elm) { + var val; + + if (self.hasClass(elm, cls)) { + if (!re) { + re = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", "g"); + } + + val = elm.className.replace(re, ' '); + val = trim(val != ' ' ? val : ''); + + elm.className = val; + + // Empty class attr + if (!val) { + elm.removeAttribute('class'); + elm.removeAttribute('className'); + } + + return val; + } + + return elm.className; + }); + }, + + /** + * Returns true if the specified element has the specified class. + * + * @method hasClass + * @param {String/Element} n HTML element or element id string to check CSS class on. + * @param {String} c CSS class to check for. + * @return {Boolean} true/false if the specified element has the specified class. + */ + hasClass: function(elm, cls) { + elm = this.get(elm); + + if (!elm || !cls) { + return false; + } + + return (' ' + elm.className + ' ').indexOf(' ' + cls + ' ') !== -1; + }, + + /** + * Toggles the specified class on/off. + * + * @method toggleClass + * @param {Element} elm Element to toggle class on. + * @param {[type]} cls Class to toggle on/off. + * @param {[type]} state Optional state to set. + */ + toggleClass: function(elm, cls, state) { + state = state === undefined ? !this.hasClass(elm, cls) : state; + + if (this.hasClass(elm, cls) !== state) { + if (state) { + this.addClass(elm, cls); + } else { + this.removeClass(elm, cls); + } + } + }, + + /** + * Shows the specified element(s) by ID by setting the "display" style. + * + * @method show + * @param {String/Element/Array} elm ID of DOM element or DOM element or array with elements or IDs to show. + */ + show: function(elm) { + return this.setStyle(elm, 'display', 'block'); + }, + + /** + * Hides the specified element(s) by ID by setting the "display" style. + * + * @method hide + * @param {String/Element/Array} e ID of DOM element or DOM element or array with elements or IDs to hide. + * @example + * // Hides a element by id in the document + * tinymce.DOM.hide('myid'); + */ + hide: function(elm) { + return this.setStyle(elm, 'display', 'none'); + }, + + /** + * Returns true/false if the element is hidden or not by checking the "display" style. + * + * @method isHidden + * @param {String/Element} e Id or element to check display state on. + * @return {Boolean} true/false if the element is hidden or not. + */ + isHidden: function(elm) { + elm = this.get(elm); + + return !elm || elm.style.display == 'none' || this.getStyle(elm, 'display') == 'none'; + }, + + /** + * Returns a unique id. This can be useful when generating elements on the fly. + * This method will not check if the element allready exists. + * + * @method uniqueId + * @param {String} prefix Optional prefix to add infront of all ids defaults to "mce_". + * @return {String} Unique id. + */ + uniqueId: function(prefix) { + return (!prefix ? 'mce_' : prefix) + (this.counter++); + }, + + /** + * Sets the specified HTML content inside the element or elements. The HTML will first be processed this means + * URLs will get converted, hex color values fixed etc. Check processHTML for details. + * + * @method setHTML + * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to set HTML inside. + * @param {String} h HTML content to set as inner HTML of the element. + * @example + * // Sets the inner HTML of all paragraphs in the active editor + * tinymce.activeEditor.dom.setHTML(tinymce.activeEditor.dom.select('p'), 'some inner html'); + * + * // Sets the inner HTML of a element by id in the document + * tinymce.DOM.setHTML('mydiv', 'some inner html'); + */ + 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 = '
    ' + 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 + var newElement = self.create('div'); + newElement.innerHTML = '
    ' + html; + + // Add all children from div to target + each (grep(newElement.childNodes), function(node, i) { + // Skip br element + if (i && element.canHaveHTML) { + element.appendChild(node); + } + }); + } + } else { + element.innerHTML = html; + } + + return html; + }); + }, + + /** + * Returns the outer HTML of an element. + * + * @method getOuterHTML + * @param {String/Element} elm Element ID or element object to get outer HTML from. + * @return {String} Outer HTML string. + * @example + * tinymce.DOM.getOuterHTML(editorElement); + * tinymce.activeEditor.getOuterHTML(tinymce.activeEditor.getBody()); + */ + 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; + }, + + /** + * Sets the specified outer HTML on a element or elements. + * + * @method setOuterHTML + * @param {Element/String/Array} elm DOM element, element id string or array of elements/ids to set outer HTML on. + * @param {Object} html HTML code to set as outer value for the element. + * @param {Document} doc Optional document scope to use in this process defaults to the document of the DOM class. + * @example + * // Sets the outer HTML of all paragraphs in the active editor + * tinymce.activeEditor.dom.setOuterHTML(tinymce.activeEditor.dom.select('p'), '
    some html
    '); + * + * // Sets the outer HTML of a element by id in the document + * tinymce.DOM.setOuterHTML('mydiv', '
    some html
    '); + */ + setOuterHTML: function(elm, html, doc) { + var self = this; + + return self.run(elm, function(elm) { + function set() { + var node, tempElm; + + tempElm = doc.createElement("body"); + tempElm.innerHTML = html; + + node = tempElm.lastChild; + while (node) { + self.insertAfter(node.cloneNode(true), elm); + node = node.previousSibling; + } + + self.remove(elm); + } + + // Only set HTML on elements + if (elm.nodeType == 1) { + doc = doc || elm.ownerDocument || self.doc; + + if (isIE) { + try { + // Try outerHTML for IE it sometimes produces an unknown runtime error + if (elm.nodeType == 1 && self.hasOuterHTML) { + elm.outerHTML = html; + } else { + set(); + } + } catch (ex) { + // Fix for unknown runtime error + set(); + } + } else { + set(); + } + } + }); + }, + + /** + * Entity decode a string, resolves any HTML entities like å. + * + * @method decode + * @param {String} s String to decode entities on. + * @return {String} Entity decoded string. + */ + decode: Entities.decode, + + /** + * Entity encodes a string, encodes the most common entities <>"& into entities. + * + * @method encode + * @param {String} text String to encode with entities. + * @return {String} Entity encoded string. + */ + encode: Entities.encodeAllRaw, + + /** + * Inserts a element after the reference element. + * + * @method insertAfter + * @param {Element} node Element to insert after the reference. + * @param {Element/String/Array} reference_node Reference element, element id or array of elements to insert after. + * @return {Element/Array} Element that got added or an array with elements. + */ + 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; + }); + }, + + /** + * Replaces the specified element or elements with the specified element, the new element will + * be cloned if multiple inputs elements are passed. + * + * @method replace + * @param {Element} newElm New element to replace old ones with. + * @param {Element/String/Array} oldELm Element DOM node, element id or array of elements or ids to replace. + * @param {Boolean} k Optional keep children state, if set to true child nodes from the old object will be added to new ones. + */ + replace: function(newElm, oldElm, keepChildren) { + var self = this; + + return self.run(oldElm, function(oldElm) { + if (is(oldElm, 'array')) { + newElm = newElm.cloneNode(true); + } + + if (keepChildren) { + each(grep(oldElm.childNodes), function(node) { + newElm.appendChild(node); + }); + } + + return oldElm.parentNode.replaceChild(newElm, oldElm); + }); + }, + + /** + * Renames the specified element to a new name and keep it's attributes and children. + * + * @method rename + * @param {Element} elm Element to rename. + * @param {String} name Name of the new element. + * @return New element or the old element if it needed renaming. + */ + rename: function(elm, name) { + var self = this, newElm; + + if (elm.nodeName != name.toUpperCase()) { + // Rename block element + newElm = self.create(name); + + // Copy attribs to new block + each(self.getAttribs(elm), function(attr_node) { + self.setAttrib(newElm, attr_node.nodeName, self.getAttrib(elm, attr_node.nodeName)); + }); + + // Replace block + self.replace(newElm, elm, 1); + } + + return newElm || elm; + }, + + /** + * Find the common ancestor of two elements. This is a shorter method than using the DOM Range logic. + * + * @method findCommonAncestor + * @param {Element} a Element to find common ancestor of. + * @param {Element} b Element to find common ancestor of. + * @return {Element} Common ancestor element of the two input elements. + */ + 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; + }, + + /** + * Parses the specified RGB color value and returns a hex version of that color. + * + * @method toHex + * @param {String} rgbVal RGB string value like rgb(1,2,3) + * @return {String} Hex version of that RGB value like #FF00FF. + */ + toHex: function(rgbVal) { + return this.styles.toHex(Tools.trim(rgbVal)); + }, + + /** + * Returns a array of all single CSS classes in the document. A single CSS class is a simple + * rule like ".class" complex ones like "div td.class" will not be added to output. + * + * @method getClasses + * @return {Array} Array with class objects each object has a class field might be other fields in the future. + */ + getClasses: function() { + var self = this, classList = [], lookup = {}, filter = self.settings.class_filter, oldVal; + + if (self.classes) { + return self.classes; + } + + function addClasses(stylesheet) { + // IE style imports + each(stylesheet.imports, function(r) { + addClasses(r); + }); + + each(stylesheet.cssRules || stylesheet.rules, function(rule) { + // Real type or fake it on IE + switch (rule.type || 1) { + // Rule + case 1: + if (rule.selectorText) { + each(rule.selectorText.split(','), function(value) { + value = value.replace(/^\s*|\s*$|^\s\./g, ""); + + // Is internal or it doesn't contain a class + if (/\.mce/.test(value) || !/\.[\w\-]+$/.test(value)) { + return; + } + + // Remove everything but class name + oldVal = value; + value = value.replace(/.*\.([a-z0-9_\-]+).*/i, '$1'); + + // Filter classes + if (filter && !(value = filter(value, oldVal))) { + return; + } + + if (!lookup[value]) { + classList.push({'class': value}); + lookup[value] = 1; + } + }); + } + break; + + // Import + case 3: + addClasses(rule.styleSheet); + break; + } + }); + } + + try { + each(self.doc.styleSheets, addClasses); + } catch (ex) { + // Ignore + } + + if (classList.length > 0) { + self.classes = classList; + } + + return classList; + }, + + /** + * Executes the specified function on the element by id or dom element node or array of elements/id. + * + * @method run + * @param {String/Element/Array} Element ID or DOM element object or array with ids or elements. + * @param {function} f Function to execute for each item. + * @param {Object} s Optional scope to execute the function in. + * @return {Object/Array} Single object or array with objects depending on multiple input or not. + */ + run: function(elm, func, scope) { + var self = this, result; + + if (typeof(elm) === 'string') { + elm = self.get(elm); + } + + if (!elm) { + return false; + } + + scope = scope || this; + if (!elm.nodeType && (elm.length || elm.length === 0)) { + result = []; + + each(elm, function(elm, i) { + if (elm) { + if (typeof(elm) == 'string') { + elm = self.get(elm); + } + + result.push(func.call(scope, elm, i)); + } + }); + + return result; + } + + return func.call(scope, elm); + }, + + /** + * Returns an NodeList with attributes for the element. + * + * @method getAttribs + * @param {HTMLElement/string} elm Element node or string id to get attributes from. + * @return {NodeList} NodeList with attributes. + */ + getAttribs: function(elm) { + var attrs; + + elm = this.get(elm); + + if (!elm) { + return []; + } + + if (isIE) { + attrs = []; + + // Object will throw exception in IE + if (elm.nodeName == 'OBJECT') { + return elm.attributes; + } + + // IE doesn't keep the selected attribute if you clone option elements + if (elm.nodeName === 'OPTION' && this.getAttrib(elm, 'selected')) { + attrs.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 + var attrRegExp = /<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi; + elm.cloneNode(false).outerHTML.replace(attrRegExp, '').replace(/[\w:\-]+/gi, function(a) { + attrs.push({specified: 1, nodeName: a}); + }); + + return attrs; + } + + return elm.attributes; + }, + + /** + * Returns true/false if the specified node is to be considered empty or not. + * + * @example + * tinymce.DOM.isEmpty(node, {img: true}); + * @method isEmpty + * @param {Object} elements Optional name/value object with elements that are automatically treated as non empty elements. + * @return {Boolean} true/false if the node is empty or not. + */ + isEmpty: function(node, elements) { + var self = this, i, attributes, type, walker, name, brCount = 0; + + node = node.firstChild; + if (node) { + walker = new 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 + name = node.nodeName.toLowerCase(); + if (elements && elements[name]) { + // Ignore single BR elements in blocks like


    or


    + if (name === 'br') { + brCount++; + continue; + } + + return false; + } + + // Keep elements with data-bookmark attributes or name attribute like + 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; + }, + + /** + * Created a new DOM Range object. This will use the native DOM Range API if it's + * available if it's not it will fallback to the custom TinyMCE implementation. + * + * @method createRng + * @return {DOMRange} DOM Range object. + * @example + * var rng = tinymce.DOM.createRng(); + * alert(rng.startContainer + "," + rng.startOffset); + */ + createRng: function() { + var doc = this.doc; + + return doc.createRange ? doc.createRange() : new Range(this); + }, + + /** + * Returns the index of the specified node within it's parent. + * + * @param {Node} node Node to look for. + * @param {boolean} normalized Optional true/false state if the index is what it would be after a normalization. + * @return {Number} Index of the specified node. + */ + 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; + }, + + /** + * Splits an element into two new elements and places the specified split + * element or element between the new ones. For example splitting the paragraph at the bold element in + * this example

    abcabc123

    would produce

    abc

    abc

    123

    . + * + * @method split + * @param {Element} parentElm Parent element to split. + * @param {Element} splitElm Element to split at. + * @param {Element} replacementElm Optional replacement element to replace the split element by. + * @return {Element} Returns the split element or the replacement element if that is specified. + */ + split: function(parentElm, splitElm, replacementElm) { + var self = this, r = self.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: + //

    text 1CHOPtext 2

    + // would produce: + //

    text 1

    CHOP

    text 2

    + // this function will then trim of empty edges and produce: + //

    text 1

    CHOP

    text 2

    + function trimNode(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--) { + trimNode(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 "

    " + // Also keep text nodes with only spaces if surrounded by spans. + // eg. "

    a b

    " should keep space between a and b + var trimmedLength = trim(node.nodeValue).length; + if (!self.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; + + // TODO fix this complex if + 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; + } + } + + self.remove(node); + } + + return node; + } + + if (parentElm && splitElm) { + // Get before chunk + r.setStart(parentElm.parentNode, self.nodeIndex(parentElm)); + r.setEnd(splitElm.parentNode, self.nodeIndex(splitElm)); + bef = r.extractContents(); + + // Get after chunk + r = self.createRng(); + r.setStart(splitElm.parentNode, self.nodeIndex(splitElm) + 1); + r.setEnd(parentElm.parentNode, self.nodeIndex(parentElm) + 1); + aft = r.extractContents(); + + // Insert before chunk + pa = parentElm.parentNode; + pa.insertBefore(trimNode(bef), parentElm); + + // Insert middle chunk + if (replacementElm) { + pa.replaceChild(replacementElm, splitElm); + } else { + pa.insertBefore(splitElm, parentElm); + } + + // Insert after chunk + pa.insertBefore(trimNode(aft), parentElm); + self.remove(parentElm); + + return replacementElm || splitElm; + } + }, + + /** + * Adds an event handler to the specified object. + * + * @method bind + * @param {Element/Document/Window/Array/String} o Object or element id string to add event + * handler to or an array of elements/ids/documents. + * @param {String} n Name of event handler to add for example: click. + * @param {function} f Function to execute when the event occurs. + * @param {Object} s Optional scope to execute the function in. + * @return {function} Function callback handler the same as the one passed in. + */ + bind: function(target, name, func, scope) { + return this.events.bind(target, name, func, scope || this); + }, + + /** + * Removes the specified event handler by name and function from a element or collection of elements. + * + * @method unbind + * @param {String/Element/Array} o Element ID string or HTML element or an array of elements or ids to remove handler from. + * @param {String} n Event handler name like for example: "click" + * @param {function} f Function to remove. + * @return {bool/Array} Bool state if true if the handler was removed or an array with states if multiple elements where passed in. + */ + unbind: function(target, name, func) { + return this.events.unbind(target, name, func); + }, + + /** + * Fires the specified event name with object on target. + * + * @method fire + * @param {Node/Document/Window} target Target element or object to fire event on. + * @param {String} name Name of the event to fire. + * @param {Object} evt Event object to send. + * @return {Event} Event object. + */ + 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; + }, + + /** + * Destroys all internal references to the DOM to solve IE leak issues. + * + * @method destroy + */ + destroy: function() { + var self = this; + + self.win = self.doc = self.root = self.events = self.frag = null; + }, + + // #ifdef debug + + dumpRng: function(r) { + return ( + 'startContainer: ' + r.startContainer.nodeName + + ', startOffset: ' + r.startOffset + + ', endContainer: ' + r.endContainer.nodeName + + ', endOffset: ' + r.endOffset + ); + }, + + // #endif + + _findSib: function(node, selector, name) { + var self = this, func = selector; + + if (node) { + // If expression make a function of it using is + if (typeof(func) == 'string') { + func = function(node) { + return self.is(node, selector); + }; + } + + // Loop all siblings + for (node = node[name]; node; node = node[name]) { + if (func(node)) { + return node; + } + } + } + + return null; + } + }; + + /** + * Instance of DOMUtils for the current document. + * + * @property DOM + * @member tinymce + * @type tinymce.dom.DOMUtils + * @example + * // Example of how to add a class to some element by id + * tinymce.DOM.addClass('someid', 'someclass'); + */ + DOMUtils.DOM = new DOMUtils(document); + + return DOMUtils; +}); + +// Included from: js/tinymce/classes/dom/ScriptLoader.js + +/** + * ScriptLoader.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*globals console*/ + +/** + * This class handles asynchronous/synchronous loading of JavaScript files it will execute callbacks + * when various items gets loaded. This class is useful to load external JavaScript files. + * + * @class tinymce.dom.ScriptLoader + * @example + * // Load a script from a specific URL using the global script loader + * tinymce.ScriptLoader.load('somescript.js'); + * + * // Load a script using a unique instance of the script loader + * var scriptLoader = new tinymce.dom.ScriptLoader(); + * + * scriptLoader.load('somescript.js'); + * + * // Load multiple scripts + * var scriptLoader = new tinymce.dom.ScriptLoader(); + * + * scriptLoader.add('somescript1.js'); + * scriptLoader.add('somescript2.js'); + * scriptLoader.add('somescript3.js'); + * + * scriptLoader.loadQueue(function() { + * alert('All scripts are now loaded.'); + * }); + */ +define("tinymce/dom/ScriptLoader", [ + "tinymce/dom/DOMUtils", + "tinymce/util/Tools" +], function(DOMUtils, Tools) { + var DOM = DOMUtils.DOM; + var each = Tools.each, grep = Tools.grep; + + function ScriptLoader() { + var QUEUED = 0, + LOADING = 1, + LOADED = 2, + states = {}, + queue = [], + scriptLoadedCallbacks = {}, + queueLoadedCallbacks = [], + loading = 0, + undef; + + /** + * Loads a specific script directly without adding it to the load queue. + * + * @method load + * @param {String} url Absolute URL to script to add. + * @param {function} callback Optional callback function to execute ones this script gets loaded. + * @param {Object} scope Optional scope to execute callback in. + */ + function loadScript(url, callback) { + var dom = DOM, elm, 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(); + + // Create new script element + elm = document.createElement('script'); + elm.id = id; + elm.type = 'text/javascript'; + elm.src = url; + + elm.onload = done; + elm.onreadystatechange = function() { + if (/loaded|complete/.test(elm.readyState)) { + done(); + } + }; + + // Add onerror event will get fired on some browsers but not all of them + elm.onerror = error; + + // Add script to document + (document.getElementsByTagName('head')[0] || document.body).appendChild(elm); + } + + /** + * Returns true/false if a script has been loaded or not. + * + * @method isDone + * @param {String} url URL to check for. + * @return [Boolean} true/false if the URL is loaded. + */ + this.isDone = function(url) { + return states[url] == LOADED; + }; + + /** + * Marks a specific script to be loaded. This can be useful if a script got loaded outside + * the script loader or to skip it from loading some script. + * + * @method markDone + * @param {string} u Absolute URL to the script to mark as loaded. + */ + this.markDone = function(url) { + states[url] = LOADED; + }; + + /** + * Adds a specific script to the load queue of the script loader. + * + * @method add + * @param {String} url Absolute URL to script to add. + * @param {function} callback Optional callback function to execute ones this script gets loaded. + * @param {Object} scope Optional scope to execute callback in. + */ + this.add = this.load = function(url, callback, scope) { + var 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 + }); + } + }; + + /** + * Starts the loading of the queue. + * + * @method loadQueue + * @param {function} callback Optional callback to execute when all queued items are loaded. + * @param {Object} scope Optional scope to execute the callback in. + */ + this.loadQueue = function(callback, scope) { + this.loadScripts(queue, callback, scope); + }; + + /** + * Loads the specified queue of files and executes the callback ones they are loaded. + * This method is generally not used outside this class but it might be useful in some scenarios. + * + * @method loadScripts + * @param {Array} scripts Array of queue items to load. + * @param {function} callback Optional callback to execute ones all items are loaded. + * @param {Object} scope Optional scope to execute callback in. + */ + this.loadScripts = function(scripts, callback, scope) { + var loadScripts; + + function execScriptLoadedCallbacks(url) { + // Execute URL callback functions + each(scriptLoadedCallbacks[url], function(callback) { + callback.func.call(callback.scope); + }); + + scriptLoadedCallbacks[url] = undef; + } + + queueLoadedCallbacks.push({ + func: callback, + scope: scope || this + }); + + loadScripts = function() { + var loadingScripts = grep(scripts); + + // Current scripts has been handled + scripts.length = 0; + + // Load scripts that needs to be loaded + 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) { + each(queueLoadedCallbacks, function(callback) { + callback.func.call(callback.scope); + }); + + queueLoadedCallbacks.length = 0; + } + }; + + loadScripts(); + }; + } + + ScriptLoader.ScriptLoader = new ScriptLoader(); + + return ScriptLoader; +}); + +// Included from: js/tinymce/classes/AddOnManager.js + +/** + * AddOnManager.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles the loading of themes/plugins or other add-ons and their language packs. + * + * @class tinymce.AddOnManager + */ +define("tinymce/AddOnManager", [ + "tinymce/dom/ScriptLoader", + "tinymce/util/Tools" +], function(ScriptLoader, Tools) { + var each = Tools.each; + + function AddOnManager() { + var self = this; + + self.items = []; + self.urls = {}; + self.lookup = {}; + } + + AddOnManager.prototype = { + /** + * Returns the specified add on by the short name. + * + * @method get + * @param {String} name Add-on to look for. + * @return {tinymce.Theme/tinymce.Plugin} Theme or plugin add-on instance or undefined. + */ + get: function(name) { + if (this.lookup[name]) { + return this.lookup[name].instance; + } else { + return undefined; + } + }, + + dependencies: function(name) { + var result; + + if (this.lookup[name]) { + result = this.lookup[name].dependencies; + } + + return result || []; + }, + + /** + * Loads a language pack for the specified add-on. + * + * @method requireLangPack + * @param {String} name Short name of the add-on. + */ + requireLangPack: function(name) { + var settings = AddOnManager.settings; + + if (settings && settings.language && settings.language_load !== false) { + ScriptLoader.ScriptLoader.add(this.urls[name] + '/langs/' + settings.language + '.js'); + } + }, + + /** + * Adds a instance of the add-on by it's short name. + * + * @method add + * @param {String} id Short name/id for the add-on. + * @param {tinymce.Theme/tinymce.Plugin} addOn Theme or plugin to add. + * @return {tinymce.Theme/tinymce.Plugin} The same theme or plugin instance that got passed in. + * @example + * // Create a simple plugin + * tinymce.create('tinymce.plugins.TestPlugin', { + * TestPlugin: function(ed, url) { + * ed.on('click', function(e) { + * ed.windowManager.alert('Hello World!'); + * }); + * } + * }); + * + * // Register plugin using the add method + * tinymce.PluginManager.add('test', tinymce.plugins.TestPlugin); + * + * // Initialize TinyMCE + * tinymce.init({ + * ... + * plugins: '-test' // Init the plugin but don't try to load it + * }); + */ + add: function(id, addOn, dependencies) { + this.items.push(addOn); + this.lookup[id] = {instance: addOn, dependencies: dependencies}; + + return addOn; + }, + + createUrl: function(baseUrl, dep) { + if (typeof dep === "object") { + return dep; + } else { + return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix}; + } + }, + + /** + * Add a set of components that will make up the add-on. Using the url of the add-on name as the base url. + * This should be used in development mode. A new compressor/javascript munger process will ensure that the + * components are put together into the plugin.js file and compressed correctly. + * @param pluginName {String} name of the plugin to load scripts from (will be used to get the base url for the plugins). + * @param scripts {Array} Array containing the names of the scripts to load. + */ + addComponents: function(pluginName, scripts) { + var pluginUrl = this.urls[pluginName]; + + each(scripts, function(script) { + ScriptLoader.ScriptLoader.add(pluginUrl + "/" + script); + }); + }, + + /** + * Loads an add-on from a specific url. + * + * @method load + * @param {String} n Short name of the add-on that gets loaded. + * @param {String} u URL to the add-on that will get loaded. + * @param {function} cb Optional callback to execute ones the add-on is loaded. + * @param {Object} s Optional scope to execute the callback in. + * @example + * // Loads a plugin from an external URL + * tinymce.PluginManager.load('myplugin', '/some/dir/someplugin/plugin.js'); + * + * // Initialize TinyMCE + * tinymce.init({ + * ... + * plugins: '-myplugin' // Don't try to load it again + * }); + */ + load: function(n, u, cb, s) { + var t = this, url = u; + + function loadDependencies() { + var dependencies = t.dependencies(n); + + 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(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 = AddOnManager.baseURL + '/' + url; + } + + t.urls[n] = url.substring(0, url.lastIndexOf('/')); + + if (t.lookup[n]) { + loadDependencies(); + } else { + ScriptLoader.ScriptLoader.add(url, loadDependencies, s); + } + } + }; + + AddOnManager.PluginManager = new AddOnManager(); + AddOnManager.ThemeManager = new AddOnManager(); + + return AddOnManager; +}); + +/** + * TinyMCE theme class. + * + * @class tinymce.Theme + */ + +/** + * Initializes the theme. + * + * @method init + * @param {tinymce.Editor} editor Editor instance that created the theme instance. + * @param {String} url Absolute URL where the theme is located. + */ + +/** + * Meta info method, this method gets executed when TinyMCE wants to present + * information about the theme for example in the about/help dialog. + * + * @method getInfo + * @return {Object} Returns an object with meta information about the theme the current items are + * longname, author, authorurl, infourl and version. + */ + +/** + * This method is responsible for rendering/generating the overall user interface with toolbars, buttons, iframe containers etc. + * + * @method renderUI + * @param {Object} obj Object parameter containing the targetNode DOM node that will be replaced visually with an editor instance. + * @return {Object} an object with items like iframeContainer, editorContainer, sizeContainer, deltaWidth, deltaHeight. + */ + +/** + * Plugin base class, this is a pseudo class that describes how a plugin is to be created for TinyMCE. The methods below are all optional. + * + * @class tinymce.Plugin + * @example + * // Create a new plugin class + * tinymce.create('tinymce.plugins.ExamplePlugin', { + * init: function(ed, url) { + * // Register an example button + * ed.addButton('example', { + * title: 'example.desc', + * onclick: function() { + * // Display an alert when the user clicks the button + * ed.windowManager.alert('Hello world!'); + * }, + * 'class': 'bold' // Use the bold icon from the theme + * }); + * } + * }); + * + * // Register plugin with a short name + * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); + * + * // Initialize TinyMCE with the new plugin and button + * tinymce.init({ + * ... + * plugins: '-example', // - means TinyMCE will not try to load it + * theme_advanced_buttons1: 'example' // Add the new example button to the toolbar + * }); + */ + +/** + * Initialization function for the plugin. This will be called when the plugin is created. + * + * @method init + * @param {tinymce.Editor} editor Editor instance that created the plugin instance. + * @param {String} url Absolute URL where the plugin is located. + * @example + * // Creates a new plugin class + * tinymce.create('tinymce.plugins.ExamplePlugin', { + * init: function(ed, url) { + * // Register the command so that it can be invoked by using tinymce.activeEditor.execCommand('mceExample'); + * ed.addCommand('mceExample', function() { + * ed.windowManager.open({ + * file: url + '/dialog.htm', + * width: 320 + ed.getLang('example.delta_width', 0), + * height: 120 + ed.getLang('example.delta_height', 0), + * inline: 1 + * }, { + * plugin_url: url, // Plugin absolute URL + * some_custom_arg: 'custom arg' // Custom argument + * }); + * }); + * + * // Register example button + * ed.addButton('example', { + * title: 'example.desc', + * cmd: 'mceExample', + * image: url + '/img/example.gif' + * }); + * + * // Add a node change handler, selects the button in the UI when a image is selected + * ed.on('NodeChange', function(e) { + * cm.setActive('example', e.element.nodeName == 'IMG'); + * }); + * } + * }); + * + * // Register plugin + * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); + */ + +/** + * Meta info method, this method gets executed when TinyMCE wants to present information about the plugin + * for example in the about/help dialog. + * + * @method getInfo + * @return {Object} Returns an object with meta information about the plugin the current items are longname, + * author, authorurl, infourl and version. + * @example + * // Creates a new plugin class + * tinymce.create('tinymce.plugins.ExamplePlugin', { + * // Meta info method + * getInfo: function() { + * return { + * longname: 'Example plugin', + * author: 'Some author', + * authorurl: 'http://www.tinymce.com', + * infourl: 'http://www.tinymce.com/wiki.php/Plugin:Plugins/example', + * version: "1.0" + * }; + * } + * }); + * + * // Register plugin + * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); + * + * // Initialize TinyMCE with the new plugin + * tinymce.init({ + * ... + * plugins: '-example' // - means TinyMCE will not try to load it + * }); + */ + +/** + * Gets called when a new control instance is created. + * + * @method createControl + * @param {String} name Control name to create for example "mylistbox" + * @param {tinymce.ControlManager} controlman Control manager/factory to use to create the control. + * @return {tinymce.ui.Control} Returns a new control instance or null. + * @example + * // Creates a new plugin class + * tinymce.create('tinymce.plugins.ExamplePlugin', { + * createControl: function(n, cm) { + * switch (n) { + * case 'mylistbox': + * var mlb = cm.createListBox('mylistbox', { + * title: 'My list box', + * onselect: function(v) { + * tinymce.activeEditor.windowManager.alert('Value selected:' + v); + * } + * }); + * + * // Add some values to the list box + * mlb.add('Some item 1', 'val1'); + * mlb.add('some item 2', 'val2'); + * mlb.add('some item 3', 'val3'); + * + * // Return the new listbox instance + * return mlb; + * } + * + * return null; + * } + * }); + * + * // Register plugin + * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); + * + * // Initialize TinyMCE with the new plugin and button + * tinymce.init({ + * ... + * plugins: '-example', // - means TinyMCE will not try to load it + * theme_advanced_buttons1: 'mylistbox' // Add the new mylistbox control to the toolbar + * }); + */ + +// Included from: js/tinymce/classes/html/Node.js + +/** + * Node.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is a minimalistic implementation of a DOM like node used by the DomParser class. + * + * @example + * var node = new tinymce.html.Node('strong', 1); + * someRoot.append(node); + * + * @class tinymce.html.Node + * @version 3.4 + */ +define("tinymce/html/Node", [], function() { + 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; + } + } + } + } + + /** + * Constructs a new Node instance. + * + * @constructor + * @method Node + * @param {String} name Name of the node type. + * @param {Number} type Numeric type representing the node. + */ + function Node(name, type) { + this.name = name; + this.type = type; + + if (type === 1) { + this.attributes = []; + this.attributes.map = {}; + } + } + + Node.prototype = { + /** + * Replaces the current node with the specified one. + * + * @example + * someNode.replace(someNewNode); + * + * @method replace + * @param {tinymce.html.Node} node Node to replace the current node with. + * @return {tinymce.html.Node} The old node that got replaced. + */ + replace: function(node) { + var self = this; + + if (node.parent) { + node.remove(); + } + + self.insert(node, self); + self.remove(); + + return self; + }, + + /** + * Gets/sets or removes an attribute by name. + * + * @example + * someNode.attr("name", "value"); // Sets an attribute + * console.log(someNode.attr("name")); // Gets an attribute + * someNode.attr("name", null); // Removes an attribute + * + * @method attr + * @param {String} name Attribute name to set or get. + * @param {String} value Optional value to set. + * @return {String/tinymce.html.Node} String or undefined on a get operation or the current node on a set operation. + */ + 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]; + } + } + }, + + /** + * Does a shallow clones the node into a new node. It will also exclude id attributes since + * there should only be one id per document. + * + * @example + * var clonedNode = node.clone(); + * + * @method clone + * @return {tinymce.html.Node} New copy of the original node. + */ + 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; + }, + + /** + * Wraps the node in in another node. + * + * @example + * node.wrap(wrapperNode); + * + * @method wrap + */ + wrap: function(wrapper) { + var self = this; + + self.parent.insert(wrapper, self); + wrapper.append(self); + + return self; + }, + + /** + * Unwraps the node in other words it removes the node but keeps the children. + * + * @example + * node.unwrap(); + * + * @method unwrap + */ + unwrap: function() { + var self = this, node, next; + + for (node = self.firstChild; node; ) { + next = node.next; + self.insert(node, self, true); + node = next; + } + + self.remove(); + }, + + /** + * Removes the node from it's parent. + * + * @example + * node.remove(); + * + * @method remove + * @return {tinymce.html.Node} Current node that got removed. + */ + 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; + }, + + /** + * Appends a new node as a child of the current node. + * + * @example + * node.append(someNode); + * + * @method append + * @param {tinymce.html.Node} node Node to append as a child of the current one. + * @return {tinymce.html.Node} The node that got appended. + */ + 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; + }, + + /** + * Inserts a node at a specific position as a child of the current node. + * + * @example + * parentNode.insert(newChildNode, oldChildNode); + * + * @method insert + * @param {tinymce.html.Node} node Node to insert as a child of the current node. + * @param {tinymce.html.Node} ref_node Reference node to set node before/after. + * @param {Boolean} before Optional state to insert the node before the reference node. + * @return {tinymce.html.Node} The node that got inserted. + */ + 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; + }, + + /** + * Get all children by name. + * + * @method getAll + * @param {String} name Name of the child nodes to collect. + * @return {Array} Array with child nodes matchin the specified name. + */ + 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; + }, + + /** + * Removes all children of the current node. + * + * @method empty + * @return {tinymce.html.Node} The current node that got cleared. + */ + 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; + }, + + /** + * Returns true/false if the node is to be considered empty or not. + * + * @example + * node.isEmpty({img: true}); + * @method isEmpty + * @param {Object} elements Name/value object with elements that are automatically treated as non empty elements. + * @return {Boolean} true/false if the node is empty or not. + */ + 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 + if (elements[node.name]) { + return false; + } + + // Keep elements with data attributes or name attribute like + i = node.attributes.length; + while (i--) { + name = node.attributes[i].name; + if (name === "name" || name.indexOf('data-mce-') === 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; + }, + + /** + * Walks to the next or previous node and returns that node or null if it wasn't found. + * + * @method walk + * @param {Boolean} prev Optional previous node state defaults to false. + * @return {tinymce.html.Node} Node that is next to or previous of the current node. + */ + walk: function(prev) { + return walk(this, null, prev); + } + }; + + /** + * Creates a node of a specific type. + * + * @static + * @method create + * @param {String} name Name of the node type to create for example "b" or "#text". + * @param {Object} attrs Name/value collection of attributes that will be applied to elements. + */ + 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; + }; + + return Node; +}); + +// Included from: js/tinymce/classes/html/Schema.js + +/** + * Schema.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Schema validator class. + * + * @class tinymce.html.Schema + * @example + * if (tinymce.activeEditor.schema.isValidChild('p', 'span')) + * alert('span is valid child of p.'); + * + * if (tinymce.activeEditor.schema.getElementRule('p')) + * alert('P is a valid element.'); + * + * @class tinymce.html.Schema + * @version 3.4 + */ +define("tinymce/html/Schema", [ + "tinymce/util/Tools" +], function(Tools) { + var mapCache = {}; + var makeMap = Tools.makeMap, each = Tools.each, extend = Tools.extend, explode = Tools.explode, inArray = Tools.inArray; + + function split(items, delim) { + return items ? items.split(delim || ' ') : []; + } + + /** + * Builds a schema lookup table + * + * @param {String} type html4, html5 or html5-strict schema type. + * @return {Object} Schema lookup table. + */ + function compileSchema(type) { + var schema = {}, globalAttributes, eventAttributes, blockContent; + var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent; + + function add(name, attributes, children) { + var ni, i, attributesOrder, args = arguments; + + function arrayToMap(array) { + var map = {}, i, l; + + for (i = 0, l = array.length; i < l; i++) { + map[array[i]] = {}; + } + + return map; + } + + children = children || []; + attributes = attributes || ""; + + if (typeof(children) === "string") { + children = split(children); + } + + // Split string children + for (i = 3; i < args.length; i++) { + if (typeof(args[i]) === "string") { + args[i] = split(args[i]); + } + + children.push.apply(children, args[i]); + } + + name = split(name); + ni = name.length; + while (ni--) { + attributesOrder = [].concat(globalAttributes, split(attributes)); + schema[name[ni]] = { + attributes: arrayToMap(attributesOrder), + attributesOrder: attributesOrder, + children: arrayToMap(children) + }; + } + } + + function addAttrs(name, attributes) { + var ni, schemaItem, i, l; + + name = split(name); + ni = name.length; + attributes = split(attributes); + while (ni--) { + schemaItem = schema[name[ni]]; + for (i = 0, l = attributes.length; i < l; i++) { + schemaItem.attributes[attributes[i]] = {}; + schemaItem.attributesOrder.push(attributes[i]); + } + } + } + + // Use cached schema + if (mapCache[type]) { + return mapCache[type]; + } + + // Attributes present on all elements + globalAttributes = split("id accesskey class dir lang style tabindex title"); + + // Event attributes can be opt-in/opt-out + eventAttributes = split("onabort onblur oncancel oncanplay oncanplaythrough onchange onclick onclose oncontextmenu oncuechange " + + "ondblclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop ondurationchange onemptied onended " + + "onerror onfocus oninput oninvalid onkeydown onkeypress onkeyup onload onloadeddata onloadedmetadata onloadstart " + + "onmousedown onmousemove onmouseout onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange " + + "onreset onscroll onseeked onseeking onseeking onselect onshow onstalled onsubmit onsuspend ontimeupdate onvolumechange " + + "onwaiting" + ); + + // Block content elements + blockContent = split( + "address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul" + ); + + // Phrasing content elements from the HTML5 spec (inline) + phrasingContent = split( + "a abbr b bdo br button cite code del dfn em embed i iframe img input ins kbd " + + "label map noscript object q s samp script select small span strong sub sup " + + "textarea u var #text #comment" + ); + + // Add HTML5 items to globalAttributes, blockContent, phrasingContent + if (type != "html4") { + globalAttributes.push.apply(globalAttributes, split("contenteditable contextmenu draggable dropzone " + + "hidden spellcheck translate")); + blockContent.push.apply(blockContent, split("article aside details dialog figure header footer hgroup section nav")); + phrasingContent.push.apply(phrasingContent, split("audio canvas command datalist mark meter output progress time wbr " + + "video ruby bdi keygen")); + } + + // Add HTML4 elements unless it's html5-strict + if (type != "html5-strict") { + globalAttributes.push("xml:lang"); + + html4PhrasingContent = split("acronym applet basefont big font strike tt"); + phrasingContent.push.apply(phrasingContent, html4PhrasingContent); + + each(html4PhrasingContent, function(name) { + add(name, "", phrasingContent); + }); + + html4BlockContent = split("center dir isindex noframes"); + blockContent.push.apply(blockContent, html4BlockContent); + + // Flow content elements from the HTML5 spec (block+inline) + flowContent = [].concat(blockContent, phrasingContent); + + each(html4BlockContent, function(name) { + add(name, "", flowContent); + }); + } + + // Flow content elements from the HTML5 spec (block+inline) + flowContent = flowContent || [].concat(blockContent, phrasingContent); + + // HTML4 base schema TODO: Move HTML5 specific attributes to HTML5 specific if statement + // Schema items , , + add("html", "manifest", "head body"); + add("head", "", "base command link meta noscript script style title"); + add("title hr noscript br"); + add("base", "href target"); + add("link", "href rel media hreflang type sizes hreflang"); + add("meta", "name http-equiv content charset"); + add("style", "media type scoped"); + add("script", "src async defer type charset"); + add("body", "onafterprint onbeforeprint onbeforeunload onblur onerror onfocus " + + "onhashchange onload onmessage onoffline ononline onpagehide onpageshow " + + "onpopstate onresize onscroll onstorage onunload", flowContent); + add("address dt dd div caption", "", flowContent); + add("h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn", "", phrasingContent); + add("blockquote", "cite", flowContent); + add("ol", "reversed start type", "li"); + add("ul", "", "li"); + add("li", "value", flowContent); + add("dl", "", "dt dd"); + add("a", "href target rel media hreflang type", phrasingContent); + add("q", "cite", phrasingContent); + add("ins del", "cite datetime", flowContent); + add("img", "src alt usemap ismap width height"); + add("iframe", "src name width height", flowContent); + add("embed", "src type width height"); + add("object", "data type typemustmatch name usemap form width height", flowContent, "param"); + add("param", "name value"); + add("map", "name", flowContent, "area"); + add("area", "alt coords shape href target rel media hreflang type"); + add("table", "border", "caption colgroup thead tfoot tbody tr" + (type == "html4" ? " col" : "")); + add("colgroup", "span", "col"); + add("col", "span"); + add("tbody thead tfoot", "", "tr"); + add("tr", "", "td th"); + add("td", "colspan rowspan headers", flowContent); + add("th", "colspan rowspan headers scope abbr", flowContent); + add("form", "accept-charset action autocomplete enctype method name novalidate target", flowContent); + add("fieldset", "disabled form name", flowContent, "legend"); + add("label", "form for", phrasingContent); + add("input", "accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate " + + "formtarget height list max maxlength min multiple name pattern readonly required size src step type value width" + ); + add("button", "disabled form formaction formenctype formmethod formnovalidate formtarget name type value", + type == "html4" ? flowContent : phrasingContent); + add("select", "disabled form multiple name required size", "option optgroup"); + add("optgroup", "disabled label", "option"); + add("option", "disabled label selected value"); + add("textarea", "cols dirname disabled form maxlength name readonly required rows wrap"); + add("menu", "type label", flowContent, "li"); + add("noscript", "", flowContent); + + // Extend with HTML5 elements + if (type != "html4") { + add("wbr"); + add("ruby", "", phrasingContent, "rt rp"); + add("figcaption", "", flowContent); + add("mark rt rp summary bdi", "", phrasingContent); + add("canvas", "width height", flowContent); + add("video", "src crossorigin poster preload autoplay mediagroup loop " + + "muted controls width height", flowContent, "track source"); + add("audio", "src crossorigin preload autoplay mediagroup loop muted controls", flowContent, "track source"); + add("source", "src type media"); + add("track", "kind src srclang label default"); + add("datalist", "", phrasingContent, "option"); + add("article section nav aside header footer", "", flowContent); + add("hgroup", "", "h1 h2 h3 h4 h5 h6"); + add("figure", "", flowContent, "figcaption"); + add("time", "datetime", phrasingContent); + add("dialog", "open", flowContent); + add("command", "type label icon disabled checked radiogroup command"); + add("output", "for form name", phrasingContent); + add("progress", "value max", phrasingContent); + add("meter", "value min max low high optimum", phrasingContent); + add("details", "open", flowContent, "summary"); + add("keygen", "autofocus challenge disabled form keytype name"); + } + + // Extend with HTML4 attributes unless it's html5-strict + if (type != "html5-strict") { + addAttrs("script", "language xml:space"); + addAttrs("style", "xml:space"); + addAttrs("object", "declare classid codebase codetype archive standby align border hspace vspace"); + addAttrs("param", "valuetype type"); + addAttrs("a", "charset name rev shape coords"); + addAttrs("br", "clear"); + addAttrs("applet", "codebase archive code object alt name width height align hspace vspace"); + addAttrs("img", "name longdesc align border hspace vspace"); + addAttrs("iframe", "longdesc frameborder marginwidth marginheight scrolling align"); + addAttrs("font basefont", "size color face"); + addAttrs("input", "usemap align"); + addAttrs("select", "onchange"); + addAttrs("textarea"); + addAttrs("h1 h2 h3 h4 h5 h6 div p legend caption", "align"); + addAttrs("ul", "type compact"); + addAttrs("li", "type"); + addAttrs("ol dl menu dir", "compact"); + addAttrs("pre", "width xml:space"); + addAttrs("hr", "align noshade size width"); + addAttrs("isindex", "prompt"); + addAttrs("table", "summary width frame rules cellspacing cellpadding align bgcolor"); + addAttrs("col", "width align char charoff valign"); + addAttrs("colgroup", "width align char charoff valign"); + addAttrs("thead", "align char charoff valign"); + addAttrs("tr", "align char charoff valign bgcolor"); + addAttrs("th", "axis align char charoff valign nowrap bgcolor width height"); + addAttrs("form", "accept"); + addAttrs("td", "abbr axis scope align char charoff valign nowrap bgcolor width height"); + addAttrs("tfoot", "align char charoff valign"); + addAttrs("tbody", "align char charoff valign"); + addAttrs("area", "nohref"); + addAttrs("body", "background bgcolor text link vlink alink"); + } + + // Extend with HTML5 attributes unless it's html4 + if (type != "html4") { + addAttrs("input button select textarea", "autofocus"); + addAttrs("input textarea", "placeholder"); + addAttrs("a", "download"); + addAttrs("link script img", "crossorigin"); + addAttrs("iframe", "srcdoc sandbox seamless allowfullscreen"); + } + + // Special: iframe, ruby, video, audio, label + + // Delete children of the same name from it's parent + // For example: form can't have a child of the name form + each(split('a form meter progress dfn'), function(name) { + if (schema[name]) { + delete schema[name].children[name]; + } + }); + + // Delete header, footer, sectioning and heading content descendants + /*each('dt th address', function(name) { + delete schema[name].children[name]; + });*/ + + // Caption can't have tables + delete schema.caption.children.table; + + // TODO: LI:s can only have value if parent is OL + + // TODO: Handle transparent elements + // a ins del canvas map + + mapCache[type] = schema; + + return schema; + } + + /** + * Constructs a new Schema instance. + * + * @constructor + * @method Schema + * @param {Object} settings Name/value settings object. + */ + return function(settings) { + var self = this, elements = {}, children = {}, patternElements = [], validStyles, schemaItems; + var whiteSpaceElementsMap, selfClosingElementsMap, shortEndedElementsMap, boolAttrMap; + var blockElementsMap, nonEmptyElementsMap, textBlockElementsMap, customElementsMap = {}, specialElements = {}; + + // Creates an lookup table map object for the specified option or the default value + function createLookupTable(option, default_value, extendWith) { + 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 = extend(value, extendWith); + + mapCache[option] = value; + } + } else { + // Create custom map + value = makeMap(value, ',', makeMap(value.toUpperCase(), ' ')); + } + + return value; + } + + settings = settings || {}; + schemaItems = compileSchema(settings.schema); + + // 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] = explode(value); + }); + } + + // Setup map objects + whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object'); + selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr'); + shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' + + 'meta param embed source wbr track'); + boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + + 'noshade nowrap readonly selected autoplay loop controls'); + nonEmptyElementsMap = createLookupTable('non_empty_elements', 'td th iframe video audio object', shortEndedElementsMap); + textBlockElementsMap = createLookupTable('text_block_elements', 'h1 h2 h3 h4 h5 h6 p div address pre form ' + + 'blockquote center dir fieldset header footer article section hgroup aside nav figure'); + blockElementsMap = createLookupTable('block_elements', 'hr table tbody thead tfoot ' + + 'th tr td li ol ul caption dl dt dd noscript menu isindex samp option ' + + 'datalist select optgroup', textBlockElementsMap); + + each((settings.special || 'script noscript style textarea').split(' '), function(name) { + specialElements[name] = new RegExp('<\/' + name + '[^>]*>','gi'); + }); + + // 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, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, + prefix, outputName, globalAttributes, globalAttributesOrder, key, 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[5]; + + // 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; + } + + if (matches[4] === '!') { + element.removeEmptyAttrs = 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(inArray(attributesOrder, attrName), 1); + continue; + } + + // Default value + if (prefix) { + // Default value + if (prefix === '=') { + element.attributesDefault = element.attributesDefault || []; + element.attributesDefault.push({name: attrName, value: value}); + attr.defaultValue = value; + } + + // Forced value + if (prefix === ':') { + element.attributesForced = element.attributesForced || []; + element.attributesForced.push({name: attrName, value: value}); + attr.forcedValue = value; + } + + // Required values + if (prefix === '<') { + attr.validValues = makeMap(value, '?'); + } + } + + // Check for attribute patterns + if (hasPatternsRegExp.test(attrName)) { + element.attributePatterns = element.attributePatterns || []; + attr.pattern = patternToRegExp(attrName); + element.attributePatterns.push(attr); + } else { + // Add attribute to order list if it doesn't already exist + if (!attributes[attrName]) { + attributesOrder.push(attrName); + } + + attributes[attrName] = attr; + } + } + } + } + + // Global rule, store away these for later usage + if (!globalAttributes && elementName == '@') { + globalAttributes = attributes; + globalAttributesOrder = attributesOrder; + } + + // Handle substitute elements such as b/strong + if (outputName) { + element.outputName = elementName; + elements[outputName] = element; + } + + // Add pattern or exact element + if (hasPatternsRegExp.test(elementName)) { + element.pattern = patternToRegExp(elementName); + patternElements.push(element); + } else { + elements[elementName] = element; + } + } + } + } + } + + function setValidElements(valid_elements) { + elements = {}; + patternElements = []; + + addValidElements(valid_elements); + + each(schemaItems, function(element, name) { + children[name] = element.children; + }); + } + + // Adds custom non HTML elements to the schema + function addCustomElements(custom_elements) { + var customElementRegExp = /^(~)?(.+)$/; + + if (custom_elements) { + each(split(custom_elements, ','), function(rule) { + var matches = customElementRegExp.exec(rule), + inline = matches[1] === '~', + cloneName = inline ? 'span' : 'div', + name = matches[2]; + + children[name] = children[cloneName]; + customElementsMap[name] = cloneName; + + // If it's not marked as inline then add it to valid block elements + if (!inline) { + blockElementsMap[name.toUpperCase()] = {}; + blockElementsMap[name] = {}; + } + + // Add elements clone if needed + if (!elements[name]) { + elements[name] = elements[cloneName]; + } + + // Add custom elements at span/div positions + each(children, function(element) { + 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; + }); + + // Remove these if they have no attributes + each(split('span'), function(name) { + elements[name].removeEmptyAttrs = 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) { + each(explode(settings.invalid_elements), function(item) { + if (elements[item]) { + delete elements[item]; + } + }); + } + + // If the user didn't allow span only allow internal spans + if (!getElementRule('span')) { + addValidElements('span[!data-mce-type|*]'); + } + + /** + * Name/value map object with valid parents and children to those parents. + * + * @example + * children = { + * div:{p:{}, h1:{}} + * }; + * @field children + * @type {Object} + */ + self.children = children; + + /** + * Name/value map object with valid styles for each element. + * + * @field styles + * @type {Object} + */ + self.styles = validStyles; + + /** + * Returns a map with boolean attributes. + * + * @method getBoolAttrs + * @return {Object} Name/value lookup map for boolean attributes. + */ + self.getBoolAttrs = function() { + return boolAttrMap; + }; + + /** + * Returns a map with block elements. + * + * @method getBlockElements + * @return {Object} Name/value lookup map for block elements. + */ + self.getBlockElements = function() { + return blockElementsMap; + }; + + /** + * Returns a map with text block elements. Such as: p,h1-h6,div,address + * + * @method getTextBlockElements + * @return {Object} Name/value lookup map for block elements. + */ + self.getTextBlockElements = function() { + return textBlockElementsMap; + }; + + /** + * Returns a map with short ended elements such as BR or IMG. + * + * @method getShortEndedElements + * @return {Object} Name/value lookup map for short ended elements. + */ + self.getShortEndedElements = function() { + return shortEndedElementsMap; + }; + + /** + * Returns a map with self closing tags such as
  • . + * + * @method getSelfClosingElements + * @return {Object} Name/value lookup map for self closing tags elements. + */ + self.getSelfClosingElements = function() { + return selfClosingElementsMap; + }; + + /** + * Returns a map with elements that should be treated as contents regardless if it has text + * content in them or not such as TD, VIDEO or IMG. + * + * @method getNonEmptyElements + * @return {Object} Name/value lookup map for non empty elements. + */ + self.getNonEmptyElements = function() { + return nonEmptyElementsMap; + }; + + /** + * Returns a map with elements where white space is to be preserved like PRE or SCRIPT. + * + * @method getWhiteSpaceElements + * @return {Object} Name/value lookup map for white space elements. + */ + self.getWhiteSpaceElements = function() { + return whiteSpaceElementsMap; + }; + + /** + * Returns a map with special elements. These are elements that needs to be parsed + * in a special way such as script, style, textarea etc. The map object values + * are regexps used to find the end of the element. + * + * @method getSpecialElements + * @return {Object} Name/value lookup map for special elements. + */ + self.getSpecialElements = function() { + return specialElements; + }; + + /** + * Returns true/false if the specified element and it's child is valid or not + * according to the schema. + * + * @method isValidChild + * @param {String} name Element name to check for. + * @param {String} child Element child to verify. + * @return {Boolean} True/false if the element is a valid child of the specified parent. + */ + self.isValidChild = function(name, child) { + var parent = children[name]; + + return !!(parent && parent[child]); + }; + + /** + * Returns true/false if the specified element name and optional attribute is + * valid according to the schema. + * + * @method isValid + * @param {String} name Name of element to check. + * @param {String} attr Optional attribute name to check for. + * @return {Boolean} True/false if the element and attribute is valid. + */ + self.isValid = function(name, attr) { + var attrPatterns, i, rule = getElementRule(name); + + // Check if it's a valid element + if (rule) { + if (attr) { + // Check if attribute name exists + if (rule.attributes[attr]) { + return true; + } + + // Check if attribute matches a regexp pattern + attrPatterns = rule.attributePatterns; + if (attrPatterns) { + i = attrPatterns.length; + while (i--) { + if (attrPatterns[i].pattern.test(name)) { + return true; + } + } + } + } else { + return true; + } + } + + // No match + return false; + }; + + /** + * Returns true/false if the specified element is valid or not + * according to the schema. + * + * @method getElementRule + * @param {String} name Element name to check for. + * @return {Object} Element object or undefined if the element isn't valid. + */ + self.getElementRule = getElementRule; + + /** + * Returns an map object of all custom elements. + * + * @method getCustomElements + * @return {Object} Name/value map object of all custom elements. + */ + self.getCustomElements = function() { + return customElementsMap; + }; + + /** + * Parses a valid elements string and adds it to the schema. The valid elements + format is for example "element[attr=default|otherattr]". + * Existing rules will be replaced with the ones specified, so this extends the schema. + * + * @method addValidElements + * @param {String} valid_elements String in the valid elements format to be parsed. + */ + self.addValidElements = addValidElements; + + /** + * Parses a valid elements string and sets it to the schema. The valid elements + * format is for example "element[attr=default|otherattr]". + * Existing rules will be replaced with the ones specified, so this extends the schema. + * + * @method setValidElements + * @param {String} valid_elements String in the valid elements format to be parsed. + */ + self.setValidElements = setValidElements; + + /** + * Adds custom non HTML elements to the schema. + * + * @method addCustomElements + * @param {String} custom_elements Comma separated list of custom elements to add. + */ + self.addCustomElements = addCustomElements; + + /** + * Parses a valid children string and adds them to the schema structure. The valid children + * format is for example: "element[child1|child2]". + * + * @method addValidChildren + * @param {String} valid_children Valid children elements string to parse + */ + self.addValidChildren = addValidChildren; + + self.elements = elements; + }; +}); + +// Included from: js/tinymce/classes/html/SaxParser.js + +/** + * SaxParser.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class parses HTML code using pure JavaScript and executes various events for each item it finds. It will + * always execute the events in the right order for tag soup code like

    . It will also remove elements + * and attributes that doesn't fit the schema if the validate setting is enabled. + * + * @example + * var parser = new tinymce.html.SaxParser({ + * validate: true, + * + * comment: function(text) { + * console.log('Comment:', text); + * }, + * + * cdata: function(text) { + * console.log('CDATA:', text); + * }, + * + * text: function(text, raw) { + * console.log('Text:', text, 'Raw:', raw); + * }, + * + * start: function(name, attrs, empty) { + * console.log('Start:', name, attrs, empty); + * }, + * + * end: function(name) { + * console.log('End:', name); + * }, + * + * pi: function(name, text) { + * console.log('PI:', name, text); + * }, + * + * doctype: function(text) { + * console.log('DocType:', text); + * } + * }, schema); + * @class tinymce.html.SaxParser + * @version 3.4 + */ +define("tinymce/html/SaxParser", [ + "tinymce/html/Schema", + "tinymce/html/Entities", + "tinymce/util/Tools" +], function(Schema, Entities, Tools) { + var each = Tools.each; + + /** + * Constructs a new SaxParser instance. + * + * @constructor + * @method SaxParser + * @param {Object} settings Name/value collection of settings. comment, cdata, text, start and end are callbacks. + * @param {tinymce.html.Schema} schema HTML Schema class to use when parsing. + */ + return function(settings, schema) { + var self = this, noop = function() {}; + + settings = settings || {}; + self.schema = schema = schema || new Schema(); + + if (settings.fix_self_closing !== false) { + settings.fix_self_closing = true; + } + + // Add handler functions from settings and setup default handlers + each('comment cdata text start end pi doctype'.split(' '), function(name) { + if (name) { + self[name] = settings[name] || noop; + } + }); + + /** + * Parses the specified HTML string and executes the callbacks for each item it finds. + * + * @example + * new SaxParser({...}).parse('text'); + * @method parse + * @param {String} html Html string to sax parse. + */ + self.parse = function(html) { + var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name; + var isInternalElement, removeInternalElements, shortEndedElements, fillAttrsMap, isShortEnded; + var validate, elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns; + var attributesRequired, attributesDefault, attributesForced; + var anyAttributesRequired, selfClosing, tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0; + var decode = Entities.decode, fixSelfClosing; + + 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-mce-') !== 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; + + // Setup lookup tables for empty elements and boolean attributes + shortEndedElements = schema.getShortEndedElements(); + selfClosing = settings.self_closing_elements || schema.getSelfClosingElements(); + fillAttrsMap = schema.getBoolAttrs(); + validate = settings.validate; + removeInternalElements = settings.remove_internals; + fixSelfClosing = settings.fix_self_closing; + specialElements = schema.getSpecialElements(); + + 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 (value.charAt(0) === ':') { + 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 (value.charAt(0) === ':') { + value = value.substr(1); + } + + isShortEnded = value in shortEndedElements; + + // Is self closing tag for example an
  • after an open
  • + 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; + anyAttributesRequired = elementRule.removeEmptyAttrs; + + // Check if any attribute exists + if (anyAttributesRequired && !attrList.length) { + isValidElement = false; + } + + // 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) { + if (text.length > 0) { + self.text(text, true); + } + + 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); + } + } + }; + }; +}); + +// Included from: js/tinymce/classes/html/DomParser.js + +/** + * DomParser.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class parses HTML code into a DOM like structure of nodes it will remove redundant whitespace and make + * sure that the node tree is valid according to the specified schema. + * So for example:

    a

    b

    c

    will become

    a

    b

    c

    + * + * @example + * var parser = new tinymce.html.DomParser({validate: true}, schema); + * var rootNode = parser.parse('

    content

    '); + * + * @class tinymce.html.DomParser + * @version 3.4 + */ +define("tinymce/html/DomParser", [ + "tinymce/html/Node", + "tinymce/html/Schema", + "tinymce/html/SaxParser", + "tinymce/util/Tools" +], function(Node, Schema, SaxParser, Tools) { + var makeMap = Tools.makeMap, each = Tools.each, explode = Tools.explode, extend = Tools.extend; + + /** + * Constructs a new DomParser instance. + * + * @constructor + * @method DomParser + * @param {Object} settings Name/value collection of settings. comment, cdata, text, start and end are callbacks. + * @param {tinymce.html.Schema} schema HTML Schema class to use when parsing. + */ + return 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 Schema(); + + function fixInvalidChildren(nodes) { + var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i; + var nonEmptyElements, nonSplitableElements, textBlockElements, sibling, nextNode; + + nonSplitableElements = makeMap('tr,td,th,tbody,thead,tfoot,table'); + nonEmptyElements = schema.getNonEmptyElements(); + textBlockElements = schema.getTextBlockElements(); + + for (ni = 0; ni < nodes.length; ni++) { + node = nodes[ni]; + + // Already removed or fixed + if (!node.parent || node.fixed) { + continue; + } + + // If the invalid element is a text block and the text block is within a parent LI element + // Then unwrap the first text block and convert other sibling text blocks to LI elements similar to Word/Open Office + if (textBlockElements[node.name] && node.parent.name == 'li') { + // Move sibling text blocks after LI element + sibling = node.next; + while (sibling) { + if (textBlockElements[sibling.name]) { + sibling.name = 'li'; + sibling.fixed = true; + node.parent.insert(sibling, node.parent); + } else { + break; + } + + sibling = sibling.next; + } + + // Unwrap current text block + node.unwrap(node); + 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


    + 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(); + } + } + } + } + } + + /** + * Runs the specified node though the element and attributes filters. + * + * @param {tinymce.html.Node} Node the node to run filters on. + * @return {tinymce.html.Node} The passed in node. + */ + 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; + }; + + /** + * Adds a node filter function to the parser, the parser will collect the specified nodes by name + * and then execute the callback ones it has finished parsing the document. + * + * @example + * parser.addNodeFilter('p,h1', function(nodes, name) { + * for (var i = 0; i < nodes.length; i++) { + * console.log(nodes[i].name); + * } + * }); + * @method addNodeFilter + * @method {String} name Comma separated list of nodes to collect. + * @param {function} callback Callback function to execute once it has collected nodes. + */ + self.addNodeFilter = function(name, callback) { + each(explode(name), function(name) { + var list = nodeFilters[name]; + + if (!list) { + nodeFilters[name] = list = []; + } + + list.push(callback); + }); + }; + + /** + * Adds a attribute filter function to the parser, the parser will collect nodes that has the specified attributes + * and then execute the callback ones it has finished parsing the document. + * + * @example + * parser.addAttributeFilter('src,href', function(nodes, name) { + * for (var i = 0; i < nodes.length; i++) { + * console.log(nodes[i].name); + * } + * }); + * @method addAttributeFilter + * @method {String} name Comma separated list of nodes to collect. + * @param {function} callback Callback function to execute once it has collected nodes. + */ + self.addAttributeFilter = function(name, callback) { + each(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]}); + }); + }; + + /** + * Parses the specified HTML string into a DOM like node tree and returns the result. + * + * @example + * var rootNode = new DomParser({...}).parse('text'); + * @method parse + * @param {String} html Html string to sax parse. + * @param {Object} args Optional args object that gets passed to all filter functions. + * @return {tinymce.html.Node} Root node containing the tree. + */ + self.parse = function(html, args) { + var parser, rootNode, node, nodes, i, l, fi, fl, list, name, validate; + var blockElements, startWhiteSpaceRegExp, invalidChildren = [], isInWhiteSpacePreservedElement; + var endWhiteSpaceRegExp, allWhiteSpaceRegExp, isAllWhiteSpaceRegExp, whiteSpaceElements; + var children, nonEmptyElements, rootBlockName; + + args = args || {}; + matchedNodes = {}; + matchedAttributes = {}; + blockElements = extend(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; + isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/; + + function addRootBlocks() { + var node = rootNode.firstChild, next, rootBlockNode; + + // Removes whitespace at beginning and end of block so: + //

    x

    ->

    x

    + function trim(rootBlockNode) { + if (rootBlockNode) { + node = rootBlockNode.firstChild; + if (node && node.type == 3) { + node.value = node.value.replace(startWhiteSpaceRegExp, ''); + } + + node = rootBlockNode.lastChild; + if (node && node.type == 3) { + node.value = node.value.replace(endWhiteSpaceRegExp, ''); + } + } + } + + // Check if rootBlock is valid within rootNode for example if P is valid in H1 if H1 is the contentEditabe root + if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) { + return; + } + + 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 { + trim(rootBlockNode); + rootBlockNode = null; + } + + node = next; + } + + trim(rootBlockNode); + } + + 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; + } + } + } + + function cloneAndExcludeBlocks(input) { + var name, output = {}; + + for (name in input) { + if (name !== 'li' && name != 'p') { + output[name] = input[name]; + } + } + + return output; + } + + parser = new SaxParser({ + validate: validate, + + // Exclude P and LI from DOM parsing since it's treated better by the DOM parser + self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()), + + 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, attrName, 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
    or + 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 of the first node in a block + textNode = node.firstChild; + if (textNode && textNode.type === 3) { + text = textNode.value.replace(startWhiteSpaceRegExp, ''); + + // Any characters left after trim or should we remove it + if (text.length > 0) { + textNode.value = text; + textNode = textNode.next; + } else { + sibling = textNode.next; + textNode.remove(); + textNode = sibling; + + // Remove any pure whitespace siblings + while (textNode && textNode.type === 3) { + text = textNode.value; + sibling = textNode.next; + + if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) { + textNode.remove(); + textNode = sibling; + } + + textNode = sibling; + } + } + } + + // Trim whitespace of the last node in a block + textNode = node.lastChild; + if (textNode && textNode.type === 3) { + text = textNode.value.replace(endWhiteSpaceRegExp, ''); + + // Any characters left after trim or should we remove it + if (text.length > 0) { + textNode.value = text; + textNode = textNode.prev; + } else { + sibling = textNode.prev; + textNode.remove(); + textNode = sibling; + + // Remove any pure whitespace siblings + while (textNode && textNode.type === 3) { + text = textNode.value; + sibling = textNode.prev; + + if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) { + textNode.remove(); + textNode = sibling; + } + + textNode = sibling; + } + } + } + } + + // Trim start white space + // Removed due to: #5424 + /*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 + if (!node.attributes.map.name && !node.attributes.map.id) { + 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' || args.isRootContent)) { + 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
    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) { + var i, l = nodes.length, node, blockElements = extend({}, schema.getBlockElements()); + var nonEmptyElements = schema.getNonEmptyElements(), parent, lastParent, prev, prevName; + var elementRule, textNode; + + // Remove brs from body element as well + blockElements.body = 1; + + // Must loop forwards since it will otherwise remove all brs in

    a


    + 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

    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 Node('#text', 3)).value = '\u00a0'; + } + } + } + } + } else { + // Replaces BR elements inside inline elements like


    + // so they become

     

    + lastParent = node; + while (parent.firstChild === lastParent && parent.lastChild === lastParent) { + lastParent = parent; + + if (blockElements[parent.name]) { + break; + } + + parent = parent.parent; + } + + if (lastParent === parent) { + textNode = new 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('id,name', function(nodes) { + var i = nodes.length, sibling, prevSibling, parent, node; + + while (i--) { + node = nodes[i]; + if (node.name === 'a' && node.firstChild && !node.attr('href')) { + parent = node.parent; + + // Move children after current node + sibling = node.lastChild; + do { + prevSibling = sibling.prev; + parent.insert(sibling, node); + sibling = prevSibling; + } while (sibling); + } + } + }); + } + }; +}); + +// Included from: js/tinymce/classes/html/Writer.js + +/** + * Writer.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is used to write HTML tags out it can be used with the Serializer or the SaxParser. + * + * @class tinymce.html.Writer + * @example + * var writer = new tinymce.html.Writer({indent: true}); + * var parser = new tinymce.html.SaxParser(writer).parse('


    '); + * console.log(writer.getContent()); + * + * @class tinymce.html.Writer + * @version 3.4 + */ +define("tinymce/html/Writer", [ + "tinymce/html/Entities", + "tinymce/util/Tools" +], function(Entities, Tools) { + var makeMap = Tools.makeMap; + + /** + * Constructs a new Writer instance. + * + * @constructor + * @method Writer + * @param {Object} settings Name/value settings object. + */ + return function(settings) { + var html = [], indent, indentBefore, indentAfter, encode, htmlOutput; + + settings = settings || {}; + indent = settings.indent; + indentBefore = makeMap(settings.indent_before || ''); + indentAfter = makeMap(settings.indent_after || ''); + encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities); + htmlOutput = settings.element_format == "html"; + + return { + /** + * Writes the a start element such as

    . + * + * @method start + * @param {String} name Name of the element. + * @param {Array} attrs Optional attribute array or undefined if it hasn't any. + * @param {Boolean} empty Optional empty state if the tag should end like
    . + */ + 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'); + } + } + }, + + /** + * Writes the a end element such as

    . + * + * @method end + * @param {String} name Name of the element. + */ + 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(''); + + if (indent && indentAfter[name] && html.length > 0) { + value = html[html.length - 1]; + + if (value.length > 0 && value !== '\n') { + html.push('\n'); + } + } + }, + + /** + * Writes a text node. + * + * @method text + * @param {String} text String to write out. + * @param {Boolean} raw Optional raw state if true the contents wont get encoded. + */ + text: function(text, raw) { + if (text.length > 0) { + html[html.length] = raw ? text : encode(text); + } + }, + + /** + * Writes a cdata node such as . + * + * @method cdata + * @param {String} text String to write out inside the cdata. + */ + cdata: function(text) { + html.push(''); + }, + + /** + * Writes a comment node such as . + * + * @method cdata + * @param {String} text String to write out inside the comment. + */ + comment: function(text) { + html.push(''); + }, + + /** + * Writes a PI node such as . + * + * @method pi + * @param {String} name Name of the pi. + * @param {String} text String to write out inside the pi. + */ + pi: function(name, text) { + if (text) { + html.push(''); + } else { + html.push(''); + } + + if (indent) { + html.push('\n'); + } + }, + + /** + * Writes a doctype node such as . + * + * @method doctype + * @param {String} text String to write out inside the doctype. + */ + doctype: function(text) { + html.push('', indent ? '\n' : ''); + }, + + /** + * Resets the internal buffer if one wants to reuse the writer. + * + * @method reset + */ + reset: function() { + html.length = 0; + }, + + /** + * Returns the contents that got serialized. + * + * @method getContent + * @return {String} HTML contents that got written down. + */ + getContent: function() { + return html.join('').replace(/\n$/, ''); + } + }; + }; +}); + +// Included from: js/tinymce/classes/html/Serializer.js + +/** + * Serializer.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is used to serialize down the DOM tree into a string using a Writer instance. + * + * + * @example + * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('

    text

    ')); + * @class tinymce.html.Serializer + * @version 3.4 + */ +define("tinymce/html/Serializer", [ + "tinymce/html/Writer", + "tinymce/html/Schema" +], function(Writer, Schema) { + /** + * Constructs a new Serializer instance. + * + * @constructor + * @method Serializer + * @param {Object} settings Name/value settings object. + * @param {tinymce.html.Schema} schema Schema instance to use. + */ + return function(settings, schema) { + var self = this, writer = new Writer(settings); + + settings = settings || {}; + settings.validate = "validate" in settings ? settings.validate : true; + + self.schema = schema = schema || new Schema(); + self.writer = writer; + + /** + * Serializes the specified node into a string. + * + * @example + * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('

    text

    ')); + * @method serialize + * @param {tinymce.html.Node} node Node instance to serialize. + * @return {String} String with HTML based on DOM tree. + */ + self.serialize = function(node) { + var handlers, validate; + + validate = settings.validate; + + handlers = { + // #text + 3: function(node) { + 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(); + }; + }; +}); + +// Included from: js/tinymce/classes/dom/Serializer.js + +/** + * Serializer.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is used to serialize DOM trees into a string. Consult the TinyMCE Wiki API for + * more details and examples on how to use this class. + * + * @class tinymce.dom.Serializer + */ +define("tinymce/dom/Serializer", [ + "tinymce/dom/DOMUtils", + "tinymce/html/DomParser", + "tinymce/html/Entities", + "tinymce/html/Serializer", + "tinymce/html/Node", + "tinymce/html/Schema", + "tinymce/Env", + "tinymce/util/Tools" +], function(DOMUtils, DomParser, Entities, Serializer, Node, Schema, Env, Tools) { + var each = Tools.each, trim = Tools.trim; + var DOM = DOMUtils.DOM; + + /** + * Constucts a new DOM serializer class. + * + * @constructor + * @method Serializer + * @param {Object} settings Serializer settings object. + * @param {tinymce.Editor} editor Optional editor to bind events to and get schema/dom from. + */ + return function(settings, editor) { + var dom, schema, htmlParser; + + if (editor) { + dom = editor.dom; + schema = editor.schema; + } + + // Default DOM and Schema if they are undefined + dom = dom || DOM; + schema = schema || new Schema(settings); + settings.entity_encoding = settings.entity_encoding || 'named'; + settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true; + + htmlParser = new 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; + var 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<..> or mceSelected + htmlParser.addAttributeFilter('class', function(nodes) { + var i = nodes.length, node, value; + + while (i--) { + node = nodes[i]; + value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\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) { + var i = nodes.length; + + while (i--) { + nodes[i].attr(name, null); + } + }); + + htmlParser.addNodeFilter('noscript', function(nodes) { + var i = nodes.length, node; + + while (i--) { + node = nodes[i].firstChild; + + if (node) { + node.value = Entities.decode(node.value); + } + } + }); + + // 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) { + /*jshint maxlen:255 */ + return value.replace(/()/g, '\n') + .replace(/^[\r\n]*|[\r\n]*$/g, '') + .replace(/^\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 = '// '; + } + } else { + if (value.length > 0) { + node.firstChild.value = ''; + } + } + } + }); + + // Convert comments to cdata and handle protected comments + htmlParser.addNodeFilter('#comment', function(nodes) { + 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) { + 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,data-mce-selected', function(nodes, name) { + var i = nodes.length; + + while (i--) { + nodes[i].attr(name, null); + } + }); + + // Return public methods + return { + /** + * Schema instance that was used to when the Serializer was constructed. + * + * @field {tinymce.html.Schema} schema + */ + schema: schema, + + /** + * Adds a node filter function to the parser used by the serializer, the parser will collect the specified nodes by name + * and then execute the callback ones it has finished parsing the document. + * + * @example + * parser.addNodeFilter('p,h1', function(nodes, name) { + * for (var i = 0; i < nodes.length; i++) { + * console.log(nodes[i].name); + * } + * }); + * @method addNodeFilter + * @method {String} name Comma separated list of nodes to collect. + * @param {function} callback Callback function to execute once it has collected nodes. + */ + addNodeFilter: htmlParser.addNodeFilter, + + /** + * Adds a attribute filter function to the parser used by the serializer, the parser will + * collect nodes that has the specified attributes + * and then execute the callback ones it has finished parsing the document. + * + * @example + * parser.addAttributeFilter('src,href', function(nodes, name) { + * for (var i = 0; i < nodes.length; i++) { + * console.log(nodes[i].name); + * } + * }); + * @method addAttributeFilter + * @method {String} name Comma separated list of nodes to collect. + * @param {function} callback Callback function to execute once it has collected nodes. + */ + addAttributeFilter: htmlParser.addAttributeFilter, + + /** + * Serializes the specified browser DOM node into a HTML string. + * + * @method serialize + * @param {DOMNode} node DOM node to serialize. + * @param {Object} args Arguments option that gets passed to event handlers. + */ + serialize: function(node, args) { + var self = this, 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 (Env.ie && 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 + // 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'; + + // Don't wrap content if we want selected html + if (args.selection) { + args.forced_root_block = ''; + } + + // Pre process + if (!args.no_events) { + args.node = node; + self.onPreProcess(args); + } + + // Setup serializer + htmlSerializer = new Serializer(settings, schema); + + // Parse and serialize HTML + args.content = htmlSerializer.serialize( + htmlParser.parse(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/g, ''); + } + + // Post process + if (!args.no_events) { + self.onPostProcess(args); + } + + // Restore the old document if it was changed + if (oldDoc) { + dom.doc = oldDoc; + } + + args.node = null; + + return args.content; + }, + + /** + * Adds valid elements rules to the serializers schema instance this enables you to specify things + * like what elements should be outputted and what attributes specific elements might have. + * Consult the Wiki for more details on this format. + * + * @method addRules + * @param {String} rules Valid elements rules string to add to schema. + */ + addRules: function(rules) { + schema.addValidElements(rules); + }, + + /** + * Sets the valid elements rules to the serializers schema instance this enables you to specify things + * like what elements should be outputted and what attributes specific elements might have. + * Consult the Wiki for more details on this format. + * + * @method setRules + * @param {String} rules Valid elements rules string. + */ + setRules: function(rules) { + schema.setValidElements(rules); + }, + + onPreProcess: function(args) { + if (editor) { + editor.fire('PreProcess', args); + } + }, + + onPostProcess: function(args) { + if (editor) { + editor.fire('PostProcess', args); + } + } + }; + }; +}); + +// Included from: js/tinymce/classes/dom/TridentSelection.js + +/** + * TridentSelection.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/dom/TridentSelection", [], function() { + function Selection(selection) { + var self = this, dom = selection.dom, 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; + + // 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(), 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, offset; + + 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, sibling, + doc = selection.dom.doc, body = doc.body, nativeRng, ctrlElm; + + 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
    |
    + // Setting innerHTML with a span marker then remove that marker seems to keep empty block elements open + container.innerHTML = ''; + 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

    + if (startOffset == endOffset && !startContainer.hasChildNodes()) { + if (startContainer.canHaveHTML) { + // Check if previous sibling is an empty block if it is then we need to render it + // IE would otherwise move the caret into the sibling instead of the empty startContainer see: #5236 + // Example this:

    |

    would become this:

    |

    + sibling = startContainer.previousSibling; + if (sibling && !sibling.hasChildNodes() && dom.isBlock(sibling)) { + sibling.innerHTML = ''; + } else { + sibling = null; + } + + startContainer.innerHTML = ''; + ieRng.moveToElementText(startContainer.lastChild); + ieRng.select(); + dom.doc.selection.clear(); + startContainer.innerHTML = ''; + + if (sibling) { + sibling.innerHTML = ''; + } + return; + } else { + startOffset = dom.nodeIndex(startContainer); + startContainer = startContainer.parentNode; + } + } + + if (startOffset == endOffset - 1) { + try { + ctrlElm = startContainer.childNodes[startOffset]; + ctrlRng = body.createControlRange(); + ctrlRng.addElement(ctrlElm); + ctrlRng.select(); + + // Check if the range produced is on the correct element and is a control range + // On IE 8 it will select the parent contentEditable container if you select an inner element see: #5398 + nativeRng = selection.getRng(); + if (nativeRng.item && ctrlElm === nativeRng.item(0)) { + 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; + } + + return Selection; +}); + +// Included from: js/tinymce/classes/util/VK.js + +/** + * VK.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This file exposes a set of the common KeyCodes for use. Please grow it as needed. + */ +define("tinymce/util/VK", [ + "tinymce/Env" +], function(Env) { + return { + 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; + }, + + metaKeyPressed: function(e) { + // Check if ctrl or meta key is pressed also check if alt is false for Polish users + return Env.mac ? e.metaKey : e.ctrlKey && !e.altKey; + } + }; +}); + +// Included from: js/tinymce/classes/dom/ControlSelection.js + +/** + * ControlSelection.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles control selection of elements. Controls are elements + * that can be resized and needs to be selected as a whole. It adds custom resize handles + * to all browser engines that support properly disabling the built in logic. + * + * @class tinymce.dom.ControlSelection + */ +define("tinymce/dom/ControlSelection", [ + "tinymce/util/VK", + "tinymce/util/Tools", + "tinymce/Env" +], function(VK, Tools, Env) { + return function(selection, editor) { + var dom = editor.dom, each = Tools.each; + var selectedElm, selectedElmGhost, resizeHandles, selectedHandle; + var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted; + var width, height, editableDoc = editor.getDoc(), rootDocument = document, isIE = Env.ie; + + // Details about each resize handle how to scale etc + resizeHandles = { + // Name: x multiplier, y multiplier, delta size x, delta size y + n: [0.5, 0, 0, -1], + e: [1, 0.5, 1, 0], + s: [0.5, 1, 0, 1], + w: [0, 0.5, -1, 0], + nw: [0, 0, -1, -1], + ne: [1, 0, 1, -1], + se: [1, 1, 1, 1], + sw: [0, 1, -1, 1] + }; + + // Add CSS for resize handles, cloned element and selected + var rootClass = '.mce-content-body'; + editor.contentStyles.push( + rootClass + ' div.mce-resizehandle {' + + 'position: absolute;' + + 'border: 1px solid black;' + + 'background: #FFF;' + + 'width: 5px;' + + 'height: 5px;' + + 'z-index: 10000' + + '}' + + rootClass + ' .mce-resizehandle:hover {' + + 'background: #000' + + '}' + + rootClass + ' img[data-mce-selected], hr[data-mce-selected] {' + + 'outline: 1px solid black;' + + 'resize: none' + // Have been talks about implementing this in browsers + '}' + + rootClass + ' .mce-clonedresizable {' + + 'position: absolute;' + + (Env.gecko ? '' : 'outline: 1px dashed black;') + // Gecko produces trails while resizing + 'opacity: .5;' + + 'filter: alpha(opacity=50);' + + 'z-index: 10000' + + '}' + ); + + function isResizable(elm) { + if (editor.settings.object_resizing === false) { + return false; + } + + if (!/TABLE|IMG|DIV/.test(elm.nodeName)) { + return false; + } + + if (elm.getAttribute('data-mce-resize') === 'false') { + return false; + } + + return true; + } + + function resizeGhostElement(e) { + var deltaX, deltaY; + + // Calc new width/height + deltaX = e.screenX - startX; + deltaY = e.screenY - startY; + + // Calc new size + width = deltaX * selectedHandle[2] + startW; + height = deltaY * selectedHandle[3] + startH; + + // Never scale down lower than 5 pixels + width = width < 5 ? 5 : width; + height = height < 5 ? 5 : height; + + // Constrain proportions when modifier key is pressed or if the nw, ne, sw, se corners are moved on an image + if (VK.modifierPressed(e) || (selectedElm.nodeName == "IMG" && selectedHandle[2] * selectedHandle[3] !== 0)) { + width = Math.round(height / ratio); + height = Math.round(width * ratio); + } + + // Update ghost size + dom.setStyles(selectedElmGhost, { + width: width, + height: height + }); + + // Update ghost X position if needed + if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) { + dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width)); + } + + // Update ghost Y position if needed + if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) { + dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height)); + } + + if (!resizeStarted) { + editor.fire('ObjectResizeStart', {target: selectedElm, width: startW, height: startH}); + resizeStarted = true; + } + } + + function endGhostResize() { + resizeStarted = false; + + function setSizeProp(name, value) { + if (value) { + // Resize by using style or attribute + if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) { + dom.setStyle(selectedElm, name, value); + } else { + dom.setAttrib(selectedElm, name, value); + } + } + } + + // Set width/height properties + setSizeProp('width', width); + setSizeProp('height', height); + + dom.unbind(editableDoc, 'mousemove', resizeGhostElement); + dom.unbind(editableDoc, 'mouseup', endGhostResize); + + if (rootDocument != editableDoc) { + dom.unbind(rootDocument, 'mousemove', resizeGhostElement); + dom.unbind(rootDocument, 'mouseup', endGhostResize); + } + + // Remove ghost and update resize handle positions + dom.remove(selectedElmGhost); + + if (!isIE || selectedElm.nodeName == "TABLE") { + showResizeRect(selectedElm); + } + + editor.fire('ObjectResized', {target: selectedElm, width: width, height: height}); + editor.nodeChanged(); + } + + function showResizeRect(targetElm, mouseDownHandleName, mouseDownEvent) { + var position, targetWidth, targetHeight, e, rect; + + // Get position and size of target + position = dom.getPos(targetElm, editor.getBody()); + selectedElmX = position.x; + selectedElmY = position.y; + rect = targetElm.getBoundingClientRect(); // Fix for Gecko offsetHeight for table with caption + targetWidth = rect.width; + targetHeight = rect.height; + + // Reset width/height if user selects a new image/table + if (selectedElm != targetElm) { + detachResizeStartListener(); + selectedElm = targetElm; + width = height = 0; + } + + // Makes it possible to disable resizing + e = editor.fire('ObjectSelected', {target: targetElm}); + + if (isResizable(targetElm) && !e.isDefaultPrevented()) { + each(resizeHandles, function(handle, name) { + var handleElm, handlerContainerElm; + + function startDrag(e) { + resizeStarted = true; + + startX = e.screenX; + startY = e.screenY; + startW = selectedElm.clientWidth; + startH = selectedElm.clientHeight; + ratio = startH / startW; + selectedHandle = handle; + + selectedElmGhost = selectedElm.cloneNode(true); + dom.addClass(selectedElmGhost, 'mce-clonedresizable'); + selectedElmGhost.contentEditable = false; // Hides IE move layer cursor + selectedElmGhost.unSelectabe = true; + dom.setStyles(selectedElmGhost, { + left: selectedElmX, + top: selectedElmY, + margin: 0 + }); + + selectedElmGhost.removeAttribute('data-mce-selected'); + editor.getBody().appendChild(selectedElmGhost); + + dom.bind(editableDoc, 'mousemove', resizeGhostElement); + dom.bind(editableDoc, 'mouseup', endGhostResize); + + if (rootDocument != editableDoc) { + dom.bind(rootDocument, 'mousemove', resizeGhostElement); + dom.bind(rootDocument, 'mouseup', endGhostResize); + } + } + + if (mouseDownHandleName) { + // Drag started by IE native resizestart + if (name == mouseDownHandleName) { + startDrag(mouseDownEvent); + } + + return; + } + + // Get existing or render resize handle + handleElm = dom.get('mceResizeHandle' + name); + if (!handleElm) { + handlerContainerElm = editor.getBody(); + + handleElm = dom.add(handlerContainerElm, 'div', { + id: 'mceResizeHandle' + name, + 'data-mce-bogus': true, + 'class': 'mce-resizehandle', + contentEditable: false, // Hides IE move layer cursor + unSelectabe: true, + style: 'cursor:' + name + '-resize; margin:0; padding:0' + }); + + dom.bind(handleElm, 'mousedown', function(e) { + e.preventDefault(); + startDrag(e); + }); + } else { + dom.show(handleElm); + } + + /* + var halfHandleW = handleElm.offsetWidth / 2; + var halfHandleH = handleElm.offsetHeight / 2; + + // Position element + dom.setStyles(handleElm, { + left: Math.floor((targetWidth * handle[0] + selectedElmX) - halfHandleW + (handle[2] * halfHandleW)), + top: Math.floor((targetHeight * handle[1] + selectedElmY) - halfHandleH + (handle[3] * halfHandleH)) + }); + */ + + // Position element + dom.setStyles(handleElm, { + left: (targetWidth * handle[0] + selectedElmX) - (handleElm.offsetWidth / 2), + top: (targetHeight * handle[1] + selectedElmY) - (handleElm.offsetHeight / 2) + }); + }); + } else { + hideResizeRect(); + } + + selectedElm.setAttribute('data-mce-selected', '1'); + } + + function hideResizeRect() { + var name, handleElm; + + if (selectedElm) { + selectedElm.removeAttribute('data-mce-selected'); + } + + for (name in resizeHandles) { + handleElm = dom.get('mceResizeHandle' + name); + if (handleElm) { + dom.unbind(handleElm); + dom.remove(handleElm); + } + } + } + + function updateResizeRect(e) { + var controlElm; + + function isChildOrEqual(node, parent) { + do { + if (node === parent) { + return true; + } + } while ((node = node.parentNode)); + } + + // Remove data-mce-selected from all elements since they might have been copied using Ctrl+c/v + each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function(img) { + img.removeAttribute('data-mce-selected'); + }); + + controlElm = e.type == 'mousedown' ? e.target : selection.getNode(); + controlElm = dom.getParent(controlElm, isIE ? 'table' : 'table,img,hr'); + + if (controlElm) { + if (isChildOrEqual(selection.getStart(), controlElm) && isChildOrEqual(selection.getEnd(), controlElm)) { + if (!isIE || (controlElm != selection.getStart() && selection.getStart().nodeName !== 'IMG')) { + showResizeRect(controlElm); + return; + } + } + } + + hideResizeRect(); + } + + function attachEvent(elm, name, func) { + if (elm && elm.attachEvent) { + elm.attachEvent('on' + name, func); + } + } + + function detachEvent(elm, name, func) { + if (elm && elm.detachEvent) { + elm.detachEvent('on' + name, func); + } + } + + function resizeNativeStart(e) { + var target = e.srcElement, pos, name, corner, cornerX, cornerY, relativeX, relativeY; + + pos = target.getBoundingClientRect(); + relativeX = e.clientX - pos.left; + relativeY = e.clientY - pos.top; + + // Figure out what corner we are draging on + for (name in resizeHandles) { + corner = resizeHandles[name]; + + cornerX = target.offsetWidth * corner[0]; + cornerY = target.offsetHeight * corner[1]; + + if (Math.abs(cornerX - relativeX) < 8 && Math.abs(cornerY - relativeY) < 8) { + selectedHandle = corner; + break; + } + } + + // Remove native selection and let the magic begin + resizeStarted = true; + editor.getDoc().selection.empty(); + showResizeRect(target, name, e); + } + + function nativeControlSelect(e) { + var target = e.srcElement; + + if (target != selectedElm) { + detachResizeStartListener(); + + if (target.id.indexOf('mceResizeHandle') === 0) { + e.returnValue = false; + return; + } + + if (target.nodeName == 'IMG' || target.nodeName == 'TABLE') { + hideResizeRect(); + selectedElm = target; + attachEvent(target, 'resizestart', resizeNativeStart); + } + } + } + + function detachResizeStartListener() { + detachEvent(selectedElm, 'resizestart', resizeNativeStart); + } + + function controlSelect(elm) { + var ctrlRng; + + if (!isIE) { + return; + } + + ctrlRng = editableDoc.body.createControlRange(); + + try { + ctrlRng.addElement(elm); + ctrlRng.select(); + return true; + } catch (ex) { + // Ignore since the element can't be control selected for example a P tag + } + } + + editor.on('init', function() { + if (isIE) { + // Hide the resize rect on resize and reselect the image + editor.on('ObjectResized', function(e) { + if (e.target.nodeName != 'TABLE') { + hideResizeRect(); + controlSelect(e.target); + } + }); + + attachEvent(editor.getBody(), 'controlselect', nativeControlSelect); + } else { + try { + // Disable object resizing on Gecko + editor.getDoc().execCommand('enableObjectResizing', false, false); + } catch (ex) { + // Ignore + } + } + + editor.on('nodechange mousedown ResizeEditor', updateResizeRect); + + // Update resize rect while typing in a table + editor.on('keydown keyup', function(e) { + if (selectedElm && selectedElm.nodeName == "TABLE") { + updateResizeRect(e); + } + }); + + // Hide rect on focusout since it would float on top of windows otherwise + //editor.on('focusout', hideResizeRect); + }); + + function destroy() { + selectedElm = selectedElmGhost = null; + + if (isIE) { + detachResizeStartListener(); + detachEvent(editor.getBody(), 'controlselect', nativeControlSelect); + } + } + + return { + controlSelect: controlSelect, + destroy: destroy + }; + }; +}); + +// Included from: js/tinymce/classes/dom/Selection.js + +/** + * Selection.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles text and control selection it's an crossbrowser utility class. + * Consult the TinyMCE Wiki API for more details and examples on how to use this class. + * + * @class tinymce.dom.Selection + * @example + * // Getting the currently selected node for the active editor + * alert(tinymce.activeEditor.selection.getNode().nodeName); + */ +define("tinymce/dom/Selection", [ + "tinymce/dom/TreeWalker", + "tinymce/dom/TridentSelection", + "tinymce/dom/ControlSelection", + "tinymce/Env", + "tinymce/util/Tools" +], function(TreeWalker, TridentSelection, ControlSelection, Env, Tools) { + var each = Tools.each, grep = Tools.grep, trim = Tools.trim; + var isIE = Env.ie, isOpera = Env.opera; + + /** + * Constructs a new selection instance. + * + * @constructor + * @method Selection + * @param {tinymce.dom.DOMUtils} dom DOMUtils object reference. + * @param {Window} win Window to bind the selection object to. + * @param {tinymce.dom.Serializer} serializer DOM serialization class to use for getContent. + */ + function Selection(dom, win, serializer, editor) { + var self = this; + + self.dom = dom; + self.win = win; + self.serializer = serializer; + self.editor = editor; + + self.controlSelection = new ControlSelection(self, editor); + + editor.on('nodechange', function() { + var rng; + + // Use old style IE range since we want to restore control selections + if (editor.getDoc().selection) { + rng = editor.getDoc().selection.createRange(); + } else { + rng = self.getRng(); + } + + self.lastRng = rng; + }); + + // No W3C Range support + if (!self.win.getSelection) { + self.tridentSel = new TridentSelection(self); + } + } + + Selection.prototype = { + /** + * Move the selection cursor range to the specified node and offset. + * @param node Node to put the cursor in. + * @param offset Offset from the start of the node to put the cursor at. + */ + setCursorLocation: function(node, offset) { + var self = this, rng = self.dom.createRng(); + rng.setStart(node, offset); + rng.setEnd(node, offset); + self.setRng(rng); + self.collapse(false); + }, + + /** + * Returns the selected contents using the DOM serializer passed in to this class. + * + * @method getContent + * @param {Object} s Optional settings class with for example output format text or html. + * @return {String} Selected contents in for example HTML format. + * @example + * // Alerts the currently selected contents + * alert(tinymce.activeEditor.selection.getContent()); + * + * // Alerts the currently selected contents as plain text + * alert(tinymce.activeEditor.selection.getContent({format: 'text'})); + */ + getContent: function(args) { + var self = this, rng = self.getRng(), tmpElm = self.dom.create("body"); + var se = self.getSel(), whiteSpaceBefore, whiteSpaceAfter, fragment; + + args = args || {}; + whiteSpaceBefore = whiteSpaceAfter = ''; + args.get = true; + args.format = args.format || 'html'; + args.selection = true; + self.editor.fire('BeforeGetContent', args); + + if (args.format == 'text') { + return self.isCollapsed() ? '' : (rng.text || (se.toString ? se.toString() : '')); + } + + if (rng.cloneContents) { + fragment = rng.cloneContents(); + + if (fragment) { + tmpElm.appendChild(fragment); + } + } else if (rng.item !== undefined || rng.htmlText !== undefined) { + // 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. + tmpElm.innerHTML = '
    ' + (rng.item ? rng.item(0).outerHTML : rng.htmlText); + tmpElm.removeChild(tmpElm.firstChild); + } else { + tmpElm.innerHTML = rng.toString(); + } + + // Keep whitespace before and after + if (/^\s/.test(tmpElm.innerHTML)) { + whiteSpaceBefore = ' '; + } + + if (/\s+$/.test(tmpElm.innerHTML)) { + whiteSpaceAfter = ' '; + } + + args.getInner = true; + + args.content = self.isCollapsed() ? '' : whiteSpaceBefore + self.serializer.serialize(tmpElm, args) + whiteSpaceAfter; + self.editor.fire('GetContent', args); + + return args.content; + }, + + /** + * Sets the current selection to the specified content. If any contents is selected it will be replaced + * with the contents passed in to this function. If there is no selection the contents will be inserted + * where the caret is placed in the editor/page. + * + * @method setContent + * @param {String} content HTML contents to set could also be other formats depending on settings. + * @param {Object} args Optional settings object with for example data format. + * @example + * // Inserts some HTML contents at the current selection + * tinymce.activeEditor.selection.setContent('Some contents'); + */ + setContent: function(content, args) { + var self = this, rng = self.getRng(), caretNode, doc = self.win.document, frag, temp; + + args = args || {format: 'html'}; + args.set = true; + args.selection = true; + content = args.content = content; + + // Dispatch before set content event + if (!args.no_events) { + self.editor.fire('BeforeSetContent', args); + } + + content = args.content; + + if (rng.insertNode) { + // Make caret marker since insertNode places the caret in the beginning of text after insert + content += '_'; + + // 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('_' + content); + self.dom.remove('__mce_tmp'); + } else { + rng.pasteHTML(content); + } + } + + // Dispatch set content event + if (!args.no_events) { + self.editor.fire('SetContent', args); + } + }, + + /** + * Returns the start element of a selection range. If the start is in a text + * node the parent element will be returned. + * + * @method getStart + * @return {Element} Start element of selection range. + */ + getStart: function() { + var self = this, rng = self.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(); + if (startElement.ownerDocument !== self.dom.doc) { + startElement = self.dom.getRoot(); + } + + // 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; + } + }, + + /** + * Returns the end element of a selection range. If the end is in a text + * node the parent element will be returned. + * + * @method getEnd + * @return {Element} End element of selection range. + */ + getEnd: function() { + var self = this, rng = self.getRng(), endElement, endOffset; + + if (rng.duplicate || rng.item) { + if (rng.item) { + return rng.item(0); + } + + rng = rng.duplicate(); + rng.collapse(0); + endElement = rng.parentElement(); + if (endElement.ownerDocument !== self.dom.doc) { + endElement = self.dom.getRoot(); + } + + if (endElement && endElement.nodeName == 'BODY') { + return endElement.lastChild || endElement; + } + + return endElement; + } else { + endElement = rng.endContainer; + endOffset = rng.endOffset; + + if (endElement.nodeType == 1 && endElement.hasChildNodes()) { + endElement = endElement.childNodes[endOffset > 0 ? endOffset - 1 : endOffset]; + } + + if (endElement && endElement.nodeType == 3) { + return endElement.parentNode; + } + + return endElement; + } + }, + + /** + * Returns a bookmark location for the current selection. This bookmark object + * can then be used to restore the selection after some content modification to the document. + * + * @method getBookmark + * @param {Number} type Optional state if the bookmark should be simple or not. Default is complex. + * @param {Boolean} normalized Optional state that enables you to get a position that it would be after normalization. + * @return {Object} Bookmark object, use moveToBookmark with this object to restore the selection. + * @example + * // Stores a bookmark of the current selection + * var bm = tinymce.activeEditor.selection.getBookmark(); + * + * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content'); + * + * // Restore the selection bookmark + * tinymce.activeEditor.selection.moveToBookmark(bm); + */ + getBookmark: function(type, normalized) { + var t = this, dom = t.dom, rng, rng2, id, collapsed, name, element, chr = '', styles; + + function findIndex(name, element) { + var index = 0; + + each(dom.select(name), function(node, i) { + if (node == element) { + index = i; + } + }); + + return index; + } + + function normalizeTableCellSelection(rng) { + function moveEndPoint(start) { + var container, offset, childNodes, prefix = start ? 'start' : 'end'; + + container = rng[prefix + 'Container']; + offset = rng[prefix + 'Offset']; + + if (container.nodeType == 1 && container.nodeName == "TR") { + childNodes = container.childNodes; + container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)]; + if (container) { + offset = start ? 0 : container.childNodes.length; + rng['set' + (start ? 'Start' : 'End')](container, offset); + } + } + } + + moveEndPoint(true); + moveEndPoint(); + + return rng; + } + + 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) { + element = t.getNode(); + name = element.nodeName; + + if (name == 'IMG') { + return {name: name, index: findIndex(name, element)}; + } + + 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 = t.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('' + chr + ''); + + // Insert end marker + if (!collapsed) { + rng2.collapse(false); + + // Detect the empty space after block elements in IE and move the + // end back one character

    ] becomes

    ]

    + rng.moveToElementText(rng2.parentElement()); + if (rng.compareEndPoints('StartToEnd', rng2) === 0) { + rng2.move('character', -1); + } + + rng2.pasteHTML('' + chr + ''); + } + } 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)}; + } + + // W3C method + rng2 = normalizeTableCellSelection(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 = normalizeTableCellSelection(rng); + 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}; + }, + + /** + * Restores the selection to the specified bookmark. + * + * @method moveToBookmark + * @param {Object} bookmark Bookmark to restore selection from. + * @return {Boolean} true/false if it was successful or not. + * @example + * // Stores a bookmark of the current selection + * var bm = tinymce.activeEditor.selection.getBookmark(); + * + * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content'); + * + * // Restore the selection bookmark + * tinymce.activeEditor.selection.moveToBookmark(bm); + */ + moveToBookmark: function(bookmark) { + var t = this, dom = t.dom, 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(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 && !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 = '
    '; + } + + 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); + } + } + }, + + /** + * Selects the specified element. This will place the start and end of the selection range around the element. + * + * @method select + * @param {Element} node HMTL DOM element to select. + * @param {Boolean} content Optional bool state if the contents should be selected or not on non IE browser. + * @return {Element} Selected element the same element as the one that got passed in. + * @example + * // Select the first paragraph in the active editor + * tinymce.activeEditor.selection.select(tinymce.activeEditor.dom.select('p')[0]); + */ + 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 && 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) { + if (!content && t.controlSelection.controlSelect(node)) { + return; + } + + 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; + }, + + /** + * Returns true/false if the selection range is collapsed or not. Collapsed means if it's a caret or a larger selection. + * + * @method isCollapsed + * @return {Boolean} true/false state if the selection range is collapsed or not. + * Collapsed means if it's a caret or a larger selection. + */ + isCollapsed: function() { + var self = this, rng = self.getRng(), sel = self.getSel(); + + if (!rng || rng.item) { + return false; + } + + if (rng.compareEndPoints) { + return rng.compareEndPoints('StartToEnd', rng) === 0; + } + + return !sel || rng.collapsed; + }, + + /** + * Collapse the selection to start or end of range. + * + * @method collapse + * @param {Boolean} to_start Optional boolean state if to collapse to end or not. Defaults to start. + */ + 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); + }, + + /** + * Returns the browsers internal selection object. + * + * @method getSel + * @return {Selection} Internal browser selection object. + */ + getSel: function() { + var win = this.win; + + return win.getSelection ? win.getSelection() : win.document.selection; + }, + + /** + * Returns the browsers internal range object. + * + * @method getRng + * @param {Boolean} w3c Forces a compatible W3C range on IE. + * @return {Range} Internal browser range object. + * @see http://www.quirksmode.org/dom/range_intro.html + * @see http://www.dotvoid.com/2001/03/using-the-range-object-in-mozilla/ + */ + getRng: function(w3c) { + var self = this, selection, rng, elm, doc = self.win.document; + + // Found tridentSel object then we need to use that one + if (w3c && self.tridentSel) { + return self.tridentSel.getRangeAt(0); + } + + try { + if ((selection = self.getSel())) { + if (selection.rangeCount > 0) { + rng = selection.getRangeAt(0); + } else { + rng = selection.createRange ? selection.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 (isIE && rng && rng.setStart && doc.selection.createRange().item) { + elm = doc.selection.createRange().item(0); + rng = doc.createRange(); + rng.setStartBefore(elm); + rng.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 (!rng) { + rng = doc.createRange ? doc.createRange() : doc.body.createTextRange(); + } + + // If range is at start of document then move it to start of body + if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) { + elm = self.dom.getRoot(); + rng.setStart(elm, 0); + rng.setEnd(elm, 0); + } + + if (self.selectedRange && self.explicitRange) { + if (rng.compareBoundaryPoints(rng.START_TO_START, self.selectedRange) === 0 && + rng.compareBoundaryPoints(rng.END_TO_END, self.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. + rng = self.explicitRange; + } else { + self.selectedRange = null; + self.explicitRange = null; + } + } + + return rng; + }, + + /** + * Changes the selection to the specified DOM range. + * + * @method setRng + * @param {Range} rng Range to select. + */ + setRng: function(rng, forward) { + var self = this, sel; + + self.lastRng = null; + + // Is IE specific range + if (rng.select) { + try { + rng.select(); + } catch (ex) { + // Needed for some odd IE bug #1843306 + } + + return; + } + + if (!self.tridentSel) { + sel = self.getSel(); + + if (sel) { + self.explicitRange = rng; + + try { + sel.removeAllRanges(); + } catch (ex) { + // IE9 might throw errors here don't know why + } + + sel.addRange(rng); + + // Forward is set to false and we have an extend function + if (forward === false && sel.extend) { + sel.collapse(rng.endContainer, rng.endOffset); + sel.extend(rng.startContainer, rng.startOffset); + } + + // adding range isn't always successful so we need to check range count otherwise an exception can occur + self.selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null; + } + } else { + // Is W3C Range fake range on IE + if (rng.cloneRange) { + try { + self.tridentSel.addRange(rng); + return; + } catch (ex) { + //IE9 throws an error here if called before selection is placed in the editor + } + } + } + }, + + /** + * Sets the current selection to the specified DOM element. + * + * @method setNode + * @param {Element} elm Element to set as the contents of the selection. + * @return {Element} Returns the element that got passed in. + * @example + * // Inserts a DOM node at current selection/caret location + * tinymce.activeEditor.selection.setNode(tinymce.activeEditor.dom.create('img', {src: 'some.gif', title: 'some title'})); + */ + setNode: function(elm) { + var self = this; + + self.setContent(self.dom.getOuterHTML(elm)); + + return elm; + }, + + /** + * Returns the currently selected element or the common ancestor element for both start and end of the selection. + * + * @method getNode + * @return {Element} Currently selected element or common ancestor element. + * @example + * // Alerts the currently selected elements node name + * alert(tinymce.activeEditor.selection.getNode().nodeName); + */ + getNode: function() { + var self = this, rng = self.getRng(), elm; + var startContainer = rng.startContainer, endContainer = rng.endContainer; + var startOffset = rng.startOffset, endOffset = rng.endOffset; + + function skipEmptyTextNodes(node, forwards) { + var orig = node; + + while (node && node.nodeType === 3 && node.length === 0) { + node = forwards ? node.nextSibling : node.previousSibling; + } + + return node || orig; + } + + // Range maybe lost after the editor is made visible again + if (!rng) { + return self.dom.getRoot(); + } + + if (rng.setStart) { + elm = rng.commonAncestorContainer; + + // Handle selection a image or other control like element such as anchors + if (!rng.collapsed) { + if (startContainer == endContainer) { + if (endOffset - startOffset < 2) { + if (startContainer.hasChildNodes()) { + elm = startContainer.childNodes[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 (startContainer.nodeType === 3 && endContainer.nodeType === 3) { + if (startContainer.length === startOffset) { + startContainer = skipEmptyTextNodes(startContainer.nextSibling, true); + } else { + startContainer = startContainer.parentNode; + } + + if (endOffset === 0) { + endContainer = skipEmptyTextNodes(endContainer.previousSibling, false); + } else { + endContainer = endContainer.parentNode; + } + + if (startContainer && startContainer === endContainer) { + return startContainer; + } + } + } + + if (elm && elm.nodeType == 3) { + return elm.parentNode; + } + + return elm; + } + + return rng.item ? rng.item(0) : rng.parentElement(); + }, + + getSelectedBlocks: function(startElm, endElm) { + var self = this, dom = self.dom, node, selectedBlocks = []; + + startElm = dom.getParent(startElm || self.getStart(), dom.isBlock); + endElm = dom.getParent(endElm || self.getEnd(), dom.isBlock); + + if (startElm) { + selectedBlocks.push(startElm); + } + + if (startElm && endElm && startElm != endElm) { + node = startElm; + + var walker = new TreeWalker(startElm, dom.getRoot()); + while ((node = walker.next()) && node != endElm) { + if (dom.isBlock(node)) { + selectedBlocks.push(node); + } + } + } + + if (endElm && startElm != endElm) { + selectedBlocks.push(endElm); + } + + return selectedBlocks; + }, + + isForward: function(){ + var dom = this.dom, sel = this.getSel(), anchorRange, focusRange; + + // No support for selection direction then always return true + if (!sel || !sel.anchorNode || !sel.focusNode) { + return true; + } + + anchorRange = dom.createRng(); + anchorRange.setStart(sel.anchorNode, sel.anchorOffset); + anchorRange.collapse(true); + + focusRange = dom.createRng(); + focusRange.setStart(sel.focusNode, sel.focusOffset); + focusRange.collapse(true); + + return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0; + }, + + normalize: function() { + var self = this, rng, normalized, collapsed; + + function normalizeEndPoint(start) { + var container, offset, walker, dom = self.dom, body = dom.getRoot(), node, nonEmptyElementsMap, nodeName; + + function hasBrBeforeAfter(node, left) { + var walker = new TreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || body); + + while ((node = walker[left ? 'prev' : 'next']())) { + if (node.nodeName === "BR") { + return true; + } + } + } + + function isPrevNode(node, name) { + return node.previousSibling && node.previousSibling.nodeName == name; + } + + // 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 = dom.getRoot(); + 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()) { + offset = Math.min(!start && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1); + container = container.childNodes[offset]; + offset = 0; + + // Don't walk into elements that doesn't have any child nodes like a IMG + if (container.hasChildNodes() && !/TABLE/.test(container.nodeName)) { + // 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: x|x + // Becomes: x|x + // 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: |
    + // Becomes: |
    + // Seems that only gecko has issues with this. + // Special edge case for

    x|

    since we don't want

    x|

    + if (container.nodeType === 1) { + node = container.childNodes[offset]; + if(node && node.nodeName === 'BR' && !isPrevNode(node, 'A') && + !hasBrBeforeAfter(node) && !hasBrBeforeAfter(node, true)) { + findTextNodeRelative(true, container.childNodes[offset]); + } + } + } + + // Lean the start of the selection right if possible + // So this: x[x] + // Becomes: x[x] + 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); + } + } + + // Normalize only on non IE browsers for now + if (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, self.isForward()); + } + }, + + /** + * Executes callback of the current selection matches the specified selector or not and passes the state and args to the callback. + * + * @method selectorChanged + * @param {String} selector CSS selector to check for. + * @param {function} callback Callback with state and args when the selector is matches or not. + */ + selectorChanged: function(selector, callback) { + var self = this, currentSelectors; + + if (!self.selectorChangedData) { + self.selectorChangedData = {}; + currentSelectors = {}; + + self.editor.on('NodeChange', function(e) { + var node = e.element, dom = self.dom, parents = dom.getParents(node, null, dom.getRoot()), matchedSelectors = {}; + + // Check for new matching selectors + each(self.selectorChangedData, function(callbacks, selector) { + each(parents, function(node) { + if (dom.is(node, selector)) { + if (!currentSelectors[selector]) { + // Execute callbacks + each(callbacks, function(callback) { + callback(true, {node: node, selector: selector, parents: parents}); + }); + + currentSelectors[selector] = callbacks; + } + + matchedSelectors[selector] = callbacks; + return false; + } + }); + }); + + // Check if current selectors still match + each(currentSelectors, function(callbacks, selector) { + if (!matchedSelectors[selector]) { + delete currentSelectors[selector]; + + each(callbacks, function(callback) { + callback(false, {node: node, selector: selector, parents: parents}); + }); + } + }); + }); + } + + // Add selector listeners + if (!self.selectorChangedData[selector]) { + self.selectorChangedData[selector] = []; + } + + self.selectorChangedData[selector].push(callback); + + return self; + }, + + scrollIntoView: function(elm) { + var y, viewPort, self = this, dom = self.dom; + + viewPort = dom.getViewPort(self.editor.getWin()); + y = dom.getPos(elm).y; + if (y < viewPort.y || y + 25 > viewPort.y + viewPort.h) { + self.editor.getWin().scrollTo(0, y < viewPort.y ? y : y - viewPort.h + 25); + } + }, + + destroy: function() { + this.win = this.lastRng = null; + this.controlSelection.destroy(); + } + }; + + return Selection; +}); + +// Included from: js/tinymce/classes/dom/RangeUtils.js + +/** + * Range.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/dom/RangeUtils", [ + "tinymce/util/Tools" +], function(Tools) { + var each = Tools.each; + + function RangeUtils(dom) { + /** + * Walks the specified range like object and executes the callback for each sibling collection it finds. + * + * @param {Object} rng Range like object. + * @param {function} callback Callback function to execute for each sibling collection. + */ + 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.mce-item-selected,th.mce-item-selected'); + if (nodes.length > 0) { + each(nodes, function(node) { + callback([node]); + }); + + return; + } + + /** + * Excludes start/end text node if they are out side the range + * + * @private + * @param {Array} nodes Nodes to exclude items from. + * @return {Array} Array with nodes excluding the start/end container if needed. + */ + 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; + } + + /** + * Collects siblings + * + * @private + * @param {Node} node Node to collect siblings from. + * @param {String} name Name of the sibling to check for. + * @return {Array} Array of collected siblings. + */ + function collectSiblings(node, name, end_node) { + var siblings = []; + + for (; node && node != end_node; node = node[name]) { + siblings.push(node); + } + + return siblings; + } + + /** + * Find an end point this is the node just before the common ancestor root. + * + * @private + * @param {Node} node Node to start at. + * @param {Node} root Root/ancestor element to stop just before. + * @return {Node} Node just before the root element. + */ + 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); + }; + + /** + * Splits the specified range at it's start/end points. + * + * @param {Range/RangeObject} rng Range to split. + * @return {Object} Range position object. + */ + 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 + }; + }; + } + + /** + * Compares two ranges and checks if they are equal. + * + * @static + * @param {DOMRange} rng1 First range to compare. + * @param {DOMRange} rng2 First range to compare. + * @return {Boolean} true/false if the ranges are equal. + */ + 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; + }; + + return RangeUtils; +}); + +// Included from: js/tinymce/classes/Formatter.js + +/** + * Formatter.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Text formatter engine class. This class is used to apply formats like bold, italic, font size + * etc to the current selection or specific nodes. This engine was build to replace the browsers + * default formatting logic for execCommand due to it's inconsistant and buggy behavior. + * + * @class tinymce.Formatter + * @example + * tinymce.activeEditor.formatter.register('mycustomformat', { + * inline: 'span', + * styles: {color: '#ff0000'} + * }); + * + * tinymce.activeEditor.formatter.apply('mycustomformat'); + */ +define("tinymce/Formatter", [ + "tinymce/dom/TreeWalker", + "tinymce/dom/RangeUtils", + "tinymce/util/Tools" +], function(TreeWalker, RangeUtils, Tools) { + /** + * Constructs a new formatter instance. + * + * @constructor Formatter + * @param {tinymce.Editor} ed Editor instance to construct the formatter engine to. + */ + return function(ed) { + var formats = {}, + dom = ed.dom, + selection = ed.selection, + rangeUtils = new RangeUtils(dom), + isValid = ed.schema.isValidChild, + isBlock = dom.isBlock, + forcedRootBlock = ed.settings.forced_root_block, + nodeIndex = dom.nodeIndex, + INVISIBLE_CHAR = '\uFEFF', + MCE_ATTR_RE = /^(src|href|style)$/, + FALSE = false, + TRUE = true, + formatChangeData, + undef, + getContentEditable = dom.getContentEditable, + disableCaretContainer, + markCaretContainersBogus; + + var each = Tools.each, + grep = Tools.grep, + walk = Tools.walk, + extend = Tools.extend; + + function isTextBlock(name) { + if (name.nodeType) { + name = name.nodeName; + } + + return !!ed.schema.getTextBlockElements()[name.toLowerCase()]; + } + + 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,tr,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,tr,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,tr,div,ul,ol,li', styles: {textAlign: 'right'}, defaultBlock: 'div'}, + {selector: 'img,table', collapsed: false, styles: {'float': 'right'}} + ], + + alignjustify: [ + {selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,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'}, + code: {inline: 'code'}, + + link: {inline: 'a', selector: 'a', remove: 'all', split: true, deep: true, + onmatch: function() { + 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 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 + + /** + * Returns the format by name or all formats if no name is specified. + * + * @method get + * @param {String} name Optional name to retrive by. + * @return {Array/Object} Array/Object with all registred formats or a specific format. + */ + function get(name) { + return name ? formats[name] : formats; + } + + /** + * Registers a specific format by name. + * + * @method register + * @param {Object/String} name Name of the format for example "bold". + * @param {Object/Array} format Optional format object or array of format variants + * can only be omitted if the first arg is an object. + */ + 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; + } + } + } + + function getTextDecoration(node) { + var decoration; + + ed.dom.getParent(node, function(n) { + decoration = ed.dom.getStyle(n, 'text-decoration'); + return decoration && decoration !== 'none'; + }); + + return decoration; + } + + function processUnderlineAndColor(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); + } + } + } + + /** + * Applies the specified format to the current selection or specified node. + * + * @method apply + * @param {String} name Name of format to apply. + * @param {Object} vars Optional list of variables to replace within format before applying it. + * @param {Node} node Optional node to apply the format to defaults to current selection. + */ + function apply(name, vars, node) { + var formatList = get(name), format = formatList[0], bookmark, rng, isCollapsed = !node && 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(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(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; + + /** + * Process a list of nodes wrap them. + */ + 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 + // TODO: Break this if up, too complex + if (contentEditable && !hasContentEditableState && format.block && + !format.wrapper && isTextBlock(nodeName) && isValid(parentName, wrapName)) { + 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 + // TODO: Break this if up, too complex + 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) && + (!format.inline || !isBlock(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(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 = grep(node.childNodes); + for (i = 0; i < children.length; i++) { + currentWrapElm.appendChild(children[i]); + } + + node.appendChild(currentWrapElm); + } + + each(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

    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: text + // will become: text + 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 texttext becomes texttext + 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.mce-item-selected,th.mce-item-selected').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)) { + walk(curSelNode, processUnderlineAndColor, 'childNodes'); + processUnderlineAndColor(curSelNode); + } + + selection.moveToBookmark(bookmark); + moveStart(selection.getRng(TRUE)); + ed.nodeChanged(); + } else { + performCaretAction('apply', name, vars); + } + } + } + } + + /** + * Removes the specified format from the current selection or specified node. + * + * @method remove + * @param {String} name Name of format to remove. + * @param {Object} vars Optional list of variables to replace within format before removing it. + * @param {Node/Range} node Optional node or DOM range to remove the format from defaults to current selection. + */ + function remove(name, vars, node) { + var formatList = get(name), format = formatList[0], bookmark, rng, contentEditable = true; + + // Merges the styles for each node + function process(node) { + var children, i, l, 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 = 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; + + 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 + if (/^(TR|TD)$/.test(startContainer.nodeName) && startContainer.firstChild) { + if (startContainer.nodeName == "TD") { + startContainer = startContainer.firstChild || startContainer; + } else { + startContainer = startContainer.firstChild.firstChild || startContainer; + } + } + + // 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.mce-item-selected,th.mce-item-selected').length) { + bookmark = selection.getBookmark(); + removeRngStyle(selection.getRng(TRUE)); + selection.moveToBookmark(bookmark); + + // Check if start element still has formatting then we are at: "text|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); + } + } + + /** + * Toggles the specified format on/off. + * + * @method toggle + * @param {String} name Name of format to apply/remove. + * @param {Object} vars Optional list of variables to replace within format before applying/removing it. + * @param {Node} node Optional node to apply the format to or remove from. Defaults to current selection. + */ + 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); + } + } + + /** + * Return true/false if the specified node has the specified format. + * + * @method matchNode + * @param {Node} node Node to check the format on. + * @param {String} name Format name to check. + * @param {Object} vars Optional list of variables to replace before checking it. + * @param {Boolean} similar Match format that has similar properties. + * @return {Object} Returns the format object it matches or undefined if it doesn't match. + */ + 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; + } + } + } + } + + /** + * Matches the current selection or specified node against the specified format name. + * + * @method match + * @param {String} name Name of format to match. + * @param {Object} vars Optional list of variables to replace before checking it. + * @param {Node} node Optional node to check. + * @return {boolean} true/false if the specified selection/node matches the 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; + } + + /** + * Matches the current selection against the array of formats and returns a new array with matching formats. + * + * @method matchAll + * @param {Array} names Name of format to match. + * @param {Object} vars Optional list of variables to replace before checking it. + * @return {Array} Array with matched formats. + */ + function matchAll(names, vars) { + var startElement, matchedFormatNames = [], checkedMap = {}; + + // 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); + } + } + }, dom.getRoot()); + + return matchedFormatNames; + } + + /** + * Returns true/false if the specified format can be applied to the current selection or not. It + * will currently only check the state for selector formats, it returns true on all other format types. + * + * @method canApply + * @param {String} name Name of format to check. + * @return {boolean} true/false if the specified format can be applied to the current selection/node. + */ + 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; + } + + /** + * Executes the specified callback when the current selection matches the formats or not. + * + * @method formatChanged + * @param {String} formats Comma separated list of formats to check for. + * @param {function} callback Callback with state and args when the format is changed/toggled on/off. + * @param {Boolean} similar True/false state if the match should handle similar or exact formats. + */ + function formatChanged(formats, callback, similar) { + var currentFormats; + + // Setup format node change logic + if (!formatChangeData) { + formatChangeData = {}; + currentFormats = {}; + + ed.on('NodeChange', function(e) { + var parents = getParents(e.element), matchedFormats = {}; + + // Check for new formats + each(formatChangeData, function(callbacks, format) { + each(parents, function(node) { + if (matchNode(node, format, {}, callbacks.similar)) { + if (!currentFormats[format]) { + // Execute callbacks + each(callbacks, function(callback) { + callback(true, {node: node, format: format, parents: parents}); + }); + + currentFormats[format] = callbacks; + } + + matchedFormats[format] = callbacks; + return false; + } + }); + }); + + // Check if current formats still match + each(currentFormats, function(callbacks, format) { + if (!matchedFormats[format]) { + delete currentFormats[format]; + + each(callbacks, function(callback) { + callback(false, {node: e.element, format: format, parents: parents}); + }); + } + }); + }); + } + + // Add format listeners + each(formats.split(','), function(format) { + if (!formatChangeData[format]) { + formatChangeData[format] = []; + formatChangeData[format].similar = similar; + } + + formatChangeData[format].push(callback); + }); + + return this; + } + + // Expose to public + extend(this, { + get: get, + register: register, + apply: apply, + remove: remove, + toggle: toggle, + match: match, + matchAll: matchAll, + matchNode: matchNode, + canApply: canApply, + formatChanged: formatChanged + }); + + // Initialize + defaultFormats(); + addKeyboardShortcuts(); + ed.on('BeforeGetContent', function() { + if (markCaretContainersBogus) { + markCaretContainersBogus(); + } + }); + ed.on('mouseup keydown', function(e) { + if (disableCaretContainer) { + disableCaretContainer(e); + } + }); + + // Private functions + + /** + * Checks if the specified nodes name matches the format inline/block or selector. + * + * @private + * @param {Node} node Node to match against the specified format. + * @param {Object} format Format object o match with. + * @return {boolean} true/false if the format matches. + */ + 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 node.nodeType == 1 && dom.is(node, format.selector); + } + } + + /** + * Compares two string/nodes regardless of their case. + * + * @private + * @param {String/Node} Node or string to compare. + * @param {String/Node} Node or string to compare. + * @return {boolean} True/false if they match. + */ + function isEq(str1, str2) { + str1 = str1 || ''; + str2 = str2 || ''; + + str1 = '' + (str1.nodeName || str1); + str2 = '' + (str2.nodeName || str2); + + return str1.toLowerCase() == str2.toLowerCase(); + } + + /** + * Returns the style by name on the specified node. This method modifies the style + * contents to make it more easy to match. This will resolve a few browser issues. + * + * @private + * @param {Node} node to get style from. + * @param {String} name Style name to get. + * @return {String} Style item value. + */ + 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; + } + + /** + * Replaces variables in the value. The variable format is %var. + * + * @private + * @param {String} value Value to replace variables in. + * @param {Object} vars Name/value array with variables to replace. + * @return {String} New value with replaced variables. + */ + 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; + } + + /** + * Expands the specified range like object to depending on format. + * + * For example on block formats it will move the start/end position + * to the beginning of the current block. + * + * @private + * @param {Object} rng Range like object. + * @param {Array} formats Array with formats to expand by. + * @return {Object} Expanded range like object. + */ + function expandRng(rng, format, remove) { + var 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, sibling, siblingName, root; + + container = parent = start ? startContainer : endContainer; + siblingName = start ? 'previousSibling' : 'nextSibling'; + root = dom.getRoot(); + + function isBogusBr(node) { + return node.nodeName == "BR" && node.getAttribute('data-mce-bogus') && !node.nextSibling; + } + + // 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) && !isBogusBr(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) { + 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, isTextBlock); + } + + // 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 !: !

    *texttext*

    ! + // 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 + }; + } + + /** + * Removes the specified format for the specified node. It will also remove the node if it doesn't have + * any attributes if the format specifies it to do so. + * + * @private + * @param {Object} format Format object with items to remove from node. + * @param {Object} vars Name/value object with variables to apply to format. + * @param {Node} node Node to remove the format styles on. + * @param {Node} compare_node Optional compare node, if specified the styles will be compared to that node. + * @return {Boolean} True/false if the node was removed or not. + */ + 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 or + if (format.remove != 'none') { + removeNode(node, format); + return TRUE; + } + } + + /** + * Removes the node and wrap it's children in paragraphs before doing so or + * appends BR elements to the beginning/end of the block element if forcedRootBlocks is disabled. + * + * If the div in the node below gets removed: + * text
    text
    text + * + * Output becomes: + * text

    text
    text + * + * So when the div is removed the result is: + * text
    text
    text + * + * @private + * @param {Node} node Node to remove + apply BR/P elements to. + * @param {Object} format Format rule. + * @return {Node} Input node. + */ + 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(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); + } + + /** + * Returns the next/previous non whitespace node. + * + * @private + * @param {Node} node Node to start at. + * @param {boolean} next (Optional) Include next or previous node defaults to previous. + * @param {boolean} inc (Optional) Include the current node in checking. Defaults to false. + * @return {Node} Next or previous node or undefined if it wasn't found. + */ + 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; + } + } + } + } + + /** + * Checks if the specified node is a bookmark node or not. + * + * @param {Node} node Node to check if it's a bookmark node or not. + * @return {Boolean} true/false if the node is a bookmark node. + */ + function isBookmarkNode(node) { + return node && node.nodeType == 1 && node.getAttribute('data-mce-type') == 'bookmark'; + } + + /** + * Merges the next/previous sibling element if they match. + * + * @private + * @param {Node} prev Previous node to compare/merge. + * @param {Node} next Next node to compare/merge. + * @return {Node} Next node if we didn't merge and prev node if we did. + */ + function mergeSiblings(prev, next) { + var sibling, tmpSibling; + + /** + * Compares two nodes and checks if it's attributes and styles matches. + * This doesn't compare classes as items since their order is significant. + * + * @private + * @param {Node} node1 First node to compare with. + * @param {Node} node2 Second node to compare with. + * @return {boolean} True/false if the nodes are the same or not. + */ + function compareElements(node1, node2) { + // Not the same name + if (node1.nodeName != node2.nodeName) { + return FALSE; + } + + /** + * Returns all the nodes attributes excluding internal ones, styles and classes. + * + * @private + * @param {Node} node Node to get attributes from. + * @return {Object} Name/value object with attributes and attribute values. + */ + 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; + } + + /** + * Compares two objects checks if it's key + value exists in the other one. + * + * @private + * @param {Object} obj1 First object to compare. + * @param {Object} obj2 Second object to compare. + * @return {boolean} True/false if the objects matches or not. + */ + 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(grep(next.childNodes), function(node) { + prev.appendChild(node); + }); + + return prev; + } + } + + return next; + } + + function getContainer(rng, start) { + var container, offset, lastIdx; + + 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); + } + } + + // Checks if the parent caret container node isn't empty if that is the case it + // will remove the bogus state on all children that isn't empty + function unmarkBogusCaretParents() { + var caretContainer; + + caretContainer = getParentCaretContainer(selection.getStart()); + if (caretContainer && !dom.isEmpty(caretContainer)) { + walk(caretContainer, function(node) { + if (node.nodeType == 1 && node.id !== caretContainerId && !dom.isEmpty(node)) { + dom.setAttrib(node, 'data-mce-bogus', null); + } + }, 'childNodes'); + } + } + + // Only bind the caret events once + if (!ed._hasCaretEvents) { + // Mark current caret container elements as bogus when getting the contents so we don't end up with empty elements + markCaretContainersBogus = 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'); + } + } + }; + + disableCaretContainer = function(e) { + var keyCode = e.keyCode; + + removeCaretContainer(); + + // Remove caret container on keydown and it's a backspace, enter or left/right arrow keys + if (keyCode == 8 || keyCode == 37 || keyCode == 39) { + removeCaretContainer(getParentCaretContainer(selection.getStart())); + } + + unmarkBogusCaretParents(); + }; + + // Remove bogus state if they got filled by contents using editor.selection.setContent + ed.on('SetContent', function(e) { + if (e.selection) { + unmarkBogusCaretParents(); + } + }); + ed._hasCaretEvents = true; + } + + // Do apply or remove caret format + if (type == "apply") { + applyCaretFormat(); + } else { + removeCaretFormat(); + } + } + + /** + * Moves the start to the first suitable text node. + */ + 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; + } + } + } + } + }; +}); + +// Included from: js/tinymce/classes/UndoManager.js + +/** + * UndoManager.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles the undo/redo history levels for the editor. Since the build in undo/redo has major drawbacks a custom one was needed. + * + * @class tinymce.UndoManager + */ +define("tinymce/UndoManager", [ + "tinymce/Env", + "tinymce/util/Tools" +], function(Env, Tools) { + var trim = Tools.trim, trimContentRegExp; + + trimContentRegExp = new RegExp([ + ']+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\\/span>', // Trim bogus spans like caret containers + ']+data-mce-bogus[^>]+><\\/div>', // Trim bogus divs like resize handles + '\\s?data-mce-selected="[^"]+"' // Trim temporaty data-mce prefixed attributes like data-mce-selected + ].join('|'), 'gi'); + + return function(editor) { + var self, index = 0, data = [], beforeBookmark; + + // Returns a trimmed version of the current editor contents + function getContent() { + return trim(editor.getContent({format: 'raw', no_events: 1}).replace(trimContentRegExp, '')); + } + + function addNonTypingUndoLevel() { + self.typing = false; + self.add(); + } + + // Add initial undo level when the editor is initialized + editor.on('init', function() { + self.add(); + }); + + // Get position before an execCommand is processed + editor.on('BeforeExecCommand', function(e) { + var cmd = e.command; + + if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint') { + self.beforeChange(); + } + }); + + // Add undo level after an execCommand call was made + editor.on('ExecCommand', function(e) { + var cmd = e.command; + + if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint') { + self.add(); + } + }); + + editor.on('ObjectResizeStart', function() { + self.beforeChange(); + }); + + editor.on('SaveContent ObjectResized', addNonTypingUndoLevel); + editor.dom.bind(editor.dom.getRoot(), 'dragend', addNonTypingUndoLevel); + editor.dom.bind(editor.getBody(), 'focusout', function() { + if (!editor.removed && self.typing) { + addNonTypingUndoLevel(); + } + }); + + editor.on('KeyUp', function(e) { + var keyCode = e.keyCode; + + if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 45 || keyCode == 13 || e.ctrlKey) { + addNonTypingUndoLevel(); + editor.nodeChanged(); + } + + if (keyCode == 46 || keyCode == 8 || (Env.isMac && (keyCode == 91 || keyCode == 93))) { + editor.nodeChanged(); + } + }); + + editor.on('KeyDown', function(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.on('MouseDown', function() { + 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'); + + editor.on('AddUndo Undo Redo ClearUndos MouseUp', function(e) { + if (!e.isDefaultPrevented()) { + editor.nodeChanged(); + } + }); + + self = { + // Explose for debugging reasons + data: data, + + /** + * State if the user is currently typing or not. This will add a typing operation into one undo + * level instead of one new level for each keystroke. + * + * @field {Boolean} typing + */ + typing: false, + + /** + * Stores away a bookmark to be used when performing an undo action so that the selection is before + * the change has been made. + * + * @method beforeChange + */ + beforeChange: function() { + beforeBookmark = editor.selection.getBookmark(2, true); + }, + + /** + * Adds a new undo level/snapshot to the undo list. + * + * @method add + * @param {Object} l Optional undo level object to add. + * @return {Object} Undo level that got added or null it a level wasn't needed. + */ + add: function(level) { + var i, settings = editor.settings, lastLevel; + + level = level || {}; + level.content = getContent(); + + if (editor.fire('BeforeAddUndo', {level: level}).isDefaultPrevented()) { + return null; + } + + // 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; + + editor.fire('AddUndo', {level: level, lastLevel: lastLevel}); + editor.isNotDirty = 0; + + return level; + }, + + /** + * Undoes the last action. + * + * @method undo + * @return {Object} Undo level or null if no undo was performed. + */ + undo: function() { + var level; + + 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); + + editor.fire('undo', {level: level}); + } + + return level; + }, + + /** + * Redoes the last action. + * + * @method redo + * @return {Object} Redo level or null if no redo was performed. + */ + redo: function() { + var level; + + if (index < data.length - 1) { + level = data[++index]; + + editor.setContent(level.content, {format: 'raw'}); + editor.selection.moveToBookmark(level.bookmark); + + editor.fire('redo', {level: level}); + } + + return level; + }, + + /** + * Removes all undo levels. + * + * @method clear + */ + clear: function() { + data = []; + index = 0; + self.typing = false; + editor.fire('ClearUndos'); + }, + + /** + * Returns true/false if the undo manager has any undo levels. + * + * @method hasUndo + * @return {Boolean} true/false if the undo manager has any undo levels. + */ + hasUndo: function() { + // Has undo levels or typing and content isn't the same as the initial level + return index > 0 || (self.typing && data[0] && getContent() != data[0].content); + }, + + /** + * Returns true/false if the undo manager has any redo levels. + * + * @method hasRedo + * @return {Boolean} true/false if the undo manager has any redo levels. + */ + hasRedo: function() { + return index < data.length - 1 && !this.typing; + }, + + /** + * Executes the specified function in an undo transation. The selection + * before the modification will be stored to the undo stack and if the DOM changes + * it will add a new undo level. + * + * @method transact + * @params {function} callback + */ + transact: function(callback) { + self.beforeChange(); + callback(); + self.add(); + } + }; + + return self; + }; +}); + +// Included from: js/tinymce/classes/EnterKey.js + +/** + * EnterKey.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Contains logic for handling the enter key to split/generate block elements. + */ +define("tinymce/EnterKey", [ + "tinymce/dom/TreeWalker", + "tinymce/Env" +], function(TreeWalker, Env) { + var isIE = Env.ie; + + return function(editor) { + var dom = editor.dom, selection = editor.selection, settings = editor.settings; + var undoManager = editor.undoManager, schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements(); + + function handleEnterKey(evt) { + var rng = selection.getRng(true), tmpRng, editableRoot, container, offset, parentBlock, documentMode, shiftKey, + 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|FORM)$/.test(node.nodeName) && + !/^(fixed|absolute)/i.test(node.style.position) && + dom.getContentEditable(node) !== "true"; + } + + // Renders empty block on IE + function renderBlockOnIE(block) { + var oldRng; + + if (dom.isBlock(block)) { + oldRng = selection.getRng(); + block.appendChild(dom.create('span', null, '\u00a0')); + selection.select(block); + block.lastChild.outerHTML = ''; + selection.setRng(oldRng); + } + } + + // Remove the first empty inline element of the block so this:

    x

    becomes this:

    x

    + function trimInlineElementsOnLeftSideOfBlock(block) { + var node = block, firstChilds = [], i; + + // Find inner most first child ex:

    *

    + while ((node = node.firstChild)) { + if (dom.isBlock(node)) { + return; + } + + if (node.nodeType == 1 && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) { + firstChilds.push(node); + } + } + + i = firstChilds.length; + while (i--) { + node = firstChilds[i]; + if (!node.hasChildNodes() || (node.firstChild == node.lastChild && node.firstChild.nodeValue === '')) { + dom.remove(node); + } else { + // Remove see #5381 + if (node.nodeName == "A" && (node.innerText || node.textContent) === ' ') { + dom.remove(node); + } + } + } + } + + // 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, 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 (nonEmptyElementsMap[node.nodeName.toLowerCase()]) { + 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); + selection.scrollIntoView(root); + } + + // 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)) { + // Never clone a caret containers + if (node.id == '_mce_caret') { + continue; + } + + 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 (!isIE) { + caretNode.innerHTML = '
    '; + } + + 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; + } + + // If the caret if before the first element in parentBlock + if (start && container.nodeType == 1 && container == parentBlock.firstChild) { + 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); + + // If caret is in beginning or end of a text block then jump to the next/previous node + if (container.nodeType == 3) { + if (start && offset === 0) { + walker.prev(); + } else if (!start && offset == container.nodeValue.length) { + walker.next(); + } + } + + while ((node = walker.current())) { + if (node.nodeType === 1) { + // Ignore bogus elements + if (!node.getAttribute('data-mce-bogus')) { + // Keep empty elements like but not trailing br:s like

    text|

    + name = node.nodeName.toLowerCase(); + if (nonEmptyElementsMap[name] && name !== 'br') { + return false; + } + } + } else if (node.nodeType === 3 && !/^[ \t\r\n]*$/.test(node.nodeValue)) { + return false; + } + + if (start) { + walker.prev(); + } else { + walker.next(); + } + } + + 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, rootBlockName, blockName = newBlockName || 'P'; + + // Not in a block element or in a table cell or caption + parentBlock = dom.getParent(container, dom.isBlock); + rootBlockName = editor.getBody().nodeName.toLowerCase(); + 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 && schema.isValidChild(rootBlockName, blockName.toLowerCase())) { + 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; + } + + function getContainerBlock() { + var containerBlockParent = containerBlock.parentNode; + + if (containerBlockParent.nodeName == 'LI') { + return containerBlockParent; + } + + return containerBlock; + } + + // Check if we are in an nested list + var containerBlockParentName = containerBlock.parentNode.nodeName; + if (/^(OL|UL|LI)$/.test(containerBlockParentName)) { + newBlockName = 'LI'; + } + + newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR'); + + if (isFirstOrLastLi(true) && isFirstOrLastLi()) { + if (containerBlockParentName == 'LI') { + // Nested list is inside a LI + dom.insertAfter(newBlock, getContainerBlock()); + } else { + // Is first and last list item then replace the OL/UL with a text block + dom.replace(newBlock, containerBlock); + } + } else if (isFirstOrLastLi(true)) { + if (containerBlockParentName == 'LI') { + // List nested in an LI then move the list to a new sibling LI + dom.insertAfter(newBlock, getContainerBlock()); + newBlock.appendChild(dom.doc.createTextNode(' ')); // Needed for IE so the caret can be placed + newBlock.appendChild(containerBlock); + } else { + // 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 remove LI and add text block after list + dom.insertAfter(newBlock, getContainerBlock()); + renderBlockOnIE(newBlock); + } 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 + containerBlock = getContainerBlock(); + 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 hasRightSideContent() { + var walker = new TreeWalker(container, parentBlock), node; + + while ((node = walker.next())) { + if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) { + return true; + } + } + } + + // Inserts a BR element if the forced_root_block option is set to false or empty string + function insertBr() { + var brElm, extraBr, marker; + + if (container && container.nodeType == 3 && offset >= container.nodeValue.length) { + // Insert extra BR element at the end block elements + if (!isIE && !hasRightSideContent()) { + 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 (isIE && parentBlockName == 'PRE' && (!documentMode || documentMode < 8)) { + brElm.parentNode.insertBefore(dom.doc.createTextNode('\r'), brElm); + } + + // Insert temp marker and scroll to that + marker = dom.create('span', {}, ' '); + brElm.parentNode.insertBefore(marker, brElm); + selection.scrollIntoView(marker); + dom.remove(marker); + + 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; + } + + // Adds a BR at the end of blocks that only contains an IMG or INPUT since + // these might be floated and then they won't expand the block + function addBrToBlockIfNeeded(block) { + var lastChild; + + // IE will render the blocks correctly other browsers needs a BR + if (!isIE) { + block.normalize(); // Remove empty text nodes that got left behind by the extract + + // Check if the block is empty or contains a floated last child + lastChild = block.lastChild; + if (!lastChild || (/^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true)))) { + dom.add(block, 'br'); + } + } + } + + // 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.force_p_newlines ? 'p' : '') || settings.forced_root_block; + newBlockName = newBlockName ? newBlockName.toUpperCase() : ''; + documentMode = dom.doc.documentMode; + shiftKey = evt.shiftKey; + + // 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; + if (isAfterLastNodeInContainer && container.nodeType == 3) { + offset = container.nodeValue.length; + } else { + 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 || shiftKey) { + insertBr(); + } + + return; + } + + // Wrap the current node and it's sibling in a default block if it's needed. + // for example this text|text2 will become this

    text|text2

    + // This won't happen if root blocks are disabled or the shiftKey is pressed + if ((newBlockName && !shiftKey) || (!newBlockName && 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 + + // Enter inside block contained within a LI then split or insert before/after LI + if (containerBlockName == 'LI' && !evt.ctrlKey) { + parentBlock = containerBlock; + parentBlockName = containerBlockName; + } + + // Handle enter in LI + if (parentBlockName == 'LI') { + if (!newBlockName && shiftKey) { + insertBr(); + return; + } + + // Handle enter inside an empty list item + if (dom.isEmpty(parentBlock)) { + 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 (!shiftKey) { + insertBr(); + return; + } + } else { + // If no root block is configured then insert a BR by default or if the shiftKey is pressed + if ((!newBlockName && !shiftKey && parentBlockName != 'LI') || (newBlockName && shiftKey)) { + insertBr(); + return; + } + } + + // If parent block is root then never insert new blocks + if (newBlockName && parentBlock === editor.getBody()) { + 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|FIGURE)$/.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); + } + + moveToCaretPosition(newBlock); + } else if (isCaretAtStartOrEndOfBlock(true)) { + // Insert new block before + newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock); + renderBlockOnIE(newBlock); + } 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); + trimInlineElementsOnLeftSideOfBlock(newBlock); + addBrToBlockIfNeeded(parentBlock); + moveToCaretPosition(newBlock); + } + + dom.setAttrib(newBlock, 'id', ''); // Remove ID since it needs to be document unique + undoManager.add(); + } + + editor.on('keydown', function(evt) { + if (evt.keyCode == 13) { + if (handleEnterKey(evt) !== false) { + evt.preventDefault(); + } + } + }); + }; +}); + +// Included from: js/tinymce/classes/ForceBlocks.js + +/** + * ForceBlocks.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/ForceBlocks", [], function() { + return function(editor) { + var settings = editor.settings, dom = editor.dom, selection = editor.selection; + var schema = editor.schema, blockElements = schema.getBlockElements(); + + function addRootBlocks() { + var node = selection.getStart(), rootNode = editor.getBody(), rng; + var startContainer, startOffset, endContainer, endOffset, rootBlockNode; + var tempNode, offset = -0xFFFFFF, wrapped, restoreSelection; + var tmpRng, rootNodeName, forcedRootBlock; + + forcedRootBlock = settings.forced_root_block; + + if (!node || node.nodeType !== 1 || !forcedRootBlock) { + return; + } + + // Check if node is wrapped in block + while (node && 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; + restoreSelection = editor.getDoc().activeElement === rootNode; + } else { + // Force control range into text range + if (rng.item) { + node = rng.item(0); + rng = editor.getDoc().body.createTextRange(); + rng.moveToElementText(node); + } + + restoreSelection = rng.parentElement().ownerDocument === editor.getDoc(); + 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; + rootNodeName = rootNode.nodeName.toLowerCase(); + while (node) { + // TODO: Break this up, too complex + if (((node.nodeType === 3 || (node.nodeType == 1 && !blockElements[node.nodeName]))) && + schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase())) { + // Remove empty text nodes + if (node.nodeType === 3 && node.nodeValue.length === 0) { + tempNode = node; + node = node.nextSibling; + dom.remove(tempNode); + continue; + } + + if (!rootBlockNode) { + rootBlockNode = dom.create(forcedRootBlock); + node.parentNode.insertBefore(rootBlockNode, node); + wrapped = true; + } + + tempNode = node; + node = node.nextSibling; + rootBlockNode.appendChild(tempNode); + } else { + rootBlockNode = null; + node = node.nextSibling; + } + } + + if (wrapped && restoreSelection) { + if (rng.setStart) { + rng.setStart(startContainer, startOffset); + rng.setEnd(endContainer, endOffset); + selection.setRng(rng); + } else { + // Only select if the previous selection was inside the document to prevent auto focus in quirks mode + 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.on('KeyUp NodeChange', addRootBlocks); + } + }; +}); + +// Included from: js/tinymce/classes/EditorCommands.js + +/** + * EditorCommands.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class enables you to add custom editor commands and it contains + * overrides for native browser commands to address various bugs and issues. + * + * @class tinymce.EditorCommands + */ +define("tinymce/EditorCommands", [ + "tinymce/html/Serializer", + "tinymce/Env", + "tinymce/util/Tools" +], function(Serializer, Env, Tools) { + // Added for compression purposes + var each = Tools.each, extend = Tools.extend; + var map = Tools.map, inArray = Tools.inArray, explode = Tools.explode; + var isGecko = Env.gecko, isIE = Env.ie; + var TRUE = true, FALSE = false; + + return function(editor) { + var dom = editor.dom, + selection = editor.selection, + commands = {state: {}, exec: {}, value: {}}, + settings = editor.settings, + formatter = editor.formatter, + bookmark; + + /** + * Executes the specified command. + * + * @method execCommand + * @param {String} command Command to execute. + * @param {Boolean} ui Optional user interface state. + * @param {Object} value Optional value for command. + * @return {Boolean} true/false if the command was found or not. + */ + function execCommand(command, ui, value) { + var func; + + command = command.toLowerCase(); + if ((func = commands.exec[command])) { + func(command, ui, value); + return TRUE; + } + + return FALSE; + } + + /** + * Queries the current state for a command for example if the current selection is "bold". + * + * @method queryCommandState + * @param {String} command Command to check the state of. + * @return {Boolean/Number} true/false if the selected contents is bold or not, -1 if it's not found. + */ + function queryCommandState(command) { + var func; + + command = command.toLowerCase(); + if ((func = commands.state[command])) { + return func(command); + } + + return -1; + } + + /** + * Queries the command value for example the current fontsize. + * + * @method queryCommandValue + * @param {String} command Command to check the value of. + * @return {Object} Command value of false if it's not found. + */ + function queryCommandValue(command) { + var func; + + command = command.toLowerCase(); + if ((func = commands.value[command])) { + return func(command); + } + + return FALSE; + } + + /** + * Adds commands to the command collection. + * + * @method addCommands + * @param {Object} command_list Name/value collection with commands to add, the names can also be comma separated. + * @param {String} type Optional type to add, defaults to exec. Can be value or state as well. + */ + 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 + extend(this, { + execCommand: execCommand, + queryCommandState: queryCommandState, + queryCommandValue: queryCommandValue, + addCommands: addCommands + }); + + // Private methods + + function execNativeCommand(command, ui, value) { + if (ui === undefined) { + ui = FALSE; + } + + if (value === undefined) { + 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} : undefined); + editor.nodeChanged(); + } + + 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 (isGecko) { + editor.windowManager.confirm(editor.getLang('clipboard_msg'), function(state) { + if (state) { + window.open('http://www.mozilla.org/editor/midasdemo/securityprefs.html', '_blank'); + } + }); + } else { + editor.windowManager.alert( + "Your browser doesn't support direct access to the clipboard. " + + "Please use the Ctrl+X/C/V keyboard shortcuts instead." + ); + } + } + }, + + // 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); + + if (align == 'full') { + align = 'justify'; + } + + // Remove all other alignments first + each('left,center,right,justify'.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 = explode(settings.font_size_style_values); + fontClasses = 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() { + 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; + var marker, nodeRect, viewPortRect, rng, node, node2, bookmarkHtml, viewportBodyElement; + + function trimOrPaddLeftRight(html) { + var rng, container, offset; + + rng = selection.getRng(true); + container = rng.startContainer; + offset = rng.startOffset; + + function hasSiblingText(siblingName) { + return container[siblingName] && container[siblingName].nodeType == 3; + } + + if (container.nodeType == 3) { + if (offset > 0) { + html = html.replace(/^ /, ' '); + } else if (!hasSiblingText('previousSibling')) { + html = html.replace(/^ /, ' '); + } + + if (offset < container.length) { + html = html.replace(/ (
    |)$/, ' '); + } else if (!hasSiblingText('nextSibling')) { + html = html.replace(/( | )(
    |)$/, ' '); + } + } + + return html; + } + + // Check for whitespace before/after value + if (/^ | $/.test(value)) { + value = trimOrPaddLeftRight(value); + } + + // Setup parser and serializer + parser = editor.parser; + serializer = new Serializer({}, editor.schema); + bookmarkHtml = ''; + + // Run beforeSetContent handlers on the HTML to be inserted + args = {content: value, format: 'html', selection: true}; + editor.fire('BeforeSetContent', 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 = 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(//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 = 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); + + // TODO: Why can't we normalize on IE + if (!isIE) { + node2 = marker.nextSibling; + if (node2 && node2.nodeType == 3) { + node.appendData(node2.data); + node2.parentNode.removeChild(node2); + } + } + } 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 + editor.fire('SetContent', 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; + }) + ); + }, + + mceToggleFormat: function(command, ui, value) { + toggleFormat(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, 10); + + 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) { + var indentStyleName; + + if (element.nodeName != "LI") { + indentStyleName = dom.getStyle(element, 'direction', true) == 'rtl' ? 'paddingRight' : 'paddingLeft'; + + if (command == 'outdent') { + value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue); + dom.setStyle(element, indentStyleName, value ? value + indentUnit : ''); + } else { + value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit; + dom.setStyle(element, indentStyleName, value); + } + } + }); + } else { + execNativeCommand(command); + } + }, + + mceRepaint: function() { + if (isGecko) { + try { + storeSelection(TRUE); + + if (selection.getSel()) { + selection.getSel().selectAllChildren(editor.getBody()); + } + + selection.collapse(TRUE); + restoreSelection(); + } catch (ex) { + // Ignore + } + } + }, + + InsertHorizontalRule: function() { + editor.execCommand('mceInsertContent', false, '
    '); + }, + + 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(); + + // Old IE does a better job with selectall than new versions + if (selection.getRng().setStart) { + rng.setStart(root, 0); + rng.setEnd(root, root.childNodes.length); + + selection.setRng(rng); + } else { + execNativeCommand('SelectAll'); + } + }, + + mceNewDocument: function() { + editor.setContent(''); + } + }); + + // Add queryCommandState overrides + addCommands({ + // Override justify commands + 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) { + var name = 'align' + command.substring(7); + var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks(); + var matches = map(nodes, function(node) { + return !!formatter.matchNode(node, name); + }); + return 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, 10) > 0) { + return TRUE; + } + + if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { + return TRUE; + } + } + + return ( + queryCommandState('InsertUnorderedList') || + queryCommandState('InsertOrderedList') || + (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')) + ); + }, + + 'InsertUnorderedList,InsertOrderedList': function(command) { + var list = dom.getParent(selection.getNode(), 'ul,ol'); + + return list && + ( + command === 'insertunorderedlist' && list.tagName === 'UL' || + command === 'insertorderedlist' && list.tagName === '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(); + } + }); + }; +}); + +// Included from: js/tinymce/classes/util/URI.js + +/** + * URI.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles parsing, modification and serialization of URI/URL strings. + * @class tinymce.util.URI + */ +define("tinymce/util/URI", [ + "tinymce/util/Tools" +], function(Tools) { + var each = Tools.each, trim = Tools.trim; + + /** + * Constucts a new URI instance. + * + * @constructor + * @method URI + * @param {String} url URI string to parse. + * @param {Object} settings Optional settings object. + */ + function URI(url, settings) { + var self = this, baseUri, base_url; + + // Trim whitespace + url = trim(url); + + // Default settings + settings = self.settings = settings || {}; + + // Strange app protocol that isn't http/https or local anchor + // For example: mailto,skype,tel etc. + if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) { + self.source = url; + return; + } + + // Absolute path with no host, fake host and protocol + if (url.indexOf('/') === 0 && url.indexOf('//') !== 0) { + url = (settings.base_uri ? settings.base_uri.protocol || 'http' : 'http') + '://mce_host' + url; + } + + // Relative path http:// or protocol relative //path + if (!/^[\w\-]*:?\/\//.test(url)) { + base_url = settings.base_uri ? settings.base_uri.path : new URI(location.href).directory; + url = ((settings.base_uri && settings.base_uri.protocol) || 'http') + '://mce_host' + self.toAbsPath(base_url, url); + } + + // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri) + url = url.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something + + /*jshint maxlen: 255 */ + url = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url); + + each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) { + var part = url[i]; + + // Zope 3 workaround, they use @@something + if (part) { + part = part.replace(/\(mce_at\)/g, '@@'); + } + + self[v] = part; + }); + + baseUri = settings.base_uri; + if (baseUri) { + if (!self.protocol) { + self.protocol = baseUri.protocol; + } + + if (!self.userInfo) { + self.userInfo = baseUri.userInfo; + } + + if (!self.port && self.host === 'mce_host') { + self.port = baseUri.port; + } + + if (!self.host || self.host === 'mce_host') { + self.host = baseUri.host; + } + + self.source = ''; + } + + //t.path = t.path || '/'; + } + + URI.prototype = { + /** + * Sets the internal path part of the URI. + * + * @method setPath + * @param {string} path Path string to set. + */ + setPath: function(path) { + var self = this; + + path = /^(.*?)\/?(\w+)?$/.exec(path); + + // Update path parts + self.path = path[0]; + self.directory = path[1]; + self.file = path[2]; + + // Rebuild source + self.source = ''; + self.getURI(); + }, + + /** + * Converts the specified URI into a relative URI based on the current URI instance location. + * + * @method toRelative + * @param {String} uri URI to convert into a relative path/URI. + * @return {String} Relative URI from the point specified in the current URI instance. + * @example + * // Converts an absolute URL to an relative URL url will be somedir/somefile.htm + * var url = new tinymce.util.URI('http://www.site.com/dir/').toRelative('http://www.site.com/dir/somedir/somefile.htm'); + */ + toRelative: function(uri) { + var self = this, output; + + if (uri === "./") { + return uri; + } + + uri = new URI(uri, {base_uri: self}); + + // Not on same domain/port or protocol + if ((uri.host != 'mce_host' && self.host != uri.host && uri.host) || self.port != uri.port || self.protocol != uri.protocol) { + return uri.getURI(); + } + + var tu = self.getURI(), uu = uri.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; + } + + output = self.toRelPath(self.path, uri.path); + + // Add query + if (uri.query) { + output += '?' + uri.query; + } + + // Add anchor + if (uri.anchor) { + output += '#' + uri.anchor; + } + + return output; + }, + + /** + * Converts the specified URI into a absolute URI based on the current URI instance location. + * + * @method toAbsolute + * @param {String} uri URI to convert into a relative path/URI. + * @param {Boolean} noHost No host and protocol prefix. + * @return {String} Absolute URI from the point specified in the current URI instance. + * @example + * // Converts an relative URL to an absolute URL url will be http://www.site.com/dir/somedir/somefile.htm + * var url = new tinymce.util.URI('http://www.site.com/dir/').toAbsolute('somedir/somefile.htm'); + */ + toAbsolute: function(uri, noHost) { + uri = new URI(uri, {base_uri: this}); + + return uri.getURI(this.host == uri.host && this.protocol == uri.protocol ? noHost : 0); + }, + + /** + * Converts a absolute path into a relative path. + * + * @method toRelPath + * @param {String} base Base point to convert the path from. + * @param {String} path Absolute path to convert into a relative path. + */ + toRelPath: function(base, path) { + var items, breakPoint = 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]) { + breakPoint = 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]) { + breakPoint = i + 1; + break; + } + } + } + + if (breakPoint === 1) { + return path; + } + + for (i = 0, l = base.length - (breakPoint - 1); i < l; i++) { + out += "../"; + } + + for (i = breakPoint - 1, l = items.length; i < l; i++) { + if (i != breakPoint - 1) { + out += "/" + items[i]; + } else { + out += items[i]; + } + } + + return out; + }, + + /** + * Converts a relative path into a absolute path. + * + * @method toAbsPath + * @param {String} base Base point to convert the path from. + * @param {String} path Relative path to convert into an absolute path. + */ + 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; + }, + + /** + * Returns the full URI of the internal structure. + * + * @method getURI + * @param {Boolean} noProtoHost Optional no host and protocol part. Defaults to false. + */ + getURI: function(noProtoHost) { + var s, self = this; + + // Rebuild source + if (!self.source || noProtoHost) { + s = ''; + + if (!noProtoHost) { + if (self.protocol) { + s += self.protocol + '://'; + } + + if (self.userInfo) { + s += self.userInfo + '@'; + } + + if (self.host) { + s += self.host; + } + + if (self.port) { + s += ':' + self.port; + } + } + + if (self.path) { + s += self.path; + } + + if (self.query) { + s += '?' + self.query; + } + + if (self.anchor) { + s += '#' + self.anchor; + } + + self.source = s; + } + + return self.source; + } + }; + + return URI; +}); + +// Included from: js/tinymce/classes/util/Class.js + +/** + * Class.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * This utilitiy class is used for easier inheritage. + * + * Features: + * * Exposed super functions: this._super(); + * * Mixins + * * Dummy functions + * * Property functions: var value = object.value(); and object.value(newValue); + * * Static functions + * * Defaults settings + */ +define("tinymce/util/Class", [ + "tinymce/util/Tools" +], function(Tools) { + var each = Tools.each, extend = Tools.extend; + + var extendClass, initializing; + + function Class() { + } + + // Provides classical inheritance, based on code made by John Resig + Class.extend = extendClass = function(prop) { + var Self = this, _super = Self.prototype, prototype, name, member; + + // The dummy class constructor + function Class() { + var i, mixins, mixin, self; + + // All construction is actually done in the init method + if (!initializing) { + self = this; + + // Run class constuctor + if (self.init) { + self.init.apply(self, arguments); + } + + // Run mixin constructors + mixins = self.Mixins; + if (mixins) { + i = mixins.length; + while (i--) { + mixin = mixins[i]; + if (mixin.init) { + mixin.init.apply(self, arguments); + } + } + } + } + } + + // Dummy function, needs to be extended in order to provide functionality + function dummy() { + return this; + } + + // Creates a overloaded method for the class + // this enables you to use this._super(); to call the super function + function createMethod(name, fn) { + return function(){ + var self = this, tmp = self._super, ret; + + self._super = _super[name]; + ret = fn.apply(self, arguments); + self._super = tmp; + + return ret; + }; + } + + // Instantiate a base class (but only create the instance, + // don't run the init constructor) + initializing = true; + prototype = new Self(); + initializing = false; + + // Add mixins + if (prop.Mixins) { + each(prop.Mixins, function(mixin) { + mixin = mixin; + + for (var name in mixin) { + if (name !== "init") { + prop[name] = mixin[name]; + } + } + }); + + if (_super.Mixins) { + prop.Mixins = _super.Mixins.concat(prop.Mixins); + } + } + + // Generate dummy methods + if (prop.Methods) { + each(prop.Methods.split(','), function(name) { + prop[name] = dummy; + }); + } + + // Generate property methods + if (prop.Properties) { + each(prop.Properties.split(','), function(name) { + var fieldName = '_' + name; + + prop[name] = function(value) { + var self = this, undef; + + // Set value + if (value !== undef) { + self[fieldName] = value; + + return self; + } + + // Get value + return self[fieldName]; + }; + }); + } + + // Static functions + if (prop.Statics) { + each(prop.Statics, function(func, name) { + Class[name] = func; + }); + } + + // Default settings + if (prop.Defaults && _super.Defaults) { + prop.Defaults = extend({}, _super.Defaults, prop.Defaults); + } + + // Copy the properties over onto the new prototype + for (name in prop) { + member = prop[name]; + + if (typeof member == "function" && _super[name]) { + prototype[name] = createMethod(name, member); + } else { + prototype[name] = member; + } + } + + // Populate our constructed prototype object + Class.prototype = prototype; + + // Enforce the constructor to be what we expect + Class.constructor = Class; + + // And make this class extendible + Class.extend = extendClass; + + return Class; + }; + + return Class; +}); + +// Included from: js/tinymce/classes/ui/Selector.js + +/** + * Selector.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Selector engine, enables you to select controls by using CSS like expressions. + * We currently only support basic CSS expressions to reduce the size of the core + * and the ones we support should be enough for most cases. + * + * Supported expressions: + * element + * element#name + * element.class + * element[attr] + * element[attr*=value] + * element[attr~=value] + * element[attr!=value] + * element[attr^=value] + * element[attr$=value] + * element: + * element:not() + * element:first + * element:last + * element:odd + * element:even + * element element + * element > element + * @class tinymce.ui.Selector + */ +define("tinymce/ui/Selector", [ + "tinymce/util/Class", + "tinymce/util/Tools" +], function(Class, Tools) { + "use strict"; + + /** + * Produces an array with a unique set of objects. It will not compare the values + * but the references of the objects. + * + * @method unqiue + * @param {Array} array Array to make into an array with unique items. + * @return {Array} Array with unique items. + */ + function unique(array) { + var uniqueItems = [], i = array.length, item; + + while (i--) { + item = array[i]; + + if (!item.__checked) { + uniqueItems.push(item); + item.__checked = 1; + } + } + + i = uniqueItems.length; + while (i--) { + delete uniqueItems[i].__checked; + } + + return uniqueItems; + } + + var expression = /^([\w\\*]+)?(?:#([\w\\]+))?(?:\.([\w\\\.]+))?(?:\[\@?([\w\\]+)([\^\$\*!~]?=)([\w\\]+)\])?(?:\:(.+))?/i; + + /*jshint maxlen:255 */ + var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + whiteSpace = /^\s*|\s*$/g, + Collection; + + var Selector = Class.extend({ + /** + * Constructs a new Selector instance. + * + * @contructor + * @method init + * @param {String} selector CSS like selector expression. + */ + init: function(selector) { + var match = this.match; + + function compileNameFilter(name) { + if (name) { + name = name.toLowerCase(); + + return function(item) { + return name === '*' || item.type === name; + }; + } + } + + function compileIdFilter(id) { + if (id) { + return function(item) { + return item._name === id; + }; + } + } + + function compileClassesFilter(classes) { + if (classes) { + classes = classes.split('.'); + + return function(item) { + var i = classes.length; + + while (i--) { + if (!item.hasClass(classes[i])) { + return false; + } + } + + return true; + }; + } + } + + function compileAttrFilter(name, cmp, check) { + if (name) { + return function(item) { + var value = item[name] ? item[name]() : ''; + + return !cmp ? !!check : + cmp === "=" ? value === check : + cmp === "*=" ? value.indexOf(check) >= 0 : + cmp === "~=" ? (" " + value + " ").indexOf(" " + check + " ") >= 0 : + cmp === "!=" ? value != check : + cmp === "^=" ? value.indexOf(check) === 0 : + cmp === "$=" ? value.substr(value.length - check.length) === check : + false; + }; + } + } + + function compilePsuedoFilter(name) { + var notSelectors; + + if (name) { + name = /(?:not\((.+)\))|(.+)/i.exec(name); + + if (!name[1]) { + name = name[2]; + + return function(item, index, length) { + return name === 'first' ? index === 0 : + name === 'last' ? index === length - 1 : + name === 'even' ? index % 2 === 0 : + name === 'odd' ? index % 2 === 1 : + item[name] ? item[name]() : + false; + }; + } else { + // Compile not expression + notSelectors = parseChunks(name[1], []); + + return function(item) { + return !match(item, notSelectors); + }; + } + } + } + + function compile(selector, filters, direct) { + var parts; + + function add(filter) { + if (filter) { + filters.push(filter); + } + } + + // Parse expression into parts + parts = expression.exec(selector.replace(whiteSpace, '')); + + add(compileNameFilter(parts[1])); + add(compileIdFilter(parts[2])); + add(compileClassesFilter(parts[3])); + add(compileAttrFilter(parts[4], parts[5], parts[6])); + add(compilePsuedoFilter(parts[7])); + + // Mark the filter with psuedo for performance + filters.psuedo = !!parts[7]; + filters.direct = direct; + + return filters; + } + + // Parser logic based on Sizzle by John Resig + function parseChunks(selector, selectors) { + var parts = [], extra, matches, i; + + do { + chunker.exec(""); + matches = chunker.exec(selector); + + if (matches) { + selector = matches[3]; + parts.push(matches[1]); + + if (matches[2]) { + extra = matches[3]; + break; + } + } + } while (matches); + + if (extra) { + parseChunks(extra, selectors); + } + + selector = []; + for (i = 0; i < parts.length; i++) { + if (parts[i] != '>') { + selector.push(compile(parts[i], [], parts[i - 1] === '>')); + } + } + + selectors.push(selector); + + return selectors; + } + + this._selectors = parseChunks(selector, []); + }, + + /** + * Returns true/false if the selector matches the specified control. + * + * @method match + * @param {tinymce.ui.Control} control Control to match agains the selector. + * @param {Array} selectors Optional array of selectors, mostly used internally. + * @return {Boolean} true/false state if the control matches or not. + */ + match: function(control, selectors) { + var i, l, si, sl, selector, fi, fl, filters, index, length, siblings, count, item; + + selectors = selectors || this._selectors; + for (i = 0, l = selectors.length; i < l; i++) { + selector = selectors[i]; + sl = selector.length; + item = control; + count = 0; + + for (si = sl - 1; si >= 0; si--) { + filters = selector[si]; + + while (item) { + // Find the index and length since a psuedo filter like :first needs it + if (filters.psuedo) { + siblings = item.parent().items(); + index = Tools.inArray(item, siblings); + length = siblings.length; + } + + for (fi = 0, fl = filters.length; fi < fl; fi++) { + if (!filters[fi](item, index, length)) { + fi = fl + 1; + break; + } + } + + if (fi === fl) { + count++; + break; + } else { + // If it didn't match the right most expression then + // break since it's no point looking at the parents + if (si === sl - 1) { + break; + } + } + + item = item.parent(); + } + } + + // If we found all selectors then return true otherwise continue looking + if (count === sl) { + return true; + } + } + + return false; + }, + + /** + * Returns a tinymce.ui.Collection with matches of the specified selector inside the specified container. + * + * @method find + * @param {tinymce.ui.Control} container Container to look for items in. + * @return {tinymce.ui.Collection} Collection with matched elements. + */ + find: function(container) { + var matches = [], i, l, selectors = this._selectors; + + function collect(items, selector, index) { + var i, l, fi, fl, item, filters = selector[index]; + + for (i = 0, l = items.length; i < l; i++) { + item = items[i]; + + // Run each filter agains the item + for (fi = 0, fl = filters.length; fi < fl; fi++) { + if (!filters[fi](item, i, l)) { + fi = fl + 1; + break; + } + } + + // All filters matched the item + if (fi === fl) { + // Matched item is on the last expession like: panel toolbar [button] + if (index == selector.length - 1) { + matches.push(item); + } else { + // Collect next expession type + if (item.items) { + collect(item.items(), selector, index + 1); + } + } + } else if (filters.direct) { + return; + } + + // Collect child items + if (item.items) { + collect(item.items(), selector, index); + } + } + } + + if (container.items) { + for (i = 0, l = selectors.length; i < l; i++) { + collect(container.items(), selectors[i], 0); + } + + // Unique the matches if needed + if (l > 1) { + matches = unique(matches); + } + } + + // Fix for circular reference + if (!Collection) { + // TODO: Fix me! + Collection = Selector.Collection; + } + + return new Collection(matches); + } + }); + + return Selector; +}); + +// Included from: js/tinymce/classes/ui/Collection.js + +/** + * Collection.js + * + * Copyright 2003-2013, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Control collection, this class contains control instances and it + * enables you to perform actions on all the contained items. This is very similar to how jQuery works. + * + * @class tinymce.ui.Collection + */ +define("tinymce/ui/Collection", [ + "tinymce/util/Tools", + "tinymce/ui/Selector", + "tinymce/util/Class" +], function(Tools, Selector, Class) { + "use strict"; + + var Collection, proto, push = Array.prototype.push, slice = Array.prototype.slice; + + proto = { + /** + * Current number of contained control instances. + * + * @field length + * @type Number + */ + length: 0, + + /** + * Constructor for the collection. + * + * @constructor + * @method init + * @param {Array} items Optional array with items to add. + */ + init: function(items) { + if (items) { + this.add(items); + } + }, + + /** + * Adds new items to the control collection. + * + * @method add + * @param {Array} items Array if items to add to collection. + * @return {tinymce.ui.Collection} Current collection instance. + */ + add: function(items) { + var self = this; + + // Force single item into array + if (!Tools.isArray(items)) { + if (items instanceof Collection) { + self.add(items.toArray()); + } else { + push.call(self, items); + } + } else { + push.apply(self, items); + } + + return self; + }, + + /** + * Sets the contents of the collection. This will remove any existing items + * and replace them with the ones specified in the input array. + * + * @method set + * @param {Array} items Array with items to set into the Collection. + * @return {tinymce.ui.Collection} + */ + set: function(items) { + var self = this, len = self.length, i; + + self.length = 0; + self.add(items); + + // Remove old entries + for (i = self.length; i < len; i++) { + delete self[i]; + } + + return self; + }, + + /** + * Filters the collection item based on the specified selector expression or selector function. + * + * @method filter + * @param {String} selector Selector expression to filter items by. + * @return {tinymce.ui.Collection} Collection containing the filtered items. + */ + filter: function(selector) { + var self = this, i, l, matches = [], item, match; + + // Compile string into selector expression + if (typeof(selector) === "string") { + selector = new Selector(selector); + + match = function(item) { + return selector.match(item); + }; + } else { + // Use selector as matching function + match = selector; + } + + for (i = 0, l = self.length; i < l; i++) { + item = self[i]; + + if (match(item)) { + matches.push(item); + } + } + + return new Collection(matches); + }, + + /** + * Slices the items within the collection. + * + * @method slice + * @param {Number} index Index to slice at. + * @param {Number} len Optional length to slice. + * @return {tinymce.ui.Collection} Current collection. + */ + slice: function() { + return new Collection(slice.apply(this, arguments)); + }, + + /** + * Makes the current collection equal to the specified index. + * + * @method eq + * @param {Number} index Index of the item to set the collection to. + * @return {tinymce.ui.Collection} Current collection. + */ + eq: function(index) { + return index === -1 ? this.slice(index) : this.slice(index, +index + 1); + }, + + /** + * Executes the specified callback on each item in collection. + * + * @method each + * @param {function} callback Callback to execute for each item in collection. + * @return {tinymce.ui.Collection} Current collection instance. + */ + each: function(callback) { + Tools.each(this, callback); + + return this; + }, + + /** + * Returns an JavaScript array object of the contents inside the collection. + * + * @method toArray + * @return {Array} Array with all items from collection. + */ + toArray: function() { + return Tools.toArray(this); + }, + + /** + * Finds the index of the specified control or return -1 if it isn't in the collection. + * + * @method indexOf + * @param {Control} ctrl Control instance to look for. + * @return {Number} Index of the specified control or -1. + */ + indexOf: function(ctrl) { + var self = this, i = self.length; + + while (i--) { + if (self[i] === ctrl) { + break; + } + } + + return i; + }, + + /** + * Returns a new collection of the contents in reverse order. + * + * @method reverse + * @return {tinymce.ui.Collection} Collection instance with reversed items. + */ + reverse: function() { + return new Collection(Tools.toArray(this).reverse()); + }, + + /** + * Returns true/false if the class exists or not. + * + * @method hasClass + * @param {String} cls Class to check for. + * @return {Boolean} true/false state if the class exists or not. + */ + hasClass: function(cls) { + return this[0] ? this[0].hasClass(cls) : false; + }, + + /** + * Sets/gets the specific property on the items in the collection. The same as executing control.(); + * + * @method prop + * @param {String} name Property name to get/set. + * @param {Object} value Optional object value to set. + * @return {tinymce.ui.Collection} Current collection instance or value of the first item on a get operation. + */ + prop: function(name, value) { + var self = this, undef, item; + + if (value !== undef) { + self.each(function(item) { + if (item[name]) { + item[name](value); + } + }); + + return self; + } + + item = self[0]; + + if (item && item[name]) { + return item[name](); + } + }, + + /** + * Executes the specific function name with optional arguments an all items in collection if it exists. + * + * @example collection.exec("myMethod", arg1, arg2, arg3); + * @method exec + * @param {String} name Name of the function to execute. + * @param {Object} ... Multiple arguments to pass to each function. + * @return {tinymce.ui.Collection} Current collection. + */ + exec: function(name) { + var self = this, args = Tools.toArray(arguments).slice(1); + + self.each(function(item) { + if (item[name]) { + item[name].apply(item, args); + } + }); + + return self; + } + + /** + * Fires the specified event by name and arguments on the control. This will execute all + * bound event handlers. + * + * @method fire + * @param {String} name Name of the event to fire. + * @param {Object} args Optional arguments to pass to the event. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // fire: function(event, args) {}, -- Generated by code below + + /** + * Binds a callback to the specified event. This event can both be + * native browser events like "click" or custom ones like PostRender. + * + * The callback function will have two parameters the first one being the control that recieved the event + * the second one will be the event object either the browsers native event object or a custom JS object. + * + * @method on + * @param {String} name Name of the event to bind. For example "click". + * @param {String/function} callback Callback function to execute ones the event occurs. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // on: function(name, callback) {}, -- Generated by code below + + /** + * Unbinds the specified event and optionally a specific callback. If you omit the name + * parameter all event handlers will be removed. If you omit the callback all event handles + * by the specified name will be removed. + * + * @method off + * @param {String} name Optional name for the event to unbind. + * @param {function} callback Optional callback function to unbind. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // off: function(name, callback) {}, -- Generated by code below + + /** + * Shows the items in the current collection. + * + * @method show + * @return {tinymce.ui.Collection} Current collection instance. + */ + // show: function() {}, -- Generated by code below + + /** + * Hides the items in the current collection. + * + * @method hide + * @return {tinymce.ui.Collection} Current collection instance. + */ + // hide: function() {}, -- Generated by code below + + /** + * Sets/gets the text contents of the items in the current collection. + * + * @method text + * @return {tinymce.ui.Collection} Current collection instance or text value of the first item on a get operation. + */ + // text: function(value) {}, -- Generated by code below + + /** + * Sets/gets the name contents of the items in the current collection. + * + * @method name + * @return {tinymce.ui.Collection} Current collection instance or name value of the first item on a get operation. + */ + // name: function(value) {}, -- Generated by code below + + /** + * Sets/gets the disabled state on the items in the current collection. + * + * @method disabled + * @return {tinymce.ui.Collection} Current collection instance or disabled state of the first item on a get operation. + */ + // disabled: function(state) {}, -- Generated by code below + + /** + * Sets/gets the active state on the items in the current collection. + * + * @method active + * @return {tinymce.ui.Collection} Current collection instance or active state of the first item on a get operation. + */ + // active: function(state) {}, -- Generated by code below + + /** + * Sets/gets the selected state on the items in the current collection. + * + * @method selected + * @return {tinymce.ui.Collection} Current collection instance or selected state of the first item on a get operation. + */ + // selected: function(state) {}, -- Generated by code below + + /** + * Sets/gets the selected state on the items in the current collection. + * + * @method visible + * @return {tinymce.ui.Collection} Current collection instance or visible state of the first item on a get operation. + */ + // visible: function(state) {}, -- Generated by code below + + /** + * Adds a class to all items in the collection. + * + * @method addClass + * @param {String} cls Class to add to each item. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // addClass: function(cls) {}, -- Generated by code below + + /** + * Removes the specified class from all items in collection. + * + * @method removeClass + * @param {String} cls Class to remove from each item. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // removeClass: function(cls) {}, -- Generated by code below + }; + + // Extend tinymce.ui.Collection prototype with some generated control specific methods + Tools.each('fire on off show hide addClass removeClass append prepend before after reflow'.split(' '), function(name) { + proto[name] = function() { + var args = Tools.toArray(arguments); + + this.each(function(ctrl) { + if (name in ctrl) { + ctrl[name].apply(ctrl, args); + } + }); + + return this; + }; + }); + + // Extend tinymce.ui.Collection prototype with some property methods + Tools.each('text name width height disabled active selected checked visible parent value data'.split(' '), function(name) { + proto[name] = function(value) { + return this.prop(name, value); + }; + }); + + // Create class based on the new prototype + Collection = Class.extend(proto); + + // Stick Collection into Selector to prevent circual references + Selector.Collection = Collection; + + return Collection; +}); + +// Included from: js/tinymce/classes/ui/DomUtils.js + +/** + * DomUtils.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +define("tinymce/ui/DomUtils", [ + "tinymce/util/Tools", + "tinymce/dom/DOMUtils" +], function(Tools, DOMUtils) { + "use strict"; + + return { + id: function() { + return DOMUtils.DOM.uniqueId(); + }, + + createFragment: function(html) { + return DOMUtils.DOM.createFragment(html); + }, + + getWindowSize: function() { + return DOMUtils.DOM.getViewPort(); + }, + + getSize: function(elm) { + return DOMUtils.DOM.getSize(elm); + }, + + getPos: function(elm, root) { + return DOMUtils.DOM.getPos(elm, root); + }, + + get: function(id) { + return document.getElementById(id); + }, + + addClass : function(elm, cls) { + return DOMUtils.DOM.addClass(elm, cls); + }, + + removeClass : function(elm, cls) { + return DOMUtils.DOM.removeClass(elm, cls); + }, + + hasClass : function(elm, cls) { + return DOMUtils.DOM.hasClass(elm, cls); + }, + + toggleClass: function(elm, cls, state) { + return DOMUtils.DOM.toggleClass(elm, cls, state); + }, + + css: function(elm, name, value) { + return DOMUtils.DOM.setStyle(elm, name, value); + }, + + on: function(target, name, callback, scope) { + return DOMUtils.DOM.bind(target, name, callback, scope); + }, + + off: function(target, name, callback) { + return DOMUtils.DOM.unbind(target, name, callback); + }, + + fire: function(target, name, args) { + return DOMUtils.DOM.fire(target, name, args); + } + }; +}); + +// Included from: js/tinymce/classes/ui/Control.js + +/** + * Control.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * ... + * + * @class tinymce.ui.Control + */ +define("tinymce/ui/Control", [ + "tinymce/util/Class", + "tinymce/util/Tools", + "tinymce/ui/Collection", + "tinymce/ui/DomUtils" +], function(Class, Tools, Collection, DomUtils) { + "use strict"; + + var nativeEvents = Tools.makeMap("focusin focusout scroll click dblclick mousedown mouseup mousemove mouseover" + + " mouseout mouseenter mouseleave wheel keydown keypress keyup contextmenu", " "); + + var elementIdCache = {}; + var hasMouseWheelEventSupport = "onmousewheel" in document; + var hasWheelEventSupport = false; + + /** + * Base control. All controls extend this class. + * + * @class tinymce.ui.Control + */ + var Control = Class.extend({ + Statics: { + controlIdLookup: {} + }, + + classPrefix: "mce-", + + getContainerElm: function() { + return document.body; + }, + + getParentCtrl: function(elm) { + var ctrl; + + while (elm) { + ctrl = Control.controlIdLookup[elm.id]; + if (ctrl) { + break; + } + + elm = elm.parentNode; + } + + return ctrl; + }, + + /** + * Constructor for the control. + * + * @constructor + * @method init + * @param {Object} settings Settings name/value object. + */ + init: function(settings) { + var self = this, classes, i; + + self.settings = settings = Tools.extend({}, self.Defaults, settings); + + // Initial states + self._id = DomUtils.id(); + self._text = self._name = ''; + self._width = self._height = 0; + self._aria = {role: settings.role}; + + // Setup classes + classes = settings.classes; + if (classes) { + classes = classes.split(' '); + classes.map = {}; + i = classes.length; + while (i--) { + classes.map[classes[i]] = true; + } + } + + self._classes = classes || []; + self.visible(true); + + // Set some properties + Tools.each('title text width height name classes visible disabled active value'.split(' '), function(name) { + var value = settings[name], undef; + + if (value !== undef) { + self[name](value); + } else if (self['_' + name] === undef) { + self['_' + name] = false; + } + }); + + self.on('click', function() { + if (self.disabled()) { + return false; + } + }); + + if (settings.classes) { + Tools.each(settings.classes.split(' '), function(cls) { + self.addClass(cls); + }); + } + + self.settings = settings; + + self._borderBox = self.parseBox(settings.border); + self._paddingBox = self.parseBox(settings.padding); + self._marginBox = self.parseBox(settings.margin); + + if (settings.hidden) { + self.hide(); + } + }, + + // Will generate getter/setter methods for these properties + Properties: 'parent,title,text,width,height,disabled,active,name,value', + + // Will generate empty dummy functions for these + Methods: 'renderHtml,refresh', + + parseBox: function(value) { + var len, radix = 10; + + if (!value) { + return; + } + + if (typeof(value) === "number") { + value = value || 0; + + return { + top: value, + left: value, + bottom: value, + right: value + }; + } + + value = value.split(' '); + len = value.length; + + if (len === 1) { + value[1] = value[2] = value[3] = value[0]; + } else if (len === 2) { + value[2] = value[0]; + value[3] = value[1]; + } else if (len === 3) { + value[3] = value[1]; + } + + return { + top: parseInt(value[0], radix) || 0, + right: parseInt(value[1], radix) || 0, + bottom: parseInt(value[2], radix) || 0, + left: parseInt(value[3], radix) || 0 + }; + }, + + borderBox: function() { + return this._borderBox; + }, + + paddingBox: function() { + return this._paddingBox; + }, + + marginBox: function() { + return this._marginBox; + }, + + measureBox: function(elm, prefix) { + function getStyle(name) { + var defaultView = document.defaultView; + + if (defaultView) { + // Remove camelcase + name = name.replace(/[A-Z]/g, function(a) { + return '-' + a; + }); + + return defaultView.getComputedStyle(elm, null).getPropertyValue(name); + } + + return elm.currentStyle[name]; + } + + function getSide(name) { + var val = parseInt(getStyle(name), 10); + + return isNaN(val) ? 0 : val; + } + + return { + top: getSide(prefix + "TopWidth"), + right: getSide(prefix + "RightWidth"), + bottom: getSide(prefix + "BottomWidth"), + left: getSide(prefix + "LeftWidth") + }; + }, + + initLayoutRect: function() { + var self = this, settings = self.settings, borderBox, layoutRect; + var elm = self.getEl(), width, height, minWidth, minHeight, autoResize; + var startMinWidth, startMinHeight; + + // Measure boxes + borderBox = self._borderBox = self._borderBox || self.measureBox(elm, 'border'); + self._paddingBox = self._paddingBox || self.measureBox(elm, 'padding'); + self._marginBox = self._marginBox || self.measureBox(elm, 'margin'); + + // Setup minWidth/minHeight and width/height + startMinWidth = settings.minWidth; + startMinHeight = settings.minHeight; + minWidth = startMinWidth || elm.offsetWidth; + minHeight = startMinHeight || elm.offsetHeight; + width = settings.width; + height = settings.height; + autoResize = settings.autoResize; + autoResize = typeof(autoResize) != "undefined" ? autoResize : !width && !height; + + width = width || minWidth; + height = height || minHeight; + + var deltaW = borderBox.left + borderBox.right; + var deltaH = borderBox.top + borderBox.bottom; + + var maxW = settings.maxWidth || 0xFFFF; + var maxH = settings.maxHeight || 0xFFFF; + + // Setup initial layout rect + self._layoutRect = layoutRect = { + x: settings.x || 0, + y: settings.y || 0, + w: width, + h: height, + deltaW: deltaW, + deltaH: deltaH, + contentW: width - deltaW, + contentH: height - deltaH, + innerW: width - deltaW, + innerH: height - deltaH, + startMinWidth: startMinWidth || 0, + startMinHeight: startMinHeight || 0, + minW: Math.min(minWidth, maxW), + minH: Math.min(minHeight, maxH), + maxW: maxW, + maxH: maxH, + autoResize: autoResize, + scrollW: 0 + }; + + self._lastLayoutRect = {}; + + return layoutRect; + }, + + layoutRect: function(newRect) { + var self = this, curRect = self._layoutRect, lastLayoutRect, size, deltaWidth, deltaHeight, undef, repaintControls; + + // Initialize default layout rect + if (!curRect) { + curRect = self.initLayoutRect(); + } + + // Set new rect values + if (newRect) { + // Calc deltas between inner and outer sizes + deltaWidth = curRect.deltaW; + deltaHeight = curRect.deltaH; + + // Set x position + if (newRect.x !== undef) { + curRect.x = newRect.x; + } + + // Set y position + if (newRect.y !== undef) { + curRect.y = newRect.y; + } + + // Set minW + if (newRect.minW !== undef) { + curRect.minW = newRect.minW; + } + + // Set minH + if (newRect.minH !== undef) { + curRect.minH = newRect.minH; + } + + // Set new width and calculate inner width + size = newRect.w; + if (size !== undef) { + size = size < curRect.minW ? curRect.minW : size; + size = size > curRect.maxW ? curRect.maxW : size; + curRect.w = size; + curRect.innerW = size - deltaWidth; + } + + // Set new height and calculate inner height + size = newRect.h; + if (size !== undef) { + size = size < curRect.minH ? curRect.minH : size; + size = size > curRect.maxH ? curRect.maxH : size; + curRect.h = size; + curRect.innerH = size - deltaHeight; + } + + // Set new inner width and calculate width + size = newRect.innerW; + if (size !== undef) { + size = size < curRect.minW - deltaWidth ? curRect.minW - deltaWidth : size; + size = size > curRect.maxW - deltaWidth ? curRect.maxW - deltaWidth : size; + curRect.innerW = size; + curRect.w = size + deltaWidth; + } + + // Set new height and calculate inner height + size = newRect.innerH; + if (size !== undef) { + size = size < curRect.minH - deltaHeight ? curRect.minH - deltaHeight : size; + size = size > curRect.maxH - deltaHeight ? curRect.maxH - deltaHeight : size; + curRect.innerH = size; + curRect.h = size + deltaHeight; + } + + // Set new contentW + if (newRect.contentW !== undef) { + curRect.contentW = newRect.contentW; + } + + // Set new contentH + if (newRect.contentH !== undef) { + curRect.contentH = newRect.contentH; + } + + // Compare last layout rect with the current one to see if we need to repaint or not + lastLayoutRect = self._lastLayoutRect; + if (lastLayoutRect.x !== curRect.x || lastLayoutRect.y !== curRect.y || + lastLayoutRect.w !== curRect.w || lastLayoutRect.h !== curRect.h) { + repaintControls = Control.repaintControls; + + if (repaintControls) { + if (repaintControls.map && !repaintControls.map[self._id]) { + repaintControls.push(self); + repaintControls.map[self._id] = true; + } + } + + lastLayoutRect.x = curRect.x; + lastLayoutRect.y = curRect.y; + lastLayoutRect.w = curRect.w; + lastLayoutRect.h = curRect.h; + } + + return self; + } + + return curRect; + }, + + repaint: function() { + var self = this, style, bodyStyle, rect, borderBox, borderW = 0, borderH = 0, lastRepaintRect; + + style = self.getEl().style; + rect = self._layoutRect; + lastRepaintRect = self._lastRepaintRect || {}; + + borderBox = self._borderBox; + borderW = borderBox.left + borderBox.right; + borderH = borderBox.top + borderBox.bottom; + + if (rect.x !== lastRepaintRect.x) { + style.left = rect.x + 'px'; + lastRepaintRect.x = rect.x; + } + + if (rect.y !== lastRepaintRect.y) { + style.top = rect.y + 'px'; + lastRepaintRect.y = rect.y; + } + + if (rect.w !== lastRepaintRect.w) { + style.width = (rect.w - borderW) + 'px'; + lastRepaintRect.w = rect.w; + } + + if (rect.h !== lastRepaintRect.h) { + style.height = (rect.h - borderH) + 'px'; + lastRepaintRect.h = rect.h; + } + + // Update body if needed + if (self._hasBody && rect.innerW !== lastRepaintRect.innerW) { + bodyStyle = self.getEl('body').style; + bodyStyle.width = (rect.innerW) + 'px'; + lastRepaintRect.innerW = rect.innerW; + } + + if (self._hasBody && rect.innerH !== lastRepaintRect.innerH) { + bodyStyle = bodyStyle || self.getEl('body').style; + bodyStyle.height = (rect.innerH) + 'px'; + lastRepaintRect.innerH = rect.innerH; + } + + self._lastRepaintRect = lastRepaintRect; + self.fire('repaint', {}, false); + }, + + /** + * Binds a callback to the specified event. This event can both be + * native browser events like "click" or custom ones like PostRender. + * + * The callback function will be passed a DOM event like object that enables yout do stop propagation. + * + * @method on + * @param {String} name Name of the event to bind. For example "click". + * @param {String/function} callback Callback function to execute ones the event occurs. + * @return {tinymce.ui.Control} Current control object. + */ + on: function(name, callback) { + var self = this, bindings, handlers, names, i; + + function resolveCallbackName(name) { + var callback, scope; + + return function(e) { + if (!callback) { + self.parents().each(function(ctrl) { + var callbacks = ctrl.settings.callbacks; + + if (callbacks && (callback = callbacks[name])) { + scope = ctrl; + return false; + } + }); + } + + return callback.call(scope, e); + }; + } + + if (callback) { + if (typeof(callback) == 'string') { + callback = resolveCallbackName(callback); + } + + names = name.toLowerCase().split(' '); + i = names.length; + while (i--) { + name = names[i]; + + bindings = self._bindings; + if (!bindings) { + bindings = self._bindings = {}; + } + + handlers = bindings[name]; + if (!handlers) { + handlers = bindings[name] = []; + } + + handlers.push(callback); + + if (nativeEvents[name]) { + if (!self._nativeEvents) { + self._nativeEvents = {name: true}; + } else { + self._nativeEvents[name] = true; + } + + if (self._rendered) { + self.bindPendingEvents(); + } + } + } + } + + return self; + }, + + /** + * Unbinds the specified event and optionally a specific callback. If you omit the name + * parameter all event handlers will be removed. If you omit the callback all event handles + * by the specified name will be removed. + * + * @method off + * @param {String} name Optional name for the event to unbind. + * @param {function} callback Optional callback function to unbind. + * @return {mxex.ui.Control} Current control object. + */ + off: function(name, callback) { + var self = this, i, bindings = self._bindings, handlers, bindingName, names, hi; + + if (bindings) { + if (name) { + names = name.toLowerCase().split(' '); + i = names.length; + while (i--) { + name = names[i]; + handlers = bindings[name]; + + // Unbind all handlers + if (!name) { + for (bindingName in bindings) { + bindings[bindingName].length = 0; + } + + return self; + } + + if (handlers) { + // Unbind all by name + if (!callback) { + handlers.length = 0; + } else { + // Unbind specific ones + hi = handlers.length; + while (hi--) { + if (handlers[hi] === callback) { + handlers.splice(hi, 1); + } + } + } + } + } + } else { + self._bindings = []; + } + } + + return self; + }, + + /** + * Fires the specified event by name and arguments on the control. This will execute all + * bound event handlers. + * + * @method fire + * @param {String} name Name of the event to fire. + * @param {Object} args Optional arguments to pass to the event. + * @param {Boolean} bubble Optional value to control bubbeling. Defaults to true. + * @return {tinymce.ui.Control} Current control object. + */ + fire: function(name, args, bubble) { + var self = this, i, l, handlers, parentCtrl; + + name = name.toLowerCase(); + + // 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; + } + + // Setup empty object if args is omited + args = args || {}; + + // Stick type into event object + if (!args.type) { + args.type = name; + } + + // Stick control into event + if (!args.control) { + args.control = self; + } + + // Add event delegation methods if they are missing + if (!args.preventDefault) { + // Add preventDefault method + args.preventDefault = function() { + args.isDefaultPrevented = returnTrue; + }; + + // Add stopPropagation + args.stopPropagation = function() { + args.isPropagationStopped = returnTrue; + }; + + // Add stopImmediatePropagation + args.stopImmediatePropagation = function() { + args.isImmediatePropagationStopped = returnTrue; + }; + + // Add event delegation states + args.isDefaultPrevented = returnFalse; + args.isPropagationStopped = returnFalse; + args.isImmediatePropagationStopped = returnFalse; + } + + if (self._bindings) { + handlers = self._bindings[name]; + + if (handlers) { + for (i = 0, l = handlers.length; i < l; i++) { + // Execute callback and break if the callback returns a false + if (!args.isImmediatePropagationStopped() && handlers[i].call(self, args) === false) { + break; + } + } + } + } + + // Bubble event up to parent controls + if (bubble !== false) { + parentCtrl = self.parent(); + while (parentCtrl && !args.isPropagationStopped()) { + parentCtrl.fire(name, args, false); + parentCtrl = parentCtrl.parent(); + } + } + + return args; + }, + + /** + * Returns a control collection with all parent controls. + * + * @method parents + * @param {String} selector Optional selector expression to find parents. + * @return {tinymce.ui.Collection} Collection with all parent controls. + */ + parents: function(selector) { + var ctrl = this, parents = new Collection(); + + // Add each parent to collection + for (ctrl = ctrl.parent(); ctrl; ctrl = ctrl.parent()) { + parents.add(ctrl); + } + + // Filter away everything that doesn't match the selector + if (selector) { + parents = parents.filter(selector); + } + + return parents; + }, + + next: function() { + var parentControls = this.parent().items(); + + return parentControls[parentControls.indexOf(this) + 1]; + }, + + prev: function() { + var parentControls = this.parent().items(); + + return parentControls[parentControls.indexOf(this) - 1]; + }, + + findCommonAncestor: function(ctrl1, ctrl2) { + var parentCtrl; + + while (ctrl1) { + parentCtrl = ctrl2; + + while (parentCtrl && ctrl1 != parentCtrl) { + parentCtrl = parentCtrl.parent(); + } + + if (ctrl1 == parentCtrl) { + break; + } + + ctrl1 = ctrl1.parent(); + } + + return ctrl1; + }, + + /** + * Returns true/false if the specific control has the specific class. + * + * @param {String} cls Class to check for. + * @return {Boolean} True/false if the control has the specified class. + */ + hasClass: function(cls, group) { + var classes = this._classes[group || 'control']; + + cls = this.classPrefix + cls; + + return classes && !!classes.map[cls]; + }, + + /** + * Adds the specified class to the control + * + * @param {String} cls Class to check for. + * @return {tinymce.ui.Control} Current control object. + */ + addClass: function(cls, group) { + var self = this, classes, elm; + + cls = this.classPrefix + cls; + classes = self._classes[group || 'control']; + + if (!classes) { + classes = []; + classes.map = {}; + self._classes[group || 'control'] = classes; + } + + if (!classes.map[cls]) { + classes.map[cls] = cls; + classes.push(cls); + + if (self._rendered) { + elm = self.getEl(group); + + if (elm) { + elm.className = classes.join(' '); + } + } + } + + return self; + }, + + /** + * Removed the specified class from the control. + * + * @param {String} cls Class to remove. + * @return {tinymce.ui.Control} Current control object. + */ + removeClass: function(cls, group) { + var self = this, classes, i, elm; + + cls = this.classPrefix + cls; + classes = self._classes[group || 'control']; + if (classes && classes.map[cls]) { + delete classes.map[cls]; + + i = classes.length; + while (i--) { + if (classes[i] === cls) { + classes.splice(i, 1); + } + } + } + + if (self._rendered) { + elm = self.getEl(group); + + if (elm) { + elm.className = classes.join(' '); + } + } + + return self; + }, + + toggleClass: function(cls, state, group) { + var self = this; + + if (state) { + self.addClass(cls, group); + } else { + self.removeClass(cls, group); + } + + return self; + }, + + classes: function(group) { + var classes = this._classes[group || 'control']; + + return classes ? classes.join(' ') : ''; + }, + + getEl: function(suffix, dropCache) { + var elm, id = suffix ? this._id + '-' + suffix : this._id; + + elm = elementIdCache[id] = (dropCache === true ? null : elementIdCache[id]) || DomUtils.get(id); + + return elm; + }, + + /** + * Sets/gets the visible for the control. + * + * @method visible + * @param {Boolean} state Value to set to control. + * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get. + */ + visible: function(state) { + var self = this, parentCtrl; + + if (typeof(state) !== "undefined") { + if (self._visible !== state) { + if (self._rendered) { + self.getEl().style.display = state ? '' : 'none'; + } + + self._visible = state; + + // Parent container needs to reflow + parentCtrl = self.parent(); + if (parentCtrl) { + parentCtrl._lastRect = null; + } + + self.fire(state ? 'show' : 'hide'); + } + + return self; + } + + return self._visible; + }, + + /** + * Sets the visible state to true. + * + * @return {tinymce.ui.Control} Current control instance. + */ + show: function() { + return this.visible(true); + }, + + /** + * Sets the visible state to false. + * + * @return {tinymce.ui.Control} Current control instance. + */ + hide: function() { + return this.visible(false); + }, + + focus: function() { + this.getEl().focus(); + }, + + blur: function() { + this.getEl().blur(); + }, + + aria: function(name, value) { + var self = this, elm = self.getEl(); + + if (typeof(value) === "undefined") { + return self._aria[name]; + } else { + self._aria[name] = value; + } + + if (self._rendered) { + if (name == 'label') { + elm.setAttribute('aria-labeledby', self._id); + } + + elm.setAttribute(name == 'role' ? name : 'aria-' + name, value); + } + + return self; + }, + + encode: function(text, translate) { + if (translate !== false && Control.translate) { + text = Control.translate(text); + } + + return (text || '').replace(/[&<>"]/g, function(match) { + return '&#' + match.charCodeAt(0) + ';'; + }); + }, + + before: function(items) { + var self = this, parent = self.parent(); + + if (parent) { + parent.insert(items, parent.items().indexOf(self), true); + } + + return self; + }, + + after: function(items) { + var self = this, parent = self.parent(); + + if (parent) { + parent.insert(items, parent.items().indexOf(self)); + } + + return self; + }, + + remove: function() { + var self = this, elm = self.getEl(), parent = self.parent(), newItems; + + if (self.items) { + var controls = self.items().toArray(); + var i = controls.length; + while (i--) { + controls[i].remove(); + } + } + + if (parent && parent.items) { + newItems = []; + + parent.items().each(function(item) { + if (item !== self) { + newItems.push(item); + } + }); + + parent.items().set(newItems); + parent._lastRect = null; + } + + if (self._eventsRoot && self._eventsRoot == self) { + DomUtils.off(elm); + } + + delete Control.controlIdLookup[self._id]; + + if (elm.parentNode) { + elm.parentNode.removeChild(elm); + } + + return self; + }, + + renderBefore: function(elm) { + var self = this; + + elm.parentNode.insertBefore(DomUtils.createFragment(self.renderHtml()), elm); + self.postRender(); + + return self; + }, + + renderTo: function(elm) { + var self = this; + + elm = elm || self.getContainerElm(); + elm.appendChild(DomUtils.createFragment(self.renderHtml())); + self.postRender(); + + return self; + }, + + postRender: function() { + var self = this, settings = self.settings, elm, box, parent, name, parentEventsRoot; + + // Bind on settings + for (name in settings) { + if (name.indexOf("on") === 0) { + self.on(name.substr(2), settings[name]); + } + } + + if (self._eventsRoot) { + for (parent = self.parent(); !parentEventsRoot && parent; parent = parent.parent()) { + parentEventsRoot = parent._eventsRoot; + } + + if (parentEventsRoot) { + for (name in parentEventsRoot._nativeEvents) { + self._nativeEvents[name] = true; + } + } + } + + self.bindPendingEvents(); + + if (settings.style) { + elm = self.getEl(); + if (elm) { + elm.setAttribute('style', settings.style); + elm.style.cssText = settings.style; + } + } + + if (!self._visible) { + DomUtils.css(self.getEl(), 'display', 'none'); + } + + if (self.settings.border) { + box = self.borderBox(); + DomUtils.css(self.getEl(), { + 'border-top-width': box.top, + 'border-right-width': box.right, + 'border-bottom-width': box.bottom, + 'border-left-width': box.left + }); + } + + // Add instance to lookup + Control.controlIdLookup[self._id] = self; + + for (var key in self._aria) { + self.aria(key, self._aria[key]); + } + + self.fire('postrender', {}, false); + }, + + scrollIntoView: function(align) { + function getOffset(elm, rootElm) { + var x, y, parent = elm; + + x = y = 0; + while (parent && parent != rootElm && parent.nodeType) { + x += parent.offsetLeft || 0; + y += parent.offsetTop || 0; + parent = parent.offsetParent; + } + + return {x: x, y: y}; + } + + var elm = this.getEl(), parentElm = elm.parentNode; + var x, y, width, height, parentWidth, parentHeight; + var pos = getOffset(elm, parentElm); + + x = pos.x; + y = pos.y; + width = elm.offsetWidth; + height = elm.offsetHeight; + parentWidth = parentElm.clientWidth; + parentHeight = parentElm.clientHeight; + + if (align == "end") { + x -= parentWidth - width; + y -= parentHeight - height; + } else if (align == "center") { + x -= (parentWidth / 2) - (width / 2); + y -= (parentHeight / 2) - (height / 2); + } + + parentElm.scrollLeft = x; + parentElm.scrollTop = y; + }, + + bindPendingEvents: function() { + var self = this, i, l, parents, eventRootCtrl, nativeEvents, name; + + function delegate(e) { + var control = self.getParentCtrl(e.target); + + if (control) { + control.fire(e.type, e); + } + } + + function mouseLeaveHandler() { + var ctrl = eventRootCtrl._lastHoverCtrl; + + if (ctrl) { + ctrl.fire("mouseleave", {target: ctrl.getEl()}); + + ctrl.parents().each(function(ctrl) { + ctrl.fire("mouseleave", {target: ctrl.getEl()}); + }); + + eventRootCtrl._lastHoverCtrl = null; + } + } + + function mouseEnterHandler(e) { + var ctrl = self.getParentCtrl(e.target), lastCtrl = eventRootCtrl._lastHoverCtrl, idx = 0, i, parents, lastParents; + + // Over on a new control + if (ctrl !== lastCtrl) { + eventRootCtrl._lastHoverCtrl = ctrl; + + parents = ctrl.parents().toArray().reverse(); + parents.push(ctrl); + + if (lastCtrl) { + lastParents = lastCtrl.parents().toArray().reverse(); + lastParents.push(lastCtrl); + + for (idx = 0; idx < lastParents.length; idx++) { + if (parents[idx] !== lastParents[idx]) { + break; + } + } + + for (i = lastParents.length - 1; i >= idx; i--) { + lastCtrl = lastParents[i]; + lastCtrl.fire("mouseleave", { + target : lastCtrl.getEl() + }); + } + } + + for (i = idx; i < parents.length; i++) { + ctrl = parents[i]; + ctrl.fire("mouseenter", { + target : ctrl.getEl() + }); + } + } + } + + function fixWheelEvent(e) { + e.preventDefault(); + + if (e.type == "mousewheel") { + e.deltaY = - 1/40 * e.wheelDelta; + + if (e.wheelDeltaX) { + e.deltaX = -1/40 * e.wheelDeltaX; + } + } else { + e.deltaX = 0; + e.deltaY = e.detail; + } + + e = self.fire("wheel", e); + } + + self._rendered = true; + + nativeEvents = self._nativeEvents; + if (nativeEvents) { + // Find event root element if it exists + parents = self.parents().toArray(); + parents.unshift(self); + for (i = 0, l = parents.length; !eventRootCtrl && i < l; i++) { + eventRootCtrl = parents[i]._eventsRoot; + } + + // Event root wasn't found the use the root control + if (!eventRootCtrl) { + eventRootCtrl = parents[parents.length - 1] || self; + } + + // Set the eventsRoot property on children that didn't have it + self._eventsRoot = eventRootCtrl; + for (l = i, i = 0; i < l; i++) { + parents[i]._eventsRoot = eventRootCtrl; + } + + // Bind native event delegates + for (name in nativeEvents) { + if (!nativeEvents) { + return false; + } + + if (name === "wheel" && !hasWheelEventSupport) { + if (hasMouseWheelEventSupport) { + DomUtils.on(self.getEl(), "mousewheel", fixWheelEvent); + } else { + DomUtils.on(self.getEl(), "DOMMouseScroll", fixWheelEvent); + } + + continue; + } + + // Special treatment for mousenter/mouseleave since these doesn't bubble + if (name === "mouseenter" || name === "mouseleave") { + // Fake mousenter/mouseleave + if (!eventRootCtrl._hasMouseEnter) { + DomUtils.on(eventRootCtrl.getEl(), "mouseleave", mouseLeaveHandler); + DomUtils.on(eventRootCtrl.getEl(), "mouseover", mouseEnterHandler); + eventRootCtrl._hasMouseEnter = 1; + } + } else if (!eventRootCtrl[name]) { + DomUtils.on(eventRootCtrl.getEl(), name, delegate); + eventRootCtrl[name] = true; + } + + // Remove the event once it's bound + nativeEvents[name] = false; + } + } + }, + + reflow: function() { + this.repaint(); + + return this; + } + + /** + * Sets/gets the parent container for the control. + * + * @method parent + * @param {tinymce.ui.Container} parent Optional parent to set. + * @return {tinymce.ui.Control} Parent control or the current control on a set action. + */ + // parent: function(parent) {} -- Generated + + /** + * Sets/gets the text for the control. + * + * @method text + * @param {String} value Value to set to control. + * @return {String/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // text: function(value) {} -- Generated + + /** + * Sets/gets the width for the control. + * + * @method width + * @param {Number} value Value to set to control. + * @return {Number/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // width: function(value) {} -- Generated + + /** + * Sets/gets the height for the control. + * + * @method height + * @param {Number} value Value to set to control. + * @return {Number/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // height: function(value) {} -- Generated + + /** + * Sets/gets the disabled for the control. + * + * @method disabled + * @param {Boolean} state Value to set to control. + * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get. + */ + // disabled: function(state) {} -- Generated + + /** + * Sets/gets the active for the control. + * + * @method active + * @param {Boolean} state Value to set to control. + * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get. + */ + // active: function(state) {} -- Generated + + /** + * Sets/gets the name for the control. + * + * @method name + * @param {String} value Value to set to control. + * @return {String/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // name: function(value) {} -- Generated + + /** + * Sets/gets the title for the control. + * + * @method title + * @param {String} value Value to set to control. + * @return {String/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // title: function(value) {} -- Generated + }); + + return Control; +}); + +// Included from: js/tinymce/classes/ui/Factory.js + +/** + * Factory.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/*global tinymce:true */ + +/** + * .. + * + * @class tinymce.ui.Factory + */ +define("tinymce/ui/Factory", [], function() { + "use strict"; + + var types = {}, namespaceInit; + + return { + add: function(type, typeClass) { + types[type.toLowerCase()] = typeClass; + }, + + has: function(type) { + return !!types[type.toLowerCase()]; + }, + + /** + * Creates a new control instance based on the settings provided. The instance created will be + * based on the specified type property. + * + * @method create + * @example tinymce.ui.Factory.create({type: 'button', text: 'Hello world!'}); + * @param {Object/String} settings Name/Value object with items used to create the type. + * @return {tinymce.ui.Control} Control instance based on the specified type. + */ + create: function(type, settings) { + var ControlType, name, namespace; + + // Build type lookup + if (!namespaceInit) { + namespace = tinymce.ui; + + for (name in namespace) { + types[name.toLowerCase()] = namespace[name]; + } + + namespaceInit = true; + } + + // If string is specified then use it as the type + if (typeof(type) == 'string') { + settings = settings || {}; + settings.type = type; + } else { + settings = type; + type = settings.type; + } + + // Find control type + type = type.toLowerCase(); + ControlType = types[type]; + + // #if debug + + if (!ControlType) { + throw new Error("Could not find control by type: " + type); + } + + // #endif + + ControlType = new ControlType(settings); + ControlType.type = type; // Set the type on the instance, this will be used by the Selector engine + + return ControlType; + } + }; +}); + +// Included from: js/tinymce/classes/ui/Container.js + +/** + * Container.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Base container control. This will be extended by all controls + * that can have children such as panels etc. + * + * @-x-less Container.less + * @class tinymce.ui.Container + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Container", [ + "tinymce/ui/Control", + "tinymce/ui/Collection", + "tinymce/ui/Selector", + "tinymce/ui/Factory", + "tinymce/util/Tools", + "tinymce/ui/DomUtils" +], function(Control, Collection, Selector, Factory, Tools, DomUtils) { + "use strict"; + + var selectorCache = {}; + + return Control.extend({ + layout: '', + innerClass: 'container-inner', + + /** + * Constructor for the control. + * + * @constructor + * @method init + * @param {Object} settings Settings name/value object. + */ + init: function(settings) { + var self = this; + + self._super(settings); + settings = self.settings; + + self._items = new Collection(); + + self.addClass('container'); + self.addClass('container-body', 'body'); + + if (settings.containerCls) { + self.addClass(settings.containerCls); + } + + self._layout = Factory.create((settings.layout || self.layout) + 'layout'); + + if (self.settings.items) { + self.add(self.settings.items); + } + + // TODO: Fix this! + self._hasBody = true; + }, + + /** + * Returns a collection of child items that the container currently have. + * + * @method items + * @return {tinymce.ui.Collection} Control collection direct child controls. + */ + items: function() { + return this._items; + }, + + /** + * Find child controls by selector. + * + * @method find + * @param {String} selector Selector CSS pattern to find children by. + * @return {tinymce.ui.Collection} Control collection with child controls. + */ + find: function(selector) { + selector = selectorCache[selector] = selectorCache[selector] || new Selector(selector); + + return selector.find(this); + }, + + /** + * Adds one or many items to the current container. This will create instances of + * the object representations if needed. + * + * @method add + * @param {Array/Object/tinymce.ui.Control} items Array or item that will be added to the container. + * @return {tinymce.ui.Collection} Current collection control. + */ + add: function(items) { + var self = this; + + self.items().add(self.create(items)).parent(self); + + return self; + }, + + focus: function() { + var self = this; + + if (self.keyNav) { + self.keyNav.focusFirst(); + } else { + self._super(); + } + + return self; + }, + + replace: function(oldItem, newItem) { + var ctrlElm, items = this.items(), i = items.length; + + // Replace the item in collection + while (i--) { + if (items[i] === oldItem) { + items[i] = newItem; + break; + } + } + + if (i >= 0) { + // Remove new item from DOM + ctrlElm = newItem.getEl(); + if (ctrlElm) { + ctrlElm.parentNode.removeChild(ctrlElm); + } + + // Remove old item from DOM + ctrlElm = oldItem.getEl(); + if (ctrlElm) { + ctrlElm.parentNode.removeChild(ctrlElm); + } + } + + // Adopt the item + newItem.parent(this); + }, + + create: function(items) { + var self = this, settings, ctrlItems = []; + + // Non array structure, then force it into an array + if (!Tools.isArray(items)) { + items = [items]; + } + + // Add default type to each child control + Tools.each(items, function(item) { + if (item !== null) { + // Construct item if needed + if (!(item instanceof Control)) { + // Name only then convert it to an object + if (typeof(item) == "string") { + item = {type: item}; + } + + // Create control instance based on input settings and default settings + settings = Tools.extend({}, self.settings.defaults, item); + item.type = settings.type = settings.type || item.type || self.settings.defaultType || + (settings.defaults ? settings.defaults.type : null); + item = Factory.create(settings); + } + + ctrlItems.push(item); + } + }); + + return ctrlItems; + }, + + renderNew: function() { + var self = this; + + // Render any new items + self.items().each(function(ctrl, index) { + var containerElm, fragment; + + ctrl.parent(self); + + if (!ctrl._rendered) { + containerElm = self.getEl('body'); + fragment = DomUtils.createFragment(ctrl.renderHtml()); + + // Insert or append the item + if (containerElm.hasChildNodes() && index <= containerElm.childNodes.length - 1) { + containerElm.insertBefore(fragment, containerElm.childNodes[index]); + } else { + containerElm.appendChild(fragment); + } + + ctrl.postRender(); + } + }); + + self._layout.applyClasses(self); + self._lastRect = null; + + return self; + }, + + append: function(items) { + return this.add(items).renderNew(); + }, + + prepend: function(items) { + var self = this; + + self.items().set(self.create(items).concat(self.items().toArray())); + + return self.renderNew(); + }, + + insert: function(items, index, before) { + var self = this, curItems, beforeItems, afterItems; + + items = self.create(items); + curItems = self.items(); + + if (!before) { + index += 1; + } + + if (index >= 0 && index < curItems.length) { + beforeItems = curItems.slice(0, index).toArray(); + afterItems = curItems.slice(index).toArray(); + curItems.set(beforeItems.concat(items, afterItems)); + } + + return self.renderNew(); + }, + + preRender: function() { + }, + + renderHtml: function() { + var self = this, layout = self._layout; + + self.preRender(); + layout.preRender(self); + + return ( + '
    ' + + '
    '+ + (self.settings.html || '') + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + }, + + postRender: function() { + var self = this, box; + + self.items().exec('postRender'); + self._super(); + + self._layout.postRender(self); + self._rendered = true; + + if (self.settings.style) { + DomUtils.css(self.getEl(), self.settings.style); + } + + if (self.settings.border) { + box = self.borderBox(); + DomUtils.css(self.getEl(), { + 'border-top-width': box.top, + 'border-right-width': box.right, + 'border-bottom-width': box.bottom, + 'border-left-width': box.left + }); + } + + return self; + }, + + initLayoutRect: function() { + var self = this, layoutRect = self._super(); + + // Recalc container size by asking layout manager + self._layout.recalc(self); + + return layoutRect; + }, + + recalc: function() { + var self = this, rect = self._layoutRect, lastRect = self._lastRect; + + if (!lastRect || lastRect.w != rect.w || lastRect.h != rect.h) { + self._layout.recalc(self); + rect = self.layoutRect(); + self._lastRect = {x: rect.x, y: rect.y, w: rect.w, h: rect.h}; + return true; + } + }, + + reflow: function() { + var i, items; + + if (this.visible()) { + Control.repaintControls = []; + Control.repaintControls.map = {}; + + items = this.recalc(); + i = Control.repaintControls.length; + + while (i--) { + Control.repaintControls[i].repaint(); + } + + // TODO: Fix me! + if (this.settings.layout !== "flow" && this.settings.layout !== "stack") { + this.repaint(); + } + + Control.repaintControls = []; + } + + return this; + } + }); +}); + +// Included from: js/tinymce/classes/ui/DragHelper.js + +/** + * DragHelper.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Drag/drop helper class. + * + * @example + * var dragHelper = new tinymce.ui.DragHelper('mydiv', { + * start: function(evt) { + * }, + * + * drag: function(evt) { + * }, + * + * end: function(evt) { + * } + * }); + */ +define("tinymce/ui/DragHelper", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + function getDocumentSize() { + var doc = document, documentElement, body, scrollWidth, clientWidth; + var offsetWidth, scrollHeight, clientHeight, offsetHeight, max = Math.max; + + documentElement = doc.documentElement; + body = doc.body; + + scrollWidth = max(documentElement.scrollWidth, body.scrollWidth); + clientWidth = max(documentElement.clientWidth, body.clientWidth); + offsetWidth = max(documentElement.offsetWidth, body.offsetWidth); + + scrollHeight = max(documentElement.scrollHeight, body.scrollHeight); + clientHeight = max(documentElement.clientHeight, body.clientHeight); + offsetHeight = max(documentElement.offsetHeight, body.offsetHeight); + + return { + width: scrollWidth < offsetWidth ? clientWidth : scrollWidth, + height: scrollHeight < offsetHeight ? clientHeight : scrollHeight + }; + } + + return function(id, settings) { + var eventOverlayElm, doc = document, downButton, start, stop, drag, startX, startY; + + settings = settings || {}; + + function getHandleElm() { + return doc.getElementById(settings.handle || id); + } + + start = function(e) { + var docSize = getDocumentSize(), handleElm, cursor; + + e.preventDefault(); + downButton = e.button; + handleElm = getHandleElm(); + startX = e.screenX; + startY = e.screenY; + + // Grab cursor from handle + if (window.getComputedStyle) { + cursor = window.getComputedStyle(handleElm, null).getPropertyValue("cursor"); + } else { + cursor = handleElm.runtimeStyle.cursor; + } + + // Create event overlay and add it to document + eventOverlayElm = doc.createElement('div'); + DomUtils.css(eventOverlayElm, { + position: "absolute", + top: 0, left: 0, + width: docSize.width, + height: docSize.height, + zIndex: 0xFFFF, + opacity: 0.0001, + background: 'red', + cursor: cursor + }); + + doc.body.appendChild(eventOverlayElm); + + // Bind mouse events + DomUtils.on(doc, 'mousemove', drag); + DomUtils.on(doc, 'mouseup', stop); + + // Begin drag + settings.start(e); + }; + + drag = function(e) { + if (e.button !== downButton) { + return stop(e); + } + + e.deltaX = e.screenX - startX; + e.deltaY = e.screenY - startY; + + e.preventDefault(); + settings.drag(e); + }; + + stop = function(e) { + DomUtils.off(doc, 'mousemove', drag); + DomUtils.off(doc, 'mouseup', stop); + + eventOverlayElm.parentNode.removeChild(eventOverlayElm); + + if (settings.stop) { + settings.stop(e); + } + }; + + this.destroy = function() { + DomUtils.off(getHandleElm()); + }; + + DomUtils.on(getHandleElm(), 'mousedown', start); + }; +}); + +// Included from: js/tinymce/classes/ui/Scrollable.js + +/** + * Scrollable.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Scrollable.less + * @mixin tinymce.ui.Scrollable + */ +define("tinymce/ui/Scrollable", [ + "tinymce/ui/DomUtils", + "tinymce/ui/DragHelper" +], function(DomUtils, DragHelper) { + "use strict"; + + return { + init: function() { + var self = this; + self.on('repaint', self.renderScroll); + }, + + renderScroll: function() { + var self = this, margin = 2; + + function repaintScroll() { + var hasScrollH, hasScrollV, bodyElm; + + function repaintAxis(axisName, posName, sizeName, contentSizeName, hasScroll, ax) { + var containerElm, scrollBarElm, scrollThumbElm; + var containerSize, scrollSize, ratio, rect; + var posNameLower, sizeNameLower; + + scrollBarElm = self.getEl('scroll' + axisName); + if (scrollBarElm) { + posNameLower = posName.toLowerCase(); + sizeNameLower = sizeName.toLowerCase(); + + if (self.getEl('absend')) { + DomUtils.css(self.getEl('absend'), posNameLower, self.layoutRect()[contentSizeName] - 1); + } + + if (!hasScroll) { + DomUtils.css(scrollBarElm, 'display', 'none'); + return; + } + + DomUtils.css(scrollBarElm, 'display', 'block'); + containerElm = self.getEl('body'); + scrollThumbElm = self.getEl('scroll' + axisName + "t"); + containerSize = containerElm["client" + sizeName] - (margin * 2); + containerSize -= hasScrollH && hasScrollV ? scrollBarElm["client" + ax] : 0; + scrollSize = containerElm["scroll" + sizeName]; + ratio = containerSize / scrollSize; + + rect = {}; + rect[posNameLower] = containerElm["offset" + posName] + margin; + rect[sizeNameLower] = containerSize; + DomUtils.css(scrollBarElm, rect); + + rect = {}; + rect[posNameLower] = containerElm["scroll" + posName] * ratio; + rect[sizeNameLower] = containerSize * ratio; + DomUtils.css(scrollThumbElm, rect); + } + } + + bodyElm = self.getEl('body'); + hasScrollH = bodyElm.scrollWidth > bodyElm.clientWidth; + hasScrollV = bodyElm.scrollHeight > bodyElm.clientHeight; + + repaintAxis("h", "Left", "Width", "contentW", hasScrollH, "Height"); + repaintAxis("v", "Top", "Height", "contentH", hasScrollV, "Width"); + } + + function addScroll() { + function addScrollAxis(axisName, posName, sizeName, deltaPosName, ax) { + var scrollStart, axisId = self._id + '-scroll' + axisName, prefix = self.classPrefix; + + self.getEl().appendChild(DomUtils.createFragment( + '
    ' + + '
    ' + + '
    ' + )); + + self.draghelper = new DragHelper(axisId + 't', { + start: function() { + scrollStart = self.getEl('body')["scroll" + posName]; + DomUtils.addClass(DomUtils.get(axisId), prefix + 'active'); + }, + + drag: function(e) { + var ratio, hasScrollH, hasScrollV, containerSize, layoutRect = self.layoutRect(); + + hasScrollH = layoutRect.contentW > layoutRect.innerW; + hasScrollV = layoutRect.contentH > layoutRect.innerH; + containerSize = self.getEl('body')["client" + sizeName] - (margin * 2); + containerSize -= hasScrollH && hasScrollV ? self.getEl('scroll' + axisName)["client" + ax] : 0; + + ratio = containerSize / self.getEl('body')["scroll" + sizeName]; + self.getEl('body')["scroll" + posName] = scrollStart + (e["delta" + deltaPosName] / ratio); + }, + + stop: function() { + DomUtils.removeClass(DomUtils.get(axisId), prefix + 'active'); + } + }); +/* + self.on('click', function(e) { + if (e.target.id == self._id + '-scrollv') { + + } + });*/ + } + + self.addClass('scroll'); + + addScrollAxis("v", "Top", "Height", "Y", "Width"); + addScrollAxis("h", "Left", "Width", "X", "Height"); + } + + if (self.settings.autoScroll) { + if (!self._hasScroll) { + self._hasScroll = true; + addScroll(); + + self.on('wheel', function(e) { + var bodyEl = self.getEl('body'); + + bodyEl.scrollLeft += (e.deltaX || 0) * 10; + bodyEl.scrollTop += e.deltaY * 10; + + repaintScroll(); + }); + + DomUtils.on(self.getEl('body'), "scroll", repaintScroll); + } + + repaintScroll(); + } + } + }; +}); + +// Included from: js/tinymce/classes/ui/Panel.js + +/** + * Panel.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Panel.less + * @class tinymce.ui.Panel + * @extends tinymce.ui.Container + */ +define("tinymce/ui/Panel", [ + "tinymce/ui/Container", + "tinymce/ui/Scrollable" +], function(Container, Scrollable) { + "use strict"; + + var Panel = Container.extend({ + Defaults: { + layout: 'fit', + containerCls: 'panel' + }, + + Mixins: [Scrollable], + + fromJSON: function(data) { + var self = this; + + for (var name in data) { + self.find('#' + name).value(data[name]); + } + + return self; + }, + + toJSON: function() { + var self = this, data = {}; + + self.find('*').each(function(ctrl) { + var name = ctrl.name(), value = ctrl.value(); + + if (name && typeof(value) != "undefined") { + data[name] = value; + } + }); + + return data; + }, + + renderHtml: function() { + var self = this, layout = self._layout, innerHtml = self.settings.html; + + self.preRender(); + layout.preRender(self); + + if (typeof(innerHtml) == "undefined") { + innerHtml = ( + '
    ' + + layout.renderHtml(self) + + '
    ' + ); + } else { + if (typeof(innerHtml) == 'function') { + innerHtml = innerHtml(); + } + + self._hasBody = false; + } + + return ( + '
    ' + + (self._preBodyHtml || '') + + innerHtml + + '
    ' + ); + } + }); + + return Panel; +}); + +// Included from: js/tinymce/classes/ui/Movable.js + +/** + * Movable.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +define("tinymce/ui/Movable", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + return { + moveRel: function(elm, rel) { + var self = this, ctrlElm, pos, x, y, selfW, selfH, targetW, targetH; + + // Get pos of target + pos = DomUtils.getPos(elm); + x = pos.x; + y = pos.y; + + // Get size of self + ctrlElm = self.getEl(); + selfW = ctrlElm.offsetWidth; + selfH = ctrlElm.offsetHeight; + + // Get size of target + targetW = elm.offsetWidth; + targetH = elm.offsetHeight; + + // Parse align string + rel = (rel || '').split(''); + + // Target corners + if (rel[0] === 'b') { + y += targetH; + } + + if (rel[1] === 'r') { + x += targetW; + } + + if (rel[0] === 'c') { + y += Math.round(targetH / 2); + } + + if (rel[1] === 'c') { + x += Math.round(targetW / 2); + } + + // Self corners + if (rel[3] === 'b') { + y -= selfH; + } + + if (rel[4] === 'r') { + x -= selfW; + } + + if (rel[3] === 'c') { + y -= Math.round(selfH / 2); + } + + if (rel[4] === 'c') { + x -= Math.round(selfW / 2); + } + + self.moveTo(x, y); + + return self; + }, + + moveBy: function(dx, dy) { + var self = this, rect = self.layoutRect(); + + self.moveTo(rect.x + dx, rect.y + dy); + + return self; + }, + + moveTo: function(x, y) { + var self = this; + + if (self._rendered) { + self.layoutRect({x: x, y: y}).repaint(); + } else { + self.settings.x = x; + self.settings.y = y; + } + + return self; + } + }; +}); + +// Included from: js/tinymce/classes/ui/Resizable.js + +/** + * Resizable.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +define("tinymce/ui/Resizable", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + return { + resizeToContent: function() { + this._layoutRect.autoResize = true; + this._lastRect = null; + this.reflow(); + }, + + resizeTo: function(w, h) { + // TODO: Fix hack + if (w <= 1 || h <= 1) { + var rect = DomUtils.getWindowSize(); + + w = w <= 1 ? w * rect.w : w; + h = h <= 1 ? h * rect.h : h; + } + + this._layoutRect.autoResize = false; + return this.layoutRect({minW: w, minH: h, w: w, h: h}).reflow(); + }, + + resizeBy: function(dw, dh) { + var self = this, rect = self.layoutRect(); + + return self.resizeTo(rect.w + dw, rect.h + dh); + } + }; +}); + +// Included from: js/tinymce/classes/ui/FloatPanel.js + +/** + * FloatPanel.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less FloatPanel.less + * @class tinymce.ui.FloatPanel + * @extends tinymce.ui.Panel + */ +define("tinymce/ui/FloatPanel", [ + "tinymce/ui/Panel", + "tinymce/ui/Movable", + "tinymce/ui/Resizable", + "tinymce/ui/DomUtils" +], function(Panel, Movable, Resizable, DomUtils) { + "use strict"; + + var documentClickHandler, autoHidePanels = []; + var zOrder = [], hasModal; + + var FloatPanel = Panel.extend({ + Mixins: [Movable, Resizable], + + init: function(settings) { + var self = this; + + function reorder() { + var i, zIndex = FloatPanel.zIndex || 0xFFFF, topModal; + + if (zOrder.length) { + for (i = 0; i < zOrder.length; i++) { + if (zOrder[i].modal) { + zIndex++; + topModal = zOrder[i]; + } + + zOrder[i].getEl().style.zIndex = zIndex; + zOrder[i].zIndex = zIndex; + zIndex++; + } + } + + var modalBlockEl = document.getElementById(self.classPrefix + 'modal-block'); + + if (topModal) { + DomUtils.css(modalBlockEl, 'z-index', topModal.zIndex - 1); + } else if (modalBlockEl) { + modalBlockEl.parentNode.removeChild(modalBlockEl); + hasModal = false; + } + + FloatPanel.currentZIndex = zIndex; + } + + function isChildOf(ctrl, parent) { + while (ctrl) { + if (ctrl == parent) { + return true; + } + + ctrl = ctrl.parent(); + } + } + + self._super(settings); + self._eventsRoot = self; + + self.addClass('floatpanel'); + + // Hide floatpanes on click out side the root button + if (settings.autohide) { + if (!documentClickHandler) { + documentClickHandler = function(e) { + var i, clickCtrl = self.getParentCtrl(e.target); + + // Hide any float panel when a click is out side that float panel and the + // float panels direct parent for example a click on a menu button + i = autoHidePanels.length; + while (i--) { + if (clickCtrl) { + if (isChildOf(clickCtrl, autoHidePanels[i]) || autoHidePanels[i].parent() === clickCtrl) { + continue; + } + } + + autoHidePanels[i].hide(); + } + }; + + DomUtils.on(document, 'click', documentClickHandler); + } + + autoHidePanels.push(self); + } + + self.on('postrender show', function(e) { + if (e.control == self) { + var modalBlockEl, prefix = self.classPrefix; + + if (self.modal && !hasModal) { + modalBlockEl = DomUtils.createFragment('
    '); + modalBlockEl = modalBlockEl.firstChild; + + self.getContainerElm().appendChild(modalBlockEl); + + setTimeout(function() { + DomUtils.addClass(modalBlockEl, prefix + 'in'); + DomUtils.addClass(self.getEl(), prefix + 'in'); + }, 0); + + hasModal = true; + } + + zOrder.push(self); + reorder(); + } + }); + + self.on('close hide', function(e) { + if (e.control == self) { + var i = zOrder.length; + + while (i--) { + if (zOrder[i] === self) { + zOrder.splice(i, 1); + } + } + + reorder(); + } + }); + + if (settings.popover) { + self._preBodyHtml = '
    '; + self.addClass('popover').addClass('bottom').addClass('start'); + } + }, + + show: function() { + var self = this, i, state = self._super(); + + i = autoHidePanels.length; + while (i--) { + if (autoHidePanels[i] === self) { + break; + } + } + + if (self.settings.autohide && i === -1) { + autoHidePanels.push(self); + } + + return state; + }, + + hide: function() { + var i; + + i = autoHidePanels.length; + while (i--) { + if (autoHidePanels[i] === this) { + autoHidePanels.splice(i, 1); + } + } + + return this._super(); + }, + + hideAll: function() { + FloatPanel.hideAll(); + }, + + close: function() { + var self = this; + + self.fire('close'); + + return self.remove(); + }, + + remove: function() { + var self = this; + + self._super(); + } + }); + + FloatPanel.hideAll = function() { + var i = autoHidePanels.length; + + while (i--) { + autoHidePanels[i].fire('cancel', {}, false); + autoHidePanels[i].hide(); + autoHidePanels.splice(i, 1); + } + }; + + return FloatPanel; +}); + +// Included from: js/tinymce/classes/ui/KeyboardNavigation.js + +/** + * KeyboardFocus.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.KeyboardNavigation + */ +define("tinymce/ui/KeyboardNavigation", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + /** + * Create a new KeyboardNavigation instance to handle the focus for a specific element. + * + * @constructor + * @method KeyboardNavigation + * @param {Object} settings the settings object to define how keyboard navigation works. + * + * @setting {tinymce.ui.Control} root the root control navigation focus movement is scoped to this root. + * @setting {Array} items an array containing the items to move focus between. Every object in this array must have an + * id attribute which maps to the actual DOM element and it must be able to have focus i.e. tabIndex=-1. + * @setting {Function} onCancel the callback for when the user presses escape or otherwise indicates cancelling. + * @setting {Function} onAction (optional) the action handler to call when the user activates an item. + * @setting {Boolean} enableLeftRight (optional, default) when true, the up/down arrows move through items. + * @setting {Boolean} enableUpDown (optional) when true, the up/down arrows move through items. + * Note for both up/down and left/right explicitly set both enableLeftRight and enableUpDown to true. + */ + return function(settings) { + var root = settings.root, enableUpDown = settings.enableUpDown !== false; + var enableLeftRight = settings.enableLeftRight !== false; + var items = settings.items, focussedId; + + /** + * Initializes the items array if needed. This will collect items/elements + * from the specified root control. + */ + function initItems() { + if (!items) { + items = []; + + if (root.find) { + // Root is a container then get child elements using the UI API + root.find('*').each(function(ctrl) { + if (ctrl.canFocus) { + items.push(ctrl.getEl()); + } + }); + } else { + // Root is a control/widget then get the child elements of that control + var elements = root.getEl().getElementsByTagName('*'); + for (var i = 0; i < elements.length; i++) { + if (elements[i].id && elements[i]) { + items.push(elements[i]); + } + } + } + } + } + + /** + * Returns the currently focused element. + * + * @return {Element} Currently focused element. + */ + function getFocusElement() { + return document.getElementById(focussedId); + } + + /** + * Returns the currently focused elements wai aria role. + * + * @param {Element} elm Optional element to get role from. + * @return {String} Role of specified element. + */ + function getRole(elm) { + elm = elm || getFocusElement(); + + return elm && elm.getAttribute('role'); + } + + /** + * Returns the role of the parent element. + * + * @param {Element} elm Optional element to get parent role from. + * @return {String} Role of the first parent that has a role. + */ + function getParentRole(elm) { + var role, parent = elm || getFocusElement(); + + while ((parent = parent.parentNode)) { + if ((role = getRole(parent))) { + return role; + } + } + } + + /** + * Returns an wai aria property by name. + * + * @param {String} name Name of the aria property to get for example "disabled". + * @return {String} Aria property value. + */ + function getAriaProp(name) { + var elm = document.getElementById(focussedId); + + if (elm) { + return elm.getAttribute('aria-' + name); + } + } + + /** + * Executes the onAction event callback. This is when the user presses enter/space. + */ + function action() { + var focusElm = getFocusElement(); + + if (focusElm && (focusElm.nodeName == "TEXTAREA" || focusElm.type == "text")) { + return; + } + + if (settings.onAction) { + settings.onAction(focussedId); + } else { + DomUtils.fire(getFocusElement(), 'click', {keyboard: true}); + } + + return true; + } + + /** + * Cancels the current navigation. The same as pressing the Esc key. + */ + function cancel() { + var focusElm; + + if (settings.onCancel) { + if ((focusElm = getFocusElement())) { + focusElm.blur(); + } + + settings.onCancel(); + } else { + settings.root.fire('cancel'); + } + } + + /** + * Moves the focus to the next or previous item. It will wrap to start/end if it can't move. + * + * @param {Number} dir Direction for move -1 or 1. + */ + function moveFocus(dir) { + var idx = -1, focusElm, i; + + initItems(); + + i = items.length; + while (i--) { + if (items[i].id === focussedId) { + idx = i; + break; + } + } + + idx += dir; + if (idx < 0) { + idx = items.length - 1; + } else if (idx >= items.length) { + idx = 0; + } + + focusElm = items[idx]; + focusElm.focus(); + focussedId = focusElm.id; + + if (settings.actOnFocus) { + action(); + } + } + + /** + * Moves focus to the first item or the last focused item if root is a toolbar. + * + * @return {[type]} [description] + */ + function focusFirst() { + var i, rootRole; + + rootRole = getRole(settings.root.getEl()); + initItems(); + + i = items.length; + while (i--) { + if (rootRole == 'toolbar' && items[i].id === focussedId) { + items[i].focus(); + return; + } + } + + items[0].focus(); + } + + // Handle accessible keys + root.on('keydown', function(e) { + var DOM_VK_LEFT = 37, DOM_VK_RIGHT = 39, DOM_VK_UP = 38, DOM_VK_DOWN = 40; + var DOM_VK_ESCAPE = 27, DOM_VK_ENTER = 14, DOM_VK_RETURN = 13, DOM_VK_SPACE = 32, DOM_VK_TAB = 9; + var preventDefault; + + switch (e.keyCode) { + case DOM_VK_LEFT: + if (enableLeftRight) { + if (settings.leftAction) { + settings.leftAction(); + } else { + moveFocus(-1); + } + + preventDefault = true; + } + break; + + case DOM_VK_RIGHT: + if (enableLeftRight) { + if (getRole() == 'menuitem' && getParentRole() == 'menu') { + if (getAriaProp('haspopup')) { + action(); + } + } else { + moveFocus(1); + } + + preventDefault = true; + } + break; + + case DOM_VK_UP: + if (enableUpDown) { + moveFocus(-1); + preventDefault = true; + } + break; + + case DOM_VK_DOWN: + if (enableUpDown) { + if (getRole() == 'menuitem' && getParentRole() == 'menubar') { + action(); + } else if (getRole() == 'button' && getAriaProp('haspopup')) { + action(); + } else { + moveFocus(1); + } + + preventDefault = true; + } + break; + + case DOM_VK_TAB: + preventDefault = true; + + if (e.shiftKey) { + moveFocus(-1); + } else { + moveFocus(1); + } + break; + + case DOM_VK_ESCAPE: + preventDefault = true; + cancel(); + break; + + case DOM_VK_ENTER: + case DOM_VK_RETURN: + case DOM_VK_SPACE: + preventDefault = action(); + break; + } + + if (preventDefault) { + e.stopPropagation(); + e.preventDefault(); + } + }); + + // Init on focus in + root.on('focusin', function(e) { + initItems(); + focussedId = e.target.id; + }); + + return { + moveFocus: moveFocus, + focusFirst: focusFirst, + cancel: cancel + }; + }; +}); + +// Included from: js/tinymce/classes/ui/Window.js + +/** + * Window.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Window.less + * @class tinymce.ui.Window + * @extends tinymce.ui.FloatPanel + */ +define("tinymce/ui/Window", [ + "tinymce/ui/FloatPanel", + "tinymce/ui/Panel", + "tinymce/ui/DomUtils", + "tinymce/ui/KeyboardNavigation", + "tinymce/ui/DragHelper" +], function(FloatPanel, Panel, DomUtils, KeyboardNavigation, DragHelper) { + "use strict"; + + var Window = FloatPanel.extend({ + modal: true, + + Defaults: { + border: 1, + layout: 'flex', + containerCls: 'panel', + role: 'dialog', + callbacks: { + submit: function() { + this.fire('submit', {data: this.toJSON()}); + }, + + close: function() { + this.close(); + } + } + }, + + init: function(settings) { + var self = this; + + self._super(settings); + + self.addClass('window'); + + // Create statusbar + if (settings.buttons) { + self.statusbar = new Panel({ + layout: 'flex', + border: '1 0 0 0', + spacing: 3, + padding: 10, + align: 'center', + pack: 'end', + defaults: { + type: 'button' + }, + items: settings.buttons + }); + + self.statusbar.addClass('foot'); + self.statusbar.parent(self); + } + + self.on('click', function(e) { + if (e.target.className.indexOf(self.classPrefix + 'close') != -1) { + self.close(); + } + }); +/* + self.on('postrender show', function(e) { + if (e.control == self) { + var parentWin = getTopMostWindow(), zIndex = FloatPanel.zIndex; + + if (parentWin) { + zIndex = parentWin.zIndex; + } + + if (!DomUtils.get(prefix + 'modal-block')) { + var modalBlockEl = DomUtils.createFragment('
    '); + + modalBlockEl = modalBlockEl.firstChild; + + self.getContainerElm().appendChild(modalBlockEl); + + setTimeout(function() { + DomUtils.addClass(modalBlockEl, prefix + 'in'); + DomUtils.addClass(self.getEl(), prefix + 'in'); + }, 0); + + FloatPanel.zOrder.push({zIndex: zIndex}); + DomUtils.css(self.getEl(), 'z-index', zIndex + 1); + } + + DomUtils.css(DomUtils.get(prefix + 'modal-block'), 'z-index', zIndex - 1); + } + }); + + self.on('close hide', function(e) { + if (e.control == self) { + var topWin = getTopMostWindow(); + + if (!topWin) { + var modalBlockEl = document.getElementById(prefix + 'modal-block'); + if (modalBlockEl) { + modalBlockEl.parentNode.removeChild(modalBlockEl); + } + } else { + DomUtils.css(DomUtils.get(prefix + 'modal-block'), 'z-index', topWin.zIndex - 1); + } + } + }); +*/ + self.aria('label', settings.title); + self._fullscreen = false; + }, + + recalc: function() { + var self = this, statusbar = self.statusbar, layoutRect, width, needsRecalc; + + if (self._fullscreen) { + self.layoutRect(DomUtils.getWindowSize()); + self.layoutRect().contentH = self.layoutRect().innerH; + } + + self._super(); + + layoutRect = self.layoutRect(); + + // Resize window based on title width + if (self.settings.title && !self._fullscreen) { + width = layoutRect.headerW; + if (width > layoutRect.minW) { + layoutRect.minW = layoutRect.w = width + (layoutRect.w - layoutRect.innerW); + layoutRect.innerW = layoutRect.w - layoutRect.deltaW; + needsRecalc = true; + } + } + + // Resize window based on statusbar width + if (statusbar) { + statusbar.layoutRect({w: self.layoutRect().innerW}).recalc(); + + width = statusbar.layoutRect().minW + layoutRect.deltaW; + if (width > layoutRect.minW) { + layoutRect.minW = layoutRect.w = width; + layoutRect.innerW = layoutRect.w - layoutRect.deltaW; + needsRecalc = true; + } + } + + // Recalc body and disable auto resize + if (needsRecalc) { + self.recalc(); + return; + } + }, + + initLayoutRect: function() { + var self = this, layoutRect = self._super(), deltaH = 0, headEl; + + // Reserve vertical space for title + if (self.settings.title && !self._fullscreen) { + headEl = self.getEl('head'); + layoutRect.headerW = headEl.offsetWidth; + layoutRect.headerH = headEl.offsetHeight; + deltaH += layoutRect.headerH; + } + + // Reserve vertical space for statusbar + if (self.statusbar) { + deltaH += self.statusbar.layoutRect().h; + } + + layoutRect.deltaH += deltaH; + layoutRect.minH += deltaH; + //layoutRect.innerH -= deltaH; + layoutRect.h += deltaH; + + var rect = DomUtils.getWindowSize(); + + layoutRect.x = Math.max(0, rect.w / 2 - layoutRect.w / 2); + layoutRect.y = Math.max(0, rect.h / 2 - layoutRect.h / 2); + + return layoutRect; + }, + + renderHtml: function() { + var self = this, layout = self._layout, id = self._id, prefix = self.classPrefix; + var settings = self.settings, headerHtml = '', footerHtml = '', html = settings.html; + + self.preRender(); + layout.preRender(self); + + if (settings.title) { + headerHtml = ( + '
    ' + + '
    ' + settings.title + '
    ' + + '' + + '
    ' + + '
    ' + ); + } + + if (settings.url) { + html = ''; + } + + if (typeof(html) == "undefined") { + html = layout.renderHtml(self); + } + + if (self.statusbar) { + footerHtml = self.statusbar.renderHtml(); + } + + return ( + '
    ' + + headerHtml + + '
    ' + + html + + '
    ' + + footerHtml + + '
    ' + ); + }, + + fullscreen: function(state) { + var self = this, documentElement = document.documentElement, slowRendering, prefix = self.classPrefix, layoutRect; + + if (state != self._fullscreen) { + DomUtils.on(window, 'resize', function() { + var time; + + if (self._fullscreen) { + // Time the layout time if it's to slow use a timeout to not hog the CPU + if (!slowRendering) { + time = new Date().getTime(); + + var rect = DomUtils.getWindowSize(); + self.moveTo(0, 0).resizeTo(rect.w, rect.h); + + if ((new Date().getTime()) - time > 50) { + slowRendering = true; + } + } else { + if (!self._timer) { + self._timer = setTimeout(function() { + var rect = DomUtils.getWindowSize(); + self.moveTo(0, 0).resizeTo(rect.w, rect.h); + + self._timer = 0; + }, 50); + } + } + } + }); + + layoutRect = self.layoutRect(); + self._fullscreen = state; + + if (!state) { + self._borderBox = self.parseBox(self.settings.border); + self.getEl('head').style.display = ''; + layoutRect.deltaH += layoutRect.headerH; + DomUtils.removeClass(documentElement, prefix + 'fullscreen'); + DomUtils.removeClass(document.body, prefix + 'fullscreen'); + self.removeClass('fullscreen'); + self.moveTo(self._initial.x, self._initial.y).resizeTo(self._initial.w, self._initial.h); + } else { + self._initial = {x: layoutRect.x, y: layoutRect.y, w: layoutRect.w, h: layoutRect.h}; + + self._borderBox = self.parseBox('0'); + self.getEl('head').style.display = 'none'; + layoutRect.deltaH -= layoutRect.headerH + 2; + DomUtils.addClass(documentElement, prefix + 'fullscreen'); + DomUtils.addClass(document.body, prefix + 'fullscreen'); + self.addClass('fullscreen'); + + var rect = DomUtils.getWindowSize(); + self.moveTo(0, 0).resizeTo(rect.w, rect.h); + } + } + + return self.reflow(); + }, + + postRender: function() { + var self = this, items = [], focusCtrl, autoFocusFound, startPos; + + setTimeout(function() { + self.addClass('in'); + }, 0); + + self.find('*').each(function(ctrl) { + if (ctrl.canFocus) { + autoFocusFound = autoFocusFound || ctrl.settings.autofocus; + focusCtrl = focusCtrl || ctrl; + + // TODO: Figure out a better way + if (ctrl.type == 'filepicker') { + items.push(ctrl.getEl('inp')); + + if (ctrl.getEl('open')) { + items.push(ctrl.getEl('open').firstChild); + } + } else { + items.push(ctrl.getEl()); + } + } + }); + + if (self.statusbar) { + self.statusbar.find('*').each(function(ctrl) { + if (ctrl.canFocus) { + autoFocusFound = autoFocusFound || ctrl.settings.autofocus; + focusCtrl = focusCtrl || ctrl; + items.push(ctrl.getEl()); + } + }); + } + + self.keyboardNavigation = new KeyboardNavigation({ + root: self, + enableLeftRight: false, + enableUpDown: false, + items: items, + onCancel: function() { + self.close(); + } + }); + + self._super(); + + if (self.statusbar) { + self.statusbar.postRender(); + } + + if (!autoFocusFound && focusCtrl) { + focusCtrl.focus(); + } + + this.dragHelger = new DragHelper(self._id + '-dragh', { + start: function() { + startPos = { + x: self.layoutRect().x, + y: self.layoutRect().y + }; + }, + + drag: function(e) { + self.moveTo(startPos.x + e.deltaX, startPos.y + e.deltaY); + } + }); + + self.on('submit', function(e) { + if (!e.isDefaultPrevented()) { + self.close(); + } + }); + }, + + submit: function() { + return this.fire('submit', {data: this.toJSON()}); + }, + + remove: function() { + var self = this; + + self._super(); + self.dragHelger.destroy(); + + if (self.statusbar) { + this.statusbar.remove(); + } + } + }); + + return Window; +}); + +// Included from: js/tinymce/classes/ui/MessageBox.js + +/** + * MessageBox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.Window + * @extends tinymce.ui.FloatPanel + */ +define("tinymce/ui/MessageBox", [ + "tinymce/ui/Window" +], function(Window) { + "use strict"; + + var MessageBox = Window.extend({ + init: function(settings) { + settings = { + border: 1, + padding: 20, + layout: 'flex', + pack: "center", + align: "center", + containerCls: 'panel', + autoScroll: true, + buttons: {type: "button", text: "Ok", action: "ok"}, + items: { + type: "label", + multiline: true, + maxWidth: 500, + maxHeight: 200 + } + }; + + this._super(settings); + }, + + Statics: { + OK: 1, + OK_CANCEL: 2, + YES_NO: 3, + YES_NO_CANCEL: 4, + + msgBox: function(settings) { + var buttons, callback = settings.callback || function() {}; + + switch (settings.buttons) { + case MessageBox.OK_CANCEL: + buttons = [ + {type: "button", text: "Ok", subtype: "primary", onClick: function(e) { + e.control.parents()[1].close(); + callback(true); + }}, + + {type: "button", text: "Cancel", onClick: function(e) { + e.control.parents()[1].close(); + callback(false); + }} + ]; + break; + + case MessageBox.YES_NO: + buttons = [ + {type: "button", text: "Ok", subtype: "primary", onClick: function(e) { + e.control.parents()[1].close(); + callback(true); + }} + ]; + break; + + case MessageBox.YES_NO_CANCEL: + buttons = [ + {type: "button", text: "Ok", subtype: "primary", onClick: function(e) { + e.control.parents()[1].close(); + }} + ]; + break; + + default: + buttons = [ + {type: "button", text: "Ok", subtype: "primary", onClick: function(e) { + e.control.parents()[1].close(); + }} + ]; + break; + } + + return new Window({ + padding: 20, + x: settings.x, + y: settings.y, + minWidth: 300, + minHeight: 100, + layout: "flex", + pack: "center", + align: "center", + buttons: buttons, + title: settings.title, + items: { + type: "label", + multiline: true, + maxWidth: 500, + maxHeight: 200, + text: settings.text + }, + onClose: settings.onClose + }).renderTo(document.body).reflow(); + }, + + alert: function(settings, callback) { + if (typeof(settings) == "string") { + settings = {text: settings}; + } + + settings.callback = callback; + return MessageBox.msgBox(settings); + }, + + confirm: function(settings, callback) { + if (typeof(settings) == "string") { + settings = {text: settings}; + } + + settings.callback = callback; + settings.buttons = MessageBox.OK_CANCEL; + + return MessageBox.msgBox(settings); + } + } + }); + + return MessageBox; +}); + +// Included from: js/tinymce/classes/WindowManager.js + +/** + * WindowManager.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles the creation of native windows and dialogs. This class can be extended to provide for example inline dialogs. + * + * @class tinymce.WindowManager + * @example + * // Opens a new dialog with the file.htm file and the size 320x240 + * // It also adds a custom parameter this can be retrieved by using tinyMCEPopup.getWindowArg inside the dialog. + * tinymce.activeEditor.windowManager.open({ + * url: 'file.htm', + * width: 320, + * height: 240 + * }, { + * custom_param: 1 + * }); + * + * // Displays an alert box using the active editors window manager instance + * tinymce.activeEditor.windowManager.alert('Hello world!'); + * + * // Displays an confirm box and an alert message will be displayed depending on what you choose in the confirm + * tinymce.activeEditor.windowManager.confirm("Do you want to do something", function(s) { + * if (s) + * tinymce.activeEditor.windowManager.alert("Ok"); + * else + * tinymce.activeEditor.windowManager.alert("Cancel"); + * }); + */ +define("tinymce/WindowManager", [ + "tinymce/ui/Window", + "tinymce/ui/MessageBox" +], function(Window, MessageBox) { + return function(editor) { + var self = this, windows = []; + + self.windows = windows; + + /** + * Opens a new window. + * + * @method open + * @param {Object} args Optional name/value settings collection contains things like width/height/url etc. + * @option {String} title Window title. + * @option {String} file URL of the file to open in the window. + * @option {Number} width Width in pixels. + * @option {Number} height Height in pixels. + * @option {Boolean} resizable Specifies whether the popup window is resizable or not. + * @option {Boolean} maximizable Specifies whether the popup window has a "maximize" button and can get maximized or not. + * @option {String/bool} scrollbars Specifies whether the popup window can have scrollbars if required (i.e. content + * larger than the popup size specified). + */ + self.open = function(args) { + var win; + + // Handle URL + args.url = args.url || args.file; // Legacy + if (args.url) { + args.width = parseInt(args.width || 320, 10); + args.height = parseInt(args.height || 240, 10); + } + + // Handle body + if (args.body) { + args.items = { + defaults: args.defaults, + type: args.bodyType || 'form', + items: args.body + }; + } + + if (!args.url && !args.buttons) { + args.buttons = [ + {text: 'Ok', subtype: 'primary', minWidth: 50, onclick: function() { + win.find('form')[0].submit(); + win.close(); + }}, + + {text: 'Cancel', onclick: function() { + win.close(); + }} + ]; + } + + win = new Window(args); + windows.push(win); + + win.on('close', function() { + var i = windows.length; + + while (i--) { + if (windows[i] === win) { + windows.splice(i, 1); + } + } + + editor.focus(); + }); + + // Handle data + if (args.data) { + win.on('postRender', function() { + this.find('*').each(function(ctrl) { + var name = ctrl.name(); + + if (name in args.data) { + ctrl.value(args.data[name]); + } + }); + }); + } + + return win.renderTo(document.body).reflow(); + }; + + /** + * Creates a alert dialog. Please don't use the blocking behavior of this + * native version use the callback method instead then it can be extended. + * + * @method alert + * @param {String} message Text to display in the new alert dialog. + * @param {function} callback Callback function to be executed after the user has selected ok. + * @param {Object} scope Optional scope to execute the callback in. + * @example + * // Displays an alert box using the active editors window manager instance + * tinymce.activeEditor.windowManager.alert('Hello world!'); + */ + self.alert = function(message, callback, scope) { + MessageBox.alert(message, function() { + callback.call(scope || this); + }); + }; + + /** + * Creates a confirm dialog. Please don't use the blocking behavior of this + * native version use the callback method instead then it can be extended. + * + * @method confirm + * @param {String} messageText to display in the new confirm dialog. + * @param {function} callback Callback function to be executed after the user has selected ok or cancel. + * @param {Object} scope Optional scope to execute the callback in. + * @example + * // Displays an confirm box and an alert message will be displayed depending on what you choose in the confirm + * tinymce.activeEditor.windowManager.confirm("Do you want to do something", function(s) { + * if (s) + * tinymce.activeEditor.windowManager.alert("Ok"); + * else + * tinymce.activeEditor.windowManager.alert("Cancel"); + * }); + */ + self.confirm = function(message, callback, scope) { + MessageBox.confirm(message, function(state) { + callback.call(scope || this, state); + }); + }; + + /** + * Closes the top most window. + * + * @method close + */ + self.close = function() { + if (windows.length) { + windows[window.length - 1].win.close(); + } + }; + }; +}); + +// Included from: js/tinymce/classes/util/Quirks.js + +/** + * Quirks.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This file includes fixes for various browser quirks it's made to make it easy to add/remove browser specific fixes. + * + * @class tinymce.util.Quirks + * @private + */ +define("tinymce/util/Quirks", [ + "tinymce/util/VK", + "tinymce/dom/RangeUtils", + "tinymce/html/Node", + "tinymce/html/Entities", + "tinymce/Env", + "tinymce/util/Tools" +], function(VK, RangeUtils, Node, Entities, Env, Tools) { + return function(editor) { + var each = Tools.each; + var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, + settings = editor.settings, parser = editor.parser, serializer = editor.serializer; + var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit; + + /** + * Executes a command with a specific state this can be to enable/disable browser editing features. + */ + function setEditorCommandState(cmd, state) { + try { + editor.getDoc().execCommand(cmd, false, state); + } catch (ex) { + // Ignore + } + } + + /** + * Returns current IE document mode. + */ + function getDocumentMode() { + var documentMode = editor.getDoc().documentMode; + + return documentMode ? documentMode : 6; + } + + /** + * Returns true/false if the event is prevented or not. + * + * @param {Event} e Event object. + * @return {Boolean} true/false if the event is prevented or not. + */ + function isDefaultPrevented(e) { + return e.isDefaultPrevented(); + } + + /** + * Fixes a WebKit bug when deleting contents using backspace or delete key. + * WebKit will produce a span element if you delete across two block elements. + * + * Example: + *

    a

    |b

    + * + * Will produce this on backspace: + *

    ab

    + * + * This fixes the backspace to produce: + *

    a|b

    + * + * See bug: https://bugs.webkit.org/show_bug.cgi?id=45784 + * + * This code is a bit of a hack and hopefully it will be fixed soon in WebKit. + */ + function cleanupStylesWhenDeleting() { + function removeMergedFormatSpans(isDelete) { + var rng, blockElm, wrapperElm, bookmark, container, offset, elm; + + function isAtStartOrEndOfElm() { + if (container.nodeType == 3) { + if (isDelete && offset == container.length) { + return true; + } + + if (!isDelete && offset === 0) { + return true; + } + } + } + + rng = selection.getRng(); + var tmpRng = [rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset]; + + if (!rng.collapsed) { + isDelete = true; + } + + container = rng[(isDelete ? 'start' : 'end') + 'Container']; + offset = rng[(isDelete ? 'start' : 'end') + 'Offset']; + + if (container.nodeType == 3) { + 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); + } + + if (blockElm && (isAtStartOrEndOfElm() || !rng.collapsed)) { + // Wrap children of block in a EM and let WebKit stick is + // runtime styles junk into that EM + wrapperElm = dom.create('em', {'id': '__mceDel'}); + + each(Tools.grep(blockElm.childNodes), function(node) { + wrapperElm.appendChild(node); + }); + + blockElm.appendChild(wrapperElm); + } + } + + // Do the backspace/delete action + rng = dom.createRng(); + rng.setStart(tmpRng[0], tmpRng[1]); + rng.setEnd(tmpRng[2], tmpRng[3]); + selection.setRng(rng); + editor.getDoc().execCommand(isDelete ? 'ForwardDelete' : 'Delete', false, null); + + // Remove temp wrapper element + if (wrapperElm) { + bookmark = selection.getBookmark(); + + while ((elm = dom.get('__mceDel'))) { + dom.remove(elm, true); + } + + selection.moveToBookmark(bookmark); + } + } + + editor.on('keydown', function(e) { + var isDelete; + + isDelete = e.keyCode == DELETE; + if (!isDefaultPrevented(e) && (isDelete || e.keyCode == BACKSPACE) && !VK.modifierPressed(e)) { + e.preventDefault(); + removeMergedFormatSpans(isDelete); + } + }); + + editor.addCommand('Delete', function() {removeMergedFormatSpans();}); + } + + /** + * Makes sure that the editor body becomes empty when backspace or delete is pressed in empty editors. + * + * For example: + *

    |

    + * + * Or: + *

    |

    + * + * Or: + * [

    ] + */ + 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.on('keydown', function(e) { + var keyCode = e.keyCode, isCollapsed; + + // Empty the editor if it's needed for example backspace at

    |

    + if (!isDefaultPrevented(e) && (keyCode == DELETE || keyCode == BACKSPACE)) { + isCollapsed = editor.selection.isCollapsed(); + + // Selection is collapsed but the editor isn't empty + if (isCollapsed && !dom.isEmpty(editor.getBody())) { + return; + } + + // IE deletes all contents correctly when everything is selected + if (isIE && !isCollapsed) { + return; + } + + // Selection isn't collapsed but not all the contents is selected + if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) { + return; + } + + // Manually empty the editor + e.preventDefault(); + editor.setContent(''); + editor.selection.setCursorLocation(editor.getBody(), 0); + editor.nodeChanged(); + } + }); + } + + /** + * WebKit doesn't select all the nodes in the body when you press Ctrl+A. + * This selects the whole body so that backspace/delete logic will delete everything + */ + function selectAll() { + editor.on('keydown', function(e) { + if (!isDefaultPrevented(e) && e.keyCode == 65 && VK.metaKeyPressed(e)) { + e.preventDefault(); + editor.execCommand('SelectAll'); + } + }); + } + + /** + * WebKit has a weird issue where it some times fails to properly convert keypresses to input method keystrokes. + * The IME on Mac doesn't initialize when it doesn't fire a proper focus event. + * + * This seems to happen when the user manages to click the documentElement element then the window doesn't get proper focus until + * you enter a character into the editor. + * + * It also happens when the first focus in made to the body. + * + * See: https://bugs.webkit.org/show_bug.cgi?id=83566 + */ + function inputMethodFocus() { + if (!editor.settings.content_editable) { + // Case 1 IME doesn't initialize if you focus the document + dom.bind(editor.getDoc(), 'focusin', function() { + selection.setRng(selection.getRng()); + }); + + // Case 2 IME doesn't initialize if you click the documentElement it also doesn't properly fire the focusin event + dom.bind(editor.getDoc(), 'mousedown', function(e) { + if (e.target == editor.getDoc().documentElement) { + editor.getWin().focus(); + selection.setRng(selection.getRng()); + } + }); + } + } + + /** + * Backspacing in FireFox/IE from a paragraph into a horizontal rule results in a floating text node because the + * browser just deletes the paragraph - the browser fails to merge the text node with a horizontal rule so it is + * left there. TinyMCE sees a floating text node and wraps it in a paragraph on the key up event (ForceBlocks.js + * addRootBlocks), meaning the action does nothing. With this code, FireFox/IE matche the behaviour of other + * browsers + */ + function removeHrOnBackspace() { + editor.on('keydown', function(e) { + if (!isDefaultPrevented(e) && 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); + e.preventDefault(); + } + } + } + }); + } + + /** + * Firefox 3.x has an issue where the body element won't get proper focus if you click out + * side it's rectangle. + */ + 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 (!window.Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4 + editor.on('mousedown', function(e) { + if (!isDefaultPrevented(e) && 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); + } + }); + } + } + + /** + * WebKit has a bug where it isn't possible to select image, hr or anchor elements + * by clicking on them so we need to fake that. + */ + function selectControlElements() { + editor.on('click', function(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(); + }); + } + + /** + * Fixes a Gecko bug where the style attribute gets added to the wrong element when deleting between two block elements. + * + * Fixes do backspace/delete on this: + *

    bla[ck

    r]ed

    + * + * Would become: + *

    bla|ed

    + * + * Instead of: + *

    bla|ed

    + */ + 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); + + each(template, function(attr) { + target.setAttributeNode(attr.cloneNode(true)); + }); + } + }; + } + + function isSelectionAcrossElements() { + return !selection.isCollapsed() && + dom.getParent(selection.getStart(), dom.isBlock) != dom.getParent(selection.getEnd(), dom.isBlock); + } + + editor.on('keypress', function(e) { + var applyAttributes; + + if (!isDefaultPrevented(e) && (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 (!isDefaultPrevented(e) && isSelectionAcrossElements()) { + applyAttributes = getAttributeApplyFunction(); + + setTimeout(function() { + applyAttributes(); + }, 0); + } + }); + } + + /** + * Fire a nodeChanged when the selection is changed on WebKit this fixes selection issues on iOS5. It only fires the nodeChange + * event every 50ms since it would other wise update the UI when you type and it hogs the CPU. + */ + function selectionChangeNodeChanged() { + var lastRng, selectionTimer; + + editor.on('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 || !RangeUtils.compareRanges(rng, lastRng)) { + editor.nodeChanged(); + lastRng = rng; + } + }, 50); + }); + } + + /** + * Screen readers on IE needs to have the role application set on the body. + */ + function ensureBodyHasRoleApplication() { + document.body.setAttribute("role", "application"); + } + + /** + * Backspacing into a table behaves differently depending upon browser type. + * Therefore, disable Backspace when cursor immediately follows a table. + */ + function disableBackspaceIntoATable() { + editor.on('keydown', function(e) { + if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { + if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { + var previousSibling = selection.getNode().previousSibling; + if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") { + e.preventDefault(); + return false; + } + } + } + }); + } + + /** + * Old IE versions can't properly render BR elements in PRE tags white in contentEditable mode. So this + * logic adds a \n before the BR so that it will get rendered. + */ + function addNewLinesBeforeBrInPre() { + // IE8+ rendering mode does the right thing with BR in PRE + if (getDocumentMode() > 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); + editor.contentStyles.push('.mceHideBrInPre pre br {display: none}'); + dom.addClass(editor.getBody(), 'mceHideBrInPre'); + + // Adds a \n before all BR elements in PRE to get them visual + parser.addNodeFilter('pre', function(nodes) { + 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 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 + serializer.addNodeFilter('pre', function(nodes) { + 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$/, ''); + } + } + } + }); + } + + /** + * Moves style width/height to attribute width/height when the user resizes an image on IE. + */ + function removePreSerializedStylesWhenSelectingControls() { + dom.bind(editor.getBody(), 'mouseup', function() { + 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', ''); + } + } + }); + } + + /** + * Backspace or delete on WebKit will combine all visual styles in a span if the last character is deleted. + * + * For example backspace on: + *

    x|

    + * + * Will produce: + *

    |

    + * + * When it should produce: + *

    |

    + * + * See: https://bugs.webkit.org/show_bug.cgi?id=81656 + */ + function keepInlineElementOnDeleteBackspace() { + editor.on('keydown', function(e) { + var isDelete, rng, container, offset, brElm, sibling, collapsed, nonEmptyElements; + + isDelete = e.keyCode == DELETE; + if (!isDefaultPrevented(e) && (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)))) { + // Edge case when deleting

    |x

    + sibling = container.previousSibling; + if (sibling && sibling.nodeName == "IMG") { + return; + } + + 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:

    |

    + 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'); + } + } + }); + } + + /** + * Removes a blockquote when backspace is pressed at the beginning of it. + * + * For example: + *

    |x

    + * + * Becomes: + *

    |x

    + */ + function removeBlockQuoteOnBackSpace() { + // Add block quote deletion handler + editor.on('keydown', function(e) { + var rng, container, offset, root, parent; + + if (isDefaultPrevented(e) || 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 && 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 = dom.createRng(); + rng.setStart(container, 0); + rng.setEnd(container, 0); + selection.setRng(rng); + } + }); + } + + /** + * Sets various Gecko editing options on mouse down and before a execCommand to disable inline table editing that is broken etc. + */ + function setGeckoEditingOptions() { + function setOpts() { + editor._refreshContentEditable(); + + setEditorCommandState("StyleWithCSS", false); + setEditorCommandState("enableInlineTableEditing", false); + + if (!settings.object_resizing) { + setEditorCommandState("enableObjectResizing", false); + } + } + + if (!settings.readonly) { + editor.on('BeforeExecCommand MouseDown', setOpts); + } + } + + /** + * Fixes a gecko link bug, when a link is placed at the end of block elements there is + * no way to move the caret behind the link. This fix adds a bogus br element after the link. + * + * For example this: + *

    x

    + * + * Becomes this: + *

    x

    + */ + function addBrAfterLastLinks() { + function fixLinks() { + 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.on('SetContent ExecCommand', function(e) { + if (e.type == "setcontent" || e.command === 'mceInsertLink') { + fixLinks(); + } + }); + } + + /** + * WebKit will produce DIV elements here and there by default. But since TinyMCE uses paragraphs by + * default we want to change that behavior. + */ + function setDefaultBlockType() { + if (settings.forced_root_block) { + editor.on('init', function() { + setEditorCommandState('DefaultParagraphSeparator', settings.forced_root_block); + }); + } + } + + /** + * Removes ghost selections from images/tables on Gecko. + */ + function removeGhostSelection() { + editor.on('Undo Redo SetContent', function(e) { + if (!e.initial) { + editor.execCommand('mceRepaint'); + } + }); + } + + /** + * Deletes the selected image on IE instead of navigating to previous page. + */ + function deleteControlItemOnBackSpace() { + editor.on('keydown', function(e) { + var rng; + + if (!isDefaultPrevented(e) && e.keyCode == BACKSPACE) { + rng = editor.getDoc().selection.createRange(); + if (rng && rng.item) { + e.preventDefault(); + editor.undoManager.beforeChange(); + dom.remove(rng.item(0)); + editor.undoManager.add(); + } + } + }); + } + + /** + * IE10 doesn't properly render block elements with the right height until you add contents to them. + * This fixes that by adding a padding-right to all empty text block elements. + * See: https://connect.microsoft.com/IE/feedback/details/743881 + */ + function renderEmptyBlocksFix() { + var emptyBlocksCSS; + + // IE10+ + if (getDocumentMode() >= 10) { + emptyBlocksCSS = ''; + each('p div h1 h2 h3 h4 h5 h6'.split(' '), function(name, i) { + emptyBlocksCSS += (i > 0 ? ',' : '') + name + ':empty'; + }); + + editor.contentStyles.push(emptyBlocksCSS + '{padding-right: 1px !important}'); + } + } + + /** + * Old IE versions can't retain contents within noscript elements so this logic will store the contents + * as a attribute and the insert that value as it's raw text when the DOM is serialized. + */ + function keepNoScriptContents() { + if (getDocumentMode() < 9) { + parser.addNodeFilter('noscript', function(nodes) { + var i = nodes.length, node, textNode; + + while (i--) { + node = nodes[i]; + textNode = node.firstChild; + + if (textNode) { + node.attr('data-mce-innertext', textNode.value); + } + } + }); + + serializer.addNodeFilter('noscript', function(nodes) { + var i = nodes.length, node, textNode, value; + + while (i--) { + node = nodes[i]; + textNode = nodes[i].firstChild; + + if (textNode) { + textNode.value = Entities.decode(textNode.value); + } else { + // Old IE can't retain noscript value so an attribute is used to store it + value = node.attributes.map['data-mce-innertext']; + if (value) { + node.attr('data-mce-innertext', null); + textNode = new Node('#text', 3); + textNode.value = value; + textNode.raw = true; + node.append(textNode); + } + } + } + }); + } + } + + /** + * IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode. + */ + function fixCaretSelectionOfDocumentElementOnIe() { + var 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(); + } + } + }); + } + + /** + * Fixes selection issues on Gecko where the caret can be placed between two inline elements like a|b + * this fix will lean the caret right into the closest inline element. + */ + function normalizeSelection() { + // Normalize selection for example a|a becomes a|a except for Ctrl+A since it selects everything + editor.on('keyup focusin', function(e) { + if (e.keyCode != 65 || !VK.metaKeyPressed(e)) { + selection.normalize(); + } + }); + } + + // All browsers + disableBackspaceIntoATable(); + removeBlockQuoteOnBackSpace(); + emptyEditorWhenDeleting(); + normalizeSelection(); + + // WebKit + if (isWebKit) { + keepInlineElementOnDeleteBackspace(); + cleanupStylesWhenDeleting(); + inputMethodFocus(); + selectControlElements(); + setDefaultBlockType(); + + // iOS + if (Env.iOS) { + selectionChangeNodeChanged(); + } else { + selectAll(); + } + } + + // IE + if (isIE) { + removeHrOnBackspace(); + ensureBodyHasRoleApplication(); + addNewLinesBeforeBrInPre(); + removePreSerializedStylesWhenSelectingControls(); + deleteControlItemOnBackSpace(); + renderEmptyBlocksFix(); + keepNoScriptContents(); + fixCaretSelectionOfDocumentElementOnIe(); + } + + // Gecko + if (isGecko) { + removeHrOnBackspace(); + focusBody(); + removeStylesWhenDeletingAccrossBlockElements(); + setGeckoEditingOptions(); + addBrAfterLastLinks(); + removeGhostSelection(); + } + }; +}); + +// Included from: js/tinymce/classes/util/Observable.js + +/** + * Observable.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/util/Observable", [ + "tinymce/util/Tools" +], function(Tools) { + var bindingsName = "__bindings"; + var nativeEvents = Tools.makeMap( + "focusin focusout click dblclick mousedown mouseup mousemove mouseover beforepaste paste cut copy" + + " mouseout mouseenter mouseleave keydown keypress keyup contextmenu dragend dragover draggesture dragdrop drop drag", ' ' + ); + + function returnFalse() { + return false; + } + + function returnTrue() { + return true; + } + + return { + fire: function(name, args, bubble) { + var self = this, handlers, i, l, callback, parent; + + name = name.toLowerCase(); + args = args || {}; + args.type = name; + + // Setup target is there isn't one + if (!args.target) { + args.target = self; + } + + // Add event delegation methods if they are missing + if (!args.preventDefault) { + // Add preventDefault method + args.preventDefault = function() { + args.isDefaultPrevented = returnTrue; + }; + + // Add stopPropagation + args.stopPropagation = function() { + args.isPropagationStopped = returnTrue; + }; + + // Add stopImmediatePropagation + args.stopImmediatePropagation = function() { + args.isImmediatePropagationStopped = returnTrue; + }; + + // Add event delegation states + args.isDefaultPrevented = returnFalse; + args.isPropagationStopped = returnFalse; + args.isImmediatePropagationStopped = returnFalse; + } + + //console.log(name, args); + + if (self[bindingsName]) { + handlers = self[bindingsName][name]; + + if (handlers) { + for (i = 0, l = handlers.length; i < l; i++) { + handlers[i] = callback = handlers[i]; + + // Stop immediate propagation if needed + if (args.isImmediatePropagationStopped()) { + break; + } + + // If callback returns false then prevent default and stop all propagation + if (callback.call(self, args) === false) { + args.preventDefault(); + return args; + } + } + } + } + + // Bubble event up to parents + if (bubble !== false && self.parent) { + parent = self.parent(); + while (parent && !args.isPropagationStopped()) { + parent.fire(name, args, false); + parent = parent.parent(); + } + } + + return args; + }, + + on: function(name, callback) { + var self = this, bindings, handlers, names, i; + + if (callback === false) { + callback = function() { + return false; + }; + } + + if (callback) { + names = name.toLowerCase().split(' '); + i = names.length; + while (i--) { + name = names[i]; + + bindings = self[bindingsName]; + if (!bindings) { + bindings = self[bindingsName] = {}; + } + + handlers = bindings[name]; + if (!handlers) { + handlers = bindings[name] = []; + if (self.bindNative && nativeEvents[name]) { + self.bindNative(name); + } + } + + handlers.push(callback); + } + } + + return self; + }, + + off: function(name, callback) { + var self = this, i, bindings = self[bindingsName], handlers, bindingName, names, hi; + + if (bindings) { + if (name) { + names = name.toLowerCase().split(' '); + i = names.length; + while (i--) { + name = names[i]; + handlers = bindings[name]; + + // Unbind all handlers + if (!name) { + for (bindingName in bindings) { + bindings[name].length = 0; + } + + return self; + } + + if (handlers) { + // Unbind all by name + if (!callback) { + handlers.length = 0; + } else { + // Unbind specific ones + hi = handlers.length; + while (hi--) { + if (handlers[hi] === callback) { + handlers.splice(hi, 1); + } + } + } + + if (!handlers.length && self.unbindNative && nativeEvents[name]) { + self.unbindNative(name); + delete bindings[name]; + } + } + } + } else { + if (self.unbindNative) { + for (name in bindings) { + self.unbindNative(name); + } + } + + self[bindingsName] = []; + } + } + + return self; + } + }; +}); + +// Included from: js/tinymce/classes/Shortcuts.js + +/** + * Shortcuts.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Contains all logic for handling of keyboard shortcuts. + */ +define("tinymce/Shortcuts", [ + "tinymce/util/Tools", + "tinymce/Env" +], function(Tools, Env) { + var each = Tools.each, explode = Tools.explode; + + var keyCodeLookup = { + "f9": 120, + "f10": 121, + "f11": 122 + }; + + return function(editor) { + var self = this, shortcuts = {}; + + editor.on('keyup keypress keydown', function(e) { + if (e.altKey || e.ctrlKey || e.metaKey) { + each(shortcuts, function(shortcut) { + var ctrlState = Env.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 (e.type == "keydown") { + shortcut.func.call(shortcut.scope); + } + + return true; + } + }); + } + }); + + /** + * Adds a keyboard shortcut for some command or function. + * + * @method addShortcut + * @param {String} pattern Shortcut pattern. Like for example: ctrl+alt+o. + * @param {String} desc Text description for the command. + * @param {String/Function} cmdFunc Command name string or function to execute when the key is pressed. + * @param {Object} sc Optional scope to execute the function in. + * @return {Boolean} true/false state if the shortcut was added or not. + */ + self.add = function(pattern, desc, cmdFunc, scope) { + var cmd; + + cmd = cmdFunc; + + if (typeof(cmdFunc) === 'string') { + cmdFunc = function() { + editor.execCommand(cmd, false, null); + }; + } else if (cmdFunc.length) { + cmdFunc = function() { + editor.execCommand(cmd[0], cmd[1], cmd[2]); + }; + } + + each(explode(pattern.toLowerCase()), function(pattern) { + var shortcut = { + func: cmdFunc, + scope: scope || editor, + desc: editor.translate(desc), + alt: false, + ctrl: false, + shift: false + }; + + each(explode(pattern, '+'), function(value) { + switch (value) { + case 'alt': + case 'ctrl': + case 'shift': + shortcut[value] = true; + break; + + default: + shortcut.charCode = value.charCodeAt(0); + shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0); + } + }); + + shortcuts[ + (shortcut.ctrl ? 'ctrl' : '') + ',' + + (shortcut.alt ? 'alt' : '') + ',' + + (shortcut.shift ? 'shift' : '') + ',' + + shortcut.keyCode + ] = shortcut; + }); + + return true; + }; + }; +}); + +// Included from: js/tinymce/classes/Editor.js + +/** + * Editor.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint scripturl:true */ + +/** + * This class contains the core logic for a TinyMCE editor. + * + * @class tinymce.Editor + * @example + * // Add a class to all paragraphs in the editor. + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass'); + * + * // Gets the current editors selection as text + * tinymce.activeEditor.selection.getContent({format: 'text'}); + * + * // Creates a new editor instance + * var ed = new tinymce.Editor('textareaid', { + * some_setting: 1 + * }, tinymce.EditorManager); + * + * // Select each item the user clicks on + * ed.on('click', function(e) { + * ed.selection.select(e.target); + * }); + * + * ed.render(); + */ +define("tinymce/Editor", [ + "tinymce/dom/DOMUtils", + "tinymce/AddOnManager", + "tinymce/html/Node", + "tinymce/dom/Serializer", + "tinymce/html/Serializer", + "tinymce/dom/Selection", + "tinymce/Formatter", + "tinymce/UndoManager", + "tinymce/EnterKey", + "tinymce/ForceBlocks", + "tinymce/EditorCommands", + "tinymce/util/URI", + "tinymce/dom/ScriptLoader", + "tinymce/dom/EventUtils", + "tinymce/WindowManager", + "tinymce/html/Schema", + "tinymce/html/DomParser", + "tinymce/util/Quirks", + "tinymce/Env", + "tinymce/util/Tools", + "tinymce/util/Observable", + "tinymce/Shortcuts" +], function( + DOMUtils, AddOnManager, Node, DomSerializer, Serializer, + Selection, Formatter, UndoManager, EnterKey, ForceBlocks, EditorCommands, + URI, ScriptLoader, EventUtils, WindowManager, + Schema, DomParser, Quirks, Env, Tools, Observable, Shortcuts +) { + // Shorten these names + var DOM = DOMUtils.DOM, ThemeManager = AddOnManager.ThemeManager, PluginManager = AddOnManager.PluginManager; + var extend = Tools.extend, each = Tools.each, explode = Tools.explode; + var inArray = Tools.inArray, trim = Tools.trim, resolve = Tools.resolve; + var Event = EventUtils.Event; + var isGecko = Env.gecko, isIE = Env.ie, isOpera = Env.opera; + + function getEventTarget(editor, eventName) { + // Need to bind mousedown/mouseup etc to document not body in iframe mode + // Since the user might click on the HTML element not the BODY + if (!editor.inline && /^mouse|click|contextmenu/.test(eventName)) { + return editor.getDoc(); + } + + return editor.getBody(); + } + + /** + * Constructs a editor instance by id. + * + * @constructor + * @method Editor + * @param {String} id Unique id for the editor. + * @param {Object} settings Settings for the editor. + * @param {tinymce.EditorManager} editorManager EditorManager instance. + * @author Moxiecode + */ + function Editor(id, settings, editorManager) { + var self = this, documentBaseUrl, baseUri; + + documentBaseUrl = self.documentBaseUrl = editorManager.documentBaseURL; + baseUri = editorManager.baseURI; + + /** + * Name/value collection with editor settings. + * + * @property settings + * @type Object + * @example + * // Get the value of the theme setting + * tinymce.activeEditor.windowManager.alert("You are using the " + tinymce.activeEditor.settings.theme + " theme"); + */ + self.settings = settings = extend({ + id: id, + theme: 'modern', + delta_width: 0, + delta_height: 0, + popup_css: '', + plugins: '', + document_base_url: 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, + doctype: '', + visual: true, + font_size_style_values: 'xx-small,x-small,small,medium,large,x-large,xx-large', + + // See: http://www.w3.org/TR/CSS2/fonts.html#propdef-font-size + font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%', + apply_source_formatting: true, + directionality: 'ltr', + forced_root_block: 'p', + hidden_input: true, + padd_empty_editor: true, + render_ui: true, + indentation: '30px', + 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,option,optgroup,datalist', + 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,option,optgroup,datalist', + validate: true, + entity_encoding: 'named', + url_converter: self.convertURL, + url_converter_scope: self, + ie7_compat: true + }, settings); + + // TODO: Fix this + AddOnManager.settings = settings; + AddOnManager.baseURL = editorManager.baseURL; + + /** + * Editor instance id, normally the same as the div/textarea that was replaced. + * + * @property id + * @type String + */ + self.id = settings.id = id; + + /** + * State to force the editor to return false on a isDirty call. + * + * @property isNotDirty + * @type Boolean + * @example + * function ajaxSave() { + * var ed = tinymce.get('elm1'); + * + * // Save contents using some XHR call + * alert(ed.getContent()); + * + * ed.isNotDirty = 1; // Force not dirty state + * } + */ + self.isNotDirty = false; + + /** + * Name/Value object containting plugin instances. + * + * @property plugins + * @type Object + * @example + * // Execute a method inside a plugin directly + * tinymce.activeEditor.plugins.someplugin.someMethod(); + */ + self.plugins = {}; + + /** + * URI object to document configured for the TinyMCE instance. + * + * @property documentBaseURI + * @type tinymce.util.URI + * @example + * // Get relative URL from the location of document_base_url + * tinymce.activeEditor.documentBaseURI.toRelative('/somedir/somefile.htm'); + * + * // Get absolute URL from the location of document_base_url + * tinymce.activeEditor.documentBaseURI.toAbsolute('somefile.htm'); + */ + self.documentBaseURI = new URI(settings.document_base_url || documentBaseUrl, { + base_uri: baseUri + }); + + /** + * URI object to current document that holds the TinyMCE editor instance. + * + * @property baseURI + * @type tinymce.util.URI + * @example + * // Get relative URL from the location of the API + * tinymce.activeEditor.baseURI.toRelative('/somedir/somefile.htm'); + * + * // Get absolute URL from the location of the API + * tinymce.activeEditor.baseURI.toAbsolute('somefile.htm'); + */ + self.baseURI = baseUri; + + /** + * Array with CSS files to load into the iframe. + * + * @property contentCSS + * @type Array + */ + self.contentCSS = []; + + /** + * Array of CSS styles to add to head of document when the editor loads. + * + * @property contentStyles + * @type Array + */ + self.contentStyles = []; + + // Creates all events like onClick, onSetContent etc see Editor.Events.js for the actual logic + self.shortcuts = new Shortcuts(self); + + // Internal command handler objects + self.execCommands = {}; + self.queryStateCommands = {}; + self.queryValueCommands = {}; + + self.suffix = editorManager.suffix; + self.editorManager = editorManager; + self.inline = settings.inline; + + // Call setup + self.execCallback('setup', self); + } + + Editor.prototype = { + /** + * Renderes the editor/adds it to the page. + * + * @method render + */ + render: function() { + var self = this, settings = self.settings, id = self.id, suffix = self.suffix; + + // Page is not loaded yet, wait for it + if (!Event.domLoaded) { + DOM.bind(window, 'ready', function() { + self.render(); + }); + return; + } + + self.editorManager.settings = settings; + + // Element not found, then skip initialization + if (!self.getElement()) { + return; + } + + // No editable support old iOS versions etc + if (!Env.contentEditable) { + return; + } + + // Hide target element early to prevent content flashing + if (!settings.inline) { + self.orgVisibility = self.getElement().style.visibility; + self.getElement().style.visibility = 'hidden'; + } else { + self.inline = true; + } + + var form = self.getElement().form || DOM.getParent(id, 'form'); + if (form) { + self.formElement = form; + + // Add hidden input for non input elements inside form elements + if (settings.hidden_input && !/TEXTAREA|INPUT/i.test(self.getElement().nodeName)) { + DOM.insertAfter(DOM.create('input', {type: 'hidden', name: id}), id); + } + + // Pass submit/reset from form to editor instance + self.formEventDelegate = function(e) { + self.fire(e.type, e); + }; + + DOM.bind(form, 'submit reset', self.formEventDelegate); + + // Reset contents in editor when the form is reset + self.on('reset', function() { + self.setContent(self.startContent, {format: 'raw'}); + }); + + // Check page uses id="submit" or name="submit" for it's submit button + if (settings.submit_patch && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) { + form._mceOldSubmit = form.submit; + form.submit = function() { + self.editorManager.triggerSave(); + self.isNotDirty = 1; + + return form._mceOldSubmit(form); + }; + } + } + + /** + * Window manager reference, use this to open new windows and dialogs. + * + * @property windowManager + * @type tinymce.WindowManager + * @example + * // Shows an alert message + * tinymce.activeEditor.windowManager.alert('Hello world!'); + * + * // Opens a new dialog with the file.htm file and the size 320x240 + * // It also adds a custom parameter this can be retrieved by using tinyMCEPopup.getWindowArg inside the dialog. + * tinymce.activeEditor.windowManager.open({ + * url: 'file.htm', + * width: 320, + * height: 240 + * }, { + * custom_param: 1 + * }); + */ + self.windowManager = new WindowManager(self); + + if (settings.encoding == 'xml') { + self.on('GetContent', function(e) { + if (e.save) { + e.content = DOM.encode(e.content); + } + }); + } + + if (settings.add_form_submit_trigger) { + self.on('submit', function() { + if (self.initialized) { + self.save(); + self.isNotDirty = 1; + } + }); + } + + if (settings.add_unload_trigger) { + self._beforeUnload = function() { + if (self.initialized && !self.destroyed && !self.isHidden()) { + self.save({format: 'raw', no_events: true}); + } + }; + + self.editorManager.on('BeforeUnload', self._beforeUnload); + } + + // Load scripts + function loadScripts() { + var scriptLoader = ScriptLoader.ScriptLoader; + + if (settings.language) { + scriptLoader.add(self.editorManager.baseURL + '/langs/' + settings.language + '.js'); + } + + if (settings.theme && typeof settings.theme != "function" && + settings.theme.charAt(0) != '-' && !ThemeManager.urls[settings.theme]) { + ThemeManager.load(settings.theme, 'themes/' + settings.theme + '/theme' + suffix + '.js'); + } + + if (Tools.isArray(settings.plugins)) { + settings.plugins = settings.plugins.join(' '); + } + + each(settings.plugins.split(/[ ,]/), function(plugin) { + plugin = trim(plugin); + + if (plugin && !PluginManager.urls[plugin]) { + if (plugin.charAt(0) == '-') { + plugin = plugin.substr(1, plugin.length); + + var dependencies = PluginManager.dependencies(plugin); + + each(dependencies, function(dep) { + var defaultSettings = { + prefix:'plugins/', + resource: dep, + suffix:'/plugin' + suffix + '.js' + }; + + dep = PluginManager.createUrl(defaultSettings, dep); + PluginManager.load(dep.resource, dep); + }); + } else { + PluginManager.load(plugin, { + prefix: 'plugins/', + resource: plugin, + suffix: '/plugin' + suffix + '.js' + }); + } + } + }); + + scriptLoader.loadQueue(function() { + if (!self.removed) { + self.init(); + } + }); + } + + loadScripts(); + }, + + /** + * Initializes the editor this will be called automatically when + * all plugins/themes and language packs are loaded by the rendered method. + * This method will setup the iframe and create the theme and plugin instances. + * + * @method init + */ + init: function() { + var self = this, settings = self.settings, elm = self.getElement(); + var w, h, minHeight, n, o, url, bodyId, bodyClass, re, i, initializedPlugins = []; + + self.editorManager.add(self); + + settings.aria_label = settings.aria_label || DOM.getAttrib(elm, 'aria-label', self.getLang('aria.rich_text_area')); + + /** + * Reference to the theme instance that was used to generate the UI. + * + * @property theme + * @type tinymce.Theme + * @example + * // Executes a method on the theme directly + * tinymce.activeEditor.theme.someMethod(); + */ + if (settings.theme) { + if (typeof settings.theme != "function") { + settings.theme = settings.theme.replace(/-/, ''); + o = ThemeManager.get(settings.theme); + self.theme = new o(self, ThemeManager.urls[settings.theme]); + + if (self.theme.init) { + self.theme.init(self, ThemeManager.urls[settings.theme] || self.documentBaseUrl.replace(/\/$/, '')); + } + } else { + self.theme = settings.theme; + } + } + + function initPlugin(plugin) { + var constr = PluginManager.get(plugin), url, pluginInstance; + + url = PluginManager.urls[plugin] || self.documentBaseUrl.replace(/\/$/, ''); + plugin = trim(plugin); + if (constr && inArray(initializedPlugins, plugin) === -1) { + each(PluginManager.dependencies(plugin), function(dep){ + initPlugin(dep); + }); + + pluginInstance = new constr(self, url); + + self.plugins[plugin] = pluginInstance; + + if (pluginInstance.init) { + pluginInstance.init(self, url); + initializedPlugins.push(plugin); + } + } + } + + // Create all plugins + each(settings.plugins.replace(/\-/g, '').split(/[ ,]/), initPlugin); + + // Enables users to override the control factory + self.fire('BeforeRenderUI'); + + // Measure box + if (settings.render_ui && self.theme) { + self.orgDisplay = elm.style.display; + + if (typeof settings.theme != "function") { + w = settings.width || elm.style.width || elm.offsetWidth; + h = settings.height || elm.style.height || elm.offsetHeight; + minHeight = settings.min_height || 100; + 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), minHeight); + } + + // Render UI + o = self.theme.renderUI({ + targetNode: elm, + width: w, + height: h, + deltaWidth: settings.delta_width, + deltaHeight: settings.delta_height + }); + + // Resize editor + if (!settings.content_editable) { + DOM.setStyles(o.sizeContainer || o.editorContainer, { + wi2dth: w, + // TODO: Fix this + h2eight: h + }); + + h = (o.iframeHeight || h) + (typeof(h) == 'number' ? (o.deltaHeight || 0) : ''); + if (h < minHeight) { + h = minHeight; + } + } + } else { + o = settings.theme(self, elm); + + // Convert element type to id:s + if (o.editorContainer.nodeType) { + o.editorContainer = o.editorContainer.id = o.editorContainer.id || self.id + "_parent"; + } + + // Convert element type to id:s + if (o.iframeContainer.nodeType) { + o.iframeContainer = o.iframeContainer.id = o.iframeContainer.id || self.id + "_iframecontainer"; + } + + // Use specified iframe height or the targets offsetHeight + h = o.iframeHeight || elm.offsetHeight; + } + + self.editorContainer = o.editorContainer; + } + + // Load specified content CSS last + if (settings.content_css) { + each(explode(settings.content_css), function(u) { + self.contentCSS.push(self.documentBaseURI.toAbsolute(u)); + }); + } + + // Load specified content CSS last + if (settings.content_style) { + self.contentStyles.push(settings.content_style); + } + + // Content editable mode ends here + if (settings.content_editable) { + elm = n = o = null; // Fix IE leak + return self.initContentBody(); + } + + // User specified a document.domain value + if (document.domain && location.hostname != document.domain) { + self.editorManager.relaxedDomain = document.domain; + } + + self.iframeHTML = settings.doctype + ''; + + // 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 (settings.document_base_url != self.documentBaseUrl) { + self.iframeHTML += ''; + } + + // IE8 doesn't support carets behind images setting ie7_compat would force IE8+ to run in IE7 compat mode. + if (!Env.caretAfter && settings.ie7_compat) { + self.iframeHTML += ''; + } + + self.iframeHTML += ''; + + // Load the CSS by injecting them into the HTML this will reduce "flicker" + for (i = 0; i < self.contentCSS.length; i++) { + self.iframeHTML += ''; + } + + self.contentCSS = []; + + bodyId = settings.body_id || 'tinymce'; + if (bodyId.indexOf('=') != -1) { + bodyId = self.getParam('body_id', '', 'hash'); + bodyId = bodyId[self.id] || bodyId; + } + + bodyClass = settings.body_class || ''; + if (bodyClass.indexOf('=') != -1) { + bodyClass = self.getParam('body_class', '', 'hash'); + bodyClass = bodyClass[self.id] || ''; + } + + self.iframeHTML += '
    '; + + // Domain relaxing enabled, then set document domain + // TODO: Fix this old stuff + if (self.editorManager.relaxedDomain && (isIE || (isOpera && parseFloat(window.opera.version()) < 11))) { + // We need to write the contents here in IE since multiple writes messes up refresh button and back button + url = 'javascript:(function(){document.open();document.domain="' + document.domain + '";' + + 'var ed = window.parent.tinymce.get("' + self.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: self.id + "_ifr", + src: url || 'javascript:""', // Workaround for HTTPS warning in IE6/7 + frameBorder: '0', + allowTransparency: "true", + title: self.editorManager.translate( + "Rich Text Area. Press ALT-F9 for menu. " + + "Press ALT-F10 for toolbar. Press ALT-0 for help" + ), + style: { + width: '100%', + height: h, + display: 'block' // Important for Gecko to render the iframe correctly + } + }); + + self.contentAreaContainer = o.iframeContainer; + + if (o.editorContainer) { + DOM.get(o.editorContainer).style.display = self.orgDisplay; + } + + DOM.get(self.id).style.display = 'none'; + DOM.setAttrib(self.id, 'aria-hidden', true); + + if (!self.editorManager.relaxedDomain || !url) { + self.initContentBody(); + } + + elm = n = o = null; // Cleanup + }, + + /** + * This method get called by the init method ones the iframe is loaded. + * It will fill the iframe with contents, setups DOM and selection objects for the iframe. + * + * @method initContentBody + * @private + */ + initContentBody: function() { + var self = this, settings = self.settings, targetElm = DOM.get(self.id), doc = self.getDoc(), body, contentCssText; + + // Restore visibility on target element + self.getElement().style.visibility = self.orgVisibility; + + // Setup iframe body + if ((!isIE || !self.editorManager.relaxedDomain) && !settings.content_editable) { + doc.open(); + doc.write(self.iframeHTML); + doc.close(); + + if (self.editorManager.relaxedDomain) { + doc.domain = self.editorManager.relaxedDomain; + } + } + + if (settings.content_editable) { + DOM.addClass(targetElm, 'mce-content-body'); + targetElm.tabIndex = -1; + 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; + + // TODO: Fix this + settings.root_name = targetElm.nodeName.toLowerCase(); + } + + // 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; + + /** + * Schema instance, enables you to validate elements and it's children. + * + * @property schema + * @type tinymce.html.Schema + */ + self.schema = new Schema(settings); + + /** + * DOM instance for the editor. + * + * @property dom + * @type tinymce.dom.DOMUtils + * @example + * // Adds a class to all paragraphs within the editor + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass'); + */ + self.dom = new 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, + onSetAttrib: function(e) { + self.fire('SetAttrib', e); + } + }); + + /** + * HTML parser will be used when contents is inserted into the editor. + * + * @property parser + * @type tinymce.html.DomParser + */ + self.parser = new 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) { + 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) { + 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) { + var i = nodes.length, node, nonEmptyElements = self.schema.getNonEmptyElements(); + + while (i--) { + node = nodes[i]; + + if (node.isEmpty(nonEmptyElements)) { + node.empty().append(new Node('br', 1)).shortEnded = true; + } + } + }); + + /** + * DOM serializer for the editor. Will be used when contents is extracted from the editor. + * + * @property serializer + * @type tinymce.dom.Serializer + * @example + * // Serializes the first paragraph in the editor into a string + * tinymce.activeEditor.serializer.serialize(tinymce.activeEditor.dom.select('p')[0]); + */ + self.serializer = new DomSerializer(settings, self); + + /** + * Selection instance for the editor. + * + * @property selection + * @type tinymce.dom.Selection + * @example + * // Sets some contents to the current selection in the editor + * tinymce.activeEditor.selection.setContent('Some contents'); + * + * // Gets the current selection + * alert(tinymce.activeEditor.selection.getContent()); + * + * // Selects the first paragraph found + * tinymce.activeEditor.selection.select(tinymce.activeEditor.dom.select('p')[0]); + */ + self.selection = new Selection(self.dom, self.getWin(), self.serializer, self); + + /** + * Formatter instance. + * + * @property formatter + * @type tinymce.Formatter + */ + self.formatter = new Formatter(self); + + /** + * Undo manager instance, responsible for handling undo levels. + * + * @property undoManager + * @type tinymce.UndoManager + * @example + * // Undoes the last modification to the editor + * tinymce.activeEditor.undoManager.undo(); + */ + self.undoManager = new UndoManager(self); + + self.forceBlocks = new ForceBlocks(self); + self.enterKey = new EnterKey(self); + self.editorCommands = new EditorCommands(self); + + self.fire('PreInit'); + + if (!settings.browser_spellcheck && !settings.gecko_spellcheck) { + doc.body.spellcheck = false; + } + + self.fire('PostRender'); + + self.quirks = Quirks(self); + + if (settings.directionality) { + body.dir = settings.directionality; + } + + if (settings.nowrap) { + body.style.whiteSpace = "nowrap"; + } + + if (settings.protect) { + self.on('BeforeSetContent', function(e) { + each(settings.protect, function(pattern) { + e.content = e.content.replace(pattern, function(str) { + return ''; + }); + }); + }); + } + + self.on('SetContent', function() { + self.addVisual(self.getBody()); + }); + + // Remove empty contents + if (settings.padd_empty_editor) { + self.on('PostProcess', function(e) { + e.content = e.content.replace(/^(]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
    [\r\n]*)$/, ''); + }); + } + + self.load({initial: true, format: 'html'}); + self.startContent = self.getContent({format: 'raw'}); + + /** + * Is set to true after the editor instance has been initialized + * + * @property initialized + * @type Boolean + * @example + * function isEditorInitialized(editor) { + * return editor && editor.initialized; + * } + */ + self.initialized = true; + + each(self._pendingNativeEvents, function(name) { + self.dom.bind(getEventTarget(self, name), name, function(e) { + self.fire(e.type, e); + }); + }); + + self.fire('init'); + self.focus(true); + self.nodeChanged({initial: true}); + self.execCallback('init_instance_callback', self); + + // Add editor specific CSS styles + if (self.contentStyles.length > 0) { + contentCssText = ''; + + each(self.contentStyles, function(style) { + contentCssText += style + "\r\n"; + }); + + self.dom.addStyle(contentCssText); + } + + // 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 = self.editorManager.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; + }, + + /** + * Focuses/activates the editor. This will set this editor as the activeEditor in the tinymce collection + * it will also place DOM focus inside the editor. + * + * @method focus + * @param {Boolean} skip_focus Skip DOM focus. Just set is as the active editor. + */ + focus: function(skip_focus) { + var oed, self = this, selection = self.selection, contentEditable = self.settings.content_editable, rng; + var controlElm, doc = self.getDoc(), body; + + if (!skip_focus) { + if ((rng = selection.lastRng)) { + selection.lastRng = null; + selection.setRng(rng); + self.nodeChanged(); + } + + // Get selected control element + rng = selection.getRng(); + if (rng.item) { + controlElm = rng.item(0); + } + + self._refreshContentEditable(); + + // Focus the window iframe + if (!contentEditable) { + self.getWin().focus(); + } + + // Focus the body as well since it's contentEditable + if (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) { + rng = doc.body.createControlRange(); + rng.addElement(controlElm); + rng.select(); + } + } + + if (self.editorManager.activeEditor != self) { + if ((oed = self.editorManager.activeEditor)) { + oed.fire('deactivate', {relatedTarget: self}); + } + + self.fire('activate', {relatedTarget: oed}); + } + + self.editorManager.activeEditor = self; + }, + + /** + * Executes a legacy callback. This method is useful to call old 2.x option callbacks. + * There new event model is a better way to add callback so this method might be removed in the future. + * + * @method execCallback + * @param {String} name Name of the callback to execute. + * @return {Object} Return value passed from callback function. + */ + execCallback: function(name) { + var self = this, callback = self.settings[name], scope; + + if (!callback) { + return; + } + + // Look through lookup + if (self.callbackLookup && (scope = self.callbackLookup[name])) { + callback = scope.func; + scope = scope.scope; + } + + if (typeof(callback) === 'string') { + scope = callback.replace(/\.\w+$/, ''); + scope = scope ? resolve(scope) : 0; + callback = resolve(callback); + self.callbackLookup = self.callbackLookup || {}; + self.callbackLookup[name] = {func: callback, scope: scope}; + } + + return callback.apply(scope || self, Array.prototype.slice.call(arguments, 1)); + }, + + /** + * Translates the specified string by replacing variables with language pack items it will also check if there is + * a key mathcin the input. + * + * @method translate + * @param {String} text String to translate by the language pack data. + * @return {String} Translated string. + */ + translate: function(text) { + var lang = this.settings.language || 'en', i18n = this.editorManager.i18n; + + if (!text) { + return ''; + } + + return i18n[lang + '.' + text] || text.replace(/\{\#([^\}]+)\}/g, function(a, b) { + return i18n[lang + '.' + b] || '{#' + b + '}'; + }); + }, + + /** + * Returns a language pack item by name/key. + * + * @method getLang + * @param {String} name Name/key to get from the language pack. + * @param {String} defaultVal Optional default value to retrive. + */ + getLang: function(name, defaultVal) { + return ( + this.editorManager.i18n[(this.settings.language || 'en') + '.' + name] || + (defaultVal !== undefined ? defaultVal : '{#' + name + '}') + ); + }, + + /** + * Returns a configuration parameter by name. + * + * @method getParam + * @param {String} name Configruation parameter to retrive. + * @param {String} defaultVal Optional default value to return. + * @param {String} type Optional type parameter. + * @return {String} Configuration parameter value or default value. + * @example + * // Returns a specific config value from the currently active editor + * var someval = tinymce.activeEditor.getParam('myvalue'); + * + * // Returns a specific config value from a specific editor instance by id + * var someval2 = tinymce.get('my_editor').getParam('myvalue'); + */ + getParam: function(name, defaultVal, type) { + var value = name in this.settings ? this.settings[name] : defaultVal, output; + + if (type === 'hash') { + output = {}; + + if (typeof(value) === 'string') { + each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function(value) { + value = value.split('='); + + if (value.length > 1) { + output[trim(value[0])] = trim(value[1]); + } else { + output[trim(value[0])] = trim(value); + } + }); + } else { + output = value; + } + + return output; + } + + return value; + }, + + /** + * Distpaches out a onNodeChange event to all observers. This method should be called when you + * need to update the UI states or element path etc. + * + * @method nodeChanged + */ + nodeChanged: function() { + var self = this, selection = self.selection, node, parents, root; + + // Fix for bug #1896577 it seems that this can not be fired while the editor is loading + if (self.initialized && !self.settings.disable_nodechange) { + // Get start node + root = self.getBody(); + node = selection.getStart() || root; + node = isIE && node.ownerDocument != self.getDoc() ? self.getBody() : node; // Fix for IE initial state + + // Edge case for

    |

    + if (node.nodeName == 'IMG' && selection.isCollapsed()) { + node = node.parentNode; + } + + // Get parents and add them to object + parents = []; + self.dom.getParent(node, function(node) { + if (node === root) { + return true; + } + + parents.push(node); + }); + + self.fire('NodeChange', {element: node, parents: parents}); + } + }, + + /** + * Adds a button that later gets created by the ControlManager. This is a shorter and easier method + * of adding buttons without the need to deal with the ControlManager directly. But it's also less + * powerfull if you need more control use the ControlManagers factory methods instead. + * + * @method addButton + * @param {String} name Button name to add. + * @param {Object} settings Settings object with title, cmd etc. + * @example + * // Adds a custom button to the editor and when a user clicks the button it will open + * // an alert box with the selected contents as plain text. + * tinymce.init({ + * ... + * + * theme_advanced_buttons1: 'example,..' + * + * setup: function(ed) { + * // Register example button + * ed.addButton('example', { + * title: 'example.desc', + * image: '../js/tinymce/plugins/example/img/example.gif', + * onclick: function() { + * ed.windowManager.alert('Hello world!! Selection: ' + ed.selection.getContent({format: 'text'})); + * } + * }); + * } + * }); + */ + addButton: function(name, settings) { + var self = this; + + if (settings.cmd) { + settings.onclick = function() { + self.execCommand(settings.cmd); + }; + } + + self.buttons = self.buttons || {}; + settings.tooltip = settings.tooltip || settings.title; + settings.icon = settings.icon || (settings.icon !== false ? name : false); + self.buttons[name] = settings; + }, + + addMenuItem: function(name, settings) { + var self = this; + + if (settings.cmd) { + settings.onclick = function() { + self.execCommand(settings.cmd); + }; + } + + self.menuItems = self.menuItems || {}; + self.menuItems[name] = settings; + }, + + /** + * Adds a custom command to the editor, you can also override existing commands with this method. + * The command that you add can be executed with execCommand. + * + * @method addCommand + * @param {String} name Command name to add/override. + * @param {addCommandCallback} callback Function to execute when the command occurs. + * @param {Object} scope Optional scope to execute the function in. + * @example + * // Adds a custom command that later can be executed using execCommand + * tinymce.init({ + * ... + * + * setup: function(ed) { + * // Register example command + * ed.addCommand('mycommand', function(ui, v) { + * ed.windowManager.alert('Hello world!! Selection: ' + ed.selection.getContent({format: 'text'})); + * }); + * } + * }); + */ + addCommand: function(name, callback, scope) { + /** + * Callback function that gets called when a command is executed. + * + * @callback addCommandCallback + * @param {Boolean} ui Display UI state true/false. + * @param {Object} value Optional value for command. + * @return {Boolean} True/false state if the command was handled or not. + */ + this.execCommands[name] = {func: callback, scope: scope || this}; + }, + + /** + * Adds a custom query state command to the editor, you can also override existing commands with this method. + * The command that you add can be executed with queryCommandState function. + * + * @method addQueryStateHandler + * @param {String} name Command name to add/override. + * @param {addQueryStateHandlerCallback} callback Function to execute when the command state retrival occurs. + * @param {Object} scope Optional scope to execute the function in. + */ + addQueryStateHandler: function(name, callback, scope) { + /** + * Callback function that gets called when a queryCommandState is executed. + * + * @callback addQueryStateHandlerCallback + * @return {Boolean} True/false state if the command is enabled or not like is it bold. + */ + this.queryStateCommands[name] = {func: callback, scope: scope || this}; + }, + + /** + * Adds a custom query value command to the editor, you can also override existing commands with this method. + * The command that you add can be executed with queryCommandValue function. + * + * @method addQueryValueHandler + * @param {String} name Command name to add/override. + * @param {addQueryValueHandlerCallback} callback Function to execute when the command value retrival occurs. + * @param {Object} scope Optional scope to execute the function in. + */ + addQueryValueHandler: function(name, callback, scope) { + /** + * Callback function that gets called when a queryCommandValue is executed. + * + * @callback addQueryValueHandlerCallback + * @return {Object} Value of the command or undefined. + */ + this.queryValueCommands[name] = {func: callback, scope: scope || this}; + }, + + /** + * Adds a keyboard shortcut for some command or function. + * + * @method addShortcut + * @param {String} pattern Shortcut pattern. Like for example: ctrl+alt+o. + * @param {String} desc Text description for the command. + * @param {String/Function} cmdFunc Command name string or function to execute when the key is pressed. + * @param {Object} sc Optional scope to execute the function in. + * @return {Boolean} true/false state if the shortcut was added or not. + */ + addShortcut: function(pattern, desc, cmdFunc, scope) { + this.shortcuts.add(pattern, desc, cmdFunc, scope); + }, + + /** + * Executes a command on the current instance. These commands can be TinyMCE internal commands prefixed with "mce" or + * they can be build in browser commands such as "Bold". A compleate list of browser commands is available on MSDN or Mozilla.org. + * This function will dispatch the execCommand function on each plugin, theme or the execcommand_callback option if none of these + * return true it will handle the command as a internal browser command. + * + * @method execCommand + * @param {String} cmd Command name to execute, for example mceLink or Bold. + * @param {Boolean} ui True/false state if a UI (dialog) should be presented or not. + * @param {mixed} value Optional command value, this can be anything. + * @param {Object} a Optional arguments object. + */ + execCommand: function(cmd, ui, value, args) { + var self = this, state = 0, cmdItem; + + if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(cmd) && (!args || !args.skip_focus)) { + self.focus(); + } + + args = extend({}, args); + self.fire('BeforeExecCommand', {command: cmd, ui: ui, value: value}); + if (args.terminate) { + return false; + } + + // Registred commands + if ((cmdItem = self.execCommands[cmd])) { + // Fall through on true + if (cmdItem.func.call(cmdItem.scope, ui, value) !== true) { + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + return true; + } + } + + // Plugin commands + each(self.plugins, function(p) { + if (p.execCommand && p.execCommand(cmd, ui, value)) { + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + state = true; + return false; + } + }); + + if (state) { + return state; + } + + // Theme commands + if (self.theme && self.theme.execCommand && self.theme.execCommand(cmd, ui, value)) { + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + return true; + } + + // Editor commands + if (self.editorCommands.execCommand(cmd, ui, value)) { + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + return true; + } + + // Browser commands + self.getDoc().execCommand(cmd, ui, value); + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + }, + + /** + * Returns a command specific state, for example if bold is enabled or not. + * + * @method queryCommandState + * @param {string} cmd Command to query state from. + * @return {Boolean} Command specific state, for example if bold is enabled or not. + */ + queryCommandState: function(cmd) { + var self = this, queryItem, returnVal; + + // Is hidden then return undefined + if (self._isHidden()) { + return; + } + + // Registred commands + if ((queryItem = self.queryStateCommands[cmd])) { + returnVal = queryItem.func.call(queryItem.scope); + + // Fall though on true + if (returnVal !== true) { + return returnVal; + } + } + + // Editor commands + returnVal = self.editorCommands.queryCommandState(cmd); + if (returnVal !== -1) { + return returnVal; + } + + // Browser commands + try { + return self.getDoc().queryCommandState(cmd); + } catch (ex) { + // Fails sometimes see bug: 1896577 + } + }, + + /** + * Returns a command specific value, for example the current font size. + * + * @method queryCommandValue + * @param {string} cmd Command to query value from. + * @return {Object} Command specific value, for example the current font size. + */ + queryCommandValue: function(cmd) { + var self = this, queryItem, returnVal; + + // Is hidden then return undefined + if (self._isHidden()) { + return; + } + + // Registred commands + if ((queryItem = self.queryValueCommands[cmd])) { + returnVal = queryItem.func.call(queryItem.scope); + + // Fall though on true + if (returnVal !== true) { + return returnVal; + } + } + + // Editor commands + returnVal = self.editorCommands.queryCommandValue(cmd); + if (returnVal !== undefined) { + return returnVal; + } + + // Browser commands + try { + return self.getDoc().queryCommandValue(cmd); + } catch (ex) { + // Fails sometimes see bug: 1896577 + } + }, + + /** + * Shows the editor and hides any textarea/div that the editor is supposed to replace. + * + * @method show + */ + show: function() { + var self = this; + + DOM.show(self.getContainer()); + DOM.hide(self.id); + self.load(); + self.fire('show'); + }, + + /** + * Hides the editor and shows any textarea/div that the editor is supposed to replace. + * + * @method hide + */ + hide: function() { + var self = this, doc = self.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(); + + // defer the call to hide to prevent an IE9 crash #4921 + DOM.hide(self.getContainer()); + DOM.setStyle(self.id, 'display', self.orgDisplay); + self.fire('hide'); + }, + + /** + * Returns true/false if the editor is hidden or not. + * + * @method isHidden + * @return {Boolean} True/false if the editor is hidden or not. + */ + isHidden: function() { + return !DOM.isHidden(this.id); + }, + + /** + * Sets the progress state, this will display a throbber/progess for the editor. + * This is ideal for asycronous operations like an AJAX save call. + * + * @method setProgressState + * @param {Boolean} state Boolean state if the progress should be shown or hidden. + * @param {Number} time Optional time to wait before the progress gets shown. + * @return {Boolean} Same as the input state. + * @example + * // Show progress for the active editor + * tinymce.activeEditor.setProgressState(true); + * + * // Hide progress for the active editor + * tinymce.activeEditor.setProgressState(false); + * + * // Show progress after 3 seconds + * tinymce.activeEditor.setProgressState(true, 3000); + */ + setProgressState: function(state, time) { + this.fire('ProgressState', {state: state, time: time}); + }, + + /** + * Loads contents from the textarea or div element that got converted into an editor instance. + * This method will move the contents from that textarea or div into the editor by using setContent + * so all events etc that method has will get dispatched as well. + * + * @method load + * @param {Object} args Optional content object, this gets passed around through the whole load process. + * @return {String} HTML string that got set into the editor. + */ + load: function(args) { + var self = this, elm = self.getElement(), html; + + if (elm) { + args = args || {}; + args.load = true; + + html = self.setContent(elm.value !== undefined ? elm.value : elm.innerHTML, args); + args.element = elm; + + if (!args.no_events) { + self.fire('LoadContent', args); + } + + args.element = elm = null; + + return html; + } + }, + + /** + * Saves the contents from a editor out to the textarea or div element that got converted into an editor instance. + * This method will move the HTML contents from the editor into that textarea or div by getContent + * so all events etc that method has will get dispatched as well. + * + * @method save + * @param {Object} args Optional content object, this gets passed around through the whole save process. + * @return {String} HTML string that got set into the textarea/div. + */ + save: function(args) { + var self = this, elm = self.getElement(), html, form; + + if (!elm || !self.initialized) { + return; + } + + args = args || {}; + args.save = true; + + args.element = elm; + html = args.content = self.getContent(args); + + if (!args.no_events) { + self.fire('SaveContent', args); + } + + html = args.content; + + if (!/TEXTAREA|INPUT/i.test(elm.nodeName)) { + elm.innerHTML = html; + + // Update hidden form element + if ((form = DOM.getParent(self.id, 'form'))) { + each(form.elements, function(elm) { + if (elm.name == self.id) { + elm.value = html; + return false; + } + }); + } + } else { + elm.value = html; + } + + args.element = elm = null; + + return html; + }, + + /** + * Sets the specified content to the editor instance, this will cleanup the content before it gets set using + * the different cleanup rules options. + * + * @method setContent + * @param {String} content Content to set to editor, normally HTML contents but can be other formats as well. + * @param {Object} args Optional content object, this gets passed around through the whole set process. + * @return {String} HTML string that got set into the editor. + * @example + * // Sets the HTML contents of the activeEditor editor + * tinymce.activeEditor.setContent('some html'); + * + * // Sets the raw contents of the activeEditor editor + * tinymce.activeEditor.setContent('some html', {format: 'raw'}); + * + * // Sets the content of a specific editor (my_editor in this example) + * tinymce.get('my_editor').setContent(data); + * + * // Sets the bbcode contents of the activeEditor editor if the bbcode plugin was added + * tinymce.activeEditor.setContent('[b]some[/b] html', {format: 'bbcode'}); + */ + setContent: function(content, args) { + var self = this, 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.fire('BeforeSetContent', 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 (!isIE && (content.length === 0 || /^\s+$/.test(content))) { + forcedRootBlockName = self.settings.forced_root_block; + + // Check if forcedRootBlock is configured and that the block is a valid child of the body + if (forcedRootBlockName && self.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) { + content = '<' + forcedRootBlockName + '>
    '; + } else { + content = '
    '; + } + + body.innerHTML = content; + self.selection.select(body, true); + self.selection.collapse(true); + return; + } + + // Parse and serialize the html + if (args.format !== 'raw') { + content = new Serializer({}, self.schema).serialize( + self.parser.parse(content, {isRootContent: true}) + ); + } + + // Set the new cleaned contents to the editor + args.content = trim(content); + self.dom.setHTML(body, args.content); + + // Do post processing + if (!args.no_events) { + self.fire('SetContent', args); + } + + // Don't normalize selection if the focused element isn't the body in content editable mode since it will steal focus otherwise + if (!self.settings.content_editable || document.activeElement === self.getBody()) { + self.selection.normalize(); + } + + return args.content; + }, + + /** + * Gets the content from the editor instance, this will cleanup the content before it gets returned using + * the different cleanup rules options. + * + * @method getContent + * @param {Object} args Optional content object, this gets passed around through the whole get process. + * @return {String} Cleaned content string, normally HTML contents. + * @example + * // Get the HTML contents of the currently active editor + * console.debug(tinymce.activeEditor.getContent()); + * + * // Get the raw contents of the currently active editor + * tinymce.activeEditor.getContent({format: 'raw'}); + * + * // Get content of a specific editor: + * tinymce.get('content id').getContent() + */ + getContent: function(args) { + var self = this, content, body = self.getBody(); + + // Setup args object + args = args || {}; + args.format = args.format || 'html'; + args.get = true; + args.getInner = true; + + // Do preprocessing + if (!args.no_events) { + self.fire('BeforeGetContent', args); + } + + // Get raw contents or by default the cleaned contents + if (args.format == 'raw') { + content = body.innerHTML; + } else if (args.format == 'text') { + content = body.innerText || body.textContent; + } else { + content = self.serializer.serialize(body, args); + } + + // Trim whitespace in beginning/end of HTML + if (args.format != 'text') { + args.content = trim(content); + } else { + args.content = content; + } + + // Do post processing + if (!args.no_events) { + self.fire('GetContent', args); + } + + return args.content; + }, + + /** + * Inserts content at caret position. + * + * @method insertContent + * @params {String} content Content to insert. + */ + insertContent: function(content) { + this.execCommand('mceInsertContent', false, content); + }, + + /** + * Returns true/false if the editor is dirty or not. It will get dirty if the user has made modifications to the contents. + * + * @method isDirty + * @return {Boolean} True/false if the editor is dirty or not. It will get dirty if the user has made modifications to the contents. + * @example + * if (tinymce.activeEditor.isDirty()) + * alert("You must save your contents."); + */ + isDirty: function() { + return !this.isNotDirty && this.undoManager.hasUndo(); + }, + + /** + * Returns the editors container element. The container element wrappes in + * all the elements added to the page for the editor. Such as UI, iframe etc. + * + * @method getContainer + * @return {Element} HTML DOM element for the editor container. + */ + getContainer: function() { + var self = this; + + if (!self.container) { + self.container = DOM.get(self.editorContainer || self.id + '_parent'); + } + + return self.container; + }, + + /** + * Returns the editors content area container element. The this element is the one who + * holds the iframe or the editable element. + * + * @method getContentAreaContainer + * @return {Element} HTML DOM element for the editor area container. + */ + getContentAreaContainer: function() { + return this.contentAreaContainer; + }, + + /** + * Returns the target element/textarea that got replaced with a TinyMCE editor instance. + * + * @method getElement + * @return {Element} HTML DOM element for the replaced element. + */ + getElement: function() { + return DOM.get(this.settings.content_element || this.id); + }, + + /** + * Returns the iframes window object. + * + * @method getWin + * @return {Window} Iframe DOM window object. + */ + getWin: function() { + var self = this, elm; + + if (!self.contentWindow) { + elm = DOM.get(self.id + "_ifr"); + + if (elm) { + self.contentWindow = elm.contentWindow; + } + } + + return self.contentWindow; + }, + + /** + * Returns the iframes document object. + * + * @method getDoc + * @return {Document} Iframe DOM document object. + */ + getDoc: function() { + var self = this, win; + + if (!self.contentDocument) { + win = self.getWin(); + + if (win) { + self.contentDocument = win.document; + } + } + + return self.contentDocument; + }, + + /** + * Returns the iframes body element. + * + * @method getBody + * @return {Element} Iframe body element. + */ + getBody: function() { + return this.bodyElement || this.getDoc().body; + }, + + /** + * URL converter function this gets executed each time a user adds an img, a or + * any other element that has a URL in it. This will be called both by the DOM and HTML + * manipulation functions. + * + * @method convertURL + * @param {string} url URL to convert. + * @param {string} name Attribute name src, href etc. + * @param {string/HTMLElement} elm Tag name or HTML DOM element depending on HTML or DOM insert. + * @return {string} Converted URL string. + */ + 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 || url.length === 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; + }, + + /** + * Adds visual aid for tables, anchors etc so they can be more easily edited inside the editor. + * + * @method addVisual + * @param {Element} elm Optional root element to loop though to find tables etc that needs the visual aid. + */ + addVisual: function(elm) { + var self = this, settings = self.settings, dom = self.dom, cls; + + elm = elm || self.getBody(); + + if (self.hasVisual === undefined) { + self.hasVisual = settings.visual; + } + + each(dom.select('table,a', elm), function(elm) { + var value; + + switch (elm.nodeName) { + case 'TABLE': + cls = settings.visual_table_class || 'mce-item-table'; + value = dom.getAttrib(elm, 'border'); + + if (!value || value == '0') { + if (self.hasVisual) { + dom.addClass(elm, cls); + } else { + dom.removeClass(elm, cls); + } + } + + return; + + case 'A': + if (!dom.getAttrib(elm, 'href', false)) { + value = dom.getAttrib(elm, 'name') || elm.id; + cls = 'mce-item-anchor'; + + if (value) { + if (self.hasVisual) { + dom.addClass(elm, cls); + } else { + dom.removeClass(elm, cls); + } + } + } + + return; + } + }); + + self.fire('VisualAid', {element: elm, hasVisual: self.hasVisual}); + }, + + /** + * Removes the editor from the dom and tinymce collection. + * + * @method remove + */ + remove: function() { + var self = this, elm = self.getContainer(), doc = self.getDoc(); + + if (!self.removed) { + self.removed = 1; // Cancels post remove event execution + + // 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.setStyle(self.id, 'display', self.orgDisplay); + + // 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.unbind(self.getWin()); + Event.unbind(self.getDoc()); + } + + Event.unbind(self.getBody()); + Event.unbind(elm); + + self.fire('remove'); + + self.editorManager.remove(self); + DOM.remove(elm); + } + }, + + bindNative: function(name) { + var self = this; + + if (self.initialized) { + self.dom.bind(getEventTarget(self, name), name, function(e) { + self.fire(name, e); + }); + } else { + if (!self._pendingNativeEvents) { + self._pendingNativeEvents = [name]; + } else { + self._pendingNativeEvents.push(name); + } + } + }, + + unbindNative: function(name) { + var self = this; + + if (self.initialized) { + self.dom.unbind(name); + } + }, + + /** + * Destroys the editor instance by removing all events, element references or other resources + * that could leak memory. This method will be called automatically when the page is unloaded + * but you can also call it directly if you know what you are doing. + * + * @method destroy + * @param {Boolean} automatic Optional state if the destroy is an automatic destroy or user called one. + */ + destroy: function(automatic) { + var self = this, form; + + // One time is enough + if (self.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(self.getDoc()); + Event.unbind(self.getWin()); + Event.unbind(self.getBody()); + } + + if (!automatic) { + self.editorManager.off(self._beforeUnload); + + // Manual destroy + if (self.theme && self.theme.destroy) { + self.theme.destroy(); + } + + // Destroy controls, selection and dom + self.selection.destroy(); + self.dom.destroy(); + } + + form = self.formElement; + if (form) { + form.submit = form._mceOldSubmit; + form._mceOldSubmit = null; + DOM.unbind(form, 'submit reset', self.formEventDelegate); + } + + self.contentAreaContainer = self.formElement = self.container = null; + self.settings.content_element = self.bodyElement = self.contentDocument = self.contentWindow = null; + + if (self.selection) { + self.selection = self.selection.win = self.selection.dom = self.selection.dom.doc = null; + } + + self.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 sel; + + if (!isGecko) { + return 0; + } + + // Weird, wheres that cursor selection? + sel = this.selection.getSel(); + return (!sel || !sel.rangeCount || sel.rangeCount === 0); + } + }; + + extend(Editor.prototype, Observable); + + return Editor; +}); + +// Included from: js/tinymce/classes/EditorManager.js + +/** + * EditorManager.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class used as a factory for manager for tinymce.Editor instaces. + * + * @class tinymce.EditorManager + */ +define("tinymce/EditorManager", [ + "tinymce/Editor", + "tinymce/dom/DOMUtils", + "tinymce/util/URI", + "tinymce/Env", + "tinymce/util/Tools", + "tinymce/util/Observable" +], function(Editor, DOMUtils, URI, Env, Tools, Observable) { + var DOM = DOMUtils.DOM; + var explode = Tools.explode, each = Tools.each, extend = Tools.extend; + var instanceCounter = 0, beforeUnloadDelegate; + + var EditorManager = { + /** + * Major version of TinyMCE build. + * + * @property majorVersion + * @type String + */ + majorVersion : '4', + + /** + * Minor version of TinyMCE build. + * + * @property minorVersion + * @type String + */ + minorVersion : '0b1', + + /** + * Release date of TinyMCE build. + * + * @property releaseDate + * @type String + */ + releaseDate: '2013-04-11', + + /** + * Collection of editor instances. + * + * @property editors + * @type Object + * @example + * for (edId in tinymce.editors) + * tinymce.editors[edId].save(); + */ + editors: [], + + /** + * Collection of language pack data. + * + * @property i18n + * @type Object + */ + i18n: {}, + + /** + * Currently active editor instance. + * + * @property activeEditor + * @type tinymce.Editor + * @example + * tinyMCE.activeEditor.selection.getContent(); + * tinymce.EditorManager.activeEditor.selection.getContent(); + */ + activeEditor: null, + + setup: function() { + var self = this, baseURL, documentBaseURL, suffix = "", preInit; + + // Get base URL for the current document + documentBaseURL = document.location.href.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, ''); + if (!/[\/\\]$/.test(documentBaseURL)) { + documentBaseURL += '/'; + } + + // If tinymce is defined and has a base use that or use the old tinyMCEPreInit + preInit = window.tinymce || window.tinyMCEPreInit; + if (preInit) { + baseURL = preInit.base || preInit.baseURL; + suffix = preInit.suffix; + } else { + // Get base where the tinymce script is located + var scripts = document.getElementsByTagName('script'); + for (var i = 0; i < scripts.length; i++) { + var src = scripts[i].src; + + if (/tinymce(\.jquery|)(\.min|\.dev|).js/.test(src)) { + if (src.indexOf('.min') != -1) { + suffix = '.min'; + } + + baseURL = src.substring(0, src.lastIndexOf('/')); + break; + } + } + } + + /** + * Base URL where the root directory if TinyMCE is located. + * + * @property baseURL + * @type {String} + */ + self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL); + + /** + * Document base URL where the current document is located. + * + * @property documentBaseURL + * @type {String} + */ + self.documentBaseURL = documentBaseURL; + + /** + * Absolute baseURI for the installation path of TinyMCE. + * + * @property baseURI + * @type tinymce.util.URI + */ + self.baseURI = new URI(self.baseURL); + + /** + * Current suffix to add to each plugin/theme that gets loaded for example ".min". + * + * @property suffix + * @type {String} + */ + self.suffix = suffix; + }, + + /** + * Initializes a set of editors. This method will create editors based on various settings. + * + * @method init + * @param {Object} settings Settings object to be passed to each editor instance. + * @example + * // Initializes a editor using the longer method + * tinymce.EditorManager.init({ + * some_settings : 'some value' + * }); + * + * // Initializes a editor instance using the shorter version + * tinyMCE.init({ + * some_settings : 'some value' + * }); + */ + init: function(settings) { + var self = this, editors = [], editor; + + 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; + } + + 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); + } + + self.settings = settings; + + DOM.bind(window, 'ready', function() { + var l, co; + + execCallback(settings, 'onpageload'); + + switch (settings.mode) { + case "exact": + l = settings.elements || ''; + + if(l.length > 0) { + each(explode(l), function(v) { + if (DOM.get(v)) { + editor = new Editor(v, settings, self); + editors.push(editor); + editor.render(true); + } else { + each(document.forms, function(f) { + each(f.elements, function(e) { + if (e.name === v) { + v = 'mce_editor_' + instanceCounter++; + DOM.setAttrib(e, 'id', v); + + editor = new Editor(v, settings, self); + editors.push(editor); + editor.render(1); + } + }); + }); + } + }); + } + break; + + case "textareas": + case "specific_textareas": + each(DOM.select('textarea'), function(elm) { + if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) { + return; + } + + if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) { + editor = new Editor(createId(elm), settings, self); + editors.push(editor); + editor.render(true); + } + }); + break; + + default: + if (settings.types) { + // Process type specific selector + each(settings.types, function(type) { + each(DOM.select(type.selector), function(elm) { + var editor = new Editor(createId(elm), extend({}, settings, type), self); + editors.push(editor); + editor.render(1); + }); + }); + } else if (settings.selector) { + // Process global selector + each(DOM.select(settings.selector), function(elm) { + var editor = new Editor(createId(elm), settings, self); + editors.push(editor); + editor.render(1); + }); + } + } + + // Call onInit when all editors are initialized + if (settings.oninit) { + l = co = 0; + + each(editors, function(ed) { + co++; + + if (!ed.initialized) { + // Wait for it + ed.on('init', function() { + l++; + + // All done + if (l == co) { + execCallback(settings, 'oninit'); + } + }); + } else { + l++; + } + + // All done + if (l == co) { + execCallback(settings, 'oninit'); + } + }); + } + }); + }, + + /** + * Returns a editor instance by id. + * + * @method get + * @param {String/Number} id Editor instance id or index to return. + * @return {tinymce.Editor} Editor instance to return. + * @example + * // Adds an onclick event to an editor by id (shorter version) + * tinymce.get('mytextbox').on('click', function(e) { + * ed.windowManager.alert('Hello world!'); + * }); + * + * // Adds an onclick event to an editor by id (longer version) + * tinymce.EditorManager.get('mytextbox').on('click', function(e) { + * ed.windowManager.alert('Hello world!'); + * }); + */ + get: function(id) { + if (id === undefined) { + return this.editors; + } + + return this.editors[id]; + }, + + /** + * Adds an editor instance to the editor collection. This will also set it as the active editor. + * + * @method add + * @param {tinymce.Editor} editor Editor instance to add to the collection. + * @return {tinymce.Editor} The same instance that got passed in. + */ + add: function(editor) { + var self = this, editors = self.editors; + + // Add named and index editor instance + editors[editor.id] = editor; + editors.push(editor); + + self.activeEditor = editor; + self.fire('AddEditor', {editor: editor}); + + if (!beforeUnloadDelegate) { + beforeUnloadDelegate = function() { + self.fire('BeforeUnload'); + }; + + DOM.bind(window, 'beforeunload', beforeUnloadDelegate); + } + + return editor; + }, + + /** + * Creates an editor instance and adds it to the EditorManager collection. + * + * @param {Object} settings Editor instance settings. + * @return {tinymce.Editor} Editor instance that got created. + */ + createEditor: function(settings) { + return this.add(new Editor(settings)); + }, + + /** + * Removes a editor instance from the collection. + * + * @method remove + * @param {tinymce.Editor} e Editor instance to remove. + * @return {tinymce.Editor} The editor that got passed in will be return if it was found otherwise null. + */ + remove: function(editor) { + var self = this, i, editors = self.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 (self.activeEditor == editor) { + self.activeEditor = editors[0]; + } + + editor.destroy(); + self.fire('RemoveEditor', {editor: editor}); + + if (!editors.length) { + DOM.unbind(window, 'beforeunload', beforeUnloadDelegate); + } + + return editor; + }, + + /** + * Executes a specific command on the currently active editor. + * + * @method execCommand + * @param {String} c Command to perform for example Bold. + * @param {Boolean} u Optional boolean state if a UI should be presented for the command or not. + * @param {String} v Optional value parameter like for example an URL to a link. + * @return {Boolean} true/false if the command was executed or not. + */ + execCommand: function(cmd, ui, value) { + var self = this, editor = self.get(value); + + // Manager commands + switch (cmd) { + case "mceAddEditor": + if (!self.get(value)) { + new Editor(value, self.settings, self).render(); + } + + return true; + + case "mceRemoveEditor": + if (editor) { + editor.remove(); + } + + return true; + + case 'mceToggleEditor': + if (!editor) { + self.execCommand('mceAddEditor', 0, value); + return true; + } + + if (editor.isHidden()) { + editor.show(); + } else { + editor.hide(); + } + + return true; + } + + // Run command on active editor + if (self.activeEditor) { + return self.activeEditor.execCommand(cmd, ui, value); + } + + return false; + }, + + /** + * Calls the save method on all editor instances in the collection. This can be useful when a form is to be submitted. + * + * @method triggerSave + * @example + * // Saves all contents + * tinyMCE.triggerSave(); + */ + triggerSave: function() { + each(this.editors, function(editor) { + editor.save(); + }); + }, + + /** + * Adds a language pack, this gets called by the loaded language files like en.js. + * + * @method addI18n + * @param {String} code Optional language code. + * @param {Object} items Name/value object with translations. + */ + addI18n: function(code, items) { + extend(this.i18n, items || code); + }, + + /** + * Translates the specified string using the language pack items. + * + * @param {String/Array} str String to translate + * @return {String} Translated string. + */ + translate: function(str) { + if (typeof(str) !== "string") { + return (this.i18n[str[0]] || str[0]).replace(/%d/, str[1]); + } + + return this.i18n[str] || str; + } + }; + + EditorManager.setup(); + + // Export EditorManager as tinymce/tinymce in global namespace + window.tinymce = window.tinyMCE = EditorManager; + + extend(EditorManager, Observable); + + return EditorManager; +}); + +// Included from: js/tinymce/classes/LegacyInput.js + +/** + * LegacyInput.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/LegacyInput", [ + "tinymce/EditorManager", + "tinymce/util/Tools" +], function(EditorManager, Tools) { + var each = Tools.each, explode = Tools.explode; + + EditorManager.on('AddEditor', function(e) { + var ed = e.editor; + + ed.on('preInit', function() { + var filters, fontSizes, dom, settings = ed.settings; + + function replaceWithSpan(node, styles) { + each(styles, function(value, name) { + if (value) { + dom.setStyle(node, name, value); + } + }); + + dom.rename(node, 'span'); + } + + function convert(e) { + dom = ed.dom; + + if (settings.convert_fonts_to_spans) { + each(dom.select('font,u,strike', e.node), function(node) { + filters[node.nodeName.toLowerCase()](dom, node); + }); + } + } + + if (settings.inline_styles) { + fontSizes = 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.on('PreProcess SetContent', convert); + } + }); + }); +}); + +// Included from: js/tinymce/classes/util/XHR.js + +/** + * XHR.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class enables you to send XMLHTTPRequests cross browser. + * @class tinymce.util.XHR + * @static + * @example + * // Sends a low level Ajax request + * tinymce.util.XHR.send({ + * url: 'someurl', + * success: function(text) { + * console.debug(text); + * } + * }); + */ +define("tinymce/util/XHR", [], function() { + return { + /** + * Sends a XMLHTTPRequest. + * Consult the Wiki for details on what settings this method takes. + * + * @method send + * @param {Object} settings Object will target URL, callbacks and other info needed to make the request. + */ + send: function(settings) { + var xhr, count = 0; + + function ready() { + if (!settings.async || xhr.readyState == 4 || count++ > 10000) { + if (settings.success && count < 10000 && xhr.status == 200) { + settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings); + } else if (settings.error) { + settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings); + } + + xhr = null; + } else { + setTimeout(ready, 10); + } + } + + // Default settings + settings.scope = settings.scope || this; + settings.success_scope = settings.success_scope || settings.scope; + settings.error_scope = settings.error_scope || settings.scope; + settings.async = settings.async === false ? false : true; + settings.data = settings.data || ''; + + xhr = new XMLHttpRequest(); + + if (xhr) { + if (xhr.overrideMimeType) { + xhr.overrideMimeType(settings.content_type); + } + + xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async); + + if (settings.content_type) { + xhr.setRequestHeader('Content-Type', settings.content_type); + } + + xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); + + xhr.send(settings.data); + + // Syncronous request + if (!settings.async) { + return ready(); + } + + // Wait for response, onReadyStateChange can not be used since it leaks memory in IE + setTimeout(ready, 10); + } + } + }; +}); + +// Included from: js/tinymce/classes/util/JSON.js + +/** + * JSON.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * JSON parser and serializer class. + * + * @class tinymce.util.JSON + * @static + * @example + * // JSON parse a string into an object + * var obj = tinymce.util.JSON.parse(somestring); + * + * // JSON serialize a object into an string + * var str = tinymce.util.JSON.serialize(obj); + */ +define("tinymce/util/JSON", [], 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 && Object.prototype.toString.call(o) === '[object Array]') { + for (i=0, 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; + } + + return { + /** + * Serializes the specified object as a JSON string. + * + * @method serialize + * @param {Object} obj Object to serialize as a JSON string. + * @param {String} quote Optional quote string defaults to ". + * @return {string} JSON string serialized from input. + */ + serialize: serialize, + + /** + * Unserializes/parses the specified JSON string into a object. + * + * @method parse + * @param {string} s JSON String to parse into a JavaScript object. + * @return {Object} Object from input JSON string or undefined if it failed. + */ + parse: function(text) { + try { + // Trick uglify JS + return window[String.fromCharCode(101) + 'val']('(' + text + ')'); + } catch (ex) { + // Ignore + } + } + + /**#@-*/ + }; +}); + +// Included from: js/tinymce/classes/util/JSONRequest.js + +/** + * JSONRequest.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class enables you to use JSON-RPC to call backend methods. + * + * @class tinymce.util.JSONRequest + * @example + * var json = new tinymce.util.JSONRequest({ + * url: 'somebackend.php' + * }); + * + * // Send RPC call 1 + * json.send({ + * method: 'someMethod1', + * params: ['a', 'b'], + * success: function(result) { + * console.dir(result); + * } + * }); + * + * // Send RPC call 2 + * json.send({ + * method: 'someMethod2', + * params: ['a', 'b'], + * success: function(result) { + * console.dir(result); + * } + * }); + */ +define("tinymce/util/JSONRequest", [ + "tinymce/util/JSON", + "tinymce/util/XHR", + "tinymce/util/Tools" +], function(JSON, XHR, Tools) { + var extend = Tools.extend; + + function JSONRequest(settings) { + this.settings = extend({}, settings); + this.count = 0; + } + + /** + * Simple helper function to send a JSON-RPC request without the need to initialize an object. + * Consult the Wiki API documentation for more details on what you can pass to this function. + * + * @method sendRPC + * @static + * @param {Object} o Call object where there are three field id, method and params this object should also contain callbacks etc. + */ + JSONRequest.sendRPC = function(o) { + return new JSONRequest().send(o); + }; + + JSONRequest.prototype = { + /** + * Sends a JSON-RPC call. Consult the Wiki API documentation for more details on what you can pass to this function. + * + * @method send + * @param {Object} args Call object where there are three field id, method and params this object should also contain callbacks etc. + */ + send: function(args) { + var ecb = args.error, scb = args.success; + + args = extend(this.settings, args); + + args.success = function(c, x) { + c = JSON.parse(c); + + if (typeof(c) == 'undefined') { + c = { + error : 'JSON Parse error.' + }; + } + + if (c.error) { + ecb.call(args.error_scope || args.scope, c.error, x); + } else { + scb.call(args.success_scope || args.scope, c.result); + } + }; + + args.error = function(ty, x) { + if (ecb) { + ecb.call(args.error_scope || args.scope, ty, x); + } + }; + + args.data = JSON.serialize({ + id : args.id || 'c' + (this.count++), + method : args.method, + params : args.params + }); + + // JSON content type for Ruby on rails. Bug: #1883287 + args.content_type = 'application/json'; + + XHR.send(args); + } + }; + + return JSONRequest; +}); + +// Included from: js/tinymce/classes/util/JSONP.js + +/** + * JSONP.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/util/JSONP", [ + "tinymce/dom/DOMUtils" +], function(DOMUtils) { + return { + callbacks: {}, + count: 0, + + send: function(settings) { + var self = this, dom = DOMUtils.DOM, count = settings.count !== undefined ? settings.count : self.count; + var id = 'tinymce_jsonp_' + count; + + self.callbacks[count] = function(json) { + dom.remove(id); + delete self.callbacks[count]; + + settings.callback(json); + }; + + dom.add(dom.doc.body, 'script', { + id: id, + src: settings.url, + type: 'text/javascript' + }); + + self.count++; + } + }; +}); + +// Included from: js/tinymce/classes/util/LocalStorage.js + +/** + * LocalStorage.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class will simulate LocalStorage on IE 7 and return the native version on modern browsers. + * Storage is done using userData on IE 7 and a special serialization format. The format is designed + * to be as small as possible by making sure that the keys and values doesn't need to be encoded. This + * makes it possible to store for example HTML data. + * + * Storage format for userData: + * ,,,,... + * + * For example this data key1=value1,key2=value2 would be: + * 4,key1,6,value1,4,key2,6,value2 + * + * @class tinymce.util.LocalStorage + * @static + * @version 4.0 + * @example + * tinymce.util.LocalStorage.setItem('key', 'value'); + * var value = tinymce.util.LocalStorage.getItem('key'); + */ +define("tinymce/util/LocalStorage", [], function() { + var LocalStorage, storageElm, items, keys, userDataKey; + + // Check for native support + if (window.localStorage) { + return localStorage; + } + + userDataKey = "tinymce"; + storageElm = document.documentElement; + storageElm.addBehavior('#default#userData'); + + /** + * Gets the keys names and updates LocalStorage.length property. Since IE7 doesn't have any getters/setters. + */ + function updateKeys() { + keys = []; + + for (var key in items) { + keys.push(key); + } + + LocalStorage.length = keys.length; + } + + /** + * Loads the userData string and parses it into the items structure. + */ + function load() { + var key, data, value, pos = 0; + + items = {}; + + function next(end) { + var value, nextPos; + + nextPos = end !== undefined ? pos + end : data.indexOf(',', pos); + if (nextPos === -1 || nextPos > data.length) { + return null; + } + + value = data.substring(pos, nextPos); + pos = nextPos + 1; + + return value; + } + + storageElm.load(userDataKey); + data = storageElm.getAttribute(userDataKey) || ''; + + do { + key = next(parseInt(next(), 32) || 0); + if (key !== null) { + value = next(parseInt(next(), 32) || 0); + items[key] = value; + } + } while (key !== null); + + updateKeys(); + } + + /** + * Saves the items structure into a the userData format. + */ + function save() { + var value, data = ''; + + for (var key in items) { + value = items[key]; + data += (data ? ',' : '') + key.length.toString(32) + ',' + key + ',' + value.length.toString(32) + ',' + value; + } + + storageElm.setAttribute(userDataKey, data); + storageElm.save(userDataKey); + updateKeys(); + } + + LocalStorage = { + /** + * Length of the number of items in storage. + * + * @property length + * @return {Number} Number of items in storage. + */ + //length:0, + + /** + * Returns the key name by index. + * + * @method key + * @param {Number} index Index of key to return. + * @return {String} Key value or null if it wasn't found. + */ + key: function(index) { + return keys[index]; + }, + + /** + * Returns the value if the specified key or null if it wasn't found. + * + * @method getItem + * @param {String} key Key of item to retrive. + * @return {String} Value of the specified item or null if it wasn't found. + */ + getItem: function(key) { + return key in items ? items[key] : null; + }, + + /** + * Sets the value of the specified item by it's key. + * + * @method setItem + * @param {String} key Key of the item to set. + * @param {String} value Value of the item to set. + */ + setItem: function(key, value) { + items[key] = "" + value; + save(); + }, + + /** + * Removes the specified item by key. + * + * @method removeItem + * @param {String} key Key of item to remove. + */ + removeItem: function(key) { + delete items[key]; + save(); + }, + + /** + * Removes all items. + * + * @method clear + */ + clear: function() { + items = {}; + save(); + } + }; + + load(); + + return LocalStorage; +}); + +// Included from: js/tinymce/classes/Compat.js + +/** + * Compat.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Adds various compatibility items. + */ +define("tinymce/Compat", [ + "tinymce/dom/DOMUtils", + "tinymce/dom/EventUtils", + "tinymce/dom/ScriptLoader", + "tinymce/AddOnManager", + "tinymce/util/Tools", + "tinymce/Env" +], function(DOMUtils, EventUtils, ScriptLoader, AddOnManager, Tools, Env) { + var tinymce = window.tinymce; + + tinymce.DOM = DOMUtils.DOM; + tinymce.ScriptLoader = ScriptLoader.ScriptLoader; + tinymce.PluginManager = AddOnManager.PluginManager; + tinymce.ThemeManager = AddOnManager.ThemeManager; + + tinymce.dom = tinymce.dom || {}; + tinymce.dom.Event = EventUtils.Event; + + Tools.each(Tools, function(func, key) { + tinymce[key] = func; + }); + + Tools.each('isOpera isWebKit isIE isGecko isMac'.split(' '), function(name) { + tinymce[name] = Env[name.substr(2).toLowerCase()]; + }); + + return {}; +}); + +// Included from: js/tinymce/classes/ui/Layout.js + +/** + * Layout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Base layout manager class. + * + * @class tinymce.ui.Layout + */ +define("tinymce/ui/Layout", [ + "tinymce/util/Class", + "tinymce/util/Tools" +], function(Class, Tools) { + "use strict"; + + return Class.extend({ + Defaults: { + firstControlClass: 'first', + lastControlClass: 'last' + }, + + init: function(settings) { + this.settings = Tools.extend({}, this.Defaults, settings); + }, + + preRender: function(container) { + container.addClass(this.settings.containerClass, 'body'); + }, + + applyClasses: function(container) { + var self = this, settings = self.settings, items, firstClass, lastClass; + + items = container.items().filter(':visible'); + firstClass = settings.firstControlClass; + lastClass = settings.lastControlClass; + + items.each(function(item) { + item.removeClass(firstClass).removeClass(lastClass); + + if (settings.controlClass) { + item.addClass(settings.controlClass); + } + }); + + items.eq(0).addClass(firstClass); + items.eq(-1).addClass(lastClass); + }, + + renderHtml: function(container) { + var self = this, settings = self.settings, items, html = ''; + + items = container.items(); + items.eq(0).addClass(settings.firstControlClass); + items.eq(-1).addClass(settings.lastControlClass); + + items.each(function(item) { + if (settings.controlClass) { + item.addClass(settings.controlClass); + } + + html += item.renderHtml(); + }); + + return html; + }, + + recalc: function() { + }, + + postRender: function() { + } + }); +}); + +// Included from: js/tinymce/classes/ui/AbsoluteLayout.js + +/** + * AbsoluteLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less AbsoluteLayout.less + * @class tinymce.ui.AbsoluteLayout + * @extends tinymce.ui.Layout + */ +define("tinymce/ui/AbsoluteLayout", [ + "tinymce/ui/Layout" +], function(Layout) { + "use strict"; + + return Layout.extend({ + Defaults: { + containerClass: 'abs-layout', + controlClass: 'abs-layout-item' + }, + + recalc: function(container) { + container.items().filter(':visible').each(function(ctrl) { + var settings = ctrl.settings; + + ctrl.layoutRect({ + x: settings.x, + y: settings.y, + w: settings.w, + h: settings.h + }); + + if (ctrl.recalc) { + ctrl.recalc(); + } + }); + }, + + renderHtml: function(container) { + return '
    ' + this._super(container); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Tooltip.js + +/** + * Tooltip.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ToolTip.less + * @class tinymce.ui.ToolTip + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Tooltip", [ + "tinymce/ui/Control", + "tinymce/ui/Movable" +], function(Control, Movable) { + return Control.extend({ + Mixins: [Movable], + + Defaults: { + classes: 'widget tooltip tooltip-n' + }, + + text: function(value) { + var self = this; + + if (typeof(value) != "undefined") { + self._value = value; + + if (self._rendered) { + self.getEl().lastChild.innerHTML = self.encode(value); + } + + return self; + } + + return self._value; + }, + + renderHtml: function() { + var self = this, prefix = self.classPrefix; + + return ( + '' + ); + }, + + repaint: function() { + var self = this, style, rect; + + style = self.getEl().style; + rect = self._layoutRect; + + style.left = rect.x + 'px'; + style.top = rect.y + 'px'; + style.zIndex = 0xFFFF + 0xFFFF; + } + }); +}); + +// Included from: js/tinymce/classes/ui/Widget.js + +/** + * Widget.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * + * @class tinymce.ui.Widget + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Widget", [ + "tinymce/ui/Control", + "tinymce/ui/Tooltip" +], function(Control, Tooltip) { + "use strict"; + + var tooltip; + + return Control.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + self.canFocus = true; + + if (settings.tooltip) { + self.on('mouseenter mouseleave', function(e) { + if (e.control == self && e.type == 'mouseenter') { + self.tooltip().moveTo(-0xFFFF).text(settings.tooltip).show().moveRel(self.getEl(), 'bc tc'); + } else { + self.tooltip().moveTo(-0xFFFF).hide(); + } + }); + } + + self.aria('label', settings.tooltip); + }, + + tooltip: function() { + var self = this; + + if (!tooltip) { + tooltip = new Tooltip({type: 'tooltip'}); + tooltip.renderTo(self.getContainerElm()); + } + + return tooltip; + }, + + active: function(state) { + var self = this, undef; + + if (state !== undef) { + self.aria('pressed', state); + self.toggleClass('active', state); + } + + return self._super(state); + }, + + disabled: function(state) { + var self = this, undef; + + if (state !== undef) { + self.aria('disabled', state); + self.toggleClass('disabled', state); + } + + return self._super(state); + }, + + postRender: function() { + var self = this, settings = self.settings; + + self._rendered = true; + + self._super(); + + if (!self.parent() && (settings.width || settings.height)) { + self.initLayoutRect(); + self.repaint(); + } + + if (settings.autofocus) { + self.focus(); + } + }, + + remove: function() { + this._super(); + + if (tooltip) { + tooltip.remove(); + tooltip = null; + } + } + }); +}); + +// Included from: js/tinymce/classes/ui/Button.js + +/** + * Button.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Button.less + * @class tinymce.ui.Button + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Button", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + Defaults: { + classes: "widget btn", + role: "button" + }, + + init: function(settings) { + var self = this, size; + + self.on('click mousedown', function(e) { + e.preventDefault(); + }); + + self._super(settings); + size = settings.size; + + if (settings.subtype) { + self.addClass(settings.subtype); + } + + if (size) { + self.addClass('btn-' + size); + } + }, + + repaint: function() { + var btnStyle = this.getEl().firstChild.style; + + btnStyle.width = btnStyle.height = "100%"; + + this._super(); + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; + var image = self.settings.image ? ' style="background-image: url(\'' + self.settings.image + '\')"' : ''; + + return ( + '
    ' + + '' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/ButtonGroup.js + +/** + * ButtonGroup.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ButtonGroup.less + * @class tinymce.ui.ButtonGroup + * @extends tinymce.ui.Container + */ +define("tinymce/ui/ButtonGroup", [ + "tinymce/ui/Container" +], function(Container) { + "use strict"; + + return Container.extend({ + Defaults: { + defaultType: 'button', + role: 'toolbar' + }, + + renderHtml: function() { + var self = this, layout = self._layout; + + self.addClass('btn-group'); + self.preRender(); + layout.preRender(self); + + return ( + '
    '+ + '
    '+ + (self.settings.html || '') + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Checkbox.js + +/** + * Checkbox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Checkbox.less + * @class tinymce.ui.Checkbox + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/Checkbox", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + Defaults: { + classes: "checkbox", + role: "checkbox", + checked: false + }, + + init: function(settings) { + var self = this; + + self._super(settings); + + self.on('click mousedown', function(e) { + e.preventDefault(); + }); + + self.on('click', function(e) { + e.preventDefault(); + + if (!self.disabled()) { + self.checked(!self.checked()); + } + }); + + self.checked(self.settings.checked); + }, + + checked: function(state) { + var self = this; + + if (typeof state != "undefined") { + if (state) { + self.addClass('checked'); + } else { + self.removeClass('checked'); + } + + self._checked = state; + self.aria('checked', state); + + return self; + } + + return self._checked; + }, + + value: function(state) { + return this.checked(state); + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + + return ( + '
    ' + + '' + + '' + self._text + '' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/CheckboxGroup.js + +/** + * CheckboxGroup.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.CheckboxGroup + * @extends tinymce.ui.Container + */ +define("tinymce/ui/CheckboxGroup", [ + "tinymce/ui/Container" +], function(Container) { + "use strict"; + + return Container.extend({}); +}); + +// Included from: js/tinymce/classes/ui/ColorButton.js + +/** + * ColorButton.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ColorButton.less + * @class tinymce.ui.ColorButton + * @extends tinymce.ui.MenuButton + */ +define("tinymce/ui/ColorButton", [ + "tinymce/ui/Button", + "tinymce/ui/FloatPanel", + "tinymce/ui/KeyboardNavigation" +], function(Button, FloatPanel, KeyboardNavigation) { + "use strict"; + + function mapColors() { + var i, colors = [], colorMap; + + colorMap = [ + "000000", "Black", + "993300", "Burnt orange", + "333300", "Dark olive", + "003300", "Dark green", + "003366", "Dark azure", + "000080", "Navy Blue", + "333399", "Indigo", + "333333", "Very dark gray", + "800000", "Maroon", + "FF6600", "Orange", + "808000", "Olive", + "008000", "Green", + "008080", "Teal", + "0000FF", "Blue", + "666699", "Grayish blue", + "808080", "Gray", + "FF0000", "Red", + "FF9900", "Amber", + "99CC00", "Yellow green", + "339966", "Sea green", + "33CCCC", "Turquoise", + "3366FF", "Royal blue", + "800080", "Purple", + "999999", "Medium gray", + "FF00FF", "Magenta", + "FFCC00", "Gold", + "FFFF00", "Yellow", + "00FF00", "Lime", + "00FFFF", "Aqua", + "00CCFF", "Sky blue", + "993366", "Brown", + "C0C0C0", "Silver", + "FF99CC", "Pink", + "FFCC99", "Peach", + "FFFF99", "Light yellow", + "CCFFCC", "Pale green", + "CCFFFF", "Pale cyan", + "99CCFF", "Light sky blue", + "CC99FF", "Plum", + "FFFFFF", "White" + ]; + + for (i = 0; i < colorMap.length; i += 2) { + colors.push({ + text: colorMap[i + 1], + color: colorMap[i] + }); + } + + return colors; + } + + return Button.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('colorbutton'); + self.on('click', function(e) { + if (e.control == self) { + self.showPicker(); + } + }); + self.hasPopup = true; + }, + + showPicker: function() { + var self = this, html = '', size, x, y, prefix = self.classPrefix, colors; + + if (!self.picker) { + colors = mapColors(); + + html = ''; + size = Math.ceil(Math.sqrt(colors.length)); + + for (y = 0; y < 5; y++) { + html += ''; + + for (x = 0; x < 8; x++) { + var color = colors[y * 8 + x]; + + html += ( + '' + ); + } + + html += ''; + } + + html += ''; + + self.picker = new FloatPanel({ + popover: true, + autohide: true, + html: html, + border: 1, + classes: 'colorpicker' + }).parent(self).renderTo(self.getContainerElm()); + + self.picker._hasBody = false; + self.picker.reflow(); + self.picker.parent(self); + self.picker.on('cancel', function(e) { + if (e.control === self.menu) { + self.focus(); + } + }); + self.picker.on('click', function(e) { + var value; + + if ((value = e.target.getAttribute('data-mce-color'))) { + self.picker.hide(); + value = '#' + value; + self.showPreview(value); + self.fire('select', {value: value}); + } + }); + + self.keyboardNavigation = new KeyboardNavigation({ + root: self.picker, + items: self.picker.getEl().getElementsByTagName('div'), + onCancel: function() { + self.picker.hide(); + self.fire('cancel'); + } + }); + } + + self.picker.show(); + self.picker.moveRel(self.getEl(), 'bc-tl'); + self.keyboardNavigation.focusFirst(); + }, + + showPreview: function(color) { + this.getEl('preview').style.backgroundColor = color; + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; + var image = self.settings.image ? ' style="background-image: url(\'' + self.settings.image + '\')"' : ''; + + return ( + '
    ' + + '' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/ComboBox.js + +/** + * ComboBox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ComboBox.less + * @class tinymce.ui.ComboBox + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/ComboBox", [ + "tinymce/ui/Widget", + "tinymce/ui/DomUtils" +], function(Widget, DomUtils) { + "use strict"; + + return Widget.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('combobox'); + + self.on('click', function(e) { + var elm = e.target; + + while (elm) { + if (elm.id && elm.id.indexOf('-open') != -1) { + self.fire('action'); + } + + elm = elm.parentNode; + } + }); + + // TODO: Rework this + self.on('keydown', function(e) { + if (e.target.nodeName == "INPUT" && e.keyCode == 13) { + self.parents().reverse().each(function(ctrl) { + e.preventDefault(); + self.fire('change'); + + if (ctrl.submit) { + ctrl.submit(); + return false; + } + }); + } + }); + + if (settings.placeholder) { + self.addClass('placeholder'); + + self.on('focusin', function() { + if (!self._hasOnChange) { + DomUtils.on(self.getEl('inp'), 'change', function() { + self.fire('change'); + }); + + self._hasOnChange = true; + } + + if (self.hasClass('placeholder')) { + self.getEl('inp').value = ''; + self.removeClass('placeholder'); + } + }); + + self.on('focusout', function() { + if (self.value().length === 0) { + self.getEl('inp').value = settings.placeholder; + self.addClass('placeholder'); + } + }); + } + }, + + value: function(value) { + var self = this; + + if (typeof(value) != "undefined") { + self._value = value; + self.removeClass('placeholder'); + + if (self._rendered) { + self.getEl('inp').value = value; + } + + return self; + } + + if (self._rendered) { + value = self.getEl('inp').value; + + if (value != self.settings.placeholder) { + return value; + } + + return ''; + } + + return self._value; + }, + + repaint: function() { + var self = this, elm = self.getEl(), openElm = self.getEl('open'), rect = self.layoutRect(); + + if (openElm) { + DomUtils.css(elm.firstChild, { + width: rect.w - openElm.offsetWidth - 10 + //lineHeight: (self.layoutRect().h - 2) + 'px' + }); + } else { + DomUtils.css(elm.firstChild, { + width: rect.w - 10 + }); + } + + self._super(); + + return self; + }, + + disabled: function(state) { + var self = this; + + self._super(state); + + if (self._rendered) { + self.getEl().disabled = state; + } + }, + + focus: function() { + this.getEl('inp').focus(); + }, + + postRender: function() { + var self = this; + + DomUtils.on(this.getEl('inp'), 'change', function() { + self.fire('change'); + }); + + return self._super(); + }, + + renderHtml: function() { + var self = this, id = self._id, settings = self.settings, prefix = self.classPrefix; + var value = settings.value || settings.placeholder || ''; + var icon, text, openBtnHtml = ''; + + icon = settings.icon ? prefix + 'ico ' + prefix + 'i-' + settings.icon : ''; + text = self._text; + + if (icon || text) { + openBtnHtml = ( + '
    ' + + '' + + '
    ' + ); + + self.addClass('has-open'); + } + + return ( + '
    ' + + '' + + openBtnHtml + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Path.js + +/** + * Path.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Path.less + * @class tinymce.ui.Path + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Path", [ + "tinymce/ui/Control", + "tinymce/ui/KeyboardNavigation" +], function(Control, KeyboardNavigation) { + "use strict"; + + return Control.extend({ + Defaults: { + delimiter: "\u00BB" + }, + + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('path'); + self.canFocus = true; + + self.on('click', function(e) { + var index, target = e.target; + + if ((index = target.getAttribute('data-index'))) { + self.fire('select', {value: self.data()[index], index: index}); + } + }); + }, + + focus: function() { + var self = this; + + self.keyNav = new KeyboardNavigation({ + root: self, + enableLeftRight: true + }); + + self.keyNav.focusFirst(); + + return self; + }, + + data: function(data) { + var self = this; + + if (typeof(data) !== "undefined") { + self._data = data; + self.update(); + + return self; + } + + return self._data; + }, + + update: function() { + var self = this, parts = self._data, i, l, html = '', prefix = self.classPrefix; + + for (i = 0, l = parts.length; i < l; i++) { + html += ( + (i > 0 ? '' : '') + + '
    ' + parts[i].name + '
    ' + ); + } + + self.getEl().innerHTML = html; + }, + + postRender: function() { + var self = this; + + self._super(); + + self.data(self.settings.data); + }, + + repa2int: function() { + var self = this; + + self.getEl('text').style.lineHeight = self.layoutRect().h + 'px'; + + return self._super(); + }, + + /** + * ... + * + * @method render + */ + renderHtml: function() { + var self = this, prefix = self.classPrefix; + + return ( + '
    ' + + '
     
    ' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/ElementPath.js + +/** + * ElementPath.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.ElementPath + * @extends tinymce.ui.Path + */ +define("tinymce/ui/ElementPath", [ + "tinymce/ui/Path", + "tinymce/EditorManager" +], function(Path, EditorManager) { + return Path.extend({ + postRender: function() { + var self = this, editor = EditorManager.activeEditor; + + function isBogus(elm) { + return elm.nodeType === 1 && (elm.nodeName == "BR" || !!elm.getAttribute('data-mce-bogus')); + } + + self.on('select', function(e) { + var parents = [], node = editor.selection.getNode(), body = editor.getBody(); + + while (node) { + if (!isBogus(node)) { + parents.push(node); + } + + node = node.parentNode; + if (node == body) { + break; + } + } + + editor.focus(); + editor.selection.select(parents[parents.length - 1 - e.index]); + editor.nodeChanged(); + }); + + editor.on('nodeChange', function(e) { + var parents = [], selectionParents = e.parents, i = selectionParents.length; + + while (i--) { + if (!isBogus(selectionParents[i])) { + var args = editor.fire('ResolveName', { + name: selectionParents[i].nodeName.toLowerCase(), + target: selectionParents[i] + }); + + parents.push({name: args.name}); + } + } + + self.data(parents); + }); + + return self._super(); + } + }); +}); + +// Included from: js/tinymce/classes/ui/FormItem.js + +/** + * FormItem.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.FormItem + * @extends tinymce.ui.Container + */ +define("tinymce/ui/FormItem", [ + "tinymce/ui/Container" +], function(Container) { + "use strict"; + + return Container.extend({ + Defaults: { + layout: 'flex', + align: 'center', + defaults: { + flex: 1 + } + }, + + renderHtml: function() { + var self = this, layout = self._layout, prefix = self.classPrefix; + + self.addClass('formitem'); + layout.preRender(self); + + return ( + '
    ' + + (self.settings.title ? ('
    ' + + self.settings.title + '
    ') : '') + + '
    ' + + (self.settings.html || '') + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Form.js + +/** + * Form.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.Form + * @extends tinymce.ui.Container + */ +define("tinymce/ui/Form", [ + "tinymce/ui/Container", + "tinymce/ui/FormItem" +], function(Container, FormItem) { + "use strict"; + + return Container.extend({ + Defaults: { + containerCls: 'form', + layout: 'flex', + direction: 'column', + align: 'stretch', + flex: 1, + padding: 20, + labelGap: 30, + spacing: 10 + }, + + preRender: function() { + var self = this, items = self.items(); + + // Wrap any labeled items in FormItems + items.each(function(ctrl) { + var formItem, label = ctrl.settings.label; + + if (label) { + formItem = new FormItem({ + layout: 'flex', + autoResize: "overflow", + defaults: {flex: 1}, + items: [ + {type: 'label', text: label, flex: 0, forId: ctrl._id} + ] + }); + + formItem.type = 'formitem'; + + if (typeof(ctrl.settings.flex) == "undefined") { + ctrl.settings.flex = 1; + } + + self.replace(ctrl, formItem); + formItem.add(ctrl); + } + }); + }, + + recalcLabels: function() { + var self = this, maxLabelWidth = 0, labels = [], i, labelGap; + + if (self.settings.labelGapCalc === false) { + return; + } + + self.items().filter('formitem').each(function(item) { + var labelCtrl = item.items()[0], labelWidth = labelCtrl.getEl().clientWidth; + + maxLabelWidth = labelWidth > maxLabelWidth ? labelWidth : maxLabelWidth; + labels.push(labelCtrl); + }); + + labelGap = self.settings.labelGap || 0; + + i = labels.length; + while (i--) { + labels[i].settings.minWidth = maxLabelWidth + labelGap; + } + }, + + visible: function(state) { + var val = this._super(state); + + if (state === true && this._rendered) { + this.recalcLabels(); + } + + return val; + }, + + fromJSON: function(data) { + var self = this; + + if (data) { + for (var name in data) { + self.find('#' + name).value(data[name]); + } + } + + return self; + }, + + toJSON: function() { + var self = this, data = {}; + + self.find('*').each(function(ctrl) { + var name = ctrl.name(), value = ctrl.value(); + + if (name && typeof(value) != "undefined") { + data[name] = value; + } + }); + + return data; + }, + + submit: function() { + return this.fire('submit', {data: this.toJSON()}); + }, + + postRender: function() { + var self = this; + + self._super(); + self.recalcLabels(); + self.fromJSON(self.settings.data); + } + }); +}); + +// Included from: js/tinymce/classes/ui/FieldSet.js + +/** + * FieldSet.js + * + * Copyright 2003-2013, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less FieldSet.less + * @class tinymce.ui.FieldSet + * @extends tinymce.ui.Form + */ +define("tinymce/ui/FieldSet", [ + "tinymce/ui/Form" +], function(Form) { + "use strict"; + + return Form.extend({ + Defaults: { + containerCls: 'fieldset', + layout: 'flex', + direction: 'column', + align: 'stretch', + flex: 1, + padding: "25 15 5 15", + labelGap: 30, + spacing: 10, + border: 1 + }, + + renderHtml: function() { + var self = this, layout = self._layout, prefix = self.classPrefix; + + self.preRender(); + layout.preRender(self); + + return ( + '
    ' + + (self.settings.title ? ('' + + self.settings.title + '') : '') + + '
    ' + + (self.settings.html || '') + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/FilePicker.js + +/** + * FilePicker.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/*global tinymce:true */ + +/** + * .. + * + * @class tinymce.ui.FilePicker + * @extends tinymce.ui.ComboBox + */ +define("tinymce/ui/FilePicker", [ + "tinymce/ui/ComboBox" +], function(ComboBox) { + "use strict"; + + return ComboBox.extend({ + init: function(settings) { + var self = this, editor = tinymce.activeEditor, fileBrowserCallback; + + settings.spellcheck = false; + + fileBrowserCallback = editor.settings.file_browser_callback; + if (fileBrowserCallback) { + settings.icon = 'browse'; + + settings.onaction = function() { + fileBrowserCallback( + self.getEl('inp').id, + self.getEl('inp').value, + settings.filetype, + window + ); + }; + } + + self._super(settings); + } + }); +}); + +// Included from: js/tinymce/classes/ui/FitLayout.js + +/** + * FitLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * This class jada jada. + * + * var x = 3; + * + * @-x-less FitLayout.less + * @class tinymce.ui.FitLayout + * @extends tinymce.ui.AbsoluteLayout + */ +define("tinymce/ui/FitLayout", [ + "tinymce/ui/AbsoluteLayout" +], function(AbsoluteLayout) { + "use strict"; + + return AbsoluteLayout.extend({ + recalc: function(container) { + var contLayoutRect = container.layoutRect(), paddingBox = container.paddingBox(); + + container.items().filter(':visible').each(function(ctrl) { + ctrl.layoutRect({ + x: paddingBox.left, + y: paddingBox.top, + w: contLayoutRect.innerW - paddingBox.right - paddingBox.left, + h: contLayoutRect.innerH - paddingBox.top - paddingBox.bottom + }); + + if (ctrl.recalc) { + ctrl.recalc(); + } + }); + } + }); +}); + +// Included from: js/tinymce/classes/ui/FlexLayout.js + +/** + * FlexLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * Settings: + * direction=row|row-reverse|column|column-reverse + * flex= + * align=start|end|center|stretch + * pack=start|end|justify + * + * @class tinymce.ui.layout.FlexLayout + * @extends tinymce.ui.AbsoluteLayout + */ +define("tinymce/ui/FlexLayout", [ + "tinymce/ui/AbsoluteLayout" +], function(AbsoluteLayout) { + "use strict"; + + return AbsoluteLayout.extend({ + recalc: function(container) { + var i, l, items, contLayoutRect, contPaddingBox, contSettings, align, pack, spacing, totalFlex, availableSpace, direction; + var ctrl, ctrlLayoutRect, ctrlSettings, flex, maxSizeItems = [], size, maxSize, ratio, rect, pos, maxAlignEndPos; + var sizeName, minSizeName, posName, maxSizeName, beforeName, innerSizeName, afterName, deltaSizeName, contentSizeName; + var alignAxisName, alignInnerSizeName, alignSizeName, alignMinSizeName, alignMaxSizeName, alignBeforeName, alignAfterName; + var alignDeltaSizeName, alignContentSizeName; + var max = Math.max, min = Math.min; + + // Get container items, properties and settings + items = container.items().filter(':visible'); + contLayoutRect = container.layoutRect(); + contPaddingBox = container._paddingBox; + contSettings = container.settings; + direction = contSettings.direction; + align = contSettings.align; + pack = contSettings.pack; + spacing = contSettings.spacing || 0; + + if (direction == "row-reversed" || direction == "column-reverse") { + items = items.set(items.toArray().reverse()); + direction = direction.split('-')[0]; + } + + // Setup axis variable name for row/column direction since the calculations is the same + if (direction == "column") { + posName = "y"; + sizeName = "h"; + minSizeName = "minH"; + maxSizeName = "maxH"; + innerSizeName = "innerH"; + beforeName = 'top'; + afterName = 'bottom'; + deltaSizeName = "deltaH"; + contentSizeName = "contentH"; + + alignBeforeName = "left"; + alignSizeName = "w"; + alignAxisName = "x"; + alignInnerSizeName = "innerW"; + alignMinSizeName = "minW"; + alignMaxSizeName = "maxW"; + alignAfterName = "right"; + alignDeltaSizeName = "deltaW"; + alignContentSizeName = "contentW"; + } else { + posName = "x"; + sizeName = "w"; + minSizeName = "minW"; + maxSizeName = "maxW"; + innerSizeName = "innerW"; + beforeName = 'left'; + afterName = 'right'; + deltaSizeName = "deltaW"; + contentSizeName = "contentW"; + + alignBeforeName = "top"; + alignSizeName = "h"; + alignAxisName = "y"; + alignInnerSizeName = "innerH"; + alignMinSizeName = "minH"; + alignMaxSizeName = "maxH"; + alignAfterName = "bottom"; + alignDeltaSizeName = "deltaH"; + alignContentSizeName = "contentH"; + } + + // Figure out total flex, availableSpace and collect any max size elements + availableSpace = contLayoutRect[innerSizeName] - contPaddingBox[beforeName] - contPaddingBox[beforeName]; + maxAlignEndPos = totalFlex = 0; + for (i = 0, l = items.length; i < l; i++) { + ctrl = items[i]; + ctrlLayoutRect = ctrl.layoutRect(); + ctrlSettings = ctrl.settings; + flex = ctrlSettings.flex; + availableSpace -= (i < l - 1 ? spacing : 0); + + if (flex > 0) { + totalFlex += flex; + + // Flexed item has a max size then we need to check if we will hit that size + if (ctrlLayoutRect[maxSizeName]) { + maxSizeItems.push(ctrl); + } + + ctrlLayoutRect.flex = flex; + } + + availableSpace -= ctrlLayoutRect[minSizeName]; + + // Calculate the align end position to be used to check for overflow/underflow + size = contPaddingBox[alignBeforeName] + ctrlLayoutRect[alignMinSizeName] + contPaddingBox[alignAfterName]; + if (size > maxAlignEndPos) { + maxAlignEndPos = size; + } + } + + // Calculate minW/minH + rect = {}; + if (availableSpace < 0) { + rect[minSizeName] = contLayoutRect[minSizeName] - availableSpace + contLayoutRect[deltaSizeName]; + } else { + rect[minSizeName] = contLayoutRect[innerSizeName] - availableSpace + contLayoutRect[deltaSizeName]; + } + + rect[alignMinSizeName] = maxAlignEndPos + contLayoutRect[alignDeltaSizeName]; + + rect[contentSizeName] = contLayoutRect[innerSizeName] - availableSpace; + rect[alignContentSizeName] = maxAlignEndPos; + rect.minW = min(rect.minW, contLayoutRect.maxW); + rect.minH = min(rect.minH, contLayoutRect.maxH); + rect.minW = max(rect.minW, contLayoutRect.startMinWidth); + rect.minH = max(rect.minH, contLayoutRect.startMinHeight); + + // Resize container container if minSize was changed + if (contLayoutRect.autoResize && (rect.minW != contLayoutRect.minW || rect.minH != contLayoutRect.minH)) { + rect.w = rect.minW; + rect.h = rect.minH; + + container.layoutRect(rect); + this.recalc(container); + + // Forced recalc for example if items are hidden/shown + if (container._lastRect === null) { + var parentCtrl = container.parent(); + if (parentCtrl) { + parentCtrl._lastRect = null; + parentCtrl.recalc(); + } + } + + return; + } + + // Handle max size elements, check if they will become to wide with current options + ratio = availableSpace / totalFlex; + for (i = 0, l = maxSizeItems.length; i < l; i++) { + ctrl = maxSizeItems[i]; + ctrlLayoutRect = ctrl.layoutRect(); + maxSize = ctrlLayoutRect[maxSizeName]; + size = ctrlLayoutRect[minSizeName] + Math.ceil(ctrlLayoutRect.flex * ratio); + + if (size > maxSize) { + availableSpace -= (ctrlLayoutRect[maxSizeName] - ctrlLayoutRect[minSizeName]); + totalFlex -= ctrlLayoutRect.flex; + ctrlLayoutRect.flex = 0; + ctrlLayoutRect.maxFlexSize = maxSize; + } else { + ctrlLayoutRect.maxFlexSize = 0; + } + } + + // Setup new ratio, target layout rect, start position + ratio = availableSpace / totalFlex; + pos = contPaddingBox[beforeName]; + rect = {}; + + // Handle pack setting moves the start position to end, center + if (totalFlex === 0) { + if (pack == "end") { + pos = availableSpace + contPaddingBox[beforeName]; + } else if (pack == "center") { + pos = Math.round( + (contLayoutRect[innerSizeName] / 2) - ((contLayoutRect[innerSizeName] - availableSpace) / 2) + ) + contPaddingBox[beforeName]; + + if (pos < 0) { + pos = contPaddingBox[beforeName]; + } + } else if (pack == "justify") { + pos = contPaddingBox[beforeName]; + spacing = Math.floor(availableSpace / (items.length - 1)); + } + } + + // Default aligning (start) the other ones needs to be calculated while doing the layout + rect[alignAxisName] = contPaddingBox[alignBeforeName]; + + // Start laying out controls + for (i = 0, l = items.length; i < l; i++) { + ctrl = items[i]; + ctrlLayoutRect = ctrl.layoutRect(); + size = ctrlLayoutRect.maxFlexSize || ctrlLayoutRect[minSizeName]; + + // Align the control on the other axis + if (align === "center") { + rect[alignAxisName] = Math.round((contLayoutRect[alignInnerSizeName] / 2) - (ctrlLayoutRect[alignSizeName] / 2)); + } else if (align === "stretch") { + rect[alignSizeName] = max( + ctrlLayoutRect[alignMinSizeName] || 0, + contLayoutRect[alignInnerSizeName] - contPaddingBox[alignBeforeName] - contPaddingBox[alignAfterName] + ); + rect[alignAxisName] = contPaddingBox[alignBeforeName]; + } else if (align === "end") { + rect[alignAxisName] = contLayoutRect[alignInnerSizeName] - ctrlLayoutRect[alignSizeName] - contPaddingBox.top; + } + + // Calculate new size based on flex + if (ctrlLayoutRect.flex > 0) { + size += Math.ceil(ctrlLayoutRect.flex * ratio); + } + + rect[sizeName] = size; + rect[posName] = pos; + ctrl.layoutRect(rect); + + // Recalculate containers + if (ctrl.recalc) { + ctrl.recalc(); + } + + // Move x/y position + pos += size + spacing; + } + } + }); +}); + +// Included from: js/tinymce/classes/ui/FlowLayout.js + +/** + * FlowLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less FlowLayout.less + * @class tinymce.ui.FlowLayout + * @extends tinymce.ui.Layout + */ +define("tinymce/ui/FlowLayout", [ + "tinymce/ui/Layout" +], function(Layout) { + return Layout.extend({ + Defaults: { + containerClass: 'flow-layout', + controlClass: 'flow-layout-item', + endClass : 'break' + }, + + recalc: function(container) { + container.items().filter(':visible').each(function(ctrl) { + if (ctrl.recalc) { + ctrl.recalc(); + } + }); + } + }); +}); + +// Included from: js/tinymce/classes/ui/FormatControls.js + +/** + * FormatControls.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * + * @class tinymce.ui.FormatControls + */ +define("tinymce/ui/FormatControls", [ + "tinymce/ui/Factory", + "tinymce/ui/Control", + "tinymce/ui/FloatPanel", + "tinymce/util/Tools", + "tinymce/EditorManager" +], function(Factory, Control, FloatPanel, Tools, EditorManager) { + var each = Tools.each; + + Control.translate = function(text) { + return EditorManager.translate(text); + }; + + // Generates a preview for a format + function getPreviewCss(editor, format) { + var name, previewElm, dom = editor.dom, previewCss = '', parentFontSize, previewStyles; + + previewStyles = editor.settings.preview_styles; + + // No preview forced + if (previewStyles === false) { + return ''; + } + + // Default preview + if (!previewStyles) { + previewStyles = 'font-family font-size font-weight text-decoration text-transform color background-color border border-radius'; + } + + // Removes any variables since these can't be previewed + function removeVars(val) { + return val.replace(/%(\w+)/g, ''); + } + + // Create block/inline element to use for preview + format = editor.formatter.get(format); + if (!format) { + return; + } + + format = format[0]; + name = format.block || format.inline || 'span'; + previewElm = dom.create(name); + + // Add format styles to preview element + each(format.styles, function(value, name) { + value = removeVars(value); + + if (value) { + dom.setStyle(previewElm, name, value); + } + }); + + // Add attributes to preview element + each(format.attributes, function(value, name) { + value = removeVars(value); + + if (value) { + dom.setAttrib(previewElm, name, value); + } + }); + + // Add classes to preview element + each(format.classes, function(value) { + value = removeVars(value); + + if (!dom.hasClass(previewElm, value)) { + dom.addClass(previewElm, value); + } + }); + + editor.fire('PreviewFormats'); + + // Add the previewElm outside the visual area + dom.setStyles(previewElm, {position: 'absolute', left: -0xFFFF}); + editor.getBody().appendChild(previewElm); + + // Get parent container font size so we can compute px values out of em/% for older IE:s + parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true); + parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0; + + each(previewStyles.split(' '), function(name) { + var value = dom.getStyle(previewElm, name, true); + + // If background is transparent then check if the body has a background color we can use + if (name == 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) { + value = dom.getStyle(editor.getBody(), name, true); + + // Ignore white since it's the default color, not the nicest fix + // TODO: Fix this by detecting runtime style + if (dom.toHex(value).toLowerCase() == '#ffffff') { + return; + } + } + + if (name == 'color') { + // Ignore black since it's the default color, not the nicest fix + // TODO: Fix this by detecting runtime style + if (dom.toHex(value).toLowerCase() == '#000000') { + return; + } + } + + // Old IE won't calculate the font size so we need to do that manually + if (name == 'font-size') { + if (/em|%$/.test(value)) { + if (parentFontSize === 0) { + return; + } + + // Convert font size from em/% to px + value = parseFloat(value, 10) / (/%$/.test(value) ? 100 : 1); + value = (value * parentFontSize) + 'px'; + } + } + + if (name == "border" && value) { + previewCss += 'padding:0 2px;'; + } + + previewCss += name + ':' + value + ';'; + }); + + editor.fire('AfterPreviewFormats'); + + //previewCss += 'line-height:normal'; + + dom.remove(previewElm); + + return previewCss; + } + + function createFormats(formats) { + formats = formats.split(';'); + + var i = formats.length; + while (i--) { + formats[i] = formats[i].split('='); + } + + return formats; + } + + EditorManager.on('AddEditor', function(e) { + var editor = e.editor, formatMenu; + + function createFormatMenu() { + var count = 0, newFormats = []; + + var defaultStyleFormats = [ + {title: 'Headers', items: [ + {title: 'Header 1', format: 'h1'}, + {title: 'Header 2', format: 'h2'}, + {title: 'Header 3', format: 'h3'}, + {title: 'Header 4', format: 'h4'}, + {title: 'Header 5', format: 'h5'}, + {title: 'Header 6', format: 'h6'} + ]}, + + {title: 'Inline', items: [ + {title: 'Bold', icon: 'bold', format: 'bold'}, + {title: 'Italic', icon: 'italic', format: 'italic'}, + {title: 'Underline', icon: 'underline', format: 'underline'}, + {title: 'Strikethrough', icon: 'strikethrough', format: 'strikethrough'}, + {title: 'Superscript', icon: 'superscript', format: 'superscript'}, + {title: 'Subscript', icon: 'subscript', format: 'subscript'}, + {title: 'Code', icon: 'code', format: 'code'} + ]}, + + {title: 'Blocks', items: [ + {title: 'Paragraph', format: 'p'}, + {title: 'Blockquote', format: 'blockquote'}, + {title: 'Div', format: 'div'}, + {title: 'Pre', format: 'pre'} + ]}, + + {title: 'Alignment', items: [ + {title: 'Left', icon: 'alignleft', format: 'alignleft'}, + {title: 'Center', icon: 'aligncenter', format: 'aligncenter'}, + {title: 'Right', icon: 'alignright', format: 'alignright'}, + {title: 'Justify', icon: 'alignjustify', format: 'alignjustify'} + ]} + ]; + + function createMenu(formats) { + var menu = []; + + if (!formats) { + return; + } + + each(formats, function(format) { + var menuItem = { + text: format.title, + icon: format.icon + }; + + if (format.items) { + menuItem.menu = createMenu(format.items); + } else { + var formatName = format.format || "custom" + count++; + + if (!format.format) { + format.name = formatName; + newFormats.push(format); + } + + menuItem.textStyle = function() { + return getPreviewCss(editor, formatName); + }; + + menuItem.onclick = function() { + editor.execCommand('mceToggleFormat', false, formatName); + }; + } + + menu.push(menuItem); + }); + + return menu; + } + + editor.on('init', function() { + each(newFormats, function(format) { + editor.formatter.register(format.name, format); + }); + }); + + var menu = createMenu(editor.settings.style_formats || defaultStyleFormats); + + return menu; + } + + formatMenu = createFormatMenu(); + + // Simple format controls : + each({ + bold: 'Bold', + italic: 'Italic', + underline: 'Underline', + strikethrough: 'Strikethrough', + subscript: 'Subscript', + superscript: 'Superscript' + }, function(text, name) { + editor.addButton(name, { + tooltip: text, + onPostRender: function() { + var self = this; + + // TODO: Fix this + if (editor.formatter) { + editor.formatter.formatChanged(name, function(state) { + self.active(state); + }); + } else { + editor.on('init', function() { + editor.formatter.formatChanged(name, function(state) { + self.active(state); + }); + }); + } + }, + onclick: function() { + editor.execCommand('mceToggleFormat', false, name); + } + }); + }); + + // Simple command controls :[,] + each({ + outdent: ['Decrease indent', 'Outdent'], + indent: ['Increase indent', 'Indent'], + cut: ['Cut', 'Cut'], + copy: ['Copy', 'Copy'], + paste: ['Paste', 'Paste'], + help: ['Help', 'mceHelp'], + selectall: ['Select all', 'SelectAll'], + hr: ['Insert horizontal rule', 'InsertHorizontalRule'], + removeformat: ['Clear formatting', 'RemoveFormat'], + visualaid: ['Visual aids', 'mceToggleVisualAid'], + newdocument: ['New document', 'mceNewDocument'] + }, function(item, name) { + editor.addButton(name, { + tooltip: item[0], + cmd: item[1] + }); + }); + + // Simple command controls with format state + each({ + blockquote: ['Toggle blockquote', 'mceBlockQuote'], + numlist: ['Numbered list', 'InsertOrderedList'], + bullist: ['Bulleted list', 'InsertUnorderedList'], + subscript: ['Subscript', 'Subscript'], + superscript: ['Superscript', 'Superscript'], + alignleft: ['Align left', 'JustifyLeft'], + aligncenter: ['Align center', 'JustifyCenter'], + alignright: ['Align right', 'JustifyRight'], + alignjustify: ['Justify', 'JustifyFull'] + }, function(item, name) { + editor.addButton(name, { + tooltip: item[0], + cmd: item[1], + onPostRender: function() { + var self = this; + + // TODO: Fix this + if (editor.formatter) { + editor.formatter.formatChanged(name, function(state) { + self.active(state); + }); + } else { + editor.on('init', function() { + editor.formatter.formatChanged(name, function(state) { + self.active(state); + }); + }); + } + } + }); + }); + + function hasUndo() { + return editor.undoManager ? editor.undoManager.hasUndo() : false; + } + + function hasRedo() { + return editor.undoManager ? editor.undoManager.hasRedo() : false; + } + + function toggleUndoState() { + var self = this; + + self.disabled(!hasUndo()); + editor.on('Undo Redo AddUndo', function() { + self.disabled(!hasUndo()); + }); + } + + function toggleRedoState() { + var self = this; + + self.disabled(!hasRedo()); + editor.on('Undo Redo AddUndo', function() { + self.disabled(!hasRedo()); + }); + } + + function toggleVisualAidState() { + var self = this; + + editor.on('VisualAid', function(e) { + self.active(e.hasVisual); + }); + + self.active(editor.hasVisual); + } + + editor.addButton('forecolor', { + type: 'colorbutton', + tooltip: 'Text color', + onselect: function(e) { + editor.execCommand('ForeColor', false, e.value); + } + }); + + editor.addButton('backcolor', { + type: 'colorbutton', + tooltip: 'Background color', + onselect: function(e) { + editor.execCommand('HiliteColor', false, e.value); + } + }); + + editor.addButton('undo', { + tooltip: 'Undo', + onPostRender: toggleUndoState, + cmd: 'undo' + }); + + editor.addButton('redo', { + tooltip: 'Redo', + onPostRender: toggleRedoState, + cmd: 'redo' + }); + + editor.addMenuItem('newdocument', { + text: 'New document', + shortcut: 'Ctrl+N', + icon: 'newdocument', + cmd: 'mceNewDocument' + }); + + editor.addMenuItem('undo', { + text: 'Undo', + icon: 'undo', + shortcut: 'Ctrl+Z', + onPostRender: toggleUndoState, + cmd: 'undo' + }); + + editor.addMenuItem('redo', { + text: 'Redo', + icon: 'redo', + shortcut: 'Ctrl+Y', + onPostRender: toggleRedoState, + cmd: 'redo' + }); + + editor.addMenuItem('visualaid', { + text: 'Visual aids', + selectable: true, + onPostRender: toggleVisualAidState, + cmd: 'mceToggleVisualAid' + }); + + each({ + cut: ['Cut', 'Cut', 'Ctrl+X'], + copy: ['Copy', 'Copy', 'Ctrl+C'], + paste: ['Paste', 'Paste', 'Ctrl+V'], + selectall: ['Select all', 'SelectAll', 'Ctrl+A'], + bold: ['Bold', 'Bold', 'Ctrl+B'], + italic: ['Italic', 'Italic', 'Ctrl+I'], + underline: ['Underline', 'Underline'], + strikethrough: ['Strikethrough', 'Strikethrough'], + subscript: ['Subscript', 'Subscript'], + superscript: ['Superscript', 'Superscript'], + removeformat: ['Clear formatting', 'RemoveFormat'] + }, function(item, name) { + editor.addMenuItem(name, { + text: item[0], + icon: name, + shortcut: item[2], + cmd: item[1] + }); + }); + + editor.on('mousedown', function() { + FloatPanel.hideAll(); + }); + + function toggleFormat(e) { + if (e.control.settings.format) { + EditorManager.activeEditor.execCommand('mceToggleFormat', false, e.control.settings.format); + } + } + + Factory.add('styleselect', function(settings) { + var menu = [].concat(formatMenu); + + /* + menu.push({text: '-'}); + menu.push({ + text: 'Remove formatting', + icon: 'removeformat', + onclick: function() { + editor.execCommand('RemoveFormat'); + } + }); + */ + + return Factory.create('menubutton', Tools.extend({ + text: 'Formats', + menu: menu + }, settings)); + }); + + Factory.add('formatselect', function(settings) { + var items = [], blocks = createFormats( + 'Paragraph=p;' + + 'Address=address;' + + 'Pre=pre;' + + 'Header 1=h1;' + + 'Header 2=h2;' + + 'Header 3=h3;' + + 'Header 4=h4;' + + 'Header 5=h5;' + + 'Header 6=h6' + ); + + each(blocks, function(block) { + items.push({ + text: block[0], + format: block[1], + textStyle: function() { + return getPreviewCss(editor, block[1]); + } + }); + }); + + return Factory.create('listbox', Tools.extend({ + text: blocks[0][0], + menu: items, + onclick: toggleFormat + }, settings)); + }); + + Factory.add('fontselect', function(settings) { + var items = [], fonts = createFormats( + 'Andale Mono=andale mono,times;' + + 'Arial=arial,helvetica,sans-serif;' + + 'Arial Black=arial black,avant garde;' + + 'Book Antiqua=book antiqua,palatino;' + + 'Comic Sans MS=comic sans ms,sans-serif;' + + 'Courier New=courier new,courier;' + + 'Georgia=georgia,palatino;' + + 'Helvetica=helvetica;' + + 'Impact=impact,chicago;' + + 'Symbol=symbol;' + + 'Tahoma=tahoma,arial,helvetica,sans-serif;' + + 'Terminal=terminal,monaco;' + + 'Times New Roman=times new roman,times;' + + 'Trebuchet MS=trebuchet ms,geneva;' + + 'Verdana=verdana,geneva;' + + 'Webdings=webdings;' + + 'Wingdings=wingdings,zapf dingbats' + ); + + each(fonts, function(font) { + items.push({ + text: font[0], + format: font[1], + style: font[1].indexOf('dings') == -1 ? 'font-family:' + font[1] : '' + }); + }); + + return Factory.create('listbox', Tools.extend({ + text: 'Font Family', + menu: items, + onclick: function(e) { + if (e.control.settings.format) { + EditorManager.activeEditor.execCommand('FontName', false, e.control.settings.format); + } + } + }, settings)); + }); + + Factory.add('fontsizeselect', function(settings) { + var items = []; + + each('8pt 10pt 12pt 14pt 18pt 24pt 36pt'.split(' '), function(item) { + items.push({text: item, format: item}); + }); + + return Factory.create('listbox', Tools.extend({ + text: 'Font Sizes', + menu: items, + onclick: function(e) { + if (e.control.settings.format) { + EditorManager.activeEditor.execCommand('FontSize', false, e.control.settings.format); + } + } + }, settings)); + }); + + editor.addMenuItem('formats', { + text: 'Formats', + menu: formatMenu + }); + }); +}); + +// Included from: js/tinymce/classes/ui/GridLayout.js + +/** + * GridLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.GridLayout + * @extends tinymce.ui.AbsoluteLayout + */ +define("tinymce/ui/GridLayout", [ + "tinymce/ui/AbsoluteLayout" +], function(AbsoluteLayout) { + "use strict"; + + return AbsoluteLayout.extend({ + recalc: function(container) { + var settings = container.settings, rows, cols, items, contLayoutRect, width, height, rect, + ctrlLayoutRect, ctrl, x, y, posX, posY, ctrlSettings, contPaddingBox, align, spacingH, spacingV, alignH, alignV, maxX, maxY, + colWidths = [], rowHeights = [], ctrlMinWidth, ctrlMinHeight, alignX, alignY, availableWidth, availableHeight; + + // Get layout settings + settings = container.settings; + items = container.items().filter(':visible'); + contLayoutRect = container.layoutRect(); + cols = settings.columns || Math.ceil(Math.sqrt(items.length)); + rows = Math.ceil(items.length / cols); + spacingH = settings.spacingH || settings.spacing || 0; + spacingV = settings.spacingV || settings.spacing || 0; + alignH = settings.alignH || settings.align; + alignV = settings.alignV || settings.align; + contPaddingBox = container._paddingBox; + + // Zero padd columnWidths + for (x = 0; x < cols; x++) { + colWidths.push(0); + } + + // Zero padd rowHeights + for (y = 0; y < rows; y++) { + rowHeights.push(0); + } + + // Calculate columnWidths and rowHeights + for (y = 0; y < rows; y++) { + for (x = 0; x < cols; x++) { + ctrl = items[y * cols + x]; + + // Out of bounds + if (!ctrl) { + break; + } + + ctrlLayoutRect = ctrl.layoutRect(); + ctrlMinWidth = ctrlLayoutRect.minW; + ctrlMinHeight = ctrlLayoutRect.minH; + + colWidths[x] = ctrlMinWidth > colWidths[x] ? ctrlMinWidth : colWidths[x]; + rowHeights[y] = ctrlMinHeight > rowHeights[y] ? ctrlMinHeight : rowHeights[y]; + } + } + + // Calculate maxX + availableWidth = contLayoutRect.innerW - contPaddingBox.left - contPaddingBox.right; + for (maxX = 0, x = 0; x < cols; x++) { + maxX += colWidths[x] + (x > 0 ? spacingH : 0); + availableWidth -= (x > 0 ? spacingH : 0) + colWidths[x]; + } + + // Calculate maxY + availableHeight = contLayoutRect.innerH - contPaddingBox.top - contPaddingBox.bottom; + for (maxY = 0, y = 0; y < rows; y++) { + maxY += rowHeights[y] + (y > 0 ? spacingV : 0); + availableHeight -= (y > 0 ? spacingV : 0) + rowHeights[y]; + } + + maxX += contPaddingBox.left + contPaddingBox.right; + maxY += contPaddingBox.top + contPaddingBox.bottom; + + // Calculate minW/minH + rect = {}; + rect.minW = maxX + (contLayoutRect.w - contLayoutRect.innerW); + rect.minH = maxY + (contLayoutRect.h - contLayoutRect.innerH); + + rect.contentW = rect.minW - contLayoutRect.deltaW; + rect.contentH = rect.minH - contLayoutRect.deltaH; + rect.minW = Math.min(rect.minW, contLayoutRect.maxW); + rect.minH = Math.min(rect.minH, contLayoutRect.maxH); + rect.minW = Math.max(rect.minW, contLayoutRect.startMinWidth); + rect.minH = Math.max(rect.minH, contLayoutRect.startMinHeight); + + // Resize container container if minSize was changed + if (contLayoutRect.autoResize && (rect.minW != contLayoutRect.minW || rect.minH != contLayoutRect.minH)) { + rect.w = rect.minW; + rect.h = rect.minH; + + container.layoutRect(rect); + this.recalc(container); + + // Forced recalc for example if items are hidden/shown + if (container._lastRect === null) { + var parentCtrl = container.parent(); + if (parentCtrl) { + parentCtrl._lastRect = null; + parentCtrl.recalc(); + } + } + + return; + } + + // Update contentW/contentH so absEnd moves correctly + if (contLayoutRect.autoResize) { + rect = container.layoutRect(rect); + rect.contentW = rect.minW - contLayoutRect.deltaW; + rect.contentH = rect.minH - contLayoutRect.deltaH; + } + + var flexV; + + if (settings.packV == 'start') { + flexV = 0; + } else { + flexV = availableHeight > 0 ? Math.floor(availableHeight / rows) : 0; + } + + // Calculate totalFlex + var totalFlex = 0; + var flexWidths = settings.flexWidths; + if (flexWidths) { + for (x = 0; x < flexWidths.length; x++) { + totalFlex += flexWidths[x]; + } + } else { + totalFlex = cols; + } + + // Calculate new column widths based on flex values + var ratio = availableWidth / totalFlex; + for (x = 0; x < cols; x++) { + colWidths[x] += flexWidths ? Math.ceil(flexWidths[x] * ratio) : ratio; + } + + // Move/resize controls + posY = contPaddingBox.top; + for (y = 0; y < rows; y++) { + posX = contPaddingBox.left; + height = rowHeights[y] + flexV; + + for (x = 0; x < cols; x++) { + ctrl = items[y * cols + x]; + + // No more controls to render then break + if (!ctrl) { + break; + } + + // Get control settings and calculate x, y + ctrlSettings = ctrl.settings; + ctrlLayoutRect = ctrl.layoutRect(); + width = colWidths[x]; + alignX = alignY = 0; + ctrlLayoutRect.x = posX; + ctrlLayoutRect.y = posY; + + // Align control horizontal + align = ctrlSettings.alignH || alignH; + if (align == "center") { + ctrlLayoutRect.x = posX + (width / 2) - (ctrlLayoutRect.w / 2); + } else if (align == "right") { + ctrlLayoutRect.x = posX + width - ctrlLayoutRect.w; + } else if (align == "stretch") { + ctrlLayoutRect.w = width; + } + + // Align control vertical + align = ctrlSettings.alignV || alignV; + if (align == "center") { + ctrlLayoutRect.y = posY + (height / 2) - (ctrlLayoutRect.h / 2); + } else if (align == "bottom") { + ctrlLayoutRect.y = posY + height - ctrlLayoutRect.h; + } else if (align == "stretch") { + ctrlLayoutRect.h = height; + } + + ctrl.layoutRect(ctrlLayoutRect); + + posX += width + spacingH; + + if (ctrl.recalc) { + ctrl.recalc(); + } + } + + posY += height + spacingV; + } + } + }); +}); + +// Included from: js/tinymce/classes/ui/Iframe.js + +/** + * Iframe.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/*jshint scripturl:true */ + +/** + * .. + * + * @-x-less Iframe.less + * @class tinymce.ui.Iframe + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/Iframe", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + renderHtml: function() { + var self = this; + + self.addClass('iframe'); + self.canFocus = false; + + return ( + '' + ); + }, + + src: function(src) { + this.getEl().src = src; + }, + + html: function(html) { + this.getEl().contentWindow.document.body.innerHTML = html; + return this; + } + }); +}); + +// Included from: js/tinymce/classes/ui/Label.js + +/** + * Label.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Label.less + * @class tinymce.ui.Label + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Label", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('widget'); + self.addClass('label'); + + if (settings.multiline) { + self.addClass('autoscroll'); + } + + if (settings.strong) { + self.addClass('strong'); + } + }, + + initLayoutRect: function() { + var self = this, layoutRect = self._super(); + + if (self.settings.multiline) { + // Check if the text fits within maxW if not then try word wrapping it + if (self.getEl().offsetWidth > layoutRect.maxW) { + layoutRect.minW = layoutRect.maxW; + self.addClass('multiline'); + } + + self.getEl().style.width = layoutRect.minW + 'px'; + layoutRect.startMinH = layoutRect.h = layoutRect.minH = Math.min(layoutRect.maxH, self.getEl().offsetHeight); + } + + return layoutRect; + }, + + disabled: function(state) { + var self = this, undef; + + if (state !== undef) { + self.toggleClass('label-disabled', state); + + if (self._rendered) { + self.getEl()[0].className = self.classes(); + } + } + + return self._super(state); + }, + + repaint: function() { + var self = this; + + if (!self.settings.multiline) { + self.getEl().style.lineHeight = self.layoutRect().h + 'px'; + } + + return self._super(); + }, + + text: function(text) { + var self = this; + + if (self._rendered && text) { + self.getEl().innerHTML = self.encode(text); + } + + return self._super(text); + }, + + /** + * ... + * + * @method render + */ + renderHtml: function() { + var self = this, forId = self.settings.forId; + + return ( + '' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Toolbar.js + +/** + * Toolbar.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.Toolbar + * @extends tinymce.ui.Container + */ +define("tinymce/ui/Toolbar", [ + "tinymce/ui/Container", + "tinymce/ui/KeyboardNavigation" +], function(Container, KeyboardNavigation) { + "use strict"; + + return Container.extend({ + Defaults: { + role: 'toolbar', + layout: 'flow' + }, + + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('toolbar'); + }, + + postRender: function() { + var self = this; + + self.items().addClass('toolbar-item'); + + self.keyNav = new KeyboardNavigation({ + root: self, + enableLeftRight: true + }); + + return self._super(); + } + }); +}); + +// Included from: js/tinymce/classes/ui/MenuBar.js + +/** + * MenuBar.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less MenuBar.less + * @class tinymce.ui.MenuBar + * @extends tinymce.ui.Container + */ +define("tinymce/ui/MenuBar", [ + "tinymce/ui/Toolbar" +], function(Toolbar) { + "use strict"; + + return Toolbar.extend({ + Defaults: { + role: 'menubar', + containerCls: 'menubar', + defaults: { + type: 'menubutton' + } + } + }); +}); + +// Included from: js/tinymce/classes/ui/MenuButton.js + +/** + * MenuButton.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less MenuButton.less + * @class tinymce.ui.MenuButton + * @extends tinymce.ui.Button + */ +define("tinymce/ui/MenuButton", [ + "tinymce/ui/Button", + "tinymce/ui/Factory", + "tinymce/ui/MenuBar" +], function(Button, Factory, MenuBar) { + "use strict"; + + // TODO: Maybe add as some global function + function isChildOf(node, parent) { + while (node) { + if (parent === node) { + return true; + } + + node = node.parentNode; + } + + return false; + } + + var MenuButton = Button.extend({ + init: function(settings) { + var self = this; + + self._renderOpen = true; + self._super(settings); + + self.addClass('menubtn'); + + self.aria('haspopup', true); + self.hasPopup = true; + }, + + showMenu: function() { + var self = this, settings = self.settings, menu; + + if (!self.menu) { + menu = settings.menu || []; + + // Is menu array then auto constuct menu control + if (menu.length) { + menu = { + type: 'menu', + items: menu + }; + } else { + menu.type = menu.type || 'menu'; + } + + self.menu = Factory.create(menu).parent(self).renderTo(self.getContainerElm()); + self.fire('createmenu'); + self.menu.reflow(); + self.menu.on('cancel', function(e) { + if (e.control === self.menu) { + self.focus(); + } + }); + + self.menu.on('show hide', function(e) { + if (e.control == self.menu) { + self.activeMenu(e.type == 'show'); + } + }).fire('show'); + + self.aria('expanded', true); + } + + self.menu.show(); + self.menu.layoutRect({w: self.layoutRect().w}); + self.menu.moveRel(self.getEl(), 'bl-tl'); + }, + + hideMenu: function() { + var self = this; + + if (self.menu) { + self.menu.items().each(function(item) { + if (item.hideMenu) { + item.hideMenu(); + } + }); + + self.menu.hide(); + self.aria('expanded', false); + } + }, + + activeMenu: function(state) { + this.toggleClass('active', state); + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; + + self.aria('role', self.parent() instanceof MenuBar ? 'menuitem' : 'button'); + + return ( + '
    ' + + '' + + '
    ' + ); + }, + + postRender: function() { + var self = this; + + self.on('click', function(e) { + if (e.control === self && isChildOf(e.target, self.getEl())) { + self.showMenu(); + + if (e.keyboard) { + self.menu.items()[0].focus(); + } + } + }); + + self.on('mouseenter', function(e) { + var overCtrl = e.control, parent = self.parent(), hasVisibleSiblingMenu; + + if (overCtrl && parent && overCtrl instanceof MenuButton && overCtrl.parent() == parent) { + parent.items().filter('MenuButton').each(function(ctrl) { + if (ctrl.hideMenu && ctrl != overCtrl) { + if (ctrl.menu && ctrl.menu.visible()) { + hasVisibleSiblingMenu = true; + } + + ctrl.hideMenu(); + } + }); + + if (hasVisibleSiblingMenu) { + overCtrl.showMenu(); + } + } + }); + + return self._super(); + }, + + text: function(text) { + var self = this, i, children; + + if (self._rendered) { + children = self.getEl('open').childNodes; + for (i = 0; i < children.length; i++) { + if (children[i].nodeType == 3) { + children[i].data = text; + } + } + } + + return this._super(text); + }, + + remove: function() { + this._super(); + + if (this.menu) { + this.menu.remove(); + } + } + }); + + return MenuButton; +}); + +// Included from: js/tinymce/classes/ui/ListBox.js + +/** + * ListBox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ListBox.less + * @class tinymce.ui.ListBox + * @extends tinymce.ui.MenuButton + */ +define("tinymce/ui/ListBox", [ + "tinymce/ui/MenuButton" +], function(MenuButton) { + "use strict"; + + return MenuButton.extend({ + init: function(settings) { + var self = this, values, i, selected, selectedText; + + self._values = values = settings.values; + if (values) { + for (i = 0; i < values.length; i++) { + selected = values[i].selected || settings.value === values[i].value; + + if (selected) { + selectedText = selectedText || values[i].text; + self._value = values[i].value; + } + } + + settings.menu = values; + } + + settings.text = settings.text || selectedText || values[0].text; + + self._super(settings); + self.addClass('listbox'); + + self.on('select', function(e) { + if (settings.multiple) { + e.control.active(!e.control.active()); + } else { + self.value(e.control.settings.value); + } + }); + }, + + value: function(value) { + var self = this, active, selectedText, menu, i; + + if (typeof(value) != "undefined") { + if (self.menu) { + self.menu.items().each(function(ctrl) { + active = ctrl.value() === value; + + if (active) { + selectedText = selectedText || ctrl.text(); + } + + ctrl.active(active); + }); + } else { + menu = self.settings.menu; + for (i = 0; i < menu.length; i++) { + active = menu[i].value == value; + + if (active) { + selectedText = selectedText || menu[i].text; + } + + menu[i].active = active; + } + } + + self.text(selectedText); + } + + return self._super(value); + } + }); +}); + +// Included from: js/tinymce/classes/ui/MenuItem.js + +/** + * MenuItem.js + * + * Copyright 2003-2013, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less MenuItem.less + * @class tinymce.ui.MenuItem + * @extends tinymce.ui.Control + */ +define("tinymce/ui/MenuItem", [ + "tinymce/ui/Widget", + "tinymce/ui/Factory" +], function(Widget, Factory) { + "use strict"; + + return Widget.extend({ + Defaults: { + border: 0, + role: 'menuitem' + }, + + init: function(settings) { + var self = this; + + self.hasPopup = true; + + self._super(settings); + + settings = self.settings; + + self.addClass('menu-item'); + + if (settings.menu) { + self.addClass('menu-item-expand'); + } + + if (self._text === '-' || self._text === '|') { + self.addClass('menu-item-sep'); + self.aria('role', 'separator'); + self.canFocus = false; + self._text = '-'; + } + + if (settings.selectable) { + self.aria('role', 'menuitemcheckbox'); + self.aria('checked', true); + self.addClass('menu-item-checkbox'); + settings.icon = 'selected'; + } + + self.on('mousedown', function(e) { + e.preventDefault(); + }); + + self.on('mouseenter click', function(e) { + if (e.control === self) { + if (!settings.menu && e.type === 'click') { + self.parent().hideAll(); + self.fire('cancel'); + self.fire('select'); + } else { + self.showMenu(); + + if (e.keyboard) { + setTimeout(function() { + self.menu.items()[0].focus(); + }, 0); + } + } + } + }); + + if (settings.menu) { + self.aria('haspopup', true); + } + }, + + hasMenus: function() { + return !!this.settings.menu; + }, + + showMenu: function() { + var self = this, settings = self.settings, menu; + + self.parent().items().each(function(ctrl) { + if (ctrl !== self) { + ctrl.hideMenu(); + } + }); + + if (settings.menu) { + if (!self.menu) { + menu = settings.menu; + + // Is menu array then auto constuct menu control + if (menu.length) { + menu = { + type: 'menu', + items: menu + }; + } else { + menu.type = menu.type || 'menu'; + } + + self.menu = Factory.create(menu).parent(self).renderTo(self.getContainerElm()); + self.menu.reflow(); + self.menu.fire('show'); + self.menu.on('cancel', function() { + self.focus(); + }); + + self.menu.on('hide', function(e) { + if (e.control === self.menu) { + self.removeClass('selected'); + } + }); + } else { + self.menu.show(); + } + + self.menu._parentMenu = self.parent(); + + self.menu.addClass('menu-sub'); + self.menu.moveRel(self.getEl(), 'tr-tl'); + self.addClass('selected'); + self.aria('expanded', true); + } + }, + + hideMenu: function() { + var self = this; + + if (self.menu) { + self.menu.items().each(function(item) { + if (item.hideMenu) { + item.hideMenu(); + } + }); + + self.menu.hide(); + self.aria('expanded', false); + } + + return self; + }, + + renderHtml: function() { + var self = this, id = self._id, settings = self.settings, prefix = self.classPrefix, text = self.encode(self._text); + var icon = self.settings.icon; + + if (icon) { + self.parent().addClass('menu-has-icons'); + } + + icon = prefix + 'ico ' + prefix + 'i-' + (self.settings.icon || 'none'); + + return ( + '
    ' + + (text !== '-' ? ' ' : '') + + (text !== '-' ? '' + text + '' : '') + + (settings.shortcut ? '
    ' + + settings.shortcut + '
    ' : '') + + (settings.menu ? '
    ' : '') + + '
    ' + ); + }, + + postRender: function() { + var self = this, settings = self.settings; + + var textStyle = settings.textStyle; + if (typeof(textStyle) == "function") { + textStyle = textStyle(); + } + + if (textStyle) { + var textElm = self.getEl('text'); + if (textElm) { + textElm.setAttribute('style', textStyle); + } + } + + return self._super(); + }, + + remove: function() { + this._super(); + + if (this.menu) { + this.menu.remove(); + } + } + }); +}); + +// Included from: js/tinymce/classes/ui/Menu.js + +/** + * Menu.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Menu.less + * @class tinymce.ui.Menu + * @extends tinymce.ui.FloatPanel + */ +define("tinymce/ui/Menu", [ + "tinymce/ui/FloatPanel", + "tinymce/ui/KeyboardNavigation", + "tinymce/ui/MenuItem" +], function(FloatPanel, KeyboardNavigation, MenuItem) { + "use strict"; + + var Menu = FloatPanel.extend({ + Defaults: { + defaultType: 'menuitem', + border: 1, + layout: 'stack', + role: 'menu' + }, + + init: function(settings) { + var self = this; + + settings.autohide = true; + + self._super(settings); + self.addClass('menu'); + + self.keyNav = new KeyboardNavigation({ + root: self, + enableUpDown: true, + enableLeftRight: true, + + leftAction: function() { + if (self.parent() instanceof MenuItem) { + self.keyNav.cancel(); + } + }, + + onCancel: function() { + self.fire('cancel', {}, false); + self.hide(); + } + }); + }, + + repaint: function() { + this.toggleClass('menu-align', true); + + this._super(); + + this.getEl().style.height = ''; + this.getEl('body').style.height = ''; + + return this; + }, + + cancel: function() { + var self = this; + + self.hideAll(); + self.fire('cancel'); + self.fire('select'); + }, + + hideAll: function() { + var self = this; + + this.find('menuitem').exec('hideMenu'); + + return self._super(); + }, + + preRender: function() { + var self = this; + + self.items().each(function(ctrl) { + var settings = ctrl.settings; + + if (settings.icon || settings.selectable) { + self._hasIcons = true; + return false; + } + }); + + return self._super(); + } + }); + + return Menu; +}); + +// Included from: js/tinymce/classes/ui/PanelButton.js + +/** + * MenuButton.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.MenuButton + * @extends tinymce.ui.Button + */ +define("tinymce/ui/PanelButton", [ + "tinymce/ui/Button", + "tinymce/ui/FloatPanel" +], function(Button, FloatPanel) { + "use strict"; + + var PanelButton = Button.extend({ + showPanel: function() { + var self = this, settings = self.settings; + + settings.panel.popover = true; + self.active(true); + + if (!self.panel) { + self.panel = new FloatPanel(settings.panel).on('hide', function() { + self.active(false); + }).parent(self).renderTo(self.getContainerElm()).reflow().moveRel(self.getEl(), settings.popoverAlign || 'bc-tc'); + } else { + self.panel.show(); + } + }, + + hidePanel: function() { + var self = this; + + if (self.panel) { + self.panel.hide(); + } + }, + + postRender: function() { + var self = this; + + self.on('click', function(e) { + if (e.control === self) { + self.showPanel(); + } + }); + + return self._super(); + } + }); + + return PanelButton; +}); + +// Included from: js/tinymce/classes/ui/Radio.js + +/** + * Radio.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Radio.less + * @class tinymce.ui.Radio + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/Radio", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + Defaults: { + classes: "radio", + checked: false + }, + + init: function(settings) { + var self = this; + + self._super(settings); + + self.on('click', function(e) { + e.preventDefault(); + + if (!self.disabled() && !self.checked()) { + self.parent().items().filter('radio:checked').exec('checked', false); + self.checked(true); + } + }); + + self.checked(settings.checked); + }, + + checked: function(state) { + var self = this; + + if (typeof state != "undefined") { + if (state) { + self.addClass('checked'); + } else { + self.removeClass('checked'); + } + + self._checked = state; + + return self; + } + + return self._checked; + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + + return ( + '' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/RadioGroup.js + +/** + * RadioGroup.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.RadioGroup + * @extends tinymce.ui.Container + */ +define("tinymce/ui/RadioGroup", [ + "tinymce/ui/Container" +], function(Container) { + "use strict"; + + return Container.extend({}); +}); + +// Included from: js/tinymce/classes/ui/ResizeHandle.js + +/** + * ResizeHandle.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ResizeHandle.less + * @class tinymce.ui.ResizeHandle + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/ResizeHandle", [ + "tinymce/ui/Widget", + "tinymce/ui/DragHelper", + "tinymce/ui/DomUtils" +], function(Widget, DragHelper, DomUtils) { + "use strict"; + + return Widget.extend({ + renderHtml: function() { + var self = this, prefix = self.classPrefix; + + self.addClass('resizehandle'); + + if (self.settings.both) { + self.addClass('resizehandle-both'); + } + + self.canFocus = false; + + return ( + '
    ' + ); + }, + + postRender: function() { + var self = this, iframeStartSize, editor = self.settings.editor; + + self._super(); + + function getSize(elm) { + return { + width: elm.clientWidth, + height: elm.clientHeight + }; + } + + function resizeIframe(width, height) { + var containerElm, iframeElm, containerSize, iframeSize, settings = editor.settings; + + containerElm = editor.getContainer(); + iframeElm = editor.getContentAreaContainer().firstChild; + containerSize = getSize(containerElm); + iframeSize = getSize(iframeElm); + + width = Math.max(settings.min_width || 100, width); + height = Math.max(settings.min_height || 100, height); + width = Math.min(settings.max_width || 0xFFFF, width); + height = Math.min(settings.max_height || 0xFFFF, height); + + if (self.settings.both) { + DomUtils.css(containerElm, 'width', width + (containerSize.width - iframeSize.width)); + } + + DomUtils.css(containerElm, 'height', height + (containerSize.height - iframeSize.height)); + + if (self.settings.both) { + DomUtils.css(iframeElm, 'width', width); + } + + DomUtils.css(iframeElm, 'height', height); + + editor.fire('ResizeEditor'); + } + + self.resizeDragHelper = new DragHelper(this._id, { + start: function() { + iframeStartSize = getSize(editor.getContentAreaContainer().firstChild); + }, + + drag: function(evt) { + resizeIframe(iframeStartSize.width + evt.deltaX, iframeStartSize.height + evt.deltaY); + }, + + end: function() { + } + }); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Spacer.js + +/** + * Spacer.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Spacer.less + * @class tinymce.ui.Spacer + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/Spacer", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + renderHtml: function() { + var self = this; + + self.addClass('spacer'); + self.canFocus = false; + + return '
    '; + } + }); +}); + +// Included from: js/tinymce/classes/ui/SplitButton.js + +/** + * SplitButton.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less SplitButton.less + * @class tinymce.ui.SplitButton + * @extends tinymce.ui.Button + */ +define("tinymce/ui/SplitButton", [ + "tinymce/ui/MenuButton", + "tinymce/dom/DOMUtils" +], function(MenuButton, DomUtils) { + var DOM = DomUtils.DOM; + + return MenuButton.extend({ + Defaults: { + classes: "widget btn splitbtn", + role: "splitbutton" + }, + + repaint: function() { + var self = this, elm = self.getEl(), rect = self.layoutRect(), mainButtonElm, menuButtonElm, btnStyle; + + self._super(); + + mainButtonElm = elm.firstChild; + menuButtonElm = elm.lastChild; + + DOM.css(mainButtonElm, { + width: rect.w - menuButtonElm.offsetWidth, + height: rect.h - 2 + }); + + DOM.css(menuButtonElm, { + height: rect.h - 2 + }); + + btnStyle = mainButtonElm.firstChild.style; + btnStyle.width = btnStyle.height = "100%"; + + btnStyle = menuButtonElm.firstChild.style; + btnStyle.width = btnStyle.height = "100%"; + + return self; + }, + + activeMenu: function(state) { + var self = this; + + DOM.toggleClass(self.getEl().lastChild, self.classPrefix + 'active', state); + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; + + return ( + '
    ' + + '' + + '' + + '
    ' + ); + }, + + postRender: function() { + var self = this, onClickHandler = self.settings.onclick; + + self.on('click', function(e) { + if (e.control == this && !DOM.getParent(e.target, '.' + this.classPrefix + 'open')) { + e.stopImmediatePropagation(); + onClickHandler.call(this, e); + } + }); + + delete self.settings.onclick; + + return self._super(); + } + }); +}); + +// Included from: js/tinymce/classes/ui/StackLayout.js + +/** + * StackLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less StackLayout.less + * @class tinymce.ui.StackLayout + * @extends tinymce.ui.FlowLayout + */ +define("tinymce/ui/StackLayout", [ + "tinymce/ui/FlowLayout" +], function(FlowLayout) { + "use strict"; + + return FlowLayout.extend({ + Defaults: { + containerClass: 'stack-layout', + controlClass: 'stack-layout-item', + endClass : 'break' + } + }); +}); + +// Included from: js/tinymce/classes/ui/TabPanel.js + +/** + * TabPanel.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less TabPanel.less + * @class tinymce.ui.TabPanel + * @extends tinymce.ui.Panel + */ +define("tinymce/ui/TabPanel", [ + "tinymce/ui/Panel", + "tinymce/ui/DomUtils" +], function(Panel, DomUtils) { + "use stict"; + + return Panel.extend({ + lastIdx: 0, + + Defaults: { + layout: 'absolute', + defaults: { + type: 'panel' + } + }, + + activateTab: function(idx) { + if (this.activeTabId) { + DomUtils.removeClass(this.getEl(this.activeTabId), this.classPrefix + 'active'); + } + + this.activeTabId = 't' + idx; + + DomUtils.addClass(this.getEl('t' + idx), this.classPrefix + 'active'); + + if (idx != this.lastIdx) { + this.items()[this.lastIdx].hide(); + this.lastIdx = idx; + } + + this.items()[idx].show().fire('showtab'); + this.reflow(); + }, + + renderHtml: function() { + var self = this, layout = self._layout, tabsHtml = '', prefix = self.classPrefix; + + self.preRender(); + layout.preRender(self); + + self.items().each(function(ctrl, i) { + tabsHtml += ( + '
    ' + + ctrl.settings.title + + '
    ' + ); + }); + + return ( + '
    ' + + '
    ' + + tabsHtml + + '
    ' + + '
    ' + + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + }, + + postRender: function() { + var self = this; + + self._super(); + + self.settings.activeTab = self.settings.activeTab || 0; + self.activateTab(self.settings.activeTab); + + this.on('click', function(e) { + var targetParent = e.target.parentNode; + + if (e.target.parentNode.id == self._id + '-head') { + var i = targetParent.childNodes.length; + + while (i--) { + if (targetParent.childNodes[i] == e.target) { + self.activateTab(i); + } + } + } + }); + }, + + initLayoutRect: function() { + var self = this, rect, minW, minH; + + minW = minH = 0; + self.items().each(function(item, i) { + minW = Math.max(minW, item.layoutRect().minW); + minH = Math.max(minH, item.layoutRect().minH); + if (self.settings.activeTab != i) { + item.hide(); + } + }); + + self.items().each(function(ctrl) { + ctrl.settings.x = 0; + ctrl.settings.y = 0; + ctrl.settings.w = minW; + ctrl.settings.h = minH; + + ctrl.layoutRect({ + x: 0, + y: 0, + w: minW, + h: minH + }); + }); + + var headH = self.getEl('head').offsetHeight; + + self.settings.minWidth = minW; + self.settings.minHeight = minH + headH; + + rect = self._super(); + rect.deltaH += self.getEl('head').offsetHeight; + rect.innerH = rect.h - rect.deltaH; + + return rect; + } + }); +}); + +// Included from: js/tinymce/classes/ui/TextBox.js + +/** + * TextBox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less TextBox.less + * @class tinymce.ui.TextBox + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/TextBox", [ + "tinymce/ui/Widget", + "tinymce/ui/DomUtils" +], function(Widget, DomUtils) { + "use strict"; + + return Widget.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + + self._value = settings.value || ''; + self.addClass('textbox'); + + if (settings.multiline) { + self.addClass('multiline'); + } else { + // TODO: Rework this + self.on('keydown', function(e) { + if (e.keyCode == 13) { + self.parents().reverse().each(function(ctrl) { + e.preventDefault(); + + if (ctrl.submit) { + ctrl.submit(); + return false; + } + }); + } + }); + } + }, + + value: function(value) { + var self = this; + + if (typeof(value) != "undefined") { + self._value = value; + + if (self._rendered) { + self.getEl().value = value; + } + + return self; + } + + if (self._rendered) { + return self.getEl().value; + } + + return self._value; + }, + + repaint: function() { + var self = this, style, rect, borderBox, borderW = 0, borderH = 0, lastRepaintRect; + + style = self.getEl().style; + rect = self._layoutRect; + lastRepaintRect = self._lastRepaintRect || {}; + + borderBox = self._borderBox; + borderW = borderBox.left + borderBox.right + 8; + borderH = borderBox.top + borderBox.bottom + (self.settings.multiline ? 8 : 0); + + if (rect.x !== lastRepaintRect.x) { + style.left = rect.x + 'px'; + lastRepaintRect.x = rect.x; + } + + if (rect.y !== lastRepaintRect.y) { + style.top = rect.y + 'px'; + lastRepaintRect.y = rect.y; + } + + if (rect.w !== lastRepaintRect.w) { + style.width = (rect.w - borderW) + 'px'; + lastRepaintRect.w = rect.w; + } + + if (rect.h !== lastRepaintRect.h) { + style.height = (rect.h - borderH) + 'px'; + lastRepaintRect.h = rect.h; + } + + /*if (!self.settings.multiline) { + //style.lineHeight = (rect.h - borderH) + 'px'; + }*/ + + self._lastRepaintRect = lastRepaintRect; + self.fire('repaint', {}, false); + + return self; + }, + + renderHtml: function() { + var self = this, id = self._id, settings = self.settings, value = self.encode(self._value, false), extraAttrs = ''; + + if ("spellcheck" in settings) { + extraAttrs += ' spellcheck="' + settings.spellcheck + '"'; + } + + if (settings.maxLength) { + extraAttrs += ' maxlength="' + settings.maxLength + '"'; + } + + if (settings.size) { + extraAttrs += ' size="' + settings.size + '"'; + } + + if (settings.subtype) { + extraAttrs += ' type="' + settings.subtype + '"'; + } + + if (settings.multiline) { + return ( + '' + ); + } + + return ''; + }, + + postRender: function() { + var self = this; + + DomUtils.on(self.getEl(), 'change', function(e) { + self.fire('change', e); + }); + + return self._super(); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Throbber.js + +/** + * Throbber.js + * + * Copyright 2003-2013, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Throbber.less + * @class tinymce.ui.Throbber + */ +define("tinymce/ui/Throbber", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + return function(elm) { + var self = this, state; + + self.show = function(time) { + self.hide(); + + state = true; + + window.setTimeout(function() { + if (state) { + elm.appendChild(DomUtils.createFragment('
    ')); + } + }, time || 0); + + return self; + }, + + self.hide = function() { + var child = elm.lastChild; + + if (child && child.className.indexOf('throbber') != -1) { + child.parentNode.removeChild(child); + } + + state = false; + + return self; + }; + }; +}); + +expose(["tinymce/dom/Sizzle","tinymce/html/Styles","tinymce/dom/EventUtils","tinymce/dom/TreeWalker","tinymce/util/Tools","tinymce/dom/Range","tinymce/html/Entities","tinymce/Env","tinymce/dom/DOMUtils","tinymce/dom/ScriptLoader","tinymce/AddOnManager","tinymce/html/Node","tinymce/html/Schema","tinymce/html/SaxParser","tinymce/html/DomParser","tinymce/html/Writer","tinymce/html/Serializer","tinymce/dom/Serializer","tinymce/dom/TridentSelection","tinymce/util/VK","tinymce/dom/ControlSelection","tinymce/dom/Selection","tinymce/dom/RangeUtils","tinymce/Formatter","tinymce/UndoManager","tinymce/EnterKey","tinymce/ForceBlocks","tinymce/EditorCommands","tinymce/util/URI","tinymce/util/Class","tinymce/ui/Selector","tinymce/ui/Collection","tinymce/ui/DomUtils","tinymce/ui/Control","tinymce/ui/Factory","tinymce/ui/Container","tinymce/ui/DragHelper","tinymce/ui/Scrollable","tinymce/ui/Panel","tinymce/ui/Movable","tinymce/ui/Resizable","tinymce/ui/FloatPanel","tinymce/ui/KeyboardNavigation","tinymce/ui/Window","tinymce/ui/MessageBox","tinymce/WindowManager","tinymce/util/Quirks","tinymce/util/Observable","tinymce/Shortcuts","tinymce/Editor","tinymce/EditorManager","tinymce/LegacyInput","tinymce/util/XHR","tinymce/util/JSON","tinymce/util/JSONRequest","tinymce/util/JSONP","tinymce/util/LocalStorage","tinymce/Compat","tinymce/ui/Layout","tinymce/ui/AbsoluteLayout","tinymce/ui/Tooltip","tinymce/ui/Widget","tinymce/ui/Button","tinymce/ui/ButtonGroup","tinymce/ui/Checkbox","tinymce/ui/CheckboxGroup","tinymce/ui/ColorButton","tinymce/ui/ComboBox","tinymce/ui/Path","tinymce/ui/ElementPath","tinymce/ui/FormItem","tinymce/ui/Form","tinymce/ui/FieldSet","tinymce/ui/FilePicker","tinymce/ui/FitLayout","tinymce/ui/FlexLayout","tinymce/ui/FlowLayout","tinymce/ui/FormatControls","tinymce/ui/GridLayout","tinymce/ui/Iframe","tinymce/ui/Label","tinymce/ui/Toolbar","tinymce/ui/MenuBar","tinymce/ui/MenuButton","tinymce/ui/ListBox","tinymce/ui/MenuItem","tinymce/ui/Menu","tinymce/ui/PanelButton","tinymce/ui/Radio","tinymce/ui/RadioGroup","tinymce/ui/ResizeHandle","tinymce/ui/Spacer","tinymce/ui/SplitButton","tinymce/ui/StackLayout","tinymce/ui/TabPanel","tinymce/ui/TextBox","tinymce/ui/Throbber"]); +})(this); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/tinymce.jquery.min.js b/lib/tinymce/jscripts/tinymce4/tinymce.jquery.min.js new file mode 100644 index 00000000..46cacc07 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/tinymce.jquery.min.js @@ -0,0 +1,9 @@ +// 4.0b1 (2013-04-11) +(function(e,t){"use strict";function n(e,t){for(var n,r=[],i=0;e.length>i;++i){if(n=s[e[i]]||o(e[i]),!n)throw"module definition dependecy not found: "+e[i];r.push(n)}t.apply(null,r)}function r(e,r,i){if("string"!=typeof e)throw"invalid module definition, module id must be defined and be a string";if(r===t)throw"invalid module definition, dependencies must be specified";if(i===t)throw"invalid module definition, definition function must be specified";n(r,function(){s[e]=i.apply(null,arguments)})}function i(e){return!!s[e]}function o(t){for(var n=e,r=t.split(/[.\/]/),i=0;r.length>i;++i){if(!n[r[i]])return;n=n[r[i]]}return n}function a(n){for(var r=0;n.length>r;r++){for(var i=e,o=n[r],a=o.split(/[.\/]/),l=0;a.length-1>l;++l)i[a[l]]===t&&(i[a[l]]={}),i=i[a[l]];i[a[a.length-1]]=s[o]}}var s={},l="tinymce/dom/Sizzle",c="tinymce/html/Styles",u="tinymce/dom/EventUtils",d="tinymce/dom/TreeWalker",f="tinymce/util/Tools",p="tinymce/dom/Range",m="tinymce/html/Entities",h="tinymce/Env",g="tinymce/dom/DOMUtils",v="tinymce/dom/ScriptLoader",y="tinymce/AddOnManager",b="tinymce/html/Node",C="tinymce/html/Schema",x="tinymce/html/SaxParser",w="tinymce/html/DomParser",_="tinymce/html/Writer",N="tinymce/html/Serializer",k="tinymce/dom/Serializer",E="tinymce/dom/TridentSelection",S="tinymce/util/VK",T="tinymce/dom/ControlSelection",R="tinymce/dom/Selection",A="tinymce/dom/RangeUtils",B="tinymce/Formatter",L="tinymce/UndoManager",H="tinymce/EnterKey",M="tinymce/ForceBlocks",D="tinymce/EditorCommands",P="tinymce/util/URI",O="tinymce/util/Class",I="tinymce/ui/Selector",F="tinymce/ui/Collection",W="tinymce/ui/DomUtils",z="tinymce/ui/Control",V="tinymce/ui/Factory",U="tinymce/ui/Container",q="tinymce/ui/DragHelper",$="tinymce/ui/Scrollable",j="tinymce/ui/Panel",G="tinymce/ui/Movable",K="tinymce/ui/Resizable",Y="tinymce/ui/FloatPanel",X="tinymce/ui/KeyboardNavigation",J="tinymce/ui/Window",Q="tinymce/ui/MessageBox",Z="tinymce/WindowManager",et="tinymce/util/Quirks",tt="tinymce/util/Observable",nt="tinymce/Shortcuts",rt="tinymce/Editor",it="tinymce/EditorManager",ot="tinymce/LegacyInput",at="tinymce/util/XHR",st="tinymce/util/JSON",lt="tinymce/util/JSONRequest",ct="tinymce/util/JSONP",ut="tinymce/util/LocalStorage",dt="tinymce/Compat",ft="tinymce/ui/Layout",pt="tinymce/ui/AbsoluteLayout",mt="tinymce/ui/Tooltip",ht="tinymce/ui/Widget",gt="tinymce/ui/Button",vt="tinymce/ui/ButtonGroup",yt="tinymce/ui/Checkbox",bt="tinymce/ui/CheckboxGroup",Ct="tinymce/ui/ColorButton",xt="tinymce/ui/ComboBox",wt="tinymce/ui/Path",_t="tinymce/ui/ElementPath",Nt="tinymce/ui/FormItem",kt="tinymce/ui/Form",Et="tinymce/ui/FieldSet",St="tinymce/ui/FilePicker",Tt="tinymce/ui/FitLayout",Rt="tinymce/ui/FlexLayout",At="tinymce/ui/FlowLayout",Bt="tinymce/ui/FormatControls",Lt="tinymce/ui/GridLayout",Ht="tinymce/ui/Iframe",Mt="tinymce/ui/Label",Dt="tinymce/ui/Toolbar",Pt="tinymce/ui/MenuBar",Ot="tinymce/ui/MenuButton",It="tinymce/ui/ListBox",Ft="tinymce/ui/MenuItem",Wt="tinymce/ui/Menu",zt="tinymce/ui/PanelButton",Vt="tinymce/ui/Radio",Ut="tinymce/ui/RadioGroup",qt="tinymce/ui/ResizeHandle",$t="tinymce/ui/Spacer",jt="tinymce/ui/SplitButton",Gt="tinymce/ui/StackLayout",Kt="tinymce/ui/TabPanel",Yt="tinymce/ui/TextBox",Xt="tinymce/ui/Throbber";r(l,[],function(){function e(e){return gt.test(e+"")}function n(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>N.cacheLength&&delete e[t.shift()],e[n]=r,r}}function i(e){return e[F]=!0,e}function o(e){var t=L.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t=null}}function a(e,t,n,r){var i,o,a,s,l,c,u,p,m,h;if((t?t.ownerDocument||t:W)!==L&&B(t),t=t||L,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(M&&!r){if(i=vt.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&I(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return et.apply(n,t.getElementsByTagName(e)),n;if((a=i[3])&&z.getElementsByClassName&&t.getElementsByClassName)return et.apply(n,t.getElementsByClassName(a)),n}if(z.qsa&&!D.test(e)){if(u=!0,p=F,m=t,h=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){for(c=d(e),(u=t.getAttribute("id"))?p=u.replace(Ct,"\\$&"):t.setAttribute("id",p),p="[id='"+p+"'] ",l=c.length;l--;)c[l]=p+f(c[l]);m=ht.test(e)&&t.parentNode||t,h=c.join(",")}if(h)try{return et.apply(n,m.querySelectorAll(h)),n}catch(g){}finally{u||t.removeAttribute("id")}}}return C(e.replace(ct,"$1"),t,n,r)}function s(e,t){var n=t&&e,r=n&&(~t.sourceIndex||X)-(~e.sourceIndex||X);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function l(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function c(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function u(e){return i(function(t){return t=+t,i(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function d(e,t){var n,r,i,o,s,l,c,u=$[e+" "];if(u)return t?0:u.slice(0);for(s=e,l=[],c=N.preFilter;s;){(!n||(r=ut.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=dt.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(ct," ")}),s=s.slice(n.length));for(o in N.filter)!(r=mt[o].exec(s))||c[o]&&!(r=c[o](r))||(n=r.shift(),i.push({value:n,type:o,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?a.error(e):$(e,l).slice(0)}function f(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function p(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=U++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,l,c,u=V+" "+o;if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i)if(c=t[F]||(t[F]={}),(l=c[r])&&l[0]===u){if((s=l[1])===!0||s===_)return s===!0}else if(l=c[r]=[u],l[1]=e(t,n,a)||_,l[1]===!0)return!0}}function m(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function h(e,t,n,r,i){for(var o,a=[],s=0,l=e.length,c=null!=t;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),c&&t.push(s));return a}function g(e,t,n,r,o,a){return r&&!r[F]&&(r=g(r)),o&&!o[F]&&(o=g(o,a)),i(function(i,a,s,l){var c,u,d,f=[],p=[],m=a.length,g=i||b(t||"*",s.nodeType?[s]:s,[]),v=!e||!i&&t?g:h(g,f,e,s,l),y=n?o||(i?e:m||r)?[]:a:v;if(n&&n(v,y,s,l),r)for(c=h(y,p),r(c,[],s,l),u=c.length;u--;)(d=c[u])&&(y[p[u]]=!(v[p[u]]=d));if(i){if(o||e){if(o){for(c=[],u=y.length;u--;)(d=y[u])&&c.push(v[u]=d);o(null,y=[],c,l)}for(u=y.length;u--;)(d=y[u])&&(c=o?nt.call(i,d):f[u])>-1&&(i[c]=!(a[c]=d))}}else y=h(y===a?y.splice(m,y.length):y),o?o(null,a,y,l):et.apply(a,y)})}function v(e){for(var t,n,r,i=e.length,o=N.relative[e[0].type],a=o||N.relative[" "],s=o?1:0,l=p(function(e){return e===t},a,!0),c=p(function(e){return nt.call(t,e)>-1},a,!0),u=[function(e,n,r){return!o&&(r||n!==T)||((t=n).nodeType?l(e,n,r):c(e,n,r))}];i>s;s++)if(n=N.relative[e[s].type])u=[p(m(u),n)];else{if(n=N.filter[e[s].type].apply(null,e[s].matches),n[F]){for(r=++s;i>r&&!N.relative[e[r].type];r++);return g(s>1&&m(u),s>1&&f(e.slice(0,s-1)).replace(ct,"$1"),n,r>s&&v(e.slice(s,r)),i>r&&v(e=e.slice(r)),i>r&&f(e))}u.push(n)}return m(u)}function y(e,t){var n=0,r=t.length>0,o=e.length>0,s=function(i,s,l,c,u){var d,f,p,m=[],g=0,v="0",y=i&&[],b=null!=u,C=T,x=i||o&&N.find.TAG("*",u&&s.parentNode||s),w=V+=null==C?1:Math.random()||.1;for(b&&(T=s!==L&&s,_=n);null!=(d=x[v]);v++){if(o&&d){for(f=0;p=e[f++];)if(p(d,s,l)){c.push(d);break}b&&(V=w,_=++n)}r&&((d=!p&&d)&&g--,i&&y.push(d))}if(g+=v,r&&v!==g){for(f=0;p=t[f++];)p(y,m,s,l);if(i){if(g>0)for(;v--;)y[v]||m[v]||(m[v]=Q.call(c));m=h(m)}et.apply(c,m),b&&!i&&m.length>0&&g+t.length>1&&a.uniqueSort(c)}return b&&(V=w,T=C),y};return r?i(s):s}function b(e,t,n){for(var r=0,i=t.length;i>r;r++)a(e,t[r],n);return n}function C(e,t,n,r){var i,o,a,s,l,c=d(e);if(!r&&1===c.length){if(o=c[0]=c[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&9===t.nodeType&&M&&N.relative[o[1].type]){if(t=(N.find.ID(a.matches[0].replace(wt,_t),t)||[])[0],!t)return n;e=e.slice(o.shift().value.length)}for(i=mt.needsContext.test(e)?0:o.length;i--&&(a=o[i],!N.relative[s=a.type]);)if((l=N.find[s])&&(r=l(a.matches[0].replace(wt,_t),ht.test(o[0].type)&&t.parentNode||t))){if(o.splice(i,1),e=r.length&&f(o),!e)return et.apply(n,r),n;break}}return S(e,c)(r,t,!M,n,ht.test(e)),n}function x(){}var w,_,N,k,E,S,T,R,A,B,L,H,M,D,P,O,I,F="sizzle"+-new Date,W=window.document,z={},V=0,U=0,q=n(),$=n(),j=n(),G=!1,K=function(){return 0},Y=typeof t,X=1<<31,J=[],Q=J.pop,Z=J.push,et=J.push,tt=J.slice,nt=J.indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},rt="[\\x20\\t\\r\\n\\f]",it="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ot=it.replace("w","w#"),at="([*^$|!~]?=)",st="\\["+rt+"*("+it+")"+rt+"*(?:"+at+rt+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+ot+")|)|)"+rt+"*\\]",lt=":("+it+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+st.replace(3,8)+")*)|.*)\\)|)",ct=RegExp("^"+rt+"+|((?:^|[^\\\\])(?:\\\\.)*)"+rt+"+$","g"),ut=RegExp("^"+rt+"*,"+rt+"*"),dt=RegExp("^"+rt+"*([\\x20\\t\\r\\n\\f>+~])"+rt+"*"),ft=RegExp(lt),pt=RegExp("^"+ot+"$"),mt={ID:RegExp("^#("+it+")"),CLASS:RegExp("^\\.("+it+")"),NAME:RegExp("^\\[name=['\"]?("+it+")['\"]?\\]"),TAG:RegExp("^("+it.replace("w","w*")+")"),ATTR:RegExp("^"+st),PSEUDO:RegExp("^"+lt),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+rt+"*(even|odd|(([+-]|)(\\d*)n|)"+rt+"*(?:([+-]|)"+rt+"*(\\d+)|))"+rt+"*\\)|)","i"),needsContext:RegExp("^"+rt+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+rt+"*((?:-\\d)?\\d*)"+rt+"*\\)|)(?=[^-]|$)","i")},ht=/[\x20\t\r\n\f]*[+~]/,gt=/^[^{]+\{\s*\[native code/,vt=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,yt=/^(?:input|select|textarea|button)$/i,bt=/^h\d$/i,Ct=/'|\\/g,xt=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,wt=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,_t=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{et.apply(J=tt.call(W.childNodes),W.childNodes),J[W.childNodes.length].nodeType}catch(Nt){et={apply:J.length?function(e,t){Z.apply(e,tt.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}E=a.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},B=a.setDocument=function(n){var r=n?n.ownerDocument||n:W;return r!==L&&9===r.nodeType&&r.documentElement?(L=r,H=r.documentElement,M=!E(r),z.getElementsByTagName=o(function(e){return e.appendChild(r.createComment("")),!e.getElementsByTagName("*").length}),z.attributes=o(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),z.getElementsByClassName=o(function(e){return e.innerHTML="",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),z.getByName=o(function(e){e.id=F+0,e.appendChild(L.createElement("a")).setAttribute("name",F),e.appendChild(L.createElement("i")).setAttribute("name",F),H.appendChild(e);var t=r.getElementsByName&&r.getElementsByName(F).length===2+r.getElementsByName(F+0).length;return H.removeChild(e),t}),z.sortDetached=o(function(e){return e.compareDocumentPosition&&1&e.compareDocumentPosition(L.createElement("div"))}),N.attrHandle=o(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==Y&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},z.getByName?(N.find.ID=function(e,t){if(typeof t.getElementById!==Y&&M){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},N.filter.ID=function(e){var t=e.replace(wt,_t);return function(e){return e.getAttribute("id")===t}}):(N.find.ID=function(e,n){if(typeof n.getElementById!==Y&&M){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==Y&&r.getAttributeNode("id").value===e?[r]:t:[]}},N.filter.ID=function(e){var t=e.replace(wt,_t);return function(e){var n=typeof e.getAttributeNode!==Y&&e.getAttributeNode("id");return n&&n.value===t}}),N.find.TAG=z.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==Y?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o},N.find.NAME=z.getByName&&function(e,n){return typeof n.getElementsByName!==Y?n.getElementsByName(name):t},N.find.CLASS=z.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==Y&&M?n.getElementsByClassName(e):t},P=[],D=[":focus"],(z.qsa=e(r.querySelectorAll))&&(o(function(e){e.innerHTML="",e.querySelectorAll("[selected]").length||D.push("\\["+rt+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||D.push(":checked")}),o(function(e){e.innerHTML="",e.querySelectorAll("[i^='']").length&&D.push("[*^$]="+rt+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||D.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),D.push(",.*:")})),(z.matchesSelector=e(O=H.matchesSelector||H.mozMatchesSelector||H.webkitMatchesSelector||H.oMatchesSelector||H.msMatchesSelector))&&o(function(e){z.disconnectedMatch=O.call(e,"div"),O.call(e,"[s!='']:x"),P.push("!=",lt)}),D=RegExp(D.join("|")),P=P.length&&RegExp(P.join("|")),I=e(H.contains)||H.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},K=H.compareDocumentPosition?function(e,t){if(e===t)return G=!0,0;var n=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return n?1&n||R&&t.compareDocumentPosition(e)===n?e===r||I(W,e)?-1:t===r||I(W,t)?1:A?nt.call(A,e)-nt.call(A,t):0:4&n?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var n,i=0,o=e.parentNode,a=t.parentNode,l=[e],c=[t];if(e===t)return G=!0,0;if(!o||!a)return e===r?-1:t===r?1:o?-1:a?1:0;if(o===a)return s(e,t);for(n=e;n=n.parentNode;)l.unshift(n);for(n=t;n=n.parentNode;)c.unshift(n);for(;l[i]===c[i];)i++;return i?s(l[i],c[i]):l[i]===W?-1:c[i]===W?1:0},L):L},a.matches=function(e,t){return a(e,null,null,t)},a.matchesSelector=function(e,t){if((e.ownerDocument||e)!==L&&B(e),t=t.replace(xt,"='$1']"),z.matchesSelector&&M&&(!P||!P.test(t))&&!D.test(t))try{var n=O.call(e,t);if(n||z.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return a(t,L,null,[e]).length>0},a.contains=function(e,t){return(e.ownerDocument||e)!==L&&B(e),I(e,t)},a.attr=function(e,t){var n;return(e.ownerDocument||e)!==L&&B(e),M&&(t=t.toLowerCase()),(n=N.attrHandle[t])?n(e):!M||z.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},a.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},a.uniqueSort=function(e){var t,n=[],r=0,i=0;if(G=!z.detectDuplicates,R=!z.sortDetached,A=!z.sortStable&&e.slice(0),e.sort(K),G){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return e},k=a.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=k(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=k(t);return n},N=a.selectors={cacheLength:50,createPseudo:i,match:mt,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(wt,_t),e[3]=(e[4]||e[5]||"").replace(wt,_t),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||a.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&a.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return mt.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&ft.test(n)&&(t=d(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(wt,_t).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=q[e+" "];return t||(t=RegExp("(^|"+rt+")"+e+"("+rt+"|$)"))&&q(e,function(e){return t.test(e.className||typeof e.getAttribute!==Y&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=a.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var c,u,d,f,p,m,h=o!==a?"nextSibling":"previousSibling",g=t.parentNode,v=s&&t.nodeName.toLowerCase(),y=!l&&!s;if(g){if(o){for(;h;){for(d=t;d=d[h];)if(s?d.nodeName.toLowerCase()===v:1===d.nodeType)return!1;m=h="only"===e&&!m&&"nextSibling"}return!0}if(m=[a?g.firstChild:g.lastChild],a&&y){for(u=g[F]||(g[F]={}),c=u[e]||[],p=c[0]===V&&c[1],f=c[0]===V&&c[2],d=p&&g.childNodes[p];d=++p&&d&&d[h]||(f=p=0)||m.pop();)if(1===d.nodeType&&++f&&d===t){u[e]=[V,p,f];break}}else if(y&&(c=(t[F]||(t[F]={}))[e])&&c[0]===V)f=c[1];else for(;(d=++p&&d&&d[h]||(f=p=0)||m.pop())&&((s?d.nodeName.toLowerCase()!==v:1!==d.nodeType)||!++f||(y&&((d[F]||(d[F]={}))[e]=[V,f]),d!==t)););return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=N.pseudos[e]||N.setFilters[e.toLowerCase()]||a.error("unsupported pseudo: "+e);return r[F]?r(t):r.length>1?(n=[e,e,"",t],N.setFilters.hasOwnProperty(e.toLowerCase())?i(function(e,n){for(var i,o=r(e,t),a=o.length;a--;)i=nt.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:i(function(e){var t=[],n=[],r=S(e.replace(ct,"$1"));return r[F]?i(function(e,t,n,i){for(var o,a=r(e,null,i,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:i(function(e){return function(t){return a(e,t).length>0}}),contains:i(function(e){return function(t){return(t.textContent||t.innerText||k(t)).indexOf(e)>-1}}),lang:i(function(e){return pt.test(e||"")||a.error("unsupported lang: "+e),e=e.replace(wt,_t).toLowerCase(),function(t){var n;do if(n=M?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(e){var t=window.location&&window.location.hash;return t&&t.slice(1)===e.id},root:function(e){return e===H},focus:function(e){return e===L.activeElement&&(!L.hasFocus||L.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!N.pseudos.empty(e)},header:function(e){return bt.test(e.nodeName)},input:function(e){return yt.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,n){return[0>n?n+t:n]}),even:u(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:u(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:u(function(e,t,n){for(var r=0>n?n+t:n;t>++r;)e.push(r);return e})}};for(w in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})N.pseudos[w]=l(w);for(w in{submit:!0,reset:!0})N.pseudos[w]=c(w);return S=a.compile=function(e,t){var n,r=[],i=[],o=j[e+" "];if(!o){for(t||(t=d(e)),n=t.length;n--;)o=v(t[n]),o[F]?r.push(o):i.push(o);o=j(e,y(i,r))}return o},N.pseudos.nth=N.pseudos.eq,x.prototype=N.filters=N.pseudos,N.setFilters=new x,z.sortStable=F.split("").sort(K).join("")===F,B(),[0,0].sort(K),z.detectDuplicates=G,"function"==typeof r&&r.amd?r(function(){return a}):window.Sizzle=a,a}),r(c,[],function(){return function(e,t){function n(e,t,n,r){function i(e){return e=parseInt(e,10).toString(16),e.length>1?e:"0"+e}return"#"+i(t)+i(n)+i(r)}var r=/rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi,i=/(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi,o=/\s*([^:]+):\s*([^;]+);?/g,a=/\s+$/,s,l,c={},u,d="\ufeff";for(e=e||{},u=("\\\" \\' \\; \\: ; : "+d).split(" "),l=0;u.length>l;l++)c[u[l]]=d+l,c[d+l]=u[l];return{toHex:function(e){return e.replace(r,n)},parse:function(t){function s(e,t){var n,r,i,o;n=m[e+"-top"+t],n&&(r=m[e+"-right"+t],n==r&&(i=m[e+"-bottom"+t],r==i&&(o=m[e+"-left"+t],i==o&&(m[e+t]=o,delete m[e+"-top"+t],delete m[e+"-right"+t],delete m[e+"-bottom"+t],delete m[e+"-left"+t]))))}function l(e){var t=m[e],n;if(t&&!(0>t.indexOf(" "))){for(t=t.split(" "),n=t.length;n--;)if(t[n]!==t[0])return!1;return m[e]=t[0],!0}}function u(e,t,n,r){l(t)&&l(n)&&l(r)&&(m[e]=m[t]+" "+m[n]+" "+m[r],delete m[t],delete m[n],delete m[r])}function d(e){return y=!0,c[e]}function f(e,t){return y&&(e=e.replace(/\uFEFF[0-9]/g,function(e){return c[e]})),t||(e=e.replace(/\\([\'\";:])/g,"$1")),e}function p(e,t,n,r,i,o){return(i=i||o)?(i=f(i),"'"+i.replace(/\'/g,"\\'")+"'"):(t=f(t||n||r),b&&(t=b.call(C,t,"style")),"url('"+t.replace(/\'/g,"\\'")+"')")}var m={},h,g,v,y,b=e.url_converter,C=e.url_converter_scope||this;if(t){for(t=t.replace(/\\[\"\';:\uFEFF]/g,d).replace(/\"[^\"]+\"|\'[^\']+\'/g,function(e){return e.replace(/[;:]/g,d)});h=o.exec(t);)g=h[1].replace(a,"").toLowerCase(),v=h[2].replace(a,""),g&&v.length>0&&("font-weight"===g&&"700"===v?v="bold":("color"===g||"background-color"===g)&&(v=v.toLowerCase()),v=v.replace(r,n),v=v.replace(i,p),m[g]=y?f(v,!0):v),o.lastIndex=h.index+h[0].length;s("border",""),s("border","-width"),s("border","-color"),s("border","-style"),s("padding",""),s("margin",""),u("border","border-width","border-style","border-color"),"medium none"===m.border&&delete m.border}return m},serialize:function(e,n){function r(n){var r,o,a,l;if(r=t.styles[n])for(o=0,a=r.length;a>o;o++)n=r[o],l=e[n],l!==s&&l.length>0&&(i+=(i.length>0?" ":"")+n+": "+l+";")}var i="",o,a;if(n&&t&&t.styles)r("*"),r(n);else for(o in e)a=e[o],a!==s&&a.length>0&&(i+=(i.length>0?" ":"")+o+": "+a+";");return i}}}}),r(u,[],function(){function e(e,t,n,r){e.addEventListener?e.addEventListener(t,n,r||!1):e.attachEvent&&e.attachEvent("on"+t,n)}function n(e,t,n,r){e.removeEventListener?e.removeEventListener(t,n,r||!1):e.detachEvent&&e.detachEvent("on"+t,n)}function r(e,t){function n(){return!1}function r(){return!0}var i,o=t||{};for(i in e)"layerX"!==i&&"layerY"!==i&&(o[i]=e[i]);return o.target||(o.target=o.srcElement||document),o.preventDefault=function(){o.isDefaultPrevented=r,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},o.stopPropagation=function(){o.isPropagationStopped=r,e&&(e.stopPropagation?e.stopPropagation():e.cancelBubble=!0)},o.stopImmediatePropagation=function(){o.isImmediatePropagationStopped=r,o.stopPropagation()},o.isDefaultPrevented||(o.isDefaultPrevented=n,o.isPropagationStopped=n,o.isImmediatePropagationStopped=n),o}function i(r,i,o){function a(){o.domLoaded||(o.domLoaded=!0,i(u))}function s(){"complete"===c.readyState&&(n(c,"readystatechange",s),a())}function l(){try{c.documentElement.doScroll("left")}catch(e){return setTimeout(l,0),t}a()}var c=r.document,u={type:"ready"};return o.domLoaded?(i(u),t):(c.addEventListener?e(r,"DOMContentLoaded",a):(e(c,"readystatechange",s),c.documentElement.doScroll&&r===r.top&&l()),e(r,"load",a),t)}function o(){function t(e,t){var n,r,i,o;if(n=s[t][e.type])for(r=0,i=n.length;i>r;r++)if(o=n[r],o&&o.func.call(o.scope,e)===!1&&e.preventDefault(),e.isImmediatePropagationStopped())return}var o=this,s={},l,c,u,d,f;c=a+(+new Date).toString(32),d="onmouseenter"in document.documentElement,u="onfocusin"in document.documentElement,f={mouseenter:"mouseover",mouseleave:"mouseout"},l=1,o.domLoaded=!1,o.events=s,o.bind=function(n,a,p,m){function h(e){t(r(e||_.event),g)}var g,v,y,b,C,x,w,_=window;if(n&&3!==n.nodeType&&8!==n.nodeType){for(n[c]?g=n[c]:(g=l++,n[c]=g,s[g]={}),m=m||n,a=a.split(" "),y=a.length;y--;)b=a[y],x=h,C=w=!1,"DOMContentLoaded"===b&&(b="ready"),o.domLoaded&&"ready"===b&&"complete"==n.readyState?p.call(m,r({type:b})):(d||(C=f[b],C&&(x=function(e){var n,i;if(n=e.currentTarget,i=e.relatedTarget,i&&n.contains)i=n.contains(i);else for(;i&&i!==n;)i=i.parentNode;i||(e=r(e||_.event),e.type="mouseout"===e.type?"mouseleave":"mouseenter",e.target=n,t(e,g))})),u||"focusin"!==b&&"focusout"!==b||(w=!0,C="focusin"===b?"focus":"blur",x=function(e){e=r(e||_.event),e.type="focus"===e.type?"focusin":"focusout",t(e,g)}),v=s[g][b],v?"ready"===b&&o.domLoaded?p({type:b}):v.push({func:p,scope:m}):(s[g][b]=v=[{func:p,scope:m}],v.fakeName=C,v.capture=w,v.nativeHandler=x,"ready"===b?i(n,x,o):e(n,C||b,x,w)));return n=v=0,p}},o.unbind=function(e,t,r){var i,a,l,u,d,f;if(!e||3===e.nodeType||8===e.nodeType)return o;if(i=e[c]){if(f=s[i],t){for(t=t.split(" "),l=t.length;l--;)if(d=t[l],a=f[d]){if(r)for(u=a.length;u--;)a[u].func===r&&a.splice(u,1);r&&0!==a.length||(delete f[d],n(e,a.fakeName||d,a.nativeHandler,a.capture))}}else{for(d in f)a=f[d],n(e,a.fakeName||d,a.nativeHandler,a.capture);f={}}for(d in f)return o;delete s[i];try{delete e[c]}catch(p){e[c]=null}}return o},o.fire=function(e,n,i){var a;if(!e||3===e.nodeType||8===e.nodeType)return o;i=r(null,i),i.type=n,i.target=e;do a=e[c],a&&t(i,a),e=e.parentNode||e.ownerDocument||e.defaultView||e.parentWindow;while(e&&!i.isPropagationStopped());return o},o.clean=function(e){var t,n,r=o.unbind;if(!e||3===e.nodeType||8===e.nodeType)return o;if(e[c]&&r(e),e.getElementsByTagName||(e=e.document),e&&e.getElementsByTagName)for(r(e),n=e.getElementsByTagName("*"),t=n.length;t--;)e=n[t],e[c]&&r(e);return o},o.destory=function(){s={}},o.cancel=function(e){return e&&(e.preventDefault(),e.stopImmediatePropagation()),!1}}var a="mce-data-";return o.Event=new o,o.Event.bind(window,"ready",function(){}),o}),r(d,[],function(){return function(e,t){function n(e,n,r,i){var o,a;if(e){if(!i&&e[n])return e[n];if(e!=t){if(o=e[r])return o;for(a=e.parentNode;a&&a!=t;a=a.parentNode)if(o=a[r])return o}}}var r=e;this.current=function(){return r},this.next=function(e){return r=n(r,"firstChild","nextSibling",e)},this.prev=function(e){return r=n(r,"lastChild","previousSibling",e)}}}),r(f,[],function(){function e(e,n){return n?"array"==n&&g(e)?!0:typeof e==n:e!==t}function n(e){var t=[],n,r;for(n=0,r=e.length;r>n;n++)t[n]=e[n];return t}function r(e,t,n){var r;for(e=e||[],t=t||",","string"==typeof e&&(e=e.split(t)),n=n||{},r=e.length;r--;)n[e[r]]={};return n}function i(e,n,r){var i,o;if(!e)return 0;if(r=r||e,e.length!==t){for(i=0,o=e.length;o>i;i++)if(n.call(r,e[i],i,e)===!1)return 0}else for(i in e)if(e.hasOwnProperty(i)&&n.call(r,e[i],i,e)===!1)return 0;return 1}function o(e,t){var n=[];return i(e,function(e){n.push(t(e))}),n}function a(e,t){var n=[];return i(e,function(e){(!t||t(e))&&n.push(e)}),n}function s(e,n,r){var i=this,o,a,s,l,c,u=0;if(e=/^((static) )?([\w.]+)(:([\w.]+))?/.exec(e),s=e[3].match(/(^|\.)(\w+)$/i)[2],a=i.createNS(e[3].replace(/\.\w+$/,""),r),!a[s]){if("static"==e[2])return a[s]=n,this.onCreate&&this.onCreate(e[2],e[3],a[s]),t;n[s]||(n[s]=function(){},u=1),a[s]=n[s],i.extend(a[s].prototype,n),e[5]&&(o=i.resolve(e[5]).prototype,l=e[5].match(/\.(\w+)$/i)[1],c=a[s],a[s]=u?function(){return o[l].apply(this,arguments)}:function(){return this.parent=o[l],c.apply(this,arguments)},a[s].prototype[s]=a[s],i.each(o,function(e,t){a[s].prototype[t]=o[t]}),i.each(n,function(e,t){o[t]?a[s].prototype[t]=function(){return this.parent=o[t],e.apply(this,arguments)}:t!=s&&(a[s].prototype[t]=e)})),i.each(n["static"],function(e,t){a[s][t]=e})}}function l(e,t){var n,r;if(e)for(n=0,r=e.length;r>n;n++)if(e[n]===t)return n;return-1}function c(e,n){var r,i,o,a=arguments,s;for(r=1,i=a.length;i>r;r++){n=a[r];for(o in n)n.hasOwnProperty(o)&&(s=n[o],s!==t&&(e[o]=s))}return e}function u(e,n,r,o){o=o||this,e&&(r&&(e=e[r]),i(e,function(e,i){return n.call(o,e,i,r)===!1?!1:(u(e,n,r,o),t)}))}function d(e,t){var n,r;for(t=t||window,e=e.split("."),n=0;e.length>n;n++)r=e[n],t[r]||(t[r]={}),t=t[r];return t}function f(e,t){var n,r;for(t=t||window,e=e.split("."),n=0,r=e.length;r>n&&(t=t[e[n]],t);n++);return t}function p(t,n){return!t||e(t,"array")?t:o(t.split(n||","),h)}var m=/^\s*|\s*$/g,h=function(e){return null===e||e===t?"":(""+e).replace(m,"")},g=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};return{trim:h,isArray:g,is:e,toArray:n,makeMap:r,each:i,map:o,grep:a,inArray:l,extend:c,create:s,walk:u,createNS:d,resolve:f,explode:p}}),r(p,[f],function(e){function n(r){function i(){return P.createDocumentFragment()}function o(e,t){N(W,e,t)}function a(e,t){N(z,e,t)}function s(e){o(e.parentNode,G(e))}function l(e){o(e.parentNode,G(e)+1)}function c(e){a(e.parentNode,G(e))}function u(e){a(e.parentNode,G(e)+1)}function d(e){e?(D[q]=D[U],D[$]=D[V]):(D[U]=D[q],D[V]=D[$]),D.collapsed=W}function f(e){s(e),u(e)}function p(e){o(e,0),a(e,1===e.nodeType?e.childNodes.length:e.nodeValue.length)}function m(e,n){var r=D[U],i=D[V],o=D[q],a=D[$],s=n.startContainer,l=n.startOffset,c=n.endContainer,u=n.endOffset;return 0===e?_(r,i,s,l):1===e?_(o,a,s,l):2===e?_(o,a,c,u):3===e?_(r,i,c,u):t}function h(){k(F)}function g(){return k(O)}function v(){return k(I)}function y(e){var t=this[U],n=this[V],i,o;3!==t.nodeType&&4!==t.nodeType||!t.nodeValue?(t.childNodes.length>0&&(o=t.childNodes[n]),o?t.insertBefore(e,o):t.appendChild(e)):n?n>=t.nodeValue.length?r.insertAfter(e,t):(i=t.splitText(n),t.parentNode.insertBefore(e,i)):t.parentNode.insertBefore(e,t)}function b(e){var t=D.extractContents();D.insertNode(e),e.appendChild(t),D.selectNode(e)}function C(){return j(new n(r),{startContainer:D[U],startOffset:D[V],endContainer:D[q],endOffset:D[$],collapsed:D.collapsed,commonAncestorContainer:D.commonAncestorContainer})}function x(e,t){var n;if(3==e.nodeType)return e;if(0>t)return e;for(n=e.firstChild;n&&t>0;)--t,n=n.nextSibling;return n?n:e}function w(){return D[U]==D[q]&&D[V]==D[$]}function _(e,t,n,i){var o,a,s,l,c,u;if(e==n)return t==i?0:i>t?-1:1;for(o=n;o&&o.parentNode!=e;)o=o.parentNode;if(o){for(a=0,s=e.firstChild;s!=o&&t>a;)a++,s=s.nextSibling;return a>=t?-1:1}for(o=e;o&&o.parentNode!=n;)o=o.parentNode;if(o){for(a=0,s=n.firstChild;s!=o&&i>a;)a++,s=s.nextSibling;return i>a?-1:1}for(l=r.findCommonAncestor(e,n),c=e;c&&c.parentNode!=l;)c=c.parentNode;for(c||(c=l),u=n;u&&u.parentNode!=l;)u=u.parentNode;if(u||(u=l),c==u)return 0;for(s=l.firstChild;s;){if(s==c)return-1;if(s==u)return 1;s=s.nextSibling}}function N(e,t,n){var i,o;for(e?(D[U]=t,D[V]=n):(D[q]=t,D[$]=n),i=D[q];i.parentNode;)i=i.parentNode;for(o=D[U];o.parentNode;)o=o.parentNode;o==i?_(D[U],D[V],D[q],D[$])>0&&D.collapse(e):D.collapse(e),D.collapsed=w(),D.commonAncestorContainer=r.findCommonAncestor(D[U],D[q])}function k(e){var t,n=0,r=0,i,o,a,s,l,c;if(D[U]==D[q])return E(e);for(t=D[q],i=t.parentNode;i;t=i,i=i.parentNode){if(i==D[U])return S(t,e);++n}for(t=D[U],i=t.parentNode;i;t=i,i=i.parentNode){if(i==D[q])return T(t,e); +++r}for(o=r-n,a=D[U];o>0;)a=a.parentNode,o--;for(s=D[q];0>o;)s=s.parentNode,o++;for(l=a.parentNode,c=s.parentNode;l!=c;l=l.parentNode,c=c.parentNode)a=l,s=c;return R(a,s,e)}function E(e){var t,n,r,o,a,s,l,c,u;if(e!=F&&(t=i()),D[V]==D[$])return t;if(3==D[U].nodeType){if(n=D[U].nodeValue,r=n.substring(D[V],D[$]),e!=I&&(o=D[U],c=D[V],u=D[$]-D[V],0===c&&u>=o.nodeValue.length-1?o.parentNode.removeChild(o):o.deleteData(c,u),D.collapse(W)),e==F)return;return r.length>0&&t.appendChild(P.createTextNode(r)),t}for(o=x(D[U],D[V]),a=D[$]-D[V];o&&a>0;)s=o.nextSibling,l=H(o,e),t&&t.appendChild(l),--a,o=s;return e!=I&&D.collapse(W),t}function S(e,t){var n,r,o,a,s,l;if(t!=F&&(n=i()),r=A(e,t),n&&n.appendChild(r),o=G(e),a=o-D[V],0>=a)return t!=I&&(D.setEndBefore(e),D.collapse(z)),n;for(r=e.previousSibling;a>0;)s=r.previousSibling,l=H(r,t),n&&n.insertBefore(l,n.firstChild),--a,r=s;return t!=I&&(D.setEndBefore(e),D.collapse(z)),n}function T(e,t){var n,r,o,a,s,l;for(t!=F&&(n=i()),o=B(e,t),n&&n.appendChild(o),r=G(e),++r,a=D[$]-r,o=e.nextSibling;o&&a>0;)s=o.nextSibling,l=H(o,t),n&&n.appendChild(l),--a,o=s;return t!=I&&(D.setStartAfter(e),D.collapse(W)),n}function R(e,t,n){var r,o,a,s,l,c,u,d;for(n!=F&&(o=i()),r=B(e,n),o&&o.appendChild(r),a=e.parentNode,s=G(e),l=G(t),++s,c=l-s,u=e.nextSibling;c>0;)d=u.nextSibling,r=H(u,n),o&&o.appendChild(r),u=d,--c;return r=A(t,n),o&&o.appendChild(r),n!=I&&(D.setStartAfter(e),D.collapse(W)),o}function A(e,t){var n=x(D[q],D[$]-1),r,i,o,a,s,l=n!=D[q];if(n==e)return L(n,l,z,t);for(r=n.parentNode,i=L(r,z,z,t);r;){for(;n;)o=n.previousSibling,a=L(n,l,z,t),t!=F&&i.insertBefore(a,i.firstChild),l=W,n=o;if(r==e)return i;n=r.previousSibling,r=r.parentNode,s=L(r,z,z,t),t!=F&&s.appendChild(i),i=s}}function B(e,t){var n=x(D[U],D[V]),r=n!=D[U],i,o,a,s,l;if(n==e)return L(n,r,W,t);for(i=n.parentNode,o=L(i,z,W,t);i;){for(;n;)a=n.nextSibling,s=L(n,r,W,t),t!=F&&o.appendChild(s),r=W,n=a;if(i==e)return o;n=i.nextSibling,i=i.parentNode,l=L(i,z,W,t),t!=F&&l.appendChild(o),o=l}}function L(e,t,n,i){var o,a,s,l,c;if(t)return H(e,i);if(3==e.nodeType){if(o=e.nodeValue,n?(l=D[V],a=o.substring(l),s=o.substring(0,l)):(l=D[$],a=o.substring(0,l),s=o.substring(l)),i!=I&&(e.nodeValue=s),i==F)return;return c=r.clone(e,z),c.nodeValue=a,c}if(i!=F)return r.clone(e,z)}function H(e,n){return n!=F?n==I?r.clone(e,W):e:(e.parentNode.removeChild(e),t)}function M(){return r.create("body",null,v()).outerText}var D=this,P=r.doc,O=0,I=1,F=2,W=!0,z=!1,V="startOffset",U="startContainer",q="endContainer",$="endOffset",j=e.extend,G=r.nodeIndex;return j(D,{startContainer:P,startOffset:0,endContainer:P,endOffset:0,collapsed:W,commonAncestorContainer:P,START_TO_START:0,START_TO_END:1,END_TO_END:2,END_TO_START:3,setStart:o,setEnd:a,setStartBefore:s,setStartAfter:l,setEndBefore:c,setEndAfter:u,collapse:d,selectNode:f,selectNodeContents:p,compareBoundaryPoints:m,deleteContents:h,extractContents:g,cloneContents:v,insertNode:y,surroundContents:b,cloneRange:C,toStringIE:M}),D}return n.prototype.toString=function(){return this.toStringIE()},n}),r(m,[f],function(e){function t(e){var t;return t=document.createElement("div"),t.innerHTML=e,t.textContent||t.innerText||e}function n(e,t){var n,r,i,a={};if(e){for(e=e.split(","),t=t||10,n=0;e.length>n;n+=2)r=String.fromCharCode(parseInt(e[n],t)),o[r]||(i="&"+e[n+1]+";",a[r]=i,a[i]=r);return a}}var r=e.makeMap,i,o,a,s=/[&<>\"\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,l=/[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,c=/[<>&\"\']/g,u=/&(#x|#)?([\w]+);/g,d={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"};o={'"':""","'":"'","<":"<",">":">","&":"&"},a={"<":"<",">":">","&":"&",""":'"',"'":"'"},i=n("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);var f={encodeRaw:function(e,t){return e.replace(t?s:l,function(e){return o[e]||e})},encodeAllRaw:function(e){return(""+e).replace(c,function(e){return o[e]||e})},encodeNumeric:function(e,t){return e.replace(t?s:l,function(e){return e.length>1?"&#"+(1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320)+65536)+";":o[e]||"&#"+e.charCodeAt(0)+";"})},encodeNamed:function(e,t,n){return n=n||i,e.replace(t?s:l,function(e){return o[e]||n[e]||e})},getEncodeFunc:function(e,t){function a(e,n){return e.replace(n?s:l,function(e){return o[e]||t[e]||"&#"+e.charCodeAt(0)+";"||e})}function c(e,n){return f.encodeNamed(e,n,t)}return t=n(t)||i,e=r(e.replace(/\+/g,",")),e.named&&e.numeric?a:e.named?t?c:f.encodeNamed:e.numeric?f.encodeNumeric:f.encodeRaw},decode:function(e){return e.replace(u,function(e,n,r){return n?(r=parseInt(r,2===n.length?16:10),r>65535?(r-=65536,String.fromCharCode(55296+(r>>10),56320+(1023&r))):d[r]||String.fromCharCode(r)):a[e]||i[e]||t(e)})}};return f}),r(h,[],function(){var e=navigator,t=e.userAgent,n,r,i,o,a,s;n=window.opera&&window.opera.buildNumber,r=/WebKit/.test(t),i=!r&&!n&&/MSIE/gi.test(t)&&/Explorer/gi.test(e.appName),i=i&&/MSIE (\w+)\./.exec(t)[1],o=!r&&/Gecko/.test(t),a=-1!=t.indexOf("Mac"),s=/(iPad|iPhone)/.test(t);var l=!s||t.match(/AppleWebKit\/(\d*)/)[1]>=534;return{opera:n,webkit:r,ie:i,gecko:o,mac:a,iOS:s,contentEditable:l,transparentSrc:"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",caretAfter:8!=i,range:window.getSelection&&"Range"in window}}),r(g,[l,c,u,d,p,m,h,f],function(e,n,r,i,o,a,s,l){function c(e,t){var i=this,o;i.doc=e,i.win=window,i.files={},i.counter=0,i.stdMode=!g||e.documentMode>=8,i.boxModel=!g||"CSS1Compat"==e.compatMode||i.stdMode,i.hasOuterHTML="outerHTML"in e.createElement("a"),i.settings=t=m({keep_values:!1,hex_colors:1},t),i.schema=t.schema,i.styles=new n({url_converter:t.url_converter,url_converter_scope:t.url_converter_scope},t.schema),i.fixDoc(e),i.events=t.ownEvents?new r(t.proxy):r.Event,o=t.schema?t.schema.getBlockElements():{},i.isBlock=function(e){if(!e)return!1;var t=e.nodeType;return t?!(1!==t||!o[e.nodeName]):!!o[e]}}var u=l.each,d=l.is,f=l.grep,p=l.trim,m=l.extend,h=s.webkit,g=s.ie,v=/^([a-z0-9],?)+$/i,y=/^[ \t\r\n]*$/,b=l.makeMap("fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom"," ");return c.prototype={root:null,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"},fixDoc:function(e){var t=this.settings,n;if(g&&t.schema){"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(t){e.createElement(t)});for(n in t.schema.getCustomElements())e.createElement(n)}},clone:function(e,t){var n=this,r,i;return!g||1!==e.nodeType||t?e.cloneNode(t):(i=n.doc,t?r.firstChild:(r=i.createElement(e.nodeName),u(n.getAttribs(e),function(t){n.setAttrib(r,t.nodeName,n.getAttrib(e,t.nodeName))}),r))},getRoot:function(){var e=this;return e.get(e.settings.root_element)||e.doc.body},getViewPort:function(e){var t,n;return e=e?e:this.win,t=e.document,n=this.boxModel?t.documentElement:t.body,{x:e.pageXOffset||n.scrollLeft,y:e.pageYOffset||n.scrollTop,w:e.innerWidth||n.clientWidth,h:e.innerHeight||n.clientHeight}},getRect:function(e){var t=this,n,r;return e=t.get(e),n=t.getPos(e),r=t.getSize(e),{x:n.x,y:n.y,w:r.w,h:r.h}},getSize:function(e){var t=this,n,r;return e=t.get(e),n=t.getStyle(e,"width"),r=t.getStyle(e,"height"),-1===n.indexOf("px")&&(n=0),-1===r.indexOf("px")&&(r=0),{w:parseInt(n,10)||e.offsetWidth||e.clientWidth,h:parseInt(r,10)||e.offsetHeight||e.clientHeight}},getParent:function(e,t,n){return this.getParents(e,t,n,!1)},getParents:function(e,n,r,i){var o=this,a,s=[];for(e=o.get(e),i=i===t,d(n,"string")&&(a=n,n="*"===n?function(e){return 1==e.nodeType}:function(e){return o.is(e,a)});e&&e!=r&&e.nodeType&&9!==e.nodeType;){if(!n||n(e)){if(!i)return e;s.push(e)}e=e.parentNode}return i?s:null},get:function(e){var t;return e&&this.doc&&"string"==typeof e&&(t=e,e=this.doc.getElementById(e),e&&e.id!==t)?this.doc.getElementsByName(t)[1]:e},getNext:function(e,t){return this._findSib(e,t,"nextSibling")},getPrev:function(e,t){return this._findSib(e,t,"previousSibling")},select:function(t,n){var r=this;return e(t,r.get(n)||r.get(r.settings.root_element)||r.doc,[])},is:function(n,r){var i;if(n.length===t){if("*"===r)return 1==n.nodeType;if(v.test(r)){for(r=r.toLowerCase().split(/,/),n=n.nodeName.toLowerCase(),i=r.length-1;i>=0;i--)if(r[i]==n)return!0;return!1}}return e.matches(r,n.nodeType?[n]:n).length>0},add:function(e,t,n,r,i){var o=this;return this.run(e,function(e){var a;return a=d(t,"string")?o.doc.createElement(t):t,o.setAttribs(a,n),r&&(r.nodeType?a.appendChild(r):o.setHTML(a,r)),i?a:e.appendChild(a)})},create:function(e,t,n){return this.add(this.doc.createElement(e),e,t,n,1)},createHTML:function(e,n,r){var i="",o;i+="<"+e;for(o in n)n.hasOwnProperty(o)&&(i+=" "+o+'="'+this.encode(n[o])+'"');return r!==t?i+">"+r+"":i+" />"},createFragment:function(e){var t,n,r=this.doc,i;for(i=r.createElement("div"),t=r.createDocumentFragment(),e&&(i.innerHTML=e);n=i.firstChild;)t.appendChild(n);return t},remove:function(e,t){return this.run(e,function(e){var n,r=e.parentNode;if(!r)return null;if(t)for(;n=e.firstChild;)!g||3!==n.nodeType||n.nodeValue?r.insertBefore(n,e):e.removeChild(n);return r.removeChild(e)})},setStyle:function(e,n,r){return this.run(e,function(e){var i=this,o,a;if(n)if("string"==typeof n){o=e.style,n=n.replace(/-(\D)/g,function(e,t){return t.toUpperCase()}),"number"!=typeof r||b[n]||(r+="px"),"opacity"===n&&e.runtimeStyle&&e.runtimeStyle.opacity===t&&(o.filter=""===r?"":"alpha(opacity="+100*r+")");try{o[n]=r}catch(s){}i.settings.update_styles&&e.removeAttribute("data-mce-style")}else for(a in n)i.setStyle(e,a,n[a])})},getStyle:function(e,n,r){if(e=this.get(e)){if(this.doc.defaultView&&r){n=n.replace(/[A-Z]/g,function(e){return"-"+e});try{return this.doc.defaultView.getComputedStyle(e,null).getPropertyValue(n)}catch(i){return null}}return n=n.replace(/-(\D)/g,function(e,t){return t.toUpperCase()}),"float"==n&&(n=g?"styleFloat":"cssFloat"),n.currentStyle&&r?e.currentStyle[n]:e.style?e.style[n]:t}},setStyles:function(e,t){this.setStyle(e,t)},css:function(e,t,n){this.setStyle(e,t,n)},removeAllAttribs:function(e){return this.run(e,function(e){var t,n=e.attributes;for(t=n.length-1;t>=0;t--)e.removeAttributeNode(n.item(t))})},setAttrib:function(e,n,r){var i=this;if(e&&n)return this.run(e,function(e){var o=i.settings,a=e.getAttribute(n);if(null!==r)switch(n){case"style":if(!d(r,"string"))return u(r,function(t,n){i.setStyle(e,n,t)}),t;o.keep_values&&(r?e.setAttribute("data-mce-style",r,2):e.removeAttribute("data-mce-style",2)),e.style.cssText=r;break;case"class":e.className=r||"";break;case"src":case"href":o.keep_values&&(o.url_converter&&(r=o.url_converter.call(o.url_converter_scope||i,r,n,e)),i.setAttrib(e,"data-mce-"+n,r,2));break;case"shape":e.setAttribute("data-mce-style",r)}d(r)&&null!==r&&0!==r.length?e.setAttribute(n,""+r,2):e.removeAttribute(n,2),a!=r&&o.onSetAttrib&&o.onSetAttrib({attrElm:e,attrName:n,attrValue:r})})},setAttribs:function(e,t){var n=this;return this.run(e,function(e){u(t,function(t,r){n.setAttrib(e,r,t)})})},getAttrib:function(e,t,n){var r,i=this,o;if(e=i.get(e),!e||1!==e.nodeType)return n===o?!1:n;if(d(n)||(n=""),/^(src|href|style|coords|shape)$/.test(t)&&(r=e.getAttribute("data-mce-"+t)))return r;if(g&&i.props[t]&&(r=e[i.props[t]],r=r&&r.nodeValue?r.nodeValue:r),r||(r=e.getAttribute(t,2)),/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noshade|nowrap|readonly|selected)$/.test(t))return e[i.props[t]]===!0&&""===r?t:r?t:"";if("FORM"===e.nodeName&&e.getAttributeNode(t))return e.getAttributeNode(t).nodeValue;if("style"===t&&(r=r||e.style.cssText,r&&(r=i.serializeStyle(i.parseStyle(r),e.nodeName),i.settings.keep_values&&e.setAttribute("data-mce-style",r))),h&&"class"===t&&r&&(r=r.replace(/(apple|webkit)\-[a-z\-]+/gi,"")),g)switch(t){case"rowspan":case"colspan":1===r&&(r="");break;case"size":("+0"===r||20===r||0===r)&&(r="");break;case"width":case"height":case"vspace":case"checked":case"disabled":case"readonly":0===r&&(r="");break;case"hspace":-1===r&&(r="");break;case"maxlength":case"tabindex":(32768===r||2147483647===r||"32768"===r)&&(r="");break;case"multiple":case"compact":case"noshade":case"nowrap":return 65535===r?t:n;case"shape":r=r.toLowerCase();break;default:0===t.indexOf("on")&&r&&(r=(""+r).replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/,"$1"))}return r!==o&&null!==r&&""!==r?""+r:n},getPos:function(e,t){var n=this,r=0,i=0,o,a=n.doc,s;if(e=n.get(e),t=t||a.body,e){if(t===a.body&&e.getBoundingClientRect)return s=e.getBoundingClientRect(),t=n.boxModel?a.documentElement:a.body,r=s.left+(a.documentElement.scrollLeft||a.body.scrollLeft)-t.clientTop,i=s.top+(a.documentElement.scrollTop||a.body.scrollTop)-t.clientLeft,{x:r,y:i};for(o=e;o&&o!=t&&o.nodeType;)r+=o.offsetLeft||0,i+=o.offsetTop||0,o=o.offsetParent;for(o=e.parentNode;o&&o!=t&&o.nodeType;)r-=o.scrollLeft||0,i-=o.scrollTop||0,o=o.parentNode}return{x:r,y:i}},parseStyle:function(e){return this.styles.parse(e)},serializeStyle:function(e,t){return this.styles.serialize(e,t)},addStyle:function(e){var t=this,n=t.doc,r,i;if(t!==c.DOM&&n===document){var o=c.DOM.addedStyles;if(o=o||[],o[e])return;o[e]=!0,c.DOM.addedStyles=o}i=n.getElementById("mceDefaultStyles"),i||(i=n.createElement("style"),i.id="mceDefaultStyles",i.type="text/css",r=n.getElementsByTagName("head")[0],r.firstChild?r.insertBefore(i,r.firstChild):r.appendChild(i)),i.styleSheet?i.styleSheet.cssText+=e:i.appendChild(n.createTextNode(e))},loadCSS:function(e){var n=this,r=n.doc,i;return n!==c.DOM&&r===document?(c.DOM.loadCSS(e),t):(e||(e=""),i=r.getElementsByTagName("head")[0],u(e.split(","),function(e){var t;n.files[e]||(n.files[e]=!0,t=n.create("link",{rel:"stylesheet",href:e}),g&&r.documentMode&&r.recalc&&(t.onload=function(){r.recalc&&r.recalc(),t.onload=null}),i.appendChild(t))}),t)},addClass:function(e,t){return this.run(e,function(e){var n;return t?this.hasClass(e,t)?e.className:(n=this.removeClass(e,t),e.className=n=(""!==n?n+" ":"")+t,n):0})},removeClass:function(e,t){var n=this,r;return n.run(e,function(e){var i;return n.hasClass(e,t)?(r||(r=RegExp("(^|\\s+)"+t+"(\\s+|$)","g")),i=e.className.replace(r," "),i=p(" "!=i?i:""),e.className=i,i||(e.removeAttribute("class"),e.removeAttribute("className")),i):e.className})},hasClass:function(e,t){return e=this.get(e),e&&t?-1!==(" "+e.className+" ").indexOf(" "+t+" "):!1},toggleClass:function(e,n,r){r=r===t?!this.hasClass(e,n):r,this.hasClass(e,n)!==r&&(r?this.addClass(e,n):this.removeClass(e,n))},show:function(e){return this.setStyle(e,"display","block")},hide:function(e){return this.setStyle(e,"display","none")},isHidden:function(e){return e=this.get(e),!e||"none"==e.style.display||"none"==this.getStyle(e,"display")},uniqueId:function(e){return(e?e:"mce_")+this.counter++},setHTML:function(e,t){var n=this;return n.run(e,function(e){if(g){for(;e.firstChild;)e.removeChild(e.firstChild);try{e.innerHTML="
    "+t,e.removeChild(e.firstChild)}catch(r){var i=n.create("div");i.innerHTML="
    "+t,u(f(i.childNodes),function(t,n){n&&e.canHaveHTML&&e.appendChild(t)})}}else e.innerHTML=t;return t})},getOuterHTML:function(e){var t,n=this;return(e=n.get(e))?1===e.nodeType&&n.hasOuterHTML?e.outerHTML:(t=(e.ownerDocument||n.doc).createElement("body"),t.appendChild(e.cloneNode(!0)),t.innerHTML):null},setOuterHTML:function(e,t,n){var r=this;return r.run(e,function(e){function i(){var i,o;for(o=n.createElement("body"),o.innerHTML=t,i=o.lastChild;i;)r.insertAfter(i.cloneNode(!0),e),i=i.previousSibling;r.remove(e)}if(1==e.nodeType)if(n=n||e.ownerDocument||r.doc,g)try{1==e.nodeType&&r.hasOuterHTML?e.outerHTML=t:i()}catch(o){i()}else i()})},decode:a.decode,encode:a.encodeAllRaw,insertAfter:function(e,t){return t=this.get(t),this.run(e,function(e){var n,r;return n=t.parentNode,r=t.nextSibling,r?n.insertBefore(e,r):n.appendChild(e),e})},replace:function(e,t,n){var r=this;return r.run(t,function(t){return d(t,"array")&&(e=e.cloneNode(!0)),n&&u(f(t.childNodes),function(t){e.appendChild(t)}),t.parentNode.replaceChild(e,t)})},rename:function(e,t){var n=this,r;return e.nodeName!=t.toUpperCase()&&(r=n.create(t),u(n.getAttribs(e),function(t){n.setAttrib(r,t.nodeName,n.getAttrib(e,t.nodeName))}),n.replace(r,e,1)),r||e},findCommonAncestor:function(e,t){for(var n=e,r;n;){for(r=t;r&&n!=r;)r=r.parentNode;if(n==r)break;n=n.parentNode}return!n&&e.ownerDocument?e.ownerDocument.documentElement:n},toHex:function(e){return this.styles.toHex(l.trim(e))},getClasses:function(){function e(t){u(t.imports,function(t){e(t)}),u(t.cssRules||t.rules,function(t){switch(t.type||1){case 1:t.selectorText&&u(t.selectorText.split(","),function(e){e=e.replace(/^\s*|\s*$|^\s\./g,""),!/\.mce/.test(e)&&/\.[\w\-]+$/.test(e)&&(o=e,e=e.replace(/.*\.([a-z0-9_\-]+).*/i,"$1"),(!i||(e=i(e,o)))&&(r[e]||(n.push({"class":e}),r[e]=1)))});break;case 3:e(t.styleSheet)}})}var t=this,n=[],r={},i=t.settings.class_filter,o;if(t.classes)return t.classes;try{u(t.doc.styleSheets,e)}catch(a){}return n.length>0&&(t.classes=n),n},run:function(e,t,n){var r=this,i;return"string"==typeof e&&(e=r.get(e)),e?(n=n||this,e.nodeType||!e.length&&0!==e.length?t.call(n,e):(i=[],u(e,function(e,o){e&&("string"==typeof e&&(e=r.get(e)),i.push(t.call(n,e,o)))}),i)):!1},getAttribs:function(e){var t;if(e=this.get(e),!e)return[];if(g){if(t=[],"OBJECT"==e.nodeName)return e.attributes;"OPTION"===e.nodeName&&this.getAttrib(e,"selected")&&t.push({specified:1,nodeName:"selected"});var n=/<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi;return e.cloneNode(!1).outerHTML.replace(n,"").replace(/[\w:\-]+/gi,function(e){t.push({specified:1,nodeName:e})}),t}return e.attributes},isEmpty:function(e,t){var n=this,r,o,a,s,l,c=0;if(e=e.firstChild){s=new i(e,e.parentNode),t=t||n.schema?n.schema.getNonEmptyElements():null;do{if(a=e.nodeType,1===a){if(e.getAttribute("data-mce-bogus"))continue;if(l=e.nodeName.toLowerCase(),t&&t[l]){if("br"===l){c++;continue}return!1}for(o=n.getAttribs(e),r=e.attributes.length;r--;)if(l=e.attributes[r].nodeName,"name"===l||"data-mce-bookmark"===l)return!1}if(8==a)return!1;if(3===a&&!y.test(e.nodeValue))return!1}while(e=s.next())}return 1>=c},createRng:function(){var e=this.doc;return e.createRange?e.createRange():new o(this)},nodeIndex:function(e,t){var n=0,r,i,o;if(e)for(r=e.nodeType,e=e.previousSibling,i=e;e;e=e.previousSibling)o=e.nodeType,(!t||3!=o||o!=r&&e.nodeValue.length)&&(n++,r=o);return n},split:function(e,n,r){function i(e){function t(e){var t=e.previousSibling&&"SPAN"==e.previousSibling.nodeName,n=e.nextSibling&&"SPAN"==e.nextSibling.nodeName;return t&&n}var n,r=e.childNodes,a=e.nodeType;if(1!=a||"bookmark"!=e.getAttribute("data-mce-type")){for(n=r.length-1;n>=0;n--)i(r[n]);if(9!=a){if(3==a&&e.nodeValue.length>0){var s=p(e.nodeValue).length;if(!o.isBlock(e.parentNode)||s>0||0===s&&t(e))return}else if(1==a&&(r=e.childNodes,1==r.length&&r[0]&&1==r[0].nodeType&&"bookmark"==r[0].getAttribute("data-mce-type")&&e.parentNode.insertBefore(r[0],e),r.length||/^(br|hr|input|img)$/i.test(e.nodeName)))return;o.remove(e)}return e}}var o=this,a=o.createRng(),s,l,c;return e&&n?(a.setStart(e.parentNode,o.nodeIndex(e)),a.setEnd(n.parentNode,o.nodeIndex(n)),s=a.extractContents(),a=o.createRng(),a.setStart(n.parentNode,o.nodeIndex(n)+1),a.setEnd(e.parentNode,o.nodeIndex(e)+1),l=a.extractContents(),c=e.parentNode,c.insertBefore(i(s),e),r?c.replaceChild(r,n):c.insertBefore(n,e),c.insertBefore(i(l),e),o.remove(e),r||n):t},bind:function(e,t,n,r){return this.events.bind(e,t,n,r||this)},unbind:function(e,t,n){return this.events.unbind(e,t,n)},fire:function(e,t,n){return this.events.fire(e,t,n)},getContentEditable:function(e){var t;return 1!=e.nodeType?null:(t=e.getAttribute("data-mce-contenteditable"),t&&"inherit"!==t?t:"inherit"!==e.contentEditable?e.contentEditable:null)},destroy:function(){var e=this;e.win=e.doc=e.root=e.events=e.frag=null},dumpRng:function(e){return"startContainer: "+e.startContainer.nodeName+", startOffset: "+e.startOffset+", endContainer: "+e.endContainer.nodeName+", endOffset: "+e.endOffset},_findSib:function(e,t,n){var r=this,i=t;if(e)for("string"==typeof i&&(i=function(e){return r.is(e,t)}),e=e[n];e;e=e[n])if(i(e))return e;return null}},c.DOM=new c(document),c}),r(v,[g,f],function(e,n){function r(){function e(e,t){function n(){o.remove(s),a&&(a.onreadystatechange=a.onload=a=null),t()}function r(){"undefined"!=typeof console&&console.log&&console.log("Failed to load: "+e)}var o=i,a,s;s=o.uniqueId(),a=document.createElement("script"),a.id=s,a.type="text/javascript",a.src=e,a.onload=n,a.onreadystatechange=function(){/loaded|complete/.test(a.readyState)&&n()},a.onerror=r,(document.getElementsByTagName("head")[0]||document.body).appendChild(a)}var n=0,r=1,s=2,l={},c=[],u={},d=[],f=0,p;this.isDone=function(e){return l[e]==s},this.markDone=function(e){l[e]=s},this.add=this.load=function(e,t,r){var i=l[e];i==p&&(c.push(e),l[e]=n),t&&(u[e]||(u[e]=[]),u[e].push({func:t,scope:r||this}))},this.loadQueue=function(e,t){this.loadScripts(c,e,t)},this.loadScripts=function(n,i,c){function m(e){o(u[e],function(e){e.func.call(e.scope)}),u[e]=p}var h;d.push({func:i,scope:c||this}),h=function(){var i=a(n);n.length=0,o(i,function(n){return l[n]==s?(m(n),t):(l[n]!=r&&(l[n]=r,f++,e(n,function(){l[n]=s,f--,m(n),h()})),t)}),f||(o(d,function(e){e.func.call(e.scope)}),d.length=0)},h()}}var i=e.DOM,o=n.each,a=n.grep;return r.ScriptLoader=new r,r}),r(y,[v,f],function(e,n){function r(){var e=this;e.items=[],e.urls={},e.lookup={}}var i=n.each;return r.prototype={get:function(e){return this.lookup[e]?this.lookup[e].instance:t},dependencies:function(e){var t;return this.lookup[e]&&(t=this.lookup[e].dependencies),t||[]},requireLangPack:function(t){var n=r.settings;n&&n.language&&n.language_load!==!1&&e.ScriptLoader.add(this.urls[t]+"/langs/"+n.language+".js")},add:function(e,t,n){return this.items.push(t),this.lookup[e]={instance:t,dependencies:n},t},createUrl:function(e,t){return"object"==typeof t?t:{prefix:e.prefix,resource:t,suffix:e.suffix}},addComponents:function(t,n){var r=this.urls[t];i(n,function(t){e.ScriptLoader.add(r+"/"+t)})},load:function(n,o,a,s){function l(){var r=c.dependencies(n);i(r,function(e){var n=c.createUrl(o,e);c.load(n.resource,n,t,t)}),a&&(s?a.call(s):a.call(e))}var c=this,u=o;c.urls[n]||("object"==typeof o&&(u=o.prefix+o.resource+o.suffix),0!==u.indexOf("/")&&-1==u.indexOf("://")&&(u=r.baseURL+"/"+u),c.urls[n]=u.substring(0,u.lastIndexOf("/")),c.lookup[n]?l():e.ScriptLoader.add(u,l,s))}},r.PluginManager=new r,r.ThemeManager=new r,r}),r(b,[],function(){function e(e,t,n){var r,i,o=n?"lastChild":"firstChild",a=n?"prev":"next";if(e[o])return e[o];if(e!==t){if(r=e[a])return r;for(i=e.parent;i&&i!==t;i=i.parent)if(r=i[a])return r}}function t(e,t){this.name=e,this.type=t,1===t&&(this.attributes=[],this.attributes.map={})}var n=/^[ \t\r\n]*$/,r={"#text":3,"#comment":8,"#cdata":4,"#pi":7,"#doctype":10,"#document-fragment":11};return t.prototype={replace:function(e){var t=this;return e.parent&&e.remove(),t.insert(e,t),t.remove(),t},attr:function(e,t){var n=this,r,i,o;if("string"!=typeof e){for(i in e)n.attr(i,e[i]);return n}if(r=n.attributes){if(t!==o){if(null===t){if(e in r.map)for(delete r.map[e],i=r.length;i--;)if(r[i].name===e)return r=r.splice(i,1),n;return n}if(e in r.map){for(i=r.length;i--;)if(r[i].name===e){r[i].value=t;break}}else r.push({name:e,value:t});return r.map[e]=t,n}return r.map[e]}},clone:function(){var e=this,n=new t(e.name,e.type),r,i,o,a,s;if(o=e.attributes){for(s=[],s.map={},r=0,i=o.length;i>r;r++)a=o[r],"id"!==a.name&&(s[s.length]={name:a.name,value:a.value},s.map[a.name]=a.value);n.attributes=s}return n.value=e.value,n.shortEnded=e.shortEnded,n},wrap:function(e){var t=this;return t.parent.insert(e,t),e.append(t),t},unwrap:function(){var e=this,t,n;for(t=e.firstChild;t;)n=t.next,e.insert(t,e,!0),t=n;e.remove()},remove:function(){var e=this,t=e.parent,n=e.next,r=e.prev;return t&&(t.firstChild===e?(t.firstChild=n,n&&(n.prev=null)):r.next=n,t.lastChild===e?(t.lastChild=r,r&&(r.next=null)):n.prev=r,e.parent=e.next=e.prev=null),e},append:function(e){var t=this,n;return e.parent&&e.remove(),n=t.lastChild,n?(n.next=e,e.prev=n,t.lastChild=e):t.lastChild=t.firstChild=e,e.parent=t,e},insert:function(e,t,n){var r;return e.parent&&e.remove(),r=t.parent||this,n?(t===r.firstChild?r.firstChild=e:t.prev.next=e,e.prev=t.prev,e.next=t,t.prev=e):(t===r.lastChild?r.lastChild=e:t.next.prev=e,e.next=t.next,e.prev=t,t.next=e),e.parent=r,e},getAll:function(t){var n=this,r,i=[];for(r=n.firstChild;r;r=e(r,n))r.name===t&&i.push(r);return i},empty:function(){var t=this,n,r,i;if(t.firstChild){for(n=[],i=t.firstChild;i;i=e(i,t))n.push(i);for(r=n.length;r--;)i=n[r],i.parent=i.firstChild=i.lastChild=i.next=i.prev=null}return t.firstChild=t.lastChild=null,t},isEmpty:function(t){var r=this,i=r.firstChild,o,a;if(i)do{if(1===i.type){if(i.attributes.map["data-mce-bogus"])continue;if(t[i.name])return!1;for(o=i.attributes.length;o--;)if(a=i.attributes[o].name,"name"===a||0===a.indexOf("data-mce-"))return!1}if(8===i.type)return!1;if(3===i.type&&!n.test(i.value))return!1}while(i=e(i,r));return!0},walk:function(t){return e(this,null,t)}},t.create=function(e,n){var i,o;if(i=new t(e,r[e]||1),n)for(o in n)i.attr(o,n[o]);return i},t}),r(C,[f],function(e){function t(e,t){return e?e.split(t||" "):[]}function n(e){function n(e,n,r){function i(e){var t={},n,r;for(n=0,r=e.length;r>n;n++)t[e[n]]={};return t}var o,l,c,u=arguments;for(r=r||[],n=n||"","string"==typeof r&&(r=t(r)),l=3;u.length>l;l++)"string"==typeof u[l]&&(u[l]=t(u[l])),r.push.apply(r,u[l]);for(e=t(e),o=e.length;o--;)c=[].concat(s,t(n)),a[e[o]]={attributes:i(c),attributesOrder:c,children:i(r)}}function i(e,n){var r,i,o,s;for(e=t(e),r=e.length,n=t(n);r--;)for(i=a[e[r]],o=0,s=n.length;s>o;o++)i.attributes[n[o]]={},i.attributesOrder.push(n[o])}var a={},s,l,c,u,d,f,p;return r[e]?r[e]:(s=t("id accesskey class dir lang style tabindex title"),l=t("onabort onblur oncancel oncanplay oncanplaythrough onchange onclick onclose oncontextmenu oncuechange ondblclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop ondurationchange onemptied onended onerror onfocus oninput oninvalid onkeydown onkeypress onkeyup onload onloadeddata onloadedmetadata onloadstart onmousedown onmousemove onmouseout onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange onreset onscroll onseeked onseeking onseeking onselect onshow onstalled onsubmit onsuspend ontimeupdate onvolumechange onwaiting"),c=t("address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul"),u=t("a abbr b bdo br button cite code del dfn em embed i iframe img input ins kbd label map noscript object q s samp script select small span strong sub sup textarea u var #text #comment"),"html4"!=e&&(s.push.apply(s,t("contenteditable contextmenu draggable dropzone hidden spellcheck translate")),c.push.apply(c,t("article aside details dialog figure header footer hgroup section nav")),u.push.apply(u,t("audio canvas command datalist mark meter output progress time wbr video ruby bdi keygen"))),"html5-strict"!=e&&(s.push("xml:lang"),p=t("acronym applet basefont big font strike tt"),u.push.apply(u,p),o(p,function(e){n(e,"",u)}),f=t("center dir isindex noframes"),c.push.apply(c,f),d=[].concat(c,u),o(f,function(e){n(e,"",d)})),d=d||[].concat(c,u),n("html","manifest","head body"),n("head","","base command link meta noscript script style title"),n("title hr noscript br"),n("base","href target"),n("link","href rel media hreflang type sizes hreflang"),n("meta","name http-equiv content charset"),n("style","media type scoped"),n("script","src async defer type charset"),n("body","onafterprint onbeforeprint onbeforeunload onblur onerror onfocus onhashchange onload onmessage onoffline ononline onpagehide onpageshow onpopstate onresize onscroll onstorage onunload",d),n("address dt dd div caption","",d),n("h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn","",u),n("blockquote","cite",d),n("ol","reversed start type","li"),n("ul","","li"),n("li","value",d),n("dl","","dt dd"),n("a","href target rel media hreflang type",u),n("q","cite",u),n("ins del","cite datetime",d),n("img","src alt usemap ismap width height"),n("iframe","src name width height",d),n("embed","src type width height"),n("object","data type typemustmatch name usemap form width height",d,"param"),n("param","name value"),n("map","name",d,"area"),n("area","alt coords shape href target rel media hreflang type"),n("table","border","caption colgroup thead tfoot tbody tr"+("html4"==e?" col":"")),n("colgroup","span","col"),n("col","span"),n("tbody thead tfoot","","tr"),n("tr","","td th"),n("td","colspan rowspan headers",d),n("th","colspan rowspan headers scope abbr",d),n("form","accept-charset action autocomplete enctype method name novalidate target",d),n("fieldset","disabled form name",d,"legend"),n("label","form for",u),n("input","accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate formtarget height list max maxlength min multiple name pattern readonly required size src step type value width"),n("button","disabled form formaction formenctype formmethod formnovalidate formtarget name type value","html4"==e?d:u),n("select","disabled form multiple name required size","option optgroup"),n("optgroup","disabled label","option"),n("option","disabled label selected value"),n("textarea","cols dirname disabled form maxlength name readonly required rows wrap"),n("menu","type label",d,"li"),n("noscript","",d),"html4"!=e&&(n("wbr"),n("ruby","",u,"rt rp"),n("figcaption","",d),n("mark rt rp summary bdi","",u),n("canvas","width height",d),n("video","src crossorigin poster preload autoplay mediagroup loop muted controls width height",d,"track source"),n("audio","src crossorigin preload autoplay mediagroup loop muted controls",d,"track source"),n("source","src type media"),n("track","kind src srclang label default"),n("datalist","",u,"option"),n("article section nav aside header footer","",d),n("hgroup","","h1 h2 h3 h4 h5 h6"),n("figure","",d,"figcaption"),n("time","datetime",u),n("dialog","open",d),n("command","type label icon disabled checked radiogroup command"),n("output","for form name",u),n("progress","value max",u),n("meter","value min max low high optimum",u),n("details","open",d,"summary"),n("keygen","autofocus challenge disabled form keytype name")),"html5-strict"!=e&&(i("script","language xml:space"),i("style","xml:space"),i("object","declare classid codebase codetype archive standby align border hspace vspace"),i("param","valuetype type"),i("a","charset name rev shape coords"),i("br","clear"),i("applet","codebase archive code object alt name width height align hspace vspace"),i("img","name longdesc align border hspace vspace"),i("iframe","longdesc frameborder marginwidth marginheight scrolling align"),i("font basefont","size color face"),i("input","usemap align"),i("select","onchange"),i("textarea"),i("h1 h2 h3 h4 h5 h6 div p legend caption","align"),i("ul","type compact"),i("li","type"),i("ol dl menu dir","compact"),i("pre","width xml:space"),i("hr","align noshade size width"),i("isindex","prompt"),i("table","summary width frame rules cellspacing cellpadding align bgcolor"),i("col","width align char charoff valign"),i("colgroup","width align char charoff valign"),i("thead","align char charoff valign"),i("tr","align char charoff valign bgcolor"),i("th","axis align char charoff valign nowrap bgcolor width height"),i("form","accept"),i("td","abbr axis scope align char charoff valign nowrap bgcolor width height"),i("tfoot","align char charoff valign"),i("tbody","align char charoff valign"),i("area","nohref"),i("body","background bgcolor text link vlink alink")),"html4"!=e&&(i("input button select textarea","autofocus"),i("input textarea","placeholder"),i("a","download"),i("link script img","crossorigin"),i("iframe","srcdoc sandbox seamless allowfullscreen")),o(t("a form meter progress dfn"),function(e){a[e]&&delete a[e].children[e] +}),delete a.caption.children.table,r[e]=a,a)}var r={},i=e.makeMap,o=e.each,a=e.extend,s=e.explode,l=e.inArray;return function(e){function c(t,n,o){var s=e[t];return s?s=i(s,",",i(s.toUpperCase()," ")):(s=r[t],s||(s=i(n," ",i(n.toUpperCase()," ")),s=a(s,o),r[t]=s)),s}function u(e){return RegExp("^"+e.replace(/([?+*])/g,".$1")+"$")}function d(e){var n,r,o,a,s,c,d,f,p,m,h,g,y,C,x,w,_,N,k,E=/^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)\])?$/,S=/^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/,T=/[*?+]/;if(e)for(e=t(e,","),v["@"]&&(w=v["@"].attributes,_=v["@"].attributesOrder),n=0,r=e.length;r>n;n++)if(s=E.exec(e[n])){if(C=s[1],p=s[2],x=s[3],f=s[5],g={},y=[],c={attributes:g,attributesOrder:y},"#"===C&&(c.paddEmpty=!0),"-"===C&&(c.removeEmpty=!0),"!"===s[4]&&(c.removeEmptyAttrs=!0),w){for(N in w)g[N]=w[N];y.push.apply(y,_)}if(f)for(f=t(f,"|"),o=0,a=f.length;a>o;o++)if(s=S.exec(f[o])){if(d={},h=s[1],m=s[2].replace(/::/g,":"),C=s[3],k=s[4],"!"===h&&(c.attributesRequired=c.attributesRequired||[],c.attributesRequired.push(m),d.required=!0),"-"===h){delete g[m],y.splice(l(y,m),1);continue}C&&("="===C&&(c.attributesDefault=c.attributesDefault||[],c.attributesDefault.push({name:m,value:k}),d.defaultValue=k),":"===C&&(c.attributesForced=c.attributesForced||[],c.attributesForced.push({name:m,value:k}),d.forcedValue=k),"<"===C&&(d.validValues=i(k,"?"))),T.test(m)?(c.attributePatterns=c.attributePatterns||[],d.pattern=u(m),c.attributePatterns.push(d)):(g[m]||y.push(m),g[m]=d)}w||"@"!=p||(w=g,_=y),x&&(c.outputName=p,v[x]=c),T.test(p)?(c.pattern=u(p),b.push(c)):v[p]=c}}function f(e){v={},b=[],d(e),o(x,function(e,t){y[t]=e.children})}function p(e){var n=/^(~)?(.+)$/;e&&o(t(e,","),function(e){var t=n.exec(e),r="~"===t[1],i=r?"span":"div",a=t[2];y[a]=y[i],R[a]=i,r||(E[a.toUpperCase()]={},E[a]={}),v[a]||(v[a]=v[i]),o(y,function(e){e[i]&&(e[a]=e[i])})})}function m(e){var n=/^([+\-]?)(\w+)\[([^\]]+)\]$/;e&&o(t(e,","),function(e){var r=n.exec(e),i,a;r&&(a=r[1],i=a?y[r[2]]:y[r[2]]={"#comment":{}},i=y[r[2]],o(t(r[3],"|"),function(e){"-"===a?delete i[e]:i[e]={}}))})}function h(e){var t=v[e],n;if(t)return t;for(n=b.length;n--;)if(t=b[n],t.pattern.test(e))return t}var g=this,v={},y={},b=[],C,x,w,_,N,k,E,S,T,R={},A={};e=e||{},x=n(e.schema),e.verify_html===!1&&(e.valid_elements="*[*]"),e.valid_styles&&(C={},o(e.valid_styles,function(e,t){C[t]=s(e)})),w=c("whitespace_elements","pre script noscript style textarea video audio iframe object"),_=c("self_closing_elements","colgroup dd dt li option p td tfoot th thead tr"),N=c("short_ended_elements","area base basefont br col frame hr img input isindex link meta param embed source wbr track"),k=c("boolean_attributes","checked compact declare defer disabled ismap multiple nohref noresize noshade nowrap readonly selected autoplay loop controls"),S=c("non_empty_elements","td th iframe video audio object",N),T=c("text_block_elements","h1 h2 h3 h4 h5 h6 p div address pre form blockquote center dir fieldset header footer article section hgroup aside nav figure"),E=c("block_elements","hr table tbody thead tfoot th tr td li ol ul caption dl dt dd noscript menu isindex samp option datalist select optgroup",T),o((e.special||"script noscript style textarea").split(" "),function(e){A[e]=RegExp("]*>","gi")}),e.valid_elements?f(e.valid_elements):(o(x,function(e,t){v[t]={attributes:e.attributes,attributesOrder:e.attributesOrder},y[t]=e.children}),"html5"!=e.schema&&o(t("strong/b em/i"),function(e){e=t(e,"/"),v[e[1]].outputName=e[0]}),v.img.attributesDefault=[{name:"alt",value:""}],o(t("ol ul sub sup blockquote span font a table tbody tr strong em b i"),function(e){v[e]&&(v[e].removeEmpty=!0)}),o(t("p h1 h2 h3 h4 h5 h6 th td pre div address caption"),function(e){v[e].paddEmpty=!0}),o(t("span"),function(e){v[e].removeEmptyAttrs=!0})),p(e.custom_elements),m(e.valid_children),d(e.extended_valid_elements),m("+ol[ul|ol],+ul[ul|ol]"),e.invalid_elements&&o(s(e.invalid_elements),function(e){v[e]&&delete v[e]}),h("span")||d("span[!data-mce-type|*]"),g.children=y,g.styles=C,g.getBoolAttrs=function(){return k},g.getBlockElements=function(){return E},g.getTextBlockElements=function(){return T},g.getShortEndedElements=function(){return N},g.getSelfClosingElements=function(){return _},g.getNonEmptyElements=function(){return S},g.getWhiteSpaceElements=function(){return w},g.getSpecialElements=function(){return A},g.isValidChild=function(e,t){var n=y[e];return!(!n||!n[t])},g.isValid=function(e,t){var n,r,i=h(e);if(i){if(!t)return!0;if(i.attributes[t])return!0;if(n=i.attributePatterns)for(r=n.length;r--;)if(n[r].pattern.test(e))return!0}return!1},g.getElementRule=h,g.getCustomElements=function(){return R},g.addValidElements=d,g.setValidElements=f,g.addCustomElements=p,g.addValidChildren=m,g.elements=v}}),r(x,[C,m,f],function(e,t,n){var r=n.each;return function(n,i){var o=this,a=function(){};n=n||{},o.schema=i=i||new e,n.fix_self_closing!==!1&&(n.fix_self_closing=!0),r("comment cdata text start end pi doctype".split(" "),function(e){e&&(o[e]=n[e]||a)}),o.parse=function(e){function r(e){var t,n;for(t=d.length;t--&&d[t].name!==e;);if(t>=0){for(n=d.length-1;n>=t;n--)e=d[n],e.valid&&a.end(e.name);d.length=t}}function o(e,t,n,r,i){var o,a;if(t=t.toLowerCase(),n=t in b?t:I(n||r||i||""),x&&!g&&0!==t.indexOf("data-mce-")){if(o=E[t],!o&&S){for(a=S.length;a--&&(o=S[a],!o.pattern.test(t)););-1===a&&(o=null)}if(!o)return;if(o.validValues&&!(n in o.validValues))return}f.map[t]=n,f.push({name:t,value:n})}var a=this,s,l=0,c,u,d=[],f,p,m,h,g,v,y,b,C,x,w,_,N,k,E,S,T,R,A,B,L,H,M,D,P,O=0,I=t.decode,F;for(H=RegExp("<(?:(?:!--([\\w\\W]*?)-->)|(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|(?:!DOCTYPE([\\w\\W]*?)>)|(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|(?:\\/([^>]+)>)|(?:([A-Za-z0-9\\-\\:\\.]+)((?:\\s+[^\"'>]+(?:(?:\"[^\"]*\")|(?:'[^']*')|[^>]*))*|\\/|\\s+)>))","g"),M=/([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g,y=i.getShortEndedElements(),L=n.self_closing_elements||i.getSelfClosingElements(),b=i.getBoolAttrs(),x=n.validate,v=n.remove_internals,F=n.fix_self_closing,D=i.getSpecialElements();s=H.exec(e);){if(s.index>l&&a.text(I(e.substr(l,s.index-l))),c=s[6])c=c.toLowerCase(),":"===c.charAt(0)&&(c=c.substr(1)),r(c);else if(c=s[7]){if(c=c.toLowerCase(),":"===c.charAt(0)&&(c=c.substr(1)),C=c in y,F&&L[c]&&d.length>0&&d[d.length-1].name===c&&r(c),!x||(w=i.getElementRule(c))){if(_=!0,x&&(E=w.attributes,S=w.attributePatterns),(k=s[8])?(g=-1!==k.indexOf("data-mce-type"),g&&v&&(_=!1),f=[],f.map={},k.replace(M,o)):(f=[],f.map={}),x&&!g){if(T=w.attributesRequired,R=w.attributesDefault,A=w.attributesForced,B=w.removeEmptyAttrs,B&&!f.length&&(_=!1),A)for(p=A.length;p--;)N=A[p],h=N.name,P=N.value,"{$uid}"===P&&(P="mce_"+O++),f.map[h]=P,f.push({name:h,value:P});if(R)for(p=R.length;p--;)N=R[p],h=N.name,h in f.map||(P=N.value,"{$uid}"===P&&(P="mce_"+O++),f.map[h]=P,f.push({name:h,value:P}));if(T){for(p=T.length;p--&&!(T[p]in f.map););-1===p&&(_=!1)}f.map["data-mce-bogus"]&&(_=!1)}_&&a.start(c,f,C)}else _=!1;if(u=D[c]){u.lastIndex=l=s.index+s[0].length,(s=u.exec(e))?(_&&(m=e.substr(l,s.index-l)),l=s.index+s[0].length):(m=e.substr(l),l=e.length),_&&(m.length>0&&a.text(m,!0),a.end(c)),H.lastIndex=l;continue}C||(k&&k.indexOf("/")==k.length-1?_&&a.end(c):d.push({name:c,valid:_}))}else(c=s[1])?a.comment(c):(c=s[2])?a.cdata(c):(c=s[3])?a.doctype(c):(c=s[4])&&a.pi(c,s[5]);l=s.index+s[0].length}for(e.length>l&&a.text(I(e.substr(l))),p=d.length-1;p>=0;p--)c=d[p],c.valid&&a.end(c.name)}}}),r(w,[b,C,x,f],function(e,n,r,i){var o=i.makeMap,a=i.each,s=i.explode,l=i.extend;return function(i,c){function u(t){var n,r,i,a,s,l,u,f,p,m,h,g,v,y;for(h=o("tr,td,th,tbody,thead,tfoot,table"),m=c.getNonEmptyElements(),g=c.getTextBlockElements(),n=0;t.length>n;n++)if(r=t[n],r.parent&&!r.fixed)if(g[r.name]&&"li"==r.parent.name){for(v=r.next;v&&g[v.name];)v.name="li",v.fixed=!0,r.parent.insert(v,r.parent),v=v.next;r.unwrap(r)}else{for(a=[r],i=r.parent;i&&!c.isValidChild(i.name,r.name)&&!h[i.name];i=i.parent)a.push(i);if(i&&a.length>1){for(a.reverse(),s=l=d.filterNode(a[0].clone()),p=0;a.length-1>p;p++){for(c.isValidChild(l.name,a[p].name)?(u=d.filterNode(a[p].clone()),l.append(u)):u=l,f=a[p].firstChild;f&&f!=a[p+1];)y=f.next,u.append(f),f=y;l=u}s.isEmpty(m)?i.insert(r,a[0],!0):(i.insert(s,a[0],!0),i.insert(r,s)),i=a[0],(i.isEmpty(m)||i.firstChild===i.lastChild&&"br"===i.firstChild.name)&&i.empty().remove()}else if(r.parent){if("li"===r.name){if(v=r.prev,v&&("ul"===v.name||"ul"===v.name)){v.append(r);continue}if(v=r.next,v&&("ul"===v.name||"ul"===v.name)){v.insert(r,v.firstChild,!0);continue}r.wrap(d.filterNode(new e("ul",1)));continue}c.isValidChild(r.parent.name,"div")&&c.isValidChild("div",r.name)?r.wrap(d.filterNode(new e("div",1))):"style"===r.name||"script"===r.name?r.empty().remove():r.unwrap()}}}var d=this,f={},p=[],m={},h={};i=i||{},i.validate="validate"in i?i.validate:!0,i.root_name=i.root_name||"body",d.schema=c=c||new n,d.filterNode=function(e){var t,n,r;n in f&&(r=m[n],r?r.push(e):m[n]=[e]),t=p.length;for(;t--;)n=p[t].name,n in e.attributes.map&&(r=h[n],r?r.push(e):h[n]=[e]);return e},d.addNodeFilter=function(e,t){a(s(e),function(e){var n=f[e];n||(f[e]=n=[]),n.push(t)})},d.addAttributeFilter=function(e,n){a(s(e),function(e){var r;for(r=0;p.length>r;r++)if(p[r].name===e)return p[r].callbacks.push(n),t;p.push({name:e,callbacks:[n]})})},d.parse=function(n,a){function s(){function e(e){e&&(t=e.firstChild,t&&3==t.type&&(t.value=t.value.replace(A,"")),t=e.lastChild,t&&3==t.type&&(t.value=t.value.replace(H,"")))}var t=b.firstChild,n,r;if(c.isValidChild(b.name,F.toLowerCase())){for(;t;)n=t.next,3==t.type||1==t.type&&"p"!==t.name&&!R[t.name]&&!t.attr("data-mce-type")?r?r.append(t):(r=d(F,1),b.insert(r,t),r.append(t)):(e(r),r=null),t=n;e(r)}}function d(t,n){var r=new e(t,n),i;return t in f&&(i=m[t],i?i.push(r):m[t]=[r]),r}function g(e){var t,n,r;for(t=e.prev;t&&3===t.type;)n=t.value.replace(H,""),n.length>0?(t.value=n,t=t.prev):(r=t.prev,t.remove(),t=r)}function v(e){var t,n={};for(t in e)"li"!==t&&"p"!=t&&(n[t]=e[t]);return n}var y,b,C,x,w,_,N,k,E,S,T,R,A,B=[],L,H,M,D,P,O,I,F;if(a=a||{},m={},h={},R=l(o("script,style,head,html,body,title,meta,param"),c.getBlockElements()),I=c.getNonEmptyElements(),O=c.children,T=i.validate,F="forced_root_block"in a?a.forced_root_block:i.forced_root_block,P=c.getWhiteSpaceElements(),A=/^[ \t\r\n]+/,H=/[ \t\r\n]+$/,M=/[ \t\r\n]+/g,D=/^[ \t\r\n]+$/,y=new r({validate:T,self_closing_elements:v(c.getSelfClosingElements()),cdata:function(e){C.append(d("#cdata",4)).value=e},text:function(e,t){var n;L||(e=e.replace(M," "),C.lastChild&&R[C.lastChild.name]&&(e=e.replace(A,""))),0!==e.length&&(n=d("#text",3),n.raw=!!t,C.append(n).value=e)},comment:function(e){C.append(d("#comment",8)).value=e},pi:function(e,t){C.append(d(e,7)).value=t,g(C)},doctype:function(e){var t;t=C.append(d("#doctype",10)),t.value=e,g(C)},start:function(e,t,n){var r,i,o,a,s;if(o=T?c.getElementRule(e):{}){for(r=d(o.outputName||e,1),r.attributes=t,r.shortEnded=n,C.append(r),s=O[C.name],s&&O[r.name]&&!s[r.name]&&B.push(r),i=p.length;i--;)a=p[i].name,a in t.map&&(E=h[a],E?E.push(r):h[a]=[r]);R[e]&&g(r),n||(C=r),!L&&P[e]&&(L=!0)}},end:function(n){var r,i,o,a,s;if(i=T?c.getElementRule(n):{}){if(R[n]&&!L){if(r=C.firstChild,r&&3===r.type)if(o=r.value.replace(A,""),o.length>0)r.value=o,r=r.next;else for(a=r.next,r.remove(),r=a;r&&3===r.type;)o=r.value,a=r.next,(0===o.length||D.test(o))&&(r.remove(),r=a),r=a;if(r=C.lastChild,r&&3===r.type)if(o=r.value.replace(H,""),o.length>0)r.value=o,r=r.prev;else for(a=r.prev,r.remove(),r=a;r&&3===r.type;)o=r.value,a=r.prev,(0===o.length||D.test(o))&&(r.remove(),r=a),r=a}if(L&&P[n]&&(L=!1),(i.removeEmpty||i.paddEmpty)&&C.isEmpty(I))if(i.paddEmpty)C.empty().append(new e("#text","3")).value="\u00a0";else if(!C.attributes.map.name&&!C.attributes.map.id)return s=C.parent,C.empty().remove(),C=s,t;C=C.parent}}},c),b=C=new e(a.context||i.root_name,11),y.parse(n),T&&B.length&&(a.context?a.invalid=!0:u(B)),F&&("body"==b.name||a.isRootContent)&&s(),!a.invalid){for(S in m){for(E=f[S],x=m[S],N=x.length;N--;)x[N].parent||x.splice(N,1);for(w=0,_=E.length;_>w;w++)E[w](x,S,a)}for(w=0,_=p.length;_>w;w++)if(E=p[w],E.name in h){for(x=h[E.name],N=x.length;N--;)x[N].parent||x.splice(N,1);for(N=0,k=E.callbacks.length;k>N;N++)E.callbacks[N](x,E.name,a)}}return b},i.remove_trailing_brs&&d.addNodeFilter("br",function(t){var n,r=t.length,i,o=l({},c.getBlockElements()),a=c.getNonEmptyElements(),s,u,d,f,p,m;for(o.body=1,n=0;r>n;n++)if(i=t[n],s=i.parent,o[i.parent.name]&&i===s.lastChild){for(d=i.prev;d;){if(f=d.name,"span"!==f||"bookmark"!==d.attr("data-mce-type")){if("br"!==f)break;if("br"===f){i=null;break}}d=d.prev}i&&(i.remove(),s.isEmpty(a)&&(p=c.getElementRule(s.name),p&&(p.removeEmpty?s.remove():p.paddEmpty&&(s.empty().append(new e("#text",3)).value="\u00a0"))))}else{for(u=i;s.firstChild===u&&s.lastChild===u&&(u=s,!o[s.name]);)s=s.parent;u===s&&(m=new e("#text",3),m.value="\u00a0",i.replace(m))}}),i.allow_html_in_named_anchor||d.addAttributeFilter("id,name",function(e){for(var t=e.length,n,r,i,o;t--;)if(o=e[t],"a"===o.name&&o.firstChild&&!o.attr("href")){i=o.parent,n=o.lastChild;do r=n.prev,i.insert(n,o),n=r;while(n)}})}}),r(_,[m,f],function(e,t){var n=t.makeMap;return function(t){var r=[],i,o,a,s,l;return t=t||{},i=t.indent,o=n(t.indent_before||""),a=n(t.indent_after||""),s=e.getEncodeFunc(t.entity_encoding||"raw",t.entities),l="html"==t.element_format,{start:function(e,t,n){var c,u,d,f;if(i&&o[e]&&r.length>0&&(f=r[r.length-1],f.length>0&&"\n"!==f&&r.push("\n")),r.push("<",e),t)for(c=0,u=t.length;u>c;c++)d=t[c],r.push(" ",d.name,'="',s(d.value,!0),'"');r[r.length]=!n||l?">":" />",n&&i&&a[e]&&r.length>0&&(f=r[r.length-1],f.length>0&&"\n"!==f&&r.push("\n"))},end:function(e){var t;r.push(""),i&&a[e]&&r.length>0&&(t=r[r.length-1],t.length>0&&"\n"!==t&&r.push("\n"))},text:function(e,t){e.length>0&&(r[r.length]=t?e:s(e))},cdata:function(e){r.push("")},comment:function(e){r.push("")},pi:function(e,t){t?r.push(""):r.push(""),i&&r.push("\n")},doctype:function(e){r.push("",i?"\n":"")},reset:function(){r.length=0},getContent:function(){return r.join("").replace(/\n$/,"")}}}}),r(N,[_,C],function(e,t){return function(n,r){var i=this,o=new e(n);n=n||{},n.validate="validate"in n?n.validate:!0,i.schema=r=r||new t,i.writer=o,i.serialize=function(e){function t(e){var n=i[e.type],s,l,c,u,d,f,p,m,h;if(n)n(e);else{if(s=e.name,l=e.shortEnded,c=e.attributes,a&&c&&c.length>1){for(f=[],f.map={},h=r.getElementRule(e.name),p=0,m=h.attributesOrder.length;m>p;p++)u=h.attributesOrder[p],u in c.map&&(d=c.map[u],f.map[u]=d,f.push({name:u,value:d}));for(p=0,m=c.length;m>p;p++)u=c[p].name,u in f.map||(d=c.map[u],f.map[u]=d,f.push({name:u,value:d}));c=f}if(o.start(e.name,c,l),!l){if(e=e.firstChild)do t(e);while(e=e.next);o.end(s)}}}var i,a;return a=n.validate,i={3:function(e){o.text(e.value,e.raw)},8:function(e){o.comment(e.value)},7:function(e){o.pi(e.name,e.value)},10:function(e){o.doctype(e.value)},4:function(e){o.cdata(e.value)},11:function(e){if(e=e.firstChild)do t(e);while(e=e.next)}},o.reset(),1!=e.type||n.inner?i[11](e):t(e),o.getContent()}}}),r(k,[g,w,m,N,b,C,h,f],function(e,t,n,r,i,o,a,s){var l=s.each,c=s.trim,u=e.DOM;return function(e,i){var s,d,f;return i&&(s=i.dom,d=i.schema),s=s||u,d=d||new o(e),e.entity_encoding=e.entity_encoding||"named",e.remove_trailing_brs="remove_trailing_brs"in e?e.remove_trailing_brs:!0,f=new t(e,d),f.addAttributeFilter("src,href,style",function(t,n){for(var r=t.length,i,o,a="data-mce-"+n,l=e.url_converter,c=e.url_converter_scope,u;r--;)i=t[r],o=i.attributes.map[a],o!==u?(i.attr(n,o.length>0?o:null),i.attr(a,null)):(o=i.attributes.map[n],"style"===n?o=s.serializeStyle(s.parseStyle(o),i.name):l&&(o=l.call(c,o,n,i.name)),i.attr(n,o.length>0?o:null))}),f.addAttributeFilter("class",function(e){for(var t=e.length,n,r;t--;)n=e[t],r=n.attr("class").replace(/(?:^|\s)mce-item-\w+(?!\S)/g,""),n.attr("class",r.length>0?r:null)}),f.addAttributeFilter("data-mce-type",function(e,t,n){for(var r=e.length,i;r--;)i=e[r],"bookmark"!==i.attributes.map["data-mce-type"]||n.cleanup||i.remove()}),f.addAttributeFilter("data-mce-expando",function(e,t){for(var n=e.length;n--;)e[n].attr(t,null)}),f.addNodeFilter("noscript",function(e){for(var t=e.length,r;t--;)r=e[t].firstChild,r&&(r.value=n.decode(r.value))}),f.addNodeFilter("script,style",function(e,t){function n(e){return e.replace(/()/g,"\n").replace(/^[\r\n]*|[\r\n]*$/g,"").replace(/^\s*(()?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g,"")}for(var r=e.length,i,o;r--;)i=e[r],o=i.firstChild?i.firstChild.value:"","script"===t?(i.attr("type",(i.attr("type")||"text/javascript").replace(/^mce\-/,"")),o.length>0&&(i.firstChild.value="// ")):o.length>0&&(i.firstChild.value="")}),f.addNodeFilter("#comment",function(e){for(var t=e.length,n;t--;)n=e[t],0===n.value.indexOf("[CDATA[")?(n.name="#cdata",n.type=4,n.value=n.value.replace(/^\[CDATA\[|\]\]$/g,"")):0===n.value.indexOf("mce:protected ")&&(n.name="#text",n.type=3,n.raw=!0,n.value=unescape(n.value).substr(14))}),f.addNodeFilter("xml:namespace,input",function(e,t){for(var n=e.length,r;n--;)r=e[n],7===r.type?r.remove():1===r.type&&("input"!==t||"type"in r.attributes.map||r.attr("type","text"))}),e.fix_list_elements&&f.addNodeFilter("ul,ol",function(e){for(var t=e.length,n,r;t--;)n=e[t],r=n.parent,("ul"===r.name||"ol"===r.name)&&n.prev&&"li"===n.prev.name&&n.prev.append(n)}),f.addAttributeFilter("data-mce-src,data-mce-href,data-mce-style,data-mce-selected",function(e,t){for(var n=e.length;n--;)e[n].attr(t,null)}),{schema:d,addNodeFilter:f.addNodeFilter,addAttributeFilter:f.addAttributeFilter,serialize:function(t,n){var i=this,o,u,p,m,h;return a.ie&&s.select("script,style,select,map").length>0?(h=t.innerHTML,t=t.cloneNode(!1),s.setHTML(t,h)):t=t.cloneNode(!0),o=t.ownerDocument.implementation,o.createHTMLDocument&&(u=o.createHTMLDocument(""),l("BODY"==t.nodeName?t.childNodes:[t],function(e){u.body.appendChild(u.importNode(e,!0))}),t="BODY"!=t.nodeName?u.body.firstChild:u.body,p=s.doc,s.doc=u),n=n||{},n.format=n.format||"html",n.selection&&(n.forced_root_block=""),n.no_events||(n.node=t,i.onPreProcess(n)),m=new r(e,d),n.content=m.serialize(f.parse(c(n.getInner?t.innerHTML:s.getOuterHTML(t)),n)),n.cleanup||(n.content=n.content.replace(/\uFEFF/g,"")),n.no_events||i.onPostProcess(n),p&&(s.doc=p),n.node=null,n.content},addRules:function(e){d.addValidElements(e)},setRules:function(e){d.setValidElements(e)},onPreProcess:function(e){i&&i.fire("PreProcess",e)},onPostProcess:function(e){i&&i.fire("PostProcess",e)}}}}),r(E,[],function(){function e(e){function n(t,n){var r,i=0,o,a,s,l,c,u,d=-1,f;if(r=t.duplicate(),r.collapse(n),f=r.parentElement(),f.ownerDocument===e.dom.doc){for(;"false"===f.contentEditable;)f=f.parentNode;if(!f.hasChildNodes())return{node:f,inside:1};for(s=f.children,o=s.length-1;o>=i;)if(u=Math.floor((i+o)/2),l=s[u],r.moveToElementText(l),d=r.compareEndPoints(n?"StartToStart":"EndToEnd",t),d>0)o=u-1;else{if(!(0>d))return{node:l};i=u+1}if(0>d)for(l?r.collapse(!1):(r.moveToElementText(f),r.collapse(!0),l=f,a=!0),c=0;0!==r.compareEndPoints(n?"StartToStart":"StartToEnd",t)&&0!==r.move("character",1)&&f==r.parentElement();)c++;else for(r.collapse(!0),c=0;0!==r.compareEndPoints(n?"StartToStart":"StartToEnd",t)&&0!==r.move("character",-1)&&f==r.parentElement();)c++;return{node:l,position:d,offset:c,inside:a}}}function r(){function r(e){var r=n(a,e),i,o,l=0,c,u,d;if(i=r.node,o=r.offset,r.inside&&!i.hasChildNodes())return s[e?"setStart":"setEnd"](i,0),t;if(o===u)return s[e?"setStartBefore":"setEndAfter"](i),t;if(0>r.position){if(c=r.inside?i.firstChild:i.nextSibling,!c)return s[e?"setStartAfter":"setEndAfter"](i),t;if(!o)return 3==c.nodeType?s[e?"setStart":"setEnd"](c,0):s[e?"setStartBefore":"setEndBefore"](c),t;for(;c;){if(d=c.nodeValue,l+=d.length,l>=o){i=c,l-=o,l=d.length-l;break}c=c.nextSibling}}else{if(c=i.previousSibling,!c)return s[e?"setStartBefore":"setEndBefore"](i);if(!o)return 3==i.nodeType?s[e?"setStart":"setEnd"](c,i.nodeValue.length):s[e?"setStartAfter":"setEndAfter"](c),t;for(;c;){if(l+=c.nodeValue.length,l>=o){i=c,l-=o;break}c=c.previousSibling}}s[e?"setStart":"setEnd"](i,l)}var a=e.getRng(),s=o.createRng(),l,c,u,d,f;if(l=a.item?a.item(0):a.parentElement(),l.ownerDocument!=o.doc)return s;if(c=e.isCollapsed(),a.item)return s.setStart(l.parentNode,o.nodeIndex(l)),s.setEnd(s.startContainer,s.startOffset+1),s;try{r(!0),c||r()}catch(p){if(-2147024809!=p.number)throw p;f=i.getBookmark(2),u=a.duplicate(),u.collapse(!0),l=u.parentElement(),c||(u=a.duplicate(),u.collapse(!1),d=u.parentElement(),d.innerHTML=d.innerHTML),l.innerHTML=l.innerHTML,i.moveToBookmark(f),a=e.getRng(),r(!0),c||r()}return s}var i=this,o=e.dom,a=!1;this.getBookmark=function(r){function i(e){var t,n,r,i,a=[];for(t=e.parentNode,n=o.getRoot().parentNode;t!=n&&9!==t.nodeType;){for(r=t.children,i=r.length;i--;)if(e===r[i]){a.push(i);break}e=t,t=t.parentNode}return a}function a(e){var r;return r=n(s,e),r?{position:r.position,offset:r.offset,indexes:i(r.node),inside:r.inside}:t}var s=e.getRng(),l={};return 2===r&&(s.item?l.start={ctrl:!0,indexes:i(s.item(0))}:(l.start=a(!0),e.isCollapsed()||(l.end=a()))),l},this.moveToBookmark=function(e){function t(e){var t,n,r,i;for(t=o.getRoot(),n=e.length-1;n>=0;n--)i=t.children,r=e[n],i.length-1>=r&&(t=i[r]);return t}function n(n){var o=e[n?"start":"end"],a,s,l,c;o&&(a=o.position>0,s=i.createTextRange(),s.moveToElementText(t(o.indexes)),c=o.offset,c!==l?(s.collapse(o.inside||a),s.moveStart("character",a?-c:c)):s.collapse(n),r.setEndPoint(n?"StartToStart":"EndToStart",s),n&&r.collapse(!0))}var r,i=o.doc.body;e.start&&(e.start.ctrl?(r=i.createControlRange(),r.addElement(t(e.start.indexes)),r.select()):(r=i.createTextRange(),n(!0),n(),r.select()))},this.addRange=function(n){function r(e){var t,n,r,s,f;r=o.create("a"),t=e?l:u,n=e?c:d,s=i.duplicate(),(t==p||t==p.documentElement)&&(t=m,n=0),3==t.nodeType?(t.parentNode.insertBefore(r,t),s.moveToElementText(r),s.moveStart("character",n),o.remove(r),i.setEndPoint(e?"StartToStart":"EndToEnd",s)):(f=t.childNodes,f.length?(n>=f.length?o.insertAfter(r,f[f.length-1]):t.insertBefore(r,f[n]),s.moveToElementText(r)):t.canHaveHTML&&(t.innerHTML="",r=t.firstChild,s.moveToElementText(r),s.collapse(a)),i.setEndPoint(e?"StartToStart":"EndToEnd",s),o.remove(r))}var i,s,l,c,u,d,f,p=e.dom.doc,m=p.body,h,g;if(l=n.startContainer,c=n.startOffset,u=n.endContainer,d=n.endOffset,i=m.createTextRange(),l==u&&1==l.nodeType){if(c==d&&!l.hasChildNodes()){if(l.canHaveHTML)return f=l.previousSibling,f&&!f.hasChildNodes()&&o.isBlock(f)?f.innerHTML="":f=null,l.innerHTML="",i.moveToElementText(l.lastChild),i.select(),o.doc.selection.clear(),l.innerHTML="",f&&(f.innerHTML=""),t;c=o.nodeIndex(l),l=l.parentNode}if(c==d-1)try{if(g=l.childNodes[c],s=m.createControlRange(),s.addElement(g),s.select(),h=e.getRng(),h.item&&g===h.item(0))return}catch(v){}}r(!0),r(),i.select()},this.getRangeAt=r}return e}),r(S,[h],function(e){return{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},metaKeyPressed:function(t){return e.mac?t.metaKey:t.ctrlKey&&!t.altKey}}}),r(T,[S,f,h],function(e,n,r){return function(i,o){function a(e){return o.settings.object_resizing===!1?!1:/TABLE|IMG|DIV/.test(e.nodeName)?"false"===e.getAttribute("data-mce-resize")?!1:!0:!1}function s(t){var n,r;n=t.screenX-k,r=t.screenY-E,H=n*N[2]+R,M=r*N[3]+A,H=5>H?5:H,M=5>M?5:M,(e.modifierPressed(t)||"IMG"==x.nodeName&&0!==N[2]*N[3])&&(H=Math.round(M/B),M=Math.round(H*B)),b.setStyles(w,{width:H,height:M}),0>N[2]&&H>=w.clientWidth&&b.setStyle(w,"left",S+(R-H)),0>N[3]&&M>=w.clientHeight&&b.setStyle(w,"top",T+(A-M)),L||(o.fire("ObjectResizeStart",{target:x,width:R,height:A}),L=!0)}function l(){function e(e,t){t&&(x.style[e]||!o.schema.isValid(x.nodeName.toLowerCase(),e)?b.setStyle(x,e,t):b.setAttrib(x,e,t))}L=!1,e("width",H),e("height",M),b.unbind(D,"mousemove",s),b.unbind(D,"mouseup",l),P!=D&&(b.unbind(P,"mousemove",s),b.unbind(P,"mouseup",l)),b.remove(w),O&&"TABLE"!=x.nodeName||c(x),o.fire("ObjectResized",{target:x,width:H,height:M}),o.nodeChanged()}function c(e,n,r){var i,c,d,f,p;i=b.getPos(e,o.getBody()),S=i.x,T=i.y,p=e.getBoundingClientRect(),c=p.width,d=p.height,x!=e&&(g(),x=e,H=M=0),f=o.fire("ObjectSelected",{target:e}),a(e)&&!f.isDefaultPrevented()?C(_,function(e,i){function a(t){L=!0,k=t.screenX,E=t.screenY,R=x.clientWidth,A=x.clientHeight,B=A/R,N=e,w=x.cloneNode(!0),b.addClass(w,"mce-clonedresizable"),w.contentEditable=!1,w.unSelectabe=!0,b.setStyles(w,{left:S,top:T,margin:0}),w.removeAttribute("data-mce-selected"),o.getBody().appendChild(w),b.bind(D,"mousemove",s),b.bind(D,"mouseup",l),P!=D&&(b.bind(P,"mousemove",s),b.bind(P,"mouseup",l))}var u,f;return n?(i==n&&a(r),t):(u=b.get("mceResizeHandle"+i),u?b.show(u):(f=o.getBody(),u=b.add(f,"div",{id:"mceResizeHandle"+i,"data-mce-bogus":!0,"class":"mce-resizehandle",contentEditable:!1,unSelectabe:!0,style:"cursor:"+i+"-resize; margin:0; padding:0"}),b.bind(u,"mousedown",function(e){e.preventDefault(),a(e)})),b.setStyles(u,{left:c*e[0]+S-u.offsetWidth/2,top:d*e[1]+T-u.offsetHeight/2}),t)}):u(),x.setAttribute("data-mce-selected","1")}function u(){var e,t;x&&x.removeAttribute("data-mce-selected");for(e in _)t=b.get("mceResizeHandle"+e),t&&(b.unbind(t),b.remove(t))}function d(e){function n(e,t){do if(e===t)return!0;while(e=e.parentNode)}var r;return C(b.select("img[data-mce-selected],hr[data-mce-selected]"),function(e){e.removeAttribute("data-mce-selected")}),r="mousedown"==e.type?e.target:i.getNode(),r=b.getParent(r,O?"table":"table,img,hr"),r&&n(i.getStart(),r)&&n(i.getEnd(),r)&&(!O||r!=i.getStart()&&"IMG"!==i.getStart().nodeName)?(c(r),t):(u(),t)}function f(e,t,n){e&&e.attachEvent&&e.attachEvent("on"+t,n)}function p(e,t,n){e&&e.detachEvent&&e.detachEvent("on"+t,n)}function m(e){var t=e.srcElement,n,r,i,a,s,l,u;n=t.getBoundingClientRect(),l=e.clientX-n.left,u=e.clientY-n.top;for(r in _)if(i=_[r],a=t.offsetWidth*i[0],s=t.offsetHeight*i[1],8>Math.abs(a-l)&&8>Math.abs(s-u)){N=i;break}L=!0,o.getDoc().selection.empty(),c(t,r,e)}function h(e){var n=e.srcElement;if(n!=x){if(g(),0===n.id.indexOf("mceResizeHandle"))return e.returnValue=!1,t;("IMG"==n.nodeName||"TABLE"==n.nodeName)&&(u(),x=n,f(n,"resizestart",m))}}function g(){p(x,"resizestart",m)}function v(e){var t;if(O){t=D.body.createControlRange();try{return t.addElement(e),t.select(),!0}catch(n){}}}function y(){x=w=null,O&&(g(),p(o.getBody(),"controlselect",h))}var b=o.dom,C=n.each,x,w,_,N,k,E,S,T,R,A,B,L,H,M,D=o.getDoc(),P=document,O=r.ie;_={n:[.5,0,0,-1],e:[1,.5,1,0],s:[.5,1,0,1],w:[0,.5,-1,0],nw:[0,0,-1,-1],ne:[1,0,1,-1],se:[1,1,1,1],sw:[0,1,-1,1]};var I=".mce-content-body";return o.contentStyles.push(I+" div.mce-resizehandle {"+"position: absolute;"+"border: 1px solid black;"+"background: #FFF;"+"width: 5px;"+"height: 5px;"+"z-index: 10000"+"}"+I+" .mce-resizehandle:hover {"+"background: #000"+"}"+I+" img[data-mce-selected], hr[data-mce-selected] {"+"outline: 1px solid black;"+"resize: none"+"}"+I+" .mce-clonedresizable {"+"position: absolute;"+(r.gecko?"":"outline: 1px dashed black;")+"opacity: .5;"+"filter: alpha(opacity=50);"+"z-index: 10000"+"}"),o.on("init",function(){if(O)o.on("ObjectResized",function(e){"TABLE"!=e.target.nodeName&&(u(),v(e.target))}),f(o.getBody(),"controlselect",h);else try{o.getDoc().execCommand("enableObjectResizing",!1,!1)}catch(e){}o.on("nodechange mousedown ResizeEditor",d),o.on("keydown keyup",function(e){x&&"TABLE"==x.nodeName&&d(e)})}),{controlSelect:v,destroy:y}}}),r(R,[d,E,T,h,f],function(e,n,r,i,o){function a(e,t,i,o){var a=this;a.dom=e,a.win=t,a.serializer=i,a.editor=o,a.controlSelection=new r(a,o),o.on("nodechange",function(){var e;e=o.getDoc().selection?o.getDoc().selection.createRange():a.getRng(),a.lastRng=e}),a.win.getSelection||(a.tridentSel=new n(a))}var s=o.each,l=o.grep,c=o.trim,u=i.ie,d=i.opera;return a.prototype={setCursorLocation:function(e,t){var n=this,r=n.dom.createRng();r.setStart(e,t),r.setEnd(e,t),n.setRng(r),n.collapse(!1)},getContent:function(e){var n=this,r=n.getRng(),i=n.dom.create("body"),o=n.getSel(),a,s,l;return e=e||{},a=s="",e.get=!0,e.format=e.format||"html",e.selection=!0,n.editor.fire("BeforeGetContent",e),"text"==e.format?n.isCollapsed()?"":r.text||(o.toString?""+o:""):(r.cloneContents?(l=r.cloneContents(),l&&i.appendChild(l)):r.item!==t||r.htmlText!==t?(i.innerHTML="
    "+(r.item?r.item(0).outerHTML:r.htmlText),i.removeChild(i.firstChild)):i.innerHTML=""+r,/^\s/.test(i.innerHTML)&&(a=" "),/\s+$/.test(i.innerHTML)&&(s=" "),e.getInner=!0,e.content=n.isCollapsed()?"":a+n.serializer.serialize(i,e)+s,n.editor.fire("GetContent",e),e.content)},setContent:function(e,t){var n=this,r=n.getRng(),i,o=n.win.document,a,s;if(t=t||{format:"html"},t.set=!0,t.selection=!0,e=t.content=e,t.no_events||n.editor.fire("BeforeSetContent",t),e=t.content,r.insertNode){e+='_',r.startContainer==o&&r.endContainer==o?o.body.innerHTML=e:(r.deleteContents(),0===o.body.childNodes.length?o.body.innerHTML=e:r.createContextualFragment?r.insertNode(r.createContextualFragment(e)):(a=o.createDocumentFragment(),s=o.createElement("div"),a.appendChild(s),s.outerHTML=e,r.insertNode(a))),i=n.dom.get("__caret"),r=o.createRange(),r.setStartBefore(i),r.setEndBefore(i),n.setRng(r),n.dom.remove("__caret");try{n.setRng(r)}catch(l){}}else r.item&&(o.execCommand("Delete",!1,null),r=n.getRng()),/^\s+/.test(e)?(r.pasteHTML('_'+e),n.dom.remove("__mce_tmp")):r.pasteHTML(e);t.no_events||n.editor.fire("SetContent",t)},getStart:function(){var e=this,t=e.getRng(),n,r,i,o;if(t.duplicate||t.item){if(t.item)return t.item(0);for(i=t.duplicate(),i.collapse(1),n=i.parentElement(),n.ownerDocument!==e.dom.doc&&(n=e.dom.getRoot()),r=o=t.parentElement();o=o.parentNode;)if(o==n){n=r;break}return n}return n=t.startContainer,1==n.nodeType&&n.hasChildNodes()&&(n=n.childNodes[Math.min(n.childNodes.length-1,t.startOffset)]),n&&3==n.nodeType?n.parentNode:n},getEnd:function(){var e=this,t=e.getRng(),n,r;return t.duplicate||t.item?t.item?t.item(0):(t=t.duplicate(),t.collapse(0),n=t.parentElement(),n.ownerDocument!==e.dom.doc&&(n=e.dom.getRoot()),n&&"BODY"==n.nodeName?n.lastChild||n:n):(n=t.endContainer,r=t.endOffset,1==n.nodeType&&n.hasChildNodes()&&(n=n.childNodes[r>0?r-1:r]),n&&3==n.nodeType?n.parentNode:n)},getBookmark:function(e,t){function n(e,t){var n=0;return s(a.select(e),function(e,r){e==t&&(n=r)}),n}function r(e){function t(t){var n,r,i,o=t?"start":"end";n=e[o+"Container"],r=e[o+"Offset"],1==n.nodeType&&"TR"==n.nodeName&&(i=n.childNodes,n=i[Math.min(t?r:r-1,i.length-1)],n&&(r=t?0:n.childNodes.length,e["set"+(t?"Start":"End")](n,r)))}return t(!0),t(),e}function i(){function e(e,n){var i=e[n?"startContainer":"endContainer"],a=e[n?"startOffset":"endOffset"],s=[],l,c,u=0;if(3==i.nodeType){if(t)for(l=i.previousSibling;l&&3==l.nodeType;l=l.previousSibling)a+=l.nodeValue.length;s.push(a)}else c=i.childNodes,a>=c.length&&c.length&&(u=1,a=Math.max(0,c.length-1)),s.push(o.dom.nodeIndex(c[a],t)+u);for(;i&&i!=r;i=i.parentNode)s.push(o.dom.nodeIndex(i,t));return s}var n=o.getRng(!0),r=a.getRoot(),i={};return i.start=e(n,!0),o.isCollapsed()||(i.end=e(n)),i}var o=this,a=o.dom,l,c,u,d,f,p,m="",h;if(2==e)return p=o.getNode(),f=p.nodeName,"IMG"==f?{name:f,index:n(f,p)}:o.tridentSel?o.tridentSel.getBookmark(e):i();if(e)return{rng:o.getRng()};if(l=o.getRng(),u=a.uniqueId(),d=o.isCollapsed(),h="overflow:hidden;line-height:0px",l.duplicate||l.item){if(l.item)return p=l.item(0),f=p.nodeName,{name:f,index:n(f,p)}; +c=l.duplicate();try{l.collapse(),l.pasteHTML(''+m+""),d||(c.collapse(!1),l.moveToElementText(c.parentElement()),0===l.compareEndPoints("StartToEnd",c)&&c.move("character",-1),c.pasteHTML(''+m+""))}catch(g){return null}}else{if(p=o.getNode(),f=p.nodeName,"IMG"==f)return{name:f,index:n(f,p)};c=r(l.cloneRange()),d||(c.collapse(!1),c.insertNode(a.create("span",{"data-mce-type":"bookmark",id:u+"_end",style:h},m))),l=r(l),l.collapse(!0),l.insertNode(a.create("span",{"data-mce-type":"bookmark",id:u+"_start",style:h},m))}return o.moveToBookmark({id:u,keep:1}),{id:u}},moveToBookmark:function(e){function t(t){var n=e[t?"start":"end"],r,i,o,s;if(n){for(o=n[0],i=c,r=n.length-1;r>=1;r--){if(s=i.childNodes,n[r]>s.length-1)return;i=s[n[r]]}3===i.nodeType&&(o=Math.min(n[0],i.nodeValue.length)),1===i.nodeType&&(o=Math.min(n[0],i.childNodes.length)),t?a.setStart(i,o):a.setEnd(i,o)}return!0}function n(t){var n=o.get(e.id+"_"+t),r,i,a,c,u=e.keep;if(n&&(r=n.parentNode,"start"==t?(u?(r=n.firstChild,i=1):i=o.nodeIndex(n),f=p=r,m=h=i):(u?(r=n.firstChild,i=1):i=o.nodeIndex(n),p=r,h=i),!u)){for(c=n.previousSibling,a=n.nextSibling,s(l(n.childNodes),function(e){3==e.nodeType&&(e.nodeValue=e.nodeValue.replace(/\uFEFF/g,""))});n=o.get(e.id+"_"+t);)o.remove(n,1);c&&a&&c.nodeType==a.nodeType&&3==c.nodeType&&!d&&(i=c.nodeValue.length,c.appendData(a.nodeValue),o.remove(a),"start"==t?(f=p=c,m=h=i):(p=c,h=i))}}function r(e){return!o.isBlock(e)||e.innerHTML||u||(e.innerHTML='
    '),e}var i=this,o=i.dom,a,c,f,p,m,h;if(e)if(e.start){if(a=o.createRng(),c=o.getRoot(),i.tridentSel)return i.tridentSel.moveToBookmark(e);t(!0)&&t()&&i.setRng(a)}else e.id?(n("start"),n("end"),f&&(a=o.createRng(),a.setStart(r(f),m),a.setEnd(r(p),h),i.setRng(a))):e.name?i.select(o.select(e.name)[e.index]):e.rng&&i.setRng(e.rng)},select:function(n,r){function i(n,r){var i=new e(n,n);do{if(3==n.nodeType&&0!==c(n.nodeValue).length)return r?s.setStart(n,0):s.setEnd(n,n.nodeValue.length),t;if("BR"==n.nodeName)return r?s.setStartBefore(n):s.setEndBefore(n),t}while(n=r?i.next():i.prev())}var o=this,a=o.dom,s=a.createRng(),l;if(n){if(!r&&o.controlSelection.controlSelect(n))return;l=a.nodeIndex(n),s.setStart(n.parentNode,l),s.setEnd(n.parentNode,l+1),r&&(i(n,1),i(n)),o.setRng(s)}return n},isCollapsed:function(){var e=this,t=e.getRng(),n=e.getSel();return!t||t.item?!1:t.compareEndPoints?0===t.compareEndPoints("StartToEnd",t):!n||t.collapsed},collapse:function(e){var t=this,n=t.getRng(),r;n.item&&(r=n.item(0),n=t.win.document.body.createTextRange(),n.moveToElementText(r)),n.collapse(!!e),t.setRng(n)},getSel:function(){var e=this.win;return e.getSelection?e.getSelection():e.document.selection},getRng:function(e){var t=this,n,r,i,o=t.win.document;if(e&&t.tridentSel)return t.tridentSel.getRangeAt(0);try{(n=t.getSel())&&(r=n.rangeCount>0?n.getRangeAt(0):n.createRange?n.createRange():o.createRange())}catch(a){}return u&&r&&r.setStart&&o.selection.createRange().item&&(i=o.selection.createRange().item(0),r=o.createRange(),r.setStartBefore(i),r.setEndAfter(i)),r||(r=o.createRange?o.createRange():o.body.createTextRange()),r.setStart&&9===r.startContainer.nodeType&&r.collapsed&&(i=t.dom.getRoot(),r.setStart(i,0),r.setEnd(i,0)),t.selectedRange&&t.explicitRange&&(0===r.compareBoundaryPoints(r.START_TO_START,t.selectedRange)&&0===r.compareBoundaryPoints(r.END_TO_END,t.selectedRange)?r=t.explicitRange:(t.selectedRange=null,t.explicitRange=null)),r},setRng:function(e,n){var r=this,i;if(r.lastRng=null,e.select)try{e.select()}catch(o){}else if(r.tridentSel){if(e.cloneRange)try{return r.tridentSel.addRange(e),t}catch(o){}}else if(i=r.getSel()){r.explicitRange=e;try{i.removeAllRanges()}catch(o){}i.addRange(e),n===!1&&i.extend&&(i.collapse(e.endContainer,e.endOffset),i.extend(e.startContainer,e.startOffset)),r.selectedRange=i.rangeCount>0?i.getRangeAt(0):null}},setNode:function(e){var t=this;return t.setContent(t.dom.getOuterHTML(e)),e},getNode:function(){function e(e,t){for(var n=e;e&&3===e.nodeType&&0===e.length;)e=t?e.nextSibling:e.previousSibling;return e||n}var t=this,n=t.getRng(),r,i=n.startContainer,o=n.endContainer,a=n.startOffset,s=n.endOffset;return n?n.setStart?(r=n.commonAncestorContainer,!n.collapsed&&(i==o&&2>s-a&&i.hasChildNodes()&&(r=i.childNodes[a]),3===i.nodeType&&3===o.nodeType&&(i=i.length===a?e(i.nextSibling,!0):i.parentNode,o=0===s?e(o.previousSibling,!1):o.parentNode,i&&i===o))?i:r&&3==r.nodeType?r.parentNode:r):n.item?n.item(0):n.parentElement():t.dom.getRoot()},getSelectedBlocks:function(t,n){var r=this,i=r.dom,o,a=[];if(t=i.getParent(t||r.getStart(),i.isBlock),n=i.getParent(n||r.getEnd(),i.isBlock),t&&a.push(t),t&&n&&t!=n){o=t;for(var s=new e(t,i.getRoot());(o=s.next())&&o!=n;)i.isBlock(o)&&a.push(o)}return n&&t!=n&&a.push(n),a},isForward:function(){var e=this.dom,t=this.getSel(),n,r;return t&&t.anchorNode&&t.focusNode?(n=e.createRng(),n.setStart(t.anchorNode,t.anchorOffset),n.collapse(!0),r=e.createRng(),r.setStart(t.focusNode,t.focusOffset),r.collapse(!0),0>=n.compareBoundaryPoints(n.START_TO_START,r)):!0},normalize:function(){function n(n){function s(t,n){for(var r=new e(t,p.getParent(t.parentNode,p.isBlock)||m);t=r[n?"prev":"next"]();)if("BR"===t.nodeName)return!0}function l(e,t){return e.previousSibling&&e.previousSibling.nodeName==t}function c(n,r){var i,s;for(r=r||u,i=new e(r,p.getParent(r.parentNode,p.isBlock)||m);h=i[n?"prev":"next"]();){if(3===h.nodeType&&h.nodeValue.length>0)return u=h,d=n?h.nodeValue.length:0,o=!0,t;if(p.isBlock(h)||g[h.nodeName.toLowerCase()])return;s=h}a&&s&&(u=s,o=!0,d=0)}var u,d,f,p=r.dom,m=p.getRoot(),h,g,v;if(u=i[(n?"start":"end")+"Container"],d=i[(n?"start":"end")+"Offset"],g=p.schema.getNonEmptyElements(),9===u.nodeType&&(u=p.getRoot(),d=0),u===m){if(n&&(h=u.childNodes[d>0?d-1:0],h&&(v=h.nodeName.toLowerCase(),g[h.nodeName]||"TABLE"==h.nodeName)))return;if(u.hasChildNodes()&&(d=Math.min(!n&&d>0?d-1:d,u.childNodes.length-1),u=u.childNodes[d],d=0,u.hasChildNodes()&&!/TABLE/.test(u.nodeName))){h=u,f=new e(u,m);do{if(3===h.nodeType&&h.nodeValue.length>0){d=n?0:h.nodeValue.length,u=h,o=!0;break}if(g[h.nodeName.toLowerCase()]){d=p.nodeIndex(h),u=h.parentNode,"IMG"!=h.nodeName||n||d++,o=!0;break}}while(h=n?f.next():f.prev())}}a&&(3===u.nodeType&&0===d&&c(!0),1===u.nodeType&&(h=u.childNodes[d],!h||"BR"!==h.nodeName||l(h,"A")||s(h)||s(h,!0)||c(!0,u.childNodes[d]))),n&&!a&&3===u.nodeType&&d===u.nodeValue.length&&c(!1),o&&i["set"+(n?"Start":"End")](u,d)}var r=this,i,o,a;u||(i=r.getRng(),a=i.collapsed,n(!0),a||n(),o&&(a&&i.collapse(!0),r.setRng(i,r.isForward())))},selectorChanged:function(e,n){var r=this,i;return r.selectorChangedData||(r.selectorChangedData={},i={},r.editor.on("NodeChange",function(e){var n=e.element,o=r.dom,a=o.getParents(n,null,o.getRoot()),l={};s(r.selectorChangedData,function(e,n){s(a,function(r){return o.is(r,n)?(i[n]||(s(e,function(e){e(!0,{node:r,selector:n,parents:a})}),i[n]=e),l[n]=e,!1):t})}),s(i,function(e,t){l[t]||(delete i[t],s(e,function(e){e(!1,{node:n,selector:t,parents:a})}))})})),r.selectorChangedData[e]||(r.selectorChangedData[e]=[]),r.selectorChangedData[e].push(n),r},scrollIntoView:function(e){var t,n,r=this,i=r.dom;n=i.getViewPort(r.editor.getWin()),t=i.getPos(e).y,(n.y>t||t+25>n.y+n.h)&&r.editor.getWin().scrollTo(0,n.y>t?t:t-n.h+25)},destroy:function(){this.win=this.lastRng=null,this.controlSelection.destroy()}},a}),r(A,[f],function(e){function n(e){this.walk=function(n,i){function o(e){var t;return t=e[0],3===t.nodeType&&t===c&&u>=t.nodeValue.length&&e.splice(0,1),t=e[e.length-1],0===f&&e.length>0&&t===d&&3===t.nodeType&&e.splice(e.length-1,1),e}function a(e,t,n){for(var r=[];e&&e!=n;e=e[t])r.push(e);return r}function s(e,t){do{if(e.parentNode==t)return e;e=e.parentNode}while(e)}function l(e,t,n){var r=n?"nextSibling":"previousSibling";for(g=e,v=g.parentNode;g&&g!=t;g=v)v=g.parentNode,y=a(g==e?g:g[r],r),y.length&&(n||y.reverse(),i(o(y)))}var c=n.startContainer,u=n.startOffset,d=n.endContainer,f=n.endOffset,p,m,h,g,v,y,b;if(b=e.select("td.mce-item-selected,th.mce-item-selected"),b.length>0)return r(b,function(e){i([e])}),t;if(1==c.nodeType&&c.hasChildNodes()&&(c=c.childNodes[u]),1==d.nodeType&&d.hasChildNodes()&&(d=d.childNodes[Math.min(f-1,d.childNodes.length-1)]),c==d)return i(o([c]));for(p=e.findCommonAncestor(c,d),g=c;g;g=g.parentNode){if(g===d)return l(c,p,!0);if(g===p)break}for(g=d;g;g=g.parentNode){if(g===c)return l(d,p);if(g===p)break}m=s(c,p)||c,h=s(d,p)||d,l(c,m,!0),y=a(m==c?m:m.nextSibling,"nextSibling",h==d?h.nextSibling:h),y.length&&i(o(y)),l(d,h)},this.split=function(e){function t(e,t){return e.splitText(t)}var n=e.startContainer,r=e.startOffset,i=e.endContainer,o=e.endOffset;return n==i&&3==n.nodeType?r>0&&n.nodeValue.length>r&&(i=t(n,r),n=i.previousSibling,o>r?(o-=r,n=i=t(i,o).previousSibling,o=i.nodeValue.length,r=0):o=0):(3==n.nodeType&&r>0&&n.nodeValue.length>r&&(n=t(n,r),r=0),3==i.nodeType&&o>0&&i.nodeValue.length>o&&(i=t(i,o).previousSibling,o=i.nodeValue.length)),{startContainer:n,startOffset:r,endContainer:i,endOffset:o}}}var r=e.each;return n.compareRanges=function(e,t){if(e&&t){if(!e.item&&!e.duplicate)return e.startContainer==t.startContainer&&e.startOffset==t.startOffset;if(e.item&&t.item&&e.item(0)===t.item(0))return!0;if(e.isEqual&&t.isEqual&&t.isEqual(e))return!0}return!1},n}),r(B,[d,A,f],function(e,n,r){return function(i){function o(e){return e.nodeType&&(e=e.nodeName),!!i.schema.getTextBlockElements()[e.toLowerCase()]}function a(e,t){return I.getParents(e,t,I.getRoot())}function s(e){return 1===e.nodeType&&"_mce_caret"===e.id}function l(){d({alignleft:[{selector:"figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",styles:{textAlign:"left"},defaultBlock:"div"},{selector:"img,table",collapsed:!1,styles:{"float":"left"}}],aligncenter:[{selector:"figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",styles:{textAlign:"center"},defaultBlock:"div"},{selector:"img",collapsed:!1,styles:{display:"block",marginLeft:"auto",marginRight:"auto"}},{selector:"table",collapsed:!1,styles:{marginLeft:"auto",marginRight:"auto"}}],alignright:[{selector:"figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",styles:{textAlign:"right"},defaultBlock:"div"},{selector:"img,table",collapsed:!1,styles:{"float":"right"}}],alignjustify:[{selector:"figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,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:!0},{inline:"u",remove:"all"}],strikethrough:[{inline:"span",styles:{textDecoration:"line-through"},exact:!0},{inline:"strike",remove:"all"}],forecolor:{inline:"span",styles:{color:"%value"},wrap_links:!1},hilitecolor:{inline:"span",styles:{backgroundColor:"%value"},wrap_links:!1},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"},code:{inline:"code"},link:{inline:"a",selector:"a",remove:"all",split:!0,deep:!0,onmatch:function(){return!0},onformat:function(e,t,n){et(n,function(t,n){I.setAttrib(e,n,t)})}},removeformat:[{selector:"b,strong,em,i,font,u,strike",remove:"all",split:!0,expand:!1,block_expand:!0,deep:!0},{selector:"span",attributes:["style","class"],remove:"empty",split:!0,expand:!1,deep:!0},{selector:"*",attributes:["style","class"],split:!1,expand:!1,deep:!0}]}),et("p h1 h2 h3 h4 h5 h6 div address pre div dt dd samp".split(/\s/),function(e){d(e,{block:e,remove:"all"})}),d(i.settings.formats)}function c(){i.addShortcut("ctrl+b","bold_desc","Bold"),i.addShortcut("ctrl+i","italic_desc","Italic"),i.addShortcut("ctrl+u","underline_desc","Underline");for(var e=1;6>=e;e++)i.addShortcut("ctrl+"+e,"",["FormatBlock",!1,"h"+e]);i.addShortcut("ctrl+7","",["FormatBlock",!1,"p"]),i.addShortcut("ctrl+8","",["FormatBlock",!1,"div"]),i.addShortcut("ctrl+9","",["FormatBlock",!1,"address"])}function u(e){return e?O[e]:O}function d(e,t){e&&("string"!=typeof e?et(e,function(e,t){d(t,e)}):(t=t.length?t:[t],et(t,function(e){e.deep===X&&(e.deep=!e.selector),e.split===X&&(e.split=!e.selector||e.inline),e.remove===X&&e.selector&&!e.inline&&(e.remove="none"),e.selector&&e.inline&&(e.mixed=!0,e.block_expand=!0),"string"==typeof e.classes&&(e.classes=e.classes.split(/\s+/))}),O[e]=t))}function f(e){var t;return i.dom.getParent(e,function(e){return t=i.dom.getStyle(e,"text-decoration"),t&&"none"!==t}),t}function p(e){var t;1===e.nodeType&&e.parentNode&&1===e.parentNode.nodeType&&(t=f(e.parentNode),i.dom.getStyle(e,"color")&&t?i.dom.setStyle(e,"text-decoration",t):i.dom.getStyle(e,"textdecoration")===t&&i.dom.setStyle(e,"text-decoration",null))}function m(n,r,a){function l(e,t){t=t||g,e&&(t.onformat&&t.onformat(e,t,r,a),et(t.styles,function(t,n){I.setStyle(e,n,k(t,r))}),et(t.attributes,function(t,n){I.setAttrib(e,n,k(t,r))}),et(t.classes,function(t){t=k(t,r),I.hasClass(e,t)||I.addClass(e,t)}))}function c(){function t(t,n){var r=new e(n);for(a=r.current();a;a=r.prev())if(a.childNodes.length>1||a==t||"BR"==a.tagName)return a}var n=i.selection.getRng(),r=n.startContainer,o=n.endContainer;if(r!=o&&0===n.endOffset){var s=t(r,o),l=3==s.nodeType?s.length:s.childNodes.length;n.setEnd(s,l)}return n}function d(e,n,r,i,o){var a=[],s=-1,l,c=-1,u=-1,d;return et(e.childNodes,function(e,n){return"UL"===e.nodeName||"OL"===e.nodeName?(s=n,l=e,!1):t}),et(e.childNodes,function(e,t){"SPAN"===e.nodeName&&"bookmark"==I.getAttrib(e,"data-mce-type")&&(e.id==n.id+"_start"?c=t:e.id==n.id+"_end"&&(u=t))}),0>=s||s>c&&u>s?(et(tt(e.childNodes),o),0):(d=I.clone(r,G),et(tt(e.childNodes),function(e,t){(s>c&&s>t||c>s&&t>s)&&(a.push(e),e.parentNode.removeChild(e))}),s>c?e.insertBefore(d,l):c>s&&e.insertBefore(d,l.nextSibling),i.push(d),et(a,function(e){d.appendChild(e)}),d)}function f(e,i,a){var c=[],u,f,p=!0;u=g.inline||g.block,f=I.create(u),l(f),W.walk(e,function(e){function m(e){var b,x,w,N,k;return k=p,b=e.nodeName.toLowerCase(),x=e.parentNode.nodeName.toLowerCase(),1===e.nodeType&&J(e)&&(k=p,p="true"===J(e),N=!0),_(b,"br")?(y=0,g.block&&I.remove(e),t):g.wrapper&&v(e,n,r)?(y=0,t):p&&!N&&g.block&&!g.wrapper&&o(b)&&z(x,u)?(e=I.rename(e,u),l(e),c.push(e),y=0,t):g.selector&&(et(h,function(t){"collapsed"in t&&t.collapsed!==C||I.is(e,t.selector)&&!s(e)&&(l(e,t),w=!0)}),!g.inline||w)?(y=0,t):(!p||N||!z(u,b)||!z(x,u)||!a&&3===e.nodeType&&1===e.nodeValue.length&&65279===e.nodeValue.charCodeAt(0)||s(e)||g.inline&&V(e)?"li"==b&&i?y=d(e,i,f,c,m):(y=0,et(tt(e.childNodes),m),N&&(p=k),y=0):(y||(y=I.clone(f,G),e.parentNode.insertBefore(y,e),c.push(y)),y.appendChild(e)),t)}var y;et(e,m)}),g.wrap_links===!1&&et(c,function(e){function t(e){var n,r,i;if("A"===e.nodeName){for(r=I.clone(f,G),c.push(r),i=tt(e.childNodes),n=0;i.length>n;n++)r.appendChild(i[n]);e.appendChild(r)}et(tt(e.childNodes),t)}t(e)}),et(c,function(e){function i(e){var t=0;return et(e.childNodes,function(e){E(e)||L(e)||t++}),t}function o(e){var n,r;return et(e.childNodes,function(e){return 1!=e.nodeType||L(e)||s(e)?t:(n=e,G)}),n&&w(n,g)&&(r=I.clone(n,G),l(r),I.replace(r,e,K),I.remove(n,1)),r||e}var a;if(a=i(e),(c.length>1||!V(e))&&0===a)return I.remove(e,1),t;if(g.inline||g.wrapper){if(g.exact||1!==a||(e=o(e)),et(h,function(t){et(I.select(t.inline,e),function(e){var n;if(t.wrap_links===!1){n=e.parentNode;do if("A"===n.nodeName)return;while(n=n.parentNode)}R(t,r,e,t.exact?e:null)})}),v(e.parentNode,n,r))return I.remove(e,1),e=0,K;g.merge_with_parents&&I.getParent(e.parentNode,function(i){return v(i,n,r)?(I.remove(e,1),e=0,K):t}),e&&g.merge_siblings!==!1&&(e=H(B(e),e),e=H(e,B(e,K)))}})}var h=u(n),g=h[0],y,b,C=!a&&F.isCollapsed();if(g)if(a)a.nodeType?(b=I.createRng(),b.setStartBefore(a),b.setEndAfter(a),f(T(b,h),null,!0)):f(a,null,!0);else if(C&&g.inline&&!I.select("td.mce-item-selected,th.mce-item-selected").length)D("apply",n,r);else{var x=i.selection.getNode();U||!h[0].defaultBlock||I.getParent(x,I.isBlock)||m(h[0].defaultBlock),i.selection.setRng(c()),y=F.getBookmark(),f(T(F.getRng(K),h),y),g.styles&&(g.styles.color||g.styles.textDecoration)&&(nt(x,p,"childNodes"),p(x)),F.moveToBookmark(y),P(F.getRng(K)),i.nodeChanged()}}function h(e,n,r){function o(e){var t,r,i,a,s;if(1===e.nodeType&&J(e)&&(a=C,C="true"===J(e),s=!0),t=tt(e.childNodes),C&&!s)for(r=0,i=m.length;i>r&&!R(m[r],n,e,e);r++);if(h.deep&&t.length){for(r=0,i=t.length;i>r;r++)o(t[r]);s&&(C=a)}}function s(t){var r;return et(a(t.parentNode).reverse(),function(t){var i;r||"_start"==t.id||"_end"==t.id||(i=v(t,e,n),i&&i.split!==!1&&(r=t))}),r}function l(e,t,r,i){var o,a,s,l,c,u;if(e){for(u=e.parentNode,o=t.parentNode;o&&o!=u;o=o.parentNode){for(a=I.clone(o,G),c=0;m.length>c;c++)if(R(m[c],n,a,a)){a=0;break}a&&(s&&a.appendChild(s),l||(l=a),s=a)}!i||h.mixed&&V(e)||(t=I.split(e,t)),s&&(r.parentNode.insertBefore(s,r),l.appendChild(r))}return t}function c(e){return l(s(e),e,e,!0)}function d(e){var t=I.get(e?"_start":"_end"),n=t[e?"firstChild":"lastChild"];return L(n)&&(n=n[e?"firstChild":"lastChild"]),I.remove(t,!0),n}function p(e){var t,n;e=T(e,m,K),h.split&&(t=M(e,K),n=M(e),t!=n?(/^(TR|TD)$/.test(t.nodeName)&&t.firstChild&&(t="TD"==t.nodeName?t.firstChild||t:t.firstChild.firstChild||t),t=S(t,"span",{id:"_start","data-mce-type":"bookmark"}),n=S(n,"span",{id:"_end","data-mce-type":"bookmark"}),c(t),c(n),t=d(K),n=d()):t=n=c(t),e.startContainer=t.parentNode,e.startOffset=q(t),e.endContainer=n.parentNode,e.endOffset=q(n)+1),W.walk(e,function(e){et(e,function(e){o(e),1===e.nodeType&&"underline"===i.dom.getStyle(e,"text-decoration")&&e.parentNode&&"underline"===f(e.parentNode)&&R({deep:!1,exact:!0,inline:"span",styles:{textDecoration:"underline"}},null,e)})})}var m=u(e),h=m[0],g,b,C=!0;return r?(r.nodeType?(b=I.createRng(),b.setStartBefore(r),b.setEndAfter(r),p(b)):p(r),t):(F.isCollapsed()&&h.inline&&!I.select("td.mce-item-selected,th.mce-item-selected").length?D("remove",e,n):(g=F.getBookmark(),p(F.getRng(K)),F.moveToBookmark(g),h.inline&&y(e,n,F.getStart())&&P(F.getRng(!0)),i.nodeChanged()),t)}function g(e,t,n){var r=u(e);!y(e,t,n)||"toggle"in r[0]&&!r[0].toggle?m(e,t,n):h(e,t,n)}function v(e,t,n,r){function i(e,t,i){var o,a,s=t[i],l;if(t.onmatch)return t.onmatch(e,t,i);if(s)if(s.length===X){for(o in s)if(s.hasOwnProperty(o)){if(a="attributes"===i?I.getAttrib(e,o):N(e,o),r&&!a&&!t.exact)return;if((!r||t.exact)&&!_(a,k(s[o],n)))return}}else for(l=0;s.length>l;l++)if("attributes"===i?I.getAttrib(e,s[l]):N(e,s[l]))return t;return t}var o=u(t),a,s,l;if(o&&e)for(s=0;o.length>s;s++)if(a=o[s],w(e,a)&&i(e,a,"attributes")&&i(e,a,"styles")){if(l=a.classes)for(s=0;l.length>s;s++)if(!I.hasClass(e,l[s]))return;return a}}function y(e,t,n){function r(n){return n=I.getParent(n,function(n){return!!v(n,e,t,!0)}),v(n,e,t)}var i;return n?r(n):(n=F.getNode(),r(n)?K:(i=F.getStart(),i!=n&&r(i)?K:G))}function b(e,t){var n,r=[],i={};return n=F.getStart(),I.getParent(n,function(n){var o,a;for(o=0;e.length>o;o++)a=e[o],!i[a]&&v(n,a,t)&&(i[a]=!0,r.push(a))},I.getRoot()),r}function C(e){var t=u(e),n,r,i,o,s;if(t)for(n=F.getStart(),r=a(n),o=t.length-1;o>=0;o--){if(s=t[o].selector,!s)return K;for(i=r.length-1;i>=0;i--)if(I.is(r[i],s))return K}return G}function x(e,n,r){var o;return Y||(Y={},o={},i.on("NodeChange",function(e){var n=a(e.element),r={};et(Y,function(e,i){et(n,function(a){return v(a,i,{},e.similar)?(o[i]||(et(e,function(e){e(!0,{node:a,format:i,parents:n})}),o[i]=e),r[i]=e,!1):t})}),et(o,function(t,i){r[i]||(delete o[i],et(t,function(t){t(!1,{node:e.element,format:i,parents:n})}))})})),et(e.split(","),function(e){Y[e]||(Y[e]=[],Y[e].similar=r),Y[e].push(n)}),this}function w(e,n){return _(e,n.inline)?K:_(e,n.block)?K:n.selector?1==e.nodeType&&I.is(e,n.selector):t}function _(e,t){return e=e||"",t=t||"",e=""+(e.nodeName||e),t=""+(t.nodeName||t),e.toLowerCase()==t.toLowerCase()}function N(e,t){var n=I.getStyle(e,t);return("color"==t||"backgroundColor"==t)&&(n=I.toHex(n)),"fontWeight"==t&&700==n&&(n="bold"),""+n}function k(e,t){return"string"!=typeof e?e=e(t):t&&(e=e.replace(/%(\w+)/g,function(e,n){return t[n]||e})),e}function E(e){return e&&3===e.nodeType&&/^([\t \r\n]+|)$/.test(e.nodeValue)}function S(e,t,n){var r=I.create(t,n);return e.parentNode.insertBefore(r,e),r.appendChild(e),r}function T(n,r,s){function l(e){function t(e){return"BR"==e.nodeName&&e.getAttribute("data-mce-bogus")&&!e.nextSibling}var n,i,o,a,s;if(n=i=e?v:b,a=e?"previousSibling":"nextSibling",s=I.getRoot(),3==n.nodeType&&!E(n)&&(e?y>0:n.nodeValue.length>C))return n;for(;;){if(!r[0].block_expand&&V(i))return i;for(o=i[a];o;o=o[a])if(!L(o)&&!E(o)&&!t(o))return i;if(i.parentNode==s){n=i;break}i=i.parentNode}return n}function c(e,t){for(t===X&&(t=3===e.nodeType?e.length:e.childNodes.length);e&&e.hasChildNodes();)e=e.childNodes[t],e&&(t=3===e.nodeType?e.length:e.childNodes.length);return{node:e,offset:t}}function u(e){for(var t=e;t;){if(1===t.nodeType&&J(t))return"false"===J(t)?t:e;t=t.parentNode}return e}function d(n,r,o){function a(e,n){var r,i,a=e.nodeValue;return n===t&&(n=o?a.length:0),o?(r=a.lastIndexOf(" ",n),i=a.lastIndexOf("\u00a0",n),r=r>i?r:i,-1===r||s||r++):(r=a.indexOf(" ",n),i=a.indexOf("\u00a0",n),r=-1!==r&&(-1===i||i>r)?r:i),r}var l,c,u,d;if(3===n.nodeType){if(u=a(n,r),-1!==u)return{container:n,offset:u};d=n}for(l=new e(n,I.getParent(n,V)||i.getBody());c=l[o?"prev":"next"]();)if(3===c.nodeType){if(d=c,u=a(c),-1!==u)return{container:c,offset:u}}else if(V(c))break;return d?(r=o?0:d.length,{container:d,offset:r}):t}function f(e,t){var i,o,s,l;for(3==e.nodeType&&0===e.nodeValue.length&&e[t]&&(e=e[t]),i=a(e),o=0;i.length>o;o++)for(s=0;r.length>s;s++)if(l=r[s],!("collapsed"in l&&l.collapsed!==n.collapsed)&&I.is(i[o],l.selector))return i[o];return e}function p(e,t){var n;if(r[0].wrapper||(n=I.getParent(e,r[0].block)),n||(n=I.getParent(3==e.nodeType?e.parentNode:e,o)),n&&r[0].wrapper&&(n=a(n,"ul,ol").reverse()[0]||n),!n)for(n=e;n[t]&&!V(n[t])&&(n=n[t],!_(n,"br")););return n||e}var m,h,g,v=n.startContainer,y=n.startOffset,b=n.endContainer,C=n.endOffset;if(1==v.nodeType&&v.hasChildNodes()&&(m=v.childNodes.length-1,v=v.childNodes[y>m?m:y],3==v.nodeType&&(y=0)),1==b.nodeType&&b.hasChildNodes()&&(m=b.childNodes.length-1,b=b.childNodes[C>m?m:C-1],3==b.nodeType&&(C=b.nodeValue.length)),v=u(v),b=u(b),(L(v.parentNode)||L(v))&&(v=L(v)?v:v.parentNode,v=v.nextSibling||v,3==v.nodeType&&(y=0)),(L(b.parentNode)||L(b))&&(b=L(b)?b:b.parentNode,b=b.previousSibling||b,3==b.nodeType&&(C=b.length)),r[0].inline&&(n.collapsed&&(g=d(v,y,!0),g&&(v=g.container,y=g.offset),g=d(b,C),g&&(b=g.container,C=g.offset)),h=c(b,C),h.node)){for(;h.node&&0===h.offset&&h.node.previousSibling;)h=c(h.node.previousSibling);h.node&&h.offset>0&&3===h.node.nodeType&&" "===h.node.nodeValue.charAt(h.offset-1)&&h.offset>1&&(b=h.node,b.splitText(h.offset-1))}return(r[0].inline||r[0].block_expand)&&(r[0].inline&&3==v.nodeType&&0!==y||(v=l(!0)),r[0].inline&&3==b.nodeType&&C!==b.nodeValue.length||(b=l())),r[0].selector&&r[0].expand!==G&&!r[0].inline&&(v=f(v,"previousSibling"),b=f(b,"nextSibling")),(r[0].block||r[0].selector)&&(v=p(v,"previousSibling"),b=p(b,"nextSibling"),r[0].block&&(V(v)||(v=l(!0)),V(b)||(b=l()))),1==v.nodeType&&(y=q(v),v=v.parentNode),1==b.nodeType&&(C=q(b)+1,b=b.parentNode),{startContainer:v,startOffset:y,endContainer:b,endOffset:C}}function R(e,n,r,i){var o,a,s;if(!w(r,e))return G;if("all"!=e.remove)for(et(e.styles,function(e,t){e=k(e,n),"number"==typeof t&&(t=e,i=0),(!i||_(N(i,t),e))&&I.setStyle(r,t,""),s=1}),s&&""===I.getAttrib(r,"style")&&(r.removeAttribute("style"),r.removeAttribute("data-mce-style")),et(e.attributes,function(e,o){var a;if(e=k(e,n),"number"==typeof o&&(o=e,i=0),!i||_(I.getAttrib(i,o),e)){if("class"==o&&(e=I.getAttrib(r,o),e&&(a="",et(e.split(/\s+/),function(e){/mce\w+/.test(e)&&(a+=(a?" ":"")+e)}),a)))return I.setAttrib(r,o,a),t;"class"==o&&r.removeAttribute("className"),j.test(o)&&r.removeAttribute("data-mce-"+o),r.removeAttribute(o)}}),et(e.classes,function(e){e=k(e,n),(!i||I.hasClass(i,e))&&I.removeClass(r,e)}),a=I.getAttribs(r),o=0;a.length>o;o++)if(0!==a[o].nodeName.indexOf("_"))return G;return"none"!=e.remove?(A(r,e),K):t}function A(e,t){function n(e,t,n){return e=B(e,t,n),!e||"BR"==e.nodeName||V(e)}var r=e.parentNode,i;t.block&&(U?r==I.getRoot()&&(t.list_block&&_(e,t.list_block)||et(tt(e.childNodes),function(e){z(U,e.nodeName.toLowerCase())?i?i.appendChild(e):i=S(e,U):i=0})):V(e)&&!V(r)&&(n(e,G)||n(e.firstChild,K,1)||e.insertBefore(I.create("br"),e.firstChild),n(e,K)||n(e.lastChild,G,1)||e.appendChild(I.create("br")))),t.selector&&t.inline&&!_(t.inline,e)||I.remove(e,1)}function B(e,t,n){if(e)for(t=t?"nextSibling":"previousSibling",e=n?e:e[t];e;e=e[t])if(1==e.nodeType||!E(e))return e}function L(e){return e&&1==e.nodeType&&"bookmark"==e.getAttribute("data-mce-type")}function H(e,t){function n(e,t){function n(e){var t={};return et(I.getAttribs(e),function(n){var r=n.nodeName.toLowerCase();0!==r.indexOf("_")&&"style"!==r&&(t[r]=I.getAttrib(e,r))}),t}function r(e,t){var n,r;for(r in e)if(e.hasOwnProperty(r)){if(n=t[r],n===X)return G;if(e[r]!=n)return G;delete t[r]}for(r in t)if(t.hasOwnProperty(r))return G;return K}return e.nodeName!=t.nodeName?G:r(n(e),n(t))?r(I.parseStyle(I.getAttrib(e,"style")),I.parseStyle(I.getAttrib(t,"style")))?K:G:G}function r(e,t){for(i=e;i;i=i[t]){if(3==i.nodeType&&0!==i.nodeValue.length)return e;if(1==i.nodeType&&!L(i))return i}return e}var i,o;if(e&&t&&(e=r(e,"previousSibling"),t=r(t,"nextSibling"),n(e,t))){for(i=e.nextSibling;i&&i!=t;)o=i,i=i.nextSibling,e.appendChild(o);return I.remove(t),et(tt(t.childNodes),function(t){e.appendChild(t)}),e}return t}function M(t,n){var r,o,a;return r=t[n?"startContainer":"endContainer"],o=t[n?"startOffset":"endOffset"],1==r.nodeType&&(a=r.childNodes.length-1,!n&&o&&o--,r=r.childNodes[o>a?a:o]),3===r.nodeType&&n&&o>=r.nodeValue.length&&(r=new e(r,i.getBody()).next()||r),3!==r.nodeType||n||0!==o||(r=new e(r,i.getBody()).prev()||r),r}function D(t,n,r){function o(e){var t=I.create("span",{id:g,"data-mce-bogus":!0,style:y?"color:red":""});return e&&t.appendChild(i.getDoc().createTextNode($)),t}function a(e,t){for(;e;){if(3===e.nodeType&&e.nodeValue!==$||e.childNodes.length>1)return!1;t&&1===e.nodeType&&t.push(e),e=e.firstChild}return!0}function s(e){for(;e;){if(e.id===g)return e;e=e.parentNode}}function l(t){var n;if(t)for(n=new e(t,t),t=n.current();t;t=n.next())if(3===t.nodeType)return t}function c(e,t){var n,r;if(e)r=F.getRng(!0),a(e)?(t!==!1&&(r.setStartBefore(e),r.setEndBefore(e)),I.remove(e)):(n=l(e),n.nodeValue.charAt(0)===$&&(n=n.deleteData(0,1)),I.remove(e,1)),F.setRng(r);else if(e=s(F.getStart()),!e)for(;e=I.get(g);)c(e,!1)}function d(){var e,t,i,a,c,d,f;e=F.getRng(!0),a=e.startOffset,d=e.startContainer,f=d.nodeValue,t=s(F.getStart()),t&&(i=l(t)),f&&a>0&&f.length>a&&/\w/.test(f.charAt(a))&&/\w/.test(f.charAt(a-1))?(c=F.getBookmark(),e.collapse(!0),e=T(e,u(n)),e=W.split(e),m(n,r,e),F.moveToBookmark(c)):(t&&i.nodeValue===$?m(n,r,t):(t=o(!0),i=t.firstChild,e.insertNode(t),a=1,m(n,r,t)),F.setCursorLocation(i,a))}function f(){var e=F.getRng(!0),t,i,a,s,l,c,d=[],f,p;for(t=e.startContainer,i=e.startOffset,l=t,3==t.nodeType&&((i!=t.nodeValue.length||t.nodeValue===$)&&(s=!0),l=l.parentNode);l;){if(v(l,n,r)){c=l;break}l.nextSibling&&(s=!0),d.push(l),l=l.parentNode}if(c)if(s)a=F.getBookmark(),e.collapse(!0),e=T(e,u(n),!0),e=W.split(e),h(n,r,e),F.moveToBookmark(a);else{for(p=o(),l=p,f=d.length-1;f>=0;f--)l.appendChild(I.clone(d[f],!1)),l=l.firstChild;l.appendChild(I.doc.createTextNode($)),l=l.firstChild,I.insertAfter(p,c),F.setCursorLocation(l,1)}}function p(){var e;e=s(F.getStart()),e&&!I.isEmpty(e)&&nt(e,function(e){1!=e.nodeType||e.id===g||I.isEmpty(e)||I.setAttrib(e,"data-mce-bogus",null)},"childNodes")}var g="_mce_caret",y=i.settings.caret_debug;i._hasCaretEvents||(Z=function(){var e=[],t;if(a(s(F.getStart()),e))for(t=e.length;t--;)I.setAttrib(e[t],"data-mce-bogus","1")},Q=function(e){var t=e.keyCode;c(),(8==t||37==t||39==t)&&c(s(F.getStart())),p()},i.on("SetContent",function(e){e.selection&&p()}),i._hasCaretEvents=!0),"apply"==t?d():f()}function P(n){var r=n.startContainer,i=n.startOffset,o,a,s,l,c;if(3==r.nodeType&&i>=r.nodeValue.length&&(i=q(r),r=r.parentNode,o=!0),1==r.nodeType)for(l=r.childNodes,r=l[Math.min(i,l.length-1)],a=new e(r,I.getParent(r,I.isBlock)),(i>l.length-1||o)&&a.next(),s=a.current();s;s=a.next())if(3==s.nodeType&&!E(s))return c=I.create("a",null,$),s.parentNode.insertBefore(c,s),n.setStart(s,0),F.setRng(n),I.remove(c),t}var O={},I=i.dom,F=i.selection,W=new n(I),z=i.schema.isValidChild,V=I.isBlock,U=i.settings.forced_root_block,q=I.nodeIndex,$="\ufeff",j=/^(src|href|style)$/,G=!1,K=!0,Y,X,J=I.getContentEditable,Q,Z,et=r.each,tt=r.grep,nt=r.walk,rt=r.extend;rt(this,{get:u,register:d,apply:m,remove:h,toggle:g,match:y,matchAll:b,matchNode:v,canApply:C,formatChanged:x}),l(),c(),i.on("BeforeGetContent",function(){Z&&Z()}),i.on("mouseup keydown",function(e){Q&&Q(e)})}}),r(L,[h,f],function(e,n){var r=n.trim,i;return i=RegExp(["]+data-mce-bogus[^>]+>[\u200b\ufeff]+<\\/span>","]+data-mce-bogus[^>]+><\\/div>",'\\s?data-mce-selected="[^"]+"'].join("|"),"gi"),function(n){function o(){return r(n.getContent({format:"raw",no_events:1}).replace(i,""))}function a(){s.typing=!1,s.add()}var s,l=0,c=[],u;return n.on("init",function(){s.add()}),n.on("BeforeExecCommand",function(e){var t=e.command;"Undo"!=t&&"Redo"!=t&&"mceRepaint"!=t&&s.beforeChange()}),n.on("ExecCommand",function(e){var t=e.command;"Undo"!=t&&"Redo"!=t&&"mceRepaint"!=t&&s.add()}),n.on("ObjectResizeStart",function(){s.beforeChange()}),n.on("SaveContent ObjectResized",a),n.dom.bind(n.dom.getRoot(),"dragend",a),n.dom.bind(n.getBody(),"focusout",function(){!n.removed&&s.typing&&a()}),n.on("KeyUp",function(t){var r=t.keyCode;(r>=33&&36>=r||r>=37&&40>=r||45==r||13==r||t.ctrlKey)&&(a(),n.nodeChanged()),(46==r||8==r||e.isMac&&(91==r||93==r))&&n.nodeChanged()}),n.on("KeyDown",function(e){var n=e.keyCode;return n>=33&&36>=n||n>=37&&40>=n||45==n?(s.typing&&a(),t):((16>n||n>20)&&224!=n&&91!=n&&!s.typing&&(s.beforeChange(),s.typing=!0,s.add()),t)}),n.on("MouseDown",function(){s.typing&&a()}),n.addShortcut("ctrl+z","undo_desc","Undo"),n.addShortcut("ctrl+y","redo_desc","Redo"),n.on("AddUndo Undo Redo ClearUndos MouseUp",function(e){e.isDefaultPrevented()||n.nodeChanged()}),s={data:c,typing:!1,beforeChange:function(){u=n.selection.getBookmark(2,!0)},add:function(e){var t,r=n.settings,i;if(e=e||{},e.content=o(),n.fire("BeforeAddUndo",{level:e}).isDefaultPrevented())return null;if(i=c[l],i&&i.content==e.content)return null;if(c[l]&&(c[l].beforeBookmark=u),r.custom_undo_redo_levels&&c.length>r.custom_undo_redo_levels){for(t=0;c.length-1>t;t++)c[t]=c[t+1];c.length--,l=c.length}return e.bookmark=n.selection.getBookmark(2,!0),c.length-1>l&&(c.length=l+1),c.push(e),l=c.length-1,n.fire("AddUndo",{level:e,lastLevel:i}),n.isNotDirty=0,e},undo:function(){var e;return s.typing&&(s.add(),s.typing=!1),l>0&&(e=c[--l],n.setContent(e.content,{format:"raw"}),n.selection.moveToBookmark(e.beforeBookmark),n.fire("undo",{level:e})),e},redo:function(){var e;return c.length-1>l&&(e=c[++l],n.setContent(e.content,{format:"raw"}),n.selection.moveToBookmark(e.bookmark),n.fire("redo",{level:e})),e},clear:function(){c=[],l=0,s.typing=!1,n.fire("ClearUndos")},hasUndo:function(){return l>0||s.typing&&c[0]&&o()!=c[0].content},hasRedo:function(){return c.length-1>l&&!this.typing},transact:function(e){s.beforeChange(),e(),s.add()}}}}),r(H,[d,h],function(e,n){var r=n.ie;return function(n){function i(i){function d(e){return e&&o.isBlock(e)&&!/^(TD|TH|CAPTION|FORM)$/.test(e.nodeName)&&!/^(fixed|absolute)/i.test(e.style.position)&&"true"!==o.getContentEditable(e) +}function f(e){var t;o.isBlock(e)&&(t=a.getRng(),e.appendChild(o.create("span",null,"\u00a0")),a.select(e),e.lastChild.outerHTML="",a.setRng(t))}function p(e){for(var t=e,n=[],r;t=t.firstChild;){if(o.isBlock(t))return;1!=t.nodeType||u[t.nodeName.toLowerCase()]||n.push(t)}for(r=n.length;r--;)t=n[r],!t.hasChildNodes()||t.firstChild==t.lastChild&&""===t.firstChild.nodeValue?o.remove(t):"A"==t.nodeName&&" "===(t.innerText||t.textContent)&&o.remove(t)}function m(t){var n,r,i,s=t,l;if(i=o.createRng(),t.hasChildNodes()){for(n=new e(t,t);r=n.current();){if(3==r.nodeType){i.setStart(r,0),i.setEnd(r,0);break}if(u[r.nodeName.toLowerCase()]){i.setStartBefore(r),i.setEndBefore(r);break}s=r,r=n.next()}r||(i.setStart(s,0),i.setEnd(s,0))}else"BR"==t.nodeName?t.nextSibling&&o.isBlock(t.nextSibling)?((!A||9>A)&&(l=o.create("br"),t.parentNode.insertBefore(l,t)),i.setStartBefore(t),i.setEndBefore(t)):(i.setStartAfter(t),i.setEndAfter(t)):(i.setStart(t,0),i.setEnd(t,0));a.setRng(i),o.remove(l),a.scrollIntoView(t)}function h(e){var t=S,n,i,a;if(n=e||"TABLE"==D?o.create(e||O):R.cloneNode(!1),a=n,s.keep_styles!==!1)do if(/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(t.nodeName)){if("_mce_caret"==t.id)continue;i=t.cloneNode(!1),o.setAttrib(i,"id",""),n.hasChildNodes()?(i.appendChild(n.firstChild),n.appendChild(i)):(a=i,n.appendChild(i))}while(t=t.parentNode);return r||(a.innerHTML='
    '),n}function g(t){var n,r,i;if(3==S.nodeType&&(t?T>0:S.nodeValue.length>T))return!1;if(S.parentNode==R&&I&&!t)return!0;if(t&&1==S.nodeType&&S==R.firstChild)return!0;if("TABLE"===S.nodeName||S.previousSibling&&"TABLE"==S.previousSibling.nodeName)return I&&!t||!I&&t;for(n=new e(S,R),3==S.nodeType&&(t&&0===T?n.prev():t||T!=S.nodeValue.length||n.next());r=n.current();){if(1===r.nodeType){if(!r.getAttribute("data-mce-bogus")&&(i=r.nodeName.toLowerCase(),u[i]&&"br"!==i))return!1}else if(3===r.nodeType&&!/^[ \t\r\n]*$/.test(r.nodeValue))return!1;t?n.prev():n.next()}return!0}function v(e,t){var r,i,a,s,l,u,f=O||"P";if(i=o.getParent(e,o.isBlock),u=n.getBody().nodeName.toLowerCase(),!i||!d(i)){if(i=i||E,!i.hasChildNodes())return r=o.create(f),i.appendChild(r),N.setStart(r,0),N.setEnd(r,0),r;for(s=e;s.parentNode!=i;)s=s.parentNode;for(;s&&!o.isBlock(s);)a=s,s=s.previousSibling;if(a&&c.isValidChild(u,f.toLowerCase())){for(r=o.create(f),a.parentNode.insertBefore(r,a),s=a;s&&!o.isBlock(s);)l=s.nextSibling,r.appendChild(s),s=l;N.setStart(e,t),N.setEnd(e,t)}}return e}function y(){function e(e){for(var t=M[e?"firstChild":"lastChild"];t&&1!=t.nodeType;)t=t[e?"nextSibling":"previousSibling"];return t===R}function t(){var e=M.parentNode;return"LI"==e.nodeName?e:M}var n=M.parentNode.nodeName;/^(OL|UL|LI)$/.test(n)&&(O="LI"),L=O?h(O):o.create("BR"),e(!0)&&e()?"LI"==n?o.insertAfter(L,t()):o.replace(L,M):e(!0)?"LI"==n?(o.insertAfter(L,t()),L.appendChild(o.doc.createTextNode(" ")),L.appendChild(M)):M.parentNode.insertBefore(L,M):e()?(o.insertAfter(L,t()),f(L)):(M=t(),k=N.cloneRange(),k.setStartAfter(R),k.setEndAfter(M),H=k.extractContents(),o.insertAfter(H,M),o.insertAfter(L,M)),o.remove(R),m(L),l.add()}function b(){for(var t=new e(S,R),n;n=t.next();)if(u[n.nodeName.toLowerCase()]||n.length>0)return!0}function C(){var e,t,n;S&&3==S.nodeType&&T>=S.nodeValue.length&&(r||b()||(e=o.create("br"),N.insertNode(e),N.setStartAfter(e),N.setEndAfter(e),t=!0)),e=o.create("br"),N.insertNode(e),r&&"PRE"==D&&(!A||8>A)&&e.parentNode.insertBefore(o.doc.createTextNode("\r"),e),n=o.create("span",{}," "),e.parentNode.insertBefore(n,e),a.scrollIntoView(n),o.remove(n),t?(N.setStartBefore(e),N.setEndBefore(e)):(N.setStartAfter(e),N.setEndAfter(e)),a.setRng(N),l.add()}function x(e){do 3===e.nodeType&&(e.nodeValue=e.nodeValue.replace(/^[\r\n]+/,"")),e=e.firstChild;while(e)}function w(e){var t=o.getRoot(),n,r;for(n=e;n!==t&&"false"!==o.getContentEditable(n);)"true"===o.getContentEditable(n)&&(r=n),n=n.parentNode;return n!==t?r:t}function _(e){var t;r||(e.normalize(),t=e.lastChild,(!t||/^(left|right)$/gi.test(o.getStyle(t,"float",!0)))&&o.add(e,"br"))}var N=a.getRng(!0),k,E,S,T,R,A,B,L,H,M,D,P,O,I;if(!N.collapsed)return n.execCommand("Delete"),t;if(!i.isDefaultPrevented()&&(S=N.startContainer,T=N.startOffset,O=(s.force_p_newlines?"p":"")||s.forced_root_block,O=O?O.toUpperCase():"",A=o.doc.documentMode,B=i.shiftKey,1==S.nodeType&&S.hasChildNodes()&&(I=T>S.childNodes.length-1,S=S.childNodes[Math.min(T,S.childNodes.length-1)]||S,T=I&&3==S.nodeType?S.nodeValue.length:0),E=w(S))){if(l.beforeChange(),!o.isBlock(E)&&E!=o.getRoot())return(!O||B)&&C(),t;if((O&&!B||!O&&B)&&(S=v(S,T)),R=o.getParent(S,o.isBlock),M=R?o.getParent(R.parentNode,o.isBlock):null,D=R?R.nodeName.toUpperCase():"",P=M?M.nodeName.toUpperCase():"","LI"!=P||i.ctrlKey||(R=M,D=P),"LI"==D){if(!O&&B)return C(),t;if(o.isEmpty(R))return y(),t}if("PRE"==D&&s.br_in_pre!==!1){if(!B)return C(),t}else if(!O&&!B&&"LI"!=D||O&&B)return C(),t;O&&R===n.getBody()||(O=O||"P",g()?(L=/^(H[1-6]|PRE|FIGURE)$/.test(D)&&"HGROUP"!=P?h(O):h(),s.end_container_on_empty_block&&d(M)&&o.isEmpty(R)?L=o.split(M,R):o.insertAfter(L,R),m(L)):g(!0)?(L=R.parentNode.insertBefore(h(),R),f(L)):(k=N.cloneRange(),k.setEndAfter(R),H=k.extractContents(),x(H),L=H.firstChild,o.insertAfter(H,R),p(L),_(R),m(L)),o.setAttrib(L,"id",""),l.add())}}var o=n.dom,a=n.selection,s=n.settings,l=n.undoManager,c=n.schema,u=c.getNonEmptyElements();n.on("keydown",function(e){13==e.keyCode&&i(e)!==!1&&e.preventDefault()})}}),r(M,[],function(){return function(e){function t(){var t=i.getStart(),s=e.getBody(),l,c,u,d,f,p,m,h=-16777215,g,v,y,b,C;if(C=n.forced_root_block,t&&1===t.nodeType&&C){for(;t&&t!=s;){if(a[t.nodeName])return;t=t.parentNode}for(l=i.getRng(),l.setStart?(c=l.startContainer,u=l.startOffset,d=l.endContainer,f=l.endOffset,v=e.getDoc().activeElement===s):(l.item&&(t=l.item(0),l=e.getDoc().body.createTextRange(),l.moveToElementText(t)),v=l.parentElement().ownerDocument===e.getDoc(),y=l.duplicate(),y.collapse(!0),u=-1*y.move("character",h),y.collapsed||(y=l.duplicate(),y.collapse(!1),f=-1*y.move("character",h)-u)),t=s.firstChild,b=s.nodeName.toLowerCase();t;)if((3===t.nodeType||1==t.nodeType&&!a[t.nodeName])&&o.isValidChild(b,C.toLowerCase())){if(3===t.nodeType&&0===t.nodeValue.length){m=t,t=t.nextSibling,r.remove(m);continue}p||(p=r.create(C),t.parentNode.insertBefore(p,t),g=!0),m=t,t=t.nextSibling,p.appendChild(m)}else p=null,t=t.nextSibling;if(g&&v){if(l.setStart)l.setStart(c,u),l.setEnd(d,f),i.setRng(l);else try{l=e.getDoc().body.createTextRange(),l.moveToElementText(s),l.collapse(!0),l.moveStart("character",u),f>0&&l.moveEnd("character",f),l.select()}catch(x){}e.nodeChanged()}}}var n=e.settings,r=e.dom,i=e.selection,o=e.schema,a=o.getBlockElements();n.forced_root_block&&e.on("KeyUp NodeChange",t)}}),r(D,[N,h,f],function(e,n,r){var i=r.each,o=r.extend,a=r.map,s=r.inArray,l=r.explode,c=n.gecko,u=n.ie,d=!0,f=!1;return function(n){function r(e,t,n){var r;return e=e.toLowerCase(),(r=_.exec[e])?(r(e,t,n),d):f}function p(e){var t;return e=e.toLowerCase(),(t=_.state[e])?t(e):-1}function m(e){var t;return e=e.toLowerCase(),(t=_.value[e])?t(e):f}function h(e,t){t=t||"exec",i(e,function(e,n){i(n.toLowerCase().split(","),function(n){_[t][n]=e})})}function g(e,r,i){return r===t&&(r=f),i===t&&(i=null),n.getDoc().execCommand(e,r,i)}function v(e){return k.match(e)}function y(e,r){k.toggle(e,r?{value:r}:t),n.nodeChanged()}function b(e){E=w.getBookmark(e)}function C(){w.moveToBookmark(E)}var x=n.dom,w=n.selection,_={state:{},exec:{},value:{}},N=n.settings,k=n.formatter,E;o(this,{execCommand:r,queryCommandState:p,queryCommandValue:m,addCommands:h}),h({"mceResetDesignMode,mceBeginUndoLevel":function(){},"mceEndUndoLevel,mceAddUndoLevel":function(){n.undoManager.add()},"Cut,Copy,Paste":function(e){var t=n.getDoc(),r;try{g(e)}catch(i){r=d}(r||!t.queryCommandSupported(e))&&(c?n.windowManager.confirm(n.getLang("clipboard_msg"),function(e){e&&window.open("http://www.mozilla.org/editor/midasdemo/securityprefs.html","_blank")}):n.windowManager.alert("Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X/C/V keyboard shortcuts instead."))},unlink:function(e){w.isCollapsed()&&w.select(w.getNode()),g(e),w.collapse(f)},"JustifyLeft,JustifyCenter,JustifyRight,JustifyFull":function(e){var t=e.substring(7);"full"==t&&(t="justify"),i("left,center,right,justify".split(","),function(e){t!=e&&k.remove("align"+e)}),y("align"+t),r("mceRepaint")},"InsertUnorderedList,InsertOrderedList":function(e){var t,n;g(e),t=x.getParent(w.getNode(),"ol,ul"),t&&(n=t.parentNode,/^(H[1-6]|P|ADDRESS|PRE)$/.test(n.nodeName)&&(b(),x.split(n,t),C()))},"Bold,Italic,Underline,Strikethrough,Superscript,Subscript":function(e){y(e)},"ForeColor,HiliteColor,FontName":function(e,t,n){y(e,n)},FontSize:function(e,t,n){var r,i;n>=1&&7>=n&&(i=l(N.font_size_style_values),r=l(N.font_size_classes),n=r?r[n-1]||n:i[n-1]||n),y(e,n)},RemoveFormat:function(e){k.remove(e)},mceBlockQuote:function(){y("blockquote")},FormatBlock:function(e,t,n){return y(n||"p")},mceCleanup:function(){var e=w.getBookmark();n.setContent(n.getContent({cleanup:d}),{cleanup:d}),w.moveToBookmark(e)},mceRemoveNode:function(e,t,r){var i=r||w.getNode();i!=n.getBody()&&(b(),n.dom.remove(i,d),C())},mceSelectNodeDepth:function(e,r,i){var o=0;x.getParent(w.getNode(),function(e){return 1==e.nodeType&&o++==i?(w.select(e),f):t},n.getBody())},mceSelectNode:function(e,t,n){w.select(n)},mceInsertContent:function(t,r,i){function o(e){function t(e){return r[e]&&3==r[e].nodeType}var n,r,i;return n=w.getRng(!0),r=n.startContainer,i=n.startOffset,3==r.nodeType&&(i>0?e=e.replace(/^ /," "):t("previousSibling")||(e=e.replace(/^ /," ")),r.length>i?e=e.replace(/ (
    |)$/," "):t("nextSibling")||(e=e.replace(/( | )(
    |)$/," "))),e}var a,s,l,c,d,f,p,m,h,g,v,y,b,C;if(/^ | $/.test(i)&&(i=o(i)),a=n.parser,s=new e({},n.schema),b='',f={content:i,format:"html",selection:!0},n.fire("BeforeSetContent",f),i=f.content,-1==i.indexOf("{$caret}")&&(i+="{$caret}"),i=i.replace(/\{\$caret\}/,b),w.isCollapsed()||n.getDoc().execCommand("Delete",!1,null),l=w.getNode(),f={context:l.nodeName.toLowerCase()},d=a.parse(i,f),v=d.lastChild,"mce_marker"==v.attr("id"))for(p=v,v=v.prev;v;v=v.walk(!0))if(3==v.type||!x.isBlock(v.name)){v.parent.insert(p,v,"br"===v.name);break}if(f.invalid){for(w.setContent(b),l=w.getNode(),c=n.getBody(),9==l.nodeType?l=v=c:v=l;v!==c;)l=v,v=v.parentNode;i=l==c?c.innerHTML:x.getOuterHTML(l),i=s.serialize(a.parse(i.replace(//i,function(){return s.serialize(d)}))),l==c?x.setHTML(c,i):x.setOuterHTML(l,i)}else i=s.serialize(d),v=l.firstChild,y=l.lastChild,!v||v===y&&"BR"===v.nodeName?x.setHTML(l,i):w.setContent(i);p=x.get("mce_marker"),m=x.getRect(p),h=x.getViewPort(n.getWin()),(m.y+m.h>h.y+h.h||m.yh.x+h.w||m.x")},mceToggleVisualAid:function(){n.hasVisual=!n.hasVisual,n.addVisual()},mceReplaceContent:function(e,t,r){n.execCommand("mceInsertContent",!1,r.replace(/\{\$selection\}/g,w.getContent({format:"text"})))},mceInsertLink:function(e,t,n){var r;"string"==typeof n&&(n={href:n}),r=x.getParent(w.getNode(),"a"),n.href=n.href.replace(" ","%20"),r&&n.href||k.remove("link"),n.href&&k.apply("link",n,r)},selectAll:function(){var e=x.getRoot(),t=x.createRng();w.getRng().setStart?(t.setStart(e,0),t.setEnd(e,e.childNodes.length),w.setRng(t)):g("SelectAll")},mceNewDocument:function(){n.setContent("")}}),h({"JustifyLeft,JustifyCenter,JustifyRight,JustifyFull":function(e){var t="align"+e.substring(7),n=w.isCollapsed()?[x.getParent(w.getNode(),x.isBlock)]:w.getSelectedBlocks(),r=a(n,function(e){return!!k.matchNode(e,t)});return-1!==s(r,d)},"Bold,Italic,Underline,Strikethrough,Superscript,Subscript":function(e){return v(e)},mceBlockQuote:function(){return v("blockquote")},Outdent:function(){var e;if(N.inline_styles){if((e=x.getParent(w.getStart(),x.isBlock))&&parseInt(e.style.paddingLeft,10)>0)return d;if((e=x.getParent(w.getEnd(),x.isBlock))&&parseInt(e.style.paddingLeft,10)>0)return d}return p("InsertUnorderedList")||p("InsertOrderedList")||!N.inline_styles&&!!x.getParent(w.getNode(),"BLOCKQUOTE")},"InsertUnorderedList,InsertOrderedList":function(e){var t=x.getParent(w.getNode(),"ul,ol");return t&&("insertunorderedlist"===e&&"UL"===t.tagName||"insertorderedlist"===e&&"OL"===t.tagName)}},"state"),h({"FontSize,FontName":function(e){var t=0,n;return(n=x.getParent(w.getNode(),"span"))&&(t="fontsize"==e?n.style.fontSize:n.style.fontFamily.replace(/, /g,",").replace(/[\'\"]/g,"").toLowerCase()),t}},"value"),h({Undo:function(){n.undoManager.undo()},Redo:function(){n.undoManager.redo()}})}}),r(P,[f],function(e){function n(e,o){var a=this,s,l;return e=i(e),o=a.settings=o||{},/^([\w\-]+):([^\/]{2})/i.test(e)||/^\s*#/.test(e)?(a.source=e,t):(0===e.indexOf("/")&&0!==e.indexOf("//")&&(e=(o.base_uri?o.base_uri.protocol||"http":"http")+"://mce_host"+e),/^[\w\-]*:?\/\//.test(e)||(l=o.base_uri?o.base_uri.path:new n(location.href).directory,e=(o.base_uri&&o.base_uri.protocol||"http")+"://mce_host"+a.toAbsPath(l,e)),e=e.replace(/@@/g,"(mce_at)"),e=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(e),r(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],function(t,n){var r=e[n];r&&(r=r.replace(/\(mce_at\)/g,"@@")),a[t]=r}),s=o.base_uri,s&&(a.protocol||(a.protocol=s.protocol),a.userInfo||(a.userInfo=s.userInfo),a.port||"mce_host"!==a.host||(a.port=s.port),a.host&&"mce_host"!==a.host||(a.host=s.host),a.source=""),t)}var r=e.each,i=e.trim;return n.prototype={setPath:function(e){var t=this;e=/^(.*?)\/?(\w+)?$/.exec(e),t.path=e[0],t.directory=e[1],t.file=e[2],t.source="",t.getURI()},toRelative:function(e){var t=this,r;if("./"===e)return e;if(e=new n(e,{base_uri:t}),"mce_host"!=e.host&&t.host!=e.host&&e.host||t.port!=e.port||t.protocol!=e.protocol)return e.getURI();var i=t.getURI(),o=e.getURI();return i==o||"/"==i.charAt(i.length-1)&&i.substr(0,i.length-1)==o?i:(r=t.toRelPath(t.path,e.path),e.query&&(r+="?"+e.query),e.anchor&&(r+="#"+e.anchor),r)},toAbsolute:function(e,t){return e=new n(e,{base_uri:this}),e.getURI(this.host==e.host&&this.protocol==e.protocol?t:0)},toRelPath:function(e,t){var n,r=0,i="",o,a;if(e=e.substring(0,e.lastIndexOf("/")),e=e.split("/"),n=t.split("/"),e.length>=n.length)for(o=0,a=e.length;a>o;o++)if(o>=n.length||e[o]!=n[o]){r=o+1;break}if(e.lengtho;o++)if(o>=e.length||e[o]!=n[o]){r=o+1;break}if(1===r)return t;for(o=0,a=e.length-(r-1);a>o;o++)i+="../";for(o=r-1,a=n.length;a>o;o++)i+=o!=r-1?"/"+n[o]:n[o];return i},toAbsPath:function(e,t){var n,i=0,o=[],a,s;for(a=/\/$/.test(t)?"/":"",e=e.split("/"),t=t.split("/"),r(e,function(e){e&&o.push(e)}),e=o,n=t.length-1,o=[];n>=0;n--)0!==t[n].length&&"."!==t[n]&&(".."!==t[n]?i>0?i--:o.push(t[n]):i++);return n=e.length-i,s=0>=n?o.reverse().join("/"):e.slice(0,n).join("/")+"/"+o.reverse().join("/"),0!==s.indexOf("/")&&(s="/"+s),a&&s.lastIndexOf("/")!==s.length-1&&(s+=a),s},getURI:function(e){var t,n=this;return(!n.source||e)&&(t="",e||(n.protocol&&(t+=n.protocol+"://"),n.userInfo&&(t+=n.userInfo+"@"),n.host&&(t+=n.host),n.port&&(t+=":"+n.port)),n.path&&(t+=n.path),n.query&&(t+="?"+n.query),n.anchor&&(t+="#"+n.anchor),n.source=t),n.source}},n}),r(O,[f],function(e){function t(){}var n=e.each,r=e.extend,i,o;return t.extend=i=function(e){function t(){var e,t,n,r;if(!o&&(r=this,r.init&&r.init.apply(r,arguments),t=r.Mixins))for(e=t.length;e--;)n=t[e],n.init&&n.init.apply(r,arguments)}function a(){return this}function s(e,t){return function(){var n=this,r=n._super,i;return n._super=c[e],i=t.apply(n,arguments),n._super=r,i}}var l=this,c=l.prototype,u,d,f;o=!0,u=new l,o=!1,e.Mixins&&(n(e.Mixins,function(t){t=t;for(var n in t)"init"!==n&&(e[n]=t[n])}),c.Mixins&&(e.Mixins=c.Mixins.concat(e.Mixins))),e.Methods&&n(e.Methods.split(","),function(t){e[t]=a}),e.Properties&&n(e.Properties.split(","),function(t){var n="_"+t;e[t]=function(e){var t=this,r;return e!==r?(t[n]=e,t):t[n]}}),e.Statics&&n(e.Statics,function(e,n){t[n]=e}),e.Defaults&&c.Defaults&&(e.Defaults=r({},c.Defaults,e.Defaults));for(d in e)f=e[d],u[d]="function"==typeof f&&c[d]?s(d,f):f;return t.prototype=u,t.constructor=t,t.extend=i,t},t}),r(I,[O,f],function(e,n){function r(e){for(var t=[],n=e.length,r;n--;)r=e[n],r.__checked||(t.push(r),r.__checked=1);for(n=t.length;n--;)delete t[n].__checked;return t}var i=/^([\w\\*]+)?(?:#([\w\\]+))?(?:\.([\w\\\.]+))?(?:\[\@?([\w\\]+)([\^\$\*!~]?=)([\w\\]+)\])?(?:\:(.+))?/i,o=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,a=/^\s*|\s*$/g,s,l=e.extend({init:function(e){function n(e){return e?(e=e.toLowerCase(),function(t){return"*"===e||t.type===e}):t}function r(e){return e?function(t){return t._name===e}:t}function s(e){return e?(e=e.split("."),function(t){for(var n=e.length;n--;)if(!t.hasClass(e[n]))return!1;return!0}):t}function l(e,n,r){return e?function(t){var i=t[e]?t[e]():"";return n?"="===n?i===r:"*="===n?i.indexOf(r)>=0:"~="===n?(" "+i+" ").indexOf(" "+r+" ")>=0:"!="===n?i!=r:"^="===n?0===i.indexOf(r):"$="===n?i.substr(i.length-r.length)===r:!1:!!r}:t}function c(e){var n;return e?(e=/(?:not\((.+)\))|(.+)/i.exec(e),e[1]?(n=d(e[1],[]),function(e){return!f(e,n)}):(e=e[2],function(t,n,r){return"first"===e?0===n:"last"===e?n===r-1:"even"===e?0===n%2:"odd"===e?1===n%2:t[e]?t[e]():!1})):t}function u(e,t,o){function u(e){e&&t.push(e)}var d;return d=i.exec(e.replace(a,"")),u(n(d[1])),u(r(d[2])),u(s(d[3])),u(l(d[4],d[5],d[6])),u(c(d[7])),t.psuedo=!!d[7],t.direct=o,t}function d(e,t){var n=[],r,i,a;do if(o.exec(""),i=o.exec(e),i&&(e=i[3],n.push(i[1]),i[2])){r=i[3];break}while(i);for(r&&d(r,t),e=[],a=0;n.length>a;a++)">"!=n[a]&&e.push(u(n[a],[],">"===n[a-1]));return t.push(e),t}var f=this.match;this._selectors=d(e,[])},match:function(e,t){var r,i,o,a,s,l,c,u,d,f,p,m,h;for(t=t||this._selectors,r=0,i=t.length;i>r;r++){for(s=t[r],a=s.length,h=e,m=0,o=a-1;o>=0;o--)for(u=s[o];h;){for(u.psuedo&&(p=h.parent().items(),d=n.inArray(h,p),f=p.length),l=0,c=u.length;c>l;l++)if(!u[l](h,d,f)){l=c+1;break}if(l===c){m++;break}if(o===a-1)break;h=h.parent()}if(m===a)return!0}return!1},find:function(e){function t(e,r,i){var o,a,s,l,c,u=r[i];for(o=0,a=e.length;a>o;o++){for(c=e[o],s=0,l=u.length;l>s;s++)if(!u[s](c,o,a)){s=l+1;break}if(s===l)i==r.length-1?n.push(c):c.items&&t(c.items(),r,i+1);else if(u.direct)return;c.items&&t(c.items(),r,i)}}var n=[],i,o,a=this._selectors;if(e.items){for(i=0,o=a.length;o>i;i++)t(e.items(),a[i],0);o>1&&(n=r(n))}return s||(s=l.Collection),new s(n)}});return l}),r(F,[f,I,O],function(e,n,r){var i,o,a=Array.prototype.push,s=Array.prototype.slice;return o={length:0,init:function(e){e&&this.add(e)},add:function(t){var n=this;return e.isArray(t)?a.apply(n,t):t instanceof i?n.add(t.toArray()):a.call(n,t),n},set:function(e){var t=this,n=t.length,r;for(t.length=0,t.add(e),r=t.length;n>r;r++)delete t[r];return t},filter:function(e){var t=this,r,o,a=[],s,l;for("string"==typeof e?(e=new n(e),l=function(t){return e.match(t)}):l=e,r=0,o=t.length;o>r;r++)s=t[r],l(s)&&a.push(s);return new i(a)},slice:function(){return new i(s.apply(this,arguments))},eq:function(e){return-1===e?this.slice(e):this.slice(e,+e+1)},each:function(t){return e.each(this,t),this},toArray:function(){return e.toArray(this)},indexOf:function(e){for(var t=this,n=t.length;n--&&t[n]!==e;);return n},reverse:function(){return new i(e.toArray(this).reverse())},hasClass:function(e){return this[0]?this[0].hasClass(e):!1},prop:function(e,n){var r=this,i,o;return n!==i?(r.each(function(t){t[e]&&t[e](n)}),r):(o=r[0],o&&o[e]?o[e]():t)},exec:function(t){var n=this,r=e.toArray(arguments).slice(1);return n.each(function(e){e[t]&&e[t].apply(e,r)}),n}},e.each("fire on off show hide addClass removeClass append prepend before after reflow".split(" "),function(t){o[t]=function(){var n=e.toArray(arguments);return this.each(function(e){t in e&&e[t].apply(e,n)}),this}}),e.each("text name width height disabled active selected checked visible parent value data".split(" "),function(e){o[e]=function(t){return this.prop(e,t)}}),i=r.extend(o),n.Collection=i,i}),r(W,[f,g],function(e,t){return{id:function(){return t.DOM.uniqueId()},createFragment:function(e){return t.DOM.createFragment(e)},getWindowSize:function(){return t.DOM.getViewPort()},getSize:function(e){return t.DOM.getSize(e)},getPos:function(e,n){return t.DOM.getPos(e,n)},get:function(e){return document.getElementById(e)},addClass:function(e,n){return t.DOM.addClass(e,n)},removeClass:function(e,n){return t.DOM.removeClass(e,n)},hasClass:function(e,n){return t.DOM.hasClass(e,n)},toggleClass:function(e,n,r){return t.DOM.toggleClass(e,n,r)},css:function(e,n,r){return t.DOM.setStyle(e,n,r)},on:function(e,n,r,i){return t.DOM.bind(e,n,r,i)},off:function(e,n,r){return t.DOM.unbind(e,n,r)},fire:function(e,n,r){return t.DOM.fire(e,n,r)}}}),r(z,[O,f,F,W],function(e,n,r,i){var o=n.makeMap("focusin focusout scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave wheel keydown keypress keyup contextmenu"," "),a={},s="onmousewheel"in document,l=!1,c=e.extend({Statics:{controlIdLookup:{}},classPrefix:"mce-",getContainerElm:function(){return document.body},getParentCtrl:function(e){for(var t;e&&!(t=c.controlIdLookup[e.id]);)e=e.parentNode;return t},init:function(e){var r=this,o,a;if(r.settings=e=n.extend({},r.Defaults,e),r._id=i.id(),r._text=r._name="",r._width=r._height=0,r._aria={role:e.role},o=e.classes)for(o=o.split(" "),o.map={},a=o.length;a--;)o.map[o[a]]=!0;r._classes=o||[],r.visible(!0),n.each("title text width height name classes visible disabled active value".split(" "),function(t){var n=e[t],i;n!==i?r[t](n):r["_"+t]===i&&(r["_"+t]=!1)}),r.on("click",function(){return r.disabled()?!1:t}),e.classes&&n.each(e.classes.split(" "),function(e){r.addClass(e)}),r.settings=e,r._borderBox=r.parseBox(e.border),r._paddingBox=r.parseBox(e.padding),r._marginBox=r.parseBox(e.margin),e.hidden&&r.hide()},Properties:"parent,title,text,width,height,disabled,active,name,value",Methods:"renderHtml,refresh",parseBox:function(e){var t,n=10;if(e)return"number"==typeof e?(e=e||0,{top:e,left:e,bottom:e,right:e}):(e=e.split(" "),t=e.length,1===t?e[1]=e[2]=e[3]=e[0]:2===t?(e[2]=e[0],e[3]=e[1]):3===t&&(e[3]=e[1]),{top:parseInt(e[0],n)||0,right:parseInt(e[1],n)||0,bottom:parseInt(e[2],n)||0,left:parseInt(e[3],n)||0})},borderBox:function(){return this._borderBox},paddingBox:function(){return this._paddingBox},marginBox:function(){return this._marginBox},measureBox:function(e,t){function n(t){var n=document.defaultView;return n?(t=t.replace(/[A-Z]/g,function(e){return"-"+e}),n.getComputedStyle(e,null).getPropertyValue(t)):e.currentStyle[t]}function r(e){var t=parseInt(n(e),10);return isNaN(t)?0:t}return{top:r(t+"TopWidth"),right:r(t+"RightWidth"),bottom:r(t+"BottomWidth"),left:r(t+"LeftWidth")}},initLayoutRect:function(){var e=this,n=e.settings,r,i,o=e.getEl(),a,s,l,c,u,d,f;r=e._borderBox=e._borderBox||e.measureBox(o,"border"),e._paddingBox=e._paddingBox||e.measureBox(o,"padding"),e._marginBox=e._marginBox||e.measureBox(o,"margin"),d=n.minWidth,f=n.minHeight,l=d||o.offsetWidth,c=f||o.offsetHeight,a=n.width,s=n.height,u=n.autoResize,u=u!==t?u:!a&&!s,a=a||l,s=s||c;var p=r.left+r.right,m=r.top+r.bottom,h=n.maxWidth||65535,g=n.maxHeight||65535;return e._layoutRect=i={x:n.x||0,y:n.y||0,w:a,h:s,deltaW:p,deltaH:m,contentW:a-p,contentH:s-m,innerW:a-p,innerH:s-m,startMinWidth:d||0,startMinHeight:f||0,minW:Math.min(l,h),minH:Math.min(c,g),maxW:h,maxH:g,autoResize:u,scrollW:0},e._lastLayoutRect={},i},layoutRect:function(e){var t=this,n=t._layoutRect,r,i,o,a,s,l;return n||(n=t.initLayoutRect()),e?(o=n.deltaW,a=n.deltaH,e.x!==s&&(n.x=e.x),e.y!==s&&(n.y=e.y),e.minW!==s&&(n.minW=e.minW),e.minH!==s&&(n.minH=e.minH),i=e.w,i!==s&&(i=n.minW>i?n.minW:i,i=i>n.maxW?n.maxW:i,n.w=i,n.innerW=i-o),i=e.h,i!==s&&(i=n.minH>i?n.minH:i,i=i>n.maxH?n.maxH:i,n.h=i,n.innerH=i-a),i=e.innerW,i!==s&&(i=n.minW-o>i?n.minW-o:i,i=i>n.maxW-o?n.maxW-o:i,n.innerW=i,n.w=i+o),i=e.innerH,i!==s&&(i=n.minH-a>i?n.minH-a:i,i=i>n.maxH-a?n.maxH-a:i,n.innerH=i,n.h=i+a),e.contentW!==s&&(n.contentW=e.contentW),e.contentH!==s&&(n.contentH=e.contentH),r=t._lastLayoutRect,(r.x!==n.x||r.y!==n.y||r.w!==n.w||r.h!==n.h)&&(l=c.repaintControls,l&&l.map&&!l.map[t._id]&&(l.push(t),l.map[t._id]=!0),r.x=n.x,r.y=n.y,r.w=n.w,r.h=n.h),t):n},repaint:function(){var e=this,t,n,r,i,o=0,a=0,s;t=e.getEl().style,r=e._layoutRect,s=e._lastRepaintRect||{},i=e._borderBox,o=i.left+i.right,a=i.top+i.bottom,r.x!==s.x&&(t.left=r.x+"px",s.x=r.x),r.y!==s.y&&(t.top=r.y+"px",s.y=r.y),r.w!==s.w&&(t.width=r.w-o+"px",s.w=r.w),r.h!==s.h&&(t.height=r.h-a+"px",s.h=r.h),e._hasBody&&r.innerW!==s.innerW&&(n=e.getEl("body").style,n.width=r.innerW+"px",s.innerW=r.innerW),e._hasBody&&r.innerH!==s.innerH&&(n=n||e.getEl("body").style,n.height=r.innerH+"px",s.innerH=r.innerH),e._lastRepaintRect=s,e.fire("repaint",{},!1)},on:function(e,n){function r(e){var n,r;return function(o){return n||i.parents().each(function(i){var o=i.settings.callbacks;return o&&(n=o[e])?(r=i,!1):t}),n.call(r,o)}}var i=this,a,s,l,c;if(n)for("string"==typeof n&&(n=r(n)),l=e.toLowerCase().split(" "),c=l.length;c--;)e=l[c],a=i._bindings,a||(a=i._bindings={}),s=a[e],s||(s=a[e]=[]),s.push(n),o[e]&&(i._nativeEvents?i._nativeEvents[e]=!0:i._nativeEvents={name:!0},i._rendered&&i.bindPendingEvents());return i},off:function(e,t){var n=this,r,i=n._bindings,o,a,s,l;if(i)if(e)for(s=e.toLowerCase().split(" "),r=s.length;r--;){if(e=s[r],o=i[e],!e){for(a in i)i[a].length=0;return n}if(o)if(t)for(l=o.length;l--;)o[l]===t&&o.splice(l,1);else o.length=0}else n._bindings=[];return n},fire:function(e,t,n){function r(){return!1}function i(){return!0}var o=this,a,s,l,c;if(e=e.toLowerCase(),t=t||{},t.type||(t.type=e),t.control||(t.control=o),t.preventDefault||(t.preventDefault=function(){t.isDefaultPrevented=i},t.stopPropagation=function(){t.isPropagationStopped=i},t.stopImmediatePropagation=function(){t.isImmediatePropagationStopped=i},t.isDefaultPrevented=r,t.isPropagationStopped=r,t.isImmediatePropagationStopped=r),o._bindings&&(l=o._bindings[e]))for(a=0,s=l.length;s>a&&(t.isImmediatePropagationStopped()||l[a].call(o,t)!==!1);a++);if(n!==!1)for(c=o.parent();c&&!t.isPropagationStopped();)c.fire(e,t,!1),c=c.parent();return t},parents:function(e){var t=this,n=new r;for(t=t.parent();t;t=t.parent())n.add(t);return e&&(n=n.filter(e)),n},next:function(){var e=this.parent().items();return e[e.indexOf(this)+1]},prev:function(){var e=this.parent().items();return e[e.indexOf(this)-1]},findCommonAncestor:function(e,t){for(var n;e;){for(n=t;n&&e!=n;)n=n.parent();if(e==n)break;e=e.parent()}return e},hasClass:function(e,t){var n=this._classes[t||"control"];return e=this.classPrefix+e,n&&!!n.map[e]},addClass:function(e,t){var n=this,r,i;return e=this.classPrefix+e,r=n._classes[t||"control"],r||(r=[],r.map={},n._classes[t||"control"]=r),r.map[e]||(r.map[e]=e,r.push(e),n._rendered&&(i=n.getEl(t),i&&(i.className=r.join(" ")))),n},removeClass:function(e,t){var n=this,r,i,o;if(e=this.classPrefix+e,r=n._classes[t||"control"],r&&r.map[e])for(delete r.map[e],i=r.length;i--;)r[i]===e&&r.splice(i,1);return n._rendered&&(o=n.getEl(t),o&&(o.className=r.join(" "))),n},toggleClass:function(e,t,n){var r=this;return t?r.addClass(e,n):r.removeClass(e,n),r},classes:function(e){var t=this._classes[e||"control"];return t?t.join(" "):""},getEl:function(e,t){var n,r=e?this._id+"-"+e:this._id;return n=a[r]=(t===!0?null:a[r])||i.get(r)},visible:function(e){var n=this,r;return e!==t?(n._visible!==e&&(n._rendered&&(n.getEl().style.display=e?"":"none"),n._visible=e,r=n.parent(),r&&(r._lastRect=null),n.fire(e?"show":"hide")),n):n._visible},show:function(){return this.visible(!0)},hide:function(){return this.visible(!1)},focus:function(){this.getEl().focus()},blur:function(){this.getEl().blur()},aria:function(e,n){var r=this,i=r.getEl();return n===t?r._aria[e]:(r._aria[e]=n,r._rendered&&("label"==e&&i.setAttribute("aria-labeledby",r._id),i.setAttribute("role"==e?e:"aria-"+e,n)),r)},encode:function(e,t){return t!==!1&&c.translate&&(e=c.translate(e)),(e||"").replace(/[&<>"]/g,function(e){return"&#"+e.charCodeAt(0)+";"})},before:function(e){var t=this,n=t.parent();return n&&n.insert(e,n.items().indexOf(t),!0),t},after:function(e){var t=this,n=t.parent();return n&&n.insert(e,n.items().indexOf(t)),t},remove:function(){var e=this,t=e.getEl(),n=e.parent(),r;if(e.items)for(var o=e.items().toArray(),a=o.length;a--;)o[a].remove();return n&&n.items&&(r=[],n.items().each(function(t){t!==e&&r.push(t)}),n.items().set(r),n._lastRect=null),e._eventsRoot&&e._eventsRoot==e&&i.off(t),delete c.controlIdLookup[e._id],t.parentNode&&t.parentNode.removeChild(t),e},renderBefore:function(e){var t=this;return e.parentNode.insertBefore(i.createFragment(t.renderHtml()),e),t.postRender(),t},renderTo:function(e){var t=this;return e=e||t.getContainerElm(),e.appendChild(i.createFragment(t.renderHtml())),t.postRender(),t},postRender:function(){var e=this,t=e.settings,n,r,o,a,s;for(a in t)0===a.indexOf("on")&&e.on(a.substr(2),t[a]);if(e._eventsRoot){for(o=e.parent();!s&&o;o=o.parent())s=o._eventsRoot;if(s)for(a in s._nativeEvents)e._nativeEvents[a]=!0}e.bindPendingEvents(),t.style&&(n=e.getEl(),n&&(n.setAttribute("style",t.style),n.style.cssText=t.style)),e._visible||i.css(e.getEl(),"display","none"),e.settings.border&&(r=e.borderBox(),i.css(e.getEl(),{"border-top-width":r.top,"border-right-width":r.right,"border-bottom-width":r.bottom,"border-left-width":r.left})),c.controlIdLookup[e._id]=e;for(var l in e._aria)e.aria(l,e._aria[l]);e.fire("postrender",{},!1)},scrollIntoView:function(e){function t(e,t){var n,r,i=e;for(n=r=0;i&&i!=t&&i.nodeType;)n+=i.offsetLeft||0,r+=i.offsetTop||0,i=i.offsetParent;return{x:n,y:r}}var n=this.getEl(),r=n.parentNode,i,o,a,s,l,c,u=t(n,r);i=u.x,o=u.y,a=n.offsetWidth,s=n.offsetHeight,l=r.clientWidth,c=r.clientHeight,"end"==e?(i-=l-a,o-=c-s):"center"==e&&(i-=l/2-a/2,o-=c/2-s/2),r.scrollLeft=i,r.scrollTop=o},bindPendingEvents:function(){function e(e){var t=o.getParentCtrl(e.target);t&&t.fire(e.type,e)}function t(){var e=d._lastHoverCtrl;e&&(e.fire("mouseleave",{target:e.getEl()}),e.parents().each(function(e){e.fire("mouseleave",{target:e.getEl()})}),d._lastHoverCtrl=null)}function n(e){var t=o.getParentCtrl(e.target),n=d._lastHoverCtrl,r=0,i,a,s;if(t!==n){if(d._lastHoverCtrl=t,a=t.parents().toArray().reverse(),a.push(t),n){for(s=n.parents().toArray().reverse(),s.push(n),r=0;s.length>r&&a[r]===s[r];r++);for(i=s.length-1;i>=r;i--)n=s[i],n.fire("mouseleave",{target:n.getEl()}) +}for(i=r;a.length>i;i++)t=a[i],t.fire("mouseenter",{target:t.getEl()})}}function r(e){e.preventDefault(),"mousewheel"==e.type?(e.deltaY=-1/40*e.wheelDelta,e.wheelDeltaX&&(e.deltaX=-1/40*e.wheelDeltaX)):(e.deltaX=0,e.deltaY=e.detail),e=o.fire("wheel",e)}var o=this,a,c,u,d,f,p;if(o._rendered=!0,f=o._nativeEvents){for(u=o.parents().toArray(),u.unshift(o),a=0,c=u.length;!d&&c>a;a++)d=u[a]._eventsRoot;for(d||(d=u[u.length-1]||o),o._eventsRoot=d,c=a,a=0;c>a;a++)u[a]._eventsRoot=d;for(p in f){if(!f)return!1;"wheel"!==p||l?("mouseenter"===p||"mouseleave"===p?d._hasMouseEnter||(i.on(d.getEl(),"mouseleave",t),i.on(d.getEl(),"mouseover",n),d._hasMouseEnter=1):d[p]||(i.on(d.getEl(),p,e),d[p]=!0),f[p]=!1):s?i.on(o.getEl(),"mousewheel",r):i.on(o.getEl(),"DOMMouseScroll",r)}}},reflow:function(){return this.repaint(),this}});return c}),r(V,[],function(){var e={},t;return{add:function(t,n){e[t.toLowerCase()]=n},has:function(t){return!!e[t.toLowerCase()]},create:function(n,r){var i,o,a;if(!t){a=tinymce.ui;for(o in a)e[o.toLowerCase()]=a[o];t=!0}if("string"==typeof n?(r=r||{},r.type=n):(r=n,n=r.type),n=n.toLowerCase(),i=e[n],!i)throw Error("Could not find control by type: "+n);return i=new i(r),i.type=n,i}}}),r(U,[z,F,I,V,f,W],function(e,n,r,i,o,a){var s={};return e.extend({layout:"",innerClass:"container-inner",init:function(e){var t=this;t._super(e),e=t.settings,t._items=new n,t.addClass("container"),t.addClass("container-body","body"),e.containerCls&&t.addClass(e.containerCls),t._layout=i.create((e.layout||t.layout)+"layout"),t.settings.items&&t.add(t.settings.items),t._hasBody=!0},items:function(){return this._items},find:function(e){return e=s[e]=s[e]||new r(e),e.find(this)},add:function(e){var t=this;return t.items().add(t.create(e)).parent(t),t},focus:function(){var e=this;return e.keyNav?e.keyNav.focusFirst():e._super(),e},replace:function(e,t){for(var n,r=this.items(),i=r.length;i--;)if(r[i]===e){r[i]=t;break}i>=0&&(n=t.getEl(),n&&n.parentNode.removeChild(n),n=e.getEl(),n&&n.parentNode.removeChild(n)),t.parent(this)},create:function(t){var n=this,r,a=[];return o.isArray(t)||(t=[t]),o.each(t,function(t){null!==t&&(t instanceof e||("string"==typeof t&&(t={type:t}),r=o.extend({},n.settings.defaults,t),t.type=r.type=r.type||t.type||n.settings.defaultType||(r.defaults?r.defaults.type:null),t=i.create(r)),a.push(t))}),a},renderNew:function(){var e=this;return e.items().each(function(t,n){var r,i;t.parent(e),t._rendered||(r=e.getEl("body"),i=a.createFragment(t.renderHtml()),r.hasChildNodes()&&r.childNodes.length-1>=n?r.insertBefore(i,r.childNodes[n]):r.appendChild(i),t.postRender())}),e._layout.applyClasses(e),e._lastRect=null,e},append:function(e){return this.add(e).renderNew()},prepend:function(e){var t=this;return t.items().set(t.create(e).concat(t.items().toArray())),t.renderNew()},insert:function(e,t,n){var r=this,i,o,a;return e=r.create(e),i=r.items(),n||(t+=1),t>=0&&i.length>t&&(o=i.slice(0,t).toArray(),a=i.slice(t).toArray(),i.set(o.concat(e,a))),r.renderNew()},preRender:function(){},renderHtml:function(){var e=this,t=e._layout;return e.preRender(),t.preRender(e),'
    '+'
    '+(e.settings.html||"")+t.renderHtml(e)+"
    "+"
    "},postRender:function(){var e=this,t;return e.items().exec("postRender"),e._super(),e._layout.postRender(e),e._rendered=!0,e.settings.style&&a.css(e.getEl(),e.settings.style),e.settings.border&&(t=e.borderBox(),a.css(e.getEl(),{"border-top-width":t.top,"border-right-width":t.right,"border-bottom-width":t.bottom,"border-left-width":t.left})),e},initLayoutRect:function(){var e=this,t=e._super();return e._layout.recalc(e),t},recalc:function(){var e=this,n=e._layoutRect,r=e._lastRect;return r&&r.w==n.w&&r.h==n.h?t:(e._layout.recalc(e),n=e.layoutRect(),e._lastRect={x:n.x,y:n.y,w:n.w,h:n.h},!0)},reflow:function(){var t,n;if(this.visible()){for(e.repaintControls=[],e.repaintControls.map={},n=this.recalc(),t=e.repaintControls.length;t--;)e.repaintControls[t].repaint();"flow"!==this.settings.layout&&"stack"!==this.settings.layout&&this.repaint(),e.repaintControls=[]}return this}})}),r(q,[W],function(e){function n(){var e=document,t,n,r,i,o,a,s,l,c=Math.max;return t=e.documentElement,n=e.body,r=c(t.scrollWidth,n.scrollWidth),i=c(t.clientWidth,n.clientWidth),o=c(t.offsetWidth,n.offsetWidth),a=c(t.scrollHeight,n.scrollHeight),s=c(t.clientHeight,n.clientHeight),l=c(t.offsetHeight,n.offsetHeight),{width:o>r?i:r,height:l>a?s:a}}return function(r,i){function o(){return s.getElementById(i.handle||r)}var a,s=document,l,c,u,d,f,p;i=i||{},c=function(t){var r=n(),c,m;t.preventDefault(),l=t.button,c=o(),f=t.screenX,p=t.screenY,m=window.getComputedStyle?window.getComputedStyle(c,null).getPropertyValue("cursor"):c.runtimeStyle.cursor,a=s.createElement("div"),e.css(a,{position:"absolute",top:0,left:0,width:r.width,height:r.height,zIndex:65535,opacity:1e-4,background:"red",cursor:m}),s.body.appendChild(a),e.on(s,"mousemove",d),e.on(s,"mouseup",u),i.start(t)},d=function(e){return e.button!==l?u(e):(e.deltaX=e.screenX-f,e.deltaY=e.screenY-p,e.preventDefault(),i.drag(e),t)},u=function(t){e.off(s,"mousemove",d),e.off(s,"mouseup",u),a.parentNode.removeChild(a),i.stop&&i.stop(t)},this.destroy=function(){e.off(o())},e.on(o(),"mousedown",c)}}),r($,[W,q],function(e,n){return{init:function(){var e=this;e.on("repaint",e.renderScroll)},renderScroll:function(){function r(){function n(n,s,l,c,u,d){var f,p,m,h,g,v,y,b,C;if(p=o.getEl("scroll"+n)){if(b=s.toLowerCase(),C=l.toLowerCase(),o.getEl("absend")&&e.css(o.getEl("absend"),b,o.layoutRect()[c]-1),!u)return e.css(p,"display","none"),t;e.css(p,"display","block"),f=o.getEl("body"),m=o.getEl("scroll"+n+"t"),h=f["client"+l]-2*a,h-=r&&i?p["client"+d]:0,g=f["scroll"+l],v=h/g,y={},y[b]=f["offset"+s]+a,y[C]=h,e.css(p,y),y={},y[b]=f["scroll"+s]*v,y[C]=h*v,e.css(m,y)}}var r,i,s;s=o.getEl("body"),r=s.scrollWidth>s.clientWidth,i=s.scrollHeight>s.clientHeight,n("h","Left","Width","contentW",r,"Height"),n("v","Top","Height","contentH",i,"Width")}function i(){function t(t,r,i,s,l){var c,u=o._id+"-scroll"+t,d=o.classPrefix;o.getEl().appendChild(e.createFragment('
    '+'
    '+"
    ")),o.draghelper=new n(u+"t",{start:function(){c=o.getEl("body")["scroll"+r],e.addClass(e.get(u),d+"active")},drag:function(e){var n,u,d,f,p=o.layoutRect();u=p.contentW>p.innerW,d=p.contentH>p.innerH,f=o.getEl("body")["client"+i]-2*a,f-=u&&d?o.getEl("scroll"+t)["client"+l]:0,n=f/o.getEl("body")["scroll"+i],o.getEl("body")["scroll"+r]=c+e["delta"+s]/n},stop:function(){e.removeClass(e.get(u),d+"active")}})}o.addClass("scroll"),t("v","Top","Height","Y","Width"),t("h","Left","Width","X","Height")}var o=this,a=2;o.settings.autoScroll&&(o._hasScroll||(o._hasScroll=!0,i(),o.on("wheel",function(e){var t=o.getEl("body");t.scrollLeft+=10*(e.deltaX||0),t.scrollTop+=10*e.deltaY,r()}),e.on(o.getEl("body"),"scroll",r)),r())}}}),r(j,[U,$],function(e,n){var r=e.extend({Defaults:{layout:"fit",containerCls:"panel"},Mixins:[n],fromJSON:function(e){var t=this;for(var n in e)t.find("#"+n).value(e[n]);return t},toJSON:function(){var e=this,n={};return e.find("*").each(function(e){var r=e.name(),i=e.value();r&&i!==t&&(n[r]=i)}),n},renderHtml:function(){var e=this,n=e._layout,r=e.settings.html;return e.preRender(),n.preRender(e),r===t?r='
    '+n.renderHtml(e)+"
    ":("function"==typeof r&&(r=r()),e._hasBody=!1),'
    '+(e._preBodyHtml||"")+r+"
    "}});return r}),r(G,[W],function(e){return{moveRel:function(t,n){var r=this,i,o,a,s,l,c,u,d;return o=e.getPos(t),a=o.x,s=o.y,i=r.getEl(),l=i.offsetWidth,c=i.offsetHeight,u=t.offsetWidth,d=t.offsetHeight,n=(n||"").split(""),"b"===n[0]&&(s+=d),"r"===n[1]&&(a+=u),"c"===n[0]&&(s+=Math.round(d/2)),"c"===n[1]&&(a+=Math.round(u/2)),"b"===n[3]&&(s-=c),"r"===n[4]&&(a-=l),"c"===n[3]&&(s-=Math.round(c/2)),"c"===n[4]&&(a-=Math.round(l/2)),r.moveTo(a,s),r},moveBy:function(e,t){var n=this,r=n.layoutRect();return n.moveTo(r.x+e,r.y+t),n},moveTo:function(e,t){var n=this;return n._rendered?n.layoutRect({x:e,y:t}).repaint():(n.settings.x=e,n.settings.y=t),n}}}),r(K,[W],function(e){return{resizeToContent:function(){this._layoutRect.autoResize=!0,this._lastRect=null,this.reflow()},resizeTo:function(t,n){if(1>=t||1>=n){var r=e.getWindowSize();t=1>=t?t*r.w:t,n=1>=n?n*r.h:n}return this._layoutRect.autoResize=!1,this.layoutRect({minW:t,minH:n,w:t,h:n}).reflow()},resizeBy:function(e,t){var n=this,r=n.layoutRect();return n.resizeTo(r.w+e,r.h+t)}}}),r(Y,[j,G,K,W],function(e,t,n,r){var i,o=[],a=[],s,l=e.extend({Mixins:[t,n],init:function(e){function t(){var e,t=l.zIndex||65535,n;if(a.length)for(e=0;a.length>e;e++)a[e].modal&&(t++,n=a[e]),a[e].getEl().style.zIndex=t,a[e].zIndex=t,t++;var i=document.getElementById(c.classPrefix+"modal-block");n?r.css(i,"z-index",n.zIndex-1):i&&(i.parentNode.removeChild(i),s=!1),l.currentZIndex=t}function n(e,t){for(;e;){if(e==t)return!0;e=e.parent()}}var c=this;c._super(e),c._eventsRoot=c,c.addClass("floatpanel"),e.autohide&&(i||(i=function(e){var t,r=c.getParentCtrl(e.target);for(t=o.length;t--;)(!r||!n(r,o[t])&&o[t].parent()!==r)&&o[t].hide()},r.on(document,"click",i)),o.push(c)),c.on("postrender show",function(e){if(e.control==c){var n,i=c.classPrefix;c.modal&&!s&&(n=r.createFragment('
    '),n=n.firstChild,c.getContainerElm().appendChild(n),setTimeout(function(){r.addClass(n,i+"in"),r.addClass(c.getEl(),i+"in")},0),s=!0),a.push(c),t()}}),c.on("close hide",function(e){if(e.control==c){for(var n=a.length;n--;)a[n]===c&&a.splice(n,1);t()}}),e.popover&&(c._preBodyHtml='
    ',c.addClass("popover").addClass("bottom").addClass("start"))},show:function(){var e=this,t,n=e._super();for(t=o.length;t--&&o[t]!==e;);return e.settings.autohide&&-1===t&&o.push(e),n},hide:function(){var e;for(e=o.length;e--;)o[e]===this&&o.splice(e,1);return this._super()},hideAll:function(){l.hideAll()},close:function(){var e=this;return e.fire("close"),e.remove()},remove:function(){var e=this;e._super()}});return l.hideAll=function(){for(var e=o.length;e--;)o[e].fire("cancel",{},!1),o[e].hide(),o.splice(e,1)},l}),r(X,[W],function(e){return function(n){function r(){if(!h)if(h=[],f.find)f.find("*").each(function(e){e.canFocus&&h.push(e.getEl())});else for(var e=f.getEl().getElementsByTagName("*"),t=0;e.length>t;t++)e[t].id&&e[t]&&h.push(e[t])}function i(){return document.getElementById(g)}function o(e){return e=e||i(),e&&e.getAttribute("role")}function a(e){for(var t,n=e||i();n=n.parentNode;)if(t=o(n))return t}function s(e){var n=document.getElementById(g);return n?n.getAttribute("aria-"+e):t}function l(){var t=i();if(!t||"TEXTAREA"!=t.nodeName&&"text"!=t.type)return n.onAction?n.onAction(g):e.fire(i(),"click",{keyboard:!0}),!0}function c(){var e;n.onCancel?((e=i())&&e.blur(),n.onCancel()):n.root.fire("cancel")}function u(e){var t=-1,i,o;for(r(),o=h.length;o--;)if(h[o].id===g){t=o;break}t+=e,0>t?t=h.length-1:t>=h.length&&(t=0),i=h[t],i.focus(),g=i.id,n.actOnFocus&&l()}function d(){var e,i;for(i=o(n.root.getEl()),r(),e=h.length;e--;)if("toolbar"==i&&h[e].id===g)return h[e].focus(),t;h[0].focus()}var f=n.root,p=n.enableUpDown!==!1,m=n.enableLeftRight!==!1,h=n.items,g;return f.on("keydown",function(e){var t=37,r=39,i=38,d=40,f=27,h=14,g=13,v=32,y=9,b;switch(e.keyCode){case t:m&&(n.leftAction?n.leftAction():u(-1),b=!0);break;case r:m&&("menuitem"==o()&&"menu"==a()?s("haspopup")&&l():u(1),b=!0);break;case i:p&&(u(-1),b=!0);break;case d:p&&("menuitem"==o()&&"menubar"==a()?l():"button"==o()&&s("haspopup")?l():u(1),b=!0);break;case y:b=!0,e.shiftKey?u(-1):u(1);break;case f:b=!0,c();break;case h:case g:case v:b=l()}b&&(e.stopPropagation(),e.preventDefault())}),f.on("focusin",function(e){r(),g=e.target.id}),{moveFocus:u,focusFirst:d,cancel:c}}}),r(J,[Y,j,W,X,q],function(e,n,r,i,o){var a=e.extend({modal:!0,Defaults:{border:1,layout:"flex",containerCls:"panel",role:"dialog",callbacks:{submit:function(){this.fire("submit",{data:this.toJSON()})},close:function(){this.close()}}},init:function(e){var t=this;t._super(e),t.addClass("window"),e.buttons&&(t.statusbar=new n({layout:"flex",border:"1 0 0 0",spacing:3,padding:10,align:"center",pack:"end",defaults:{type:"button"},items:e.buttons}),t.statusbar.addClass("foot"),t.statusbar.parent(t)),t.on("click",function(e){-1!=e.target.className.indexOf(t.classPrefix+"close")&&t.close()}),t.aria("label",e.title),t._fullscreen=!1},recalc:function(){var e=this,n=e.statusbar,i,o,a;return e._fullscreen&&(e.layoutRect(r.getWindowSize()),e.layoutRect().contentH=e.layoutRect().innerH),e._super(),i=e.layoutRect(),e.settings.title&&!e._fullscreen&&(o=i.headerW,o>i.minW&&(i.minW=i.w=o+(i.w-i.innerW),i.innerW=i.w-i.deltaW,a=!0)),n&&(n.layoutRect({w:e.layoutRect().innerW}).recalc(),o=n.layoutRect().minW+i.deltaW,o>i.minW&&(i.minW=i.w=o,i.innerW=i.w-i.deltaW,a=!0)),a?(e.recalc(),t):t},initLayoutRect:function(){var e=this,t=e._super(),n=0,i;e.settings.title&&!e._fullscreen&&(i=e.getEl("head"),t.headerW=i.offsetWidth,t.headerH=i.offsetHeight,n+=t.headerH),e.statusbar&&(n+=e.statusbar.layoutRect().h),t.deltaH+=n,t.minH+=n,t.h+=n;var o=r.getWindowSize();return t.x=Math.max(0,o.w/2-t.w/2),t.y=Math.max(0,o.h/2-t.h/2),t},renderHtml:function(){var e=this,n=e._layout,r=e._id,i=e.classPrefix,o=e.settings,a="",s="",l=o.html;return e.preRender(),n.preRender(e),o.title&&(a='
    '+'
    '+o.title+"
    "+''+'
    '+"
    "),o.url&&(l=''),l===t&&(l=n.renderHtml(e)),e.statusbar&&(s=e.statusbar.renderHtml()),'
    '+a+'
    '+l+"
    "+s+"
    "},fullscreen:function(e){var t=this,n=document.documentElement,i,o=t.classPrefix,a;if(e!=t._fullscreen)if(r.on(window,"resize",function(){var e;if(t._fullscreen)if(i)t._timer||(t._timer=setTimeout(function(){var e=r.getWindowSize();t.moveTo(0,0).resizeTo(e.w,e.h),t._timer=0},50));else{e=(new Date).getTime();var n=r.getWindowSize();t.moveTo(0,0).resizeTo(n.w,n.h),(new Date).getTime()-e>50&&(i=!0)}}),a=t.layoutRect(),t._fullscreen=e,e){t._initial={x:a.x,y:a.y,w:a.w,h:a.h},t._borderBox=t.parseBox("0"),t.getEl("head").style.display="none",a.deltaH-=a.headerH+2,r.addClass(n,o+"fullscreen"),r.addClass(document.body,o+"fullscreen"),t.addClass("fullscreen");var s=r.getWindowSize();t.moveTo(0,0).resizeTo(s.w,s.h)}else t._borderBox=t.parseBox(t.settings.border),t.getEl("head").style.display="",a.deltaH+=a.headerH,r.removeClass(n,o+"fullscreen"),r.removeClass(document.body,o+"fullscreen"),t.removeClass("fullscreen"),t.moveTo(t._initial.x,t._initial.y).resizeTo(t._initial.w,t._initial.h);return t.reflow()},postRender:function(){var e=this,t=[],n,r,a;setTimeout(function(){e.addClass("in")},0),e.find("*").each(function(e){e.canFocus&&(r=r||e.settings.autofocus,n=n||e,"filepicker"==e.type?(t.push(e.getEl("inp")),e.getEl("open")&&t.push(e.getEl("open").firstChild)):t.push(e.getEl()))}),e.statusbar&&e.statusbar.find("*").each(function(e){e.canFocus&&(r=r||e.settings.autofocus,n=n||e,t.push(e.getEl()))}),e.keyboardNavigation=new i({root:e,enableLeftRight:!1,enableUpDown:!1,items:t,onCancel:function(){e.close()}}),e._super(),e.statusbar&&e.statusbar.postRender(),!r&&n&&n.focus(),this.dragHelger=new o(e._id+"-dragh",{start:function(){a={x:e.layoutRect().x,y:e.layoutRect().y}},drag:function(t){e.moveTo(a.x+t.deltaX,a.y+t.deltaY)}}),e.on("submit",function(t){t.isDefaultPrevented()||e.close()})},submit:function(){return this.fire("submit",{data:this.toJSON()})},remove:function(){var e=this;e._super(),e.dragHelger.destroy(),e.statusbar&&this.statusbar.remove()}});return a}),r(Q,[J],function(e){var t=e.extend({init:function(e){e={border:1,padding:20,layout:"flex",pack:"center",align:"center",containerCls:"panel",autoScroll:!0,buttons:{type:"button",text:"Ok",action:"ok"},items:{type:"label",multiline:!0,maxWidth:500,maxHeight:200}},this._super(e)},Statics:{OK:1,OK_CANCEL:2,YES_NO:3,YES_NO_CANCEL:4,msgBox:function(n){var r,i=n.callback||function(){};switch(n.buttons){case t.OK_CANCEL:r=[{type:"button",text:"Ok",subtype:"primary",onClick:function(e){e.control.parents()[1].close(),i(!0)}},{type:"button",text:"Cancel",onClick:function(e){e.control.parents()[1].close(),i(!1)}}];break;case t.YES_NO:r=[{type:"button",text:"Ok",subtype:"primary",onClick:function(e){e.control.parents()[1].close(),i(!0)}}];break;case t.YES_NO_CANCEL:r=[{type:"button",text:"Ok",subtype:"primary",onClick:function(e){e.control.parents()[1].close()}}];break;default:r=[{type:"button",text:"Ok",subtype:"primary",onClick:function(e){e.control.parents()[1].close()}}]}return new e({padding:20,x:n.x,y:n.y,minWidth:300,minHeight:100,layout:"flex",pack:"center",align:"center",buttons:r,title:n.title,items:{type:"label",multiline:!0,maxWidth:500,maxHeight:200,text:n.text},onClose:n.onClose}).renderTo(document.body).reflow()},alert:function(e,n){return"string"==typeof e&&(e={text:e}),e.callback=n,t.msgBox(e)},confirm:function(e,n){return"string"==typeof e&&(e={text:e}),e.callback=n,e.buttons=t.OK_CANCEL,t.msgBox(e)}}});return t}),r(Z,[J,Q],function(e,t){return function(n){var r=this,i=[];r.windows=i,r.open=function(t){var r;return t.url=t.url||t.file,t.url&&(t.width=parseInt(t.width||320,10),t.height=parseInt(t.height||240,10)),t.body&&(t.items={defaults:t.defaults,type:t.bodyType||"form",items:t.body}),t.url||t.buttons||(t.buttons=[{text:"Ok",subtype:"primary",minWidth:50,onclick:function(){r.find("form")[0].submit(),r.close()}},{text:"Cancel",onclick:function(){r.close()}}]),r=new e(t),i.push(r),r.on("close",function(){for(var e=i.length;e--;)i[e]===r&&i.splice(e,1);n.focus()}),t.data&&r.on("postRender",function(){this.find("*").each(function(e){var n=e.name();n in t.data&&e.value(t.data[n])})}),r.renderTo(document.body).reflow()},r.alert=function(e,n,r){t.alert(e,function(){n.call(r||this)})},r.confirm=function(e,n,r){t.confirm(e,function(e){n.call(r||this,e)})},r.close=function(){i.length&&i[window.length-1].win.close()}}}),r(et,[S,A,b,m,h,f],function(e,n,r,i,o,a){return function(s){function l(e,t){try{s.getDoc().execCommand(e,!1,t)}catch(n){}}function c(){var e=s.getDoc().documentMode;return e?e:6}function u(e){return e.isDefaultPrevented()}function d(){function t(e){function t(){if(3==l.nodeType){if(e&&c==l.length)return!0;if(!e&&0===c)return!0}}var n,r,i,o,l,c,u;n=F.getRng();var d=[n.startContainer,n.startOffset,n.endContainer,n.endOffset];if(n.collapsed||(e=!0),l=n[(e?"start":"end")+"Container"],c=n[(e?"start":"end")+"Offset"],3==l.nodeType&&(r=I.getParent(n.startContainer,I.isBlock),e&&(r=I.getNext(r,I.isBlock)),!r||!t()&&n.collapsed||(i=I.create("em",{id:"__mceDel"}),D(a.grep(r.childNodes),function(e){i.appendChild(e)}),r.appendChild(i))),n=I.createRng(),n.setStart(d[0],d[1]),n.setEnd(d[2],d[3]),F.setRng(n),s.getDoc().execCommand(e?"ForwardDelete":"Delete",!1,null),i){for(o=F.getBookmark();u=I.get("__mceDel");)I.remove(u,!0);F.moveToBookmark(o)}}s.on("keydown",function(n){var r;r=n.keyCode==O,u(n)||!r&&n.keyCode!=P||e.modifierPressed(n)||(n.preventDefault(),t(r))}),s.addCommand("Delete",function(){t()})}function f(){function e(e){var t=I.create("body"),n=e.cloneContents();return t.appendChild(n),F.serializer.serialize(t,{format:"html"})}function t(t){var n=e(t),r=I.createRng();r.selectNode(s.getBody());var i=e(r);return n===i}s.on("keydown",function(e){var n=e.keyCode,r;if(!u(e)&&(n==O||n==P)){if(r=s.selection.isCollapsed(),r&&!I.isEmpty(s.getBody()))return;if(q&&!r)return;if(!r&&!t(s.selection.getRng()))return;e.preventDefault(),s.setContent(""),s.selection.setCursorLocation(s.getBody(),0),s.nodeChanged()}})}function p(){s.on("keydown",function(t){!u(t)&&65==t.keyCode&&e.metaKeyPressed(t)&&(t.preventDefault(),s.execCommand("SelectAll"))})}function m(){s.settings.content_editable||(I.bind(s.getDoc(),"focusin",function(){F.setRng(F.getRng())}),I.bind(s.getDoc(),"mousedown",function(e){e.target==s.getDoc().documentElement&&(s.getWin().focus(),F.setRng(F.getRng()))}))}function h(){s.on("keydown",function(e){if(!u(e)&&e.keyCode===P&&F.isCollapsed()&&0===F.getRng(!0).startOffset){var t=F.getNode(),n=t.previousSibling;n&&n.nodeName&&"hr"===n.nodeName.toLowerCase()&&(I.remove(n),e.preventDefault())}})}function g(){window.Range.prototype.getClientRects||s.on("mousedown",function(e){if(!u(e)&&"HTML"===e.target.nodeName){var t=s.getBody();t.blur(),setTimeout(function(){t.focus()},0)}})}function v(){s.on("click",function(e){e=e.target,/^(IMG|HR)$/.test(e.nodeName)&&F.getSel().setBaseAndExtent(e,0,e,1),"A"==e.nodeName&&I.hasClass(e,"mceItemAnchor")&&F.select(e),s.nodeChanged()})}function y(){function e(){var e=I.getAttribs(F.getStart().cloneNode(!1));return function(){var t=F.getStart();t!==s.getBody()&&(I.setAttrib(t,"style",null),D(e,function(e){t.setAttributeNode(e.cloneNode(!0))}))}}function n(){return!F.isCollapsed()&&I.getParent(F.getStart(),I.isBlock)!=I.getParent(F.getEnd(),I.isBlock)}s.on("keypress",function(r){var i;return u(r)||8!=r.keyCode&&46!=r.keyCode||!n()?t:(i=e(),s.getDoc().execCommand("delete",!1,null),i(),r.preventDefault(),!1)}),I.bind(s.getDoc(),"cut",function(t){var r;!u(t)&&n()&&(r=e(),setTimeout(function(){r()},0))})}function b(){var e,t;s.on("selectionchange",function(){t&&(clearTimeout(t),t=0),t=window.setTimeout(function(){var t=F.getRng();e&&n.compareRanges(t,e)||(s.nodeChanged(),e=t)},50)})}function C(){document.body.setAttribute("role","application")}function x(){s.on("keydown",function(e){if(!u(e)&&e.keyCode===P&&F.isCollapsed()&&0===F.getRng(!0).startOffset){var t=F.getNode().previousSibling;if(t&&t.nodeName&&"table"===t.nodeName.toLowerCase())return e.preventDefault(),!1}})}function w(){c()>7||(l("RespectVisibilityInDesign",!0),s.contentStyles.push(".mceHideBrInPre pre br {display: none}"),I.addClass(s.getBody(),"mceHideBrInPre"),z.addNodeFilter("pre",function(e){for(var t=e.length,n,i,o,a;t--;)for(n=e[t].getAll("br"),i=n.length;i--;)o=n[i],a=o.prev,a&&3===a.type&&"\n"!=a.value.charAt(a.value-1)?a.value+="\n":o.parent.insert(new r("#text",3),o,!0).value="\n"}),V.addNodeFilter("pre",function(e){for(var t=e.length,n,r,i,o;t--;)for(n=e[t].getAll("br"),r=n.length;r--;)i=n[r],o=i.prev,o&&3==o.type&&(o.value=o.value.replace(/\r?\n$/,""))}))}function _(){I.bind(s.getBody(),"mouseup",function(){var e,t=F.getNode();"IMG"==t.nodeName&&((e=I.getStyle(t,"width"))&&(I.setAttrib(t,"width",e.replace(/[^0-9%]+/g,"")),I.setStyle(t,"width","")),(e=I.getStyle(t,"height"))&&(I.setAttrib(t,"height",e.replace(/[^0-9%]+/g,"")),I.setStyle(t,"height","")))})}function N(){s.on("keydown",function(t){var n,r,i,o,a,l,c,d;if(n=t.keyCode==O,!u(t)&&(n||t.keyCode==P)&&!e.modifierPressed(t)&&(r=F.getRng(),i=r.startContainer,o=r.startOffset,c=r.collapsed,3==i.nodeType&&i.nodeValue.length>0&&(0===o&&!c||c&&o===(n?0:1)))){if(l=i.previousSibling,l&&"IMG"==l.nodeName)return;d=s.schema.getNonEmptyElements(),t.preventDefault(),a=I.create("br",{id:"__tmp"}),i.parentNode.insertBefore(a,i),s.getDoc().execCommand(n?"ForwardDelete":"Delete",!1,null),i=F.getRng().startContainer,l=i.previousSibling,l&&1==l.nodeType&&!I.isBlock(l)&&I.isEmpty(l)&&!d[l.nodeName.toLowerCase()]&&I.remove(l),I.remove("__tmp")}})}function k(){s.on("keydown",function(t){var n,r,i,o,a;if(!u(t)&&t.keyCode==e.BACKSPACE&&(n=F.getRng(),r=n.startContainer,i=n.startOffset,o=I.getRoot(),a=r,n.collapsed&&0===i)){for(;a&&a.parentNode&&a.parentNode.firstChild==a&&a.parentNode!=o;)a=a.parentNode;"BLOCKQUOTE"===a.tagName&&(s.formatter.toggle("blockquote",null,a),n=I.createRng(),n.setStart(r,0),n.setEnd(r,0),F.setRng(n))}})}function E(){function e(){s._refreshContentEditable(),l("StyleWithCSS",!1),l("enableInlineTableEditing",!1),W.object_resizing||l("enableObjectResizing",!1)}W.readonly||s.on("BeforeExecCommand MouseDown",e)}function S(){function e(){D(I.select("a"),function(e){var t=e.parentNode,n=I.getRoot();if(t.lastChild===e){for(;t&&!I.isBlock(t);){if(t.parentNode.lastChild!==t||t===n)return;t=t.parentNode}I.add(t,"br",{"data-mce-bogus":1})}})}s.on("SetContent ExecCommand",function(t){("setcontent"==t.type||"mceInsertLink"===t.command)&&e()})}function T(){W.forced_root_block&&s.on("init",function(){l("DefaultParagraphSeparator",W.forced_root_block)})}function R(){s.on("Undo Redo SetContent",function(e){e.initial||s.execCommand("mceRepaint")})}function A(){s.on("keydown",function(e){var t;u(e)||e.keyCode!=P||(t=s.getDoc().selection.createRange(),t&&t.item&&(e.preventDefault(),s.undoManager.beforeChange(),I.remove(t.item(0)),s.undoManager.add()))})}function B(){var e;c()>=10&&(e="",D("p div h1 h2 h3 h4 h5 h6".split(" "),function(t,n){e+=(n>0?",":"")+t+":empty"}),s.contentStyles.push(e+"{padding-right: 1px !important}"))}function L(){9>c()&&(z.addNodeFilter("noscript",function(e){for(var t=e.length,n,r;t--;)n=e[t],r=n.firstChild,r&&n.attr("data-mce-innertext",r.value)}),V.addNodeFilter("noscript",function(e){for(var t=e.length,n,o,a;t--;)n=e[t],o=e[t].firstChild,o?o.value=i.decode(o.value):(a=n.attributes.map["data-mce-innertext"],a&&(n.attr("data-mce-innertext",null),o=new r("#text",3),o.value=a,o.raw=!0,n.append(o)))}))}function H(){function e(e,t){var n=i.createTextRange();try{n.moveToPoint(e,t)}catch(r){n=null}return n}function t(t){var r;t.button?(r=e(t.x,t.y),r&&(r.compareEndPoints("StartToStart",a)>0?r.setEndPoint("StartToStart",a):r.setEndPoint("EndToEnd",a),r.select())):n()}function n(){var e=r.selection.createRange();a&&!e.item&&0===e.compareEndPoints("StartToEnd",e)&&a.select(),I.unbind(r,"mouseup",n),I.unbind(r,"mousemove",t),a=o=0}var r=I.doc,i=r.body,o,a,s;r.documentElement.unselectable=!0,I.bind(r,"mousedown contextmenu",function(i){if("HTML"===i.target.nodeName){if(o&&n(),s=r.documentElement,s.scrollHeight>s.clientHeight)return;o=1,a=e(i.x,i.y),a&&(I.bind(r,"mouseup",n),I.bind(r,"mousemove",t),I.win.focus(),a.select())}})}function M(){s.on("keyup focusin",function(t){65==t.keyCode&&e.metaKeyPressed(t)||F.normalize()})}var D=a.each,P=e.BACKSPACE,O=e.DELETE,I=s.dom,F=s.selection,W=s.settings,z=s.parser,V=s.serializer,U=o.gecko,q=o.ie,$=o.webkit;x(),k(),f(),M(),$&&(N(),d(),m(),v(),T(),o.iOS?b():p()),q&&(h(),C(),w(),_(),A(),B(),L(),H()),U&&(h(),g(),y(),E(),S(),R())}}),r(tt,[f],function(e){function t(){return!1}function n(){return!0}var r="__bindings",i=e.makeMap("focusin focusout click dblclick mousedown mouseup mousemove mouseover beforepaste paste cut copy mouseout mouseenter mouseleave keydown keypress keyup contextmenu dragend dragover draggesture dragdrop drop drag"," ");return{fire:function(e,i,o){var a=this,s,l,c,u,d;if(e=e.toLowerCase(),i=i||{},i.type=e,i.target||(i.target=a),i.preventDefault||(i.preventDefault=function(){i.isDefaultPrevented=n},i.stopPropagation=function(){i.isPropagationStopped=n},i.stopImmediatePropagation=function(){i.isImmediatePropagationStopped=n},i.isDefaultPrevented=t,i.isPropagationStopped=t,i.isImmediatePropagationStopped=t),a[r]&&(s=a[r][e]))for(l=0,c=s.length;c>l&&(s[l]=u=s[l],!i.isImmediatePropagationStopped());l++)if(u.call(a,i)===!1)return i.preventDefault(),i;if(o!==!1&&a.parent)for(d=a.parent();d&&!i.isPropagationStopped();)d.fire(e,i,!1),d=d.parent();return i},on:function(e,t){var n=this,o,a,s,l;if(t===!1&&(t=function(){return!1}),t)for(s=e.toLowerCase().split(" "),l=s.length;l--;)e=s[l],o=n[r],o||(o=n[r]={}),a=o[e],a||(a=o[e]=[],n.bindNative&&i[e]&&n.bindNative(e)),a.push(t);return n},off:function(e,t){var n=this,o,a=n[r],s,l,c,u;if(a)if(e)for(c=e.toLowerCase().split(" "),o=c.length;o--;){if(e=c[o],s=a[e],!e){for(l in a)a[e].length=0;return n}if(s){if(t)for(u=s.length;u--;)s[u]===t&&s.splice(u,1);else s.length=0;!s.length&&n.unbindNative&&i[e]&&(n.unbindNative(e),delete a[e])}}else{if(n.unbindNative)for(e in a)n.unbindNative(e);n[r]=[]}return n}}}),r(nt,[f,h],function(e,n){var r=e.each,i=e.explode,o={f9:120,f10:121,f11:122};return function(e){var a=this,s={};e.on("keyup keypress keydown",function(e){(e.altKey||e.ctrlKey||e.metaKey)&&r(s,function(r){var i=n.isMac?e.metaKey:e.ctrlKey;if(r.ctrl==i&&r.alt==e.altKey&&r.shift==e.shiftKey)return e.keyCode==r.keyCode||e.charCode&&e.charCode==r.charCode?(e.preventDefault(),"keydown"==e.type&&r.func.call(r.scope),!0):t})}),a.add=function(t,n,a,l){var c;return c=a,"string"==typeof a?a=function(){e.execCommand(c,!1,null)}:a.length&&(a=function(){e.execCommand(c[0],c[1],c[2])}),r(i(t.toLowerCase()),function(t){var c={func:a,scope:l||e,desc:e.translate(n),alt:!1,ctrl:!1,shift:!1};r(i(t,"+"),function(e){switch(e){case"alt":case"ctrl":case"shift":c[e]=!0;break;default:c.charCode=e.charCodeAt(0),c.keyCode=o[e]||e.toUpperCase().charCodeAt(0)}}),s[(c.ctrl?"ctrl":"")+","+(c.alt?"alt":"")+","+(c.shift?"shift":"")+","+c.keyCode]=c}),!0}}}),r(rt,[g,y,b,k,N,R,B,L,H,M,D,P,v,u,Z,C,w,et,h,f,tt,nt],function(e,n,r,i,o,a,s,l,c,u,d,f,p,m,h,g,v,y,b,C,x,w){function _(e,t){return!e.inline&&/^mouse|click|contextmenu/.test(t)?e.getDoc():e.getBody()}function N(e,t,r){var i=this,o,a;o=i.documentBaseUrl=r.documentBaseURL,a=r.baseURI,i.settings=t=T({id:e,theme:"modern",delta_width:0,delta_height:0,popup_css:"",plugins:"",document_base_url:o,add_form_submit_trigger:!0,submit_patch:!0,add_unload_trigger:!0,convert_urls:!0,relative_urls:!0,remove_script_host:!0,table_inline_editing:!1,object_resizing:!0,doctype:"",visual:!0,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%",apply_source_formatting:!0,directionality:"ltr",forced_root_block:"p",hidden_input:!0,padd_empty_editor:!0,render_ui:!0,indentation:"30px",inline_styles:!0,convert_fonts_to_spans:!0,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,option,optgroup,datalist",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,option,optgroup,datalist",validate:!0,entity_encoding:"named",url_converter:i.convertURL,url_converter_scope:i,ie7_compat:!0},t),n.settings=t,n.baseURL=r.baseURL,i.id=t.id=e,i.isNotDirty=!1,i.plugins={},i.documentBaseURI=new f(t.document_base_url||o,{base_uri:a}),i.baseURI=a,i.contentCSS=[],i.contentStyles=[],i.shortcuts=new w(i),i.execCommands={},i.queryStateCommands={},i.queryValueCommands={},i.suffix=r.suffix,i.editorManager=r,i.inline=t.inline,i.execCallback("setup",i)}var k=e.DOM,E=n.ThemeManager,S=n.PluginManager,T=C.extend,R=C.each,A=C.explode,B=C.inArray,L=C.trim,H=C.resolve,M=m.Event,D=b.gecko,P=b.ie,O=b.opera;return N.prototype={render:function(){function e(){var e=p.ScriptLoader;r.language&&e.add(n.editorManager.baseURL+"/langs/"+r.language+".js"),r.theme&&"function"!=typeof r.theme&&"-"!=r.theme.charAt(0)&&!E.urls[r.theme]&&E.load(r.theme,"themes/"+r.theme+"/theme"+o+".js"),C.isArray(r.plugins)&&(r.plugins=r.plugins.join(" ")),R(r.plugins.split(/[ ,]/),function(e){if(e=L(e),e&&!S.urls[e])if("-"==e.charAt(0)){e=e.substr(1,e.length);var t=S.dependencies(e);R(t,function(e){var t={prefix:"plugins/",resource:e,suffix:"/plugin"+o+".js"};e=S.createUrl(t,e),S.load(e.resource,e)})}else S.load(e,{prefix:"plugins/",resource:e,suffix:"/plugin"+o+".js"})}),e.loadQueue(function(){n.removed||n.init()})}var n=this,r=n.settings,i=n.id,o=n.suffix;if(!M.domLoaded)return k.bind(window,"ready",function(){n.render()}),t;if(n.editorManager.settings=r,n.getElement()&&b.contentEditable){r.inline?n.inline=!0:(n.orgVisibility=n.getElement().style.visibility,n.getElement().style.visibility="hidden"); +var a=n.getElement().form||k.getParent(i,"form");a&&(n.formElement=a,r.hidden_input&&!/TEXTAREA|INPUT/i.test(n.getElement().nodeName)&&k.insertAfter(k.create("input",{type:"hidden",name:i}),i),n.formEventDelegate=function(e){n.fire(e.type,e)},k.bind(a,"submit reset",n.formEventDelegate),n.on("reset",function(){n.setContent(n.startContent,{format:"raw"})}),!r.submit_patch||a.submit.nodeType||a.submit.length||a._mceOldSubmit||(a._mceOldSubmit=a.submit,a.submit=function(){return n.editorManager.triggerSave(),n.isNotDirty=1,a._mceOldSubmit(a)})),n.windowManager=new h(n),"xml"==r.encoding&&n.on("GetContent",function(e){e.save&&(e.content=k.encode(e.content))}),r.add_form_submit_trigger&&n.on("submit",function(){n.initialized&&(n.save(),n.isNotDirty=1)}),r.add_unload_trigger&&(n._beforeUnload=function(){!n.initialized||n.destroyed||n.isHidden()||n.save({format:"raw",no_events:!0})},n.editorManager.on("BeforeUnload",n._beforeUnload)),e()}},init:function(){function e(n){var r=S.get(n),i,o;i=S.urls[n]||t.documentBaseUrl.replace(/\/$/,""),n=L(n),r&&-1===B(m,n)&&(R(S.dependencies(n),function(t){e(t)}),o=new r(t,i),t.plugins[n]=o,o.init&&(o.init(t,i),m.push(n)))}var t=this,n=t.settings,r=t.getElement(),i,o,a,s,l,c,u,d,f,p,m=[];if(t.editorManager.add(t),n.aria_label=n.aria_label||k.getAttrib(r,"aria-label",t.getLang("aria.rich_text_area")),n.theme&&("function"!=typeof n.theme?(n.theme=n.theme.replace(/-/,""),l=E.get(n.theme),t.theme=new l(t,E.urls[n.theme]),t.theme.init&&t.theme.init(t,E.urls[n.theme]||t.documentBaseUrl.replace(/\/$/,""))):t.theme=n.theme),R(n.plugins.replace(/\-/g,"").split(/[ ,]/),e),t.fire("BeforeRenderUI"),n.render_ui&&t.theme&&(t.orgDisplay=r.style.display,"function"!=typeof n.theme?(i=n.width||r.style.width||r.offsetWidth,o=n.height||r.style.height||r.offsetHeight,a=n.min_height||100,f=/^[0-9\.]+(|px)$/i,f.test(""+i)&&(i=Math.max(parseInt(i,10)+(l.deltaWidth||0),100)),f.test(""+o)&&(o=Math.max(parseInt(o,10)+(l.deltaHeight||0),a)),l=t.theme.renderUI({targetNode:r,width:i,height:o,deltaWidth:n.delta_width,deltaHeight:n.delta_height}),n.content_editable||(k.setStyles(l.sizeContainer||l.editorContainer,{wi2dth:i,h2eight:o}),o=(l.iframeHeight||o)+("number"==typeof o?l.deltaHeight||0:""),a>o&&(o=a))):(l=n.theme(t,r),l.editorContainer.nodeType&&(l.editorContainer=l.editorContainer.id=l.editorContainer.id||t.id+"_parent"),l.iframeContainer.nodeType&&(l.iframeContainer=l.iframeContainer.id=l.iframeContainer.id||t.id+"_iframecontainer"),o=l.iframeHeight||r.offsetHeight),t.editorContainer=l.editorContainer),n.content_css&&R(A(n.content_css),function(e){t.contentCSS.push(t.documentBaseURI.toAbsolute(e))}),n.content_style&&t.contentStyles.push(n.content_style),n.content_editable)return r=s=l=null,t.initContentBody();for(document.domain&&location.hostname!=document.domain&&(t.editorManager.relaxedDomain=document.domain),t.iframeHTML=n.doctype+"",n.document_base_url!=t.documentBaseUrl&&(t.iframeHTML+=''),!b.caretAfter&&n.ie7_compat&&(t.iframeHTML+=''),t.iframeHTML+='',p=0;t.contentCSS.length>p;p++)t.iframeHTML+='';t.contentCSS=[],u=n.body_id||"tinymce",-1!=u.indexOf("=")&&(u=t.getParam("body_id","","hash"),u=u[t.id]||u),d=n.body_class||"",-1!=d.indexOf("=")&&(d=t.getParam("body_class","","hash"),d=d[t.id]||""),t.iframeHTML+='
    ",t.editorManager.relaxedDomain&&(P||O&&11>parseFloat(window.opera.version()))&&(c='javascript:(function(){document.open();document.domain="'+document.domain+'";'+'var ed = window.parent.tinymce.get("'+t.id+'");document.write(ed.iframeHTML);'+"document.close();ed.initContentBody();})()"),s=k.add(l.iframeContainer,"iframe",{id:t.id+"_ifr",src:c||'javascript:""',frameBorder:"0",allowTransparency:"true",title:t.editorManager.translate("Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help"),style:{width:"100%",height:o,display:"block"}}),t.contentAreaContainer=l.iframeContainer,l.editorContainer&&(k.get(l.editorContainer).style.display=t.orgDisplay),k.get(t.id).style.display="none",k.setAttrib(t.id,"aria-hidden",!0),t.editorManager.relaxedDomain&&c||t.initContentBody(),r=s=l=null},initContentBody:function(){var t=this,n=t.settings,o=k.get(t.id),f=t.getDoc(),p,m;t.getElement().style.visibility=t.orgVisibility,P&&t.editorManager.relaxedDomain||n.content_editable||(f.open(),f.write(t.iframeHTML),f.close(),t.editorManager.relaxedDomain&&(f.domain=t.editorManager.relaxedDomain)),n.content_editable&&(k.addClass(o,"mce-content-body"),o.tabIndex=-1,t.contentDocument=f=n.content_document||document,t.contentWindow=n.content_window||window,t.bodyElement=o,n.content_document=n.content_window=null,n.root_name=o.nodeName.toLowerCase()),p=t.getBody(),p.disabled=!0,n.readonly||(p.contentEditable=t.getParam("content_editable_state",!0)),p.disabled=!1,t.schema=new g(n),t.dom=new e(f,{keep_values:!0,url_converter:t.convertURL,url_converter_scope:t,hex_colors:n.force_hex_style_colors,class_filter:n.class_filter,update_styles:!0,root_element:n.content_editable?t.id:null,schema:t.schema,onSetAttrib:function(e){t.fire("SetAttrib",e)}}),t.parser=new v(n,t.schema),t.parser.addAttributeFilter("src,href,style",function(e,n){for(var r=e.length,i,o=t.dom,a,s;r--;)i=e[r],a=i.attr(n),s="data-mce-"+n,i.attributes.map[s]||("style"===n?i.attr(s,o.serializeStyle(o.parseStyle(a),i.name)):i.attr(s,t.convertURL(a,n,i.name)))}),t.parser.addNodeFilter("script",function(e){for(var t=e.length,n;t--;)n=e[t],n.attr("type","mce-"+(n.attr("type")||"text/javascript"))}),t.parser.addNodeFilter("#cdata",function(e){for(var t=e.length,n;t--;)n=e[t],n.type=8,n.name="#comment",n.value="[CDATA["+n.value+"]]"}),t.parser.addNodeFilter("p,h1,h2,h3,h4,h5,h6,div",function(e){for(var n=e.length,i,o=t.schema.getNonEmptyElements();n--;)i=e[n],i.isEmpty(o)&&(i.empty().append(new r("br",1)).shortEnded=!0)}),t.serializer=new i(n,t),t.selection=new a(t.dom,t.getWin(),t.serializer,t),t.formatter=new s(t),t.undoManager=new l(t),t.forceBlocks=new u(t),t.enterKey=new c(t),t.editorCommands=new d(t),t.fire("PreInit"),n.browser_spellcheck||n.gecko_spellcheck||(f.body.spellcheck=!1),t.fire("PostRender"),t.quirks=y(t),n.directionality&&(p.dir=n.directionality),n.nowrap&&(p.style.whiteSpace="nowrap"),n.protect&&t.on("BeforeSetContent",function(e){R(n.protect,function(t){e.content=e.content.replace(t,function(e){return""})})}),t.on("SetContent",function(){t.addVisual(t.getBody())}),n.padd_empty_editor&&t.on("PostProcess",function(e){e.content=e.content.replace(/^(]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
    [\r\n]*)$/,"")}),t.load({initial:!0,format:"html"}),t.startContent=t.getContent({format:"raw"}),t.initialized=!0,R(t._pendingNativeEvents,function(e){t.dom.bind(_(t,e),e,function(e){t.fire(e.type,e)})}),t.fire("init"),t.focus(!0),t.nodeChanged({initial:!0}),t.execCallback("init_instance_callback",t),t.contentStyles.length>0&&(m="",R(t.contentStyles,function(e){m+=e+"\r\n"}),t.dom.addStyle(m)),R(t.contentCSS,function(e){t.dom.loadCSS(e)}),n.auto_focus&&setTimeout(function(){var e=t.editorManager.get(n.auto_focus);e.selection.select(e.getBody(),1),e.selection.collapse(1),e.getBody().focus(),e.getWin().focus()},100),o=f=p=null},focus:function(e){var t,n=this,r=n.selection,i=n.settings.content_editable,o,a,s=n.getDoc(),l;e||((o=r.lastRng)&&(r.lastRng=null,r.setRng(o),n.nodeChanged()),o=r.getRng(),o.item&&(a=o.item(0)),n._refreshContentEditable(),i||n.getWin().focus(),(D||i)&&(l=n.getBody(),l.setActive?l.setActive():l.focus(),i&&r.normalize()),a&&a.ownerDocument==s&&(o=s.body.createControlRange(),o.addElement(a),o.select())),n.editorManager.activeEditor!=n&&((t=n.editorManager.activeEditor)&&t.fire("deactivate",{relatedTarget:n}),n.fire("activate",{relatedTarget:t})),n.editorManager.activeEditor=n},execCallback:function(e){var t=this,n=t.settings[e],r;if(n)return t.callbackLookup&&(r=t.callbackLookup[e])&&(n=r.func,r=r.scope),"string"==typeof n&&(r=n.replace(/\.\w+$/,""),r=r?H(r):0,n=H(n),t.callbackLookup=t.callbackLookup||{},t.callbackLookup[e]={func:n,scope:r}),n.apply(r||t,Array.prototype.slice.call(arguments,1))},translate:function(e){var t=this.settings.language||"en",n=this.editorManager.i18n;return e?n[t+"."+e]||e.replace(/\{\#([^\}]+)\}/g,function(e,r){return n[t+"."+r]||"{#"+r+"}"}):""},getLang:function(e,n){return this.editorManager.i18n[(this.settings.language||"en")+"."+e]||(n!==t?n:"{#"+e+"}")},getParam:function(e,t,n){var r=e in this.settings?this.settings[e]:t,i;return"hash"===n?(i={},"string"==typeof r?R(r.indexOf("=")>0?r.split(/[;,](?![^=;,]*(?:[;,]|$))/):r.split(","),function(e){e=e.split("="),i[L(e[0])]=e.length>1?L(e[1]):L(e)}):i=r,i):r},nodeChanged:function(){var e=this,n=e.selection,r,i,o;e.initialized&&!e.settings.disable_nodechange&&(o=e.getBody(),r=n.getStart()||o,r=P&&r.ownerDocument!=e.getDoc()?e.getBody():r,"IMG"==r.nodeName&&n.isCollapsed()&&(r=r.parentNode),i=[],e.dom.getParent(r,function(e){return e===o?!0:(i.push(e),t)}),e.fire("NodeChange",{element:r,parents:i}))},addButton:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),n.buttons=n.buttons||{},t.tooltip=t.tooltip||t.title,t.icon=t.icon||(t.icon!==!1?e:!1),n.buttons[e]=t},addMenuItem:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),n.menuItems=n.menuItems||{},n.menuItems[e]=t},addCommand:function(e,t,n){this.execCommands[e]={func:t,scope:n||this}},addQueryStateHandler:function(e,t,n){this.queryStateCommands[e]={func:t,scope:n||this}},addQueryValueHandler:function(e,t,n){this.queryValueCommands[e]={func:t,scope:n||this}},addShortcut:function(e,t,n,r){this.shortcuts.add(e,t,n,r)},execCommand:function(e,n,r,i){var o=this,a=0,s;return/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(e)||i&&i.skip_focus||o.focus(),i=T({},i),o.fire("BeforeExecCommand",{command:e,ui:n,value:r}),i.terminate?!1:(s=o.execCommands[e])&&s.func.call(s.scope,n,r)!==!0?(o.fire("ExecCommand",{command:e,ui:n,value:r}),!0):(R(o.plugins,function(i){return i.execCommand&&i.execCommand(e,n,r)?(o.fire("ExecCommand",{command:e,ui:n,value:r}),a=!0,!1):t}),a?a:o.theme&&o.theme.execCommand&&o.theme.execCommand(e,n,r)?(o.fire("ExecCommand",{command:e,ui:n,value:r}),!0):o.editorCommands.execCommand(e,n,r)?(o.fire("ExecCommand",{command:e,ui:n,value:r}),!0):(o.getDoc().execCommand(e,n,r),o.fire("ExecCommand",{command:e,ui:n,value:r}),t))},queryCommandState:function(e){var t=this,n,r;if(!t._isHidden()){if((n=t.queryStateCommands[e])&&(r=n.func.call(n.scope),r!==!0))return r;if(r=t.editorCommands.queryCommandState(e),-1!==r)return r;try{return t.getDoc().queryCommandState(e)}catch(i){}}},queryCommandValue:function(e){var n=this,r,i;if(!n._isHidden()){if((r=n.queryValueCommands[e])&&(i=r.func.call(r.scope),i!==!0))return i;if(i=n.editorCommands.queryCommandValue(e),i!==t)return i;try{return n.getDoc().queryCommandValue(e)}catch(o){}}},show:function(){var e=this;k.show(e.getContainer()),k.hide(e.id),e.load(),e.fire("show")},hide:function(){var e=this,t=e.getDoc();P&&t&&t.execCommand("SelectAll"),e.save(),k.hide(e.getContainer()),k.setStyle(e.id,"display",e.orgDisplay),e.fire("hide")},isHidden:function(){return!k.isHidden(this.id)},setProgressState:function(e,t){this.fire("ProgressState",{state:e,time:t})},load:function(e){var n=this,r=n.getElement(),i;return r?(e=e||{},e.load=!0,i=n.setContent(r.value!==t?r.value:r.innerHTML,e),e.element=r,e.no_events||n.fire("LoadContent",e),e.element=r=null,i):t},save:function(e){var n=this,r=n.getElement(),i,o;if(r&&n.initialized)return e=e||{},e.save=!0,e.element=r,i=e.content=n.getContent(e),e.no_events||n.fire("SaveContent",e),i=e.content,/TEXTAREA|INPUT/i.test(r.nodeName)?r.value=i:(r.innerHTML=i,(o=k.getParent(n.id,"form"))&&R(o.elements,function(e){return e.name==n.id?(e.value=i,!1):t})),e.element=r=null,i},setContent:function(e,n){var r=this,i=r.getBody(),a;return n=n||{},n.format=n.format||"html",n.set=!0,n.content=e,n.no_events||r.fire("BeforeSetContent",n),e=n.content,P||0!==e.length&&!/^\s+$/.test(e)?("raw"!==n.format&&(e=new o({},r.schema).serialize(r.parser.parse(e,{isRootContent:!0}))),n.content=L(e),r.dom.setHTML(i,n.content),n.no_events||r.fire("SetContent",n),r.settings.content_editable&&document.activeElement!==r.getBody()||r.selection.normalize(),n.content):(a=r.settings.forced_root_block,e=a&&r.schema.isValidChild(i.nodeName.toLowerCase(),a.toLowerCase())?"<"+a+'>
    ":'
    ',i.innerHTML=e,r.selection.select(i,!0),r.selection.collapse(!0),t)},getContent:function(e){var t=this,n,r=t.getBody();return e=e||{},e.format=e.format||"html",e.get=!0,e.getInner=!0,e.no_events||t.fire("BeforeGetContent",e),n="raw"==e.format?r.innerHTML:"text"==e.format?r.innerText||r.textContent:t.serializer.serialize(r,e),e.content="text"!=e.format?L(n):n,e.no_events||t.fire("GetContent",e),e.content},insertContent:function(e){this.execCommand("mceInsertContent",!1,e)},isDirty:function(){return!this.isNotDirty&&this.undoManager.hasUndo()},getContainer:function(){var e=this;return e.container||(e.container=k.get(e.editorContainer||e.id+"_parent")),e.container},getContentAreaContainer:function(){return this.contentAreaContainer},getElement:function(){return k.get(this.settings.content_element||this.id)},getWin:function(){var e=this,t;return e.contentWindow||(t=k.get(e.id+"_ifr"),t&&(e.contentWindow=t.contentWindow)),e.contentWindow},getDoc:function(){var e=this,t;return e.contentDocument||(t=e.getWin(),t&&(e.contentDocument=t.document)),e.contentDocument},getBody:function(){return this.bodyElement||this.getDoc().body},convertURL:function(e,t,n){var r=this,i=r.settings;return i.urlconverter_callback?r.execCallback("urlconverter_callback",e,n,!0,t):!i.convert_urls||n&&"LINK"==n.nodeName||0===e.indexOf("file:")||0===e.length?e:i.relative_urls?r.documentBaseURI.toRelative(e):e=r.documentBaseURI.toAbsolute(e,i.remove_script_host)},addVisual:function(e){var n=this,r=n.settings,i=n.dom,o;e=e||n.getBody(),n.hasVisual===t&&(n.hasVisual=r.visual),R(i.select("table,a",e),function(e){var a;switch(e.nodeName){case"TABLE":return o=r.visual_table_class||"mce-item-table",a=i.getAttrib(e,"border"),a&&"0"!=a||(n.hasVisual?i.addClass(e,o):i.removeClass(e,o)),t;case"A":return i.getAttrib(e,"href",!1)||(a=i.getAttrib(e,"name")||e.id,o="mce-item-anchor",a&&(n.hasVisual?i.addClass(e,o):i.removeClass(e,o))),t}}),n.fire("VisualAid",{element:e,hasVisual:n.hasVisual})},remove:function(){var e=this,t=e.getContainer(),n=e.getDoc();e.removed||(e.removed=1,P&&n&&n.execCommand("SelectAll"),e.save(),k.setStyle(e.id,"display",e.orgDisplay),e.settings.content_editable||(M.unbind(e.getWin()),M.unbind(e.getDoc())),M.unbind(e.getBody()),M.unbind(t),e.fire("remove"),e.editorManager.remove(e),k.remove(t))},bindNative:function(e){var t=this;t.initialized?t.dom.bind(_(t,e),e,function(n){t.fire(e,n)}):t._pendingNativeEvents?t._pendingNativeEvents.push(e):t._pendingNativeEvents=[e]},unbindNative:function(e){var t=this;t.initialized&&t.dom.unbind(e)},destroy:function(e){var t=this,n;t.destroyed||(D&&(M.unbind(t.getDoc()),M.unbind(t.getWin()),M.unbind(t.getBody())),e||(t.editorManager.off(t._beforeUnload),t.theme&&t.theme.destroy&&t.theme.destroy(),t.selection.destroy(),t.dom.destroy()),n=t.formElement,n&&(n.submit=n._mceOldSubmit,n._mceOldSubmit=null,k.unbind(n,"submit reset",t.formEventDelegate)),t.contentAreaContainer=t.formElement=t.container=null,t.settings.content_element=t.bodyElement=t.contentDocument=t.contentWindow=null,t.selection&&(t.selection=t.selection.win=t.selection.dom=t.selection.dom.doc=null),t.destroyed=1)},_refreshContentEditable:function(){var e=this,t,n;e._isHidden()&&(t=e.getBody(),n=t.parentNode,n.removeChild(t),n.appendChild(t),t.focus())},_isHidden:function(){var e;return D?(e=this.selection.getSel(),!e||!e.rangeCount||0===e.rangeCount):0}},T(N.prototype,x),N}),r(it,[rt,g,P,h,f,tt],function(e,n,r,i,o,a){var s=n.DOM,l=o.explode,c=o.each,u=o.extend,d=0,f,p={majorVersion:"4",minorVersion:"0b1",releaseDate:"2013-04-11",editors:[],i18n:{},activeEditor:null,setup:function(){var e=this,t,n,i="",o;if(n=document.location.href.replace(/[\?#].*$/,"").replace(/[\/\\][^\/]+$/,""),/[\/\\]$/.test(n)||(n+="/"),o=window.tinymce||window.tinyMCEPreInit)t=o.base||o.baseURL,i=o.suffix;else for(var a=document.getElementsByTagName("script"),s=0;a.length>s;s++){var l=a[s].src;if(/tinymce(\.jquery|)(\.min|\.dev|).js/.test(l)){-1!=l.indexOf(".min")&&(i=".min"),t=l.substring(0,l.lastIndexOf("/"));break}}e.baseURL=new r(n).toAbsolute(t),e.documentBaseURL=n,e.baseURI=new r(e.baseURL),e.suffix=i},init:function(t){function n(e){var t=e.id;return t||(t=e.name,t=t&&!s.get(t)?e.name:s.uniqueId(),e.setAttribute("id",t)),t}function r(e,t,n){var r=e[t];if(r)return r.apply(n||this,Array.prototype.slice.call(arguments,2))}function i(e,t){return t.constructor===RegExp?t.test(e.className):s.hasClass(e,t)}var o=this,a=[],f;o.settings=t,s.bind(window,"ready",function(){var p,m;switch(r(t,"onpageload"),t.mode){case"exact":p=t.elements||"",p.length>0&&c(l(p),function(n){s.get(n)?(f=new e(n,t,o),a.push(f),f.render(!0)):c(document.forms,function(r){c(r.elements,function(r){r.name===n&&(n="mce_editor_"+d++,s.setAttrib(r,"id",n),f=new e(n,t,o),a.push(f),f.render(1))})})});break;case"textareas":case"specific_textareas":c(s.select("textarea"),function(r){t.editor_deselector&&i(r,t.editor_deselector)||(!t.editor_selector||i(r,t.editor_selector))&&(f=new e(n(r),t,o),a.push(f),f.render(!0))});break;default:t.types?c(t.types,function(r){c(s.select(r.selector),function(i){var s=new e(n(i),u({},t,r),o);a.push(s),s.render(1)})}):t.selector&&c(s.select(t.selector),function(r){var i=new e(n(r),t,o);a.push(i),i.render(1)})}t.oninit&&(p=m=0,c(a,function(e){m++,e.initialized?p++:e.on("init",function(){p++,p==m&&r(t,"oninit")}),p==m&&r(t,"oninit")}))})},get:function(e){return e===t?this.editors:this.editors[e]},add:function(e){var t=this,n=t.editors;return n[e.id]=e,n.push(e),t.activeEditor=e,t.fire("AddEditor",{editor:e}),f||(f=function(){t.fire("BeforeUnload")},s.bind(window,"beforeunload",f)),e},createEditor:function(t){return this.add(new e(t))},remove:function(e){var t=this,n,r=t.editors;if(!r[e.id])return null;for(delete r[e.id],n=0;r.length>n;n++)if(r[n]==e){r.splice(n,1);break}return t.activeEditor==e&&(t.activeEditor=r[0]),e.destroy(),t.fire("RemoveEditor",{editor:e}),r.length||s.unbind(window,"beforeunload",f),e},execCommand:function(t,n,r){var i=this,o=i.get(r);switch(t){case"mceAddEditor":return i.get(r)||new e(r,i.settings,i).render(),!0;case"mceRemoveEditor":return o&&o.remove(),!0;case"mceToggleEditor":return o?(o.isHidden()?o.show():o.hide(),!0):(i.execCommand("mceAddEditor",0,r),!0)}return i.activeEditor?i.activeEditor.execCommand(t,n,r):!1},triggerSave:function(){c(this.editors,function(e){e.save()})},addI18n:function(e,t){u(this.i18n,t||e)},translate:function(e){return"string"!=typeof e?(this.i18n[e[0]]||e[0]).replace(/%d/,e[1]):this.i18n[e]||e}};return p.setup(),window.tinymce=window.tinyMCE=p,u(p,a),p}),r(ot,[it,f],function(e,t){var n=t.each,r=t.explode;e.on("AddEditor",function(e){var t=e.editor;t.on("preInit",function(){function e(e,t){n(t,function(t,n){t&&s.setStyle(e,n,t)}),s.rename(e,"span")}function i(e){s=t.dom,l.convert_fonts_to_spans&&n(s.select("font,u,strike",e.node),function(e){o[e.nodeName.toLowerCase()](s,e)})}var o,a,s,l=t.settings;l.inline_styles&&(a=r(l.font_size_legacy_values),o={font:function(t,n){e(n,{backgroundColor:n.style.backgroundColor,color:n.color,fontFamily:n.face,fontSize:a[parseInt(n.size,10)-1]})},u:function(t,n){e(n,{textDecoration:"underline"})},strike:function(t,n){e(n,{textDecoration:"line-through"})}},t.on("PreProcess SetContent",i))})})}),r(at,[],function(){return{send:function(e){function t(){!e.async||4==n.readyState||r++>1e4?(e.success&&1e4>r&&200==n.status?e.success.call(e.success_scope,""+n.responseText,n,e):e.error&&e.error.call(e.error_scope,r>1e4?"TIMED_OUT":"GENERAL",n,e),n=null):setTimeout(t,10)}var n,r=0;if(e.scope=e.scope||this,e.success_scope=e.success_scope||e.scope,e.error_scope=e.error_scope||e.scope,e.async=e.async===!1?!1:!0,e.data=e.data||"",n=new XMLHttpRequest){if(n.overrideMimeType&&n.overrideMimeType(e.content_type),n.open(e.type||(e.data?"POST":"GET"),e.url,e.async),e.content_type&&n.setRequestHeader("Content-Type",e.content_type),n.setRequestHeader("X-Requested-With","XMLHttpRequest"),n.send(e.data),!e.async)return t();setTimeout(t,10)}}}}),r(st,[],function(){function e(t,n){var r,i,o,a;if(n=n||'"',null===t)return"null";if(o=typeof t,"string"==o)return i="\bb t\nn\ff\rr\"\"''\\\\",n+t.replace(/([\u0080-\uFFFF\x00-\x1f\"\'\\])/g,function(e,t){return'"'===n&&"'"===e?e:(r=i.indexOf(t),r+1?"\\"+i.charAt(r+1):(e=t.charCodeAt().toString(16),"\\u"+"0000".substring(e.length)+e))})+n;if("object"==o){if(t.hasOwnProperty&&"[object Array]"===Object.prototype.toString.call(t)){for(r=0,i="[";t.length>r;r++)i+=(r>0?",":"")+e(t[r],n);return i+"]"}i="{";for(a in t)t.hasOwnProperty(a)&&(i+="function"!=typeof t[a]?(i.length>1?","+n:n)+a+n+":"+e(t[a],n):"");return i+"}"}return""+t}return{serialize:e,parse:function(e){try{return window[String.fromCharCode(101)+"val"]("("+e+")")}catch(t){}}}}),r(lt,[st,at,f],function(e,n,r){function i(e){this.settings=o({},e),this.count=0}var o=r.extend;return i.sendRPC=function(e){return(new i).send(e)},i.prototype={send:function(r){var i=r.error,a=r.success;r=o(this.settings,r),r.success=function(n,o){n=e.parse(n),n===t&&(n={error:"JSON Parse error."}),n.error?i.call(r.error_scope||r.scope,n.error,o):a.call(r.success_scope||r.scope,n.result)},r.error=function(e,t){i&&i.call(r.error_scope||r.scope,e,t)},r.data=e.serialize({id:r.id||"c"+this.count++,method:r.method,params:r.params}),r.content_type="application/json",n.send(r)}},i}),r(ct,[g],function(e){return{callbacks:{},count:0,send:function(n){var r=this,i=e.DOM,o=n.count!==t?n.count:r.count,a="tinymce_jsonp_"+o;r.callbacks[o]=function(e){i.remove(a),delete r.callbacks[o],n.callback(e)},i.add(i.doc.body,"script",{id:a,src:n.url,type:"text/javascript"}),r.count++}}}),r(ut,[],function(){function e(){s=[];for(var e in a)s.push(e);i.length=s.length}function n(){function n(e){var n,r;return r=e!==t?c+e:i.indexOf(",",c),-1===r||r>i.length?null:(n=i.substring(c,r),c=r+1,n)}var r,i,s,c=0;a={},o.load(l),i=o.getAttribute(l)||"";do r=n(parseInt(n(),32)||0),null!==r&&(s=n(parseInt(n(),32)||0),a[r]=s);while(null!==r);e()}function r(){var t,n="";for(var r in a)t=a[r],n+=(n?",":"")+r.length.toString(32)+","+r+","+t.length.toString(32)+","+t;o.setAttribute(l,n),o.save(l),e()}var i,o,a,s,l;return window.localStorage?localStorage:(l="tinymce",o=document.documentElement,o.addBehavior("#default#userData"),i={key:function(e){return s[e]},getItem:function(e){return e in a?a[e]:null},setItem:function(e,t){a[e]=""+t,r()},removeItem:function(e){delete a[e],r()},clear:function(){a={},r()}},n(),i)}),r(dt,[g,u,v,y,f,h],function(e,t,n,r,i,o){var a=window.tinymce;return a.DOM=e.DOM,a.ScriptLoader=n.ScriptLoader,a.PluginManager=r.PluginManager,a.ThemeManager=r.ThemeManager,a.dom=a.dom||{},a.dom.Event=t.Event,i.each(i,function(e,t){a[t]=e}),i.each("isOpera isWebKit isIE isGecko isMac".split(" "),function(e){a[e]=o[e.substr(2).toLowerCase()]}),{}}),r(ft,[O,f],function(e,t){return e.extend({Defaults:{firstControlClass:"first",lastControlClass:"last"},init:function(e){this.settings=t.extend({},this.Defaults,e)},preRender:function(e){e.addClass(this.settings.containerClass,"body")},applyClasses:function(e){var t=this,n=t.settings,r,i,o;r=e.items().filter(":visible"),i=n.firstControlClass,o=n.lastControlClass,r.each(function(e){e.removeClass(i).removeClass(o),n.controlClass&&e.addClass(n.controlClass)}),r.eq(0).addClass(i),r.eq(-1).addClass(o)},renderHtml:function(e){var t=this,n=t.settings,r,i="";return r=e.items(),r.eq(0).addClass(n.firstControlClass),r.eq(-1).addClass(n.lastControlClass),r.each(function(e){n.controlClass&&e.addClass(n.controlClass),i+=e.renderHtml()}),i},recalc:function(){},postRender:function(){}})}),r(pt,[ft],function(e){return e.extend({Defaults:{containerClass:"abs-layout",controlClass:"abs-layout-item"},recalc:function(e){e.items().filter(":visible").each(function(e){var t=e.settings;e.layoutRect({x:t.x,y:t.y,w:t.w,h:t.h}),e.recalc&&e.recalc()})},renderHtml:function(e){return'
    '+this._super(e)}})}),r(mt,[z,G],function(e,n){return e.extend({Mixins:[n],Defaults:{classes:"widget tooltip tooltip-n"},text:function(e){var n=this;return e!==t?(n._value=e,n._rendered&&(n.getEl().lastChild.innerHTML=n.encode(e)),n):n._value},renderHtml:function(){var e=this,t=e.classPrefix;return'"},repaint:function(){var e=this,t,n;t=e.getEl().style,n=e._layoutRect,t.left=n.x+"px",t.top=n.y+"px",t.zIndex=131070}})}),r(ht,[z,mt],function(e,t){var n;return e.extend({init:function(e){var t=this;t._super(e),t.canFocus=!0,e.tooltip&&t.on("mouseenter mouseleave",function(n){n.control==t&&"mouseenter"==n.type?t.tooltip().moveTo(-65535).text(e.tooltip).show().moveRel(t.getEl(),"bc tc"):t.tooltip().moveTo(-65535).hide()}),t.aria("label",e.tooltip)},tooltip:function(){var e=this;return n||(n=new t({type:"tooltip"}),n.renderTo(e.getContainerElm())),n},active:function(e){var t=this,n;return e!==n&&(t.aria("pressed",e),t.toggleClass("active",e)),t._super(e)},disabled:function(e){var t=this,n;return e!==n&&(t.aria("disabled",e),t.toggleClass("disabled",e)),t._super(e)},postRender:function(){var e=this,t=e.settings;e._rendered=!0,e._super(),e.parent()||!t.width&&!t.height||(e.initLayoutRect(),e.repaint()),t.autofocus&&e.focus()},remove:function(){this._super(),n&&(n.remove(),n=null)}})}),r(gt,[ht],function(e){return e.extend({Defaults:{classes:"widget btn",role:"button"},init:function(e){var t=this,n;t.on("click mousedown",function(e){e.preventDefault()}),t._super(e),n=e.size,e.subtype&&t.addClass(e.subtype),n&&t.addClass("btn-"+n)},repaint:function(){var e=this.getEl().firstChild.style;e.width=e.height="100%",this._super()},renderHtml:function(){var e=this,t=e._id,n=e.classPrefix,r=e.settings.icon?n+"ico "+n+"i-"+e.settings.icon:"",i=e.settings.image?" style=\"background-image: url('"+e.settings.image+"')\"":"";return'
    '+'"+"
    "}})}),r(vt,[U],function(e){return e.extend({Defaults:{defaultType:"button",role:"toolbar"},renderHtml:function(){var e=this,t=e._layout;return e.addClass("btn-group"),e.preRender(),t.preRender(e),'
    '+'
    '+(e.settings.html||"")+t.renderHtml(e)+"
    "+"
    "}})}),r(yt,[ht],function(e){return e.extend({Defaults:{classes:"checkbox",role:"checkbox",checked:!1},init:function(e){var t=this;t._super(e),t.on("click mousedown",function(e){e.preventDefault()}),t.on("click",function(e){e.preventDefault(),t.disabled()||t.checked(!t.checked())}),t.checked(t.settings.checked)},checked:function(e){var n=this;return e!==t?(e?n.addClass("checked"):n.removeClass("checked"),n._checked=e,n.aria("checked",e),n):n._checked},value:function(e){return this.checked(e)},renderHtml:function(){var e=this,t=e._id,n=e.classPrefix;return'
    '+''+''+e._text+""+"
    "}})}),r(bt,[U],function(e){return e.extend({})}),r(Ct,[gt,Y,X],function(e,t,n){function r(){var e,t=[],n;for(n=["000000","Black","993300","Burnt orange","333300","Dark olive","003300","Dark green","003366","Dark azure","000080","Navy Blue","333399","Indigo","333333","Very dark gray","800000","Maroon","FF6600","Orange","808000","Olive","008000","Green","008080","Teal","0000FF","Blue","666699","Grayish blue","808080","Gray","FF0000","Red","FF9900","Amber","99CC00","Yellow green","339966","Sea green","33CCCC","Turquoise","3366FF","Royal blue","800080","Purple","999999","Medium gray","FF00FF","Magenta","FFCC00","Gold","FFFF00","Yellow","00FF00","Lime","00FFFF","Aqua","00CCFF","Sky blue","993366","Brown","C0C0C0","Silver","FF99CC","Pink","FFCC99","Peach","FFFF99","Light yellow","CCFFCC","Pale green","CCFFFF","Pale cyan","99CCFF","Light sky blue","CC99FF","Plum","FFFFFF","White"],e=0;n.length>e;e+=2)t.push({text:n[e+1],color:n[e]});return t}return e.extend({init:function(e){var t=this;t._super(e),t.addClass("colorbutton"),t.on("click",function(e){e.control==t&&t.showPicker()}),t.hasPopup=!0},showPicker:function(){var e=this,i="",o,a,s,l=e.classPrefix,c;if(!e.picker){for(c=r(),i='',o=Math.ceil(Math.sqrt(c.length)),s=0;5>s;s++){for(i+="",a=0;8>a;a++){var u=c[8*s+a];i+='"}i+=""}i+="",e.picker=new t({popover:!0,autohide:!0,html:i,border:1,classes:"colorpicker"}).parent(e).renderTo(e.getContainerElm()),e.picker._hasBody=!1,e.picker.reflow(),e.picker.parent(e),e.picker.on("cancel",function(t){t.control===e.menu&&e.focus()}),e.picker.on("click",function(t){var n;(n=t.target.getAttribute("data-mce-color"))&&(e.picker.hide(),n="#"+n,e.showPreview(n),e.fire("select",{value:n}))}),e.keyboardNavigation=new n({root:e.picker,items:e.picker.getEl().getElementsByTagName("div"),onCancel:function(){e.picker.hide(),e.fire("cancel")}})}e.picker.show(),e.picker.moveRel(e.getEl(),"bc-tl"),e.keyboardNavigation.focusFirst()},showPreview:function(e){this.getEl("preview").style.backgroundColor=e},renderHtml:function(){var e=this,t=e._id,n=e.classPrefix,r=e.settings.icon?n+"ico "+n+"i-"+e.settings.icon:"",i=e.settings.image?" style=\"background-image: url('"+e.settings.image+"')\"":"";return'
    '+'"+"
    "}})}),r(xt,[ht,W],function(e,n){return e.extend({init:function(e){var r=this;r._super(e),r.addClass("combobox"),r.on("click",function(e){for(var t=e.target;t;)t.id&&-1!=t.id.indexOf("-open")&&r.fire("action"),t=t.parentNode}),r.on("keydown",function(e){"INPUT"==e.target.nodeName&&13==e.keyCode&&r.parents().reverse().each(function(n){return e.preventDefault(),r.fire("change"),n.submit?(n.submit(),!1):t})}),e.placeholder&&(r.addClass("placeholder"),r.on("focusin",function(){r._hasOnChange||(n.on(r.getEl("inp"),"change",function(){r.fire("change")}),r._hasOnChange=!0),r.hasClass("placeholder")&&(r.getEl("inp").value="",r.removeClass("placeholder"))}),r.on("focusout",function(){0===r.value().length&&(r.getEl("inp").value=e.placeholder,r.addClass("placeholder"))}))},value:function(e){var n=this;return e!==t?(n._value=e,n.removeClass("placeholder"),n._rendered&&(n.getEl("inp").value=e),n):n._rendered?(e=n.getEl("inp").value,e!=n.settings.placeholder?e:""):n._value},repaint:function(){var e=this,t=e.getEl(),r=e.getEl("open"),i=e.layoutRect();return r?n.css(t.firstChild,{width:i.w-r.offsetWidth-10}):n.css(t.firstChild,{width:i.w-10}),e._super(),e},disabled:function(e){var t=this; +t._super(e),t._rendered&&(t.getEl().disabled=e)},focus:function(){this.getEl("inp").focus()},postRender:function(){var e=this;return n.on(this.getEl("inp"),"change",function(){e.fire("change")}),e._super()},renderHtml:function(){var e=this,t=e._id,n=e.settings,r=e.classPrefix,i=n.value||n.placeholder||"",o,a,s="";return o=n.icon?r+"ico "+r+"i-"+n.icon:"",a=e._text,(o||a)&&(s='
    '+'"+"
    ",e.addClass("has-open")),'
    '+''+s+"
    "}})}),r(wt,[z,X],function(e,n){return e.extend({Defaults:{delimiter:"\u00bb"},init:function(e){var t=this;t._super(e),t.addClass("path"),t.canFocus=!0,t.on("click",function(e){var n,r=e.target;(n=r.getAttribute("data-index"))&&t.fire("select",{value:t.data()[n],index:n})})},focus:function(){var e=this;return e.keyNav=new n({root:e,enableLeftRight:!0}),e.keyNav.focusFirst(),e},data:function(e){var n=this;return e!==t?(n._data=e,n.update(),n):n._data},update:function(){var e=this,t=e._data,n,r,i="",o=e.classPrefix;for(n=0,r=t.length;r>n;n++)i+=(n>0?'":"")+'
    '+t[n].name+"
    ";e.getEl().innerHTML=i},postRender:function(){var e=this;e._super(),e.data(e.settings.data)},repa2int:function(){var e=this;return e.getEl("text").style.lineHeight=e.layoutRect().h+"px",e._super()},renderHtml:function(){var e=this,t=e.classPrefix;return'
    '+'
     
    '+"
    "}})}),r(_t,[wt,it],function(e,t){return e.extend({postRender:function(){function e(e){return 1===e.nodeType&&("BR"==e.nodeName||!!e.getAttribute("data-mce-bogus"))}var n=this,r=t.activeEditor;return n.on("select",function(t){for(var n=[],i=r.selection.getNode(),o=r.getBody();i&&(e(i)||n.push(i),i=i.parentNode,i!=o););r.focus(),r.selection.select(n[n.length-1-t.index]),r.nodeChanged()}),r.on("nodeChange",function(t){for(var i=[],o=t.parents,a=o.length;a--;)if(!e(o[a])){var s=r.fire("ResolveName",{name:o[a].nodeName.toLowerCase(),target:o[a]});i.push({name:s.name})}n.data(i)}),n._super()}})}),r(Nt,[U],function(e){return e.extend({Defaults:{layout:"flex",align:"center",defaults:{flex:1}},renderHtml:function(){var e=this,t=e._layout,n=e.classPrefix;return e.addClass("formitem"),t.preRender(e),'
    '+(e.settings.title?'
    '+e.settings.title+"
    ":"")+'
    '+(e.settings.html||"")+t.renderHtml(e)+"
    "+"
    "}})}),r(kt,[U,Nt],function(e,n){return e.extend({Defaults:{containerCls:"form",layout:"flex",direction:"column",align:"stretch",flex:1,padding:20,labelGap:30,spacing:10},preRender:function(){var e=this,r=e.items();r.each(function(r){var i,o=r.settings.label;o&&(i=new n({layout:"flex",autoResize:"overflow",defaults:{flex:1},items:[{type:"label",text:o,flex:0,forId:r._id}]}),i.type="formitem",r.settings.flex===t&&(r.settings.flex=1),e.replace(r,i),i.add(r))})},recalcLabels:function(){var e=this,t=0,n=[],r,i;if(e.settings.labelGapCalc!==!1)for(e.items().filter("formitem").each(function(e){var r=e.items()[0],i=r.getEl().clientWidth;t=i>t?i:t,n.push(r)}),i=e.settings.labelGap||0,r=n.length;r--;)n[r].settings.minWidth=t+i},visible:function(e){var t=this._super(e);return e===!0&&this._rendered&&this.recalcLabels(),t},fromJSON:function(e){var t=this;if(e)for(var n in e)t.find("#"+n).value(e[n]);return t},toJSON:function(){var e=this,n={};return e.find("*").each(function(e){var r=e.name(),i=e.value();r&&i!==t&&(n[r]=i)}),n},submit:function(){return this.fire("submit",{data:this.toJSON()})},postRender:function(){var e=this;e._super(),e.recalcLabels(),e.fromJSON(e.settings.data)}})}),r(Et,[kt],function(e){return e.extend({Defaults:{containerCls:"fieldset",layout:"flex",direction:"column",align:"stretch",flex:1,padding:"25 15 5 15",labelGap:30,spacing:10,border:1},renderHtml:function(){var e=this,t=e._layout,n=e.classPrefix;return e.preRender(),t.preRender(e),'
    '+(e.settings.title?''+e.settings.title+"":"")+'
    '+(e.settings.html||"")+t.renderHtml(e)+"
    "+"
    "}})}),r(St,[xt],function(e){return e.extend({init:function(e){var t=this,n=tinymce.activeEditor,r;e.spellcheck=!1,r=n.settings.file_browser_callback,r&&(e.icon="browse",e.onaction=function(){r(t.getEl("inp").id,t.getEl("inp").value,e.filetype,window)}),t._super(e)}})}),r(Tt,[pt],function(e){return e.extend({recalc:function(e){var t=e.layoutRect(),n=e.paddingBox();e.items().filter(":visible").each(function(e){e.layoutRect({x:n.left,y:n.top,w:t.innerW-n.right-n.left,h:t.innerH-n.top-n.bottom}),e.recalc&&e.recalc()})}})}),r(Rt,[pt],function(e){return e.extend({recalc:function(e){var t,n,r,i,o,a,s,l,c,u,d,f,p,m,h,g,v=[],y,b,C,x,w,_,N,k,E,S,T,R,A,B,L,H,M,D,P,O,I,F,W,z,V=Math.max,U=Math.min;for(r=e.items().filter(":visible"),i=e.layoutRect(),o=e._paddingBox,a=e.settings,f=a.direction,s=a.align,l=a.pack,c=a.spacing||0,("row-reversed"==f||"column-reverse"==f)&&(r=r.set(r.toArray().reverse()),f=f.split("-")[0]),"column"==f?(E="y",N="h",k="minH",S="maxH",R="innerH",T="top",A="bottom",B="deltaH",L="contentH",I="left",D="w",H="x",M="innerW",P="minW",O="maxW",F="right",W="deltaW",z="contentW"):(E="x",N="w",k="minW",S="maxW",R="innerW",T="left",A="right",B="deltaW",L="contentW",I="top",D="h",H="y",M="innerH",P="minH",O="maxH",F="bottom",W="deltaH",z="contentH"),d=i[R]-o[T]-o[T],_=u=0,t=0,n=r.length;n>t;t++)p=r[t],m=p.layoutRect(),h=p.settings,g=h.flex,d-=n-1>t?c:0,g>0&&(u+=g,m[S]&&v.push(p),m.flex=g),d-=m[k],y=o[I]+m[P]+o[F],y>_&&(_=y);if(x={},x[k]=0>d?i[k]-d+i[B]:i[R]-d+i[B],x[P]=_+i[W],x[L]=i[R]-d,x[z]=_,x.minW=U(x.minW,i.maxW),x.minH=U(x.minH,i.maxH),x.minW=V(x.minW,i.startMinWidth),x.minH=V(x.minH,i.startMinHeight),!i.autoResize||x.minW==i.minW&&x.minH==i.minH){for(C=d/u,t=0,n=v.length;n>t;t++)p=v[t],m=p.layoutRect(),b=m[S],y=m[k]+Math.ceil(m.flex*C),y>b?(d-=m[S]-m[k],u-=m.flex,m.flex=0,m.maxFlexSize=b):m.maxFlexSize=0;for(C=d/u,w=o[T],x={},0===u&&("end"==l?w=d+o[T]:"center"==l?(w=Math.round(i[R]/2-(i[R]-d)/2)+o[T],0>w&&(w=o[T])):"justify"==l&&(w=o[T],c=Math.floor(d/(r.length-1)))),x[H]=o[I],t=0,n=r.length;n>t;t++)p=r[t],m=p.layoutRect(),y=m.maxFlexSize||m[k],"center"===s?x[H]=Math.round(i[M]/2-m[D]/2):"stretch"===s?(x[D]=V(m[P]||0,i[M]-o[I]-o[F]),x[H]=o[I]):"end"===s&&(x[H]=i[M]-m[D]-o.top),m.flex>0&&(y+=Math.ceil(m.flex*C)),x[N]=y,x[E]=w,p.layoutRect(x),p.recalc&&p.recalc(),w+=y+c}else if(x.w=x.minW,x.h=x.minH,e.layoutRect(x),this.recalc(e),null===e._lastRect){var q=e.parent();q&&(q._lastRect=null,q.recalc())}}})}),r(At,[ft],function(e){return e.extend({Defaults:{containerClass:"flow-layout",controlClass:"flow-layout-item",endClass:"break"},recalc:function(e){e.items().filter(":visible").each(function(e){e.recalc&&e.recalc()})}})}),r(Bt,[V,z,Y,f,it],function(e,n,r,i,o){function a(e,n){function r(e){return e.replace(/%(\w+)/g,"")}var i,o,a=e.dom,s="",c,u;return u=e.settings.preview_styles,u===!1?"":(u||(u="font-family font-size font-weight text-decoration text-transform color background-color border border-radius"),(n=e.formatter.get(n))?(n=n[0],i=n.block||n.inline||"span",o=a.create(i),l(n.styles,function(e,t){e=r(e),e&&a.setStyle(o,t,e)}),l(n.attributes,function(e,t){e=r(e),e&&a.setAttrib(o,t,e)}),l(n.classes,function(e){e=r(e),a.hasClass(o,e)||a.addClass(o,e)}),e.fire("PreviewFormats"),a.setStyles(o,{position:"absolute",left:-65535}),e.getBody().appendChild(o),c=a.getStyle(e.getBody(),"fontSize",!0),c=/px$/.test(c)?parseInt(c,10):0,l(u.split(" "),function(t){var n=a.getStyle(o,t,!0);if(!("background-color"==t&&/transparent|rgba\s*\([^)]+,\s*0\)/.test(n)&&(n=a.getStyle(e.getBody(),t,!0),"#ffffff"==a.toHex(n).toLowerCase())||"color"==t&&"#000000"==a.toHex(n).toLowerCase())){if("font-size"==t&&/em|%$/.test(n)){if(0===c)return;n=parseFloat(n,10)/(/%$/.test(n)?100:1),n=n*c+"px"}"border"==t&&n&&(s+="padding:0 2px;"),s+=t+":"+n+";"}}),e.fire("AfterPreviewFormats"),a.remove(o),s):t)}function s(e){e=e.split(";");for(var t=e.length;t--;)e[t]=e[t].split("=");return e}var l=i.each;n.translate=function(e){return o.translate(e)},o.on("AddEditor",function(t){function n(){function e(r){var i=[];if(r)return l(r,function(r){var o={text:r.title,icon:r.icon};if(r.items)o.menu=e(r.items);else{var s=r.format||"custom"+t++;r.format||(r.name=s,n.push(r)),o.textStyle=function(){return a(h,s)},o.onclick=function(){h.execCommand("mceToggleFormat",!1,s)}}i.push(o)}),i}var t=0,n=[],r=[{title:"Headers",items:[{title:"Header 1",format:"h1"},{title:"Header 2",format:"h2"},{title:"Header 3",format:"h3"},{title:"Header 4",format:"h4"},{title:"Header 5",format:"h5"},{title:"Header 6",format:"h6"}]},{title:"Inline",items:[{title:"Bold",icon:"bold",format:"bold"},{title:"Italic",icon:"italic",format:"italic"},{title:"Underline",icon:"underline",format:"underline"},{title:"Strikethrough",icon:"strikethrough",format:"strikethrough"},{title:"Superscript",icon:"superscript",format:"superscript"},{title:"Subscript",icon:"subscript",format:"subscript"},{title:"Code",icon:"code",format:"code"}]},{title:"Blocks",items:[{title:"Paragraph",format:"p"},{title:"Blockquote",format:"blockquote"},{title:"Div",format:"div"},{title:"Pre",format:"pre"}]},{title:"Alignment",items:[{title:"Left",icon:"alignleft",format:"alignleft"},{title:"Center",icon:"aligncenter",format:"aligncenter"},{title:"Right",icon:"alignright",format:"alignright"},{title:"Justify",icon:"alignjustify",format:"alignjustify"}]}];h.on("init",function(){l(n,function(e){h.formatter.register(e.name,e)})});var i=e(h.settings.style_formats||r);return i}function c(){return h.undoManager?h.undoManager.hasUndo():!1}function u(){return h.undoManager?h.undoManager.hasRedo():!1}function d(){var e=this;e.disabled(!c()),h.on("Undo Redo AddUndo",function(){e.disabled(!c())})}function f(){var e=this;e.disabled(!u()),h.on("Undo Redo AddUndo",function(){e.disabled(!u())})}function p(){var e=this;h.on("VisualAid",function(t){e.active(t.hasVisual)}),e.active(h.hasVisual)}function m(e){e.control.settings.format&&o.activeEditor.execCommand("mceToggleFormat",!1,e.control.settings.format)}var h=t.editor,g;g=n(),l({bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",subscript:"Subscript",superscript:"Superscript"},function(e,t){h.addButton(t,{tooltip:e,onPostRender:function(){var e=this;h.formatter?h.formatter.formatChanged(t,function(t){e.active(t)}):h.on("init",function(){h.formatter.formatChanged(t,function(t){e.active(t)})})},onclick:function(){h.execCommand("mceToggleFormat",!1,t)}})}),l({outdent:["Decrease indent","Outdent"],indent:["Increase indent","Indent"],cut:["Cut","Cut"],copy:["Copy","Copy"],paste:["Paste","Paste"],help:["Help","mceHelp"],selectall:["Select all","SelectAll"],hr:["Insert horizontal rule","InsertHorizontalRule"],removeformat:["Clear formatting","RemoveFormat"],visualaid:["Visual aids","mceToggleVisualAid"],newdocument:["New document","mceNewDocument"]},function(e,t){h.addButton(t,{tooltip:e[0],cmd:e[1]})}),l({blockquote:["Toggle blockquote","mceBlockQuote"],numlist:["Numbered list","InsertOrderedList"],bullist:["Bulleted list","InsertUnorderedList"],subscript:["Subscript","Subscript"],superscript:["Superscript","Superscript"],alignleft:["Align left","JustifyLeft"],aligncenter:["Align center","JustifyCenter"],alignright:["Align right","JustifyRight"],alignjustify:["Justify","JustifyFull"]},function(e,t){h.addButton(t,{tooltip:e[0],cmd:e[1],onPostRender:function(){var e=this;h.formatter?h.formatter.formatChanged(t,function(t){e.active(t)}):h.on("init",function(){h.formatter.formatChanged(t,function(t){e.active(t)})})}})}),h.addButton("forecolor",{type:"colorbutton",tooltip:"Text color",onselect:function(e){h.execCommand("ForeColor",!1,e.value)}}),h.addButton("backcolor",{type:"colorbutton",tooltip:"Background color",onselect:function(e){h.execCommand("HiliteColor",!1,e.value)}}),h.addButton("undo",{tooltip:"Undo",onPostRender:d,cmd:"undo"}),h.addButton("redo",{tooltip:"Redo",onPostRender:f,cmd:"redo"}),h.addMenuItem("newdocument",{text:"New document",shortcut:"Ctrl+N",icon:"newdocument",cmd:"mceNewDocument"}),h.addMenuItem("undo",{text:"Undo",icon:"undo",shortcut:"Ctrl+Z",onPostRender:d,cmd:"undo"}),h.addMenuItem("redo",{text:"Redo",icon:"redo",shortcut:"Ctrl+Y",onPostRender:f,cmd:"redo"}),h.addMenuItem("visualaid",{text:"Visual aids",selectable:!0,onPostRender:p,cmd:"mceToggleVisualAid"}),l({cut:["Cut","Cut","Ctrl+X"],copy:["Copy","Copy","Ctrl+C"],paste:["Paste","Paste","Ctrl+V"],selectall:["Select all","SelectAll","Ctrl+A"],bold:["Bold","Bold","Ctrl+B"],italic:["Italic","Italic","Ctrl+I"],underline:["Underline","Underline"],strikethrough:["Strikethrough","Strikethrough"],subscript:["Subscript","Subscript"],superscript:["Superscript","Superscript"],removeformat:["Clear formatting","RemoveFormat"]},function(e,t){h.addMenuItem(t,{text:e[0],icon:t,shortcut:e[2],cmd:e[1]})}),h.on("mousedown",function(){r.hideAll()}),e.add("styleselect",function(t){var n=[].concat(g);return e.create("menubutton",i.extend({text:"Formats",menu:n},t))}),e.add("formatselect",function(t){var n=[],r=s("Paragraph=p;Address=address;Pre=pre;Header 1=h1;Header 2=h2;Header 3=h3;Header 4=h4;Header 5=h5;Header 6=h6");return l(r,function(e){n.push({text:e[0],format:e[1],textStyle:function(){return a(h,e[1])}})}),e.create("listbox",i.extend({text:r[0][0],menu:n,onclick:m},t))}),e.add("fontselect",function(t){var n=[],r=s("Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats");return l(r,function(e){n.push({text:e[0],format:e[1],style:-1==e[1].indexOf("dings")?"font-family:"+e[1]:""})}),e.create("listbox",i.extend({text:"Font Family",menu:n,onclick:function(e){e.control.settings.format&&o.activeEditor.execCommand("FontName",!1,e.control.settings.format)}},t))}),e.add("fontsizeselect",function(t){var n=[];return l("8pt 10pt 12pt 14pt 18pt 24pt 36pt".split(" "),function(e){n.push({text:e,format:e})}),e.create("listbox",i.extend({text:"Font Sizes",menu:n,onclick:function(e){e.control.settings.format&&o.activeEditor.execCommand("FontSize",!1,e.control.settings.format)}},t))}),h.addMenuItem("formats",{text:"Formats",menu:g})})}),r(Lt,[pt],function(e){return e.extend({recalc:function(e){var t=e.settings,n,r,i,o,a,s,l,c,u,d,f,p,m,h,g,v,y,b,C,x,w,_,N=[],k=[],E,S,T,R,A,B;for(t=e.settings,i=e.items().filter(":visible"),o=e.layoutRect(),r=t.columns||Math.ceil(Math.sqrt(i.length)),n=Math.ceil(i.length/r),y=t.spacingH||t.spacing||0,b=t.spacingV||t.spacing||0,C=t.alignH||t.align,x=t.alignV||t.align,g=e._paddingBox,d=0;r>d;d++)N.push(0);for(f=0;n>f;f++)k.push(0);for(f=0;n>f;f++)for(d=0;r>d&&(u=i[f*r+d],u);d++)c=u.layoutRect(),E=c.minW,S=c.minH,N[d]=E>N[d]?E:N[d],k[f]=S>k[f]?S:k[f];for(A=o.innerW-g.left-g.right,w=0,d=0;r>d;d++)w+=N[d]+(d>0?y:0),A-=(d>0?y:0)+N[d];for(B=o.innerH-g.top-g.bottom,_=0,f=0;n>f;f++)_+=k[f]+(f>0?b:0),B-=(f>0?b:0)+k[f];if(w+=g.left+g.right,_+=g.top+g.bottom,l={},l.minW=w+(o.w-o.innerW),l.minH=_+(o.h-o.innerH),l.contentW=l.minW-o.deltaW,l.contentH=l.minH-o.deltaH,l.minW=Math.min(l.minW,o.maxW),l.minH=Math.min(l.minH,o.maxH),l.minW=Math.max(l.minW,o.startMinWidth),l.minH=Math.max(l.minH,o.startMinHeight),!o.autoResize||l.minW==o.minW&&l.minH==o.minH){o.autoResize&&(l=e.layoutRect(l),l.contentW=l.minW-o.deltaW,l.contentH=l.minH-o.deltaH);var L;L="start"==t.packV?0:B>0?Math.floor(B/n):0;var H=0,M=t.flexWidths;if(M)for(d=0;M.length>d;d++)H+=M[d];else H=r;var D=A/H;for(d=0;r>d;d++)N[d]+=M?Math.ceil(M[d]*D):D;for(m=g.top,f=0;n>f;f++){for(p=g.left,s=k[f]+L,d=0;r>d&&(u=i[f*r+d],u);d++)h=u.settings,c=u.layoutRect(),a=N[d],T=R=0,c.x=p,c.y=m,v=h.alignH||C,"center"==v?c.x=p+a/2-c.w/2:"right"==v?c.x=p+a-c.w:"stretch"==v&&(c.w=a),v=h.alignV||x,"center"==v?c.y=m+s/2-c.h/2:"bottom"==v?c.y=m+s-c.h:"stretch"==v&&(c.h=s),u.layoutRect(c),p+=a+y,u.recalc&&u.recalc();m+=s+b}}else if(l.w=l.minW,l.h=l.minH,e.layoutRect(l),this.recalc(e),null===e._lastRect){var P=e.parent();P&&(P._lastRect=null,P.recalc())}}})}),r(Ht,[ht],function(e){return e.extend({renderHtml:function(){var e=this;return e.addClass("iframe"),e.canFocus=!1,''},src:function(e){this.getEl().src=e},html:function(e){return this.getEl().contentWindow.document.body.innerHTML=e,this}})}),r(Mt,[ht],function(e){return e.extend({init:function(e){var t=this;t._super(e),t.addClass("widget"),t.addClass("label"),e.multiline&&t.addClass("autoscroll"),e.strong&&t.addClass("strong")},initLayoutRect:function(){var e=this,t=e._super();return e.settings.multiline&&(e.getEl().offsetWidth>t.maxW&&(t.minW=t.maxW,e.addClass("multiline")),e.getEl().style.width=t.minW+"px",t.startMinH=t.h=t.minH=Math.min(t.maxH,e.getEl().offsetHeight)),t},disabled:function(e){var t=this,n;return e!==n&&(t.toggleClass("label-disabled",e),t._rendered&&(t.getEl()[0].className=t.classes())),t._super(e)},repaint:function(){var e=this;return e.settings.multiline||(e.getEl().style.lineHeight=e.layoutRect().h+"px"),e._super()},text:function(e){var t=this;return t._rendered&&e&&(t.getEl().innerHTML=t.encode(e)),t._super(e)},renderHtml:function(){var e=this,t=e.settings.forId;return'"}})}),r(Dt,[U,X],function(e,t){return e.extend({Defaults:{role:"toolbar",layout:"flow"},init:function(e){var t=this;t._super(e),t.addClass("toolbar")},postRender:function(){var e=this;return e.items().addClass("toolbar-item"),e.keyNav=new t({root:e,enableLeftRight:!0}),e._super()}})}),r(Pt,[Dt],function(e){return e.extend({Defaults:{role:"menubar",containerCls:"menubar",defaults:{type:"menubutton"}}})}),r(Ot,[gt,V,Pt],function(e,t,n){function r(e,t){for(;e;){if(t===e)return!0;e=e.parentNode}return!1}var i=e.extend({init:function(e){var t=this;t._renderOpen=!0,t._super(e),t.addClass("menubtn"),t.aria("haspopup",!0),t.hasPopup=!0},showMenu:function(){var e=this,n=e.settings,r;e.menu||(r=n.menu||[],r.length?r={type:"menu",items:r}:r.type=r.type||"menu",e.menu=t.create(r).parent(e).renderTo(e.getContainerElm()),e.fire("createmenu"),e.menu.reflow(),e.menu.on("cancel",function(t){t.control===e.menu&&e.focus()}),e.menu.on("show hide",function(t){t.control==e.menu&&e.activeMenu("show"==t.type)}).fire("show"),e.aria("expanded",!0)),e.menu.show(),e.menu.layoutRect({w:e.layoutRect().w}),e.menu.moveRel(e.getEl(),"bl-tl")},hideMenu:function(){var e=this;e.menu&&(e.menu.items().each(function(e){e.hideMenu&&e.hideMenu()}),e.menu.hide(),e.aria("expanded",!1))},activeMenu:function(e){this.toggleClass("active",e)},renderHtml:function(){var e=this,t=e._id,r=e.classPrefix,i=e.settings.icon?r+"ico "+r+"i-"+e.settings.icon:"";return e.aria("role",e.parent()instanceof n?"menuitem":"button"),'
    '+'"+"
    "},postRender:function(){var e=this;return e.on("click",function(t){t.control===e&&r(t.target,e.getEl())&&(e.showMenu(),t.keyboard&&e.menu.items()[0].focus())}),e.on("mouseenter",function(t){var n=t.control,r=e.parent(),o;n&&r&&n instanceof i&&n.parent()==r&&(r.items().filter("MenuButton").each(function(e){e.hideMenu&&e!=n&&(e.menu&&e.menu.visible()&&(o=!0),e.hideMenu())}),o&&n.showMenu())}),e._super()},text:function(e){var t=this,n,r;if(t._rendered)for(r=t.getEl("open").childNodes,n=0;r.length>n;n++)3==r[n].nodeType&&(r[n].data=e);return this._super(e)},remove:function(){this._super(),this.menu&&this.menu.remove()}});return i}),r(It,[Ot],function(e){return e.extend({init:function(e){var t=this,n,r,i,o;if(t._values=n=e.values,n){for(r=0;n.length>r;r++)i=n[r].selected||e.value===n[r].value,i&&(o=o||n[r].text,t._value=n[r].value);e.menu=n}e.text=e.text||o||n[0].text,t._super(e),t.addClass("listbox"),t.on("select",function(n){e.multiple?n.control.active(!n.control.active()):t.value(n.control.settings.value)})},value:function(e){var n=this,r,i,o,a;if(e!==t){if(n.menu)n.menu.items().each(function(t){r=t.value()===e,r&&(i=i||t.text()),t.active(r)});else for(o=n.settings.menu,a=0;o.length>a;a++)r=o[a].value==e,r&&(i=i||o[a].text),o[a].active=r;n.text(i)}return n._super(e)}})}),r(Ft,[ht,V],function(e,t){return e.extend({Defaults:{border:0,role:"menuitem"},init:function(e){var t=this;t.hasPopup=!0,t._super(e),e=t.settings,t.addClass("menu-item"),e.menu&&t.addClass("menu-item-expand"),("-"===t._text||"|"===t._text)&&(t.addClass("menu-item-sep"),t.aria("role","separator"),t.canFocus=!1,t._text="-"),e.selectable&&(t.aria("role","menuitemcheckbox"),t.aria("checked",!0),t.addClass("menu-item-checkbox"),e.icon="selected"),t.on("mousedown",function(e){e.preventDefault()}),t.on("mouseenter click",function(n){n.control===t&&(e.menu||"click"!==n.type?(t.showMenu(),n.keyboard&&setTimeout(function(){t.menu.items()[0].focus()},0)):(t.parent().hideAll(),t.fire("cancel"),t.fire("select")))}),e.menu&&t.aria("haspopup",!0)},hasMenus:function(){return!!this.settings.menu},showMenu:function(){var e=this,n=e.settings,r;e.parent().items().each(function(t){t!==e&&t.hideMenu()}),n.menu&&(e.menu?e.menu.show():(r=n.menu,r.length?r={type:"menu",items:r}:r.type=r.type||"menu",e.menu=t.create(r).parent(e).renderTo(e.getContainerElm()),e.menu.reflow(),e.menu.fire("show"),e.menu.on("cancel",function(){e.focus()}),e.menu.on("hide",function(t){t.control===e.menu&&e.removeClass("selected")})),e.menu._parentMenu=e.parent(),e.menu.addClass("menu-sub"),e.menu.moveRel(e.getEl(),"tr-tl"),e.addClass("selected"),e.aria("expanded",!0))},hideMenu:function(){var e=this;return e.menu&&(e.menu.items().each(function(e){e.hideMenu&&e.hideMenu()}),e.menu.hide(),e.aria("expanded",!1)),e},renderHtml:function(){var e=this,t=e._id,n=e.settings,r=e.classPrefix,i=e.encode(e._text),o=e.settings.icon;return o&&e.parent().addClass("menu-has-icons"),o=r+"ico "+r+"i-"+(e.settings.icon||"none"),'
    '+("-"!==i?' ':"")+("-"!==i?''+i+"":"")+(n.shortcut?'
    '+n.shortcut+"
    ":"")+(n.menu?'
    ':"")+"
    "},postRender:function(){var e=this,t=e.settings,n=t.textStyle;if("function"==typeof n&&(n=n()),n){var r=e.getEl("text");r&&r.setAttribute("style",n)}return e._super()},remove:function(){this._super(),this.menu&&this.menu.remove()}})}),r(Wt,[Y,X,Ft],function(e,n,r){var i=e.extend({Defaults:{defaultType:"menuitem",border:1,layout:"stack",role:"menu"},init:function(e){var t=this;e.autohide=!0,t._super(e),t.addClass("menu"),t.keyNav=new n({root:t,enableUpDown:!0,enableLeftRight:!0,leftAction:function(){t.parent()instanceof r&&t.keyNav.cancel()},onCancel:function(){t.fire("cancel",{},!1),t.hide()}})},repaint:function(){return this.toggleClass("menu-align",!0),this._super(),this.getEl().style.height="",this.getEl("body").style.height="",this},cancel:function(){var e=this;e.hideAll(),e.fire("cancel"),e.fire("select")},hideAll:function(){var e=this;return this.find("menuitem").exec("hideMenu"),e._super()},preRender:function(){var e=this;return e.items().each(function(n){var r=n.settings;return r.icon||r.selectable?(e._hasIcons=!0,!1):t}),e._super()}});return i}),r(zt,[gt,Y],function(e,t){var n=e.extend({showPanel:function(){var e=this,n=e.settings;n.panel.popover=!0,e.active(!0),e.panel?e.panel.show():e.panel=new t(n.panel).on("hide",function(){e.active(!1)}).parent(e).renderTo(e.getContainerElm()).reflow().moveRel(e.getEl(),n.popoverAlign||"bc-tc")},hidePanel:function(){var e=this;e.panel&&e.panel.hide()},postRender:function(){var e=this;return e.on("click",function(t){t.control===e&&e.showPanel()}),e._super()}});return n}),r(Vt,[ht],function(e){return e.extend({Defaults:{classes:"radio",checked:!1},init:function(e){var t=this;t._super(e),t.on("click",function(e){e.preventDefault(),t.disabled()||t.checked()||(t.parent().items().filter("radio:checked").exec("checked",!1),t.checked(!0))}),t.checked(e.checked)},checked:function(e){var n=this;return e!==t?(e?n.addClass("checked"):n.removeClass("checked"),n._checked=e,n):n._checked},renderHtml:function(){var e=this,t=e._id,n=e.classPrefix;return'"}})}),r(Ut,[U],function(e){return e.extend({})}),r(qt,[ht,q,W],function(e,t,n){return e.extend({renderHtml:function(){var e=this,t=e.classPrefix;return e.addClass("resizehandle"),e.settings.both&&e.addClass("resizehandle-both"),e.canFocus=!1,'
    '},postRender:function(){function e(e){return{width:e.clientWidth,height:e.clientHeight}}function r(t,r){var o,s,l,c,u=a.settings;o=a.getContainer(),s=a.getContentAreaContainer().firstChild,l=e(o),c=e(s),t=Math.max(u.min_width||100,t),r=Math.max(u.min_height||100,r),t=Math.min(u.max_width||65535,t),r=Math.min(u.max_height||65535,r),i.settings.both&&n.css(o,"width",t+(l.width-c.width)),n.css(o,"height",r+(l.height-c.height)),i.settings.both&&n.css(s,"width",t),n.css(s,"height",r),a.fire("ResizeEditor")}var i=this,o,a=i.settings.editor;i._super(),i.resizeDragHelper=new t(this._id,{start:function(){o=e(a.getContentAreaContainer().firstChild)},drag:function(e){r(o.width+e.deltaX,o.height+e.deltaY)},end:function(){}})}})}),r($t,[ht],function(e){return e.extend({renderHtml:function(){var e=this;return e.addClass("spacer"),e.canFocus=!1,'
    '}})}),r(jt,[Ot,g],function(e,t){var n=t.DOM;return e.extend({Defaults:{classes:"widget btn splitbtn",role:"splitbutton"},repaint:function(){var e=this,t=e.getEl(),r=e.layoutRect(),i,o,a;return e._super(),i=t.firstChild,o=t.lastChild,n.css(i,{width:r.w-o.offsetWidth,height:r.h-2}),n.css(o,{height:r.h-2}),a=i.firstChild.style,a.width=a.height="100%",a=o.firstChild.style,a.width=a.height="100%",e},activeMenu:function(e){var t=this;n.toggleClass(t.getEl().lastChild,t.classPrefix+"active",e)},renderHtml:function(){var e=this,t=e._id,n=e.classPrefix,r=e.settings.icon?n+"ico "+n+"i-"+e.settings.icon:"";return'
    '+'"+'"+"
    "},postRender:function(){var e=this,t=e.settings.onclick;return e.on("click",function(e){e.control!=this||n.getParent(e.target,"."+this.classPrefix+"open")||(e.stopImmediatePropagation(),t.call(this,e))}),delete e.settings.onclick,e._super()}})}),r(Gt,[At],function(e){return e.extend({Defaults:{containerClass:"stack-layout",controlClass:"stack-layout-item",endClass:"break"}})}),r(Kt,[j,W],function(e,t){"use stict";return e.extend({lastIdx:0,Defaults:{layout:"absolute",defaults:{type:"panel"}},activateTab:function(e){this.activeTabId&&t.removeClass(this.getEl(this.activeTabId),this.classPrefix+"active"),this.activeTabId="t"+e,t.addClass(this.getEl("t"+e),this.classPrefix+"active"),e!=this.lastIdx&&(this.items()[this.lastIdx].hide(),this.lastIdx=e),this.items()[e].show().fire("showtab"),this.reflow()},renderHtml:function(){var e=this,t=e._layout,n="",r=e.classPrefix;return e.preRender(),t.preRender(e),e.items().each(function(t,i){n+='
    '+t.settings.title+"
    "}),'
    '+'
    '+n+"
    "+'
    '+t.renderHtml(e)+"
    "+"
    "},postRender:function(){var e=this;e._super(),e.settings.activeTab=e.settings.activeTab||0,e.activateTab(e.settings.activeTab),this.on("click",function(t){var n=t.target.parentNode;if(t.target.parentNode.id==e._id+"-head")for(var r=n.childNodes.length;r--;)n.childNodes[r]==t.target&&e.activateTab(r)})},initLayoutRect:function(){var e=this,t,n,r;n=r=0,e.items().each(function(t,i){n=Math.max(n,t.layoutRect().minW),r=Math.max(r,t.layoutRect().minH),e.settings.activeTab!=i&&t.hide()}),e.items().each(function(e){e.settings.x=0,e.settings.y=0,e.settings.w=n,e.settings.h=r,e.layoutRect({x:0,y:0,w:n,h:r})});var i=e.getEl("head").offsetHeight;return e.settings.minWidth=n,e.settings.minHeight=r+i,t=e._super(),t.deltaH+=e.getEl("head").offsetHeight,t.innerH=t.h-t.deltaH,t}})}),r(Yt,[ht,W],function(e,n){return e.extend({init:function(e){var n=this;n._super(e),n._value=e.value||"",n.addClass("textbox"),e.multiline?n.addClass("multiline"):n.on("keydown",function(e){13==e.keyCode&&n.parents().reverse().each(function(n){return e.preventDefault(),n.submit?(n.submit(),!1):t})})},value:function(e){var n=this;return e!==t?(n._value=e,n._rendered&&(n.getEl().value=e),n):n._rendered?n.getEl().value:n._value},repaint:function(){var e=this,t,n,r,i=0,o=0,a;return t=e.getEl().style,n=e._layoutRect,a=e._lastRepaintRect||{},r=e._borderBox,i=r.left+r.right+8,o=r.top+r.bottom+(e.settings.multiline?8:0),n.x!==a.x&&(t.left=n.x+"px",a.x=n.x),n.y!==a.y&&(t.top=n.y+"px",a.y=n.y),n.w!==a.w&&(t.width=n.w-i+"px",a.w=n.w),n.h!==a.h&&(t.height=n.h-o+"px",a.h=n.h),e._lastRepaintRect=a,e.fire("repaint",{},!1),e},renderHtml:function(){var e=this,t=e._id,n=e.settings,r=e.encode(e._value,!1),i="";return"spellcheck"in n&&(i+=' spellcheck="'+n.spellcheck+'"'),n.maxLength&&(i+=' maxlength="'+n.maxLength+'"'),n.size&&(i+=' size="'+n.size+'"'),n.subtype&&(i+=' type="'+n.subtype+'"'),n.multiline?'":'"},postRender:function(){var e=this;return n.on(e.getEl(),"change",function(t){e.fire("change",t)}),e._super()}})}),r(Xt,[W],function(e){return function(t){var n=this,r;n.show=function(i){return n.hide(),r=!0,window.setTimeout(function(){r&&t.appendChild(e.createFragment('
    '))},i||0),n},n.hide=function(){var e=t.lastChild;return e&&-1!=e.className.indexOf("throbber")&&e.parentNode.removeChild(e),r=!1,n}}}),a([l,c,u,d,f,p,m,h,g,v,y,b,C,x,w,_,N,k,E,S,T,R,A,B,L,H,M,D,P,O,I,F,W,z,V,U,q,$,j,G,K,Y,X,J,Q,Z,et,tt,nt,rt,it,ot,at,st,lt,ct,ut,dt,ft,pt,mt,ht,gt,vt,yt,bt,Ct,xt,wt,_t,Nt,kt,Et,St,Tt,Rt,At,Bt,Lt,Ht,Mt,Dt,Pt,Ot,It,Ft,Wt,zt,Vt,Ut,qt,$t,jt,Gt,Kt,Yt,Xt])})(this); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/tinymce.js b/lib/tinymce/jscripts/tinymce4/tinymce.js new file mode 100644 index 00000000..b388238e --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/tinymce.js @@ -0,0 +1,31217 @@ +// 4.0b1 (2013-04-11) + +/** + * Compiled inline version. (Library mode) + */ + +/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ +/*globals $code */ + +(function(exports, undefined) { + "use strict"; + + var modules = {}; + + function require(ids, callback) { + var module, defs = []; + + for (var i = 0; i < ids.length; ++i) { + module = modules[ids[i]] || resolve(ids[i]); + if (!module) { + throw 'module definition dependecy not found: ' + ids[i]; + } + + defs.push(module); + } + + callback.apply(null, defs); + } + + function define(id, dependencies, definition) { + if (typeof id !== 'string') { + throw 'invalid module definition, module id must be defined and be a string'; + } + + if (dependencies === undefined) { + throw 'invalid module definition, dependencies must be specified'; + } + + if (definition === undefined) { + throw 'invalid module definition, definition function must be specified'; + } + + require(dependencies, function() { + modules[id] = definition.apply(null, arguments); + }); + } + + function defined(id) { + return !!modules[id]; + } + + function resolve(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length; ++fi) { + if (!target[fragments[fi]]) { + return; + } + + target = target[fragments[fi]]; + } + + return target; + } + + function expose(ids) { + for (var i = 0; i < ids.length; i++) { + var target = exports; + var id = ids[i]; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length - 1; ++fi) { + if (target[fragments[fi]] === undefined) { + target[fragments[fi]] = {}; + } + + target = target[fragments[fi]]; + } + + target[fragments[fragments.length - 1]] = modules[id]; + } + } + +// Included from: js/tinymce/classes/dom/EventUtils.js + +/** + * EventUtils.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint loopfunc:true*/ + +define("tinymce/dom/EventUtils", [], function() { + "use strict"; + + var eventExpandoPrefix = "mce-data-"; + + /** + * Binds a native event to a callback on the speified target. + */ + function addEvent(target, name, callback, capture) { + if (target.addEventListener) { + target.addEventListener(name, callback, capture || false); + } else if (target.attachEvent) { + target.attachEvent('on' + name, callback); + } + } + + /** + * Unbinds a native event callback on the specified target. + */ + function removeEvent(target, name, callback, capture) { + if (target.removeEventListener) { + target.removeEventListener(name, callback, capture || false); + } else if (target.detachEvent) { + target.detachEvent('on' + name, callback); + } + } + + /** + * Normalizes a native event object or just adds the event specific methods on a custom event. + */ + function fix(originalEvent, 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 originalEvent) { + // layerX/layerY is deprecated in Chrome and produces a warning + if (name !== "layerX" && name !== "layerY") { + event[name] = originalEvent[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 (originalEvent) { + if (originalEvent.preventDefault) { + originalEvent.preventDefault(); + } else { + originalEvent.returnValue = false; // IE + } + } + }; + + // Add stopPropagation + event.stopPropagation = function() { + event.isPropagationStopped = returnTrue; + + // Execute stopPropagation on the original event object + if (originalEvent) { + if (originalEvent.stopPropagation) { + originalEvent.stopPropagation(); + } else { + originalEvent.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; + } + + /** + * Bind a DOMContentLoaded event across browsers and executes the callback once the page DOM is initialized. + * It will also set/check the domLoaded state of the event_utils instance so ready isn't called multiple times. + */ + function bindOnReady(win, callback, eventUtils) { + var doc = win.document, event = {type: 'ready'}; + + if (eventUtils.domLoaded) { + callback(event); + return; + } + + // Gets called when the DOM is ready + function readyHandler() { + if (!eventUtils.domLoaded) { + eventUtils.domLoaded = true; + callback(event); + } + } + + function waitForDomLoaded() { + if (doc.readyState === "complete") { + removeEvent(doc, "readystatechange", waitForDomLoaded); + readyHandler(); + } + } + + function tryScroll() { + 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(tryScroll, 0); + return; + } + + readyHandler(); + } + + // Use W3C method + if (doc.addEventListener) { + addEvent(win, 'DOMContentLoaded', readyHandler); + } else { + // Use IE method + addEvent(doc, "readystatechange", waitForDomLoaded); + + // Wait until we can scroll, when we can the DOM is initialized + if (doc.documentElement.doScroll && win === win.top) { + tryScroll(); + } + } + + // Fallback if any of the above methods should fail for some odd reason + addEvent(win, 'load', readyHandler); + } + + /** + * This class enables you to bind/unbind native events to elements and normalize it's behavior across browsers. + */ + function EventUtils() { + var self = this, events = {}, count, expando, hasFocusIn, hasMouseEnterLeave, mouseEnterLeave; + + expando = eventExpandoPrefix + (+new Date()).toString(32); + 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; + + /** + * Executes all event handler callbacks for a specific event. + * + * @param {Event} evt Event object. + * @param {String} id Expando id value to look for. + */ + 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; + } + } + } + } + + /** + * Binds a callback to an event on the specified target. + * + * @method bind + * @param {Object} target Target node/window or custom object. + * @param {String} names Name of the event to bind. + * @param {function} callback Callback function to execute when the event occurs. + * @param {Object} scope Scope to call the callback function on, defaults to target. + * @return {function} Callback function that got bound. + */ + 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]; + } + + // 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 && name === "ready" && target.readyState == 'complete') { + 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; + + // Check if the target has native events support + + if (name === "ready") { + bindOnReady(target, nativeHandler, self); + } else { + addEvent(target, fakeName || name, nativeHandler, capture); + } + } else { + if (name === "ready" && self.domLoaded) { + callback({type: name}); + } 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; + }; + + /** + * Unbinds the specified event by name, name and callback or all events on the target. + * + * @method unbind + * @param {Object} target Target node/window or custom object. + * @param {String} names Optional event name to unbind. + * @param {function} callback Optional callback function to unbind. + * @return {EventUtils} Event utils instance. + */ + 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, callbackList.nativeHandler, callbackList.capture); + } + } + } + } else { + // All events for a specific element + for (name in eventMap) { + callbackList = eventMap[name]; + removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, 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; + }; + + /** + * Fires the specified event on the specified target. + * + * @method fire + * @param {Object} target Target node/window or custom object. + * @param {String} name Event name to fire. + * @param {Object} args Optional arguments to send to the observers. + * @return {EventUtils} Event utils instance. + */ + self.fire = function(target, name, args) { + var id; + + // 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 + args = fix(null, args); + args.type = name; + args.target = target; + + do { + // Found an expando that means there is listeners to execute + id = target[expando]; + if (id) { + executeHandlers(args, id); + } + + // Walk up the DOM + target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow; + } while (target && !args.isPropagationStopped()); + + return self; + }; + + /** + * Removes all bound event listeners for the specified target. This will also remove any bound + * listeners to child nodes within that target. + * + * @method clean + * @param {Object} target Target node/window object. + * @return {EventUtils} Event utils instance. + */ + 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; + }; + + /** + * Destroys the event object. Call this on IE to remove memory leaks. + */ + self.destory = function() { + events = {}; + }; + + // Legacy function for canceling events + self.cancel = function(e) { + if (e) { + e.preventDefault(); + e.stopImmediatePropagation(); + } + + return false; + }; + } + + EventUtils.Event = new EventUtils(); + EventUtils.Event.bind(window, 'ready', function() {}); + + return EventUtils; +}); + +// Included from: js/tinymce/classes/dom/Sizzle.js + +/** + * Sizzle.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint bitwise:false, expr:true, noempty:false, sub:true, eqnull:true, latedef:false, maxlen:255 */ + +/* + * Sizzle CSS Selector Engine + * Copyright, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +define("tinymce/dom/Sizzle", [], function() { +var i, + cachedruns, + Expr, + getText, + isXML, + compile, + outermostContext, + recompare, + sortInput, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + -(new Date()), + preferredDoc = window.document, + support = {}, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + hasDuplicate = false, + sortOrder = function() { return 0; }, + + // General-purpose constants + strundefined = typeof undefined, + MAX_NEGATIVE = 1 << 31, + + // Array methods + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf if we can't use a native one + indexOf = arr.indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + + // 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/, + + // 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 ); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +/** + * 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 = []; + + 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() ]; + } + cache[ key ] = value; + return value; + }; + + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // 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 ( documentIsHTML && !seed ) { + + // Shortcuts + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // QSA path + if ( support.qsa && !rbuggyQSA.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, + newContext.querySelectorAll( newSelector ) + ); + 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 + documentIsHTML = !isXML( doc ); + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = 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 = ""; + 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.getElementsByClassName = assert(function( div ) { + // Opera can't find a second classname (in 9.6) + div.innerHTML = ""; + 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 getElementsByName privileges form controls or returns elements by ID + // If so, assume (for broader support) that getElementById returns elements by name + support.getByName = assert(function( div ) { + // Inject content + div.id = expando + 0; + // Support: Windows 8 Native Apps + // Assigning innerHTML with "name" attributes throws uncatchable exceptions + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx + div.appendChild( document.createElement("a") ).setAttribute( "name", expando ); + div.appendChild( document.createElement("i") ).setAttribute( "name", expando ); + docElem.appendChild( div ); + + // 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; + + // Cleanup + docElem.removeChild( div ); + + return pass; + }); + + // Support: Webkit<537.32 + // Detached nodes confoundingly follow *each other* + support.sortDetached = assert(function( div1 ) { + return div1.compareDocumentPosition && + // Should return 1, but Webkit returns 4 (following) + (div1.compareDocumentPosition( document.createElement("div") ) & 1); + }); + + // IE6/7 return modified attributes + Expr.attrHandle = assert(function( div ) { + div.innerHTML = ""; + 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.getByName ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + 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.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var elem, + tmp = [], + i = 0, + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Name + Expr.find["NAME"] = support.getByName && function( tag, context ) { + if ( typeof context.getElementsByName !== strundefined ) { + return context.getElementsByName( name ); + } + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { + 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 explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // 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 = ""; + 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 = rbuggyMatches.length && 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 ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); + + if ( compare ) { + // Disconnected nodes + if ( compare & 1 || + (recompare && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === doc || contains(preferredDoc, a) ) { + return -1; + } + if ( b === doc || contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } + + // Not directly comparable, sort on existence of method + return a.compareDocumentPosition ? -1 : 1; + } : + function( a, b ) { + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Parentless nodes are either documents or disconnected + } else if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return 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 && documentIsHTML && (!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 ( documentIsHTML ) { + name = name.toLowerCase(); + } + if ( (val = Expr.attrHandle[ name ]) ) { + return val( elem ); + } + if ( !documentIsHTML || 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 = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + // Compensate for sort limitations + recompare = !support.sortDetached; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + return results; +}; + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns Returns -1 if a precedes b, 1 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +// Returns a function to use in pseudos for input types +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.slice( -check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), + // not comment, processing instructions, or others + // Thanks to Diego Perini for the nodeName shortcut + // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +// 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 && 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 ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); + + if ( outermost ) { + outermostContext = context !== document && context; + cachedruns = matcherCachedRuns; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + for ( ; (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + cachedruns = ++matcherCachedRuns; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !group ) { + group = tokenize( selector ); + } + i = group.length; + while ( i-- ) { + cached = matcherFromTokens( group[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + } + return cached; +}; + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function select( selector, context, results, seed ) { + var i, tokens, token, type, find, + match = tokenize( selector ); + + if ( !seed ) { + // Try to minimize operations if there is only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && context.parentNode || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + } + + // Compile and execute a filtering function + // Provide `match` to avoid retokenization if we modified the selector above + compile( selector, match )( + seed, + context, + !documentIsHTML, + results, + rsibling.test( selector ) + ); + return results; +} + +// Deprecated +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +// Check sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Initialize with the default document +setDocument(); + +// Always assume the presence of duplicates if sort doesn't +// pass them to our comparison function (as in Google Chrome). +[0, 0].sort( sortOrder ); +support.detectDuplicates = hasDuplicate; + +// EXPOSE +if ( typeof define === "function" && define.amd ) { + define(function() { return Sizzle; }); +} else { + window.Sizzle = Sizzle; +} + +// EXPOSE +return Sizzle; +}); + +// Included from: js/tinymce/classes/dom/DomQuery.js + +/** + * DomQuery.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + * + * Some of this logic is based on jQuery code that is released under + * MIT license that grants us to sublicense it under LGPL. + */ + +define("tinymce/dom/DomQuery", [ + "tinymce/dom/EventUtils", + "tinymce/dom/Sizzle" +], function(EventUtils, Sizzle) { + var doc = document, push = Array.prototype.push, slice = Array.prototype.slice; + var rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/; + var Event = EventUtils.Event; + + function isDefined(obj) { + return typeof obj !== "undefined"; + } + + function isString(obj) { + return typeof obj === "string"; + } + + function createFragment(html) { + var frag, node, container; + + container = doc.createElement("div"); + frag = doc.createDocumentFragment(); + container.innerHTML = html; + + while ((node = container.firstChild)) { + frag.appendChild(node); + } + + return frag; + } + + function domManipulate(targetNodes, sourceItem, callback) { + var i; + + if (typeof sourceItem === "string") { + sourceItem = createFragment(sourceItem); + } else if (sourceItem.length) { + for (i = 0; i < sourceItem.length; i++) { + domManipulate(targetNodes, sourceItem[i], callback); + } + + return targetNodes; + } + + i = targetNodes.length; + while (i--) { + callback.call(targetNodes[i], sourceItem.parentNode ? sourceItem : sourceItem); + } + + return targetNodes; + } + + function hasClass(node, className) { + return node && className && (' ' + node.className + ' ').indexOf(' ' + className + ' ') !== -1; + } + + /** + * Makes a map object out of a string that gets separated by a delimiter. + * + * @method makeMap + * @param {String} items Item string to split. + * @param {Object} map Optional object to add items to. + * @return {Object} name/value object with items as keys. + */ + function makeMap(items, map) { + var i; + + items = items || []; + + if (typeof(items) == "string") { + items = items.split(' '); + } + + map = map || {}; + + i = items.length; + while (i--) { + map[items[i]] = {}; + } + + return map; + } + + var numericCssMap = makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom'); + + function DomQuery(selector, context) { + return new DomQuery.fn.init(selector, context); + } + + /** + * Extends the specified object with another object. + * + * @method extend + * @param {Object} target Object to extend. + * @param {Object..} obj Multiple objects to extend with. + * @return {Object} Same as target, the extended object. + */ + function extend(target) { + var args = arguments, arg, i, key; + + for (i = 1; i < args.length; i++) { + arg = args[i]; + + for (key in arg) { + target[key] = arg[key]; + } + } + + return target; + } + + /** + * Converts the specified object into a real JavaScript array. + * + * @method toArray + * @param {Object} obj Object to convert into array. + * @return {Array} Array object based in input. + */ + function toArray(obj) { + var array = [], i, l; + + for (i = 0, l = obj.length; i < l; i++) { + array[i] = obj[i]; + } + + return array; + } + + /** + * Returns the index of the specified item inside the array. + * + * @method inArray + * @param {Object} item Item to look for. + * @param {Array} array Array to look for item in. + * @return {Number} Index of the item or -1. + */ + function inArray(item, array) { + var i; + + if (array.indexOf) { + return array.indexOf(item); + } + + i = array.length; + while (i--) { + if (array[i] === item) { + return i; + } + } + + return -1; + } + + /** + * Returns true/false if the specified object is an array. + * + * @method isArray + * @param {Object} obj Object to check if it's an array. + * @return {Boolean} true/false if the input object is array or not. + */ + var isArray = Array.isArray || function(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + + var whiteSpaceRegExp = /^\s*|\s*$/g; + var trim = function(str) { + return (str === null || str === undefined) ? '' : ("" + str).replace(whiteSpaceRegExp, ''); + }; + + /** + * Executes the callback function for each item in array/object. If you return false in the + * callback it will break the loop. + * + * @method each + * @param {Object} obj Object to iterate. + * @param {function} callback Callback function to execute for each item. + */ + function each(obj, callback) { + var length, key, i, undef, value; + + if (obj) { + length = obj.length; + + if (length === undef) { + // Loop object items + for (key in obj) { + if (obj.hasOwnProperty(key)) { + value = obj[key]; + if (callback.call(value, value, key) === false) { + break; + } + } + } + } else { + // Loop array items + for (i = 0; i < length; i++) { + value = obj[i]; + if (callback.call(value, value, key) === false) { + break; + } + } + } + } + + return obj; + } + + DomQuery.fn = DomQuery.prototype = { + constructor: DomQuery, + selector: "", + length: 0, + + init: function(selector, context) { + var self = this, match, node; + + if (!selector) { + return self; + } + + if (selector.nodeType) { + self.context = self[0] = selector; + self.length = 1; + + return self; + } + + if (isString(selector)) { + if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) { + match = [null, selector, null]; + } else { + match = rquickExpr.exec(selector); + } + + if (match) { + if (match[1]) { + node = createFragment(selector).firstChild; + while (node) { + this.add(node); + node = node.nextSibling; + } + } else { + node = doc.getElementById(match[2]); + + if (node.id !== match[2]) { + return self.find(selector); + } + + self.length = 1; + self[0] = node; + } + } else { + return DomQuery(context || document).find(selector); + } + } else { + this.add(selector); + } + + return self; + }, + + toArray: function() { + return toArray(this); + }, + + add: function(items) { + var self = this; + + // Force single item into array + if (!isArray(items)) { + if (items instanceof DomQuery) { + self.add(items.toArray()); + } else { + push.call(self, items); + } + } else { + push.apply(self, items); + } + + return self; + }, + + attr: function(name, value) { + var self = this; + + if (typeof name === "object") { + each(name, function(value, name) { + self.attr(name, value); + }); + } else if (isDefined(value)) { + this.each(function() { + if (this.nodeType === 1) { + this.setAttribute(name, value); + } + }); + } else { + return self[0] && self[0].nodeType === 1 ? self[0].getAttribute(name) : undefined; + } + + return self; + }, + + css: function(name, value) { + var self = this; + + if (typeof name === "object") { + each(name, function(value, name) { + self.css(name, value); + }); + } else { + // Camelcase it, if needed + name = name.replace(/-(\D)/g, function(a, b) { + return b.toUpperCase(); + }); + + if (isDefined(value)) { + // Default px suffix on these + if (typeof(value) === 'number' && !numericCssMap[name]) { + value += 'px'; + } + + self.each(function() { + var style = this.style; + + // IE specific opacity + if (name === "opacity" && this.runtimeStyle && typeof(this.runtimeStyle.opacity) === "undefined") { + style.filter = value === '' ? '' : "alpha(opacity=" + (value * 100) + ")"; + } + + try { + style[name] = value; + } catch (ex) { + // Ignore + } + }); + } else { + return self[0] ? self[0].style[name] : undefined; + } + } + + return self; + }, + + remove: function() { + var self = this, node, i = this.length; + + while (i--) { + node = self[i]; + Event.clean(node); + + if (node.parentNode) { + node.parentNode.removeChild(node); + } + } + + return this; + }, + + empty: function() { + var self = this, node, i = this.length; + + while (i--) { + node = self[i]; + while (node.firstChild) { + node.removeChild(node.firstChild); + } + } + + return this; + }, + + html: function(value) { + var self = this, i; + + if (isDefined(value)) { + i = self.length; + while (i--) { + self[i].innerHTML = value; + } + + return self; + } + + return self[0] ? self[0].innerHTML : ''; + }, + + text: function(value) { + var self = this, i; + + if (isDefined(value)) { + i = self.length; + while (i--) { + self[i].innerText = self[0].textContent = value; + } + + return self; + } + + return self[0] ? self[0].innerText || self[0].textContent : ''; + }, + + append: function() { + return domManipulate(this, arguments, function(node) { + if (this.nodeType === 1) { + this.appendChild(node); + } + }); + }, + + prepend: function() { + return domManipulate(this, arguments, function(node) { + if (this.nodeType === 1) { + this.insertBefore(node, this.firstChild); + } + }); + }, + + before: function() { + var self = this; + + if (self[0] && self[0].parentNode) { + return domManipulate(self, arguments, function(node) { + this.parentNode.insertBefore(node, this.nextSibling); + }); + } + + return self; + }, + + after: function() { + var self = this; + + if (self[0] && self[0].parentNode) { + return domManipulate(self, arguments, function(node) { + this.parentNode.insertBefore(node, this); + }); + } + + return self; + }, + + appendTo: function(val) { + DomQuery(val).append(this); + + return this; + }, + + addClass: function(className) { + return this.toggleClass(className, true); + }, + + removeClass: function(className) { + return this.toggleClass(className, false); + }, + + toggleClass: function(className, state) { + var self = this; + + if (className.indexOf(' ') !== -1) { + each(className.split(' '), function() { + self.toggleClass(this, state); + }); + } else { + self.each(function() { + var node = this, existingClassName; + + if (hasClass(node, className) !== state) { + existingClassName = node.className; + + if (state) { + node.className += existingClassName ? ' ' + className : className; + } else { + node.className = trim((" " + existingClassName + " ").replace(' ' + className + ' ', ' ')); + } + } + }); + } + + return self; + }, + + hasClass: function(className) { + return hasClass(this[0], className); + }, + + each: function(callback) { + return each(this, callback); + }, + + on: function(name, callback) { + return this.each(function() { + Event.bind(this, name, callback); + }); + }, + + off: function(name, callback) { + return this.each(function() { + Event.unbind(this, name, callback); + }); + }, + + show: function() { + return this.css('display', ''); + }, + + hide: function() { + return this.css('display', 'none'); + }, + + slice: function() { + return new DomQuery(slice.apply(this, arguments)); + }, + + eq: function(index) { + return index === -1 ? this.slice(index) : this.slice(index, +index + 1); + }, + + first: function() { + return this.eq(0); + }, + + last: function() { + return this.eq(-1); + }, + + replaceWith: function(content) { + var self = this; + + if (self[0]) { + self[0].parentNode.replaceChild(DomQuery(content)[0], self[0]); + } + + return self; + }, + + wrap: function(wrapper) { + wrapper = DomQuery(wrapper)[0]; + + return this.each(function() { + var self = this, newWrapper = wrapper.cloneNode(false); + self.parentNode.insertBefore(newWrapper, self); + newWrapper.appendChild(self); + }); + }, + + unwrap: function() { + return this.each(function() { + var self = this, node = self.firstChild, currentNode; + + while (node) { + currentNode = node; + node = node.nextSibling; + self.parentNode.insertBefore(currentNode, self); + } + }); + }, + + clone: function() { + var result = []; + + this.each(function() { + result.push(this.cloneNode(true)); + }); + + return DomQuery(result); + }, + + find: function(selector) { + var i, l, ret = []; + + for (i = 0, l = this.length; i < l; i++) { + DomQuery.find(selector, this[i], ret); + } + + return DomQuery(ret); + }, + + push: push, + sort: [].sort, + splice: [].splice + }; + + // Static members + extend(DomQuery, { + extend: extend, + toArray: toArray, + inArray: inArray, + isArray: isArray, + each: each, + trim: trim, + makeMap: makeMap, + + // Sizzle + find: Sizzle, + expr: Sizzle.selectors, + unique: Sizzle.uniqueSort, + text: Sizzle.getText, + isXMLDoc: Sizzle.isXML, + contains: Sizzle.contains, + filter: function(expr, elems, not) { + if (not) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [] : + DomQuery.find.matches(expr, elems); + } + }); + + function dir(el, prop, until) { + var matched = [], cur = el[prop]; + + while (cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !DomQuery(cur).is(until))) { + if (cur.nodeType === 1) { + matched.push(cur); + } + + cur = cur[prop]; + } + + return matched; + } + + function sibling(n, el, siblingName, nodeType) { + var r = []; + + for(; n; n = n[siblingName]) { + if ((!nodeType || n.nodeType === nodeType) && n !== el) { + r.push(n); + } + } + + return r; + } + + each({ + parent: function(node) { + var parent = node.parentNode; + + return parent && parent.nodeType !== 11 ? parent : null; + }, + + parents: function(node) { + return dir(node, "parentNode"); + }, + + parentsUntil: function(node, until) { + return dir(node, "parentNode", until); + }, + + next: function(node) { + return sibling(node, 'nextSibling', 1); + }, + + prev: function(node) { + return sibling(node, 'previousSibling', 1); + }, + + nextNodes: function(node) { + return sibling(node, 'nextSibling'); + }, + + prevNodes: function(node) { + return sibling(node, 'previousSibling'); + }, + + children: function(node) { + return sibling(node.firstChild, 'nextSibling', 1); + }, + + contents: function(node) { + return toArray((node.nodeName === "iframe" ? node.contentDocument || node.contentWindow.document : node).childNodes); + } + }, function(name, fn){ + DomQuery.fn[name] = function(selector) { + var self = this, result; + + if (self.length > 1) { + throw new Error("DomQuery only supports traverse functions on a single node."); + } + + if (self[0]) { + result = fn(self[0], selector); + } + + result = DomQuery(result); + + if (selector && name !== "parentsUntil") { + return result.filter(selector); + } + + return result; + }; + }); + + DomQuery.fn.filter = function(selector) { + return DomQuery.filter(selector); + }; + + DomQuery.fn.is = function(selector) { + return !!selector && this.filter(selector).length > 0; + }; + + DomQuery.fn.init.prototype = DomQuery.fn; + + return DomQuery; +}); + +// Included from: js/tinymce/classes/html/Styles.js + +/** + * Styles.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is used to parse CSS styles it also compresses styles to reduce the output size. + * + * @example + * var Styles = new tinymce.html.Styles({ + * url_converter: function(url) { + * return url; + * } + * }); + * + * styles = Styles.parse('border: 1px solid red'); + * styles.color = 'red'; + * + * console.log(new tinymce.html.StyleSerializer().serialize(styles)); + * + * @class tinymce.html.Styles + * @version 3.4 + */ +define("tinymce/html/Styles", [], function() { + return function(settings, schema) { + /*jshint maxlen:255 */ + 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+$/, + undef, i, encodingLookup = {}, encodingItems, invisibleChar = '\uFEFF'; + + settings = settings || {}; + + encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' '); + for (i = 0; i < encodingItems.length; i++) { + encodingLookup[encodingItems[i]] = invisibleChar + i; + encodingLookup[invisibleChar + i] = encodingItems[i]; + } + + function toHex(match, r, g, b) { + function hex(val) { + val = parseInt(val, 10).toString(16); + + return val.length > 1 ? val : '0' + val; // 0 -> 00 + } + + return '#' + hex(r) + hex(g) + hex(b); + } + + return { + /** + * Parses the specified RGB color value and returns a hex version of that color. + * + * @method toHex + * @param {String} color RGB string value like rgb(1,2,3) + * @return {String} Hex version of that RGB value like #FF00FF. + */ + toHex: function(color) { + return color.replace(rgbRegExp, toHex); + }, + + /** + * Parses the specified style value into an object collection. This parser will also + * merge and remove any redundant items that browsers might have added. It will also convert non hex + * colors to hex values. Urls inside the styles will also be converted to absolute/relative based on settings. + * + * @method parse + * @param {String} css Style value to parse for example: border:1px solid red;. + * @return {Object} Object representation of that style like {border: '1px solid red'} + */ + 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]; + } + + /** + * Checks if the specific style can be compressed in other words if all border-width are equal. + */ + 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; + } + + /** + * Compresses multiple styles into one style. + */ + 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 _ + function encode(str) { + isEncoded = true; + + return encodingLookup[str]; + } + + // Decodes the specified string by replacing all _ 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; + }, + + /** + * Serializes the specified style object into a string. + * + * @method serialize + * @param {Object} styles Object to serialize as string for example: {border: '1px solid red'} + * @param {String} element_name Optional element name, if specified only the styles that matches the schema will be serialized. + * @return {String} String representation of the style object for example: border: 1px solid red. + */ + 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; + } + }; + }; +}); + +// Included from: js/tinymce/classes/dom/TreeWalker.js + +/** + * TreeWalker.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/dom/TreeWalker", [], function() { + return 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; + } + } + } + } + } + + /** + * Returns the current node. + * + * @return {Node} Current node where the walker is. + */ + this.current = function() { + return node; + }; + + /** + * Walks to the next node in tree. + * + * @return {Node} Current node where the walker is after moving to the next node. + */ + this.next = function(shallow) { + node = findSibling(node, 'firstChild', 'nextSibling', shallow); + return node; + }; + + /** + * Walks to the previous node in tree. + * + * @return {Node} Current node where the walker is after moving to the previous node. + */ + this.prev = function(shallow) { + node = findSibling(node, 'lastChild', 'previousSibling', shallow); + return node; + }; + }; +}); + +// Included from: js/tinymce/classes/util/Tools.js + +/** + * Quirks.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/util/Tools", [], function() { + /** + * Removes whitespace from the beginning and end of a string. + * + * @method trim + * @param {String} s String to remove whitespace from. + * @return {String} New string with removed whitespace. + */ + var whiteSpaceRegExp = /^\s*|\s*$/g; + var trim = function(str) { + return (str === null || str === undefined) ? '' : ("" + str).replace(whiteSpaceRegExp, ''); + }; + + /** + * Returns true/false if the object is an array or not. + * + * @method isArray + * @param {Object} obj Object to check. + * @return {boolean} true/false state if the object is an array or not. + */ + var isArray = Array.isArray || function(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + + /** + * Checks if a object is of a specific type for example an array. + * + * @method is + * @param {Object} o Object to check type of. + * @param {string} t Optional type to check for. + * @return {Boolean} true/false if the object is of the specified type. + */ + function is(o, t) { + if (!t) { + return o !== undefined; + } + + if (t == 'array' && isArray(o)) { + return true; + } + + return typeof(o) == t; + } + + /** + * Converts the specified object into a real JavaScript array. + * + * @method toArray + * @param {Object} obj Object to convert into array. + * @return {Array} Array object based in input. + */ + function toArray(obj) { + var array = [], i, l; + + for (i = 0, l = obj.length; i < l; i++) { + array[i] = obj[i]; + } + + return array; + } + + /** + * Makes a name/object map out of an array with names. + * + * @method makeMap + * @param {Array/String} items Items to make map out of. + * @param {String} delim Optional delimiter to split string by. + * @param {Object} map Optional map to add items to. + * @return {Object} Name/value map of items. + */ + function makeMap(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; + } + + /** + * Performs an iteration of all items in a collection such as an object or array. This method will execure the + * callback function for each item in the collection, if the callback returns false the iteration will terminate. + * The callback has the following format: cb(value, key_or_index). + * + * @method each + * @param {Object} o Collection to iterate. + * @param {function} cb Callback function to execute for each item. + * @param {Object} s Optional scope to execute the callback in. + * @example + * // Iterate an array + * tinymce.each([1,2,3], function(v, i) { + * console.debug("Value: " + v + ", Index: " + i); + * }); + * + * // Iterate an object + * tinymce.each({a: 1, b: 2, c: 3], function(v, k) { + * console.debug("Value: " + v + ", Key: " + k); + * }); + */ + function each(o, cb, s) { + var n, l; + + if (!o) { + return 0; + } + + s = s || o; + + if (o.length !== undefined) { + // 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; + } + + /** + * Creates a new array by the return value of each iteration function call. This enables you to convert + * one array list into another. + * + * @method map + * @param {Array} a Array of items to iterate. + * @param {function} f Function to call for each item. It's return value will be the new value. + * @return {Array} Array with new values based on function return values. + */ + function map(a, f) { + var o = []; + + each(a, function(v) { + o.push(f(v)); + }); + + return o; + } + + /** + * Filters out items from the input array by calling the specified function for each item. + * If the function returns false the item will be excluded if it returns true it will be included. + * + * @method grep + * @param {Array} a Array of items to loop though. + * @param {function} f Function to call for each item. Include/exclude depends on it's return value. + * @return {Array} New array with values imported and filtered based in input. + * @example + * // Filter out some items, this will return an array with 4 and 5 + * var items = tinymce.grep([1,2,3,4,5], function(v) {return v > 3;}); + */ + function grep(a, f) { + var o = []; + + each(a, function(v) { + if (!f || f(v)) { + o.push(v); + } + }); + + return o; + } + + /** + * Creates a class, subclass or static singleton. + * More details on this method can be found in the Wiki. + * + * @method create + * @param {String} s Class name, inheritage and prefix. + * @param {Object} p Collection of methods to add to the class. + * @param {Object} root Optional root object defaults to the global window object. + * @example + * // Creates a basic class + * tinymce.create('tinymce.somepackage.SomeClass', { + * SomeClass: function() { + * // Class constructor + * }, + * + * method: function() { + * // Some method + * } + * }); + * + * // Creates a basic subclass class + * tinymce.create('tinymce.somepackage.SomeSubClass:tinymce.somepackage.SomeClass', { + * SomeSubClass: function() { + * // Class constructor + * this.parent(); // Call parent constructor + * }, + * + * method: function() { + * // Some method + * this.parent(); // Call parent method + * }, + * + * 'static': { + * staticMethod: function() { + * // Static method + * } + * } + * }); + * + * // Creates a singleton/static class + * tinymce.create('static tinymce.somepackage.SomeSingletonClass', { + * method: function() { + * // Some method + * } + * }); + */ + function create(s, p, root) { + var t = this, sp, ns, cn, scn, c, de = 0; + + // Parse : : + 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 + /*jshint sub:true*/ + t.each(p['static'], function(f, n) { + ns[cn][n] = f; + }); + } + + /** + * Returns the index of a value in an array, this method will return -1 if the item wasn't found. + * + * @method inArray + * @param {Array} a Array/Object to search for value in. + * @param {Object} v Value to check for inside the array. + * @return {Number/String} Index of item inside the array inside an object. Or -1 if it wasn't found. + * @example + * // Get index of value in array this will alert 1 since 2 is at that index + * alert(tinymce.inArray([1,2,3], 2)); + */ + function inArray(a, v) { + var i, l; + + if (a) { + for (i = 0, l = a.length; i < l; i++) { + if (a[i] === v) { + return i; + } + } + } + + return -1; + } + + function extend(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 !== undefined) { + obj[name] = value; + } + } + } + } + + return obj; + } + + /** + * Executed the specified function for each item in a object tree. + * + * @method walk + * @param {Object} o Object tree to walk though. + * @param {function} f Function to call for each item. + * @param {String} n Optional name of collection inside the objects to walk for example childNodes. + * @param {String} s Optional scope to execute the function in. + */ + function walk(o, f, n, s) { + s = s || this; + + if (o) { + if (n) { + o = o[n]; + } + + each(o, function(o, i) { + if (f.call(s, o, i, n) === false) { + return false; + } + + walk(o, f, n, s); + }); + } + } + + /** + * Creates a namespace on a specific object. + * + * @method createNS + * @param {String} n Namespace to create for example a.b.c.d. + * @param {Object} o Optional object to add namespace to, defaults to window. + * @return {Object} New namespace object the last item in path. + * @example + * // Create some namespace + * tinymce.createNS('tinymce.somepackage.subpackage'); + * + * // Add a singleton + * var tinymce.somepackage.subpackage.SomeSingleton = { + * method: function() { + * // Some method + * } + * }; + */ + function createNS(n, o) { + var i, v; + + o = o || window; + + n = n.split('.'); + for (i=0; i= 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; + var 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]; + var 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); + } + + function toStringIE() { + return dom.create('body', null, cloneContents()).outerText; + } + + 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, + toStringIE: toStringIE + }); + + return t; + } + + // Older IE versions doesn't let you override toString by it's constructor so we have to stick it in the prototype + Range.prototype.toString = function() { + return this.toStringIE(); + }; + + return Range; +}); + +// Included from: js/tinymce/classes/html/Entities.js + +/** + * Entities.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint bitwise:false */ + +/** + * Entity encoder class. + * + * @class tinymce.html.Entities + * @static + * @version 3.4 + */ +define("tinymce/html/Entities", [ + "tinymce/util/Tools" +], function(Tools) { + var makeMap = Tools.makeMap; + + 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 = { + '\"': '"', // Needs to be escaped since the YUI compressor would otherwise break the code + "'": ''', + '<': '<', + '>': '>', + '&': '&' + }; + + // Reverse lookup table for raw entities + reverseEntities = { + '<': '<', + '>': '>', + '&': '&', + '"': '"', + ''': "'" + }; + + // 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); + + var Entities = { + /** + * Encodes the specified string using raw entities. This means only the required XML base entities will be endoded. + * + * @method encodeRaw + * @param {String} text Text to encode. + * @param {Boolean} attr Optional flag to specify if the text is attribute contents. + * @return {String} Entity encoded text. + */ + encodeRaw: function(text, attr) { + return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { + return baseEntities[chr] || chr; + }); + }, + + /** + * Encoded the specified text with both the attributes and text entities. This function will produce larger text contents + * since it doesn't know if the context is within a attribute or text node. This was added for compatibility + * and is exposed as the DOMUtils.encode function. + * + * @method encodeAllRaw + * @param {String} text Text to encode. + * @return {String} Entity encoded text. + */ + encodeAllRaw: function(text) { + return ('' + text).replace(rawCharsRegExp, function(chr) { + return baseEntities[chr] || chr; + }); + }, + + /** + * Encodes the specified string using numeric entities. The core entities will be + * encoded as named ones but all non lower ascii characters will be encoded into numeric entities. + * + * @method encodeNumeric + * @param {String} text Text to encode. + * @param {Boolean} attr Optional flag to specify if the text is attribute contents. + * @return {String} Entity encoded text. + */ + 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) + ';'; + }); + }, + + /** + * Encodes the specified string using named entities. The core entities will be encoded + * as named ones but all non lower ascii characters will be encoded into named entities. + * + * @method encodeNamed + * @param {String} text Text to encode. + * @param {Boolean} attr Optional flag to specify if the text is attribute contents. + * @param {Object} entities Optional parameter with entities to use. + * @return {String} Entity encoded text. + */ + encodeNamed: function(text, attr, entities) { + entities = entities || namedEntities; + + return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { + return baseEntities[chr] || entities[chr] || chr; + }); + }, + + /** + * Returns an encode function based on the name(s) and it's optional entities. + * + * @method getEncodeFunc + * @param {String} name Comma separated list of encoders for example named,numeric. + * @param {String} entities Optional parameter with entities to use instead of the built in set. + * @return {function} Encode function to be used. + */ + getEncodeFunc: function(name, 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 = 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; + }, + + /** + * Decodes the specified string, this will replace entities with raw UTF characters. + * + * @param {String} text Text to entity decode. + * @return {String} Entity decoded string. + */ + 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); + }); + } + }; + + return Entities; +}); + +// Included from: js/tinymce/classes/Env.js + +/** + * Env.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/Env", [], function() { + var nav = navigator, userAgent = nav.userAgent; + var opera, webkit, ie, gecko, mac, iDevice; + + opera = window.opera && window.opera.buildNumber; + webkit = /WebKit/.test(userAgent); + ie = !webkit && !opera && (/MSIE/gi).test(userAgent) && (/Explorer/gi).test(nav.appName); + ie = ie && /MSIE (\w+)\./.exec(userAgent)[1]; + gecko = !webkit && /Gecko/.test(userAgent); + mac = userAgent.indexOf('Mac') != -1; + iDevice = /(iPad|iPhone)/.test(userAgent); + + // Is a iPad/iPhone and not on iOS5 sniff the WebKit version since older iOS WebKit versions + // says it has contentEditable support but there is no visible caret. + var contentEditable = !iDevice || userAgent.match(/AppleWebKit\/(\d*)/)[1] >= 534; + + return { + /** + * Constant that is true if the browser is Opera. + * + * @property opera + * @type Boolean + * @final + */ + opera: opera, + + /** + * Constant that is true if the browser is WebKit (Safari/Chrome). + * + * @property webKit + * @type Boolean + * @final + */ + webkit: webkit, + + /** + * Constant that is more than zero if the browser is IE. + * + * @property ie + * @type Boolean + * @final + */ + ie: ie, + + /** + * Constant that is true if the browser is Gecko. + * + * @property gecko + * @type Boolean + * @final + */ + gecko: gecko, + + /** + * Constant that is true if the os is Mac OS. + * + * @property mac + * @type Boolean + * @final + */ + mac: mac, + + /** + * Constant that is true if the os is iOS. + * + * @property iOS + * @type Boolean + * @final + */ + iOS: iDevice, + + /** + * Constant that is true if the browser supports editing. + * + * @property contentEditable + * @type Boolean + * @final + */ + contentEditable: contentEditable, + + /** + * Transparent image data url. + * + * @property transparentSrc + * @type Boolean + * @final + */ + transparentSrc: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", + + /** + * Returns true/false if the browser can or can't place the caret after a inline block like an image. + * + * @property noCaretAfter + * @type Boolean + * @final + */ + caretAfter: ie != 8, + + /** + * Constant that is true if the browser supports native DOM Ranges. IE 9+. + * + * @property range + * @type Boolean + */ + range: window.getSelection && "Range" in window + }; +}); + +// Included from: js/tinymce/classes/dom/DOMUtils.js + +/** + * DOMUtils.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Utility class for various DOM manipulation and retrival functions. + * + * @class tinymce.dom.DOMUtils + * @example + * // Add a class to an element by id in the page + * tinymce.DOM.addClass('someid', 'someclass'); + * + * // Add a class to an element by id inside the editor + * tinymce.activeEditor.dom.addClass('someid', 'someclass'); + */ +define("tinymce/dom/DOMUtils", [ + "tinymce/dom/Sizzle", + "tinymce/html/Styles", + "tinymce/dom/EventUtils", + "tinymce/dom/TreeWalker", + "tinymce/dom/Range", + "tinymce/html/Entities", + "tinymce/Env", + "tinymce/util/Tools" +], function(Sizzle, Styles, EventUtils, TreeWalker, Range, Entities, Env, Tools) { + // Shorten names + var each = Tools.each, is = Tools.is, grep = Tools.grep, trim = Tools.trim, extend = Tools.extend; + var isWebKit = Env.webkit, isIE = Env.ie; + var simpleSelectorRe = /^([a-z0-9],?)+$/i; + var whiteSpaceRegExp = /^[ \t\r\n]*$/; + var numericCssMap = Tools.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' '); + + /** + * Constructs a new DOMUtils instance. Consult the Wiki for more details on settings etc for this class. + * + * @constructor + * @method DOMUtils + * @param {Document} d Document reference to bind the utility class to. + * @param {settings} s Optional settings collection. + */ + function DOMUtils(doc, settings) { + var self = this, blockElementsMap; + + self.doc = doc; + self.win = window; + self.files = {}; + self.counter = 0; + self.stdMode = !isIE || doc.documentMode >= 8; + self.boxModel = !isIE || doc.compatMode == "CSS1Compat" || self.stdMode; + self.hasOuterHTML = "outerHTML" in doc.createElement("a"); + + self.settings = settings = extend({ + keep_values: false, + hex_colors: 1 + }, settings); + + self.schema = settings.schema; + self.styles = new Styles({ + url_converter: settings.url_converter, + url_converter_scope: settings.url_converter_scope + }, settings.schema); + + self.fixDoc(doc); + self.events = settings.ownEvents ? new EventUtils(settings.proxy) : EventUtils.Event; + blockElementsMap = settings.schema ? settings.schema.getBlockElements() : {}; + + /** + * Returns true/false if the specified element is a block element or not. + * + * @method isBlock + * @param {Node/String} node Element/Node to check. + * @return {Boolean} True/False state if the node is a block element or not. + */ + self.isBlock = function(node) { + // Fix for #5446 + if (!node) { + return false; + } + + // 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]; + }; + } + + DOMUtils.prototype = { + root: null, + 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" + }, + + 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; + }, + + /** + * Returns the root node of the document this is normally the body but might be a DIV. Parents like getParent will not + * go above the point of this root node. + * + * @method getRoot + * @return {Element} Root element for the utility class. + */ + getRoot: function() { + var self = this; + + return self.get(self.settings.root_element) || self.doc.body; + }, + + /** + * Returns the viewport of the window. + * + * @method getViewPort + * @param {Window} win Optional window to get viewport of. + * @return {Object} Viewport object with fields x, y, w and h. + */ + getViewPort: function(win) { + var doc, rootElm; + + win = !win ? this.win : win; + doc = win.document; + rootElm = this.boxModel ? doc.documentElement : doc.body; + + // Returns viewport size excluding scrollbars + return { + x: win.pageXOffset || rootElm.scrollLeft, + y: win.pageYOffset || rootElm.scrollTop, + w: win.innerWidth || rootElm.clientWidth, + h: win.innerHeight || rootElm.clientHeight + }; + }, + + /** + * Returns the rectangle for a specific element. + * + * @method getRect + * @param {Element/String} elm Element object or element ID to get rectange from. + * @return {object} Rectange for specified element object with x, y, w, h fields. + */ + getRect: function(elm) { + var self = this, pos, size; + + elm = self.get(elm); + pos = self.getPos(elm); + size = self.getSize(elm); + + return { + x: pos.x, y: pos.y, + w: size.w, h: size.h + }; + }, + + /** + * Returns the size dimensions of the specified element. + * + * @method getSize + * @param {Element/String} elm Element object or element ID to get rectange from. + * @return {object} Rectange for specified element object with w, h fields. + */ + getSize: function(elm) { + var self = this, w, h; + + elm = self.get(elm); + w = self.getStyle(elm, 'width'); + h = self.getStyle(elm, '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) || elm.offsetWidth || elm.clientWidth, + h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight + }; + }, + + /** + * Returns a node by the specified selector function. This function will + * loop through all parent nodes and call the specified function for each node. + * If the function then returns true indicating that it has found what it was looking for, the loop execution will then end + * and the node it found will be returned. + * + * @method getParent + * @param {Node/String} node DOM node to search parents on or ID string. + * @param {function} selector Selection function or CSS selector to execute on each node. + * @param {Node} root Optional root element, never go below this point. + * @return {Node} DOM Node or null if it wasn't found. + */ + getParent: function(node, selector, root) { + return this.getParents(node, selector, root, false); + }, + + /** + * Returns a node list of all parents matching the specified selector function or pattern. + * If the function then returns true indicating that it has found what it was looking for and that node will be collected. + * + * @method getParents + * @param {Node/String} node DOM node to search parents on or ID string. + * @param {function} selector Selection function to execute on each node or CSS pattern. + * @param {Node} root Optional root element, never go below this point. + * @return {Array} Array of nodes or null if it wasn't found. + */ + getParents: function(node, selector, root, collect) { + var self = this, selectorVal, result = []; + + node = self.get(node); + collect = collect === undefined; + + // Wrap node name as func + if (is(selector, 'string')) { + selectorVal = selector; + + if (selector === '*') { + selector = function(node) {return node.nodeType == 1;}; + } else { + selector = function(node) { + return self.is(node, selectorVal); + }; + } + } + + while (node) { + if (node == root || !node.nodeType || node.nodeType === 9) { + break; + } + + if (!selector || selector(node)) { + if (collect) { + result.push(node); + } else { + return node; + } + } + + node = node.parentNode; + } + + return collect ? result : null; + }, + + /** + * Returns the specified element by ID or the input element if it isn't a string. + * + * @method get + * @param {String/Element} n Element id to look for or element to just pass though. + * @return {Element} Element matching the specified id or null if it wasn't found. + */ + get: function(elm) { + var name; + + if (elm && this.doc && typeof(elm) == 'string') { + name = elm; + elm = this.doc.getElementById(elm); + + // IE and Opera returns meta elements when they match the specified input ID, but getElementsByName seems to do the trick + if (elm && elm.id !== name) { + return this.doc.getElementsByName(name)[1]; + } + } + + return elm; + }, + + /** + * Returns the next node that matches selector or function + * + * @method getNext + * @param {Node} node Node to find siblings from. + * @param {String/function} selector Selector CSS expression or function. + * @return {Node} Next node item matching the selector or null if it wasn't found. + */ + getNext: function(node, selector) { + return this._findSib(node, selector, 'nextSibling'); + }, + + /** + * Returns the previous node that matches selector or function + * + * @method getPrev + * @param {Node} node Node to find siblings from. + * @param {String/function} selector Selector CSS expression or function. + * @return {Node} Previous node item matching the selector or null if it wasn't found. + */ + getPrev: function(node, selector) { + return this._findSib(node, selector, 'previousSibling'); + }, + + // #ifndef jquery + + /** + * Selects specific elements by a CSS level 3 pattern. For example "div#a1 p.test". + * This function is optimized for the most common patterns needed in TinyMCE but it also performes good enough + * on more complex patterns. + * + * @method select + * @param {String} selector CSS level 3 pattern to select/find elements by. + * @param {Object} scope Optional root element/scope element to search in. + * @return {Array} Array with all matched elements. + * @example + * // Adds a class to all paragraphs in the currently active editor + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass'); + * + * // Adds a class to all spans that has the test class in the currently active editor + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('span.test'), 'someclass') + */ + select: function(selector, scope) { + var self = this; + + //Sizzle.selectors.cacheLength = 0; + return Sizzle(selector, self.get(scope) || self.get(self.settings.root_element) || self.doc, []); + }, + + /** + * Returns true/false if the specified element matches the specified css pattern. + * + * @method is + * @param {Node/NodeList} elm DOM node to match or an array of nodes to match. + * @param {String} selector CSS pattern to match the element agains. + */ + is: function(elm, selector) { + var i; + + // If it isn't an array then try to do some simple selectors instead of Sizzle for to boost performance + if (elm.length === undefined) { + // Simple all selector + if (selector === '*') { + return elm.nodeType == 1; + } + + // Simple selector just elements + if (simpleSelectorRe.test(selector)) { + selector = selector.toLowerCase().split(/,/); + elm = elm.nodeName.toLowerCase(); + + for (i = selector.length - 1; i >= 0; i--) { + if (selector[i] == elm) { + return true; + } + } + + return false; + } + } + + return Sizzle.matches(selector, elm.nodeType ? [elm] : elm).length > 0; + }, + + // #endif + + /** + * Adds the specified element to another element or elements. + * + * @method add + * @param {String/Element/Array} parentElm Element id string, DOM node element or array of id's or elements to add to. + * @param {String/Element} name Name of new element to add or existing element to add. + * @param {Object} attrs Optional object collection with arguments to add to the new element(s). + * @param {String} html Optional inner HTML contents to add for each element. + * @return {Element/Array} Element that got created or array with elements if multiple elements where passed. + * @example + * // Adds a new paragraph to the end of the active editor + * tinymce.activeEditor.dom.add(tinymce.activeEditor.getBody(), 'p', {title: 'my title'}, 'Some content'); + */ + add: function(parentElm, name, attrs, html, create) { + var self = this; + + return this.run(parentElm, function(parentElm) { + var newElm; + + newElm = is(name, 'string') ? self.doc.createElement(name) : name; + self.setAttribs(newElm, attrs); + + if (html) { + if (html.nodeType) { + newElm.appendChild(html); + } else { + self.setHTML(newElm, html); + } + } + + return !create ? parentElm.appendChild(newElm) : newElm; + }); + }, + + /** + * Creates a new element. + * + * @method create + * @param {String} name Name of new element. + * @param {Object} attrs Optional object name/value collection with element attributes. + * @param {String} html Optional HTML string to set as inner HTML of the element. + * @return {Element} HTML DOM node element that got created. + * @example + * // Adds an element where the caret/selection is in the active editor + * var el = tinymce.activeEditor.dom.create('div', {id: 'test', 'class': 'myclass'}, 'some content'); + * tinymce.activeEditor.selection.setNode(el); + */ + create: function(name, attrs, html) { + return this.add(this.doc.createElement(name), name, attrs, html, 1); + }, + + /** + * Create HTML string for element. The element will be closed unless an empty inner HTML string is passed. + * + * @method createHTML + * @param {String} name Name of new element. + * @param {Object} attrs Optional object name/value collection with element attributes. + * @param {String} html Optional HTML string to set as inner HTML of the element. + * @return {String} String with new HTML element like for example: test. + * @example + * // Creates a html chunk and inserts it at the current selection/caret location + * tinymce.activeEditor.selection.setContent(tinymce.activeEditor.dom.createHTML('a', {href: 'test.html'}, 'some line')); + */ + createHTML: function(name, attrs, html) { + var outHtml = '', key; + + outHtml += '<' + name; + + for (key in attrs) { + if (attrs.hasOwnProperty(key)) { + outHtml += ' ' + key + '="' + this.encode(attrs[key]) + '"'; + } + } + + // A call to tinymce.is doesn't work for some odd reason on IE9 possible bug inside their JS runtime + if (typeof(html) != "undefined") { + return outHtml + '>' + html + ''; + } + + return outHtml + ' />'; + }, + + /** + * Creates a document fragment out of the specified HTML string. + * + * @method createFragment + * @param {String} html Html string to create fragment from. + * @return {DocumentFragment} Document fragment node. + */ + createFragment: function(html) { + var frag, node, doc = this.doc, container; + + container = doc.createElement("div"); + frag = doc.createDocumentFragment(); + + if (html) { + container.innerHTML = html; + } + + while ((node = container.firstChild)) { + frag.appendChild(node); + } + + return frag; + }, + + /** + * Removes/deletes the specified element(s) from the DOM. + * + * @method remove + * @param {String/Element/Array} node ID of element or DOM element object or array containing multiple elements/ids. + * @param {Boolean} keep_children Optional state to keep children or not. If set to true all children will be + * placed at the location of the removed element. + * @return {Element/Array} HTML DOM element that got removed or array of elements depending on input. + * @example + * // Removes all paragraphs in the active editor + * tinymce.activeEditor.dom.remove(tinymce.activeEditor.dom.select('p')); + * + * // Removes a element by id in the document + * tinymce.DOM.remove('mydiv'); + */ + 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 (!isIE || child.nodeType !== 3 || child.nodeValue) { + parent.insertBefore(child, node); + } else { + node.removeChild(child); + } + } + } + + return parent.removeChild(node); + }); + }, + + /** + * Sets the CSS style value on a HTML element. The name can be a camelcase string + * or the CSS style name like background-color. + * + * @method setStyle + * @param {String/Element/Array} n HTML element/Element ID or Array of elements/ids to set CSS style value on. + * @param {String} na Name of the style value to set. + * @param {String} v Value to set on the style. + * @example + * // Sets a style value on all paragraphs in the currently active editor + * tinymce.activeEditor.dom.setStyle(tinymce.activeEditor.dom.select('p'), 'background-color', 'red'); + * + * // Sets a style value to an element by id in the current document + * tinymce.DOM.setStyle('mydiv', 'background-color', 'red'); + */ + setStyle: function(elm, name, value) { + return this.run(elm, function(elm) { + var self = this, style, key; + + if (name) { + if (typeof(name) === 'string') { + style = elm.style; + + // Camelcase it, if needed + name = name.replace(/-(\D)/g, function(a, b) { + return b.toUpperCase(); + }); + + // Default px suffix on these + if (typeof(value) === 'number' && !numericCssMap[name]) { + value += 'px'; + } + + // IE specific opacity + if (name === "opacity" && elm.runtimeStyle && typeof(elm.runtimeStyle.opacity) === "undefined") { + style.filter = value === '' ? '' : "alpha(opacity=" + (value * 100) + ")"; + } + + try { + style[name] = value; + } catch (ex) { + // Ignore IE errors + } + + // Force update of the style data + if (self.settings.update_styles) { + elm.removeAttribute('data-mce-style'); + } + } else { + for (key in name) { + self.setStyle(elm, key, name[key]); + } + } + } + }); + }, + + /** + * Returns the current style or runtime/computed value of a element. + * + * @method getStyle + * @param {String/Element} elm HTML element or element id string to get style from. + * @param {String} name Style name to return. + * @param {Boolean} computed Computed style. + * @return {String} Current style or computed style value of a element. + */ + getStyle: function(elm, name, computed) { + elm = this.get(elm); + + if (!elm) { + return; + } + + // W3C + if (this.doc.defaultView && computed) { + // Remove camelcase + name = name.replace(/[A-Z]/g, function(a){ + return '-' + a; + }); + + try { + return this.doc.defaultView.getComputedStyle(elm, null).getPropertyValue(name); + } catch (ex) { + // Old safari might fail + return null; + } + } + + // Camelcase it, if needed + name = name.replace(/-(\D)/g, function(a, b) { + return b.toUpperCase(); + }); + + if (name == 'float') { + name = isIE ? 'styleFloat' : 'cssFloat'; + } + + // IE & Opera + if (name.currentStyle && computed) { + return elm.currentStyle[name]; + } + + return elm.style ? elm.style[name] : undefined; + }, + + /** + * Sets multiple styles on the specified element(s). + * + * @method setStyles + * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to set styles on. + * @param {Object} o Name/Value collection of style items to add to the element(s). + * @example + * // Sets styles on all paragraphs in the currently active editor + * tinymce.activeEditor.dom.setStyles(tinymce.activeEditor.dom.select('p'), {'background-color': 'red', 'color': 'green'}); + * + * // Sets styles to an element by id in the current document + * tinymce.DOM.setStyles('mydiv', {'background-color': 'red', 'color': 'green'}); + */ + setStyles: function(elm, styles) { + this.setStyle(elm, styles); + }, + + css: function(elm, name, value) { + this.setStyle(elm, name, value); + }, + + /** + * Removes all attributes from an element or elements. + * + * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to remove attributes from. + */ + 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)); + } + }); + }, + + /** + * Sets the specified attributes value of a element or elements. + * + * @method setAttrib + * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to set attribute on. + * @param {String} n Name of attribute to set. + * @param {String} v Value to set on the attribute of this value is falsy like null 0 or '' it will remove the attribute instead. + * @example + * // Sets an attribute to all paragraphs in the active editor + * tinymce.activeEditor.dom.setAttrib(tinymce.activeEditor.dom.select('p'), 'class', 'myclass'); + * + * // Sets an attribute to a specific element in the current page + * tinymce.dom.setAttrib('mydiv', 'class', 'myclass'); + */ + setAttrib: function(e, n, v) { + var t = this; + + // Whats the point + if (!e || !n) { + return; + } + + 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) { + 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 (originalValue != v && s.onSetAttrib) { + s.onSetAttrib({attrElm: e, attrName: n, attrValue: v}); + } + }); + }, + + /** + * Sets the specified attributes of a element or elements. + * + * @method setAttribs + * @param {Element/String/Array} elm DOM element, element id string or array of elements/ids to set attributes on. + * @param {Object} attrs Name/Value collection of attribute items to add to the element(s). + * @example + * // Sets some attributes to all paragraphs in the active editor + * tinymce.activeEditor.dom.setAttribs(tinymce.activeEditor.dom.select('p'), {'class': 'myclass', title: 'some title'}); + * + * // Sets some attributes to a specific element in the current page + * tinymce.DOM.setAttribs('mydiv', {'class': 'myclass', title: 'some title'}); + */ + setAttribs: function(elm, attrs) { + var self = this; + + return this.run(elm, function(elm) { + each(attrs, function(value, name) { + self.setAttrib(elm, name, value); + }); + }); + }, + + /** + * Returns the specified attribute by name. + * + * @method getAttrib + * @param {String/Element} elm Element string id or DOM element to get attribute from. + * @param {String} name Name of attribute to get. + * @param {String} defaultVal Optional default value to return if the attribute didn't exist. + * @return {String} Attribute value string, default value or null if the attribute wasn't found. + */ + getAttrib: function(elm, name, defaultVal) { + var value, self = this, undef; + + elm = self.get(elm); + + if (!elm || elm.nodeType !== 1) { + return defaultVal === undef ? false : defaultVal; + } + + if (!is(defaultVal)) { + defaultVal = ''; + } + + // Try the mce variant for these + if (/^(src|href|style|coords|shape)$/.test(name)) { + value = elm.getAttribute("data-mce-" + name); + + if (value) { + return value; + } + } + + if (isIE && self.props[name]) { + value = elm[self.props[name]]; + value = value && value.nodeValue ? value.nodeValue : value; + } + + if (!value) { + value = elm.getAttribute(name, 2); + } + + // Check boolean attribs + if (/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noshade|nowrap|readonly|selected)$/.test(name)) { + if (elm[self.props[name]] === true && value === '') { + return name; + } + + return value ? name : ''; + } + + // Inner input elements will override attributes on form elements + if (elm.nodeName === "FORM" && elm.getAttributeNode(name)) { + return elm.getAttributeNode(name).nodeValue; + } + + if (name === 'style') { + value = value || elm.style.cssText; + + if (value) { + value = self.serializeStyle(self.parseStyle(value), elm.nodeName); + + if (self.settings.keep_values) { + elm.setAttribute('data-mce-style', value); + } + } + } + + // Remove Apple and WebKit stuff + if (isWebKit && name === "class" && value) { + value = value.replace(/(apple|webkit)\-[a-z\-]+/gi, ''); + } + + // Handle IE issues + if (isIE) { + switch (name) { + case 'rowspan': + case 'colspan': + // IE returns 1 as default value + if (value === 1) { + value = ''; + } + + break; + + case 'size': + // IE returns +0 as default value for size + if (value === '+0' || value === 20 || value === 0) { + value = ''; + } + + break; + + case 'width': + case 'height': + case 'vspace': + case 'checked': + case 'disabled': + case 'readonly': + if (value === 0) { + value = ''; + } + + break; + + case 'hspace': + // IE returns -1 as default value + if (value === -1) { + value = ''; + } + + break; + + case 'maxlength': + case 'tabindex': + // IE returns default value + if (value === 32768 || value === 2147483647 || value === '32768') { + value = ''; + } + + break; + + case 'multiple': + case 'compact': + case 'noshade': + case 'nowrap': + if (value === 65535) { + return name; + } + + return defaultVal; + + case 'shape': + value = value.toLowerCase(); + break; + + default: + // IE has odd anonymous function for event attributes + if (name.indexOf('on') === 0 && value) { + value = ('' + value).replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/, '$1'); + } + } + } + + return (value !== undef && value !== null && value !== '') ? '' + value : defaultVal; + }, + + /** + * Returns the absolute x, y position of a node. The position will be returned in a object with x, y fields. + * + * @method getPos + * @param {Element/String} n HTML element or element id to get x, y position from. + * @param {Element} ro Optional root element to stop calculations at. + * @return {object} Absolute position of the specified element object with x, y fields. + */ + getPos: function(elm, rootElm) { + var self = this, x = 0, y = 0, offsetParent, doc = self.doc, pos; + + elm = self.get(elm); + rootElm = rootElm || doc.body; + + if (elm) { + // Use getBoundingClientRect if it exists since it's faster than looping offset nodes + if (rootElm === doc.body && elm.getBoundingClientRect) { + pos = elm.getBoundingClientRect(); + rootElm = self.boxModel ? doc.documentElement : doc.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 = pos.left + (doc.documentElement.scrollLeft || doc.body.scrollLeft) - rootElm.clientTop; + y = pos.top + (doc.documentElement.scrollTop || doc.body.scrollTop) - rootElm.clientLeft; + + return {x: x, y: y}; + } + + offsetParent = elm; + while (offsetParent && offsetParent != rootElm && offsetParent.nodeType) { + x += offsetParent.offsetLeft || 0; + y += offsetParent.offsetTop || 0; + offsetParent = offsetParent.offsetParent; + } + + offsetParent = elm.parentNode; + while (offsetParent && offsetParent != rootElm && offsetParent.nodeType) { + x -= offsetParent.scrollLeft || 0; + y -= offsetParent.scrollTop || 0; + offsetParent = offsetParent.parentNode; + } + } + + return {x: x, y: y}; + }, + + /** + * Parses the specified style value into an object collection. This parser will also + * merge and remove any redundant items that browsers might have added. It will also convert non hex + * colors to hex values. Urls inside the styles will also be converted to absolute/relative based on settings. + * + * @method parseStyle + * @param {String} cssText Style value to parse for example: border:1px solid red;. + * @return {Object} Object representation of that style like {border: '1px solid red'} + */ + parseStyle: function(cssText) { + return this.styles.parse(cssText); + }, + + /** + * Serializes the specified style object into a string. + * + * @method serializeStyle + * @param {Object} styles Object to serialize as string for example: {border: '1px solid red'} + * @param {String} name Optional element name. + * @return {String} String representation of the style object for example: border: 1px solid red. + */ + serializeStyle: function(styles, name) { + return this.styles.serialize(styles, name); + }, + + /** + * Adds a style element at the top of the document with the specified cssText content. + * + * @method addStyle + * @param {String} cssText CSS Text style to add to top of head of document. + */ + addStyle: function(cssText) { + var self = this, doc = self.doc, head, styleElm; + + // Prevent inline from loading the same styles twice + if (self !== DOMUtils.DOM && doc === document) { + var addedStyles = DOMUtils.DOM.addedStyles; + + addedStyles = addedStyles || []; + if (addedStyles[cssText]) { + return; + } + + addedStyles[cssText] = true; + DOMUtils.DOM.addedStyles = addedStyles; + } + + // Create style element if needed + styleElm = doc.getElementById('mceDefaultStyles'); + if (!styleElm) { + styleElm = doc.createElement('style'), + styleElm.id = 'mceDefaultStyles'; + styleElm.type = 'text/css'; + + head = doc.getElementsByTagName('head')[0]; + if (head.firstChild) { + head.insertBefore(styleElm, head.firstChild); + } else { + head.appendChild(styleElm); + } + } + + // Append style data to old or new style element + if (styleElm.styleSheet) { + styleElm.styleSheet.cssText += cssText; + } else { + styleElm.appendChild(doc.createTextNode(cssText)); + } + }, + + /** + * Imports/loads the specified CSS file into the document bound to the class. + * + * @method loadCSS + * @param {String} u URL to CSS file to load. + * @example + * // Loads a CSS file dynamically into the current document + * tinymce.DOM.loadCSS('somepath/some.css'); + * + * // Loads a CSS file into the currently active editor instance + * tinymce.activeEditor.dom.loadCSS('somepath/some.css'); + * + * // Loads a CSS file into an editor instance by id + * tinymce.get('someid').dom.loadCSS('somepath/some.css'); + * + * // Loads multiple CSS files into the current document + * tinymce.DOM.loadCSS('somepath/some.css,somepath/someother.css'); + */ + loadCSS: function(url) { + var self = this, doc = self.doc, head; + + // Prevent inline from loading the same CSS file twice + if (self !== DOMUtils.DOM && doc === document) { + DOMUtils.DOM.loadCSS(url); + return; + } + + if (!url) { + url = ''; + } + + head = doc.getElementsByTagName('head')[0]; + + each(url.split(','), function(url) { + var link; + + if (self.files[url]) { + return; + } + + self.files[url] = true; + link = self.create('link', {rel: 'stylesheet', href: url}); + + // 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 && doc.documentMode && doc.recalc) { + link.onload = function() { + if (doc.recalc) { + doc.recalc(); + } + + link.onload = null; + }; + } + + head.appendChild(link); + }); + }, + + /** + * Adds a class to the specified element or elements. + * + * @method addClass + * @param {String/Element/Array} elm Element ID string or DOM element or array with elements or IDs. + * @param {String} cls Class name to add to each element. + * @return {String/Array} String with new class value or array with new class values for all elements. + * @example + * // Adds a class to all paragraphs in the active editor + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'myclass'); + * + * // Adds a class to a specific element in the current page + * tinymce.DOM.addClass('mydiv', 'myclass'); + */ + addClass: function(elm, cls) { + return this.run(elm, function(elm) { + var clsVal; + + if (!cls) { + return 0; + } + + if (this.hasClass(elm, cls)) { + return elm.className; + } + + clsVal = this.removeClass(elm, cls); + elm.className = clsVal = (clsVal !== '' ? (clsVal + ' ') : '') + cls; + + return clsVal; + }); + }, + + /** + * Removes a class from the specified element or elements. + * + * @method removeClass + * @param {String/Element/Array} elm Element ID string or DOM element or array with elements or IDs. + * @param {String} cls Class name to remove to each element. + * @return {String/Array} String with new class value or array with new class values for all elements. + * @example + * // Removes a class from all paragraphs in the active editor + * tinymce.activeEditor.dom.removeClass(tinymce.activeEditor.dom.select('p'), 'myclass'); + * + * // Removes a class from a specific element in the current page + * tinymce.DOM.removeClass('mydiv', 'myclass'); + */ + removeClass: function(elm, cls) { + var self = this, re; + + return self.run(elm, function(elm) { + var val; + + if (self.hasClass(elm, cls)) { + if (!re) { + re = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", "g"); + } + + val = elm.className.replace(re, ' '); + val = trim(val != ' ' ? val : ''); + + elm.className = val; + + // Empty class attr + if (!val) { + elm.removeAttribute('class'); + elm.removeAttribute('className'); + } + + return val; + } + + return elm.className; + }); + }, + + /** + * Returns true if the specified element has the specified class. + * + * @method hasClass + * @param {String/Element} n HTML element or element id string to check CSS class on. + * @param {String} c CSS class to check for. + * @return {Boolean} true/false if the specified element has the specified class. + */ + hasClass: function(elm, cls) { + elm = this.get(elm); + + if (!elm || !cls) { + return false; + } + + return (' ' + elm.className + ' ').indexOf(' ' + cls + ' ') !== -1; + }, + + /** + * Toggles the specified class on/off. + * + * @method toggleClass + * @param {Element} elm Element to toggle class on. + * @param {[type]} cls Class to toggle on/off. + * @param {[type]} state Optional state to set. + */ + toggleClass: function(elm, cls, state) { + state = state === undefined ? !this.hasClass(elm, cls) : state; + + if (this.hasClass(elm, cls) !== state) { + if (state) { + this.addClass(elm, cls); + } else { + this.removeClass(elm, cls); + } + } + }, + + /** + * Shows the specified element(s) by ID by setting the "display" style. + * + * @method show + * @param {String/Element/Array} elm ID of DOM element or DOM element or array with elements or IDs to show. + */ + show: function(elm) { + return this.setStyle(elm, 'display', 'block'); + }, + + /** + * Hides the specified element(s) by ID by setting the "display" style. + * + * @method hide + * @param {String/Element/Array} e ID of DOM element or DOM element or array with elements or IDs to hide. + * @example + * // Hides a element by id in the document + * tinymce.DOM.hide('myid'); + */ + hide: function(elm) { + return this.setStyle(elm, 'display', 'none'); + }, + + /** + * Returns true/false if the element is hidden or not by checking the "display" style. + * + * @method isHidden + * @param {String/Element} e Id or element to check display state on. + * @return {Boolean} true/false if the element is hidden or not. + */ + isHidden: function(elm) { + elm = this.get(elm); + + return !elm || elm.style.display == 'none' || this.getStyle(elm, 'display') == 'none'; + }, + + /** + * Returns a unique id. This can be useful when generating elements on the fly. + * This method will not check if the element allready exists. + * + * @method uniqueId + * @param {String} prefix Optional prefix to add infront of all ids defaults to "mce_". + * @return {String} Unique id. + */ + uniqueId: function(prefix) { + return (!prefix ? 'mce_' : prefix) + (this.counter++); + }, + + /** + * Sets the specified HTML content inside the element or elements. The HTML will first be processed this means + * URLs will get converted, hex color values fixed etc. Check processHTML for details. + * + * @method setHTML + * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to set HTML inside. + * @param {String} h HTML content to set as inner HTML of the element. + * @example + * // Sets the inner HTML of all paragraphs in the active editor + * tinymce.activeEditor.dom.setHTML(tinymce.activeEditor.dom.select('p'), 'some inner html'); + * + * // Sets the inner HTML of a element by id in the document + * tinymce.DOM.setHTML('mydiv', 'some inner html'); + */ + 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 = '
    ' + 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 + var newElement = self.create('div'); + newElement.innerHTML = '
    ' + html; + + // Add all children from div to target + each (grep(newElement.childNodes), function(node, i) { + // Skip br element + if (i && element.canHaveHTML) { + element.appendChild(node); + } + }); + } + } else { + element.innerHTML = html; + } + + return html; + }); + }, + + /** + * Returns the outer HTML of an element. + * + * @method getOuterHTML + * @param {String/Element} elm Element ID or element object to get outer HTML from. + * @return {String} Outer HTML string. + * @example + * tinymce.DOM.getOuterHTML(editorElement); + * tinymce.activeEditor.getOuterHTML(tinymce.activeEditor.getBody()); + */ + 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; + }, + + /** + * Sets the specified outer HTML on a element or elements. + * + * @method setOuterHTML + * @param {Element/String/Array} elm DOM element, element id string or array of elements/ids to set outer HTML on. + * @param {Object} html HTML code to set as outer value for the element. + * @param {Document} doc Optional document scope to use in this process defaults to the document of the DOM class. + * @example + * // Sets the outer HTML of all paragraphs in the active editor + * tinymce.activeEditor.dom.setOuterHTML(tinymce.activeEditor.dom.select('p'), '
    some html
    '); + * + * // Sets the outer HTML of a element by id in the document + * tinymce.DOM.setOuterHTML('mydiv', '
    some html
    '); + */ + setOuterHTML: function(elm, html, doc) { + var self = this; + + return self.run(elm, function(elm) { + function set() { + var node, tempElm; + + tempElm = doc.createElement("body"); + tempElm.innerHTML = html; + + node = tempElm.lastChild; + while (node) { + self.insertAfter(node.cloneNode(true), elm); + node = node.previousSibling; + } + + self.remove(elm); + } + + // Only set HTML on elements + if (elm.nodeType == 1) { + doc = doc || elm.ownerDocument || self.doc; + + if (isIE) { + try { + // Try outerHTML for IE it sometimes produces an unknown runtime error + if (elm.nodeType == 1 && self.hasOuterHTML) { + elm.outerHTML = html; + } else { + set(); + } + } catch (ex) { + // Fix for unknown runtime error + set(); + } + } else { + set(); + } + } + }); + }, + + /** + * Entity decode a string, resolves any HTML entities like å. + * + * @method decode + * @param {String} s String to decode entities on. + * @return {String} Entity decoded string. + */ + decode: Entities.decode, + + /** + * Entity encodes a string, encodes the most common entities <>"& into entities. + * + * @method encode + * @param {String} text String to encode with entities. + * @return {String} Entity encoded string. + */ + encode: Entities.encodeAllRaw, + + /** + * Inserts a element after the reference element. + * + * @method insertAfter + * @param {Element} node Element to insert after the reference. + * @param {Element/String/Array} reference_node Reference element, element id or array of elements to insert after. + * @return {Element/Array} Element that got added or an array with elements. + */ + 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; + }); + }, + + /** + * Replaces the specified element or elements with the specified element, the new element will + * be cloned if multiple inputs elements are passed. + * + * @method replace + * @param {Element} newElm New element to replace old ones with. + * @param {Element/String/Array} oldELm Element DOM node, element id or array of elements or ids to replace. + * @param {Boolean} k Optional keep children state, if set to true child nodes from the old object will be added to new ones. + */ + replace: function(newElm, oldElm, keepChildren) { + var self = this; + + return self.run(oldElm, function(oldElm) { + if (is(oldElm, 'array')) { + newElm = newElm.cloneNode(true); + } + + if (keepChildren) { + each(grep(oldElm.childNodes), function(node) { + newElm.appendChild(node); + }); + } + + return oldElm.parentNode.replaceChild(newElm, oldElm); + }); + }, + + /** + * Renames the specified element to a new name and keep it's attributes and children. + * + * @method rename + * @param {Element} elm Element to rename. + * @param {String} name Name of the new element. + * @return New element or the old element if it needed renaming. + */ + rename: function(elm, name) { + var self = this, newElm; + + if (elm.nodeName != name.toUpperCase()) { + // Rename block element + newElm = self.create(name); + + // Copy attribs to new block + each(self.getAttribs(elm), function(attr_node) { + self.setAttrib(newElm, attr_node.nodeName, self.getAttrib(elm, attr_node.nodeName)); + }); + + // Replace block + self.replace(newElm, elm, 1); + } + + return newElm || elm; + }, + + /** + * Find the common ancestor of two elements. This is a shorter method than using the DOM Range logic. + * + * @method findCommonAncestor + * @param {Element} a Element to find common ancestor of. + * @param {Element} b Element to find common ancestor of. + * @return {Element} Common ancestor element of the two input elements. + */ + 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; + }, + + /** + * Parses the specified RGB color value and returns a hex version of that color. + * + * @method toHex + * @param {String} rgbVal RGB string value like rgb(1,2,3) + * @return {String} Hex version of that RGB value like #FF00FF. + */ + toHex: function(rgbVal) { + return this.styles.toHex(Tools.trim(rgbVal)); + }, + + /** + * Returns a array of all single CSS classes in the document. A single CSS class is a simple + * rule like ".class" complex ones like "div td.class" will not be added to output. + * + * @method getClasses + * @return {Array} Array with class objects each object has a class field might be other fields in the future. + */ + getClasses: function() { + var self = this, classList = [], lookup = {}, filter = self.settings.class_filter, oldVal; + + if (self.classes) { + return self.classes; + } + + function addClasses(stylesheet) { + // IE style imports + each(stylesheet.imports, function(r) { + addClasses(r); + }); + + each(stylesheet.cssRules || stylesheet.rules, function(rule) { + // Real type or fake it on IE + switch (rule.type || 1) { + // Rule + case 1: + if (rule.selectorText) { + each(rule.selectorText.split(','), function(value) { + value = value.replace(/^\s*|\s*$|^\s\./g, ""); + + // Is internal or it doesn't contain a class + if (/\.mce/.test(value) || !/\.[\w\-]+$/.test(value)) { + return; + } + + // Remove everything but class name + oldVal = value; + value = value.replace(/.*\.([a-z0-9_\-]+).*/i, '$1'); + + // Filter classes + if (filter && !(value = filter(value, oldVal))) { + return; + } + + if (!lookup[value]) { + classList.push({'class': value}); + lookup[value] = 1; + } + }); + } + break; + + // Import + case 3: + addClasses(rule.styleSheet); + break; + } + }); + } + + try { + each(self.doc.styleSheets, addClasses); + } catch (ex) { + // Ignore + } + + if (classList.length > 0) { + self.classes = classList; + } + + return classList; + }, + + /** + * Executes the specified function on the element by id or dom element node or array of elements/id. + * + * @method run + * @param {String/Element/Array} Element ID or DOM element object or array with ids or elements. + * @param {function} f Function to execute for each item. + * @param {Object} s Optional scope to execute the function in. + * @return {Object/Array} Single object or array with objects depending on multiple input or not. + */ + run: function(elm, func, scope) { + var self = this, result; + + if (typeof(elm) === 'string') { + elm = self.get(elm); + } + + if (!elm) { + return false; + } + + scope = scope || this; + if (!elm.nodeType && (elm.length || elm.length === 0)) { + result = []; + + each(elm, function(elm, i) { + if (elm) { + if (typeof(elm) == 'string') { + elm = self.get(elm); + } + + result.push(func.call(scope, elm, i)); + } + }); + + return result; + } + + return func.call(scope, elm); + }, + + /** + * Returns an NodeList with attributes for the element. + * + * @method getAttribs + * @param {HTMLElement/string} elm Element node or string id to get attributes from. + * @return {NodeList} NodeList with attributes. + */ + getAttribs: function(elm) { + var attrs; + + elm = this.get(elm); + + if (!elm) { + return []; + } + + if (isIE) { + attrs = []; + + // Object will throw exception in IE + if (elm.nodeName == 'OBJECT') { + return elm.attributes; + } + + // IE doesn't keep the selected attribute if you clone option elements + if (elm.nodeName === 'OPTION' && this.getAttrib(elm, 'selected')) { + attrs.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 + var attrRegExp = /<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi; + elm.cloneNode(false).outerHTML.replace(attrRegExp, '').replace(/[\w:\-]+/gi, function(a) { + attrs.push({specified: 1, nodeName: a}); + }); + + return attrs; + } + + return elm.attributes; + }, + + /** + * Returns true/false if the specified node is to be considered empty or not. + * + * @example + * tinymce.DOM.isEmpty(node, {img: true}); + * @method isEmpty + * @param {Object} elements Optional name/value object with elements that are automatically treated as non empty elements. + * @return {Boolean} true/false if the node is empty or not. + */ + isEmpty: function(node, elements) { + var self = this, i, attributes, type, walker, name, brCount = 0; + + node = node.firstChild; + if (node) { + walker = new 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 + name = node.nodeName.toLowerCase(); + if (elements && elements[name]) { + // Ignore single BR elements in blocks like


    or


    + if (name === 'br') { + brCount++; + continue; + } + + return false; + } + + // Keep elements with data-bookmark attributes or name attribute like + 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; + }, + + /** + * Created a new DOM Range object. This will use the native DOM Range API if it's + * available if it's not it will fallback to the custom TinyMCE implementation. + * + * @method createRng + * @return {DOMRange} DOM Range object. + * @example + * var rng = tinymce.DOM.createRng(); + * alert(rng.startContainer + "," + rng.startOffset); + */ + createRng: function() { + var doc = this.doc; + + return doc.createRange ? doc.createRange() : new Range(this); + }, + + /** + * Returns the index of the specified node within it's parent. + * + * @param {Node} node Node to look for. + * @param {boolean} normalized Optional true/false state if the index is what it would be after a normalization. + * @return {Number} Index of the specified node. + */ + 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; + }, + + /** + * Splits an element into two new elements and places the specified split + * element or element between the new ones. For example splitting the paragraph at the bold element in + * this example

    abcabc123

    would produce

    abc

    abc

    123

    . + * + * @method split + * @param {Element} parentElm Parent element to split. + * @param {Element} splitElm Element to split at. + * @param {Element} replacementElm Optional replacement element to replace the split element by. + * @return {Element} Returns the split element or the replacement element if that is specified. + */ + split: function(parentElm, splitElm, replacementElm) { + var self = this, r = self.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: + //

    text 1CHOPtext 2

    + // would produce: + //

    text 1

    CHOP

    text 2

    + // this function will then trim of empty edges and produce: + //

    text 1

    CHOP

    text 2

    + function trimNode(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--) { + trimNode(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 "

    " + // Also keep text nodes with only spaces if surrounded by spans. + // eg. "

    a b

    " should keep space between a and b + var trimmedLength = trim(node.nodeValue).length; + if (!self.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; + + // TODO fix this complex if + 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; + } + } + + self.remove(node); + } + + return node; + } + + if (parentElm && splitElm) { + // Get before chunk + r.setStart(parentElm.parentNode, self.nodeIndex(parentElm)); + r.setEnd(splitElm.parentNode, self.nodeIndex(splitElm)); + bef = r.extractContents(); + + // Get after chunk + r = self.createRng(); + r.setStart(splitElm.parentNode, self.nodeIndex(splitElm) + 1); + r.setEnd(parentElm.parentNode, self.nodeIndex(parentElm) + 1); + aft = r.extractContents(); + + // Insert before chunk + pa = parentElm.parentNode; + pa.insertBefore(trimNode(bef), parentElm); + + // Insert middle chunk + if (replacementElm) { + pa.replaceChild(replacementElm, splitElm); + } else { + pa.insertBefore(splitElm, parentElm); + } + + // Insert after chunk + pa.insertBefore(trimNode(aft), parentElm); + self.remove(parentElm); + + return replacementElm || splitElm; + } + }, + + /** + * Adds an event handler to the specified object. + * + * @method bind + * @param {Element/Document/Window/Array/String} o Object or element id string to add event + * handler to or an array of elements/ids/documents. + * @param {String} n Name of event handler to add for example: click. + * @param {function} f Function to execute when the event occurs. + * @param {Object} s Optional scope to execute the function in. + * @return {function} Function callback handler the same as the one passed in. + */ + bind: function(target, name, func, scope) { + return this.events.bind(target, name, func, scope || this); + }, + + /** + * Removes the specified event handler by name and function from a element or collection of elements. + * + * @method unbind + * @param {String/Element/Array} o Element ID string or HTML element or an array of elements or ids to remove handler from. + * @param {String} n Event handler name like for example: "click" + * @param {function} f Function to remove. + * @return {bool/Array} Bool state if true if the handler was removed or an array with states if multiple elements where passed in. + */ + unbind: function(target, name, func) { + return this.events.unbind(target, name, func); + }, + + /** + * Fires the specified event name with object on target. + * + * @method fire + * @param {Node/Document/Window} target Target element or object to fire event on. + * @param {String} name Name of the event to fire. + * @param {Object} evt Event object to send. + * @return {Event} Event object. + */ + 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; + }, + + /** + * Destroys all internal references to the DOM to solve IE leak issues. + * + * @method destroy + */ + destroy: function() { + var self = this; + + self.win = self.doc = self.root = self.events = self.frag = null; + }, + + // #ifdef debug + + dumpRng: function(r) { + return ( + 'startContainer: ' + r.startContainer.nodeName + + ', startOffset: ' + r.startOffset + + ', endContainer: ' + r.endContainer.nodeName + + ', endOffset: ' + r.endOffset + ); + }, + + // #endif + + _findSib: function(node, selector, name) { + var self = this, func = selector; + + if (node) { + // If expression make a function of it using is + if (typeof(func) == 'string') { + func = function(node) { + return self.is(node, selector); + }; + } + + // Loop all siblings + for (node = node[name]; node; node = node[name]) { + if (func(node)) { + return node; + } + } + } + + return null; + } + }; + + /** + * Instance of DOMUtils for the current document. + * + * @property DOM + * @member tinymce + * @type tinymce.dom.DOMUtils + * @example + * // Example of how to add a class to some element by id + * tinymce.DOM.addClass('someid', 'someclass'); + */ + DOMUtils.DOM = new DOMUtils(document); + + return DOMUtils; +}); + +// Included from: js/tinymce/classes/dom/ScriptLoader.js + +/** + * ScriptLoader.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*globals console*/ + +/** + * This class handles asynchronous/synchronous loading of JavaScript files it will execute callbacks + * when various items gets loaded. This class is useful to load external JavaScript files. + * + * @class tinymce.dom.ScriptLoader + * @example + * // Load a script from a specific URL using the global script loader + * tinymce.ScriptLoader.load('somescript.js'); + * + * // Load a script using a unique instance of the script loader + * var scriptLoader = new tinymce.dom.ScriptLoader(); + * + * scriptLoader.load('somescript.js'); + * + * // Load multiple scripts + * var scriptLoader = new tinymce.dom.ScriptLoader(); + * + * scriptLoader.add('somescript1.js'); + * scriptLoader.add('somescript2.js'); + * scriptLoader.add('somescript3.js'); + * + * scriptLoader.loadQueue(function() { + * alert('All scripts are now loaded.'); + * }); + */ +define("tinymce/dom/ScriptLoader", [ + "tinymce/dom/DOMUtils", + "tinymce/util/Tools" +], function(DOMUtils, Tools) { + var DOM = DOMUtils.DOM; + var each = Tools.each, grep = Tools.grep; + + function ScriptLoader() { + var QUEUED = 0, + LOADING = 1, + LOADED = 2, + states = {}, + queue = [], + scriptLoadedCallbacks = {}, + queueLoadedCallbacks = [], + loading = 0, + undef; + + /** + * Loads a specific script directly without adding it to the load queue. + * + * @method load + * @param {String} url Absolute URL to script to add. + * @param {function} callback Optional callback function to execute ones this script gets loaded. + * @param {Object} scope Optional scope to execute callback in. + */ + function loadScript(url, callback) { + var dom = DOM, elm, 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(); + + // Create new script element + elm = document.createElement('script'); + elm.id = id; + elm.type = 'text/javascript'; + elm.src = url; + + elm.onload = done; + elm.onreadystatechange = function() { + if (/loaded|complete/.test(elm.readyState)) { + done(); + } + }; + + // Add onerror event will get fired on some browsers but not all of them + elm.onerror = error; + + // Add script to document + (document.getElementsByTagName('head')[0] || document.body).appendChild(elm); + } + + /** + * Returns true/false if a script has been loaded or not. + * + * @method isDone + * @param {String} url URL to check for. + * @return [Boolean} true/false if the URL is loaded. + */ + this.isDone = function(url) { + return states[url] == LOADED; + }; + + /** + * Marks a specific script to be loaded. This can be useful if a script got loaded outside + * the script loader or to skip it from loading some script. + * + * @method markDone + * @param {string} u Absolute URL to the script to mark as loaded. + */ + this.markDone = function(url) { + states[url] = LOADED; + }; + + /** + * Adds a specific script to the load queue of the script loader. + * + * @method add + * @param {String} url Absolute URL to script to add. + * @param {function} callback Optional callback function to execute ones this script gets loaded. + * @param {Object} scope Optional scope to execute callback in. + */ + this.add = this.load = function(url, callback, scope) { + var 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 + }); + } + }; + + /** + * Starts the loading of the queue. + * + * @method loadQueue + * @param {function} callback Optional callback to execute when all queued items are loaded. + * @param {Object} scope Optional scope to execute the callback in. + */ + this.loadQueue = function(callback, scope) { + this.loadScripts(queue, callback, scope); + }; + + /** + * Loads the specified queue of files and executes the callback ones they are loaded. + * This method is generally not used outside this class but it might be useful in some scenarios. + * + * @method loadScripts + * @param {Array} scripts Array of queue items to load. + * @param {function} callback Optional callback to execute ones all items are loaded. + * @param {Object} scope Optional scope to execute callback in. + */ + this.loadScripts = function(scripts, callback, scope) { + var loadScripts; + + function execScriptLoadedCallbacks(url) { + // Execute URL callback functions + each(scriptLoadedCallbacks[url], function(callback) { + callback.func.call(callback.scope); + }); + + scriptLoadedCallbacks[url] = undef; + } + + queueLoadedCallbacks.push({ + func: callback, + scope: scope || this + }); + + loadScripts = function() { + var loadingScripts = grep(scripts); + + // Current scripts has been handled + scripts.length = 0; + + // Load scripts that needs to be loaded + 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) { + each(queueLoadedCallbacks, function(callback) { + callback.func.call(callback.scope); + }); + + queueLoadedCallbacks.length = 0; + } + }; + + loadScripts(); + }; + } + + ScriptLoader.ScriptLoader = new ScriptLoader(); + + return ScriptLoader; +}); + +// Included from: js/tinymce/classes/AddOnManager.js + +/** + * AddOnManager.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles the loading of themes/plugins or other add-ons and their language packs. + * + * @class tinymce.AddOnManager + */ +define("tinymce/AddOnManager", [ + "tinymce/dom/ScriptLoader", + "tinymce/util/Tools" +], function(ScriptLoader, Tools) { + var each = Tools.each; + + function AddOnManager() { + var self = this; + + self.items = []; + self.urls = {}; + self.lookup = {}; + } + + AddOnManager.prototype = { + /** + * Returns the specified add on by the short name. + * + * @method get + * @param {String} name Add-on to look for. + * @return {tinymce.Theme/tinymce.Plugin} Theme or plugin add-on instance or undefined. + */ + get: function(name) { + if (this.lookup[name]) { + return this.lookup[name].instance; + } else { + return undefined; + } + }, + + dependencies: function(name) { + var result; + + if (this.lookup[name]) { + result = this.lookup[name].dependencies; + } + + return result || []; + }, + + /** + * Loads a language pack for the specified add-on. + * + * @method requireLangPack + * @param {String} name Short name of the add-on. + */ + requireLangPack: function(name) { + var settings = AddOnManager.settings; + + if (settings && settings.language && settings.language_load !== false) { + ScriptLoader.ScriptLoader.add(this.urls[name] + '/langs/' + settings.language + '.js'); + } + }, + + /** + * Adds a instance of the add-on by it's short name. + * + * @method add + * @param {String} id Short name/id for the add-on. + * @param {tinymce.Theme/tinymce.Plugin} addOn Theme or plugin to add. + * @return {tinymce.Theme/tinymce.Plugin} The same theme or plugin instance that got passed in. + * @example + * // Create a simple plugin + * tinymce.create('tinymce.plugins.TestPlugin', { + * TestPlugin: function(ed, url) { + * ed.on('click', function(e) { + * ed.windowManager.alert('Hello World!'); + * }); + * } + * }); + * + * // Register plugin using the add method + * tinymce.PluginManager.add('test', tinymce.plugins.TestPlugin); + * + * // Initialize TinyMCE + * tinymce.init({ + * ... + * plugins: '-test' // Init the plugin but don't try to load it + * }); + */ + add: function(id, addOn, dependencies) { + this.items.push(addOn); + this.lookup[id] = {instance: addOn, dependencies: dependencies}; + + return addOn; + }, + + createUrl: function(baseUrl, dep) { + if (typeof dep === "object") { + return dep; + } else { + return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix}; + } + }, + + /** + * Add a set of components that will make up the add-on. Using the url of the add-on name as the base url. + * This should be used in development mode. A new compressor/javascript munger process will ensure that the + * components are put together into the plugin.js file and compressed correctly. + * @param pluginName {String} name of the plugin to load scripts from (will be used to get the base url for the plugins). + * @param scripts {Array} Array containing the names of the scripts to load. + */ + addComponents: function(pluginName, scripts) { + var pluginUrl = this.urls[pluginName]; + + each(scripts, function(script) { + ScriptLoader.ScriptLoader.add(pluginUrl + "/" + script); + }); + }, + + /** + * Loads an add-on from a specific url. + * + * @method load + * @param {String} n Short name of the add-on that gets loaded. + * @param {String} u URL to the add-on that will get loaded. + * @param {function} cb Optional callback to execute ones the add-on is loaded. + * @param {Object} s Optional scope to execute the callback in. + * @example + * // Loads a plugin from an external URL + * tinymce.PluginManager.load('myplugin', '/some/dir/someplugin/plugin.js'); + * + * // Initialize TinyMCE + * tinymce.init({ + * ... + * plugins: '-myplugin' // Don't try to load it again + * }); + */ + load: function(n, u, cb, s) { + var t = this, url = u; + + function loadDependencies() { + var dependencies = t.dependencies(n); + + 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(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 = AddOnManager.baseURL + '/' + url; + } + + t.urls[n] = url.substring(0, url.lastIndexOf('/')); + + if (t.lookup[n]) { + loadDependencies(); + } else { + ScriptLoader.ScriptLoader.add(url, loadDependencies, s); + } + } + }; + + AddOnManager.PluginManager = new AddOnManager(); + AddOnManager.ThemeManager = new AddOnManager(); + + return AddOnManager; +}); + +/** + * TinyMCE theme class. + * + * @class tinymce.Theme + */ + +/** + * Initializes the theme. + * + * @method init + * @param {tinymce.Editor} editor Editor instance that created the theme instance. + * @param {String} url Absolute URL where the theme is located. + */ + +/** + * Meta info method, this method gets executed when TinyMCE wants to present + * information about the theme for example in the about/help dialog. + * + * @method getInfo + * @return {Object} Returns an object with meta information about the theme the current items are + * longname, author, authorurl, infourl and version. + */ + +/** + * This method is responsible for rendering/generating the overall user interface with toolbars, buttons, iframe containers etc. + * + * @method renderUI + * @param {Object} obj Object parameter containing the targetNode DOM node that will be replaced visually with an editor instance. + * @return {Object} an object with items like iframeContainer, editorContainer, sizeContainer, deltaWidth, deltaHeight. + */ + +/** + * Plugin base class, this is a pseudo class that describes how a plugin is to be created for TinyMCE. The methods below are all optional. + * + * @class tinymce.Plugin + * @example + * // Create a new plugin class + * tinymce.create('tinymce.plugins.ExamplePlugin', { + * init: function(ed, url) { + * // Register an example button + * ed.addButton('example', { + * title: 'example.desc', + * onclick: function() { + * // Display an alert when the user clicks the button + * ed.windowManager.alert('Hello world!'); + * }, + * 'class': 'bold' // Use the bold icon from the theme + * }); + * } + * }); + * + * // Register plugin with a short name + * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); + * + * // Initialize TinyMCE with the new plugin and button + * tinymce.init({ + * ... + * plugins: '-example', // - means TinyMCE will not try to load it + * theme_advanced_buttons1: 'example' // Add the new example button to the toolbar + * }); + */ + +/** + * Initialization function for the plugin. This will be called when the plugin is created. + * + * @method init + * @param {tinymce.Editor} editor Editor instance that created the plugin instance. + * @param {String} url Absolute URL where the plugin is located. + * @example + * // Creates a new plugin class + * tinymce.create('tinymce.plugins.ExamplePlugin', { + * init: function(ed, url) { + * // Register the command so that it can be invoked by using tinymce.activeEditor.execCommand('mceExample'); + * ed.addCommand('mceExample', function() { + * ed.windowManager.open({ + * file: url + '/dialog.htm', + * width: 320 + ed.getLang('example.delta_width', 0), + * height: 120 + ed.getLang('example.delta_height', 0), + * inline: 1 + * }, { + * plugin_url: url, // Plugin absolute URL + * some_custom_arg: 'custom arg' // Custom argument + * }); + * }); + * + * // Register example button + * ed.addButton('example', { + * title: 'example.desc', + * cmd: 'mceExample', + * image: url + '/img/example.gif' + * }); + * + * // Add a node change handler, selects the button in the UI when a image is selected + * ed.on('NodeChange', function(e) { + * cm.setActive('example', e.element.nodeName == 'IMG'); + * }); + * } + * }); + * + * // Register plugin + * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); + */ + +/** + * Meta info method, this method gets executed when TinyMCE wants to present information about the plugin + * for example in the about/help dialog. + * + * @method getInfo + * @return {Object} Returns an object with meta information about the plugin the current items are longname, + * author, authorurl, infourl and version. + * @example + * // Creates a new plugin class + * tinymce.create('tinymce.plugins.ExamplePlugin', { + * // Meta info method + * getInfo: function() { + * return { + * longname: 'Example plugin', + * author: 'Some author', + * authorurl: 'http://www.tinymce.com', + * infourl: 'http://www.tinymce.com/wiki.php/Plugin:Plugins/example', + * version: "1.0" + * }; + * } + * }); + * + * // Register plugin + * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); + * + * // Initialize TinyMCE with the new plugin + * tinymce.init({ + * ... + * plugins: '-example' // - means TinyMCE will not try to load it + * }); + */ + +/** + * Gets called when a new control instance is created. + * + * @method createControl + * @param {String} name Control name to create for example "mylistbox" + * @param {tinymce.ControlManager} controlman Control manager/factory to use to create the control. + * @return {tinymce.ui.Control} Returns a new control instance or null. + * @example + * // Creates a new plugin class + * tinymce.create('tinymce.plugins.ExamplePlugin', { + * createControl: function(n, cm) { + * switch (n) { + * case 'mylistbox': + * var mlb = cm.createListBox('mylistbox', { + * title: 'My list box', + * onselect: function(v) { + * tinymce.activeEditor.windowManager.alert('Value selected:' + v); + * } + * }); + * + * // Add some values to the list box + * mlb.add('Some item 1', 'val1'); + * mlb.add('some item 2', 'val2'); + * mlb.add('some item 3', 'val3'); + * + * // Return the new listbox instance + * return mlb; + * } + * + * return null; + * } + * }); + * + * // Register plugin + * tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); + * + * // Initialize TinyMCE with the new plugin and button + * tinymce.init({ + * ... + * plugins: '-example', // - means TinyMCE will not try to load it + * theme_advanced_buttons1: 'mylistbox' // Add the new mylistbox control to the toolbar + * }); + */ + +// Included from: js/tinymce/classes/html/Node.js + +/** + * Node.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is a minimalistic implementation of a DOM like node used by the DomParser class. + * + * @example + * var node = new tinymce.html.Node('strong', 1); + * someRoot.append(node); + * + * @class tinymce.html.Node + * @version 3.4 + */ +define("tinymce/html/Node", [], function() { + 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; + } + } + } + } + + /** + * Constructs a new Node instance. + * + * @constructor + * @method Node + * @param {String} name Name of the node type. + * @param {Number} type Numeric type representing the node. + */ + function Node(name, type) { + this.name = name; + this.type = type; + + if (type === 1) { + this.attributes = []; + this.attributes.map = {}; + } + } + + Node.prototype = { + /** + * Replaces the current node with the specified one. + * + * @example + * someNode.replace(someNewNode); + * + * @method replace + * @param {tinymce.html.Node} node Node to replace the current node with. + * @return {tinymce.html.Node} The old node that got replaced. + */ + replace: function(node) { + var self = this; + + if (node.parent) { + node.remove(); + } + + self.insert(node, self); + self.remove(); + + return self; + }, + + /** + * Gets/sets or removes an attribute by name. + * + * @example + * someNode.attr("name", "value"); // Sets an attribute + * console.log(someNode.attr("name")); // Gets an attribute + * someNode.attr("name", null); // Removes an attribute + * + * @method attr + * @param {String} name Attribute name to set or get. + * @param {String} value Optional value to set. + * @return {String/tinymce.html.Node} String or undefined on a get operation or the current node on a set operation. + */ + 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]; + } + } + }, + + /** + * Does a shallow clones the node into a new node. It will also exclude id attributes since + * there should only be one id per document. + * + * @example + * var clonedNode = node.clone(); + * + * @method clone + * @return {tinymce.html.Node} New copy of the original node. + */ + 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; + }, + + /** + * Wraps the node in in another node. + * + * @example + * node.wrap(wrapperNode); + * + * @method wrap + */ + wrap: function(wrapper) { + var self = this; + + self.parent.insert(wrapper, self); + wrapper.append(self); + + return self; + }, + + /** + * Unwraps the node in other words it removes the node but keeps the children. + * + * @example + * node.unwrap(); + * + * @method unwrap + */ + unwrap: function() { + var self = this, node, next; + + for (node = self.firstChild; node; ) { + next = node.next; + self.insert(node, self, true); + node = next; + } + + self.remove(); + }, + + /** + * Removes the node from it's parent. + * + * @example + * node.remove(); + * + * @method remove + * @return {tinymce.html.Node} Current node that got removed. + */ + 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; + }, + + /** + * Appends a new node as a child of the current node. + * + * @example + * node.append(someNode); + * + * @method append + * @param {tinymce.html.Node} node Node to append as a child of the current one. + * @return {tinymce.html.Node} The node that got appended. + */ + 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; + }, + + /** + * Inserts a node at a specific position as a child of the current node. + * + * @example + * parentNode.insert(newChildNode, oldChildNode); + * + * @method insert + * @param {tinymce.html.Node} node Node to insert as a child of the current node. + * @param {tinymce.html.Node} ref_node Reference node to set node before/after. + * @param {Boolean} before Optional state to insert the node before the reference node. + * @return {tinymce.html.Node} The node that got inserted. + */ + 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; + }, + + /** + * Get all children by name. + * + * @method getAll + * @param {String} name Name of the child nodes to collect. + * @return {Array} Array with child nodes matchin the specified name. + */ + 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; + }, + + /** + * Removes all children of the current node. + * + * @method empty + * @return {tinymce.html.Node} The current node that got cleared. + */ + 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; + }, + + /** + * Returns true/false if the node is to be considered empty or not. + * + * @example + * node.isEmpty({img: true}); + * @method isEmpty + * @param {Object} elements Name/value object with elements that are automatically treated as non empty elements. + * @return {Boolean} true/false if the node is empty or not. + */ + 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 + if (elements[node.name]) { + return false; + } + + // Keep elements with data attributes or name attribute like + i = node.attributes.length; + while (i--) { + name = node.attributes[i].name; + if (name === "name" || name.indexOf('data-mce-') === 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; + }, + + /** + * Walks to the next or previous node and returns that node or null if it wasn't found. + * + * @method walk + * @param {Boolean} prev Optional previous node state defaults to false. + * @return {tinymce.html.Node} Node that is next to or previous of the current node. + */ + walk: function(prev) { + return walk(this, null, prev); + } + }; + + /** + * Creates a node of a specific type. + * + * @static + * @method create + * @param {String} name Name of the node type to create for example "b" or "#text". + * @param {Object} attrs Name/value collection of attributes that will be applied to elements. + */ + 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; + }; + + return Node; +}); + +// Included from: js/tinymce/classes/html/Schema.js + +/** + * Schema.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Schema validator class. + * + * @class tinymce.html.Schema + * @example + * if (tinymce.activeEditor.schema.isValidChild('p', 'span')) + * alert('span is valid child of p.'); + * + * if (tinymce.activeEditor.schema.getElementRule('p')) + * alert('P is a valid element.'); + * + * @class tinymce.html.Schema + * @version 3.4 + */ +define("tinymce/html/Schema", [ + "tinymce/util/Tools" +], function(Tools) { + var mapCache = {}; + var makeMap = Tools.makeMap, each = Tools.each, extend = Tools.extend, explode = Tools.explode, inArray = Tools.inArray; + + function split(items, delim) { + return items ? items.split(delim || ' ') : []; + } + + /** + * Builds a schema lookup table + * + * @param {String} type html4, html5 or html5-strict schema type. + * @return {Object} Schema lookup table. + */ + function compileSchema(type) { + var schema = {}, globalAttributes, eventAttributes, blockContent; + var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent; + + function add(name, attributes, children) { + var ni, i, attributesOrder, args = arguments; + + function arrayToMap(array) { + var map = {}, i, l; + + for (i = 0, l = array.length; i < l; i++) { + map[array[i]] = {}; + } + + return map; + } + + children = children || []; + attributes = attributes || ""; + + if (typeof(children) === "string") { + children = split(children); + } + + // Split string children + for (i = 3; i < args.length; i++) { + if (typeof(args[i]) === "string") { + args[i] = split(args[i]); + } + + children.push.apply(children, args[i]); + } + + name = split(name); + ni = name.length; + while (ni--) { + attributesOrder = [].concat(globalAttributes, split(attributes)); + schema[name[ni]] = { + attributes: arrayToMap(attributesOrder), + attributesOrder: attributesOrder, + children: arrayToMap(children) + }; + } + } + + function addAttrs(name, attributes) { + var ni, schemaItem, i, l; + + name = split(name); + ni = name.length; + attributes = split(attributes); + while (ni--) { + schemaItem = schema[name[ni]]; + for (i = 0, l = attributes.length; i < l; i++) { + schemaItem.attributes[attributes[i]] = {}; + schemaItem.attributesOrder.push(attributes[i]); + } + } + } + + // Use cached schema + if (mapCache[type]) { + return mapCache[type]; + } + + // Attributes present on all elements + globalAttributes = split("id accesskey class dir lang style tabindex title"); + + // Event attributes can be opt-in/opt-out + eventAttributes = split("onabort onblur oncancel oncanplay oncanplaythrough onchange onclick onclose oncontextmenu oncuechange " + + "ondblclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop ondurationchange onemptied onended " + + "onerror onfocus oninput oninvalid onkeydown onkeypress onkeyup onload onloadeddata onloadedmetadata onloadstart " + + "onmousedown onmousemove onmouseout onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange " + + "onreset onscroll onseeked onseeking onseeking onselect onshow onstalled onsubmit onsuspend ontimeupdate onvolumechange " + + "onwaiting" + ); + + // Block content elements + blockContent = split( + "address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul" + ); + + // Phrasing content elements from the HTML5 spec (inline) + phrasingContent = split( + "a abbr b bdo br button cite code del dfn em embed i iframe img input ins kbd " + + "label map noscript object q s samp script select small span strong sub sup " + + "textarea u var #text #comment" + ); + + // Add HTML5 items to globalAttributes, blockContent, phrasingContent + if (type != "html4") { + globalAttributes.push.apply(globalAttributes, split("contenteditable contextmenu draggable dropzone " + + "hidden spellcheck translate")); + blockContent.push.apply(blockContent, split("article aside details dialog figure header footer hgroup section nav")); + phrasingContent.push.apply(phrasingContent, split("audio canvas command datalist mark meter output progress time wbr " + + "video ruby bdi keygen")); + } + + // Add HTML4 elements unless it's html5-strict + if (type != "html5-strict") { + globalAttributes.push("xml:lang"); + + html4PhrasingContent = split("acronym applet basefont big font strike tt"); + phrasingContent.push.apply(phrasingContent, html4PhrasingContent); + + each(html4PhrasingContent, function(name) { + add(name, "", phrasingContent); + }); + + html4BlockContent = split("center dir isindex noframes"); + blockContent.push.apply(blockContent, html4BlockContent); + + // Flow content elements from the HTML5 spec (block+inline) + flowContent = [].concat(blockContent, phrasingContent); + + each(html4BlockContent, function(name) { + add(name, "", flowContent); + }); + } + + // Flow content elements from the HTML5 spec (block+inline) + flowContent = flowContent || [].concat(blockContent, phrasingContent); + + // HTML4 base schema TODO: Move HTML5 specific attributes to HTML5 specific if statement + // Schema items , , + add("html", "manifest", "head body"); + add("head", "", "base command link meta noscript script style title"); + add("title hr noscript br"); + add("base", "href target"); + add("link", "href rel media hreflang type sizes hreflang"); + add("meta", "name http-equiv content charset"); + add("style", "media type scoped"); + add("script", "src async defer type charset"); + add("body", "onafterprint onbeforeprint onbeforeunload onblur onerror onfocus " + + "onhashchange onload onmessage onoffline ononline onpagehide onpageshow " + + "onpopstate onresize onscroll onstorage onunload", flowContent); + add("address dt dd div caption", "", flowContent); + add("h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn", "", phrasingContent); + add("blockquote", "cite", flowContent); + add("ol", "reversed start type", "li"); + add("ul", "", "li"); + add("li", "value", flowContent); + add("dl", "", "dt dd"); + add("a", "href target rel media hreflang type", phrasingContent); + add("q", "cite", phrasingContent); + add("ins del", "cite datetime", flowContent); + add("img", "src alt usemap ismap width height"); + add("iframe", "src name width height", flowContent); + add("embed", "src type width height"); + add("object", "data type typemustmatch name usemap form width height", flowContent, "param"); + add("param", "name value"); + add("map", "name", flowContent, "area"); + add("area", "alt coords shape href target rel media hreflang type"); + add("table", "border", "caption colgroup thead tfoot tbody tr" + (type == "html4" ? " col" : "")); + add("colgroup", "span", "col"); + add("col", "span"); + add("tbody thead tfoot", "", "tr"); + add("tr", "", "td th"); + add("td", "colspan rowspan headers", flowContent); + add("th", "colspan rowspan headers scope abbr", flowContent); + add("form", "accept-charset action autocomplete enctype method name novalidate target", flowContent); + add("fieldset", "disabled form name", flowContent, "legend"); + add("label", "form for", phrasingContent); + add("input", "accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate " + + "formtarget height list max maxlength min multiple name pattern readonly required size src step type value width" + ); + add("button", "disabled form formaction formenctype formmethod formnovalidate formtarget name type value", + type == "html4" ? flowContent : phrasingContent); + add("select", "disabled form multiple name required size", "option optgroup"); + add("optgroup", "disabled label", "option"); + add("option", "disabled label selected value"); + add("textarea", "cols dirname disabled form maxlength name readonly required rows wrap"); + add("menu", "type label", flowContent, "li"); + add("noscript", "", flowContent); + + // Extend with HTML5 elements + if (type != "html4") { + add("wbr"); + add("ruby", "", phrasingContent, "rt rp"); + add("figcaption", "", flowContent); + add("mark rt rp summary bdi", "", phrasingContent); + add("canvas", "width height", flowContent); + add("video", "src crossorigin poster preload autoplay mediagroup loop " + + "muted controls width height", flowContent, "track source"); + add("audio", "src crossorigin preload autoplay mediagroup loop muted controls", flowContent, "track source"); + add("source", "src type media"); + add("track", "kind src srclang label default"); + add("datalist", "", phrasingContent, "option"); + add("article section nav aside header footer", "", flowContent); + add("hgroup", "", "h1 h2 h3 h4 h5 h6"); + add("figure", "", flowContent, "figcaption"); + add("time", "datetime", phrasingContent); + add("dialog", "open", flowContent); + add("command", "type label icon disabled checked radiogroup command"); + add("output", "for form name", phrasingContent); + add("progress", "value max", phrasingContent); + add("meter", "value min max low high optimum", phrasingContent); + add("details", "open", flowContent, "summary"); + add("keygen", "autofocus challenge disabled form keytype name"); + } + + // Extend with HTML4 attributes unless it's html5-strict + if (type != "html5-strict") { + addAttrs("script", "language xml:space"); + addAttrs("style", "xml:space"); + addAttrs("object", "declare classid codebase codetype archive standby align border hspace vspace"); + addAttrs("param", "valuetype type"); + addAttrs("a", "charset name rev shape coords"); + addAttrs("br", "clear"); + addAttrs("applet", "codebase archive code object alt name width height align hspace vspace"); + addAttrs("img", "name longdesc align border hspace vspace"); + addAttrs("iframe", "longdesc frameborder marginwidth marginheight scrolling align"); + addAttrs("font basefont", "size color face"); + addAttrs("input", "usemap align"); + addAttrs("select", "onchange"); + addAttrs("textarea"); + addAttrs("h1 h2 h3 h4 h5 h6 div p legend caption", "align"); + addAttrs("ul", "type compact"); + addAttrs("li", "type"); + addAttrs("ol dl menu dir", "compact"); + addAttrs("pre", "width xml:space"); + addAttrs("hr", "align noshade size width"); + addAttrs("isindex", "prompt"); + addAttrs("table", "summary width frame rules cellspacing cellpadding align bgcolor"); + addAttrs("col", "width align char charoff valign"); + addAttrs("colgroup", "width align char charoff valign"); + addAttrs("thead", "align char charoff valign"); + addAttrs("tr", "align char charoff valign bgcolor"); + addAttrs("th", "axis align char charoff valign nowrap bgcolor width height"); + addAttrs("form", "accept"); + addAttrs("td", "abbr axis scope align char charoff valign nowrap bgcolor width height"); + addAttrs("tfoot", "align char charoff valign"); + addAttrs("tbody", "align char charoff valign"); + addAttrs("area", "nohref"); + addAttrs("body", "background bgcolor text link vlink alink"); + } + + // Extend with HTML5 attributes unless it's html4 + if (type != "html4") { + addAttrs("input button select textarea", "autofocus"); + addAttrs("input textarea", "placeholder"); + addAttrs("a", "download"); + addAttrs("link script img", "crossorigin"); + addAttrs("iframe", "srcdoc sandbox seamless allowfullscreen"); + } + + // Special: iframe, ruby, video, audio, label + + // Delete children of the same name from it's parent + // For example: form can't have a child of the name form + each(split('a form meter progress dfn'), function(name) { + if (schema[name]) { + delete schema[name].children[name]; + } + }); + + // Delete header, footer, sectioning and heading content descendants + /*each('dt th address', function(name) { + delete schema[name].children[name]; + });*/ + + // Caption can't have tables + delete schema.caption.children.table; + + // TODO: LI:s can only have value if parent is OL + + // TODO: Handle transparent elements + // a ins del canvas map + + mapCache[type] = schema; + + return schema; + } + + /** + * Constructs a new Schema instance. + * + * @constructor + * @method Schema + * @param {Object} settings Name/value settings object. + */ + return function(settings) { + var self = this, elements = {}, children = {}, patternElements = [], validStyles, schemaItems; + var whiteSpaceElementsMap, selfClosingElementsMap, shortEndedElementsMap, boolAttrMap; + var blockElementsMap, nonEmptyElementsMap, textBlockElementsMap, customElementsMap = {}, specialElements = {}; + + // Creates an lookup table map object for the specified option or the default value + function createLookupTable(option, default_value, extendWith) { + 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 = extend(value, extendWith); + + mapCache[option] = value; + } + } else { + // Create custom map + value = makeMap(value, ',', makeMap(value.toUpperCase(), ' ')); + } + + return value; + } + + settings = settings || {}; + schemaItems = compileSchema(settings.schema); + + // 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] = explode(value); + }); + } + + // Setup map objects + whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object'); + selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr'); + shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' + + 'meta param embed source wbr track'); + boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + + 'noshade nowrap readonly selected autoplay loop controls'); + nonEmptyElementsMap = createLookupTable('non_empty_elements', 'td th iframe video audio object', shortEndedElementsMap); + textBlockElementsMap = createLookupTable('text_block_elements', 'h1 h2 h3 h4 h5 h6 p div address pre form ' + + 'blockquote center dir fieldset header footer article section hgroup aside nav figure'); + blockElementsMap = createLookupTable('block_elements', 'hr table tbody thead tfoot ' + + 'th tr td li ol ul caption dl dt dd noscript menu isindex samp option ' + + 'datalist select optgroup', textBlockElementsMap); + + each((settings.special || 'script noscript style textarea').split(' '), function(name) { + specialElements[name] = new RegExp('<\/' + name + '[^>]*>','gi'); + }); + + // 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, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, + prefix, outputName, globalAttributes, globalAttributesOrder, key, 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[5]; + + // 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; + } + + if (matches[4] === '!') { + element.removeEmptyAttrs = 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(inArray(attributesOrder, attrName), 1); + continue; + } + + // Default value + if (prefix) { + // Default value + if (prefix === '=') { + element.attributesDefault = element.attributesDefault || []; + element.attributesDefault.push({name: attrName, value: value}); + attr.defaultValue = value; + } + + // Forced value + if (prefix === ':') { + element.attributesForced = element.attributesForced || []; + element.attributesForced.push({name: attrName, value: value}); + attr.forcedValue = value; + } + + // Required values + if (prefix === '<') { + attr.validValues = makeMap(value, '?'); + } + } + + // Check for attribute patterns + if (hasPatternsRegExp.test(attrName)) { + element.attributePatterns = element.attributePatterns || []; + attr.pattern = patternToRegExp(attrName); + element.attributePatterns.push(attr); + } else { + // Add attribute to order list if it doesn't already exist + if (!attributes[attrName]) { + attributesOrder.push(attrName); + } + + attributes[attrName] = attr; + } + } + } + } + + // Global rule, store away these for later usage + if (!globalAttributes && elementName == '@') { + globalAttributes = attributes; + globalAttributesOrder = attributesOrder; + } + + // Handle substitute elements such as b/strong + if (outputName) { + element.outputName = elementName; + elements[outputName] = element; + } + + // Add pattern or exact element + if (hasPatternsRegExp.test(elementName)) { + element.pattern = patternToRegExp(elementName); + patternElements.push(element); + } else { + elements[elementName] = element; + } + } + } + } + } + + function setValidElements(valid_elements) { + elements = {}; + patternElements = []; + + addValidElements(valid_elements); + + each(schemaItems, function(element, name) { + children[name] = element.children; + }); + } + + // Adds custom non HTML elements to the schema + function addCustomElements(custom_elements) { + var customElementRegExp = /^(~)?(.+)$/; + + if (custom_elements) { + each(split(custom_elements, ','), function(rule) { + var matches = customElementRegExp.exec(rule), + inline = matches[1] === '~', + cloneName = inline ? 'span' : 'div', + name = matches[2]; + + children[name] = children[cloneName]; + customElementsMap[name] = cloneName; + + // If it's not marked as inline then add it to valid block elements + if (!inline) { + blockElementsMap[name.toUpperCase()] = {}; + blockElementsMap[name] = {}; + } + + // Add elements clone if needed + if (!elements[name]) { + elements[name] = elements[cloneName]; + } + + // Add custom elements at span/div positions + each(children, function(element) { + 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; + }); + + // Remove these if they have no attributes + each(split('span'), function(name) { + elements[name].removeEmptyAttrs = 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) { + each(explode(settings.invalid_elements), function(item) { + if (elements[item]) { + delete elements[item]; + } + }); + } + + // If the user didn't allow span only allow internal spans + if (!getElementRule('span')) { + addValidElements('span[!data-mce-type|*]'); + } + + /** + * Name/value map object with valid parents and children to those parents. + * + * @example + * children = { + * div:{p:{}, h1:{}} + * }; + * @field children + * @type {Object} + */ + self.children = children; + + /** + * Name/value map object with valid styles for each element. + * + * @field styles + * @type {Object} + */ + self.styles = validStyles; + + /** + * Returns a map with boolean attributes. + * + * @method getBoolAttrs + * @return {Object} Name/value lookup map for boolean attributes. + */ + self.getBoolAttrs = function() { + return boolAttrMap; + }; + + /** + * Returns a map with block elements. + * + * @method getBlockElements + * @return {Object} Name/value lookup map for block elements. + */ + self.getBlockElements = function() { + return blockElementsMap; + }; + + /** + * Returns a map with text block elements. Such as: p,h1-h6,div,address + * + * @method getTextBlockElements + * @return {Object} Name/value lookup map for block elements. + */ + self.getTextBlockElements = function() { + return textBlockElementsMap; + }; + + /** + * Returns a map with short ended elements such as BR or IMG. + * + * @method getShortEndedElements + * @return {Object} Name/value lookup map for short ended elements. + */ + self.getShortEndedElements = function() { + return shortEndedElementsMap; + }; + + /** + * Returns a map with self closing tags such as
  • . + * + * @method getSelfClosingElements + * @return {Object} Name/value lookup map for self closing tags elements. + */ + self.getSelfClosingElements = function() { + return selfClosingElementsMap; + }; + + /** + * Returns a map with elements that should be treated as contents regardless if it has text + * content in them or not such as TD, VIDEO or IMG. + * + * @method getNonEmptyElements + * @return {Object} Name/value lookup map for non empty elements. + */ + self.getNonEmptyElements = function() { + return nonEmptyElementsMap; + }; + + /** + * Returns a map with elements where white space is to be preserved like PRE or SCRIPT. + * + * @method getWhiteSpaceElements + * @return {Object} Name/value lookup map for white space elements. + */ + self.getWhiteSpaceElements = function() { + return whiteSpaceElementsMap; + }; + + /** + * Returns a map with special elements. These are elements that needs to be parsed + * in a special way such as script, style, textarea etc. The map object values + * are regexps used to find the end of the element. + * + * @method getSpecialElements + * @return {Object} Name/value lookup map for special elements. + */ + self.getSpecialElements = function() { + return specialElements; + }; + + /** + * Returns true/false if the specified element and it's child is valid or not + * according to the schema. + * + * @method isValidChild + * @param {String} name Element name to check for. + * @param {String} child Element child to verify. + * @return {Boolean} True/false if the element is a valid child of the specified parent. + */ + self.isValidChild = function(name, child) { + var parent = children[name]; + + return !!(parent && parent[child]); + }; + + /** + * Returns true/false if the specified element name and optional attribute is + * valid according to the schema. + * + * @method isValid + * @param {String} name Name of element to check. + * @param {String} attr Optional attribute name to check for. + * @return {Boolean} True/false if the element and attribute is valid. + */ + self.isValid = function(name, attr) { + var attrPatterns, i, rule = getElementRule(name); + + // Check if it's a valid element + if (rule) { + if (attr) { + // Check if attribute name exists + if (rule.attributes[attr]) { + return true; + } + + // Check if attribute matches a regexp pattern + attrPatterns = rule.attributePatterns; + if (attrPatterns) { + i = attrPatterns.length; + while (i--) { + if (attrPatterns[i].pattern.test(name)) { + return true; + } + } + } + } else { + return true; + } + } + + // No match + return false; + }; + + /** + * Returns true/false if the specified element is valid or not + * according to the schema. + * + * @method getElementRule + * @param {String} name Element name to check for. + * @return {Object} Element object or undefined if the element isn't valid. + */ + self.getElementRule = getElementRule; + + /** + * Returns an map object of all custom elements. + * + * @method getCustomElements + * @return {Object} Name/value map object of all custom elements. + */ + self.getCustomElements = function() { + return customElementsMap; + }; + + /** + * Parses a valid elements string and adds it to the schema. The valid elements + format is for example "element[attr=default|otherattr]". + * Existing rules will be replaced with the ones specified, so this extends the schema. + * + * @method addValidElements + * @param {String} valid_elements String in the valid elements format to be parsed. + */ + self.addValidElements = addValidElements; + + /** + * Parses a valid elements string and sets it to the schema. The valid elements + * format is for example "element[attr=default|otherattr]". + * Existing rules will be replaced with the ones specified, so this extends the schema. + * + * @method setValidElements + * @param {String} valid_elements String in the valid elements format to be parsed. + */ + self.setValidElements = setValidElements; + + /** + * Adds custom non HTML elements to the schema. + * + * @method addCustomElements + * @param {String} custom_elements Comma separated list of custom elements to add. + */ + self.addCustomElements = addCustomElements; + + /** + * Parses a valid children string and adds them to the schema structure. The valid children + * format is for example: "element[child1|child2]". + * + * @method addValidChildren + * @param {String} valid_children Valid children elements string to parse + */ + self.addValidChildren = addValidChildren; + + self.elements = elements; + }; +}); + +// Included from: js/tinymce/classes/html/SaxParser.js + +/** + * SaxParser.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class parses HTML code using pure JavaScript and executes various events for each item it finds. It will + * always execute the events in the right order for tag soup code like

    . It will also remove elements + * and attributes that doesn't fit the schema if the validate setting is enabled. + * + * @example + * var parser = new tinymce.html.SaxParser({ + * validate: true, + * + * comment: function(text) { + * console.log('Comment:', text); + * }, + * + * cdata: function(text) { + * console.log('CDATA:', text); + * }, + * + * text: function(text, raw) { + * console.log('Text:', text, 'Raw:', raw); + * }, + * + * start: function(name, attrs, empty) { + * console.log('Start:', name, attrs, empty); + * }, + * + * end: function(name) { + * console.log('End:', name); + * }, + * + * pi: function(name, text) { + * console.log('PI:', name, text); + * }, + * + * doctype: function(text) { + * console.log('DocType:', text); + * } + * }, schema); + * @class tinymce.html.SaxParser + * @version 3.4 + */ +define("tinymce/html/SaxParser", [ + "tinymce/html/Schema", + "tinymce/html/Entities", + "tinymce/util/Tools" +], function(Schema, Entities, Tools) { + var each = Tools.each; + + /** + * Constructs a new SaxParser instance. + * + * @constructor + * @method SaxParser + * @param {Object} settings Name/value collection of settings. comment, cdata, text, start and end are callbacks. + * @param {tinymce.html.Schema} schema HTML Schema class to use when parsing. + */ + return function(settings, schema) { + var self = this, noop = function() {}; + + settings = settings || {}; + self.schema = schema = schema || new Schema(); + + if (settings.fix_self_closing !== false) { + settings.fix_self_closing = true; + } + + // Add handler functions from settings and setup default handlers + each('comment cdata text start end pi doctype'.split(' '), function(name) { + if (name) { + self[name] = settings[name] || noop; + } + }); + + /** + * Parses the specified HTML string and executes the callbacks for each item it finds. + * + * @example + * new SaxParser({...}).parse('text'); + * @method parse + * @param {String} html Html string to sax parse. + */ + self.parse = function(html) { + var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name; + var isInternalElement, removeInternalElements, shortEndedElements, fillAttrsMap, isShortEnded; + var validate, elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns; + var attributesRequired, attributesDefault, attributesForced; + var anyAttributesRequired, selfClosing, tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0; + var decode = Entities.decode, fixSelfClosing; + + 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-mce-') !== 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; + + // Setup lookup tables for empty elements and boolean attributes + shortEndedElements = schema.getShortEndedElements(); + selfClosing = settings.self_closing_elements || schema.getSelfClosingElements(); + fillAttrsMap = schema.getBoolAttrs(); + validate = settings.validate; + removeInternalElements = settings.remove_internals; + fixSelfClosing = settings.fix_self_closing; + specialElements = schema.getSpecialElements(); + + 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 (value.charAt(0) === ':') { + 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 (value.charAt(0) === ':') { + value = value.substr(1); + } + + isShortEnded = value in shortEndedElements; + + // Is self closing tag for example an
  • after an open
  • + 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; + anyAttributesRequired = elementRule.removeEmptyAttrs; + + // Check if any attribute exists + if (anyAttributesRequired && !attrList.length) { + isValidElement = false; + } + + // 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) { + if (text.length > 0) { + self.text(text, true); + } + + 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); + } + } + }; + }; +}); + +// Included from: js/tinymce/classes/html/DomParser.js + +/** + * DomParser.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class parses HTML code into a DOM like structure of nodes it will remove redundant whitespace and make + * sure that the node tree is valid according to the specified schema. + * So for example:

    a

    b

    c

    will become

    a

    b

    c

    + * + * @example + * var parser = new tinymce.html.DomParser({validate: true}, schema); + * var rootNode = parser.parse('

    content

    '); + * + * @class tinymce.html.DomParser + * @version 3.4 + */ +define("tinymce/html/DomParser", [ + "tinymce/html/Node", + "tinymce/html/Schema", + "tinymce/html/SaxParser", + "tinymce/util/Tools" +], function(Node, Schema, SaxParser, Tools) { + var makeMap = Tools.makeMap, each = Tools.each, explode = Tools.explode, extend = Tools.extend; + + /** + * Constructs a new DomParser instance. + * + * @constructor + * @method DomParser + * @param {Object} settings Name/value collection of settings. comment, cdata, text, start and end are callbacks. + * @param {tinymce.html.Schema} schema HTML Schema class to use when parsing. + */ + return 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 Schema(); + + function fixInvalidChildren(nodes) { + var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i; + var nonEmptyElements, nonSplitableElements, textBlockElements, sibling, nextNode; + + nonSplitableElements = makeMap('tr,td,th,tbody,thead,tfoot,table'); + nonEmptyElements = schema.getNonEmptyElements(); + textBlockElements = schema.getTextBlockElements(); + + for (ni = 0; ni < nodes.length; ni++) { + node = nodes[ni]; + + // Already removed or fixed + if (!node.parent || node.fixed) { + continue; + } + + // If the invalid element is a text block and the text block is within a parent LI element + // Then unwrap the first text block and convert other sibling text blocks to LI elements similar to Word/Open Office + if (textBlockElements[node.name] && node.parent.name == 'li') { + // Move sibling text blocks after LI element + sibling = node.next; + while (sibling) { + if (textBlockElements[sibling.name]) { + sibling.name = 'li'; + sibling.fixed = true; + node.parent.insert(sibling, node.parent); + } else { + break; + } + + sibling = sibling.next; + } + + // Unwrap current text block + node.unwrap(node); + 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


    + 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(); + } + } + } + } + } + + /** + * Runs the specified node though the element and attributes filters. + * + * @param {tinymce.html.Node} Node the node to run filters on. + * @return {tinymce.html.Node} The passed in node. + */ + 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; + }; + + /** + * Adds a node filter function to the parser, the parser will collect the specified nodes by name + * and then execute the callback ones it has finished parsing the document. + * + * @example + * parser.addNodeFilter('p,h1', function(nodes, name) { + * for (var i = 0; i < nodes.length; i++) { + * console.log(nodes[i].name); + * } + * }); + * @method addNodeFilter + * @method {String} name Comma separated list of nodes to collect. + * @param {function} callback Callback function to execute once it has collected nodes. + */ + self.addNodeFilter = function(name, callback) { + each(explode(name), function(name) { + var list = nodeFilters[name]; + + if (!list) { + nodeFilters[name] = list = []; + } + + list.push(callback); + }); + }; + + /** + * Adds a attribute filter function to the parser, the parser will collect nodes that has the specified attributes + * and then execute the callback ones it has finished parsing the document. + * + * @example + * parser.addAttributeFilter('src,href', function(nodes, name) { + * for (var i = 0; i < nodes.length; i++) { + * console.log(nodes[i].name); + * } + * }); + * @method addAttributeFilter + * @method {String} name Comma separated list of nodes to collect. + * @param {function} callback Callback function to execute once it has collected nodes. + */ + self.addAttributeFilter = function(name, callback) { + each(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]}); + }); + }; + + /** + * Parses the specified HTML string into a DOM like node tree and returns the result. + * + * @example + * var rootNode = new DomParser({...}).parse('text'); + * @method parse + * @param {String} html Html string to sax parse. + * @param {Object} args Optional args object that gets passed to all filter functions. + * @return {tinymce.html.Node} Root node containing the tree. + */ + self.parse = function(html, args) { + var parser, rootNode, node, nodes, i, l, fi, fl, list, name, validate; + var blockElements, startWhiteSpaceRegExp, invalidChildren = [], isInWhiteSpacePreservedElement; + var endWhiteSpaceRegExp, allWhiteSpaceRegExp, isAllWhiteSpaceRegExp, whiteSpaceElements; + var children, nonEmptyElements, rootBlockName; + + args = args || {}; + matchedNodes = {}; + matchedAttributes = {}; + blockElements = extend(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; + isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/; + + function addRootBlocks() { + var node = rootNode.firstChild, next, rootBlockNode; + + // Removes whitespace at beginning and end of block so: + //

    x

    ->

    x

    + function trim(rootBlockNode) { + if (rootBlockNode) { + node = rootBlockNode.firstChild; + if (node && node.type == 3) { + node.value = node.value.replace(startWhiteSpaceRegExp, ''); + } + + node = rootBlockNode.lastChild; + if (node && node.type == 3) { + node.value = node.value.replace(endWhiteSpaceRegExp, ''); + } + } + } + + // Check if rootBlock is valid within rootNode for example if P is valid in H1 if H1 is the contentEditabe root + if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) { + return; + } + + 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 { + trim(rootBlockNode); + rootBlockNode = null; + } + + node = next; + } + + trim(rootBlockNode); + } + + 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; + } + } + } + + function cloneAndExcludeBlocks(input) { + var name, output = {}; + + for (name in input) { + if (name !== 'li' && name != 'p') { + output[name] = input[name]; + } + } + + return output; + } + + parser = new SaxParser({ + validate: validate, + + // Exclude P and LI from DOM parsing since it's treated better by the DOM parser + self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()), + + 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, attrName, 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
    or + 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 of the first node in a block + textNode = node.firstChild; + if (textNode && textNode.type === 3) { + text = textNode.value.replace(startWhiteSpaceRegExp, ''); + + // Any characters left after trim or should we remove it + if (text.length > 0) { + textNode.value = text; + textNode = textNode.next; + } else { + sibling = textNode.next; + textNode.remove(); + textNode = sibling; + + // Remove any pure whitespace siblings + while (textNode && textNode.type === 3) { + text = textNode.value; + sibling = textNode.next; + + if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) { + textNode.remove(); + textNode = sibling; + } + + textNode = sibling; + } + } + } + + // Trim whitespace of the last node in a block + textNode = node.lastChild; + if (textNode && textNode.type === 3) { + text = textNode.value.replace(endWhiteSpaceRegExp, ''); + + // Any characters left after trim or should we remove it + if (text.length > 0) { + textNode.value = text; + textNode = textNode.prev; + } else { + sibling = textNode.prev; + textNode.remove(); + textNode = sibling; + + // Remove any pure whitespace siblings + while (textNode && textNode.type === 3) { + text = textNode.value; + sibling = textNode.prev; + + if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) { + textNode.remove(); + textNode = sibling; + } + + textNode = sibling; + } + } + } + } + + // Trim start white space + // Removed due to: #5424 + /*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 + if (!node.attributes.map.name && !node.attributes.map.id) { + 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' || args.isRootContent)) { + 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
    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) { + var i, l = nodes.length, node, blockElements = extend({}, schema.getBlockElements()); + var nonEmptyElements = schema.getNonEmptyElements(), parent, lastParent, prev, prevName; + var elementRule, textNode; + + // Remove brs from body element as well + blockElements.body = 1; + + // Must loop forwards since it will otherwise remove all brs in

    a


    + 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

    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 Node('#text', 3)).value = '\u00a0'; + } + } + } + } + } else { + // Replaces BR elements inside inline elements like


    + // so they become

     

    + lastParent = node; + while (parent.firstChild === lastParent && parent.lastChild === lastParent) { + lastParent = parent; + + if (blockElements[parent.name]) { + break; + } + + parent = parent.parent; + } + + if (lastParent === parent) { + textNode = new 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('id,name', function(nodes) { + var i = nodes.length, sibling, prevSibling, parent, node; + + while (i--) { + node = nodes[i]; + if (node.name === 'a' && node.firstChild && !node.attr('href')) { + parent = node.parent; + + // Move children after current node + sibling = node.lastChild; + do { + prevSibling = sibling.prev; + parent.insert(sibling, node); + sibling = prevSibling; + } while (sibling); + } + } + }); + } + }; +}); + +// Included from: js/tinymce/classes/html/Writer.js + +/** + * Writer.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is used to write HTML tags out it can be used with the Serializer or the SaxParser. + * + * @class tinymce.html.Writer + * @example + * var writer = new tinymce.html.Writer({indent: true}); + * var parser = new tinymce.html.SaxParser(writer).parse('


    '); + * console.log(writer.getContent()); + * + * @class tinymce.html.Writer + * @version 3.4 + */ +define("tinymce/html/Writer", [ + "tinymce/html/Entities", + "tinymce/util/Tools" +], function(Entities, Tools) { + var makeMap = Tools.makeMap; + + /** + * Constructs a new Writer instance. + * + * @constructor + * @method Writer + * @param {Object} settings Name/value settings object. + */ + return function(settings) { + var html = [], indent, indentBefore, indentAfter, encode, htmlOutput; + + settings = settings || {}; + indent = settings.indent; + indentBefore = makeMap(settings.indent_before || ''); + indentAfter = makeMap(settings.indent_after || ''); + encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities); + htmlOutput = settings.element_format == "html"; + + return { + /** + * Writes the a start element such as

    . + * + * @method start + * @param {String} name Name of the element. + * @param {Array} attrs Optional attribute array or undefined if it hasn't any. + * @param {Boolean} empty Optional empty state if the tag should end like
    . + */ + 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'); + } + } + }, + + /** + * Writes the a end element such as

    . + * + * @method end + * @param {String} name Name of the element. + */ + 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(''); + + if (indent && indentAfter[name] && html.length > 0) { + value = html[html.length - 1]; + + if (value.length > 0 && value !== '\n') { + html.push('\n'); + } + } + }, + + /** + * Writes a text node. + * + * @method text + * @param {String} text String to write out. + * @param {Boolean} raw Optional raw state if true the contents wont get encoded. + */ + text: function(text, raw) { + if (text.length > 0) { + html[html.length] = raw ? text : encode(text); + } + }, + + /** + * Writes a cdata node such as . + * + * @method cdata + * @param {String} text String to write out inside the cdata. + */ + cdata: function(text) { + html.push(''); + }, + + /** + * Writes a comment node such as . + * + * @method cdata + * @param {String} text String to write out inside the comment. + */ + comment: function(text) { + html.push(''); + }, + + /** + * Writes a PI node such as . + * + * @method pi + * @param {String} name Name of the pi. + * @param {String} text String to write out inside the pi. + */ + pi: function(name, text) { + if (text) { + html.push(''); + } else { + html.push(''); + } + + if (indent) { + html.push('\n'); + } + }, + + /** + * Writes a doctype node such as . + * + * @method doctype + * @param {String} text String to write out inside the doctype. + */ + doctype: function(text) { + html.push('', indent ? '\n' : ''); + }, + + /** + * Resets the internal buffer if one wants to reuse the writer. + * + * @method reset + */ + reset: function() { + html.length = 0; + }, + + /** + * Returns the contents that got serialized. + * + * @method getContent + * @return {String} HTML contents that got written down. + */ + getContent: function() { + return html.join('').replace(/\n$/, ''); + } + }; + }; +}); + +// Included from: js/tinymce/classes/html/Serializer.js + +/** + * Serializer.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is used to serialize down the DOM tree into a string using a Writer instance. + * + * + * @example + * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('

    text

    ')); + * @class tinymce.html.Serializer + * @version 3.4 + */ +define("tinymce/html/Serializer", [ + "tinymce/html/Writer", + "tinymce/html/Schema" +], function(Writer, Schema) { + /** + * Constructs a new Serializer instance. + * + * @constructor + * @method Serializer + * @param {Object} settings Name/value settings object. + * @param {tinymce.html.Schema} schema Schema instance to use. + */ + return function(settings, schema) { + var self = this, writer = new Writer(settings); + + settings = settings || {}; + settings.validate = "validate" in settings ? settings.validate : true; + + self.schema = schema = schema || new Schema(); + self.writer = writer; + + /** + * Serializes the specified node into a string. + * + * @example + * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('

    text

    ')); + * @method serialize + * @param {tinymce.html.Node} node Node instance to serialize. + * @return {String} String with HTML based on DOM tree. + */ + self.serialize = function(node) { + var handlers, validate; + + validate = settings.validate; + + handlers = { + // #text + 3: function(node) { + 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(); + }; + }; +}); + +// Included from: js/tinymce/classes/dom/Serializer.js + +/** + * Serializer.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class is used to serialize DOM trees into a string. Consult the TinyMCE Wiki API for + * more details and examples on how to use this class. + * + * @class tinymce.dom.Serializer + */ +define("tinymce/dom/Serializer", [ + "tinymce/dom/DOMUtils", + "tinymce/html/DomParser", + "tinymce/html/Entities", + "tinymce/html/Serializer", + "tinymce/html/Node", + "tinymce/html/Schema", + "tinymce/Env", + "tinymce/util/Tools" +], function(DOMUtils, DomParser, Entities, Serializer, Node, Schema, Env, Tools) { + var each = Tools.each, trim = Tools.trim; + var DOM = DOMUtils.DOM; + + /** + * Constucts a new DOM serializer class. + * + * @constructor + * @method Serializer + * @param {Object} settings Serializer settings object. + * @param {tinymce.Editor} editor Optional editor to bind events to and get schema/dom from. + */ + return function(settings, editor) { + var dom, schema, htmlParser; + + if (editor) { + dom = editor.dom; + schema = editor.schema; + } + + // Default DOM and Schema if they are undefined + dom = dom || DOM; + schema = schema || new Schema(settings); + settings.entity_encoding = settings.entity_encoding || 'named'; + settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true; + + htmlParser = new 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; + var 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<..> or mceSelected + htmlParser.addAttributeFilter('class', function(nodes) { + var i = nodes.length, node, value; + + while (i--) { + node = nodes[i]; + value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\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) { + var i = nodes.length; + + while (i--) { + nodes[i].attr(name, null); + } + }); + + htmlParser.addNodeFilter('noscript', function(nodes) { + var i = nodes.length, node; + + while (i--) { + node = nodes[i].firstChild; + + if (node) { + node.value = Entities.decode(node.value); + } + } + }); + + // 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) { + /*jshint maxlen:255 */ + return value.replace(/()/g, '\n') + .replace(/^[\r\n]*|[\r\n]*$/g, '') + .replace(/^\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 = '// '; + } + } else { + if (value.length > 0) { + node.firstChild.value = ''; + } + } + } + }); + + // Convert comments to cdata and handle protected comments + htmlParser.addNodeFilter('#comment', function(nodes) { + 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) { + 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,data-mce-selected', function(nodes, name) { + var i = nodes.length; + + while (i--) { + nodes[i].attr(name, null); + } + }); + + // Return public methods + return { + /** + * Schema instance that was used to when the Serializer was constructed. + * + * @field {tinymce.html.Schema} schema + */ + schema: schema, + + /** + * Adds a node filter function to the parser used by the serializer, the parser will collect the specified nodes by name + * and then execute the callback ones it has finished parsing the document. + * + * @example + * parser.addNodeFilter('p,h1', function(nodes, name) { + * for (var i = 0; i < nodes.length; i++) { + * console.log(nodes[i].name); + * } + * }); + * @method addNodeFilter + * @method {String} name Comma separated list of nodes to collect. + * @param {function} callback Callback function to execute once it has collected nodes. + */ + addNodeFilter: htmlParser.addNodeFilter, + + /** + * Adds a attribute filter function to the parser used by the serializer, the parser will + * collect nodes that has the specified attributes + * and then execute the callback ones it has finished parsing the document. + * + * @example + * parser.addAttributeFilter('src,href', function(nodes, name) { + * for (var i = 0; i < nodes.length; i++) { + * console.log(nodes[i].name); + * } + * }); + * @method addAttributeFilter + * @method {String} name Comma separated list of nodes to collect. + * @param {function} callback Callback function to execute once it has collected nodes. + */ + addAttributeFilter: htmlParser.addAttributeFilter, + + /** + * Serializes the specified browser DOM node into a HTML string. + * + * @method serialize + * @param {DOMNode} node DOM node to serialize. + * @param {Object} args Arguments option that gets passed to event handlers. + */ + serialize: function(node, args) { + var self = this, 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 (Env.ie && 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 + // 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'; + + // Don't wrap content if we want selected html + if (args.selection) { + args.forced_root_block = ''; + } + + // Pre process + if (!args.no_events) { + args.node = node; + self.onPreProcess(args); + } + + // Setup serializer + htmlSerializer = new Serializer(settings, schema); + + // Parse and serialize HTML + args.content = htmlSerializer.serialize( + htmlParser.parse(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/g, ''); + } + + // Post process + if (!args.no_events) { + self.onPostProcess(args); + } + + // Restore the old document if it was changed + if (oldDoc) { + dom.doc = oldDoc; + } + + args.node = null; + + return args.content; + }, + + /** + * Adds valid elements rules to the serializers schema instance this enables you to specify things + * like what elements should be outputted and what attributes specific elements might have. + * Consult the Wiki for more details on this format. + * + * @method addRules + * @param {String} rules Valid elements rules string to add to schema. + */ + addRules: function(rules) { + schema.addValidElements(rules); + }, + + /** + * Sets the valid elements rules to the serializers schema instance this enables you to specify things + * like what elements should be outputted and what attributes specific elements might have. + * Consult the Wiki for more details on this format. + * + * @method setRules + * @param {String} rules Valid elements rules string. + */ + setRules: function(rules) { + schema.setValidElements(rules); + }, + + onPreProcess: function(args) { + if (editor) { + editor.fire('PreProcess', args); + } + }, + + onPostProcess: function(args) { + if (editor) { + editor.fire('PostProcess', args); + } + } + }; + }; +}); + +// Included from: js/tinymce/classes/dom/TridentSelection.js + +/** + * TridentSelection.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/dom/TridentSelection", [], function() { + function Selection(selection) { + var self = this, dom = selection.dom, 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; + + // 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(), 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, offset; + + 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, sibling, + doc = selection.dom.doc, body = doc.body, nativeRng, ctrlElm; + + 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
    |
    + // Setting innerHTML with a span marker then remove that marker seems to keep empty block elements open + container.innerHTML = ''; + 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

    + if (startOffset == endOffset && !startContainer.hasChildNodes()) { + if (startContainer.canHaveHTML) { + // Check if previous sibling is an empty block if it is then we need to render it + // IE would otherwise move the caret into the sibling instead of the empty startContainer see: #5236 + // Example this:

    |

    would become this:

    |

    + sibling = startContainer.previousSibling; + if (sibling && !sibling.hasChildNodes() && dom.isBlock(sibling)) { + sibling.innerHTML = ''; + } else { + sibling = null; + } + + startContainer.innerHTML = ''; + ieRng.moveToElementText(startContainer.lastChild); + ieRng.select(); + dom.doc.selection.clear(); + startContainer.innerHTML = ''; + + if (sibling) { + sibling.innerHTML = ''; + } + return; + } else { + startOffset = dom.nodeIndex(startContainer); + startContainer = startContainer.parentNode; + } + } + + if (startOffset == endOffset - 1) { + try { + ctrlElm = startContainer.childNodes[startOffset]; + ctrlRng = body.createControlRange(); + ctrlRng.addElement(ctrlElm); + ctrlRng.select(); + + // Check if the range produced is on the correct element and is a control range + // On IE 8 it will select the parent contentEditable container if you select an inner element see: #5398 + nativeRng = selection.getRng(); + if (nativeRng.item && ctrlElm === nativeRng.item(0)) { + 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; + } + + return Selection; +}); + +// Included from: js/tinymce/classes/util/VK.js + +/** + * VK.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This file exposes a set of the common KeyCodes for use. Please grow it as needed. + */ +define("tinymce/util/VK", [ + "tinymce/Env" +], function(Env) { + return { + 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; + }, + + metaKeyPressed: function(e) { + // Check if ctrl or meta key is pressed also check if alt is false for Polish users + return Env.mac ? e.metaKey : e.ctrlKey && !e.altKey; + } + }; +}); + +// Included from: js/tinymce/classes/dom/ControlSelection.js + +/** + * ControlSelection.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles control selection of elements. Controls are elements + * that can be resized and needs to be selected as a whole. It adds custom resize handles + * to all browser engines that support properly disabling the built in logic. + * + * @class tinymce.dom.ControlSelection + */ +define("tinymce/dom/ControlSelection", [ + "tinymce/util/VK", + "tinymce/util/Tools", + "tinymce/Env" +], function(VK, Tools, Env) { + return function(selection, editor) { + var dom = editor.dom, each = Tools.each; + var selectedElm, selectedElmGhost, resizeHandles, selectedHandle; + var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted; + var width, height, editableDoc = editor.getDoc(), rootDocument = document, isIE = Env.ie; + + // Details about each resize handle how to scale etc + resizeHandles = { + // Name: x multiplier, y multiplier, delta size x, delta size y + n: [0.5, 0, 0, -1], + e: [1, 0.5, 1, 0], + s: [0.5, 1, 0, 1], + w: [0, 0.5, -1, 0], + nw: [0, 0, -1, -1], + ne: [1, 0, 1, -1], + se: [1, 1, 1, 1], + sw: [0, 1, -1, 1] + }; + + // Add CSS for resize handles, cloned element and selected + var rootClass = '.mce-content-body'; + editor.contentStyles.push( + rootClass + ' div.mce-resizehandle {' + + 'position: absolute;' + + 'border: 1px solid black;' + + 'background: #FFF;' + + 'width: 5px;' + + 'height: 5px;' + + 'z-index: 10000' + + '}' + + rootClass + ' .mce-resizehandle:hover {' + + 'background: #000' + + '}' + + rootClass + ' img[data-mce-selected], hr[data-mce-selected] {' + + 'outline: 1px solid black;' + + 'resize: none' + // Have been talks about implementing this in browsers + '}' + + rootClass + ' .mce-clonedresizable {' + + 'position: absolute;' + + (Env.gecko ? '' : 'outline: 1px dashed black;') + // Gecko produces trails while resizing + 'opacity: .5;' + + 'filter: alpha(opacity=50);' + + 'z-index: 10000' + + '}' + ); + + function isResizable(elm) { + if (editor.settings.object_resizing === false) { + return false; + } + + if (!/TABLE|IMG|DIV/.test(elm.nodeName)) { + return false; + } + + if (elm.getAttribute('data-mce-resize') === 'false') { + return false; + } + + return true; + } + + function resizeGhostElement(e) { + var deltaX, deltaY; + + // Calc new width/height + deltaX = e.screenX - startX; + deltaY = e.screenY - startY; + + // Calc new size + width = deltaX * selectedHandle[2] + startW; + height = deltaY * selectedHandle[3] + startH; + + // Never scale down lower than 5 pixels + width = width < 5 ? 5 : width; + height = height < 5 ? 5 : height; + + // Constrain proportions when modifier key is pressed or if the nw, ne, sw, se corners are moved on an image + if (VK.modifierPressed(e) || (selectedElm.nodeName == "IMG" && selectedHandle[2] * selectedHandle[3] !== 0)) { + width = Math.round(height / ratio); + height = Math.round(width * ratio); + } + + // Update ghost size + dom.setStyles(selectedElmGhost, { + width: width, + height: height + }); + + // Update ghost X position if needed + if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) { + dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width)); + } + + // Update ghost Y position if needed + if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) { + dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height)); + } + + if (!resizeStarted) { + editor.fire('ObjectResizeStart', {target: selectedElm, width: startW, height: startH}); + resizeStarted = true; + } + } + + function endGhostResize() { + resizeStarted = false; + + function setSizeProp(name, value) { + if (value) { + // Resize by using style or attribute + if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) { + dom.setStyle(selectedElm, name, value); + } else { + dom.setAttrib(selectedElm, name, value); + } + } + } + + // Set width/height properties + setSizeProp('width', width); + setSizeProp('height', height); + + dom.unbind(editableDoc, 'mousemove', resizeGhostElement); + dom.unbind(editableDoc, 'mouseup', endGhostResize); + + if (rootDocument != editableDoc) { + dom.unbind(rootDocument, 'mousemove', resizeGhostElement); + dom.unbind(rootDocument, 'mouseup', endGhostResize); + } + + // Remove ghost and update resize handle positions + dom.remove(selectedElmGhost); + + if (!isIE || selectedElm.nodeName == "TABLE") { + showResizeRect(selectedElm); + } + + editor.fire('ObjectResized', {target: selectedElm, width: width, height: height}); + editor.nodeChanged(); + } + + function showResizeRect(targetElm, mouseDownHandleName, mouseDownEvent) { + var position, targetWidth, targetHeight, e, rect; + + // Get position and size of target + position = dom.getPos(targetElm, editor.getBody()); + selectedElmX = position.x; + selectedElmY = position.y; + rect = targetElm.getBoundingClientRect(); // Fix for Gecko offsetHeight for table with caption + targetWidth = rect.width; + targetHeight = rect.height; + + // Reset width/height if user selects a new image/table + if (selectedElm != targetElm) { + detachResizeStartListener(); + selectedElm = targetElm; + width = height = 0; + } + + // Makes it possible to disable resizing + e = editor.fire('ObjectSelected', {target: targetElm}); + + if (isResizable(targetElm) && !e.isDefaultPrevented()) { + each(resizeHandles, function(handle, name) { + var handleElm, handlerContainerElm; + + function startDrag(e) { + resizeStarted = true; + + startX = e.screenX; + startY = e.screenY; + startW = selectedElm.clientWidth; + startH = selectedElm.clientHeight; + ratio = startH / startW; + selectedHandle = handle; + + selectedElmGhost = selectedElm.cloneNode(true); + dom.addClass(selectedElmGhost, 'mce-clonedresizable'); + selectedElmGhost.contentEditable = false; // Hides IE move layer cursor + selectedElmGhost.unSelectabe = true; + dom.setStyles(selectedElmGhost, { + left: selectedElmX, + top: selectedElmY, + margin: 0 + }); + + selectedElmGhost.removeAttribute('data-mce-selected'); + editor.getBody().appendChild(selectedElmGhost); + + dom.bind(editableDoc, 'mousemove', resizeGhostElement); + dom.bind(editableDoc, 'mouseup', endGhostResize); + + if (rootDocument != editableDoc) { + dom.bind(rootDocument, 'mousemove', resizeGhostElement); + dom.bind(rootDocument, 'mouseup', endGhostResize); + } + } + + if (mouseDownHandleName) { + // Drag started by IE native resizestart + if (name == mouseDownHandleName) { + startDrag(mouseDownEvent); + } + + return; + } + + // Get existing or render resize handle + handleElm = dom.get('mceResizeHandle' + name); + if (!handleElm) { + handlerContainerElm = editor.getBody(); + + handleElm = dom.add(handlerContainerElm, 'div', { + id: 'mceResizeHandle' + name, + 'data-mce-bogus': true, + 'class': 'mce-resizehandle', + contentEditable: false, // Hides IE move layer cursor + unSelectabe: true, + style: 'cursor:' + name + '-resize; margin:0; padding:0' + }); + + dom.bind(handleElm, 'mousedown', function(e) { + e.preventDefault(); + startDrag(e); + }); + } else { + dom.show(handleElm); + } + + /* + var halfHandleW = handleElm.offsetWidth / 2; + var halfHandleH = handleElm.offsetHeight / 2; + + // Position element + dom.setStyles(handleElm, { + left: Math.floor((targetWidth * handle[0] + selectedElmX) - halfHandleW + (handle[2] * halfHandleW)), + top: Math.floor((targetHeight * handle[1] + selectedElmY) - halfHandleH + (handle[3] * halfHandleH)) + }); + */ + + // Position element + dom.setStyles(handleElm, { + left: (targetWidth * handle[0] + selectedElmX) - (handleElm.offsetWidth / 2), + top: (targetHeight * handle[1] + selectedElmY) - (handleElm.offsetHeight / 2) + }); + }); + } else { + hideResizeRect(); + } + + selectedElm.setAttribute('data-mce-selected', '1'); + } + + function hideResizeRect() { + var name, handleElm; + + if (selectedElm) { + selectedElm.removeAttribute('data-mce-selected'); + } + + for (name in resizeHandles) { + handleElm = dom.get('mceResizeHandle' + name); + if (handleElm) { + dom.unbind(handleElm); + dom.remove(handleElm); + } + } + } + + function updateResizeRect(e) { + var controlElm; + + function isChildOrEqual(node, parent) { + do { + if (node === parent) { + return true; + } + } while ((node = node.parentNode)); + } + + // Remove data-mce-selected from all elements since they might have been copied using Ctrl+c/v + each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function(img) { + img.removeAttribute('data-mce-selected'); + }); + + controlElm = e.type == 'mousedown' ? e.target : selection.getNode(); + controlElm = dom.getParent(controlElm, isIE ? 'table' : 'table,img,hr'); + + if (controlElm) { + if (isChildOrEqual(selection.getStart(), controlElm) && isChildOrEqual(selection.getEnd(), controlElm)) { + if (!isIE || (controlElm != selection.getStart() && selection.getStart().nodeName !== 'IMG')) { + showResizeRect(controlElm); + return; + } + } + } + + hideResizeRect(); + } + + function attachEvent(elm, name, func) { + if (elm && elm.attachEvent) { + elm.attachEvent('on' + name, func); + } + } + + function detachEvent(elm, name, func) { + if (elm && elm.detachEvent) { + elm.detachEvent('on' + name, func); + } + } + + function resizeNativeStart(e) { + var target = e.srcElement, pos, name, corner, cornerX, cornerY, relativeX, relativeY; + + pos = target.getBoundingClientRect(); + relativeX = e.clientX - pos.left; + relativeY = e.clientY - pos.top; + + // Figure out what corner we are draging on + for (name in resizeHandles) { + corner = resizeHandles[name]; + + cornerX = target.offsetWidth * corner[0]; + cornerY = target.offsetHeight * corner[1]; + + if (Math.abs(cornerX - relativeX) < 8 && Math.abs(cornerY - relativeY) < 8) { + selectedHandle = corner; + break; + } + } + + // Remove native selection and let the magic begin + resizeStarted = true; + editor.getDoc().selection.empty(); + showResizeRect(target, name, e); + } + + function nativeControlSelect(e) { + var target = e.srcElement; + + if (target != selectedElm) { + detachResizeStartListener(); + + if (target.id.indexOf('mceResizeHandle') === 0) { + e.returnValue = false; + return; + } + + if (target.nodeName == 'IMG' || target.nodeName == 'TABLE') { + hideResizeRect(); + selectedElm = target; + attachEvent(target, 'resizestart', resizeNativeStart); + } + } + } + + function detachResizeStartListener() { + detachEvent(selectedElm, 'resizestart', resizeNativeStart); + } + + function controlSelect(elm) { + var ctrlRng; + + if (!isIE) { + return; + } + + ctrlRng = editableDoc.body.createControlRange(); + + try { + ctrlRng.addElement(elm); + ctrlRng.select(); + return true; + } catch (ex) { + // Ignore since the element can't be control selected for example a P tag + } + } + + editor.on('init', function() { + if (isIE) { + // Hide the resize rect on resize and reselect the image + editor.on('ObjectResized', function(e) { + if (e.target.nodeName != 'TABLE') { + hideResizeRect(); + controlSelect(e.target); + } + }); + + attachEvent(editor.getBody(), 'controlselect', nativeControlSelect); + } else { + try { + // Disable object resizing on Gecko + editor.getDoc().execCommand('enableObjectResizing', false, false); + } catch (ex) { + // Ignore + } + } + + editor.on('nodechange mousedown ResizeEditor', updateResizeRect); + + // Update resize rect while typing in a table + editor.on('keydown keyup', function(e) { + if (selectedElm && selectedElm.nodeName == "TABLE") { + updateResizeRect(e); + } + }); + + // Hide rect on focusout since it would float on top of windows otherwise + //editor.on('focusout', hideResizeRect); + }); + + function destroy() { + selectedElm = selectedElmGhost = null; + + if (isIE) { + detachResizeStartListener(); + detachEvent(editor.getBody(), 'controlselect', nativeControlSelect); + } + } + + return { + controlSelect: controlSelect, + destroy: destroy + }; + }; +}); + +// Included from: js/tinymce/classes/dom/Selection.js + +/** + * Selection.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles text and control selection it's an crossbrowser utility class. + * Consult the TinyMCE Wiki API for more details and examples on how to use this class. + * + * @class tinymce.dom.Selection + * @example + * // Getting the currently selected node for the active editor + * alert(tinymce.activeEditor.selection.getNode().nodeName); + */ +define("tinymce/dom/Selection", [ + "tinymce/dom/TreeWalker", + "tinymce/dom/TridentSelection", + "tinymce/dom/ControlSelection", + "tinymce/Env", + "tinymce/util/Tools" +], function(TreeWalker, TridentSelection, ControlSelection, Env, Tools) { + var each = Tools.each, grep = Tools.grep, trim = Tools.trim; + var isIE = Env.ie, isOpera = Env.opera; + + /** + * Constructs a new selection instance. + * + * @constructor + * @method Selection + * @param {tinymce.dom.DOMUtils} dom DOMUtils object reference. + * @param {Window} win Window to bind the selection object to. + * @param {tinymce.dom.Serializer} serializer DOM serialization class to use for getContent. + */ + function Selection(dom, win, serializer, editor) { + var self = this; + + self.dom = dom; + self.win = win; + self.serializer = serializer; + self.editor = editor; + + self.controlSelection = new ControlSelection(self, editor); + + editor.on('nodechange', function() { + var rng; + + // Use old style IE range since we want to restore control selections + if (editor.getDoc().selection) { + rng = editor.getDoc().selection.createRange(); + } else { + rng = self.getRng(); + } + + self.lastRng = rng; + }); + + // No W3C Range support + if (!self.win.getSelection) { + self.tridentSel = new TridentSelection(self); + } + } + + Selection.prototype = { + /** + * Move the selection cursor range to the specified node and offset. + * @param node Node to put the cursor in. + * @param offset Offset from the start of the node to put the cursor at. + */ + setCursorLocation: function(node, offset) { + var self = this, rng = self.dom.createRng(); + rng.setStart(node, offset); + rng.setEnd(node, offset); + self.setRng(rng); + self.collapse(false); + }, + + /** + * Returns the selected contents using the DOM serializer passed in to this class. + * + * @method getContent + * @param {Object} s Optional settings class with for example output format text or html. + * @return {String} Selected contents in for example HTML format. + * @example + * // Alerts the currently selected contents + * alert(tinymce.activeEditor.selection.getContent()); + * + * // Alerts the currently selected contents as plain text + * alert(tinymce.activeEditor.selection.getContent({format: 'text'})); + */ + getContent: function(args) { + var self = this, rng = self.getRng(), tmpElm = self.dom.create("body"); + var se = self.getSel(), whiteSpaceBefore, whiteSpaceAfter, fragment; + + args = args || {}; + whiteSpaceBefore = whiteSpaceAfter = ''; + args.get = true; + args.format = args.format || 'html'; + args.selection = true; + self.editor.fire('BeforeGetContent', args); + + if (args.format == 'text') { + return self.isCollapsed() ? '' : (rng.text || (se.toString ? se.toString() : '')); + } + + if (rng.cloneContents) { + fragment = rng.cloneContents(); + + if (fragment) { + tmpElm.appendChild(fragment); + } + } else if (rng.item !== undefined || rng.htmlText !== undefined) { + // 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. + tmpElm.innerHTML = '
    ' + (rng.item ? rng.item(0).outerHTML : rng.htmlText); + tmpElm.removeChild(tmpElm.firstChild); + } else { + tmpElm.innerHTML = rng.toString(); + } + + // Keep whitespace before and after + if (/^\s/.test(tmpElm.innerHTML)) { + whiteSpaceBefore = ' '; + } + + if (/\s+$/.test(tmpElm.innerHTML)) { + whiteSpaceAfter = ' '; + } + + args.getInner = true; + + args.content = self.isCollapsed() ? '' : whiteSpaceBefore + self.serializer.serialize(tmpElm, args) + whiteSpaceAfter; + self.editor.fire('GetContent', args); + + return args.content; + }, + + /** + * Sets the current selection to the specified content. If any contents is selected it will be replaced + * with the contents passed in to this function. If there is no selection the contents will be inserted + * where the caret is placed in the editor/page. + * + * @method setContent + * @param {String} content HTML contents to set could also be other formats depending on settings. + * @param {Object} args Optional settings object with for example data format. + * @example + * // Inserts some HTML contents at the current selection + * tinymce.activeEditor.selection.setContent('Some contents'); + */ + setContent: function(content, args) { + var self = this, rng = self.getRng(), caretNode, doc = self.win.document, frag, temp; + + args = args || {format: 'html'}; + args.set = true; + args.selection = true; + content = args.content = content; + + // Dispatch before set content event + if (!args.no_events) { + self.editor.fire('BeforeSetContent', args); + } + + content = args.content; + + if (rng.insertNode) { + // Make caret marker since insertNode places the caret in the beginning of text after insert + content += '_'; + + // 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('_' + content); + self.dom.remove('__mce_tmp'); + } else { + rng.pasteHTML(content); + } + } + + // Dispatch set content event + if (!args.no_events) { + self.editor.fire('SetContent', args); + } + }, + + /** + * Returns the start element of a selection range. If the start is in a text + * node the parent element will be returned. + * + * @method getStart + * @return {Element} Start element of selection range. + */ + getStart: function() { + var self = this, rng = self.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(); + if (startElement.ownerDocument !== self.dom.doc) { + startElement = self.dom.getRoot(); + } + + // 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; + } + }, + + /** + * Returns the end element of a selection range. If the end is in a text + * node the parent element will be returned. + * + * @method getEnd + * @return {Element} End element of selection range. + */ + getEnd: function() { + var self = this, rng = self.getRng(), endElement, endOffset; + + if (rng.duplicate || rng.item) { + if (rng.item) { + return rng.item(0); + } + + rng = rng.duplicate(); + rng.collapse(0); + endElement = rng.parentElement(); + if (endElement.ownerDocument !== self.dom.doc) { + endElement = self.dom.getRoot(); + } + + if (endElement && endElement.nodeName == 'BODY') { + return endElement.lastChild || endElement; + } + + return endElement; + } else { + endElement = rng.endContainer; + endOffset = rng.endOffset; + + if (endElement.nodeType == 1 && endElement.hasChildNodes()) { + endElement = endElement.childNodes[endOffset > 0 ? endOffset - 1 : endOffset]; + } + + if (endElement && endElement.nodeType == 3) { + return endElement.parentNode; + } + + return endElement; + } + }, + + /** + * Returns a bookmark location for the current selection. This bookmark object + * can then be used to restore the selection after some content modification to the document. + * + * @method getBookmark + * @param {Number} type Optional state if the bookmark should be simple or not. Default is complex. + * @param {Boolean} normalized Optional state that enables you to get a position that it would be after normalization. + * @return {Object} Bookmark object, use moveToBookmark with this object to restore the selection. + * @example + * // Stores a bookmark of the current selection + * var bm = tinymce.activeEditor.selection.getBookmark(); + * + * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content'); + * + * // Restore the selection bookmark + * tinymce.activeEditor.selection.moveToBookmark(bm); + */ + getBookmark: function(type, normalized) { + var t = this, dom = t.dom, rng, rng2, id, collapsed, name, element, chr = '', styles; + + function findIndex(name, element) { + var index = 0; + + each(dom.select(name), function(node, i) { + if (node == element) { + index = i; + } + }); + + return index; + } + + function normalizeTableCellSelection(rng) { + function moveEndPoint(start) { + var container, offset, childNodes, prefix = start ? 'start' : 'end'; + + container = rng[prefix + 'Container']; + offset = rng[prefix + 'Offset']; + + if (container.nodeType == 1 && container.nodeName == "TR") { + childNodes = container.childNodes; + container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)]; + if (container) { + offset = start ? 0 : container.childNodes.length; + rng['set' + (start ? 'Start' : 'End')](container, offset); + } + } + } + + moveEndPoint(true); + moveEndPoint(); + + return rng; + } + + 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) { + element = t.getNode(); + name = element.nodeName; + + if (name == 'IMG') { + return {name: name, index: findIndex(name, element)}; + } + + 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 = t.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('' + chr + ''); + + // Insert end marker + if (!collapsed) { + rng2.collapse(false); + + // Detect the empty space after block elements in IE and move the + // end back one character

    ] becomes

    ]

    + rng.moveToElementText(rng2.parentElement()); + if (rng.compareEndPoints('StartToEnd', rng2) === 0) { + rng2.move('character', -1); + } + + rng2.pasteHTML('' + chr + ''); + } + } 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)}; + } + + // W3C method + rng2 = normalizeTableCellSelection(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 = normalizeTableCellSelection(rng); + 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}; + }, + + /** + * Restores the selection to the specified bookmark. + * + * @method moveToBookmark + * @param {Object} bookmark Bookmark to restore selection from. + * @return {Boolean} true/false if it was successful or not. + * @example + * // Stores a bookmark of the current selection + * var bm = tinymce.activeEditor.selection.getBookmark(); + * + * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content'); + * + * // Restore the selection bookmark + * tinymce.activeEditor.selection.moveToBookmark(bm); + */ + moveToBookmark: function(bookmark) { + var t = this, dom = t.dom, 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(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 && !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 = '
    '; + } + + 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); + } + } + }, + + /** + * Selects the specified element. This will place the start and end of the selection range around the element. + * + * @method select + * @param {Element} node HMTL DOM element to select. + * @param {Boolean} content Optional bool state if the contents should be selected or not on non IE browser. + * @return {Element} Selected element the same element as the one that got passed in. + * @example + * // Select the first paragraph in the active editor + * tinymce.activeEditor.selection.select(tinymce.activeEditor.dom.select('p')[0]); + */ + 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 && 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) { + if (!content && t.controlSelection.controlSelect(node)) { + return; + } + + 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; + }, + + /** + * Returns true/false if the selection range is collapsed or not. Collapsed means if it's a caret or a larger selection. + * + * @method isCollapsed + * @return {Boolean} true/false state if the selection range is collapsed or not. + * Collapsed means if it's a caret or a larger selection. + */ + isCollapsed: function() { + var self = this, rng = self.getRng(), sel = self.getSel(); + + if (!rng || rng.item) { + return false; + } + + if (rng.compareEndPoints) { + return rng.compareEndPoints('StartToEnd', rng) === 0; + } + + return !sel || rng.collapsed; + }, + + /** + * Collapse the selection to start or end of range. + * + * @method collapse + * @param {Boolean} to_start Optional boolean state if to collapse to end or not. Defaults to start. + */ + 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); + }, + + /** + * Returns the browsers internal selection object. + * + * @method getSel + * @return {Selection} Internal browser selection object. + */ + getSel: function() { + var win = this.win; + + return win.getSelection ? win.getSelection() : win.document.selection; + }, + + /** + * Returns the browsers internal range object. + * + * @method getRng + * @param {Boolean} w3c Forces a compatible W3C range on IE. + * @return {Range} Internal browser range object. + * @see http://www.quirksmode.org/dom/range_intro.html + * @see http://www.dotvoid.com/2001/03/using-the-range-object-in-mozilla/ + */ + getRng: function(w3c) { + var self = this, selection, rng, elm, doc = self.win.document; + + // Found tridentSel object then we need to use that one + if (w3c && self.tridentSel) { + return self.tridentSel.getRangeAt(0); + } + + try { + if ((selection = self.getSel())) { + if (selection.rangeCount > 0) { + rng = selection.getRangeAt(0); + } else { + rng = selection.createRange ? selection.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 (isIE && rng && rng.setStart && doc.selection.createRange().item) { + elm = doc.selection.createRange().item(0); + rng = doc.createRange(); + rng.setStartBefore(elm); + rng.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 (!rng) { + rng = doc.createRange ? doc.createRange() : doc.body.createTextRange(); + } + + // If range is at start of document then move it to start of body + if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) { + elm = self.dom.getRoot(); + rng.setStart(elm, 0); + rng.setEnd(elm, 0); + } + + if (self.selectedRange && self.explicitRange) { + if (rng.compareBoundaryPoints(rng.START_TO_START, self.selectedRange) === 0 && + rng.compareBoundaryPoints(rng.END_TO_END, self.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. + rng = self.explicitRange; + } else { + self.selectedRange = null; + self.explicitRange = null; + } + } + + return rng; + }, + + /** + * Changes the selection to the specified DOM range. + * + * @method setRng + * @param {Range} rng Range to select. + */ + setRng: function(rng, forward) { + var self = this, sel; + + self.lastRng = null; + + // Is IE specific range + if (rng.select) { + try { + rng.select(); + } catch (ex) { + // Needed for some odd IE bug #1843306 + } + + return; + } + + if (!self.tridentSel) { + sel = self.getSel(); + + if (sel) { + self.explicitRange = rng; + + try { + sel.removeAllRanges(); + } catch (ex) { + // IE9 might throw errors here don't know why + } + + sel.addRange(rng); + + // Forward is set to false and we have an extend function + if (forward === false && sel.extend) { + sel.collapse(rng.endContainer, rng.endOffset); + sel.extend(rng.startContainer, rng.startOffset); + } + + // adding range isn't always successful so we need to check range count otherwise an exception can occur + self.selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null; + } + } else { + // Is W3C Range fake range on IE + if (rng.cloneRange) { + try { + self.tridentSel.addRange(rng); + return; + } catch (ex) { + //IE9 throws an error here if called before selection is placed in the editor + } + } + } + }, + + /** + * Sets the current selection to the specified DOM element. + * + * @method setNode + * @param {Element} elm Element to set as the contents of the selection. + * @return {Element} Returns the element that got passed in. + * @example + * // Inserts a DOM node at current selection/caret location + * tinymce.activeEditor.selection.setNode(tinymce.activeEditor.dom.create('img', {src: 'some.gif', title: 'some title'})); + */ + setNode: function(elm) { + var self = this; + + self.setContent(self.dom.getOuterHTML(elm)); + + return elm; + }, + + /** + * Returns the currently selected element or the common ancestor element for both start and end of the selection. + * + * @method getNode + * @return {Element} Currently selected element or common ancestor element. + * @example + * // Alerts the currently selected elements node name + * alert(tinymce.activeEditor.selection.getNode().nodeName); + */ + getNode: function() { + var self = this, rng = self.getRng(), elm; + var startContainer = rng.startContainer, endContainer = rng.endContainer; + var startOffset = rng.startOffset, endOffset = rng.endOffset; + + function skipEmptyTextNodes(node, forwards) { + var orig = node; + + while (node && node.nodeType === 3 && node.length === 0) { + node = forwards ? node.nextSibling : node.previousSibling; + } + + return node || orig; + } + + // Range maybe lost after the editor is made visible again + if (!rng) { + return self.dom.getRoot(); + } + + if (rng.setStart) { + elm = rng.commonAncestorContainer; + + // Handle selection a image or other control like element such as anchors + if (!rng.collapsed) { + if (startContainer == endContainer) { + if (endOffset - startOffset < 2) { + if (startContainer.hasChildNodes()) { + elm = startContainer.childNodes[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 (startContainer.nodeType === 3 && endContainer.nodeType === 3) { + if (startContainer.length === startOffset) { + startContainer = skipEmptyTextNodes(startContainer.nextSibling, true); + } else { + startContainer = startContainer.parentNode; + } + + if (endOffset === 0) { + endContainer = skipEmptyTextNodes(endContainer.previousSibling, false); + } else { + endContainer = endContainer.parentNode; + } + + if (startContainer && startContainer === endContainer) { + return startContainer; + } + } + } + + if (elm && elm.nodeType == 3) { + return elm.parentNode; + } + + return elm; + } + + return rng.item ? rng.item(0) : rng.parentElement(); + }, + + getSelectedBlocks: function(startElm, endElm) { + var self = this, dom = self.dom, node, selectedBlocks = []; + + startElm = dom.getParent(startElm || self.getStart(), dom.isBlock); + endElm = dom.getParent(endElm || self.getEnd(), dom.isBlock); + + if (startElm) { + selectedBlocks.push(startElm); + } + + if (startElm && endElm && startElm != endElm) { + node = startElm; + + var walker = new TreeWalker(startElm, dom.getRoot()); + while ((node = walker.next()) && node != endElm) { + if (dom.isBlock(node)) { + selectedBlocks.push(node); + } + } + } + + if (endElm && startElm != endElm) { + selectedBlocks.push(endElm); + } + + return selectedBlocks; + }, + + isForward: function(){ + var dom = this.dom, sel = this.getSel(), anchorRange, focusRange; + + // No support for selection direction then always return true + if (!sel || !sel.anchorNode || !sel.focusNode) { + return true; + } + + anchorRange = dom.createRng(); + anchorRange.setStart(sel.anchorNode, sel.anchorOffset); + anchorRange.collapse(true); + + focusRange = dom.createRng(); + focusRange.setStart(sel.focusNode, sel.focusOffset); + focusRange.collapse(true); + + return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0; + }, + + normalize: function() { + var self = this, rng, normalized, collapsed; + + function normalizeEndPoint(start) { + var container, offset, walker, dom = self.dom, body = dom.getRoot(), node, nonEmptyElementsMap, nodeName; + + function hasBrBeforeAfter(node, left) { + var walker = new TreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || body); + + while ((node = walker[left ? 'prev' : 'next']())) { + if (node.nodeName === "BR") { + return true; + } + } + } + + function isPrevNode(node, name) { + return node.previousSibling && node.previousSibling.nodeName == name; + } + + // 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 = dom.getRoot(); + 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()) { + offset = Math.min(!start && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1); + container = container.childNodes[offset]; + offset = 0; + + // Don't walk into elements that doesn't have any child nodes like a IMG + if (container.hasChildNodes() && !/TABLE/.test(container.nodeName)) { + // 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: x|x + // Becomes: x|x + // 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: |
    + // Becomes: |
    + // Seems that only gecko has issues with this. + // Special edge case for

    x|

    since we don't want

    x|

    + if (container.nodeType === 1) { + node = container.childNodes[offset]; + if(node && node.nodeName === 'BR' && !isPrevNode(node, 'A') && + !hasBrBeforeAfter(node) && !hasBrBeforeAfter(node, true)) { + findTextNodeRelative(true, container.childNodes[offset]); + } + } + } + + // Lean the start of the selection right if possible + // So this: x[x] + // Becomes: x[x] + 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); + } + } + + // Normalize only on non IE browsers for now + if (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, self.isForward()); + } + }, + + /** + * Executes callback of the current selection matches the specified selector or not and passes the state and args to the callback. + * + * @method selectorChanged + * @param {String} selector CSS selector to check for. + * @param {function} callback Callback with state and args when the selector is matches or not. + */ + selectorChanged: function(selector, callback) { + var self = this, currentSelectors; + + if (!self.selectorChangedData) { + self.selectorChangedData = {}; + currentSelectors = {}; + + self.editor.on('NodeChange', function(e) { + var node = e.element, dom = self.dom, parents = dom.getParents(node, null, dom.getRoot()), matchedSelectors = {}; + + // Check for new matching selectors + each(self.selectorChangedData, function(callbacks, selector) { + each(parents, function(node) { + if (dom.is(node, selector)) { + if (!currentSelectors[selector]) { + // Execute callbacks + each(callbacks, function(callback) { + callback(true, {node: node, selector: selector, parents: parents}); + }); + + currentSelectors[selector] = callbacks; + } + + matchedSelectors[selector] = callbacks; + return false; + } + }); + }); + + // Check if current selectors still match + each(currentSelectors, function(callbacks, selector) { + if (!matchedSelectors[selector]) { + delete currentSelectors[selector]; + + each(callbacks, function(callback) { + callback(false, {node: node, selector: selector, parents: parents}); + }); + } + }); + }); + } + + // Add selector listeners + if (!self.selectorChangedData[selector]) { + self.selectorChangedData[selector] = []; + } + + self.selectorChangedData[selector].push(callback); + + return self; + }, + + scrollIntoView: function(elm) { + var y, viewPort, self = this, dom = self.dom; + + viewPort = dom.getViewPort(self.editor.getWin()); + y = dom.getPos(elm).y; + if (y < viewPort.y || y + 25 > viewPort.y + viewPort.h) { + self.editor.getWin().scrollTo(0, y < viewPort.y ? y : y - viewPort.h + 25); + } + }, + + destroy: function() { + this.win = this.lastRng = null; + this.controlSelection.destroy(); + } + }; + + return Selection; +}); + +// Included from: js/tinymce/classes/dom/RangeUtils.js + +/** + * Range.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/dom/RangeUtils", [ + "tinymce/util/Tools" +], function(Tools) { + var each = Tools.each; + + function RangeUtils(dom) { + /** + * Walks the specified range like object and executes the callback for each sibling collection it finds. + * + * @param {Object} rng Range like object. + * @param {function} callback Callback function to execute for each sibling collection. + */ + 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.mce-item-selected,th.mce-item-selected'); + if (nodes.length > 0) { + each(nodes, function(node) { + callback([node]); + }); + + return; + } + + /** + * Excludes start/end text node if they are out side the range + * + * @private + * @param {Array} nodes Nodes to exclude items from. + * @return {Array} Array with nodes excluding the start/end container if needed. + */ + 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; + } + + /** + * Collects siblings + * + * @private + * @param {Node} node Node to collect siblings from. + * @param {String} name Name of the sibling to check for. + * @return {Array} Array of collected siblings. + */ + function collectSiblings(node, name, end_node) { + var siblings = []; + + for (; node && node != end_node; node = node[name]) { + siblings.push(node); + } + + return siblings; + } + + /** + * Find an end point this is the node just before the common ancestor root. + * + * @private + * @param {Node} node Node to start at. + * @param {Node} root Root/ancestor element to stop just before. + * @return {Node} Node just before the root element. + */ + 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); + }; + + /** + * Splits the specified range at it's start/end points. + * + * @param {Range/RangeObject} rng Range to split. + * @return {Object} Range position object. + */ + 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 + }; + }; + } + + /** + * Compares two ranges and checks if they are equal. + * + * @static + * @param {DOMRange} rng1 First range to compare. + * @param {DOMRange} rng2 First range to compare. + * @return {Boolean} true/false if the ranges are equal. + */ + 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; + }; + + return RangeUtils; +}); + +// Included from: js/tinymce/classes/Formatter.js + +/** + * Formatter.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Text formatter engine class. This class is used to apply formats like bold, italic, font size + * etc to the current selection or specific nodes. This engine was build to replace the browsers + * default formatting logic for execCommand due to it's inconsistant and buggy behavior. + * + * @class tinymce.Formatter + * @example + * tinymce.activeEditor.formatter.register('mycustomformat', { + * inline: 'span', + * styles: {color: '#ff0000'} + * }); + * + * tinymce.activeEditor.formatter.apply('mycustomformat'); + */ +define("tinymce/Formatter", [ + "tinymce/dom/TreeWalker", + "tinymce/dom/RangeUtils", + "tinymce/util/Tools" +], function(TreeWalker, RangeUtils, Tools) { + /** + * Constructs a new formatter instance. + * + * @constructor Formatter + * @param {tinymce.Editor} ed Editor instance to construct the formatter engine to. + */ + return function(ed) { + var formats = {}, + dom = ed.dom, + selection = ed.selection, + rangeUtils = new RangeUtils(dom), + isValid = ed.schema.isValidChild, + isBlock = dom.isBlock, + forcedRootBlock = ed.settings.forced_root_block, + nodeIndex = dom.nodeIndex, + INVISIBLE_CHAR = '\uFEFF', + MCE_ATTR_RE = /^(src|href|style)$/, + FALSE = false, + TRUE = true, + formatChangeData, + undef, + getContentEditable = dom.getContentEditable, + disableCaretContainer, + markCaretContainersBogus; + + var each = Tools.each, + grep = Tools.grep, + walk = Tools.walk, + extend = Tools.extend; + + function isTextBlock(name) { + if (name.nodeType) { + name = name.nodeName; + } + + return !!ed.schema.getTextBlockElements()[name.toLowerCase()]; + } + + 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,tr,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,tr,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,tr,div,ul,ol,li', styles: {textAlign: 'right'}, defaultBlock: 'div'}, + {selector: 'img,table', collapsed: false, styles: {'float': 'right'}} + ], + + alignjustify: [ + {selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,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'}, + code: {inline: 'code'}, + + link: {inline: 'a', selector: 'a', remove: 'all', split: true, deep: true, + onmatch: function() { + 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 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 + + /** + * Returns the format by name or all formats if no name is specified. + * + * @method get + * @param {String} name Optional name to retrive by. + * @return {Array/Object} Array/Object with all registred formats or a specific format. + */ + function get(name) { + return name ? formats[name] : formats; + } + + /** + * Registers a specific format by name. + * + * @method register + * @param {Object/String} name Name of the format for example "bold". + * @param {Object/Array} format Optional format object or array of format variants + * can only be omitted if the first arg is an object. + */ + 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; + } + } + } + + function getTextDecoration(node) { + var decoration; + + ed.dom.getParent(node, function(n) { + decoration = ed.dom.getStyle(n, 'text-decoration'); + return decoration && decoration !== 'none'; + }); + + return decoration; + } + + function processUnderlineAndColor(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); + } + } + } + + /** + * Applies the specified format to the current selection or specified node. + * + * @method apply + * @param {String} name Name of format to apply. + * @param {Object} vars Optional list of variables to replace within format before applying it. + * @param {Node} node Optional node to apply the format to defaults to current selection. + */ + function apply(name, vars, node) { + var formatList = get(name), format = formatList[0], bookmark, rng, isCollapsed = !node && 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(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(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; + + /** + * Process a list of nodes wrap them. + */ + 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 + // TODO: Break this if up, too complex + if (contentEditable && !hasContentEditableState && format.block && + !format.wrapper && isTextBlock(nodeName) && isValid(parentName, wrapName)) { + 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 + // TODO: Break this if up, too complex + 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) && + (!format.inline || !isBlock(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(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 = grep(node.childNodes); + for (i = 0; i < children.length; i++) { + currentWrapElm.appendChild(children[i]); + } + + node.appendChild(currentWrapElm); + } + + each(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

    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: text + // will become: text + 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 texttext becomes texttext + 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.mce-item-selected,th.mce-item-selected').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)) { + walk(curSelNode, processUnderlineAndColor, 'childNodes'); + processUnderlineAndColor(curSelNode); + } + + selection.moveToBookmark(bookmark); + moveStart(selection.getRng(TRUE)); + ed.nodeChanged(); + } else { + performCaretAction('apply', name, vars); + } + } + } + } + + /** + * Removes the specified format from the current selection or specified node. + * + * @method remove + * @param {String} name Name of format to remove. + * @param {Object} vars Optional list of variables to replace within format before removing it. + * @param {Node/Range} node Optional node or DOM range to remove the format from defaults to current selection. + */ + function remove(name, vars, node) { + var formatList = get(name), format = formatList[0], bookmark, rng, contentEditable = true; + + // Merges the styles for each node + function process(node) { + var children, i, l, 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 = 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; + + 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 + if (/^(TR|TD)$/.test(startContainer.nodeName) && startContainer.firstChild) { + if (startContainer.nodeName == "TD") { + startContainer = startContainer.firstChild || startContainer; + } else { + startContainer = startContainer.firstChild.firstChild || startContainer; + } + } + + // 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.mce-item-selected,th.mce-item-selected').length) { + bookmark = selection.getBookmark(); + removeRngStyle(selection.getRng(TRUE)); + selection.moveToBookmark(bookmark); + + // Check if start element still has formatting then we are at: "text|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); + } + } + + /** + * Toggles the specified format on/off. + * + * @method toggle + * @param {String} name Name of format to apply/remove. + * @param {Object} vars Optional list of variables to replace within format before applying/removing it. + * @param {Node} node Optional node to apply the format to or remove from. Defaults to current selection. + */ + 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); + } + } + + /** + * Return true/false if the specified node has the specified format. + * + * @method matchNode + * @param {Node} node Node to check the format on. + * @param {String} name Format name to check. + * @param {Object} vars Optional list of variables to replace before checking it. + * @param {Boolean} similar Match format that has similar properties. + * @return {Object} Returns the format object it matches or undefined if it doesn't match. + */ + 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; + } + } + } + } + + /** + * Matches the current selection or specified node against the specified format name. + * + * @method match + * @param {String} name Name of format to match. + * @param {Object} vars Optional list of variables to replace before checking it. + * @param {Node} node Optional node to check. + * @return {boolean} true/false if the specified selection/node matches the 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; + } + + /** + * Matches the current selection against the array of formats and returns a new array with matching formats. + * + * @method matchAll + * @param {Array} names Name of format to match. + * @param {Object} vars Optional list of variables to replace before checking it. + * @return {Array} Array with matched formats. + */ + function matchAll(names, vars) { + var startElement, matchedFormatNames = [], checkedMap = {}; + + // 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); + } + } + }, dom.getRoot()); + + return matchedFormatNames; + } + + /** + * Returns true/false if the specified format can be applied to the current selection or not. It + * will currently only check the state for selector formats, it returns true on all other format types. + * + * @method canApply + * @param {String} name Name of format to check. + * @return {boolean} true/false if the specified format can be applied to the current selection/node. + */ + 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; + } + + /** + * Executes the specified callback when the current selection matches the formats or not. + * + * @method formatChanged + * @param {String} formats Comma separated list of formats to check for. + * @param {function} callback Callback with state and args when the format is changed/toggled on/off. + * @param {Boolean} similar True/false state if the match should handle similar or exact formats. + */ + function formatChanged(formats, callback, similar) { + var currentFormats; + + // Setup format node change logic + if (!formatChangeData) { + formatChangeData = {}; + currentFormats = {}; + + ed.on('NodeChange', function(e) { + var parents = getParents(e.element), matchedFormats = {}; + + // Check for new formats + each(formatChangeData, function(callbacks, format) { + each(parents, function(node) { + if (matchNode(node, format, {}, callbacks.similar)) { + if (!currentFormats[format]) { + // Execute callbacks + each(callbacks, function(callback) { + callback(true, {node: node, format: format, parents: parents}); + }); + + currentFormats[format] = callbacks; + } + + matchedFormats[format] = callbacks; + return false; + } + }); + }); + + // Check if current formats still match + each(currentFormats, function(callbacks, format) { + if (!matchedFormats[format]) { + delete currentFormats[format]; + + each(callbacks, function(callback) { + callback(false, {node: e.element, format: format, parents: parents}); + }); + } + }); + }); + } + + // Add format listeners + each(formats.split(','), function(format) { + if (!formatChangeData[format]) { + formatChangeData[format] = []; + formatChangeData[format].similar = similar; + } + + formatChangeData[format].push(callback); + }); + + return this; + } + + // Expose to public + extend(this, { + get: get, + register: register, + apply: apply, + remove: remove, + toggle: toggle, + match: match, + matchAll: matchAll, + matchNode: matchNode, + canApply: canApply, + formatChanged: formatChanged + }); + + // Initialize + defaultFormats(); + addKeyboardShortcuts(); + ed.on('BeforeGetContent', function() { + if (markCaretContainersBogus) { + markCaretContainersBogus(); + } + }); + ed.on('mouseup keydown', function(e) { + if (disableCaretContainer) { + disableCaretContainer(e); + } + }); + + // Private functions + + /** + * Checks if the specified nodes name matches the format inline/block or selector. + * + * @private + * @param {Node} node Node to match against the specified format. + * @param {Object} format Format object o match with. + * @return {boolean} true/false if the format matches. + */ + 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 node.nodeType == 1 && dom.is(node, format.selector); + } + } + + /** + * Compares two string/nodes regardless of their case. + * + * @private + * @param {String/Node} Node or string to compare. + * @param {String/Node} Node or string to compare. + * @return {boolean} True/false if they match. + */ + function isEq(str1, str2) { + str1 = str1 || ''; + str2 = str2 || ''; + + str1 = '' + (str1.nodeName || str1); + str2 = '' + (str2.nodeName || str2); + + return str1.toLowerCase() == str2.toLowerCase(); + } + + /** + * Returns the style by name on the specified node. This method modifies the style + * contents to make it more easy to match. This will resolve a few browser issues. + * + * @private + * @param {Node} node to get style from. + * @param {String} name Style name to get. + * @return {String} Style item value. + */ + 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; + } + + /** + * Replaces variables in the value. The variable format is %var. + * + * @private + * @param {String} value Value to replace variables in. + * @param {Object} vars Name/value array with variables to replace. + * @return {String} New value with replaced variables. + */ + 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; + } + + /** + * Expands the specified range like object to depending on format. + * + * For example on block formats it will move the start/end position + * to the beginning of the current block. + * + * @private + * @param {Object} rng Range like object. + * @param {Array} formats Array with formats to expand by. + * @return {Object} Expanded range like object. + */ + function expandRng(rng, format, remove) { + var 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, sibling, siblingName, root; + + container = parent = start ? startContainer : endContainer; + siblingName = start ? 'previousSibling' : 'nextSibling'; + root = dom.getRoot(); + + function isBogusBr(node) { + return node.nodeName == "BR" && node.getAttribute('data-mce-bogus') && !node.nextSibling; + } + + // 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) && !isBogusBr(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) { + 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, isTextBlock); + } + + // 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 !: !

    *texttext*

    ! + // 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 + }; + } + + /** + * Removes the specified format for the specified node. It will also remove the node if it doesn't have + * any attributes if the format specifies it to do so. + * + * @private + * @param {Object} format Format object with items to remove from node. + * @param {Object} vars Name/value object with variables to apply to format. + * @param {Node} node Node to remove the format styles on. + * @param {Node} compare_node Optional compare node, if specified the styles will be compared to that node. + * @return {Boolean} True/false if the node was removed or not. + */ + 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 or + if (format.remove != 'none') { + removeNode(node, format); + return TRUE; + } + } + + /** + * Removes the node and wrap it's children in paragraphs before doing so or + * appends BR elements to the beginning/end of the block element if forcedRootBlocks is disabled. + * + * If the div in the node below gets removed: + * text
    text
    text + * + * Output becomes: + * text

    text
    text + * + * So when the div is removed the result is: + * text
    text
    text + * + * @private + * @param {Node} node Node to remove + apply BR/P elements to. + * @param {Object} format Format rule. + * @return {Node} Input node. + */ + 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(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); + } + + /** + * Returns the next/previous non whitespace node. + * + * @private + * @param {Node} node Node to start at. + * @param {boolean} next (Optional) Include next or previous node defaults to previous. + * @param {boolean} inc (Optional) Include the current node in checking. Defaults to false. + * @return {Node} Next or previous node or undefined if it wasn't found. + */ + 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; + } + } + } + } + + /** + * Checks if the specified node is a bookmark node or not. + * + * @param {Node} node Node to check if it's a bookmark node or not. + * @return {Boolean} true/false if the node is a bookmark node. + */ + function isBookmarkNode(node) { + return node && node.nodeType == 1 && node.getAttribute('data-mce-type') == 'bookmark'; + } + + /** + * Merges the next/previous sibling element if they match. + * + * @private + * @param {Node} prev Previous node to compare/merge. + * @param {Node} next Next node to compare/merge. + * @return {Node} Next node if we didn't merge and prev node if we did. + */ + function mergeSiblings(prev, next) { + var sibling, tmpSibling; + + /** + * Compares two nodes and checks if it's attributes and styles matches. + * This doesn't compare classes as items since their order is significant. + * + * @private + * @param {Node} node1 First node to compare with. + * @param {Node} node2 Second node to compare with. + * @return {boolean} True/false if the nodes are the same or not. + */ + function compareElements(node1, node2) { + // Not the same name + if (node1.nodeName != node2.nodeName) { + return FALSE; + } + + /** + * Returns all the nodes attributes excluding internal ones, styles and classes. + * + * @private + * @param {Node} node Node to get attributes from. + * @return {Object} Name/value object with attributes and attribute values. + */ + 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; + } + + /** + * Compares two objects checks if it's key + value exists in the other one. + * + * @private + * @param {Object} obj1 First object to compare. + * @param {Object} obj2 Second object to compare. + * @return {boolean} True/false if the objects matches or not. + */ + 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(grep(next.childNodes), function(node) { + prev.appendChild(node); + }); + + return prev; + } + } + + return next; + } + + function getContainer(rng, start) { + var container, offset, lastIdx; + + 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); + } + } + + // Checks if the parent caret container node isn't empty if that is the case it + // will remove the bogus state on all children that isn't empty + function unmarkBogusCaretParents() { + var caretContainer; + + caretContainer = getParentCaretContainer(selection.getStart()); + if (caretContainer && !dom.isEmpty(caretContainer)) { + walk(caretContainer, function(node) { + if (node.nodeType == 1 && node.id !== caretContainerId && !dom.isEmpty(node)) { + dom.setAttrib(node, 'data-mce-bogus', null); + } + }, 'childNodes'); + } + } + + // Only bind the caret events once + if (!ed._hasCaretEvents) { + // Mark current caret container elements as bogus when getting the contents so we don't end up with empty elements + markCaretContainersBogus = 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'); + } + } + }; + + disableCaretContainer = function(e) { + var keyCode = e.keyCode; + + removeCaretContainer(); + + // Remove caret container on keydown and it's a backspace, enter or left/right arrow keys + if (keyCode == 8 || keyCode == 37 || keyCode == 39) { + removeCaretContainer(getParentCaretContainer(selection.getStart())); + } + + unmarkBogusCaretParents(); + }; + + // Remove bogus state if they got filled by contents using editor.selection.setContent + ed.on('SetContent', function(e) { + if (e.selection) { + unmarkBogusCaretParents(); + } + }); + ed._hasCaretEvents = true; + } + + // Do apply or remove caret format + if (type == "apply") { + applyCaretFormat(); + } else { + removeCaretFormat(); + } + } + + /** + * Moves the start to the first suitable text node. + */ + 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; + } + } + } + } + }; +}); + +// Included from: js/tinymce/classes/UndoManager.js + +/** + * UndoManager.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles the undo/redo history levels for the editor. Since the build in undo/redo has major drawbacks a custom one was needed. + * + * @class tinymce.UndoManager + */ +define("tinymce/UndoManager", [ + "tinymce/Env", + "tinymce/util/Tools" +], function(Env, Tools) { + var trim = Tools.trim, trimContentRegExp; + + trimContentRegExp = new RegExp([ + ']+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\\/span>', // Trim bogus spans like caret containers + ']+data-mce-bogus[^>]+><\\/div>', // Trim bogus divs like resize handles + '\\s?data-mce-selected="[^"]+"' // Trim temporaty data-mce prefixed attributes like data-mce-selected + ].join('|'), 'gi'); + + return function(editor) { + var self, index = 0, data = [], beforeBookmark; + + // Returns a trimmed version of the current editor contents + function getContent() { + return trim(editor.getContent({format: 'raw', no_events: 1}).replace(trimContentRegExp, '')); + } + + function addNonTypingUndoLevel() { + self.typing = false; + self.add(); + } + + // Add initial undo level when the editor is initialized + editor.on('init', function() { + self.add(); + }); + + // Get position before an execCommand is processed + editor.on('BeforeExecCommand', function(e) { + var cmd = e.command; + + if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint') { + self.beforeChange(); + } + }); + + // Add undo level after an execCommand call was made + editor.on('ExecCommand', function(e) { + var cmd = e.command; + + if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint') { + self.add(); + } + }); + + editor.on('ObjectResizeStart', function() { + self.beforeChange(); + }); + + editor.on('SaveContent ObjectResized', addNonTypingUndoLevel); + editor.dom.bind(editor.dom.getRoot(), 'dragend', addNonTypingUndoLevel); + editor.dom.bind(editor.getBody(), 'focusout', function() { + if (!editor.removed && self.typing) { + addNonTypingUndoLevel(); + } + }); + + editor.on('KeyUp', function(e) { + var keyCode = e.keyCode; + + if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 45 || keyCode == 13 || e.ctrlKey) { + addNonTypingUndoLevel(); + editor.nodeChanged(); + } + + if (keyCode == 46 || keyCode == 8 || (Env.isMac && (keyCode == 91 || keyCode == 93))) { + editor.nodeChanged(); + } + }); + + editor.on('KeyDown', function(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.on('MouseDown', function() { + 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'); + + editor.on('AddUndo Undo Redo ClearUndos MouseUp', function(e) { + if (!e.isDefaultPrevented()) { + editor.nodeChanged(); + } + }); + + self = { + // Explose for debugging reasons + data: data, + + /** + * State if the user is currently typing or not. This will add a typing operation into one undo + * level instead of one new level for each keystroke. + * + * @field {Boolean} typing + */ + typing: false, + + /** + * Stores away a bookmark to be used when performing an undo action so that the selection is before + * the change has been made. + * + * @method beforeChange + */ + beforeChange: function() { + beforeBookmark = editor.selection.getBookmark(2, true); + }, + + /** + * Adds a new undo level/snapshot to the undo list. + * + * @method add + * @param {Object} l Optional undo level object to add. + * @return {Object} Undo level that got added or null it a level wasn't needed. + */ + add: function(level) { + var i, settings = editor.settings, lastLevel; + + level = level || {}; + level.content = getContent(); + + if (editor.fire('BeforeAddUndo', {level: level}).isDefaultPrevented()) { + return null; + } + + // 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; + + editor.fire('AddUndo', {level: level, lastLevel: lastLevel}); + editor.isNotDirty = 0; + + return level; + }, + + /** + * Undoes the last action. + * + * @method undo + * @return {Object} Undo level or null if no undo was performed. + */ + undo: function() { + var level; + + 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); + + editor.fire('undo', {level: level}); + } + + return level; + }, + + /** + * Redoes the last action. + * + * @method redo + * @return {Object} Redo level or null if no redo was performed. + */ + redo: function() { + var level; + + if (index < data.length - 1) { + level = data[++index]; + + editor.setContent(level.content, {format: 'raw'}); + editor.selection.moveToBookmark(level.bookmark); + + editor.fire('redo', {level: level}); + } + + return level; + }, + + /** + * Removes all undo levels. + * + * @method clear + */ + clear: function() { + data = []; + index = 0; + self.typing = false; + editor.fire('ClearUndos'); + }, + + /** + * Returns true/false if the undo manager has any undo levels. + * + * @method hasUndo + * @return {Boolean} true/false if the undo manager has any undo levels. + */ + hasUndo: function() { + // Has undo levels or typing and content isn't the same as the initial level + return index > 0 || (self.typing && data[0] && getContent() != data[0].content); + }, + + /** + * Returns true/false if the undo manager has any redo levels. + * + * @method hasRedo + * @return {Boolean} true/false if the undo manager has any redo levels. + */ + hasRedo: function() { + return index < data.length - 1 && !this.typing; + }, + + /** + * Executes the specified function in an undo transation. The selection + * before the modification will be stored to the undo stack and if the DOM changes + * it will add a new undo level. + * + * @method transact + * @params {function} callback + */ + transact: function(callback) { + self.beforeChange(); + callback(); + self.add(); + } + }; + + return self; + }; +}); + +// Included from: js/tinymce/classes/EnterKey.js + +/** + * EnterKey.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Contains logic for handling the enter key to split/generate block elements. + */ +define("tinymce/EnterKey", [ + "tinymce/dom/TreeWalker", + "tinymce/Env" +], function(TreeWalker, Env) { + var isIE = Env.ie; + + return function(editor) { + var dom = editor.dom, selection = editor.selection, settings = editor.settings; + var undoManager = editor.undoManager, schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements(); + + function handleEnterKey(evt) { + var rng = selection.getRng(true), tmpRng, editableRoot, container, offset, parentBlock, documentMode, shiftKey, + 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|FORM)$/.test(node.nodeName) && + !/^(fixed|absolute)/i.test(node.style.position) && + dom.getContentEditable(node) !== "true"; + } + + // Renders empty block on IE + function renderBlockOnIE(block) { + var oldRng; + + if (dom.isBlock(block)) { + oldRng = selection.getRng(); + block.appendChild(dom.create('span', null, '\u00a0')); + selection.select(block); + block.lastChild.outerHTML = ''; + selection.setRng(oldRng); + } + } + + // Remove the first empty inline element of the block so this:

    x

    becomes this:

    x

    + function trimInlineElementsOnLeftSideOfBlock(block) { + var node = block, firstChilds = [], i; + + // Find inner most first child ex:

    *

    + while ((node = node.firstChild)) { + if (dom.isBlock(node)) { + return; + } + + if (node.nodeType == 1 && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) { + firstChilds.push(node); + } + } + + i = firstChilds.length; + while (i--) { + node = firstChilds[i]; + if (!node.hasChildNodes() || (node.firstChild == node.lastChild && node.firstChild.nodeValue === '')) { + dom.remove(node); + } else { + // Remove see #5381 + if (node.nodeName == "A" && (node.innerText || node.textContent) === ' ') { + dom.remove(node); + } + } + } + } + + // 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, 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 (nonEmptyElementsMap[node.nodeName.toLowerCase()]) { + 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); + selection.scrollIntoView(root); + } + + // 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)) { + // Never clone a caret containers + if (node.id == '_mce_caret') { + continue; + } + + 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 (!isIE) { + caretNode.innerHTML = '
    '; + } + + 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; + } + + // If the caret if before the first element in parentBlock + if (start && container.nodeType == 1 && container == parentBlock.firstChild) { + 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); + + // If caret is in beginning or end of a text block then jump to the next/previous node + if (container.nodeType == 3) { + if (start && offset === 0) { + walker.prev(); + } else if (!start && offset == container.nodeValue.length) { + walker.next(); + } + } + + while ((node = walker.current())) { + if (node.nodeType === 1) { + // Ignore bogus elements + if (!node.getAttribute('data-mce-bogus')) { + // Keep empty elements like but not trailing br:s like

    text|

    + name = node.nodeName.toLowerCase(); + if (nonEmptyElementsMap[name] && name !== 'br') { + return false; + } + } + } else if (node.nodeType === 3 && !/^[ \t\r\n]*$/.test(node.nodeValue)) { + return false; + } + + if (start) { + walker.prev(); + } else { + walker.next(); + } + } + + 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, rootBlockName, blockName = newBlockName || 'P'; + + // Not in a block element or in a table cell or caption + parentBlock = dom.getParent(container, dom.isBlock); + rootBlockName = editor.getBody().nodeName.toLowerCase(); + 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 && schema.isValidChild(rootBlockName, blockName.toLowerCase())) { + 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; + } + + function getContainerBlock() { + var containerBlockParent = containerBlock.parentNode; + + if (containerBlockParent.nodeName == 'LI') { + return containerBlockParent; + } + + return containerBlock; + } + + // Check if we are in an nested list + var containerBlockParentName = containerBlock.parentNode.nodeName; + if (/^(OL|UL|LI)$/.test(containerBlockParentName)) { + newBlockName = 'LI'; + } + + newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR'); + + if (isFirstOrLastLi(true) && isFirstOrLastLi()) { + if (containerBlockParentName == 'LI') { + // Nested list is inside a LI + dom.insertAfter(newBlock, getContainerBlock()); + } else { + // Is first and last list item then replace the OL/UL with a text block + dom.replace(newBlock, containerBlock); + } + } else if (isFirstOrLastLi(true)) { + if (containerBlockParentName == 'LI') { + // List nested in an LI then move the list to a new sibling LI + dom.insertAfter(newBlock, getContainerBlock()); + newBlock.appendChild(dom.doc.createTextNode(' ')); // Needed for IE so the caret can be placed + newBlock.appendChild(containerBlock); + } else { + // 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 remove LI and add text block after list + dom.insertAfter(newBlock, getContainerBlock()); + renderBlockOnIE(newBlock); + } 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 + containerBlock = getContainerBlock(); + 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 hasRightSideContent() { + var walker = new TreeWalker(container, parentBlock), node; + + while ((node = walker.next())) { + if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) { + return true; + } + } + } + + // Inserts a BR element if the forced_root_block option is set to false or empty string + function insertBr() { + var brElm, extraBr, marker; + + if (container && container.nodeType == 3 && offset >= container.nodeValue.length) { + // Insert extra BR element at the end block elements + if (!isIE && !hasRightSideContent()) { + 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 (isIE && parentBlockName == 'PRE' && (!documentMode || documentMode < 8)) { + brElm.parentNode.insertBefore(dom.doc.createTextNode('\r'), brElm); + } + + // Insert temp marker and scroll to that + marker = dom.create('span', {}, ' '); + brElm.parentNode.insertBefore(marker, brElm); + selection.scrollIntoView(marker); + dom.remove(marker); + + 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; + } + + // Adds a BR at the end of blocks that only contains an IMG or INPUT since + // these might be floated and then they won't expand the block + function addBrToBlockIfNeeded(block) { + var lastChild; + + // IE will render the blocks correctly other browsers needs a BR + if (!isIE) { + block.normalize(); // Remove empty text nodes that got left behind by the extract + + // Check if the block is empty or contains a floated last child + lastChild = block.lastChild; + if (!lastChild || (/^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true)))) { + dom.add(block, 'br'); + } + } + } + + // 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.force_p_newlines ? 'p' : '') || settings.forced_root_block; + newBlockName = newBlockName ? newBlockName.toUpperCase() : ''; + documentMode = dom.doc.documentMode; + shiftKey = evt.shiftKey; + + // 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; + if (isAfterLastNodeInContainer && container.nodeType == 3) { + offset = container.nodeValue.length; + } else { + 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 || shiftKey) { + insertBr(); + } + + return; + } + + // Wrap the current node and it's sibling in a default block if it's needed. + // for example this text|text2 will become this

    text|text2

    + // This won't happen if root blocks are disabled or the shiftKey is pressed + if ((newBlockName && !shiftKey) || (!newBlockName && 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 + + // Enter inside block contained within a LI then split or insert before/after LI + if (containerBlockName == 'LI' && !evt.ctrlKey) { + parentBlock = containerBlock; + parentBlockName = containerBlockName; + } + + // Handle enter in LI + if (parentBlockName == 'LI') { + if (!newBlockName && shiftKey) { + insertBr(); + return; + } + + // Handle enter inside an empty list item + if (dom.isEmpty(parentBlock)) { + 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 (!shiftKey) { + insertBr(); + return; + } + } else { + // If no root block is configured then insert a BR by default or if the shiftKey is pressed + if ((!newBlockName && !shiftKey && parentBlockName != 'LI') || (newBlockName && shiftKey)) { + insertBr(); + return; + } + } + + // If parent block is root then never insert new blocks + if (newBlockName && parentBlock === editor.getBody()) { + 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|FIGURE)$/.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); + } + + moveToCaretPosition(newBlock); + } else if (isCaretAtStartOrEndOfBlock(true)) { + // Insert new block before + newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock); + renderBlockOnIE(newBlock); + } 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); + trimInlineElementsOnLeftSideOfBlock(newBlock); + addBrToBlockIfNeeded(parentBlock); + moveToCaretPosition(newBlock); + } + + dom.setAttrib(newBlock, 'id', ''); // Remove ID since it needs to be document unique + undoManager.add(); + } + + editor.on('keydown', function(evt) { + if (evt.keyCode == 13) { + if (handleEnterKey(evt) !== false) { + evt.preventDefault(); + } + } + }); + }; +}); + +// Included from: js/tinymce/classes/ForceBlocks.js + +/** + * ForceBlocks.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/ForceBlocks", [], function() { + return function(editor) { + var settings = editor.settings, dom = editor.dom, selection = editor.selection; + var schema = editor.schema, blockElements = schema.getBlockElements(); + + function addRootBlocks() { + var node = selection.getStart(), rootNode = editor.getBody(), rng; + var startContainer, startOffset, endContainer, endOffset, rootBlockNode; + var tempNode, offset = -0xFFFFFF, wrapped, restoreSelection; + var tmpRng, rootNodeName, forcedRootBlock; + + forcedRootBlock = settings.forced_root_block; + + if (!node || node.nodeType !== 1 || !forcedRootBlock) { + return; + } + + // Check if node is wrapped in block + while (node && 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; + restoreSelection = editor.getDoc().activeElement === rootNode; + } else { + // Force control range into text range + if (rng.item) { + node = rng.item(0); + rng = editor.getDoc().body.createTextRange(); + rng.moveToElementText(node); + } + + restoreSelection = rng.parentElement().ownerDocument === editor.getDoc(); + 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; + rootNodeName = rootNode.nodeName.toLowerCase(); + while (node) { + // TODO: Break this up, too complex + if (((node.nodeType === 3 || (node.nodeType == 1 && !blockElements[node.nodeName]))) && + schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase())) { + // Remove empty text nodes + if (node.nodeType === 3 && node.nodeValue.length === 0) { + tempNode = node; + node = node.nextSibling; + dom.remove(tempNode); + continue; + } + + if (!rootBlockNode) { + rootBlockNode = dom.create(forcedRootBlock); + node.parentNode.insertBefore(rootBlockNode, node); + wrapped = true; + } + + tempNode = node; + node = node.nextSibling; + rootBlockNode.appendChild(tempNode); + } else { + rootBlockNode = null; + node = node.nextSibling; + } + } + + if (wrapped && restoreSelection) { + if (rng.setStart) { + rng.setStart(startContainer, startOffset); + rng.setEnd(endContainer, endOffset); + selection.setRng(rng); + } else { + // Only select if the previous selection was inside the document to prevent auto focus in quirks mode + 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.on('KeyUp NodeChange', addRootBlocks); + } + }; +}); + +// Included from: js/tinymce/classes/EditorCommands.js + +/** + * EditorCommands.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class enables you to add custom editor commands and it contains + * overrides for native browser commands to address various bugs and issues. + * + * @class tinymce.EditorCommands + */ +define("tinymce/EditorCommands", [ + "tinymce/html/Serializer", + "tinymce/Env", + "tinymce/util/Tools" +], function(Serializer, Env, Tools) { + // Added for compression purposes + var each = Tools.each, extend = Tools.extend; + var map = Tools.map, inArray = Tools.inArray, explode = Tools.explode; + var isGecko = Env.gecko, isIE = Env.ie; + var TRUE = true, FALSE = false; + + return function(editor) { + var dom = editor.dom, + selection = editor.selection, + commands = {state: {}, exec: {}, value: {}}, + settings = editor.settings, + formatter = editor.formatter, + bookmark; + + /** + * Executes the specified command. + * + * @method execCommand + * @param {String} command Command to execute. + * @param {Boolean} ui Optional user interface state. + * @param {Object} value Optional value for command. + * @return {Boolean} true/false if the command was found or not. + */ + function execCommand(command, ui, value) { + var func; + + command = command.toLowerCase(); + if ((func = commands.exec[command])) { + func(command, ui, value); + return TRUE; + } + + return FALSE; + } + + /** + * Queries the current state for a command for example if the current selection is "bold". + * + * @method queryCommandState + * @param {String} command Command to check the state of. + * @return {Boolean/Number} true/false if the selected contents is bold or not, -1 if it's not found. + */ + function queryCommandState(command) { + var func; + + command = command.toLowerCase(); + if ((func = commands.state[command])) { + return func(command); + } + + return -1; + } + + /** + * Queries the command value for example the current fontsize. + * + * @method queryCommandValue + * @param {String} command Command to check the value of. + * @return {Object} Command value of false if it's not found. + */ + function queryCommandValue(command) { + var func; + + command = command.toLowerCase(); + if ((func = commands.value[command])) { + return func(command); + } + + return FALSE; + } + + /** + * Adds commands to the command collection. + * + * @method addCommands + * @param {Object} command_list Name/value collection with commands to add, the names can also be comma separated. + * @param {String} type Optional type to add, defaults to exec. Can be value or state as well. + */ + 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 + extend(this, { + execCommand: execCommand, + queryCommandState: queryCommandState, + queryCommandValue: queryCommandValue, + addCommands: addCommands + }); + + // Private methods + + function execNativeCommand(command, ui, value) { + if (ui === undefined) { + ui = FALSE; + } + + if (value === undefined) { + 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} : undefined); + editor.nodeChanged(); + } + + 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 (isGecko) { + editor.windowManager.confirm(editor.getLang('clipboard_msg'), function(state) { + if (state) { + window.open('http://www.mozilla.org/editor/midasdemo/securityprefs.html', '_blank'); + } + }); + } else { + editor.windowManager.alert( + "Your browser doesn't support direct access to the clipboard. " + + "Please use the Ctrl+X/C/V keyboard shortcuts instead." + ); + } + } + }, + + // 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); + + if (align == 'full') { + align = 'justify'; + } + + // Remove all other alignments first + each('left,center,right,justify'.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 = explode(settings.font_size_style_values); + fontClasses = 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() { + 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; + var marker, nodeRect, viewPortRect, rng, node, node2, bookmarkHtml, viewportBodyElement; + + function trimOrPaddLeftRight(html) { + var rng, container, offset; + + rng = selection.getRng(true); + container = rng.startContainer; + offset = rng.startOffset; + + function hasSiblingText(siblingName) { + return container[siblingName] && container[siblingName].nodeType == 3; + } + + if (container.nodeType == 3) { + if (offset > 0) { + html = html.replace(/^ /, ' '); + } else if (!hasSiblingText('previousSibling')) { + html = html.replace(/^ /, ' '); + } + + if (offset < container.length) { + html = html.replace(/ (
    |)$/, ' '); + } else if (!hasSiblingText('nextSibling')) { + html = html.replace(/( | )(
    |)$/, ' '); + } + } + + return html; + } + + // Check for whitespace before/after value + if (/^ | $/.test(value)) { + value = trimOrPaddLeftRight(value); + } + + // Setup parser and serializer + parser = editor.parser; + serializer = new Serializer({}, editor.schema); + bookmarkHtml = ''; + + // Run beforeSetContent handlers on the HTML to be inserted + args = {content: value, format: 'html', selection: true}; + editor.fire('BeforeSetContent', 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 = 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(//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 = 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); + + // TODO: Why can't we normalize on IE + if (!isIE) { + node2 = marker.nextSibling; + if (node2 && node2.nodeType == 3) { + node.appendData(node2.data); + node2.parentNode.removeChild(node2); + } + } + } 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 + editor.fire('SetContent', 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; + }) + ); + }, + + mceToggleFormat: function(command, ui, value) { + toggleFormat(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, 10); + + 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) { + var indentStyleName; + + if (element.nodeName != "LI") { + indentStyleName = dom.getStyle(element, 'direction', true) == 'rtl' ? 'paddingRight' : 'paddingLeft'; + + if (command == 'outdent') { + value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue); + dom.setStyle(element, indentStyleName, value ? value + indentUnit : ''); + } else { + value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit; + dom.setStyle(element, indentStyleName, value); + } + } + }); + } else { + execNativeCommand(command); + } + }, + + mceRepaint: function() { + if (isGecko) { + try { + storeSelection(TRUE); + + if (selection.getSel()) { + selection.getSel().selectAllChildren(editor.getBody()); + } + + selection.collapse(TRUE); + restoreSelection(); + } catch (ex) { + // Ignore + } + } + }, + + InsertHorizontalRule: function() { + editor.execCommand('mceInsertContent', false, '
    '); + }, + + 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(); + + // Old IE does a better job with selectall than new versions + if (selection.getRng().setStart) { + rng.setStart(root, 0); + rng.setEnd(root, root.childNodes.length); + + selection.setRng(rng); + } else { + execNativeCommand('SelectAll'); + } + }, + + mceNewDocument: function() { + editor.setContent(''); + } + }); + + // Add queryCommandState overrides + addCommands({ + // Override justify commands + 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) { + var name = 'align' + command.substring(7); + var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks(); + var matches = map(nodes, function(node) { + return !!formatter.matchNode(node, name); + }); + return 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, 10) > 0) { + return TRUE; + } + + if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { + return TRUE; + } + } + + return ( + queryCommandState('InsertUnorderedList') || + queryCommandState('InsertOrderedList') || + (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')) + ); + }, + + 'InsertUnorderedList,InsertOrderedList': function(command) { + var list = dom.getParent(selection.getNode(), 'ul,ol'); + + return list && + ( + command === 'insertunorderedlist' && list.tagName === 'UL' || + command === 'insertorderedlist' && list.tagName === '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(); + } + }); + }; +}); + +// Included from: js/tinymce/classes/util/URI.js + +/** + * URI.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles parsing, modification and serialization of URI/URL strings. + * @class tinymce.util.URI + */ +define("tinymce/util/URI", [ + "tinymce/util/Tools" +], function(Tools) { + var each = Tools.each, trim = Tools.trim; + + /** + * Constucts a new URI instance. + * + * @constructor + * @method URI + * @param {String} url URI string to parse. + * @param {Object} settings Optional settings object. + */ + function URI(url, settings) { + var self = this, baseUri, base_url; + + // Trim whitespace + url = trim(url); + + // Default settings + settings = self.settings = settings || {}; + + // Strange app protocol that isn't http/https or local anchor + // For example: mailto,skype,tel etc. + if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) { + self.source = url; + return; + } + + // Absolute path with no host, fake host and protocol + if (url.indexOf('/') === 0 && url.indexOf('//') !== 0) { + url = (settings.base_uri ? settings.base_uri.protocol || 'http' : 'http') + '://mce_host' + url; + } + + // Relative path http:// or protocol relative //path + if (!/^[\w\-]*:?\/\//.test(url)) { + base_url = settings.base_uri ? settings.base_uri.path : new URI(location.href).directory; + url = ((settings.base_uri && settings.base_uri.protocol) || 'http') + '://mce_host' + self.toAbsPath(base_url, url); + } + + // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri) + url = url.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something + + /*jshint maxlen: 255 */ + url = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url); + + each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) { + var part = url[i]; + + // Zope 3 workaround, they use @@something + if (part) { + part = part.replace(/\(mce_at\)/g, '@@'); + } + + self[v] = part; + }); + + baseUri = settings.base_uri; + if (baseUri) { + if (!self.protocol) { + self.protocol = baseUri.protocol; + } + + if (!self.userInfo) { + self.userInfo = baseUri.userInfo; + } + + if (!self.port && self.host === 'mce_host') { + self.port = baseUri.port; + } + + if (!self.host || self.host === 'mce_host') { + self.host = baseUri.host; + } + + self.source = ''; + } + + //t.path = t.path || '/'; + } + + URI.prototype = { + /** + * Sets the internal path part of the URI. + * + * @method setPath + * @param {string} path Path string to set. + */ + setPath: function(path) { + var self = this; + + path = /^(.*?)\/?(\w+)?$/.exec(path); + + // Update path parts + self.path = path[0]; + self.directory = path[1]; + self.file = path[2]; + + // Rebuild source + self.source = ''; + self.getURI(); + }, + + /** + * Converts the specified URI into a relative URI based on the current URI instance location. + * + * @method toRelative + * @param {String} uri URI to convert into a relative path/URI. + * @return {String} Relative URI from the point specified in the current URI instance. + * @example + * // Converts an absolute URL to an relative URL url will be somedir/somefile.htm + * var url = new tinymce.util.URI('http://www.site.com/dir/').toRelative('http://www.site.com/dir/somedir/somefile.htm'); + */ + toRelative: function(uri) { + var self = this, output; + + if (uri === "./") { + return uri; + } + + uri = new URI(uri, {base_uri: self}); + + // Not on same domain/port or protocol + if ((uri.host != 'mce_host' && self.host != uri.host && uri.host) || self.port != uri.port || self.protocol != uri.protocol) { + return uri.getURI(); + } + + var tu = self.getURI(), uu = uri.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; + } + + output = self.toRelPath(self.path, uri.path); + + // Add query + if (uri.query) { + output += '?' + uri.query; + } + + // Add anchor + if (uri.anchor) { + output += '#' + uri.anchor; + } + + return output; + }, + + /** + * Converts the specified URI into a absolute URI based on the current URI instance location. + * + * @method toAbsolute + * @param {String} uri URI to convert into a relative path/URI. + * @param {Boolean} noHost No host and protocol prefix. + * @return {String} Absolute URI from the point specified in the current URI instance. + * @example + * // Converts an relative URL to an absolute URL url will be http://www.site.com/dir/somedir/somefile.htm + * var url = new tinymce.util.URI('http://www.site.com/dir/').toAbsolute('somedir/somefile.htm'); + */ + toAbsolute: function(uri, noHost) { + uri = new URI(uri, {base_uri: this}); + + return uri.getURI(this.host == uri.host && this.protocol == uri.protocol ? noHost : 0); + }, + + /** + * Converts a absolute path into a relative path. + * + * @method toRelPath + * @param {String} base Base point to convert the path from. + * @param {String} path Absolute path to convert into a relative path. + */ + toRelPath: function(base, path) { + var items, breakPoint = 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]) { + breakPoint = 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]) { + breakPoint = i + 1; + break; + } + } + } + + if (breakPoint === 1) { + return path; + } + + for (i = 0, l = base.length - (breakPoint - 1); i < l; i++) { + out += "../"; + } + + for (i = breakPoint - 1, l = items.length; i < l; i++) { + if (i != breakPoint - 1) { + out += "/" + items[i]; + } else { + out += items[i]; + } + } + + return out; + }, + + /** + * Converts a relative path into a absolute path. + * + * @method toAbsPath + * @param {String} base Base point to convert the path from. + * @param {String} path Relative path to convert into an absolute path. + */ + 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; + }, + + /** + * Returns the full URI of the internal structure. + * + * @method getURI + * @param {Boolean} noProtoHost Optional no host and protocol part. Defaults to false. + */ + getURI: function(noProtoHost) { + var s, self = this; + + // Rebuild source + if (!self.source || noProtoHost) { + s = ''; + + if (!noProtoHost) { + if (self.protocol) { + s += self.protocol + '://'; + } + + if (self.userInfo) { + s += self.userInfo + '@'; + } + + if (self.host) { + s += self.host; + } + + if (self.port) { + s += ':' + self.port; + } + } + + if (self.path) { + s += self.path; + } + + if (self.query) { + s += '?' + self.query; + } + + if (self.anchor) { + s += '#' + self.anchor; + } + + self.source = s; + } + + return self.source; + } + }; + + return URI; +}); + +// Included from: js/tinymce/classes/util/Class.js + +/** + * Class.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * This utilitiy class is used for easier inheritage. + * + * Features: + * * Exposed super functions: this._super(); + * * Mixins + * * Dummy functions + * * Property functions: var value = object.value(); and object.value(newValue); + * * Static functions + * * Defaults settings + */ +define("tinymce/util/Class", [ + "tinymce/util/Tools" +], function(Tools) { + var each = Tools.each, extend = Tools.extend; + + var extendClass, initializing; + + function Class() { + } + + // Provides classical inheritance, based on code made by John Resig + Class.extend = extendClass = function(prop) { + var Self = this, _super = Self.prototype, prototype, name, member; + + // The dummy class constructor + function Class() { + var i, mixins, mixin, self; + + // All construction is actually done in the init method + if (!initializing) { + self = this; + + // Run class constuctor + if (self.init) { + self.init.apply(self, arguments); + } + + // Run mixin constructors + mixins = self.Mixins; + if (mixins) { + i = mixins.length; + while (i--) { + mixin = mixins[i]; + if (mixin.init) { + mixin.init.apply(self, arguments); + } + } + } + } + } + + // Dummy function, needs to be extended in order to provide functionality + function dummy() { + return this; + } + + // Creates a overloaded method for the class + // this enables you to use this._super(); to call the super function + function createMethod(name, fn) { + return function(){ + var self = this, tmp = self._super, ret; + + self._super = _super[name]; + ret = fn.apply(self, arguments); + self._super = tmp; + + return ret; + }; + } + + // Instantiate a base class (but only create the instance, + // don't run the init constructor) + initializing = true; + prototype = new Self(); + initializing = false; + + // Add mixins + if (prop.Mixins) { + each(prop.Mixins, function(mixin) { + mixin = mixin; + + for (var name in mixin) { + if (name !== "init") { + prop[name] = mixin[name]; + } + } + }); + + if (_super.Mixins) { + prop.Mixins = _super.Mixins.concat(prop.Mixins); + } + } + + // Generate dummy methods + if (prop.Methods) { + each(prop.Methods.split(','), function(name) { + prop[name] = dummy; + }); + } + + // Generate property methods + if (prop.Properties) { + each(prop.Properties.split(','), function(name) { + var fieldName = '_' + name; + + prop[name] = function(value) { + var self = this, undef; + + // Set value + if (value !== undef) { + self[fieldName] = value; + + return self; + } + + // Get value + return self[fieldName]; + }; + }); + } + + // Static functions + if (prop.Statics) { + each(prop.Statics, function(func, name) { + Class[name] = func; + }); + } + + // Default settings + if (prop.Defaults && _super.Defaults) { + prop.Defaults = extend({}, _super.Defaults, prop.Defaults); + } + + // Copy the properties over onto the new prototype + for (name in prop) { + member = prop[name]; + + if (typeof member == "function" && _super[name]) { + prototype[name] = createMethod(name, member); + } else { + prototype[name] = member; + } + } + + // Populate our constructed prototype object + Class.prototype = prototype; + + // Enforce the constructor to be what we expect + Class.constructor = Class; + + // And make this class extendible + Class.extend = extendClass; + + return Class; + }; + + return Class; +}); + +// Included from: js/tinymce/classes/ui/Selector.js + +/** + * Selector.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Selector engine, enables you to select controls by using CSS like expressions. + * We currently only support basic CSS expressions to reduce the size of the core + * and the ones we support should be enough for most cases. + * + * Supported expressions: + * element + * element#name + * element.class + * element[attr] + * element[attr*=value] + * element[attr~=value] + * element[attr!=value] + * element[attr^=value] + * element[attr$=value] + * element: + * element:not() + * element:first + * element:last + * element:odd + * element:even + * element element + * element > element + * @class tinymce.ui.Selector + */ +define("tinymce/ui/Selector", [ + "tinymce/util/Class", + "tinymce/util/Tools" +], function(Class, Tools) { + "use strict"; + + /** + * Produces an array with a unique set of objects. It will not compare the values + * but the references of the objects. + * + * @method unqiue + * @param {Array} array Array to make into an array with unique items. + * @return {Array} Array with unique items. + */ + function unique(array) { + var uniqueItems = [], i = array.length, item; + + while (i--) { + item = array[i]; + + if (!item.__checked) { + uniqueItems.push(item); + item.__checked = 1; + } + } + + i = uniqueItems.length; + while (i--) { + delete uniqueItems[i].__checked; + } + + return uniqueItems; + } + + var expression = /^([\w\\*]+)?(?:#([\w\\]+))?(?:\.([\w\\\.]+))?(?:\[\@?([\w\\]+)([\^\$\*!~]?=)([\w\\]+)\])?(?:\:(.+))?/i; + + /*jshint maxlen:255 */ + var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + whiteSpace = /^\s*|\s*$/g, + Collection; + + var Selector = Class.extend({ + /** + * Constructs a new Selector instance. + * + * @contructor + * @method init + * @param {String} selector CSS like selector expression. + */ + init: function(selector) { + var match = this.match; + + function compileNameFilter(name) { + if (name) { + name = name.toLowerCase(); + + return function(item) { + return name === '*' || item.type === name; + }; + } + } + + function compileIdFilter(id) { + if (id) { + return function(item) { + return item._name === id; + }; + } + } + + function compileClassesFilter(classes) { + if (classes) { + classes = classes.split('.'); + + return function(item) { + var i = classes.length; + + while (i--) { + if (!item.hasClass(classes[i])) { + return false; + } + } + + return true; + }; + } + } + + function compileAttrFilter(name, cmp, check) { + if (name) { + return function(item) { + var value = item[name] ? item[name]() : ''; + + return !cmp ? !!check : + cmp === "=" ? value === check : + cmp === "*=" ? value.indexOf(check) >= 0 : + cmp === "~=" ? (" " + value + " ").indexOf(" " + check + " ") >= 0 : + cmp === "!=" ? value != check : + cmp === "^=" ? value.indexOf(check) === 0 : + cmp === "$=" ? value.substr(value.length - check.length) === check : + false; + }; + } + } + + function compilePsuedoFilter(name) { + var notSelectors; + + if (name) { + name = /(?:not\((.+)\))|(.+)/i.exec(name); + + if (!name[1]) { + name = name[2]; + + return function(item, index, length) { + return name === 'first' ? index === 0 : + name === 'last' ? index === length - 1 : + name === 'even' ? index % 2 === 0 : + name === 'odd' ? index % 2 === 1 : + item[name] ? item[name]() : + false; + }; + } else { + // Compile not expression + notSelectors = parseChunks(name[1], []); + + return function(item) { + return !match(item, notSelectors); + }; + } + } + } + + function compile(selector, filters, direct) { + var parts; + + function add(filter) { + if (filter) { + filters.push(filter); + } + } + + // Parse expression into parts + parts = expression.exec(selector.replace(whiteSpace, '')); + + add(compileNameFilter(parts[1])); + add(compileIdFilter(parts[2])); + add(compileClassesFilter(parts[3])); + add(compileAttrFilter(parts[4], parts[5], parts[6])); + add(compilePsuedoFilter(parts[7])); + + // Mark the filter with psuedo for performance + filters.psuedo = !!parts[7]; + filters.direct = direct; + + return filters; + } + + // Parser logic based on Sizzle by John Resig + function parseChunks(selector, selectors) { + var parts = [], extra, matches, i; + + do { + chunker.exec(""); + matches = chunker.exec(selector); + + if (matches) { + selector = matches[3]; + parts.push(matches[1]); + + if (matches[2]) { + extra = matches[3]; + break; + } + } + } while (matches); + + if (extra) { + parseChunks(extra, selectors); + } + + selector = []; + for (i = 0; i < parts.length; i++) { + if (parts[i] != '>') { + selector.push(compile(parts[i], [], parts[i - 1] === '>')); + } + } + + selectors.push(selector); + + return selectors; + } + + this._selectors = parseChunks(selector, []); + }, + + /** + * Returns true/false if the selector matches the specified control. + * + * @method match + * @param {tinymce.ui.Control} control Control to match agains the selector. + * @param {Array} selectors Optional array of selectors, mostly used internally. + * @return {Boolean} true/false state if the control matches or not. + */ + match: function(control, selectors) { + var i, l, si, sl, selector, fi, fl, filters, index, length, siblings, count, item; + + selectors = selectors || this._selectors; + for (i = 0, l = selectors.length; i < l; i++) { + selector = selectors[i]; + sl = selector.length; + item = control; + count = 0; + + for (si = sl - 1; si >= 0; si--) { + filters = selector[si]; + + while (item) { + // Find the index and length since a psuedo filter like :first needs it + if (filters.psuedo) { + siblings = item.parent().items(); + index = Tools.inArray(item, siblings); + length = siblings.length; + } + + for (fi = 0, fl = filters.length; fi < fl; fi++) { + if (!filters[fi](item, index, length)) { + fi = fl + 1; + break; + } + } + + if (fi === fl) { + count++; + break; + } else { + // If it didn't match the right most expression then + // break since it's no point looking at the parents + if (si === sl - 1) { + break; + } + } + + item = item.parent(); + } + } + + // If we found all selectors then return true otherwise continue looking + if (count === sl) { + return true; + } + } + + return false; + }, + + /** + * Returns a tinymce.ui.Collection with matches of the specified selector inside the specified container. + * + * @method find + * @param {tinymce.ui.Control} container Container to look for items in. + * @return {tinymce.ui.Collection} Collection with matched elements. + */ + find: function(container) { + var matches = [], i, l, selectors = this._selectors; + + function collect(items, selector, index) { + var i, l, fi, fl, item, filters = selector[index]; + + for (i = 0, l = items.length; i < l; i++) { + item = items[i]; + + // Run each filter agains the item + for (fi = 0, fl = filters.length; fi < fl; fi++) { + if (!filters[fi](item, i, l)) { + fi = fl + 1; + break; + } + } + + // All filters matched the item + if (fi === fl) { + // Matched item is on the last expession like: panel toolbar [button] + if (index == selector.length - 1) { + matches.push(item); + } else { + // Collect next expession type + if (item.items) { + collect(item.items(), selector, index + 1); + } + } + } else if (filters.direct) { + return; + } + + // Collect child items + if (item.items) { + collect(item.items(), selector, index); + } + } + } + + if (container.items) { + for (i = 0, l = selectors.length; i < l; i++) { + collect(container.items(), selectors[i], 0); + } + + // Unique the matches if needed + if (l > 1) { + matches = unique(matches); + } + } + + // Fix for circular reference + if (!Collection) { + // TODO: Fix me! + Collection = Selector.Collection; + } + + return new Collection(matches); + } + }); + + return Selector; +}); + +// Included from: js/tinymce/classes/ui/Collection.js + +/** + * Collection.js + * + * Copyright 2003-2013, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Control collection, this class contains control instances and it + * enables you to perform actions on all the contained items. This is very similar to how jQuery works. + * + * @class tinymce.ui.Collection + */ +define("tinymce/ui/Collection", [ + "tinymce/util/Tools", + "tinymce/ui/Selector", + "tinymce/util/Class" +], function(Tools, Selector, Class) { + "use strict"; + + var Collection, proto, push = Array.prototype.push, slice = Array.prototype.slice; + + proto = { + /** + * Current number of contained control instances. + * + * @field length + * @type Number + */ + length: 0, + + /** + * Constructor for the collection. + * + * @constructor + * @method init + * @param {Array} items Optional array with items to add. + */ + init: function(items) { + if (items) { + this.add(items); + } + }, + + /** + * Adds new items to the control collection. + * + * @method add + * @param {Array} items Array if items to add to collection. + * @return {tinymce.ui.Collection} Current collection instance. + */ + add: function(items) { + var self = this; + + // Force single item into array + if (!Tools.isArray(items)) { + if (items instanceof Collection) { + self.add(items.toArray()); + } else { + push.call(self, items); + } + } else { + push.apply(self, items); + } + + return self; + }, + + /** + * Sets the contents of the collection. This will remove any existing items + * and replace them with the ones specified in the input array. + * + * @method set + * @param {Array} items Array with items to set into the Collection. + * @return {tinymce.ui.Collection} + */ + set: function(items) { + var self = this, len = self.length, i; + + self.length = 0; + self.add(items); + + // Remove old entries + for (i = self.length; i < len; i++) { + delete self[i]; + } + + return self; + }, + + /** + * Filters the collection item based on the specified selector expression or selector function. + * + * @method filter + * @param {String} selector Selector expression to filter items by. + * @return {tinymce.ui.Collection} Collection containing the filtered items. + */ + filter: function(selector) { + var self = this, i, l, matches = [], item, match; + + // Compile string into selector expression + if (typeof(selector) === "string") { + selector = new Selector(selector); + + match = function(item) { + return selector.match(item); + }; + } else { + // Use selector as matching function + match = selector; + } + + for (i = 0, l = self.length; i < l; i++) { + item = self[i]; + + if (match(item)) { + matches.push(item); + } + } + + return new Collection(matches); + }, + + /** + * Slices the items within the collection. + * + * @method slice + * @param {Number} index Index to slice at. + * @param {Number} len Optional length to slice. + * @return {tinymce.ui.Collection} Current collection. + */ + slice: function() { + return new Collection(slice.apply(this, arguments)); + }, + + /** + * Makes the current collection equal to the specified index. + * + * @method eq + * @param {Number} index Index of the item to set the collection to. + * @return {tinymce.ui.Collection} Current collection. + */ + eq: function(index) { + return index === -1 ? this.slice(index) : this.slice(index, +index + 1); + }, + + /** + * Executes the specified callback on each item in collection. + * + * @method each + * @param {function} callback Callback to execute for each item in collection. + * @return {tinymce.ui.Collection} Current collection instance. + */ + each: function(callback) { + Tools.each(this, callback); + + return this; + }, + + /** + * Returns an JavaScript array object of the contents inside the collection. + * + * @method toArray + * @return {Array} Array with all items from collection. + */ + toArray: function() { + return Tools.toArray(this); + }, + + /** + * Finds the index of the specified control or return -1 if it isn't in the collection. + * + * @method indexOf + * @param {Control} ctrl Control instance to look for. + * @return {Number} Index of the specified control or -1. + */ + indexOf: function(ctrl) { + var self = this, i = self.length; + + while (i--) { + if (self[i] === ctrl) { + break; + } + } + + return i; + }, + + /** + * Returns a new collection of the contents in reverse order. + * + * @method reverse + * @return {tinymce.ui.Collection} Collection instance with reversed items. + */ + reverse: function() { + return new Collection(Tools.toArray(this).reverse()); + }, + + /** + * Returns true/false if the class exists or not. + * + * @method hasClass + * @param {String} cls Class to check for. + * @return {Boolean} true/false state if the class exists or not. + */ + hasClass: function(cls) { + return this[0] ? this[0].hasClass(cls) : false; + }, + + /** + * Sets/gets the specific property on the items in the collection. The same as executing control.(); + * + * @method prop + * @param {String} name Property name to get/set. + * @param {Object} value Optional object value to set. + * @return {tinymce.ui.Collection} Current collection instance or value of the first item on a get operation. + */ + prop: function(name, value) { + var self = this, undef, item; + + if (value !== undef) { + self.each(function(item) { + if (item[name]) { + item[name](value); + } + }); + + return self; + } + + item = self[0]; + + if (item && item[name]) { + return item[name](); + } + }, + + /** + * Executes the specific function name with optional arguments an all items in collection if it exists. + * + * @example collection.exec("myMethod", arg1, arg2, arg3); + * @method exec + * @param {String} name Name of the function to execute. + * @param {Object} ... Multiple arguments to pass to each function. + * @return {tinymce.ui.Collection} Current collection. + */ + exec: function(name) { + var self = this, args = Tools.toArray(arguments).slice(1); + + self.each(function(item) { + if (item[name]) { + item[name].apply(item, args); + } + }); + + return self; + } + + /** + * Fires the specified event by name and arguments on the control. This will execute all + * bound event handlers. + * + * @method fire + * @param {String} name Name of the event to fire. + * @param {Object} args Optional arguments to pass to the event. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // fire: function(event, args) {}, -- Generated by code below + + /** + * Binds a callback to the specified event. This event can both be + * native browser events like "click" or custom ones like PostRender. + * + * The callback function will have two parameters the first one being the control that recieved the event + * the second one will be the event object either the browsers native event object or a custom JS object. + * + * @method on + * @param {String} name Name of the event to bind. For example "click". + * @param {String/function} callback Callback function to execute ones the event occurs. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // on: function(name, callback) {}, -- Generated by code below + + /** + * Unbinds the specified event and optionally a specific callback. If you omit the name + * parameter all event handlers will be removed. If you omit the callback all event handles + * by the specified name will be removed. + * + * @method off + * @param {String} name Optional name for the event to unbind. + * @param {function} callback Optional callback function to unbind. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // off: function(name, callback) {}, -- Generated by code below + + /** + * Shows the items in the current collection. + * + * @method show + * @return {tinymce.ui.Collection} Current collection instance. + */ + // show: function() {}, -- Generated by code below + + /** + * Hides the items in the current collection. + * + * @method hide + * @return {tinymce.ui.Collection} Current collection instance. + */ + // hide: function() {}, -- Generated by code below + + /** + * Sets/gets the text contents of the items in the current collection. + * + * @method text + * @return {tinymce.ui.Collection} Current collection instance or text value of the first item on a get operation. + */ + // text: function(value) {}, -- Generated by code below + + /** + * Sets/gets the name contents of the items in the current collection. + * + * @method name + * @return {tinymce.ui.Collection} Current collection instance or name value of the first item on a get operation. + */ + // name: function(value) {}, -- Generated by code below + + /** + * Sets/gets the disabled state on the items in the current collection. + * + * @method disabled + * @return {tinymce.ui.Collection} Current collection instance or disabled state of the first item on a get operation. + */ + // disabled: function(state) {}, -- Generated by code below + + /** + * Sets/gets the active state on the items in the current collection. + * + * @method active + * @return {tinymce.ui.Collection} Current collection instance or active state of the first item on a get operation. + */ + // active: function(state) {}, -- Generated by code below + + /** + * Sets/gets the selected state on the items in the current collection. + * + * @method selected + * @return {tinymce.ui.Collection} Current collection instance or selected state of the first item on a get operation. + */ + // selected: function(state) {}, -- Generated by code below + + /** + * Sets/gets the selected state on the items in the current collection. + * + * @method visible + * @return {tinymce.ui.Collection} Current collection instance or visible state of the first item on a get operation. + */ + // visible: function(state) {}, -- Generated by code below + + /** + * Adds a class to all items in the collection. + * + * @method addClass + * @param {String} cls Class to add to each item. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // addClass: function(cls) {}, -- Generated by code below + + /** + * Removes the specified class from all items in collection. + * + * @method removeClass + * @param {String} cls Class to remove from each item. + * @return {tinymce.ui.Collection} Current collection instance. + */ + // removeClass: function(cls) {}, -- Generated by code below + }; + + // Extend tinymce.ui.Collection prototype with some generated control specific methods + Tools.each('fire on off show hide addClass removeClass append prepend before after reflow'.split(' '), function(name) { + proto[name] = function() { + var args = Tools.toArray(arguments); + + this.each(function(ctrl) { + if (name in ctrl) { + ctrl[name].apply(ctrl, args); + } + }); + + return this; + }; + }); + + // Extend tinymce.ui.Collection prototype with some property methods + Tools.each('text name width height disabled active selected checked visible parent value data'.split(' '), function(name) { + proto[name] = function(value) { + return this.prop(name, value); + }; + }); + + // Create class based on the new prototype + Collection = Class.extend(proto); + + // Stick Collection into Selector to prevent circual references + Selector.Collection = Collection; + + return Collection; +}); + +// Included from: js/tinymce/classes/ui/DomUtils.js + +/** + * DomUtils.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +define("tinymce/ui/DomUtils", [ + "tinymce/util/Tools", + "tinymce/dom/DOMUtils" +], function(Tools, DOMUtils) { + "use strict"; + + return { + id: function() { + return DOMUtils.DOM.uniqueId(); + }, + + createFragment: function(html) { + return DOMUtils.DOM.createFragment(html); + }, + + getWindowSize: function() { + return DOMUtils.DOM.getViewPort(); + }, + + getSize: function(elm) { + return DOMUtils.DOM.getSize(elm); + }, + + getPos: function(elm, root) { + return DOMUtils.DOM.getPos(elm, root); + }, + + get: function(id) { + return document.getElementById(id); + }, + + addClass : function(elm, cls) { + return DOMUtils.DOM.addClass(elm, cls); + }, + + removeClass : function(elm, cls) { + return DOMUtils.DOM.removeClass(elm, cls); + }, + + hasClass : function(elm, cls) { + return DOMUtils.DOM.hasClass(elm, cls); + }, + + toggleClass: function(elm, cls, state) { + return DOMUtils.DOM.toggleClass(elm, cls, state); + }, + + css: function(elm, name, value) { + return DOMUtils.DOM.setStyle(elm, name, value); + }, + + on: function(target, name, callback, scope) { + return DOMUtils.DOM.bind(target, name, callback, scope); + }, + + off: function(target, name, callback) { + return DOMUtils.DOM.unbind(target, name, callback); + }, + + fire: function(target, name, args) { + return DOMUtils.DOM.fire(target, name, args); + } + }; +}); + +// Included from: js/tinymce/classes/ui/Control.js + +/** + * Control.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * ... + * + * @class tinymce.ui.Control + */ +define("tinymce/ui/Control", [ + "tinymce/util/Class", + "tinymce/util/Tools", + "tinymce/ui/Collection", + "tinymce/ui/DomUtils" +], function(Class, Tools, Collection, DomUtils) { + "use strict"; + + var nativeEvents = Tools.makeMap("focusin focusout scroll click dblclick mousedown mouseup mousemove mouseover" + + " mouseout mouseenter mouseleave wheel keydown keypress keyup contextmenu", " "); + + var elementIdCache = {}; + var hasMouseWheelEventSupport = "onmousewheel" in document; + var hasWheelEventSupport = false; + + /** + * Base control. All controls extend this class. + * + * @class tinymce.ui.Control + */ + var Control = Class.extend({ + Statics: { + controlIdLookup: {} + }, + + classPrefix: "mce-", + + getContainerElm: function() { + return document.body; + }, + + getParentCtrl: function(elm) { + var ctrl; + + while (elm) { + ctrl = Control.controlIdLookup[elm.id]; + if (ctrl) { + break; + } + + elm = elm.parentNode; + } + + return ctrl; + }, + + /** + * Constructor for the control. + * + * @constructor + * @method init + * @param {Object} settings Settings name/value object. + */ + init: function(settings) { + var self = this, classes, i; + + self.settings = settings = Tools.extend({}, self.Defaults, settings); + + // Initial states + self._id = DomUtils.id(); + self._text = self._name = ''; + self._width = self._height = 0; + self._aria = {role: settings.role}; + + // Setup classes + classes = settings.classes; + if (classes) { + classes = classes.split(' '); + classes.map = {}; + i = classes.length; + while (i--) { + classes.map[classes[i]] = true; + } + } + + self._classes = classes || []; + self.visible(true); + + // Set some properties + Tools.each('title text width height name classes visible disabled active value'.split(' '), function(name) { + var value = settings[name], undef; + + if (value !== undef) { + self[name](value); + } else if (self['_' + name] === undef) { + self['_' + name] = false; + } + }); + + self.on('click', function() { + if (self.disabled()) { + return false; + } + }); + + if (settings.classes) { + Tools.each(settings.classes.split(' '), function(cls) { + self.addClass(cls); + }); + } + + self.settings = settings; + + self._borderBox = self.parseBox(settings.border); + self._paddingBox = self.parseBox(settings.padding); + self._marginBox = self.parseBox(settings.margin); + + if (settings.hidden) { + self.hide(); + } + }, + + // Will generate getter/setter methods for these properties + Properties: 'parent,title,text,width,height,disabled,active,name,value', + + // Will generate empty dummy functions for these + Methods: 'renderHtml,refresh', + + parseBox: function(value) { + var len, radix = 10; + + if (!value) { + return; + } + + if (typeof(value) === "number") { + value = value || 0; + + return { + top: value, + left: value, + bottom: value, + right: value + }; + } + + value = value.split(' '); + len = value.length; + + if (len === 1) { + value[1] = value[2] = value[3] = value[0]; + } else if (len === 2) { + value[2] = value[0]; + value[3] = value[1]; + } else if (len === 3) { + value[3] = value[1]; + } + + return { + top: parseInt(value[0], radix) || 0, + right: parseInt(value[1], radix) || 0, + bottom: parseInt(value[2], radix) || 0, + left: parseInt(value[3], radix) || 0 + }; + }, + + borderBox: function() { + return this._borderBox; + }, + + paddingBox: function() { + return this._paddingBox; + }, + + marginBox: function() { + return this._marginBox; + }, + + measureBox: function(elm, prefix) { + function getStyle(name) { + var defaultView = document.defaultView; + + if (defaultView) { + // Remove camelcase + name = name.replace(/[A-Z]/g, function(a) { + return '-' + a; + }); + + return defaultView.getComputedStyle(elm, null).getPropertyValue(name); + } + + return elm.currentStyle[name]; + } + + function getSide(name) { + var val = parseInt(getStyle(name), 10); + + return isNaN(val) ? 0 : val; + } + + return { + top: getSide(prefix + "TopWidth"), + right: getSide(prefix + "RightWidth"), + bottom: getSide(prefix + "BottomWidth"), + left: getSide(prefix + "LeftWidth") + }; + }, + + initLayoutRect: function() { + var self = this, settings = self.settings, borderBox, layoutRect; + var elm = self.getEl(), width, height, minWidth, minHeight, autoResize; + var startMinWidth, startMinHeight; + + // Measure boxes + borderBox = self._borderBox = self._borderBox || self.measureBox(elm, 'border'); + self._paddingBox = self._paddingBox || self.measureBox(elm, 'padding'); + self._marginBox = self._marginBox || self.measureBox(elm, 'margin'); + + // Setup minWidth/minHeight and width/height + startMinWidth = settings.minWidth; + startMinHeight = settings.minHeight; + minWidth = startMinWidth || elm.offsetWidth; + minHeight = startMinHeight || elm.offsetHeight; + width = settings.width; + height = settings.height; + autoResize = settings.autoResize; + autoResize = typeof(autoResize) != "undefined" ? autoResize : !width && !height; + + width = width || minWidth; + height = height || minHeight; + + var deltaW = borderBox.left + borderBox.right; + var deltaH = borderBox.top + borderBox.bottom; + + var maxW = settings.maxWidth || 0xFFFF; + var maxH = settings.maxHeight || 0xFFFF; + + // Setup initial layout rect + self._layoutRect = layoutRect = { + x: settings.x || 0, + y: settings.y || 0, + w: width, + h: height, + deltaW: deltaW, + deltaH: deltaH, + contentW: width - deltaW, + contentH: height - deltaH, + innerW: width - deltaW, + innerH: height - deltaH, + startMinWidth: startMinWidth || 0, + startMinHeight: startMinHeight || 0, + minW: Math.min(minWidth, maxW), + minH: Math.min(minHeight, maxH), + maxW: maxW, + maxH: maxH, + autoResize: autoResize, + scrollW: 0 + }; + + self._lastLayoutRect = {}; + + return layoutRect; + }, + + layoutRect: function(newRect) { + var self = this, curRect = self._layoutRect, lastLayoutRect, size, deltaWidth, deltaHeight, undef, repaintControls; + + // Initialize default layout rect + if (!curRect) { + curRect = self.initLayoutRect(); + } + + // Set new rect values + if (newRect) { + // Calc deltas between inner and outer sizes + deltaWidth = curRect.deltaW; + deltaHeight = curRect.deltaH; + + // Set x position + if (newRect.x !== undef) { + curRect.x = newRect.x; + } + + // Set y position + if (newRect.y !== undef) { + curRect.y = newRect.y; + } + + // Set minW + if (newRect.minW !== undef) { + curRect.minW = newRect.minW; + } + + // Set minH + if (newRect.minH !== undef) { + curRect.minH = newRect.minH; + } + + // Set new width and calculate inner width + size = newRect.w; + if (size !== undef) { + size = size < curRect.minW ? curRect.minW : size; + size = size > curRect.maxW ? curRect.maxW : size; + curRect.w = size; + curRect.innerW = size - deltaWidth; + } + + // Set new height and calculate inner height + size = newRect.h; + if (size !== undef) { + size = size < curRect.minH ? curRect.minH : size; + size = size > curRect.maxH ? curRect.maxH : size; + curRect.h = size; + curRect.innerH = size - deltaHeight; + } + + // Set new inner width and calculate width + size = newRect.innerW; + if (size !== undef) { + size = size < curRect.minW - deltaWidth ? curRect.minW - deltaWidth : size; + size = size > curRect.maxW - deltaWidth ? curRect.maxW - deltaWidth : size; + curRect.innerW = size; + curRect.w = size + deltaWidth; + } + + // Set new height and calculate inner height + size = newRect.innerH; + if (size !== undef) { + size = size < curRect.minH - deltaHeight ? curRect.minH - deltaHeight : size; + size = size > curRect.maxH - deltaHeight ? curRect.maxH - deltaHeight : size; + curRect.innerH = size; + curRect.h = size + deltaHeight; + } + + // Set new contentW + if (newRect.contentW !== undef) { + curRect.contentW = newRect.contentW; + } + + // Set new contentH + if (newRect.contentH !== undef) { + curRect.contentH = newRect.contentH; + } + + // Compare last layout rect with the current one to see if we need to repaint or not + lastLayoutRect = self._lastLayoutRect; + if (lastLayoutRect.x !== curRect.x || lastLayoutRect.y !== curRect.y || + lastLayoutRect.w !== curRect.w || lastLayoutRect.h !== curRect.h) { + repaintControls = Control.repaintControls; + + if (repaintControls) { + if (repaintControls.map && !repaintControls.map[self._id]) { + repaintControls.push(self); + repaintControls.map[self._id] = true; + } + } + + lastLayoutRect.x = curRect.x; + lastLayoutRect.y = curRect.y; + lastLayoutRect.w = curRect.w; + lastLayoutRect.h = curRect.h; + } + + return self; + } + + return curRect; + }, + + repaint: function() { + var self = this, style, bodyStyle, rect, borderBox, borderW = 0, borderH = 0, lastRepaintRect; + + style = self.getEl().style; + rect = self._layoutRect; + lastRepaintRect = self._lastRepaintRect || {}; + + borderBox = self._borderBox; + borderW = borderBox.left + borderBox.right; + borderH = borderBox.top + borderBox.bottom; + + if (rect.x !== lastRepaintRect.x) { + style.left = rect.x + 'px'; + lastRepaintRect.x = rect.x; + } + + if (rect.y !== lastRepaintRect.y) { + style.top = rect.y + 'px'; + lastRepaintRect.y = rect.y; + } + + if (rect.w !== lastRepaintRect.w) { + style.width = (rect.w - borderW) + 'px'; + lastRepaintRect.w = rect.w; + } + + if (rect.h !== lastRepaintRect.h) { + style.height = (rect.h - borderH) + 'px'; + lastRepaintRect.h = rect.h; + } + + // Update body if needed + if (self._hasBody && rect.innerW !== lastRepaintRect.innerW) { + bodyStyle = self.getEl('body').style; + bodyStyle.width = (rect.innerW) + 'px'; + lastRepaintRect.innerW = rect.innerW; + } + + if (self._hasBody && rect.innerH !== lastRepaintRect.innerH) { + bodyStyle = bodyStyle || self.getEl('body').style; + bodyStyle.height = (rect.innerH) + 'px'; + lastRepaintRect.innerH = rect.innerH; + } + + self._lastRepaintRect = lastRepaintRect; + self.fire('repaint', {}, false); + }, + + /** + * Binds a callback to the specified event. This event can both be + * native browser events like "click" or custom ones like PostRender. + * + * The callback function will be passed a DOM event like object that enables yout do stop propagation. + * + * @method on + * @param {String} name Name of the event to bind. For example "click". + * @param {String/function} callback Callback function to execute ones the event occurs. + * @return {tinymce.ui.Control} Current control object. + */ + on: function(name, callback) { + var self = this, bindings, handlers, names, i; + + function resolveCallbackName(name) { + var callback, scope; + + return function(e) { + if (!callback) { + self.parents().each(function(ctrl) { + var callbacks = ctrl.settings.callbacks; + + if (callbacks && (callback = callbacks[name])) { + scope = ctrl; + return false; + } + }); + } + + return callback.call(scope, e); + }; + } + + if (callback) { + if (typeof(callback) == 'string') { + callback = resolveCallbackName(callback); + } + + names = name.toLowerCase().split(' '); + i = names.length; + while (i--) { + name = names[i]; + + bindings = self._bindings; + if (!bindings) { + bindings = self._bindings = {}; + } + + handlers = bindings[name]; + if (!handlers) { + handlers = bindings[name] = []; + } + + handlers.push(callback); + + if (nativeEvents[name]) { + if (!self._nativeEvents) { + self._nativeEvents = {name: true}; + } else { + self._nativeEvents[name] = true; + } + + if (self._rendered) { + self.bindPendingEvents(); + } + } + } + } + + return self; + }, + + /** + * Unbinds the specified event and optionally a specific callback. If you omit the name + * parameter all event handlers will be removed. If you omit the callback all event handles + * by the specified name will be removed. + * + * @method off + * @param {String} name Optional name for the event to unbind. + * @param {function} callback Optional callback function to unbind. + * @return {mxex.ui.Control} Current control object. + */ + off: function(name, callback) { + var self = this, i, bindings = self._bindings, handlers, bindingName, names, hi; + + if (bindings) { + if (name) { + names = name.toLowerCase().split(' '); + i = names.length; + while (i--) { + name = names[i]; + handlers = bindings[name]; + + // Unbind all handlers + if (!name) { + for (bindingName in bindings) { + bindings[bindingName].length = 0; + } + + return self; + } + + if (handlers) { + // Unbind all by name + if (!callback) { + handlers.length = 0; + } else { + // Unbind specific ones + hi = handlers.length; + while (hi--) { + if (handlers[hi] === callback) { + handlers.splice(hi, 1); + } + } + } + } + } + } else { + self._bindings = []; + } + } + + return self; + }, + + /** + * Fires the specified event by name and arguments on the control. This will execute all + * bound event handlers. + * + * @method fire + * @param {String} name Name of the event to fire. + * @param {Object} args Optional arguments to pass to the event. + * @param {Boolean} bubble Optional value to control bubbeling. Defaults to true. + * @return {tinymce.ui.Control} Current control object. + */ + fire: function(name, args, bubble) { + var self = this, i, l, handlers, parentCtrl; + + name = name.toLowerCase(); + + // 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; + } + + // Setup empty object if args is omited + args = args || {}; + + // Stick type into event object + if (!args.type) { + args.type = name; + } + + // Stick control into event + if (!args.control) { + args.control = self; + } + + // Add event delegation methods if they are missing + if (!args.preventDefault) { + // Add preventDefault method + args.preventDefault = function() { + args.isDefaultPrevented = returnTrue; + }; + + // Add stopPropagation + args.stopPropagation = function() { + args.isPropagationStopped = returnTrue; + }; + + // Add stopImmediatePropagation + args.stopImmediatePropagation = function() { + args.isImmediatePropagationStopped = returnTrue; + }; + + // Add event delegation states + args.isDefaultPrevented = returnFalse; + args.isPropagationStopped = returnFalse; + args.isImmediatePropagationStopped = returnFalse; + } + + if (self._bindings) { + handlers = self._bindings[name]; + + if (handlers) { + for (i = 0, l = handlers.length; i < l; i++) { + // Execute callback and break if the callback returns a false + if (!args.isImmediatePropagationStopped() && handlers[i].call(self, args) === false) { + break; + } + } + } + } + + // Bubble event up to parent controls + if (bubble !== false) { + parentCtrl = self.parent(); + while (parentCtrl && !args.isPropagationStopped()) { + parentCtrl.fire(name, args, false); + parentCtrl = parentCtrl.parent(); + } + } + + return args; + }, + + /** + * Returns a control collection with all parent controls. + * + * @method parents + * @param {String} selector Optional selector expression to find parents. + * @return {tinymce.ui.Collection} Collection with all parent controls. + */ + parents: function(selector) { + var ctrl = this, parents = new Collection(); + + // Add each parent to collection + for (ctrl = ctrl.parent(); ctrl; ctrl = ctrl.parent()) { + parents.add(ctrl); + } + + // Filter away everything that doesn't match the selector + if (selector) { + parents = parents.filter(selector); + } + + return parents; + }, + + next: function() { + var parentControls = this.parent().items(); + + return parentControls[parentControls.indexOf(this) + 1]; + }, + + prev: function() { + var parentControls = this.parent().items(); + + return parentControls[parentControls.indexOf(this) - 1]; + }, + + findCommonAncestor: function(ctrl1, ctrl2) { + var parentCtrl; + + while (ctrl1) { + parentCtrl = ctrl2; + + while (parentCtrl && ctrl1 != parentCtrl) { + parentCtrl = parentCtrl.parent(); + } + + if (ctrl1 == parentCtrl) { + break; + } + + ctrl1 = ctrl1.parent(); + } + + return ctrl1; + }, + + /** + * Returns true/false if the specific control has the specific class. + * + * @param {String} cls Class to check for. + * @return {Boolean} True/false if the control has the specified class. + */ + hasClass: function(cls, group) { + var classes = this._classes[group || 'control']; + + cls = this.classPrefix + cls; + + return classes && !!classes.map[cls]; + }, + + /** + * Adds the specified class to the control + * + * @param {String} cls Class to check for. + * @return {tinymce.ui.Control} Current control object. + */ + addClass: function(cls, group) { + var self = this, classes, elm; + + cls = this.classPrefix + cls; + classes = self._classes[group || 'control']; + + if (!classes) { + classes = []; + classes.map = {}; + self._classes[group || 'control'] = classes; + } + + if (!classes.map[cls]) { + classes.map[cls] = cls; + classes.push(cls); + + if (self._rendered) { + elm = self.getEl(group); + + if (elm) { + elm.className = classes.join(' '); + } + } + } + + return self; + }, + + /** + * Removed the specified class from the control. + * + * @param {String} cls Class to remove. + * @return {tinymce.ui.Control} Current control object. + */ + removeClass: function(cls, group) { + var self = this, classes, i, elm; + + cls = this.classPrefix + cls; + classes = self._classes[group || 'control']; + if (classes && classes.map[cls]) { + delete classes.map[cls]; + + i = classes.length; + while (i--) { + if (classes[i] === cls) { + classes.splice(i, 1); + } + } + } + + if (self._rendered) { + elm = self.getEl(group); + + if (elm) { + elm.className = classes.join(' '); + } + } + + return self; + }, + + toggleClass: function(cls, state, group) { + var self = this; + + if (state) { + self.addClass(cls, group); + } else { + self.removeClass(cls, group); + } + + return self; + }, + + classes: function(group) { + var classes = this._classes[group || 'control']; + + return classes ? classes.join(' ') : ''; + }, + + getEl: function(suffix, dropCache) { + var elm, id = suffix ? this._id + '-' + suffix : this._id; + + elm = elementIdCache[id] = (dropCache === true ? null : elementIdCache[id]) || DomUtils.get(id); + + return elm; + }, + + /** + * Sets/gets the visible for the control. + * + * @method visible + * @param {Boolean} state Value to set to control. + * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get. + */ + visible: function(state) { + var self = this, parentCtrl; + + if (typeof(state) !== "undefined") { + if (self._visible !== state) { + if (self._rendered) { + self.getEl().style.display = state ? '' : 'none'; + } + + self._visible = state; + + // Parent container needs to reflow + parentCtrl = self.parent(); + if (parentCtrl) { + parentCtrl._lastRect = null; + } + + self.fire(state ? 'show' : 'hide'); + } + + return self; + } + + return self._visible; + }, + + /** + * Sets the visible state to true. + * + * @return {tinymce.ui.Control} Current control instance. + */ + show: function() { + return this.visible(true); + }, + + /** + * Sets the visible state to false. + * + * @return {tinymce.ui.Control} Current control instance. + */ + hide: function() { + return this.visible(false); + }, + + focus: function() { + this.getEl().focus(); + }, + + blur: function() { + this.getEl().blur(); + }, + + aria: function(name, value) { + var self = this, elm = self.getEl(); + + if (typeof(value) === "undefined") { + return self._aria[name]; + } else { + self._aria[name] = value; + } + + if (self._rendered) { + if (name == 'label') { + elm.setAttribute('aria-labeledby', self._id); + } + + elm.setAttribute(name == 'role' ? name : 'aria-' + name, value); + } + + return self; + }, + + encode: function(text, translate) { + if (translate !== false && Control.translate) { + text = Control.translate(text); + } + + return (text || '').replace(/[&<>"]/g, function(match) { + return '&#' + match.charCodeAt(0) + ';'; + }); + }, + + before: function(items) { + var self = this, parent = self.parent(); + + if (parent) { + parent.insert(items, parent.items().indexOf(self), true); + } + + return self; + }, + + after: function(items) { + var self = this, parent = self.parent(); + + if (parent) { + parent.insert(items, parent.items().indexOf(self)); + } + + return self; + }, + + remove: function() { + var self = this, elm = self.getEl(), parent = self.parent(), newItems; + + if (self.items) { + var controls = self.items().toArray(); + var i = controls.length; + while (i--) { + controls[i].remove(); + } + } + + if (parent && parent.items) { + newItems = []; + + parent.items().each(function(item) { + if (item !== self) { + newItems.push(item); + } + }); + + parent.items().set(newItems); + parent._lastRect = null; + } + + if (self._eventsRoot && self._eventsRoot == self) { + DomUtils.off(elm); + } + + delete Control.controlIdLookup[self._id]; + + if (elm.parentNode) { + elm.parentNode.removeChild(elm); + } + + return self; + }, + + renderBefore: function(elm) { + var self = this; + + elm.parentNode.insertBefore(DomUtils.createFragment(self.renderHtml()), elm); + self.postRender(); + + return self; + }, + + renderTo: function(elm) { + var self = this; + + elm = elm || self.getContainerElm(); + elm.appendChild(DomUtils.createFragment(self.renderHtml())); + self.postRender(); + + return self; + }, + + postRender: function() { + var self = this, settings = self.settings, elm, box, parent, name, parentEventsRoot; + + // Bind on settings + for (name in settings) { + if (name.indexOf("on") === 0) { + self.on(name.substr(2), settings[name]); + } + } + + if (self._eventsRoot) { + for (parent = self.parent(); !parentEventsRoot && parent; parent = parent.parent()) { + parentEventsRoot = parent._eventsRoot; + } + + if (parentEventsRoot) { + for (name in parentEventsRoot._nativeEvents) { + self._nativeEvents[name] = true; + } + } + } + + self.bindPendingEvents(); + + if (settings.style) { + elm = self.getEl(); + if (elm) { + elm.setAttribute('style', settings.style); + elm.style.cssText = settings.style; + } + } + + if (!self._visible) { + DomUtils.css(self.getEl(), 'display', 'none'); + } + + if (self.settings.border) { + box = self.borderBox(); + DomUtils.css(self.getEl(), { + 'border-top-width': box.top, + 'border-right-width': box.right, + 'border-bottom-width': box.bottom, + 'border-left-width': box.left + }); + } + + // Add instance to lookup + Control.controlIdLookup[self._id] = self; + + for (var key in self._aria) { + self.aria(key, self._aria[key]); + } + + self.fire('postrender', {}, false); + }, + + scrollIntoView: function(align) { + function getOffset(elm, rootElm) { + var x, y, parent = elm; + + x = y = 0; + while (parent && parent != rootElm && parent.nodeType) { + x += parent.offsetLeft || 0; + y += parent.offsetTop || 0; + parent = parent.offsetParent; + } + + return {x: x, y: y}; + } + + var elm = this.getEl(), parentElm = elm.parentNode; + var x, y, width, height, parentWidth, parentHeight; + var pos = getOffset(elm, parentElm); + + x = pos.x; + y = pos.y; + width = elm.offsetWidth; + height = elm.offsetHeight; + parentWidth = parentElm.clientWidth; + parentHeight = parentElm.clientHeight; + + if (align == "end") { + x -= parentWidth - width; + y -= parentHeight - height; + } else if (align == "center") { + x -= (parentWidth / 2) - (width / 2); + y -= (parentHeight / 2) - (height / 2); + } + + parentElm.scrollLeft = x; + parentElm.scrollTop = y; + }, + + bindPendingEvents: function() { + var self = this, i, l, parents, eventRootCtrl, nativeEvents, name; + + function delegate(e) { + var control = self.getParentCtrl(e.target); + + if (control) { + control.fire(e.type, e); + } + } + + function mouseLeaveHandler() { + var ctrl = eventRootCtrl._lastHoverCtrl; + + if (ctrl) { + ctrl.fire("mouseleave", {target: ctrl.getEl()}); + + ctrl.parents().each(function(ctrl) { + ctrl.fire("mouseleave", {target: ctrl.getEl()}); + }); + + eventRootCtrl._lastHoverCtrl = null; + } + } + + function mouseEnterHandler(e) { + var ctrl = self.getParentCtrl(e.target), lastCtrl = eventRootCtrl._lastHoverCtrl, idx = 0, i, parents, lastParents; + + // Over on a new control + if (ctrl !== lastCtrl) { + eventRootCtrl._lastHoverCtrl = ctrl; + + parents = ctrl.parents().toArray().reverse(); + parents.push(ctrl); + + if (lastCtrl) { + lastParents = lastCtrl.parents().toArray().reverse(); + lastParents.push(lastCtrl); + + for (idx = 0; idx < lastParents.length; idx++) { + if (parents[idx] !== lastParents[idx]) { + break; + } + } + + for (i = lastParents.length - 1; i >= idx; i--) { + lastCtrl = lastParents[i]; + lastCtrl.fire("mouseleave", { + target : lastCtrl.getEl() + }); + } + } + + for (i = idx; i < parents.length; i++) { + ctrl = parents[i]; + ctrl.fire("mouseenter", { + target : ctrl.getEl() + }); + } + } + } + + function fixWheelEvent(e) { + e.preventDefault(); + + if (e.type == "mousewheel") { + e.deltaY = - 1/40 * e.wheelDelta; + + if (e.wheelDeltaX) { + e.deltaX = -1/40 * e.wheelDeltaX; + } + } else { + e.deltaX = 0; + e.deltaY = e.detail; + } + + e = self.fire("wheel", e); + } + + self._rendered = true; + + nativeEvents = self._nativeEvents; + if (nativeEvents) { + // Find event root element if it exists + parents = self.parents().toArray(); + parents.unshift(self); + for (i = 0, l = parents.length; !eventRootCtrl && i < l; i++) { + eventRootCtrl = parents[i]._eventsRoot; + } + + // Event root wasn't found the use the root control + if (!eventRootCtrl) { + eventRootCtrl = parents[parents.length - 1] || self; + } + + // Set the eventsRoot property on children that didn't have it + self._eventsRoot = eventRootCtrl; + for (l = i, i = 0; i < l; i++) { + parents[i]._eventsRoot = eventRootCtrl; + } + + // Bind native event delegates + for (name in nativeEvents) { + if (!nativeEvents) { + return false; + } + + if (name === "wheel" && !hasWheelEventSupport) { + if (hasMouseWheelEventSupport) { + DomUtils.on(self.getEl(), "mousewheel", fixWheelEvent); + } else { + DomUtils.on(self.getEl(), "DOMMouseScroll", fixWheelEvent); + } + + continue; + } + + // Special treatment for mousenter/mouseleave since these doesn't bubble + if (name === "mouseenter" || name === "mouseleave") { + // Fake mousenter/mouseleave + if (!eventRootCtrl._hasMouseEnter) { + DomUtils.on(eventRootCtrl.getEl(), "mouseleave", mouseLeaveHandler); + DomUtils.on(eventRootCtrl.getEl(), "mouseover", mouseEnterHandler); + eventRootCtrl._hasMouseEnter = 1; + } + } else if (!eventRootCtrl[name]) { + DomUtils.on(eventRootCtrl.getEl(), name, delegate); + eventRootCtrl[name] = true; + } + + // Remove the event once it's bound + nativeEvents[name] = false; + } + } + }, + + reflow: function() { + this.repaint(); + + return this; + } + + /** + * Sets/gets the parent container for the control. + * + * @method parent + * @param {tinymce.ui.Container} parent Optional parent to set. + * @return {tinymce.ui.Control} Parent control or the current control on a set action. + */ + // parent: function(parent) {} -- Generated + + /** + * Sets/gets the text for the control. + * + * @method text + * @param {String} value Value to set to control. + * @return {String/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // text: function(value) {} -- Generated + + /** + * Sets/gets the width for the control. + * + * @method width + * @param {Number} value Value to set to control. + * @return {Number/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // width: function(value) {} -- Generated + + /** + * Sets/gets the height for the control. + * + * @method height + * @param {Number} value Value to set to control. + * @return {Number/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // height: function(value) {} -- Generated + + /** + * Sets/gets the disabled for the control. + * + * @method disabled + * @param {Boolean} state Value to set to control. + * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get. + */ + // disabled: function(state) {} -- Generated + + /** + * Sets/gets the active for the control. + * + * @method active + * @param {Boolean} state Value to set to control. + * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get. + */ + // active: function(state) {} -- Generated + + /** + * Sets/gets the name for the control. + * + * @method name + * @param {String} value Value to set to control. + * @return {String/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // name: function(value) {} -- Generated + + /** + * Sets/gets the title for the control. + * + * @method title + * @param {String} value Value to set to control. + * @return {String/tinymce.ui.Control} Current control on a set operation or current value on a get. + */ + // title: function(value) {} -- Generated + }); + + return Control; +}); + +// Included from: js/tinymce/classes/ui/Factory.js + +/** + * Factory.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/*global tinymce:true */ + +/** + * .. + * + * @class tinymce.ui.Factory + */ +define("tinymce/ui/Factory", [], function() { + "use strict"; + + var types = {}, namespaceInit; + + return { + add: function(type, typeClass) { + types[type.toLowerCase()] = typeClass; + }, + + has: function(type) { + return !!types[type.toLowerCase()]; + }, + + /** + * Creates a new control instance based on the settings provided. The instance created will be + * based on the specified type property. + * + * @method create + * @example tinymce.ui.Factory.create({type: 'button', text: 'Hello world!'}); + * @param {Object/String} settings Name/Value object with items used to create the type. + * @return {tinymce.ui.Control} Control instance based on the specified type. + */ + create: function(type, settings) { + var ControlType, name, namespace; + + // Build type lookup + if (!namespaceInit) { + namespace = tinymce.ui; + + for (name in namespace) { + types[name.toLowerCase()] = namespace[name]; + } + + namespaceInit = true; + } + + // If string is specified then use it as the type + if (typeof(type) == 'string') { + settings = settings || {}; + settings.type = type; + } else { + settings = type; + type = settings.type; + } + + // Find control type + type = type.toLowerCase(); + ControlType = types[type]; + + // #if debug + + if (!ControlType) { + throw new Error("Could not find control by type: " + type); + } + + // #endif + + ControlType = new ControlType(settings); + ControlType.type = type; // Set the type on the instance, this will be used by the Selector engine + + return ControlType; + } + }; +}); + +// Included from: js/tinymce/classes/ui/Container.js + +/** + * Container.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Base container control. This will be extended by all controls + * that can have children such as panels etc. + * + * @-x-less Container.less + * @class tinymce.ui.Container + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Container", [ + "tinymce/ui/Control", + "tinymce/ui/Collection", + "tinymce/ui/Selector", + "tinymce/ui/Factory", + "tinymce/util/Tools", + "tinymce/ui/DomUtils" +], function(Control, Collection, Selector, Factory, Tools, DomUtils) { + "use strict"; + + var selectorCache = {}; + + return Control.extend({ + layout: '', + innerClass: 'container-inner', + + /** + * Constructor for the control. + * + * @constructor + * @method init + * @param {Object} settings Settings name/value object. + */ + init: function(settings) { + var self = this; + + self._super(settings); + settings = self.settings; + + self._items = new Collection(); + + self.addClass('container'); + self.addClass('container-body', 'body'); + + if (settings.containerCls) { + self.addClass(settings.containerCls); + } + + self._layout = Factory.create((settings.layout || self.layout) + 'layout'); + + if (self.settings.items) { + self.add(self.settings.items); + } + + // TODO: Fix this! + self._hasBody = true; + }, + + /** + * Returns a collection of child items that the container currently have. + * + * @method items + * @return {tinymce.ui.Collection} Control collection direct child controls. + */ + items: function() { + return this._items; + }, + + /** + * Find child controls by selector. + * + * @method find + * @param {String} selector Selector CSS pattern to find children by. + * @return {tinymce.ui.Collection} Control collection with child controls. + */ + find: function(selector) { + selector = selectorCache[selector] = selectorCache[selector] || new Selector(selector); + + return selector.find(this); + }, + + /** + * Adds one or many items to the current container. This will create instances of + * the object representations if needed. + * + * @method add + * @param {Array/Object/tinymce.ui.Control} items Array or item that will be added to the container. + * @return {tinymce.ui.Collection} Current collection control. + */ + add: function(items) { + var self = this; + + self.items().add(self.create(items)).parent(self); + + return self; + }, + + focus: function() { + var self = this; + + if (self.keyNav) { + self.keyNav.focusFirst(); + } else { + self._super(); + } + + return self; + }, + + replace: function(oldItem, newItem) { + var ctrlElm, items = this.items(), i = items.length; + + // Replace the item in collection + while (i--) { + if (items[i] === oldItem) { + items[i] = newItem; + break; + } + } + + if (i >= 0) { + // Remove new item from DOM + ctrlElm = newItem.getEl(); + if (ctrlElm) { + ctrlElm.parentNode.removeChild(ctrlElm); + } + + // Remove old item from DOM + ctrlElm = oldItem.getEl(); + if (ctrlElm) { + ctrlElm.parentNode.removeChild(ctrlElm); + } + } + + // Adopt the item + newItem.parent(this); + }, + + create: function(items) { + var self = this, settings, ctrlItems = []; + + // Non array structure, then force it into an array + if (!Tools.isArray(items)) { + items = [items]; + } + + // Add default type to each child control + Tools.each(items, function(item) { + if (item !== null) { + // Construct item if needed + if (!(item instanceof Control)) { + // Name only then convert it to an object + if (typeof(item) == "string") { + item = {type: item}; + } + + // Create control instance based on input settings and default settings + settings = Tools.extend({}, self.settings.defaults, item); + item.type = settings.type = settings.type || item.type || self.settings.defaultType || + (settings.defaults ? settings.defaults.type : null); + item = Factory.create(settings); + } + + ctrlItems.push(item); + } + }); + + return ctrlItems; + }, + + renderNew: function() { + var self = this; + + // Render any new items + self.items().each(function(ctrl, index) { + var containerElm, fragment; + + ctrl.parent(self); + + if (!ctrl._rendered) { + containerElm = self.getEl('body'); + fragment = DomUtils.createFragment(ctrl.renderHtml()); + + // Insert or append the item + if (containerElm.hasChildNodes() && index <= containerElm.childNodes.length - 1) { + containerElm.insertBefore(fragment, containerElm.childNodes[index]); + } else { + containerElm.appendChild(fragment); + } + + ctrl.postRender(); + } + }); + + self._layout.applyClasses(self); + self._lastRect = null; + + return self; + }, + + append: function(items) { + return this.add(items).renderNew(); + }, + + prepend: function(items) { + var self = this; + + self.items().set(self.create(items).concat(self.items().toArray())); + + return self.renderNew(); + }, + + insert: function(items, index, before) { + var self = this, curItems, beforeItems, afterItems; + + items = self.create(items); + curItems = self.items(); + + if (!before) { + index += 1; + } + + if (index >= 0 && index < curItems.length) { + beforeItems = curItems.slice(0, index).toArray(); + afterItems = curItems.slice(index).toArray(); + curItems.set(beforeItems.concat(items, afterItems)); + } + + return self.renderNew(); + }, + + preRender: function() { + }, + + renderHtml: function() { + var self = this, layout = self._layout; + + self.preRender(); + layout.preRender(self); + + return ( + '
    ' + + '
    '+ + (self.settings.html || '') + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + }, + + postRender: function() { + var self = this, box; + + self.items().exec('postRender'); + self._super(); + + self._layout.postRender(self); + self._rendered = true; + + if (self.settings.style) { + DomUtils.css(self.getEl(), self.settings.style); + } + + if (self.settings.border) { + box = self.borderBox(); + DomUtils.css(self.getEl(), { + 'border-top-width': box.top, + 'border-right-width': box.right, + 'border-bottom-width': box.bottom, + 'border-left-width': box.left + }); + } + + return self; + }, + + initLayoutRect: function() { + var self = this, layoutRect = self._super(); + + // Recalc container size by asking layout manager + self._layout.recalc(self); + + return layoutRect; + }, + + recalc: function() { + var self = this, rect = self._layoutRect, lastRect = self._lastRect; + + if (!lastRect || lastRect.w != rect.w || lastRect.h != rect.h) { + self._layout.recalc(self); + rect = self.layoutRect(); + self._lastRect = {x: rect.x, y: rect.y, w: rect.w, h: rect.h}; + return true; + } + }, + + reflow: function() { + var i, items; + + if (this.visible()) { + Control.repaintControls = []; + Control.repaintControls.map = {}; + + items = this.recalc(); + i = Control.repaintControls.length; + + while (i--) { + Control.repaintControls[i].repaint(); + } + + // TODO: Fix me! + if (this.settings.layout !== "flow" && this.settings.layout !== "stack") { + this.repaint(); + } + + Control.repaintControls = []; + } + + return this; + } + }); +}); + +// Included from: js/tinymce/classes/ui/DragHelper.js + +/** + * DragHelper.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Drag/drop helper class. + * + * @example + * var dragHelper = new tinymce.ui.DragHelper('mydiv', { + * start: function(evt) { + * }, + * + * drag: function(evt) { + * }, + * + * end: function(evt) { + * } + * }); + */ +define("tinymce/ui/DragHelper", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + function getDocumentSize() { + var doc = document, documentElement, body, scrollWidth, clientWidth; + var offsetWidth, scrollHeight, clientHeight, offsetHeight, max = Math.max; + + documentElement = doc.documentElement; + body = doc.body; + + scrollWidth = max(documentElement.scrollWidth, body.scrollWidth); + clientWidth = max(documentElement.clientWidth, body.clientWidth); + offsetWidth = max(documentElement.offsetWidth, body.offsetWidth); + + scrollHeight = max(documentElement.scrollHeight, body.scrollHeight); + clientHeight = max(documentElement.clientHeight, body.clientHeight); + offsetHeight = max(documentElement.offsetHeight, body.offsetHeight); + + return { + width: scrollWidth < offsetWidth ? clientWidth : scrollWidth, + height: scrollHeight < offsetHeight ? clientHeight : scrollHeight + }; + } + + return function(id, settings) { + var eventOverlayElm, doc = document, downButton, start, stop, drag, startX, startY; + + settings = settings || {}; + + function getHandleElm() { + return doc.getElementById(settings.handle || id); + } + + start = function(e) { + var docSize = getDocumentSize(), handleElm, cursor; + + e.preventDefault(); + downButton = e.button; + handleElm = getHandleElm(); + startX = e.screenX; + startY = e.screenY; + + // Grab cursor from handle + if (window.getComputedStyle) { + cursor = window.getComputedStyle(handleElm, null).getPropertyValue("cursor"); + } else { + cursor = handleElm.runtimeStyle.cursor; + } + + // Create event overlay and add it to document + eventOverlayElm = doc.createElement('div'); + DomUtils.css(eventOverlayElm, { + position: "absolute", + top: 0, left: 0, + width: docSize.width, + height: docSize.height, + zIndex: 0xFFFF, + opacity: 0.0001, + background: 'red', + cursor: cursor + }); + + doc.body.appendChild(eventOverlayElm); + + // Bind mouse events + DomUtils.on(doc, 'mousemove', drag); + DomUtils.on(doc, 'mouseup', stop); + + // Begin drag + settings.start(e); + }; + + drag = function(e) { + if (e.button !== downButton) { + return stop(e); + } + + e.deltaX = e.screenX - startX; + e.deltaY = e.screenY - startY; + + e.preventDefault(); + settings.drag(e); + }; + + stop = function(e) { + DomUtils.off(doc, 'mousemove', drag); + DomUtils.off(doc, 'mouseup', stop); + + eventOverlayElm.parentNode.removeChild(eventOverlayElm); + + if (settings.stop) { + settings.stop(e); + } + }; + + this.destroy = function() { + DomUtils.off(getHandleElm()); + }; + + DomUtils.on(getHandleElm(), 'mousedown', start); + }; +}); + +// Included from: js/tinymce/classes/ui/Scrollable.js + +/** + * Scrollable.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Scrollable.less + * @mixin tinymce.ui.Scrollable + */ +define("tinymce/ui/Scrollable", [ + "tinymce/ui/DomUtils", + "tinymce/ui/DragHelper" +], function(DomUtils, DragHelper) { + "use strict"; + + return { + init: function() { + var self = this; + self.on('repaint', self.renderScroll); + }, + + renderScroll: function() { + var self = this, margin = 2; + + function repaintScroll() { + var hasScrollH, hasScrollV, bodyElm; + + function repaintAxis(axisName, posName, sizeName, contentSizeName, hasScroll, ax) { + var containerElm, scrollBarElm, scrollThumbElm; + var containerSize, scrollSize, ratio, rect; + var posNameLower, sizeNameLower; + + scrollBarElm = self.getEl('scroll' + axisName); + if (scrollBarElm) { + posNameLower = posName.toLowerCase(); + sizeNameLower = sizeName.toLowerCase(); + + if (self.getEl('absend')) { + DomUtils.css(self.getEl('absend'), posNameLower, self.layoutRect()[contentSizeName] - 1); + } + + if (!hasScroll) { + DomUtils.css(scrollBarElm, 'display', 'none'); + return; + } + + DomUtils.css(scrollBarElm, 'display', 'block'); + containerElm = self.getEl('body'); + scrollThumbElm = self.getEl('scroll' + axisName + "t"); + containerSize = containerElm["client" + sizeName] - (margin * 2); + containerSize -= hasScrollH && hasScrollV ? scrollBarElm["client" + ax] : 0; + scrollSize = containerElm["scroll" + sizeName]; + ratio = containerSize / scrollSize; + + rect = {}; + rect[posNameLower] = containerElm["offset" + posName] + margin; + rect[sizeNameLower] = containerSize; + DomUtils.css(scrollBarElm, rect); + + rect = {}; + rect[posNameLower] = containerElm["scroll" + posName] * ratio; + rect[sizeNameLower] = containerSize * ratio; + DomUtils.css(scrollThumbElm, rect); + } + } + + bodyElm = self.getEl('body'); + hasScrollH = bodyElm.scrollWidth > bodyElm.clientWidth; + hasScrollV = bodyElm.scrollHeight > bodyElm.clientHeight; + + repaintAxis("h", "Left", "Width", "contentW", hasScrollH, "Height"); + repaintAxis("v", "Top", "Height", "contentH", hasScrollV, "Width"); + } + + function addScroll() { + function addScrollAxis(axisName, posName, sizeName, deltaPosName, ax) { + var scrollStart, axisId = self._id + '-scroll' + axisName, prefix = self.classPrefix; + + self.getEl().appendChild(DomUtils.createFragment( + '
    ' + + '
    ' + + '
    ' + )); + + self.draghelper = new DragHelper(axisId + 't', { + start: function() { + scrollStart = self.getEl('body')["scroll" + posName]; + DomUtils.addClass(DomUtils.get(axisId), prefix + 'active'); + }, + + drag: function(e) { + var ratio, hasScrollH, hasScrollV, containerSize, layoutRect = self.layoutRect(); + + hasScrollH = layoutRect.contentW > layoutRect.innerW; + hasScrollV = layoutRect.contentH > layoutRect.innerH; + containerSize = self.getEl('body')["client" + sizeName] - (margin * 2); + containerSize -= hasScrollH && hasScrollV ? self.getEl('scroll' + axisName)["client" + ax] : 0; + + ratio = containerSize / self.getEl('body')["scroll" + sizeName]; + self.getEl('body')["scroll" + posName] = scrollStart + (e["delta" + deltaPosName] / ratio); + }, + + stop: function() { + DomUtils.removeClass(DomUtils.get(axisId), prefix + 'active'); + } + }); +/* + self.on('click', function(e) { + if (e.target.id == self._id + '-scrollv') { + + } + });*/ + } + + self.addClass('scroll'); + + addScrollAxis("v", "Top", "Height", "Y", "Width"); + addScrollAxis("h", "Left", "Width", "X", "Height"); + } + + if (self.settings.autoScroll) { + if (!self._hasScroll) { + self._hasScroll = true; + addScroll(); + + self.on('wheel', function(e) { + var bodyEl = self.getEl('body'); + + bodyEl.scrollLeft += (e.deltaX || 0) * 10; + bodyEl.scrollTop += e.deltaY * 10; + + repaintScroll(); + }); + + DomUtils.on(self.getEl('body'), "scroll", repaintScroll); + } + + repaintScroll(); + } + } + }; +}); + +// Included from: js/tinymce/classes/ui/Panel.js + +/** + * Panel.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Panel.less + * @class tinymce.ui.Panel + * @extends tinymce.ui.Container + */ +define("tinymce/ui/Panel", [ + "tinymce/ui/Container", + "tinymce/ui/Scrollable" +], function(Container, Scrollable) { + "use strict"; + + var Panel = Container.extend({ + Defaults: { + layout: 'fit', + containerCls: 'panel' + }, + + Mixins: [Scrollable], + + fromJSON: function(data) { + var self = this; + + for (var name in data) { + self.find('#' + name).value(data[name]); + } + + return self; + }, + + toJSON: function() { + var self = this, data = {}; + + self.find('*').each(function(ctrl) { + var name = ctrl.name(), value = ctrl.value(); + + if (name && typeof(value) != "undefined") { + data[name] = value; + } + }); + + return data; + }, + + renderHtml: function() { + var self = this, layout = self._layout, innerHtml = self.settings.html; + + self.preRender(); + layout.preRender(self); + + if (typeof(innerHtml) == "undefined") { + innerHtml = ( + '
    ' + + layout.renderHtml(self) + + '
    ' + ); + } else { + if (typeof(innerHtml) == 'function') { + innerHtml = innerHtml(); + } + + self._hasBody = false; + } + + return ( + '
    ' + + (self._preBodyHtml || '') + + innerHtml + + '
    ' + ); + } + }); + + return Panel; +}); + +// Included from: js/tinymce/classes/ui/Movable.js + +/** + * Movable.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +define("tinymce/ui/Movable", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + return { + moveRel: function(elm, rel) { + var self = this, ctrlElm, pos, x, y, selfW, selfH, targetW, targetH; + + // Get pos of target + pos = DomUtils.getPos(elm); + x = pos.x; + y = pos.y; + + // Get size of self + ctrlElm = self.getEl(); + selfW = ctrlElm.offsetWidth; + selfH = ctrlElm.offsetHeight; + + // Get size of target + targetW = elm.offsetWidth; + targetH = elm.offsetHeight; + + // Parse align string + rel = (rel || '').split(''); + + // Target corners + if (rel[0] === 'b') { + y += targetH; + } + + if (rel[1] === 'r') { + x += targetW; + } + + if (rel[0] === 'c') { + y += Math.round(targetH / 2); + } + + if (rel[1] === 'c') { + x += Math.round(targetW / 2); + } + + // Self corners + if (rel[3] === 'b') { + y -= selfH; + } + + if (rel[4] === 'r') { + x -= selfW; + } + + if (rel[3] === 'c') { + y -= Math.round(selfH / 2); + } + + if (rel[4] === 'c') { + x -= Math.round(selfW / 2); + } + + self.moveTo(x, y); + + return self; + }, + + moveBy: function(dx, dy) { + var self = this, rect = self.layoutRect(); + + self.moveTo(rect.x + dx, rect.y + dy); + + return self; + }, + + moveTo: function(x, y) { + var self = this; + + if (self._rendered) { + self.layoutRect({x: x, y: y}).repaint(); + } else { + self.settings.x = x; + self.settings.y = y; + } + + return self; + } + }; +}); + +// Included from: js/tinymce/classes/ui/Resizable.js + +/** + * Resizable.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +define("tinymce/ui/Resizable", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + return { + resizeToContent: function() { + this._layoutRect.autoResize = true; + this._lastRect = null; + this.reflow(); + }, + + resizeTo: function(w, h) { + // TODO: Fix hack + if (w <= 1 || h <= 1) { + var rect = DomUtils.getWindowSize(); + + w = w <= 1 ? w * rect.w : w; + h = h <= 1 ? h * rect.h : h; + } + + this._layoutRect.autoResize = false; + return this.layoutRect({minW: w, minH: h, w: w, h: h}).reflow(); + }, + + resizeBy: function(dw, dh) { + var self = this, rect = self.layoutRect(); + + return self.resizeTo(rect.w + dw, rect.h + dh); + } + }; +}); + +// Included from: js/tinymce/classes/ui/FloatPanel.js + +/** + * FloatPanel.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less FloatPanel.less + * @class tinymce.ui.FloatPanel + * @extends tinymce.ui.Panel + */ +define("tinymce/ui/FloatPanel", [ + "tinymce/ui/Panel", + "tinymce/ui/Movable", + "tinymce/ui/Resizable", + "tinymce/ui/DomUtils" +], function(Panel, Movable, Resizable, DomUtils) { + "use strict"; + + var documentClickHandler, autoHidePanels = []; + var zOrder = [], hasModal; + + var FloatPanel = Panel.extend({ + Mixins: [Movable, Resizable], + + init: function(settings) { + var self = this; + + function reorder() { + var i, zIndex = FloatPanel.zIndex || 0xFFFF, topModal; + + if (zOrder.length) { + for (i = 0; i < zOrder.length; i++) { + if (zOrder[i].modal) { + zIndex++; + topModal = zOrder[i]; + } + + zOrder[i].getEl().style.zIndex = zIndex; + zOrder[i].zIndex = zIndex; + zIndex++; + } + } + + var modalBlockEl = document.getElementById(self.classPrefix + 'modal-block'); + + if (topModal) { + DomUtils.css(modalBlockEl, 'z-index', topModal.zIndex - 1); + } else if (modalBlockEl) { + modalBlockEl.parentNode.removeChild(modalBlockEl); + hasModal = false; + } + + FloatPanel.currentZIndex = zIndex; + } + + function isChildOf(ctrl, parent) { + while (ctrl) { + if (ctrl == parent) { + return true; + } + + ctrl = ctrl.parent(); + } + } + + self._super(settings); + self._eventsRoot = self; + + self.addClass('floatpanel'); + + // Hide floatpanes on click out side the root button + if (settings.autohide) { + if (!documentClickHandler) { + documentClickHandler = function(e) { + var i, clickCtrl = self.getParentCtrl(e.target); + + // Hide any float panel when a click is out side that float panel and the + // float panels direct parent for example a click on a menu button + i = autoHidePanels.length; + while (i--) { + if (clickCtrl) { + if (isChildOf(clickCtrl, autoHidePanels[i]) || autoHidePanels[i].parent() === clickCtrl) { + continue; + } + } + + autoHidePanels[i].hide(); + } + }; + + DomUtils.on(document, 'click', documentClickHandler); + } + + autoHidePanels.push(self); + } + + self.on('postrender show', function(e) { + if (e.control == self) { + var modalBlockEl, prefix = self.classPrefix; + + if (self.modal && !hasModal) { + modalBlockEl = DomUtils.createFragment('
    '); + modalBlockEl = modalBlockEl.firstChild; + + self.getContainerElm().appendChild(modalBlockEl); + + setTimeout(function() { + DomUtils.addClass(modalBlockEl, prefix + 'in'); + DomUtils.addClass(self.getEl(), prefix + 'in'); + }, 0); + + hasModal = true; + } + + zOrder.push(self); + reorder(); + } + }); + + self.on('close hide', function(e) { + if (e.control == self) { + var i = zOrder.length; + + while (i--) { + if (zOrder[i] === self) { + zOrder.splice(i, 1); + } + } + + reorder(); + } + }); + + if (settings.popover) { + self._preBodyHtml = '
    '; + self.addClass('popover').addClass('bottom').addClass('start'); + } + }, + + show: function() { + var self = this, i, state = self._super(); + + i = autoHidePanels.length; + while (i--) { + if (autoHidePanels[i] === self) { + break; + } + } + + if (self.settings.autohide && i === -1) { + autoHidePanels.push(self); + } + + return state; + }, + + hide: function() { + var i; + + i = autoHidePanels.length; + while (i--) { + if (autoHidePanels[i] === this) { + autoHidePanels.splice(i, 1); + } + } + + return this._super(); + }, + + hideAll: function() { + FloatPanel.hideAll(); + }, + + close: function() { + var self = this; + + self.fire('close'); + + return self.remove(); + }, + + remove: function() { + var self = this; + + self._super(); + } + }); + + FloatPanel.hideAll = function() { + var i = autoHidePanels.length; + + while (i--) { + autoHidePanels[i].fire('cancel', {}, false); + autoHidePanels[i].hide(); + autoHidePanels.splice(i, 1); + } + }; + + return FloatPanel; +}); + +// Included from: js/tinymce/classes/ui/KeyboardNavigation.js + +/** + * KeyboardFocus.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.KeyboardNavigation + */ +define("tinymce/ui/KeyboardNavigation", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + /** + * Create a new KeyboardNavigation instance to handle the focus for a specific element. + * + * @constructor + * @method KeyboardNavigation + * @param {Object} settings the settings object to define how keyboard navigation works. + * + * @setting {tinymce.ui.Control} root the root control navigation focus movement is scoped to this root. + * @setting {Array} items an array containing the items to move focus between. Every object in this array must have an + * id attribute which maps to the actual DOM element and it must be able to have focus i.e. tabIndex=-1. + * @setting {Function} onCancel the callback for when the user presses escape or otherwise indicates cancelling. + * @setting {Function} onAction (optional) the action handler to call when the user activates an item. + * @setting {Boolean} enableLeftRight (optional, default) when true, the up/down arrows move through items. + * @setting {Boolean} enableUpDown (optional) when true, the up/down arrows move through items. + * Note for both up/down and left/right explicitly set both enableLeftRight and enableUpDown to true. + */ + return function(settings) { + var root = settings.root, enableUpDown = settings.enableUpDown !== false; + var enableLeftRight = settings.enableLeftRight !== false; + var items = settings.items, focussedId; + + /** + * Initializes the items array if needed. This will collect items/elements + * from the specified root control. + */ + function initItems() { + if (!items) { + items = []; + + if (root.find) { + // Root is a container then get child elements using the UI API + root.find('*').each(function(ctrl) { + if (ctrl.canFocus) { + items.push(ctrl.getEl()); + } + }); + } else { + // Root is a control/widget then get the child elements of that control + var elements = root.getEl().getElementsByTagName('*'); + for (var i = 0; i < elements.length; i++) { + if (elements[i].id && elements[i]) { + items.push(elements[i]); + } + } + } + } + } + + /** + * Returns the currently focused element. + * + * @return {Element} Currently focused element. + */ + function getFocusElement() { + return document.getElementById(focussedId); + } + + /** + * Returns the currently focused elements wai aria role. + * + * @param {Element} elm Optional element to get role from. + * @return {String} Role of specified element. + */ + function getRole(elm) { + elm = elm || getFocusElement(); + + return elm && elm.getAttribute('role'); + } + + /** + * Returns the role of the parent element. + * + * @param {Element} elm Optional element to get parent role from. + * @return {String} Role of the first parent that has a role. + */ + function getParentRole(elm) { + var role, parent = elm || getFocusElement(); + + while ((parent = parent.parentNode)) { + if ((role = getRole(parent))) { + return role; + } + } + } + + /** + * Returns an wai aria property by name. + * + * @param {String} name Name of the aria property to get for example "disabled". + * @return {String} Aria property value. + */ + function getAriaProp(name) { + var elm = document.getElementById(focussedId); + + if (elm) { + return elm.getAttribute('aria-' + name); + } + } + + /** + * Executes the onAction event callback. This is when the user presses enter/space. + */ + function action() { + var focusElm = getFocusElement(); + + if (focusElm && (focusElm.nodeName == "TEXTAREA" || focusElm.type == "text")) { + return; + } + + if (settings.onAction) { + settings.onAction(focussedId); + } else { + DomUtils.fire(getFocusElement(), 'click', {keyboard: true}); + } + + return true; + } + + /** + * Cancels the current navigation. The same as pressing the Esc key. + */ + function cancel() { + var focusElm; + + if (settings.onCancel) { + if ((focusElm = getFocusElement())) { + focusElm.blur(); + } + + settings.onCancel(); + } else { + settings.root.fire('cancel'); + } + } + + /** + * Moves the focus to the next or previous item. It will wrap to start/end if it can't move. + * + * @param {Number} dir Direction for move -1 or 1. + */ + function moveFocus(dir) { + var idx = -1, focusElm, i; + + initItems(); + + i = items.length; + while (i--) { + if (items[i].id === focussedId) { + idx = i; + break; + } + } + + idx += dir; + if (idx < 0) { + idx = items.length - 1; + } else if (idx >= items.length) { + idx = 0; + } + + focusElm = items[idx]; + focusElm.focus(); + focussedId = focusElm.id; + + if (settings.actOnFocus) { + action(); + } + } + + /** + * Moves focus to the first item or the last focused item if root is a toolbar. + * + * @return {[type]} [description] + */ + function focusFirst() { + var i, rootRole; + + rootRole = getRole(settings.root.getEl()); + initItems(); + + i = items.length; + while (i--) { + if (rootRole == 'toolbar' && items[i].id === focussedId) { + items[i].focus(); + return; + } + } + + items[0].focus(); + } + + // Handle accessible keys + root.on('keydown', function(e) { + var DOM_VK_LEFT = 37, DOM_VK_RIGHT = 39, DOM_VK_UP = 38, DOM_VK_DOWN = 40; + var DOM_VK_ESCAPE = 27, DOM_VK_ENTER = 14, DOM_VK_RETURN = 13, DOM_VK_SPACE = 32, DOM_VK_TAB = 9; + var preventDefault; + + switch (e.keyCode) { + case DOM_VK_LEFT: + if (enableLeftRight) { + if (settings.leftAction) { + settings.leftAction(); + } else { + moveFocus(-1); + } + + preventDefault = true; + } + break; + + case DOM_VK_RIGHT: + if (enableLeftRight) { + if (getRole() == 'menuitem' && getParentRole() == 'menu') { + if (getAriaProp('haspopup')) { + action(); + } + } else { + moveFocus(1); + } + + preventDefault = true; + } + break; + + case DOM_VK_UP: + if (enableUpDown) { + moveFocus(-1); + preventDefault = true; + } + break; + + case DOM_VK_DOWN: + if (enableUpDown) { + if (getRole() == 'menuitem' && getParentRole() == 'menubar') { + action(); + } else if (getRole() == 'button' && getAriaProp('haspopup')) { + action(); + } else { + moveFocus(1); + } + + preventDefault = true; + } + break; + + case DOM_VK_TAB: + preventDefault = true; + + if (e.shiftKey) { + moveFocus(-1); + } else { + moveFocus(1); + } + break; + + case DOM_VK_ESCAPE: + preventDefault = true; + cancel(); + break; + + case DOM_VK_ENTER: + case DOM_VK_RETURN: + case DOM_VK_SPACE: + preventDefault = action(); + break; + } + + if (preventDefault) { + e.stopPropagation(); + e.preventDefault(); + } + }); + + // Init on focus in + root.on('focusin', function(e) { + initItems(); + focussedId = e.target.id; + }); + + return { + moveFocus: moveFocus, + focusFirst: focusFirst, + cancel: cancel + }; + }; +}); + +// Included from: js/tinymce/classes/ui/Window.js + +/** + * Window.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Window.less + * @class tinymce.ui.Window + * @extends tinymce.ui.FloatPanel + */ +define("tinymce/ui/Window", [ + "tinymce/ui/FloatPanel", + "tinymce/ui/Panel", + "tinymce/ui/DomUtils", + "tinymce/ui/KeyboardNavigation", + "tinymce/ui/DragHelper" +], function(FloatPanel, Panel, DomUtils, KeyboardNavigation, DragHelper) { + "use strict"; + + var Window = FloatPanel.extend({ + modal: true, + + Defaults: { + border: 1, + layout: 'flex', + containerCls: 'panel', + role: 'dialog', + callbacks: { + submit: function() { + this.fire('submit', {data: this.toJSON()}); + }, + + close: function() { + this.close(); + } + } + }, + + init: function(settings) { + var self = this; + + self._super(settings); + + self.addClass('window'); + + // Create statusbar + if (settings.buttons) { + self.statusbar = new Panel({ + layout: 'flex', + border: '1 0 0 0', + spacing: 3, + padding: 10, + align: 'center', + pack: 'end', + defaults: { + type: 'button' + }, + items: settings.buttons + }); + + self.statusbar.addClass('foot'); + self.statusbar.parent(self); + } + + self.on('click', function(e) { + if (e.target.className.indexOf(self.classPrefix + 'close') != -1) { + self.close(); + } + }); +/* + self.on('postrender show', function(e) { + if (e.control == self) { + var parentWin = getTopMostWindow(), zIndex = FloatPanel.zIndex; + + if (parentWin) { + zIndex = parentWin.zIndex; + } + + if (!DomUtils.get(prefix + 'modal-block')) { + var modalBlockEl = DomUtils.createFragment('
    '); + + modalBlockEl = modalBlockEl.firstChild; + + self.getContainerElm().appendChild(modalBlockEl); + + setTimeout(function() { + DomUtils.addClass(modalBlockEl, prefix + 'in'); + DomUtils.addClass(self.getEl(), prefix + 'in'); + }, 0); + + FloatPanel.zOrder.push({zIndex: zIndex}); + DomUtils.css(self.getEl(), 'z-index', zIndex + 1); + } + + DomUtils.css(DomUtils.get(prefix + 'modal-block'), 'z-index', zIndex - 1); + } + }); + + self.on('close hide', function(e) { + if (e.control == self) { + var topWin = getTopMostWindow(); + + if (!topWin) { + var modalBlockEl = document.getElementById(prefix + 'modal-block'); + if (modalBlockEl) { + modalBlockEl.parentNode.removeChild(modalBlockEl); + } + } else { + DomUtils.css(DomUtils.get(prefix + 'modal-block'), 'z-index', topWin.zIndex - 1); + } + } + }); +*/ + self.aria('label', settings.title); + self._fullscreen = false; + }, + + recalc: function() { + var self = this, statusbar = self.statusbar, layoutRect, width, needsRecalc; + + if (self._fullscreen) { + self.layoutRect(DomUtils.getWindowSize()); + self.layoutRect().contentH = self.layoutRect().innerH; + } + + self._super(); + + layoutRect = self.layoutRect(); + + // Resize window based on title width + if (self.settings.title && !self._fullscreen) { + width = layoutRect.headerW; + if (width > layoutRect.minW) { + layoutRect.minW = layoutRect.w = width + (layoutRect.w - layoutRect.innerW); + layoutRect.innerW = layoutRect.w - layoutRect.deltaW; + needsRecalc = true; + } + } + + // Resize window based on statusbar width + if (statusbar) { + statusbar.layoutRect({w: self.layoutRect().innerW}).recalc(); + + width = statusbar.layoutRect().minW + layoutRect.deltaW; + if (width > layoutRect.minW) { + layoutRect.minW = layoutRect.w = width; + layoutRect.innerW = layoutRect.w - layoutRect.deltaW; + needsRecalc = true; + } + } + + // Recalc body and disable auto resize + if (needsRecalc) { + self.recalc(); + return; + } + }, + + initLayoutRect: function() { + var self = this, layoutRect = self._super(), deltaH = 0, headEl; + + // Reserve vertical space for title + if (self.settings.title && !self._fullscreen) { + headEl = self.getEl('head'); + layoutRect.headerW = headEl.offsetWidth; + layoutRect.headerH = headEl.offsetHeight; + deltaH += layoutRect.headerH; + } + + // Reserve vertical space for statusbar + if (self.statusbar) { + deltaH += self.statusbar.layoutRect().h; + } + + layoutRect.deltaH += deltaH; + layoutRect.minH += deltaH; + //layoutRect.innerH -= deltaH; + layoutRect.h += deltaH; + + var rect = DomUtils.getWindowSize(); + + layoutRect.x = Math.max(0, rect.w / 2 - layoutRect.w / 2); + layoutRect.y = Math.max(0, rect.h / 2 - layoutRect.h / 2); + + return layoutRect; + }, + + renderHtml: function() { + var self = this, layout = self._layout, id = self._id, prefix = self.classPrefix; + var settings = self.settings, headerHtml = '', footerHtml = '', html = settings.html; + + self.preRender(); + layout.preRender(self); + + if (settings.title) { + headerHtml = ( + '
    ' + + '
    ' + settings.title + '
    ' + + '' + + '
    ' + + '
    ' + ); + } + + if (settings.url) { + html = ''; + } + + if (typeof(html) == "undefined") { + html = layout.renderHtml(self); + } + + if (self.statusbar) { + footerHtml = self.statusbar.renderHtml(); + } + + return ( + '
    ' + + headerHtml + + '
    ' + + html + + '
    ' + + footerHtml + + '
    ' + ); + }, + + fullscreen: function(state) { + var self = this, documentElement = document.documentElement, slowRendering, prefix = self.classPrefix, layoutRect; + + if (state != self._fullscreen) { + DomUtils.on(window, 'resize', function() { + var time; + + if (self._fullscreen) { + // Time the layout time if it's to slow use a timeout to not hog the CPU + if (!slowRendering) { + time = new Date().getTime(); + + var rect = DomUtils.getWindowSize(); + self.moveTo(0, 0).resizeTo(rect.w, rect.h); + + if ((new Date().getTime()) - time > 50) { + slowRendering = true; + } + } else { + if (!self._timer) { + self._timer = setTimeout(function() { + var rect = DomUtils.getWindowSize(); + self.moveTo(0, 0).resizeTo(rect.w, rect.h); + + self._timer = 0; + }, 50); + } + } + } + }); + + layoutRect = self.layoutRect(); + self._fullscreen = state; + + if (!state) { + self._borderBox = self.parseBox(self.settings.border); + self.getEl('head').style.display = ''; + layoutRect.deltaH += layoutRect.headerH; + DomUtils.removeClass(documentElement, prefix + 'fullscreen'); + DomUtils.removeClass(document.body, prefix + 'fullscreen'); + self.removeClass('fullscreen'); + self.moveTo(self._initial.x, self._initial.y).resizeTo(self._initial.w, self._initial.h); + } else { + self._initial = {x: layoutRect.x, y: layoutRect.y, w: layoutRect.w, h: layoutRect.h}; + + self._borderBox = self.parseBox('0'); + self.getEl('head').style.display = 'none'; + layoutRect.deltaH -= layoutRect.headerH + 2; + DomUtils.addClass(documentElement, prefix + 'fullscreen'); + DomUtils.addClass(document.body, prefix + 'fullscreen'); + self.addClass('fullscreen'); + + var rect = DomUtils.getWindowSize(); + self.moveTo(0, 0).resizeTo(rect.w, rect.h); + } + } + + return self.reflow(); + }, + + postRender: function() { + var self = this, items = [], focusCtrl, autoFocusFound, startPos; + + setTimeout(function() { + self.addClass('in'); + }, 0); + + self.find('*').each(function(ctrl) { + if (ctrl.canFocus) { + autoFocusFound = autoFocusFound || ctrl.settings.autofocus; + focusCtrl = focusCtrl || ctrl; + + // TODO: Figure out a better way + if (ctrl.type == 'filepicker') { + items.push(ctrl.getEl('inp')); + + if (ctrl.getEl('open')) { + items.push(ctrl.getEl('open').firstChild); + } + } else { + items.push(ctrl.getEl()); + } + } + }); + + if (self.statusbar) { + self.statusbar.find('*').each(function(ctrl) { + if (ctrl.canFocus) { + autoFocusFound = autoFocusFound || ctrl.settings.autofocus; + focusCtrl = focusCtrl || ctrl; + items.push(ctrl.getEl()); + } + }); + } + + self.keyboardNavigation = new KeyboardNavigation({ + root: self, + enableLeftRight: false, + enableUpDown: false, + items: items, + onCancel: function() { + self.close(); + } + }); + + self._super(); + + if (self.statusbar) { + self.statusbar.postRender(); + } + + if (!autoFocusFound && focusCtrl) { + focusCtrl.focus(); + } + + this.dragHelger = new DragHelper(self._id + '-dragh', { + start: function() { + startPos = { + x: self.layoutRect().x, + y: self.layoutRect().y + }; + }, + + drag: function(e) { + self.moveTo(startPos.x + e.deltaX, startPos.y + e.deltaY); + } + }); + + self.on('submit', function(e) { + if (!e.isDefaultPrevented()) { + self.close(); + } + }); + }, + + submit: function() { + return this.fire('submit', {data: this.toJSON()}); + }, + + remove: function() { + var self = this; + + self._super(); + self.dragHelger.destroy(); + + if (self.statusbar) { + this.statusbar.remove(); + } + } + }); + + return Window; +}); + +// Included from: js/tinymce/classes/ui/MessageBox.js + +/** + * MessageBox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.Window + * @extends tinymce.ui.FloatPanel + */ +define("tinymce/ui/MessageBox", [ + "tinymce/ui/Window" +], function(Window) { + "use strict"; + + var MessageBox = Window.extend({ + init: function(settings) { + settings = { + border: 1, + padding: 20, + layout: 'flex', + pack: "center", + align: "center", + containerCls: 'panel', + autoScroll: true, + buttons: {type: "button", text: "Ok", action: "ok"}, + items: { + type: "label", + multiline: true, + maxWidth: 500, + maxHeight: 200 + } + }; + + this._super(settings); + }, + + Statics: { + OK: 1, + OK_CANCEL: 2, + YES_NO: 3, + YES_NO_CANCEL: 4, + + msgBox: function(settings) { + var buttons, callback = settings.callback || function() {}; + + switch (settings.buttons) { + case MessageBox.OK_CANCEL: + buttons = [ + {type: "button", text: "Ok", subtype: "primary", onClick: function(e) { + e.control.parents()[1].close(); + callback(true); + }}, + + {type: "button", text: "Cancel", onClick: function(e) { + e.control.parents()[1].close(); + callback(false); + }} + ]; + break; + + case MessageBox.YES_NO: + buttons = [ + {type: "button", text: "Ok", subtype: "primary", onClick: function(e) { + e.control.parents()[1].close(); + callback(true); + }} + ]; + break; + + case MessageBox.YES_NO_CANCEL: + buttons = [ + {type: "button", text: "Ok", subtype: "primary", onClick: function(e) { + e.control.parents()[1].close(); + }} + ]; + break; + + default: + buttons = [ + {type: "button", text: "Ok", subtype: "primary", onClick: function(e) { + e.control.parents()[1].close(); + }} + ]; + break; + } + + return new Window({ + padding: 20, + x: settings.x, + y: settings.y, + minWidth: 300, + minHeight: 100, + layout: "flex", + pack: "center", + align: "center", + buttons: buttons, + title: settings.title, + items: { + type: "label", + multiline: true, + maxWidth: 500, + maxHeight: 200, + text: settings.text + }, + onClose: settings.onClose + }).renderTo(document.body).reflow(); + }, + + alert: function(settings, callback) { + if (typeof(settings) == "string") { + settings = {text: settings}; + } + + settings.callback = callback; + return MessageBox.msgBox(settings); + }, + + confirm: function(settings, callback) { + if (typeof(settings) == "string") { + settings = {text: settings}; + } + + settings.callback = callback; + settings.buttons = MessageBox.OK_CANCEL; + + return MessageBox.msgBox(settings); + } + } + }); + + return MessageBox; +}); + +// Included from: js/tinymce/classes/WindowManager.js + +/** + * WindowManager.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class handles the creation of native windows and dialogs. This class can be extended to provide for example inline dialogs. + * + * @class tinymce.WindowManager + * @example + * // Opens a new dialog with the file.htm file and the size 320x240 + * // It also adds a custom parameter this can be retrieved by using tinyMCEPopup.getWindowArg inside the dialog. + * tinymce.activeEditor.windowManager.open({ + * url: 'file.htm', + * width: 320, + * height: 240 + * }, { + * custom_param: 1 + * }); + * + * // Displays an alert box using the active editors window manager instance + * tinymce.activeEditor.windowManager.alert('Hello world!'); + * + * // Displays an confirm box and an alert message will be displayed depending on what you choose in the confirm + * tinymce.activeEditor.windowManager.confirm("Do you want to do something", function(s) { + * if (s) + * tinymce.activeEditor.windowManager.alert("Ok"); + * else + * tinymce.activeEditor.windowManager.alert("Cancel"); + * }); + */ +define("tinymce/WindowManager", [ + "tinymce/ui/Window", + "tinymce/ui/MessageBox" +], function(Window, MessageBox) { + return function(editor) { + var self = this, windows = []; + + self.windows = windows; + + /** + * Opens a new window. + * + * @method open + * @param {Object} args Optional name/value settings collection contains things like width/height/url etc. + * @option {String} title Window title. + * @option {String} file URL of the file to open in the window. + * @option {Number} width Width in pixels. + * @option {Number} height Height in pixels. + * @option {Boolean} resizable Specifies whether the popup window is resizable or not. + * @option {Boolean} maximizable Specifies whether the popup window has a "maximize" button and can get maximized or not. + * @option {String/bool} scrollbars Specifies whether the popup window can have scrollbars if required (i.e. content + * larger than the popup size specified). + */ + self.open = function(args) { + var win; + + // Handle URL + args.url = args.url || args.file; // Legacy + if (args.url) { + args.width = parseInt(args.width || 320, 10); + args.height = parseInt(args.height || 240, 10); + } + + // Handle body + if (args.body) { + args.items = { + defaults: args.defaults, + type: args.bodyType || 'form', + items: args.body + }; + } + + if (!args.url && !args.buttons) { + args.buttons = [ + {text: 'Ok', subtype: 'primary', minWidth: 50, onclick: function() { + win.find('form')[0].submit(); + win.close(); + }}, + + {text: 'Cancel', onclick: function() { + win.close(); + }} + ]; + } + + win = new Window(args); + windows.push(win); + + win.on('close', function() { + var i = windows.length; + + while (i--) { + if (windows[i] === win) { + windows.splice(i, 1); + } + } + + editor.focus(); + }); + + // Handle data + if (args.data) { + win.on('postRender', function() { + this.find('*').each(function(ctrl) { + var name = ctrl.name(); + + if (name in args.data) { + ctrl.value(args.data[name]); + } + }); + }); + } + + return win.renderTo(document.body).reflow(); + }; + + /** + * Creates a alert dialog. Please don't use the blocking behavior of this + * native version use the callback method instead then it can be extended. + * + * @method alert + * @param {String} message Text to display in the new alert dialog. + * @param {function} callback Callback function to be executed after the user has selected ok. + * @param {Object} scope Optional scope to execute the callback in. + * @example + * // Displays an alert box using the active editors window manager instance + * tinymce.activeEditor.windowManager.alert('Hello world!'); + */ + self.alert = function(message, callback, scope) { + MessageBox.alert(message, function() { + callback.call(scope || this); + }); + }; + + /** + * Creates a confirm dialog. Please don't use the blocking behavior of this + * native version use the callback method instead then it can be extended. + * + * @method confirm + * @param {String} messageText to display in the new confirm dialog. + * @param {function} callback Callback function to be executed after the user has selected ok or cancel. + * @param {Object} scope Optional scope to execute the callback in. + * @example + * // Displays an confirm box and an alert message will be displayed depending on what you choose in the confirm + * tinymce.activeEditor.windowManager.confirm("Do you want to do something", function(s) { + * if (s) + * tinymce.activeEditor.windowManager.alert("Ok"); + * else + * tinymce.activeEditor.windowManager.alert("Cancel"); + * }); + */ + self.confirm = function(message, callback, scope) { + MessageBox.confirm(message, function(state) { + callback.call(scope || this, state); + }); + }; + + /** + * Closes the top most window. + * + * @method close + */ + self.close = function() { + if (windows.length) { + windows[window.length - 1].win.close(); + } + }; + }; +}); + +// Included from: js/tinymce/classes/util/Quirks.js + +/** + * Quirks.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This file includes fixes for various browser quirks it's made to make it easy to add/remove browser specific fixes. + * + * @class tinymce.util.Quirks + * @private + */ +define("tinymce/util/Quirks", [ + "tinymce/util/VK", + "tinymce/dom/RangeUtils", + "tinymce/html/Node", + "tinymce/html/Entities", + "tinymce/Env", + "tinymce/util/Tools" +], function(VK, RangeUtils, Node, Entities, Env, Tools) { + return function(editor) { + var each = Tools.each; + var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, + settings = editor.settings, parser = editor.parser, serializer = editor.serializer; + var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit; + + /** + * Executes a command with a specific state this can be to enable/disable browser editing features. + */ + function setEditorCommandState(cmd, state) { + try { + editor.getDoc().execCommand(cmd, false, state); + } catch (ex) { + // Ignore + } + } + + /** + * Returns current IE document mode. + */ + function getDocumentMode() { + var documentMode = editor.getDoc().documentMode; + + return documentMode ? documentMode : 6; + } + + /** + * Returns true/false if the event is prevented or not. + * + * @param {Event} e Event object. + * @return {Boolean} true/false if the event is prevented or not. + */ + function isDefaultPrevented(e) { + return e.isDefaultPrevented(); + } + + /** + * Fixes a WebKit bug when deleting contents using backspace or delete key. + * WebKit will produce a span element if you delete across two block elements. + * + * Example: + *

    a

    |b

    + * + * Will produce this on backspace: + *

    ab

    + * + * This fixes the backspace to produce: + *

    a|b

    + * + * See bug: https://bugs.webkit.org/show_bug.cgi?id=45784 + * + * This code is a bit of a hack and hopefully it will be fixed soon in WebKit. + */ + function cleanupStylesWhenDeleting() { + function removeMergedFormatSpans(isDelete) { + var rng, blockElm, wrapperElm, bookmark, container, offset, elm; + + function isAtStartOrEndOfElm() { + if (container.nodeType == 3) { + if (isDelete && offset == container.length) { + return true; + } + + if (!isDelete && offset === 0) { + return true; + } + } + } + + rng = selection.getRng(); + var tmpRng = [rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset]; + + if (!rng.collapsed) { + isDelete = true; + } + + container = rng[(isDelete ? 'start' : 'end') + 'Container']; + offset = rng[(isDelete ? 'start' : 'end') + 'Offset']; + + if (container.nodeType == 3) { + 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); + } + + if (blockElm && (isAtStartOrEndOfElm() || !rng.collapsed)) { + // Wrap children of block in a EM and let WebKit stick is + // runtime styles junk into that EM + wrapperElm = dom.create('em', {'id': '__mceDel'}); + + each(Tools.grep(blockElm.childNodes), function(node) { + wrapperElm.appendChild(node); + }); + + blockElm.appendChild(wrapperElm); + } + } + + // Do the backspace/delete action + rng = dom.createRng(); + rng.setStart(tmpRng[0], tmpRng[1]); + rng.setEnd(tmpRng[2], tmpRng[3]); + selection.setRng(rng); + editor.getDoc().execCommand(isDelete ? 'ForwardDelete' : 'Delete', false, null); + + // Remove temp wrapper element + if (wrapperElm) { + bookmark = selection.getBookmark(); + + while ((elm = dom.get('__mceDel'))) { + dom.remove(elm, true); + } + + selection.moveToBookmark(bookmark); + } + } + + editor.on('keydown', function(e) { + var isDelete; + + isDelete = e.keyCode == DELETE; + if (!isDefaultPrevented(e) && (isDelete || e.keyCode == BACKSPACE) && !VK.modifierPressed(e)) { + e.preventDefault(); + removeMergedFormatSpans(isDelete); + } + }); + + editor.addCommand('Delete', function() {removeMergedFormatSpans();}); + } + + /** + * Makes sure that the editor body becomes empty when backspace or delete is pressed in empty editors. + * + * For example: + *

    |

    + * + * Or: + *

    |

    + * + * Or: + * [

    ] + */ + 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.on('keydown', function(e) { + var keyCode = e.keyCode, isCollapsed; + + // Empty the editor if it's needed for example backspace at

    |

    + if (!isDefaultPrevented(e) && (keyCode == DELETE || keyCode == BACKSPACE)) { + isCollapsed = editor.selection.isCollapsed(); + + // Selection is collapsed but the editor isn't empty + if (isCollapsed && !dom.isEmpty(editor.getBody())) { + return; + } + + // IE deletes all contents correctly when everything is selected + if (isIE && !isCollapsed) { + return; + } + + // Selection isn't collapsed but not all the contents is selected + if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) { + return; + } + + // Manually empty the editor + e.preventDefault(); + editor.setContent(''); + editor.selection.setCursorLocation(editor.getBody(), 0); + editor.nodeChanged(); + } + }); + } + + /** + * WebKit doesn't select all the nodes in the body when you press Ctrl+A. + * This selects the whole body so that backspace/delete logic will delete everything + */ + function selectAll() { + editor.on('keydown', function(e) { + if (!isDefaultPrevented(e) && e.keyCode == 65 && VK.metaKeyPressed(e)) { + e.preventDefault(); + editor.execCommand('SelectAll'); + } + }); + } + + /** + * WebKit has a weird issue where it some times fails to properly convert keypresses to input method keystrokes. + * The IME on Mac doesn't initialize when it doesn't fire a proper focus event. + * + * This seems to happen when the user manages to click the documentElement element then the window doesn't get proper focus until + * you enter a character into the editor. + * + * It also happens when the first focus in made to the body. + * + * See: https://bugs.webkit.org/show_bug.cgi?id=83566 + */ + function inputMethodFocus() { + if (!editor.settings.content_editable) { + // Case 1 IME doesn't initialize if you focus the document + dom.bind(editor.getDoc(), 'focusin', function() { + selection.setRng(selection.getRng()); + }); + + // Case 2 IME doesn't initialize if you click the documentElement it also doesn't properly fire the focusin event + dom.bind(editor.getDoc(), 'mousedown', function(e) { + if (e.target == editor.getDoc().documentElement) { + editor.getWin().focus(); + selection.setRng(selection.getRng()); + } + }); + } + } + + /** + * Backspacing in FireFox/IE from a paragraph into a horizontal rule results in a floating text node because the + * browser just deletes the paragraph - the browser fails to merge the text node with a horizontal rule so it is + * left there. TinyMCE sees a floating text node and wraps it in a paragraph on the key up event (ForceBlocks.js + * addRootBlocks), meaning the action does nothing. With this code, FireFox/IE matche the behaviour of other + * browsers + */ + function removeHrOnBackspace() { + editor.on('keydown', function(e) { + if (!isDefaultPrevented(e) && 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); + e.preventDefault(); + } + } + } + }); + } + + /** + * Firefox 3.x has an issue where the body element won't get proper focus if you click out + * side it's rectangle. + */ + 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 (!window.Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4 + editor.on('mousedown', function(e) { + if (!isDefaultPrevented(e) && 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); + } + }); + } + } + + /** + * WebKit has a bug where it isn't possible to select image, hr or anchor elements + * by clicking on them so we need to fake that. + */ + function selectControlElements() { + editor.on('click', function(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(); + }); + } + + /** + * Fixes a Gecko bug where the style attribute gets added to the wrong element when deleting between two block elements. + * + * Fixes do backspace/delete on this: + *

    bla[ck

    r]ed

    + * + * Would become: + *

    bla|ed

    + * + * Instead of: + *

    bla|ed

    + */ + 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); + + each(template, function(attr) { + target.setAttributeNode(attr.cloneNode(true)); + }); + } + }; + } + + function isSelectionAcrossElements() { + return !selection.isCollapsed() && + dom.getParent(selection.getStart(), dom.isBlock) != dom.getParent(selection.getEnd(), dom.isBlock); + } + + editor.on('keypress', function(e) { + var applyAttributes; + + if (!isDefaultPrevented(e) && (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 (!isDefaultPrevented(e) && isSelectionAcrossElements()) { + applyAttributes = getAttributeApplyFunction(); + + setTimeout(function() { + applyAttributes(); + }, 0); + } + }); + } + + /** + * Fire a nodeChanged when the selection is changed on WebKit this fixes selection issues on iOS5. It only fires the nodeChange + * event every 50ms since it would other wise update the UI when you type and it hogs the CPU. + */ + function selectionChangeNodeChanged() { + var lastRng, selectionTimer; + + editor.on('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 || !RangeUtils.compareRanges(rng, lastRng)) { + editor.nodeChanged(); + lastRng = rng; + } + }, 50); + }); + } + + /** + * Screen readers on IE needs to have the role application set on the body. + */ + function ensureBodyHasRoleApplication() { + document.body.setAttribute("role", "application"); + } + + /** + * Backspacing into a table behaves differently depending upon browser type. + * Therefore, disable Backspace when cursor immediately follows a table. + */ + function disableBackspaceIntoATable() { + editor.on('keydown', function(e) { + if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { + if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { + var previousSibling = selection.getNode().previousSibling; + if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") { + e.preventDefault(); + return false; + } + } + } + }); + } + + /** + * Old IE versions can't properly render BR elements in PRE tags white in contentEditable mode. So this + * logic adds a \n before the BR so that it will get rendered. + */ + function addNewLinesBeforeBrInPre() { + // IE8+ rendering mode does the right thing with BR in PRE + if (getDocumentMode() > 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); + editor.contentStyles.push('.mceHideBrInPre pre br {display: none}'); + dom.addClass(editor.getBody(), 'mceHideBrInPre'); + + // Adds a \n before all BR elements in PRE to get them visual + parser.addNodeFilter('pre', function(nodes) { + 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 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 + serializer.addNodeFilter('pre', function(nodes) { + 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$/, ''); + } + } + } + }); + } + + /** + * Moves style width/height to attribute width/height when the user resizes an image on IE. + */ + function removePreSerializedStylesWhenSelectingControls() { + dom.bind(editor.getBody(), 'mouseup', function() { + 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', ''); + } + } + }); + } + + /** + * Backspace or delete on WebKit will combine all visual styles in a span if the last character is deleted. + * + * For example backspace on: + *

    x|

    + * + * Will produce: + *

    |

    + * + * When it should produce: + *

    |

    + * + * See: https://bugs.webkit.org/show_bug.cgi?id=81656 + */ + function keepInlineElementOnDeleteBackspace() { + editor.on('keydown', function(e) { + var isDelete, rng, container, offset, brElm, sibling, collapsed, nonEmptyElements; + + isDelete = e.keyCode == DELETE; + if (!isDefaultPrevented(e) && (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)))) { + // Edge case when deleting

    |x

    + sibling = container.previousSibling; + if (sibling && sibling.nodeName == "IMG") { + return; + } + + 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:

    |

    + 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'); + } + } + }); + } + + /** + * Removes a blockquote when backspace is pressed at the beginning of it. + * + * For example: + *

    |x

    + * + * Becomes: + *

    |x

    + */ + function removeBlockQuoteOnBackSpace() { + // Add block quote deletion handler + editor.on('keydown', function(e) { + var rng, container, offset, root, parent; + + if (isDefaultPrevented(e) || 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 && 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 = dom.createRng(); + rng.setStart(container, 0); + rng.setEnd(container, 0); + selection.setRng(rng); + } + }); + } + + /** + * Sets various Gecko editing options on mouse down and before a execCommand to disable inline table editing that is broken etc. + */ + function setGeckoEditingOptions() { + function setOpts() { + editor._refreshContentEditable(); + + setEditorCommandState("StyleWithCSS", false); + setEditorCommandState("enableInlineTableEditing", false); + + if (!settings.object_resizing) { + setEditorCommandState("enableObjectResizing", false); + } + } + + if (!settings.readonly) { + editor.on('BeforeExecCommand MouseDown', setOpts); + } + } + + /** + * Fixes a gecko link bug, when a link is placed at the end of block elements there is + * no way to move the caret behind the link. This fix adds a bogus br element after the link. + * + * For example this: + *

    x

    + * + * Becomes this: + *

    x

    + */ + function addBrAfterLastLinks() { + function fixLinks() { + 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.on('SetContent ExecCommand', function(e) { + if (e.type == "setcontent" || e.command === 'mceInsertLink') { + fixLinks(); + } + }); + } + + /** + * WebKit will produce DIV elements here and there by default. But since TinyMCE uses paragraphs by + * default we want to change that behavior. + */ + function setDefaultBlockType() { + if (settings.forced_root_block) { + editor.on('init', function() { + setEditorCommandState('DefaultParagraphSeparator', settings.forced_root_block); + }); + } + } + + /** + * Removes ghost selections from images/tables on Gecko. + */ + function removeGhostSelection() { + editor.on('Undo Redo SetContent', function(e) { + if (!e.initial) { + editor.execCommand('mceRepaint'); + } + }); + } + + /** + * Deletes the selected image on IE instead of navigating to previous page. + */ + function deleteControlItemOnBackSpace() { + editor.on('keydown', function(e) { + var rng; + + if (!isDefaultPrevented(e) && e.keyCode == BACKSPACE) { + rng = editor.getDoc().selection.createRange(); + if (rng && rng.item) { + e.preventDefault(); + editor.undoManager.beforeChange(); + dom.remove(rng.item(0)); + editor.undoManager.add(); + } + } + }); + } + + /** + * IE10 doesn't properly render block elements with the right height until you add contents to them. + * This fixes that by adding a padding-right to all empty text block elements. + * See: https://connect.microsoft.com/IE/feedback/details/743881 + */ + function renderEmptyBlocksFix() { + var emptyBlocksCSS; + + // IE10+ + if (getDocumentMode() >= 10) { + emptyBlocksCSS = ''; + each('p div h1 h2 h3 h4 h5 h6'.split(' '), function(name, i) { + emptyBlocksCSS += (i > 0 ? ',' : '') + name + ':empty'; + }); + + editor.contentStyles.push(emptyBlocksCSS + '{padding-right: 1px !important}'); + } + } + + /** + * Old IE versions can't retain contents within noscript elements so this logic will store the contents + * as a attribute and the insert that value as it's raw text when the DOM is serialized. + */ + function keepNoScriptContents() { + if (getDocumentMode() < 9) { + parser.addNodeFilter('noscript', function(nodes) { + var i = nodes.length, node, textNode; + + while (i--) { + node = nodes[i]; + textNode = node.firstChild; + + if (textNode) { + node.attr('data-mce-innertext', textNode.value); + } + } + }); + + serializer.addNodeFilter('noscript', function(nodes) { + var i = nodes.length, node, textNode, value; + + while (i--) { + node = nodes[i]; + textNode = nodes[i].firstChild; + + if (textNode) { + textNode.value = Entities.decode(textNode.value); + } else { + // Old IE can't retain noscript value so an attribute is used to store it + value = node.attributes.map['data-mce-innertext']; + if (value) { + node.attr('data-mce-innertext', null); + textNode = new Node('#text', 3); + textNode.value = value; + textNode.raw = true; + node.append(textNode); + } + } + } + }); + } + } + + /** + * IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode. + */ + function fixCaretSelectionOfDocumentElementOnIe() { + var 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(); + } + } + }); + } + + /** + * Fixes selection issues on Gecko where the caret can be placed between two inline elements like a|b + * this fix will lean the caret right into the closest inline element. + */ + function normalizeSelection() { + // Normalize selection for example a|a becomes a|a except for Ctrl+A since it selects everything + editor.on('keyup focusin', function(e) { + if (e.keyCode != 65 || !VK.metaKeyPressed(e)) { + selection.normalize(); + } + }); + } + + // All browsers + disableBackspaceIntoATable(); + removeBlockQuoteOnBackSpace(); + emptyEditorWhenDeleting(); + normalizeSelection(); + + // WebKit + if (isWebKit) { + keepInlineElementOnDeleteBackspace(); + cleanupStylesWhenDeleting(); + inputMethodFocus(); + selectControlElements(); + setDefaultBlockType(); + + // iOS + if (Env.iOS) { + selectionChangeNodeChanged(); + } else { + selectAll(); + } + } + + // IE + if (isIE) { + removeHrOnBackspace(); + ensureBodyHasRoleApplication(); + addNewLinesBeforeBrInPre(); + removePreSerializedStylesWhenSelectingControls(); + deleteControlItemOnBackSpace(); + renderEmptyBlocksFix(); + keepNoScriptContents(); + fixCaretSelectionOfDocumentElementOnIe(); + } + + // Gecko + if (isGecko) { + removeHrOnBackspace(); + focusBody(); + removeStylesWhenDeletingAccrossBlockElements(); + setGeckoEditingOptions(); + addBrAfterLastLinks(); + removeGhostSelection(); + } + }; +}); + +// Included from: js/tinymce/classes/util/Observable.js + +/** + * Observable.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/util/Observable", [ + "tinymce/util/Tools" +], function(Tools) { + var bindingsName = "__bindings"; + var nativeEvents = Tools.makeMap( + "focusin focusout click dblclick mousedown mouseup mousemove mouseover beforepaste paste cut copy" + + " mouseout mouseenter mouseleave keydown keypress keyup contextmenu dragend dragover draggesture dragdrop drop drag", ' ' + ); + + function returnFalse() { + return false; + } + + function returnTrue() { + return true; + } + + return { + fire: function(name, args, bubble) { + var self = this, handlers, i, l, callback, parent; + + name = name.toLowerCase(); + args = args || {}; + args.type = name; + + // Setup target is there isn't one + if (!args.target) { + args.target = self; + } + + // Add event delegation methods if they are missing + if (!args.preventDefault) { + // Add preventDefault method + args.preventDefault = function() { + args.isDefaultPrevented = returnTrue; + }; + + // Add stopPropagation + args.stopPropagation = function() { + args.isPropagationStopped = returnTrue; + }; + + // Add stopImmediatePropagation + args.stopImmediatePropagation = function() { + args.isImmediatePropagationStopped = returnTrue; + }; + + // Add event delegation states + args.isDefaultPrevented = returnFalse; + args.isPropagationStopped = returnFalse; + args.isImmediatePropagationStopped = returnFalse; + } + + //console.log(name, args); + + if (self[bindingsName]) { + handlers = self[bindingsName][name]; + + if (handlers) { + for (i = 0, l = handlers.length; i < l; i++) { + handlers[i] = callback = handlers[i]; + + // Stop immediate propagation if needed + if (args.isImmediatePropagationStopped()) { + break; + } + + // If callback returns false then prevent default and stop all propagation + if (callback.call(self, args) === false) { + args.preventDefault(); + return args; + } + } + } + } + + // Bubble event up to parents + if (bubble !== false && self.parent) { + parent = self.parent(); + while (parent && !args.isPropagationStopped()) { + parent.fire(name, args, false); + parent = parent.parent(); + } + } + + return args; + }, + + on: function(name, callback) { + var self = this, bindings, handlers, names, i; + + if (callback === false) { + callback = function() { + return false; + }; + } + + if (callback) { + names = name.toLowerCase().split(' '); + i = names.length; + while (i--) { + name = names[i]; + + bindings = self[bindingsName]; + if (!bindings) { + bindings = self[bindingsName] = {}; + } + + handlers = bindings[name]; + if (!handlers) { + handlers = bindings[name] = []; + if (self.bindNative && nativeEvents[name]) { + self.bindNative(name); + } + } + + handlers.push(callback); + } + } + + return self; + }, + + off: function(name, callback) { + var self = this, i, bindings = self[bindingsName], handlers, bindingName, names, hi; + + if (bindings) { + if (name) { + names = name.toLowerCase().split(' '); + i = names.length; + while (i--) { + name = names[i]; + handlers = bindings[name]; + + // Unbind all handlers + if (!name) { + for (bindingName in bindings) { + bindings[name].length = 0; + } + + return self; + } + + if (handlers) { + // Unbind all by name + if (!callback) { + handlers.length = 0; + } else { + // Unbind specific ones + hi = handlers.length; + while (hi--) { + if (handlers[hi] === callback) { + handlers.splice(hi, 1); + } + } + } + + if (!handlers.length && self.unbindNative && nativeEvents[name]) { + self.unbindNative(name); + delete bindings[name]; + } + } + } + } else { + if (self.unbindNative) { + for (name in bindings) { + self.unbindNative(name); + } + } + + self[bindingsName] = []; + } + } + + return self; + } + }; +}); + +// Included from: js/tinymce/classes/Shortcuts.js + +/** + * Shortcuts.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Contains all logic for handling of keyboard shortcuts. + */ +define("tinymce/Shortcuts", [ + "tinymce/util/Tools", + "tinymce/Env" +], function(Tools, Env) { + var each = Tools.each, explode = Tools.explode; + + var keyCodeLookup = { + "f9": 120, + "f10": 121, + "f11": 122 + }; + + return function(editor) { + var self = this, shortcuts = {}; + + editor.on('keyup keypress keydown', function(e) { + if (e.altKey || e.ctrlKey || e.metaKey) { + each(shortcuts, function(shortcut) { + var ctrlState = Env.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 (e.type == "keydown") { + shortcut.func.call(shortcut.scope); + } + + return true; + } + }); + } + }); + + /** + * Adds a keyboard shortcut for some command or function. + * + * @method addShortcut + * @param {String} pattern Shortcut pattern. Like for example: ctrl+alt+o. + * @param {String} desc Text description for the command. + * @param {String/Function} cmdFunc Command name string or function to execute when the key is pressed. + * @param {Object} sc Optional scope to execute the function in. + * @return {Boolean} true/false state if the shortcut was added or not. + */ + self.add = function(pattern, desc, cmdFunc, scope) { + var cmd; + + cmd = cmdFunc; + + if (typeof(cmdFunc) === 'string') { + cmdFunc = function() { + editor.execCommand(cmd, false, null); + }; + } else if (cmdFunc.length) { + cmdFunc = function() { + editor.execCommand(cmd[0], cmd[1], cmd[2]); + }; + } + + each(explode(pattern.toLowerCase()), function(pattern) { + var shortcut = { + func: cmdFunc, + scope: scope || editor, + desc: editor.translate(desc), + alt: false, + ctrl: false, + shift: false + }; + + each(explode(pattern, '+'), function(value) { + switch (value) { + case 'alt': + case 'ctrl': + case 'shift': + shortcut[value] = true; + break; + + default: + shortcut.charCode = value.charCodeAt(0); + shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0); + } + }); + + shortcuts[ + (shortcut.ctrl ? 'ctrl' : '') + ',' + + (shortcut.alt ? 'alt' : '') + ',' + + (shortcut.shift ? 'shift' : '') + ',' + + shortcut.keyCode + ] = shortcut; + }); + + return true; + }; + }; +}); + +// Included from: js/tinymce/classes/Editor.js + +/** + * Editor.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/*jshint scripturl:true */ + +/** + * This class contains the core logic for a TinyMCE editor. + * + * @class tinymce.Editor + * @example + * // Add a class to all paragraphs in the editor. + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass'); + * + * // Gets the current editors selection as text + * tinymce.activeEditor.selection.getContent({format: 'text'}); + * + * // Creates a new editor instance + * var ed = new tinymce.Editor('textareaid', { + * some_setting: 1 + * }, tinymce.EditorManager); + * + * // Select each item the user clicks on + * ed.on('click', function(e) { + * ed.selection.select(e.target); + * }); + * + * ed.render(); + */ +define("tinymce/Editor", [ + "tinymce/dom/DOMUtils", + "tinymce/AddOnManager", + "tinymce/html/Node", + "tinymce/dom/Serializer", + "tinymce/html/Serializer", + "tinymce/dom/Selection", + "tinymce/Formatter", + "tinymce/UndoManager", + "tinymce/EnterKey", + "tinymce/ForceBlocks", + "tinymce/EditorCommands", + "tinymce/util/URI", + "tinymce/dom/ScriptLoader", + "tinymce/dom/EventUtils", + "tinymce/WindowManager", + "tinymce/html/Schema", + "tinymce/html/DomParser", + "tinymce/util/Quirks", + "tinymce/Env", + "tinymce/util/Tools", + "tinymce/util/Observable", + "tinymce/Shortcuts" +], function( + DOMUtils, AddOnManager, Node, DomSerializer, Serializer, + Selection, Formatter, UndoManager, EnterKey, ForceBlocks, EditorCommands, + URI, ScriptLoader, EventUtils, WindowManager, + Schema, DomParser, Quirks, Env, Tools, Observable, Shortcuts +) { + // Shorten these names + var DOM = DOMUtils.DOM, ThemeManager = AddOnManager.ThemeManager, PluginManager = AddOnManager.PluginManager; + var extend = Tools.extend, each = Tools.each, explode = Tools.explode; + var inArray = Tools.inArray, trim = Tools.trim, resolve = Tools.resolve; + var Event = EventUtils.Event; + var isGecko = Env.gecko, isIE = Env.ie, isOpera = Env.opera; + + function getEventTarget(editor, eventName) { + // Need to bind mousedown/mouseup etc to document not body in iframe mode + // Since the user might click on the HTML element not the BODY + if (!editor.inline && /^mouse|click|contextmenu/.test(eventName)) { + return editor.getDoc(); + } + + return editor.getBody(); + } + + /** + * Constructs a editor instance by id. + * + * @constructor + * @method Editor + * @param {String} id Unique id for the editor. + * @param {Object} settings Settings for the editor. + * @param {tinymce.EditorManager} editorManager EditorManager instance. + * @author Moxiecode + */ + function Editor(id, settings, editorManager) { + var self = this, documentBaseUrl, baseUri; + + documentBaseUrl = self.documentBaseUrl = editorManager.documentBaseURL; + baseUri = editorManager.baseURI; + + /** + * Name/value collection with editor settings. + * + * @property settings + * @type Object + * @example + * // Get the value of the theme setting + * tinymce.activeEditor.windowManager.alert("You are using the " + tinymce.activeEditor.settings.theme + " theme"); + */ + self.settings = settings = extend({ + id: id, + theme: 'modern', + delta_width: 0, + delta_height: 0, + popup_css: '', + plugins: '', + document_base_url: 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, + doctype: '', + visual: true, + font_size_style_values: 'xx-small,x-small,small,medium,large,x-large,xx-large', + + // See: http://www.w3.org/TR/CSS2/fonts.html#propdef-font-size + font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%', + apply_source_formatting: true, + directionality: 'ltr', + forced_root_block: 'p', + hidden_input: true, + padd_empty_editor: true, + render_ui: true, + indentation: '30px', + 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,option,optgroup,datalist', + 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,option,optgroup,datalist', + validate: true, + entity_encoding: 'named', + url_converter: self.convertURL, + url_converter_scope: self, + ie7_compat: true + }, settings); + + // TODO: Fix this + AddOnManager.settings = settings; + AddOnManager.baseURL = editorManager.baseURL; + + /** + * Editor instance id, normally the same as the div/textarea that was replaced. + * + * @property id + * @type String + */ + self.id = settings.id = id; + + /** + * State to force the editor to return false on a isDirty call. + * + * @property isNotDirty + * @type Boolean + * @example + * function ajaxSave() { + * var ed = tinymce.get('elm1'); + * + * // Save contents using some XHR call + * alert(ed.getContent()); + * + * ed.isNotDirty = 1; // Force not dirty state + * } + */ + self.isNotDirty = false; + + /** + * Name/Value object containting plugin instances. + * + * @property plugins + * @type Object + * @example + * // Execute a method inside a plugin directly + * tinymce.activeEditor.plugins.someplugin.someMethod(); + */ + self.plugins = {}; + + /** + * URI object to document configured for the TinyMCE instance. + * + * @property documentBaseURI + * @type tinymce.util.URI + * @example + * // Get relative URL from the location of document_base_url + * tinymce.activeEditor.documentBaseURI.toRelative('/somedir/somefile.htm'); + * + * // Get absolute URL from the location of document_base_url + * tinymce.activeEditor.documentBaseURI.toAbsolute('somefile.htm'); + */ + self.documentBaseURI = new URI(settings.document_base_url || documentBaseUrl, { + base_uri: baseUri + }); + + /** + * URI object to current document that holds the TinyMCE editor instance. + * + * @property baseURI + * @type tinymce.util.URI + * @example + * // Get relative URL from the location of the API + * tinymce.activeEditor.baseURI.toRelative('/somedir/somefile.htm'); + * + * // Get absolute URL from the location of the API + * tinymce.activeEditor.baseURI.toAbsolute('somefile.htm'); + */ + self.baseURI = baseUri; + + /** + * Array with CSS files to load into the iframe. + * + * @property contentCSS + * @type Array + */ + self.contentCSS = []; + + /** + * Array of CSS styles to add to head of document when the editor loads. + * + * @property contentStyles + * @type Array + */ + self.contentStyles = []; + + // Creates all events like onClick, onSetContent etc see Editor.Events.js for the actual logic + self.shortcuts = new Shortcuts(self); + + // Internal command handler objects + self.execCommands = {}; + self.queryStateCommands = {}; + self.queryValueCommands = {}; + + self.suffix = editorManager.suffix; + self.editorManager = editorManager; + self.inline = settings.inline; + + // Call setup + self.execCallback('setup', self); + } + + Editor.prototype = { + /** + * Renderes the editor/adds it to the page. + * + * @method render + */ + render: function() { + var self = this, settings = self.settings, id = self.id, suffix = self.suffix; + + // Page is not loaded yet, wait for it + if (!Event.domLoaded) { + DOM.bind(window, 'ready', function() { + self.render(); + }); + return; + } + + self.editorManager.settings = settings; + + // Element not found, then skip initialization + if (!self.getElement()) { + return; + } + + // No editable support old iOS versions etc + if (!Env.contentEditable) { + return; + } + + // Hide target element early to prevent content flashing + if (!settings.inline) { + self.orgVisibility = self.getElement().style.visibility; + self.getElement().style.visibility = 'hidden'; + } else { + self.inline = true; + } + + var form = self.getElement().form || DOM.getParent(id, 'form'); + if (form) { + self.formElement = form; + + // Add hidden input for non input elements inside form elements + if (settings.hidden_input && !/TEXTAREA|INPUT/i.test(self.getElement().nodeName)) { + DOM.insertAfter(DOM.create('input', {type: 'hidden', name: id}), id); + } + + // Pass submit/reset from form to editor instance + self.formEventDelegate = function(e) { + self.fire(e.type, e); + }; + + DOM.bind(form, 'submit reset', self.formEventDelegate); + + // Reset contents in editor when the form is reset + self.on('reset', function() { + self.setContent(self.startContent, {format: 'raw'}); + }); + + // Check page uses id="submit" or name="submit" for it's submit button + if (settings.submit_patch && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) { + form._mceOldSubmit = form.submit; + form.submit = function() { + self.editorManager.triggerSave(); + self.isNotDirty = 1; + + return form._mceOldSubmit(form); + }; + } + } + + /** + * Window manager reference, use this to open new windows and dialogs. + * + * @property windowManager + * @type tinymce.WindowManager + * @example + * // Shows an alert message + * tinymce.activeEditor.windowManager.alert('Hello world!'); + * + * // Opens a new dialog with the file.htm file and the size 320x240 + * // It also adds a custom parameter this can be retrieved by using tinyMCEPopup.getWindowArg inside the dialog. + * tinymce.activeEditor.windowManager.open({ + * url: 'file.htm', + * width: 320, + * height: 240 + * }, { + * custom_param: 1 + * }); + */ + self.windowManager = new WindowManager(self); + + if (settings.encoding == 'xml') { + self.on('GetContent', function(e) { + if (e.save) { + e.content = DOM.encode(e.content); + } + }); + } + + if (settings.add_form_submit_trigger) { + self.on('submit', function() { + if (self.initialized) { + self.save(); + self.isNotDirty = 1; + } + }); + } + + if (settings.add_unload_trigger) { + self._beforeUnload = function() { + if (self.initialized && !self.destroyed && !self.isHidden()) { + self.save({format: 'raw', no_events: true}); + } + }; + + self.editorManager.on('BeforeUnload', self._beforeUnload); + } + + // Load scripts + function loadScripts() { + var scriptLoader = ScriptLoader.ScriptLoader; + + if (settings.language) { + scriptLoader.add(self.editorManager.baseURL + '/langs/' + settings.language + '.js'); + } + + if (settings.theme && typeof settings.theme != "function" && + settings.theme.charAt(0) != '-' && !ThemeManager.urls[settings.theme]) { + ThemeManager.load(settings.theme, 'themes/' + settings.theme + '/theme' + suffix + '.js'); + } + + if (Tools.isArray(settings.plugins)) { + settings.plugins = settings.plugins.join(' '); + } + + each(settings.plugins.split(/[ ,]/), function(plugin) { + plugin = trim(plugin); + + if (plugin && !PluginManager.urls[plugin]) { + if (plugin.charAt(0) == '-') { + plugin = plugin.substr(1, plugin.length); + + var dependencies = PluginManager.dependencies(plugin); + + each(dependencies, function(dep) { + var defaultSettings = { + prefix:'plugins/', + resource: dep, + suffix:'/plugin' + suffix + '.js' + }; + + dep = PluginManager.createUrl(defaultSettings, dep); + PluginManager.load(dep.resource, dep); + }); + } else { + PluginManager.load(plugin, { + prefix: 'plugins/', + resource: plugin, + suffix: '/plugin' + suffix + '.js' + }); + } + } + }); + + scriptLoader.loadQueue(function() { + if (!self.removed) { + self.init(); + } + }); + } + + loadScripts(); + }, + + /** + * Initializes the editor this will be called automatically when + * all plugins/themes and language packs are loaded by the rendered method. + * This method will setup the iframe and create the theme and plugin instances. + * + * @method init + */ + init: function() { + var self = this, settings = self.settings, elm = self.getElement(); + var w, h, minHeight, n, o, url, bodyId, bodyClass, re, i, initializedPlugins = []; + + self.editorManager.add(self); + + settings.aria_label = settings.aria_label || DOM.getAttrib(elm, 'aria-label', self.getLang('aria.rich_text_area')); + + /** + * Reference to the theme instance that was used to generate the UI. + * + * @property theme + * @type tinymce.Theme + * @example + * // Executes a method on the theme directly + * tinymce.activeEditor.theme.someMethod(); + */ + if (settings.theme) { + if (typeof settings.theme != "function") { + settings.theme = settings.theme.replace(/-/, ''); + o = ThemeManager.get(settings.theme); + self.theme = new o(self, ThemeManager.urls[settings.theme]); + + if (self.theme.init) { + self.theme.init(self, ThemeManager.urls[settings.theme] || self.documentBaseUrl.replace(/\/$/, '')); + } + } else { + self.theme = settings.theme; + } + } + + function initPlugin(plugin) { + var constr = PluginManager.get(plugin), url, pluginInstance; + + url = PluginManager.urls[plugin] || self.documentBaseUrl.replace(/\/$/, ''); + plugin = trim(plugin); + if (constr && inArray(initializedPlugins, plugin) === -1) { + each(PluginManager.dependencies(plugin), function(dep){ + initPlugin(dep); + }); + + pluginInstance = new constr(self, url); + + self.plugins[plugin] = pluginInstance; + + if (pluginInstance.init) { + pluginInstance.init(self, url); + initializedPlugins.push(plugin); + } + } + } + + // Create all plugins + each(settings.plugins.replace(/\-/g, '').split(/[ ,]/), initPlugin); + + // Enables users to override the control factory + self.fire('BeforeRenderUI'); + + // Measure box + if (settings.render_ui && self.theme) { + self.orgDisplay = elm.style.display; + + if (typeof settings.theme != "function") { + w = settings.width || elm.style.width || elm.offsetWidth; + h = settings.height || elm.style.height || elm.offsetHeight; + minHeight = settings.min_height || 100; + 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), minHeight); + } + + // Render UI + o = self.theme.renderUI({ + targetNode: elm, + width: w, + height: h, + deltaWidth: settings.delta_width, + deltaHeight: settings.delta_height + }); + + // Resize editor + if (!settings.content_editable) { + DOM.setStyles(o.sizeContainer || o.editorContainer, { + wi2dth: w, + // TODO: Fix this + h2eight: h + }); + + h = (o.iframeHeight || h) + (typeof(h) == 'number' ? (o.deltaHeight || 0) : ''); + if (h < minHeight) { + h = minHeight; + } + } + } else { + o = settings.theme(self, elm); + + // Convert element type to id:s + if (o.editorContainer.nodeType) { + o.editorContainer = o.editorContainer.id = o.editorContainer.id || self.id + "_parent"; + } + + // Convert element type to id:s + if (o.iframeContainer.nodeType) { + o.iframeContainer = o.iframeContainer.id = o.iframeContainer.id || self.id + "_iframecontainer"; + } + + // Use specified iframe height or the targets offsetHeight + h = o.iframeHeight || elm.offsetHeight; + } + + self.editorContainer = o.editorContainer; + } + + // Load specified content CSS last + if (settings.content_css) { + each(explode(settings.content_css), function(u) { + self.contentCSS.push(self.documentBaseURI.toAbsolute(u)); + }); + } + + // Load specified content CSS last + if (settings.content_style) { + self.contentStyles.push(settings.content_style); + } + + // Content editable mode ends here + if (settings.content_editable) { + elm = n = o = null; // Fix IE leak + return self.initContentBody(); + } + + // User specified a document.domain value + if (document.domain && location.hostname != document.domain) { + self.editorManager.relaxedDomain = document.domain; + } + + self.iframeHTML = settings.doctype + ''; + + // 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 (settings.document_base_url != self.documentBaseUrl) { + self.iframeHTML += ''; + } + + // IE8 doesn't support carets behind images setting ie7_compat would force IE8+ to run in IE7 compat mode. + if (!Env.caretAfter && settings.ie7_compat) { + self.iframeHTML += ''; + } + + self.iframeHTML += ''; + + // Load the CSS by injecting them into the HTML this will reduce "flicker" + for (i = 0; i < self.contentCSS.length; i++) { + self.iframeHTML += ''; + } + + self.contentCSS = []; + + bodyId = settings.body_id || 'tinymce'; + if (bodyId.indexOf('=') != -1) { + bodyId = self.getParam('body_id', '', 'hash'); + bodyId = bodyId[self.id] || bodyId; + } + + bodyClass = settings.body_class || ''; + if (bodyClass.indexOf('=') != -1) { + bodyClass = self.getParam('body_class', '', 'hash'); + bodyClass = bodyClass[self.id] || ''; + } + + self.iframeHTML += '
    '; + + // Domain relaxing enabled, then set document domain + // TODO: Fix this old stuff + if (self.editorManager.relaxedDomain && (isIE || (isOpera && parseFloat(window.opera.version()) < 11))) { + // We need to write the contents here in IE since multiple writes messes up refresh button and back button + url = 'javascript:(function(){document.open();document.domain="' + document.domain + '";' + + 'var ed = window.parent.tinymce.get("' + self.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: self.id + "_ifr", + src: url || 'javascript:""', // Workaround for HTTPS warning in IE6/7 + frameBorder: '0', + allowTransparency: "true", + title: self.editorManager.translate( + "Rich Text Area. Press ALT-F9 for menu. " + + "Press ALT-F10 for toolbar. Press ALT-0 for help" + ), + style: { + width: '100%', + height: h, + display: 'block' // Important for Gecko to render the iframe correctly + } + }); + + self.contentAreaContainer = o.iframeContainer; + + if (o.editorContainer) { + DOM.get(o.editorContainer).style.display = self.orgDisplay; + } + + DOM.get(self.id).style.display = 'none'; + DOM.setAttrib(self.id, 'aria-hidden', true); + + if (!self.editorManager.relaxedDomain || !url) { + self.initContentBody(); + } + + elm = n = o = null; // Cleanup + }, + + /** + * This method get called by the init method ones the iframe is loaded. + * It will fill the iframe with contents, setups DOM and selection objects for the iframe. + * + * @method initContentBody + * @private + */ + initContentBody: function() { + var self = this, settings = self.settings, targetElm = DOM.get(self.id), doc = self.getDoc(), body, contentCssText; + + // Restore visibility on target element + self.getElement().style.visibility = self.orgVisibility; + + // Setup iframe body + if ((!isIE || !self.editorManager.relaxedDomain) && !settings.content_editable) { + doc.open(); + doc.write(self.iframeHTML); + doc.close(); + + if (self.editorManager.relaxedDomain) { + doc.domain = self.editorManager.relaxedDomain; + } + } + + if (settings.content_editable) { + DOM.addClass(targetElm, 'mce-content-body'); + targetElm.tabIndex = -1; + 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; + + // TODO: Fix this + settings.root_name = targetElm.nodeName.toLowerCase(); + } + + // 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; + + /** + * Schema instance, enables you to validate elements and it's children. + * + * @property schema + * @type tinymce.html.Schema + */ + self.schema = new Schema(settings); + + /** + * DOM instance for the editor. + * + * @property dom + * @type tinymce.dom.DOMUtils + * @example + * // Adds a class to all paragraphs within the editor + * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass'); + */ + self.dom = new 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, + onSetAttrib: function(e) { + self.fire('SetAttrib', e); + } + }); + + /** + * HTML parser will be used when contents is inserted into the editor. + * + * @property parser + * @type tinymce.html.DomParser + */ + self.parser = new 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) { + 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) { + 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) { + var i = nodes.length, node, nonEmptyElements = self.schema.getNonEmptyElements(); + + while (i--) { + node = nodes[i]; + + if (node.isEmpty(nonEmptyElements)) { + node.empty().append(new Node('br', 1)).shortEnded = true; + } + } + }); + + /** + * DOM serializer for the editor. Will be used when contents is extracted from the editor. + * + * @property serializer + * @type tinymce.dom.Serializer + * @example + * // Serializes the first paragraph in the editor into a string + * tinymce.activeEditor.serializer.serialize(tinymce.activeEditor.dom.select('p')[0]); + */ + self.serializer = new DomSerializer(settings, self); + + /** + * Selection instance for the editor. + * + * @property selection + * @type tinymce.dom.Selection + * @example + * // Sets some contents to the current selection in the editor + * tinymce.activeEditor.selection.setContent('Some contents'); + * + * // Gets the current selection + * alert(tinymce.activeEditor.selection.getContent()); + * + * // Selects the first paragraph found + * tinymce.activeEditor.selection.select(tinymce.activeEditor.dom.select('p')[0]); + */ + self.selection = new Selection(self.dom, self.getWin(), self.serializer, self); + + /** + * Formatter instance. + * + * @property formatter + * @type tinymce.Formatter + */ + self.formatter = new Formatter(self); + + /** + * Undo manager instance, responsible for handling undo levels. + * + * @property undoManager + * @type tinymce.UndoManager + * @example + * // Undoes the last modification to the editor + * tinymce.activeEditor.undoManager.undo(); + */ + self.undoManager = new UndoManager(self); + + self.forceBlocks = new ForceBlocks(self); + self.enterKey = new EnterKey(self); + self.editorCommands = new EditorCommands(self); + + self.fire('PreInit'); + + if (!settings.browser_spellcheck && !settings.gecko_spellcheck) { + doc.body.spellcheck = false; + } + + self.fire('PostRender'); + + self.quirks = Quirks(self); + + if (settings.directionality) { + body.dir = settings.directionality; + } + + if (settings.nowrap) { + body.style.whiteSpace = "nowrap"; + } + + if (settings.protect) { + self.on('BeforeSetContent', function(e) { + each(settings.protect, function(pattern) { + e.content = e.content.replace(pattern, function(str) { + return ''; + }); + }); + }); + } + + self.on('SetContent', function() { + self.addVisual(self.getBody()); + }); + + // Remove empty contents + if (settings.padd_empty_editor) { + self.on('PostProcess', function(e) { + e.content = e.content.replace(/^(]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
    [\r\n]*)$/, ''); + }); + } + + self.load({initial: true, format: 'html'}); + self.startContent = self.getContent({format: 'raw'}); + + /** + * Is set to true after the editor instance has been initialized + * + * @property initialized + * @type Boolean + * @example + * function isEditorInitialized(editor) { + * return editor && editor.initialized; + * } + */ + self.initialized = true; + + each(self._pendingNativeEvents, function(name) { + self.dom.bind(getEventTarget(self, name), name, function(e) { + self.fire(e.type, e); + }); + }); + + self.fire('init'); + self.focus(true); + self.nodeChanged({initial: true}); + self.execCallback('init_instance_callback', self); + + // Add editor specific CSS styles + if (self.contentStyles.length > 0) { + contentCssText = ''; + + each(self.contentStyles, function(style) { + contentCssText += style + "\r\n"; + }); + + self.dom.addStyle(contentCssText); + } + + // 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 = self.editorManager.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; + }, + + /** + * Focuses/activates the editor. This will set this editor as the activeEditor in the tinymce collection + * it will also place DOM focus inside the editor. + * + * @method focus + * @param {Boolean} skip_focus Skip DOM focus. Just set is as the active editor. + */ + focus: function(skip_focus) { + var oed, self = this, selection = self.selection, contentEditable = self.settings.content_editable, rng; + var controlElm, doc = self.getDoc(), body; + + if (!skip_focus) { + if ((rng = selection.lastRng)) { + selection.lastRng = null; + selection.setRng(rng); + self.nodeChanged(); + } + + // Get selected control element + rng = selection.getRng(); + if (rng.item) { + controlElm = rng.item(0); + } + + self._refreshContentEditable(); + + // Focus the window iframe + if (!contentEditable) { + self.getWin().focus(); + } + + // Focus the body as well since it's contentEditable + if (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) { + rng = doc.body.createControlRange(); + rng.addElement(controlElm); + rng.select(); + } + } + + if (self.editorManager.activeEditor != self) { + if ((oed = self.editorManager.activeEditor)) { + oed.fire('deactivate', {relatedTarget: self}); + } + + self.fire('activate', {relatedTarget: oed}); + } + + self.editorManager.activeEditor = self; + }, + + /** + * Executes a legacy callback. This method is useful to call old 2.x option callbacks. + * There new event model is a better way to add callback so this method might be removed in the future. + * + * @method execCallback + * @param {String} name Name of the callback to execute. + * @return {Object} Return value passed from callback function. + */ + execCallback: function(name) { + var self = this, callback = self.settings[name], scope; + + if (!callback) { + return; + } + + // Look through lookup + if (self.callbackLookup && (scope = self.callbackLookup[name])) { + callback = scope.func; + scope = scope.scope; + } + + if (typeof(callback) === 'string') { + scope = callback.replace(/\.\w+$/, ''); + scope = scope ? resolve(scope) : 0; + callback = resolve(callback); + self.callbackLookup = self.callbackLookup || {}; + self.callbackLookup[name] = {func: callback, scope: scope}; + } + + return callback.apply(scope || self, Array.prototype.slice.call(arguments, 1)); + }, + + /** + * Translates the specified string by replacing variables with language pack items it will also check if there is + * a key mathcin the input. + * + * @method translate + * @param {String} text String to translate by the language pack data. + * @return {String} Translated string. + */ + translate: function(text) { + var lang = this.settings.language || 'en', i18n = this.editorManager.i18n; + + if (!text) { + return ''; + } + + return i18n[lang + '.' + text] || text.replace(/\{\#([^\}]+)\}/g, function(a, b) { + return i18n[lang + '.' + b] || '{#' + b + '}'; + }); + }, + + /** + * Returns a language pack item by name/key. + * + * @method getLang + * @param {String} name Name/key to get from the language pack. + * @param {String} defaultVal Optional default value to retrive. + */ + getLang: function(name, defaultVal) { + return ( + this.editorManager.i18n[(this.settings.language || 'en') + '.' + name] || + (defaultVal !== undefined ? defaultVal : '{#' + name + '}') + ); + }, + + /** + * Returns a configuration parameter by name. + * + * @method getParam + * @param {String} name Configruation parameter to retrive. + * @param {String} defaultVal Optional default value to return. + * @param {String} type Optional type parameter. + * @return {String} Configuration parameter value or default value. + * @example + * // Returns a specific config value from the currently active editor + * var someval = tinymce.activeEditor.getParam('myvalue'); + * + * // Returns a specific config value from a specific editor instance by id + * var someval2 = tinymce.get('my_editor').getParam('myvalue'); + */ + getParam: function(name, defaultVal, type) { + var value = name in this.settings ? this.settings[name] : defaultVal, output; + + if (type === 'hash') { + output = {}; + + if (typeof(value) === 'string') { + each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function(value) { + value = value.split('='); + + if (value.length > 1) { + output[trim(value[0])] = trim(value[1]); + } else { + output[trim(value[0])] = trim(value); + } + }); + } else { + output = value; + } + + return output; + } + + return value; + }, + + /** + * Distpaches out a onNodeChange event to all observers. This method should be called when you + * need to update the UI states or element path etc. + * + * @method nodeChanged + */ + nodeChanged: function() { + var self = this, selection = self.selection, node, parents, root; + + // Fix for bug #1896577 it seems that this can not be fired while the editor is loading + if (self.initialized && !self.settings.disable_nodechange) { + // Get start node + root = self.getBody(); + node = selection.getStart() || root; + node = isIE && node.ownerDocument != self.getDoc() ? self.getBody() : node; // Fix for IE initial state + + // Edge case for

    |

    + if (node.nodeName == 'IMG' && selection.isCollapsed()) { + node = node.parentNode; + } + + // Get parents and add them to object + parents = []; + self.dom.getParent(node, function(node) { + if (node === root) { + return true; + } + + parents.push(node); + }); + + self.fire('NodeChange', {element: node, parents: parents}); + } + }, + + /** + * Adds a button that later gets created by the ControlManager. This is a shorter and easier method + * of adding buttons without the need to deal with the ControlManager directly. But it's also less + * powerfull if you need more control use the ControlManagers factory methods instead. + * + * @method addButton + * @param {String} name Button name to add. + * @param {Object} settings Settings object with title, cmd etc. + * @example + * // Adds a custom button to the editor and when a user clicks the button it will open + * // an alert box with the selected contents as plain text. + * tinymce.init({ + * ... + * + * theme_advanced_buttons1: 'example,..' + * + * setup: function(ed) { + * // Register example button + * ed.addButton('example', { + * title: 'example.desc', + * image: '../js/tinymce/plugins/example/img/example.gif', + * onclick: function() { + * ed.windowManager.alert('Hello world!! Selection: ' + ed.selection.getContent({format: 'text'})); + * } + * }); + * } + * }); + */ + addButton: function(name, settings) { + var self = this; + + if (settings.cmd) { + settings.onclick = function() { + self.execCommand(settings.cmd); + }; + } + + self.buttons = self.buttons || {}; + settings.tooltip = settings.tooltip || settings.title; + settings.icon = settings.icon || (settings.icon !== false ? name : false); + self.buttons[name] = settings; + }, + + addMenuItem: function(name, settings) { + var self = this; + + if (settings.cmd) { + settings.onclick = function() { + self.execCommand(settings.cmd); + }; + } + + self.menuItems = self.menuItems || {}; + self.menuItems[name] = settings; + }, + + /** + * Adds a custom command to the editor, you can also override existing commands with this method. + * The command that you add can be executed with execCommand. + * + * @method addCommand + * @param {String} name Command name to add/override. + * @param {addCommandCallback} callback Function to execute when the command occurs. + * @param {Object} scope Optional scope to execute the function in. + * @example + * // Adds a custom command that later can be executed using execCommand + * tinymce.init({ + * ... + * + * setup: function(ed) { + * // Register example command + * ed.addCommand('mycommand', function(ui, v) { + * ed.windowManager.alert('Hello world!! Selection: ' + ed.selection.getContent({format: 'text'})); + * }); + * } + * }); + */ + addCommand: function(name, callback, scope) { + /** + * Callback function that gets called when a command is executed. + * + * @callback addCommandCallback + * @param {Boolean} ui Display UI state true/false. + * @param {Object} value Optional value for command. + * @return {Boolean} True/false state if the command was handled or not. + */ + this.execCommands[name] = {func: callback, scope: scope || this}; + }, + + /** + * Adds a custom query state command to the editor, you can also override existing commands with this method. + * The command that you add can be executed with queryCommandState function. + * + * @method addQueryStateHandler + * @param {String} name Command name to add/override. + * @param {addQueryStateHandlerCallback} callback Function to execute when the command state retrival occurs. + * @param {Object} scope Optional scope to execute the function in. + */ + addQueryStateHandler: function(name, callback, scope) { + /** + * Callback function that gets called when a queryCommandState is executed. + * + * @callback addQueryStateHandlerCallback + * @return {Boolean} True/false state if the command is enabled or not like is it bold. + */ + this.queryStateCommands[name] = {func: callback, scope: scope || this}; + }, + + /** + * Adds a custom query value command to the editor, you can also override existing commands with this method. + * The command that you add can be executed with queryCommandValue function. + * + * @method addQueryValueHandler + * @param {String} name Command name to add/override. + * @param {addQueryValueHandlerCallback} callback Function to execute when the command value retrival occurs. + * @param {Object} scope Optional scope to execute the function in. + */ + addQueryValueHandler: function(name, callback, scope) { + /** + * Callback function that gets called when a queryCommandValue is executed. + * + * @callback addQueryValueHandlerCallback + * @return {Object} Value of the command or undefined. + */ + this.queryValueCommands[name] = {func: callback, scope: scope || this}; + }, + + /** + * Adds a keyboard shortcut for some command or function. + * + * @method addShortcut + * @param {String} pattern Shortcut pattern. Like for example: ctrl+alt+o. + * @param {String} desc Text description for the command. + * @param {String/Function} cmdFunc Command name string or function to execute when the key is pressed. + * @param {Object} sc Optional scope to execute the function in. + * @return {Boolean} true/false state if the shortcut was added or not. + */ + addShortcut: function(pattern, desc, cmdFunc, scope) { + this.shortcuts.add(pattern, desc, cmdFunc, scope); + }, + + /** + * Executes a command on the current instance. These commands can be TinyMCE internal commands prefixed with "mce" or + * they can be build in browser commands such as "Bold". A compleate list of browser commands is available on MSDN or Mozilla.org. + * This function will dispatch the execCommand function on each plugin, theme or the execcommand_callback option if none of these + * return true it will handle the command as a internal browser command. + * + * @method execCommand + * @param {String} cmd Command name to execute, for example mceLink or Bold. + * @param {Boolean} ui True/false state if a UI (dialog) should be presented or not. + * @param {mixed} value Optional command value, this can be anything. + * @param {Object} a Optional arguments object. + */ + execCommand: function(cmd, ui, value, args) { + var self = this, state = 0, cmdItem; + + if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(cmd) && (!args || !args.skip_focus)) { + self.focus(); + } + + args = extend({}, args); + self.fire('BeforeExecCommand', {command: cmd, ui: ui, value: value}); + if (args.terminate) { + return false; + } + + // Registred commands + if ((cmdItem = self.execCommands[cmd])) { + // Fall through on true + if (cmdItem.func.call(cmdItem.scope, ui, value) !== true) { + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + return true; + } + } + + // Plugin commands + each(self.plugins, function(p) { + if (p.execCommand && p.execCommand(cmd, ui, value)) { + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + state = true; + return false; + } + }); + + if (state) { + return state; + } + + // Theme commands + if (self.theme && self.theme.execCommand && self.theme.execCommand(cmd, ui, value)) { + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + return true; + } + + // Editor commands + if (self.editorCommands.execCommand(cmd, ui, value)) { + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + return true; + } + + // Browser commands + self.getDoc().execCommand(cmd, ui, value); + self.fire('ExecCommand', {command: cmd, ui: ui, value: value}); + }, + + /** + * Returns a command specific state, for example if bold is enabled or not. + * + * @method queryCommandState + * @param {string} cmd Command to query state from. + * @return {Boolean} Command specific state, for example if bold is enabled or not. + */ + queryCommandState: function(cmd) { + var self = this, queryItem, returnVal; + + // Is hidden then return undefined + if (self._isHidden()) { + return; + } + + // Registred commands + if ((queryItem = self.queryStateCommands[cmd])) { + returnVal = queryItem.func.call(queryItem.scope); + + // Fall though on true + if (returnVal !== true) { + return returnVal; + } + } + + // Editor commands + returnVal = self.editorCommands.queryCommandState(cmd); + if (returnVal !== -1) { + return returnVal; + } + + // Browser commands + try { + return self.getDoc().queryCommandState(cmd); + } catch (ex) { + // Fails sometimes see bug: 1896577 + } + }, + + /** + * Returns a command specific value, for example the current font size. + * + * @method queryCommandValue + * @param {string} cmd Command to query value from. + * @return {Object} Command specific value, for example the current font size. + */ + queryCommandValue: function(cmd) { + var self = this, queryItem, returnVal; + + // Is hidden then return undefined + if (self._isHidden()) { + return; + } + + // Registred commands + if ((queryItem = self.queryValueCommands[cmd])) { + returnVal = queryItem.func.call(queryItem.scope); + + // Fall though on true + if (returnVal !== true) { + return returnVal; + } + } + + // Editor commands + returnVal = self.editorCommands.queryCommandValue(cmd); + if (returnVal !== undefined) { + return returnVal; + } + + // Browser commands + try { + return self.getDoc().queryCommandValue(cmd); + } catch (ex) { + // Fails sometimes see bug: 1896577 + } + }, + + /** + * Shows the editor and hides any textarea/div that the editor is supposed to replace. + * + * @method show + */ + show: function() { + var self = this; + + DOM.show(self.getContainer()); + DOM.hide(self.id); + self.load(); + self.fire('show'); + }, + + /** + * Hides the editor and shows any textarea/div that the editor is supposed to replace. + * + * @method hide + */ + hide: function() { + var self = this, doc = self.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(); + + // defer the call to hide to prevent an IE9 crash #4921 + DOM.hide(self.getContainer()); + DOM.setStyle(self.id, 'display', self.orgDisplay); + self.fire('hide'); + }, + + /** + * Returns true/false if the editor is hidden or not. + * + * @method isHidden + * @return {Boolean} True/false if the editor is hidden or not. + */ + isHidden: function() { + return !DOM.isHidden(this.id); + }, + + /** + * Sets the progress state, this will display a throbber/progess for the editor. + * This is ideal for asycronous operations like an AJAX save call. + * + * @method setProgressState + * @param {Boolean} state Boolean state if the progress should be shown or hidden. + * @param {Number} time Optional time to wait before the progress gets shown. + * @return {Boolean} Same as the input state. + * @example + * // Show progress for the active editor + * tinymce.activeEditor.setProgressState(true); + * + * // Hide progress for the active editor + * tinymce.activeEditor.setProgressState(false); + * + * // Show progress after 3 seconds + * tinymce.activeEditor.setProgressState(true, 3000); + */ + setProgressState: function(state, time) { + this.fire('ProgressState', {state: state, time: time}); + }, + + /** + * Loads contents from the textarea or div element that got converted into an editor instance. + * This method will move the contents from that textarea or div into the editor by using setContent + * so all events etc that method has will get dispatched as well. + * + * @method load + * @param {Object} args Optional content object, this gets passed around through the whole load process. + * @return {String} HTML string that got set into the editor. + */ + load: function(args) { + var self = this, elm = self.getElement(), html; + + if (elm) { + args = args || {}; + args.load = true; + + html = self.setContent(elm.value !== undefined ? elm.value : elm.innerHTML, args); + args.element = elm; + + if (!args.no_events) { + self.fire('LoadContent', args); + } + + args.element = elm = null; + + return html; + } + }, + + /** + * Saves the contents from a editor out to the textarea or div element that got converted into an editor instance. + * This method will move the HTML contents from the editor into that textarea or div by getContent + * so all events etc that method has will get dispatched as well. + * + * @method save + * @param {Object} args Optional content object, this gets passed around through the whole save process. + * @return {String} HTML string that got set into the textarea/div. + */ + save: function(args) { + var self = this, elm = self.getElement(), html, form; + + if (!elm || !self.initialized) { + return; + } + + args = args || {}; + args.save = true; + + args.element = elm; + html = args.content = self.getContent(args); + + if (!args.no_events) { + self.fire('SaveContent', args); + } + + html = args.content; + + if (!/TEXTAREA|INPUT/i.test(elm.nodeName)) { + elm.innerHTML = html; + + // Update hidden form element + if ((form = DOM.getParent(self.id, 'form'))) { + each(form.elements, function(elm) { + if (elm.name == self.id) { + elm.value = html; + return false; + } + }); + } + } else { + elm.value = html; + } + + args.element = elm = null; + + return html; + }, + + /** + * Sets the specified content to the editor instance, this will cleanup the content before it gets set using + * the different cleanup rules options. + * + * @method setContent + * @param {String} content Content to set to editor, normally HTML contents but can be other formats as well. + * @param {Object} args Optional content object, this gets passed around through the whole set process. + * @return {String} HTML string that got set into the editor. + * @example + * // Sets the HTML contents of the activeEditor editor + * tinymce.activeEditor.setContent('some html'); + * + * // Sets the raw contents of the activeEditor editor + * tinymce.activeEditor.setContent('some html', {format: 'raw'}); + * + * // Sets the content of a specific editor (my_editor in this example) + * tinymce.get('my_editor').setContent(data); + * + * // Sets the bbcode contents of the activeEditor editor if the bbcode plugin was added + * tinymce.activeEditor.setContent('[b]some[/b] html', {format: 'bbcode'}); + */ + setContent: function(content, args) { + var self = this, 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.fire('BeforeSetContent', 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 (!isIE && (content.length === 0 || /^\s+$/.test(content))) { + forcedRootBlockName = self.settings.forced_root_block; + + // Check if forcedRootBlock is configured and that the block is a valid child of the body + if (forcedRootBlockName && self.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) { + content = '<' + forcedRootBlockName + '>
    '; + } else { + content = '
    '; + } + + body.innerHTML = content; + self.selection.select(body, true); + self.selection.collapse(true); + return; + } + + // Parse and serialize the html + if (args.format !== 'raw') { + content = new Serializer({}, self.schema).serialize( + self.parser.parse(content, {isRootContent: true}) + ); + } + + // Set the new cleaned contents to the editor + args.content = trim(content); + self.dom.setHTML(body, args.content); + + // Do post processing + if (!args.no_events) { + self.fire('SetContent', args); + } + + // Don't normalize selection if the focused element isn't the body in content editable mode since it will steal focus otherwise + if (!self.settings.content_editable || document.activeElement === self.getBody()) { + self.selection.normalize(); + } + + return args.content; + }, + + /** + * Gets the content from the editor instance, this will cleanup the content before it gets returned using + * the different cleanup rules options. + * + * @method getContent + * @param {Object} args Optional content object, this gets passed around through the whole get process. + * @return {String} Cleaned content string, normally HTML contents. + * @example + * // Get the HTML contents of the currently active editor + * console.debug(tinymce.activeEditor.getContent()); + * + * // Get the raw contents of the currently active editor + * tinymce.activeEditor.getContent({format: 'raw'}); + * + * // Get content of a specific editor: + * tinymce.get('content id').getContent() + */ + getContent: function(args) { + var self = this, content, body = self.getBody(); + + // Setup args object + args = args || {}; + args.format = args.format || 'html'; + args.get = true; + args.getInner = true; + + // Do preprocessing + if (!args.no_events) { + self.fire('BeforeGetContent', args); + } + + // Get raw contents or by default the cleaned contents + if (args.format == 'raw') { + content = body.innerHTML; + } else if (args.format == 'text') { + content = body.innerText || body.textContent; + } else { + content = self.serializer.serialize(body, args); + } + + // Trim whitespace in beginning/end of HTML + if (args.format != 'text') { + args.content = trim(content); + } else { + args.content = content; + } + + // Do post processing + if (!args.no_events) { + self.fire('GetContent', args); + } + + return args.content; + }, + + /** + * Inserts content at caret position. + * + * @method insertContent + * @params {String} content Content to insert. + */ + insertContent: function(content) { + this.execCommand('mceInsertContent', false, content); + }, + + /** + * Returns true/false if the editor is dirty or not. It will get dirty if the user has made modifications to the contents. + * + * @method isDirty + * @return {Boolean} True/false if the editor is dirty or not. It will get dirty if the user has made modifications to the contents. + * @example + * if (tinymce.activeEditor.isDirty()) + * alert("You must save your contents."); + */ + isDirty: function() { + return !this.isNotDirty && this.undoManager.hasUndo(); + }, + + /** + * Returns the editors container element. The container element wrappes in + * all the elements added to the page for the editor. Such as UI, iframe etc. + * + * @method getContainer + * @return {Element} HTML DOM element for the editor container. + */ + getContainer: function() { + var self = this; + + if (!self.container) { + self.container = DOM.get(self.editorContainer || self.id + '_parent'); + } + + return self.container; + }, + + /** + * Returns the editors content area container element. The this element is the one who + * holds the iframe or the editable element. + * + * @method getContentAreaContainer + * @return {Element} HTML DOM element for the editor area container. + */ + getContentAreaContainer: function() { + return this.contentAreaContainer; + }, + + /** + * Returns the target element/textarea that got replaced with a TinyMCE editor instance. + * + * @method getElement + * @return {Element} HTML DOM element for the replaced element. + */ + getElement: function() { + return DOM.get(this.settings.content_element || this.id); + }, + + /** + * Returns the iframes window object. + * + * @method getWin + * @return {Window} Iframe DOM window object. + */ + getWin: function() { + var self = this, elm; + + if (!self.contentWindow) { + elm = DOM.get(self.id + "_ifr"); + + if (elm) { + self.contentWindow = elm.contentWindow; + } + } + + return self.contentWindow; + }, + + /** + * Returns the iframes document object. + * + * @method getDoc + * @return {Document} Iframe DOM document object. + */ + getDoc: function() { + var self = this, win; + + if (!self.contentDocument) { + win = self.getWin(); + + if (win) { + self.contentDocument = win.document; + } + } + + return self.contentDocument; + }, + + /** + * Returns the iframes body element. + * + * @method getBody + * @return {Element} Iframe body element. + */ + getBody: function() { + return this.bodyElement || this.getDoc().body; + }, + + /** + * URL converter function this gets executed each time a user adds an img, a or + * any other element that has a URL in it. This will be called both by the DOM and HTML + * manipulation functions. + * + * @method convertURL + * @param {string} url URL to convert. + * @param {string} name Attribute name src, href etc. + * @param {string/HTMLElement} elm Tag name or HTML DOM element depending on HTML or DOM insert. + * @return {string} Converted URL string. + */ + 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 || url.length === 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; + }, + + /** + * Adds visual aid for tables, anchors etc so they can be more easily edited inside the editor. + * + * @method addVisual + * @param {Element} elm Optional root element to loop though to find tables etc that needs the visual aid. + */ + addVisual: function(elm) { + var self = this, settings = self.settings, dom = self.dom, cls; + + elm = elm || self.getBody(); + + if (self.hasVisual === undefined) { + self.hasVisual = settings.visual; + } + + each(dom.select('table,a', elm), function(elm) { + var value; + + switch (elm.nodeName) { + case 'TABLE': + cls = settings.visual_table_class || 'mce-item-table'; + value = dom.getAttrib(elm, 'border'); + + if (!value || value == '0') { + if (self.hasVisual) { + dom.addClass(elm, cls); + } else { + dom.removeClass(elm, cls); + } + } + + return; + + case 'A': + if (!dom.getAttrib(elm, 'href', false)) { + value = dom.getAttrib(elm, 'name') || elm.id; + cls = 'mce-item-anchor'; + + if (value) { + if (self.hasVisual) { + dom.addClass(elm, cls); + } else { + dom.removeClass(elm, cls); + } + } + } + + return; + } + }); + + self.fire('VisualAid', {element: elm, hasVisual: self.hasVisual}); + }, + + /** + * Removes the editor from the dom and tinymce collection. + * + * @method remove + */ + remove: function() { + var self = this, elm = self.getContainer(), doc = self.getDoc(); + + if (!self.removed) { + self.removed = 1; // Cancels post remove event execution + + // 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.setStyle(self.id, 'display', self.orgDisplay); + + // 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.unbind(self.getWin()); + Event.unbind(self.getDoc()); + } + + Event.unbind(self.getBody()); + Event.unbind(elm); + + self.fire('remove'); + + self.editorManager.remove(self); + DOM.remove(elm); + } + }, + + bindNative: function(name) { + var self = this; + + if (self.initialized) { + self.dom.bind(getEventTarget(self, name), name, function(e) { + self.fire(name, e); + }); + } else { + if (!self._pendingNativeEvents) { + self._pendingNativeEvents = [name]; + } else { + self._pendingNativeEvents.push(name); + } + } + }, + + unbindNative: function(name) { + var self = this; + + if (self.initialized) { + self.dom.unbind(name); + } + }, + + /** + * Destroys the editor instance by removing all events, element references or other resources + * that could leak memory. This method will be called automatically when the page is unloaded + * but you can also call it directly if you know what you are doing. + * + * @method destroy + * @param {Boolean} automatic Optional state if the destroy is an automatic destroy or user called one. + */ + destroy: function(automatic) { + var self = this, form; + + // One time is enough + if (self.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(self.getDoc()); + Event.unbind(self.getWin()); + Event.unbind(self.getBody()); + } + + if (!automatic) { + self.editorManager.off(self._beforeUnload); + + // Manual destroy + if (self.theme && self.theme.destroy) { + self.theme.destroy(); + } + + // Destroy controls, selection and dom + self.selection.destroy(); + self.dom.destroy(); + } + + form = self.formElement; + if (form) { + form.submit = form._mceOldSubmit; + form._mceOldSubmit = null; + DOM.unbind(form, 'submit reset', self.formEventDelegate); + } + + self.contentAreaContainer = self.formElement = self.container = null; + self.settings.content_element = self.bodyElement = self.contentDocument = self.contentWindow = null; + + if (self.selection) { + self.selection = self.selection.win = self.selection.dom = self.selection.dom.doc = null; + } + + self.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 sel; + + if (!isGecko) { + return 0; + } + + // Weird, wheres that cursor selection? + sel = this.selection.getSel(); + return (!sel || !sel.rangeCount || sel.rangeCount === 0); + } + }; + + extend(Editor.prototype, Observable); + + return Editor; +}); + +// Included from: js/tinymce/classes/EditorManager.js + +/** + * EditorManager.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class used as a factory for manager for tinymce.Editor instaces. + * + * @class tinymce.EditorManager + */ +define("tinymce/EditorManager", [ + "tinymce/Editor", + "tinymce/dom/DOMUtils", + "tinymce/util/URI", + "tinymce/Env", + "tinymce/util/Tools", + "tinymce/util/Observable" +], function(Editor, DOMUtils, URI, Env, Tools, Observable) { + var DOM = DOMUtils.DOM; + var explode = Tools.explode, each = Tools.each, extend = Tools.extend; + var instanceCounter = 0, beforeUnloadDelegate; + + var EditorManager = { + /** + * Major version of TinyMCE build. + * + * @property majorVersion + * @type String + */ + majorVersion : '4', + + /** + * Minor version of TinyMCE build. + * + * @property minorVersion + * @type String + */ + minorVersion : '0b1', + + /** + * Release date of TinyMCE build. + * + * @property releaseDate + * @type String + */ + releaseDate: '2013-04-11', + + /** + * Collection of editor instances. + * + * @property editors + * @type Object + * @example + * for (edId in tinymce.editors) + * tinymce.editors[edId].save(); + */ + editors: [], + + /** + * Collection of language pack data. + * + * @property i18n + * @type Object + */ + i18n: {}, + + /** + * Currently active editor instance. + * + * @property activeEditor + * @type tinymce.Editor + * @example + * tinyMCE.activeEditor.selection.getContent(); + * tinymce.EditorManager.activeEditor.selection.getContent(); + */ + activeEditor: null, + + setup: function() { + var self = this, baseURL, documentBaseURL, suffix = "", preInit; + + // Get base URL for the current document + documentBaseURL = document.location.href.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, ''); + if (!/[\/\\]$/.test(documentBaseURL)) { + documentBaseURL += '/'; + } + + // If tinymce is defined and has a base use that or use the old tinyMCEPreInit + preInit = window.tinymce || window.tinyMCEPreInit; + if (preInit) { + baseURL = preInit.base || preInit.baseURL; + suffix = preInit.suffix; + } else { + // Get base where the tinymce script is located + var scripts = document.getElementsByTagName('script'); + for (var i = 0; i < scripts.length; i++) { + var src = scripts[i].src; + + if (/tinymce(\.jquery|)(\.min|\.dev|).js/.test(src)) { + if (src.indexOf('.min') != -1) { + suffix = '.min'; + } + + baseURL = src.substring(0, src.lastIndexOf('/')); + break; + } + } + } + + /** + * Base URL where the root directory if TinyMCE is located. + * + * @property baseURL + * @type {String} + */ + self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL); + + /** + * Document base URL where the current document is located. + * + * @property documentBaseURL + * @type {String} + */ + self.documentBaseURL = documentBaseURL; + + /** + * Absolute baseURI for the installation path of TinyMCE. + * + * @property baseURI + * @type tinymce.util.URI + */ + self.baseURI = new URI(self.baseURL); + + /** + * Current suffix to add to each plugin/theme that gets loaded for example ".min". + * + * @property suffix + * @type {String} + */ + self.suffix = suffix; + }, + + /** + * Initializes a set of editors. This method will create editors based on various settings. + * + * @method init + * @param {Object} settings Settings object to be passed to each editor instance. + * @example + * // Initializes a editor using the longer method + * tinymce.EditorManager.init({ + * some_settings : 'some value' + * }); + * + * // Initializes a editor instance using the shorter version + * tinyMCE.init({ + * some_settings : 'some value' + * }); + */ + init: function(settings) { + var self = this, editors = [], editor; + + 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; + } + + 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); + } + + self.settings = settings; + + DOM.bind(window, 'ready', function() { + var l, co; + + execCallback(settings, 'onpageload'); + + switch (settings.mode) { + case "exact": + l = settings.elements || ''; + + if(l.length > 0) { + each(explode(l), function(v) { + if (DOM.get(v)) { + editor = new Editor(v, settings, self); + editors.push(editor); + editor.render(true); + } else { + each(document.forms, function(f) { + each(f.elements, function(e) { + if (e.name === v) { + v = 'mce_editor_' + instanceCounter++; + DOM.setAttrib(e, 'id', v); + + editor = new Editor(v, settings, self); + editors.push(editor); + editor.render(1); + } + }); + }); + } + }); + } + break; + + case "textareas": + case "specific_textareas": + each(DOM.select('textarea'), function(elm) { + if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) { + return; + } + + if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) { + editor = new Editor(createId(elm), settings, self); + editors.push(editor); + editor.render(true); + } + }); + break; + + default: + if (settings.types) { + // Process type specific selector + each(settings.types, function(type) { + each(DOM.select(type.selector), function(elm) { + var editor = new Editor(createId(elm), extend({}, settings, type), self); + editors.push(editor); + editor.render(1); + }); + }); + } else if (settings.selector) { + // Process global selector + each(DOM.select(settings.selector), function(elm) { + var editor = new Editor(createId(elm), settings, self); + editors.push(editor); + editor.render(1); + }); + } + } + + // Call onInit when all editors are initialized + if (settings.oninit) { + l = co = 0; + + each(editors, function(ed) { + co++; + + if (!ed.initialized) { + // Wait for it + ed.on('init', function() { + l++; + + // All done + if (l == co) { + execCallback(settings, 'oninit'); + } + }); + } else { + l++; + } + + // All done + if (l == co) { + execCallback(settings, 'oninit'); + } + }); + } + }); + }, + + /** + * Returns a editor instance by id. + * + * @method get + * @param {String/Number} id Editor instance id or index to return. + * @return {tinymce.Editor} Editor instance to return. + * @example + * // Adds an onclick event to an editor by id (shorter version) + * tinymce.get('mytextbox').on('click', function(e) { + * ed.windowManager.alert('Hello world!'); + * }); + * + * // Adds an onclick event to an editor by id (longer version) + * tinymce.EditorManager.get('mytextbox').on('click', function(e) { + * ed.windowManager.alert('Hello world!'); + * }); + */ + get: function(id) { + if (id === undefined) { + return this.editors; + } + + return this.editors[id]; + }, + + /** + * Adds an editor instance to the editor collection. This will also set it as the active editor. + * + * @method add + * @param {tinymce.Editor} editor Editor instance to add to the collection. + * @return {tinymce.Editor} The same instance that got passed in. + */ + add: function(editor) { + var self = this, editors = self.editors; + + // Add named and index editor instance + editors[editor.id] = editor; + editors.push(editor); + + self.activeEditor = editor; + self.fire('AddEditor', {editor: editor}); + + if (!beforeUnloadDelegate) { + beforeUnloadDelegate = function() { + self.fire('BeforeUnload'); + }; + + DOM.bind(window, 'beforeunload', beforeUnloadDelegate); + } + + return editor; + }, + + /** + * Creates an editor instance and adds it to the EditorManager collection. + * + * @param {Object} settings Editor instance settings. + * @return {tinymce.Editor} Editor instance that got created. + */ + createEditor: function(settings) { + return this.add(new Editor(settings)); + }, + + /** + * Removes a editor instance from the collection. + * + * @method remove + * @param {tinymce.Editor} e Editor instance to remove. + * @return {tinymce.Editor} The editor that got passed in will be return if it was found otherwise null. + */ + remove: function(editor) { + var self = this, i, editors = self.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 (self.activeEditor == editor) { + self.activeEditor = editors[0]; + } + + editor.destroy(); + self.fire('RemoveEditor', {editor: editor}); + + if (!editors.length) { + DOM.unbind(window, 'beforeunload', beforeUnloadDelegate); + } + + return editor; + }, + + /** + * Executes a specific command on the currently active editor. + * + * @method execCommand + * @param {String} c Command to perform for example Bold. + * @param {Boolean} u Optional boolean state if a UI should be presented for the command or not. + * @param {String} v Optional value parameter like for example an URL to a link. + * @return {Boolean} true/false if the command was executed or not. + */ + execCommand: function(cmd, ui, value) { + var self = this, editor = self.get(value); + + // Manager commands + switch (cmd) { + case "mceAddEditor": + if (!self.get(value)) { + new Editor(value, self.settings, self).render(); + } + + return true; + + case "mceRemoveEditor": + if (editor) { + editor.remove(); + } + + return true; + + case 'mceToggleEditor': + if (!editor) { + self.execCommand('mceAddEditor', 0, value); + return true; + } + + if (editor.isHidden()) { + editor.show(); + } else { + editor.hide(); + } + + return true; + } + + // Run command on active editor + if (self.activeEditor) { + return self.activeEditor.execCommand(cmd, ui, value); + } + + return false; + }, + + /** + * Calls the save method on all editor instances in the collection. This can be useful when a form is to be submitted. + * + * @method triggerSave + * @example + * // Saves all contents + * tinyMCE.triggerSave(); + */ + triggerSave: function() { + each(this.editors, function(editor) { + editor.save(); + }); + }, + + /** + * Adds a language pack, this gets called by the loaded language files like en.js. + * + * @method addI18n + * @param {String} code Optional language code. + * @param {Object} items Name/value object with translations. + */ + addI18n: function(code, items) { + extend(this.i18n, items || code); + }, + + /** + * Translates the specified string using the language pack items. + * + * @param {String/Array} str String to translate + * @return {String} Translated string. + */ + translate: function(str) { + if (typeof(str) !== "string") { + return (this.i18n[str[0]] || str[0]).replace(/%d/, str[1]); + } + + return this.i18n[str] || str; + } + }; + + EditorManager.setup(); + + // Export EditorManager as tinymce/tinymce in global namespace + window.tinymce = window.tinyMCE = EditorManager; + + extend(EditorManager, Observable); + + return EditorManager; +}); + +// Included from: js/tinymce/classes/LegacyInput.js + +/** + * LegacyInput.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/LegacyInput", [ + "tinymce/EditorManager", + "tinymce/util/Tools" +], function(EditorManager, Tools) { + var each = Tools.each, explode = Tools.explode; + + EditorManager.on('AddEditor', function(e) { + var ed = e.editor; + + ed.on('preInit', function() { + var filters, fontSizes, dom, settings = ed.settings; + + function replaceWithSpan(node, styles) { + each(styles, function(value, name) { + if (value) { + dom.setStyle(node, name, value); + } + }); + + dom.rename(node, 'span'); + } + + function convert(e) { + dom = ed.dom; + + if (settings.convert_fonts_to_spans) { + each(dom.select('font,u,strike', e.node), function(node) { + filters[node.nodeName.toLowerCase()](dom, node); + }); + } + } + + if (settings.inline_styles) { + fontSizes = 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.on('PreProcess SetContent', convert); + } + }); + }); +}); + +// Included from: js/tinymce/classes/util/XHR.js + +/** + * XHR.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class enables you to send XMLHTTPRequests cross browser. + * @class tinymce.util.XHR + * @static + * @example + * // Sends a low level Ajax request + * tinymce.util.XHR.send({ + * url: 'someurl', + * success: function(text) { + * console.debug(text); + * } + * }); + */ +define("tinymce/util/XHR", [], function() { + return { + /** + * Sends a XMLHTTPRequest. + * Consult the Wiki for details on what settings this method takes. + * + * @method send + * @param {Object} settings Object will target URL, callbacks and other info needed to make the request. + */ + send: function(settings) { + var xhr, count = 0; + + function ready() { + if (!settings.async || xhr.readyState == 4 || count++ > 10000) { + if (settings.success && count < 10000 && xhr.status == 200) { + settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings); + } else if (settings.error) { + settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings); + } + + xhr = null; + } else { + setTimeout(ready, 10); + } + } + + // Default settings + settings.scope = settings.scope || this; + settings.success_scope = settings.success_scope || settings.scope; + settings.error_scope = settings.error_scope || settings.scope; + settings.async = settings.async === false ? false : true; + settings.data = settings.data || ''; + + xhr = new XMLHttpRequest(); + + if (xhr) { + if (xhr.overrideMimeType) { + xhr.overrideMimeType(settings.content_type); + } + + xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async); + + if (settings.content_type) { + xhr.setRequestHeader('Content-Type', settings.content_type); + } + + xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); + + xhr.send(settings.data); + + // Syncronous request + if (!settings.async) { + return ready(); + } + + // Wait for response, onReadyStateChange can not be used since it leaks memory in IE + setTimeout(ready, 10); + } + } + }; +}); + +// Included from: js/tinymce/classes/util/JSON.js + +/** + * JSON.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * JSON parser and serializer class. + * + * @class tinymce.util.JSON + * @static + * @example + * // JSON parse a string into an object + * var obj = tinymce.util.JSON.parse(somestring); + * + * // JSON serialize a object into an string + * var str = tinymce.util.JSON.serialize(obj); + */ +define("tinymce/util/JSON", [], 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 && Object.prototype.toString.call(o) === '[object Array]') { + for (i=0, 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; + } + + return { + /** + * Serializes the specified object as a JSON string. + * + * @method serialize + * @param {Object} obj Object to serialize as a JSON string. + * @param {String} quote Optional quote string defaults to ". + * @return {string} JSON string serialized from input. + */ + serialize: serialize, + + /** + * Unserializes/parses the specified JSON string into a object. + * + * @method parse + * @param {string} s JSON String to parse into a JavaScript object. + * @return {Object} Object from input JSON string or undefined if it failed. + */ + parse: function(text) { + try { + // Trick uglify JS + return window[String.fromCharCode(101) + 'val']('(' + text + ')'); + } catch (ex) { + // Ignore + } + } + + /**#@-*/ + }; +}); + +// Included from: js/tinymce/classes/util/JSONRequest.js + +/** + * JSONRequest.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class enables you to use JSON-RPC to call backend methods. + * + * @class tinymce.util.JSONRequest + * @example + * var json = new tinymce.util.JSONRequest({ + * url: 'somebackend.php' + * }); + * + * // Send RPC call 1 + * json.send({ + * method: 'someMethod1', + * params: ['a', 'b'], + * success: function(result) { + * console.dir(result); + * } + * }); + * + * // Send RPC call 2 + * json.send({ + * method: 'someMethod2', + * params: ['a', 'b'], + * success: function(result) { + * console.dir(result); + * } + * }); + */ +define("tinymce/util/JSONRequest", [ + "tinymce/util/JSON", + "tinymce/util/XHR", + "tinymce/util/Tools" +], function(JSON, XHR, Tools) { + var extend = Tools.extend; + + function JSONRequest(settings) { + this.settings = extend({}, settings); + this.count = 0; + } + + /** + * Simple helper function to send a JSON-RPC request without the need to initialize an object. + * Consult the Wiki API documentation for more details on what you can pass to this function. + * + * @method sendRPC + * @static + * @param {Object} o Call object where there are three field id, method and params this object should also contain callbacks etc. + */ + JSONRequest.sendRPC = function(o) { + return new JSONRequest().send(o); + }; + + JSONRequest.prototype = { + /** + * Sends a JSON-RPC call. Consult the Wiki API documentation for more details on what you can pass to this function. + * + * @method send + * @param {Object} args Call object where there are three field id, method and params this object should also contain callbacks etc. + */ + send: function(args) { + var ecb = args.error, scb = args.success; + + args = extend(this.settings, args); + + args.success = function(c, x) { + c = JSON.parse(c); + + if (typeof(c) == 'undefined') { + c = { + error : 'JSON Parse error.' + }; + } + + if (c.error) { + ecb.call(args.error_scope || args.scope, c.error, x); + } else { + scb.call(args.success_scope || args.scope, c.result); + } + }; + + args.error = function(ty, x) { + if (ecb) { + ecb.call(args.error_scope || args.scope, ty, x); + } + }; + + args.data = JSON.serialize({ + id : args.id || 'c' + (this.count++), + method : args.method, + params : args.params + }); + + // JSON content type for Ruby on rails. Bug: #1883287 + args.content_type = 'application/json'; + + XHR.send(args); + } + }; + + return JSONRequest; +}); + +// Included from: js/tinymce/classes/util/JSONP.js + +/** + * JSONP.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +define("tinymce/util/JSONP", [ + "tinymce/dom/DOMUtils" +], function(DOMUtils) { + return { + callbacks: {}, + count: 0, + + send: function(settings) { + var self = this, dom = DOMUtils.DOM, count = settings.count !== undefined ? settings.count : self.count; + var id = 'tinymce_jsonp_' + count; + + self.callbacks[count] = function(json) { + dom.remove(id); + delete self.callbacks[count]; + + settings.callback(json); + }; + + dom.add(dom.doc.body, 'script', { + id: id, + src: settings.url, + type: 'text/javascript' + }); + + self.count++; + } + }; +}); + +// Included from: js/tinymce/classes/util/LocalStorage.js + +/** + * LocalStorage.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * This class will simulate LocalStorage on IE 7 and return the native version on modern browsers. + * Storage is done using userData on IE 7 and a special serialization format. The format is designed + * to be as small as possible by making sure that the keys and values doesn't need to be encoded. This + * makes it possible to store for example HTML data. + * + * Storage format for userData: + * ,,,,... + * + * For example this data key1=value1,key2=value2 would be: + * 4,key1,6,value1,4,key2,6,value2 + * + * @class tinymce.util.LocalStorage + * @static + * @version 4.0 + * @example + * tinymce.util.LocalStorage.setItem('key', 'value'); + * var value = tinymce.util.LocalStorage.getItem('key'); + */ +define("tinymce/util/LocalStorage", [], function() { + var LocalStorage, storageElm, items, keys, userDataKey; + + // Check for native support + if (window.localStorage) { + return localStorage; + } + + userDataKey = "tinymce"; + storageElm = document.documentElement; + storageElm.addBehavior('#default#userData'); + + /** + * Gets the keys names and updates LocalStorage.length property. Since IE7 doesn't have any getters/setters. + */ + function updateKeys() { + keys = []; + + for (var key in items) { + keys.push(key); + } + + LocalStorage.length = keys.length; + } + + /** + * Loads the userData string and parses it into the items structure. + */ + function load() { + var key, data, value, pos = 0; + + items = {}; + + function next(end) { + var value, nextPos; + + nextPos = end !== undefined ? pos + end : data.indexOf(',', pos); + if (nextPos === -1 || nextPos > data.length) { + return null; + } + + value = data.substring(pos, nextPos); + pos = nextPos + 1; + + return value; + } + + storageElm.load(userDataKey); + data = storageElm.getAttribute(userDataKey) || ''; + + do { + key = next(parseInt(next(), 32) || 0); + if (key !== null) { + value = next(parseInt(next(), 32) || 0); + items[key] = value; + } + } while (key !== null); + + updateKeys(); + } + + /** + * Saves the items structure into a the userData format. + */ + function save() { + var value, data = ''; + + for (var key in items) { + value = items[key]; + data += (data ? ',' : '') + key.length.toString(32) + ',' + key + ',' + value.length.toString(32) + ',' + value; + } + + storageElm.setAttribute(userDataKey, data); + storageElm.save(userDataKey); + updateKeys(); + } + + LocalStorage = { + /** + * Length of the number of items in storage. + * + * @property length + * @return {Number} Number of items in storage. + */ + //length:0, + + /** + * Returns the key name by index. + * + * @method key + * @param {Number} index Index of key to return. + * @return {String} Key value or null if it wasn't found. + */ + key: function(index) { + return keys[index]; + }, + + /** + * Returns the value if the specified key or null if it wasn't found. + * + * @method getItem + * @param {String} key Key of item to retrive. + * @return {String} Value of the specified item or null if it wasn't found. + */ + getItem: function(key) { + return key in items ? items[key] : null; + }, + + /** + * Sets the value of the specified item by it's key. + * + * @method setItem + * @param {String} key Key of the item to set. + * @param {String} value Value of the item to set. + */ + setItem: function(key, value) { + items[key] = "" + value; + save(); + }, + + /** + * Removes the specified item by key. + * + * @method removeItem + * @param {String} key Key of item to remove. + */ + removeItem: function(key) { + delete items[key]; + save(); + }, + + /** + * Removes all items. + * + * @method clear + */ + clear: function() { + items = {}; + save(); + } + }; + + load(); + + return LocalStorage; +}); + +// Included from: js/tinymce/classes/Compat.js + +/** + * Compat.js + * + * Copyright, Moxiecode Systems AB + * Released under LGPL License. + * + * License: http://www.tinymce.com/license + * Contributing: http://www.tinymce.com/contributing + */ + +/** + * Adds various compatibility items. + */ +define("tinymce/Compat", [ + "tinymce/dom/DOMUtils", + "tinymce/dom/EventUtils", + "tinymce/dom/ScriptLoader", + "tinymce/AddOnManager", + "tinymce/util/Tools", + "tinymce/Env" +], function(DOMUtils, EventUtils, ScriptLoader, AddOnManager, Tools, Env) { + var tinymce = window.tinymce; + + tinymce.DOM = DOMUtils.DOM; + tinymce.ScriptLoader = ScriptLoader.ScriptLoader; + tinymce.PluginManager = AddOnManager.PluginManager; + tinymce.ThemeManager = AddOnManager.ThemeManager; + + tinymce.dom = tinymce.dom || {}; + tinymce.dom.Event = EventUtils.Event; + + Tools.each(Tools, function(func, key) { + tinymce[key] = func; + }); + + Tools.each('isOpera isWebKit isIE isGecko isMac'.split(' '), function(name) { + tinymce[name] = Env[name.substr(2).toLowerCase()]; + }); + + return {}; +}); + +// Included from: js/tinymce/classes/ui/Layout.js + +/** + * Layout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * Base layout manager class. + * + * @class tinymce.ui.Layout + */ +define("tinymce/ui/Layout", [ + "tinymce/util/Class", + "tinymce/util/Tools" +], function(Class, Tools) { + "use strict"; + + return Class.extend({ + Defaults: { + firstControlClass: 'first', + lastControlClass: 'last' + }, + + init: function(settings) { + this.settings = Tools.extend({}, this.Defaults, settings); + }, + + preRender: function(container) { + container.addClass(this.settings.containerClass, 'body'); + }, + + applyClasses: function(container) { + var self = this, settings = self.settings, items, firstClass, lastClass; + + items = container.items().filter(':visible'); + firstClass = settings.firstControlClass; + lastClass = settings.lastControlClass; + + items.each(function(item) { + item.removeClass(firstClass).removeClass(lastClass); + + if (settings.controlClass) { + item.addClass(settings.controlClass); + } + }); + + items.eq(0).addClass(firstClass); + items.eq(-1).addClass(lastClass); + }, + + renderHtml: function(container) { + var self = this, settings = self.settings, items, html = ''; + + items = container.items(); + items.eq(0).addClass(settings.firstControlClass); + items.eq(-1).addClass(settings.lastControlClass); + + items.each(function(item) { + if (settings.controlClass) { + item.addClass(settings.controlClass); + } + + html += item.renderHtml(); + }); + + return html; + }, + + recalc: function() { + }, + + postRender: function() { + } + }); +}); + +// Included from: js/tinymce/classes/ui/AbsoluteLayout.js + +/** + * AbsoluteLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less AbsoluteLayout.less + * @class tinymce.ui.AbsoluteLayout + * @extends tinymce.ui.Layout + */ +define("tinymce/ui/AbsoluteLayout", [ + "tinymce/ui/Layout" +], function(Layout) { + "use strict"; + + return Layout.extend({ + Defaults: { + containerClass: 'abs-layout', + controlClass: 'abs-layout-item' + }, + + recalc: function(container) { + container.items().filter(':visible').each(function(ctrl) { + var settings = ctrl.settings; + + ctrl.layoutRect({ + x: settings.x, + y: settings.y, + w: settings.w, + h: settings.h + }); + + if (ctrl.recalc) { + ctrl.recalc(); + } + }); + }, + + renderHtml: function(container) { + return '
    ' + this._super(container); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Tooltip.js + +/** + * Tooltip.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ToolTip.less + * @class tinymce.ui.ToolTip + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Tooltip", [ + "tinymce/ui/Control", + "tinymce/ui/Movable" +], function(Control, Movable) { + return Control.extend({ + Mixins: [Movable], + + Defaults: { + classes: 'widget tooltip tooltip-n' + }, + + text: function(value) { + var self = this; + + if (typeof(value) != "undefined") { + self._value = value; + + if (self._rendered) { + self.getEl().lastChild.innerHTML = self.encode(value); + } + + return self; + } + + return self._value; + }, + + renderHtml: function() { + var self = this, prefix = self.classPrefix; + + return ( + '' + ); + }, + + repaint: function() { + var self = this, style, rect; + + style = self.getEl().style; + rect = self._layoutRect; + + style.left = rect.x + 'px'; + style.top = rect.y + 'px'; + style.zIndex = 0xFFFF + 0xFFFF; + } + }); +}); + +// Included from: js/tinymce/classes/ui/Widget.js + +/** + * Widget.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * + * @class tinymce.ui.Widget + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Widget", [ + "tinymce/ui/Control", + "tinymce/ui/Tooltip" +], function(Control, Tooltip) { + "use strict"; + + var tooltip; + + return Control.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + self.canFocus = true; + + if (settings.tooltip) { + self.on('mouseenter mouseleave', function(e) { + if (e.control == self && e.type == 'mouseenter') { + self.tooltip().moveTo(-0xFFFF).text(settings.tooltip).show().moveRel(self.getEl(), 'bc tc'); + } else { + self.tooltip().moveTo(-0xFFFF).hide(); + } + }); + } + + self.aria('label', settings.tooltip); + }, + + tooltip: function() { + var self = this; + + if (!tooltip) { + tooltip = new Tooltip({type: 'tooltip'}); + tooltip.renderTo(self.getContainerElm()); + } + + return tooltip; + }, + + active: function(state) { + var self = this, undef; + + if (state !== undef) { + self.aria('pressed', state); + self.toggleClass('active', state); + } + + return self._super(state); + }, + + disabled: function(state) { + var self = this, undef; + + if (state !== undef) { + self.aria('disabled', state); + self.toggleClass('disabled', state); + } + + return self._super(state); + }, + + postRender: function() { + var self = this, settings = self.settings; + + self._rendered = true; + + self._super(); + + if (!self.parent() && (settings.width || settings.height)) { + self.initLayoutRect(); + self.repaint(); + } + + if (settings.autofocus) { + self.focus(); + } + }, + + remove: function() { + this._super(); + + if (tooltip) { + tooltip.remove(); + tooltip = null; + } + } + }); +}); + +// Included from: js/tinymce/classes/ui/Button.js + +/** + * Button.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Button.less + * @class tinymce.ui.Button + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Button", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + Defaults: { + classes: "widget btn", + role: "button" + }, + + init: function(settings) { + var self = this, size; + + self.on('click mousedown', function(e) { + e.preventDefault(); + }); + + self._super(settings); + size = settings.size; + + if (settings.subtype) { + self.addClass(settings.subtype); + } + + if (size) { + self.addClass('btn-' + size); + } + }, + + repaint: function() { + var btnStyle = this.getEl().firstChild.style; + + btnStyle.width = btnStyle.height = "100%"; + + this._super(); + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; + var image = self.settings.image ? ' style="background-image: url(\'' + self.settings.image + '\')"' : ''; + + return ( + '
    ' + + '' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/ButtonGroup.js + +/** + * ButtonGroup.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ButtonGroup.less + * @class tinymce.ui.ButtonGroup + * @extends tinymce.ui.Container + */ +define("tinymce/ui/ButtonGroup", [ + "tinymce/ui/Container" +], function(Container) { + "use strict"; + + return Container.extend({ + Defaults: { + defaultType: 'button', + role: 'toolbar' + }, + + renderHtml: function() { + var self = this, layout = self._layout; + + self.addClass('btn-group'); + self.preRender(); + layout.preRender(self); + + return ( + '
    '+ + '
    '+ + (self.settings.html || '') + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Checkbox.js + +/** + * Checkbox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Checkbox.less + * @class tinymce.ui.Checkbox + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/Checkbox", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + Defaults: { + classes: "checkbox", + role: "checkbox", + checked: false + }, + + init: function(settings) { + var self = this; + + self._super(settings); + + self.on('click mousedown', function(e) { + e.preventDefault(); + }); + + self.on('click', function(e) { + e.preventDefault(); + + if (!self.disabled()) { + self.checked(!self.checked()); + } + }); + + self.checked(self.settings.checked); + }, + + checked: function(state) { + var self = this; + + if (typeof state != "undefined") { + if (state) { + self.addClass('checked'); + } else { + self.removeClass('checked'); + } + + self._checked = state; + self.aria('checked', state); + + return self; + } + + return self._checked; + }, + + value: function(state) { + return this.checked(state); + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + + return ( + '
    ' + + '' + + '' + self._text + '' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/CheckboxGroup.js + +/** + * CheckboxGroup.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.CheckboxGroup + * @extends tinymce.ui.Container + */ +define("tinymce/ui/CheckboxGroup", [ + "tinymce/ui/Container" +], function(Container) { + "use strict"; + + return Container.extend({}); +}); + +// Included from: js/tinymce/classes/ui/ColorButton.js + +/** + * ColorButton.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ColorButton.less + * @class tinymce.ui.ColorButton + * @extends tinymce.ui.MenuButton + */ +define("tinymce/ui/ColorButton", [ + "tinymce/ui/Button", + "tinymce/ui/FloatPanel", + "tinymce/ui/KeyboardNavigation" +], function(Button, FloatPanel, KeyboardNavigation) { + "use strict"; + + function mapColors() { + var i, colors = [], colorMap; + + colorMap = [ + "000000", "Black", + "993300", "Burnt orange", + "333300", "Dark olive", + "003300", "Dark green", + "003366", "Dark azure", + "000080", "Navy Blue", + "333399", "Indigo", + "333333", "Very dark gray", + "800000", "Maroon", + "FF6600", "Orange", + "808000", "Olive", + "008000", "Green", + "008080", "Teal", + "0000FF", "Blue", + "666699", "Grayish blue", + "808080", "Gray", + "FF0000", "Red", + "FF9900", "Amber", + "99CC00", "Yellow green", + "339966", "Sea green", + "33CCCC", "Turquoise", + "3366FF", "Royal blue", + "800080", "Purple", + "999999", "Medium gray", + "FF00FF", "Magenta", + "FFCC00", "Gold", + "FFFF00", "Yellow", + "00FF00", "Lime", + "00FFFF", "Aqua", + "00CCFF", "Sky blue", + "993366", "Brown", + "C0C0C0", "Silver", + "FF99CC", "Pink", + "FFCC99", "Peach", + "FFFF99", "Light yellow", + "CCFFCC", "Pale green", + "CCFFFF", "Pale cyan", + "99CCFF", "Light sky blue", + "CC99FF", "Plum", + "FFFFFF", "White" + ]; + + for (i = 0; i < colorMap.length; i += 2) { + colors.push({ + text: colorMap[i + 1], + color: colorMap[i] + }); + } + + return colors; + } + + return Button.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('colorbutton'); + self.on('click', function(e) { + if (e.control == self) { + self.showPicker(); + } + }); + self.hasPopup = true; + }, + + showPicker: function() { + var self = this, html = '', size, x, y, prefix = self.classPrefix, colors; + + if (!self.picker) { + colors = mapColors(); + + html = ''; + size = Math.ceil(Math.sqrt(colors.length)); + + for (y = 0; y < 5; y++) { + html += ''; + + for (x = 0; x < 8; x++) { + var color = colors[y * 8 + x]; + + html += ( + '' + ); + } + + html += ''; + } + + html += ''; + + self.picker = new FloatPanel({ + popover: true, + autohide: true, + html: html, + border: 1, + classes: 'colorpicker' + }).parent(self).renderTo(self.getContainerElm()); + + self.picker._hasBody = false; + self.picker.reflow(); + self.picker.parent(self); + self.picker.on('cancel', function(e) { + if (e.control === self.menu) { + self.focus(); + } + }); + self.picker.on('click', function(e) { + var value; + + if ((value = e.target.getAttribute('data-mce-color'))) { + self.picker.hide(); + value = '#' + value; + self.showPreview(value); + self.fire('select', {value: value}); + } + }); + + self.keyboardNavigation = new KeyboardNavigation({ + root: self.picker, + items: self.picker.getEl().getElementsByTagName('div'), + onCancel: function() { + self.picker.hide(); + self.fire('cancel'); + } + }); + } + + self.picker.show(); + self.picker.moveRel(self.getEl(), 'bc-tl'); + self.keyboardNavigation.focusFirst(); + }, + + showPreview: function(color) { + this.getEl('preview').style.backgroundColor = color; + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; + var image = self.settings.image ? ' style="background-image: url(\'' + self.settings.image + '\')"' : ''; + + return ( + '
    ' + + '' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/ComboBox.js + +/** + * ComboBox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ComboBox.less + * @class tinymce.ui.ComboBox + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/ComboBox", [ + "tinymce/ui/Widget", + "tinymce/ui/DomUtils" +], function(Widget, DomUtils) { + "use strict"; + + return Widget.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('combobox'); + + self.on('click', function(e) { + var elm = e.target; + + while (elm) { + if (elm.id && elm.id.indexOf('-open') != -1) { + self.fire('action'); + } + + elm = elm.parentNode; + } + }); + + // TODO: Rework this + self.on('keydown', function(e) { + if (e.target.nodeName == "INPUT" && e.keyCode == 13) { + self.parents().reverse().each(function(ctrl) { + e.preventDefault(); + self.fire('change'); + + if (ctrl.submit) { + ctrl.submit(); + return false; + } + }); + } + }); + + if (settings.placeholder) { + self.addClass('placeholder'); + + self.on('focusin', function() { + if (!self._hasOnChange) { + DomUtils.on(self.getEl('inp'), 'change', function() { + self.fire('change'); + }); + + self._hasOnChange = true; + } + + if (self.hasClass('placeholder')) { + self.getEl('inp').value = ''; + self.removeClass('placeholder'); + } + }); + + self.on('focusout', function() { + if (self.value().length === 0) { + self.getEl('inp').value = settings.placeholder; + self.addClass('placeholder'); + } + }); + } + }, + + value: function(value) { + var self = this; + + if (typeof(value) != "undefined") { + self._value = value; + self.removeClass('placeholder'); + + if (self._rendered) { + self.getEl('inp').value = value; + } + + return self; + } + + if (self._rendered) { + value = self.getEl('inp').value; + + if (value != self.settings.placeholder) { + return value; + } + + return ''; + } + + return self._value; + }, + + repaint: function() { + var self = this, elm = self.getEl(), openElm = self.getEl('open'), rect = self.layoutRect(); + + if (openElm) { + DomUtils.css(elm.firstChild, { + width: rect.w - openElm.offsetWidth - 10 + //lineHeight: (self.layoutRect().h - 2) + 'px' + }); + } else { + DomUtils.css(elm.firstChild, { + width: rect.w - 10 + }); + } + + self._super(); + + return self; + }, + + disabled: function(state) { + var self = this; + + self._super(state); + + if (self._rendered) { + self.getEl().disabled = state; + } + }, + + focus: function() { + this.getEl('inp').focus(); + }, + + postRender: function() { + var self = this; + + DomUtils.on(this.getEl('inp'), 'change', function() { + self.fire('change'); + }); + + return self._super(); + }, + + renderHtml: function() { + var self = this, id = self._id, settings = self.settings, prefix = self.classPrefix; + var value = settings.value || settings.placeholder || ''; + var icon, text, openBtnHtml = ''; + + icon = settings.icon ? prefix + 'ico ' + prefix + 'i-' + settings.icon : ''; + text = self._text; + + if (icon || text) { + openBtnHtml = ( + '
    ' + + '' + + '
    ' + ); + + self.addClass('has-open'); + } + + return ( + '
    ' + + '' + + openBtnHtml + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Path.js + +/** + * Path.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Path.less + * @class tinymce.ui.Path + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Path", [ + "tinymce/ui/Control", + "tinymce/ui/KeyboardNavigation" +], function(Control, KeyboardNavigation) { + "use strict"; + + return Control.extend({ + Defaults: { + delimiter: "\u00BB" + }, + + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('path'); + self.canFocus = true; + + self.on('click', function(e) { + var index, target = e.target; + + if ((index = target.getAttribute('data-index'))) { + self.fire('select', {value: self.data()[index], index: index}); + } + }); + }, + + focus: function() { + var self = this; + + self.keyNav = new KeyboardNavigation({ + root: self, + enableLeftRight: true + }); + + self.keyNav.focusFirst(); + + return self; + }, + + data: function(data) { + var self = this; + + if (typeof(data) !== "undefined") { + self._data = data; + self.update(); + + return self; + } + + return self._data; + }, + + update: function() { + var self = this, parts = self._data, i, l, html = '', prefix = self.classPrefix; + + for (i = 0, l = parts.length; i < l; i++) { + html += ( + (i > 0 ? '' : '') + + '
    ' + parts[i].name + '
    ' + ); + } + + self.getEl().innerHTML = html; + }, + + postRender: function() { + var self = this; + + self._super(); + + self.data(self.settings.data); + }, + + repa2int: function() { + var self = this; + + self.getEl('text').style.lineHeight = self.layoutRect().h + 'px'; + + return self._super(); + }, + + /** + * ... + * + * @method render + */ + renderHtml: function() { + var self = this, prefix = self.classPrefix; + + return ( + '
    ' + + '
     
    ' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/ElementPath.js + +/** + * ElementPath.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.ElementPath + * @extends tinymce.ui.Path + */ +define("tinymce/ui/ElementPath", [ + "tinymce/ui/Path", + "tinymce/EditorManager" +], function(Path, EditorManager) { + return Path.extend({ + postRender: function() { + var self = this, editor = EditorManager.activeEditor; + + function isBogus(elm) { + return elm.nodeType === 1 && (elm.nodeName == "BR" || !!elm.getAttribute('data-mce-bogus')); + } + + self.on('select', function(e) { + var parents = [], node = editor.selection.getNode(), body = editor.getBody(); + + while (node) { + if (!isBogus(node)) { + parents.push(node); + } + + node = node.parentNode; + if (node == body) { + break; + } + } + + editor.focus(); + editor.selection.select(parents[parents.length - 1 - e.index]); + editor.nodeChanged(); + }); + + editor.on('nodeChange', function(e) { + var parents = [], selectionParents = e.parents, i = selectionParents.length; + + while (i--) { + if (!isBogus(selectionParents[i])) { + var args = editor.fire('ResolveName', { + name: selectionParents[i].nodeName.toLowerCase(), + target: selectionParents[i] + }); + + parents.push({name: args.name}); + } + } + + self.data(parents); + }); + + return self._super(); + } + }); +}); + +// Included from: js/tinymce/classes/ui/FormItem.js + +/** + * FormItem.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.FormItem + * @extends tinymce.ui.Container + */ +define("tinymce/ui/FormItem", [ + "tinymce/ui/Container" +], function(Container) { + "use strict"; + + return Container.extend({ + Defaults: { + layout: 'flex', + align: 'center', + defaults: { + flex: 1 + } + }, + + renderHtml: function() { + var self = this, layout = self._layout, prefix = self.classPrefix; + + self.addClass('formitem'); + layout.preRender(self); + + return ( + '
    ' + + (self.settings.title ? ('
    ' + + self.settings.title + '
    ') : '') + + '
    ' + + (self.settings.html || '') + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Form.js + +/** + * Form.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.Form + * @extends tinymce.ui.Container + */ +define("tinymce/ui/Form", [ + "tinymce/ui/Container", + "tinymce/ui/FormItem" +], function(Container, FormItem) { + "use strict"; + + return Container.extend({ + Defaults: { + containerCls: 'form', + layout: 'flex', + direction: 'column', + align: 'stretch', + flex: 1, + padding: 20, + labelGap: 30, + spacing: 10 + }, + + preRender: function() { + var self = this, items = self.items(); + + // Wrap any labeled items in FormItems + items.each(function(ctrl) { + var formItem, label = ctrl.settings.label; + + if (label) { + formItem = new FormItem({ + layout: 'flex', + autoResize: "overflow", + defaults: {flex: 1}, + items: [ + {type: 'label', text: label, flex: 0, forId: ctrl._id} + ] + }); + + formItem.type = 'formitem'; + + if (typeof(ctrl.settings.flex) == "undefined") { + ctrl.settings.flex = 1; + } + + self.replace(ctrl, formItem); + formItem.add(ctrl); + } + }); + }, + + recalcLabels: function() { + var self = this, maxLabelWidth = 0, labels = [], i, labelGap; + + if (self.settings.labelGapCalc === false) { + return; + } + + self.items().filter('formitem').each(function(item) { + var labelCtrl = item.items()[0], labelWidth = labelCtrl.getEl().clientWidth; + + maxLabelWidth = labelWidth > maxLabelWidth ? labelWidth : maxLabelWidth; + labels.push(labelCtrl); + }); + + labelGap = self.settings.labelGap || 0; + + i = labels.length; + while (i--) { + labels[i].settings.minWidth = maxLabelWidth + labelGap; + } + }, + + visible: function(state) { + var val = this._super(state); + + if (state === true && this._rendered) { + this.recalcLabels(); + } + + return val; + }, + + fromJSON: function(data) { + var self = this; + + if (data) { + for (var name in data) { + self.find('#' + name).value(data[name]); + } + } + + return self; + }, + + toJSON: function() { + var self = this, data = {}; + + self.find('*').each(function(ctrl) { + var name = ctrl.name(), value = ctrl.value(); + + if (name && typeof(value) != "undefined") { + data[name] = value; + } + }); + + return data; + }, + + submit: function() { + return this.fire('submit', {data: this.toJSON()}); + }, + + postRender: function() { + var self = this; + + self._super(); + self.recalcLabels(); + self.fromJSON(self.settings.data); + } + }); +}); + +// Included from: js/tinymce/classes/ui/FieldSet.js + +/** + * FieldSet.js + * + * Copyright 2003-2013, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less FieldSet.less + * @class tinymce.ui.FieldSet + * @extends tinymce.ui.Form + */ +define("tinymce/ui/FieldSet", [ + "tinymce/ui/Form" +], function(Form) { + "use strict"; + + return Form.extend({ + Defaults: { + containerCls: 'fieldset', + layout: 'flex', + direction: 'column', + align: 'stretch', + flex: 1, + padding: "25 15 5 15", + labelGap: 30, + spacing: 10, + border: 1 + }, + + renderHtml: function() { + var self = this, layout = self._layout, prefix = self.classPrefix; + + self.preRender(); + layout.preRender(self); + + return ( + '
    ' + + (self.settings.title ? ('' + + self.settings.title + '') : '') + + '
    ' + + (self.settings.html || '') + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/FilePicker.js + +/** + * FilePicker.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/*global tinymce:true */ + +/** + * .. + * + * @class tinymce.ui.FilePicker + * @extends tinymce.ui.ComboBox + */ +define("tinymce/ui/FilePicker", [ + "tinymce/ui/ComboBox" +], function(ComboBox) { + "use strict"; + + return ComboBox.extend({ + init: function(settings) { + var self = this, editor = tinymce.activeEditor, fileBrowserCallback; + + settings.spellcheck = false; + + fileBrowserCallback = editor.settings.file_browser_callback; + if (fileBrowserCallback) { + settings.icon = 'browse'; + + settings.onaction = function() { + fileBrowserCallback( + self.getEl('inp').id, + self.getEl('inp').value, + settings.filetype, + window + ); + }; + } + + self._super(settings); + } + }); +}); + +// Included from: js/tinymce/classes/ui/FitLayout.js + +/** + * FitLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * This class jada jada. + * + * var x = 3; + * + * @-x-less FitLayout.less + * @class tinymce.ui.FitLayout + * @extends tinymce.ui.AbsoluteLayout + */ +define("tinymce/ui/FitLayout", [ + "tinymce/ui/AbsoluteLayout" +], function(AbsoluteLayout) { + "use strict"; + + return AbsoluteLayout.extend({ + recalc: function(container) { + var contLayoutRect = container.layoutRect(), paddingBox = container.paddingBox(); + + container.items().filter(':visible').each(function(ctrl) { + ctrl.layoutRect({ + x: paddingBox.left, + y: paddingBox.top, + w: contLayoutRect.innerW - paddingBox.right - paddingBox.left, + h: contLayoutRect.innerH - paddingBox.top - paddingBox.bottom + }); + + if (ctrl.recalc) { + ctrl.recalc(); + } + }); + } + }); +}); + +// Included from: js/tinymce/classes/ui/FlexLayout.js + +/** + * FlexLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * Settings: + * direction=row|row-reverse|column|column-reverse + * flex= + * align=start|end|center|stretch + * pack=start|end|justify + * + * @class tinymce.ui.layout.FlexLayout + * @extends tinymce.ui.AbsoluteLayout + */ +define("tinymce/ui/FlexLayout", [ + "tinymce/ui/AbsoluteLayout" +], function(AbsoluteLayout) { + "use strict"; + + return AbsoluteLayout.extend({ + recalc: function(container) { + var i, l, items, contLayoutRect, contPaddingBox, contSettings, align, pack, spacing, totalFlex, availableSpace, direction; + var ctrl, ctrlLayoutRect, ctrlSettings, flex, maxSizeItems = [], size, maxSize, ratio, rect, pos, maxAlignEndPos; + var sizeName, minSizeName, posName, maxSizeName, beforeName, innerSizeName, afterName, deltaSizeName, contentSizeName; + var alignAxisName, alignInnerSizeName, alignSizeName, alignMinSizeName, alignMaxSizeName, alignBeforeName, alignAfterName; + var alignDeltaSizeName, alignContentSizeName; + var max = Math.max, min = Math.min; + + // Get container items, properties and settings + items = container.items().filter(':visible'); + contLayoutRect = container.layoutRect(); + contPaddingBox = container._paddingBox; + contSettings = container.settings; + direction = contSettings.direction; + align = contSettings.align; + pack = contSettings.pack; + spacing = contSettings.spacing || 0; + + if (direction == "row-reversed" || direction == "column-reverse") { + items = items.set(items.toArray().reverse()); + direction = direction.split('-')[0]; + } + + // Setup axis variable name for row/column direction since the calculations is the same + if (direction == "column") { + posName = "y"; + sizeName = "h"; + minSizeName = "minH"; + maxSizeName = "maxH"; + innerSizeName = "innerH"; + beforeName = 'top'; + afterName = 'bottom'; + deltaSizeName = "deltaH"; + contentSizeName = "contentH"; + + alignBeforeName = "left"; + alignSizeName = "w"; + alignAxisName = "x"; + alignInnerSizeName = "innerW"; + alignMinSizeName = "minW"; + alignMaxSizeName = "maxW"; + alignAfterName = "right"; + alignDeltaSizeName = "deltaW"; + alignContentSizeName = "contentW"; + } else { + posName = "x"; + sizeName = "w"; + minSizeName = "minW"; + maxSizeName = "maxW"; + innerSizeName = "innerW"; + beforeName = 'left'; + afterName = 'right'; + deltaSizeName = "deltaW"; + contentSizeName = "contentW"; + + alignBeforeName = "top"; + alignSizeName = "h"; + alignAxisName = "y"; + alignInnerSizeName = "innerH"; + alignMinSizeName = "minH"; + alignMaxSizeName = "maxH"; + alignAfterName = "bottom"; + alignDeltaSizeName = "deltaH"; + alignContentSizeName = "contentH"; + } + + // Figure out total flex, availableSpace and collect any max size elements + availableSpace = contLayoutRect[innerSizeName] - contPaddingBox[beforeName] - contPaddingBox[beforeName]; + maxAlignEndPos = totalFlex = 0; + for (i = 0, l = items.length; i < l; i++) { + ctrl = items[i]; + ctrlLayoutRect = ctrl.layoutRect(); + ctrlSettings = ctrl.settings; + flex = ctrlSettings.flex; + availableSpace -= (i < l - 1 ? spacing : 0); + + if (flex > 0) { + totalFlex += flex; + + // Flexed item has a max size then we need to check if we will hit that size + if (ctrlLayoutRect[maxSizeName]) { + maxSizeItems.push(ctrl); + } + + ctrlLayoutRect.flex = flex; + } + + availableSpace -= ctrlLayoutRect[minSizeName]; + + // Calculate the align end position to be used to check for overflow/underflow + size = contPaddingBox[alignBeforeName] + ctrlLayoutRect[alignMinSizeName] + contPaddingBox[alignAfterName]; + if (size > maxAlignEndPos) { + maxAlignEndPos = size; + } + } + + // Calculate minW/minH + rect = {}; + if (availableSpace < 0) { + rect[minSizeName] = contLayoutRect[minSizeName] - availableSpace + contLayoutRect[deltaSizeName]; + } else { + rect[minSizeName] = contLayoutRect[innerSizeName] - availableSpace + contLayoutRect[deltaSizeName]; + } + + rect[alignMinSizeName] = maxAlignEndPos + contLayoutRect[alignDeltaSizeName]; + + rect[contentSizeName] = contLayoutRect[innerSizeName] - availableSpace; + rect[alignContentSizeName] = maxAlignEndPos; + rect.minW = min(rect.minW, contLayoutRect.maxW); + rect.minH = min(rect.minH, contLayoutRect.maxH); + rect.minW = max(rect.minW, contLayoutRect.startMinWidth); + rect.minH = max(rect.minH, contLayoutRect.startMinHeight); + + // Resize container container if minSize was changed + if (contLayoutRect.autoResize && (rect.minW != contLayoutRect.minW || rect.minH != contLayoutRect.minH)) { + rect.w = rect.minW; + rect.h = rect.minH; + + container.layoutRect(rect); + this.recalc(container); + + // Forced recalc for example if items are hidden/shown + if (container._lastRect === null) { + var parentCtrl = container.parent(); + if (parentCtrl) { + parentCtrl._lastRect = null; + parentCtrl.recalc(); + } + } + + return; + } + + // Handle max size elements, check if they will become to wide with current options + ratio = availableSpace / totalFlex; + for (i = 0, l = maxSizeItems.length; i < l; i++) { + ctrl = maxSizeItems[i]; + ctrlLayoutRect = ctrl.layoutRect(); + maxSize = ctrlLayoutRect[maxSizeName]; + size = ctrlLayoutRect[minSizeName] + Math.ceil(ctrlLayoutRect.flex * ratio); + + if (size > maxSize) { + availableSpace -= (ctrlLayoutRect[maxSizeName] - ctrlLayoutRect[minSizeName]); + totalFlex -= ctrlLayoutRect.flex; + ctrlLayoutRect.flex = 0; + ctrlLayoutRect.maxFlexSize = maxSize; + } else { + ctrlLayoutRect.maxFlexSize = 0; + } + } + + // Setup new ratio, target layout rect, start position + ratio = availableSpace / totalFlex; + pos = contPaddingBox[beforeName]; + rect = {}; + + // Handle pack setting moves the start position to end, center + if (totalFlex === 0) { + if (pack == "end") { + pos = availableSpace + contPaddingBox[beforeName]; + } else if (pack == "center") { + pos = Math.round( + (contLayoutRect[innerSizeName] / 2) - ((contLayoutRect[innerSizeName] - availableSpace) / 2) + ) + contPaddingBox[beforeName]; + + if (pos < 0) { + pos = contPaddingBox[beforeName]; + } + } else if (pack == "justify") { + pos = contPaddingBox[beforeName]; + spacing = Math.floor(availableSpace / (items.length - 1)); + } + } + + // Default aligning (start) the other ones needs to be calculated while doing the layout + rect[alignAxisName] = contPaddingBox[alignBeforeName]; + + // Start laying out controls + for (i = 0, l = items.length; i < l; i++) { + ctrl = items[i]; + ctrlLayoutRect = ctrl.layoutRect(); + size = ctrlLayoutRect.maxFlexSize || ctrlLayoutRect[minSizeName]; + + // Align the control on the other axis + if (align === "center") { + rect[alignAxisName] = Math.round((contLayoutRect[alignInnerSizeName] / 2) - (ctrlLayoutRect[alignSizeName] / 2)); + } else if (align === "stretch") { + rect[alignSizeName] = max( + ctrlLayoutRect[alignMinSizeName] || 0, + contLayoutRect[alignInnerSizeName] - contPaddingBox[alignBeforeName] - contPaddingBox[alignAfterName] + ); + rect[alignAxisName] = contPaddingBox[alignBeforeName]; + } else if (align === "end") { + rect[alignAxisName] = contLayoutRect[alignInnerSizeName] - ctrlLayoutRect[alignSizeName] - contPaddingBox.top; + } + + // Calculate new size based on flex + if (ctrlLayoutRect.flex > 0) { + size += Math.ceil(ctrlLayoutRect.flex * ratio); + } + + rect[sizeName] = size; + rect[posName] = pos; + ctrl.layoutRect(rect); + + // Recalculate containers + if (ctrl.recalc) { + ctrl.recalc(); + } + + // Move x/y position + pos += size + spacing; + } + } + }); +}); + +// Included from: js/tinymce/classes/ui/FlowLayout.js + +/** + * FlowLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less FlowLayout.less + * @class tinymce.ui.FlowLayout + * @extends tinymce.ui.Layout + */ +define("tinymce/ui/FlowLayout", [ + "tinymce/ui/Layout" +], function(Layout) { + return Layout.extend({ + Defaults: { + containerClass: 'flow-layout', + controlClass: 'flow-layout-item', + endClass : 'break' + }, + + recalc: function(container) { + container.items().filter(':visible').each(function(ctrl) { + if (ctrl.recalc) { + ctrl.recalc(); + } + }); + } + }); +}); + +// Included from: js/tinymce/classes/ui/FormatControls.js + +/** + * FormatControls.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * + * @class tinymce.ui.FormatControls + */ +define("tinymce/ui/FormatControls", [ + "tinymce/ui/Factory", + "tinymce/ui/Control", + "tinymce/ui/FloatPanel", + "tinymce/util/Tools", + "tinymce/EditorManager" +], function(Factory, Control, FloatPanel, Tools, EditorManager) { + var each = Tools.each; + + Control.translate = function(text) { + return EditorManager.translate(text); + }; + + // Generates a preview for a format + function getPreviewCss(editor, format) { + var name, previewElm, dom = editor.dom, previewCss = '', parentFontSize, previewStyles; + + previewStyles = editor.settings.preview_styles; + + // No preview forced + if (previewStyles === false) { + return ''; + } + + // Default preview + if (!previewStyles) { + previewStyles = 'font-family font-size font-weight text-decoration text-transform color background-color border border-radius'; + } + + // Removes any variables since these can't be previewed + function removeVars(val) { + return val.replace(/%(\w+)/g, ''); + } + + // Create block/inline element to use for preview + format = editor.formatter.get(format); + if (!format) { + return; + } + + format = format[0]; + name = format.block || format.inline || 'span'; + previewElm = dom.create(name); + + // Add format styles to preview element + each(format.styles, function(value, name) { + value = removeVars(value); + + if (value) { + dom.setStyle(previewElm, name, value); + } + }); + + // Add attributes to preview element + each(format.attributes, function(value, name) { + value = removeVars(value); + + if (value) { + dom.setAttrib(previewElm, name, value); + } + }); + + // Add classes to preview element + each(format.classes, function(value) { + value = removeVars(value); + + if (!dom.hasClass(previewElm, value)) { + dom.addClass(previewElm, value); + } + }); + + editor.fire('PreviewFormats'); + + // Add the previewElm outside the visual area + dom.setStyles(previewElm, {position: 'absolute', left: -0xFFFF}); + editor.getBody().appendChild(previewElm); + + // Get parent container font size so we can compute px values out of em/% for older IE:s + parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true); + parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0; + + each(previewStyles.split(' '), function(name) { + var value = dom.getStyle(previewElm, name, true); + + // If background is transparent then check if the body has a background color we can use + if (name == 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) { + value = dom.getStyle(editor.getBody(), name, true); + + // Ignore white since it's the default color, not the nicest fix + // TODO: Fix this by detecting runtime style + if (dom.toHex(value).toLowerCase() == '#ffffff') { + return; + } + } + + if (name == 'color') { + // Ignore black since it's the default color, not the nicest fix + // TODO: Fix this by detecting runtime style + if (dom.toHex(value).toLowerCase() == '#000000') { + return; + } + } + + // Old IE won't calculate the font size so we need to do that manually + if (name == 'font-size') { + if (/em|%$/.test(value)) { + if (parentFontSize === 0) { + return; + } + + // Convert font size from em/% to px + value = parseFloat(value, 10) / (/%$/.test(value) ? 100 : 1); + value = (value * parentFontSize) + 'px'; + } + } + + if (name == "border" && value) { + previewCss += 'padding:0 2px;'; + } + + previewCss += name + ':' + value + ';'; + }); + + editor.fire('AfterPreviewFormats'); + + //previewCss += 'line-height:normal'; + + dom.remove(previewElm); + + return previewCss; + } + + function createFormats(formats) { + formats = formats.split(';'); + + var i = formats.length; + while (i--) { + formats[i] = formats[i].split('='); + } + + return formats; + } + + EditorManager.on('AddEditor', function(e) { + var editor = e.editor, formatMenu; + + function createFormatMenu() { + var count = 0, newFormats = []; + + var defaultStyleFormats = [ + {title: 'Headers', items: [ + {title: 'Header 1', format: 'h1'}, + {title: 'Header 2', format: 'h2'}, + {title: 'Header 3', format: 'h3'}, + {title: 'Header 4', format: 'h4'}, + {title: 'Header 5', format: 'h5'}, + {title: 'Header 6', format: 'h6'} + ]}, + + {title: 'Inline', items: [ + {title: 'Bold', icon: 'bold', format: 'bold'}, + {title: 'Italic', icon: 'italic', format: 'italic'}, + {title: 'Underline', icon: 'underline', format: 'underline'}, + {title: 'Strikethrough', icon: 'strikethrough', format: 'strikethrough'}, + {title: 'Superscript', icon: 'superscript', format: 'superscript'}, + {title: 'Subscript', icon: 'subscript', format: 'subscript'}, + {title: 'Code', icon: 'code', format: 'code'} + ]}, + + {title: 'Blocks', items: [ + {title: 'Paragraph', format: 'p'}, + {title: 'Blockquote', format: 'blockquote'}, + {title: 'Div', format: 'div'}, + {title: 'Pre', format: 'pre'} + ]}, + + {title: 'Alignment', items: [ + {title: 'Left', icon: 'alignleft', format: 'alignleft'}, + {title: 'Center', icon: 'aligncenter', format: 'aligncenter'}, + {title: 'Right', icon: 'alignright', format: 'alignright'}, + {title: 'Justify', icon: 'alignjustify', format: 'alignjustify'} + ]} + ]; + + function createMenu(formats) { + var menu = []; + + if (!formats) { + return; + } + + each(formats, function(format) { + var menuItem = { + text: format.title, + icon: format.icon + }; + + if (format.items) { + menuItem.menu = createMenu(format.items); + } else { + var formatName = format.format || "custom" + count++; + + if (!format.format) { + format.name = formatName; + newFormats.push(format); + } + + menuItem.textStyle = function() { + return getPreviewCss(editor, formatName); + }; + + menuItem.onclick = function() { + editor.execCommand('mceToggleFormat', false, formatName); + }; + } + + menu.push(menuItem); + }); + + return menu; + } + + editor.on('init', function() { + each(newFormats, function(format) { + editor.formatter.register(format.name, format); + }); + }); + + var menu = createMenu(editor.settings.style_formats || defaultStyleFormats); + + return menu; + } + + formatMenu = createFormatMenu(); + + // Simple format controls : + each({ + bold: 'Bold', + italic: 'Italic', + underline: 'Underline', + strikethrough: 'Strikethrough', + subscript: 'Subscript', + superscript: 'Superscript' + }, function(text, name) { + editor.addButton(name, { + tooltip: text, + onPostRender: function() { + var self = this; + + // TODO: Fix this + if (editor.formatter) { + editor.formatter.formatChanged(name, function(state) { + self.active(state); + }); + } else { + editor.on('init', function() { + editor.formatter.formatChanged(name, function(state) { + self.active(state); + }); + }); + } + }, + onclick: function() { + editor.execCommand('mceToggleFormat', false, name); + } + }); + }); + + // Simple command controls :[,] + each({ + outdent: ['Decrease indent', 'Outdent'], + indent: ['Increase indent', 'Indent'], + cut: ['Cut', 'Cut'], + copy: ['Copy', 'Copy'], + paste: ['Paste', 'Paste'], + help: ['Help', 'mceHelp'], + selectall: ['Select all', 'SelectAll'], + hr: ['Insert horizontal rule', 'InsertHorizontalRule'], + removeformat: ['Clear formatting', 'RemoveFormat'], + visualaid: ['Visual aids', 'mceToggleVisualAid'], + newdocument: ['New document', 'mceNewDocument'] + }, function(item, name) { + editor.addButton(name, { + tooltip: item[0], + cmd: item[1] + }); + }); + + // Simple command controls with format state + each({ + blockquote: ['Toggle blockquote', 'mceBlockQuote'], + numlist: ['Numbered list', 'InsertOrderedList'], + bullist: ['Bulleted list', 'InsertUnorderedList'], + subscript: ['Subscript', 'Subscript'], + superscript: ['Superscript', 'Superscript'], + alignleft: ['Align left', 'JustifyLeft'], + aligncenter: ['Align center', 'JustifyCenter'], + alignright: ['Align right', 'JustifyRight'], + alignjustify: ['Justify', 'JustifyFull'] + }, function(item, name) { + editor.addButton(name, { + tooltip: item[0], + cmd: item[1], + onPostRender: function() { + var self = this; + + // TODO: Fix this + if (editor.formatter) { + editor.formatter.formatChanged(name, function(state) { + self.active(state); + }); + } else { + editor.on('init', function() { + editor.formatter.formatChanged(name, function(state) { + self.active(state); + }); + }); + } + } + }); + }); + + function hasUndo() { + return editor.undoManager ? editor.undoManager.hasUndo() : false; + } + + function hasRedo() { + return editor.undoManager ? editor.undoManager.hasRedo() : false; + } + + function toggleUndoState() { + var self = this; + + self.disabled(!hasUndo()); + editor.on('Undo Redo AddUndo', function() { + self.disabled(!hasUndo()); + }); + } + + function toggleRedoState() { + var self = this; + + self.disabled(!hasRedo()); + editor.on('Undo Redo AddUndo', function() { + self.disabled(!hasRedo()); + }); + } + + function toggleVisualAidState() { + var self = this; + + editor.on('VisualAid', function(e) { + self.active(e.hasVisual); + }); + + self.active(editor.hasVisual); + } + + editor.addButton('forecolor', { + type: 'colorbutton', + tooltip: 'Text color', + onselect: function(e) { + editor.execCommand('ForeColor', false, e.value); + } + }); + + editor.addButton('backcolor', { + type: 'colorbutton', + tooltip: 'Background color', + onselect: function(e) { + editor.execCommand('HiliteColor', false, e.value); + } + }); + + editor.addButton('undo', { + tooltip: 'Undo', + onPostRender: toggleUndoState, + cmd: 'undo' + }); + + editor.addButton('redo', { + tooltip: 'Redo', + onPostRender: toggleRedoState, + cmd: 'redo' + }); + + editor.addMenuItem('newdocument', { + text: 'New document', + shortcut: 'Ctrl+N', + icon: 'newdocument', + cmd: 'mceNewDocument' + }); + + editor.addMenuItem('undo', { + text: 'Undo', + icon: 'undo', + shortcut: 'Ctrl+Z', + onPostRender: toggleUndoState, + cmd: 'undo' + }); + + editor.addMenuItem('redo', { + text: 'Redo', + icon: 'redo', + shortcut: 'Ctrl+Y', + onPostRender: toggleRedoState, + cmd: 'redo' + }); + + editor.addMenuItem('visualaid', { + text: 'Visual aids', + selectable: true, + onPostRender: toggleVisualAidState, + cmd: 'mceToggleVisualAid' + }); + + each({ + cut: ['Cut', 'Cut', 'Ctrl+X'], + copy: ['Copy', 'Copy', 'Ctrl+C'], + paste: ['Paste', 'Paste', 'Ctrl+V'], + selectall: ['Select all', 'SelectAll', 'Ctrl+A'], + bold: ['Bold', 'Bold', 'Ctrl+B'], + italic: ['Italic', 'Italic', 'Ctrl+I'], + underline: ['Underline', 'Underline'], + strikethrough: ['Strikethrough', 'Strikethrough'], + subscript: ['Subscript', 'Subscript'], + superscript: ['Superscript', 'Superscript'], + removeformat: ['Clear formatting', 'RemoveFormat'] + }, function(item, name) { + editor.addMenuItem(name, { + text: item[0], + icon: name, + shortcut: item[2], + cmd: item[1] + }); + }); + + editor.on('mousedown', function() { + FloatPanel.hideAll(); + }); + + function toggleFormat(e) { + if (e.control.settings.format) { + EditorManager.activeEditor.execCommand('mceToggleFormat', false, e.control.settings.format); + } + } + + Factory.add('styleselect', function(settings) { + var menu = [].concat(formatMenu); + + /* + menu.push({text: '-'}); + menu.push({ + text: 'Remove formatting', + icon: 'removeformat', + onclick: function() { + editor.execCommand('RemoveFormat'); + } + }); + */ + + return Factory.create('menubutton', Tools.extend({ + text: 'Formats', + menu: menu + }, settings)); + }); + + Factory.add('formatselect', function(settings) { + var items = [], blocks = createFormats( + 'Paragraph=p;' + + 'Address=address;' + + 'Pre=pre;' + + 'Header 1=h1;' + + 'Header 2=h2;' + + 'Header 3=h3;' + + 'Header 4=h4;' + + 'Header 5=h5;' + + 'Header 6=h6' + ); + + each(blocks, function(block) { + items.push({ + text: block[0], + format: block[1], + textStyle: function() { + return getPreviewCss(editor, block[1]); + } + }); + }); + + return Factory.create('listbox', Tools.extend({ + text: blocks[0][0], + menu: items, + onclick: toggleFormat + }, settings)); + }); + + Factory.add('fontselect', function(settings) { + var items = [], fonts = createFormats( + 'Andale Mono=andale mono,times;' + + 'Arial=arial,helvetica,sans-serif;' + + 'Arial Black=arial black,avant garde;' + + 'Book Antiqua=book antiqua,palatino;' + + 'Comic Sans MS=comic sans ms,sans-serif;' + + 'Courier New=courier new,courier;' + + 'Georgia=georgia,palatino;' + + 'Helvetica=helvetica;' + + 'Impact=impact,chicago;' + + 'Symbol=symbol;' + + 'Tahoma=tahoma,arial,helvetica,sans-serif;' + + 'Terminal=terminal,monaco;' + + 'Times New Roman=times new roman,times;' + + 'Trebuchet MS=trebuchet ms,geneva;' + + 'Verdana=verdana,geneva;' + + 'Webdings=webdings;' + + 'Wingdings=wingdings,zapf dingbats' + ); + + each(fonts, function(font) { + items.push({ + text: font[0], + format: font[1], + style: font[1].indexOf('dings') == -1 ? 'font-family:' + font[1] : '' + }); + }); + + return Factory.create('listbox', Tools.extend({ + text: 'Font Family', + menu: items, + onclick: function(e) { + if (e.control.settings.format) { + EditorManager.activeEditor.execCommand('FontName', false, e.control.settings.format); + } + } + }, settings)); + }); + + Factory.add('fontsizeselect', function(settings) { + var items = []; + + each('8pt 10pt 12pt 14pt 18pt 24pt 36pt'.split(' '), function(item) { + items.push({text: item, format: item}); + }); + + return Factory.create('listbox', Tools.extend({ + text: 'Font Sizes', + menu: items, + onclick: function(e) { + if (e.control.settings.format) { + EditorManager.activeEditor.execCommand('FontSize', false, e.control.settings.format); + } + } + }, settings)); + }); + + editor.addMenuItem('formats', { + text: 'Formats', + menu: formatMenu + }); + }); +}); + +// Included from: js/tinymce/classes/ui/GridLayout.js + +/** + * GridLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.GridLayout + * @extends tinymce.ui.AbsoluteLayout + */ +define("tinymce/ui/GridLayout", [ + "tinymce/ui/AbsoluteLayout" +], function(AbsoluteLayout) { + "use strict"; + + return AbsoluteLayout.extend({ + recalc: function(container) { + var settings = container.settings, rows, cols, items, contLayoutRect, width, height, rect, + ctrlLayoutRect, ctrl, x, y, posX, posY, ctrlSettings, contPaddingBox, align, spacingH, spacingV, alignH, alignV, maxX, maxY, + colWidths = [], rowHeights = [], ctrlMinWidth, ctrlMinHeight, alignX, alignY, availableWidth, availableHeight; + + // Get layout settings + settings = container.settings; + items = container.items().filter(':visible'); + contLayoutRect = container.layoutRect(); + cols = settings.columns || Math.ceil(Math.sqrt(items.length)); + rows = Math.ceil(items.length / cols); + spacingH = settings.spacingH || settings.spacing || 0; + spacingV = settings.spacingV || settings.spacing || 0; + alignH = settings.alignH || settings.align; + alignV = settings.alignV || settings.align; + contPaddingBox = container._paddingBox; + + // Zero padd columnWidths + for (x = 0; x < cols; x++) { + colWidths.push(0); + } + + // Zero padd rowHeights + for (y = 0; y < rows; y++) { + rowHeights.push(0); + } + + // Calculate columnWidths and rowHeights + for (y = 0; y < rows; y++) { + for (x = 0; x < cols; x++) { + ctrl = items[y * cols + x]; + + // Out of bounds + if (!ctrl) { + break; + } + + ctrlLayoutRect = ctrl.layoutRect(); + ctrlMinWidth = ctrlLayoutRect.minW; + ctrlMinHeight = ctrlLayoutRect.minH; + + colWidths[x] = ctrlMinWidth > colWidths[x] ? ctrlMinWidth : colWidths[x]; + rowHeights[y] = ctrlMinHeight > rowHeights[y] ? ctrlMinHeight : rowHeights[y]; + } + } + + // Calculate maxX + availableWidth = contLayoutRect.innerW - contPaddingBox.left - contPaddingBox.right; + for (maxX = 0, x = 0; x < cols; x++) { + maxX += colWidths[x] + (x > 0 ? spacingH : 0); + availableWidth -= (x > 0 ? spacingH : 0) + colWidths[x]; + } + + // Calculate maxY + availableHeight = contLayoutRect.innerH - contPaddingBox.top - contPaddingBox.bottom; + for (maxY = 0, y = 0; y < rows; y++) { + maxY += rowHeights[y] + (y > 0 ? spacingV : 0); + availableHeight -= (y > 0 ? spacingV : 0) + rowHeights[y]; + } + + maxX += contPaddingBox.left + contPaddingBox.right; + maxY += contPaddingBox.top + contPaddingBox.bottom; + + // Calculate minW/minH + rect = {}; + rect.minW = maxX + (contLayoutRect.w - contLayoutRect.innerW); + rect.minH = maxY + (contLayoutRect.h - contLayoutRect.innerH); + + rect.contentW = rect.minW - contLayoutRect.deltaW; + rect.contentH = rect.minH - contLayoutRect.deltaH; + rect.minW = Math.min(rect.minW, contLayoutRect.maxW); + rect.minH = Math.min(rect.minH, contLayoutRect.maxH); + rect.minW = Math.max(rect.minW, contLayoutRect.startMinWidth); + rect.minH = Math.max(rect.minH, contLayoutRect.startMinHeight); + + // Resize container container if minSize was changed + if (contLayoutRect.autoResize && (rect.minW != contLayoutRect.minW || rect.minH != contLayoutRect.minH)) { + rect.w = rect.minW; + rect.h = rect.minH; + + container.layoutRect(rect); + this.recalc(container); + + // Forced recalc for example if items are hidden/shown + if (container._lastRect === null) { + var parentCtrl = container.parent(); + if (parentCtrl) { + parentCtrl._lastRect = null; + parentCtrl.recalc(); + } + } + + return; + } + + // Update contentW/contentH so absEnd moves correctly + if (contLayoutRect.autoResize) { + rect = container.layoutRect(rect); + rect.contentW = rect.minW - contLayoutRect.deltaW; + rect.contentH = rect.minH - contLayoutRect.deltaH; + } + + var flexV; + + if (settings.packV == 'start') { + flexV = 0; + } else { + flexV = availableHeight > 0 ? Math.floor(availableHeight / rows) : 0; + } + + // Calculate totalFlex + var totalFlex = 0; + var flexWidths = settings.flexWidths; + if (flexWidths) { + for (x = 0; x < flexWidths.length; x++) { + totalFlex += flexWidths[x]; + } + } else { + totalFlex = cols; + } + + // Calculate new column widths based on flex values + var ratio = availableWidth / totalFlex; + for (x = 0; x < cols; x++) { + colWidths[x] += flexWidths ? Math.ceil(flexWidths[x] * ratio) : ratio; + } + + // Move/resize controls + posY = contPaddingBox.top; + for (y = 0; y < rows; y++) { + posX = contPaddingBox.left; + height = rowHeights[y] + flexV; + + for (x = 0; x < cols; x++) { + ctrl = items[y * cols + x]; + + // No more controls to render then break + if (!ctrl) { + break; + } + + // Get control settings and calculate x, y + ctrlSettings = ctrl.settings; + ctrlLayoutRect = ctrl.layoutRect(); + width = colWidths[x]; + alignX = alignY = 0; + ctrlLayoutRect.x = posX; + ctrlLayoutRect.y = posY; + + // Align control horizontal + align = ctrlSettings.alignH || alignH; + if (align == "center") { + ctrlLayoutRect.x = posX + (width / 2) - (ctrlLayoutRect.w / 2); + } else if (align == "right") { + ctrlLayoutRect.x = posX + width - ctrlLayoutRect.w; + } else if (align == "stretch") { + ctrlLayoutRect.w = width; + } + + // Align control vertical + align = ctrlSettings.alignV || alignV; + if (align == "center") { + ctrlLayoutRect.y = posY + (height / 2) - (ctrlLayoutRect.h / 2); + } else if (align == "bottom") { + ctrlLayoutRect.y = posY + height - ctrlLayoutRect.h; + } else if (align == "stretch") { + ctrlLayoutRect.h = height; + } + + ctrl.layoutRect(ctrlLayoutRect); + + posX += width + spacingH; + + if (ctrl.recalc) { + ctrl.recalc(); + } + } + + posY += height + spacingV; + } + } + }); +}); + +// Included from: js/tinymce/classes/ui/Iframe.js + +/** + * Iframe.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/*jshint scripturl:true */ + +/** + * .. + * + * @-x-less Iframe.less + * @class tinymce.ui.Iframe + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/Iframe", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + renderHtml: function() { + var self = this; + + self.addClass('iframe'); + self.canFocus = false; + + return ( + '' + ); + }, + + src: function(src) { + this.getEl().src = src; + }, + + html: function(html) { + this.getEl().contentWindow.document.body.innerHTML = html; + return this; + } + }); +}); + +// Included from: js/tinymce/classes/ui/Label.js + +/** + * Label.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Label.less + * @class tinymce.ui.Label + * @extends tinymce.ui.Control + */ +define("tinymce/ui/Label", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('widget'); + self.addClass('label'); + + if (settings.multiline) { + self.addClass('autoscroll'); + } + + if (settings.strong) { + self.addClass('strong'); + } + }, + + initLayoutRect: function() { + var self = this, layoutRect = self._super(); + + if (self.settings.multiline) { + // Check if the text fits within maxW if not then try word wrapping it + if (self.getEl().offsetWidth > layoutRect.maxW) { + layoutRect.minW = layoutRect.maxW; + self.addClass('multiline'); + } + + self.getEl().style.width = layoutRect.minW + 'px'; + layoutRect.startMinH = layoutRect.h = layoutRect.minH = Math.min(layoutRect.maxH, self.getEl().offsetHeight); + } + + return layoutRect; + }, + + disabled: function(state) { + var self = this, undef; + + if (state !== undef) { + self.toggleClass('label-disabled', state); + + if (self._rendered) { + self.getEl()[0].className = self.classes(); + } + } + + return self._super(state); + }, + + repaint: function() { + var self = this; + + if (!self.settings.multiline) { + self.getEl().style.lineHeight = self.layoutRect().h + 'px'; + } + + return self._super(); + }, + + text: function(text) { + var self = this; + + if (self._rendered && text) { + self.getEl().innerHTML = self.encode(text); + } + + return self._super(text); + }, + + /** + * ... + * + * @method render + */ + renderHtml: function() { + var self = this, forId = self.settings.forId; + + return ( + '' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Toolbar.js + +/** + * Toolbar.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.Toolbar + * @extends tinymce.ui.Container + */ +define("tinymce/ui/Toolbar", [ + "tinymce/ui/Container", + "tinymce/ui/KeyboardNavigation" +], function(Container, KeyboardNavigation) { + "use strict"; + + return Container.extend({ + Defaults: { + role: 'toolbar', + layout: 'flow' + }, + + init: function(settings) { + var self = this; + + self._super(settings); + self.addClass('toolbar'); + }, + + postRender: function() { + var self = this; + + self.items().addClass('toolbar-item'); + + self.keyNav = new KeyboardNavigation({ + root: self, + enableLeftRight: true + }); + + return self._super(); + } + }); +}); + +// Included from: js/tinymce/classes/ui/MenuBar.js + +/** + * MenuBar.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less MenuBar.less + * @class tinymce.ui.MenuBar + * @extends tinymce.ui.Container + */ +define("tinymce/ui/MenuBar", [ + "tinymce/ui/Toolbar" +], function(Toolbar) { + "use strict"; + + return Toolbar.extend({ + Defaults: { + role: 'menubar', + containerCls: 'menubar', + defaults: { + type: 'menubutton' + } + } + }); +}); + +// Included from: js/tinymce/classes/ui/MenuButton.js + +/** + * MenuButton.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less MenuButton.less + * @class tinymce.ui.MenuButton + * @extends tinymce.ui.Button + */ +define("tinymce/ui/MenuButton", [ + "tinymce/ui/Button", + "tinymce/ui/Factory", + "tinymce/ui/MenuBar" +], function(Button, Factory, MenuBar) { + "use strict"; + + // TODO: Maybe add as some global function + function isChildOf(node, parent) { + while (node) { + if (parent === node) { + return true; + } + + node = node.parentNode; + } + + return false; + } + + var MenuButton = Button.extend({ + init: function(settings) { + var self = this; + + self._renderOpen = true; + self._super(settings); + + self.addClass('menubtn'); + + self.aria('haspopup', true); + self.hasPopup = true; + }, + + showMenu: function() { + var self = this, settings = self.settings, menu; + + if (!self.menu) { + menu = settings.menu || []; + + // Is menu array then auto constuct menu control + if (menu.length) { + menu = { + type: 'menu', + items: menu + }; + } else { + menu.type = menu.type || 'menu'; + } + + self.menu = Factory.create(menu).parent(self).renderTo(self.getContainerElm()); + self.fire('createmenu'); + self.menu.reflow(); + self.menu.on('cancel', function(e) { + if (e.control === self.menu) { + self.focus(); + } + }); + + self.menu.on('show hide', function(e) { + if (e.control == self.menu) { + self.activeMenu(e.type == 'show'); + } + }).fire('show'); + + self.aria('expanded', true); + } + + self.menu.show(); + self.menu.layoutRect({w: self.layoutRect().w}); + self.menu.moveRel(self.getEl(), 'bl-tl'); + }, + + hideMenu: function() { + var self = this; + + if (self.menu) { + self.menu.items().each(function(item) { + if (item.hideMenu) { + item.hideMenu(); + } + }); + + self.menu.hide(); + self.aria('expanded', false); + } + }, + + activeMenu: function(state) { + this.toggleClass('active', state); + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; + + self.aria('role', self.parent() instanceof MenuBar ? 'menuitem' : 'button'); + + return ( + '
    ' + + '' + + '
    ' + ); + }, + + postRender: function() { + var self = this; + + self.on('click', function(e) { + if (e.control === self && isChildOf(e.target, self.getEl())) { + self.showMenu(); + + if (e.keyboard) { + self.menu.items()[0].focus(); + } + } + }); + + self.on('mouseenter', function(e) { + var overCtrl = e.control, parent = self.parent(), hasVisibleSiblingMenu; + + if (overCtrl && parent && overCtrl instanceof MenuButton && overCtrl.parent() == parent) { + parent.items().filter('MenuButton').each(function(ctrl) { + if (ctrl.hideMenu && ctrl != overCtrl) { + if (ctrl.menu && ctrl.menu.visible()) { + hasVisibleSiblingMenu = true; + } + + ctrl.hideMenu(); + } + }); + + if (hasVisibleSiblingMenu) { + overCtrl.showMenu(); + } + } + }); + + return self._super(); + }, + + text: function(text) { + var self = this, i, children; + + if (self._rendered) { + children = self.getEl('open').childNodes; + for (i = 0; i < children.length; i++) { + if (children[i].nodeType == 3) { + children[i].data = text; + } + } + } + + return this._super(text); + }, + + remove: function() { + this._super(); + + if (this.menu) { + this.menu.remove(); + } + } + }); + + return MenuButton; +}); + +// Included from: js/tinymce/classes/ui/ListBox.js + +/** + * ListBox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ListBox.less + * @class tinymce.ui.ListBox + * @extends tinymce.ui.MenuButton + */ +define("tinymce/ui/ListBox", [ + "tinymce/ui/MenuButton" +], function(MenuButton) { + "use strict"; + + return MenuButton.extend({ + init: function(settings) { + var self = this, values, i, selected, selectedText; + + self._values = values = settings.values; + if (values) { + for (i = 0; i < values.length; i++) { + selected = values[i].selected || settings.value === values[i].value; + + if (selected) { + selectedText = selectedText || values[i].text; + self._value = values[i].value; + } + } + + settings.menu = values; + } + + settings.text = settings.text || selectedText || values[0].text; + + self._super(settings); + self.addClass('listbox'); + + self.on('select', function(e) { + if (settings.multiple) { + e.control.active(!e.control.active()); + } else { + self.value(e.control.settings.value); + } + }); + }, + + value: function(value) { + var self = this, active, selectedText, menu, i; + + if (typeof(value) != "undefined") { + if (self.menu) { + self.menu.items().each(function(ctrl) { + active = ctrl.value() === value; + + if (active) { + selectedText = selectedText || ctrl.text(); + } + + ctrl.active(active); + }); + } else { + menu = self.settings.menu; + for (i = 0; i < menu.length; i++) { + active = menu[i].value == value; + + if (active) { + selectedText = selectedText || menu[i].text; + } + + menu[i].active = active; + } + } + + self.text(selectedText); + } + + return self._super(value); + } + }); +}); + +// Included from: js/tinymce/classes/ui/MenuItem.js + +/** + * MenuItem.js + * + * Copyright 2003-2013, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less MenuItem.less + * @class tinymce.ui.MenuItem + * @extends tinymce.ui.Control + */ +define("tinymce/ui/MenuItem", [ + "tinymce/ui/Widget", + "tinymce/ui/Factory" +], function(Widget, Factory) { + "use strict"; + + return Widget.extend({ + Defaults: { + border: 0, + role: 'menuitem' + }, + + init: function(settings) { + var self = this; + + self.hasPopup = true; + + self._super(settings); + + settings = self.settings; + + self.addClass('menu-item'); + + if (settings.menu) { + self.addClass('menu-item-expand'); + } + + if (self._text === '-' || self._text === '|') { + self.addClass('menu-item-sep'); + self.aria('role', 'separator'); + self.canFocus = false; + self._text = '-'; + } + + if (settings.selectable) { + self.aria('role', 'menuitemcheckbox'); + self.aria('checked', true); + self.addClass('menu-item-checkbox'); + settings.icon = 'selected'; + } + + self.on('mousedown', function(e) { + e.preventDefault(); + }); + + self.on('mouseenter click', function(e) { + if (e.control === self) { + if (!settings.menu && e.type === 'click') { + self.parent().hideAll(); + self.fire('cancel'); + self.fire('select'); + } else { + self.showMenu(); + + if (e.keyboard) { + setTimeout(function() { + self.menu.items()[0].focus(); + }, 0); + } + } + } + }); + + if (settings.menu) { + self.aria('haspopup', true); + } + }, + + hasMenus: function() { + return !!this.settings.menu; + }, + + showMenu: function() { + var self = this, settings = self.settings, menu; + + self.parent().items().each(function(ctrl) { + if (ctrl !== self) { + ctrl.hideMenu(); + } + }); + + if (settings.menu) { + if (!self.menu) { + menu = settings.menu; + + // Is menu array then auto constuct menu control + if (menu.length) { + menu = { + type: 'menu', + items: menu + }; + } else { + menu.type = menu.type || 'menu'; + } + + self.menu = Factory.create(menu).parent(self).renderTo(self.getContainerElm()); + self.menu.reflow(); + self.menu.fire('show'); + self.menu.on('cancel', function() { + self.focus(); + }); + + self.menu.on('hide', function(e) { + if (e.control === self.menu) { + self.removeClass('selected'); + } + }); + } else { + self.menu.show(); + } + + self.menu._parentMenu = self.parent(); + + self.menu.addClass('menu-sub'); + self.menu.moveRel(self.getEl(), 'tr-tl'); + self.addClass('selected'); + self.aria('expanded', true); + } + }, + + hideMenu: function() { + var self = this; + + if (self.menu) { + self.menu.items().each(function(item) { + if (item.hideMenu) { + item.hideMenu(); + } + }); + + self.menu.hide(); + self.aria('expanded', false); + } + + return self; + }, + + renderHtml: function() { + var self = this, id = self._id, settings = self.settings, prefix = self.classPrefix, text = self.encode(self._text); + var icon = self.settings.icon; + + if (icon) { + self.parent().addClass('menu-has-icons'); + } + + icon = prefix + 'ico ' + prefix + 'i-' + (self.settings.icon || 'none'); + + return ( + '
    ' + + (text !== '-' ? ' ' : '') + + (text !== '-' ? '' + text + '' : '') + + (settings.shortcut ? '
    ' + + settings.shortcut + '
    ' : '') + + (settings.menu ? '
    ' : '') + + '
    ' + ); + }, + + postRender: function() { + var self = this, settings = self.settings; + + var textStyle = settings.textStyle; + if (typeof(textStyle) == "function") { + textStyle = textStyle(); + } + + if (textStyle) { + var textElm = self.getEl('text'); + if (textElm) { + textElm.setAttribute('style', textStyle); + } + } + + return self._super(); + }, + + remove: function() { + this._super(); + + if (this.menu) { + this.menu.remove(); + } + } + }); +}); + +// Included from: js/tinymce/classes/ui/Menu.js + +/** + * Menu.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Menu.less + * @class tinymce.ui.Menu + * @extends tinymce.ui.FloatPanel + */ +define("tinymce/ui/Menu", [ + "tinymce/ui/FloatPanel", + "tinymce/ui/KeyboardNavigation", + "tinymce/ui/MenuItem" +], function(FloatPanel, KeyboardNavigation, MenuItem) { + "use strict"; + + var Menu = FloatPanel.extend({ + Defaults: { + defaultType: 'menuitem', + border: 1, + layout: 'stack', + role: 'menu' + }, + + init: function(settings) { + var self = this; + + settings.autohide = true; + + self._super(settings); + self.addClass('menu'); + + self.keyNav = new KeyboardNavigation({ + root: self, + enableUpDown: true, + enableLeftRight: true, + + leftAction: function() { + if (self.parent() instanceof MenuItem) { + self.keyNav.cancel(); + } + }, + + onCancel: function() { + self.fire('cancel', {}, false); + self.hide(); + } + }); + }, + + repaint: function() { + this.toggleClass('menu-align', true); + + this._super(); + + this.getEl().style.height = ''; + this.getEl('body').style.height = ''; + + return this; + }, + + cancel: function() { + var self = this; + + self.hideAll(); + self.fire('cancel'); + self.fire('select'); + }, + + hideAll: function() { + var self = this; + + this.find('menuitem').exec('hideMenu'); + + return self._super(); + }, + + preRender: function() { + var self = this; + + self.items().each(function(ctrl) { + var settings = ctrl.settings; + + if (settings.icon || settings.selectable) { + self._hasIcons = true; + return false; + } + }); + + return self._super(); + } + }); + + return Menu; +}); + +// Included from: js/tinymce/classes/ui/PanelButton.js + +/** + * MenuButton.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.MenuButton + * @extends tinymce.ui.Button + */ +define("tinymce/ui/PanelButton", [ + "tinymce/ui/Button", + "tinymce/ui/FloatPanel" +], function(Button, FloatPanel) { + "use strict"; + + var PanelButton = Button.extend({ + showPanel: function() { + var self = this, settings = self.settings; + + settings.panel.popover = true; + self.active(true); + + if (!self.panel) { + self.panel = new FloatPanel(settings.panel).on('hide', function() { + self.active(false); + }).parent(self).renderTo(self.getContainerElm()).reflow().moveRel(self.getEl(), settings.popoverAlign || 'bc-tc'); + } else { + self.panel.show(); + } + }, + + hidePanel: function() { + var self = this; + + if (self.panel) { + self.panel.hide(); + } + }, + + postRender: function() { + var self = this; + + self.on('click', function(e) { + if (e.control === self) { + self.showPanel(); + } + }); + + return self._super(); + } + }); + + return PanelButton; +}); + +// Included from: js/tinymce/classes/ui/Radio.js + +/** + * Radio.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Radio.less + * @class tinymce.ui.Radio + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/Radio", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + Defaults: { + classes: "radio", + checked: false + }, + + init: function(settings) { + var self = this; + + self._super(settings); + + self.on('click', function(e) { + e.preventDefault(); + + if (!self.disabled() && !self.checked()) { + self.parent().items().filter('radio:checked').exec('checked', false); + self.checked(true); + } + }); + + self.checked(settings.checked); + }, + + checked: function(state) { + var self = this; + + if (typeof state != "undefined") { + if (state) { + self.addClass('checked'); + } else { + self.removeClass('checked'); + } + + self._checked = state; + + return self; + } + + return self._checked; + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + + return ( + '' + ); + } + }); +}); + +// Included from: js/tinymce/classes/ui/RadioGroup.js + +/** + * RadioGroup.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @class tinymce.ui.RadioGroup + * @extends tinymce.ui.Container + */ +define("tinymce/ui/RadioGroup", [ + "tinymce/ui/Container" +], function(Container) { + "use strict"; + + return Container.extend({}); +}); + +// Included from: js/tinymce/classes/ui/ResizeHandle.js + +/** + * ResizeHandle.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less ResizeHandle.less + * @class tinymce.ui.ResizeHandle + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/ResizeHandle", [ + "tinymce/ui/Widget", + "tinymce/ui/DragHelper", + "tinymce/ui/DomUtils" +], function(Widget, DragHelper, DomUtils) { + "use strict"; + + return Widget.extend({ + renderHtml: function() { + var self = this, prefix = self.classPrefix; + + self.addClass('resizehandle'); + + if (self.settings.both) { + self.addClass('resizehandle-both'); + } + + self.canFocus = false; + + return ( + '
    ' + ); + }, + + postRender: function() { + var self = this, iframeStartSize, editor = self.settings.editor; + + self._super(); + + function getSize(elm) { + return { + width: elm.clientWidth, + height: elm.clientHeight + }; + } + + function resizeIframe(width, height) { + var containerElm, iframeElm, containerSize, iframeSize, settings = editor.settings; + + containerElm = editor.getContainer(); + iframeElm = editor.getContentAreaContainer().firstChild; + containerSize = getSize(containerElm); + iframeSize = getSize(iframeElm); + + width = Math.max(settings.min_width || 100, width); + height = Math.max(settings.min_height || 100, height); + width = Math.min(settings.max_width || 0xFFFF, width); + height = Math.min(settings.max_height || 0xFFFF, height); + + if (self.settings.both) { + DomUtils.css(containerElm, 'width', width + (containerSize.width - iframeSize.width)); + } + + DomUtils.css(containerElm, 'height', height + (containerSize.height - iframeSize.height)); + + if (self.settings.both) { + DomUtils.css(iframeElm, 'width', width); + } + + DomUtils.css(iframeElm, 'height', height); + + editor.fire('ResizeEditor'); + } + + self.resizeDragHelper = new DragHelper(this._id, { + start: function() { + iframeStartSize = getSize(editor.getContentAreaContainer().firstChild); + }, + + drag: function(evt) { + resizeIframe(iframeStartSize.width + evt.deltaX, iframeStartSize.height + evt.deltaY); + }, + + end: function() { + } + }); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Spacer.js + +/** + * Spacer.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Spacer.less + * @class tinymce.ui.Spacer + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/Spacer", [ + "tinymce/ui/Widget" +], function(Widget) { + "use strict"; + + return Widget.extend({ + renderHtml: function() { + var self = this; + + self.addClass('spacer'); + self.canFocus = false; + + return '
    '; + } + }); +}); + +// Included from: js/tinymce/classes/ui/SplitButton.js + +/** + * SplitButton.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less SplitButton.less + * @class tinymce.ui.SplitButton + * @extends tinymce.ui.Button + */ +define("tinymce/ui/SplitButton", [ + "tinymce/ui/MenuButton", + "tinymce/dom/DOMUtils" +], function(MenuButton, DomUtils) { + var DOM = DomUtils.DOM; + + return MenuButton.extend({ + Defaults: { + classes: "widget btn splitbtn", + role: "splitbutton" + }, + + repaint: function() { + var self = this, elm = self.getEl(), rect = self.layoutRect(), mainButtonElm, menuButtonElm, btnStyle; + + self._super(); + + mainButtonElm = elm.firstChild; + menuButtonElm = elm.lastChild; + + DOM.css(mainButtonElm, { + width: rect.w - menuButtonElm.offsetWidth, + height: rect.h - 2 + }); + + DOM.css(menuButtonElm, { + height: rect.h - 2 + }); + + btnStyle = mainButtonElm.firstChild.style; + btnStyle.width = btnStyle.height = "100%"; + + btnStyle = menuButtonElm.firstChild.style; + btnStyle.width = btnStyle.height = "100%"; + + return self; + }, + + activeMenu: function(state) { + var self = this; + + DOM.toggleClass(self.getEl().lastChild, self.classPrefix + 'active', state); + }, + + renderHtml: function() { + var self = this, id = self._id, prefix = self.classPrefix; + var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : ''; + + return ( + '
    ' + + '' + + '' + + '
    ' + ); + }, + + postRender: function() { + var self = this, onClickHandler = self.settings.onclick; + + self.on('click', function(e) { + if (e.control == this && !DOM.getParent(e.target, '.' + this.classPrefix + 'open')) { + e.stopImmediatePropagation(); + onClickHandler.call(this, e); + } + }); + + delete self.settings.onclick; + + return self._super(); + } + }); +}); + +// Included from: js/tinymce/classes/ui/StackLayout.js + +/** + * StackLayout.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less StackLayout.less + * @class tinymce.ui.StackLayout + * @extends tinymce.ui.FlowLayout + */ +define("tinymce/ui/StackLayout", [ + "tinymce/ui/FlowLayout" +], function(FlowLayout) { + "use strict"; + + return FlowLayout.extend({ + Defaults: { + containerClass: 'stack-layout', + controlClass: 'stack-layout-item', + endClass : 'break' + } + }); +}); + +// Included from: js/tinymce/classes/ui/TabPanel.js + +/** + * TabPanel.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less TabPanel.less + * @class tinymce.ui.TabPanel + * @extends tinymce.ui.Panel + */ +define("tinymce/ui/TabPanel", [ + "tinymce/ui/Panel", + "tinymce/ui/DomUtils" +], function(Panel, DomUtils) { + "use stict"; + + return Panel.extend({ + lastIdx: 0, + + Defaults: { + layout: 'absolute', + defaults: { + type: 'panel' + } + }, + + activateTab: function(idx) { + if (this.activeTabId) { + DomUtils.removeClass(this.getEl(this.activeTabId), this.classPrefix + 'active'); + } + + this.activeTabId = 't' + idx; + + DomUtils.addClass(this.getEl('t' + idx), this.classPrefix + 'active'); + + if (idx != this.lastIdx) { + this.items()[this.lastIdx].hide(); + this.lastIdx = idx; + } + + this.items()[idx].show().fire('showtab'); + this.reflow(); + }, + + renderHtml: function() { + var self = this, layout = self._layout, tabsHtml = '', prefix = self.classPrefix; + + self.preRender(); + layout.preRender(self); + + self.items().each(function(ctrl, i) { + tabsHtml += ( + '
    ' + + ctrl.settings.title + + '
    ' + ); + }); + + return ( + '
    ' + + '
    ' + + tabsHtml + + '
    ' + + '
    ' + + layout.renderHtml(self) + + '
    ' + + '
    ' + ); + }, + + postRender: function() { + var self = this; + + self._super(); + + self.settings.activeTab = self.settings.activeTab || 0; + self.activateTab(self.settings.activeTab); + + this.on('click', function(e) { + var targetParent = e.target.parentNode; + + if (e.target.parentNode.id == self._id + '-head') { + var i = targetParent.childNodes.length; + + while (i--) { + if (targetParent.childNodes[i] == e.target) { + self.activateTab(i); + } + } + } + }); + }, + + initLayoutRect: function() { + var self = this, rect, minW, minH; + + minW = minH = 0; + self.items().each(function(item, i) { + minW = Math.max(minW, item.layoutRect().minW); + minH = Math.max(minH, item.layoutRect().minH); + if (self.settings.activeTab != i) { + item.hide(); + } + }); + + self.items().each(function(ctrl) { + ctrl.settings.x = 0; + ctrl.settings.y = 0; + ctrl.settings.w = minW; + ctrl.settings.h = minH; + + ctrl.layoutRect({ + x: 0, + y: 0, + w: minW, + h: minH + }); + }); + + var headH = self.getEl('head').offsetHeight; + + self.settings.minWidth = minW; + self.settings.minHeight = minH + headH; + + rect = self._super(); + rect.deltaH += self.getEl('head').offsetHeight; + rect.innerH = rect.h - rect.deltaH; + + return rect; + } + }); +}); + +// Included from: js/tinymce/classes/ui/TextBox.js + +/** + * TextBox.js + * + * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less TextBox.less + * @class tinymce.ui.TextBox + * @extends tinymce.ui.Widget + */ +define("tinymce/ui/TextBox", [ + "tinymce/ui/Widget", + "tinymce/ui/DomUtils" +], function(Widget, DomUtils) { + "use strict"; + + return Widget.extend({ + init: function(settings) { + var self = this; + + self._super(settings); + + self._value = settings.value || ''; + self.addClass('textbox'); + + if (settings.multiline) { + self.addClass('multiline'); + } else { + // TODO: Rework this + self.on('keydown', function(e) { + if (e.keyCode == 13) { + self.parents().reverse().each(function(ctrl) { + e.preventDefault(); + + if (ctrl.submit) { + ctrl.submit(); + return false; + } + }); + } + }); + } + }, + + value: function(value) { + var self = this; + + if (typeof(value) != "undefined") { + self._value = value; + + if (self._rendered) { + self.getEl().value = value; + } + + return self; + } + + if (self._rendered) { + return self.getEl().value; + } + + return self._value; + }, + + repaint: function() { + var self = this, style, rect, borderBox, borderW = 0, borderH = 0, lastRepaintRect; + + style = self.getEl().style; + rect = self._layoutRect; + lastRepaintRect = self._lastRepaintRect || {}; + + borderBox = self._borderBox; + borderW = borderBox.left + borderBox.right + 8; + borderH = borderBox.top + borderBox.bottom + (self.settings.multiline ? 8 : 0); + + if (rect.x !== lastRepaintRect.x) { + style.left = rect.x + 'px'; + lastRepaintRect.x = rect.x; + } + + if (rect.y !== lastRepaintRect.y) { + style.top = rect.y + 'px'; + lastRepaintRect.y = rect.y; + } + + if (rect.w !== lastRepaintRect.w) { + style.width = (rect.w - borderW) + 'px'; + lastRepaintRect.w = rect.w; + } + + if (rect.h !== lastRepaintRect.h) { + style.height = (rect.h - borderH) + 'px'; + lastRepaintRect.h = rect.h; + } + + /*if (!self.settings.multiline) { + //style.lineHeight = (rect.h - borderH) + 'px'; + }*/ + + self._lastRepaintRect = lastRepaintRect; + self.fire('repaint', {}, false); + + return self; + }, + + renderHtml: function() { + var self = this, id = self._id, settings = self.settings, value = self.encode(self._value, false), extraAttrs = ''; + + if ("spellcheck" in settings) { + extraAttrs += ' spellcheck="' + settings.spellcheck + '"'; + } + + if (settings.maxLength) { + extraAttrs += ' maxlength="' + settings.maxLength + '"'; + } + + if (settings.size) { + extraAttrs += ' size="' + settings.size + '"'; + } + + if (settings.subtype) { + extraAttrs += ' type="' + settings.subtype + '"'; + } + + if (settings.multiline) { + return ( + '' + ); + } + + return ''; + }, + + postRender: function() { + var self = this; + + DomUtils.on(self.getEl(), 'change', function(e) { + self.fire('change', e); + }); + + return self._super(); + } + }); +}); + +// Included from: js/tinymce/classes/ui/Throbber.js + +/** + * Throbber.js + * + * Copyright 2003-2013, Moxiecode Systems AB, All rights reserved. + */ + +/** + * .. + * + * @-x-less Throbber.less + * @class tinymce.ui.Throbber + */ +define("tinymce/ui/Throbber", [ + "tinymce/ui/DomUtils" +], function(DomUtils) { + "use strict"; + + return function(elm) { + var self = this, state; + + self.show = function(time) { + self.hide(); + + state = true; + + window.setTimeout(function() { + if (state) { + elm.appendChild(DomUtils.createFragment('
    ')); + } + }, time || 0); + + return self; + }, + + self.hide = function() { + var child = elm.lastChild; + + if (child && child.className.indexOf('throbber') != -1) { + child.parentNode.removeChild(child); + } + + state = false; + + return self; + }; + }; +}); + +expose(["tinymce/dom/EventUtils","tinymce/dom/Sizzle","tinymce/dom/DomQuery","tinymce/html/Styles","tinymce/dom/TreeWalker","tinymce/util/Tools","tinymce/dom/Range","tinymce/html/Entities","tinymce/Env","tinymce/dom/DOMUtils","tinymce/dom/ScriptLoader","tinymce/AddOnManager","tinymce/html/Node","tinymce/html/Schema","tinymce/html/SaxParser","tinymce/html/DomParser","tinymce/html/Writer","tinymce/html/Serializer","tinymce/dom/Serializer","tinymce/dom/TridentSelection","tinymce/util/VK","tinymce/dom/ControlSelection","tinymce/dom/Selection","tinymce/dom/RangeUtils","tinymce/Formatter","tinymce/UndoManager","tinymce/EnterKey","tinymce/ForceBlocks","tinymce/EditorCommands","tinymce/util/URI","tinymce/util/Class","tinymce/ui/Selector","tinymce/ui/Collection","tinymce/ui/DomUtils","tinymce/ui/Control","tinymce/ui/Factory","tinymce/ui/Container","tinymce/ui/DragHelper","tinymce/ui/Scrollable","tinymce/ui/Panel","tinymce/ui/Movable","tinymce/ui/Resizable","tinymce/ui/FloatPanel","tinymce/ui/KeyboardNavigation","tinymce/ui/Window","tinymce/ui/MessageBox","tinymce/WindowManager","tinymce/util/Quirks","tinymce/util/Observable","tinymce/Shortcuts","tinymce/Editor","tinymce/EditorManager","tinymce/LegacyInput","tinymce/util/XHR","tinymce/util/JSON","tinymce/util/JSONRequest","tinymce/util/JSONP","tinymce/util/LocalStorage","tinymce/Compat","tinymce/ui/Layout","tinymce/ui/AbsoluteLayout","tinymce/ui/Tooltip","tinymce/ui/Widget","tinymce/ui/Button","tinymce/ui/ButtonGroup","tinymce/ui/Checkbox","tinymce/ui/CheckboxGroup","tinymce/ui/ColorButton","tinymce/ui/ComboBox","tinymce/ui/Path","tinymce/ui/ElementPath","tinymce/ui/FormItem","tinymce/ui/Form","tinymce/ui/FieldSet","tinymce/ui/FilePicker","tinymce/ui/FitLayout","tinymce/ui/FlexLayout","tinymce/ui/FlowLayout","tinymce/ui/FormatControls","tinymce/ui/GridLayout","tinymce/ui/Iframe","tinymce/ui/Label","tinymce/ui/Toolbar","tinymce/ui/MenuBar","tinymce/ui/MenuButton","tinymce/ui/ListBox","tinymce/ui/MenuItem","tinymce/ui/Menu","tinymce/ui/PanelButton","tinymce/ui/Radio","tinymce/ui/RadioGroup","tinymce/ui/ResizeHandle","tinymce/ui/Spacer","tinymce/ui/SplitButton","tinymce/ui/StackLayout","tinymce/ui/TabPanel","tinymce/ui/TextBox","tinymce/ui/Throbber"]); +})(this); \ No newline at end of file diff --git a/lib/tinymce/jscripts/tinymce4/tinymce.min.js b/lib/tinymce/jscripts/tinymce4/tinymce.min.js new file mode 100644 index 00000000..b52d1741 --- /dev/null +++ b/lib/tinymce/jscripts/tinymce4/tinymce.min.js @@ -0,0 +1,10 @@ +// 4.0b1 (2013-04-11) +(function(e,t){"use strict";function n(e,t){for(var n,r=[],i=0;e.length>i;++i){if(n=s[e[i]]||o(e[i]),!n)throw"module definition dependecy not found: "+e[i];r.push(n)}t.apply(null,r)}function r(e,r,i){if("string"!=typeof e)throw"invalid module definition, module id must be defined and be a string";if(r===t)throw"invalid module definition, dependencies must be specified";if(i===t)throw"invalid module definition, definition function must be specified";n(r,function(){s[e]=i.apply(null,arguments)})}function i(e){return!!s[e]}function o(t){for(var n=e,r=t.split(/[.\/]/),i=0;r.length>i;++i){if(!n[r[i]])return;n=n[r[i]]}return n}function a(n){for(var r=0;n.length>r;r++){for(var i=e,o=n[r],a=o.split(/[.\/]/),l=0;a.length-1>l;++l)i[a[l]]===t&&(i[a[l]]={}),i=i[a[l]];i[a[a.length-1]]=s[o]}}var s={},l="tinymce/dom/EventUtils",c="tinymce/dom/Sizzle",u="tinymce/dom/DomQuery",d="tinymce/html/Styles",f="tinymce/dom/TreeWalker",p="tinymce/util/Tools",h="tinymce/dom/Range",m="tinymce/html/Entities",g="tinymce/Env",v="tinymce/dom/DOMUtils",y="tinymce/dom/ScriptLoader",b="tinymce/AddOnManager",C="tinymce/html/Node",x="tinymce/html/Schema",w="tinymce/html/SaxParser",_="tinymce/html/DomParser",N="tinymce/html/Writer",k="tinymce/html/Serializer",E="tinymce/dom/Serializer",S="tinymce/dom/TridentSelection",T="tinymce/util/VK",R="tinymce/dom/ControlSelection",A="tinymce/dom/Selection",B="tinymce/dom/RangeUtils",L="tinymce/Formatter",H="tinymce/UndoManager",M="tinymce/EnterKey",D="tinymce/ForceBlocks",P="tinymce/EditorCommands",O="tinymce/util/URI",I="tinymce/util/Class",F="tinymce/ui/Selector",W="tinymce/ui/Collection",z="tinymce/ui/DomUtils",V="tinymce/ui/Control",U="tinymce/ui/Factory",q="tinymce/ui/Container",$="tinymce/ui/DragHelper",j="tinymce/ui/Scrollable",G="tinymce/ui/Panel",K="tinymce/ui/Movable",X="tinymce/ui/Resizable",Y="tinymce/ui/FloatPanel",J="tinymce/ui/KeyboardNavigation",Q="tinymce/ui/Window",Z="tinymce/ui/MessageBox",et="tinymce/WindowManager",tt="tinymce/util/Quirks",nt="tinymce/util/Observable",rt="tinymce/Shortcuts",it="tinymce/Editor",ot="tinymce/EditorManager",at="tinymce/LegacyInput",st="tinymce/util/XHR",lt="tinymce/util/JSON",ct="tinymce/util/JSONRequest",ut="tinymce/util/JSONP",dt="tinymce/util/LocalStorage",ft="tinymce/Compat",pt="tinymce/ui/Layout",ht="tinymce/ui/AbsoluteLayout",mt="tinymce/ui/Tooltip",gt="tinymce/ui/Widget",vt="tinymce/ui/Button",yt="tinymce/ui/ButtonGroup",bt="tinymce/ui/Checkbox",Ct="tinymce/ui/CheckboxGroup",xt="tinymce/ui/ColorButton",wt="tinymce/ui/ComboBox",_t="tinymce/ui/Path",Nt="tinymce/ui/ElementPath",kt="tinymce/ui/FormItem",Et="tinymce/ui/Form",St="tinymce/ui/FieldSet",Tt="tinymce/ui/FilePicker",Rt="tinymce/ui/FitLayout",At="tinymce/ui/FlexLayout",Bt="tinymce/ui/FlowLayout",Lt="tinymce/ui/FormatControls",Ht="tinymce/ui/GridLayout",Mt="tinymce/ui/Iframe",Dt="tinymce/ui/Label",Pt="tinymce/ui/Toolbar",Ot="tinymce/ui/MenuBar",It="tinymce/ui/MenuButton",Ft="tinymce/ui/ListBox",Wt="tinymce/ui/MenuItem",zt="tinymce/ui/Menu",Vt="tinymce/ui/PanelButton",Ut="tinymce/ui/Radio",qt="tinymce/ui/RadioGroup",$t="tinymce/ui/ResizeHandle",jt="tinymce/ui/Spacer",Gt="tinymce/ui/SplitButton",Kt="tinymce/ui/StackLayout",Xt="tinymce/ui/TabPanel",Yt="tinymce/ui/TextBox",Jt="tinymce/ui/Throbber";r(l,[],function(){function e(e,t,n,r){e.addEventListener?e.addEventListener(t,n,r||!1):e.attachEvent&&e.attachEvent("on"+t,n)}function n(e,t,n,r){e.removeEventListener?e.removeEventListener(t,n,r||!1):e.detachEvent&&e.detachEvent("on"+t,n)}function r(e,t){function n(){return!1}function r(){return!0}var i,o=t||{};for(i in e)"layerX"!==i&&"layerY"!==i&&(o[i]=e[i]);return o.target||(o.target=o.srcElement||document),o.preventDefault=function(){o.isDefaultPrevented=r,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},o.stopPropagation=function(){o.isPropagationStopped=r,e&&(e.stopPropagation?e.stopPropagation():e.cancelBubble=!0)},o.stopImmediatePropagation=function(){o.isImmediatePropagationStopped=r,o.stopPropagation()},o.isDefaultPrevented||(o.isDefaultPrevented=n,o.isPropagationStopped=n,o.isImmediatePropagationStopped=n),o}function i(r,i,o){function a(){o.domLoaded||(o.domLoaded=!0,i(u))}function s(){"complete"===c.readyState&&(n(c,"readystatechange",s),a())}function l(){try{c.documentElement.doScroll("left")}catch(e){return setTimeout(l,0),t}a()}var c=r.document,u={type:"ready"};return o.domLoaded?(i(u),t):(c.addEventListener?e(r,"DOMContentLoaded",a):(e(c,"readystatechange",s),c.documentElement.doScroll&&r===r.top&&l()),e(r,"load",a),t)}function o(){function t(e,t){var n,r,i,o;if(n=s[t][e.type])for(r=0,i=n.length;i>r;r++)if(o=n[r],o&&o.func.call(o.scope,e)===!1&&e.preventDefault(),e.isImmediatePropagationStopped())return}var o=this,s={},l,c,u,d,f;c=a+(+new Date).toString(32),d="onmouseenter"in document.documentElement,u="onfocusin"in document.documentElement,f={mouseenter:"mouseover",mouseleave:"mouseout"},l=1,o.domLoaded=!1,o.events=s,o.bind=function(n,a,p,h){function m(e){t(r(e||_.event),g)}var g,v,y,b,C,x,w,_=window;if(n&&3!==n.nodeType&&8!==n.nodeType){for(n[c]?g=n[c]:(g=l++,n[c]=g,s[g]={}),h=h||n,a=a.split(" "),y=a.length;y--;)b=a[y],x=m,C=w=!1,"DOMContentLoaded"===b&&(b="ready"),o.domLoaded&&"ready"===b&&"complete"==n.readyState?p.call(h,r({type:b})):(d||(C=f[b],C&&(x=function(e){var n,i;if(n=e.currentTarget,i=e.relatedTarget,i&&n.contains)i=n.contains(i);else for(;i&&i!==n;)i=i.parentNode;i||(e=r(e||_.event),e.type="mouseout"===e.type?"mouseleave":"mouseenter",e.target=n,t(e,g))})),u||"focusin"!==b&&"focusout"!==b||(w=!0,C="focusin"===b?"focus":"blur",x=function(e){e=r(e||_.event),e.type="focus"===e.type?"focusin":"focusout",t(e,g)}),v=s[g][b],v?"ready"===b&&o.domLoaded?p({type:b}):v.push({func:p,scope:h}):(s[g][b]=v=[{func:p,scope:h}],v.fakeName=C,v.capture=w,v.nativeHandler=x,"ready"===b?i(n,x,o):e(n,C||b,x,w)));return n=v=0,p}},o.unbind=function(e,t,r){var i,a,l,u,d,f;if(!e||3===e.nodeType||8===e.nodeType)return o;if(i=e[c]){if(f=s[i],t){for(t=t.split(" "),l=t.length;l--;)if(d=t[l],a=f[d]){if(r)for(u=a.length;u--;)a[u].func===r&&a.splice(u,1);r&&0!==a.length||(delete f[d],n(e,a.fakeName||d,a.nativeHandler,a.capture))}}else{for(d in f)a=f[d],n(e,a.fakeName||d,a.nativeHandler,a.capture);f={}}for(d in f)return o;delete s[i];try{delete e[c]}catch(p){e[c]=null}}return o},o.fire=function(e,n,i){var a;if(!e||3===e.nodeType||8===e.nodeType)return o;i=r(null,i),i.type=n,i.target=e;do a=e[c],a&&t(i,a),e=e.parentNode||e.ownerDocument||e.defaultView||e.parentWindow;while(e&&!i.isPropagationStopped());return o},o.clean=function(e){var t,n,r=o.unbind;if(!e||3===e.nodeType||8===e.nodeType)return o;if(e[c]&&r(e),e.getElementsByTagName||(e=e.document),e&&e.getElementsByTagName)for(r(e),n=e.getElementsByTagName("*"),t=n.length;t--;)e=n[t],e[c]&&r(e);return o},o.destory=function(){s={}},o.cancel=function(e){return e&&(e.preventDefault(),e.stopImmediatePropagation()),!1}}var a="mce-data-";return o.Event=new o,o.Event.bind(window,"ready",function(){}),o}),r(c,[],function(){function e(e){return gt.test(e+"")}function n(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>N.cacheLength&&delete e[t.shift()],e[n]=r,r}}function i(e){return e[F]=!0,e}function o(e){var t=L.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t=null}}function a(e,t,n,r){var i,o,a,s,l,c,u,p,h,m;if((t?t.ownerDocument||t:W)!==L&&B(t),t=t||L,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(M&&!r){if(i=vt.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&I(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return et.apply(n,t.getElementsByTagName(e)),n;if((a=i[3])&&z.getElementsByClassName&&t.getElementsByClassName)return et.apply(n,t.getElementsByClassName(a)),n}if(z.qsa&&!D.test(e)){if(u=!0,p=F,h=t,m=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){for(c=d(e),(u=t.getAttribute("id"))?p=u.replace(Ct,"\\$&"):t.setAttribute("id",p),p="[id='"+p+"'] ",l=c.length;l--;)c[l]=p+f(c[l]);h=mt.test(e)&&t.parentNode||t,m=c.join(",")}if(m)try{return et.apply(n,h.querySelectorAll(m)),n}catch(g){}finally{u||t.removeAttribute("id")}}}return C(e.replace(ct,"$1"),t,n,r)}function s(e,t){var n=t&&e,r=n&&(~t.sourceIndex||Y)-(~e.sourceIndex||Y);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function l(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function c(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function u(e){return i(function(t){return t=+t,i(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function d(e,t){var n,r,i,o,s,l,c,u=$[e+" "];if(u)return t?0:u.slice(0);for(s=e,l=[],c=N.preFilter;s;){(!n||(r=ut.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=dt.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(ct," ")}),s=s.slice(n.length));for(o in N.filter)!(r=ht[o].exec(s))||c[o]&&!(r=c[o](r))||(n=r.shift(),i.push({value:n,type:o,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?a.error(e):$(e,l).slice(0)}function f(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function p(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=U++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,l,c,u=V+" "+o;if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i)if(c=t[F]||(t[F]={}),(l=c[r])&&l[0]===u){if((s=l[1])===!0||s===_)return s===!0}else if(l=c[r]=[u],l[1]=e(t,n,a)||_,l[1]===!0)return!0}}function h(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function m(e,t,n,r,i){for(var o,a=[],s=0,l=e.length,c=null!=t;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),c&&t.push(s));return a}function g(e,t,n,r,o,a){return r&&!r[F]&&(r=g(r)),o&&!o[F]&&(o=g(o,a)),i(function(i,a,s,l){var c,u,d,f=[],p=[],h=a.length,g=i||b(t||"*",s.nodeType?[s]:s,[]),v=!e||!i&&t?g:m(g,f,e,s,l),y=n?o||(i?e:h||r)?[]:a:v;if(n&&n(v,y,s,l),r)for(c=m(y,p),r(c,[],s,l),u=c.length;u--;)(d=c[u])&&(y[p[u]]=!(v[p[u]]=d));if(i){if(o||e){if(o){for(c=[],u=y.length;u--;)(d=y[u])&&c.push(v[u]=d);o(null,y=[],c,l)}for(u=y.length;u--;)(d=y[u])&&(c=o?nt.call(i,d):f[u])>-1&&(i[c]=!(a[c]=d))}}else y=m(y===a?y.splice(h,y.length):y),o?o(null,a,y,l):et.apply(a,y)})}function v(e){for(var t,n,r,i=e.length,o=N.relative[e[0].type],a=o||N.relative[" "],s=o?1:0,l=p(function(e){return e===t},a,!0),c=p(function(e){return nt.call(t,e)>-1},a,!0),u=[function(e,n,r){return!o&&(r||n!==T)||((t=n).nodeType?l(e,n,r):c(e,n,r))}];i>s;s++)if(n=N.relative[e[s].type])u=[p(h(u),n)];else{if(n=N.filter[e[s].type].apply(null,e[s].matches),n[F]){for(r=++s;i>r&&!N.relative[e[r].type];r++);return g(s>1&&h(u),s>1&&f(e.slice(0,s-1)).replace(ct,"$1"),n,r>s&&v(e.slice(s,r)),i>r&&v(e=e.slice(r)),i>r&&f(e))}u.push(n)}return h(u)}function y(e,t){var n=0,r=t.length>0,o=e.length>0,s=function(i,s,l,c,u){var d,f,p,h=[],g=0,v="0",y=i&&[],b=null!=u,C=T,x=i||o&&N.find.TAG("*",u&&s.parentNode||s),w=V+=null==C?1:Math.random()||.1;for(b&&(T=s!==L&&s,_=n);null!=(d=x[v]);v++){if(o&&d){for(f=0;p=e[f++];)if(p(d,s,l)){c.push(d);break}b&&(V=w,_=++n)}r&&((d=!p&&d)&&g--,i&&y.push(d))}if(g+=v,r&&v!==g){for(f=0;p=t[f++];)p(y,h,s,l);if(i){if(g>0)for(;v--;)y[v]||h[v]||(h[v]=Q.call(c));h=m(h)}et.apply(c,h),b&&!i&&h.length>0&&g+t.length>1&&a.uniqueSort(c)}return b&&(V=w,T=C),y};return r?i(s):s}function b(e,t,n){for(var r=0,i=t.length;i>r;r++)a(e,t[r],n);return n}function C(e,t,n,r){var i,o,a,s,l,c=d(e);if(!r&&1===c.length){if(o=c[0]=c[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&9===t.nodeType&&M&&N.relative[o[1].type]){if(t=(N.find.ID(a.matches[0].replace(wt,_t),t)||[])[0],!t)return n;e=e.slice(o.shift().value.length)}for(i=ht.needsContext.test(e)?0:o.length;i--&&(a=o[i],!N.relative[s=a.type]);)if((l=N.find[s])&&(r=l(a.matches[0].replace(wt,_t),mt.test(o[0].type)&&t.parentNode||t))){if(o.splice(i,1),e=r.length&&f(o),!e)return et.apply(n,r),n;break}}return S(e,c)(r,t,!M,n,mt.test(e)),n}function x(){}var w,_,N,k,E,S,T,R,A,B,L,H,M,D,P,O,I,F="sizzle"+-new Date,W=window.document,z={},V=0,U=0,q=n(),$=n(),j=n(),G=!1,K=function(){return 0},X=typeof t,Y=1<<31,J=[],Q=J.pop,Z=J.push,et=J.push,tt=J.slice,nt=J.indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},rt="[\\x20\\t\\r\\n\\f]",it="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ot=it.replace("w","w#"),at="([*^$|!~]?=)",st="\\["+rt+"*("+it+")"+rt+"*(?:"+at+rt+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+ot+")|)|)"+rt+"*\\]",lt=":("+it+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+st.replace(3,8)+")*)|.*)\\)|)",ct=RegExp("^"+rt+"+|((?:^|[^\\\\])(?:\\\\.)*)"+rt+"+$","g"),ut=RegExp("^"+rt+"*,"+rt+"*"),dt=RegExp("^"+rt+"*([\\x20\\t\\r\\n\\f>+~])"+rt+"*"),ft=RegExp(lt),pt=RegExp("^"+ot+"$"),ht={ID:RegExp("^#("+it+")"),CLASS:RegExp("^\\.("+it+")"),NAME:RegExp("^\\[name=['\"]?("+it+")['\"]?\\]"),TAG:RegExp("^("+it.replace("w","w*")+")"),ATTR:RegExp("^"+st),PSEUDO:RegExp("^"+lt),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+rt+"*(even|odd|(([+-]|)(\\d*)n|)"+rt+"*(?:([+-]|)"+rt+"*(\\d+)|))"+rt+"*\\)|)","i"),needsContext:RegExp("^"+rt+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+rt+"*((?:-\\d)?\\d*)"+rt+"*\\)|)(?=[^-]|$)","i")},mt=/[\x20\t\r\n\f]*[+~]/,gt=/^[^{]+\{\s*\[native code/,vt=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,yt=/^(?:input|select|textarea|button)$/i,bt=/^h\d$/i,Ct=/'|\\/g,xt=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,wt=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,_t=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{et.apply(J=tt.call(W.childNodes),W.childNodes),J[W.childNodes.length].nodeType}catch(Nt){et={apply:J.length?function(e,t){Z.apply(e,tt.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}E=a.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},B=a.setDocument=function(n){var r=n?n.ownerDocument||n:W;return r!==L&&9===r.nodeType&&r.documentElement?(L=r,H=r.documentElement,M=!E(r),z.getElementsByTagName=o(function(e){return e.appendChild(r.createComment("")),!e.getElementsByTagName("*").length}),z.attributes=o(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),z.getElementsByClassName=o(function(e){return e.innerHTML="",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),z.getByName=o(function(e){e.id=F+0,e.appendChild(L.createElement("a")).setAttribute("name",F),e.appendChild(L.createElement("i")).setAttribute("name",F),H.appendChild(e);var t=r.getElementsByName&&r.getElementsByName(F).length===2+r.getElementsByName(F+0).length;return H.removeChild(e),t}),z.sortDetached=o(function(e){return e.compareDocumentPosition&&1&e.compareDocumentPosition(L.createElement("div"))}),N.attrHandle=o(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==X&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},z.getByName?(N.find.ID=function(e,t){if(typeof t.getElementById!==X&&M){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},N.filter.ID=function(e){var t=e.replace(wt,_t);return function(e){return e.getAttribute("id")===t}}):(N.find.ID=function(e,n){if(typeof n.getElementById!==X&&M){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==X&&r.getAttributeNode("id").value===e?[r]:t:[]}},N.filter.ID=function(e){var t=e.replace(wt,_t);return function(e){var n=typeof e.getAttributeNode!==X&&e.getAttributeNode("id");return n&&n.value===t}}),N.find.TAG=z.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==X?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o},N.find.NAME=z.getByName&&function(e,n){return typeof n.getElementsByName!==X?n.getElementsByName(name):t},N.find.CLASS=z.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==X&&M?n.getElementsByClassName(e):t},P=[],D=[":focus"],(z.qsa=e(r.querySelectorAll))&&(o(function(e){e.innerHTML="",e.querySelectorAll("[selected]").length||D.push("\\["+rt+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||D.push(":checked")}),o(function(e){e.innerHTML="",e.querySelectorAll("[i^='']").length&&D.push("[*^$]="+rt+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||D.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),D.push(",.*:")})),(z.matchesSelector=e(O=H.matchesSelector||H.mozMatchesSelector||H.webkitMatchesSelector||H.oMatchesSelector||H.msMatchesSelector))&&o(function(e){z.disconnectedMatch=O.call(e,"div"),O.call(e,"[s!='']:x"),P.push("!=",lt)}),D=RegExp(D.join("|")),P=P.length&&RegExp(P.join("|")),I=e(H.contains)||H.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},K=H.compareDocumentPosition?function(e,t){if(e===t)return G=!0,0;var n=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return n?1&n||R&&t.compareDocumentPosition(e)===n?e===r||I(W,e)?-1:t===r||I(W,t)?1:A?nt.call(A,e)-nt.call(A,t):0:4&n?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var n,i=0,o=e.parentNode,a=t.parentNode,l=[e],c=[t];if(e===t)return G=!0,0;if(!o||!a)return e===r?-1:t===r?1:o?-1:a?1:0;if(o===a)return s(e,t);for(n=e;n=n.parentNode;)l.unshift(n);for(n=t;n=n.parentNode;)c.unshift(n);for(;l[i]===c[i];)i++;return i?s(l[i],c[i]):l[i]===W?-1:c[i]===W?1:0},L):L},a.matches=function(e,t){return a(e,null,null,t)},a.matchesSelector=function(e,t){if((e.ownerDocument||e)!==L&&B(e),t=t.replace(xt,"='$1']"),z.matchesSelector&&M&&(!P||!P.test(t))&&!D.test(t))try{var n=O.call(e,t);if(n||z.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return a(t,L,null,[e]).length>0},a.contains=function(e,t){return(e.ownerDocument||e)!==L&&B(e),I(e,t)},a.attr=function(e,t){var n;return(e.ownerDocument||e)!==L&&B(e),M&&(t=t.toLowerCase()),(n=N.attrHandle[t])?n(e):!M||z.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},a.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},a.uniqueSort=function(e){var t,n=[],r=0,i=0;if(G=!z.detectDuplicates,R=!z.sortDetached,A=!z.sortStable&&e.slice(0),e.sort(K),G){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return e},k=a.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=k(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=k(t);return n},N=a.selectors={cacheLength:50,createPseudo:i,match:ht,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(wt,_t),e[3]=(e[4]||e[5]||"").replace(wt,_t),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||a.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&a.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return ht.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&ft.test(n)&&(t=d(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(wt,_t).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=q[e+" "];return t||(t=RegExp("(^|"+rt+")"+e+"("+rt+"|$)"))&&q(e,function(e){return t.test(e.className||typeof e.getAttribute!==X&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=a.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var c,u,d,f,p,h,m=o!==a?"nextSibling":"previousSibling",g=t.parentNode,v=s&&t.nodeName.toLowerCase(),y=!l&&!s;if(g){if(o){for(;m;){for(d=t;d=d[m];)if(s?d.nodeName.toLowerCase()===v:1===d.nodeType)return!1;h=m="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?g.firstChild:g.lastChild],a&&y){for(u=g[F]||(g[F]={}),c=u[e]||[],p=c[0]===V&&c[1],f=c[0]===V&&c[2],d=p&&g.childNodes[p];d=++p&&d&&d[m]||(f=p=0)||h.pop();)if(1===d.nodeType&&++f&&d===t){u[e]=[V,p,f];break}}else if(y&&(c=(t[F]||(t[F]={}))[e])&&c[0]===V)f=c[1];else for(;(d=++p&&d&&d[m]||(f=p=0)||h.pop())&&((s?d.nodeName.toLowerCase()!==v:1!==d.nodeType)||!++f||(y&&((d[F]||(d[F]={}))[e]=[V,f]),d!==t)););return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=N.pseudos[e]||N.setFilters[e.toLowerCase()]||a.error("unsupported pseudo: "+e);return r[F]?r(t):r.length>1?(n=[e,e,"",t],N.setFilters.hasOwnProperty(e.toLowerCase())?i(function(e,n){for(var i,o=r(e,t),a=o.length;a--;)i=nt.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:i(function(e){var t=[],n=[],r=S(e.replace(ct,"$1"));return r[F]?i(function(e,t,n,i){for(var o,a=r(e,null,i,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:i(function(e){return function(t){return a(e,t).length>0}}),contains:i(function(e){return function(t){return(t.textContent||t.innerText||k(t)).indexOf(e)>-1}}),lang:i(function(e){return pt.test(e||"")||a.error("unsupported lang: "+e),e=e.replace(wt,_t).toLowerCase(),function(t){var n;do if(n=M?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(e){var t=window.location&&window.location.hash;return t&&t.slice(1)===e.id},root:function(e){return e===H},focus:function(e){return e===L.activeElement&&(!L.hasFocus||L.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!N.pseudos.empty(e)},header:function(e){return bt.test(e.nodeName)},input:function(e){return yt.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,n){return[0>n?n+t:n]}),even:u(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:u(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:u(function(e,t,n){for(var r=0>n?n+t:n;t>++r;)e.push(r);return e})}};for(w in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})N.pseudos[w]=l(w);for(w in{submit:!0,reset:!0})N.pseudos[w]=c(w);return S=a.compile=function(e,t){var n,r=[],i=[],o=j[e+" "];if(!o){for(t||(t=d(e)),n=t.length;n--;)o=v(t[n]),o[F]?r.push(o):i.push(o);o=j(e,y(i,r))}return o},N.pseudos.nth=N.pseudos.eq,x.prototype=N.filters=N.pseudos,N.setFilters=new x,z.sortStable=F.split("").sort(K).join("")===F,B(),[0,0].sort(K),z.detectDuplicates=G,"function"==typeof r&&r.amd?r(function(){return a}):window.Sizzle=a,a}),r(u,[l,c],function(e,n){function r(e){return e!==t}function i(e){return"string"==typeof e}function o(e){var t,n,r;for(r=g.createElement("div"),t=g.createDocumentFragment(),r.innerHTML=e;n=r.firstChild;)t.appendChild(n);return t}function a(e,t,n){var r;if("string"==typeof t)t=o(t);else if(t.length){for(r=0;t.length>r;r++)a(e,t[r],n);return e}for(r=e.length;r--;)n.call(e[r],t.parentNode?t:t);return e}function s(e,t){return e&&t&&-1!==(" "+e.className+" ").indexOf(" "+t+" ")}function l(e,t){var n;for(e=e||[],"string"==typeof e&&(e=e.split(" ")),t=t||{},n=e.length;n--;)t[e[n]]={};return t}function c(e,t){return new c.fn.init(e,t)}function u(e){var t=arguments,n,r,i;for(r=1;t.length>r;r++){n=t[r];for(i in n)e[i]=n[i]}return e}function d(e){var t=[],n,r;for(n=0,r=e.length;r>n;n++)t[n]=e[n];return t}function f(e,t){var n;if(t.indexOf)return t.indexOf(e);for(n=t.length;n--;)if(t[n]===e)return n;return-1}function p(e,t){var n,r,i,o,a;if(e)if(n=e.length,n===o){for(r in e)if(e.hasOwnProperty(r)&&(a=e[r],t.call(a,a,r)===!1))break}else for(i=0;n>i&&(a=e[i],t.call(a,a,r)!==!1);i++);return e}function h(e,n,r){for(var i=[],o=e[n];o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!c(o).is(r));)1===o.nodeType&&i.push(o),o=o[n];return i}function m(e,t,n,r){for(var i=[];e;e=e[n])r&&e.nodeType!==r||e===t||i.push(e);return i}var g=document,v=Array.prototype.push,y=Array.prototype.slice,b=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,C=e.Event,x=l("fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom"),w=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},_=/^\s*|\s*$/g,N=function(e){return null===e||e===t?"":(""+e).replace(_,"")};return c.fn=c.prototype={constructor:c,selector:"",length:0,init:function(e,t){var n=this,r,a;if(!e)return n;if(e.nodeType)return n.context=n[0]=e,n.length=1,n;if(i(e)){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:b.exec(e),!r)return c(t||document).find(e);if(r[1])for(a=o(e).firstChild;a;)this.add(a),a=a.nextSibling;else{if(a=g.getElementById(r[2]),a.id!==r[2])return n.find(e);n.length=1,n[0]=a}}else this.add(e);return n},toArray:function(){return d(this)},add:function(e){var t=this;return w(e)?v.apply(t,e):e instanceof c?t.add(e.toArray()):v.call(t,e),t},attr:function(e,n){var i=this;if("object"==typeof e)p(e,function(e,t){i.attr(t,e)});else{if(!r(n))return i[0]&&1===i[0].nodeType?i[0].getAttribute(e):t;this.each(function(){1===this.nodeType&&this.setAttribute(e,n)})}return i},css:function(e,n){var i=this;if("object"==typeof e)p(e,function(e,t){i.css(t,e)});else{if(e=e.replace(/-(\D)/g,function(e,t){return t.toUpperCase()}),!r(n))return i[0]?i[0].style[e]:t;"number"!=typeof n||x[e]||(n+="px"),i.each(function(){var r=this.style;"opacity"===e&&this.runtimeStyle&&this.runtimeStyle.opacity===t&&(r.filter=""===n?"":"alpha(opacity="+100*n+")");try{r[e]=n}catch(i){}})}return i},remove:function(){for(var e=this,t,n=this.length;n--;)t=e[n],C.clean(t),t.parentNode&&t.parentNode.removeChild(t);return this},empty:function(){for(var e=this,t,n=this.length;n--;)for(t=e[n];t.firstChild;)t.removeChild(t.firstChild);return this},html:function(e){var t=this,n;if(r(e)){for(n=t.length;n--;)t[n].innerHTML=e;return t}return t[0]?t[0].innerHTML:""},text:function(e){var t=this,n;if(r(e)){for(n=t.length;n--;)t[n].innerText=t[0].textContent=e;return t}return t[0]?t[0].innerText||t[0].textContent:""},append:function(){return a(this,arguments,function(e){1===this.nodeType&&this.appendChild(e)})},prepend:function(){return a(this,arguments,function(e){1===this.nodeType&&this.insertBefore(e,this.firstChild)})},before:function(){var e=this;return e[0]&&e[0].parentNode?a(e,arguments,function(e){this.parentNode.insertBefore(e,this.nextSibling)}):e},after:function(){var e=this;return e[0]&&e[0].parentNode?a(e,arguments,function(e){this.parentNode.insertBefore(e,this)}):e},appendTo:function(e){return c(e).append(this),this},addClass:function(e){return this.toggleClass(e,!0)},removeClass:function(e){return this.toggleClass(e,!1)},toggleClass:function(e,t){var n=this;return-1!==e.indexOf(" ")?p(e.split(" "),function(){n.toggleClass(this,t)}):n.each(function(){var n=this,r;s(n,e)!==t&&(r=n.className,t?n.className+=r?" "+e:e:n.className=N((" "+r+" ").replace(" "+e+" "," ")))}),n},hasClass:function(e){return s(this[0],e)},each:function(e){return p(this,e)},on:function(e,t){return this.each(function(){C.bind(this,e,t)})},off:function(e,t){return this.each(function(){C.unbind(this,e,t)})},show:function(){return this.css("display","")},hide:function(){return this.css("display","none")},slice:function(){return new c(y.apply(this,arguments))},eq:function(e){return-1===e?this.slice(e):this.slice(e,+e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},replaceWith:function(e){var t=this;return t[0]&&t[0].parentNode.replaceChild(c(e)[0],t[0]),t},wrap:function(e){return e=c(e)[0],this.each(function(){var t=this,n=e.cloneNode(!1);t.parentNode.insertBefore(n,t),n.appendChild(t)})},unwrap:function(){return this.each(function(){for(var e=this,t=e.firstChild,n;t;)n=t,t=t.nextSibling,e.parentNode.insertBefore(n,e)})},clone:function(){var e=[];return this.each(function(){e.push(this.cloneNode(!0))}),c(e)},find:function(e){var t,n,r=[];for(t=0,n=this.length;n>t;t++)c.find(e,this[t],r);return c(r)},push:v,sort:[].sort,splice:[].splice},u(c,{extend:u,toArray:d,inArray:f,isArray:w,each:p,trim:N,makeMap:l,find:n,expr:n.selectors,unique:n.uniqueSort,text:n.getText,isXMLDoc:n.isXML,contains:n.contains,filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?c.find.matchesSelector(t[0],e)?[t[0]]:[]:c.find.matches(e,t)}}),p({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return h(e,"parentNode")},parentsUntil:function(e,t){return h(e,"parentNode",t)},next:function(e){return m(e,"nextSibling",1)},prev:function(e){return m(e,"previousSibling",1)},nextNodes:function(e){return m(e,"nextSibling")},prevNodes:function(e){return m(e,"previousSibling")},children:function(e){return m(e.firstChild,"nextSibling",1)},contents:function(e){return d(("iframe"===e.nodeName?e.contentDocument||e.contentWindow.document:e).childNodes)}},function(e,t){c.fn[e]=function(n){var r=this,i;if(r.length>1)throw Error("DomQuery only supports traverse functions on a single node.");return r[0]&&(i=t(r[0],n)),i=c(i),n&&"parentsUntil"!==e?i.filter(n):i}}),c.fn.filter=function(e){return c.filter(e)},c.fn.is=function(e){return!!e&&this.filter(e).length>0},c.fn.init.prototype=c.fn,c}),r(d,[],function(){return function(e,t){function n(e,t,n,r){function i(e){return e=parseInt(e,10).toString(16),e.length>1?e:"0"+e}return"#"+i(t)+i(n)+i(r)}var r=/rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi,i=/(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi,o=/\s*([^:]+):\s*([^;]+);?/g,a=/\s+$/,s,l,c={},u,d="\ufeff";for(e=e||{},u=("\\\" \\' \\; \\: ; : "+d).split(" "),l=0;u.length>l;l++)c[u[l]]=d+l,c[d+l]=u[l];return{toHex:function(e){return e.replace(r,n)},parse:function(t){function s(e,t){var n,r,i,o;n=h[e+"-top"+t],n&&(r=h[e+"-right"+t],n==r&&(i=h[e+"-bottom"+t],r==i&&(o=h[e+"-left"+t],i==o&&(h[e+t]=o,delete h[e+"-top"+t],delete h[e+"-right"+t],delete h[e+"-bottom"+t],delete h[e+"-left"+t]))))}function l(e){var t=h[e],n;if(t&&!(0>t.indexOf(" "))){for(t=t.split(" "),n=t.length;n--;)if(t[n]!==t[0])return!1; +return h[e]=t[0],!0}}function u(e,t,n,r){l(t)&&l(n)&&l(r)&&(h[e]=h[t]+" "+h[n]+" "+h[r],delete h[t],delete h[n],delete h[r])}function d(e){return y=!0,c[e]}function f(e,t){return y&&(e=e.replace(/\uFEFF[0-9]/g,function(e){return c[e]})),t||(e=e.replace(/\\([\'\";:])/g,"$1")),e}function p(e,t,n,r,i,o){return(i=i||o)?(i=f(i),"'"+i.replace(/\'/g,"\\'")+"'"):(t=f(t||n||r),b&&(t=b.call(C,t,"style")),"url('"+t.replace(/\'/g,"\\'")+"')")}var h={},m,g,v,y,b=e.url_converter,C=e.url_converter_scope||this;if(t){for(t=t.replace(/\\[\"\';:\uFEFF]/g,d).replace(/\"[^\"]+\"|\'[^\']+\'/g,function(e){return e.replace(/[;:]/g,d)});m=o.exec(t);)g=m[1].replace(a,"").toLowerCase(),v=m[2].replace(a,""),g&&v.length>0&&("font-weight"===g&&"700"===v?v="bold":("color"===g||"background-color"===g)&&(v=v.toLowerCase()),v=v.replace(r,n),v=v.replace(i,p),h[g]=y?f(v,!0):v),o.lastIndex=m.index+m[0].length;s("border",""),s("border","-width"),s("border","-color"),s("border","-style"),s("padding",""),s("margin",""),u("border","border-width","border-style","border-color"),"medium none"===h.border&&delete h.border}return h},serialize:function(e,n){function r(n){var r,o,a,l;if(r=t.styles[n])for(o=0,a=r.length;a>o;o++)n=r[o],l=e[n],l!==s&&l.length>0&&(i+=(i.length>0?" ":"")+n+": "+l+";")}var i="",o,a;if(n&&t&&t.styles)r("*"),r(n);else for(o in e)a=e[o],a!==s&&a.length>0&&(i+=(i.length>0?" ":"")+o+": "+a+";");return i}}}}),r(f,[],function(){return function(e,t){function n(e,n,r,i){var o,a;if(e){if(!i&&e[n])return e[n];if(e!=t){if(o=e[r])return o;for(a=e.parentNode;a&&a!=t;a=a.parentNode)if(o=a[r])return o}}}var r=e;this.current=function(){return r},this.next=function(e){return r=n(r,"firstChild","nextSibling",e)},this.prev=function(e){return r=n(r,"lastChild","previousSibling",e)}}}),r(p,[],function(){function e(e,n){return n?"array"==n&&g(e)?!0:typeof e==n:e!==t}function n(e){var t=[],n,r;for(n=0,r=e.length;r>n;n++)t[n]=e[n];return t}function r(e,t,n){var r;for(e=e||[],t=t||",","string"==typeof e&&(e=e.split(t)),n=n||{},r=e.length;r--;)n[e[r]]={};return n}function i(e,n,r){var i,o;if(!e)return 0;if(r=r||e,e.length!==t){for(i=0,o=e.length;o>i;i++)if(n.call(r,e[i],i,e)===!1)return 0}else for(i in e)if(e.hasOwnProperty(i)&&n.call(r,e[i],i,e)===!1)return 0;return 1}function o(e,t){var n=[];return i(e,function(e){n.push(t(e))}),n}function a(e,t){var n=[];return i(e,function(e){(!t||t(e))&&n.push(e)}),n}function s(e,n,r){var i=this,o,a,s,l,c,u=0;if(e=/^((static) )?([\w.]+)(:([\w.]+))?/.exec(e),s=e[3].match(/(^|\.)(\w+)$/i)[2],a=i.createNS(e[3].replace(/\.\w+$/,""),r),!a[s]){if("static"==e[2])return a[s]=n,this.onCreate&&this.onCreate(e[2],e[3],a[s]),t;n[s]||(n[s]=function(){},u=1),a[s]=n[s],i.extend(a[s].prototype,n),e[5]&&(o=i.resolve(e[5]).prototype,l=e[5].match(/\.(\w+)$/i)[1],c=a[s],a[s]=u?function(){return o[l].apply(this,arguments)}:function(){return this.parent=o[l],c.apply(this,arguments)},a[s].prototype[s]=a[s],i.each(o,function(e,t){a[s].prototype[t]=o[t]}),i.each(n,function(e,t){o[t]?a[s].prototype[t]=function(){return this.parent=o[t],e.apply(this,arguments)}:t!=s&&(a[s].prototype[t]=e)})),i.each(n["static"],function(e,t){a[s][t]=e})}}function l(e,t){var n,r;if(e)for(n=0,r=e.length;r>n;n++)if(e[n]===t)return n;return-1}function c(e,n){var r,i,o,a=arguments,s;for(r=1,i=a.length;i>r;r++){n=a[r];for(o in n)n.hasOwnProperty(o)&&(s=n[o],s!==t&&(e[o]=s))}return e}function u(e,n,r,o){o=o||this,e&&(r&&(e=e[r]),i(e,function(e,i){return n.call(o,e,i,r)===!1?!1:(u(e,n,r,o),t)}))}function d(e,t){var n,r;for(t=t||window,e=e.split("."),n=0;e.length>n;n++)r=e[n],t[r]||(t[r]={}),t=t[r];return t}function f(e,t){var n,r;for(t=t||window,e=e.split("."),n=0,r=e.length;r>n&&(t=t[e[n]],t);n++);return t}function p(t,n){return!t||e(t,"array")?t:o(t.split(n||","),m)}var h=/^\s*|\s*$/g,m=function(e){return null===e||e===t?"":(""+e).replace(h,"")},g=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};return{trim:m,isArray:g,is:e,toArray:n,makeMap:r,each:i,map:o,grep:a,inArray:l,extend:c,create:s,walk:u,createNS:d,resolve:f,explode:p}}),r(h,[p],function(e){function n(r){function i(){return P.createDocumentFragment()}function o(e,t){N(W,e,t)}function a(e,t){N(z,e,t)}function s(e){o(e.parentNode,G(e))}function l(e){o(e.parentNode,G(e)+1)}function c(e){a(e.parentNode,G(e))}function u(e){a(e.parentNode,G(e)+1)}function d(e){e?(D[q]=D[U],D[$]=D[V]):(D[U]=D[q],D[V]=D[$]),D.collapsed=W}function f(e){s(e),u(e)}function p(e){o(e,0),a(e,1===e.nodeType?e.childNodes.length:e.nodeValue.length)}function h(e,n){var r=D[U],i=D[V],o=D[q],a=D[$],s=n.startContainer,l=n.startOffset,c=n.endContainer,u=n.endOffset;return 0===e?_(r,i,s,l):1===e?_(o,a,s,l):2===e?_(o,a,c,u):3===e?_(r,i,c,u):t}function m(){k(F)}function g(){return k(O)}function v(){return k(I)}function y(e){var t=this[U],n=this[V],i,o;3!==t.nodeType&&4!==t.nodeType||!t.nodeValue?(t.childNodes.length>0&&(o=t.childNodes[n]),o?t.insertBefore(e,o):t.appendChild(e)):n?n>=t.nodeValue.length?r.insertAfter(e,t):(i=t.splitText(n),t.parentNode.insertBefore(e,i)):t.parentNode.insertBefore(e,t)}function b(e){var t=D.extractContents();D.insertNode(e),e.appendChild(t),D.selectNode(e)}function C(){return j(new n(r),{startContainer:D[U],startOffset:D[V],endContainer:D[q],endOffset:D[$],collapsed:D.collapsed,commonAncestorContainer:D.commonAncestorContainer})}function x(e,t){var n;if(3==e.nodeType)return e;if(0>t)return e;for(n=e.firstChild;n&&t>0;)--t,n=n.nextSibling;return n?n:e}function w(){return D[U]==D[q]&&D[V]==D[$]}function _(e,t,n,i){var o,a,s,l,c,u;if(e==n)return t==i?0:i>t?-1:1;for(o=n;o&&o.parentNode!=e;)o=o.parentNode;if(o){for(a=0,s=e.firstChild;s!=o&&t>a;)a++,s=s.nextSibling;return a>=t?-1:1}for(o=e;o&&o.parentNode!=n;)o=o.parentNode;if(o){for(a=0,s=n.firstChild;s!=o&&i>a;)a++,s=s.nextSibling;return i>a?-1:1}for(l=r.findCommonAncestor(e,n),c=e;c&&c.parentNode!=l;)c=c.parentNode;for(c||(c=l),u=n;u&&u.parentNode!=l;)u=u.parentNode;if(u||(u=l),c==u)return 0;for(s=l.firstChild;s;){if(s==c)return-1;if(s==u)return 1;s=s.nextSibling}}function N(e,t,n){var i,o;for(e?(D[U]=t,D[V]=n):(D[q]=t,D[$]=n),i=D[q];i.parentNode;)i=i.parentNode;for(o=D[U];o.parentNode;)o=o.parentNode;o==i?_(D[U],D[V],D[q],D[$])>0&&D.collapse(e):D.collapse(e),D.collapsed=w(),D.commonAncestorContainer=r.findCommonAncestor(D[U],D[q])}function k(e){var t,n=0,r=0,i,o,a,s,l,c;if(D[U]==D[q])return E(e);for(t=D[q],i=t.parentNode;i;t=i,i=i.parentNode){if(i==D[U])return S(t,e);++n}for(t=D[U],i=t.parentNode;i;t=i,i=i.parentNode){if(i==D[q])return T(t,e);++r}for(o=r-n,a=D[U];o>0;)a=a.parentNode,o--;for(s=D[q];0>o;)s=s.parentNode,o++;for(l=a.parentNode,c=s.parentNode;l!=c;l=l.parentNode,c=c.parentNode)a=l,s=c;return R(a,s,e)}function E(e){var t,n,r,o,a,s,l,c,u;if(e!=F&&(t=i()),D[V]==D[$])return t;if(3==D[U].nodeType){if(n=D[U].nodeValue,r=n.substring(D[V],D[$]),e!=I&&(o=D[U],c=D[V],u=D[$]-D[V],0===c&&u>=o.nodeValue.length-1?o.parentNode.removeChild(o):o.deleteData(c,u),D.collapse(W)),e==F)return;return r.length>0&&t.appendChild(P.createTextNode(r)),t}for(o=x(D[U],D[V]),a=D[$]-D[V];o&&a>0;)s=o.nextSibling,l=H(o,e),t&&t.appendChild(l),--a,o=s;return e!=I&&D.collapse(W),t}function S(e,t){var n,r,o,a,s,l;if(t!=F&&(n=i()),r=A(e,t),n&&n.appendChild(r),o=G(e),a=o-D[V],0>=a)return t!=I&&(D.setEndBefore(e),D.collapse(z)),n;for(r=e.previousSibling;a>0;)s=r.previousSibling,l=H(r,t),n&&n.insertBefore(l,n.firstChild),--a,r=s;return t!=I&&(D.setEndBefore(e),D.collapse(z)),n}function T(e,t){var n,r,o,a,s,l;for(t!=F&&(n=i()),o=B(e,t),n&&n.appendChild(o),r=G(e),++r,a=D[$]-r,o=e.nextSibling;o&&a>0;)s=o.nextSibling,l=H(o,t),n&&n.appendChild(l),--a,o=s;return t!=I&&(D.setStartAfter(e),D.collapse(W)),n}function R(e,t,n){var r,o,a,s,l,c,u,d;for(n!=F&&(o=i()),r=B(e,n),o&&o.appendChild(r),a=e.parentNode,s=G(e),l=G(t),++s,c=l-s,u=e.nextSibling;c>0;)d=u.nextSibling,r=H(u,n),o&&o.appendChild(r),u=d,--c;return r=A(t,n),o&&o.appendChild(r),n!=I&&(D.setStartAfter(e),D.collapse(W)),o}function A(e,t){var n=x(D[q],D[$]-1),r,i,o,a,s,l=n!=D[q];if(n==e)return L(n,l,z,t);for(r=n.parentNode,i=L(r,z,z,t);r;){for(;n;)o=n.previousSibling,a=L(n,l,z,t),t!=F&&i.insertBefore(a,i.firstChild),l=W,n=o;if(r==e)return i;n=r.previousSibling,r=r.parentNode,s=L(r,z,z,t),t!=F&&s.appendChild(i),i=s}}function B(e,t){var n=x(D[U],D[V]),r=n!=D[U],i,o,a,s,l;if(n==e)return L(n,r,W,t);for(i=n.parentNode,o=L(i,z,W,t);i;){for(;n;)a=n.nextSibling,s=L(n,r,W,t),t!=F&&o.appendChild(s),r=W,n=a;if(i==e)return o;n=i.nextSibling,i=i.parentNode,l=L(i,z,W,t),t!=F&&l.appendChild(o),o=l}}function L(e,t,n,i){var o,a,s,l,c;if(t)return H(e,i);if(3==e.nodeType){if(o=e.nodeValue,n?(l=D[V],a=o.substring(l),s=o.substring(0,l)):(l=D[$],a=o.substring(0,l),s=o.substring(l)),i!=I&&(e.nodeValue=s),i==F)return;return c=r.clone(e,z),c.nodeValue=a,c}if(i!=F)return r.clone(e,z)}function H(e,n){return n!=F?n==I?r.clone(e,W):e:(e.parentNode.removeChild(e),t)}function M(){return r.create("body",null,v()).outerText}var D=this,P=r.doc,O=0,I=1,F=2,W=!0,z=!1,V="startOffset",U="startContainer",q="endContainer",$="endOffset",j=e.extend,G=r.nodeIndex;return j(D,{startContainer:P,startOffset:0,endContainer:P,endOffset:0,collapsed:W,commonAncestorContainer:P,START_TO_START:0,START_TO_END:1,END_TO_END:2,END_TO_START:3,setStart:o,setEnd:a,setStartBefore:s,setStartAfter:l,setEndBefore:c,setEndAfter:u,collapse:d,selectNode:f,selectNodeContents:p,compareBoundaryPoints:h,deleteContents:m,extractContents:g,cloneContents:v,insertNode:y,surroundContents:b,cloneRange:C,toStringIE:M}),D}return n.prototype.toString=function(){return this.toStringIE()},n}),r(m,[p],function(e){function t(e){var t;return t=document.createElement("div"),t.innerHTML=e,t.textContent||t.innerText||e}function n(e,t){var n,r,i,a={};if(e){for(e=e.split(","),t=t||10,n=0;e.length>n;n+=2)r=String.fromCharCode(parseInt(e[n],t)),o[r]||(i="&"+e[n+1]+";",a[r]=i,a[i]=r);return a}}var r=e.makeMap,i,o,a,s=/[&<>\"\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,l=/[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,c=/[<>&\"\']/g,u=/&(#x|#)?([\w]+);/g,d={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"};o={'"':""","'":"'","<":"<",">":">","&":"&"},a={"<":"<",">":">","&":"&",""":'"',"'":"'"},i=n("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);var f={encodeRaw:function(e,t){return e.replace(t?s:l,function(e){return o[e]||e})},encodeAllRaw:function(e){return(""+e).replace(c,function(e){return o[e]||e})},encodeNumeric:function(e,t){return e.replace(t?s:l,function(e){return e.length>1?"&#"+(1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320)+65536)+";":o[e]||"&#"+e.charCodeAt(0)+";"})},encodeNamed:function(e,t,n){return n=n||i,e.replace(t?s:l,function(e){return o[e]||n[e]||e})},getEncodeFunc:function(e,t){function a(e,n){return e.replace(n?s:l,function(e){return o[e]||t[e]||"&#"+e.charCodeAt(0)+";"||e})}function c(e,n){return f.encodeNamed(e,n,t)}return t=n(t)||i,e=r(e.replace(/\+/g,",")),e.named&&e.numeric?a:e.named?t?c:f.encodeNamed:e.numeric?f.encodeNumeric:f.encodeRaw},decode:function(e){return e.replace(u,function(e,n,r){return n?(r=parseInt(r,2===n.length?16:10),r>65535?(r-=65536,String.fromCharCode(55296+(r>>10),56320+(1023&r))):d[r]||String.fromCharCode(r)):a[e]||i[e]||t(e)})}};return f}),r(g,[],function(){var e=navigator,t=e.userAgent,n,r,i,o,a,s;n=window.opera&&window.opera.buildNumber,r=/WebKit/.test(t),i=!r&&!n&&/MSIE/gi.test(t)&&/Explorer/gi.test(e.appName),i=i&&/MSIE (\w+)\./.exec(t)[1],o=!r&&/Gecko/.test(t),a=-1!=t.indexOf("Mac"),s=/(iPad|iPhone)/.test(t);var l=!s||t.match(/AppleWebKit\/(\d*)/)[1]>=534;return{opera:n,webkit:r,ie:i,gecko:o,mac:a,iOS:s,contentEditable:l,transparentSrc:"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",caretAfter:8!=i,range:window.getSelection&&"Range"in window}}),r(v,[c,d,l,f,h,m,g,p],function(e,n,r,i,o,a,s,l){function c(e,t){var i=this,o;i.doc=e,i.win=window,i.files={},i.counter=0,i.stdMode=!g||e.documentMode>=8,i.boxModel=!g||"CSS1Compat"==e.compatMode||i.stdMode,i.hasOuterHTML="outerHTML"in e.createElement("a"),i.settings=t=h({keep_values:!1,hex_colors:1},t),i.schema=t.schema,i.styles=new n({url_converter:t.url_converter,url_converter_scope:t.url_converter_scope},t.schema),i.fixDoc(e),i.events=t.ownEvents?new r(t.proxy):r.Event,o=t.schema?t.schema.getBlockElements():{},i.isBlock=function(e){if(!e)return!1;var t=e.nodeType;return t?!(1!==t||!o[e.nodeName]):!!o[e]}}var u=l.each,d=l.is,f=l.grep,p=l.trim,h=l.extend,m=s.webkit,g=s.ie,v=/^([a-z0-9],?)+$/i,y=/^[ \t\r\n]*$/,b=l.makeMap("fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom"," ");return c.prototype={root:null,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"},fixDoc:function(e){var t=this.settings,n;if(g&&t.schema){"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(t){e.createElement(t)});for(n in t.schema.getCustomElements())e.createElement(n)}},clone:function(e,t){var n=this,r,i;return!g||1!==e.nodeType||t?e.cloneNode(t):(i=n.doc,t?r.firstChild:(r=i.createElement(e.nodeName),u(n.getAttribs(e),function(t){n.setAttrib(r,t.nodeName,n.getAttrib(e,t.nodeName))}),r))},getRoot:function(){var e=this;return e.get(e.settings.root_element)||e.doc.body},getViewPort:function(e){var t,n;return e=e?e:this.win,t=e.document,n=this.boxModel?t.documentElement:t.body,{x:e.pageXOffset||n.scrollLeft,y:e.pageYOffset||n.scrollTop,w:e.innerWidth||n.clientWidth,h:e.innerHeight||n.clientHeight}},getRect:function(e){var t=this,n,r;return e=t.get(e),n=t.getPos(e),r=t.getSize(e),{x:n.x,y:n.y,w:r.w,h:r.h}},getSize:function(e){var t=this,n,r;return e=t.get(e),n=t.getStyle(e,"width"),r=t.getStyle(e,"height"),-1===n.indexOf("px")&&(n=0),-1===r.indexOf("px")&&(r=0),{w:parseInt(n,10)||e.offsetWidth||e.clientWidth,h:parseInt(r,10)||e.offsetHeight||e.clientHeight}},getParent:function(e,t,n){return this.getParents(e,t,n,!1)},getParents:function(e,n,r,i){var o=this,a,s=[];for(e=o.get(e),i=i===t,d(n,"string")&&(a=n,n="*"===n?function(e){return 1==e.nodeType}:function(e){return o.is(e,a)});e&&e!=r&&e.nodeType&&9!==e.nodeType;){if(!n||n(e)){if(!i)return e;s.push(e)}e=e.parentNode}return i?s:null},get:function(e){var t;return e&&this.doc&&"string"==typeof e&&(t=e,e=this.doc.getElementById(e),e&&e.id!==t)?this.doc.getElementsByName(t)[1]:e},getNext:function(e,t){return this._findSib(e,t,"nextSibling")},getPrev:function(e,t){return this._findSib(e,t,"previousSibling")},select:function(t,n){var r=this;return e(t,r.get(n)||r.get(r.settings.root_element)||r.doc,[])},is:function(n,r){var i;if(n.length===t){if("*"===r)return 1==n.nodeType;if(v.test(r)){for(r=r.toLowerCase().split(/,/),n=n.nodeName.toLowerCase(),i=r.length-1;i>=0;i--)if(r[i]==n)return!0;return!1}}return e.matches(r,n.nodeType?[n]:n).length>0},add:function(e,t,n,r,i){var o=this;return this.run(e,function(e){var a;return a=d(t,"string")?o.doc.createElement(t):t,o.setAttribs(a,n),r&&(r.nodeType?a.appendChild(r):o.setHTML(a,r)),i?a:e.appendChild(a)})},create:function(e,t,n){return this.add(this.doc.createElement(e),e,t,n,1)},createHTML:function(e,n,r){var i="",o;i+="<"+e;for(o in n)n.hasOwnProperty(o)&&(i+=" "+o+'="'+this.encode(n[o])+'"');return r!==t?i+">"+r+"":i+" />"},createFragment:function(e){var t,n,r=this.doc,i;for(i=r.createElement("div"),t=r.createDocumentFragment(),e&&(i.innerHTML=e);n=i.firstChild;)t.appendChild(n);return t},remove:function(e,t){return this.run(e,function(e){var n,r=e.parentNode;if(!r)return null;if(t)for(;n=e.firstChild;)!g||3!==n.nodeType||n.nodeValue?r.insertBefore(n,e):e.removeChild(n);return r.removeChild(e)})},setStyle:function(e,n,r){return this.run(e,function(e){var i=this,o,a;if(n)if("string"==typeof n){o=e.style,n=n.replace(/-(\D)/g,function(e,t){return t.toUpperCase()}),"number"!=typeof r||b[n]||(r+="px"),"opacity"===n&&e.runtimeStyle&&e.runtimeStyle.opacity===t&&(o.filter=""===r?"":"alpha(opacity="+100*r+")");try{o[n]=r}catch(s){}i.settings.update_styles&&e.removeAttribute("data-mce-style")}else for(a in n)i.setStyle(e,a,n[a])})},getStyle:function(e,n,r){if(e=this.get(e)){if(this.doc.defaultView&&r){n=n.replace(/[A-Z]/g,function(e){return"-"+e});try{return this.doc.defaultView.getComputedStyle(e,null).getPropertyValue(n)}catch(i){return null}}return n=n.replace(/-(\D)/g,function(e,t){return t.toUpperCase()}),"float"==n&&(n=g?"styleFloat":"cssFloat"),n.currentStyle&&r?e.currentStyle[n]:e.style?e.style[n]:t}},setStyles:function(e,t){this.setStyle(e,t)},css:function(e,t,n){this.setStyle(e,t,n)},removeAllAttribs:function(e){return this.run(e,function(e){var t,n=e.attributes;for(t=n.length-1;t>=0;t--)e.removeAttributeNode(n.item(t))})},setAttrib:function(e,n,r){var i=this;if(e&&n)return this.run(e,function(e){var o=i.settings,a=e.getAttribute(n);if(null!==r)switch(n){case"style":if(!d(r,"string"))return u(r,function(t,n){i.setStyle(e,n,t)}),t;o.keep_values&&(r?e.setAttribute("data-mce-style",r,2):e.removeAttribute("data-mce-style",2)),e.style.cssText=r;break;case"class":e.className=r||"";break;case"src":case"href":o.keep_values&&(o.url_converter&&(r=o.url_converter.call(o.url_converter_scope||i,r,n,e)),i.setAttrib(e,"data-mce-"+n,r,2));break;case"shape":e.setAttribute("data-mce-style",r)}d(r)&&null!==r&&0!==r.length?e.setAttribute(n,""+r,2):e.removeAttribute(n,2),a!=r&&o.onSetAttrib&&o.onSetAttrib({attrElm:e,attrName:n,attrValue:r})})},setAttribs:function(e,t){var n=this;return this.run(e,function(e){u(t,function(t,r){n.setAttrib(e,r,t)})})},getAttrib:function(e,t,n){var r,i=this,o;if(e=i.get(e),!e||1!==e.nodeType)return n===o?!1:n;if(d(n)||(n=""),/^(src|href|style|coords|shape)$/.test(t)&&(r=e.getAttribute("data-mce-"+t)))return r;if(g&&i.props[t]&&(r=e[i.props[t]],r=r&&r.nodeValue?r.nodeValue:r),r||(r=e.getAttribute(t,2)),/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noshade|nowrap|readonly|selected)$/.test(t))return e[i.props[t]]===!0&&""===r?t:r?t:"";if("FORM"===e.nodeName&&e.getAttributeNode(t))return e.getAttributeNode(t).nodeValue;if("style"===t&&(r=r||e.style.cssText,r&&(r=i.serializeStyle(i.parseStyle(r),e.nodeName),i.settings.keep_values&&e.setAttribute("data-mce-style",r))),m&&"class"===t&&r&&(r=r.replace(/(apple|webkit)\-[a-z\-]+/gi,"")),g)switch(t){case"rowspan":case"colspan":1===r&&(r="");break;case"size":("+0"===r||20===r||0===r)&&(r="");break;case"width":case"height":case"vspace":case"checked":case"disabled":case"readonly":0===r&&(r="");break;case"hspace":-1===r&&(r="");break;case"maxlength":case"tabindex":(32768===r||2147483647===r||"32768"===r)&&(r="");break;case"multiple":case"compact":case"noshade":case"nowrap":return 65535===r?t:n;case"shape":r=r.toLowerCase();break;default:0===t.indexOf("on")&&r&&(r=(""+r).replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/,"$1"))}return r!==o&&null!==r&&""!==r?""+r:n},getPos:function(e,t){var n=this,r=0,i=0,o,a=n.doc,s;if(e=n.get(e),t=t||a.body,e){if(t===a.body&&e.getBoundingClientRect)return s=e.getBoundingClientRect(),t=n.boxModel?a.documentElement:a.body,r=s.left+(a.documentElement.scrollLeft||a.body.scrollLeft)-t.clientTop,i=s.top+(a.documentElement.scrollTop||a.body.scrollTop)-t.clientLeft,{x:r,y:i};for(o=e;o&&o!=t&&o.nodeType;)r+=o.offsetLeft||0,i+=o.offsetTop||0,o=o.offsetParent;for(o=e.parentNode;o&&o!=t&&o.nodeType;)r-=o.scrollLeft||0,i-=o.scrollTop||0,o=o.parentNode}return{x:r,y:i}},parseStyle:function(e){return this.styles.parse(e)},serializeStyle:function(e,t){return this.styles.serialize(e,t)},addStyle:function(e){var t=this,n=t.doc,r,i;if(t!==c.DOM&&n===document){var o=c.DOM.addedStyles;if(o=o||[],o[e])return;o[e]=!0,c.DOM.addedStyles=o}i=n.getElementById("mceDefaultStyles"),i||(i=n.createElement("style"),i.id="mceDefaultStyles",i.type="text/css",r=n.getElementsByTagName("head")[0],r.firstChild?r.insertBefore(i,r.firstChild):r.appendChild(i)),i.styleSheet?i.styleSheet.cssText+=e:i.appendChild(n.createTextNode(e))},loadCSS:function(e){var n=this,r=n.doc,i;return n!==c.DOM&&r===document?(c.DOM.loadCSS(e),t):(e||(e=""),i=r.getElementsByTagName("head")[0],u(e.split(","),function(e){var t;n.files[e]||(n.files[e]=!0,t=n.create("link",{rel:"stylesheet",href:e}),g&&r.documentMode&&r.recalc&&(t.onload=function(){r.recalc&&r.recalc(),t.onload=null}),i.appendChild(t))}),t)},addClass:function(e,t){return this.run(e,function(e){var n;return t?this.hasClass(e,t)?e.className:(n=this.removeClass(e,t),e.className=n=(""!==n?n+" ":"")+t,n):0})},removeClass:function(e,t){var n=this,r;return n.run(e,function(e){var i;return n.hasClass(e,t)?(r||(r=RegExp("(^|\\s+)"+t+"(\\s+|$)","g")),i=e.className.replace(r," "),i=p(" "!=i?i:""),e.className=i,i||(e.removeAttribute("class"),e.removeAttribute("className")),i):e.className})},hasClass:function(e,t){return e=this.get(e),e&&t?-1!==(" "+e.className+" ").indexOf(" "+t+" "):!1},toggleClass:function(e,n,r){r=r===t?!this.hasClass(e,n):r,this.hasClass(e,n)!==r&&(r?this.addClass(e,n):this.removeClass(e,n))},show:function(e){return this.setStyle(e,"display","block")},hide:function(e){return this.setStyle(e,"display","none")},isHidden:function(e){return e=this.get(e),!e||"none"==e.style.display||"none"==this.getStyle(e,"display")},uniqueId:function(e){return(e?e:"mce_")+this.counter++},setHTML:function(e,t){var n=this;return n.run(e,function(e){if(g){for(;e.firstChild;)e.removeChild(e.firstChild);try{e.innerHTML="
    "+t,e.removeChild(e.firstChild)}catch(r){var i=n.create("div");i.innerHTML="
    "+t,u(f(i.childNodes),function(t,n){n&&e.canHaveHTML&&e.appendChild(t)})}}else e.innerHTML=t;return t})},getOuterHTML:function(e){var t,n=this;return(e=n.get(e))?1===e.nodeType&&n.hasOuterHTML?e.outerHTML:(t=(e.ownerDocument||n.doc).createElement("body"),t.appendChild(e.cloneNode(!0)),t.innerHTML):null},setOuterHTML:function(e,t,n){var r=this;return r.run(e,function(e){function i(){var i,o;for(o=n.createElement("body"),o.innerHTML=t,i=o.lastChild;i;)r.insertAfter(i.cloneNode(!0),e),i=i.previousSibling;r.remove(e)}if(1==e.nodeType)if(n=n||e.ownerDocument||r.doc,g)try{1==e.nodeType&&r.hasOuterHTML?e.outerHTML=t:i()}catch(o){i()}else i()})},decode:a.decode,encode:a.encodeAllRaw,insertAfter:function(e,t){return t=this.get(t),this.run(e,function(e){var n,r;return n=t.parentNode,r=t.nextSibling,r?n.insertBefore(e,r):n.appendChild(e),e})},replace:function(e,t,n){var r=this;return r.run(t,function(t){return d(t,"array")&&(e=e.cloneNode(!0)),n&&u(f(t.childNodes),function(t){e.appendChild(t)}),t.parentNode.replaceChild(e,t)})},rename:function(e,t){var n=this,r;return e.nodeName!=t.toUpperCase()&&(r=n.create(t),u(n.getAttribs(e),function(t){n.setAttrib(r,t.nodeName,n.getAttrib(e,t.nodeName))}),n.replace(r,e,1)),r||e},findCommonAncestor:function(e,t){for(var n=e,r;n;){for(r=t;r&&n!=r;)r=r.parentNode;if(n==r)break;n=n.parentNode}return!n&&e.ownerDocument?e.ownerDocument.documentElement:n},toHex:function(e){return this.styles.toHex(l.trim(e))},getClasses:function(){function e(t){u(t.imports,function(t){e(t)}),u(t.cssRules||t.rules,function(t){switch(t.type||1){case 1:t.selectorText&&u(t.selectorText.split(","),function(e){e=e.replace(/^\s*|\s*$|^\s\./g,""),!/\.mce/.test(e)&&/\.[\w\-]+$/.test(e)&&(o=e,e=e.replace(/.*\.([a-z0-9_\-]+).*/i,"$1"),(!i||(e=i(e,o)))&&(r[e]||(n.push({"class":e}),r[e]=1)))});break;case 3:e(t.styleSheet)}})}var t=this,n=[],r={},i=t.settings.class_filter,o;if(t.classes)return t.classes;try{u(t.doc.styleSheets,e)}catch(a){}return n.length>0&&(t.classes=n),n},run:function(e,t,n){var r=this,i;return"string"==typeof e&&(e=r.get(e)),e?(n=n||this,e.nodeType||!e.length&&0!==e.length?t.call(n,e):(i=[],u(e,function(e,o){e&&("string"==typeof e&&(e=r.get(e)),i.push(t.call(n,e,o)))}),i)):!1},getAttribs:function(e){var t;if(e=this.get(e),!e)return[];if(g){if(t=[],"OBJECT"==e.nodeName)return e.attributes;"OPTION"===e.nodeName&&this.getAttrib(e,"selected")&&t.push({specified:1,nodeName:"selected"});var n=/<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi;return e.cloneNode(!1).outerHTML.replace(n,"").replace(/[\w:\-]+/gi,function(e){t.push({specified:1,nodeName:e})}),t}return e.attributes},isEmpty:function(e,t){var n=this,r,o,a,s,l,c=0;if(e=e.firstChild){s=new i(e,e.parentNode),t=t||n.schema?n.schema.getNonEmptyElements():null;do{if(a=e.nodeType,1===a){if(e.getAttribute("data-mce-bogus"))continue;if(l=e.nodeName.toLowerCase(),t&&t[l]){if("br"===l){c++;continue}return!1}for(o=n.getAttribs(e),r=e.attributes.length;r--;)if(l=e.attributes[r].nodeName,"name"===l||"data-mce-bookmark"===l)return!1}if(8==a)return!1;if(3===a&&!y.test(e.nodeValue))return!1}while(e=s.next())}return 1>=c},createRng:function(){var e=this.doc;return e.createRange?e.createRange():new o(this)},nodeIndex:function(e,t){var n=0,r,i,o;if(e)for(r=e.nodeType,e=e.previousSibling,i=e;e;e=e.previousSibling)o=e.nodeType,(!t||3!=o||o!=r&&e.nodeValue.length)&&(n++,r=o);return n},split:function(e,n,r){function i(e){function t(e){var t=e.previousSibling&&"SPAN"==e.previousSibling.nodeName,n=e.nextSibling&&"SPAN"==e.nextSibling.nodeName;return t&&n}var n,r=e.childNodes,a=e.nodeType;if(1!=a||"bookmark"!=e.getAttribute("data-mce-type")){for(n=r.length-1;n>=0;n--)i(r[n]);if(9!=a){if(3==a&&e.nodeValue.length>0){var s=p(e.nodeValue).length;if(!o.isBlock(e.parentNode)||s>0||0===s&&t(e))return}else if(1==a&&(r=e.childNodes,1==r.length&&r[0]&&1==r[0].nodeType&&"bookmark"==r[0].getAttribute("data-mce-type")&&e.parentNode.insertBefore(r[0],e),r.length||/^(br|hr|input|img)$/i.test(e.nodeName)))return;o.remove(e)}return e}}var o=this,a=o.createRng(),s,l,c;return e&&n?(a.setStart(e.parentNode,o.nodeIndex(e)),a.setEnd(n.parentNode,o.nodeIndex(n)),s=a.extractContents(),a=o.createRng(),a.setStart(n.parentNode,o.nodeIndex(n)+1),a.setEnd(e.parentNode,o.nodeIndex(e)+1),l=a.extractContents(),c=e.parentNode,c.insertBefore(i(s),e),r?c.replaceChild(r,n):c.insertBefore(n,e),c.insertBefore(i(l),e),o.remove(e),r||n):t},bind:function(e,t,n,r){return this.events.bind(e,t,n,r||this)},unbind:function(e,t,n){return this.events.unbind(e,t,n)},fire:function(e,t,n){return this.events.fire(e,t,n)},getContentEditable:function(e){var t;return 1!=e.nodeType?null:(t=e.getAttribute("data-mce-contenteditable"),t&&"inherit"!==t?t:"inherit"!==e.contentEditable?e.contentEditable:null)},destroy:function(){var e=this;e.win=e.doc=e.root=e.events=e.frag=null},dumpRng:function(e){return"startContainer: "+e.startContainer.nodeName+", startOffset: "+e.startOffset+", endContainer: "+e.endContainer.nodeName+", endOffset: "+e.endOffset},_findSib:function(e,t,n){var r=this,i=t;if(e)for("string"==typeof i&&(i=function(e){return r.is(e,t)}),e=e[n];e;e=e[n])if(i(e))return e;return null}},c.DOM=new c(document),c}),r(y,[v,p],function(e,n){function r(){function e(e,t){function n(){o.remove(s),a&&(a.onreadystatechange=a.onload=a=null),t()}function r(){"undefined"!=typeof console&&console.log&&console.log("Failed to load: "+e)}var o=i,a,s;s=o.uniqueId(),a=document.createElement("script"),a.id=s,a.type="text/javascript",a.src=e,a.onload=n,a.onreadystatechange=function(){/loaded|complete/.test(a.readyState)&&n()},a.onerror=r,(document.getElementsByTagName("head")[0]||document.body).appendChild(a)}var n=0,r=1,s=2,l={},c=[],u={},d=[],f=0,p;this.isDone=function(e){return l[e]==s},this.markDone=function(e){l[e]=s},this.add=this.load=function(e,t,r){var i=l[e];i==p&&(c.push(e),l[e]=n),t&&(u[e]||(u[e]=[]),u[e].push({func:t,scope:r||this}))},this.loadQueue=function(e,t){this.loadScripts(c,e,t)},this.loadScripts=function(n,i,c){function h(e){o(u[e],function(e){e.func.call(e.scope)}),u[e]=p}var m;d.push({func:i,scope:c||this}),m=function(){var i=a(n);n.length=0,o(i,function(n){return l[n]==s?(h(n),t):(l[n]!=r&&(l[n]=r,f++,e(n,function(){l[n]=s,f--,h(n),m()})),t)}),f||(o(d,function(e){e.func.call(e.scope)}),d.length=0)},m()}}var i=e.DOM,o=n.each,a=n.grep;return r.ScriptLoader=new r,r}),r(b,[y,p],function(e,n){function r(){var e=this;e.items=[],e.urls={},e.lookup={}}var i=n.each;return r.prototype={get:function(e){return this.lookup[e]?this.lookup[e].instance:t},dependencies:function(e){var t;return this.lookup[e]&&(t=this.lookup[e].dependencies),t||[]},requireLangPack:function(t){var n=r.settings;n&&n.language&&n.language_load!==!1&&e.ScriptLoader.add(this.urls[t]+"/langs/"+n.language+".js")},add:function(e,t,n){return this.items.push(t),this.lookup[e]={instance:t,dependencies:n},t},createUrl:function(e,t){return"object"==typeof t?t:{prefix:e.prefix,resource:t,suffix:e.suffix}},addComponents:function(t,n){var r=this.urls[t];i(n,function(t){e.ScriptLoader.add(r+"/"+t)})},load:function(n,o,a,s){function l(){var r=c.dependencies(n);i(r,function(e){var n=c.createUrl(o,e);c.load(n.resource,n,t,t)}),a&&(s?a.call(s):a.call(e))}var c=this,u=o;c.urls[n]||("object"==typeof o&&(u=o.prefix+o.resource+o.suffix),0!==u.indexOf("/")&&-1==u.indexOf("://")&&(u=r.baseURL+"/"+u),c.urls[n]=u.substring(0,u.lastIndexOf("/")),c.lookup[n]?l():e.ScriptLoader.add(u,l,s))}},r.PluginManager=new r,r.ThemeManager=new r,r}),r(C,[],function(){function e(e,t,n){var r,i,o=n?"lastChild":"firstChild",a=n?"prev":"next";if(e[o])return e[o];if(e!==t){if(r=e[a])return r;for(i=e.parent;i&&i!==t;i=i.parent)if(r=i[a])return r}}function t(e,t){this.name=e,this.type=t,1===t&&(this.attributes=[],this.attributes.map={})}var n=/^[ \t\r\n]*$/,r={"#text":3,"#comment":8,"#cdata":4,"#pi":7,"#doctype":10,"#document-fragment":11}; +return t.prototype={replace:function(e){var t=this;return e.parent&&e.remove(),t.insert(e,t),t.remove(),t},attr:function(e,t){var n=this,r,i,o;if("string"!=typeof e){for(i in e)n.attr(i,e[i]);return n}if(r=n.attributes){if(t!==o){if(null===t){if(e in r.map)for(delete r.map[e],i=r.length;i--;)if(r[i].name===e)return r=r.splice(i,1),n;return n}if(e in r.map){for(i=r.length;i--;)if(r[i].name===e){r[i].value=t;break}}else r.push({name:e,value:t});return r.map[e]=t,n}return r.map[e]}},clone:function(){var e=this,n=new t(e.name,e.type),r,i,o,a,s;if(o=e.attributes){for(s=[],s.map={},r=0,i=o.length;i>r;r++)a=o[r],"id"!==a.name&&(s[s.length]={name:a.name,value:a.value},s.map[a.name]=a.value);n.attributes=s}return n.value=e.value,n.shortEnded=e.shortEnded,n},wrap:function(e){var t=this;return t.parent.insert(e,t),e.append(t),t},unwrap:function(){var e=this,t,n;for(t=e.firstChild;t;)n=t.next,e.insert(t,e,!0),t=n;e.remove()},remove:function(){var e=this,t=e.parent,n=e.next,r=e.prev;return t&&(t.firstChild===e?(t.firstChild=n,n&&(n.prev=null)):r.next=n,t.lastChild===e?(t.lastChild=r,r&&(r.next=null)):n.prev=r,e.parent=e.next=e.prev=null),e},append:function(e){var t=this,n;return e.parent&&e.remove(),n=t.lastChild,n?(n.next=e,e.prev=n,t.lastChild=e):t.lastChild=t.firstChild=e,e.parent=t,e},insert:function(e,t,n){var r;return e.parent&&e.remove(),r=t.parent||this,n?(t===r.firstChild?r.firstChild=e:t.prev.next=e,e.prev=t.prev,e.next=t,t.prev=e):(t===r.lastChild?r.lastChild=e:t.next.prev=e,e.next=t.next,e.prev=t,t.next=e),e.parent=r,e},getAll:function(t){var n=this,r,i=[];for(r=n.firstChild;r;r=e(r,n))r.name===t&&i.push(r);return i},empty:function(){var t=this,n,r,i;if(t.firstChild){for(n=[],i=t.firstChild;i;i=e(i,t))n.push(i);for(r=n.length;r--;)i=n[r],i.parent=i.firstChild=i.lastChild=i.next=i.prev=null}return t.firstChild=t.lastChild=null,t},isEmpty:function(t){var r=this,i=r.firstChild,o,a;if(i)do{if(1===i.type){if(i.attributes.map["data-mce-bogus"])continue;if(t[i.name])return!1;for(o=i.attributes.length;o--;)if(a=i.attributes[o].name,"name"===a||0===a.indexOf("data-mce-"))return!1}if(8===i.type)return!1;if(3===i.type&&!n.test(i.value))return!1}while(i=e(i,r));return!0},walk:function(t){return e(this,null,t)}},t.create=function(e,n){var i,o;if(i=new t(e,r[e]||1),n)for(o in n)i.attr(o,n[o]);return i},t}),r(x,[p],function(e){function t(e,t){return e?e.split(t||" "):[]}function n(e){function n(e,n,r){function i(e){var t={},n,r;for(n=0,r=e.length;r>n;n++)t[e[n]]={};return t}var o,l,c,u=arguments;for(r=r||[],n=n||"","string"==typeof r&&(r=t(r)),l=3;u.length>l;l++)"string"==typeof u[l]&&(u[l]=t(u[l])),r.push.apply(r,u[l]);for(e=t(e),o=e.length;o--;)c=[].concat(s,t(n)),a[e[o]]={attributes:i(c),attributesOrder:c,children:i(r)}}function i(e,n){var r,i,o,s;for(e=t(e),r=e.length,n=t(n);r--;)for(i=a[e[r]],o=0,s=n.length;s>o;o++)i.attributes[n[o]]={},i.attributesOrder.push(n[o])}var a={},s,l,c,u,d,f,p;return r[e]?r[e]:(s=t("id accesskey class dir lang style tabindex title"),l=t("onabort onblur oncancel oncanplay oncanplaythrough onchange onclick onclose oncontextmenu oncuechange ondblclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop ondurationchange onemptied onended onerror onfocus oninput oninvalid onkeydown onkeypress onkeyup onload onloadeddata onloadedmetadata onloadstart onmousedown onmousemove onmouseout onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange onreset onscroll onseeked onseeking onseeking onselect onshow onstalled onsubmit onsuspend ontimeupdate onvolumechange onwaiting"),c=t("address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul"),u=t("a abbr b bdo br button cite code del dfn em embed i iframe img input ins kbd label map noscript object q s samp script select small span strong sub sup textarea u var #text #comment"),"html4"!=e&&(s.push.apply(s,t("contenteditable contextmenu draggable dropzone hidden spellcheck translate")),c.push.apply(c,t("article aside details dialog figure header footer hgroup section nav")),u.push.apply(u,t("audio canvas command datalist mark meter output progress time wbr video ruby bdi keygen"))),"html5-strict"!=e&&(s.push("xml:lang"),p=t("acronym applet basefont big font strike tt"),u.push.apply(u,p),o(p,function(e){n(e,"",u)}),f=t("center dir isindex noframes"),c.push.apply(c,f),d=[].concat(c,u),o(f,function(e){n(e,"",d)})),d=d||[].concat(c,u),n("html","manifest","head body"),n("head","","base command link meta noscript script style title"),n("title hr noscript br"),n("base","href target"),n("link","href rel media hreflang type sizes hreflang"),n("meta","name http-equiv content charset"),n("style","media type scoped"),n("script","src async defer type charset"),n("body","onafterprint onbeforeprint onbeforeunload onblur onerror onfocus onhashchange onload onmessage onoffline ononline onpagehide onpageshow onpopstate onresize onscroll onstorage onunload",d),n("address dt dd div caption","",d),n("h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn","",u),n("blockquote","cite",d),n("ol","reversed start type","li"),n("ul","","li"),n("li","value",d),n("dl","","dt dd"),n("a","href target rel media hreflang type",u),n("q","cite",u),n("ins del","cite datetime",d),n("img","src alt usemap ismap width height"),n("iframe","src name width height",d),n("embed","src type width height"),n("object","data type typemustmatch name usemap form width height",d,"param"),n("param","name value"),n("map","name",d,"area"),n("area","alt coords shape href target rel media hreflang type"),n("table","border","caption colgroup thead tfoot tbody tr"+("html4"==e?" col":"")),n("colgroup","span","col"),n("col","span"),n("tbody thead tfoot","","tr"),n("tr","","td th"),n("td","colspan rowspan headers",d),n("th","colspan rowspan headers scope abbr",d),n("form","accept-charset action autocomplete enctype method name novalidate target",d),n("fieldset","disabled form name",d,"legend"),n("label","form for",u),n("input","accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate formtarget height list max maxlength min multiple name pattern readonly required size src step type value width"),n("button","disabled form formaction formenctype formmethod formnovalidate formtarget name type value","html4"==e?d:u),n("select","disabled form multiple name required size","option optgroup"),n("optgroup","disabled label","option"),n("option","disabled label selected value"),n("textarea","cols dirname disabled form maxlength name readonly required rows wrap"),n("menu","type label",d,"li"),n("noscript","",d),"html4"!=e&&(n("wbr"),n("ruby","",u,"rt rp"),n("figcaption","",d),n("mark rt rp summary bdi","",u),n("canvas","width height",d),n("video","src crossorigin poster preload autoplay mediagroup loop muted controls width height",d,"track source"),n("audio","src crossorigin preload autoplay mediagroup loop muted controls",d,"track source"),n("source","src type media"),n("track","kind src srclang label default"),n("datalist","",u,"option"),n("article section nav aside header footer","",d),n("hgroup","","h1 h2 h3 h4 h5 h6"),n("figure","",d,"figcaption"),n("time","datetime",u),n("dialog","open",d),n("command","type label icon disabled checked radiogroup command"),n("output","for form name",u),n("progress","value max",u),n("meter","value min max low high optimum",u),n("details","open",d,"summary"),n("keygen","autofocus challenge disabled form keytype name")),"html5-strict"!=e&&(i("script","language xml:space"),i("style","xml:space"),i("object","declare classid codebase codetype archive standby align border hspace vspace"),i("param","valuetype type"),i("a","charset name rev shape coords"),i("br","clear"),i("applet","codebase archive code object alt name width height align hspace vspace"),i("img","name longdesc align border hspace vspace"),i("iframe","longdesc frameborder marginwidth marginheight scrolling align"),i("font basefont","size color face"),i("input","usemap align"),i("select","onchange"),i("textarea"),i("h1 h2 h3 h4 h5 h6 div p legend caption","align"),i("ul","type compact"),i("li","type"),i("ol dl menu dir","compact"),i("pre","width xml:space"),i("hr","align noshade size width"),i("isindex","prompt"),i("table","summary width frame rules cellspacing cellpadding align bgcolor"),i("col","width align char charoff valign"),i("colgroup","width align char charoff valign"),i("thead","align char charoff valign"),i("tr","align char charoff valign bgcolor"),i("th","axis align char charoff valign nowrap bgcolor width height"),i("form","accept"),i("td","abbr axis scope align char charoff valign nowrap bgcolor width height"),i("tfoot","align char charoff valign"),i("tbody","align char charoff valign"),i("area","nohref"),i("body","background bgcolor text link vlink alink")),"html4"!=e&&(i("input button select textarea","autofocus"),i("input textarea","placeholder"),i("a","download"),i("link script img","crossorigin"),i("iframe","srcdoc sandbox seamless allowfullscreen")),o(t("a form meter progress dfn"),function(e){a[e]&&delete a[e].children[e]}),delete a.caption.children.table,r[e]=a,a)}var r={},i=e.makeMap,o=e.each,a=e.extend,s=e.explode,l=e.inArray;return function(e){function c(t,n,o){var s=e[t];return s?s=i(s,",",i(s.toUpperCase()," ")):(s=r[t],s||(s=i(n," ",i(n.toUpperCase()," ")),s=a(s,o),r[t]=s)),s}function u(e){return RegExp("^"+e.replace(/([?+*])/g,".$1")+"$")}function d(e){var n,r,o,a,s,c,d,f,p,h,m,g,y,C,x,w,_,N,k,E=/^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)\])?$/,S=/^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/,T=/[*?+]/;if(e)for(e=t(e,","),v["@"]&&(w=v["@"].attributes,_=v["@"].attributesOrder),n=0,r=e.length;r>n;n++)if(s=E.exec(e[n])){if(C=s[1],p=s[2],x=s[3],f=s[5],g={},y=[],c={attributes:g,attributesOrder:y},"#"===C&&(c.paddEmpty=!0),"-"===C&&(c.removeEmpty=!0),"!"===s[4]&&(c.removeEmptyAttrs=!0),w){for(N in w)g[N]=w[N];y.push.apply(y,_)}if(f)for(f=t(f,"|"),o=0,a=f.length;a>o;o++)if(s=S.exec(f[o])){if(d={},m=s[1],h=s[2].replace(/::/g,":"),C=s[3],k=s[4],"!"===m&&(c.attributesRequired=c.attributesRequired||[],c.attributesRequired.push(h),d.required=!0),"-"===m){delete g[h],y.splice(l(y,h),1);continue}C&&("="===C&&(c.attributesDefault=c.attributesDefault||[],c.attributesDefault.push({name:h,value:k}),d.defaultValue=k),":"===C&&(c.attributesForced=c.attributesForced||[],c.attributesForced.push({name:h,value:k}),d.forcedValue=k),"<"===C&&(d.validValues=i(k,"?"))),T.test(h)?(c.attributePatterns=c.attributePatterns||[],d.pattern=u(h),c.attributePatterns.push(d)):(g[h]||y.push(h),g[h]=d)}w||"@"!=p||(w=g,_=y),x&&(c.outputName=p,v[x]=c),T.test(p)?(c.pattern=u(p),b.push(c)):v[p]=c}}function f(e){v={},b=[],d(e),o(x,function(e,t){y[t]=e.children})}function p(e){var n=/^(~)?(.+)$/;e&&o(t(e,","),function(e){var t=n.exec(e),r="~"===t[1],i=r?"span":"div",a=t[2];y[a]=y[i],R[a]=i,r||(E[a.toUpperCase()]={},E[a]={}),v[a]||(v[a]=v[i]),o(y,function(e){e[i]&&(e[a]=e[i])})})}function h(e){var n=/^([+\-]?)(\w+)\[([^\]]+)\]$/;e&&o(t(e,","),function(e){var r=n.exec(e),i,a;r&&(a=r[1],i=a?y[r[2]]:y[r[2]]={"#comment":{}},i=y[r[2]],o(t(r[3],"|"),function(e){"-"===a?delete i[e]:i[e]={}}))})}function m(e){var t=v[e],n;if(t)return t;for(n=b.length;n--;)if(t=b[n],t.pattern.test(e))return t}var g=this,v={},y={},b=[],C,x,w,_,N,k,E,S,T,R={},A={};e=e||{},x=n(e.schema),e.verify_html===!1&&(e.valid_elements="*[*]"),e.valid_styles&&(C={},o(e.valid_styles,function(e,t){C[t]=s(e)})),w=c("whitespace_elements","pre script noscript style textarea video audio iframe object"),_=c("self_closing_elements","colgroup dd dt li option p td tfoot th thead tr"),N=c("short_ended_elements","area base basefont br col frame hr img input isindex link meta param embed source wbr track"),k=c("boolean_attributes","checked compact declare defer disabled ismap multiple nohref noresize noshade nowrap readonly selected autoplay loop controls"),S=c("non_empty_elements","td th iframe video audio object",N),T=c("text_block_elements","h1 h2 h3 h4 h5 h6 p div address pre form blockquote center dir fieldset header footer article section hgroup aside nav figure"),E=c("block_elements","hr table tbody thead tfoot th tr td li ol ul caption dl dt dd noscript menu isindex samp option datalist select optgroup",T),o((e.special||"script noscript style textarea").split(" "),function(e){A[e]=RegExp("]*>","gi")}),e.valid_elements?f(e.valid_elements):(o(x,function(e,t){v[t]={attributes:e.attributes,attributesOrder:e.attributesOrder},y[t]=e.children}),"html5"!=e.schema&&o(t("strong/b em/i"),function(e){e=t(e,"/"),v[e[1]].outputName=e[0]}),v.img.attributesDefault=[{name:"alt",value:""}],o(t("ol ul sub sup blockquote span font a table tbody tr strong em b i"),function(e){v[e]&&(v[e].removeEmpty=!0)}),o(t("p h1 h2 h3 h4 h5 h6 th td pre div address caption"),function(e){v[e].paddEmpty=!0}),o(t("span"),function(e){v[e].removeEmptyAttrs=!0})),p(e.custom_elements),h(e.valid_children),d(e.extended_valid_elements),h("+ol[ul|ol],+ul[ul|ol]"),e.invalid_elements&&o(s(e.invalid_elements),function(e){v[e]&&delete v[e]}),m("span")||d("span[!data-mce-type|*]"),g.children=y,g.styles=C,g.getBoolAttrs=function(){return k},g.getBlockElements=function(){return E},g.getTextBlockElements=function(){return T},g.getShortEndedElements=function(){return N},g.getSelfClosingElements=function(){return _},g.getNonEmptyElements=function(){return S},g.getWhiteSpaceElements=function(){return w},g.getSpecialElements=function(){return A},g.isValidChild=function(e,t){var n=y[e];return!(!n||!n[t])},g.isValid=function(e,t){var n,r,i=m(e);if(i){if(!t)return!0;if(i.attributes[t])return!0;if(n=i.attributePatterns)for(r=n.length;r--;)if(n[r].pattern.test(e))return!0}return!1},g.getElementRule=m,g.getCustomElements=function(){return R},g.addValidElements=d,g.setValidElements=f,g.addCustomElements=p,g.addValidChildren=h,g.elements=v}}),r(w,[x,m,p],function(e,t,n){var r=n.each;return function(n,i){var o=this,a=function(){};n=n||{},o.schema=i=i||new e,n.fix_self_closing!==!1&&(n.fix_self_closing=!0),r("comment cdata text start end pi doctype".split(" "),function(e){e&&(o[e]=n[e]||a)}),o.parse=function(e){function r(e){var t,n;for(t=d.length;t--&&d[t].name!==e;);if(t>=0){for(n=d.length-1;n>=t;n--)e=d[n],e.valid&&a.end(e.name);d.length=t}}function o(e,t,n,r,i){var o,a;if(t=t.toLowerCase(),n=t in b?t:I(n||r||i||""),x&&!g&&0!==t.indexOf("data-mce-")){if(o=E[t],!o&&S){for(a=S.length;a--&&(o=S[a],!o.pattern.test(t)););-1===a&&(o=null)}if(!o)return;if(o.validValues&&!(n in o.validValues))return}f.map[t]=n,f.push({name:t,value:n})}var a=this,s,l=0,c,u,d=[],f,p,h,m,g,v,y,b,C,x,w,_,N,k,E,S,T,R,A,B,L,H,M,D,P,O=0,I=t.decode,F;for(H=RegExp("<(?:(?:!--([\\w\\W]*?)-->)|(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|(?:!DOCTYPE([\\w\\W]*?)>)|(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|(?:\\/([^>]+)>)|(?:([A-Za-z0-9\\-\\:\\.]+)((?:\\s+[^\"'>]+(?:(?:\"[^\"]*\")|(?:'[^']*')|[^>]*))*|\\/|\\s+)>))","g"),M=/([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g,y=i.getShortEndedElements(),L=n.self_closing_elements||i.getSelfClosingElements(),b=i.getBoolAttrs(),x=n.validate,v=n.remove_internals,F=n.fix_self_closing,D=i.getSpecialElements();s=H.exec(e);){if(s.index>l&&a.text(I(e.substr(l,s.index-l))),c=s[6])c=c.toLowerCase(),":"===c.charAt(0)&&(c=c.substr(1)),r(c);else if(c=s[7]){if(c=c.toLowerCase(),":"===c.charAt(0)&&(c=c.substr(1)),C=c in y,F&&L[c]&&d.length>0&&d[d.length-1].name===c&&r(c),!x||(w=i.getElementRule(c))){if(_=!0,x&&(E=w.attributes,S=w.attributePatterns),(k=s[8])?(g=-1!==k.indexOf("data-mce-type"),g&&v&&(_=!1),f=[],f.map={},k.replace(M,o)):(f=[],f.map={}),x&&!g){if(T=w.attributesRequired,R=w.attributesDefault,A=w.attributesForced,B=w.removeEmptyAttrs,B&&!f.length&&(_=!1),A)for(p=A.length;p--;)N=A[p],m=N.name,P=N.value,"{$uid}"===P&&(P="mce_"+O++),f.map[m]=P,f.push({name:m,value:P});if(R)for(p=R.length;p--;)N=R[p],m=N.name,m in f.map||(P=N.value,"{$uid}"===P&&(P="mce_"+O++),f.map[m]=P,f.push({name:m,value:P}));if(T){for(p=T.length;p--&&!(T[p]in f.map););-1===p&&(_=!1)}f.map["data-mce-bogus"]&&(_=!1)}_&&a.start(c,f,C)}else _=!1;if(u=D[c]){u.lastIndex=l=s.index+s[0].length,(s=u.exec(e))?(_&&(h=e.substr(l,s.index-l)),l=s.index+s[0].length):(h=e.substr(l),l=e.length),_&&(h.length>0&&a.text(h,!0),a.end(c)),H.lastIndex=l;continue}C||(k&&k.indexOf("/")==k.length-1?_&&a.end(c):d.push({name:c,valid:_}))}else(c=s[1])?a.comment(c):(c=s[2])?a.cdata(c):(c=s[3])?a.doctype(c):(c=s[4])&&a.pi(c,s[5]);l=s.index+s[0].length}for(e.length>l&&a.text(I(e.substr(l))),p=d.length-1;p>=0;p--)c=d[p],c.valid&&a.end(c.name)}}}),r(_,[C,x,w,p],function(e,n,r,i){var o=i.makeMap,a=i.each,s=i.explode,l=i.extend;return function(i,c){function u(t){var n,r,i,a,s,l,u,f,p,h,m,g,v,y;for(m=o("tr,td,th,tbody,thead,tfoot,table"),h=c.getNonEmptyElements(),g=c.getTextBlockElements(),n=0;t.length>n;n++)if(r=t[n],r.parent&&!r.fixed)if(g[r.name]&&"li"==r.parent.name){for(v=r.next;v&&g[v.name];)v.name="li",v.fixed=!0,r.parent.insert(v,r.parent),v=v.next;r.unwrap(r)}else{for(a=[r],i=r.parent;i&&!c.isValidChild(i.name,r.name)&&!m[i.name];i=i.parent)a.push(i);if(i&&a.length>1){for(a.reverse(),s=l=d.filterNode(a[0].clone()),p=0;a.length-1>p;p++){for(c.isValidChild(l.name,a[p].name)?(u=d.filterNode(a[p].clone()),l.append(u)):u=l,f=a[p].firstChild;f&&f!=a[p+1];)y=f.next,u.append(f),f=y;l=u}s.isEmpty(h)?i.insert(r,a[0],!0):(i.insert(s,a[0],!0),i.insert(r,s)),i=a[0],(i.isEmpty(h)||i.firstChild===i.lastChild&&"br"===i.firstChild.name)&&i.empty().remove()}else if(r.parent){if("li"===r.name){if(v=r.prev,v&&("ul"===v.name||"ul"===v.name)){v.append(r);continue}if(v=r.next,v&&("ul"===v.name||"ul"===v.name)){v.insert(r,v.firstChild,!0);continue}r.wrap(d.filterNode(new e("ul",1)));continue}c.isValidChild(r.parent.name,"div")&&c.isValidChild("div",r.name)?r.wrap(d.filterNode(new e("div",1))):"style"===r.name||"script"===r.name?r.empty().remove():r.unwrap()}}}var d=this,f={},p=[],h={},m={};i=i||{},i.validate="validate"in i?i.validate:!0,i.root_name=i.root_name||"body",d.schema=c=c||new n,d.filterNode=function(e){var t,n,r;n in f&&(r=h[n],r?r.push(e):h[n]=[e]),t=p.length;for(;t--;)n=p[t].name,n in e.attributes.map&&(r=m[n],r?r.push(e):m[n]=[e]);return e},d.addNodeFilter=function(e,t){a(s(e),function(e){var n=f[e];n||(f[e]=n=[]),n.push(t)})},d.addAttributeFilter=function(e,n){a(s(e),function(e){var r;for(r=0;p.length>r;r++)if(p[r].name===e)return p[r].callbacks.push(n),t;p.push({name:e,callbacks:[n]})})},d.parse=function(n,a){function s(){function e(e){e&&(t=e.firstChild,t&&3==t.type&&(t.value=t.value.replace(A,"")),t=e.lastChild,t&&3==t.type&&(t.value=t.value.replace(H,"")))}var t=b.firstChild,n,r;if(c.isValidChild(b.name,F.toLowerCase())){for(;t;)n=t.next,3==t.type||1==t.type&&"p"!==t.name&&!R[t.name]&&!t.attr("data-mce-type")?r?r.append(t):(r=d(F,1),b.insert(r,t),r.append(t)):(e(r),r=null),t=n;e(r)}}function d(t,n){var r=new e(t,n),i;return t in f&&(i=h[t],i?i.push(r):h[t]=[r]),r}function g(e){var t,n,r;for(t=e.prev;t&&3===t.type;)n=t.value.replace(H,""),n.length>0?(t.value=n,t=t.prev):(r=t.prev,t.remove(),t=r)}function v(e){var t,n={};for(t in e)"li"!==t&&"p"!=t&&(n[t]=e[t]);return n}var y,b,C,x,w,_,N,k,E,S,T,R,A,B=[],L,H,M,D,P,O,I,F;if(a=a||{},h={},m={},R=l(o("script,style,head,html,body,title,meta,param"),c.getBlockElements()),I=c.getNonEmptyElements(),O=c.children,T=i.validate,F="forced_root_block"in a?a.forced_root_block:i.forced_root_block,P=c.getWhiteSpaceElements(),A=/^[ \t\r\n]+/,H=/[ \t\r\n]+$/,M=/[ \t\r\n]+/g,D=/^[ \t\r\n]+$/,y=new r({validate:T,self_closing_elements:v(c.getSelfClosingElements()),cdata:function(e){C.append(d("#cdata",4)).value=e},text:function(e,t){var n;L||(e=e.replace(M," "),C.lastChild&&R[C.lastChild.name]&&(e=e.replace(A,""))),0!==e.length&&(n=d("#text",3),n.raw=!!t,C.append(n).value=e)},comment:function(e){C.append(d("#comment",8)).value=e},pi:function(e,t){C.append(d(e,7)).value=t,g(C)},doctype:function(e){var t;t=C.append(d("#doctype",10)),t.value=e,g(C)},start:function(e,t,n){var r,i,o,a,s;if(o=T?c.getElementRule(e):{}){for(r=d(o.outputName||e,1),r.attributes=t,r.shortEnded=n,C.append(r),s=O[C.name],s&&O[r.name]&&!s[r.name]&&B.push(r),i=p.length;i--;)a=p[i].name,a in t.map&&(E=m[a],E?E.push(r):m[a]=[r]);R[e]&&g(r),n||(C=r),!L&&P[e]&&(L=!0)}},end:function(n){var r,i,o,a,s;if(i=T?c.getElementRule(n):{}){if(R[n]&&!L){if(r=C.firstChild,r&&3===r.type)if(o=r.value.replace(A,""),o.length>0)r.value=o,r=r.next;else for(a=r.next,r.remove(),r=a;r&&3===r.type;)o=r.value,a=r.next,(0===o.length||D.test(o))&&(r.remove(),r=a),r=a;if(r=C.lastChild,r&&3===r.type)if(o=r.value.replace(H,""),o.length>0)r.value=o,r=r.prev;else for(a=r.prev,r.remove(),r=a;r&&3===r.type;)o=r.value,a=r.prev,(0===o.length||D.test(o))&&(r.remove(),r=a),r=a}if(L&&P[n]&&(L=!1),(i.removeEmpty||i.paddEmpty)&&C.isEmpty(I))if(i.paddEmpty)C.empty().append(new e("#text","3")).value="\u00a0";else if(!C.attributes.map.name&&!C.attributes.map.id)return s=C.parent,C.empty().remove(),C=s,t;C=C.parent}}},c),b=C=new e(a.context||i.root_name,11),y.parse(n),T&&B.length&&(a.context?a.invalid=!0:u(B)),F&&("body"==b.name||a.isRootContent)&&s(),!a.invalid){for(S in h){for(E=f[S],x=h[S],N=x.length;N--;)x[N].parent||x.splice(N,1);for(w=0,_=E.length;_>w;w++)E[w](x,S,a)}for(w=0,_=p.length;_>w;w++)if(E=p[w],E.name in m){for(x=m[E.name],N=x.length;N--;)x[N].parent||x.splice(N,1);for(N=0,k=E.callbacks.length;k>N;N++)E.callbacks[N](x,E.name,a)}}return b},i.remove_trailing_brs&&d.addNodeFilter("br",function(t){var n,r=t.length,i,o=l({},c.getBlockElements()),a=c.getNonEmptyElements(),s,u,d,f,p,h;for(o.body=1,n=0;r>n;n++)if(i=t[n],s=i.parent,o[i.parent.name]&&i===s.lastChild){for(d=i.prev;d;){if(f=d.name,"span"!==f||"bookmark"!==d.attr("data-mce-type")){if("br"!==f)break;if("br"===f){i=null;break}}d=d.prev}i&&(i.remove(),s.isEmpty(a)&&(p=c.getElementRule(s.name),p&&(p.removeEmpty?s.remove():p.paddEmpty&&(s.empty().append(new e("#text",3)).value="\u00a0"))))}else{for(u=i;s.firstChild===u&&s.lastChild===u&&(u=s,!o[s.name]);)s=s.parent;u===s&&(h=new e("#text",3),h.value="\u00a0",i.replace(h))}}),i.allow_html_in_named_anchor||d.addAttributeFilter("id,name",function(e){for(var t=e.length,n,r,i,o;t--;)if(o=e[t],"a"===o.name&&o.firstChild&&!o.attr("href")){i=o.parent,n=o.lastChild;do r=n.prev,i.insert(n,o),n=r;while(n)}})}}),r(N,[m,p],function(e,t){var n=t.makeMap;return function(t){var r=[],i,o,a,s,l;return t=t||{},i=t.indent,o=n(t.indent_before||""),a=n(t.indent_after||""),s=e.getEncodeFunc(t.entity_encoding||"raw",t.entities),l="html"==t.element_format,{start:function(e,t,n){var c,u,d,f;if(i&&o[e]&&r.length>0&&(f=r[r.length-1],f.length>0&&"\n"!==f&&r.push("\n")),r.push("<",e),t)for(c=0,u=t.length;u>c;c++)d=t[c],r.push(" ",d.name,'="',s(d.value,!0),'"');r[r.length]=!n||l?">":" />",n&&i&&a[e]&&r.length>0&&(f=r[r.length-1],f.length>0&&"\n"!==f&&r.push("\n"))},end:function(e){var t;r.push(""),i&&a[e]&&r.length>0&&(t=r[r.length-1],t.length>0&&"\n"!==t&&r.push("\n"))},text:function(e,t){e.length>0&&(r[r.length]=t?e:s(e))},cdata:function(e){r.push("")},comment:function(e){r.push("")},pi:function(e,t){t?r.push(""):r.push(""),i&&r.push("\n")},doctype:function(e){r.push("",i?"\n":"")},reset:function(){r.length=0},getContent:function(){return r.join("").replace(/\n$/,"")}}}}),r(k,[N,x],function(e,t){return function(n,r){var i=this,o=new e(n);n=n||{},n.validate="validate"in n?n.validate:!0,i.schema=r=r||new t,i.writer=o,i.serialize=function(e){function t(e){var n=i[e.type],s,l,c,u,d,f,p,h,m;if(n)n(e);else{if(s=e.name,l=e.shortEnded,c=e.attributes,a&&c&&c.length>1){for(f=[],f.map={},m=r.getElementRule(e.name),p=0,h=m.attributesOrder.length;h>p;p++)u=m.attributesOrder[p],u in c.map&&(d=c.map[u],f.map[u]=d,f.push({name:u,value:d}));for(p=0,h=c.length;h>p;p++)u=c[p].name,u in f.map||(d=c.map[u],f.map[u]=d,f.push({name:u,value:d}));c=f}if(o.start(e.name,c,l),!l){if(e=e.firstChild)do t(e);while(e=e.next);o.end(s)}}}var i,a;return a=n.validate,i={3:function(e){o.text(e.value,e.raw)},8:function(e){o.comment(e.value)},7:function(e){o.pi(e.name,e.value)},10:function(e){o.doctype(e.value)},4:function(e){o.cdata(e.value)},11:function(e){if(e=e.firstChild)do t(e);while(e=e.next)}},o.reset(),1!=e.type||n.inner?i[11](e):t(e),o.getContent()}}}),r(E,[v,_,m,k,C,x,g,p],function(e,t,n,r,i,o,a,s){var l=s.each,c=s.trim,u=e.DOM;return function(e,i){var s,d,f;return i&&(s=i.dom,d=i.schema),s=s||u,d=d||new o(e),e.entity_encoding=e.entity_encoding||"named",e.remove_trailing_brs="remove_trailing_brs"in e?e.remove_trailing_brs:!0,f=new t(e,d),f.addAttributeFilter("src,href,style",function(t,n){for(var r=t.length,i,o,a="data-mce-"+n,l=e.url_converter,c=e.url_converter_scope,u;r--;)i=t[r],o=i.attributes.map[a],o!==u?(i.attr(n,o.length>0?o:null),i.attr(a,null)):(o=i.attributes.map[n],"style"===n?o=s.serializeStyle(s.parseStyle(o),i.name):l&&(o=l.call(c,o,n,i.name)),i.attr(n,o.length>0?o:null))}),f.addAttributeFilter("class",function(e){for(var t=e.length,n,r;t--;)n=e[t],r=n.attr("class").replace(/(?:^|\s)mce-item-\w+(?!\S)/g,""),n.attr("class",r.length>0?r:null)}),f.addAttributeFilter("data-mce-type",function(e,t,n){for(var r=e.length,i;r--;)i=e[r],"bookmark"!==i.attributes.map["data-mce-type"]||n.cleanup||i.remove()}),f.addAttributeFilter("data-mce-expando",function(e,t){for(var n=e.length;n--;)e[n].attr(t,null)}),f.addNodeFilter("noscript",function(e){for(var t=e.length,r;t--;)r=e[t].firstChild,r&&(r.value=n.decode(r.value))}),f.addNodeFilter("script,style",function(e,t){function n(e){return e.replace(/()/g,"\n").replace(/^[\r\n]*|[\r\n]*$/g,"").replace(/^\s*(()?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g,"")}for(var r=e.length,i,o;r--;)i=e[r],o=i.firstChild?i.firstChild.value:"","script"===t?(i.attr("type",(i.attr("type")||"text/javascript").replace(/^mce\-/,"")),o.length>0&&(i.firstChild.value="// ")):o.length>0&&(i.firstChild.value="")}),f.addNodeFilter("#comment",function(e){for(var t=e.length,n;t--;)n=e[t],0===n.value.indexOf("[CDATA[")?(n.name="#cdata",n.type=4,n.value=n.value.replace(/^\[CDATA\[|\]\]$/g,"")):0===n.value.indexOf("mce:protected ")&&(n.name="#text",n.type=3,n.raw=!0,n.value=unescape(n.value).substr(14))}),f.addNodeFilter("xml:namespace,input",function(e,t){for(var n=e.length,r;n--;)r=e[n],7===r.type?r.remove():1===r.type&&("input"!==t||"type"in r.attributes.map||r.attr("type","text"))}),e.fix_list_elements&&f.addNodeFilter("ul,ol",function(e){for(var t=e.length,n,r;t--;)n=e[t],r=n.parent,("ul"===r.name||"ol"===r.name)&&n.prev&&"li"===n.prev.name&&n.prev.append(n)}),f.addAttributeFilter("data-mce-src,data-mce-href,data-mce-style,data-mce-selected",function(e,t){for(var n=e.length;n--;)e[n].attr(t,null)}),{schema:d,addNodeFilter:f.addNodeFilter,addAttributeFilter:f.addAttributeFilter,serialize:function(t,n){var i=this,o,u,p,h,m;return a.ie&&s.select("script,style,select,map").length>0?(m=t.innerHTML,t=t.cloneNode(!1),s.setHTML(t,m)):t=t.cloneNode(!0),o=t.ownerDocument.implementation,o.createHTMLDocument&&(u=o.createHTMLDocument(""),l("BODY"==t.nodeName?t.childNodes:[t],function(e){u.body.appendChild(u.importNode(e,!0))}),t="BODY"!=t.nodeName?u.body.firstChild:u.body,p=s.doc,s.doc=u),n=n||{},n.format=n.format||"html",n.selection&&(n.forced_root_block=""),n.no_events||(n.node=t,i.onPreProcess(n)),h=new r(e,d),n.content=h.serialize(f.parse(c(n.getInner?t.innerHTML:s.getOuterHTML(t)),n)),n.cleanup||(n.content=n.content.replace(/\uFEFF/g,"")),n.no_events||i.onPostProcess(n),p&&(s.doc=p),n.node=null,n.content},addRules:function(e){d.addValidElements(e)},setRules:function(e){d.setValidElements(e)},onPreProcess:function(e){i&&i.fire("PreProcess",e)},onPostProcess:function(e){i&&i.fire("PostProcess",e)}}}}),r(S,[],function(){function e(e){function n(t,n){var r,i=0,o,a,s,l,c,u,d=-1,f;if(r=t.duplicate(),r.collapse(n),f=r.parentElement(),f.ownerDocument===e.dom.doc){for(;"false"===f.contentEditable;)f=f.parentNode;if(!f.hasChildNodes())return{node:f,inside:1};for(s=f.children,o=s.length-1;o>=i;)if(u=Math.floor((i+o)/2),l=s[u],r.moveToElementText(l),d=r.compareEndPoints(n?"StartToStart":"EndToEnd",t),d>0)o=u-1;else{if(!(0>d))return{node:l};i=u+1}if(0>d)for(l?r.collapse(!1):(r.moveToElementText(f),r.collapse(!0),l=f,a=!0),c=0;0!==r.compareEndPoints(n?"StartToStart":"StartToEnd",t)&&0!==r.move("character",1)&&f==r.parentElement();)c++;else for(r.collapse(!0),c=0;0!==r.compareEndPoints(n?"StartToStart":"StartToEnd",t)&&0!==r.move("character",-1)&&f==r.parentElement();)c++;return{node:l,position:d,offset:c,inside:a}}}function r(){function r(e){var r=n(a,e),i,o,l=0,c,u,d;if(i=r.node,o=r.offset,r.inside&&!i.hasChildNodes())return s[e?"setStart":"setEnd"](i,0),t;if(o===u)return s[e?"setStartBefore":"setEndAfter"](i),t;if(0>r.position){if(c=r.inside?i.firstChild:i.nextSibling,!c)return s[e?"setStartAfter":"setEndAfter"](i),t;if(!o)return 3==c.nodeType?s[e?"setStart":"setEnd"](c,0):s[e?"setStartBefore":"setEndBefore"](c),t;for(;c;){if(d=c.nodeValue,l+=d.length,l>=o){i=c,l-=o,l=d.length-l;break}c=c.nextSibling}}else{if(c=i.previousSibling,!c)return s[e?"setStartBefore":"setEndBefore"](i);if(!o)return 3==i.nodeType?s[e?"setStart":"setEnd"](c,i.nodeValue.length):s[e?"setStartAfter":"setEndAfter"](c),t;for(;c;){if(l+=c.nodeValue.length,l>=o){i=c,l-=o;break}c=c.previousSibling}}s[e?"setStart":"setEnd"](i,l)}var a=e.getRng(),s=o.createRng(),l,c,u,d,f;if(l=a.item?a.item(0):a.parentElement(),l.ownerDocument!=o.doc)return s;if(c=e.isCollapsed(),a.item)return s.setStart(l.parentNode,o.nodeIndex(l)),s.setEnd(s.startContainer,s.startOffset+1),s;try{r(!0),c||r()}catch(p){if(-2147024809!=p.number)throw p;f=i.getBookmark(2),u=a.duplicate(),u.collapse(!0),l=u.parentElement(),c||(u=a.duplicate(),u.collapse(!1),d=u.parentElement(),d.innerHTML=d.innerHTML),l.innerHTML=l.innerHTML,i.moveToBookmark(f),a=e.getRng(),r(!0),c||r()}return s}var i=this,o=e.dom,a=!1;this.getBookmark=function(r){function i(e){var t,n,r,i,a=[];for(t=e.parentNode,n=o.getRoot().parentNode;t!=n&&9!==t.nodeType;){for(r=t.children,i=r.length;i--;)if(e===r[i]){a.push(i);break}e=t,t=t.parentNode}return a}function a(e){var r;return r=n(s,e),r?{position:r.position,offset:r.offset,indexes:i(r.node),inside:r.inside}:t}var s=e.getRng(),l={};return 2===r&&(s.item?l.start={ctrl:!0,indexes:i(s.item(0))}:(l.start=a(!0),e.isCollapsed()||(l.end=a()))),l},this.moveToBookmark=function(e){function t(e){var t,n,r,i;for(t=o.getRoot(),n=e.length-1;n>=0;n--)i=t.children,r=e[n],i.length-1>=r&&(t=i[r]);return t}function n(n){var o=e[n?"start":"end"],a,s,l,c;o&&(a=o.position>0,s=i.createTextRange(),s.moveToElementText(t(o.indexes)),c=o.offset,c!==l?(s.collapse(o.inside||a),s.moveStart("character",a?-c:c)):s.collapse(n),r.setEndPoint(n?"StartToStart":"EndToStart",s),n&&r.collapse(!0))}var r,i=o.doc.body;e.start&&(e.start.ctrl?(r=i.createControlRange(),r.addElement(t(e.start.indexes)),r.select()):(r=i.createTextRange(),n(!0),n(),r.select()))},this.addRange=function(n){function r(e){var t,n,r,s,f;r=o.create("a"),t=e?l:u,n=e?c:d,s=i.duplicate(),(t==p||t==p.documentElement)&&(t=h,n=0),3==t.nodeType?(t.parentNode.insertBefore(r,t),s.moveToElementText(r),s.moveStart("character",n),o.remove(r),i.setEndPoint(e?"StartToStart":"EndToEnd",s)):(f=t.childNodes,f.length?(n>=f.length?o.insertAfter(r,f[f.length-1]):t.insertBefore(r,f[n]),s.moveToElementText(r)):t.canHaveHTML&&(t.innerHTML="",r=t.firstChild,s.moveToElementText(r),s.collapse(a)),i.setEndPoint(e?"StartToStart":"EndToEnd",s),o.remove(r))}var i,s,l,c,u,d,f,p=e.dom.doc,h=p.body,m,g;if(l=n.startContainer,c=n.startOffset,u=n.endContainer,d=n.endOffset,i=h.createTextRange(),l==u&&1==l.nodeType){if(c==d&&!l.hasChildNodes()){if(l.canHaveHTML)return f=l.previousSibling,f&&!f.hasChildNodes()&&o.isBlock(f)?f.innerHTML="":f=null,l.innerHTML="",i.moveToElementText(l.lastChild),i.select(),o.doc.selection.clear(),l.innerHTML="",f&&(f.innerHTML=""),t; +c=o.nodeIndex(l),l=l.parentNode}if(c==d-1)try{if(g=l.childNodes[c],s=h.createControlRange(),s.addElement(g),s.select(),m=e.getRng(),m.item&&g===m.item(0))return}catch(v){}}r(!0),r(),i.select()},this.getRangeAt=r}return e}),r(T,[g],function(e){return{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},metaKeyPressed:function(t){return e.mac?t.metaKey:t.ctrlKey&&!t.altKey}}}),r(R,[T,p,g],function(e,n,r){return function(i,o){function a(e){return o.settings.object_resizing===!1?!1:/TABLE|IMG|DIV/.test(e.nodeName)?"false"===e.getAttribute("data-mce-resize")?!1:!0:!1}function s(t){var n,r;n=t.screenX-k,r=t.screenY-E,H=n*N[2]+R,M=r*N[3]+A,H=5>H?5:H,M=5>M?5:M,(e.modifierPressed(t)||"IMG"==x.nodeName&&0!==N[2]*N[3])&&(H=Math.round(M/B),M=Math.round(H*B)),b.setStyles(w,{width:H,height:M}),0>N[2]&&H>=w.clientWidth&&b.setStyle(w,"left",S+(R-H)),0>N[3]&&M>=w.clientHeight&&b.setStyle(w,"top",T+(A-M)),L||(o.fire("ObjectResizeStart",{target:x,width:R,height:A}),L=!0)}function l(){function e(e,t){t&&(x.style[e]||!o.schema.isValid(x.nodeName.toLowerCase(),e)?b.setStyle(x,e,t):b.setAttrib(x,e,t))}L=!1,e("width",H),e("height",M),b.unbind(D,"mousemove",s),b.unbind(D,"mouseup",l),P!=D&&(b.unbind(P,"mousemove",s),b.unbind(P,"mouseup",l)),b.remove(w),O&&"TABLE"!=x.nodeName||c(x),o.fire("ObjectResized",{target:x,width:H,height:M}),o.nodeChanged()}function c(e,n,r){var i,c,d,f,p;i=b.getPos(e,o.getBody()),S=i.x,T=i.y,p=e.getBoundingClientRect(),c=p.width,d=p.height,x!=e&&(g(),x=e,H=M=0),f=o.fire("ObjectSelected",{target:e}),a(e)&&!f.isDefaultPrevented()?C(_,function(e,i){function a(t){L=!0,k=t.screenX,E=t.screenY,R=x.clientWidth,A=x.clientHeight,B=A/R,N=e,w=x.cloneNode(!0),b.addClass(w,"mce-clonedresizable"),w.contentEditable=!1,w.unSelectabe=!0,b.setStyles(w,{left:S,top:T,margin:0}),w.removeAttribute("data-mce-selected"),o.getBody().appendChild(w),b.bind(D,"mousemove",s),b.bind(D,"mouseup",l),P!=D&&(b.bind(P,"mousemove",s),b.bind(P,"mouseup",l))}var u,f;return n?(i==n&&a(r),t):(u=b.get("mceResizeHandle"+i),u?b.show(u):(f=o.getBody(),u=b.add(f,"div",{id:"mceResizeHandle"+i,"data-mce-bogus":!0,"class":"mce-resizehandle",contentEditable:!1,unSelectabe:!0,style:"cursor:"+i+"-resize; margin:0; padding:0"}),b.bind(u,"mousedown",function(e){e.preventDefault(),a(e)})),b.setStyles(u,{left:c*e[0]+S-u.offsetWidth/2,top:d*e[1]+T-u.offsetHeight/2}),t)}):u(),x.setAttribute("data-mce-selected","1")}function u(){var e,t;x&&x.removeAttribute("data-mce-selected");for(e in _)t=b.get("mceResizeHandle"+e),t&&(b.unbind(t),b.remove(t))}function d(e){function n(e,t){do if(e===t)return!0;while(e=e.parentNode)}var r;return C(b.select("img[data-mce-selected],hr[data-mce-selected]"),function(e){e.removeAttribute("data-mce-selected")}),r="mousedown"==e.type?e.target:i.getNode(),r=b.getParent(r,O?"table":"table,img,hr"),r&&n(i.getStart(),r)&&n(i.getEnd(),r)&&(!O||r!=i.getStart()&&"IMG"!==i.getStart().nodeName)?(c(r),t):(u(),t)}function f(e,t,n){e&&e.attachEvent&&e.attachEvent("on"+t,n)}function p(e,t,n){e&&e.detachEvent&&e.detachEvent("on"+t,n)}function h(e){var t=e.srcElement,n,r,i,a,s,l,u;n=t.getBoundingClientRect(),l=e.clientX-n.left,u=e.clientY-n.top;for(r in _)if(i=_[r],a=t.offsetWidth*i[0],s=t.offsetHeight*i[1],8>Math.abs(a-l)&&8>Math.abs(s-u)){N=i;break}L=!0,o.getDoc().selection.empty(),c(t,r,e)}function m(e){var n=e.srcElement;if(n!=x){if(g(),0===n.id.indexOf("mceResizeHandle"))return e.returnValue=!1,t;("IMG"==n.nodeName||"TABLE"==n.nodeName)&&(u(),x=n,f(n,"resizestart",h))}}function g(){p(x,"resizestart",h)}function v(e){var t;if(O){t=D.body.createControlRange();try{return t.addElement(e),t.select(),!0}catch(n){}}}function y(){x=w=null,O&&(g(),p(o.getBody(),"controlselect",m))}var b=o.dom,C=n.each,x,w,_,N,k,E,S,T,R,A,B,L,H,M,D=o.getDoc(),P=document,O=r.ie;_={n:[.5,0,0,-1],e:[1,.5,1,0],s:[.5,1,0,1],w:[0,.5,-1,0],nw:[0,0,-1,-1],ne:[1,0,1,-1],se:[1,1,1,1],sw:[0,1,-1,1]};var I=".mce-content-body";return o.contentStyles.push(I+" div.mce-resizehandle {"+"position: absolute;"+"border: 1px solid black;"+"background: #FFF;"+"width: 5px;"+"height: 5px;"+"z-index: 10000"+"}"+I+" .mce-resizehandle:hover {"+"background: #000"+"}"+I+" img[data-mce-selected], hr[data-mce-selected] {"+"outline: 1px solid black;"+"resize: none"+"}"+I+" .mce-clonedresizable {"+"position: absolute;"+(r.gecko?"":"outline: 1px dashed black;")+"opacity: .5;"+"filter: alpha(opacity=50);"+"z-index: 10000"+"}"),o.on("init",function(){if(O)o.on("ObjectResized",function(e){"TABLE"!=e.target.nodeName&&(u(),v(e.target))}),f(o.getBody(),"controlselect",m);else try{o.getDoc().execCommand("enableObjectResizing",!1,!1)}catch(e){}o.on("nodechange mousedown ResizeEditor",d),o.on("keydown keyup",function(e){x&&"TABLE"==x.nodeName&&d(e)})}),{controlSelect:v,destroy:y}}}),r(A,[f,S,R,g,p],function(e,n,r,i,o){function a(e,t,i,o){var a=this;a.dom=e,a.win=t,a.serializer=i,a.editor=o,a.controlSelection=new r(a,o),o.on("nodechange",function(){var e;e=o.getDoc().selection?o.getDoc().selection.createRange():a.getRng(),a.lastRng=e}),a.win.getSelection||(a.tridentSel=new n(a))}var s=o.each,l=o.grep,c=o.trim,u=i.ie,d=i.opera;return a.prototype={setCursorLocation:function(e,t){var n=this,r=n.dom.createRng();r.setStart(e,t),r.setEnd(e,t),n.setRng(r),n.collapse(!1)},getContent:function(e){var n=this,r=n.getRng(),i=n.dom.create("body"),o=n.getSel(),a,s,l;return e=e||{},a=s="",e.get=!0,e.format=e.format||"html",e.selection=!0,n.editor.fire("BeforeGetContent",e),"text"==e.format?n.isCollapsed()?"":r.text||(o.toString?""+o:""):(r.cloneContents?(l=r.cloneContents(),l&&i.appendChild(l)):r.item!==t||r.htmlText!==t?(i.innerHTML="
    "+(r.item?r.item(0).outerHTML:r.htmlText),i.removeChild(i.firstChild)):i.innerHTML=""+r,/^\s/.test(i.innerHTML)&&(a=" "),/\s+$/.test(i.innerHTML)&&(s=" "),e.getInner=!0,e.content=n.isCollapsed()?"":a+n.serializer.serialize(i,e)+s,n.editor.fire("GetContent",e),e.content)},setContent:function(e,t){var n=this,r=n.getRng(),i,o=n.win.document,a,s;if(t=t||{format:"html"},t.set=!0,t.selection=!0,e=t.content=e,t.no_events||n.editor.fire("BeforeSetContent",t),e=t.content,r.insertNode){e+='_',r.startContainer==o&&r.endContainer==o?o.body.innerHTML=e:(r.deleteContents(),0===o.body.childNodes.length?o.body.innerHTML=e:r.createContextualFragment?r.insertNode(r.createContextualFragment(e)):(a=o.createDocumentFragment(),s=o.createElement("div"),a.appendChild(s),s.outerHTML=e,r.insertNode(a))),i=n.dom.get("__caret"),r=o.createRange(),r.setStartBefore(i),r.setEndBefore(i),n.setRng(r),n.dom.remove("__caret");try{n.setRng(r)}catch(l){}}else r.item&&(o.execCommand("Delete",!1,null),r=n.getRng()),/^\s+/.test(e)?(r.pasteHTML('_'+e),n.dom.remove("__mce_tmp")):r.pasteHTML(e);t.no_events||n.editor.fire("SetContent",t)},getStart:function(){var e=this,t=e.getRng(),n,r,i,o;if(t.duplicate||t.item){if(t.item)return t.item(0);for(i=t.duplicate(),i.collapse(1),n=i.parentElement(),n.ownerDocument!==e.dom.doc&&(n=e.dom.getRoot()),r=o=t.parentElement();o=o.parentNode;)if(o==n){n=r;break}return n}return n=t.startContainer,1==n.nodeType&&n.hasChildNodes()&&(n=n.childNodes[Math.min(n.childNodes.length-1,t.startOffset)]),n&&3==n.nodeType?n.parentNode:n},getEnd:function(){var e=this,t=e.getRng(),n,r;return t.duplicate||t.item?t.item?t.item(0):(t=t.duplicate(),t.collapse(0),n=t.parentElement(),n.ownerDocument!==e.dom.doc&&(n=e.dom.getRoot()),n&&"BODY"==n.nodeName?n.lastChild||n:n):(n=t.endContainer,r=t.endOffset,1==n.nodeType&&n.hasChildNodes()&&(n=n.childNodes[r>0?r-1:r]),n&&3==n.nodeType?n.parentNode:n)},getBookmark:function(e,t){function n(e,t){var n=0;return s(a.select(e),function(e,r){e==t&&(n=r)}),n}function r(e){function t(t){var n,r,i,o=t?"start":"end";n=e[o+"Container"],r=e[o+"Offset"],1==n.nodeType&&"TR"==n.nodeName&&(i=n.childNodes,n=i[Math.min(t?r:r-1,i.length-1)],n&&(r=t?0:n.childNodes.length,e["set"+(t?"Start":"End")](n,r)))}return t(!0),t(),e}function i(){function e(e,n){var i=e[n?"startContainer":"endContainer"],a=e[n?"startOffset":"endOffset"],s=[],l,c,u=0;if(3==i.nodeType){if(t)for(l=i.previousSibling;l&&3==l.nodeType;l=l.previousSibling)a+=l.nodeValue.length;s.push(a)}else c=i.childNodes,a>=c.length&&c.length&&(u=1,a=Math.max(0,c.length-1)),s.push(o.dom.nodeIndex(c[a],t)+u);for(;i&&i!=r;i=i.parentNode)s.push(o.dom.nodeIndex(i,t));return s}var n=o.getRng(!0),r=a.getRoot(),i={};return i.start=e(n,!0),o.isCollapsed()||(i.end=e(n)),i}var o=this,a=o.dom,l,c,u,d,f,p,h="",m;if(2==e)return p=o.getNode(),f=p.nodeName,"IMG"==f?{name:f,index:n(f,p)}:o.tridentSel?o.tridentSel.getBookmark(e):i();if(e)return{rng:o.getRng()};if(l=o.getRng(),u=a.uniqueId(),d=o.isCollapsed(),m="overflow:hidden;line-height:0px",l.duplicate||l.item){if(l.item)return p=l.item(0),f=p.nodeName,{name:f,index:n(f,p)};c=l.duplicate();try{l.collapse(),l.pasteHTML(''+h+""),d||(c.collapse(!1),l.moveToElementText(c.parentElement()),0===l.compareEndPoints("StartToEnd",c)&&c.move("character",-1),c.pasteHTML(''+h+""))}catch(g){return null}}else{if(p=o.getNode(),f=p.nodeName,"IMG"==f)return{name:f,index:n(f,p)};c=r(l.cloneRange()),d||(c.collapse(!1),c.insertNode(a.create("span",{"data-mce-type":"bookmark",id:u+"_end",style:m},h))),l=r(l),l.collapse(!0),l.insertNode(a.create("span",{"data-mce-type":"bookmark",id:u+"_start",style:m},h))}return o.moveToBookmark({id:u,keep:1}),{id:u}},moveToBookmark:function(e){function t(t){var n=e[t?"start":"end"],r,i,o,s;if(n){for(o=n[0],i=c,r=n.length-1;r>=1;r--){if(s=i.childNodes,n[r]>s.length-1)return;i=s[n[r]]}3===i.nodeType&&(o=Math.min(n[0],i.nodeValue.length)),1===i.nodeType&&(o=Math.min(n[0],i.childNodes.length)),t?a.setStart(i,o):a.setEnd(i,o)}return!0}function n(t){var n=o.get(e.id+"_"+t),r,i,a,c,u=e.keep;if(n&&(r=n.parentNode,"start"==t?(u?(r=n.firstChild,i=1):i=o.nodeIndex(n),f=p=r,h=m=i):(u?(r=n.firstChild,i=1):i=o.nodeIndex(n),p=r,m=i),!u)){for(c=n.previousSibling,a=n.nextSibling,s(l(n.childNodes),function(e){3==e.nodeType&&(e.nodeValue=e.nodeValue.replace(/\uFEFF/g,""))});n=o.get(e.id+"_"+t);)o.remove(n,1);c&&a&&c.nodeType==a.nodeType&&3==c.nodeType&&!d&&(i=c.nodeValue.length,c.appendData(a.nodeValue),o.remove(a),"start"==t?(f=p=c,h=m=i):(p=c,m=i))}}function r(e){return!o.isBlock(e)||e.innerHTML||u||(e.innerHTML='
    '),e}var i=this,o=i.dom,a,c,f,p,h,m;if(e)if(e.start){if(a=o.createRng(),c=o.getRoot(),i.tridentSel)return i.tridentSel.moveToBookmark(e);t(!0)&&t()&&i.setRng(a)}else e.id?(n("start"),n("end"),f&&(a=o.createRng(),a.setStart(r(f),h),a.setEnd(r(p),m),i.setRng(a))):e.name?i.select(o.select(e.name)[e.index]):e.rng&&i.setRng(e.rng)},select:function(n,r){function i(n,r){var i=new e(n,n);do{if(3==n.nodeType&&0!==c(n.nodeValue).length)return r?s.setStart(n,0):s.setEnd(n,n.nodeValue.length),t;if("BR"==n.nodeName)return r?s.setStartBefore(n):s.setEndBefore(n),t}while(n=r?i.next():i.prev())}var o=this,a=o.dom,s=a.createRng(),l;if(n){if(!r&&o.controlSelection.controlSelect(n))return;l=a.nodeIndex(n),s.setStart(n.parentNode,l),s.setEnd(n.parentNode,l+1),r&&(i(n,1),i(n)),o.setRng(s)}return n},isCollapsed:function(){var e=this,t=e.getRng(),n=e.getSel();return!t||t.item?!1:t.compareEndPoints?0===t.compareEndPoints("StartToEnd",t):!n||t.collapsed},collapse:function(e){var t=this,n=t.getRng(),r;n.item&&(r=n.item(0),n=t.win.document.body.createTextRange(),n.moveToElementText(r)),n.collapse(!!e),t.setRng(n)},getSel:function(){var e=this.win;return e.getSelection?e.getSelection():e.document.selection},getRng:function(e){var t=this,n,r,i,o=t.win.document;if(e&&t.tridentSel)return t.tridentSel.getRangeAt(0);try{(n=t.getSel())&&(r=n.rangeCount>0?n.getRangeAt(0):n.createRange?n.createRange():o.createRange())}catch(a){}return u&&r&&r.setStart&&o.selection.createRange().item&&(i=o.selection.createRange().item(0),r=o.createRange(),r.setStartBefore(i),r.setEndAfter(i)),r||(r=o.createRange?o.createRange():o.body.createTextRange()),r.setStart&&9===r.startContainer.nodeType&&r.collapsed&&(i=t.dom.getRoot(),r.setStart(i,0),r.setEnd(i,0)),t.selectedRange&&t.explicitRange&&(0===r.compareBoundaryPoints(r.START_TO_START,t.selectedRange)&&0===r.compareBoundaryPoints(r.END_TO_END,t.selectedRange)?r=t.explicitRange:(t.selectedRange=null,t.explicitRange=null)),r},setRng:function(e,n){var r=this,i;if(r.lastRng=null,e.select)try{e.select()}catch(o){}else if(r.tridentSel){if(e.cloneRange)try{return r.tridentSel.addRange(e),t}catch(o){}}else if(i=r.getSel()){r.explicitRange=e;try{i.removeAllRanges()}catch(o){}i.addRange(e),n===!1&&i.extend&&(i.collapse(e.endContainer,e.endOffset),i.extend(e.startContainer,e.startOffset)),r.selectedRange=i.rangeCount>0?i.getRangeAt(0):null}},setNode:function(e){var t=this;return t.setContent(t.dom.getOuterHTML(e)),e},getNode:function(){function e(e,t){for(var n=e;e&&3===e.nodeType&&0===e.length;)e=t?e.nextSibling:e.previousSibling;return e||n}var t=this,n=t.getRng(),r,i=n.startContainer,o=n.endContainer,a=n.startOffset,s=n.endOffset;return n?n.setStart?(r=n.commonAncestorContainer,!n.collapsed&&(i==o&&2>s-a&&i.hasChildNodes()&&(r=i.childNodes[a]),3===i.nodeType&&3===o.nodeType&&(i=i.length===a?e(i.nextSibling,!0):i.parentNode,o=0===s?e(o.previousSibling,!1):o.parentNode,i&&i===o))?i:r&&3==r.nodeType?r.parentNode:r):n.item?n.item(0):n.parentElement():t.dom.getRoot()},getSelectedBlocks:function(t,n){var r=this,i=r.dom,o,a=[];if(t=i.getParent(t||r.getStart(),i.isBlock),n=i.getParent(n||r.getEnd(),i.isBlock),t&&a.push(t),t&&n&&t!=n){o=t;for(var s=new e(t,i.getRoot());(o=s.next())&&o!=n;)i.isBlock(o)&&a.push(o)}return n&&t!=n&&a.push(n),a},isForward:function(){var e=this.dom,t=this.getSel(),n,r;return t&&t.anchorNode&&t.focusNode?(n=e.createRng(),n.setStart(t.anchorNode,t.anchorOffset),n.collapse(!0),r=e.createRng(),r.setStart(t.focusNode,t.focusOffset),r.collapse(!0),0>=n.compareBoundaryPoints(n.START_TO_START,r)):!0},normalize:function(){function n(n){function s(t,n){for(var r=new e(t,p.getParent(t.parentNode,p.isBlock)||h);t=r[n?"prev":"next"]();)if("BR"===t.nodeName)return!0}function l(e,t){return e.previousSibling&&e.previousSibling.nodeName==t}function c(n,r){var i,s;for(r=r||u,i=new e(r,p.getParent(r.parentNode,p.isBlock)||h);m=i[n?"prev":"next"]();){if(3===m.nodeType&&m.nodeValue.length>0)return u=m,d=n?m.nodeValue.length:0,o=!0,t;if(p.isBlock(m)||g[m.nodeName.toLowerCase()])return;s=m}a&&s&&(u=s,o=!0,d=0)}var u,d,f,p=r.dom,h=p.getRoot(),m,g,v;if(u=i[(n?"start":"end")+"Container"],d=i[(n?"start":"end")+"Offset"],g=p.schema.getNonEmptyElements(),9===u.nodeType&&(u=p.getRoot(),d=0),u===h){if(n&&(m=u.childNodes[d>0?d-1:0],m&&(v=m.nodeName.toLowerCase(),g[m.nodeName]||"TABLE"==m.nodeName)))return;if(u.hasChildNodes()&&(d=Math.min(!n&&d>0?d-1:d,u.childNodes.length-1),u=u.childNodes[d],d=0,u.hasChildNodes()&&!/TABLE/.test(u.nodeName))){m=u,f=new e(u,h);do{if(3===m.nodeType&&m.nodeValue.length>0){d=n?0:m.nodeValue.length,u=m,o=!0;break}if(g[m.nodeName.toLowerCase()]){d=p.nodeIndex(m),u=m.parentNode,"IMG"!=m.nodeName||n||d++,o=!0;break}}while(m=n?f.next():f.prev())}}a&&(3===u.nodeType&&0===d&&c(!0),1===u.nodeType&&(m=u.childNodes[d],!m||"BR"!==m.nodeName||l(m,"A")||s(m)||s(m,!0)||c(!0,u.childNodes[d]))),n&&!a&&3===u.nodeType&&d===u.nodeValue.length&&c(!1),o&&i["set"+(n?"Start":"End")](u,d)}var r=this,i,o,a;u||(i=r.getRng(),a=i.collapsed,n(!0),a||n(),o&&(a&&i.collapse(!0),r.setRng(i,r.isForward())))},selectorChanged:function(e,n){var r=this,i;return r.selectorChangedData||(r.selectorChangedData={},i={},r.editor.on("NodeChange",function(e){var n=e.element,o=r.dom,a=o.getParents(n,null,o.getRoot()),l={};s(r.selectorChangedData,function(e,n){s(a,function(r){return o.is(r,n)?(i[n]||(s(e,function(e){e(!0,{node:r,selector:n,parents:a})}),i[n]=e),l[n]=e,!1):t})}),s(i,function(e,t){l[t]||(delete i[t],s(e,function(e){e(!1,{node:n,selector:t,parents:a})}))})})),r.selectorChangedData[e]||(r.selectorChangedData[e]=[]),r.selectorChangedData[e].push(n),r},scrollIntoView:function(e){var t,n,r=this,i=r.dom;n=i.getViewPort(r.editor.getWin()),t=i.getPos(e).y,(n.y>t||t+25>n.y+n.h)&&r.editor.getWin().scrollTo(0,n.y>t?t:t-n.h+25)},destroy:function(){this.win=this.lastRng=null,this.controlSelection.destroy()}},a}),r(B,[p],function(e){function n(e){this.walk=function(n,i){function o(e){var t;return t=e[0],3===t.nodeType&&t===c&&u>=t.nodeValue.length&&e.splice(0,1),t=e[e.length-1],0===f&&e.length>0&&t===d&&3===t.nodeType&&e.splice(e.length-1,1),e}function a(e,t,n){for(var r=[];e&&e!=n;e=e[t])r.push(e);return r}function s(e,t){do{if(e.parentNode==t)return e;e=e.parentNode}while(e)}function l(e,t,n){var r=n?"nextSibling":"previousSibling";for(g=e,v=g.parentNode;g&&g!=t;g=v)v=g.parentNode,y=a(g==e?g:g[r],r),y.length&&(n||y.reverse(),i(o(y)))}var c=n.startContainer,u=n.startOffset,d=n.endContainer,f=n.endOffset,p,h,m,g,v,y,b;if(b=e.select("td.mce-item-selected,th.mce-item-selected"),b.length>0)return r(b,function(e){i([e])}),t;if(1==c.nodeType&&c.hasChildNodes()&&(c=c.childNodes[u]),1==d.nodeType&&d.hasChildNodes()&&(d=d.childNodes[Math.min(f-1,d.childNodes.length-1)]),c==d)return i(o([c]));for(p=e.findCommonAncestor(c,d),g=c;g;g=g.parentNode){if(g===d)return l(c,p,!0);if(g===p)break}for(g=d;g;g=g.parentNode){if(g===c)return l(d,p);if(g===p)break}h=s(c,p)||c,m=s(d,p)||d,l(c,h,!0),y=a(h==c?h:h.nextSibling,"nextSibling",m==d?m.nextSibling:m),y.length&&i(o(y)),l(d,m)},this.split=function(e){function t(e,t){return e.splitText(t)}var n=e.startContainer,r=e.startOffset,i=e.endContainer,o=e.endOffset;return n==i&&3==n.nodeType?r>0&&n.nodeValue.length>r&&(i=t(n,r),n=i.previousSibling,o>r?(o-=r,n=i=t(i,o).previousSibling,o=i.nodeValue.length,r=0):o=0):(3==n.nodeType&&r>0&&n.nodeValue.length>r&&(n=t(n,r),r=0),3==i.nodeType&&o>0&&i.nodeValue.length>o&&(i=t(i,o).previousSibling,o=i.nodeValue.length)),{startContainer:n,startOffset:r,endContainer:i,endOffset:o}}}var r=e.each;return n.compareRanges=function(e,t){if(e&&t){if(!e.item&&!e.duplicate)return e.startContainer==t.startContainer&&e.startOffset==t.startOffset;if(e.item&&t.item&&e.item(0)===t.item(0))return!0;if(e.isEqual&&t.isEqual&&t.isEqual(e))return!0}return!1},n}),r(L,[f,B,p],function(e,n,r){return function(i){function o(e){return e.nodeType&&(e=e.nodeName),!!i.schema.getTextBlockElements()[e.toLowerCase()]}function a(e,t){return I.getParents(e,t,I.getRoot())}function s(e){return 1===e.nodeType&&"_mce_caret"===e.id}function l(){d({alignleft:[{selector:"figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",styles:{textAlign:"left"},defaultBlock:"div"},{selector:"img,table",collapsed:!1,styles:{"float":"left"}}],aligncenter:[{selector:"figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",styles:{textAlign:"center"},defaultBlock:"div"},{selector:"img",collapsed:!1,styles:{display:"block",marginLeft:"auto",marginRight:"auto"}},{selector:"table",collapsed:!1,styles:{marginLeft:"auto",marginRight:"auto"}}],alignright:[{selector:"figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",styles:{textAlign:"right"},defaultBlock:"div"},{selector:"img,table",collapsed:!1,styles:{"float":"right"}}],alignjustify:[{selector:"figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,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:!0},{inline:"u",remove:"all"}],strikethrough:[{inline:"span",styles:{textDecoration:"line-through"},exact:!0},{inline:"strike",remove:"all"}],forecolor:{inline:"span",styles:{color:"%value"},wrap_links:!1},hilitecolor:{inline:"span",styles:{backgroundColor:"%value"},wrap_links:!1},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"},code:{inline:"code"},link:{inline:"a",selector:"a",remove:"all",split:!0,deep:!0,onmatch:function(){return!0},onformat:function(e,t,n){et(n,function(t,n){I.setAttrib(e,n,t)})}},removeformat:[{selector:"b,strong,em,i,font,u,strike",remove:"all",split:!0,expand:!1,block_expand:!0,deep:!0},{selector:"span",attributes:["style","class"],remove:"empty",split:!0,expand:!1,deep:!0},{selector:"*",attributes:["style","class"],split:!1,expand:!1,deep:!0}]}),et("p h1 h2 h3 h4 h5 h6 div address pre div dt dd samp".split(/\s/),function(e){d(e,{block:e,remove:"all"})}),d(i.settings.formats)}function c(){i.addShortcut("ctrl+b","bold_desc","Bold"),i.addShortcut("ctrl+i","italic_desc","Italic"),i.addShortcut("ctrl+u","underline_desc","Underline");for(var e=1;6>=e;e++)i.addShortcut("ctrl+"+e,"",["FormatBlock",!1,"h"+e]);i.addShortcut("ctrl+7","",["FormatBlock",!1,"p"]),i.addShortcut("ctrl+8","",["FormatBlock",!1,"div"]),i.addShortcut("ctrl+9","",["FormatBlock",!1,"address"])}function u(e){return e?O[e]:O}function d(e,t){e&&("string"!=typeof e?et(e,function(e,t){d(t,e)}):(t=t.length?t:[t],et(t,function(e){e.deep===Y&&(e.deep=!e.selector),e.split===Y&&(e.split=!e.selector||e.inline),e.remove===Y&&e.selector&&!e.inline&&(e.remove="none"),e.selector&&e.inline&&(e.mixed=!0,e.block_expand=!0),"string"==typeof e.classes&&(e.classes=e.classes.split(/\s+/))}),O[e]=t))}function f(e){var t;return i.dom.getParent(e,function(e){return t=i.dom.getStyle(e,"text-decoration"),t&&"none"!==t}),t}function p(e){var t;1===e.nodeType&&e.parentNode&&1===e.parentNode.nodeType&&(t=f(e.parentNode),i.dom.getStyle(e,"color")&&t?i.dom.setStyle(e,"text-decoration",t):i.dom.getStyle(e,"textdecoration")===t&&i.dom.setStyle(e,"text-decoration",null))}function h(n,r,a){function l(e,t){t=t||g,e&&(t.onformat&&t.onformat(e,t,r,a),et(t.styles,function(t,n){I.setStyle(e,n,k(t,r))}),et(t.attributes,function(t,n){I.setAttrib(e,n,k(t,r))}),et(t.classes,function(t){t=k(t,r),I.hasClass(e,t)||I.addClass(e,t)}))}function c(){function t(t,n){var r=new e(n);for(a=r.current();a;a=r.prev())if(a.childNodes.length>1||a==t||"BR"==a.tagName)return a}var n=i.selection.getRng(),r=n.startContainer,o=n.endContainer;if(r!=o&&0===n.endOffset){var s=t(r,o),l=3==s.nodeType?s.length:s.childNodes.length;n.setEnd(s,l)}return n}function d(e,n,r,i,o){var a=[],s=-1,l,c=-1,u=-1,d;return et(e.childNodes,function(e,n){return"UL"===e.nodeName||"OL"===e.nodeName?(s=n,l=e,!1):t}),et(e.childNodes,function(e,t){"SPAN"===e.nodeName&&"bookmark"==I.getAttrib(e,"data-mce-type")&&(e.id==n.id+"_start"?c=t:e.id==n.id+"_end"&&(u=t))}),0>=s||s>c&&u>s?(et(tt(e.childNodes),o),0):(d=I.clone(r,G),et(tt(e.childNodes),function(e,t){(s>c&&s>t||c>s&&t>s)&&(a.push(e),e.parentNode.removeChild(e))}),s>c?e.insertBefore(d,l):c>s&&e.insertBefore(d,l.nextSibling),i.push(d),et(a,function(e){d.appendChild(e)}),d)}function f(e,i,a){var c=[],u,f,p=!0;u=g.inline||g.block,f=I.create(u),l(f),W.walk(e,function(e){function h(e){var b,x,w,N,k;return k=p,b=e.nodeName.toLowerCase(),x=e.parentNode.nodeName.toLowerCase(),1===e.nodeType&&J(e)&&(k=p,p="true"===J(e),N=!0),_(b,"br")?(y=0,g.block&&I.remove(e),t):g.wrapper&&v(e,n,r)?(y=0,t):p&&!N&&g.block&&!g.wrapper&&o(b)&&z(x,u)?(e=I.rename(e,u),l(e),c.push(e),y=0,t):g.selector&&(et(m,function(t){"collapsed"in t&&t.collapsed!==C||I.is(e,t.selector)&&!s(e)&&(l(e,t),w=!0)}),!g.inline||w)?(y=0,t):(!p||N||!z(u,b)||!z(x,u)||!a&&3===e.nodeType&&1===e.nodeValue.length&&65279===e.nodeValue.charCodeAt(0)||s(e)||g.inline&&V(e)?"li"==b&&i?y=d(e,i,f,c,h):(y=0,et(tt(e.childNodes),h),N&&(p=k),y=0):(y||(y=I.clone(f,G),e.parentNode.insertBefore(y,e),c.push(y)),y.appendChild(e)),t)}var y;et(e,h)}),g.wrap_links===!1&&et(c,function(e){function t(e){var n,r,i;if("A"===e.nodeName){for(r=I.clone(f,G),c.push(r),i=tt(e.childNodes),n=0;i.length>n;n++)r.appendChild(i[n]);e.appendChild(r)}et(tt(e.childNodes),t)}t(e)}),et(c,function(e){function i(e){var t=0;return et(e.childNodes,function(e){E(e)||L(e)||t++}),t}function o(e){var n,r;return et(e.childNodes,function(e){return 1!=e.nodeType||L(e)||s(e)?t:(n=e,G)}),n&&w(n,g)&&(r=I.clone(n,G),l(r),I.replace(r,e,K),I.remove(n,1)),r||e}var a;if(a=i(e),(c.length>1||!V(e))&&0===a)return I.remove(e,1),t;if(g.inline||g.wrapper){if(g.exact||1!==a||(e=o(e)),et(m,function(t){et(I.select(t.inline,e),function(e){var n;if(t.wrap_links===!1){n=e.parentNode;do if("A"===n.nodeName)return;while(n=n.parentNode)}R(t,r,e,t.exact?e:null)})}),v(e.parentNode,n,r))return I.remove(e,1),e=0,K;g.merge_with_parents&&I.getParent(e.parentNode,function(i){return v(i,n,r)?(I.remove(e,1),e=0,K):t}),e&&g.merge_siblings!==!1&&(e=H(B(e),e),e=H(e,B(e,K)))}})}var m=u(n),g=m[0],y,b,C=!a&&F.isCollapsed();if(g)if(a)a.nodeType?(b=I.createRng(),b.setStartBefore(a),b.setEndAfter(a),f(T(b,m),null,!0)):f(a,null,!0);else if(C&&g.inline&&!I.select("td.mce-item-selected,th.mce-item-selected").length)D("apply",n,r);else{var x=i.selection.getNode();U||!m[0].defaultBlock||I.getParent(x,I.isBlock)||h(m[0].defaultBlock),i.selection.setRng(c()),y=F.getBookmark(),f(T(F.getRng(K),m),y),g.styles&&(g.styles.color||g.styles.textDecoration)&&(nt(x,p,"childNodes"),p(x)),F.moveToBookmark(y),P(F.getRng(K)),i.nodeChanged()}}function m(e,n,r){function o(e){var t,r,i,a,s;if(1===e.nodeType&&J(e)&&(a=C,C="true"===J(e),s=!0),t=tt(e.childNodes),C&&!s)for(r=0,i=h.length;i>r&&!R(h[r],n,e,e);r++);if(m.deep&&t.length){for(r=0,i=t.length;i>r;r++)o(t[r]);s&&(C=a)}}function s(t){var r;return et(a(t.parentNode).reverse(),function(t){var i;r||"_start"==t.id||"_end"==t.id||(i=v(t,e,n),i&&i.split!==!1&&(r=t))}),r}function l(e,t,r,i){var o,a,s,l,c,u;if(e){for(u=e.parentNode,o=t.parentNode;o&&o!=u;o=o.parentNode){for(a=I.clone(o,G),c=0;h.length>c;c++)if(R(h[c],n,a,a)){a=0;break}a&&(s&&a.appendChild(s),l||(l=a),s=a)}!i||m.mixed&&V(e)||(t=I.split(e,t)),s&&(r.parentNode.insertBefore(s,r),l.appendChild(r))}return t}function c(e){return l(s(e),e,e,!0)}function d(e){var t=I.get(e?"_start":"_end"),n=t[e?"firstChild":"lastChild"];return L(n)&&(n=n[e?"firstChild":"lastChild"]),I.remove(t,!0),n}function p(e){var t,n;e=T(e,h,K),m.split&&(t=M(e,K),n=M(e),t!=n?(/^(TR|TD)$/.test(t.nodeName)&&t.firstChild&&(t="TD"==t.nodeName?t.firstChild||t:t.firstChild.firstChild||t),t=S(t,"span",{id:"_start","data-mce-type":"bookmark"}),n=S(n,"span",{id:"_end","data-mce-type":"bookmark"}),c(t),c(n),t=d(K),n=d()):t=n=c(t),e.startContainer=t.parentNode,e.startOffset=q(t),e.endContainer=n.parentNode,e.endOffset=q(n)+1),W.walk(e,function(e){et(e,function(e){o(e),1===e.nodeType&&"underline"===i.dom.getStyle(e,"text-decoration")&&e.parentNode&&"underline"===f(e.parentNode)&&R({deep:!1,exact:!0,inline:"span",styles:{textDecoration:"underline"}},null,e)})})}var h=u(e),m=h[0],g,b,C=!0;return r?(r.nodeType?(b=I.createRng(),b.setStartBefore(r),b.setEndAfter(r),p(b)):p(r),t):(F.isCollapsed()&&m.inline&&!I.select("td.mce-item-selected,th.mce-item-selected").length?D("remove",e,n):(g=F.getBookmark(),p(F.getRng(K)),F.moveToBookmark(g),m.inline&&y(e,n,F.getStart())&&P(F.getRng(!0)),i.nodeChanged()),t)}function g(e,t,n){var r=u(e);!y(e,t,n)||"toggle"in r[0]&&!r[0].toggle?h(e,t,n):m(e,t,n)}function v(e,t,n,r){function i(e,t,i){var o,a,s=t[i],l;if(t.onmatch)return t.onmatch(e,t,i);if(s)if(s.length===Y){for(o in s)if(s.hasOwnProperty(o)){if(a="attributes"===i?I.getAttrib(e,o):N(e,o),r&&!a&&!t.exact)return;if((!r||t.exact)&&!_(a,k(s[o],n)))return}}else for(l=0;s.length>l;l++)if("attributes"===i?I.getAttrib(e,s[l]):N(e,s[l]))return t;return t}var o=u(t),a,s,l;if(o&&e)for(s=0;o.length>s;s++)if(a=o[s],w(e,a)&&i(e,a,"attributes")&&i(e,a,"styles")){if(l=a.classes)for(s=0;l.length>s;s++)if(!I.hasClass(e,l[s]))return;return a}}function y(e,t,n){function r(n){return n=I.getParent(n,function(n){return!!v(n,e,t,!0)}),v(n,e,t)}var i;return n?r(n):(n=F.getNode(),r(n)?K:(i=F.getStart(),i!=n&&r(i)?K:G))}function b(e,t){var n,r=[],i={};return n=F.getStart(),I.getParent(n,function(n){var o,a;for(o=0;e.length>o;o++)a=e[o],!i[a]&&v(n,a,t)&&(i[a]=!0,r.push(a))},I.getRoot()),r}function C(e){var t=u(e),n,r,i,o,s;if(t)for(n=F.getStart(),r=a(n),o=t.length-1;o>=0;o--){if(s=t[o].selector,!s)return K;for(i=r.length-1;i>=0;i--)if(I.is(r[i],s))return K}return G}function x(e,n,r){var o;return X||(X={},o={},i.on("NodeChange",function(e){var n=a(e.element),r={};et(X,function(e,i){et(n,function(a){return v(a,i,{},e.similar)?(o[i]||(et(e,function(e){e(!0,{node:a,format:i,parents:n})}),o[i]=e),r[i]=e,!1):t})}),et(o,function(t,i){r[i]||(delete o[i],et(t,function(t){t(!1,{node:e.element,format:i,parents:n})}))})})),et(e.split(","),function(e){X[e]||(X[e]=[],X[e].similar=r),X[e].push(n)}),this}function w(e,n){return _(e,n.inline)?K:_(e,n.block)?K:n.selector?1==e.nodeType&&I.is(e,n.selector):t}function _(e,t){return e=e||"",t=t||"",e=""+(e.nodeName||e),t=""+(t.nodeName||t),e.toLowerCase()==t.toLowerCase()}function N(e,t){var n=I.getStyle(e,t);return("color"==t||"backgroundColor"==t)&&(n=I.toHex(n)),"fontWeight"==t&&700==n&&(n="bold"),""+n}function k(e,t){return"string"!=typeof e?e=e(t):t&&(e=e.replace(/%(\w+)/g,function(e,n){return t[n]||e})),e}function E(e){return e&&3===e.nodeType&&/^([\t \r\n]+|)$/.test(e.nodeValue)}function S(e,t,n){var r=I.create(t,n);return e.parentNode.insertBefore(r,e),r.appendChild(e),r}function T(n,r,s){function l(e){function t(e){return"BR"==e.nodeName&&e.getAttribute("data-mce-bogus")&&!e.nextSibling}var n,i,o,a,s;if(n=i=e?v:b,a=e?"previousSibling":"nextSibling",s=I.getRoot(),3==n.nodeType&&!E(n)&&(e?y>0:n.nodeValue.length>C))return n;for(;;){if(!r[0].block_expand&&V(i))return i;for(o=i[a];o;o=o[a])if(!L(o)&&!E(o)&&!t(o))return i;if(i.parentNode==s){n=i;break}i=i.parentNode}return n}function c(e,t){for(t===Y&&(t=3===e.nodeType?e.length:e.childNodes.length);e&&e.hasChildNodes();)e=e.childNodes[t],e&&(t=3===e.nodeType?e.length:e.childNodes.length);return{node:e,offset:t}}function u(e){for(var t=e;t;){if(1===t.nodeType&&J(t))return"false"===J(t)?t:e;t=t.parentNode}return e}function d(n,r,o){function a(e,n){var r,i,a=e.nodeValue;return n===t&&(n=o?a.length:0),o?(r=a.lastIndexOf(" ",n),i=a.lastIndexOf("\u00a0",n),r=r>i?r:i,-1===r||s||r++):(r=a.indexOf(" ",n),i=a.indexOf("\u00a0",n),r=-1!==r&&(-1===i||i>r)?r:i),r}var l,c,u,d;if(3===n.nodeType){if(u=a(n,r),-1!==u)return{container:n,offset:u};d=n}for(l=new e(n,I.getParent(n,V)||i.getBody());c=l[o?"prev":"next"]();)if(3===c.nodeType){if(d=c,u=a(c),-1!==u)return{container:c,offset:u}}else if(V(c))break;return d?(r=o?0:d.length,{container:d,offset:r}):t}function f(e,t){var i,o,s,l;for(3==e.nodeType&&0===e.nodeValue.length&&e[t]&&(e=e[t]),i=a(e),o=0;i.length>o;o++)for(s=0;r.length>s;s++)if(l=r[s],!("collapsed"in l&&l.collapsed!==n.collapsed)&&I.is(i[o],l.selector))return i[o];return e}function p(e,t){var n;if(r[0].wrapper||(n=I.getParent(e,r[0].block)),n||(n=I.getParent(3==e.nodeType?e.parentNode:e,o)),n&&r[0].wrapper&&(n=a(n,"ul,ol").reverse()[0]||n),!n)for(n=e;n[t]&&!V(n[t])&&(n=n[t],!_(n,"br")););return n||e}var h,m,g,v=n.startContainer,y=n.startOffset,b=n.endContainer,C=n.endOffset;if(1==v.nodeType&&v.hasChildNodes()&&(h=v.childNodes.length-1,v=v.childNodes[y>h?h:y],3==v.nodeType&&(y=0)),1==b.nodeType&&b.hasChildNodes()&&(h=b.childNodes.length-1,b=b.childNodes[C>h?h:C-1],3==b.nodeType&&(C=b.nodeValue.length)),v=u(v),b=u(b),(L(v.parentNode)||L(v))&&(v=L(v)?v:v.parentNode,v=v.nextSibling||v,3==v.nodeType&&(y=0)),(L(b.parentNode)||L(b))&&(b=L(b)?b:b.parentNode,b=b.previousSibling||b,3==b.nodeType&&(C=b.length)),r[0].inline&&(n.collapsed&&(g=d(v,y,!0),g&&(v=g.container,y=g.offset),g=d(b,C),g&&(b=g.container,C=g.offset)),m=c(b,C),m.node)){for(;m.node&&0===m.offset&&m.node.previousSibling;)m=c(m.node.previousSibling);m.node&&m.offset>0&&3===m.node.nodeType&&" "===m.node.nodeValue.charAt(m.offset-1)&&m.offset>1&&(b=m.node,b.splitText(m.offset-1)) +}return(r[0].inline||r[0].block_expand)&&(r[0].inline&&3==v.nodeType&&0!==y||(v=l(!0)),r[0].inline&&3==b.nodeType&&C!==b.nodeValue.length||(b=l())),r[0].selector&&r[0].expand!==G&&!r[0].inline&&(v=f(v,"previousSibling"),b=f(b,"nextSibling")),(r[0].block||r[0].selector)&&(v=p(v,"previousSibling"),b=p(b,"nextSibling"),r[0].block&&(V(v)||(v=l(!0)),V(b)||(b=l()))),1==v.nodeType&&(y=q(v),v=v.parentNode),1==b.nodeType&&(C=q(b)+1,b=b.parentNode),{startContainer:v,startOffset:y,endContainer:b,endOffset:C}}function R(e,n,r,i){var o,a,s;if(!w(r,e))return G;if("all"!=e.remove)for(et(e.styles,function(e,t){e=k(e,n),"number"==typeof t&&(t=e,i=0),(!i||_(N(i,t),e))&&I.setStyle(r,t,""),s=1}),s&&""===I.getAttrib(r,"style")&&(r.removeAttribute("style"),r.removeAttribute("data-mce-style")),et(e.attributes,function(e,o){var a;if(e=k(e,n),"number"==typeof o&&(o=e,i=0),!i||_(I.getAttrib(i,o),e)){if("class"==o&&(e=I.getAttrib(r,o),e&&(a="",et(e.split(/\s+/),function(e){/mce\w+/.test(e)&&(a+=(a?" ":"")+e)}),a)))return I.setAttrib(r,o,a),t;"class"==o&&r.removeAttribute("className"),j.test(o)&&r.removeAttribute("data-mce-"+o),r.removeAttribute(o)}}),et(e.classes,function(e){e=k(e,n),(!i||I.hasClass(i,e))&&I.removeClass(r,e)}),a=I.getAttribs(r),o=0;a.length>o;o++)if(0!==a[o].nodeName.indexOf("_"))return G;return"none"!=e.remove?(A(r,e),K):t}function A(e,t){function n(e,t,n){return e=B(e,t,n),!e||"BR"==e.nodeName||V(e)}var r=e.parentNode,i;t.block&&(U?r==I.getRoot()&&(t.list_block&&_(e,t.list_block)||et(tt(e.childNodes),function(e){z(U,e.nodeName.toLowerCase())?i?i.appendChild(e):i=S(e,U):i=0})):V(e)&&!V(r)&&(n(e,G)||n(e.firstChild,K,1)||e.insertBefore(I.create("br"),e.firstChild),n(e,K)||n(e.lastChild,G,1)||e.appendChild(I.create("br")))),t.selector&&t.inline&&!_(t.inline,e)||I.remove(e,1)}function B(e,t,n){if(e)for(t=t?"nextSibling":"previousSibling",e=n?e:e[t];e;e=e[t])if(1==e.nodeType||!E(e))return e}function L(e){return e&&1==e.nodeType&&"bookmark"==e.getAttribute("data-mce-type")}function H(e,t){function n(e,t){function n(e){var t={};return et(I.getAttribs(e),function(n){var r=n.nodeName.toLowerCase();0!==r.indexOf("_")&&"style"!==r&&(t[r]=I.getAttrib(e,r))}),t}function r(e,t){var n,r;for(r in e)if(e.hasOwnProperty(r)){if(n=t[r],n===Y)return G;if(e[r]!=n)return G;delete t[r]}for(r in t)if(t.hasOwnProperty(r))return G;return K}return e.nodeName!=t.nodeName?G:r(n(e),n(t))?r(I.parseStyle(I.getAttrib(e,"style")),I.parseStyle(I.getAttrib(t,"style")))?K:G:G}function r(e,t){for(i=e;i;i=i[t]){if(3==i.nodeType&&0!==i.nodeValue.length)return e;if(1==i.nodeType&&!L(i))return i}return e}var i,o;if(e&&t&&(e=r(e,"previousSibling"),t=r(t,"nextSibling"),n(e,t))){for(i=e.nextSibling;i&&i!=t;)o=i,i=i.nextSibling,e.appendChild(o);return I.remove(t),et(tt(t.childNodes),function(t){e.appendChild(t)}),e}return t}function M(t,n){var r,o,a;return r=t[n?"startContainer":"endContainer"],o=t[n?"startOffset":"endOffset"],1==r.nodeType&&(a=r.childNodes.length-1,!n&&o&&o--,r=r.childNodes[o>a?a:o]),3===r.nodeType&&n&&o>=r.nodeValue.length&&(r=new e(r,i.getBody()).next()||r),3!==r.nodeType||n||0!==o||(r=new e(r,i.getBody()).prev()||r),r}function D(t,n,r){function o(e){var t=I.create("span",{id:g,"data-mce-bogus":!0,style:y?"color:red":""});return e&&t.appendChild(i.getDoc().createTextNode($)),t}function a(e,t){for(;e;){if(3===e.nodeType&&e.nodeValue!==$||e.childNodes.length>1)return!1;t&&1===e.nodeType&&t.push(e),e=e.firstChild}return!0}function s(e){for(;e;){if(e.id===g)return e;e=e.parentNode}}function l(t){var n;if(t)for(n=new e(t,t),t=n.current();t;t=n.next())if(3===t.nodeType)return t}function c(e,t){var n,r;if(e)r=F.getRng(!0),a(e)?(t!==!1&&(r.setStartBefore(e),r.setEndBefore(e)),I.remove(e)):(n=l(e),n.nodeValue.charAt(0)===$&&(n=n.deleteData(0,1)),I.remove(e,1)),F.setRng(r);else if(e=s(F.getStart()),!e)for(;e=I.get(g);)c(e,!1)}function d(){var e,t,i,a,c,d,f;e=F.getRng(!0),a=e.startOffset,d=e.startContainer,f=d.nodeValue,t=s(F.getStart()),t&&(i=l(t)),f&&a>0&&f.length>a&&/\w/.test(f.charAt(a))&&/\w/.test(f.charAt(a-1))?(c=F.getBookmark(),e.collapse(!0),e=T(e,u(n)),e=W.split(e),h(n,r,e),F.moveToBookmark(c)):(t&&i.nodeValue===$?h(n,r,t):(t=o(!0),i=t.firstChild,e.insertNode(t),a=1,h(n,r,t)),F.setCursorLocation(i,a))}function f(){var e=F.getRng(!0),t,i,a,s,l,c,d=[],f,p;for(t=e.startContainer,i=e.startOffset,l=t,3==t.nodeType&&((i!=t.nodeValue.length||t.nodeValue===$)&&(s=!0),l=l.parentNode);l;){if(v(l,n,r)){c=l;break}l.nextSibling&&(s=!0),d.push(l),l=l.parentNode}if(c)if(s)a=F.getBookmark(),e.collapse(!0),e=T(e,u(n),!0),e=W.split(e),m(n,r,e),F.moveToBookmark(a);else{for(p=o(),l=p,f=d.length-1;f>=0;f--)l.appendChild(I.clone(d[f],!1)),l=l.firstChild;l.appendChild(I.doc.createTextNode($)),l=l.firstChild,I.insertAfter(p,c),F.setCursorLocation(l,1)}}function p(){var e;e=s(F.getStart()),e&&!I.isEmpty(e)&&nt(e,function(e){1!=e.nodeType||e.id===g||I.isEmpty(e)||I.setAttrib(e,"data-mce-bogus",null)},"childNodes")}var g="_mce_caret",y=i.settings.caret_debug;i._hasCaretEvents||(Z=function(){var e=[],t;if(a(s(F.getStart()),e))for(t=e.length;t--;)I.setAttrib(e[t],"data-mce-bogus","1")},Q=function(e){var t=e.keyCode;c(),(8==t||37==t||39==t)&&c(s(F.getStart())),p()},i.on("SetContent",function(e){e.selection&&p()}),i._hasCaretEvents=!0),"apply"==t?d():f()}function P(n){var r=n.startContainer,i=n.startOffset,o,a,s,l,c;if(3==r.nodeType&&i>=r.nodeValue.length&&(i=q(r),r=r.parentNode,o=!0),1==r.nodeType)for(l=r.childNodes,r=l[Math.min(i,l.length-1)],a=new e(r,I.getParent(r,I.isBlock)),(i>l.length-1||o)&&a.next(),s=a.current();s;s=a.next())if(3==s.nodeType&&!E(s))return c=I.create("a",null,$),s.parentNode.insertBefore(c,s),n.setStart(s,0),F.setRng(n),I.remove(c),t}var O={},I=i.dom,F=i.selection,W=new n(I),z=i.schema.isValidChild,V=I.isBlock,U=i.settings.forced_root_block,q=I.nodeIndex,$="\ufeff",j=/^(src|href|style)$/,G=!1,K=!0,X,Y,J=I.getContentEditable,Q,Z,et=r.each,tt=r.grep,nt=r.walk,rt=r.extend;rt(this,{get:u,register:d,apply:h,remove:m,toggle:g,match:y,matchAll:b,matchNode:v,canApply:C,formatChanged:x}),l(),c(),i.on("BeforeGetContent",function(){Z&&Z()}),i.on("mouseup keydown",function(e){Q&&Q(e)})}}),r(H,[g,p],function(e,n){var r=n.trim,i;return i=RegExp(["]+data-mce-bogus[^>]+>[\u200b\ufeff]+<\\/span>","]+data-mce-bogus[^>]+><\\/div>",'\\s?data-mce-selected="[^"]+"'].join("|"),"gi"),function(n){function o(){return r(n.getContent({format:"raw",no_events:1}).replace(i,""))}function a(){s.typing=!1,s.add()}var s,l=0,c=[],u;return n.on("init",function(){s.add()}),n.on("BeforeExecCommand",function(e){var t=e.command;"Undo"!=t&&"Redo"!=t&&"mceRepaint"!=t&&s.beforeChange()}),n.on("ExecCommand",function(e){var t=e.command;"Undo"!=t&&"Redo"!=t&&"mceRepaint"!=t&&s.add()}),n.on("ObjectResizeStart",function(){s.beforeChange()}),n.on("SaveContent ObjectResized",a),n.dom.bind(n.dom.getRoot(),"dragend",a),n.dom.bind(n.getBody(),"focusout",function(){!n.removed&&s.typing&&a()}),n.on("KeyUp",function(t){var r=t.keyCode;(r>=33&&36>=r||r>=37&&40>=r||45==r||13==r||t.ctrlKey)&&(a(),n.nodeChanged()),(46==r||8==r||e.isMac&&(91==r||93==r))&&n.nodeChanged()}),n.on("KeyDown",function(e){var n=e.keyCode;return n>=33&&36>=n||n>=37&&40>=n||45==n?(s.typing&&a(),t):((16>n||n>20)&&224!=n&&91!=n&&!s.typing&&(s.beforeChange(),s.typing=!0,s.add()),t)}),n.on("MouseDown",function(){s.typing&&a()}),n.addShortcut("ctrl+z","undo_desc","Undo"),n.addShortcut("ctrl+y","redo_desc","Redo"),n.on("AddUndo Undo Redo ClearUndos MouseUp",function(e){e.isDefaultPrevented()||n.nodeChanged()}),s={data:c,typing:!1,beforeChange:function(){u=n.selection.getBookmark(2,!0)},add:function(e){var t,r=n.settings,i;if(e=e||{},e.content=o(),n.fire("BeforeAddUndo",{level:e}).isDefaultPrevented())return null;if(i=c[l],i&&i.content==e.content)return null;if(c[l]&&(c[l].beforeBookmark=u),r.custom_undo_redo_levels&&c.length>r.custom_undo_redo_levels){for(t=0;c.length-1>t;t++)c[t]=c[t+1];c.length--,l=c.length}return e.bookmark=n.selection.getBookmark(2,!0),c.length-1>l&&(c.length=l+1),c.push(e),l=c.length-1,n.fire("AddUndo",{level:e,lastLevel:i}),n.isNotDirty=0,e},undo:function(){var e;return s.typing&&(s.add(),s.typing=!1),l>0&&(e=c[--l],n.setContent(e.content,{format:"raw"}),n.selection.moveToBookmark(e.beforeBookmark),n.fire("undo",{level:e})),e},redo:function(){var e;return c.length-1>l&&(e=c[++l],n.setContent(e.content,{format:"raw"}),n.selection.moveToBookmark(e.bookmark),n.fire("redo",{level:e})),e},clear:function(){c=[],l=0,s.typing=!1,n.fire("ClearUndos")},hasUndo:function(){return l>0||s.typing&&c[0]&&o()!=c[0].content},hasRedo:function(){return c.length-1>l&&!this.typing},transact:function(e){s.beforeChange(),e(),s.add()}}}}),r(M,[f,g],function(e,n){var r=n.ie;return function(n){function i(i){function d(e){return e&&o.isBlock(e)&&!/^(TD|TH|CAPTION|FORM)$/.test(e.nodeName)&&!/^(fixed|absolute)/i.test(e.style.position)&&"true"!==o.getContentEditable(e)}function f(e){var t;o.isBlock(e)&&(t=a.getRng(),e.appendChild(o.create("span",null,"\u00a0")),a.select(e),e.lastChild.outerHTML="",a.setRng(t))}function p(e){for(var t=e,n=[],r;t=t.firstChild;){if(o.isBlock(t))return;1!=t.nodeType||u[t.nodeName.toLowerCase()]||n.push(t)}for(r=n.length;r--;)t=n[r],!t.hasChildNodes()||t.firstChild==t.lastChild&&""===t.firstChild.nodeValue?o.remove(t):"A"==t.nodeName&&" "===(t.innerText||t.textContent)&&o.remove(t)}function h(t){var n,r,i,s=t,l;if(i=o.createRng(),t.hasChildNodes()){for(n=new e(t,t);r=n.current();){if(3==r.nodeType){i.setStart(r,0),i.setEnd(r,0);break}if(u[r.nodeName.toLowerCase()]){i.setStartBefore(r),i.setEndBefore(r);break}s=r,r=n.next()}r||(i.setStart(s,0),i.setEnd(s,0))}else"BR"==t.nodeName?t.nextSibling&&o.isBlock(t.nextSibling)?((!A||9>A)&&(l=o.create("br"),t.parentNode.insertBefore(l,t)),i.setStartBefore(t),i.setEndBefore(t)):(i.setStartAfter(t),i.setEndAfter(t)):(i.setStart(t,0),i.setEnd(t,0));a.setRng(i),o.remove(l),a.scrollIntoView(t)}function m(e){var t=S,n,i,a;if(n=e||"TABLE"==D?o.create(e||O):R.cloneNode(!1),a=n,s.keep_styles!==!1)do if(/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(t.nodeName)){if("_mce_caret"==t.id)continue;i=t.cloneNode(!1),o.setAttrib(i,"id",""),n.hasChildNodes()?(i.appendChild(n.firstChild),n.appendChild(i)):(a=i,n.appendChild(i))}while(t=t.parentNode);return r||(a.innerHTML='
    '),n}function g(t){var n,r,i;if(3==S.nodeType&&(t?T>0:S.nodeValue.length>T))return!1;if(S.parentNode==R&&I&&!t)return!0;if(t&&1==S.nodeType&&S==R.firstChild)return!0;if("TABLE"===S.nodeName||S.previousSibling&&"TABLE"==S.previousSibling.nodeName)return I&&!t||!I&&t;for(n=new e(S,R),3==S.nodeType&&(t&&0===T?n.prev():t||T!=S.nodeValue.length||n.next());r=n.current();){if(1===r.nodeType){if(!r.getAttribute("data-mce-bogus")&&(i=r.nodeName.toLowerCase(),u[i]&&"br"!==i))return!1}else if(3===r.nodeType&&!/^[ \t\r\n]*$/.test(r.nodeValue))return!1;t?n.prev():n.next()}return!0}function v(e,t){var r,i,a,s,l,u,f=O||"P";if(i=o.getParent(e,o.isBlock),u=n.getBody().nodeName.toLowerCase(),!i||!d(i)){if(i=i||E,!i.hasChildNodes())return r=o.create(f),i.appendChild(r),N.setStart(r,0),N.setEnd(r,0),r;for(s=e;s.parentNode!=i;)s=s.parentNode;for(;s&&!o.isBlock(s);)a=s,s=s.previousSibling;if(a&&c.isValidChild(u,f.toLowerCase())){for(r=o.create(f),a.parentNode.insertBefore(r,a),s=a;s&&!o.isBlock(s);)l=s.nextSibling,r.appendChild(s),s=l;N.setStart(e,t),N.setEnd(e,t)}}return e}function y(){function e(e){for(var t=M[e?"firstChild":"lastChild"];t&&1!=t.nodeType;)t=t[e?"nextSibling":"previousSibling"];return t===R}function t(){var e=M.parentNode;return"LI"==e.nodeName?e:M}var n=M.parentNode.nodeName;/^(OL|UL|LI)$/.test(n)&&(O="LI"),L=O?m(O):o.create("BR"),e(!0)&&e()?"LI"==n?o.insertAfter(L,t()):o.replace(L,M):e(!0)?"LI"==n?(o.insertAfter(L,t()),L.appendChild(o.doc.createTextNode(" ")),L.appendChild(M)):M.parentNode.insertBefore(L,M):e()?(o.insertAfter(L,t()),f(L)):(M=t(),k=N.cloneRange(),k.setStartAfter(R),k.setEndAfter(M),H=k.extractContents(),o.insertAfter(H,M),o.insertAfter(L,M)),o.remove(R),h(L),l.add()}function b(){for(var t=new e(S,R),n;n=t.next();)if(u[n.nodeName.toLowerCase()]||n.length>0)return!0}function C(){var e,t,n;S&&3==S.nodeType&&T>=S.nodeValue.length&&(r||b()||(e=o.create("br"),N.insertNode(e),N.setStartAfter(e),N.setEndAfter(e),t=!0)),e=o.create("br"),N.insertNode(e),r&&"PRE"==D&&(!A||8>A)&&e.parentNode.insertBefore(o.doc.createTextNode("\r"),e),n=o.create("span",{}," "),e.parentNode.insertBefore(n,e),a.scrollIntoView(n),o.remove(n),t?(N.setStartBefore(e),N.setEndBefore(e)):(N.setStartAfter(e),N.setEndAfter(e)),a.setRng(N),l.add()}function x(e){do 3===e.nodeType&&(e.nodeValue=e.nodeValue.replace(/^[\r\n]+/,"")),e=e.firstChild;while(e)}function w(e){var t=o.getRoot(),n,r;for(n=e;n!==t&&"false"!==o.getContentEditable(n);)"true"===o.getContentEditable(n)&&(r=n),n=n.parentNode;return n!==t?r:t}function _(e){var t;r||(e.normalize(),t=e.lastChild,(!t||/^(left|right)$/gi.test(o.getStyle(t,"float",!0)))&&o.add(e,"br"))}var N=a.getRng(!0),k,E,S,T,R,A,B,L,H,M,D,P,O,I;if(!N.collapsed)return n.execCommand("Delete"),t;if(!i.isDefaultPrevented()&&(S=N.startContainer,T=N.startOffset,O=(s.force_p_newlines?"p":"")||s.forced_root_block,O=O?O.toUpperCase():"",A=o.doc.documentMode,B=i.shiftKey,1==S.nodeType&&S.hasChildNodes()&&(I=T>S.childNodes.length-1,S=S.childNodes[Math.min(T,S.childNodes.length-1)]||S,T=I&&3==S.nodeType?S.nodeValue.length:0),E=w(S))){if(l.beforeChange(),!o.isBlock(E)&&E!=o.getRoot())return(!O||B)&&C(),t;if((O&&!B||!O&&B)&&(S=v(S,T)),R=o.getParent(S,o.isBlock),M=R?o.getParent(R.parentNode,o.isBlock):null,D=R?R.nodeName.toUpperCase():"",P=M?M.nodeName.toUpperCase():"","LI"!=P||i.ctrlKey||(R=M,D=P),"LI"==D){if(!O&&B)return C(),t;if(o.isEmpty(R))return y(),t}if("PRE"==D&&s.br_in_pre!==!1){if(!B)return C(),t}else if(!O&&!B&&"LI"!=D||O&&B)return C(),t;O&&R===n.getBody()||(O=O||"P",g()?(L=/^(H[1-6]|PRE|FIGURE)$/.test(D)&&"HGROUP"!=P?m(O):m(),s.end_container_on_empty_block&&d(M)&&o.isEmpty(R)?L=o.split(M,R):o.insertAfter(L,R),h(L)):g(!0)?(L=R.parentNode.insertBefore(m(),R),f(L)):(k=N.cloneRange(),k.setEndAfter(R),H=k.extractContents(),x(H),L=H.firstChild,o.insertAfter(H,R),p(L),_(R),h(L)),o.setAttrib(L,"id",""),l.add())}}var o=n.dom,a=n.selection,s=n.settings,l=n.undoManager,c=n.schema,u=c.getNonEmptyElements();n.on("keydown",function(e){13==e.keyCode&&i(e)!==!1&&e.preventDefault()})}}),r(D,[],function(){return function(e){function t(){var t=i.getStart(),s=e.getBody(),l,c,u,d,f,p,h,m=-16777215,g,v,y,b,C;if(C=n.forced_root_block,t&&1===t.nodeType&&C){for(;t&&t!=s;){if(a[t.nodeName])return;t=t.parentNode}for(l=i.getRng(),l.setStart?(c=l.startContainer,u=l.startOffset,d=l.endContainer,f=l.endOffset,v=e.getDoc().activeElement===s):(l.item&&(t=l.item(0),l=e.getDoc().body.createTextRange(),l.moveToElementText(t)),v=l.parentElement().ownerDocument===e.getDoc(),y=l.duplicate(),y.collapse(!0),u=-1*y.move("character",m),y.collapsed||(y=l.duplicate(),y.collapse(!1),f=-1*y.move("character",m)-u)),t=s.firstChild,b=s.nodeName.toLowerCase();t;)if((3===t.nodeType||1==t.nodeType&&!a[t.nodeName])&&o.isValidChild(b,C.toLowerCase())){if(3===t.nodeType&&0===t.nodeValue.length){h=t,t=t.nextSibling,r.remove(h);continue}p||(p=r.create(C),t.parentNode.insertBefore(p,t),g=!0),h=t,t=t.nextSibling,p.appendChild(h)}else p=null,t=t.nextSibling;if(g&&v){if(l.setStart)l.setStart(c,u),l.setEnd(d,f),i.setRng(l);else try{l=e.getDoc().body.createTextRange(),l.moveToElementText(s),l.collapse(!0),l.moveStart("character",u),f>0&&l.moveEnd("character",f),l.select()}catch(x){}e.nodeChanged()}}}var n=e.settings,r=e.dom,i=e.selection,o=e.schema,a=o.getBlockElements();n.forced_root_block&&e.on("KeyUp NodeChange",t)}}),r(P,[k,g,p],function(e,n,r){var i=r.each,o=r.extend,a=r.map,s=r.inArray,l=r.explode,c=n.gecko,u=n.ie,d=!0,f=!1;return function(n){function r(e,t,n){var r;return e=e.toLowerCase(),(r=_.exec[e])?(r(e,t,n),d):f}function p(e){var t;return e=e.toLowerCase(),(t=_.state[e])?t(e):-1}function h(e){var t;return e=e.toLowerCase(),(t=_.value[e])?t(e):f}function m(e,t){t=t||"exec",i(e,function(e,n){i(n.toLowerCase().split(","),function(n){_[t][n]=e})})}function g(e,r,i){return r===t&&(r=f),i===t&&(i=null),n.getDoc().execCommand(e,r,i)}function v(e){return k.match(e)}function y(e,r){k.toggle(e,r?{value:r}:t),n.nodeChanged()}function b(e){E=w.getBookmark(e)}function C(){w.moveToBookmark(E)}var x=n.dom,w=n.selection,_={state:{},exec:{},value:{}},N=n.settings,k=n.formatter,E;o(this,{execCommand:r,queryCommandState:p,queryCommandValue:h,addCommands:m}),m({"mceResetDesignMode,mceBeginUndoLevel":function(){},"mceEndUndoLevel,mceAddUndoLevel":function(){n.undoManager.add()},"Cut,Copy,Paste":function(e){var t=n.getDoc(),r;try{g(e)}catch(i){r=d}(r||!t.queryCommandSupported(e))&&(c?n.windowManager.confirm(n.getLang("clipboard_msg"),function(e){e&&window.open("http://www.mozilla.org/editor/midasdemo/securityprefs.html","_blank")}):n.windowManager.alert("Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X/C/V keyboard shortcuts instead."))},unlink:function(e){w.isCollapsed()&&w.select(w.getNode()),g(e),w.collapse(f)},"JustifyLeft,JustifyCenter,JustifyRight,JustifyFull":function(e){var t=e.substring(7);"full"==t&&(t="justify"),i("left,center,right,justify".split(","),function(e){t!=e&&k.remove("align"+e)}),y("align"+t),r("mceRepaint")},"InsertUnorderedList,InsertOrderedList":function(e){var t,n;g(e),t=x.getParent(w.getNode(),"ol,ul"),t&&(n=t.parentNode,/^(H[1-6]|P|ADDRESS|PRE)$/.test(n.nodeName)&&(b(),x.split(n,t),C()))},"Bold,Italic,Underline,Strikethrough,Superscript,Subscript":function(e){y(e)},"ForeColor,HiliteColor,FontName":function(e,t,n){y(e,n)},FontSize:function(e,t,n){var r,i;n>=1&&7>=n&&(i=l(N.font_size_style_values),r=l(N.font_size_classes),n=r?r[n-1]||n:i[n-1]||n),y(e,n)},RemoveFormat:function(e){k.remove(e)},mceBlockQuote:function(){y("blockquote")},FormatBlock:function(e,t,n){return y(n||"p")},mceCleanup:function(){var e=w.getBookmark();n.setContent(n.getContent({cleanup:d}),{cleanup:d}),w.moveToBookmark(e)},mceRemoveNode:function(e,t,r){var i=r||w.getNode();i!=n.getBody()&&(b(),n.dom.remove(i,d),C())},mceSelectNodeDepth:function(e,r,i){var o=0;x.getParent(w.getNode(),function(e){return 1==e.nodeType&&o++==i?(w.select(e),f):t},n.getBody())},mceSelectNode:function(e,t,n){w.select(n)},mceInsertContent:function(t,r,i){function o(e){function t(e){return r[e]&&3==r[e].nodeType}var n,r,i;return n=w.getRng(!0),r=n.startContainer,i=n.startOffset,3==r.nodeType&&(i>0?e=e.replace(/^ /," "):t("previousSibling")||(e=e.replace(/^ /," ")),r.length>i?e=e.replace(/ (
    |)$/," "):t("nextSibling")||(e=e.replace(/( | )(
    |)$/," "))),e}var a,s,l,c,d,f,p,h,m,g,v,y,b,C;if(/^ | $/.test(i)&&(i=o(i)),a=n.parser,s=new e({},n.schema),b='',f={content:i,format:"html",selection:!0},n.fire("BeforeSetContent",f),i=f.content,-1==i.indexOf("{$caret}")&&(i+="{$caret}"),i=i.replace(/\{\$caret\}/,b),w.isCollapsed()||n.getDoc().execCommand("Delete",!1,null),l=w.getNode(),f={context:l.nodeName.toLowerCase()},d=a.parse(i,f),v=d.lastChild,"mce_marker"==v.attr("id"))for(p=v,v=v.prev;v;v=v.walk(!0))if(3==v.type||!x.isBlock(v.name)){v.parent.insert(p,v,"br"===v.name);break}if(f.invalid){for(w.setContent(b),l=w.getNode(),c=n.getBody(),9==l.nodeType?l=v=c:v=l;v!==c;)l=v,v=v.parentNode;i=l==c?c.innerHTML:x.getOuterHTML(l),i=s.serialize(a.parse(i.replace(//i,function(){return s.serialize(d)}))),l==c?x.setHTML(c,i):x.setOuterHTML(l,i)}else i=s.serialize(d),v=l.firstChild,y=l.lastChild,!v||v===y&&"BR"===v.nodeName?x.setHTML(l,i):w.setContent(i);p=x.get("mce_marker"),h=x.getRect(p),m=x.getViewPort(n.getWin()),(h.y+h.h>m.y+m.h||h.ym.x+m.w||h.x")},mceToggleVisualAid:function(){n.hasVisual=!n.hasVisual,n.addVisual()},mceReplaceContent:function(e,t,r){n.execCommand("mceInsertContent",!1,r.replace(/\{\$selection\}/g,w.getContent({format:"text"})))},mceInsertLink:function(e,t,n){var r;"string"==typeof n&&(n={href:n}),r=x.getParent(w.getNode(),"a"),n.href=n.href.replace(" ","%20"),r&&n.href||k.remove("link"),n.href&&k.apply("link",n,r)},selectAll:function(){var e=x.getRoot(),t=x.createRng();w.getRng().setStart?(t.setStart(e,0),t.setEnd(e,e.childNodes.length),w.setRng(t)):g("SelectAll")},mceNewDocument:function(){n.setContent("")}}),m({"JustifyLeft,JustifyCenter,JustifyRight,JustifyFull":function(e){var t="align"+e.substring(7),n=w.isCollapsed()?[x.getParent(w.getNode(),x.isBlock)]:w.getSelectedBlocks(),r=a(n,function(e){return!!k.matchNode(e,t)});return-1!==s(r,d)},"Bold,Italic,Underline,Strikethrough,Superscript,Subscript":function(e){return v(e)},mceBlockQuote:function(){return v("blockquote")},Outdent:function(){var e;if(N.inline_styles){if((e=x.getParent(w.getStart(),x.isBlock))&&parseInt(e.style.paddingLeft,10)>0)return d;if((e=x.getParent(w.getEnd(),x.isBlock))&&parseInt(e.style.paddingLeft,10)>0)return d}return p("InsertUnorderedList")||p("InsertOrderedList")||!N.inline_styles&&!!x.getParent(w.getNode(),"BLOCKQUOTE")},"InsertUnorderedList,InsertOrderedList":function(e){var t=x.getParent(w.getNode(),"ul,ol");return t&&("insertunorderedlist"===e&&"UL"===t.tagName||"insertorderedlist"===e&&"OL"===t.tagName)}},"state"),m({"FontSize,FontName":function(e){var t=0,n;return(n=x.getParent(w.getNode(),"span"))&&(t="fontsize"==e?n.style.fontSize:n.style.fontFamily.replace(/, /g,",").replace(/[\'\"]/g,"").toLowerCase()),t}},"value"),m({Undo:function(){n.undoManager.undo()},Redo:function(){n.undoManager.redo()}})}}),r(O,[p],function(e){function n(e,o){var a=this,s,l;return e=i(e),o=a.settings=o||{},/^([\w\-]+):([^\/]{2})/i.test(e)||/^\s*#/.test(e)?(a.source=e,t):(0===e.indexOf("/")&&0!==e.indexOf("//")&&(e=(o.base_uri?o.base_uri.protocol||"http":"http")+"://mce_host"+e),/^[\w\-]*:?\/\//.test(e)||(l=o.base_uri?o.base_uri.path:new n(location.href).directory,e=(o.base_uri&&o.base_uri.protocol||"http")+"://mce_host"+a.toAbsPath(l,e)),e=e.replace(/@@/g,"(mce_at)"),e=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(e),r(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],function(t,n){var r=e[n];r&&(r=r.replace(/\(mce_at\)/g,"@@")),a[t]=r}),s=o.base_uri,s&&(a.protocol||(a.protocol=s.protocol),a.userInfo||(a.userInfo=s.userInfo),a.port||"mce_host"!==a.host||(a.port=s.port),a.host&&"mce_host"!==a.host||(a.host=s.host),a.source=""),t)}var r=e.each,i=e.trim;return n.prototype={setPath:function(e){var t=this;e=/^(.*?)\/?(\w+)?$/.exec(e),t.path=e[0],t.directory=e[1],t.file=e[2],t.source="",t.getURI()},toRelative:function(e){var t=this,r;if("./"===e)return e;if(e=new n(e,{base_uri:t}),"mce_host"!=e.host&&t.host!=e.host&&e.host||t.port!=e.port||t.protocol!=e.protocol)return e.getURI();var i=t.getURI(),o=e.getURI();return i==o||"/"==i.charAt(i.length-1)&&i.substr(0,i.length-1)==o?i:(r=t.toRelPath(t.path,e.path),e.query&&(r+="?"+e.query),e.anchor&&(r+="#"+e.anchor),r)},toAbsolute:function(e,t){return e=new n(e,{base_uri:this}),e.getURI(this.host==e.host&&this.protocol==e.protocol?t:0)},toRelPath:function(e,t){var n,r=0,i="",o,a;if(e=e.substring(0,e.lastIndexOf("/")),e=e.split("/"),n=t.split("/"),e.length>=n.length)for(o=0,a=e.length;a>o;o++)if(o>=n.length||e[o]!=n[o]){r=o+1;break}if(e.lengtho;o++)if(o>=e.length||e[o]!=n[o]){r=o+1;break}if(1===r)return t;for(o=0,a=e.length-(r-1);a>o;o++)i+="../";for(o=r-1,a=n.length;a>o;o++)i+=o!=r-1?"/"+n[o]:n[o];return i},toAbsPath:function(e,t){var n,i=0,o=[],a,s;for(a=/\/$/.test(t)?"/":"",e=e.split("/"),t=t.split("/"),r(e,function(e){e&&o.push(e)}),e=o,n=t.length-1,o=[];n>=0;n--)0!==t[n].length&&"."!==t[n]&&(".."!==t[n]?i>0?i--:o.push(t[n]):i++);return n=e.length-i,s=0>=n?o.reverse().join("/"):e.slice(0,n).join("/")+"/"+o.reverse().join("/"),0!==s.indexOf("/")&&(s="/"+s),a&&s.lastIndexOf("/")!==s.length-1&&(s+=a),s},getURI:function(e){var t,n=this;return(!n.source||e)&&(t="",e||(n.protocol&&(t+=n.protocol+"://"),n.userInfo&&(t+=n.userInfo+"@"),n.host&&(t+=n.host),n.port&&(t+=":"+n.port)),n.path&&(t+=n.path),n.query&&(t+="?"+n.query),n.anchor&&(t+="#"+n.anchor),n.source=t),n.source}},n}),r(I,[p],function(e){function t(){}var n=e.each,r=e.extend,i,o;return t.extend=i=function(e){function t(){var e,t,n,r;if(!o&&(r=this,r.init&&r.init.apply(r,arguments),t=r.Mixins))for(e=t.length;e--;)n=t[e],n.init&&n.init.apply(r,arguments)}function a(){return this}function s(e,t){return function(){var n=this,r=n._super,i;return n._super=c[e],i=t.apply(n,arguments),n._super=r,i}}var l=this,c=l.prototype,u,d,f;o=!0,u=new l,o=!1,e.Mixins&&(n(e.Mixins,function(t){t=t;for(var n in t)"init"!==n&&(e[n]=t[n])}),c.Mixins&&(e.Mixins=c.Mixins.concat(e.Mixins))),e.Methods&&n(e.Methods.split(","),function(t){e[t]=a}),e.Properties&&n(e.Properties.split(","),function(t){var n="_"+t;e[t]=function(e){var t=this,r;return e!==r?(t[n]=e,t):t[n]}}),e.Statics&&n(e.Statics,function(e,n){t[n]=e}),e.Defaults&&c.Defaults&&(e.Defaults=r({},c.Defaults,e.Defaults));for(d in e)f=e[d],u[d]="function"==typeof f&&c[d]?s(d,f):f;return t.prototype=u,t.constructor=t,t.extend=i,t},t}),r(F,[I,p],function(e,n){function r(e){for(var t=[],n=e.length,r;n--;)r=e[n],r.__checked||(t.push(r),r.__checked=1);for(n=t.length;n--;)delete t[n].__checked;return t}var i=/^([\w\\*]+)?(?:#([\w\\]+))?(?:\.([\w\\\.]+))?(?:\[\@?([\w\\]+)([\^\$\*!~]?=)([\w\\]+)\])?(?:\:(.+))?/i,o=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,a=/^\s*|\s*$/g,s,l=e.extend({init:function(e){function n(e){return e?(e=e.toLowerCase(),function(t){return"*"===e||t.type===e}):t}function r(e){return e?function(t){return t._name===e}:t}function s(e){return e?(e=e.split("."),function(t){for(var n=e.length;n--;)if(!t.hasClass(e[n]))return!1;return!0}):t}function l(e,n,r){return e?function(t){var i=t[e]?t[e]():"";return n?"="===n?i===r:"*="===n?i.indexOf(r)>=0:"~="===n?(" "+i+" ").indexOf(" "+r+" ")>=0:"!="===n?i!=r:"^="===n?0===i.indexOf(r):"$="===n?i.substr(i.length-r.length)===r:!1:!!r}:t}function c(e){var n;return e?(e=/(?:not\((.+)\))|(.+)/i.exec(e),e[1]?(n=d(e[1],[]),function(e){return!f(e,n)}):(e=e[2],function(t,n,r){return"first"===e?0===n:"last"===e?n===r-1:"even"===e?0===n%2:"odd"===e?1===n%2:t[e]?t[e]():!1})):t}function u(e,t,o){function u(e){e&&t.push(e)}var d;return d=i.exec(e.replace(a,"")),u(n(d[1])),u(r(d[2])),u(s(d[3])),u(l(d[4],d[5],d[6])),u(c(d[7])),t.psuedo=!!d[7],t.direct=o,t}function d(e,t){var n=[],r,i,a;do if(o.exec(""),i=o.exec(e),i&&(e=i[3],n.push(i[1]),i[2])){r=i[3];break}while(i);for(r&&d(r,t),e=[],a=0;n.length>a;a++)">"!=n[a]&&e.push(u(n[a],[],">"===n[a-1]));return t.push(e),t}var f=this.match;this._selectors=d(e,[])},match:function(e,t){var r,i,o,a,s,l,c,u,d,f,p,h,m;for(t=t||this._selectors,r=0,i=t.length;i>r;r++){for(s=t[r],a=s.length,m=e,h=0,o=a-1;o>=0;o--)for(u=s[o];m;){for(u.psuedo&&(p=m.parent().items(),d=n.inArray(m,p),f=p.length),l=0,c=u.length;c>l;l++)if(!u[l](m,d,f)){l=c+1;break}if(l===c){h++;break}if(o===a-1)break;m=m.parent()}if(h===a)return!0}return!1},find:function(e){function t(e,r,i){var o,a,s,l,c,u=r[i];for(o=0,a=e.length;a>o;o++){for(c=e[o],s=0,l=u.length;l>s;s++)if(!u[s](c,o,a)){s=l+1;break}if(s===l)i==r.length-1?n.push(c):c.items&&t(c.items(),r,i+1);else if(u.direct)return;c.items&&t(c.items(),r,i)}}var n=[],i,o,a=this._selectors;if(e.items){for(i=0,o=a.length;o>i;i++)t(e.items(),a[i],0);o>1&&(n=r(n))}return s||(s=l.Collection),new s(n)}});return l}),r(W,[p,F,I],function(e,n,r){var i,o,a=Array.prototype.push,s=Array.prototype.slice;return o={length:0,init:function(e){e&&this.add(e)},add:function(t){var n=this;return e.isArray(t)?a.apply(n,t):t instanceof i?n.add(t.toArray()):a.call(n,t),n},set:function(e){var t=this,n=t.length,r;for(t.length=0,t.add(e),r=t.length;n>r;r++)delete t[r];return t},filter:function(e){var t=this,r,o,a=[],s,l;for("string"==typeof e?(e=new n(e),l=function(t){return e.match(t)}):l=e,r=0,o=t.length;o>r;r++)s=t[r],l(s)&&a.push(s);return new i(a)},slice:function(){return new i(s.apply(this,arguments))},eq:function(e){return-1===e?this.slice(e):this.slice(e,+e+1)},each:function(t){return e.each(this,t),this},toArray:function(){return e.toArray(this)},indexOf:function(e){for(var t=this,n=t.length;n--&&t[n]!==e;);return n},reverse:function(){return new i(e.toArray(this).reverse())},hasClass:function(e){return this[0]?this[0].hasClass(e):!1},prop:function(e,n){var r=this,i,o;return n!==i?(r.each(function(t){t[e]&&t[e](n)}),r):(o=r[0],o&&o[e]?o[e]():t)},exec:function(t){var n=this,r=e.toArray(arguments).slice(1);return n.each(function(e){e[t]&&e[t].apply(e,r)}),n}},e.each("fire on off show hide addClass removeClass append prepend before after reflow".split(" "),function(t){o[t]=function(){var n=e.toArray(arguments);return this.each(function(e){t in e&&e[t].apply(e,n)}),this}}),e.each("text name width height disabled active selected checked visible parent value data".split(" "),function(e){o[e]=function(t){return this.prop(e,t)}}),i=r.extend(o),n.Collection=i,i}),r(z,[p,v],function(e,t){return{id:function(){return t.DOM.uniqueId()},createFragment:function(e){return t.DOM.createFragment(e)},getWindowSize:function(){return t.DOM.getViewPort()},getSize:function(e){return t.DOM.getSize(e)},getPos:function(e,n){return t.DOM.getPos(e,n)},get:function(e){return document.getElementById(e)},addClass:function(e,n){return t.DOM.addClass(e,n)},removeClass:function(e,n){return t.DOM.removeClass(e,n)},hasClass:function(e,n){return t.DOM.hasClass(e,n)},toggleClass:function(e,n,r){return t.DOM.toggleClass(e,n,r)},css:function(e,n,r){return t.DOM.setStyle(e,n,r)},on:function(e,n,r,i){return t.DOM.bind(e,n,r,i)},off:function(e,n,r){return t.DOM.unbind(e,n,r)},fire:function(e,n,r){return t.DOM.fire(e,n,r)}}}),r(V,[I,p,W,z],function(e,n,r,i){var o=n.makeMap("focusin focusout scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave wheel keydown keypress keyup contextmenu"," "),a={},s="onmousewheel"in document,l=!1,c=e.extend({Statics:{controlIdLookup:{}},classPrefix:"mce-",getContainerElm:function(){return document.body},getParentCtrl:function(e){for(var t;e&&!(t=c.controlIdLookup[e.id]);)e=e.parentNode;return t},init:function(e){var r=this,o,a;if(r.settings=e=n.extend({},r.Defaults,e),r._id=i.id(),r._text=r._name="",r._width=r._height=0,r._aria={role:e.role},o=e.classes)for(o=o.split(" "),o.map={},a=o.length;a--;)o.map[o[a]]=!0; +r._classes=o||[],r.visible(!0),n.each("title text width height name classes visible disabled active value".split(" "),function(t){var n=e[t],i;n!==i?r[t](n):r["_"+t]===i&&(r["_"+t]=!1)}),r.on("click",function(){return r.disabled()?!1:t}),e.classes&&n.each(e.classes.split(" "),function(e){r.addClass(e)}),r.settings=e,r._borderBox=r.parseBox(e.border),r._paddingBox=r.parseBox(e.padding),r._marginBox=r.parseBox(e.margin),e.hidden&&r.hide()},Properties:"parent,title,text,width,height,disabled,active,name,value",Methods:"renderHtml,refresh",parseBox:function(e){var t,n=10;if(e)return"number"==typeof e?(e=e||0,{top:e,left:e,bottom:e,right:e}):(e=e.split(" "),t=e.length,1===t?e[1]=e[2]=e[3]=e[0]:2===t?(e[2]=e[0],e[3]=e[1]):3===t&&(e[3]=e[1]),{top:parseInt(e[0],n)||0,right:parseInt(e[1],n)||0,bottom:parseInt(e[2],n)||0,left:parseInt(e[3],n)||0})},borderBox:function(){return this._borderBox},paddingBox:function(){return this._paddingBox},marginBox:function(){return this._marginBox},measureBox:function(e,t){function n(t){var n=document.defaultView;return n?(t=t.replace(/[A-Z]/g,function(e){return"-"+e}),n.getComputedStyle(e,null).getPropertyValue(t)):e.currentStyle[t]}function r(e){var t=parseInt(n(e),10);return isNaN(t)?0:t}return{top:r(t+"TopWidth"),right:r(t+"RightWidth"),bottom:r(t+"BottomWidth"),left:r(t+"LeftWidth")}},initLayoutRect:function(){var e=this,n=e.settings,r,i,o=e.getEl(),a,s,l,c,u,d,f;r=e._borderBox=e._borderBox||e.measureBox(o,"border"),e._paddingBox=e._paddingBox||e.measureBox(o,"padding"),e._marginBox=e._marginBox||e.measureBox(o,"margin"),d=n.minWidth,f=n.minHeight,l=d||o.offsetWidth,c=f||o.offsetHeight,a=n.width,s=n.height,u=n.autoResize,u=u!==t?u:!a&&!s,a=a||l,s=s||c;var p=r.left+r.right,h=r.top+r.bottom,m=n.maxWidth||65535,g=n.maxHeight||65535;return e._layoutRect=i={x:n.x||0,y:n.y||0,w:a,h:s,deltaW:p,deltaH:h,contentW:a-p,contentH:s-h,innerW:a-p,innerH:s-h,startMinWidth:d||0,startMinHeight:f||0,minW:Math.min(l,m),minH:Math.min(c,g),maxW:m,maxH:g,autoResize:u,scrollW:0},e._lastLayoutRect={},i},layoutRect:function(e){var t=this,n=t._layoutRect,r,i,o,a,s,l;return n||(n=t.initLayoutRect()),e?(o=n.deltaW,a=n.deltaH,e.x!==s&&(n.x=e.x),e.y!==s&&(n.y=e.y),e.minW!==s&&(n.minW=e.minW),e.minH!==s&&(n.minH=e.minH),i=e.w,i!==s&&(i=n.minW>i?n.minW:i,i=i>n.maxW?n.maxW:i,n.w=i,n.innerW=i-o),i=e.h,i!==s&&(i=n.minH>i?n.minH:i,i=i>n.maxH?n.maxH:i,n.h=i,n.innerH=i-a),i=e.innerW,i!==s&&(i=n.minW-o>i?n.minW-o:i,i=i>n.maxW-o?n.maxW-o:i,n.innerW=i,n.w=i+o),i=e.innerH,i!==s&&(i=n.minH-a>i?n.minH-a:i,i=i>n.maxH-a?n.maxH-a:i,n.innerH=i,n.h=i+a),e.contentW!==s&&(n.contentW=e.contentW),e.contentH!==s&&(n.contentH=e.contentH),r=t._lastLayoutRect,(r.x!==n.x||r.y!==n.y||r.w!==n.w||r.h!==n.h)&&(l=c.repaintControls,l&&l.map&&!l.map[t._id]&&(l.push(t),l.map[t._id]=!0),r.x=n.x,r.y=n.y,r.w=n.w,r.h=n.h),t):n},repaint:function(){var e=this,t,n,r,i,o=0,a=0,s;t=e.getEl().style,r=e._layoutRect,s=e._lastRepaintRect||{},i=e._borderBox,o=i.left+i.right,a=i.top+i.bottom,r.x!==s.x&&(t.left=r.x+"px",s.x=r.x),r.y!==s.y&&(t.top=r.y+"px",s.y=r.y),r.w!==s.w&&(t.width=r.w-o+"px",s.w=r.w),r.h!==s.h&&(t.height=r.h-a+"px",s.h=r.h),e._hasBody&&r.innerW!==s.innerW&&(n=e.getEl("body").style,n.width=r.innerW+"px",s.innerW=r.innerW),e._hasBody&&r.innerH!==s.innerH&&(n=n||e.getEl("body").style,n.height=r.innerH+"px",s.innerH=r.innerH),e._lastRepaintRect=s,e.fire("repaint",{},!1)},on:function(e,n){function r(e){var n,r;return function(o){return n||i.parents().each(function(i){var o=i.settings.callbacks;return o&&(n=o[e])?(r=i,!1):t}),n.call(r,o)}}var i=this,a,s,l,c;if(n)for("string"==typeof n&&(n=r(n)),l=e.toLowerCase().split(" "),c=l.length;c--;)e=l[c],a=i._bindings,a||(a=i._bindings={}),s=a[e],s||(s=a[e]=[]),s.push(n),o[e]&&(i._nativeEvents?i._nativeEvents[e]=!0:i._nativeEvents={name:!0},i._rendered&&i.bindPendingEvents());return i},off:function(e,t){var n=this,r,i=n._bindings,o,a,s,l;if(i)if(e)for(s=e.toLowerCase().split(" "),r=s.length;r--;){if(e=s[r],o=i[e],!e){for(a in i)i[a].length=0;return n}if(o)if(t)for(l=o.length;l--;)o[l]===t&&o.splice(l,1);else o.length=0}else n._bindings=[];return n},fire:function(e,t,n){function r(){return!1}function i(){return!0}var o=this,a,s,l,c;if(e=e.toLowerCase(),t=t||{},t.type||(t.type=e),t.control||(t.control=o),t.preventDefault||(t.preventDefault=function(){t.isDefaultPrevented=i},t.stopPropagation=function(){t.isPropagationStopped=i},t.stopImmediatePropagation=function(){t.isImmediatePropagationStopped=i},t.isDefaultPrevented=r,t.isPropagationStopped=r,t.isImmediatePropagationStopped=r),o._bindings&&(l=o._bindings[e]))for(a=0,s=l.length;s>a&&(t.isImmediatePropagationStopped()||l[a].call(o,t)!==!1);a++);if(n!==!1)for(c=o.parent();c&&!t.isPropagationStopped();)c.fire(e,t,!1),c=c.parent();return t},parents:function(e){var t=this,n=new r;for(t=t.parent();t;t=t.parent())n.add(t);return e&&(n=n.filter(e)),n},next:function(){var e=this.parent().items();return e[e.indexOf(this)+1]},prev:function(){var e=this.parent().items();return e[e.indexOf(this)-1]},findCommonAncestor:function(e,t){for(var n;e;){for(n=t;n&&e!=n;)n=n.parent();if(e==n)break;e=e.parent()}return e},hasClass:function(e,t){var n=this._classes[t||"control"];return e=this.classPrefix+e,n&&!!n.map[e]},addClass:function(e,t){var n=this,r,i;return e=this.classPrefix+e,r=n._classes[t||"control"],r||(r=[],r.map={},n._classes[t||"control"]=r),r.map[e]||(r.map[e]=e,r.push(e),n._rendered&&(i=n.getEl(t),i&&(i.className=r.join(" ")))),n},removeClass:function(e,t){var n=this,r,i,o;if(e=this.classPrefix+e,r=n._classes[t||"control"],r&&r.map[e])for(delete r.map[e],i=r.length;i--;)r[i]===e&&r.splice(i,1);return n._rendered&&(o=n.getEl(t),o&&(o.className=r.join(" "))),n},toggleClass:function(e,t,n){var r=this;return t?r.addClass(e,n):r.removeClass(e,n),r},classes:function(e){var t=this._classes[e||"control"];return t?t.join(" "):""},getEl:function(e,t){var n,r=e?this._id+"-"+e:this._id;return n=a[r]=(t===!0?null:a[r])||i.get(r)},visible:function(e){var n=this,r;return e!==t?(n._visible!==e&&(n._rendered&&(n.getEl().style.display=e?"":"none"),n._visible=e,r=n.parent(),r&&(r._lastRect=null),n.fire(e?"show":"hide")),n):n._visible},show:function(){return this.visible(!0)},hide:function(){return this.visible(!1)},focus:function(){this.getEl().focus()},blur:function(){this.getEl().blur()},aria:function(e,n){var r=this,i=r.getEl();return n===t?r._aria[e]:(r._aria[e]=n,r._rendered&&("label"==e&&i.setAttribute("aria-labeledby",r._id),i.setAttribute("role"==e?e:"aria-"+e,n)),r)},encode:function(e,t){return t!==!1&&c.translate&&(e=c.translate(e)),(e||"").replace(/[&<>"]/g,function(e){return"&#"+e.charCodeAt(0)+";"})},before:function(e){var t=this,n=t.parent();return n&&n.insert(e,n.items().indexOf(t),!0),t},after:function(e){var t=this,n=t.parent();return n&&n.insert(e,n.items().indexOf(t)),t},remove:function(){var e=this,t=e.getEl(),n=e.parent(),r;if(e.items)for(var o=e.items().toArray(),a=o.length;a--;)o[a].remove();return n&&n.items&&(r=[],n.items().each(function(t){t!==e&&r.push(t)}),n.items().set(r),n._lastRect=null),e._eventsRoot&&e._eventsRoot==e&&i.off(t),delete c.controlIdLookup[e._id],t.parentNode&&t.parentNode.removeChild(t),e},renderBefore:function(e){var t=this;return e.parentNode.insertBefore(i.createFragment(t.renderHtml()),e),t.postRender(),t},renderTo:function(e){var t=this;return e=e||t.getContainerElm(),e.appendChild(i.createFragment(t.renderHtml())),t.postRender(),t},postRender:function(){var e=this,t=e.settings,n,r,o,a,s;for(a in t)0===a.indexOf("on")&&e.on(a.substr(2),t[a]);if(e._eventsRoot){for(o=e.parent();!s&&o;o=o.parent())s=o._eventsRoot;if(s)for(a in s._nativeEvents)e._nativeEvents[a]=!0}e.bindPendingEvents(),t.style&&(n=e.getEl(),n&&(n.setAttribute("style",t.style),n.style.cssText=t.style)),e._visible||i.css(e.getEl(),"display","none"),e.settings.border&&(r=e.borderBox(),i.css(e.getEl(),{"border-top-width":r.top,"border-right-width":r.right,"border-bottom-width":r.bottom,"border-left-width":r.left})),c.controlIdLookup[e._id]=e;for(var l in e._aria)e.aria(l,e._aria[l]);e.fire("postrender",{},!1)},scrollIntoView:function(e){function t(e,t){var n,r,i=e;for(n=r=0;i&&i!=t&&i.nodeType;)n+=i.offsetLeft||0,r+=i.offsetTop||0,i=i.offsetParent;return{x:n,y:r}}var n=this.getEl(),r=n.parentNode,i,o,a,s,l,c,u=t(n,r);i=u.x,o=u.y,a=n.offsetWidth,s=n.offsetHeight,l=r.clientWidth,c=r.clientHeight,"end"==e?(i-=l-a,o-=c-s):"center"==e&&(i-=l/2-a/2,o-=c/2-s/2),r.scrollLeft=i,r.scrollTop=o},bindPendingEvents:function(){function e(e){var t=o.getParentCtrl(e.target);t&&t.fire(e.type,e)}function t(){var e=d._lastHoverCtrl;e&&(e.fire("mouseleave",{target:e.getEl()}),e.parents().each(function(e){e.fire("mouseleave",{target:e.getEl()})}),d._lastHoverCtrl=null)}function n(e){var t=o.getParentCtrl(e.target),n=d._lastHoverCtrl,r=0,i,a,s;if(t!==n){if(d._lastHoverCtrl=t,a=t.parents().toArray().reverse(),a.push(t),n){for(s=n.parents().toArray().reverse(),s.push(n),r=0;s.length>r&&a[r]===s[r];r++);for(i=s.length-1;i>=r;i--)n=s[i],n.fire("mouseleave",{target:n.getEl()})}for(i=r;a.length>i;i++)t=a[i],t.fire("mouseenter",{target:t.getEl()})}}function r(e){e.preventDefault(),"mousewheel"==e.type?(e.deltaY=-1/40*e.wheelDelta,e.wheelDeltaX&&(e.deltaX=-1/40*e.wheelDeltaX)):(e.deltaX=0,e.deltaY=e.detail),e=o.fire("wheel",e)}var o=this,a,c,u,d,f,p;if(o._rendered=!0,f=o._nativeEvents){for(u=o.parents().toArray(),u.unshift(o),a=0,c=u.length;!d&&c>a;a++)d=u[a]._eventsRoot;for(d||(d=u[u.length-1]||o),o._eventsRoot=d,c=a,a=0;c>a;a++)u[a]._eventsRoot=d;for(p in f){if(!f)return!1;"wheel"!==p||l?("mouseenter"===p||"mouseleave"===p?d._hasMouseEnter||(i.on(d.getEl(),"mouseleave",t),i.on(d.getEl(),"mouseover",n),d._hasMouseEnter=1):d[p]||(i.on(d.getEl(),p,e),d[p]=!0),f[p]=!1):s?i.on(o.getEl(),"mousewheel",r):i.on(o.getEl(),"DOMMouseScroll",r)}}},reflow:function(){return this.repaint(),this}});return c}),r(U,[],function(){var e={},t;return{add:function(t,n){e[t.toLowerCase()]=n},has:function(t){return!!e[t.toLowerCase()]},create:function(n,r){var i,o,a;if(!t){a=tinymce.ui;for(o in a)e[o.toLowerCase()]=a[o];t=!0}if("string"==typeof n?(r=r||{},r.type=n):(r=n,n=r.type),n=n.toLowerCase(),i=e[n],!i)throw Error("Could not find control by type: "+n);return i=new i(r),i.type=n,i}}}),r(q,[V,W,F,U,p,z],function(e,n,r,i,o,a){var s={};return e.extend({layout:"",innerClass:"container-inner",init:function(e){var t=this;t._super(e),e=t.settings,t._items=new n,t.addClass("container"),t.addClass("container-body","body"),e.containerCls&&t.addClass(e.containerCls),t._layout=i.create((e.layout||t.layout)+"layout"),t.settings.items&&t.add(t.settings.items),t._hasBody=!0},items:function(){return this._items},find:function(e){return e=s[e]=s[e]||new r(e),e.find(this)},add:function(e){var t=this;return t.items().add(t.create(e)).parent(t),t},focus:function(){var e=this;return e.keyNav?e.keyNav.focusFirst():e._super(),e},replace:function(e,t){for(var n,r=this.items(),i=r.length;i--;)if(r[i]===e){r[i]=t;break}i>=0&&(n=t.getEl(),n&&n.parentNode.removeChild(n),n=e.getEl(),n&&n.parentNode.removeChild(n)),t.parent(this)},create:function(t){var n=this,r,a=[];return o.isArray(t)||(t=[t]),o.each(t,function(t){null!==t&&(t instanceof e||("string"==typeof t&&(t={type:t}),r=o.extend({},n.settings.defaults,t),t.type=r.type=r.type||t.type||n.settings.defaultType||(r.defaults?r.defaults.type:null),t=i.create(r)),a.push(t))}),a},renderNew:function(){var e=this;return e.items().each(function(t,n){var r,i;t.parent(e),t._rendered||(r=e.getEl("body"),i=a.createFragment(t.renderHtml()),r.hasChildNodes()&&r.childNodes.length-1>=n?r.insertBefore(i,r.childNodes[n]):r.appendChild(i),t.postRender())}),e._layout.applyClasses(e),e._lastRect=null,e},append:function(e){return this.add(e).renderNew()},prepend:function(e){var t=this;return t.items().set(t.create(e).concat(t.items().toArray())),t.renderNew()},insert:function(e,t,n){var r=this,i,o,a;return e=r.create(e),i=r.items(),n||(t+=1),t>=0&&i.length>t&&(o=i.slice(0,t).toArray(),a=i.slice(t).toArray(),i.set(o.concat(e,a))),r.renderNew()},preRender:function(){},renderHtml:function(){var e=this,t=e._layout;return e.preRender(),t.preRender(e),'
    '+'
    '+(e.settings.html||"")+t.renderHtml(e)+"
    "+"
    "},postRender:function(){var e=this,t;return e.items().exec("postRender"),e._super(),e._layout.postRender(e),e._rendered=!0,e.settings.style&&a.css(e.getEl(),e.settings.style),e.settings.border&&(t=e.borderBox(),a.css(e.getEl(),{"border-top-width":t.top,"border-right-width":t.right,"border-bottom-width":t.bottom,"border-left-width":t.left})),e},initLayoutRect:function(){var e=this,t=e._super();return e._layout.recalc(e),t},recalc:function(){var e=this,n=e._layoutRect,r=e._lastRect;return r&&r.w==n.w&&r.h==n.h?t:(e._layout.recalc(e),n=e.layoutRect(),e._lastRect={x:n.x,y:n.y,w:n.w,h:n.h},!0)},reflow:function(){var t,n;if(this.visible()){for(e.repaintControls=[],e.repaintControls.map={},n=this.recalc(),t=e.repaintControls.length;t--;)e.repaintControls[t].repaint();"flow"!==this.settings.layout&&"stack"!==this.settings.layout&&this.repaint(),e.repaintControls=[]}return this}})}),r($,[z],function(e){function n(){var e=document,t,n,r,i,o,a,s,l,c=Math.max;return t=e.documentElement,n=e.body,r=c(t.scrollWidth,n.scrollWidth),i=c(t.clientWidth,n.clientWidth),o=c(t.offsetWidth,n.offsetWidth),a=c(t.scrollHeight,n.scrollHeight),s=c(t.clientHeight,n.clientHeight),l=c(t.offsetHeight,n.offsetHeight),{width:o>r?i:r,height:l>a?s:a}}return function(r,i){function o(){return s.getElementById(i.handle||r)}var a,s=document,l,c,u,d,f,p;i=i||{},c=function(t){var r=n(),c,h;t.preventDefault(),l=t.button,c=o(),f=t.screenX,p=t.screenY,h=window.getComputedStyle?window.getComputedStyle(c,null).getPropertyValue("cursor"):c.runtimeStyle.cursor,a=s.createElement("div"),e.css(a,{position:"absolute",top:0,left:0,width:r.width,height:r.height,zIndex:65535,opacity:1e-4,background:"red",cursor:h}),s.body.appendChild(a),e.on(s,"mousemove",d),e.on(s,"mouseup",u),i.start(t)},d=function(e){return e.button!==l?u(e):(e.deltaX=e.screenX-f,e.deltaY=e.screenY-p,e.preventDefault(),i.drag(e),t)},u=function(t){e.off(s,"mousemove",d),e.off(s,"mouseup",u),a.parentNode.removeChild(a),i.stop&&i.stop(t)},this.destroy=function(){e.off(o())},e.on(o(),"mousedown",c)}}),r(j,[z,$],function(e,n){return{init:function(){var e=this;e.on("repaint",e.renderScroll)},renderScroll:function(){function r(){function n(n,s,l,c,u,d){var f,p,h,m,g,v,y,b,C;if(p=o.getEl("scroll"+n)){if(b=s.toLowerCase(),C=l.toLowerCase(),o.getEl("absend")&&e.css(o.getEl("absend"),b,o.layoutRect()[c]-1),!u)return e.css(p,"display","none"),t;e.css(p,"display","block"),f=o.getEl("body"),h=o.getEl("scroll"+n+"t"),m=f["client"+l]-2*a,m-=r&&i?p["client"+d]:0,g=f["scroll"+l],v=m/g,y={},y[b]=f["offset"+s]+a,y[C]=m,e.css(p,y),y={},y[b]=f["scroll"+s]*v,y[C]=m*v,e.css(h,y)}}var r,i,s;s=o.getEl("body"),r=s.scrollWidth>s.clientWidth,i=s.scrollHeight>s.clientHeight,n("h","Left","Width","contentW",r,"Height"),n("v","Top","Height","contentH",i,"Width")}function i(){function t(t,r,i,s,l){var c,u=o._id+"-scroll"+t,d=o.classPrefix;o.getEl().appendChild(e.createFragment('
    '+'
    '+"
    ")),o.draghelper=new n(u+"t",{start:function(){c=o.getEl("body")["scroll"+r],e.addClass(e.get(u),d+"active")},drag:function(e){var n,u,d,f,p=o.layoutRect();u=p.contentW>p.innerW,d=p.contentH>p.innerH,f=o.getEl("body")["client"+i]-2*a,f-=u&&d?o.getEl("scroll"+t)["client"+l]:0,n=f/o.getEl("body")["scroll"+i],o.getEl("body")["scroll"+r]=c+e["delta"+s]/n},stop:function(){e.removeClass(e.get(u),d+"active")}})}o.addClass("scroll"),t("v","Top","Height","Y","Width"),t("h","Left","Width","X","Height")}var o=this,a=2;o.settings.autoScroll&&(o._hasScroll||(o._hasScroll=!0,i(),o.on("wheel",function(e){var t=o.getEl("body");t.scrollLeft+=10*(e.deltaX||0),t.scrollTop+=10*e.deltaY,r()}),e.on(o.getEl("body"),"scroll",r)),r())}}}),r(G,[q,j],function(e,n){var r=e.extend({Defaults:{layout:"fit",containerCls:"panel"},Mixins:[n],fromJSON:function(e){var t=this;for(var n in e)t.find("#"+n).value(e[n]);return t},toJSON:function(){var e=this,n={};return e.find("*").each(function(e){var r=e.name(),i=e.value();r&&i!==t&&(n[r]=i)}),n},renderHtml:function(){var e=this,n=e._layout,r=e.settings.html;return e.preRender(),n.preRender(e),r===t?r='
    '+n.renderHtml(e)+"
    ":("function"==typeof r&&(r=r()),e._hasBody=!1),'
    '+(e._preBodyHtml||"")+r+"
    "}});return r}),r(K,[z],function(e){return{moveRel:function(t,n){var r=this,i,o,a,s,l,c,u,d;return o=e.getPos(t),a=o.x,s=o.y,i=r.getEl(),l=i.offsetWidth,c=i.offsetHeight,u=t.offsetWidth,d=t.offsetHeight,n=(n||"").split(""),"b"===n[0]&&(s+=d),"r"===n[1]&&(a+=u),"c"===n[0]&&(s+=Math.round(d/2)),"c"===n[1]&&(a+=Math.round(u/2)),"b"===n[3]&&(s-=c),"r"===n[4]&&(a-=l),"c"===n[3]&&(s-=Math.round(c/2)),"c"===n[4]&&(a-=Math.round(l/2)),r.moveTo(a,s),r},moveBy:function(e,t){var n=this,r=n.layoutRect();return n.moveTo(r.x+e,r.y+t),n},moveTo:function(e,t){var n=this;return n._rendered?n.layoutRect({x:e,y:t}).repaint():(n.settings.x=e,n.settings.y=t),n}}}),r(X,[z],function(e){return{resizeToContent:function(){this._layoutRect.autoResize=!0,this._lastRect=null,this.reflow()},resizeTo:function(t,n){if(1>=t||1>=n){var r=e.getWindowSize();t=1>=t?t*r.w:t,n=1>=n?n*r.h:n}return this._layoutRect.autoResize=!1,this.layoutRect({minW:t,minH:n,w:t,h:n}).reflow()},resizeBy:function(e,t){var n=this,r=n.layoutRect();return n.resizeTo(r.w+e,r.h+t)}}}),r(Y,[G,K,X,z],function(e,t,n,r){var i,o=[],a=[],s,l=e.extend({Mixins:[t,n],init:function(e){function t(){var e,t=l.zIndex||65535,n;if(a.length)for(e=0;a.length>e;e++)a[e].modal&&(t++,n=a[e]),a[e].getEl().style.zIndex=t,a[e].zIndex=t,t++;var i=document.getElementById(c.classPrefix+"modal-block");n?r.css(i,"z-index",n.zIndex-1):i&&(i.parentNode.removeChild(i),s=!1),l.currentZIndex=t}function n(e,t){for(;e;){if(e==t)return!0;e=e.parent()}}var c=this;c._super(e),c._eventsRoot=c,c.addClass("floatpanel"),e.autohide&&(i||(i=function(e){var t,r=c.getParentCtrl(e.target);for(t=o.length;t--;)(!r||!n(r,o[t])&&o[t].parent()!==r)&&o[t].hide()},r.on(document,"click",i)),o.push(c)),c.on("postrender show",function(e){if(e.control==c){var n,i=c.classPrefix;c.modal&&!s&&(n=r.createFragment('
    '),n=n.firstChild,c.getContainerElm().appendChild(n),setTimeout(function(){r.addClass(n,i+"in"),r.addClass(c.getEl(),i+"in")},0),s=!0),a.push(c),t()}}),c.on("close hide",function(e){if(e.control==c){for(var n=a.length;n--;)a[n]===c&&a.splice(n,1);t()}}),e.popover&&(c._preBodyHtml='
    ',c.addClass("popover").addClass("bottom").addClass("start"))},show:function(){var e=this,t,n=e._super();for(t=o.length;t--&&o[t]!==e;);return e.settings.autohide&&-1===t&&o.push(e),n},hide:function(){var e;for(e=o.length;e--;)o[e]===this&&o.splice(e,1);return this._super()},hideAll:function(){l.hideAll()},close:function(){var e=this;return e.fire("close"),e.remove()},remove:function(){var e=this;e._super()}});return l.hideAll=function(){for(var e=o.length;e--;)o[e].fire("cancel",{},!1),o[e].hide(),o.splice(e,1)},l}),r(J,[z],function(e){return function(n){function r(){if(!m)if(m=[],f.find)f.find("*").each(function(e){e.canFocus&&m.push(e.getEl())});else for(var e=f.getEl().getElementsByTagName("*"),t=0;e.length>t;t++)e[t].id&&e[t]&&m.push(e[t])}function i(){return document.getElementById(g)}function o(e){return e=e||i(),e&&e.getAttribute("role")}function a(e){for(var t,n=e||i();n=n.parentNode;)if(t=o(n))return t}function s(e){var n=document.getElementById(g);return n?n.getAttribute("aria-"+e):t}function l(){var t=i();if(!t||"TEXTAREA"!=t.nodeName&&"text"!=t.type)return n.onAction?n.onAction(g):e.fire(i(),"click",{keyboard:!0}),!0}function c(){var e;n.onCancel?((e=i())&&e.blur(),n.onCancel()):n.root.fire("cancel")}function u(e){var t=-1,i,o;for(r(),o=m.length;o--;)if(m[o].id===g){t=o;break}t+=e,0>t?t=m.length-1:t>=m.length&&(t=0),i=m[t],i.focus(),g=i.id,n.actOnFocus&&l()}function d(){var e,i;for(i=o(n.root.getEl()),r(),e=m.length;e--;)if("toolbar"==i&&m[e].id===g)return m[e].focus(),t;m[0].focus()}var f=n.root,p=n.enableUpDown!==!1,h=n.enableLeftRight!==!1,m=n.items,g;return f.on("keydown",function(e){var t=37,r=39,i=38,d=40,f=27,m=14,g=13,v=32,y=9,b;switch(e.keyCode){case t:h&&(n.leftAction?n.leftAction():u(-1),b=!0);break;case r:h&&("menuitem"==o()&&"menu"==a()?s("haspopup")&&l():u(1),b=!0);break;case i:p&&(u(-1),b=!0);break;case d:p&&("menuitem"==o()&&"menubar"==a()?l():"button"==o()&&s("haspopup")?l():u(1),b=!0);break;case y:b=!0,e.shiftKey?u(-1):u(1);break;case f:b=!0,c();break;case m:case g:case v:b=l()}b&&(e.stopPropagation(),e.preventDefault())}),f.on("focusin",function(e){r(),g=e.target.id}),{moveFocus:u,focusFirst:d,cancel:c}}}),r(Q,[Y,G,z,J,$],function(e,n,r,i,o){var a=e.extend({modal:!0,Defaults:{border:1,layout:"flex",containerCls:"panel",role:"dialog",callbacks:{submit:function(){this.fire("submit",{data:this.toJSON()})},close:function(){this.close()}}},init:function(e){var t=this;t._super(e),t.addClass("window"),e.buttons&&(t.statusbar=new n({layout:"flex",border:"1 0 0 0",spacing:3,padding:10,align:"center",pack:"end",defaults:{type:"button"},items:e.buttons}),t.statusbar.addClass("foot"),t.statusbar.parent(t)),t.on("click",function(e){-1!=e.target.className.indexOf(t.classPrefix+"close")&&t.close()}),t.aria("label",e.title),t._fullscreen=!1},recalc:function(){var e=this,n=e.statusbar,i,o,a;return e._fullscreen&&(e.layoutRect(r.getWindowSize()),e.layoutRect().contentH=e.layoutRect().innerH),e._super(),i=e.layoutRect(),e.settings.title&&!e._fullscreen&&(o=i.headerW,o>i.minW&&(i.minW=i.w=o+(i.w-i.innerW),i.innerW=i.w-i.deltaW,a=!0)),n&&(n.layoutRect({w:e.layoutRect().innerW}).recalc(),o=n.layoutRect().minW+i.deltaW,o>i.minW&&(i.minW=i.w=o,i.innerW=i.w-i.deltaW,a=!0)),a?(e.recalc(),t):t},initLayoutRect:function(){var e=this,t=e._super(),n=0,i;e.settings.title&&!e._fullscreen&&(i=e.getEl("head"),t.headerW=i.offsetWidth,t.headerH=i.offsetHeight,n+=t.headerH),e.statusbar&&(n+=e.statusbar.layoutRect().h),t.deltaH+=n,t.minH+=n,t.h+=n;var o=r.getWindowSize();return t.x=Math.max(0,o.w/2-t.w/2),t.y=Math.max(0,o.h/2-t.h/2),t},renderHtml:function(){var e=this,n=e._layout,r=e._id,i=e.classPrefix,o=e.settings,a="",s="",l=o.html;return e.preRender(),n.preRender(e),o.title&&(a='
    '+'
    '+o.title+"
    "+''+'
    '+"
    "),o.url&&(l=''),l===t&&(l=n.renderHtml(e)),e.statusbar&&(s=e.statusbar.renderHtml()),'
    '+a+'
    '+l+"
    "+s+"
    "},fullscreen:function(e){var t=this,n=document.documentElement,i,o=t.classPrefix,a;if(e!=t._fullscreen)if(r.on(window,"resize",function(){var e;if(t._fullscreen)if(i)t._timer||(t._timer=setTimeout(function(){var e=r.getWindowSize();t.moveTo(0,0).resizeTo(e.w,e.h),t._timer=0},50));else{e=(new Date).getTime();var n=r.getWindowSize();t.moveTo(0,0).resizeTo(n.w,n.h),(new Date).getTime()-e>50&&(i=!0)}}),a=t.layoutRect(),t._fullscreen=e,e){t._initial={x:a.x,y:a.y,w:a.w,h:a.h},t._borderBox=t.parseBox("0"),t.getEl("head").style.display="none",a.deltaH-=a.headerH+2,r.addClass(n,o+"fullscreen"),r.addClass(document.body,o+"fullscreen"),t.addClass("fullscreen");var s=r.getWindowSize();t.moveTo(0,0).resizeTo(s.w,s.h)}else t._borderBox=t.parseBox(t.settings.border),t.getEl("head").style.display="",a.deltaH+=a.headerH,r.removeClass(n,o+"fullscreen"),r.removeClass(document.body,o+"fullscreen"),t.removeClass("fullscreen"),t.moveTo(t._initial.x,t._initial.y).resizeTo(t._initial.w,t._initial.h);return t.reflow()},postRender:function(){var e=this,t=[],n,r,a;setTimeout(function(){e.addClass("in")},0),e.find("*").each(function(e){e.canFocus&&(r=r||e.settings.autofocus,n=n||e,"filepicker"==e.type?(t.push(e.getEl("inp")),e.getEl("open")&&t.push(e.getEl("open").firstChild)):t.push(e.getEl()))}),e.statusbar&&e.statusbar.find("*").each(function(e){e.canFocus&&(r=r||e.settings.autofocus,n=n||e,t.push(e.getEl()))}),e.keyboardNavigation=new i({root:e,enableLeftRight:!1,enableUpDown:!1,items:t,onCancel:function(){e.close()}}),e._super(),e.statusbar&&e.statusbar.postRender(),!r&&n&&n.focus(),this.dragHelger=new o(e._id+"-dragh",{start:function(){a={x:e.layoutRect().x,y:e.layoutRect().y}},drag:function(t){e.moveTo(a.x+t.deltaX,a.y+t.deltaY)}}),e.on("submit",function(t){t.isDefaultPrevented()||e.close()})},submit:function(){return this.fire("submit",{data:this.toJSON()})},remove:function(){var e=this;e._super(),e.dragHelger.destroy(),e.statusbar&&this.statusbar.remove()}});return a}),r(Z,[Q],function(e){var t=e.extend({init:function(e){e={border:1,padding:20,layout:"flex",pack:"center",align:"center",containerCls:"panel",autoScroll:!0,buttons:{type:"button",text:"Ok",action:"ok"},items:{type:"label",multiline:!0,maxWidth:500,maxHeight:200}},this._super(e)},Statics:{OK:1,OK_CANCEL:2,YES_NO:3,YES_NO_CANCEL:4,msgBox:function(n){var r,i=n.callback||function(){};switch(n.buttons){case t.OK_CANCEL:r=[{type:"button",text:"Ok",subtype:"primary",onClick:function(e){e.control.parents()[1].close(),i(!0)}},{type:"button",text:"Cancel",onClick:function(e){e.control.parents()[1].close(),i(!1)}}];break;case t.YES_NO:r=[{type:"button",text:"Ok",subtype:"primary",onClick:function(e){e.control.parents()[1].close(),i(!0)}}];break;case t.YES_NO_CANCEL:r=[{type:"button",text:"Ok",subtype:"primary",onClick:function(e){e.control.parents()[1].close()}}];break;default:r=[{type:"button",text:"Ok",subtype:"primary",onClick:function(e){e.control.parents()[1].close()}}]}return new e({padding:20,x:n.x,y:n.y,minWidth:300,minHeight:100,layout:"flex",pack:"center",align:"center",buttons:r,title:n.title,items:{type:"label",multiline:!0,maxWidth:500,maxHeight:200,text:n.text},onClose:n.onClose}).renderTo(document.body).reflow()},alert:function(e,n){return"string"==typeof e&&(e={text:e}),e.callback=n,t.msgBox(e)},confirm:function(e,n){return"string"==typeof e&&(e={text:e}),e.callback=n,e.buttons=t.OK_CANCEL,t.msgBox(e)}}});return t}),r(et,[Q,Z],function(e,t){return function(n){var r=this,i=[];r.windows=i,r.open=function(t){var r;return t.url=t.url||t.file,t.url&&(t.width=parseInt(t.width||320,10),t.height=parseInt(t.height||240,10)),t.body&&(t.items={defaults:t.defaults,type:t.bodyType||"form",items:t.body}),t.url||t.buttons||(t.buttons=[{text:"Ok",subtype:"primary",minWidth:50,onclick:function(){r.find("form")[0].submit(),r.close()}},{text:"Cancel",onclick:function(){r.close()}}]),r=new e(t),i.push(r),r.on("close",function(){for(var e=i.length;e--;)i[e]===r&&i.splice(e,1);n.focus()}),t.data&&r.on("postRender",function(){this.find("*").each(function(e){var n=e.name();n in t.data&&e.value(t.data[n])})}),r.renderTo(document.body).reflow()},r.alert=function(e,n,r){t.alert(e,function(){n.call(r||this)})},r.confirm=function(e,n,r){t.confirm(e,function(e){n.call(r||this,e)})},r.close=function(){i.length&&i[window.length-1].win.close()}}}),r(tt,[T,B,C,m,g,p],function(e,n,r,i,o,a){return function(s){function l(e,t){try{s.getDoc().execCommand(e,!1,t)}catch(n){}}function c(){var e=s.getDoc().documentMode;return e?e:6}function u(e){return e.isDefaultPrevented()}function d(){function t(e){function t(){if(3==l.nodeType){if(e&&c==l.length)return!0;if(!e&&0===c)return!0}}var n,r,i,o,l,c,u;n=F.getRng();var d=[n.startContainer,n.startOffset,n.endContainer,n.endOffset];if(n.collapsed||(e=!0),l=n[(e?"start":"end")+"Container"],c=n[(e?"start":"end")+"Offset"],3==l.nodeType&&(r=I.getParent(n.startContainer,I.isBlock),e&&(r=I.getNext(r,I.isBlock)),!r||!t()&&n.collapsed||(i=I.create("em",{id:"__mceDel"}),D(a.grep(r.childNodes),function(e){i.appendChild(e)}),r.appendChild(i))),n=I.createRng(),n.setStart(d[0],d[1]),n.setEnd(d[2],d[3]),F.setRng(n),s.getDoc().execCommand(e?"ForwardDelete":"Delete",!1,null),i){for(o=F.getBookmark();u=I.get("__mceDel");)I.remove(u,!0);F.moveToBookmark(o)}}s.on("keydown",function(n){var r;r=n.keyCode==O,u(n)||!r&&n.keyCode!=P||e.modifierPressed(n)||(n.preventDefault(),t(r))}),s.addCommand("Delete",function(){t()})}function f(){function e(e){var t=I.create("body"),n=e.cloneContents();return t.appendChild(n),F.serializer.serialize(t,{format:"html"})}function t(t){var n=e(t),r=I.createRng();r.selectNode(s.getBody());var i=e(r);return n===i}s.on("keydown",function(e){var n=e.keyCode,r;if(!u(e)&&(n==O||n==P)){if(r=s.selection.isCollapsed(),r&&!I.isEmpty(s.getBody()))return;if(q&&!r)return;if(!r&&!t(s.selection.getRng()))return;e.preventDefault(),s.setContent(""),s.selection.setCursorLocation(s.getBody(),0),s.nodeChanged()}})}function p(){s.on("keydown",function(t){!u(t)&&65==t.keyCode&&e.metaKeyPressed(t)&&(t.preventDefault(),s.execCommand("SelectAll"))})}function h(){s.settings.content_editable||(I.bind(s.getDoc(),"focusin",function(){F.setRng(F.getRng())}),I.bind(s.getDoc(),"mousedown",function(e){e.target==s.getDoc().documentElement&&(s.getWin().focus(),F.setRng(F.getRng()))}))}function m(){s.on("keydown",function(e){if(!u(e)&&e.keyCode===P&&F.isCollapsed()&&0===F.getRng(!0).startOffset){var t=F.getNode(),n=t.previousSibling;n&&n.nodeName&&"hr"===n.nodeName.toLowerCase()&&(I.remove(n),e.preventDefault())}})}function g(){window.Range.prototype.getClientRects||s.on("mousedown",function(e){if(!u(e)&&"HTML"===e.target.nodeName){var t=s.getBody();t.blur(),setTimeout(function(){t.focus()},0)}})}function v(){s.on("click",function(e){e=e.target,/^(IMG|HR)$/.test(e.nodeName)&&F.getSel().setBaseAndExtent(e,0,e,1),"A"==e.nodeName&&I.hasClass(e,"mceItemAnchor")&&F.select(e),s.nodeChanged()})}function y(){function e(){var e=I.getAttribs(F.getStart().cloneNode(!1));return function(){var t=F.getStart();t!==s.getBody()&&(I.setAttrib(t,"style",null),D(e,function(e){t.setAttributeNode(e.cloneNode(!0))}))}}function n(){return!F.isCollapsed()&&I.getParent(F.getStart(),I.isBlock)!=I.getParent(F.getEnd(),I.isBlock)}s.on("keypress",function(r){var i;return u(r)||8!=r.keyCode&&46!=r.keyCode||!n()?t:(i=e(),s.getDoc().execCommand("delete",!1,null),i(),r.preventDefault(),!1)}),I.bind(s.getDoc(),"cut",function(t){var r;!u(t)&&n()&&(r=e(),setTimeout(function(){r()},0))})}function b(){var e,t;s.on("selectionchange",function(){t&&(clearTimeout(t),t=0),t=window.setTimeout(function(){var t=F.getRng();e&&n.compareRanges(t,e)||(s.nodeChanged(),e=t)},50)})}function C(){document.body.setAttribute("role","application")}function x(){s.on("keydown",function(e){if(!u(e)&&e.keyCode===P&&F.isCollapsed()&&0===F.getRng(!0).startOffset){var t=F.getNode().previousSibling;if(t&&t.nodeName&&"table"===t.nodeName.toLowerCase())return e.preventDefault(),!1}})}function w(){c()>7||(l("RespectVisibilityInDesign",!0),s.contentStyles.push(".mceHideBrInPre pre br {display: none}"),I.addClass(s.getBody(),"mceHideBrInPre"),z.addNodeFilter("pre",function(e){for(var t=e.length,n,i,o,a;t--;)for(n=e[t].getAll("br"),i=n.length;i--;)o=n[i],a=o.prev,a&&3===a.type&&"\n"!=a.value.charAt(a.value-1)?a.value+="\n":o.parent.insert(new r("#text",3),o,!0).value="\n"}),V.addNodeFilter("pre",function(e){for(var t=e.length,n,r,i,o;t--;)for(n=e[t].getAll("br"),r=n.length;r--;)i=n[r],o=i.prev,o&&3==o.type&&(o.value=o.value.replace(/\r?\n$/,""))}))}function _(){I.bind(s.getBody(),"mouseup",function(){var e,t=F.getNode();"IMG"==t.nodeName&&((e=I.getStyle(t,"width"))&&(I.setAttrib(t,"width",e.replace(/[^0-9%]+/g,"")),I.setStyle(t,"width","")),(e=I.getStyle(t,"height"))&&(I.setAttrib(t,"height",e.replace(/[^0-9%]+/g,"")),I.setStyle(t,"height",""))) +})}function N(){s.on("keydown",function(t){var n,r,i,o,a,l,c,d;if(n=t.keyCode==O,!u(t)&&(n||t.keyCode==P)&&!e.modifierPressed(t)&&(r=F.getRng(),i=r.startContainer,o=r.startOffset,c=r.collapsed,3==i.nodeType&&i.nodeValue.length>0&&(0===o&&!c||c&&o===(n?0:1)))){if(l=i.previousSibling,l&&"IMG"==l.nodeName)return;d=s.schema.getNonEmptyElements(),t.preventDefault(),a=I.create("br",{id:"__tmp"}),i.parentNode.insertBefore(a,i),s.getDoc().execCommand(n?"ForwardDelete":"Delete",!1,null),i=F.getRng().startContainer,l=i.previousSibling,l&&1==l.nodeType&&!I.isBlock(l)&&I.isEmpty(l)&&!d[l.nodeName.toLowerCase()]&&I.remove(l),I.remove("__tmp")}})}function k(){s.on("keydown",function(t){var n,r,i,o,a;if(!u(t)&&t.keyCode==e.BACKSPACE&&(n=F.getRng(),r=n.startContainer,i=n.startOffset,o=I.getRoot(),a=r,n.collapsed&&0===i)){for(;a&&a.parentNode&&a.parentNode.firstChild==a&&a.parentNode!=o;)a=a.parentNode;"BLOCKQUOTE"===a.tagName&&(s.formatter.toggle("blockquote",null,a),n=I.createRng(),n.setStart(r,0),n.setEnd(r,0),F.setRng(n))}})}function E(){function e(){s._refreshContentEditable(),l("StyleWithCSS",!1),l("enableInlineTableEditing",!1),W.object_resizing||l("enableObjectResizing",!1)}W.readonly||s.on("BeforeExecCommand MouseDown",e)}function S(){function e(){D(I.select("a"),function(e){var t=e.parentNode,n=I.getRoot();if(t.lastChild===e){for(;t&&!I.isBlock(t);){if(t.parentNode.lastChild!==t||t===n)return;t=t.parentNode}I.add(t,"br",{"data-mce-bogus":1})}})}s.on("SetContent ExecCommand",function(t){("setcontent"==t.type||"mceInsertLink"===t.command)&&e()})}function T(){W.forced_root_block&&s.on("init",function(){l("DefaultParagraphSeparator",W.forced_root_block)})}function R(){s.on("Undo Redo SetContent",function(e){e.initial||s.execCommand("mceRepaint")})}function A(){s.on("keydown",function(e){var t;u(e)||e.keyCode!=P||(t=s.getDoc().selection.createRange(),t&&t.item&&(e.preventDefault(),s.undoManager.beforeChange(),I.remove(t.item(0)),s.undoManager.add()))})}function B(){var e;c()>=10&&(e="",D("p div h1 h2 h3 h4 h5 h6".split(" "),function(t,n){e+=(n>0?",":"")+t+":empty"}),s.contentStyles.push(e+"{padding-right: 1px !important}"))}function L(){9>c()&&(z.addNodeFilter("noscript",function(e){for(var t=e.length,n,r;t--;)n=e[t],r=n.firstChild,r&&n.attr("data-mce-innertext",r.value)}),V.addNodeFilter("noscript",function(e){for(var t=e.length,n,o,a;t--;)n=e[t],o=e[t].firstChild,o?o.value=i.decode(o.value):(a=n.attributes.map["data-mce-innertext"],a&&(n.attr("data-mce-innertext",null),o=new r("#text",3),o.value=a,o.raw=!0,n.append(o)))}))}function H(){function e(e,t){var n=i.createTextRange();try{n.moveToPoint(e,t)}catch(r){n=null}return n}function t(t){var r;t.button?(r=e(t.x,t.y),r&&(r.compareEndPoints("StartToStart",a)>0?r.setEndPoint("StartToStart",a):r.setEndPoint("EndToEnd",a),r.select())):n()}function n(){var e=r.selection.createRange();a&&!e.item&&0===e.compareEndPoints("StartToEnd",e)&&a.select(),I.unbind(r,"mouseup",n),I.unbind(r,"mousemove",t),a=o=0}var r=I.doc,i=r.body,o,a,s;r.documentElement.unselectable=!0,I.bind(r,"mousedown contextmenu",function(i){if("HTML"===i.target.nodeName){if(o&&n(),s=r.documentElement,s.scrollHeight>s.clientHeight)return;o=1,a=e(i.x,i.y),a&&(I.bind(r,"mouseup",n),I.bind(r,"mousemove",t),I.win.focus(),a.select())}})}function M(){s.on("keyup focusin",function(t){65==t.keyCode&&e.metaKeyPressed(t)||F.normalize()})}var D=a.each,P=e.BACKSPACE,O=e.DELETE,I=s.dom,F=s.selection,W=s.settings,z=s.parser,V=s.serializer,U=o.gecko,q=o.ie,$=o.webkit;x(),k(),f(),M(),$&&(N(),d(),h(),v(),T(),o.iOS?b():p()),q&&(m(),C(),w(),_(),A(),B(),L(),H()),U&&(m(),g(),y(),E(),S(),R())}}),r(nt,[p],function(e){function t(){return!1}function n(){return!0}var r="__bindings",i=e.makeMap("focusin focusout click dblclick mousedown mouseup mousemove mouseover beforepaste paste cut copy mouseout mouseenter mouseleave keydown keypress keyup contextmenu dragend dragover draggesture dragdrop drop drag"," ");return{fire:function(e,i,o){var a=this,s,l,c,u,d;if(e=e.toLowerCase(),i=i||{},i.type=e,i.target||(i.target=a),i.preventDefault||(i.preventDefault=function(){i.isDefaultPrevented=n},i.stopPropagation=function(){i.isPropagationStopped=n},i.stopImmediatePropagation=function(){i.isImmediatePropagationStopped=n},i.isDefaultPrevented=t,i.isPropagationStopped=t,i.isImmediatePropagationStopped=t),a[r]&&(s=a[r][e]))for(l=0,c=s.length;c>l&&(s[l]=u=s[l],!i.isImmediatePropagationStopped());l++)if(u.call(a,i)===!1)return i.preventDefault(),i;if(o!==!1&&a.parent)for(d=a.parent();d&&!i.isPropagationStopped();)d.fire(e,i,!1),d=d.parent();return i},on:function(e,t){var n=this,o,a,s,l;if(t===!1&&(t=function(){return!1}),t)for(s=e.toLowerCase().split(" "),l=s.length;l--;)e=s[l],o=n[r],o||(o=n[r]={}),a=o[e],a||(a=o[e]=[],n.bindNative&&i[e]&&n.bindNative(e)),a.push(t);return n},off:function(e,t){var n=this,o,a=n[r],s,l,c,u;if(a)if(e)for(c=e.toLowerCase().split(" "),o=c.length;o--;){if(e=c[o],s=a[e],!e){for(l in a)a[e].length=0;return n}if(s){if(t)for(u=s.length;u--;)s[u]===t&&s.splice(u,1);else s.length=0;!s.length&&n.unbindNative&&i[e]&&(n.unbindNative(e),delete a[e])}}else{if(n.unbindNative)for(e in a)n.unbindNative(e);n[r]=[]}return n}}}),r(rt,[p,g],function(e,n){var r=e.each,i=e.explode,o={f9:120,f10:121,f11:122};return function(e){var a=this,s={};e.on("keyup keypress keydown",function(e){(e.altKey||e.ctrlKey||e.metaKey)&&r(s,function(r){var i=n.isMac?e.metaKey:e.ctrlKey;if(r.ctrl==i&&r.alt==e.altKey&&r.shift==e.shiftKey)return e.keyCode==r.keyCode||e.charCode&&e.charCode==r.charCode?(e.preventDefault(),"keydown"==e.type&&r.func.call(r.scope),!0):t})}),a.add=function(t,n,a,l){var c;return c=a,"string"==typeof a?a=function(){e.execCommand(c,!1,null)}:a.length&&(a=function(){e.execCommand(c[0],c[1],c[2])}),r(i(t.toLowerCase()),function(t){var c={func:a,scope:l||e,desc:e.translate(n),alt:!1,ctrl:!1,shift:!1};r(i(t,"+"),function(e){switch(e){case"alt":case"ctrl":case"shift":c[e]=!0;break;default:c.charCode=e.charCodeAt(0),c.keyCode=o[e]||e.toUpperCase().charCodeAt(0)}}),s[(c.ctrl?"ctrl":"")+","+(c.alt?"alt":"")+","+(c.shift?"shift":"")+","+c.keyCode]=c}),!0}}}),r(it,[v,b,C,E,k,A,L,H,M,D,P,O,y,l,et,x,_,tt,g,p,nt,rt],function(e,n,r,i,o,a,s,l,c,u,d,f,p,h,m,g,v,y,b,C,x,w){function _(e,t){return!e.inline&&/^mouse|click|contextmenu/.test(t)?e.getDoc():e.getBody()}function N(e,t,r){var i=this,o,a;o=i.documentBaseUrl=r.documentBaseURL,a=r.baseURI,i.settings=t=T({id:e,theme:"modern",delta_width:0,delta_height:0,popup_css:"",plugins:"",document_base_url:o,add_form_submit_trigger:!0,submit_patch:!0,add_unload_trigger:!0,convert_urls:!0,relative_urls:!0,remove_script_host:!0,table_inline_editing:!1,object_resizing:!0,doctype:"",visual:!0,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%",apply_source_formatting:!0,directionality:"ltr",forced_root_block:"p",hidden_input:!0,padd_empty_editor:!0,render_ui:!0,indentation:"30px",inline_styles:!0,convert_fonts_to_spans:!0,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,option,optgroup,datalist",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,option,optgroup,datalist",validate:!0,entity_encoding:"named",url_converter:i.convertURL,url_converter_scope:i,ie7_compat:!0},t),n.settings=t,n.baseURL=r.baseURL,i.id=t.id=e,i.isNotDirty=!1,i.plugins={},i.documentBaseURI=new f(t.document_base_url||o,{base_uri:a}),i.baseURI=a,i.contentCSS=[],i.contentStyles=[],i.shortcuts=new w(i),i.execCommands={},i.queryStateCommands={},i.queryValueCommands={},i.suffix=r.suffix,i.editorManager=r,i.inline=t.inline,i.execCallback("setup",i)}var k=e.DOM,E=n.ThemeManager,S=n.PluginManager,T=C.extend,R=C.each,A=C.explode,B=C.inArray,L=C.trim,H=C.resolve,M=h.Event,D=b.gecko,P=b.ie,O=b.opera;return N.prototype={render:function(){function e(){var e=p.ScriptLoader;r.language&&e.add(n.editorManager.baseURL+"/langs/"+r.language+".js"),r.theme&&"function"!=typeof r.theme&&"-"!=r.theme.charAt(0)&&!E.urls[r.theme]&&E.load(r.theme,"themes/"+r.theme+"/theme"+o+".js"),C.isArray(r.plugins)&&(r.plugins=r.plugins.join(" ")),R(r.plugins.split(/[ ,]/),function(e){if(e=L(e),e&&!S.urls[e])if("-"==e.charAt(0)){e=e.substr(1,e.length);var t=S.dependencies(e);R(t,function(e){var t={prefix:"plugins/",resource:e,suffix:"/plugin"+o+".js"};e=S.createUrl(t,e),S.load(e.resource,e)})}else S.load(e,{prefix:"plugins/",resource:e,suffix:"/plugin"+o+".js"})}),e.loadQueue(function(){n.removed||n.init()})}var n=this,r=n.settings,i=n.id,o=n.suffix;if(!M.domLoaded)return k.bind(window,"ready",function(){n.render()}),t;if(n.editorManager.settings=r,n.getElement()&&b.contentEditable){r.inline?n.inline=!0:(n.orgVisibility=n.getElement().style.visibility,n.getElement().style.visibility="hidden");var a=n.getElement().form||k.getParent(i,"form");a&&(n.formElement=a,r.hidden_input&&!/TEXTAREA|INPUT/i.test(n.getElement().nodeName)&&k.insertAfter(k.create("input",{type:"hidden",name:i}),i),n.formEventDelegate=function(e){n.fire(e.type,e)},k.bind(a,"submit reset",n.formEventDelegate),n.on("reset",function(){n.setContent(n.startContent,{format:"raw"})}),!r.submit_patch||a.submit.nodeType||a.submit.length||a._mceOldSubmit||(a._mceOldSubmit=a.submit,a.submit=function(){return n.editorManager.triggerSave(),n.isNotDirty=1,a._mceOldSubmit(a)})),n.windowManager=new m(n),"xml"==r.encoding&&n.on("GetContent",function(e){e.save&&(e.content=k.encode(e.content))}),r.add_form_submit_trigger&&n.on("submit",function(){n.initialized&&(n.save(),n.isNotDirty=1)}),r.add_unload_trigger&&(n._beforeUnload=function(){!n.initialized||n.destroyed||n.isHidden()||n.save({format:"raw",no_events:!0})},n.editorManager.on("BeforeUnload",n._beforeUnload)),e()}},init:function(){function e(n){var r=S.get(n),i,o;i=S.urls[n]||t.documentBaseUrl.replace(/\/$/,""),n=L(n),r&&-1===B(h,n)&&(R(S.dependencies(n),function(t){e(t)}),o=new r(t,i),t.plugins[n]=o,o.init&&(o.init(t,i),h.push(n)))}var t=this,n=t.settings,r=t.getElement(),i,o,a,s,l,c,u,d,f,p,h=[];if(t.editorManager.add(t),n.aria_label=n.aria_label||k.getAttrib(r,"aria-label",t.getLang("aria.rich_text_area")),n.theme&&("function"!=typeof n.theme?(n.theme=n.theme.replace(/-/,""),l=E.get(n.theme),t.theme=new l(t,E.urls[n.theme]),t.theme.init&&t.theme.init(t,E.urls[n.theme]||t.documentBaseUrl.replace(/\/$/,""))):t.theme=n.theme),R(n.plugins.replace(/\-/g,"").split(/[ ,]/),e),t.fire("BeforeRenderUI"),n.render_ui&&t.theme&&(t.orgDisplay=r.style.display,"function"!=typeof n.theme?(i=n.width||r.style.width||r.offsetWidth,o=n.height||r.style.height||r.offsetHeight,a=n.min_height||100,f=/^[0-9\.]+(|px)$/i,f.test(""+i)&&(i=Math.max(parseInt(i,10)+(l.deltaWidth||0),100)),f.test(""+o)&&(o=Math.max(parseInt(o,10)+(l.deltaHeight||0),a)),l=t.theme.renderUI({targetNode:r,width:i,height:o,deltaWidth:n.delta_width,deltaHeight:n.delta_height}),n.content_editable||(k.setStyles(l.sizeContainer||l.editorContainer,{wi2dth:i,h2eight:o}),o=(l.iframeHeight||o)+("number"==typeof o?l.deltaHeight||0:""),a>o&&(o=a))):(l=n.theme(t,r),l.editorContainer.nodeType&&(l.editorContainer=l.editorContainer.id=l.editorContainer.id||t.id+"_parent"),l.iframeContainer.nodeType&&(l.iframeContainer=l.iframeContainer.id=l.iframeContainer.id||t.id+"_iframecontainer"),o=l.iframeHeight||r.offsetHeight),t.editorContainer=l.editorContainer),n.content_css&&R(A(n.content_css),function(e){t.contentCSS.push(t.documentBaseURI.toAbsolute(e))}),n.content_style&&t.contentStyles.push(n.content_style),n.content_editable)return r=s=l=null,t.initContentBody();for(document.domain&&location.hostname!=document.domain&&(t.editorManager.relaxedDomain=document.domain),t.iframeHTML=n.doctype+"",n.document_base_url!=t.documentBaseUrl&&(t.iframeHTML+=''),!b.caretAfter&&n.ie7_compat&&(t.iframeHTML+=''),t.iframeHTML+='',p=0;t.contentCSS.length>p;p++)t.iframeHTML+='';t.contentCSS=[],u=n.body_id||"tinymce",-1!=u.indexOf("=")&&(u=t.getParam("body_id","","hash"),u=u[t.id]||u),d=n.body_class||"",-1!=d.indexOf("=")&&(d=t.getParam("body_class","","hash"),d=d[t.id]||""),t.iframeHTML+='
    ",t.editorManager.relaxedDomain&&(P||O&&11>parseFloat(window.opera.version()))&&(c='javascript:(function(){document.open();document.domain="'+document.domain+'";'+'var ed = window.parent.tinymce.get("'+t.id+'");document.write(ed.iframeHTML);'+"document.close();ed.initContentBody();})()"),s=k.add(l.iframeContainer,"iframe",{id:t.id+"_ifr",src:c||'javascript:""',frameBorder:"0",allowTransparency:"true",title:t.editorManager.translate("Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help"),style:{width:"100%",height:o,display:"block"}}),t.contentAreaContainer=l.iframeContainer,l.editorContainer&&(k.get(l.editorContainer).style.display=t.orgDisplay),k.get(t.id).style.display="none",k.setAttrib(t.id,"aria-hidden",!0),t.editorManager.relaxedDomain&&c||t.initContentBody(),r=s=l=null},initContentBody:function(){var t=this,n=t.settings,o=k.get(t.id),f=t.getDoc(),p,h;t.getElement().style.visibility=t.orgVisibility,P&&t.editorManager.relaxedDomain||n.content_editable||(f.open(),f.write(t.iframeHTML),f.close(),t.editorManager.relaxedDomain&&(f.domain=t.editorManager.relaxedDomain)),n.content_editable&&(k.addClass(o,"mce-content-body"),o.tabIndex=-1,t.contentDocument=f=n.content_document||document,t.contentWindow=n.content_window||window,t.bodyElement=o,n.content_document=n.content_window=null,n.root_name=o.nodeName.toLowerCase()),p=t.getBody(),p.disabled=!0,n.readonly||(p.contentEditable=t.getParam("content_editable_state",!0)),p.disabled=!1,t.schema=new g(n),t.dom=new e(f,{keep_values:!0,url_converter:t.convertURL,url_converter_scope:t,hex_colors:n.force_hex_style_colors,class_filter:n.class_filter,update_styles:!0,root_element:n.content_editable?t.id:null,schema:t.schema,onSetAttrib:function(e){t.fire("SetAttrib",e)}}),t.parser=new v(n,t.schema),t.parser.addAttributeFilter("src,href,style",function(e,n){for(var r=e.length,i,o=t.dom,a,s;r--;)i=e[r],a=i.attr(n),s="data-mce-"+n,i.attributes.map[s]||("style"===n?i.attr(s,o.serializeStyle(o.parseStyle(a),i.name)):i.attr(s,t.convertURL(a,n,i.name)))}),t.parser.addNodeFilter("script",function(e){for(var t=e.length,n;t--;)n=e[t],n.attr("type","mce-"+(n.attr("type")||"text/javascript"))}),t.parser.addNodeFilter("#cdata",function(e){for(var t=e.length,n;t--;)n=e[t],n.type=8,n.name="#comment",n.value="[CDATA["+n.value+"]]"}),t.parser.addNodeFilter("p,h1,h2,h3,h4,h5,h6,div",function(e){for(var n=e.length,i,o=t.schema.getNonEmptyElements();n--;)i=e[n],i.isEmpty(o)&&(i.empty().append(new r("br",1)).shortEnded=!0)}),t.serializer=new i(n,t),t.selection=new a(t.dom,t.getWin(),t.serializer,t),t.formatter=new s(t),t.undoManager=new l(t),t.forceBlocks=new u(t),t.enterKey=new c(t),t.editorCommands=new d(t),t.fire("PreInit"),n.browser_spellcheck||n.gecko_spellcheck||(f.body.spellcheck=!1),t.fire("PostRender"),t.quirks=y(t),n.directionality&&(p.dir=n.directionality),n.nowrap&&(p.style.whiteSpace="nowrap"),n.protect&&t.on("BeforeSetContent",function(e){R(n.protect,function(t){e.content=e.content.replace(t,function(e){return""})})}),t.on("SetContent",function(){t.addVisual(t.getBody())}),n.padd_empty_editor&&t.on("PostProcess",function(e){e.content=e.content.replace(/^(]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
    [\r\n]*)$/,"")}),t.load({initial:!0,format:"html"}),t.startContent=t.getContent({format:"raw"}),t.initialized=!0,R(t._pendingNativeEvents,function(e){t.dom.bind(_(t,e),e,function(e){t.fire(e.type,e)})}),t.fire("init"),t.focus(!0),t.nodeChanged({initial:!0}),t.execCallback("init_instance_callback",t),t.contentStyles.length>0&&(h="",R(t.contentStyles,function(e){h+=e+"\r\n"}),t.dom.addStyle(h)),R(t.contentCSS,function(e){t.dom.loadCSS(e)}),n.auto_focus&&setTimeout(function(){var e=t.editorManager.get(n.auto_focus);e.selection.select(e.getBody(),1),e.selection.collapse(1),e.getBody().focus(),e.getWin().focus()},100),o=f=p=null},focus:function(e){var t,n=this,r=n.selection,i=n.settings.content_editable,o,a,s=n.getDoc(),l;e||((o=r.lastRng)&&(r.lastRng=null,r.setRng(o),n.nodeChanged()),o=r.getRng(),o.item&&(a=o.item(0)),n._refreshContentEditable(),i||n.getWin().focus(),(D||i)&&(l=n.getBody(),l.setActive?l.setActive():l.focus(),i&&r.normalize()),a&&a.ownerDocument==s&&(o=s.body.createControlRange(),o.addElement(a),o.select())),n.editorManager.activeEditor!=n&&((t=n.editorManager.activeEditor)&&t.fire("deactivate",{relatedTarget:n}),n.fire("activate",{relatedTarget:t})),n.editorManager.activeEditor=n},execCallback:function(e){var t=this,n=t.settings[e],r;if(n)return t.callbackLookup&&(r=t.callbackLookup[e])&&(n=r.func,r=r.scope),"string"==typeof n&&(r=n.replace(/\.\w+$/,""),r=r?H(r):0,n=H(n),t.callbackLookup=t.callbackLookup||{},t.callbackLookup[e]={func:n,scope:r}),n.apply(r||t,Array.prototype.slice.call(arguments,1))},translate:function(e){var t=this.settings.language||"en",n=this.editorManager.i18n;return e?n[t+"."+e]||e.replace(/\{\#([^\}]+)\}/g,function(e,r){return n[t+"."+r]||"{#"+r+"}"}):""},getLang:function(e,n){return this.editorManager.i18n[(this.settings.language||"en")+"."+e]||(n!==t?n:"{#"+e+"}")},getParam:function(e,t,n){var r=e in this.settings?this.settings[e]:t,i;return"hash"===n?(i={},"string"==typeof r?R(r.indexOf("=")>0?r.split(/[;,](?![^=;,]*(?:[;,]|$))/):r.split(","),function(e){e=e.split("="),i[L(e[0])]=e.length>1?L(e[1]):L(e)}):i=r,i):r},nodeChanged:function(){var e=this,n=e.selection,r,i,o;e.initialized&&!e.settings.disable_nodechange&&(o=e.getBody(),r=n.getStart()||o,r=P&&r.ownerDocument!=e.getDoc()?e.getBody():r,"IMG"==r.nodeName&&n.isCollapsed()&&(r=r.parentNode),i=[],e.dom.getParent(r,function(e){return e===o?!0:(i.push(e),t)}),e.fire("NodeChange",{element:r,parents:i}))},addButton:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),n.buttons=n.buttons||{},t.tooltip=t.tooltip||t.title,t.icon=t.icon||(t.icon!==!1?e:!1),n.buttons[e]=t},addMenuItem:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),n.menuItems=n.menuItems||{},n.menuItems[e]=t},addCommand:function(e,t,n){this.execCommands[e]={func:t,scope:n||this}},addQueryStateHandler:function(e,t,n){this.queryStateCommands[e]={func:t,scope:n||this}},addQueryValueHandler:function(e,t,n){this.queryValueCommands[e]={func:t,scope:n||this}},addShortcut:function(e,t,n,r){this.shortcuts.add(e,t,n,r)},execCommand:function(e,n,r,i){var o=this,a=0,s;return/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(e)||i&&i.skip_focus||o.focus(),i=T({},i),o.fire("BeforeExecCommand",{command:e,ui:n,value:r}),i.terminate?!1:(s=o.execCommands[e])&&s.func.call(s.scope,n,r)!==!0?(o.fire("ExecCommand",{command:e,ui:n,value:r}),!0):(R(o.plugins,function(i){return i.execCommand&&i.execCommand(e,n,r)?(o.fire("ExecCommand",{command:e,ui:n,value:r}),a=!0,!1):t}),a?a:o.theme&&o.theme.execCommand&&o.theme.execCommand(e,n,r)?(o.fire("ExecCommand",{command:e,ui:n,value:r}),!0):o.editorCommands.execCommand(e,n,r)?(o.fire("ExecCommand",{command:e,ui:n,value:r}),!0):(o.getDoc().execCommand(e,n,r),o.fire("ExecCommand",{command:e,ui:n,value:r}),t))},queryCommandState:function(e){var t=this,n,r;if(!t._isHidden()){if((n=t.queryStateCommands[e])&&(r=n.func.call(n.scope),r!==!0))return r;if(r=t.editorCommands.queryCommandState(e),-1!==r)return r;try{return t.getDoc().queryCommandState(e)}catch(i){}}},queryCommandValue:function(e){var n=this,r,i;if(!n._isHidden()){if((r=n.queryValueCommands[e])&&(i=r.func.call(r.scope),i!==!0))return i;if(i=n.editorCommands.queryCommandValue(e),i!==t)return i;try{return n.getDoc().queryCommandValue(e)}catch(o){}}},show:function(){var e=this;k.show(e.getContainer()),k.hide(e.id),e.load(),e.fire("show")},hide:function(){var e=this,t=e.getDoc();P&&t&&t.execCommand("SelectAll"),e.save(),k.hide(e.getContainer()),k.setStyle(e.id,"display",e.orgDisplay),e.fire("hide")},isHidden:function(){return!k.isHidden(this.id)},setProgressState:function(e,t){this.fire("ProgressState",{state:e,time:t})},load:function(e){var n=this,r=n.getElement(),i;return r?(e=e||{},e.load=!0,i=n.setContent(r.value!==t?r.value:r.innerHTML,e),e.element=r,e.no_events||n.fire("LoadContent",e),e.element=r=null,i):t},save:function(e){var n=this,r=n.getElement(),i,o;if(r&&n.initialized)return e=e||{},e.save=!0,e.element=r,i=e.content=n.getContent(e),e.no_events||n.fire("SaveContent",e),i=e.content,/TEXTAREA|INPUT/i.test(r.nodeName)?r.value=i:(r.innerHTML=i,(o=k.getParent(n.id,"form"))&&R(o.elements,function(e){return e.name==n.id?(e.value=i,!1):t})),e.element=r=null,i},setContent:function(e,n){var r=this,i=r.getBody(),a;return n=n||{},n.format=n.format||"html",n.set=!0,n.content=e,n.no_events||r.fire("BeforeSetContent",n),e=n.content,P||0!==e.length&&!/^\s+$/.test(e)?("raw"!==n.format&&(e=new o({},r.schema).serialize(r.parser.parse(e,{isRootContent:!0}))),n.content=L(e),r.dom.setHTML(i,n.content),n.no_events||r.fire("SetContent",n),r.settings.content_editable&&document.activeElement!==r.getBody()||r.selection.normalize(),n.content):(a=r.settings.forced_root_block,e=a&&r.schema.isValidChild(i.nodeName.toLowerCase(),a.toLowerCase())?"<"+a+'>
    ":'
    ',i.innerHTML=e,r.selection.select(i,!0),r.selection.collapse(!0),t)},getContent:function(e){var t=this,n,r=t.getBody();return e=e||{},e.format=e.format||"html",e.get=!0,e.getInner=!0,e.no_events||t.fire("BeforeGetContent",e),n="raw"==e.format?r.innerHTML:"text"==e.format?r.innerText||r.textContent:t.serializer.serialize(r,e),e.content="text"!=e.format?L(n):n,e.no_events||t.fire("GetContent",e),e.content},insertContent:function(e){this.execCommand("mceInsertContent",!1,e)},isDirty:function(){return!this.isNotDirty&&this.undoManager.hasUndo()},getContainer:function(){var e=this;return e.container||(e.container=k.get(e.editorContainer||e.id+"_parent")),e.container},getContentAreaContainer:function(){return this.contentAreaContainer},getElement:function(){return k.get(this.settings.content_element||this.id)},getWin:function(){var e=this,t;return e.contentWindow||(t=k.get(e.id+"_ifr"),t&&(e.contentWindow=t.contentWindow)),e.contentWindow},getDoc:function(){var e=this,t;return e.contentDocument||(t=e.getWin(),t&&(e.contentDocument=t.document)),e.contentDocument},getBody:function(){return this.bodyElement||this.getDoc().body},convertURL:function(e,t,n){var r=this,i=r.settings;return i.urlconverter_callback?r.execCallback("urlconverter_callback",e,n,!0,t):!i.convert_urls||n&&"LINK"==n.nodeName||0===e.indexOf("file:")||0===e.length?e:i.relative_urls?r.documentBaseURI.toRelative(e):e=r.documentBaseURI.toAbsolute(e,i.remove_script_host)},addVisual:function(e){var n=this,r=n.settings,i=n.dom,o;e=e||n.getBody(),n.hasVisual===t&&(n.hasVisual=r.visual),R(i.select("table,a",e),function(e){var a;switch(e.nodeName){case"TABLE":return o=r.visual_table_class||"mce-item-table",a=i.getAttrib(e,"border"),a&&"0"!=a||(n.hasVisual?i.addClass(e,o):i.removeClass(e,o)),t;case"A":return i.getAttrib(e,"href",!1)||(a=i.getAttrib(e,"name")||e.id,o="mce-item-anchor",a&&(n.hasVisual?i.addClass(e,o):i.removeClass(e,o))),t}}),n.fire("VisualAid",{element:e,hasVisual:n.hasVisual})},remove:function(){var e=this,t=e.getContainer(),n=e.getDoc();e.removed||(e.removed=1,P&&n&&n.execCommand("SelectAll"),e.save(),k.setStyle(e.id,"display",e.orgDisplay),e.settings.content_editable||(M.unbind(e.getWin()),M.unbind(e.getDoc())),M.unbind(e.getBody()),M.unbind(t),e.fire("remove"),e.editorManager.remove(e),k.remove(t))},bindNative:function(e){var t=this;t.initialized?t.dom.bind(_(t,e),e,function(n){t.fire(e,n)}):t._pendingNativeEvents?t._pendingNativeEvents.push(e):t._pendingNativeEvents=[e]},unbindNative:function(e){var t=this;t.initialized&&t.dom.unbind(e)},destroy:function(e){var t=this,n;t.destroyed||(D&&(M.unbind(t.getDoc()),M.unbind(t.getWin()),M.unbind(t.getBody())),e||(t.editorManager.off(t._beforeUnload),t.theme&&t.theme.destroy&&t.theme.destroy(),t.selection.destroy(),t.dom.destroy()),n=t.formElement,n&&(n.submit=n._mceOldSubmit,n._mceOldSubmit=null,k.unbind(n,"submit reset",t.formEventDelegate)),t.contentAreaContainer=t.formElement=t.container=null,t.settings.content_element=t.bodyElement=t.contentDocument=t.contentWindow=null,t.selection&&(t.selection=t.selection.win=t.selection.dom=t.selection.dom.doc=null),t.destroyed=1)},_refreshContentEditable:function(){var e=this,t,n;e._isHidden()&&(t=e.getBody(),n=t.parentNode,n.removeChild(t),n.appendChild(t),t.focus())},_isHidden:function(){var e;return D?(e=this.selection.getSel(),!e||!e.rangeCount||0===e.rangeCount):0}},T(N.prototype,x),N}),r(ot,[it,v,O,g,p,nt],function(e,n,r,i,o,a){var s=n.DOM,l=o.explode,c=o.each,u=o.extend,d=0,f,p={majorVersion:"4",minorVersion:"0b1",releaseDate:"2013-04-11",editors:[],i18n:{},activeEditor:null,setup:function(){var e=this,t,n,i="",o;if(n=document.location.href.replace(/[\?#].*$/,"").replace(/[\/\\][^\/]+$/,""),/[\/\\]$/.test(n)||(n+="/"),o=window.tinymce||window.tinyMCEPreInit)t=o.base||o.baseURL,i=o.suffix;else for(var a=document.getElementsByTagName("script"),s=0;a.length>s;s++){var l=a[s].src;if(/tinymce(\.jquery|)(\.min|\.dev|).js/.test(l)){-1!=l.indexOf(".min")&&(i=".min"),t=l.substring(0,l.lastIndexOf("/"));break}}e.baseURL=new r(n).toAbsolute(t),e.documentBaseURL=n,e.baseURI=new r(e.baseURL),e.suffix=i},init:function(t){function n(e){var t=e.id;return t||(t=e.name,t=t&&!s.get(t)?e.name:s.uniqueId(),e.setAttribute("id",t)),t}function r(e,t,n){var r=e[t];if(r)return r.apply(n||this,Array.prototype.slice.call(arguments,2))}function i(e,t){return t.constructor===RegExp?t.test(e.className):s.hasClass(e,t)}var o=this,a=[],f;o.settings=t,s.bind(window,"ready",function(){var p,h;switch(r(t,"onpageload"),t.mode){case"exact":p=t.elements||"",p.length>0&&c(l(p),function(n){s.get(n)?(f=new e(n,t,o),a.push(f),f.render(!0)):c(document.forms,function(r){c(r.elements,function(r){r.name===n&&(n="mce_editor_"+d++,s.setAttrib(r,"id",n),f=new e(n,t,o),a.push(f),f.render(1))})})});break;case"textareas":case"specific_textareas":c(s.select("textarea"),function(r){t.editor_deselector&&i(r,t.editor_deselector)||(!t.editor_selector||i(r,t.editor_selector))&&(f=new e(n(r),t,o),a.push(f),f.render(!0))});break;default:t.types?c(t.types,function(r){c(s.select(r.selector),function(i){var s=new e(n(i),u({},t,r),o);a.push(s),s.render(1)})}):t.selector&&c(s.select(t.selector),function(r){var i=new e(n(r),t,o);a.push(i),i.render(1)})}t.oninit&&(p=h=0,c(a,function(e){h++,e.initialized?p++:e.on("init",function(){p++,p==h&&r(t,"oninit")}),p==h&&r(t,"oninit")}))})},get:function(e){return e===t?this.editors:this.editors[e]},add:function(e){var t=this,n=t.editors;return n[e.id]=e,n.push(e),t.activeEditor=e,t.fire("AddEditor",{editor:e}),f||(f=function(){t.fire("BeforeUnload")},s.bind(window,"beforeunload",f)),e},createEditor:function(t){return this.add(new e(t))},remove:function(e){var t=this,n,r=t.editors;if(!r[e.id])return null;for(delete r[e.id],n=0;r.length>n;n++)if(r[n]==e){r.splice(n,1);break}return t.activeEditor==e&&(t.activeEditor=r[0]),e.destroy(),t.fire("RemoveEditor",{editor:e}),r.length||s.unbind(window,"beforeunload",f),e},execCommand:function(t,n,r){var i=this,o=i.get(r);switch(t){case"mceAddEditor":return i.get(r)||new e(r,i.settings,i).render(),!0;case"mceRemoveEditor":return o&&o.remove(),!0;case"mceToggleEditor":return o?(o.isHidden()?o.show():o.hide(),!0):(i.execCommand("mceAddEditor",0,r),!0)}return i.activeEditor?i.activeEditor.execCommand(t,n,r):!1},triggerSave:function(){c(this.editors,function(e){e.save()})},addI18n:function(e,t){u(this.i18n,t||e)},translate:function(e){return"string"!=typeof e?(this.i18n[e[0]]||e[0]).replace(/%d/,e[1]):this.i18n[e]||e}};return p.setup(),window.tinymce=window.tinyMCE=p,u(p,a),p}),r(at,[ot,p],function(e,t){var n=t.each,r=t.explode;e.on("AddEditor",function(e){var t=e.editor;t.on("preInit",function(){function e(e,t){n(t,function(t,n){t&&s.setStyle(e,n,t)}),s.rename(e,"span")}function i(e){s=t.dom,l.convert_fonts_to_spans&&n(s.select("font,u,strike",e.node),function(e){o[e.nodeName.toLowerCase()](s,e)})}var o,a,s,l=t.settings;l.inline_styles&&(a=r(l.font_size_legacy_values),o={font:function(t,n){e(n,{backgroundColor:n.style.backgroundColor,color:n.color,fontFamily:n.face,fontSize:a[parseInt(n.size,10)-1]})},u:function(t,n){e(n,{textDecoration:"underline"})},strike:function(t,n){e(n,{textDecoration:"line-through"})}},t.on("PreProcess SetContent",i))})})}),r(st,[],function(){return{send:function(e){function t(){!e.async||4==n.readyState||r++>1e4?(e.success&&1e4>r&&200==n.status?e.success.call(e.success_scope,""+n.responseText,n,e):e.error&&e.error.call(e.error_scope,r>1e4?"TIMED_OUT":"GENERAL",n,e),n=null):setTimeout(t,10)}var n,r=0;if(e.scope=e.scope||this,e.success_scope=e.success_scope||e.scope,e.error_scope=e.error_scope||e.scope,e.async=e.async===!1?!1:!0,e.data=e.data||"",n=new XMLHttpRequest){if(n.overrideMimeType&&n.overrideMimeType(e.content_type),n.open(e.type||(e.data?"POST":"GET"),e.url,e.async),e.content_type&&n.setRequestHeader("Content-Type",e.content_type),n.setRequestHeader("X-Requested-With","XMLHttpRequest"),n.send(e.data),!e.async)return t();setTimeout(t,10)}}}}),r(lt,[],function(){function e(t,n){var r,i,o,a;if(n=n||'"',null===t)return"null";if(o=typeof t,"string"==o)return i="\bb t\nn\ff\rr\"\"''\\\\",n+t.replace(/([\u0080-\uFFFF\x00-\x1f\"\'\\])/g,function(e,t){return'"'===n&&"'"===e?e:(r=i.indexOf(t),r+1?"\\"+i.charAt(r+1):(e=t.charCodeAt().toString(16),"\\u"+"0000".substring(e.length)+e))})+n;if("object"==o){if(t.hasOwnProperty&&"[object Array]"===Object.prototype.toString.call(t)){for(r=0,i="[";t.length>r;r++)i+=(r>0?",":"")+e(t[r],n);return i+"]"}i="{";for(a in t)t.hasOwnProperty(a)&&(i+="function"!=typeof t[a]?(i.length>1?","+n:n)+a+n+":"+e(t[a],n):"");return i+"}"}return""+t}return{serialize:e,parse:function(e){try{return window[String.fromCharCode(101)+"val"]("("+e+")")}catch(t){}}}}),r(ct,[lt,st,p],function(e,n,r){function i(e){this.settings=o({},e),this.count=0}var o=r.extend;return i.sendRPC=function(e){return(new i).send(e)},i.prototype={send:function(r){var i=r.error,a=r.success;r=o(this.settings,r),r.success=function(n,o){n=e.parse(n),n===t&&(n={error:"JSON Parse error."}),n.error?i.call(r.error_scope||r.scope,n.error,o):a.call(r.success_scope||r.scope,n.result)},r.error=function(e,t){i&&i.call(r.error_scope||r.scope,e,t)},r.data=e.serialize({id:r.id||"c"+this.count++,method:r.method,params:r.params}),r.content_type="application/json",n.send(r)}},i}),r(ut,[v],function(e){return{callbacks:{},count:0,send:function(n){var r=this,i=e.DOM,o=n.count!==t?n.count:r.count,a="tinymce_jsonp_"+o;r.callbacks[o]=function(e){i.remove(a),delete r.callbacks[o],n.callback(e)},i.add(i.doc.body,"script",{id:a,src:n.url,type:"text/javascript"}),r.count++}}}),r(dt,[],function(){function e(){s=[];for(var e in a)s.push(e);i.length=s.length}function n(){function n(e){var n,r;return r=e!==t?c+e:i.indexOf(",",c),-1===r||r>i.length?null:(n=i.substring(c,r),c=r+1,n)}var r,i,s,c=0;a={},o.load(l),i=o.getAttribute(l)||"";do r=n(parseInt(n(),32)||0),null!==r&&(s=n(parseInt(n(),32)||0),a[r]=s);while(null!==r);e()}function r(){var t,n="";for(var r in a)t=a[r],n+=(n?",":"")+r.length.toString(32)+","+r+","+t.length.toString(32)+","+t;o.setAttribute(l,n),o.save(l),e()}var i,o,a,s,l;return window.localStorage?localStorage:(l="tinymce",o=document.documentElement,o.addBehavior("#default#userData"),i={key:function(e){return s[e] +},getItem:function(e){return e in a?a[e]:null},setItem:function(e,t){a[e]=""+t,r()},removeItem:function(e){delete a[e],r()},clear:function(){a={},r()}},n(),i)}),r(ft,[v,l,y,b,p,g],function(e,t,n,r,i,o){var a=window.tinymce;return a.DOM=e.DOM,a.ScriptLoader=n.ScriptLoader,a.PluginManager=r.PluginManager,a.ThemeManager=r.ThemeManager,a.dom=a.dom||{},a.dom.Event=t.Event,i.each(i,function(e,t){a[t]=e}),i.each("isOpera isWebKit isIE isGecko isMac".split(" "),function(e){a[e]=o[e.substr(2).toLowerCase()]}),{}}),r(pt,[I,p],function(e,t){return e.extend({Defaults:{firstControlClass:"first",lastControlClass:"last"},init:function(e){this.settings=t.extend({},this.Defaults,e)},preRender:function(e){e.addClass(this.settings.containerClass,"body")},applyClasses:function(e){var t=this,n=t.settings,r,i,o;r=e.items().filter(":visible"),i=n.firstControlClass,o=n.lastControlClass,r.each(function(e){e.removeClass(i).removeClass(o),n.controlClass&&e.addClass(n.controlClass)}),r.eq(0).addClass(i),r.eq(-1).addClass(o)},renderHtml:function(e){var t=this,n=t.settings,r,i="";return r=e.items(),r.eq(0).addClass(n.firstControlClass),r.eq(-1).addClass(n.lastControlClass),r.each(function(e){n.controlClass&&e.addClass(n.controlClass),i+=e.renderHtml()}),i},recalc:function(){},postRender:function(){}})}),r(ht,[pt],function(e){return e.extend({Defaults:{containerClass:"abs-layout",controlClass:"abs-layout-item"},recalc:function(e){e.items().filter(":visible").each(function(e){var t=e.settings;e.layoutRect({x:t.x,y:t.y,w:t.w,h:t.h}),e.recalc&&e.recalc()})},renderHtml:function(e){return'
    '+this._super(e)}})}),r(mt,[V,K],function(e,n){return e.extend({Mixins:[n],Defaults:{classes:"widget tooltip tooltip-n"},text:function(e){var n=this;return e!==t?(n._value=e,n._rendered&&(n.getEl().lastChild.innerHTML=n.encode(e)),n):n._value},renderHtml:function(){var e=this,t=e.classPrefix;return'"},repaint:function(){var e=this,t,n;t=e.getEl().style,n=e._layoutRect,t.left=n.x+"px",t.top=n.y+"px",t.zIndex=131070}})}),r(gt,[V,mt],function(e,t){var n;return e.extend({init:function(e){var t=this;t._super(e),t.canFocus=!0,e.tooltip&&t.on("mouseenter mouseleave",function(n){n.control==t&&"mouseenter"==n.type?t.tooltip().moveTo(-65535).text(e.tooltip).show().moveRel(t.getEl(),"bc tc"):t.tooltip().moveTo(-65535).hide()}),t.aria("label",e.tooltip)},tooltip:function(){var e=this;return n||(n=new t({type:"tooltip"}),n.renderTo(e.getContainerElm())),n},active:function(e){var t=this,n;return e!==n&&(t.aria("pressed",e),t.toggleClass("active",e)),t._super(e)},disabled:function(e){var t=this,n;return e!==n&&(t.aria("disabled",e),t.toggleClass("disabled",e)),t._super(e)},postRender:function(){var e=this,t=e.settings;e._rendered=!0,e._super(),e.parent()||!t.width&&!t.height||(e.initLayoutRect(),e.repaint()),t.autofocus&&e.focus()},remove:function(){this._super(),n&&(n.remove(),n=null)}})}),r(vt,[gt],function(e){return e.extend({Defaults:{classes:"widget btn",role:"button"},init:function(e){var t=this,n;t.on("click mousedown",function(e){e.preventDefault()}),t._super(e),n=e.size,e.subtype&&t.addClass(e.subtype),n&&t.addClass("btn-"+n)},repaint:function(){var e=this.getEl().firstChild.style;e.width=e.height="100%",this._super()},renderHtml:function(){var e=this,t=e._id,n=e.classPrefix,r=e.settings.icon?n+"ico "+n+"i-"+e.settings.icon:"",i=e.settings.image?" style=\"background-image: url('"+e.settings.image+"')\"":"";return'
    '+'"+"
    "}})}),r(yt,[q],function(e){return e.extend({Defaults:{defaultType:"button",role:"toolbar"},renderHtml:function(){var e=this,t=e._layout;return e.addClass("btn-group"),e.preRender(),t.preRender(e),'
    '+'
    '+(e.settings.html||"")+t.renderHtml(e)+"
    "+"
    "}})}),r(bt,[gt],function(e){return e.extend({Defaults:{classes:"checkbox",role:"checkbox",checked:!1},init:function(e){var t=this;t._super(e),t.on("click mousedown",function(e){e.preventDefault()}),t.on("click",function(e){e.preventDefault(),t.disabled()||t.checked(!t.checked())}),t.checked(t.settings.checked)},checked:function(e){var n=this;return e!==t?(e?n.addClass("checked"):n.removeClass("checked"),n._checked=e,n.aria("checked",e),n):n._checked},value:function(e){return this.checked(e)},renderHtml:function(){var e=this,t=e._id,n=e.classPrefix;return'
    '+''+''+e._text+""+"
    "}})}),r(Ct,[q],function(e){return e.extend({})}),r(xt,[vt,Y,J],function(e,t,n){function r(){var e,t=[],n;for(n=["000000","Black","993300","Burnt orange","333300","Dark olive","003300","Dark green","003366","Dark azure","000080","Navy Blue","333399","Indigo","333333","Very dark gray","800000","Maroon","FF6600","Orange","808000","Olive","008000","Green","008080","Teal","0000FF","Blue","666699","Grayish blue","808080","Gray","FF0000","Red","FF9900","Amber","99CC00","Yellow green","339966","Sea green","33CCCC","Turquoise","3366FF","Royal blue","800080","Purple","999999","Medium gray","FF00FF","Magenta","FFCC00","Gold","FFFF00","Yellow","00FF00","Lime","00FFFF","Aqua","00CCFF","Sky blue","993366","Brown","C0C0C0","Silver","FF99CC","Pink","FFCC99","Peach","FFFF99","Light yellow","CCFFCC","Pale green","CCFFFF","Pale cyan","99CCFF","Light sky blue","CC99FF","Plum","FFFFFF","White"],e=0;n.length>e;e+=2)t.push({text:n[e+1],color:n[e]});return t}return e.extend({init:function(e){var t=this;t._super(e),t.addClass("colorbutton"),t.on("click",function(e){e.control==t&&t.showPicker()}),t.hasPopup=!0},showPicker:function(){var e=this,i="",o,a,s,l=e.classPrefix,c;if(!e.picker){for(c=r(),i='',o=Math.ceil(Math.sqrt(c.length)),s=0;5>s;s++){for(i+="",a=0;8>a;a++){var u=c[8*s+a];i+='"}i+=""}i+="",e.picker=new t({popover:!0,autohide:!0,html:i,border:1,classes:"colorpicker"}).parent(e).renderTo(e.getContainerElm()),e.picker._hasBody=!1,e.picker.reflow(),e.picker.parent(e),e.picker.on("cancel",function(t){t.control===e.menu&&e.focus()}),e.picker.on("click",function(t){var n;(n=t.target.getAttribute("data-mce-color"))&&(e.picker.hide(),n="#"+n,e.showPreview(n),e.fire("select",{value:n}))}),e.keyboardNavigation=new n({root:e.picker,items:e.picker.getEl().getElementsByTagName("div"),onCancel:function(){e.picker.hide(),e.fire("cancel")}})}e.picker.show(),e.picker.moveRel(e.getEl(),"bc-tl"),e.keyboardNavigation.focusFirst()},showPreview:function(e){this.getEl("preview").style.backgroundColor=e},renderHtml:function(){var e=this,t=e._id,n=e.classPrefix,r=e.settings.icon?n+"ico "+n+"i-"+e.settings.icon:"",i=e.settings.image?" style=\"background-image: url('"+e.settings.image+"')\"":"";return'
    '+'"+"
    "}})}),r(wt,[gt,z],function(e,n){return e.extend({init:function(e){var r=this;r._super(e),r.addClass("combobox"),r.on("click",function(e){for(var t=e.target;t;)t.id&&-1!=t.id.indexOf("-open")&&r.fire("action"),t=t.parentNode}),r.on("keydown",function(e){"INPUT"==e.target.nodeName&&13==e.keyCode&&r.parents().reverse().each(function(n){return e.preventDefault(),r.fire("change"),n.submit?(n.submit(),!1):t})}),e.placeholder&&(r.addClass("placeholder"),r.on("focusin",function(){r._hasOnChange||(n.on(r.getEl("inp"),"change",function(){r.fire("change")}),r._hasOnChange=!0),r.hasClass("placeholder")&&(r.getEl("inp").value="",r.removeClass("placeholder"))}),r.on("focusout",function(){0===r.value().length&&(r.getEl("inp").value=e.placeholder,r.addClass("placeholder"))}))},value:function(e){var n=this;return e!==t?(n._value=e,n.removeClass("placeholder"),n._rendered&&(n.getEl("inp").value=e),n):n._rendered?(e=n.getEl("inp").value,e!=n.settings.placeholder?e:""):n._value},repaint:function(){var e=this,t=e.getEl(),r=e.getEl("open"),i=e.layoutRect();return r?n.css(t.firstChild,{width:i.w-r.offsetWidth-10}):n.css(t.firstChild,{width:i.w-10}),e._super(),e},disabled:function(e){var t=this;t._super(e),t._rendered&&(t.getEl().disabled=e)},focus:function(){this.getEl("inp").focus()},postRender:function(){var e=this;return n.on(this.getEl("inp"),"change",function(){e.fire("change")}),e._super()},renderHtml:function(){var e=this,t=e._id,n=e.settings,r=e.classPrefix,i=n.value||n.placeholder||"",o,a,s="";return o=n.icon?r+"ico "+r+"i-"+n.icon:"",a=e._text,(o||a)&&(s='
    '+'"+"
    ",e.addClass("has-open")),'
    '+''+s+"
    "}})}),r(_t,[V,J],function(e,n){return e.extend({Defaults:{delimiter:"\u00bb"},init:function(e){var t=this;t._super(e),t.addClass("path"),t.canFocus=!0,t.on("click",function(e){var n,r=e.target;(n=r.getAttribute("data-index"))&&t.fire("select",{value:t.data()[n],index:n})})},focus:function(){var e=this;return e.keyNav=new n({root:e,enableLeftRight:!0}),e.keyNav.focusFirst(),e},data:function(e){var n=this;return e!==t?(n._data=e,n.update(),n):n._data},update:function(){var e=this,t=e._data,n,r,i="",o=e.classPrefix;for(n=0,r=t.length;r>n;n++)i+=(n>0?'":"")+'
    '+t[n].name+"
    ";e.getEl().innerHTML=i},postRender:function(){var e=this;e._super(),e.data(e.settings.data)},repa2int:function(){var e=this;return e.getEl("text").style.lineHeight=e.layoutRect().h+"px",e._super()},renderHtml:function(){var e=this,t=e.classPrefix;return'
    '+'
     
    '+"
    "}})}),r(Nt,[_t,ot],function(e,t){return e.extend({postRender:function(){function e(e){return 1===e.nodeType&&("BR"==e.nodeName||!!e.getAttribute("data-mce-bogus"))}var n=this,r=t.activeEditor;return n.on("select",function(t){for(var n=[],i=r.selection.getNode(),o=r.getBody();i&&(e(i)||n.push(i),i=i.parentNode,i!=o););r.focus(),r.selection.select(n[n.length-1-t.index]),r.nodeChanged()}),r.on("nodeChange",function(t){for(var i=[],o=t.parents,a=o.length;a--;)if(!e(o[a])){var s=r.fire("ResolveName",{name:o[a].nodeName.toLowerCase(),target:o[a]});i.push({name:s.name})}n.data(i)}),n._super()}})}),r(kt,[q],function(e){return e.extend({Defaults:{layout:"flex",align:"center",defaults:{flex:1}},renderHtml:function(){var e=this,t=e._layout,n=e.classPrefix;return e.addClass("formitem"),t.preRender(e),'
    '+(e.settings.title?'
    '+e.settings.title+"
    ":"")+'
    '+(e.settings.html||"")+t.renderHtml(e)+"
    "+"
    "}})}),r(Et,[q,kt],function(e,n){return e.extend({Defaults:{containerCls:"form",layout:"flex",direction:"column",align:"stretch",flex:1,padding:20,labelGap:30,spacing:10},preRender:function(){var e=this,r=e.items();r.each(function(r){var i,o=r.settings.label;o&&(i=new n({layout:"flex",autoResize:"overflow",defaults:{flex:1},items:[{type:"label",text:o,flex:0,forId:r._id}]}),i.type="formitem",r.settings.flex===t&&(r.settings.flex=1),e.replace(r,i),i.add(r))})},recalcLabels:function(){var e=this,t=0,n=[],r,i;if(e.settings.labelGapCalc!==!1)for(e.items().filter("formitem").each(function(e){var r=e.items()[0],i=r.getEl().clientWidth;t=i>t?i:t,n.push(r)}),i=e.settings.labelGap||0,r=n.length;r--;)n[r].settings.minWidth=t+i},visible:function(e){var t=this._super(e);return e===!0&&this._rendered&&this.recalcLabels(),t},fromJSON:function(e){var t=this;if(e)for(var n in e)t.find("#"+n).value(e[n]);return t},toJSON:function(){var e=this,n={};return e.find("*").each(function(e){var r=e.name(),i=e.value();r&&i!==t&&(n[r]=i)}),n},submit:function(){return this.fire("submit",{data:this.toJSON()})},postRender:function(){var e=this;e._super(),e.recalcLabels(),e.fromJSON(e.settings.data)}})}),r(St,[Et],function(e){return e.extend({Defaults:{containerCls:"fieldset",layout:"flex",direction:"column",align:"stretch",flex:1,padding:"25 15 5 15",labelGap:30,spacing:10,border:1},renderHtml:function(){var e=this,t=e._layout,n=e.classPrefix;return e.preRender(),t.preRender(e),'
    '+(e.settings.title?''+e.settings.title+"":"")+'
    '+(e.settings.html||"")+t.renderHtml(e)+"
    "+"
    "}})}),r(Tt,[wt],function(e){return e.extend({init:function(e){var t=this,n=tinymce.activeEditor,r;e.spellcheck=!1,r=n.settings.file_browser_callback,r&&(e.icon="browse",e.onaction=function(){r(t.getEl("inp").id,t.getEl("inp").value,e.filetype,window)}),t._super(e)}})}),r(Rt,[ht],function(e){return e.extend({recalc:function(e){var t=e.layoutRect(),n=e.paddingBox();e.items().filter(":visible").each(function(e){e.layoutRect({x:n.left,y:n.top,w:t.innerW-n.right-n.left,h:t.innerH-n.top-n.bottom}),e.recalc&&e.recalc()})}})}),r(At,[ht],function(e){return e.extend({recalc:function(e){var t,n,r,i,o,a,s,l,c,u,d,f,p,h,m,g,v=[],y,b,C,x,w,_,N,k,E,S,T,R,A,B,L,H,M,D,P,O,I,F,W,z,V=Math.max,U=Math.min;for(r=e.items().filter(":visible"),i=e.layoutRect(),o=e._paddingBox,a=e.settings,f=a.direction,s=a.align,l=a.pack,c=a.spacing||0,("row-reversed"==f||"column-reverse"==f)&&(r=r.set(r.toArray().reverse()),f=f.split("-")[0]),"column"==f?(E="y",N="h",k="minH",S="maxH",R="innerH",T="top",A="bottom",B="deltaH",L="contentH",I="left",D="w",H="x",M="innerW",P="minW",O="maxW",F="right",W="deltaW",z="contentW"):(E="x",N="w",k="minW",S="maxW",R="innerW",T="left",A="right",B="deltaW",L="contentW",I="top",D="h",H="y",M="innerH",P="minH",O="maxH",F="bottom",W="deltaH",z="contentH"),d=i[R]-o[T]-o[T],_=u=0,t=0,n=r.length;n>t;t++)p=r[t],h=p.layoutRect(),m=p.settings,g=m.flex,d-=n-1>t?c:0,g>0&&(u+=g,h[S]&&v.push(p),h.flex=g),d-=h[k],y=o[I]+h[P]+o[F],y>_&&(_=y);if(x={},x[k]=0>d?i[k]-d+i[B]:i[R]-d+i[B],x[P]=_+i[W],x[L]=i[R]-d,x[z]=_,x.minW=U(x.minW,i.maxW),x.minH=U(x.minH,i.maxH),x.minW=V(x.minW,i.startMinWidth),x.minH=V(x.minH,i.startMinHeight),!i.autoResize||x.minW==i.minW&&x.minH==i.minH){for(C=d/u,t=0,n=v.length;n>t;t++)p=v[t],h=p.layoutRect(),b=h[S],y=h[k]+Math.ceil(h.flex*C),y>b?(d-=h[S]-h[k],u-=h.flex,h.flex=0,h.maxFlexSize=b):h.maxFlexSize=0;for(C=d/u,w=o[T],x={},0===u&&("end"==l?w=d+o[T]:"center"==l?(w=Math.round(i[R]/2-(i[R]-d)/2)+o[T],0>w&&(w=o[T])):"justify"==l&&(w=o[T],c=Math.floor(d/(r.length-1)))),x[H]=o[I],t=0,n=r.length;n>t;t++)p=r[t],h=p.layoutRect(),y=h.maxFlexSize||h[k],"center"===s?x[H]=Math.round(i[M]/2-h[D]/2):"stretch"===s?(x[D]=V(h[P]||0,i[M]-o[I]-o[F]),x[H]=o[I]):"end"===s&&(x[H]=i[M]-h[D]-o.top),h.flex>0&&(y+=Math.ceil(h.flex*C)),x[N]=y,x[E]=w,p.layoutRect(x),p.recalc&&p.recalc(),w+=y+c}else if(x.w=x.minW,x.h=x.minH,e.layoutRect(x),this.recalc(e),null===e._lastRect){var q=e.parent();q&&(q._lastRect=null,q.recalc())}}})}),r(Bt,[pt],function(e){return e.extend({Defaults:{containerClass:"flow-layout",controlClass:"flow-layout-item",endClass:"break"},recalc:function(e){e.items().filter(":visible").each(function(e){e.recalc&&e.recalc()})}})}),r(Lt,[U,V,Y,p,ot],function(e,n,r,i,o){function a(e,n){function r(e){return e.replace(/%(\w+)/g,"")}var i,o,a=e.dom,s="",c,u;return u=e.settings.preview_styles,u===!1?"":(u||(u="font-family font-size font-weight text-decoration text-transform color background-color border border-radius"),(n=e.formatter.get(n))?(n=n[0],i=n.block||n.inline||"span",o=a.create(i),l(n.styles,function(e,t){e=r(e),e&&a.setStyle(o,t,e)}),l(n.attributes,function(e,t){e=r(e),e&&a.setAttrib(o,t,e)}),l(n.classes,function(e){e=r(e),a.hasClass(o,e)||a.addClass(o,e)}),e.fire("PreviewFormats"),a.setStyles(o,{position:"absolute",left:-65535}),e.getBody().appendChild(o),c=a.getStyle(e.getBody(),"fontSize",!0),c=/px$/.test(c)?parseInt(c,10):0,l(u.split(" "),function(t){var n=a.getStyle(o,t,!0);if(!("background-color"==t&&/transparent|rgba\s*\([^)]+,\s*0\)/.test(n)&&(n=a.getStyle(e.getBody(),t,!0),"#ffffff"==a.toHex(n).toLowerCase())||"color"==t&&"#000000"==a.toHex(n).toLowerCase())){if("font-size"==t&&/em|%$/.test(n)){if(0===c)return;n=parseFloat(n,10)/(/%$/.test(n)?100:1),n=n*c+"px"}"border"==t&&n&&(s+="padding:0 2px;"),s+=t+":"+n+";"}}),e.fire("AfterPreviewFormats"),a.remove(o),s):t)}function s(e){e=e.split(";");for(var t=e.length;t--;)e[t]=e[t].split("=");return e}var l=i.each;n.translate=function(e){return o.translate(e)},o.on("AddEditor",function(t){function n(){function e(r){var i=[];if(r)return l(r,function(r){var o={text:r.title,icon:r.icon};if(r.items)o.menu=e(r.items);else{var s=r.format||"custom"+t++;r.format||(r.name=s,n.push(r)),o.textStyle=function(){return a(m,s)},o.onclick=function(){m.execCommand("mceToggleFormat",!1,s)}}i.push(o)}),i}var t=0,n=[],r=[{title:"Headers",items:[{title:"Header 1",format:"h1"},{title:"Header 2",format:"h2"},{title:"Header 3",format:"h3"},{title:"Header 4",format:"h4"},{title:"Header 5",format:"h5"},{title:"Header 6",format:"h6"}]},{title:"Inline",items:[{title:"Bold",icon:"bold",format:"bold"},{title:"Italic",icon:"italic",format:"italic"},{title:"Underline",icon:"underline",format:"underline"},{title:"Strikethrough",icon:"strikethrough",format:"strikethrough"},{title:"Superscript",icon:"superscript",format:"superscript"},{title:"Subscript",icon:"subscript",format:"subscript"},{title:"Code",icon:"code",format:"code"}]},{title:"Blocks",items:[{title:"Paragraph",format:"p"},{title:"Blockquote",format:"blockquote"},{title:"Div",format:"div"},{title:"Pre",format:"pre"}]},{title:"Alignment",items:[{title:"Left",icon:"alignleft",format:"alignleft"},{title:"Center",icon:"aligncenter",format:"aligncenter"},{title:"Right",icon:"alignright",format:"alignright"},{title:"Justify",icon:"alignjustify",format:"alignjustify"}]}];m.on("init",function(){l(n,function(e){m.formatter.register(e.name,e)})});var i=e(m.settings.style_formats||r);return i}function c(){return m.undoManager?m.undoManager.hasUndo():!1}function u(){return m.undoManager?m.undoManager.hasRedo():!1}function d(){var e=this;e.disabled(!c()),m.on("Undo Redo AddUndo",function(){e.disabled(!c())})}function f(){var e=this;e.disabled(!u()),m.on("Undo Redo AddUndo",function(){e.disabled(!u())})}function p(){var e=this;m.on("VisualAid",function(t){e.active(t.hasVisual)}),e.active(m.hasVisual)}function h(e){e.control.settings.format&&o.activeEditor.execCommand("mceToggleFormat",!1,e.control.settings.format)}var m=t.editor,g;g=n(),l({bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",subscript:"Subscript",superscript:"Superscript"},function(e,t){m.addButton(t,{tooltip:e,onPostRender:function(){var e=this;m.formatter?m.formatter.formatChanged(t,function(t){e.active(t)}):m.on("init",function(){m.formatter.formatChanged(t,function(t){e.active(t)})})},onclick:function(){m.execCommand("mceToggleFormat",!1,t)}})}),l({outdent:["Decrease indent","Outdent"],indent:["Increase indent","Indent"],cut:["Cut","Cut"],copy:["Copy","Copy"],paste:["Paste","Paste"],help:["Help","mceHelp"],selectall:["Select all","SelectAll"],hr:["Insert horizontal rule","InsertHorizontalRule"],removeformat:["Clear formatting","RemoveFormat"],visualaid:["Visual aids","mceToggleVisualAid"],newdocument:["New document","mceNewDocument"]},function(e,t){m.addButton(t,{tooltip:e[0],cmd:e[1]})}),l({blockquote:["Toggle blockquote","mceBlockQuote"],numlist:["Numbered list","InsertOrderedList"],bullist:["Bulleted list","InsertUnorderedList"],subscript:["Subscript","Subscript"],superscript:["Superscript","Superscript"],alignleft:["Align left","JustifyLeft"],aligncenter:["Align center","JustifyCenter"],alignright:["Align right","JustifyRight"],alignjustify:["Justify","JustifyFull"]},function(e,t){m.addButton(t,{tooltip:e[0],cmd:e[1],onPostRender:function(){var e=this;m.formatter?m.formatter.formatChanged(t,function(t){e.active(t)}):m.on("init",function(){m.formatter.formatChanged(t,function(t){e.active(t)})})}})}),m.addButton("forecolor",{type:"colorbutton",tooltip:"Text color",onselect:function(e){m.execCommand("ForeColor",!1,e.value)}}),m.addButton("backcolor",{type:"colorbutton",tooltip:"Background color",onselect:function(e){m.execCommand("HiliteColor",!1,e.value)}}),m.addButton("undo",{tooltip:"Undo",onPostRender:d,cmd:"undo"}),m.addButton("redo",{tooltip:"Redo",onPostRender:f,cmd:"redo"}),m.addMenuItem("newdocument",{text:"New document",shortcut:"Ctrl+N",icon:"newdocument",cmd:"mceNewDocument"}),m.addMenuItem("undo",{text:"Undo",icon:"undo",shortcut:"Ctrl+Z",onPostRender:d,cmd:"undo"}),m.addMenuItem("redo",{text:"Redo",icon:"redo",shortcut:"Ctrl+Y",onPostRender:f,cmd:"redo"}),m.addMenuItem("visualaid",{text:"Visual aids",selectable:!0,onPostRender:p,cmd:"mceToggleVisualAid"}),l({cut:["Cut","Cut","Ctrl+X"],copy:["Copy","Copy","Ctrl+C"],paste:["Paste","Paste","Ctrl+V"],selectall:["Select all","SelectAll","Ctrl+A"],bold:["Bold","Bold","Ctrl+B"],italic:["Italic","Italic","Ctrl+I"],underline:["Underline","Underline"],strikethrough:["Strikethrough","Strikethrough"],subscript:["Subscript","Subscript"],superscript:["Superscript","Superscript"],removeformat:["Clear formatting","RemoveFormat"]},function(e,t){m.addMenuItem(t,{text:e[0],icon:t,shortcut:e[2],cmd:e[1]})}),m.on("mousedown",function(){r.hideAll()}),e.add("styleselect",function(t){var n=[].concat(g);return e.create("menubutton",i.extend({text:"Formats",menu:n},t))}),e.add("formatselect",function(t){var n=[],r=s("Paragraph=p;Address=address;Pre=pre;Header 1=h1;Header 2=h2;Header 3=h3;Header 4=h4;Header 5=h5;Header 6=h6");return l(r,function(e){n.push({text:e[0],format:e[1],textStyle:function(){return a(m,e[1])}})}),e.create("listbox",i.extend({text:r[0][0],menu:n,onclick:h},t))}),e.add("fontselect",function(t){var n=[],r=s("Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats");return l(r,function(e){n.push({text:e[0],format:e[1],style:-1==e[1].indexOf("dings")?"font-family:"+e[1]:""})}),e.create("listbox",i.extend({text:"Font Family",menu:n,onclick:function(e){e.control.settings.format&&o.activeEditor.execCommand("FontName",!1,e.control.settings.format)}},t))}),e.add("fontsizeselect",function(t){var n=[];return l("8pt 10pt 12pt 14pt 18pt 24pt 36pt".split(" "),function(e){n.push({text:e,format:e})}),e.create("listbox",i.extend({text:"Font Sizes",menu:n,onclick:function(e){e.control.settings.format&&o.activeEditor.execCommand("FontSize",!1,e.control.settings.format)}},t))}),m.addMenuItem("formats",{text:"Formats",menu:g})})}),r(Ht,[ht],function(e){return e.extend({recalc:function(e){var t=e.settings,n,r,i,o,a,s,l,c,u,d,f,p,h,m,g,v,y,b,C,x,w,_,N=[],k=[],E,S,T,R,A,B;for(t=e.settings,i=e.items().filter(":visible"),o=e.layoutRect(),r=t.columns||Math.ceil(Math.sqrt(i.length)),n=Math.ceil(i.length/r),y=t.spacingH||t.spacing||0,b=t.spacingV||t.spacing||0,C=t.alignH||t.align,x=t.alignV||t.align,g=e._paddingBox,d=0;r>d;d++)N.push(0);for(f=0;n>f;f++)k.push(0);for(f=0;n>f;f++)for(d=0;r>d&&(u=i[f*r+d],u);d++)c=u.layoutRect(),E=c.minW,S=c.minH,N[d]=E>N[d]?E:N[d],k[f]=S>k[f]?S:k[f];for(A=o.innerW-g.left-g.right,w=0,d=0;r>d;d++)w+=N[d]+(d>0?y:0),A-=(d>0?y:0)+N[d];for(B=o.innerH-g.top-g.bottom,_=0,f=0;n>f;f++)_+=k[f]+(f>0?b:0),B-=(f>0?b:0)+k[f];if(w+=g.left+g.right,_+=g.top+g.bottom,l={},l.minW=w+(o.w-o.innerW),l.minH=_+(o.h-o.innerH),l.contentW=l.minW-o.deltaW,l.contentH=l.minH-o.deltaH,l.minW=Math.min(l.minW,o.maxW),l.minH=Math.min(l.minH,o.maxH),l.minW=Math.max(l.minW,o.startMinWidth),l.minH=Math.max(l.minH,o.startMinHeight),!o.autoResize||l.minW==o.minW&&l.minH==o.minH){o.autoResize&&(l=e.layoutRect(l),l.contentW=l.minW-o.deltaW,l.contentH=l.minH-o.deltaH);var L;L="start"==t.packV?0:B>0?Math.floor(B/n):0;var H=0,M=t.flexWidths;if(M)for(d=0;M.length>d;d++)H+=M[d];else H=r;var D=A/H;for(d=0;r>d;d++)N[d]+=M?Math.ceil(M[d]*D):D;for(h=g.top,f=0;n>f;f++){for(p=g.left,s=k[f]+L,d=0;r>d&&(u=i[f*r+d],u);d++)m=u.settings,c=u.layoutRect(),a=N[d],T=R=0,c.x=p,c.y=h,v=m.alignH||C,"center"==v?c.x=p+a/2-c.w/2:"right"==v?c.x=p+a-c.w:"stretch"==v&&(c.w=a),v=m.alignV||x,"center"==v?c.y=h+s/2-c.h/2:"bottom"==v?c.y=h+s-c.h:"stretch"==v&&(c.h=s),u.layoutRect(c),p+=a+y,u.recalc&&u.recalc();h+=s+b}}else if(l.w=l.minW,l.h=l.minH,e.layoutRect(l),this.recalc(e),null===e._lastRect){var P=e.parent();P&&(P._lastRect=null,P.recalc())}}})}),r(Mt,[gt],function(e){return e.extend({renderHtml:function(){var e=this;return e.addClass("iframe"),e.canFocus=!1,''},src:function(e){this.getEl().src=e},html:function(e){return this.getEl().contentWindow.document.body.innerHTML=e,this}})}),r(Dt,[gt],function(e){return e.extend({init:function(e){var t=this;t._super(e),t.addClass("widget"),t.addClass("label"),e.multiline&&t.addClass("autoscroll"),e.strong&&t.addClass("strong")},initLayoutRect:function(){var e=this,t=e._super();return e.settings.multiline&&(e.getEl().offsetWidth>t.maxW&&(t.minW=t.maxW,e.addClass("multiline")),e.getEl().style.width=t.minW+"px",t.startMinH=t.h=t.minH=Math.min(t.maxH,e.getEl().offsetHeight)),t},disabled:function(e){var t=this,n;return e!==n&&(t.toggleClass("label-disabled",e),t._rendered&&(t.getEl()[0].className=t.classes())),t._super(e)},repaint:function(){var e=this;return e.settings.multiline||(e.getEl().style.lineHeight=e.layoutRect().h+"px"),e._super()},text:function(e){var t=this;return t._rendered&&e&&(t.getEl().innerHTML=t.encode(e)),t._super(e)},renderHtml:function(){var e=this,t=e.settings.forId;return'"}})}),r(Pt,[q,J],function(e,t){return e.extend({Defaults:{role:"toolbar",layout:"flow"},init:function(e){var t=this;t._super(e),t.addClass("toolbar")},postRender:function(){var e=this;return e.items().addClass("toolbar-item"),e.keyNav=new t({root:e,enableLeftRight:!0}),e._super()}})}),r(Ot,[Pt],function(e){return e.extend({Defaults:{role:"menubar",containerCls:"menubar",defaults:{type:"menubutton"}}})}),r(It,[vt,U,Ot],function(e,t,n){function r(e,t){for(;e;){if(t===e)return!0;e=e.parentNode}return!1}var i=e.extend({init:function(e){var t=this;t._renderOpen=!0,t._super(e),t.addClass("menubtn"),t.aria("haspopup",!0),t.hasPopup=!0},showMenu:function(){var e=this,n=e.settings,r;e.menu||(r=n.menu||[],r.length?r={type:"menu",items:r}:r.type=r.type||"menu",e.menu=t.create(r).parent(e).renderTo(e.getContainerElm()),e.fire("createmenu"),e.menu.reflow(),e.menu.on("cancel",function(t){t.control===e.menu&&e.focus()}),e.menu.on("show hide",function(t){t.control==e.menu&&e.activeMenu("show"==t.type)}).fire("show"),e.aria("expanded",!0)),e.menu.show(),e.menu.layoutRect({w:e.layoutRect().w}),e.menu.moveRel(e.getEl(),"bl-tl")},hideMenu:function(){var e=this;e.menu&&(e.menu.items().each(function(e){e.hideMenu&&e.hideMenu()}),e.menu.hide(),e.aria("expanded",!1))},activeMenu:function(e){this.toggleClass("active",e)},renderHtml:function(){var e=this,t=e._id,r=e.classPrefix,i=e.settings.icon?r+"ico "+r+"i-"+e.settings.icon:"";return e.aria("role",e.parent()instanceof n?"menuitem":"button"),'
    '+'"+"
    "},postRender:function(){var e=this;return e.on("click",function(t){t.control===e&&r(t.target,e.getEl())&&(e.showMenu(),t.keyboard&&e.menu.items()[0].focus())}),e.on("mouseenter",function(t){var n=t.control,r=e.parent(),o;n&&r&&n instanceof i&&n.parent()==r&&(r.items().filter("MenuButton").each(function(e){e.hideMenu&&e!=n&&(e.menu&&e.menu.visible()&&(o=!0),e.hideMenu())}),o&&n.showMenu())}),e._super()},text:function(e){var t=this,n,r;if(t._rendered)for(r=t.getEl("open").childNodes,n=0;r.length>n;n++)3==r[n].nodeType&&(r[n].data=e);return this._super(e)},remove:function(){this._super(),this.menu&&this.menu.remove()}});return i}),r(Ft,[It],function(e){return e.extend({init:function(e){var t=this,n,r,i,o;if(t._values=n=e.values,n){for(r=0;n.length>r;r++)i=n[r].selected||e.value===n[r].value,i&&(o=o||n[r].text,t._value=n[r].value);e.menu=n}e.text=e.text||o||n[0].text,t._super(e),t.addClass("listbox"),t.on("select",function(n){e.multiple?n.control.active(!n.control.active()):t.value(n.control.settings.value)})},value:function(e){var n=this,r,i,o,a;if(e!==t){if(n.menu)n.menu.items().each(function(t){r=t.value()===e,r&&(i=i||t.text()),t.active(r)});else for(o=n.settings.menu,a=0;o.length>a;a++)r=o[a].value==e,r&&(i=i||o[a].text),o[a].active=r;n.text(i)}return n._super(e)}})}),r(Wt,[gt,U],function(e,t){return e.extend({Defaults:{border:0,role:"menuitem"},init:function(e){var t=this;t.hasPopup=!0,t._super(e),e=t.settings,t.addClass("menu-item"),e.menu&&t.addClass("menu-item-expand"),("-"===t._text||"|"===t._text)&&(t.addClass("menu-item-sep"),t.aria("role","separator"),t.canFocus=!1,t._text="-"),e.selectable&&(t.aria("role","menuitemcheckbox"),t.aria("checked",!0),t.addClass("menu-item-checkbox"),e.icon="selected"),t.on("mousedown",function(e){e.preventDefault()}),t.on("mouseenter click",function(n){n.control===t&&(e.menu||"click"!==n.type?(t.showMenu(),n.keyboard&&setTimeout(function(){t.menu.items()[0].focus()},0)):(t.parent().hideAll(),t.fire("cancel"),t.fire("select")))}),e.menu&&t.aria("haspopup",!0)},hasMenus:function(){return!!this.settings.menu},showMenu:function(){var e=this,n=e.settings,r;e.parent().items().each(function(t){t!==e&&t.hideMenu()}),n.menu&&(e.menu?e.menu.show():(r=n.menu,r.length?r={type:"menu",items:r}:r.type=r.type||"menu",e.menu=t.create(r).parent(e).renderTo(e.getContainerElm()),e.menu.reflow(),e.menu.fire("show"),e.menu.on("cancel",function(){e.focus()}),e.menu.on("hide",function(t){t.control===e.menu&&e.removeClass("selected")})),e.menu._parentMenu=e.parent(),e.menu.addClass("menu-sub"),e.menu.moveRel(e.getEl(),"tr-tl"),e.addClass("selected"),e.aria("expanded",!0))},hideMenu:function(){var e=this;return e.menu&&(e.menu.items().each(function(e){e.hideMenu&&e.hideMenu()}),e.menu.hide(),e.aria("expanded",!1)),e},renderHtml:function(){var e=this,t=e._id,n=e.settings,r=e.classPrefix,i=e.encode(e._text),o=e.settings.icon;return o&&e.parent().addClass("menu-has-icons"),o=r+"ico "+r+"i-"+(e.settings.icon||"none"),'
    '+("-"!==i?' ':"")+("-"!==i?''+i+"":"")+(n.shortcut?'
    '+n.shortcut+"
    ":"")+(n.menu?'
    ':"")+"
    " +},postRender:function(){var e=this,t=e.settings,n=t.textStyle;if("function"==typeof n&&(n=n()),n){var r=e.getEl("text");r&&r.setAttribute("style",n)}return e._super()},remove:function(){this._super(),this.menu&&this.menu.remove()}})}),r(zt,[Y,J,Wt],function(e,n,r){var i=e.extend({Defaults:{defaultType:"menuitem",border:1,layout:"stack",role:"menu"},init:function(e){var t=this;e.autohide=!0,t._super(e),t.addClass("menu"),t.keyNav=new n({root:t,enableUpDown:!0,enableLeftRight:!0,leftAction:function(){t.parent()instanceof r&&t.keyNav.cancel()},onCancel:function(){t.fire("cancel",{},!1),t.hide()}})},repaint:function(){return this.toggleClass("menu-align",!0),this._super(),this.getEl().style.height="",this.getEl("body").style.height="",this},cancel:function(){var e=this;e.hideAll(),e.fire("cancel"),e.fire("select")},hideAll:function(){var e=this;return this.find("menuitem").exec("hideMenu"),e._super()},preRender:function(){var e=this;return e.items().each(function(n){var r=n.settings;return r.icon||r.selectable?(e._hasIcons=!0,!1):t}),e._super()}});return i}),r(Vt,[vt,Y],function(e,t){var n=e.extend({showPanel:function(){var e=this,n=e.settings;n.panel.popover=!0,e.active(!0),e.panel?e.panel.show():e.panel=new t(n.panel).on("hide",function(){e.active(!1)}).parent(e).renderTo(e.getContainerElm()).reflow().moveRel(e.getEl(),n.popoverAlign||"bc-tc")},hidePanel:function(){var e=this;e.panel&&e.panel.hide()},postRender:function(){var e=this;return e.on("click",function(t){t.control===e&&e.showPanel()}),e._super()}});return n}),r(Ut,[gt],function(e){return e.extend({Defaults:{classes:"radio",checked:!1},init:function(e){var t=this;t._super(e),t.on("click",function(e){e.preventDefault(),t.disabled()||t.checked()||(t.parent().items().filter("radio:checked").exec("checked",!1),t.checked(!0))}),t.checked(e.checked)},checked:function(e){var n=this;return e!==t?(e?n.addClass("checked"):n.removeClass("checked"),n._checked=e,n):n._checked},renderHtml:function(){var e=this,t=e._id,n=e.classPrefix;return'"}})}),r(qt,[q],function(e){return e.extend({})}),r($t,[gt,$,z],function(e,t,n){return e.extend({renderHtml:function(){var e=this,t=e.classPrefix;return e.addClass("resizehandle"),e.settings.both&&e.addClass("resizehandle-both"),e.canFocus=!1,'
    '},postRender:function(){function e(e){return{width:e.clientWidth,height:e.clientHeight}}function r(t,r){var o,s,l,c,u=a.settings;o=a.getContainer(),s=a.getContentAreaContainer().firstChild,l=e(o),c=e(s),t=Math.max(u.min_width||100,t),r=Math.max(u.min_height||100,r),t=Math.min(u.max_width||65535,t),r=Math.min(u.max_height||65535,r),i.settings.both&&n.css(o,"width",t+(l.width-c.width)),n.css(o,"height",r+(l.height-c.height)),i.settings.both&&n.css(s,"width",t),n.css(s,"height",r),a.fire("ResizeEditor")}var i=this,o,a=i.settings.editor;i._super(),i.resizeDragHelper=new t(this._id,{start:function(){o=e(a.getContentAreaContainer().firstChild)},drag:function(e){r(o.width+e.deltaX,o.height+e.deltaY)},end:function(){}})}})}),r(jt,[gt],function(e){return e.extend({renderHtml:function(){var e=this;return e.addClass("spacer"),e.canFocus=!1,'
    '}})}),r(Gt,[It,v],function(e,t){var n=t.DOM;return e.extend({Defaults:{classes:"widget btn splitbtn",role:"splitbutton"},repaint:function(){var e=this,t=e.getEl(),r=e.layoutRect(),i,o,a;return e._super(),i=t.firstChild,o=t.lastChild,n.css(i,{width:r.w-o.offsetWidth,height:r.h-2}),n.css(o,{height:r.h-2}),a=i.firstChild.style,a.width=a.height="100%",a=o.firstChild.style,a.width=a.height="100%",e},activeMenu:function(e){var t=this;n.toggleClass(t.getEl().lastChild,t.classPrefix+"active",e)},renderHtml:function(){var e=this,t=e._id,n=e.classPrefix,r=e.settings.icon?n+"ico "+n+"i-"+e.settings.icon:"";return'
    '+'"+'"+"
    "},postRender:function(){var e=this,t=e.settings.onclick;return e.on("click",function(e){e.control!=this||n.getParent(e.target,"."+this.classPrefix+"open")||(e.stopImmediatePropagation(),t.call(this,e))}),delete e.settings.onclick,e._super()}})}),r(Kt,[Bt],function(e){return e.extend({Defaults:{containerClass:"stack-layout",controlClass:"stack-layout-item",endClass:"break"}})}),r(Xt,[G,z],function(e,t){"use stict";return e.extend({lastIdx:0,Defaults:{layout:"absolute",defaults:{type:"panel"}},activateTab:function(e){this.activeTabId&&t.removeClass(this.getEl(this.activeTabId),this.classPrefix+"active"),this.activeTabId="t"+e,t.addClass(this.getEl("t"+e),this.classPrefix+"active"),e!=this.lastIdx&&(this.items()[this.lastIdx].hide(),this.lastIdx=e),this.items()[e].show().fire("showtab"),this.reflow()},renderHtml:function(){var e=this,t=e._layout,n="",r=e.classPrefix;return e.preRender(),t.preRender(e),e.items().each(function(t,i){n+='
    '+t.settings.title+"
    "}),'
    '+'
    '+n+"
    "+'
    '+t.renderHtml(e)+"
    "+"
    "},postRender:function(){var e=this;e._super(),e.settings.activeTab=e.settings.activeTab||0,e.activateTab(e.settings.activeTab),this.on("click",function(t){var n=t.target.parentNode;if(t.target.parentNode.id==e._id+"-head")for(var r=n.childNodes.length;r--;)n.childNodes[r]==t.target&&e.activateTab(r)})},initLayoutRect:function(){var e=this,t,n,r;n=r=0,e.items().each(function(t,i){n=Math.max(n,t.layoutRect().minW),r=Math.max(r,t.layoutRect().minH),e.settings.activeTab!=i&&t.hide()}),e.items().each(function(e){e.settings.x=0,e.settings.y=0,e.settings.w=n,e.settings.h=r,e.layoutRect({x:0,y:0,w:n,h:r})});var i=e.getEl("head").offsetHeight;return e.settings.minWidth=n,e.settings.minHeight=r+i,t=e._super(),t.deltaH+=e.getEl("head").offsetHeight,t.innerH=t.h-t.deltaH,t}})}),r(Yt,[gt,z],function(e,n){return e.extend({init:function(e){var n=this;n._super(e),n._value=e.value||"",n.addClass("textbox"),e.multiline?n.addClass("multiline"):n.on("keydown",function(e){13==e.keyCode&&n.parents().reverse().each(function(n){return e.preventDefault(),n.submit?(n.submit(),!1):t})})},value:function(e){var n=this;return e!==t?(n._value=e,n._rendered&&(n.getEl().value=e),n):n._rendered?n.getEl().value:n._value},repaint:function(){var e=this,t,n,r,i=0,o=0,a;return t=e.getEl().style,n=e._layoutRect,a=e._lastRepaintRect||{},r=e._borderBox,i=r.left+r.right+8,o=r.top+r.bottom+(e.settings.multiline?8:0),n.x!==a.x&&(t.left=n.x+"px",a.x=n.x),n.y!==a.y&&(t.top=n.y+"px",a.y=n.y),n.w!==a.w&&(t.width=n.w-i+"px",a.w=n.w),n.h!==a.h&&(t.height=n.h-o+"px",a.h=n.h),e._lastRepaintRect=a,e.fire("repaint",{},!1),e},renderHtml:function(){var e=this,t=e._id,n=e.settings,r=e.encode(e._value,!1),i="";return"spellcheck"in n&&(i+=' spellcheck="'+n.spellcheck+'"'),n.maxLength&&(i+=' maxlength="'+n.maxLength+'"'),n.size&&(i+=' size="'+n.size+'"'),n.subtype&&(i+=' type="'+n.subtype+'"'),n.multiline?'":'"},postRender:function(){var e=this;return n.on(e.getEl(),"change",function(t){e.fire("change",t)}),e._super()}})}),r(Jt,[z],function(e){return function(t){var n=this,r;n.show=function(i){return n.hide(),r=!0,window.setTimeout(function(){r&&t.appendChild(e.createFragment('
    '))},i||0),n},n.hide=function(){var e=t.lastChild;return e&&-1!=e.className.indexOf("throbber")&&e.parentNode.removeChild(e),r=!1,n}}}),a([l,c,u,d,f,p,h,m,g,v,y,b,C,x,w,_,N,k,E,S,T,R,A,B,L,H,M,D,P,O,I,F,W,z,V,U,q,$,j,G,K,X,Y,J,Q,Z,et,tt,nt,rt,it,ot,at,st,lt,ct,ut,dt,ft,pt,ht,mt,gt,vt,yt,bt,Ct,xt,wt,_t,Nt,kt,Et,St,Tt,Rt,At,Bt,Lt,Ht,Mt,Dt,Pt,Ot,It,Ft,Wt,zt,Vt,Ut,qt,$t,jt,Gt,Kt,Xt,Yt,Jt])})(this); \ No newline at end of file From 69314caf0a7ee88923c1e4f7bbcf8d0e20620162 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 28 Jun 2013 11:55:28 -0700 Subject: [PATCH 02/15] Ported ICE to TinyMCE 4 and added comments for changes --- lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js index 145093b6..0df475cb 100644 --- a/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js +++ b/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js @@ -37,9 +37,9 @@ // make sure only the plugin is handling this event ed.on('keydown', function(e) { // prevent the delete key and backspace keys from firing twice - if(e.keyCode == 46 || e.keyCode==8) + if(e.keyCode == 46 || e.keyCode==8) { e.preventDefault(); - + } }); /** @@ -126,6 +126,8 @@ } }).startTracking(); + + // since onEvent doesn't seem to exist in TinyMce4 override the events as necessary ed.on('mousedown', function(e) { return changeEditor.handleEvent(e); }); From 59d022b38feabee81f652e88baa679e3d59ecba0 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 28 Jun 2013 12:02:02 -0700 Subject: [PATCH 03/15] changed comment --- lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js index 0df475cb..05a4de7c 100644 --- a/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js +++ b/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js @@ -34,7 +34,7 @@ changeEditor = null; - // make sure only the plugin is handling this event + // make sure only the plugin is handling this event and not the editor ed.on('keydown', function(e) { // prevent the delete key and backspace keys from firing twice if(e.keyCode == 46 || e.keyCode==8) { From 92c3cf46bbbd43f25c03f4bd94f5f3ae4406c099 Mon Sep 17 00:00:00 2001 From: danransom Date: Wed, 21 Aug 2013 11:23:47 -0700 Subject: [PATCH 04/15] Updated plugin to allow disable/enable buttons Updated to allow actions to disable/enable buttons using TinyMCE4. Also added a couple menu items for accept and reject. --- .../jscripts/tinymce4/plugins/ice/plugin.js | 127 +++++++++++++++--- 1 file changed, 107 insertions(+), 20 deletions(-) diff --git a/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js index 05a4de7c..18532d46 100644 --- a/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js +++ b/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js @@ -24,6 +24,13 @@ afterClean: function(body) { return body; }, beforePasteClean: function(body) { return body; }, afterPasteClean: function(body) { return body; }, + //buttons to activate/deactivate + trackChangesButton: function () { }, + showChangesButton: function () { }, + acceptButton: function () { }, + rejectButton: function () { }, + acceptAllButton: function () { }, + rejectAllButton: function () { }, /** * Plugin initialization - register buttons, commands, and take care of setup. @@ -276,17 +283,21 @@ var body = ed.getBody(), cm = ed.controlManager, disabled = true; if(ed.dom.hasClass(body,'CT-hide')) { - //cm.setActive('ice_toggleshowchanges', true); + //activate show changes button + ed.plugins.ice.showChangesButton.active(true); ed.dom.removeClass(body, 'CT-hide'); disabled = false; } else { - //cm.setActive('ice_toggleshowchanges', false); + //deactivate show changes button + ed.plugins.ice.showChangesButton.active(false); ed.dom.addClass(body, 'CT-hide'); } - tinymce.each(['iceacceptall','icerejectall'], function(button){ - //cm.setDisabled(button, disabled); - }); + //toggle button disabling + ed.plugins.ice.acceptAllButton.disabled(disabled); + ed.plugins.ice.rejectAllButton.disabled(disabled); + ed.plugins.ice.acceptButton.disabled(disabled); + ed.plugins.ice.rejectButton.disabled(disabled); ed.execCommand('mceRepaint'); }); @@ -315,7 +326,10 @@ */ ed.addCommand('ice_enable', function() { changeEditor.enableChangeTracking(); - //ed.controlManager.setActive('ice_togglechanges', true); + //toggle buttons and call show changes + ed.plugins.ice.trackChangesButton.active(true); + ed.plugins.ice.showChangesButton.disabled(false); + ed.execCommand('ice_toggleshowchanges'); self.isTracking = true; }); @@ -324,8 +338,17 @@ * or act on events. */ ed.addCommand('ice_disable', function() { + //hide changes and toggle buttons + var body = ed.getBody(); + ed.dom.addClass(body, 'CT-hide'); + ed.plugins.ice.trackChangesButton.active(false); + ed.plugins.ice.showChangesButton.active(false); + ed.plugins.ice.showChangesButton.disabled(true); + ed.plugins.ice.acceptAllButton.disabled(true); + ed.plugins.ice.rejectAllButton.disabled(true); + ed.plugins.ice.acceptButton.disabled(true); + ed.plugins.ice.rejectButton.disabled(true); changeEditor.disableChangeTracking(); - //ed.controlManager.setActive('ice_togglechanges', false); self.isTracking = false; }); @@ -365,31 +388,76 @@ ed.addButton('iceaccept', { title : 'Accept Change', image : url + '/img/accept.gif', - cmd : 'iceaccept' + cmd : 'iceaccept', + onPostRender: function () { //assigns button and changes disabled status on node change + var self = this; + ed.plugins.ice.acceptButton = self; + ed.plugins.ice.acceptButton.disabled = self.disabled; + + ed.on('NodeChange', function (e) { + if (isInsideChangeTag(e.element)) { + self.disabled(false); + } else { + self.disabled(true); + } + }); + } }); ed.addButton('icereject', { title : 'Reject Change', image : url + '/img/reject.gif', - cmd : 'icereject' + cmd : 'icereject', + onPostRender: function () {//assigns button and changes disabled status on node change + var self = this; + ed.plugins.ice.rejectButton = self; + ed.plugins.ice.rejectButton.disabled = self.disabled; + + ed.on('NodeChange', function (e) { + if (isInsideChangeTag(e.element)) { + self.disabled(false); + } else { + self.disabled(true); + } + }); + } }); ed.addButton('iceacceptall', { title : 'Accept All Changes', image : url + '/img/ice-accept.png', - cmd : 'iceacceptall' + cmd : 'iceacceptall', + onPostRender: function () { //assigns button + var self = this; + ed.plugins.ice.acceptAllButton = self; + ed.plugins.ice.acceptAllButton.disabled = self.disabled; + } }); ed.addButton('icerejectall', { title : 'Reject All Changes', image : url + '/img/ice-reject.png', - cmd : 'icerejectall' + cmd : 'icerejectall', + onPostRender: function () { //assigns button + var self = this; + ed.plugins.ice.rejectAllButton = self; + ed.plugins.ice.rejectAllButton.disabled = self.disabled; + } }); ed.addButton('ice_toggleshowchanges', { title : 'Show/Hide Track Changes', image : url + '/img/ice-showchanges.png', - cmd : 'ice_toggleshowchanges' + onclick: function () { + ed.fire('ice_toggleshowchanges'); + ed.execCommand('ice_toggleshowchanges'); + }, + onPostRender: function () { //assigns button + var self = this; + ed.plugins.ice.showChangesButton = self; + ed.plugins.ice.showChangesButton.disabled = self.disabled; + ed.plugins.ice.showChangesButton.active = self.active; + } }); ed.addButton('ice_smartquotes', { @@ -401,9 +469,35 @@ ed.addButton('ice_togglechanges', { title : 'Turn On Track Changes ', image : url + '/img/ice-togglechanges.png', - cmd : 'ice_togglechanges' + cmd : 'ice_togglechanges', + onPostRender: function () { //assigns button + var self = this; + ed.plugins.ice.trackChangesButton = self; + ed.plugins.ice.trackChangesButton.disabled = self.disabled; + ed.plugins.ice.trackChangesButton.active = self.active; + } }); + ed.addMenuItem('iceaccept', { + icon: 'accept', + text: 'Accept Change', + onclick: function () { + ed.execCommand('iceaccept'); + }, + context: 'tools', + prependToContext: true + }); + + ed.addMenuItem('icereject', { + icon: 'reject', + text: 'Reject Change', + onclick: function () { + ed.execCommand('icereject'); + }, + context: 'tools', + prependToContext: true + }); + if(ed.plugins.contextmenu) { ed.plugins.contextmenu.onContextMenu.add(function(th, menu, node) { if(isInsideChangeTag(node)) { @@ -425,13 +519,6 @@ * Node Change event - watch for node changes and toggle buttons. */ ed.on('NodeChange',function(e) { - if (isInsideChangeTag(e.element)) { - //cm.setDisabled('iceaccept', false); - //cm.setDisabled('icereject', false); - } else { - //cm.setDisabled('iceaccept', true); - //cm.setDisabled('icereject', true); - } cleanup(); }); From 2fa1beaee06d4c7b81bb6af1c0d6ef4a3012773a Mon Sep 17 00:00:00 2001 From: danransom Date: Thu, 22 Aug 2013 14:09:03 -0700 Subject: [PATCH 05/15] enables default backspace and delete key when ICE is not tracking without this if you turn off track changes then the editor does not process deletes and backspaces --- lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js b/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js index 05a4de7c..34854cd4 100644 --- a/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js +++ b/lib/tinymce/jscripts/tinymce4/plugins/ice/plugin.js @@ -37,7 +37,7 @@ // make sure only the plugin is handling this event and not the editor ed.on('keydown', function(e) { // prevent the delete key and backspace keys from firing twice - if(e.keyCode == 46 || e.keyCode==8) { + if((e.keyCode == 46 || e.keyCode == 8) && self.isTracking) { e.preventDefault(); } }); From fb2171f7952f46aaea7e24b1ab410676a0a606e2 Mon Sep 17 00:00:00 2001 From: Curt Mullin Date: Wed, 11 Sep 2013 23:01:52 -0700 Subject: [PATCH 06/15] work in progress on mce4 and requirejs --- demo/index-mce4-requirejs.html | 92 ++++++++++++++++++++++++++++++++++ demo/js/main.js | 0 demo/js/require-config.js | 66 ++++++++++++++++++++++++ demo/js/require.js | 36 +++++++++++++ 4 files changed, 194 insertions(+) create mode 100644 demo/index-mce4-requirejs.html create mode 100644 demo/js/main.js create mode 100644 demo/js/require-config.js create mode 100644 demo/js/require.js diff --git a/demo/index-mce4-requirejs.html b/demo/index-mce4-requirejs.html new file mode 100644 index 00000000..f36a9416 --- /dev/null +++ b/demo/index-mce4-requirejs.html @@ -0,0 +1,92 @@ + + + + + + + + + + + + + +
    + +

    Ice Demo

    + + +
    +
    + Set User: + +
    +
    +
    + +
    +
    +
    + + + +
    + + diff --git a/demo/js/main.js b/demo/js/main.js new file mode 100644 index 00000000..e69de29b diff --git a/demo/js/require-config.js b/demo/js/require-config.js new file mode 100644 index 00000000..4e7be483 --- /dev/null +++ b/demo/js/require-config.js @@ -0,0 +1,66 @@ +var require = { + "paths": { + "jquery": "http://code.jquery.com/jquery-1.9.1.min", + 'tinymce': "tinymce/js/tinymce/tinymce", + "tinymce.jquery": "tinymce/js/tinymce/jquery.tinymce.min", + // "rangy": "rangy/rangy-core", + // "ice": "ice/ice", + // "icePluginManager": "ice/icePluginManager", + // "IceAddTitlePlugin":'ice/plugins/IceAddTitlePlugin/IceAddTitlePlugin', + // "IceCopyPastePlugin":'ice/plugins/IceCopyPastePlugin/IceCopyPastePlugin.js', + // "IceEmdashPlugin":'ice/plugins/IceEmdashPlugin/IceEmdashPlugin.js', + // "IceSmartQuotesPlugin":'ice/plugins/IceSmartQuotesPlugin/IceSmartQuotesPlugin.js', + + "jquery1.9": "http://code.jquery.com/jquery-1.9.1.min", + "jquery-migrate" : "http://code.jquery.com/jquery-migrate-1.0.0", + "rangy-core": "../../lib/rangy/rangy-core", + "polyfills": "../../src/polyfills", + "ice":"../../src/ice", + "dom":"../../src/dom", + "icePlugin":"../../src/icePlugin", + "icePluginManager":"../../src/icePluginManager", + "bookmark":"../../src/bookmark", + "selection":"../../src/selection", + "IceAddTitlePlugin":"../../src/plugins/IceAddTitlePlugin/IceAddTitlePlugin", + "IceCopyPastePlugin":"../../src/plugins/IceCopyPastePlugin/IceCopyPastePlugin", + "IceEmdashPlugin":"../../src/plugins/IceEmdashPlugin/IceEmdashPlugin", + "IceSmartQuotesPlugin":"../../src/plugins/IceSmartQuotesPlugin/IceSmartQuotesPlugin", + "tinymce":"../../lib/tinymce/jscripts/tinymce4/tinymce", + }, + "shim": { + "jquery1.9": { + exports: "$" + }, + "rangy-core": { + exports: "window.rangy" + }, + "dom": { + deps:['ice'], + exports: "dom" + }, + "selection" : { + exports: "Selection" + }, + "bookmark": { + exports: "Bookmark" + }, + "ice" : { + exports: "ice" + }, + "icePluginManager": {deps: ['ice'] }, + "IceAddTitlePlugin":{ deps: ['icePluginManager']}, + "IceCopyPastePlugin":{ deps: ['icePluginManager']}, + "IceEmdashPlugin":{ deps: ['icePluginManager']}, + "IceSmartQuotesPlugin":{ deps: ['icePluginManager']}, + "tinymce": { + exports: "tinymce", + init: function() { + this.tinymce.DOM.events.domLoaded = true; + return this.tinymce; + } + }, + "tinymce.jquery" :{ + deps: ['jquery'] + } + } +}; \ No newline at end of file diff --git a/demo/js/require.js b/demo/js/require.js new file mode 100644 index 00000000..0de1ec89 --- /dev/null +++ b/demo/js/require.js @@ -0,0 +1,36 @@ +/* + RequireJS 2.1.8 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. + Available via the MIT or new BSD license. + see: http://github.com/jrburke/requirejs for details +*/ +var requirejs,require,define; +(function(Z){function H(b){return"[object Function]"===L.call(b)}function I(b){return"[object Array]"===L.call(b)}function y(b,c){if(b){var d;for(d=0;dthis.depCount&&!this.defined){if(H(m)){if(this.events.error&&this.map.isDefine||j.onError!==aa)try{e=i.execCb(c,m,b,e)}catch(d){a=d}else e=i.execCb(c,m,b,e);this.map.isDefine&&((b=this.module)&&void 0!==b.exports&&b.exports!== +this.exports?e=b.exports:void 0===e&&this.usingExports&&(e=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",v(this.error=a)}else e=m;this.exports=e;if(this.map.isDefine&&!this.ignore&&(r[c]=e,j.onResourceLoad))j.onResourceLoad(i,this.map,this.depMaps);x(c);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete= +!0)}}else this.fetch()}},callPlugin:function(){var a=this.map,b=a.id,d=n(a.prefix);this.depMaps.push(d);t(d,"defined",u(this,function(e){var m,d;d=this.map.name;var g=this.map.parentMap?this.map.parentMap.name:null,h=i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(e.normalize&&(d=e.normalize(d,function(a){return c(a,g,!0)})||""),e=n(a.prefix+"!"+d,this.map.parentMap),t(e,"defined",u(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})), +d=l(p,e.id)){this.depMaps.push(e);if(this.events.error)d.on("error",u(this,function(a){this.emit("error",a)}));d.enable()}}else m=u(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),m.error=u(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];F(p,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&x(a.map.id)});v(a)}),m.fromText=u(this,function(e,c){var d=a.name,g=n(d),B=O;c&&(e=c);B&&(O=!1);q(g);s(k.config,b)&&(k.config[d]=k.config[b]);try{j.exec(e)}catch(ca){return v(A("fromtexteval", +"fromText eval for "+b+" failed: "+ca,ca,[b]))}B&&(O=!0);this.depMaps.push(g);i.completeLoad(d);h([d],m)}),e.load(a.name,h,m,k)}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){T[this.map.id]=this;this.enabling=this.enabled=!0;y(this.depMaps,u(this,function(a,b){var c,e;if("string"===typeof a){a=n(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=l(N,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;t(a,"defined",u(this,function(a){this.defineDep(b, +a);this.check()}));this.errback&&t(a,"error",u(this,this.errback))}c=a.id;e=p[c];!s(N,c)&&(e&&!e.enabled)&&i.enable(a,this)}));F(this.pluginMaps,u(this,function(a){var b=l(p,a.id);b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){y(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:k,contextName:b,registry:p,defined:r,urlFetched:S,defQueue:G,Module:X,makeModuleMap:n, +nextTick:j.nextTick,onError:v,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=k.pkgs,c=k.shim,e={paths:!0,config:!0,map:!0};F(a,function(a,b){e[b]?"map"===b?(k.map||(k.map={}),Q(k[b],a,!0,!0)):Q(k[b],a,!0):k[b]=a});a.shim&&(F(a.shim,function(a,b){I(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);c[b]=a}),k.shim=c);a.packages&&(y(a.packages,function(a){a="string"===typeof a?{name:a}:a;b[a.name]={name:a.name, +location:a.location||a.name,main:(a.main||"main").replace(ja,"").replace(ea,"")}}),k.pkgs=b);F(p,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=n(b))});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(Z,arguments));return b||a.exports&&ba(a.exports)}},makeRequire:function(a,f){function d(e,c,h){var g,k;f.enableBuildCallback&&(c&&H(c))&&(c.__requireJsBuild=!0);if("string"===typeof e){if(H(c))return v(A("requireargs", +"Invalid require call"),h);if(a&&s(N,e))return N[e](p[a.id]);if(j.get)return j.get(i,e,a,d);g=n(e,a,!1,!0);g=g.id;return!s(r,g)?v(A("notloaded",'Module name "'+g+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):r[g]}K();i.nextTick(function(){K();k=q(n(null,a));k.skipMap=f.skipMap;k.init(e,c,h,{enabled:!0});C()});return d}f=f||{};Q(d,{isBrowser:z,toUrl:function(b){var d,f=b.lastIndexOf("."),g=b.split("/")[0];if(-1!==f&&(!("."===g||".."===g)||1h.attachEvent.toString().indexOf("[native code"))&&!W?(O=!0,h.attachEvent("onreadystatechange",b.onScriptLoad)):(h.addEventListener("load",b.onScriptLoad,!1),h.addEventListener("error", +b.onScriptError,!1)),h.src=d,K=h,C?x.insertBefore(h,C):x.appendChild(h),K=null,h;if(da)try{importScripts(d),b.completeLoad(c)}catch(l){b.onError(A("importscripts","importScripts failed for "+c+" at "+d,l,[c]))}};z&&M(document.getElementsByTagName("script"),function(b){x||(x=b.parentNode);if(J=b.getAttribute("data-main"))return q=J,t.baseUrl||(D=q.split("/"),q=D.pop(),fa=D.length?D.join("/")+"/":"./",t.baseUrl=fa),q=q.replace(ea,""),j.jsExtRegExp.test(q)&&(q=J),t.deps=t.deps?t.deps.concat(q):[q],!0}); +define=function(b,c,d){var h,j;"string"!==typeof b&&(d=c,c=b,b=null);I(c)||(d=c,c=null);!c&&H(d)&&(c=[],d.length&&(d.toString().replace(la,"").replace(ma,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(O){if(!(h=K))P&&"interactive"===P.readyState||M(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return P=b}),h=P;h&&(b||(b=h.getAttribute("data-requiremodule")),j=E[h.getAttribute("data-requirecontext")])}(j?j.defQueue: +R).push([b,c,d])};define.amd={jQuery:!0};j.exec=function(b){return eval(b)};j(t)}})(this); \ No newline at end of file From 3c7a805fac15e6f3696182aa4c0a4e62cdb22f69 Mon Sep 17 00:00:00 2001 From: Unknower Date: Thu, 19 Sep 2013 17:24:38 -0400 Subject: [PATCH 07/15] Make pasteDiv removal compatible with older browsers --- ice-master.min.js | 2 +- src/plugins/IceCopyPastePlugin/IceCopyPastePlugin.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ice-master.min.js b/ice-master.min.js index 1cb75b43..16a08c2c 100644 --- a/ice-master.min.js +++ b/ice-master.min.js @@ -5,5 +5,5 @@ // window.rangy=function(){function e(e,t){var n=typeof e[t];return n==u||!(n!=d||!e[t])||"unknown"==n}function t(e,t){return!(typeof e[t]!=d||!e[t])}function n(e,t){return typeof e[t]!=h}function i(e){return function(t,n){for(var i=n.length;i--;)if(!e(t,n[i]))return!1;return!0}}function r(e){return e&&C(e,p)&&N(e,m)}function o(e){window.alert("Rangy not supported in your browser. Reason: "+e),E.initialized=!0,E.supported=!1}function s(e){var t="Rangy warning: "+e;E.config.alertOnWarn?window.alert(t):typeof window.console!=h&&typeof window.console.log!=h&&window.console.log(t)}function a(){if(!E.initialized){var n,i=!1,s=!1;e(document,"createRange")&&(n=document.createRange(),C(n,g)&&N(n,f)&&(i=!0),n.detach());var a=t(document,"body")?document.body:document.getElementsByTagName("body")[0];a&&e(a,"createTextRange")&&(n=a.createTextRange(),r(n)&&(s=!0)),i||s||o("Neither Range nor TextRange are implemented"),E.initialized=!0,E.features={implementsDomRange:i,implementsTextRange:s};for(var c=_.concat(y),l=0,d=c.length;d>l;++l)try{c[l](E)}catch(u){t(window,"console")&&e(window.console,"log")&&window.console.log("Init listener threw an exception. Continuing.",u)}}}function c(e){e=e||window,a();for(var t=0,n=T.length;n>t;++t)T[t](e)}function l(e){this.name=e,this.initialized=!1,this.supported=!1}var d="object",u="function",h="undefined",f=["startContainer","startOffset","endContainer","endOffset","collapsed","commonAncestorContainer","START_TO_START","START_TO_END","END_TO_START","END_TO_END"],g=["setStart","setStartBefore","setStartAfter","setEnd","setEndBefore","setEndAfter","collapse","selectNode","selectNodeContents","compareBoundaryPoints","deleteContents","extractContents","cloneContents","insertNode","surroundContents","cloneRange","toString","detach"],m=["boundingHeight","boundingLeft","boundingTop","boundingWidth","htmlText","text"],p=["collapse","compareEndPoints","duplicate","getBookmark","moveToBookmark","moveToElementText","parentElement","pasteHTML","select","setEndPoint","getBoundingClientRect"],C=i(e),v=i(t),N=i(n),E={version:"1.2.3",initialized:!1,supported:!0,util:{isHostMethod:e,isHostObject:t,isHostProperty:n,areHostMethods:C,areHostObjects:v,areHostProperties:N,isTextRange:r},features:{},modules:{},config:{alertOnWarn:!1,preferTextRange:!1}};E.fail=o,E.warn=s,{}.hasOwnProperty?E.util.extend=function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}:o("hasOwnProperty not supported");var y=[],_=[];E.init=a,E.addInitListener=function(e){E.initialized?e(E):y.push(e)};var T=[];E.addCreateMissingNativeApiListener=function(e){T.push(e)},E.createMissingNativeApi=c,l.prototype.fail=function(e){throw this.initialized=!0,this.supported=!1,Error("Module '"+this.name+"' failed to load: "+e)},l.prototype.warn=function(e){E.warn("Module "+this.name+": "+e)},l.prototype.createError=function(e){return Error("Error in Rangy "+this.name+" module: "+e)},E.createModule=function(e,t){var n=new l(e);E.modules[e]=n,_.push(function(e){t(e,n),n.initialized=!0,n.supported=!0})},E.requireModules=function(e){for(var t,n,i=0,r=e.length;r>i;++i){if(n=e[i],t=E.modules[n],!(t&&t instanceof l))throw Error("Module '"+n+"' not found");if(!t.supported)throw Error("Module '"+n+"' not supported")}};var S=!1,R=function(){S||(S=!0,E.initialized||a())};return typeof window==h?(o("No window found"),void 0):typeof document==h?(o("No document found"),void 0):(e(document,"addEventListener")&&document.addEventListener("DOMContentLoaded",R,!1),e(window,"addEventListener")?window.addEventListener("load",R,!1):e(window,"attachEvent")?window.attachEvent("onload",R):o("Window does not have required addEventListener or attachEvent method"),E)}(),rangy.createModule("DomUtil",function(e,t){function n(e){var t;return typeof e.namespaceURI==R||null===(t=e.namespaceURI)||"http://www.w3.org/1999/xhtml"==t}function i(e){var t=e.parentNode;return 1==t.nodeType?t:null}function r(e){for(var t=0;e=e.previousSibling;)t++;return t}function o(e){var t;return l(e)?e.length:(t=e.childNodes)?t.length:0}function s(e,t){var n,i=[];for(n=e;n;n=n.parentNode)i.push(n);for(n=t;n;n=n.parentNode)if(D(i,n))return n;return null}function a(e,t,n){for(var i=n?t:t.parentNode;i;){if(i===e)return!0;i=i.parentNode}return!1}function c(e,t,n){for(var i,r=n?e:e.parentNode;r;){if(i=r.parentNode,i===t)return r;r=i}return null}function l(e){var t=e.nodeType;return 3==t||4==t||8==t}function d(e,t){var n=t.nextSibling,i=t.parentNode;return n?i.insertBefore(e,n):i.appendChild(e),e}function u(e,t){var n=e.cloneNode(!1);return n.deleteData(0,t),e.deleteData(t,e.length-t),d(n,e),n}function h(e){if(9==e.nodeType)return e;if(typeof e.ownerDocument!=R)return e.ownerDocument;if(typeof e.document!=R)return e.document;if(e.parentNode)return h(e.parentNode);throw Error("getDocument: no document found for node")}function f(e){var t=h(e);if(typeof t.defaultView!=R)return t.defaultView;if(typeof t.parentWindow!=R)return t.parentWindow;throw Error("Cannot get a window object for node")}function g(e){if(typeof e.contentDocument!=R)return e.contentDocument;if(typeof e.contentWindow!=R)return e.contentWindow.document;throw Error("getIframeWindow: No Document object found for iframe element")}function m(e){if(typeof e.contentWindow!=R)return e.contentWindow;if(typeof e.contentDocument!=R)return e.contentDocument.defaultView;throw Error("getIframeWindow: No Window object found for iframe element")}function p(e){return b.isHostObject(e,"body")?e.body:e.getElementsByTagName("body")[0]}function C(e){for(var t;t=e.parentNode;)e=t;return e}function v(e,t,n,i){var o,a,l,d,u;if(e==n)return t===i?0:i>t?-1:1;if(o=c(n,e,!0))return r(o)>=t?-1:1;if(o=c(e,n,!0))return i>r(o)?-1:1;if(a=s(e,n),l=e===a?a:c(e,a,!0),d=n===a?a:c(n,a,!0),l===d)throw Error("comparePoints got to case 4 and childA and childB are the same!");for(u=a.firstChild;u;){if(u===l)return-1;if(u===d)return 1;u=u.nextSibling}throw Error("Should not be here!")}function N(e){for(var t,n=h(e).createDocumentFragment();t=e.firstChild;)n.appendChild(t);return n}function E(e){if(!e)return"[No node]";if(l(e))return'"'+e.data+'"';if(1==e.nodeType){var t=e.id?' id="'+e.id+'"':"";return"<"+e.nodeName+t+">["+e.childNodes.length+"]"}return e.nodeName}function y(e){this.root=e,this._next=e}function _(e){return new y(e)}function T(e,t){this.node=e,this.offset=t}function S(e){this.code=this[e],this.codeName=e,this.message="DOMException: "+this.codeName}var R="undefined",b=e.util;b.areHostMethods(document,["createDocumentFragment","createElement","createTextNode"])||t.fail("document missing a Node creation method"),b.isHostMethod(document,"getElementsByTagName")||t.fail("document missing getElementsByTagName method");var O=document.createElement("div");b.areHostMethods(O,["insertBefore","appendChild","cloneNode"]||!b.areHostObjects(O,["previousSibling","nextSibling","childNodes","parentNode"]))||t.fail("Incomplete Element implementation"),b.isHostProperty(O,"innerHTML")||t.fail("Element is missing innerHTML property");var w=document.createTextNode("test");b.areHostMethods(w,["splitText","deleteData","insertData","appendData","cloneNode"]||!b.areHostObjects(O,["previousSibling","nextSibling","childNodes","parentNode"])||!b.areHostProperties(w,["data"]))||t.fail("Incomplete Text Node implementation");var D=function(e,t){for(var n=e.length;n--;)if(e[n]===t)return!0;return!1};y.prototype={_current:null,hasNext:function(){return!!this._next},next:function(){var e,t,n=this._current=this._next;if(this._current)if(e=n.firstChild)this._next=e;else{for(t=null;n!==this.root&&!(t=n.nextSibling);)n=n.parentNode;this._next=t}return this._current},detach:function(){this._current=this._next=this.root=null}},T.prototype={equals:function(e){return this.node===e.node&this.offset==e.offset},inspect:function(){return"[DomPosition("+E(this.node)+":"+this.offset+")]"}},S.prototype={INDEX_SIZE_ERR:1,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INVALID_STATE_ERR:11},S.prototype.toString=function(){return this.message},e.dom={arrayContains:D,isHtmlNamespace:n,parentElement:i,getNodeIndex:r,getNodeLength:o,getCommonAncestor:s,isAncestorOf:a,getClosestAncestorIn:c,isCharacterDataNode:l,insertAfter:d,splitDataNode:u,getDocument:h,getWindow:f,getIframeWindow:m,getIframeDocument:g,getBody:p,getRootContainer:C,comparePoints:v,inspectNode:E,fragmentFromNodeChildren:N,createIterator:_,DomPosition:T},e.DOMException=S}),rangy.createModule("DomRange",function(e){function t(e,t){return 3!=e.nodeType&&(L.isAncestorOf(e,t.startContainer,!0)||L.isAncestorOf(e,t.endContainer,!0))}function n(e){return L.getDocument(e.startContainer)}function i(e,t,n){var i=e._listeners[t];if(i)for(var r=0,o=i.length;o>r;++r)i[r].call(e,{target:e,args:n})}function r(e){return new H(e.parentNode,L.getNodeIndex(e))}function o(e){return new H(e.parentNode,L.getNodeIndex(e)+1)}function s(e,t,n){var i=11==e.nodeType?e.firstChild:e;return L.isCharacterDataNode(t)?n==t.length?L.insertAfter(e,t):t.parentNode.insertBefore(e,0==n?t:L.splitDataNode(t,n)):n>=t.childNodes.length?t.appendChild(e):t.insertBefore(e,t.childNodes[n]),i}function a(e){for(var t,i,r,o=n(e.range).createDocumentFragment();i=e.next();){if(t=e.isPartiallySelectedSubtree(),i=i.cloneNode(!t),t&&(r=e.getSubtreeIterator(),i.appendChild(a(r)),r.detach(!0)),10==i.nodeType)throw new j("HIERARCHY_REQUEST_ERR");o.appendChild(i)}return o}function c(e,t,n){var i,r;n=n||{stop:!1};for(var o,s;o=e.next();)if(e.isPartiallySelectedSubtree()){if(t(o)===!1)return n.stop=!0,void 0;if(s=e.getSubtreeIterator(),c(s,t,n),s.detach(!0),n.stop)return}else for(i=L.createIterator(o);r=i.next();)if(t(r)===!1)return n.stop=!0,void 0}function l(e){for(var t;e.next();)e.isPartiallySelectedSubtree()?(t=e.getSubtreeIterator(),l(t),t.detach(!0)):e.remove()}function d(e){for(var t,i,r=n(e.range).createDocumentFragment();t=e.next();){if(e.isPartiallySelectedSubtree()?(t=t.cloneNode(!1),i=e.getSubtreeIterator(),t.appendChild(d(i)),i.detach(!0)):e.remove(),10==t.nodeType)throw new j("HIERARCHY_REQUEST_ERR");r.appendChild(t)}return r}function u(e,t,n){var i,r=!(!t||!t.length),o=!!n;r&&(i=RegExp("^("+t.join("|")+")$"));var s=[];return c(new f(e,!1),function(e){r&&!i.test(e.nodeType)||o&&!n(e)||s.push(e)}),s}function h(e){var t=e.getName===void 0?"Range":e.getName();return"["+t+"("+L.inspectNode(e.startContainer)+":"+e.startOffset+", "+L.inspectNode(e.endContainer)+":"+e.endOffset+")]"}function f(e,t){if(this.range=e,this.clonePartiallySelectedTextNodes=t,!e.collapsed){this.sc=e.startContainer,this.so=e.startOffset,this.ec=e.endContainer,this.eo=e.endOffset;var n=e.commonAncestorContainer;this.sc===this.ec&&L.isCharacterDataNode(this.sc)?(this.isSingleCharacterDataNode=!0,this._first=this._last=this._next=this.sc):(this._first=this._next=this.sc!==n||L.isCharacterDataNode(this.sc)?L.getClosestAncestorIn(this.sc,n,!0):this.sc.childNodes[this.so],this._last=this.ec!==n||L.isCharacterDataNode(this.ec)?L.getClosestAncestorIn(this.ec,n,!0):this.ec.childNodes[this.eo-1])}}function g(e){this.code=this[e],this.codeName=e,this.message="RangeException: "+this.codeName}function m(e,t,n){this.nodes=u(e,t,n),this._next=this.nodes[0],this._position=0}function p(e){return function(t,n){for(var i,r=n?t:t.parentNode;r;){if(i=r.nodeType,L.arrayContains(e,i))return r;r=r.parentNode}return null}}function C(e,t){if(q(e,t))throw new g("INVALID_NODE_TYPE_ERR")}function v(e){if(!e.startContainer)throw new j("INVALID_STATE_ERR")}function N(e,t){if(!L.arrayContains(t,e.nodeType))throw new g("INVALID_NODE_TYPE_ERR")}function E(e,t){if(0>t||t>(L.isCharacterDataNode(e)?e.length:e.childNodes.length))throw new j("INDEX_SIZE_ERR")}function y(e,t){if(X(e,!0)!==X(t,!0))throw new j("WRONG_DOCUMENT_ERR")}function _(e){if(z(e,!0))throw new j("NO_MODIFICATION_ALLOWED_ERR")}function T(e,t){if(!e)throw new j(t)}function S(e){return!L.arrayContains(Q,e.nodeType)&&!X(e,!0)}function R(e,t){return(L.isCharacterDataNode(e)?e.length:e.childNodes.length)>=t}function b(e){return!!e.startContainer&&!!e.endContainer&&!S(e.startContainer)&&!S(e.endContainer)&&R(e.startContainer,e.startOffset)&&R(e.endContainer,e.endOffset)}function O(e){if(v(e),!b(e))throw Error("Range error: Range is no longer valid after DOM mutation ("+e.inspect()+")")}function w(){}function D(e){e.START_TO_START=et,e.START_TO_END=tt,e.END_TO_END=nt,e.END_TO_START=it,e.NODE_BEFORE=rt,e.NODE_AFTER=ot,e.NODE_BEFORE_AND_AFTER=st,e.NODE_INSIDE=at}function x(e){D(e),D(e.prototype)}function k(e,t){return function(){O(this);var n,i,r=this.startContainer,s=this.startOffset,a=this.commonAncestorContainer,l=new f(this,!0);r!==a&&(n=L.getClosestAncestorIn(r,a,!0),i=o(n),r=i.node,s=i.offset),c(l,_),l.reset();var d=e(l);return l.detach(),t(this,r,s,r,s),d}}function A(n,i,s){function a(e,t){return function(n){v(this),N(n,U),N(V(n),Q);var i=(e?r:o)(n);(t?c:u)(this,i.node,i.offset)}}function c(e,t,n){var r=e.endContainer,o=e.endOffset;(t!==e.startContainer||n!==e.startOffset)&&((V(t)!=V(r)||1==L.comparePoints(t,n,r,o))&&(r=t,o=n),i(e,t,n,r,o))}function u(e,t,n){var r=e.startContainer,o=e.startOffset;(t!==e.endContainer||n!==e.endOffset)&&((V(t)!=V(r)||-1==L.comparePoints(t,n,r,o))&&(r=t,o=n),i(e,r,o,t,n))}function h(e,t,n){(t!==e.startContainer||n!==e.startOffset||t!==e.endContainer||n!==e.endOffset)&&i(e,t,n,t,n)}n.prototype=new w,e.util.extend(n.prototype,{setStart:function(e,t){v(this),C(e,!0),E(e,t),c(this,e,t)},setEnd:function(e,t){v(this),C(e,!0),E(e,t),u(this,e,t)},setStartBefore:a(!0,!0),setStartAfter:a(!1,!0),setEndBefore:a(!0,!1),setEndAfter:a(!1,!1),collapse:function(e){O(this),e?i(this,this.startContainer,this.startOffset,this.startContainer,this.startOffset):i(this,this.endContainer,this.endOffset,this.endContainer,this.endOffset)},selectNodeContents:function(e){v(this),C(e,!0),i(this,e,0,e,L.getNodeLength(e))},selectNode:function(e){v(this),C(e,!1),N(e,U);var t=r(e),n=o(e);i(this,t.node,t.offset,n.node,n.offset)},extractContents:k(d,i),deleteContents:k(l,i),canSurroundContents:function(){O(this),_(this.startContainer),_(this.endContainer);var e=new f(this,!0),n=e._first&&t(e._first,this)||e._last&&t(e._last,this);return e.detach(),!n},detach:function(){s(this)},splitBoundaries:function(){O(this);var e=this.startContainer,t=this.startOffset,n=this.endContainer,r=this.endOffset,o=e===n;L.isCharacterDataNode(n)&&r>0&&n.length>r&&L.splitDataNode(n,r),L.isCharacterDataNode(e)&&t>0&&e.length>t&&(e=L.splitDataNode(e,t),o?(r-=t,n=e):n==e.parentNode&&r>=L.getNodeIndex(e)&&r++,t=0),i(this,e,t,n,r)},normalizeBoundaries:function(){O(this);var e=this.startContainer,t=this.startOffset,n=this.endContainer,r=this.endOffset,o=function(e){var t=e.nextSibling;t&&t.nodeType==e.nodeType&&(n=e,r=e.length,e.appendData(t.data),t.parentNode.removeChild(t))},s=function(i){var o=i.previousSibling;if(o&&o.nodeType==i.nodeType){e=i;var s=i.length;if(t=o.length,i.insertData(0,o.data),o.parentNode.removeChild(o),e==n)r+=t,n=e;else if(n==i.parentNode){var a=L.getNodeIndex(i);r==a?(n=i,r=s):r>a&&r--}}},a=!0;if(L.isCharacterDataNode(n))n.length==r&&o(n);else{if(r>0){var c=n.childNodes[r-1];c&&L.isCharacterDataNode(c)&&o(c)}a=!this.collapsed}if(a){if(L.isCharacterDataNode(e))0==t&&s(e);else if(e.childNodes.length>t){var l=e.childNodes[t];l&&L.isCharacterDataNode(l)&&s(l)}}else e=n,t=r;i(this,e,t,n,r)},collapseToPoint:function(e,t){v(this),C(e,!0),E(e,t),h(this,e,t)}}),x(n)}function P(e){e.collapsed=e.startContainer===e.endContainer&&e.startOffset===e.endOffset,e.commonAncestorContainer=e.collapsed?e.startContainer:L.getCommonAncestor(e.startContainer,e.endContainer)}function I(e,t,n,r,o){var s=e.startContainer!==t||e.startOffset!==n,a=e.endContainer!==r||e.endOffset!==o;e.startContainer=t,e.startOffset=n,e.endContainer=r,e.endOffset=o,P(e),i(e,"boundarychange",{startMoved:s,endMoved:a})}function B(e){v(e),e.startContainer=e.startOffset=e.endContainer=e.endOffset=null,e.collapsed=e.commonAncestorContainer=null,i(e,"detach",null),e._listeners=null}function M(e){this.startContainer=e,this.startOffset=0,this.endContainer=e,this.endOffset=0,this._listeners={boundarychange:[],detach:[]},P(this)}e.requireModules(["DomUtil"]);var L=e.dom,H=L.DomPosition,j=e.DOMException;f.prototype={_current:null,_next:null,_first:null,_last:null,isSingleCharacterDataNode:!1,reset:function(){this._current=null,this._next=this._first},hasNext:function(){return!!this._next},next:function(){var e=this._current=this._next;return e&&(this._next=e!==this._last?e.nextSibling:null,L.isCharacterDataNode(e)&&this.clonePartiallySelectedTextNodes&&(e===this.ec&&(e=e.cloneNode(!0)).deleteData(this.eo,e.length-this.eo),this._current===this.sc&&(e=e.cloneNode(!0)).deleteData(0,this.so))),e},remove:function(){var e,t,n=this._current;!L.isCharacterDataNode(n)||n!==this.sc&&n!==this.ec?n.parentNode&&n.parentNode.removeChild(n):(e=n===this.sc?this.so:0,t=n===this.ec?this.eo:n.length,e!=t&&n.deleteData(e,t-e))},isPartiallySelectedSubtree:function(){var e=this._current;return t(e,this.range)},getSubtreeIterator:function(){var e;if(this.isSingleCharacterDataNode)e=this.range.cloneRange(),e.collapse();else{e=new M(n(this.range));var t=this._current,i=t,r=0,o=t,s=L.getNodeLength(t);L.isAncestorOf(t,this.sc,!0)&&(i=this.sc,r=this.so),L.isAncestorOf(t,this.ec,!0)&&(o=this.ec,s=this.eo),I(e,i,r,o,s)}return new f(e,this.clonePartiallySelectedTextNodes)},detach:function(e){e&&this.range.detach(),this.range=this._current=this._next=this._first=this._last=this.sc=this.so=this.ec=this.eo=null}},g.prototype={BAD_BOUNDARYPOINTS_ERR:1,INVALID_NODE_TYPE_ERR:2},g.prototype.toString=function(){return this.message},m.prototype={_current:null,hasNext:function(){return!!this._next},next:function(){return this._current=this._next,this._next=this.nodes[++this._position],this._current},detach:function(){this._current=this._next=this.nodes=null}};var U=[1,3,4,5,7,8,10],Q=[2,9,11],W=[5,6,10,12],F=[1,3,4,5,7,8,10,11],K=[1,3,4,5,7,8],V=L.getRootContainer,X=p([9,11]),z=p(W),q=p([6,10,12]),Y=document.createElement("style"),$=!1;try{Y.innerHTML="x",$=3==Y.firstChild.nodeType}catch(G){}e.features.htmlParsingConforms=$;var Z=$?function(e){var t=this.startContainer,n=L.getDocument(t);if(!t)throw new j("INVALID_STATE_ERR");var i=null;return 1==t.nodeType?i=t:L.isCharacterDataNode(t)&&(i=L.parentElement(t)),i=null===i||"HTML"==i.nodeName&&L.isHtmlNamespace(L.getDocument(i).documentElement)&&L.isHtmlNamespace(i)?n.createElement("body"):i.cloneNode(!1),i.innerHTML=e,L.fragmentFromNodeChildren(i)}:function(e){v(this);var t=n(this),i=t.createElement("body");return i.innerHTML=e,L.fragmentFromNodeChildren(i)},J=["startContainer","startOffset","endContainer","endOffset","collapsed","commonAncestorContainer"],et=0,tt=1,nt=2,it=3,rt=0,ot=1,st=2,at=3;w.prototype={attachListener:function(e,t){this._listeners[e].push(t)},compareBoundaryPoints:function(e,t){O(this),y(this.startContainer,t.startContainer);var n,i,r,o,s=e==it||e==et?"start":"end",a=e==tt||e==et?"start":"end";return n=this[s+"Container"],i=this[s+"Offset"],r=t[a+"Container"],o=t[a+"Offset"],L.comparePoints(n,i,r,o)},insertNode:function(e){if(O(this),N(e,F),_(this.startContainer),L.isAncestorOf(e,this.startContainer,!0))throw new j("HIERARCHY_REQUEST_ERR");var t=s(e,this.startContainer,this.startOffset);this.setStartBefore(t)},cloneContents:function(){O(this);var e,t;if(this.collapsed)return n(this).createDocumentFragment();if(this.startContainer===this.endContainer&&L.isCharacterDataNode(this.startContainer))return e=this.startContainer.cloneNode(!0),e.data=e.data.slice(this.startOffset,this.endOffset),t=n(this).createDocumentFragment(),t.appendChild(e),t;var i=new f(this,!0);return e=a(i),i.detach(),e},canSurroundContents:function(){O(this),_(this.startContainer),_(this.endContainer);var e=new f(this,!0),n=e._first&&t(e._first,this)||e._last&&t(e._last,this);return e.detach(),!n},surroundContents:function(e){if(N(e,K),!this.canSurroundContents())throw new g("BAD_BOUNDARYPOINTS_ERR");var t=this.extractContents();if(e.hasChildNodes())for(;e.lastChild;)e.removeChild(e.lastChild);s(e,this.startContainer,this.startOffset),e.appendChild(t),this.selectNode(e)},cloneRange:function(){O(this);for(var e,t=new M(n(this)),i=J.length;i--;)e=J[i],t[e]=this[e];return t},toString:function(){O(this);var e=this.startContainer;if(e===this.endContainer&&L.isCharacterDataNode(e))return 3==e.nodeType||4==e.nodeType?e.data.slice(this.startOffset,this.endOffset):"";var t=[],n=new f(this,!0);return c(n,function(e){(3==e.nodeType||4==e.nodeType)&&t.push(e.data)}),n.detach(),t.join("")},compareNode:function(e){O(this);var t=e.parentNode,n=L.getNodeIndex(e);if(!t)throw new j("NOT_FOUND_ERR");var i=this.comparePoint(t,n),r=this.comparePoint(t,n+1);return 0>i?r>0?st:rt:r>0?ot:at},comparePoint:function(e,t){return O(this),T(e,"HIERARCHY_REQUEST_ERR"),y(e,this.startContainer),0>L.comparePoints(e,t,this.startContainer,this.startOffset)?-1:L.comparePoints(e,t,this.endContainer,this.endOffset)>0?1:0},createContextualFragment:Z,toHtml:function(){O(this);var e=n(this).createElement("div");return e.appendChild(this.cloneContents()),e.innerHTML},intersectsNode:function(e,t){if(O(this),T(e,"NOT_FOUND_ERR"),L.getDocument(e)!==n(this))return!1;var i=e.parentNode,r=L.getNodeIndex(e);T(i,"NOT_FOUND_ERR");var o=L.comparePoints(i,r,this.endContainer,this.endOffset),s=L.comparePoints(i,r+1,this.startContainer,this.startOffset);return t?0>=o&&s>=0:0>o&&s>0},isPointInRange:function(e,t){return O(this),T(e,"HIERARCHY_REQUEST_ERR"),y(e,this.startContainer),L.comparePoints(e,t,this.startContainer,this.startOffset)>=0&&0>=L.comparePoints(e,t,this.endContainer,this.endOffset)},intersectsRange:function(e,t){if(O(this),n(e)!=n(this))throw new j("WRONG_DOCUMENT_ERR");var i=L.comparePoints(this.startContainer,this.startOffset,e.endContainer,e.endOffset),r=L.comparePoints(this.endContainer,this.endOffset,e.startContainer,e.startOffset);return t?0>=i&&r>=0:0>i&&r>0},intersection:function(e){if(this.intersectsRange(e)){var t=L.comparePoints(this.startContainer,this.startOffset,e.startContainer,e.startOffset),n=L.comparePoints(this.endContainer,this.endOffset,e.endContainer,e.endOffset),i=this.cloneRange();return-1==t&&i.setStart(e.startContainer,e.startOffset),1==n&&i.setEnd(e.endContainer,e.endOffset),i}return null},union:function(e){if(this.intersectsRange(e,!0)){var t=this.cloneRange();return-1==L.comparePoints(e.startContainer,e.startOffset,this.startContainer,this.startOffset)&&t.setStart(e.startContainer,e.startOffset),1==L.comparePoints(e.endContainer,e.endOffset,this.endContainer,this.endOffset)&&t.setEnd(e.endContainer,e.endOffset),t}throw new g("Ranges do not intersect")},containsNode:function(e,t){return t?this.intersectsNode(e,!1):this.compareNode(e)==at},containsNodeContents:function(e){return this.comparePoint(e,0)>=0&&0>=this.comparePoint(e,L.getNodeLength(e))},containsRange:function(e){return this.intersection(e).equals(e)},containsNodeText:function(e){var t=this.cloneRange();t.selectNode(e);var n=t.getNodes([3]);if(n.length>0){t.setStart(n[0],0);var i=n.pop();t.setEnd(i,i.length);var r=this.containsRange(t);return t.detach(),r}return this.containsNodeContents(e)},createNodeIterator:function(e,t){return O(this),new m(this,e,t)},getNodes:function(e,t){return O(this),u(this,e,t)},getDocument:function(){return n(this)},collapseBefore:function(e){v(this),this.setEndBefore(e),this.collapse(!1)},collapseAfter:function(e){v(this),this.setStartAfter(e),this.collapse(!0)},getName:function(){return"DomRange"},equals:function(e){return M.rangesEqual(this,e)},isValid:function(){return b(this)},inspect:function(){return h(this)}},A(M,I,B),e.rangePrototype=w.prototype,M.rangeProperties=J,M.RangeIterator=f,M.copyComparisonConstants=x,M.createPrototypeRange=A,M.inspect=h,M.getRangeDocument=n,M.rangesEqual=function(e,t){return e.startContainer===t.startContainer&&e.startOffset===t.startOffset&&e.endContainer===t.endContainer&&e.endOffset===t.endOffset},e.DomRange=M,e.RangeException=g}),rangy.createModule("WrappedRange",function(e){function t(e){var t=e.parentElement(),n=e.duplicate();n.collapse(!0);var i=n.parentElement();n=e.duplicate(),n.collapse(!1);var r=n.parentElement(),o=i==r?i:s.getCommonAncestor(i,r);return o==t?o:s.getCommonAncestor(t,o)}function n(e){return 0==e.compareEndPoints("StartToEnd",e)}function i(e,t,n,i){var r=e.duplicate();r.collapse(n);var o=r.parentElement();if(s.isAncestorOf(t,o,!0)||(o=t),!o.canHaveHTML)return new a(o.parentNode,s.getNodeIndex(o));var c,l,d,u,h,f=s.getDocument(o).createElement("span"),g=n?"StartToStart":"StartToEnd";do o.insertBefore(f,f.previousSibling),r.moveToElementText(f);while((c=r.compareEndPoints(g,e))>0&&f.previousSibling);if(h=f.nextSibling,-1==c&&h&&s.isCharacterDataNode(h)){r.setEndPoint(n?"EndToStart":"EndToEnd",e);var m;if(/[\r\n]/.test(h.data)){var p=r.duplicate(),C=p.text.replace(/\r\n/g,"\r").length;for(m=p.moveStart("character",C);-1==(c=p.compareEndPoints("StartToEnd",p));)m++,p.moveStart("character",1)}else m=r.text.length;u=new a(h,m)}else l=(i||!n)&&f.previousSibling,d=(i||n)&&f.nextSibling,u=d&&s.isCharacterDataNode(d)?new a(d,0):l&&s.isCharacterDataNode(l)?new a(l,l.length):new a(o,s.getNodeIndex(f));return f.parentNode.removeChild(f),u}function r(e,t){var n,i,r,o,a=e.offset,c=s.getDocument(e.node),l=c.body.createTextRange(),d=s.isCharacterDataNode(e.node);return d?(n=e.node,i=n.parentNode):(o=e.node.childNodes,n=o.length>a?o[a]:null,i=e.node),r=c.createElement("span"),r.innerHTML="&#feff;",n?i.insertBefore(r,n):i.appendChild(r),l.moveToElementText(r),l.collapse(!t),i.removeChild(r),d&&l[t?"moveStart":"moveEnd"]("character",a),l}e.requireModules(["DomUtil","DomRange"]);var o,s=e.dom,a=s.DomPosition,c=e.DomRange;if(!e.features.implementsDomRange||e.features.implementsTextRange&&e.config.preferTextRange){if(e.features.implementsTextRange){o=function(e){this.textRange=e,this.refresh()},o.prototype=new c(document),o.prototype.refresh=function(){var e,r,o=t(this.textRange);n(this.textRange)?r=e=i(this.textRange,o,!0,!0):(e=i(this.textRange,o,!0,!1),r=i(this.textRange,o,!1,!1)),this.setStart(e.node,e.offset),this.setEnd(r.node,r.offset)},c.copyComparisonConstants(o);var l=function(){return this}();l.Range===void 0&&(l.Range=o),e.createNativeRange=function(e){return e=e||document,e.body.createTextRange()}}}else(function(){function t(e){for(var t,n=d.length;n--;)t=d[n],e[t]=e.nativeRange[t]}function n(e,t,n,i,r){var o=e.startContainer!==t||e.startOffset!=n,s=e.endContainer!==i||e.endOffset!=r;(o||s)&&(e.setEnd(i,r),e.setStart(t,n))}function i(e){e.nativeRange.detach(),e.detached=!0;for(var t,n=d.length;n--;)t=d[n],e[t]=null}var r,a,l,d=c.rangeProperties;o=function(e){if(!e)throw Error("Range must be specified");this.nativeRange=e,t(this)},c.createPrototypeRange(o,n,i),r=o.prototype,r.selectNode=function(e){this.nativeRange.selectNode(e),t(this)},r.deleteContents=function(){this.nativeRange.deleteContents(),t(this)},r.extractContents=function(){var e=this.nativeRange.extractContents();return t(this),e},r.cloneContents=function(){return this.nativeRange.cloneContents()},r.surroundContents=function(e){this.nativeRange.surroundContents(e),t(this)},r.collapse=function(e){this.nativeRange.collapse(e),t(this)},r.cloneRange=function(){return new o(this.nativeRange.cloneRange())},r.refresh=function(){t(this)},r.toString=function(){return""+this.nativeRange};var u=document.createTextNode("test");s.getBody(document).appendChild(u);var h=document.createRange();h.setStart(u,0),h.setEnd(u,0);try{h.setStart(u,1),a=!0,r.setStart=function(e,n){this.nativeRange.setStart(e,n),t(this)},r.setEnd=function(e,n){this.nativeRange.setEnd(e,n),t(this)},l=function(e){return function(n){this.nativeRange[e](n),t(this)}}}catch(f){a=!1,r.setStart=function(e,n){try{this.nativeRange.setStart(e,n)}catch(i){this.nativeRange.setEnd(e,n),this.nativeRange.setStart(e,n)}t(this)},r.setEnd=function(e,n){try{this.nativeRange.setEnd(e,n)}catch(i){this.nativeRange.setStart(e,n),this.nativeRange.setEnd(e,n)}t(this)},l=function(e,n){return function(i){try{this.nativeRange[e](i)}catch(r){this.nativeRange[n](i),this.nativeRange[e](i)}t(this)}}}r.setStartBefore=l("setStartBefore","setEndBefore"),r.setStartAfter=l("setStartAfter","setEndAfter"),r.setEndBefore=l("setEndBefore","setStartBefore"),r.setEndAfter=l("setEndAfter","setStartAfter"),h.selectNodeContents(u),r.selectNodeContents=h.startContainer==u&&h.endContainer==u&&0==h.startOffset&&h.endOffset==u.length?function(e){this.nativeRange.selectNodeContents(e),t(this)}:function(e){this.setStart(e,0),this.setEnd(e,c.getEndOffset(e))},h.selectNodeContents(u),h.setEnd(u,3);var g=document.createRange();g.selectNodeContents(u),g.setEnd(u,4),g.setStart(u,2),r.compareBoundaryPoints=-1==h.compareBoundaryPoints(h.START_TO_END,g)&1==h.compareBoundaryPoints(h.END_TO_START,g)?function(e,t){return t=t.nativeRange||t,e==t.START_TO_END?e=t.END_TO_START:e==t.END_TO_START&&(e=t.START_TO_END),this.nativeRange.compareBoundaryPoints(e,t)}:function(e,t){return this.nativeRange.compareBoundaryPoints(e,t.nativeRange||t)},e.util.isHostMethod(h,"createContextualFragment")&&(r.createContextualFragment=function(e){return this.nativeRange.createContextualFragment(e)}),s.getBody(document).removeChild(u),h.detach(),g.detach()})(),e.createNativeRange=function(e){return e=e||document,e.createRange()};e.features.implementsTextRange&&(o.rangeToTextRange=function(e){if(e.collapsed){var t=r(new a(e.startContainer,e.startOffset),!0);return t}var n=r(new a(e.startContainer,e.startOffset),!0),i=r(new a(e.endContainer,e.endOffset),!1),o=s.getDocument(e.startContainer).body.createTextRange();return o.setEndPoint("StartToStart",n),o.setEndPoint("EndToEnd",i),o}),o.prototype.getName=function(){return"WrappedRange"},e.WrappedRange=o,e.createRange=function(t){return t=t||document,new o(e.createNativeRange(t))},e.createRangyRange=function(e){return e=e||document,new c(e)},e.createIframeRange=function(t){return e.createRange(s.getIframeDocument(t))},e.createIframeRangyRange=function(t){return e.createRangyRange(s.getIframeDocument(t))},e.addCreateMissingNativeApiListener(function(t){var n=t.document;n.createRange===void 0&&(n.createRange=function(){return e.createRange(this)}),n=t=null})}),rangy.createModule("WrappedSelection",function(e,t){function n(e){return(e||window).getSelection()}function i(e){return(e||window).document.selection}function r(e,t,n){var i=n?"end":"start",r=n?"start":"end";e.anchorNode=t[i+"Container"],e.anchorOffset=t[i+"Offset"],e.focusNode=t[r+"Container"],e.focusOffset=t[r+"Offset"]}function o(e){var t=e.nativeSelection;e.anchorNode=t.anchorNode,e.anchorOffset=t.anchorOffset,e.focusNode=t.focusNode,e.focusOffset=t.focusOffset}function s(e){e.anchorNode=e.focusNode=null,e.anchorOffset=e.focusOffset=0,e.rangeCount=0,e.isCollapsed=!0,e._ranges.length=0}function a(t){var n;return t instanceof S?(n=t._selectionNativeRange,n||(n=e.createNativeRange(_.getDocument(t.startContainer)),n.setEnd(t.endContainer,t.endOffset),n.setStart(t.startContainer,t.startOffset),t._selectionNativeRange=n,t.attachListener("detach",function(){this._selectionNativeRange=null}))):t instanceof R?n=t.nativeRange:e.features.implementsDomRange&&t instanceof _.getWindow(t.startContainer).Range&&(n=t),n}function c(e){if(!e.length||1!=e[0].nodeType)return!1;for(var t=1,n=e.length;n>t;++t)if(!_.isAncestorOf(e[0],e[t]))return!1;return!0}function l(e){var t=e.getNodes();if(!c(t))throw Error("getSingleElementFromRange: range "+e.inspect()+" did not consist of a single element");return t[0]}function d(e){return!!e&&e.text!==void 0}function u(e,t){var n=new R(t);e._ranges=[n],r(e,n,!1),e.rangeCount=1,e.isCollapsed=n.collapsed}function h(t){if(t._ranges.length=0,"None"==t.docSelection.type)s(t);else{var n=t.docSelection.createRange();if(d(n))u(t,n);else{t.rangeCount=n.length;for(var i,o=_.getDocument(n.item(0)),a=0;t.rangeCount>a;++a)i=e.createRange(o),i.selectNode(n.item(a)),t._ranges.push(i);t.isCollapsed=1==t.rangeCount&&t._ranges[0].collapsed,r(t,t._ranges[t.rangeCount-1],!1) }}}function f(e,t){for(var n=e.docSelection.createRange(),i=l(t),r=_.getDocument(n.item(0)),o=_.getBody(r).createControlRange(),s=0,a=n.length;a>s;++s)o.add(n.item(s));try{o.add(i)}catch(c){throw Error("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)")}o.select(),h(e)}function g(e,t,n){this.nativeSelection=e,this.docSelection=t,this._ranges=[],this.win=n,this.refresh()}function m(e,t){for(var n,i=_.getDocument(t[0].startContainer),r=_.getBody(i).createControlRange(),o=0;rangeCount>o;++o){n=l(t[o]);try{r.add(n)}catch(s){throw Error("setRanges(): Element within the one of the specified Ranges could not be added to control selection (does it have layout?)")}}r.select(),h(e)}function p(e,t){if(e.anchorNode&&_.getDocument(e.anchorNode)!==_.getDocument(t))throw new b("WRONG_DOCUMENT_ERR")}function C(e){var t=[],n=new O(e.anchorNode,e.anchorOffset),i=new O(e.focusNode,e.focusOffset),r="function"==typeof e.getName?e.getName():"Selection";if(e.rangeCount!==void 0)for(var o=0,s=e.rangeCount;s>o;++o)t[o]=S.inspect(e.getRangeAt(o));return"["+r+"(Ranges: "+t.join(", ")+")(anchor: "+n.inspect()+", focus: "+i.inspect()+"]"}e.requireModules(["DomUtil","DomRange","WrappedRange"]),e.config.checkSelectionRanges=!0;var v,N,E="boolean",y="_rangySelection",_=e.dom,T=e.util,S=e.DomRange,R=e.WrappedRange,b=e.DOMException,O=_.DomPosition,w="Control",D=e.util.isHostMethod(window,"getSelection"),x=e.util.isHostObject(document,"selection"),k=x&&(!D||e.config.preferTextRange);k?(v=i,e.isSelectionValid=function(e){var t=(e||window).document,n=t.selection;return"None"!=n.type||_.getDocument(n.createRange().parentElement())==t}):D?(v=n,e.isSelectionValid=function(){return!0}):t.fail("Neither document.selection or window.getSelection() detected."),e.getNativeSelection=v;var A=v(),P=e.createNativeRange(document),I=_.getBody(document),B=T.areHostObjects(A,["anchorNode","focusNode"]&&T.areHostProperties(A,["anchorOffset","focusOffset"]));e.features.selectionHasAnchorAndFocus=B;var M=T.isHostMethod(A,"extend");e.features.selectionHasExtend=M;var L="number"==typeof A.rangeCount;e.features.selectionHasRangeCount=L;var H=!1,j=!0;T.areHostMethods(A,["addRange","getRangeAt","removeAllRanges"])&&"number"==typeof A.rangeCount&&e.features.implementsDomRange&&function(){var e=document.createElement("iframe");e.frameBorder=0,e.style.position="absolute",e.style.left="-10000px",I.appendChild(e);var t=_.getIframeDocument(e);t.open(),t.write("12"),t.close();var n=_.getIframeWindow(e).getSelection(),i=t.documentElement,r=i.lastChild,o=r.firstChild,s=t.createRange();s.setStart(o,1),s.collapse(!0),n.addRange(s),j=1==n.rangeCount,n.removeAllRanges();var a=s.cloneRange();s.setStart(o,0),a.setEnd(o,2),n.addRange(s),n.addRange(a),H=2==n.rangeCount,s.detach(),a.detach(),I.removeChild(e)}(),e.features.selectionSupportsMultipleRanges=H,e.features.collapsedNonEditableSelectionsSupported=j;var U,Q=!1;I&&T.isHostMethod(I,"createControlRange")&&(U=I.createControlRange(),T.areHostProperties(U,["item","add"])&&(Q=!0)),e.features.implementsControlRange=Q,N=B?function(e){return e.anchorNode===e.focusNode&&e.anchorOffset===e.focusOffset}:function(e){return e.rangeCount?e.getRangeAt(e.rangeCount-1).collapsed:!1};var W;T.isHostMethod(A,"getRangeAt")?W=function(e,t){try{return e.getRangeAt(t)}catch(n){return null}}:B&&(W=function(t){var n=_.getDocument(t.anchorNode),i=e.createRange(n);return i.setStart(t.anchorNode,t.anchorOffset),i.setEnd(t.focusNode,t.focusOffset),i.collapsed!==this.isCollapsed&&(i.setStart(t.focusNode,t.focusOffset),i.setEnd(t.anchorNode,t.anchorOffset)),i}),e.getSelection=function(e){e=e||window;var t=e[y],n=v(e),r=x?i(e):null;return t?(t.nativeSelection=n,t.docSelection=r,t.refresh(e)):(t=new g(n,r,e),e[y]=t),t},e.getIframeSelection=function(t){return e.getSelection(_.getIframeWindow(t))};var F=g.prototype;if(!k&&B&&T.areHostMethods(A,["removeAllRanges","addRange"])){F.removeAllRanges=function(){this.nativeSelection.removeAllRanges(),s(this)};var K=function(t,n){var i=S.getRangeDocument(n),r=e.createRange(i);r.collapseToPoint(n.endContainer,n.endOffset),t.nativeSelection.addRange(a(r)),t.nativeSelection.extend(n.startContainer,n.startOffset),t.refresh()};F.addRange=L?function(t,n){if(Q&&x&&this.docSelection.type==w)f(this,t);else if(n&&M)K(this,t);else{var i;if(H?i=this.rangeCount:(this.removeAllRanges(),i=0),this.nativeSelection.addRange(a(t)),this.rangeCount=this.nativeSelection.rangeCount,this.rangeCount==i+1){if(e.config.checkSelectionRanges){var o=W(this.nativeSelection,this.rangeCount-1);o&&!S.rangesEqual(o,t)&&(t=new R(o))}this._ranges[this.rangeCount-1]=t,r(this,t,z(this.nativeSelection)),this.isCollapsed=N(this)}else this.refresh()}}:function(e,t){t&&M?K(this,e):(this.nativeSelection.addRange(a(e)),this.refresh())},F.setRanges=function(e){if(Q&&e.length>1)m(this,e);else{this.removeAllRanges();for(var t=0,n=e.length;n>t;++t)this.addRange(e[t])}}}else{if(!(T.isHostMethod(A,"empty")&&T.isHostMethod(P,"select")&&Q&&k))return t.fail("No means of selecting a Range or TextRange was found"),!1;F.removeAllRanges=function(){try{if(this.docSelection.empty(),"None"!=this.docSelection.type){var e;if(this.anchorNode)e=_.getDocument(this.anchorNode);else if(this.docSelection.type==w){var t=this.docSelection.createRange();t.length&&(e=_.getDocument(t.item(0)).body.createTextRange())}if(e){var n=e.body.createTextRange();n.select(),this.docSelection.empty()}}}catch(i){}s(this)},F.addRange=function(e){this.docSelection.type==w?f(this,e):(R.rangeToTextRange(e).select(),this._ranges[0]=e,this.rangeCount=1,this.isCollapsed=this._ranges[0].collapsed,r(this,e,!1))},F.setRanges=function(e){this.removeAllRanges();var t=e.length;t>1?m(this,e):t&&this.addRange(e[0])}}F.getRangeAt=function(e){if(0>e||e>=this.rangeCount)throw new b("INDEX_SIZE_ERR");return this._ranges[e]};var V;if(k)V=function(t){var n;e.isSelectionValid(t.win)?n=t.docSelection.createRange():(n=_.getBody(t.win.document).createTextRange(),n.collapse(!0)),t.docSelection.type==w?h(t):d(n)?u(t,n):s(t)};else if(T.isHostMethod(A,"getRangeAt")&&"number"==typeof A.rangeCount)V=function(t){if(Q&&x&&t.docSelection.type==w)h(t);else if(t._ranges.length=t.rangeCount=t.nativeSelection.rangeCount,t.rangeCount){for(var n=0,i=t.rangeCount;i>n;++n)t._ranges[n]=new e.WrappedRange(t.nativeSelection.getRangeAt(n));r(t,t._ranges[t.rangeCount-1],z(t.nativeSelection)),t.isCollapsed=N(t)}else s(t)};else{if(!B||typeof A.isCollapsed!=E||typeof P.collapsed!=E||!e.features.implementsDomRange)return t.fail("No means of obtaining a Range or TextRange from the user's selection was found"),!1;V=function(e){var t,n=e.nativeSelection;n.anchorNode?(t=W(n,0),e._ranges=[t],e.rangeCount=1,o(e),e.isCollapsed=N(e)):s(e)}}F.refresh=function(e){var t=e?this._ranges.slice(0):null;if(V(this),e){var n=t.length;if(n!=this._ranges.length)return!1;for(;n--;)if(!S.rangesEqual(t[n],this._ranges[n]))return!1;return!0}};var X=function(e,t){var n=e.getAllRanges(),i=!1;e.removeAllRanges();for(var r=0,o=n.length;o>r;++r)i||t!==n[r]?e.addRange(n[r]):i=!0;e.rangeCount||s(e)};F.removeRange=Q?function(e){if(this.docSelection.type==w){for(var t,n=this.docSelection.createRange(),i=l(e),r=_.getDocument(n.item(0)),o=_.getBody(r).createControlRange(),s=!1,a=0,c=n.length;c>a;++a)t=n.item(a),t!==i||s?o.add(n.item(a)):s=!0;o.select(),h(this)}else X(this,e)}:function(e){X(this,e)};var z;!k&&B&&e.features.implementsDomRange?(z=function(e){var t=!1;return e.anchorNode&&(t=1==_.comparePoints(e.anchorNode,e.anchorOffset,e.focusNode,e.focusOffset)),t},F.isBackwards=function(){return z(this)}):z=F.isBackwards=function(){return!1},F.toString=function(){for(var e=[],t=0,n=this.rangeCount;n>t;++t)e[t]=""+this._ranges[t];return e.join("")},F.collapse=function(t,n){p(this,t);var i=e.createRange(_.getDocument(t));i.collapseToPoint(t,n),this.removeAllRanges(),this.addRange(i),this.isCollapsed=!0},F.collapseToStart=function(){if(!this.rangeCount)throw new b("INVALID_STATE_ERR");var e=this._ranges[0];this.collapse(e.startContainer,e.startOffset)},F.collapseToEnd=function(){if(!this.rangeCount)throw new b("INVALID_STATE_ERR");var e=this._ranges[this.rangeCount-1];this.collapse(e.endContainer,e.endOffset)},F.selectAllChildren=function(t){p(this,t);var n=e.createRange(_.getDocument(t));n.selectNodeContents(t),this.removeAllRanges(),this.addRange(n)},F.deleteFromDocument=function(){if(Q&&x&&this.docSelection.type==w){for(var e,t=this.docSelection.createRange();t.length;)e=t.item(0),t.remove(e),e.parentNode.removeChild(e);this.refresh()}else if(this.rangeCount){var n=this.getAllRanges();this.removeAllRanges();for(var i=0,r=n.length;r>i;++i)n[i].deleteContents();this.addRange(n[r-1])}},F.getAllRanges=function(){return this._ranges.slice(0)},F.setSingleRange=function(e){this.setRanges([e])},F.containsNode=function(e,t){for(var n=0,i=this._ranges.length;i>n;++n)if(this._ranges[n].containsNode(e,t))return!0;return!1},F.toHtml=function(){var e="";if(this.rangeCount){for(var t=S.getRangeDocument(this._ranges[0]).createElement("div"),n=0,i=this._ranges.length;i>n;++n)t.appendChild(this._ranges[n].cloneContents());e=t.innerHTML}return e},F.getName=function(){return"WrappedSelection"},F.inspect=function(){return C(this)},F.detach=function(){this.win[y]=null,this.win=this.anchorNode=this.focusNode=null},g.inspect=C,e.Selection=g,e.selectionPrototype=F,e.addCreateMissingNativeApiListener(function(t){t.getSelection===void 0&&(t.getSelection=function(){return e.getSelection(this)}),t=null})}),"function"!=typeof String.prototype.trim&&(String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}),"indexOf"in Array.prototype||(Array.prototype.indexOf=function(e,t){void 0===t&&(t=0),0>t&&(t+=this.length),0>t&&(t=0);for(var n=this.length;n>t;t++)if(t in this&&this[t]===e)return t;return-1}),"lastIndexOf"in Array.prototype||(Array.prototype.lastIndexOf=function(e,t){for(void 0===t&&(t=this.length-1),0>t&&(t+=this.length),t>this.length-1&&(t=this.length-1),t++;t-->0;)if(t in this&&this[t]===e)return t;return-1}),"map"in Array.prototype||(Array.prototype.map=function(e,t){for(var n=Array(this.length),i=0,r=this.length;r>i;i++)i in this&&(n[i]=e.call(t,this[i],i,this));return n}),"filter"in Array.prototype||(Array.prototype.filter=function(e,t){for(var n,i=[],r=0,o=this.length;o>r;r++)r in this&&e.call(t,n=this[r],r,this)&&i.push(n);return i}),function(){var e,t,n=this;e={changeIdAttribute:"data-cid",userIdAttribute:"data-userid",userNameAttribute:"data-username",timeAttribute:"data-time",attrValuePrefix:"",blockEl:"p",blockEls:["p","ol","ul","li","h1","h2","h3","h4","h5","h6","blockquote"],stylePrefix:"cts",currentUser:{id:null,name:null},changeTypes:{insertType:{tag:"span",alias:"ins",action:"Inserted"},deleteType:{tag:"span",alias:"del",action:"Deleted"}},handleEvents:!1,contentEditable:!0,isTracking:!0,noTrack:".ice-no-track",avoid:".ice-avoid",mergeBlocks:!0},t=function(t){if(this._changes={},t||(t={}),!t.element)throw Error("`options.element` must be defined for ice construction.");ice.dom.extend(!0,this,e,t),this.pluginsManager=new ice.IcePluginManager(this),t.plugins&&this.pluginsManager.usePlugins("ice-init",t.plugins)},t.prototype={_userStyles:{},_styles:{},_uniqueStyleIndex:0,_browserType:null,_batchChangeid:null,_uniqueIDIndex:1,_delBookmark:"tempdel",isPlaceHoldingDeletes:!1,startTracking:function(){if(this.element.setAttribute("contentEditable",this.contentEditable),this.handleEvents){var e=this;ice.dom.bind(e.element,"keyup.ice keydown.ice keypress.ice mousedown.ice mouseup.ice",function(t){return e.handleEvent(t)})}return this.initializeEnvironment(),this.initializeEditor(),this.initializeRange(),this.pluginsManager.fireEnabled(this.element),this},stopTracking:function(){if(this.element.setAttribute("contentEditable",!this.contentEditable),this.handleEvents){var e=this;ice.dom.unbind(e.element,"keyup.ice keydown.ice keypress.ice mousedown.ice mouseup.ice")}return this.pluginsManager.fireDisabled(this.element),this},initializeEnvironment:function(){this.env||(this.env={}),this.env.element=this.element,this.env.document=this.element.ownerDocument,this.env.window=this.env.document.defaultView||this.env.document.parentWindow||window,this.env.frame=this.env.window.frameElement,this.env.selection=this.selection=new ice.Selection(this.env),this.env.document.createElement(this.changeTypes.insertType.tag),this.env.document.createElement(this.changeTypes.deleteType.tag)},initializeRange:function(){var e=this.selection.createRange();e.setStart(ice.dom.find(this.element,this.blockEls.join(", "))[0],0),e.collapse(!0),this.selection.addRange(e),this.env.frame?this.env.frame.contentWindow.focus():this.element.focus()},initializeEditor:function(){var e=this,t=this.env.document.createElement("div");this.element.childNodes.length?(t.innerHTML=this.element.innerHTML,ice.dom.removeWhitespace(t),""===t.innerHTML&&t.appendChild(ice.dom.create("<"+this.blockEl+" >
    "))):t.appendChild(ice.dom.create("<"+this.blockEl+" >
    ")),this.element.innerHTML=t.innerHTML;var n=[];for(var i in this.changeTypes)n.push(this._getIceNodeClass(i));ice.dom.each(ice.dom.find(this.element,"."+n.join(", .")),function(t,i){for(var r=0,o="",s=i.className.split(" "),t=0;s.length>t;t++){var a=RegExp(e.stylePrefix+"-(\\d+)").exec(s[t]);a&&(r=a[1]);var c=RegExp("("+n.join("|")+")").exec(s[t]);c&&(o=e._getChangeTypeFromAlias(c[1]))}var l=ice.dom.attr(i,e.userIdAttribute);e.setUserStyle(l,Number(r));var d=ice.dom.attr(i,e.changeIdAttribute);e._changes[d]={type:o,userid:l,username:ice.dom.attr(i,e.userNameAttribute),time:ice.dom.attr(i,e.timeAttribute)}})},enableChangeTracking:function(){this.isTracking=!0,this.pluginsManager.fireEnabled(this.element)},disableChangeTracking:function(){this.isTracking=!1,this.pluginsManager.fireDisabled(this.element)},setCurrentUser:function(e){this.currentUser=e},handleEvent:function(e){if(this.isTracking)if("mouseup"==e.type){var t=this;setTimeout(function(){t.mouseUp(e)},200)}else{if("mousedown"==e.type)return this.mouseDown(e);if("keypress"==e.type){var n=this.keyPress(e);return n||e.preventDefault(),n}if("keydown"==e.type){var n=this.keyDown(e);return n||e.preventDefault(),n}"keyup"==e.type&&this.pluginsManager.fireCaretUpdated()}},createIceNode:function(e,t){var n=this.env.document.createElement(this.changeTypes[e].tag);return ice.dom.addClass(n,this._getIceNodeClass(e)),n.appendChild(t?t:this.env.document.createTextNode("")),this.addChange(this.changeTypes[e].alias,[n]),this.pluginsManager.fireNodeCreated(n,{action:this.changeTypes[e].action}),n},insert:function(e,t){var n=!e;if(e||(e=""),t?this.selection.addRange(t):t=this.getCurrentRange(),"string"==typeof e&&(e=document.createTextNode(e)),!t.collapsed&&(this.deleteContents(),t=this.getCurrentRange(),t.startContainer===t.endContainer&&this.element===t.startContainer)){ice.dom.empty(this.element);var i=t.getLastSelectableChild(this.element);t.setStartAfter(i),t.collapse(!0)}this._moveRangeToValidTrackingPos(t);var r=this.startBatchChange();return this._insertNode(e,t,n),this.pluginsManager.fireNodeInserted(e,t),this.endBatchChange(r),n},placeholdDeletes:function(){var e=this;this.isPlaceholdingDeletes&&this.revertDeletePlaceholders(),this.isPlaceholdingDeletes=!0,this._deletes=[];var t="."+this._getIceNodeClass("deleteType");return ice.dom.each(ice.dom.find(this.element,t),function(t,n){e._deletes.push(ice.dom.cloneNode(n)),ice.dom.replaceWith(n,"<"+e._delBookmark+' data-allocation="'+(e._deletes.length-1)+'"/>')}),!0},revertDeletePlaceholders:function(){var e=this;return this.isPlaceholdingDeletes?(ice.dom.each(this._deletes,function(t,n){ice.dom.find(e.element,e._delBookmark+"[data-allocation="+t+"]").replaceWith(n)}),this.isPlaceholdingDeletes=!1,!0):!1},deleteContents:function(e,t){var n=!0;t?this.selection.addRange(t):t=this.getCurrentRange();var i=this.startBatchChange(this.changeTypes.deleteType.alias);return t.collapsed===!1?this._deleteSelection(t):n=e?this._deleteRight(t):this._deleteLeft(t),this.selection.addRange(t),this.endBatchChange(i),n},getChanges:function(){return this._changes},getChangeUserids:function(){var e=[],t=Object.keys(this._changes);for(var n in t)e.push(this._changes[t[n]].userid);return e.sort().filter(function(e,t,n){return t==n.indexOf(e)?1:0})},getElementContent:function(){return this.element.innerHTML},getCleanContent:function(e,t,n){var i="",r=this;ice.dom.each(this.changeTypes,function(e,t){"deleteType"!=e&&(t>0&&(i+=","),i+="."+r._getIceNodeClass(e))}),e=e?"string"==typeof e?ice.dom.create("
    "+e+"
    "):ice.dom.cloneNode(e,!1)[0]:ice.dom.cloneNode(this.element,!1)[0],e=n?n.call(this,e):e;var o=ice.dom.find(e,i);ice.dom.each(o,function(){ice.dom.replaceWith(this,ice.dom.contents(this))});var s=ice.dom.find(e,"."+this._getIceNodeClass("deleteType"));return ice.dom.remove(s),e=t?t.call(this,e):e,e.innerHTML},acceptAll:function(){this.element.innerHTML=this.getCleanContent()},rejectAll:function(){var e="."+this._getIceNodeClass("insertType"),t="."+this._getIceNodeClass("deleteType");ice.dom.remove(ice.dom.find(this.element,e)),ice.dom.each(ice.dom.find(this.element,t),function(e,t){ice.dom.replaceWith(t,ice.dom.contents(t))})},acceptChange:function(e){this.acceptRejectChange(e,!0)},rejectChange:function(e){this.acceptRejectChange(e,!1)},acceptRejectChange:function(e,t){var n,i,r,o,s,a,c,l=ice.dom;if(!e){var d=this.getCurrentRange();if(!d.collapsed)return;e=d.startContainer}n=o="."+this._getIceNodeClass("deleteType"),i=s="."+this._getIceNodeClass("insertType"),r=n+","+i,a=l.getNode(e,r),c=l.find(this.element,"["+this.changeIdAttribute+"="+l.attr(a,this.changeIdAttribute)+"]"),t||(o=i,s=n),ice.dom.is(a,s)?l.each(c,function(e,t){l.replaceWith(t,ice.dom.contents(t))}):l.is(a,o)&&l.remove(c)},isInsideChange:function(e){var t="."+this._getIceNodeClass("insertType")+", ."+this._getIceNodeClass("deleteType");if(!e){if(range=this.getCurrentRange(),!range.collapsed)return!1;e=range.startContainer}return!!ice.dom.getNode(e,t)},addChangeType:function(e,t,n,i){var r={tag:t,alias:n};i&&(r.action=i),this.changeTypes[e]=r},getIceNode:function(e,t){var n="."+this._getIceNodeClass(t);return ice.dom.getNode(e,n)},_moveRangeToValidTrackingPos:function(e){for(var t=!1,n=this._getVoidElement(e.endContainer);n;){try{e.moveEnd(ice.dom.CHARACTER_UNIT,1),e.moveEnd(ice.dom.CHARACTER_UNIT,-1)}catch(i){t=!0}if(t||ice.dom.onBlockBoundary(e.endContainer,e.startContainer,this.blockEls)){e.setStartAfter(n),e.collapse(!0);break}n=this._getVoidElement(e.endContainer),n?(e.setEnd(e.endContainer,0),e.moveEnd(ice.dom.CHARACTER_UNIT,ice.dom.getNodeCharacterLength(e.endContainer)),e.collapse()):(e.setStart(e.endContainer,0),e.collapse(!0))}},_getNoTrackElement:function(e){var t=this._getNoTrackSelector(),n=ice.dom.is(e,t)?e:ice.dom.parents(e,t)[0]||null;return n},_getNoTrackSelector:function(){return this.noTrack},_getVoidElement:function(e){var t=this._getVoidElSelector();return ice.dom.is(e,t)?e:ice.dom.parents(e,t)[0]||null},_getVoidElSelector:function(){return"."+this._getIceNodeClass("deleteType")+","+this.avoid},_currentUserIceNode:function(e){return ice.dom.attr(e,this.userIdAttribute)==this.currentUser.id},_getChangeTypeFromAlias:function(e){var t,n=null;for(t in this.changeTypes)this.changeTypes.hasOwnProperty(t)&&this.changeTypes[t].alias==e&&(n=t);return n},_getIceNodeClass:function(e){return this.attrValuePrefix+this.changeTypes[e].alias},getUserStyle:function(e){var t=null;return t=this._userStyles[e]?this._userStyles[e]:this.setUserStyle(e,this.getNewStyleId())},setUserStyle:function(e,t){var n=this.stylePrefix+"-"+t;return this._styles[t]||(this._styles[t]=!0),this._userStyles[e]=n},getNewStyleId:function(){var e=++this._uniqueStyleIndex;return this._styles[e]?this.getNewStyleId():(this._styles[e]=!0,e)},addChange:function(e,t){var n=this._batchChangeid||this.getNewChangeId();this._changes[n]||(this._changes[n]={type:this._getChangeTypeFromAlias(e),time:(new Date).getTime(),userid:this.currentUser.id,username:this.currentUser.name});var i=this;return ice.dom.foreach(t,function(e){i.addNodeToChange(n,t[e])}),n},addNodeToChange:function(e,t){null!==this._batchChangeid&&(e=this._batchChangeid);var n=this.getChange(e);t.getAttribute(this.changeIdAttribute)||t.setAttribute(this.changeIdAttribute,e),t.getAttribute(this.userIdAttribute)||t.setAttribute(this.userIdAttribute,n.userid),t.getAttribute(this.userNameAttribute)||t.setAttribute(this.userNameAttribute,n.username),t.getAttribute(this.timeAttribute)||t.setAttribute(this.timeAttribute,n.time),ice.dom.hasClass(t,this._getIceNodeClass(n.type))||ice.dom.addClass(t,this._getIceNodeClass(n.type));var i=this.getUserStyle(n.userid);ice.dom.hasClass(t,i)||ice.dom.addClass(t,i)},getChange:function(e){var t=null;return this._changes[e]&&(t=this._changes[e]),t},getNewChangeId:function(){var e=++this._uniqueIDIndex;return this._changes[e]&&(e=this.getNewChangeId()),e},startBatchChange:function(){return this._batchChangeid=this.getNewChangeId(),this._batchChangeid},endBatchChange:function(e){e===this._batchChangeid&&(this._batchChangeid=null)},getCurrentRange:function(){return this.selection.getRangeAt(0)},_insertNode:function(e,t,n){ice.dom.isBlockElement(t.startContainer)||ice.dom.canContainTextElement(ice.dom.getBlockParent(t.startContainer,this.element))||!t.startContainer.previousSibling||t.setStart(t.startContainer.previousSibling,0),t.startContainer;var i=ice.dom.isBlockElement(t.startContainer)&&t.startContainer||ice.dom.getBlockParent(t.startContainer,this.element)||null;if(i===this.element){var r=document.createElement(this.blockEl);return i.appendChild(r),t.setStart(r,0),t.collapse(),this._insertNode(e,t,n)}ice.dom.hasNoTextOrStubContent(i)&&(ice.dom.empty(i),ice.dom.append(i,"
    "),t.setStart(i,0));var o=this.getIceNode(t.startContainer,"insertType"),s=this._currentUserIceNode(o);n&&s||(s||(e=this.createIceNode("insertType",e)),t.insertNode(e),t.setEnd(e,1),n?t.setStart(e,0):t.collapse(),this.selection.addRange(t))},_handleVoidEl:function(e,t){var n=this._getVoidElement(e);return n&&!this.getIceNode(n,"deleteType")?(t.collapse(!0),!0):!1},_deleteSelection:function(e){for(var t=new ice.Bookmark(this.env,e),n=ice.dom.getElementsBetween(t.start,t.end),i=ice.dom.parents(e.startContainer,this.blockEls.join(", "))[0],r=ice.dom.parents(e.endContainer,this.blockEls.join(", "))[0],o=[],s=0;n.length>s;s++){var a=n[s];if(!ice.dom.isBlockElement(a)||(o.push(a),ice.dom.canContainTextElement(a))){if((a.nodeType!==ice.dom.TEXT_NODE||0!==ice.dom.getNodeTextContent(a).length)&&!this._getVoidElement(a)){if(a.nodeType!==ice.dom.TEXT_NODE){if(ice.dom.BREAK_ELEMENT==ice.dom.getTagName(a))continue;if(ice.dom.isStubElement(a)){this._addNodeTracking(a,!1,!0);continue}for(ice.dom.hasNoTextOrStubContent(a)&&ice.dom.remove(a),j=0;a.childNodes.length>j;j++){var c=a.childNodes[j];n.push(c)}continue}var l=ice.dom.getBlockParent(a);this._addNodeTracking(a,!1,!0,!0),ice.dom.hasNoTextOrStubContent(l)&&ice.dom.remove(l)}}else for(var d=0;a.childNodes.length>d;d++)n.push(a.childNodes[d])}if(this.mergeBlocks&&i!==r){for(;o.length;)ice.dom.mergeContainers(o.shift(),i);ice.dom.removeBRFromChild(r),ice.dom.removeBRFromChild(i),ice.dom.mergeContainers(r,i)}t.selectBookmark(),e.collapse(!1)},_deleteRight:function(e){var t,n,i=ice.dom.isBlockElement(e.startContainer)&&e.startContainer||ice.dom.getBlockParent(e.startContainer,this.element)||null,r=i?ice.dom.hasNoTextOrStubContent(i):!1,o=i&&ice.dom.getNextContentNode(i,this.element),s=o?ice.dom.hasNoTextOrStubContent(o):!1,a=e.endContainer,c=e.endOffset,l=e.commonAncestorContainer;if(r)return!1;if(l.nodeType!==ice.dom.TEXT_NODE){if(0===c&&ice.dom.isBlockElement(l)&&!ice.dom.canContainTextElement(l)){var d=l.firstElementChild;if(d)return e.setStart(d,0),e.collapse(),this._deleteRight(e)}if(l.childNodes.length>c){var u=document.createTextNode(" ");return l.insertBefore(u,l.childNodes[c]),e.setStart(u,1),e.collapse(!0),n=this._deleteRight(e),ice.dom.remove(u),n}return t=ice.dom.getNextContentNode(l,this.element),e.setEnd(t,0),e.collapse(),this._deleteRight(e)}if(e.moveEnd(ice.dom.CHARACTER_UNIT,1),e.moveEnd(ice.dom.CHARACTER_UNIT,-1),c===a.data.length&&!ice.dom.hasNoTextOrStubContent(a)){if(t=ice.dom.getNextNode(a,this.element),!t)return e.selectNodeContents(a),e.collapse(),!1;if(ice.dom.BREAK_ELEMENT==ice.dom.getTagName(t)&&(t=ice.dom.getNextNode(t,this.element)),t.nodeType===ice.dom.TEXT_NODE&&(t=t.parentNode),!t.isContentEditable){n=this._addNodeTracking(t,!1,!1);var h=document.createTextNode("");return t.parentNode.insertBefore(h,t.nextSibling),e.selectNode(h),e.collapse(!0),n}if(this._handleVoidEl(t,e))return!0;if(ice.dom.isChildOf(t,i)&&ice.dom.isStubElement(t))return this._addNodeTracking(t,e,!1)}if(this._handleVoidEl(t,e))return!0;if(this._getNoTrackElement(e.endContainer.parentElement))return e.deleteContents(),!1;if(ice.dom.isOnBlockBoundary(e.startContainer,e.endContainer,this.element)){if(this.mergeBlocks&&ice.dom.is(ice.dom.getBlockParent(t,this.element),this.blockEl)){o!==ice.dom.getBlockParent(e.endContainer,this.element)&&e.setEnd(o,0);for(var f=ice.dom.getElementsBetween(e.startContainer,e.endContainer),g=0;f.length>g;g++)ice.dom.remove(f[g]);var m=e.startContainer,p=e.endContainer;return ice.dom.remove(ice.dom.find(m,"br")),ice.dom.remove(ice.dom.find(p,"br")),ice.dom.mergeBlockWithSibling(e,ice.dom.getBlockParent(e.endContainer,this.element)||i)}return s?(ice.dom.remove(o),e.collapse(!0),!0):(e.setStart(o,0),e.collapse(!0),!0)}var C=e.endContainer,v=C.splitText(e.endOffset);return v.splitText(1),this._addNodeTracking(v,e,!1)},_deleteLeft:function(e){var t,n,i=ice.dom.isBlockElement(e.startContainer)&&e.startContainer||ice.dom.getBlockParent(e.startContainer,this.element)||null,r=i?ice.dom.hasNoTextOrStubContent(i):!1,o=i&&ice.dom.getPrevContentNode(i,this.element),s=o?ice.dom.hasNoTextOrStubContent(o):!1,a=e.startContainer,c=e.startOffset,l=e.commonAncestorContainer;if(r)return!1;if(0===c||l.nodeType!==ice.dom.TEXT_NODE){if(ice.dom.isBlockElement(l)&&!ice.dom.canContainTextElement(l))if(0===c){var d=l.firstElementChild;if(d)return e.setStart(d,0),e.collapse(),this._deleteLeft(e)}else{var u=l.lastElementChild;if(u&&(t=e.getLastSelectableChild(u)))return e.setStart(t,t.data.length),e.collapse(),this._deleteLeft(e)}if(n=0===c?ice.dom.getPrevContentNode(a,this.element):l.childNodes[c-1],!n)return!1;if(ice.dom.is(n,"."+this._getIceNodeClass("insertType")+", ."+this._getIceNodeClass("deleteType"))&&n.childNodes.length>0&&n.lastChild&&(n=n.lastChild),n.nodeType===ice.dom.TEXT_NODE&&(n=n.parentNode),!n.isContentEditable){var h=this._addNodeTracking(n,!1,!0),f=document.createTextNode("");return n.parentNode.insertBefore(f,n),e.selectNode(f),e.collapse(!0),h}if(this._handleVoidEl(n,e))return!0;if(ice.dom.isStubElement(n)&&ice.dom.isChildOf(n,i)||!n.isContentEditable)return this._addNodeTracking(n,e,!0);if(ice.dom.isStubElement(n))return ice.dom.remove(n),e.collapse(!0),!1;if(n!==i&&!ice.dom.isChildOf(n,i)){if(ice.dom.canContainTextElement(n)||(n=n.lastElementChild),n.lastChild&&n.lastChild.nodeType!==ice.dom.TEXT_NODE&&ice.dom.isStubElement(n.lastChild)&&"BR"!==n.lastChild.tagName)return e.setStartAfter(n.lastChild),e.collapse(!0),!0;if(t=e.getLastSelectableChild(n),t&&!ice.dom.isOnBlockBoundary(e.startContainer,t,this.element))return e.selectNodeContents(t),e.collapse(),!0}}if(1===c&&!ice.dom.isBlockElement(l)&&e.startContainer.childNodes.length>1&&e.startContainer.childNodes[0].nodeType===ice.dom.TEXT_NODE&&0===e.startContainer.childNodes[0].data.length)return e.setStart(e.startContainer,0),this._deleteLeft(e);if(e.moveStart(ice.dom.CHARACTER_UNIT,-1),e.moveStart(ice.dom.CHARACTER_UNIT,1),this._getNoTrackElement(e.startContainer.parentElement))return e.deleteContents(),!1;if(ice.dom.isOnBlockBoundary(e.startContainer,e.endContainer,this.element)){if(s)return ice.dom.remove(o),e.collapse(),!0;if(this.mergeBlocks&&ice.dom.is(ice.dom.getBlockParent(n,this.element),this.blockEl)){o!==ice.dom.getBlockParent(e.startContainer,this.element)&&e.setStart(o,o.childNodes.length);for(var g=ice.dom.getElementsBetween(e.startContainer,e.endContainer),m=0;g.length>m;m++)ice.dom.remove(g[m]);var p=e.startContainer,C=e.endContainer;return ice.dom.remove(ice.dom.find(p,"br")),ice.dom.remove(ice.dom.find(C,"br")),ice.dom.mergeBlockWithSibling(e,ice.dom.getBlockParent(e.endContainer,this.element)||i)}return o&&o.lastChild&&ice.dom.isStubElement(o.lastChild)?(e.setStartAfter(o.lastChild),e.collapse(!0),!0):(t=e.getLastSelectableChild(o),t?(e.setStart(t,t.data.length),e.collapse(!0)):o&&(e.setStart(o,o.childNodes.length),e.collapse(!0)),!0)}var v=e.startContainer,N=v.splitText(e.startOffset-1);return N.splitText(1),this._addNodeTracking(N,e,!0)},_addNodeTracking:function(e,t,n){var i=this.getIceNode(e,"insertType");if(i&&this._currentUserIceNode(i)){t&&n&&t.selectNode(e),e.parentNode.removeChild(e);var r=ice.dom.cloneNode(i);if(ice.dom.remove(ice.dom.find(r,".iceBookmark")),null!==i&&ice.dom.hasNoTextOrStubContent(r[0])){var o=this.env.document.createTextNode("");ice.dom.insertBefore(i,o),t&&(t.setStart(o,0),t.collapse(!0)),ice.dom.replaceWith(i,ice.dom.contents(i))}return!0}if(t&&this.getIceNode(e,"deleteType")){e.normalize();var s=!1;if(n){for(var a=ice.dom.getPrevContentNode(e,this.element);!s;)d=this.getIceNode(a,"deleteType"),d?a=ice.dom.getPrevContentNode(a,this.element):s=!0;if(a){var c=t.getLastSelectableChild(a);c&&(a=c),t.setStart(a,ice.dom.getNodeCharacterLength(a)),t.collapse(!0)}return!0}for(var l=ice.dom.getNextContentNode(e,this.element);!s;)d=this.getIceNode(l,"deleteType"),d?l=ice.dom.getNextContentNode(l,this.element):s=!0;return l&&(t.selectNodeContents(l),t.collapse(!0)),!0}e.previousSibling&&e.previousSibling.nodeType===ice.dom.TEXT_NODE&&0===e.previousSibling.length&&e.parentNode.removeChild(e.previousSibling),e.nextSibling&&e.nextSibling.nodeType===ice.dom.TEXT_NODE&&0===e.nextSibling.length&&e.parentNode.removeChild(e.nextSibling);var d,u=this.getIceNode(e.previousSibling,"deleteType"),h=this.getIceNode(e.nextSibling,"deleteType");if(u&&this._currentUserIceNode(u)){if(d=u,d.appendChild(e),h&&this._currentUserIceNode(h)){var f=ice.dom.extractContent(h);ice.dom.append(d,f),h.parentNode.removeChild(h)}}else h&&this._currentUserIceNode(h)?(d=h,d.insertBefore(e,d.firstChild)):(d=this.createIceNode("deleteType"),e.parentNode.insertBefore(d,e),d.appendChild(e));return t&&(ice.dom.isStubElement(e)?t.selectNode(e):t.selectNodeContents(e),n?t.collapse(!0):t.collapse(),e.normalize()),!0},_handleAncillaryKey:function(e){var t=e.keyCode,n=!0;switch(e.shiftKey,t){case ice.dom.DOM_VK_DELETE:n=this.deleteContents(),this.pluginsManager.fireKeyPressed(e);break;case 46:n=this.deleteContents(!0),this.pluginsManager.fireKeyPressed(e);break;case ice.dom.DOM_VK_DOWN:case ice.dom.DOM_VK_UP:case ice.dom.DOM_VK_LEFT:case ice.dom.DOM_VK_RIGHT:this.pluginsManager.fireCaretPositioned(),n=!1;break;default:n=!1}return n===!0?(ice.dom.preventDefault(e),!1):!0},keyDown:function(e){if(!this.pluginsManager.fireKeyDown(e))return ice.dom.preventDefault(e),!1;var t=!1;if(this._handleSpecialKey(e)===!1)return ice.dom.isBrowser("msie")!==!0&&(this._preventKeyPress=!0),!1;if(!(e.ctrlKey!==!0&&e.metaKey!==!0||ice.dom.isBrowser("msie")!==!0&&ice.dom.isBrowser("chrome")!==!0||this.pluginsManager.fireKeyPressed(e)))return!1;switch(e.keyCode){case 27:break;default:/Firefox/.test(navigator.userAgent)!==!0&&(t=!this._handleAncillaryKey(e))}return t?(ice.dom.preventDefault(e),!1):!0},keyPress:function(e){if(this._preventKeyPress===!0)return this._preventKeyPress=!1,void 0;var t=null;if(null==e.which?t=String.fromCharCode(e.keyCode):e.which>0&&(t=String.fromCharCode(e.which)),!this.pluginsManager.fireKeyPress(e))return!1;if(e.ctrlKey||e.metaKey)return!0;var n=this.getCurrentRange(),i=ice.dom.parents(n.startContainer,"br")[0]||null;if(i&&(n.moveToNextEl(i),i.parentNode.removeChild(i)),null!==t&&e.ctrlKey!==!0&&e.metaKey!==!0)switch(e.keyCode){case ice.dom.DOM_VK_DELETE:return this._handleAncillaryKey(e); -case ice.dom.DOM_VK_ENTER:return this._handleEnter();default:return this._moveRangeToValidTrackingPos(n,n.startContainer),this.insert()}return this._handleAncillaryKey(e)},_handleEnter:function(){var e=this.getCurrentRange();return e.collapsed||this.deleteContents(),!0},_handleSpecialKey:function(e){var t=e.which;null===t&&(t=e.keyCode);var n=!1;switch(t){case 65:if(e.ctrlKey===!0||e.metaKey===!0){n=!0;var i=this.getCurrentRange();if(ice.dom.isBrowser("msie")===!0){var r=this.env.document.createTextNode(""),o=this.env.document.createTextNode("");this.element.firstChild?ice.dom.insertBefore(this.element.firstChild,r):this.element.appendChild(r),this.element.appendChild(o),i.setStart(r,0),i.setEnd(o,0)}else{i.setStart(i.getFirstSelectableChild(this.element),0);var s=i.getLastSelectableChild(this.element);i.setEnd(s,s.length)}this.selection.addRange(i)}break;default:}return n===!0?(ice.dom.preventDefault(e),!1):!0},mouseUp:function(e){return this.pluginsManager.fireClicked(e)?(this.pluginsManager.fireSelectionChanged(this.getCurrentRange()),void 0):!1},mouseDown:function(e){return this.pluginsManager.fireMouseDown(e)?(this.pluginsManager.fireCaretUpdated(),void 0):!1}},n.ice=this.ice||{},n.ice.InlineChangeEditor=t}.call(this),function(){var e=this,t={};t.DOM_VK_DELETE=8,t.DOM_VK_LEFT=37,t.DOM_VK_UP=38,t.DOM_VK_RIGHT=39,t.DOM_VK_DOWN=40,t.DOM_VK_ENTER=13,t.ELEMENT_NODE=1,t.ATTRIBUTE_NODE=2,t.TEXT_NODE=3,t.CDATA_SECTION_NODE=4,t.ENTITY_REFERENCE_NODE=5,t.ENTITY_NODE=6,t.PROCESSING_INSTRUCTION_NODE=7,t.COMMENT_NODE=8,t.DOCUMENT_NODE=9,t.DOCUMENT_TYPE_NODE=10,t.DOCUMENT_FRAGMENT_NODE=11,t.NOTATION_NODE=12,t.CHARACTER_UNIT="character",t.WORD_UNIT="word",t.BREAK_ELEMENT="br",t.CONTENT_STUB_ELEMENTS=["img","hr","iframe","param","link","meta","input","frame","col","base","area"],t.BLOCK_ELEMENTS=["p","div","pre","ul","ol","li","table","tbody","td","th","fieldset","form","blockquote","dl","dt","dd","dir","center","address","h1","h2","h3","h4","h5","h6"],t.TEXT_CONTAINER_ELEMENTS=["p","div","pre","li","td","th","blockquote","dt","dd","center","address","h1","h2","h3","h4","h5","h6"],t.STUB_ELEMENTS=t.CONTENT_STUB_ELEMENTS.slice(),t.STUB_ELEMENTS.push(t.BREAK_ELEMENT),t.getKeyChar=function(e){return String.fromCharCode(e.which)},t.getClass=function(e,t,n){return t||(t=document.body),e="."+e.split(" ").join("."),n&&(e=n+e),jQuery.makeArray(jQuery(t).find(e))},t.getId=function(e,t){return t||(t=document),element=t.getElementById(e)},t.getTag=function(e,t){return t||(t=document),jQuery.makeArray(jQuery(t).find(e))},t.getElementWidth=function(e){return e.offsetWidth},t.getElementHeight=function(e){return e.offsetHeight},t.getElementDimensions=function(e){var n={width:t.getElementWidth(e),height:t.getElementHeight(e)};return n},t.trim=function(e){return jQuery.trim(e)},t.empty=function(e){return e?jQuery(e).empty():void 0},t.remove=function(e){return e?jQuery(e).remove():void 0},t.prepend=function(e,t){jQuery(e).prepend(t)},t.append=function(e,t){jQuery(e).append(t)},t.insertBefore=function(e,t){jQuery(e).before(t)},t.insertAfter=function(e,t){jQuery(e).after(t)},t.getHtml=function(e){return jQuery(e).html()},t.setHtml=function(e,t){e&&jQuery(e).html(t)},t.removeWhitespace=function(e){jQuery(e).contents().filter(function(){return this.nodeType!=ice.dom.TEXT_NODE&&"UL"==this.nodeName||"OL"==this.nodeName?(t.removeWhitespace(this),!1):this.nodeType!=ice.dom.TEXT_NODE?!1:!/\S/.test(this.nodeValue)}).remove()},t.contents=function(e){return jQuery.makeArray(jQuery(e).contents())},t.extractContent=function(e){for(var t,n=document.createDocumentFragment();t=e.firstChild;)n.appendChild(t);return n},t.getNode=function(e,n){return t.is(e,n)?e:t.parents(e,n)[0]||null},t.getParents=function(e,t,n){for(var i=jQuery(e).parents(t),r=i.length,o=[],s=0;r>s&&i[s]!==n;s++)o.push(i[s]);return o},t.hasBlockChildren=function(e){for(var n=e.childNodes.length,i=0;n>i;i++)if(e.childNodes[i].nodeType===t.ELEMENT_NODE&&t.isBlockElement(e.childNodes[i])===!0)return!0;return!1},t.removeTag=function(e,t){return jQuery(e).find(t).replaceWith(function(){return jQuery(this).contents()}),e},t.stripEnclosingTags=function(e,t){var n=jQuery(e);return n.find("*").not(t).replaceWith(function(){var e,t=jQuery();try{e=jQuery(this),t=e.contents()}catch(n){}return 0===t.length&&e.remove(),t}),n[0]},t.getSiblings=function(e,t,n,i){if(n===!0)return"prev"===t?jQuery(e).prevAll():jQuery(e).nextAll();var r=[];if("prev"===t)for(;e.previousSibling&&(e=e.previousSibling,e!==i);)r.push(e);else for(;e.nextSibling&&(e=e.nextSibling,e!==i);)r.push(e);return r},t.getNodeTextContent=function(e){return jQuery(e).text()},t.getNodeStubContent=function(e){return jQuery(e).find(t.CONTENT_STUB_ELEMENTS.join(", "))},t.hasNoTextOrStubContent=function(e){return t.getNodeTextContent(e).length>0?!1:jQuery(e).find(t.CONTENT_STUB_ELEMENTS.join(", ")).length>0?!1:!0},t.getNodeCharacterLength=function(e){return t.getNodeTextContent(e).length+jQuery(e).find(t.STUB_ELEMENTS.join(", ")).length},t.setNodeTextContent=function(e,t){return jQuery(e).text(t)},t.getTagName=function(e){return e.tagName&&e.tagName.toLowerCase()||null},t.getIframeDocument=function(e){var t=null;return e.contentDocument?t=e.contentDocument:e.contentWindow?t=e.contentWindow.document:e.document&&(t=e.document),t},t.isBlockElement=function(e){return-1!=t.BLOCK_ELEMENTS.lastIndexOf(e.nodeName.toLowerCase())},t.isStubElement=function(e){return-1!=t.STUB_ELEMENTS.lastIndexOf(e.nodeName.toLowerCase())},t.removeBRFromChild=function(e){if(e&&e.hasChildNodes())for(var t=0;e.childNodes.length>t;t++){var n=e.childNodes[t];n&&ice.dom.BREAK_ELEMENT==ice.dom.getTagName(n)&&n.parentNode.removeChild(n)}},t.isChildOf=function(e,t){try{for(;e&&e.parentNode;){if(e.parentNode===t)return!0;e=e.parentNode}}catch(n){}return!1},t.isChildOfTagName=function(e,t){try{for(;e&&e.parentNode;){if(e.parentNode&&e.parentNode.tagName&&e.parentNode.tagName.toLowerCase()===t)return e.parentNode;e=e.parentNode}}catch(n){}return!1},t.isChildOfTagNames=function(e,t){try{for(;e&&e.parentNode;){if(e.parentNode&&e.parentNode.tagName){tagName=e.parentNode.tagName.toLowerCase();for(var n=0;t.length>n;n++)if(tagName===t[n])return e.parentNode}e=e.parentNode}}catch(i){}return null},t.isChildOfClassName=function(e,t){try{for(;e&&e.parentNode;){if(jQuery(e.parentNode).hasClass(t))return e.parentNode;e=e.parentNode}}catch(n){}return null},t.cloneNode=function(e,t){return void 0===t&&(t=!0),jQuery(e).clone(t)},t.bind=function(e,t,n){return jQuery(e).bind(t,n)},t.unbind=function(e,t,n){return jQuery(e).unbind(t,n)},t.attr=function(e,t,n){return n?jQuery(e).attr(t,n):jQuery(e).attr(t)},t.replaceWith=function(e,t){return jQuery(e).replaceWith(t)},t.removeAttr=function(e,t){jQuery(e).removeAttr(t)},t.getElementsBetween=function(e,n){var i=[];if(e===n)return i;if(t.isChildOf(n,e)===!0){for(var r=e.childNodes.length,o=0;r>o&&e.childNodes[o]!==n;o++){if(t.isChildOf(n,e.childNodes[o])===!0)return t.arrayMerge(i,t.getElementsBetween(e.childNodes[o],n));i.push(e.childNodes[o])}return i}for(var s=e.nextSibling;s;){if(t.isChildOf(n,s)===!0)return i=t.arrayMerge(i,t.getElementsBetween(s,n));if(s===n)return i;i.push(s),s=s.nextSibling}for(var a=t.getParents(e),c=t.getParents(n),l=t.arrayDiff(a,c,!0),d=l.length,u=0;d-1>u;u++)i=t.arrayMerge(i,t.getSiblings(l[u],"next"));var h=l[l.length-1];return i=t.arrayMerge(i,t.getElementsBetween(h,n))},t.getCommonAncestor=function(e,n){for(var i=e;i;){if(t.isChildOf(n,i)===!0)return i;i=i.parentNode}return null},t.getNextNode=function(e,n){if(e)for(;e.parentNode;){if(e===n)return null;if(e.nextSibling){if(e.nextSibling.nodeType===t.TEXT_NODE&&0===e.nextSibling.length){e=e.nextSibling;continue}return t.getFirstChild(e.nextSibling)}e=e.parentNode}return null},t.getNextContentNode=function(e,n){if(e)for(;e.parentNode;){if(e===n)return null;if(e.nextSibling&&t.canContainTextElement(t.getBlockParent(e))){if(e.nextSibling.nodeType===t.TEXT_NODE&&0===e.nextSibling.length){e=e.nextSibling;continue}return e.nextSibling}if(e.nextElementSibling)return e.nextElementSibling;e=e.parentNode}return null},t.getPrevNode=function(e,n){if(e)for(;e.parentNode;){if(e===n)return null;if(e.previousSibling){if(e.previousSibling.nodeType===t.TEXT_NODE&&0===e.previousSibling.length){e=e.previousSibling;continue}return t.getLastChild(e.previousSibling)}e=e.parentNode}return null},t.getPrevContentNode=function(e,n){if(e)for(;e.parentNode;){if(e===n)return null;if(e.previousSibling&&t.canContainTextElement(t.getBlockParent(e))){if(e.previousSibling.nodeType===t.TEXT_NODE&&0===e.previousSibling.length){e=e.previousSibling;continue}return e.previousSibling}if(e.previousElementSibling)return e.previousElementSibling;e=e.parentNode}return null},t.canContainTextElement=function(e){return e&&e.nodeName?-1!=t.TEXT_CONTAINER_ELEMENTS.lastIndexOf(e.nodeName.toLowerCase()):!1},t.getFirstChild=function(e){return e.firstChild?e.firstChild.nodeType===t.ELEMENT_NODE?t.getFirstChild(e.firstChild):e.firstChild:e},t.getLastChild=function(e){return e.lastChild?e.lastChild.nodeType===t.ELEMENT_NODE?t.getLastChild(e.lastChild):e.lastChild:e},t.removeEmptyNodes=function(e,n){for(var i=jQuery(e).find(":empty"),r=i.length;r>0;)r--,t.isStubElement(i[r])===!1&&(n&&n.call(this,i[r])===!1||t.remove(i[r]))},t.create=function(e){return jQuery(e)[0]},t.find=function(e,t){return jQuery(e).find(t)},t.children=function(e,t){return jQuery(e).children(t)},t.parent=function(e,t){return jQuery(e).parent(t)[0]},t.parents=function(e,t){return jQuery(e).parents(t)},t.is=function(e,t){return jQuery(e).is(t)},t.extend=function(){return jQuery.extend.apply(this,arguments)},t.walk=function(e,n,i){if(e){i||(i=0);var r=n.call(this,e,i);r!==!1&&(e.childNodes&&e.childNodes.length>0?t.walk(e.firstChild,n,i+1):e.nextSibling?t.walk(e.nextSibling,n,i):e.parentNode&&e.parentNode.nextSibling&&t.walk(e.parentNode.nextSibling,n,i-1))}},t.revWalk=function(e,n){if(e){var i=n.call(this,e);i!==!1&&(e.childNodes&&e.childNodes.length>0?t.walk(e.lastChild,n):e.previousSibling?t.walk(e.previousSibling,n):e.parentNode&&e.parentNode.previousSibling&&t.walk(e.parentNode.previousSibling,n))}},t.setStyle=function(e,t,n){e&&jQuery(e).css(t,n)},t.getStyle=function(e,t){return jQuery(e).css(t)},t.hasClass=function(e,t){return jQuery(e).hasClass(t)},t.addClass=function(e,t){jQuery(e).addClass(t)},t.removeClass=function(e,t){jQuery(e).removeClass(t)},t.preventDefault=function(e){e.preventDefault(),t.stopPropagation(e)},t.stopPropagation=function(e){e.stopPropagation()},t.noInclusionInherits=function(e,n){(n instanceof String||"string"==typeof n)&&(n=window[n]),(e instanceof String||"string"==typeof e)&&(e=window[e]);var i=function(){};if(t.isset(n)===!0)for(value in n.prototype)e.prototype[value]?i.prototype[value]=n.prototype[value]:e.prototype[value]=n.prototype[value];e.prototype&&(i.prototype.constructor=n,e.prototype["super"]=new i)},t.each=function(e,t){jQuery.each(e,function(e,n){t.call(this,e,n)})},t.foreach=function(e,t){if(e instanceof Array||e instanceof NodeList||e.length!==void 0&&e.item!==void 0)for(var n=e.length,i=0;n>i;i++){var r=t.call(this,i,e[i]);if(r===!1)break}else for(var o in e)if(e.hasOwnProperty(o)===!0){var r=t.call(this,o);if(r===!1)break}},t.isBlank=function(e){return!e||/^\s*$/.test(e)?!0:!1},t.isFn=function(e){return"function"==typeof e?!0:!1},t.isObj=function(e){return null!==e&&"object"==typeof e?!0:!1},t.isset=function(e){return e!==void 0&&null!==e?!0:!1},t.isArray=function(e){return jQuery.isArray(e)},t.isNumeric=function(e){var t=e.match(/^\d+$/);return null!==t?!0:!1},t.getUniqueId=function(){var e=(new Date).getTime(),t=Math.ceil(1e6*Math.random()),n=e+""+t;return n.substr(5,18).replace(/,/,"")},t.inArray=function(e,t){for(var n=t.length,i=0;n>i;i++)if(e===t[i])return!0;return!1},t.arrayDiff=function(e,n,i){for(var r=e.length,o=[],s=0;r>s;s++)t.inArray(e[s],n)===!1&&o.push(e[s]);if(i!==!0){r=n.length;for(var s=0;r>s;s++)t.inArray(n[s],e)===!1&&o.push(n[s])}return o},t.arrayMerge=function(e,t){for(var n=t.length,i=0;n>i;i++)e.push(t[i]);return e},t.stripTags=function(e,n){if("string"==typeof n){var i=jQuery("
    "+e+"
    ");return i.find("*").not(n).remove(),i.html()}for(var r,o=RegExp(/<\/?(\w+)((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim),s=e;null!=(r=o.exec(e));)(t.isset(n)===!1||t.inArray(r[1],n)!==!0)&&(s=s.replace(r[0],""));return s},t.browser=function(){var e={};return e.version=jQuery.browser.version,jQuery.browser.mozilla===!0?e.type="mozilla":jQuery.browser.msie===!0?e.type="msie":jQuery.browser.opera===!0?e.type="opera":jQuery.browser.webkit===!0&&(e.type="webkit"),e},t.getBrowserType=function(){if(null===this._browserType){for(var e=["msie","firefox","chrome","safari"],t=e.length,n=0;t>n;n++){var i=RegExp(e[n],"i");if(i.test(navigator.userAgent)===!0)return this._browserType=e[n],this._browserType}this._browserType="other"}return this._browserType},t.getWebkitType=function(){if("webkit"!==t.browser().type)return console.log("Not a webkit!"),!1;var e=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0;return e?"safari":"chrome"},t.isBrowser=function(e){return t.browser().type===e},t.getBlockParent=function(e,n){if(t.isBlockElement(e)===!0)return e;if(e)for(;e.parentNode;){if(e=e.parentNode,e===n)return null;if(t.isBlockElement(e)===!0)return e}return null},t.findNodeParent=function(e,n,i){if(e)for(;e.parentNode;){if(e===i)return null;if(t.is(e,n)===!0)return e;e=e.parentNode}return null},t.onBlockBoundary=function(e,n,i){if(!e||!n)return!1;var r=t.isChildOfTagNames(e,i)||t.is(e,i.join(", "))&&e||null,o=t.isChildOfTagNames(n,i)||t.is(n,i.join(", "))&&n||null;return r!==o},t.isOnBlockBoundary=function(e,n,i){if(!e||!n)return!1;var r=t.getBlockParent(e,i)||t.isBlockElement(e,i)&&e||null,o=t.getBlockParent(n,i)||t.isBlockElement(n,i)&&n||null;return r!==o},t.mergeContainers=function(e,n){if(!e||!n)return!1;if(e.nodeType===t.TEXT_NODE||t.isStubElement(e))n.appendChild(e);else if(e.nodeType===t.ELEMENT_NODE){for(;e.firstChild;)n.appendChild(e.firstChild);t.remove(e)}return!0},t.mergeBlockWithSibling=function(e,n,i){var r=i?jQuery(n).next().get(0):jQuery(n).prev().get(0);return i?t.mergeContainers(r,n):t.mergeContainers(n,r),e.collapse(!0),!0},t.date=function(e,n,i){if(null!==n||!i||(n=t.tsIso8601ToTimestamp(i))){for(var r=new Date(n),o=e.split(""),s=o.length,a="",c=0;s>c;c++){var l="",d=o[c];switch(d){case"D":case"l":var u=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];l=u[r.getDay()],"D"===d&&(l=l.substring(0,3));break;case"F":case"m":l=r.getMonth()+1,10>l&&(l="0"+l);break;case"M":months=["January","February","March","April","May","June","July","August","September","October","November","December"],l=months[r.getMonth()],"M"===d&&(l=l.substring(0,3));break;case"d":l=r.getDate();break;case"S":l=t.getOrdinalSuffix(r.getDate());break;case"Y":l=r.getFullYear();break;case"y":l=r.getFullYear(),l=(""+l).substring(2);break;case"H":l=r.getHours();break;case"h":l=r.getHours(),0===l?l=12:l>12&&(l-=12);break;case"i":l=t.addNumberPadding(r.getMinutes());break;case"a":l="am",r.getHours()>=12&&(l="pm");break;default:l=d}a+=l}return a}},t.getOrdinalSuffix=function(e){var t="",n=e%100;if(n>=4&&20>=n)t="th";else switch(e%10){case 1:t="st";break;case 2:t="nd";break;case 3:t="rd";break;default:t="th"}return t},t.addNumberPadding=function(e){return 10>e&&(e="0"+e),e},t.tsIso8601ToTimestamp=function(e){var t=/(\d\d\d\d)(?:-?(\d\d)(?:-?(\d\d)(?:[T ](\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(?:Z|(?:([-+])(\d\d)(?::?(\d\d))?)?)?)?)?)?/,n=e.match(RegExp(t));if(n){var i=new Date;i.setDate(n[3]),i.setFullYear(n[1]),i.setMonth(n[2]-1),i.setHours(n[4]),i.setMinutes(n[5]),i.setSeconds(n[6]);var r=60*n[9];"+"===n[8]&&(r*=-1),r-=i.getTimezoneOffset();var o=i.getTime()+1e3*60*r;return o}return null},e.dom=t}.call(this.ice),function(){var e,t=this;e=function(e,t,n){this.env=e,this.element=e.element,this.selection=this.env.selection,n||this.removeBookmarks(this.element);var i=t||this.selection.getRangeAt(0);t=i.cloneRange();var r=t.startContainer;t.endContainer;var o=t.startOffset;t.endOffset;var s;t.collapse(!1);var a=this.env.document.createElement("span");a.style.display="none",ice.dom.setHtml(a," "),ice.dom.addClass(a,"iceBookmark iceBookmark_end"),a.setAttribute("iceBookmark","end"),t.insertNode(a),ice.dom.isChildOf(a,this.element)||this.element.appendChild(a),t.setStart(r,o),t.collapse(!0);var c=this.env.document.createElement("span");c.style.display="none",ice.dom.addClass(c,"iceBookmark iceBookmark_start"),ice.dom.setHtml(c," "),c.setAttribute("iceBookmark","start");try{t.insertNode(c),c.previousSibling===a&&(s=c,c=a,a=s)}catch(l){ice.dom.insertBefore(a,c)}ice.dom.isChildOf(c,this.element)===!1&&(this.element.firstChild?ice.dom.insertBefore(this.element.firstChild,c):this.element.appendChild(c)),a.previousSibling||(s=this.env.document.createTextNode(""),ice.dom.insertBefore(a,s)),c.nextSibling||(s=this.env.document.createTextNode(""),ice.dom.insertAfter(c,s)),i.setStart(c.nextSibling,0),i.setEnd(a.previousSibling,a.previousSibling.length||0),this.start=c,this.end=a},e.prototype={selectBookmark:function(){var e=this.selection.getRangeAt(0),t=null,n=null,i=0,r=null;if(this.start.nextSibling===this.end||0===ice.dom.getElementsBetween(this.start,this.end).length)this.end.nextSibling?t=ice.dom.getFirstChild(this.end.nextSibling):this.start.previousSibling?(t=ice.dom.getFirstChild(this.start.previousSibling),t.nodeType===ice.dom.TEXT_NODE&&(i=t.length)):(this.end.parentNode.appendChild(this.env.document.createTextNode("")),t=ice.dom.getFirstChild(this.end.nextSibling));else{if(this.start.nextSibling)t=ice.dom.getFirstChild(this.start.nextSibling);else{if(!this.start.previousSibling){var o=this.env.document.createTextNode("");ice.dom.insertBefore(this.start,o)}t=ice.dom.getLastChild(this.start.previousSibling),i=t.length}this.end.previousSibling?n=ice.dom.getLastChild(this.end.previousSibling):(n=ice.dom.getFirstChild(this.end.nextSibling||this.end),r=0)}ice.dom.remove([this.start,this.end]),null===n?(e.setEnd(t,i),e.collapse(!1)):(e.setStart(t,i),null===r&&(r=n.length||0),e.setEnd(n,r));try{this.selection.addRange(e)}catch(s){}},getBookmark:function(e,t){var n=ice.dom.getClass("iceBookmark_"+t,e)[0];return n},removeBookmarks:function(e){ice.dom.remove(ice.dom.getClass("iceBookmark",e,"span"))}},t.Bookmark=e}.call(this.ice),function(){var e,t=this;e=function(e){this._selection=null,this.env=e,this._initializeRangeLibrary(),this._getSelection()},e.prototype={_getSelection:function(){return this._selection?this._selection.refresh():this._selection=this.env.frame?rangy.getIframeSelection(this.env.frame):rangy.getSelection(),this._selection},createRange:function(){return rangy.createRange(this.env.document)},getRangeAt:function(e){this._selection.refresh();try{return this._selection.getRangeAt(e)}catch(t){return this._selection=null,this._getSelection().getRangeAt(0)}},addRange:function(e){this._selection||(this._selection=this._getSelection()),this._selection.setSingleRange(e),this._selection.ranges=[e]},_initializeRangeLibrary:function(){var e=this;rangy.init(),rangy.config.checkSelectionRanges=!1;var t=function(e,t,n,i){if(0===n)throw Error("InvalidArgumentException: units cannot be 0");switch(t){case ice.dom.CHARACTER_UNIT:n>0?e.moveCharRight(i,n):e.moveCharLeft(i,-1*n);break;case ice.dom.WORD_UNIT:default:}};rangy.rangePrototype.moveStart=function(e,n){t(this,e,n,!0)},rangy.rangePrototype.moveEnd=function(e,n){t(this,e,n,!1)},rangy.rangePrototype.setRange=function(e,t,n){e?this.setStart(t,n):this.setEnd(t,n)},rangy.rangePrototype.moveCharLeft=function(e,t){var n,i;if(e?(n=this.startContainer,i=this.startOffset):(n=this.endContainer,i=this.endOffset),n.nodeType===ice.dom.ELEMENT_NODE)if(n.hasChildNodes()){for(n=n.childNodes[i],n=this.getPreviousTextNode(n);n&&n.nodeType==ice.dom.TEXT_NODE&&""===n.nodeValue;)n=this.getPreviousTextNode(n);i=n.data.length-t}else i=-1*t;else i-=t;if(0>i)for(;0>i;){var r=[];if(n=this.getPreviousTextNode(n,r),!n)return;n.nodeType!==ice.dom.ELEMENT_NODE&&(i+=n.data.length)}this.setRange(e,n,i)},rangy.rangePrototype.moveCharRight=function(e,t){var n,i;e?(n=this.startContainer,i=this.startOffset):(n=this.endContainer,i=this.endOffset),n.nodeType===ice.dom.ELEMENT_NODE?(n=n.childNodes[i],n.nodeType!==ice.dom.TEXT_NODE&&(n=this.getNextTextNode(n)),i=t):i+=t;var r=i-n.data.length;if(r>0){for(var o=[];r>0;)if(n=this.getNextContainer(n,o),n.nodeType!==ice.dom.ELEMENT_NODE){if(n.data.length>=r)break;n.data.length>0&&(r-=n.data.length)}i=r}this.setRange(e,n,i)},rangy.rangePrototype.getNextContainer=function(e,t){if(!e)return null;for(;e.nextSibling;)if(e=e.nextSibling,e.nodeType!==ice.dom.TEXT_NODE){var n=this.getFirstSelectableChild(e);if(null!==n)return n}else if(this.isSelectable(e)===!0)return e;for(;e&&!e.nextSibling;)e=e.parentNode;if(!e)return null;if(e=e.nextSibling,this.isSelectable(e)===!0)return e;t&&ice.dom.isBlockElement(e)===!0&&t.push(e);var i=this.getFirstSelectableChild(e);return null!==i?i:this.getNextContainer(e,t)},rangy.rangePrototype.getPreviousContainer=function(e,t){if(!e)return null;for(;e.previousSibling;)if(e=e.previousSibling,e.nodeType!==ice.dom.TEXT_NODE){if(ice.dom.isStubElement(e)===!0)return e;var n=this.getLastSelectableChild(e);if(null!==n)return n}else if(this.isSelectable(e)===!0)return e;for(;e&&!e.previousSibling;)e=e.parentNode;if(!e)return null;if(e=e.previousSibling,this.isSelectable(e)===!0)return e;t&&ice.dom.isBlockElement(e)===!0&&t.push(e);var i=this.getLastSelectableChild(e);return null!==i?i:this.getPreviousContainer(e,t)},rangy.rangePrototype.getNextTextNode=function(e){return e.nodeType===ice.dom.ELEMENT_NODE&&0!==e.childNodes.length?this.getFirstSelectableChild(e):(e=this.getNextContainer(e),e.nodeType===ice.dom.TEXT_NODE?e:this.getNextTextNode(e))},rangy.rangePrototype.getPreviousTextNode=function(e,t){return e=this.getPreviousContainer(e,t),e.nodeType===ice.dom.TEXT_NODE?e:this.getPreviousTextNode(e,t)},rangy.rangePrototype.getFirstSelectableChild=function(e){if(e){if(e.nodeType===ice.dom.TEXT_NODE)return e;for(var t=e.firstChild;t;){if(this.isSelectable(t)===!0)return t;if(t.firstChild){var n=this.getFirstSelectableChild(t);if(null!==n)return n;t=t.nextSibling}else t=t.nextSibling}}return null},rangy.rangePrototype.getLastSelectableChild=function(e){if(e){if(e.nodeType===ice.dom.TEXT_NODE)return e;for(var t=e.lastChild;t;){if(this.isSelectable(t)===!0)return t;if(t.lastChild){var n=this.getLastSelectableChild(t);if(null!==n)return n;t=t.previousSibling}else t=t.previousSibling}}return null},rangy.rangePrototype.isSelectable=function(e){return e&&e.nodeType===ice.dom.TEXT_NODE&&0!==e.data.length?!0:!1},rangy.rangePrototype.getHTMLContents=function(t){t||(t=this.cloneContents());var n=e.env.document.createElement("div");return n.appendChild(t.cloneNode(!0)),n.innerHTML},rangy.rangePrototype.getHTMLContentsObj=function(){return this.cloneContents()}}},t.Selection=e}.call(this.ice),function(){var e=this,t=function(e){this._ice=e};t.prototype={start:function(){},clicked:function(){return!0},mouseDown:function(){return!0},keyDown:function(){return!0},keyPress:function(){return!0},selectionChanged:function(){},setEnabled:function(){},setDisabled:function(){},caretUpdated:function(){},nodeInserted:function(){},nodeCreated:function(){},caretPositioned:function(){},remove:function(){this._ice.removeKeyPressListener(this)},setSettings:function(){}},e.IcePlugin=t}.call(this.ice),function(){var e=this,t=function(e){this.plugins={},this.pluginConstructors={},this.keyPressListeners={},this.activePlugin=null,this.pluginSets={},this.activePluginSet=null,this._ice=e};t.prototype={getPluginNames:function(){var e=[];for(var t in this.plugins)e.push(t);return e},addPluginObject:function(e,t){this.plugins[e]=t},addPlugin:function(e,t){if("function"!=typeof t)throw Error("IcePluginException: plugin must be a constructor function");ice.dom.isset(this.pluginConstructors[e])===!1&&(this.pluginConstructors[e]=t)},loadPlugins:function(e,t){if(0===e.length)t.call(this);else{var n=e.shift();if("object"==typeof n&&(n=n.name),ice.dom.isset(ice._plugin[n])!==!0)throw Error("plugin was not included in the page: "+n);this.addPlugin(n,ice._plugin[n]),this.loadPlugins(e,t)}},_enableSet:function(e){this.activePluginSet=e;for(var t=this.pluginSets[e].length,n=0;t>n;n++){var i=this.pluginSets[e][n],r="";r="object"==typeof i?i.name:i;var o=this.pluginConstructors[r];if(o){var s=new o(this._ice);this.plugins[r]=s,ice.dom.isset(i.settings)===!0&&s.setSettings(i.settings),s.start()}}},setActivePlugin:function(e){this.activePlugin=e},getActivePlugin:function(){return this.activePlugin},_getPluginName:function(e){var t=""+e,n="function ".length,i=t.substr(n,t.indexOf("(")-n);return i},removePlugin:function(e){this.plugins[e]&&this.plugins[e].remove()},getPlugin:function(e){return this.plugins[e]},usePlugins:function(e,t,n){var i=this;this.pluginSets[e]=ice.dom.isset(t)===!0?t:[];var r=this.pluginSets[e].concat([]);this.loadPlugins(r,function(){i._enableSet(e),n&&n.call(this)})},disablePlugin:function(e){this.plugins[e].disable()},isPluginElement:function(e){for(var t in this.plugins)if(this.plugins[t].isPluginElement&&this.plugins[t].isPluginElement(e)===!0)return!0;return!1},fireKeyPressed:function(e){if(this._fireKeyPressFns(e,"all_keys")===!1)return!1;var t=[];switch((e.ctrlKey===!0||e.metaKey===!0)&&t.push("ctrl"),e.shiftKey===!0&&t.push("shift"),e.altKey===!0&&t.push("alt"),e.keyCode){case 13:t.push("enter");break;case ice.dom.DOM_VK_LEFT:t.push("left");break;case ice.dom.DOM_VK_RIGHT:t.push("right");break;case ice.dom.DOM_VK_UP:t.push("up");break;case ice.dom.DOM_VK_DOWN:t.push("down");break;case 9:t.push("tab");break;case ice.dom.DOM_VK_DELETE:t.push("delete");break;default:var n;e.keyCode?n=e.keyCode:e.which&&(n=e.which),n&&t.push(String.fromCharCode(n).toLowerCase())}var i=t.sort().join("+");return this._fireKeyPressFns(e,i)},_fireKeyPressFns:function(e,t){if(this.keyPressListeners[t])for(var n=this.keyPressListeners[t].length,i=0;n>i;i++){var r=this.keyPressListeners[t][i],o=r.fn,s=r.plugin,a=r.data;if(o)if(ice.dom.isFn(o)===!0){if(o.call(s,e,a)===!0)return ice.dom.preventDefault(e),!1}else if(s[o]&&s[o].call(s,e,a)===!0)return ice.dom.preventDefault(e),!1}return!0},fireSelectionChanged:function(e){for(var t in this.plugins)this.plugins[t].selectionChanged(e)},fireNodeInserted:function(e,t){for(var n in this.plugins)if(this.plugins[n].nodeInserted(e,t)===!1)return!1},fireNodeCreated:function(e,t){for(var n in this.plugins)if(this.plugins[n].nodeCreated(e,t)===!1)return!1},fireCaretPositioned:function(){for(var e in this.plugins)this.plugins[e].caretPositioned()},fireClicked:function(e){var t=!0;for(var n in this.plugins)this.plugins[n].clicked(e)===!1&&(t=!1);return t},fireMouseDown:function(e){var t=!0;for(var n in this.plugins)this.plugins[n].mouseDown(e)===!1&&(t=!1);return t},fireKeyDown:function(e){var t=!0;for(var n in this.plugins)this.plugins[n].keyDown(e)===!1&&(t=!1);return t},fireKeyPress:function(e){var t=!0;for(var n in this.plugins)this.plugins[n].keyPress(e)===!1&&(t=!1);return t},fireEnabled:function(e){for(var t in this.plugins)this.plugins[t].setEnabled(e)},fireDisabled:function(e){for(var t in this.plugins)this.plugins[t].setDisabled(e)},fireCaretUpdated:function(){for(var e in this.plugins)this.plugins[e].caretUpdated&&this.plugins[e].caretUpdated()}},e._plugin={},e.IcePluginManager=t}.call(this.ice),function(){var e,t=this;e=function(e){this._ice=e},e.prototype={nodeCreated:function(e,t){e.setAttribute("title",(t.action||"Modified")+" by "+e.getAttribute(this._ice.userNameAttribute)+" - "+ice.dom.date("m/d/Y h:ia",parseInt(e.getAttribute(this._ice.timeAttribute))))}},ice.dom.noInclusionInherits(e,ice.IcePlugin),t._plugin.IceAddTitlePlugin=e}.call(this.ice),function(){var e,t=this;e=function(e){this._ice=e,this._tmpNode=null,this._tmpNodeTagName="icepaste",this._pasteId="icepastediv";var t=this;this.pasteType="formattedClean",this.preserve="p",this.beforePasteClean=function(e){return e},this.afterPasteClean=function(e){return e},e.element.oncopy=function(){return t.handleCopy.apply(t)}},e.prototype={setSettings:function(e){e=e||{},ice.dom.extend(this,e),this.preserve+=","+this._tmpNodeTagName,this.setupPreserved()},keyDown:function(e){return e.metaKey===!0||e.ctrlKey===!0?(86==e.keyCode?this.handlePaste():88==e.keyCode&&this.handleCut(),!0):void 0},keyPress:function(e){var t=null;null==e.which?t=String.fromCharCode(e.keyCode):e.which>0&&(t=String.fromCharCode(e.which));var n=this;return this.cutElement&&"x"===t?ice.dom.isBrowser("webkit")&&n.cutElement.focus():"v"===t&&ice.dom.isBrowser("webkit")&&this._ice.env.document.getElementById(n._pasteId).focus(),!0},handleCopy:function(){},handlePaste:function(){var e=this._ice.getCurrentRange();if(e.collapsed||(this._ice.isTracking?(this._ice.deleteContents(),e=e.cloneRange()):(e.deleteContents(),e.collapse(!0))),this._ice.isTracking&&this._ice._moveRangeToValidTrackingPos(e),e.startContainer==this._ice.element){var t=ice.dom.find(this._ice.element,this._ice.blockEl)[0];t||(t=ice.dom.create("<"+this._ice.blockEl+" >
    "),this._ice.element.appendChild(t)),e.setStart(t,0),e.collapse(!0),this._ice.env.selection.addRange(e)}switch(this._tmpNode=this._ice.env.document.createElement(this._tmpNodeTagName),e.insertNode(this._tmpNode),this.pasteType){case"formatted":this.setupPaste();break;case"formattedClean":this.setupPaste(!0)}return!0},setupPaste:function(e){var t=this.createDiv(this._pasteId),n=this,i=this._ice.getCurrentRange();return i.selectNodeContents(t),this._ice.selection.addRange(i),t.onpaste=function(){setTimeout(function(){n.handlePasteValue(e)},0)},t.focus(),!0},handlePasteValue:function(e){var t=this._ice.env.document,n=t.getElementById(this._pasteId),i=ice.dom.getHtml(n),r=ice.dom.children("
    "+i+"
    ",this._ice.blockEl);1===r.length&&ice.dom.getNodeTextContent("
    "+i+"
    ")===ice.dom.getNodeTextContent(r)&&(i=ice.dom.getHtml(i)),i=this.beforePasteClean.call(this,i),e&&(i=this._ice.getCleanContent(i),i=this.stripPaste(i)),i=this.afterPasteClean.call(this,i),i=ice.dom.trim(i);var o=this._ice.getCurrentRange();o.setStartAfter(this._tmpNode),o.collapse(!0);var s=null,a=null,c=null,l=o.createContextualFragment(i),d=this._ice.startBatchChange();if(ice.dom.hasBlockChildren(l)){var u=ice.dom.isChildOfTagName(this._tmpNode,this._ice.blockEl);o.setEndAfter(u.lastChild),this._ice.selection.addRange(o);var h=o.extractContents(),f=t.createElement(this._ice.blockEl);f.appendChild(h),ice.dom.insertAfter(u,f),o.setStart(f,0),o.collapse(!0),this._ice.selection.addRange(o);for(var g=o.startContainer;l.firstChild;)if(3!==l.firstChild.nodeType||jQuery.trim(l.firstChild.nodeValue))if(ice.dom.isBlockElement(l.firstChild)){if(""!==l.firstChild.textContent){s=null;var m=null;this._ice.isTracking?(m=this._ice.createIceNode("insertType"),this._ice.addChange("insertType",[m]),c=t.createElement(l.firstChild.tagName),m.innerHTML=l.firstChild.innerHTML,c.appendChild(m)):(m=c=t.createElement(l.firstChild.tagName),c.innerHTML=l.firstChild.innerHTML),a=m,ice.dom.insertBefore(g,c)}l.removeChild(l.firstChild)}else s||(c=t.createElement(this._ice.blockEl),ice.dom.insertBefore(g,c),this._ice.isTracking?(s=this._ice.createIceNode("insertType"),this._ice.addChange("insertType",[s]),c.appendChild(s)):s=c),a=s,s.appendChild(l.removeChild(l.firstChild));else l.removeChild(l.firstChild);f.textContent||f.parentNode.removeChild(f)}else if(this._ice.isTracking)c=this._ice.createIceNode("insertType",l),this._ice.addChange("insertType",[c]),o.insertNode(c),a=c;else for(var p;p=l.firstChild;)o.insertNode(p),o.setStartAfter(p),o.collapse(!0),a=p;this._ice.endBatchChange(d),n.remove(),this._cleanup(a)},createDiv:function(e){var t=this._ice.env.document,n=t.getElementById(e);n&&ice.dom.remove(n);var i=t.createElement("div");return i.id=e,i.setAttribute("contentEditable",!0),ice.dom.setStyle(i,"width","1px"),ice.dom.setStyle(i,"height","1px"),ice.dom.setStyle(i,"overflow","hidden"),ice.dom.setStyle(i,"position","fixed"),ice.dom.setStyle(i,"top","10px"),ice.dom.setStyle(i,"left","10px"),i.appendChild(t.createElement("br")),t.body.appendChild(i),i +case ice.dom.DOM_VK_ENTER:return this._handleEnter();default:return this._moveRangeToValidTrackingPos(n,n.startContainer),this.insert()}return this._handleAncillaryKey(e)},_handleEnter:function(){var e=this.getCurrentRange();return e.collapsed||this.deleteContents(),!0},_handleSpecialKey:function(e){var t=e.which;null===t&&(t=e.keyCode);var n=!1;switch(t){case 65:if(e.ctrlKey===!0||e.metaKey===!0){n=!0;var i=this.getCurrentRange();if(ice.dom.isBrowser("msie")===!0){var r=this.env.document.createTextNode(""),o=this.env.document.createTextNode("");this.element.firstChild?ice.dom.insertBefore(this.element.firstChild,r):this.element.appendChild(r),this.element.appendChild(o),i.setStart(r,0),i.setEnd(o,0)}else{i.setStart(i.getFirstSelectableChild(this.element),0);var s=i.getLastSelectableChild(this.element);i.setEnd(s,s.length)}this.selection.addRange(i)}break;default:}return n===!0?(ice.dom.preventDefault(e),!1):!0},mouseUp:function(e){return this.pluginsManager.fireClicked(e)?(this.pluginsManager.fireSelectionChanged(this.getCurrentRange()),void 0):!1},mouseDown:function(e){return this.pluginsManager.fireMouseDown(e)?(this.pluginsManager.fireCaretUpdated(),void 0):!1}},n.ice=this.ice||{},n.ice.InlineChangeEditor=t}.call(this),function(){var e=this,t={};t.DOM_VK_DELETE=8,t.DOM_VK_LEFT=37,t.DOM_VK_UP=38,t.DOM_VK_RIGHT=39,t.DOM_VK_DOWN=40,t.DOM_VK_ENTER=13,t.ELEMENT_NODE=1,t.ATTRIBUTE_NODE=2,t.TEXT_NODE=3,t.CDATA_SECTION_NODE=4,t.ENTITY_REFERENCE_NODE=5,t.ENTITY_NODE=6,t.PROCESSING_INSTRUCTION_NODE=7,t.COMMENT_NODE=8,t.DOCUMENT_NODE=9,t.DOCUMENT_TYPE_NODE=10,t.DOCUMENT_FRAGMENT_NODE=11,t.NOTATION_NODE=12,t.CHARACTER_UNIT="character",t.WORD_UNIT="word",t.BREAK_ELEMENT="br",t.CONTENT_STUB_ELEMENTS=["img","hr","iframe","param","link","meta","input","frame","col","base","area"],t.BLOCK_ELEMENTS=["p","div","pre","ul","ol","li","table","tbody","td","th","fieldset","form","blockquote","dl","dt","dd","dir","center","address","h1","h2","h3","h4","h5","h6"],t.TEXT_CONTAINER_ELEMENTS=["p","div","pre","li","td","th","blockquote","dt","dd","center","address","h1","h2","h3","h4","h5","h6"],t.STUB_ELEMENTS=t.CONTENT_STUB_ELEMENTS.slice(),t.STUB_ELEMENTS.push(t.BREAK_ELEMENT),t.getKeyChar=function(e){return String.fromCharCode(e.which)},t.getClass=function(e,t,n){return t||(t=document.body),e="."+e.split(" ").join("."),n&&(e=n+e),jQuery.makeArray(jQuery(t).find(e))},t.getId=function(e,t){return t||(t=document),element=t.getElementById(e)},t.getTag=function(e,t){return t||(t=document),jQuery.makeArray(jQuery(t).find(e))},t.getElementWidth=function(e){return e.offsetWidth},t.getElementHeight=function(e){return e.offsetHeight},t.getElementDimensions=function(e){var n={width:t.getElementWidth(e),height:t.getElementHeight(e)};return n},t.trim=function(e){return jQuery.trim(e)},t.empty=function(e){return e?jQuery(e).empty():void 0},t.remove=function(e){return e?jQuery(e).remove():void 0},t.prepend=function(e,t){jQuery(e).prepend(t)},t.append=function(e,t){jQuery(e).append(t)},t.insertBefore=function(e,t){jQuery(e).before(t)},t.insertAfter=function(e,t){jQuery(e).after(t)},t.getHtml=function(e){return jQuery(e).html()},t.setHtml=function(e,t){e&&jQuery(e).html(t)},t.removeWhitespace=function(e){jQuery(e).contents().filter(function(){return this.nodeType!=ice.dom.TEXT_NODE&&"UL"==this.nodeName||"OL"==this.nodeName?(t.removeWhitespace(this),!1):this.nodeType!=ice.dom.TEXT_NODE?!1:!/\S/.test(this.nodeValue)}).remove()},t.contents=function(e){return jQuery.makeArray(jQuery(e).contents())},t.extractContent=function(e){for(var t,n=document.createDocumentFragment();t=e.firstChild;)n.appendChild(t);return n},t.getNode=function(e,n){return t.is(e,n)?e:t.parents(e,n)[0]||null},t.getParents=function(e,t,n){for(var i=jQuery(e).parents(t),r=i.length,o=[],s=0;r>s&&i[s]!==n;s++)o.push(i[s]);return o},t.hasBlockChildren=function(e){for(var n=e.childNodes.length,i=0;n>i;i++)if(e.childNodes[i].nodeType===t.ELEMENT_NODE&&t.isBlockElement(e.childNodes[i])===!0)return!0;return!1},t.removeTag=function(e,t){return jQuery(e).find(t).replaceWith(function(){return jQuery(this).contents()}),e},t.stripEnclosingTags=function(e,t){var n=jQuery(e);return n.find("*").not(t).replaceWith(function(){var e,t=jQuery();try{e=jQuery(this),t=e.contents()}catch(n){}return 0===t.length&&e.remove(),t}),n[0]},t.getSiblings=function(e,t,n,i){if(n===!0)return"prev"===t?jQuery(e).prevAll():jQuery(e).nextAll();var r=[];if("prev"===t)for(;e.previousSibling&&(e=e.previousSibling,e!==i);)r.push(e);else for(;e.nextSibling&&(e=e.nextSibling,e!==i);)r.push(e);return r},t.getNodeTextContent=function(e){return jQuery(e).text()},t.getNodeStubContent=function(e){return jQuery(e).find(t.CONTENT_STUB_ELEMENTS.join(", "))},t.hasNoTextOrStubContent=function(e){return t.getNodeTextContent(e).length>0?!1:jQuery(e).find(t.CONTENT_STUB_ELEMENTS.join(", ")).length>0?!1:!0},t.getNodeCharacterLength=function(e){return t.getNodeTextContent(e).length+jQuery(e).find(t.STUB_ELEMENTS.join(", ")).length},t.setNodeTextContent=function(e,t){return jQuery(e).text(t)},t.getTagName=function(e){return e.tagName&&e.tagName.toLowerCase()||null},t.getIframeDocument=function(e){var t=null;return e.contentDocument?t=e.contentDocument:e.contentWindow?t=e.contentWindow.document:e.document&&(t=e.document),t},t.isBlockElement=function(e){return-1!=t.BLOCK_ELEMENTS.lastIndexOf(e.nodeName.toLowerCase())},t.isStubElement=function(e){return-1!=t.STUB_ELEMENTS.lastIndexOf(e.nodeName.toLowerCase())},t.removeBRFromChild=function(e){if(e&&e.hasChildNodes())for(var t=0;e.childNodes.length>t;t++){var n=e.childNodes[t];n&&ice.dom.BREAK_ELEMENT==ice.dom.getTagName(n)&&n.parentNode.removeChild(n)}},t.isChildOf=function(e,t){try{for(;e&&e.parentNode;){if(e.parentNode===t)return!0;e=e.parentNode}}catch(n){}return!1},t.isChildOfTagName=function(e,t){try{for(;e&&e.parentNode;){if(e.parentNode&&e.parentNode.tagName&&e.parentNode.tagName.toLowerCase()===t)return e.parentNode;e=e.parentNode}}catch(n){}return!1},t.isChildOfTagNames=function(e,t){try{for(;e&&e.parentNode;){if(e.parentNode&&e.parentNode.tagName){tagName=e.parentNode.tagName.toLowerCase();for(var n=0;t.length>n;n++)if(tagName===t[n])return e.parentNode}e=e.parentNode}}catch(i){}return null},t.isChildOfClassName=function(e,t){try{for(;e&&e.parentNode;){if(jQuery(e.parentNode).hasClass(t))return e.parentNode;e=e.parentNode}}catch(n){}return null},t.cloneNode=function(e,t){return void 0===t&&(t=!0),jQuery(e).clone(t)},t.bind=function(e,t,n){return jQuery(e).bind(t,n)},t.unbind=function(e,t,n){return jQuery(e).unbind(t,n)},t.attr=function(e,t,n){return n?jQuery(e).attr(t,n):jQuery(e).attr(t)},t.replaceWith=function(e,t){return jQuery(e).replaceWith(t)},t.removeAttr=function(e,t){jQuery(e).removeAttr(t)},t.getElementsBetween=function(e,n){var i=[];if(e===n)return i;if(t.isChildOf(n,e)===!0){for(var r=e.childNodes.length,o=0;r>o&&e.childNodes[o]!==n;o++){if(t.isChildOf(n,e.childNodes[o])===!0)return t.arrayMerge(i,t.getElementsBetween(e.childNodes[o],n));i.push(e.childNodes[o])}return i}for(var s=e.nextSibling;s;){if(t.isChildOf(n,s)===!0)return i=t.arrayMerge(i,t.getElementsBetween(s,n));if(s===n)return i;i.push(s),s=s.nextSibling}for(var a=t.getParents(e),c=t.getParents(n),l=t.arrayDiff(a,c,!0),d=l.length,u=0;d-1>u;u++)i=t.arrayMerge(i,t.getSiblings(l[u],"next"));var h=l[l.length-1];return i=t.arrayMerge(i,t.getElementsBetween(h,n))},t.getCommonAncestor=function(e,n){for(var i=e;i;){if(t.isChildOf(n,i)===!0)return i;i=i.parentNode}return null},t.getNextNode=function(e,n){if(e)for(;e.parentNode;){if(e===n)return null;if(e.nextSibling){if(e.nextSibling.nodeType===t.TEXT_NODE&&0===e.nextSibling.length){e=e.nextSibling;continue}return t.getFirstChild(e.nextSibling)}e=e.parentNode}return null},t.getNextContentNode=function(e,n){if(e)for(;e.parentNode;){if(e===n)return null;if(e.nextSibling&&t.canContainTextElement(t.getBlockParent(e))){if(e.nextSibling.nodeType===t.TEXT_NODE&&0===e.nextSibling.length){e=e.nextSibling;continue}return e.nextSibling}if(e.nextElementSibling)return e.nextElementSibling;e=e.parentNode}return null},t.getPrevNode=function(e,n){if(e)for(;e.parentNode;){if(e===n)return null;if(e.previousSibling){if(e.previousSibling.nodeType===t.TEXT_NODE&&0===e.previousSibling.length){e=e.previousSibling;continue}return t.getLastChild(e.previousSibling)}e=e.parentNode}return null},t.getPrevContentNode=function(e,n){if(e)for(;e.parentNode;){if(e===n)return null;if(e.previousSibling&&t.canContainTextElement(t.getBlockParent(e))){if(e.previousSibling.nodeType===t.TEXT_NODE&&0===e.previousSibling.length){e=e.previousSibling;continue}return e.previousSibling}if(e.previousElementSibling)return e.previousElementSibling;e=e.parentNode}return null},t.canContainTextElement=function(e){return e&&e.nodeName?-1!=t.TEXT_CONTAINER_ELEMENTS.lastIndexOf(e.nodeName.toLowerCase()):!1},t.getFirstChild=function(e){return e.firstChild?e.firstChild.nodeType===t.ELEMENT_NODE?t.getFirstChild(e.firstChild):e.firstChild:e},t.getLastChild=function(e){return e.lastChild?e.lastChild.nodeType===t.ELEMENT_NODE?t.getLastChild(e.lastChild):e.lastChild:e},t.removeEmptyNodes=function(e,n){for(var i=jQuery(e).find(":empty"),r=i.length;r>0;)r--,t.isStubElement(i[r])===!1&&(n&&n.call(this,i[r])===!1||t.remove(i[r]))},t.create=function(e){return jQuery(e)[0]},t.find=function(e,t){return jQuery(e).find(t)},t.children=function(e,t){return jQuery(e).children(t)},t.parent=function(e,t){return jQuery(e).parent(t)[0]},t.parents=function(e,t){return jQuery(e).parents(t)},t.is=function(e,t){return jQuery(e).is(t)},t.extend=function(){return jQuery.extend.apply(this,arguments)},t.walk=function(e,n,i){if(e){i||(i=0);var r=n.call(this,e,i);r!==!1&&(e.childNodes&&e.childNodes.length>0?t.walk(e.firstChild,n,i+1):e.nextSibling?t.walk(e.nextSibling,n,i):e.parentNode&&e.parentNode.nextSibling&&t.walk(e.parentNode.nextSibling,n,i-1))}},t.revWalk=function(e,n){if(e){var i=n.call(this,e);i!==!1&&(e.childNodes&&e.childNodes.length>0?t.walk(e.lastChild,n):e.previousSibling?t.walk(e.previousSibling,n):e.parentNode&&e.parentNode.previousSibling&&t.walk(e.parentNode.previousSibling,n))}},t.setStyle=function(e,t,n){e&&jQuery(e).css(t,n)},t.getStyle=function(e,t){return jQuery(e).css(t)},t.hasClass=function(e,t){return jQuery(e).hasClass(t)},t.addClass=function(e,t){jQuery(e).addClass(t)},t.removeClass=function(e,t){jQuery(e).removeClass(t)},t.preventDefault=function(e){e.preventDefault(),t.stopPropagation(e)},t.stopPropagation=function(e){e.stopPropagation()},t.noInclusionInherits=function(e,n){(n instanceof String||"string"==typeof n)&&(n=window[n]),(e instanceof String||"string"==typeof e)&&(e=window[e]);var i=function(){};if(t.isset(n)===!0)for(value in n.prototype)e.prototype[value]?i.prototype[value]=n.prototype[value]:e.prototype[value]=n.prototype[value];e.prototype&&(i.prototype.constructor=n,e.prototype["super"]=new i)},t.each=function(e,t){jQuery.each(e,function(e,n){t.call(this,e,n)})},t.foreach=function(e,t){if(e instanceof Array||e instanceof NodeList||e.length!==void 0&&e.item!==void 0)for(var n=e.length,i=0;n>i;i++){var r=t.call(this,i,e[i]);if(r===!1)break}else for(var o in e)if(e.hasOwnProperty(o)===!0){var r=t.call(this,o);if(r===!1)break}},t.isBlank=function(e){return!e||/^\s*$/.test(e)?!0:!1},t.isFn=function(e){return"function"==typeof e?!0:!1},t.isObj=function(e){return null!==e&&"object"==typeof e?!0:!1},t.isset=function(e){return e!==void 0&&null!==e?!0:!1},t.isArray=function(e){return jQuery.isArray(e)},t.isNumeric=function(e){var t=e.match(/^\d+$/);return null!==t?!0:!1},t.getUniqueId=function(){var e=(new Date).getTime(),t=Math.ceil(1e6*Math.random()),n=e+""+t;return n.substr(5,18).replace(/,/,"")},t.inArray=function(e,t){for(var n=t.length,i=0;n>i;i++)if(e===t[i])return!0;return!1},t.arrayDiff=function(e,n,i){for(var r=e.length,o=[],s=0;r>s;s++)t.inArray(e[s],n)===!1&&o.push(e[s]);if(i!==!0){r=n.length;for(var s=0;r>s;s++)t.inArray(n[s],e)===!1&&o.push(n[s])}return o},t.arrayMerge=function(e,t){for(var n=t.length,i=0;n>i;i++)e.push(t[i]);return e},t.stripTags=function(e,n){if("string"==typeof n){var i=jQuery("
    "+e+"
    ");return i.find("*").not(n).remove(),i.html()}for(var r,o=RegExp(/<\/?(\w+)((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim),s=e;null!=(r=o.exec(e));)(t.isset(n)===!1||t.inArray(r[1],n)!==!0)&&(s=s.replace(r[0],""));return s},t.browser=function(){var e={};return e.version=jQuery.browser.version,jQuery.browser.mozilla===!0?e.type="mozilla":jQuery.browser.msie===!0?e.type="msie":jQuery.browser.opera===!0?e.type="opera":jQuery.browser.webkit===!0&&(e.type="webkit"),e},t.getBrowserType=function(){if(null===this._browserType){for(var e=["msie","firefox","chrome","safari"],t=e.length,n=0;t>n;n++){var i=RegExp(e[n],"i");if(i.test(navigator.userAgent)===!0)return this._browserType=e[n],this._browserType}this._browserType="other"}return this._browserType},t.getWebkitType=function(){if("webkit"!==t.browser().type)return console.log("Not a webkit!"),!1;var e=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0;return e?"safari":"chrome"},t.isBrowser=function(e){return t.browser().type===e},t.getBlockParent=function(e,n){if(t.isBlockElement(e)===!0)return e;if(e)for(;e.parentNode;){if(e=e.parentNode,e===n)return null;if(t.isBlockElement(e)===!0)return e}return null},t.findNodeParent=function(e,n,i){if(e)for(;e.parentNode;){if(e===i)return null;if(t.is(e,n)===!0)return e;e=e.parentNode}return null},t.onBlockBoundary=function(e,n,i){if(!e||!n)return!1;var r=t.isChildOfTagNames(e,i)||t.is(e,i.join(", "))&&e||null,o=t.isChildOfTagNames(n,i)||t.is(n,i.join(", "))&&n||null;return r!==o},t.isOnBlockBoundary=function(e,n,i){if(!e||!n)return!1;var r=t.getBlockParent(e,i)||t.isBlockElement(e,i)&&e||null,o=t.getBlockParent(n,i)||t.isBlockElement(n,i)&&n||null;return r!==o},t.mergeContainers=function(e,n){if(!e||!n)return!1;if(e.nodeType===t.TEXT_NODE||t.isStubElement(e))n.appendChild(e);else if(e.nodeType===t.ELEMENT_NODE){for(;e.firstChild;)n.appendChild(e.firstChild);t.remove(e)}return!0},t.mergeBlockWithSibling=function(e,n,i){var r=i?jQuery(n).next().get(0):jQuery(n).prev().get(0);return i?t.mergeContainers(r,n):t.mergeContainers(n,r),e.collapse(!0),!0},t.date=function(e,n,i){if(null!==n||!i||(n=t.tsIso8601ToTimestamp(i))){for(var r=new Date(n),o=e.split(""),s=o.length,a="",c=0;s>c;c++){var l="",d=o[c];switch(d){case"D":case"l":var u=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];l=u[r.getDay()],"D"===d&&(l=l.substring(0,3));break;case"F":case"m":l=r.getMonth()+1,10>l&&(l="0"+l);break;case"M":months=["January","February","March","April","May","June","July","August","September","October","November","December"],l=months[r.getMonth()],"M"===d&&(l=l.substring(0,3));break;case"d":l=r.getDate();break;case"S":l=t.getOrdinalSuffix(r.getDate());break;case"Y":l=r.getFullYear();break;case"y":l=r.getFullYear(),l=(""+l).substring(2);break;case"H":l=r.getHours();break;case"h":l=r.getHours(),0===l?l=12:l>12&&(l-=12);break;case"i":l=t.addNumberPadding(r.getMinutes());break;case"a":l="am",r.getHours()>=12&&(l="pm");break;default:l=d}a+=l}return a}},t.getOrdinalSuffix=function(e){var t="",n=e%100;if(n>=4&&20>=n)t="th";else switch(e%10){case 1:t="st";break;case 2:t="nd";break;case 3:t="rd";break;default:t="th"}return t},t.addNumberPadding=function(e){return 10>e&&(e="0"+e),e},t.tsIso8601ToTimestamp=function(e){var t=/(\d\d\d\d)(?:-?(\d\d)(?:-?(\d\d)(?:[T ](\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(?:Z|(?:([-+])(\d\d)(?::?(\d\d))?)?)?)?)?)?/,n=e.match(RegExp(t));if(n){var i=new Date;i.setDate(n[3]),i.setFullYear(n[1]),i.setMonth(n[2]-1),i.setHours(n[4]),i.setMinutes(n[5]),i.setSeconds(n[6]);var r=60*n[9];"+"===n[8]&&(r*=-1),r-=i.getTimezoneOffset();var o=i.getTime()+1e3*60*r;return o}return null},e.dom=t}.call(this.ice),function(){var e,t=this;e=function(e,t,n){this.env=e,this.element=e.element,this.selection=this.env.selection,n||this.removeBookmarks(this.element);var i=t||this.selection.getRangeAt(0);t=i.cloneRange();var r=t.startContainer;t.endContainer;var o=t.startOffset;t.endOffset;var s;t.collapse(!1);var a=this.env.document.createElement("span");a.style.display="none",ice.dom.setHtml(a," "),ice.dom.addClass(a,"iceBookmark iceBookmark_end"),a.setAttribute("iceBookmark","end"),t.insertNode(a),ice.dom.isChildOf(a,this.element)||this.element.appendChild(a),t.setStart(r,o),t.collapse(!0);var c=this.env.document.createElement("span");c.style.display="none",ice.dom.addClass(c,"iceBookmark iceBookmark_start"),ice.dom.setHtml(c," "),c.setAttribute("iceBookmark","start");try{t.insertNode(c),c.previousSibling===a&&(s=c,c=a,a=s)}catch(l){ice.dom.insertBefore(a,c)}ice.dom.isChildOf(c,this.element)===!1&&(this.element.firstChild?ice.dom.insertBefore(this.element.firstChild,c):this.element.appendChild(c)),a.previousSibling||(s=this.env.document.createTextNode(""),ice.dom.insertBefore(a,s)),c.nextSibling||(s=this.env.document.createTextNode(""),ice.dom.insertAfter(c,s)),i.setStart(c.nextSibling,0),i.setEnd(a.previousSibling,a.previousSibling.length||0),this.start=c,this.end=a},e.prototype={selectBookmark:function(){var e=this.selection.getRangeAt(0),t=null,n=null,i=0,r=null;if(this.start.nextSibling===this.end||0===ice.dom.getElementsBetween(this.start,this.end).length)this.end.nextSibling?t=ice.dom.getFirstChild(this.end.nextSibling):this.start.previousSibling?(t=ice.dom.getFirstChild(this.start.previousSibling),t.nodeType===ice.dom.TEXT_NODE&&(i=t.length)):(this.end.parentNode.appendChild(this.env.document.createTextNode("")),t=ice.dom.getFirstChild(this.end.nextSibling));else{if(this.start.nextSibling)t=ice.dom.getFirstChild(this.start.nextSibling);else{if(!this.start.previousSibling){var o=this.env.document.createTextNode("");ice.dom.insertBefore(this.start,o)}t=ice.dom.getLastChild(this.start.previousSibling),i=t.length}this.end.previousSibling?n=ice.dom.getLastChild(this.end.previousSibling):(n=ice.dom.getFirstChild(this.end.nextSibling||this.end),r=0)}ice.dom.remove([this.start,this.end]),null===n?(e.setEnd(t,i),e.collapse(!1)):(e.setStart(t,i),null===r&&(r=n.length||0),e.setEnd(n,r));try{this.selection.addRange(e)}catch(s){}},getBookmark:function(e,t){var n=ice.dom.getClass("iceBookmark_"+t,e)[0];return n},removeBookmarks:function(e){ice.dom.remove(ice.dom.getClass("iceBookmark",e,"span"))}},t.Bookmark=e}.call(this.ice),function(){var e,t=this;e=function(e){this._selection=null,this.env=e,this._initializeRangeLibrary(),this._getSelection()},e.prototype={_getSelection:function(){return this._selection?this._selection.refresh():this._selection=this.env.frame?rangy.getIframeSelection(this.env.frame):rangy.getSelection(),this._selection},createRange:function(){return rangy.createRange(this.env.document)},getRangeAt:function(e){this._selection.refresh();try{return this._selection.getRangeAt(e)}catch(t){return this._selection=null,this._getSelection().getRangeAt(0)}},addRange:function(e){this._selection||(this._selection=this._getSelection()),this._selection.setSingleRange(e),this._selection.ranges=[e]},_initializeRangeLibrary:function(){var e=this;rangy.init(),rangy.config.checkSelectionRanges=!1;var t=function(e,t,n,i){if(0===n)throw Error("InvalidArgumentException: units cannot be 0");switch(t){case ice.dom.CHARACTER_UNIT:n>0?e.moveCharRight(i,n):e.moveCharLeft(i,-1*n);break;case ice.dom.WORD_UNIT:default:}};rangy.rangePrototype.moveStart=function(e,n){t(this,e,n,!0)},rangy.rangePrototype.moveEnd=function(e,n){t(this,e,n,!1)},rangy.rangePrototype.setRange=function(e,t,n){e?this.setStart(t,n):this.setEnd(t,n)},rangy.rangePrototype.moveCharLeft=function(e,t){var n,i;if(e?(n=this.startContainer,i=this.startOffset):(n=this.endContainer,i=this.endOffset),n.nodeType===ice.dom.ELEMENT_NODE)if(n.hasChildNodes()){for(n=n.childNodes[i],n=this.getPreviousTextNode(n);n&&n.nodeType==ice.dom.TEXT_NODE&&""===n.nodeValue;)n=this.getPreviousTextNode(n);i=n.data.length-t}else i=-1*t;else i-=t;if(0>i)for(;0>i;){var r=[];if(n=this.getPreviousTextNode(n,r),!n)return;n.nodeType!==ice.dom.ELEMENT_NODE&&(i+=n.data.length)}this.setRange(e,n,i)},rangy.rangePrototype.moveCharRight=function(e,t){var n,i;e?(n=this.startContainer,i=this.startOffset):(n=this.endContainer,i=this.endOffset),n.nodeType===ice.dom.ELEMENT_NODE?(n=n.childNodes[i],n.nodeType!==ice.dom.TEXT_NODE&&(n=this.getNextTextNode(n)),i=t):i+=t;var r=i-n.data.length;if(r>0){for(var o=[];r>0;)if(n=this.getNextContainer(n,o),n.nodeType!==ice.dom.ELEMENT_NODE){if(n.data.length>=r)break;n.data.length>0&&(r-=n.data.length)}i=r}this.setRange(e,n,i)},rangy.rangePrototype.getNextContainer=function(e,t){if(!e)return null;for(;e.nextSibling;)if(e=e.nextSibling,e.nodeType!==ice.dom.TEXT_NODE){var n=this.getFirstSelectableChild(e);if(null!==n)return n}else if(this.isSelectable(e)===!0)return e;for(;e&&!e.nextSibling;)e=e.parentNode;if(!e)return null;if(e=e.nextSibling,this.isSelectable(e)===!0)return e;t&&ice.dom.isBlockElement(e)===!0&&t.push(e);var i=this.getFirstSelectableChild(e);return null!==i?i:this.getNextContainer(e,t)},rangy.rangePrototype.getPreviousContainer=function(e,t){if(!e)return null;for(;e.previousSibling;)if(e=e.previousSibling,e.nodeType!==ice.dom.TEXT_NODE){if(ice.dom.isStubElement(e)===!0)return e;var n=this.getLastSelectableChild(e);if(null!==n)return n}else if(this.isSelectable(e)===!0)return e;for(;e&&!e.previousSibling;)e=e.parentNode;if(!e)return null;if(e=e.previousSibling,this.isSelectable(e)===!0)return e;t&&ice.dom.isBlockElement(e)===!0&&t.push(e);var i=this.getLastSelectableChild(e);return null!==i?i:this.getPreviousContainer(e,t)},rangy.rangePrototype.getNextTextNode=function(e){return e.nodeType===ice.dom.ELEMENT_NODE&&0!==e.childNodes.length?this.getFirstSelectableChild(e):(e=this.getNextContainer(e),e.nodeType===ice.dom.TEXT_NODE?e:this.getNextTextNode(e))},rangy.rangePrototype.getPreviousTextNode=function(e,t){return e=this.getPreviousContainer(e,t),e.nodeType===ice.dom.TEXT_NODE?e:this.getPreviousTextNode(e,t)},rangy.rangePrototype.getFirstSelectableChild=function(e){if(e){if(e.nodeType===ice.dom.TEXT_NODE)return e;for(var t=e.firstChild;t;){if(this.isSelectable(t)===!0)return t;if(t.firstChild){var n=this.getFirstSelectableChild(t);if(null!==n)return n;t=t.nextSibling}else t=t.nextSibling}}return null},rangy.rangePrototype.getLastSelectableChild=function(e){if(e){if(e.nodeType===ice.dom.TEXT_NODE)return e;for(var t=e.lastChild;t;){if(this.isSelectable(t)===!0)return t;if(t.lastChild){var n=this.getLastSelectableChild(t);if(null!==n)return n;t=t.previousSibling}else t=t.previousSibling}}return null},rangy.rangePrototype.isSelectable=function(e){return e&&e.nodeType===ice.dom.TEXT_NODE&&0!==e.data.length?!0:!1},rangy.rangePrototype.getHTMLContents=function(t){t||(t=this.cloneContents());var n=e.env.document.createElement("div");return n.appendChild(t.cloneNode(!0)),n.innerHTML},rangy.rangePrototype.getHTMLContentsObj=function(){return this.cloneContents()}}},t.Selection=e}.call(this.ice),function(){var e=this,t=function(e){this._ice=e};t.prototype={start:function(){},clicked:function(){return!0},mouseDown:function(){return!0},keyDown:function(){return!0},keyPress:function(){return!0},selectionChanged:function(){},setEnabled:function(){},setDisabled:function(){},caretUpdated:function(){},nodeInserted:function(){},nodeCreated:function(){},caretPositioned:function(){},remove:function(){this._ice.removeKeyPressListener(this)},setSettings:function(){}},e.IcePlugin=t}.call(this.ice),function(){var e=this,t=function(e){this.plugins={},this.pluginConstructors={},this.keyPressListeners={},this.activePlugin=null,this.pluginSets={},this.activePluginSet=null,this._ice=e};t.prototype={getPluginNames:function(){var e=[];for(var t in this.plugins)e.push(t);return e},addPluginObject:function(e,t){this.plugins[e]=t},addPlugin:function(e,t){if("function"!=typeof t)throw Error("IcePluginException: plugin must be a constructor function");ice.dom.isset(this.pluginConstructors[e])===!1&&(this.pluginConstructors[e]=t)},loadPlugins:function(e,t){if(0===e.length)t.call(this);else{var n=e.shift();if("object"==typeof n&&(n=n.name),ice.dom.isset(ice._plugin[n])!==!0)throw Error("plugin was not included in the page: "+n);this.addPlugin(n,ice._plugin[n]),this.loadPlugins(e,t)}},_enableSet:function(e){this.activePluginSet=e;for(var t=this.pluginSets[e].length,n=0;t>n;n++){var i=this.pluginSets[e][n],r="";r="object"==typeof i?i.name:i;var o=this.pluginConstructors[r];if(o){var s=new o(this._ice);this.plugins[r]=s,ice.dom.isset(i.settings)===!0&&s.setSettings(i.settings),s.start()}}},setActivePlugin:function(e){this.activePlugin=e},getActivePlugin:function(){return this.activePlugin},_getPluginName:function(e){var t=""+e,n="function ".length,i=t.substr(n,t.indexOf("(")-n);return i},removePlugin:function(e){this.plugins[e]&&this.plugins[e].remove()},getPlugin:function(e){return this.plugins[e]},usePlugins:function(e,t,n){var i=this;this.pluginSets[e]=ice.dom.isset(t)===!0?t:[];var r=this.pluginSets[e].concat([]);this.loadPlugins(r,function(){i._enableSet(e),n&&n.call(this)})},disablePlugin:function(e){this.plugins[e].disable()},isPluginElement:function(e){for(var t in this.plugins)if(this.plugins[t].isPluginElement&&this.plugins[t].isPluginElement(e)===!0)return!0;return!1},fireKeyPressed:function(e){if(this._fireKeyPressFns(e,"all_keys")===!1)return!1;var t=[];switch((e.ctrlKey===!0||e.metaKey===!0)&&t.push("ctrl"),e.shiftKey===!0&&t.push("shift"),e.altKey===!0&&t.push("alt"),e.keyCode){case 13:t.push("enter");break;case ice.dom.DOM_VK_LEFT:t.push("left");break;case ice.dom.DOM_VK_RIGHT:t.push("right");break;case ice.dom.DOM_VK_UP:t.push("up");break;case ice.dom.DOM_VK_DOWN:t.push("down");break;case 9:t.push("tab");break;case ice.dom.DOM_VK_DELETE:t.push("delete");break;default:var n;e.keyCode?n=e.keyCode:e.which&&(n=e.which),n&&t.push(String.fromCharCode(n).toLowerCase())}var i=t.sort().join("+");return this._fireKeyPressFns(e,i)},_fireKeyPressFns:function(e,t){if(this.keyPressListeners[t])for(var n=this.keyPressListeners[t].length,i=0;n>i;i++){var r=this.keyPressListeners[t][i],o=r.fn,s=r.plugin,a=r.data;if(o)if(ice.dom.isFn(o)===!0){if(o.call(s,e,a)===!0)return ice.dom.preventDefault(e),!1}else if(s[o]&&s[o].call(s,e,a)===!0)return ice.dom.preventDefault(e),!1}return!0},fireSelectionChanged:function(e){for(var t in this.plugins)this.plugins[t].selectionChanged(e)},fireNodeInserted:function(e,t){for(var n in this.plugins)if(this.plugins[n].nodeInserted(e,t)===!1)return!1},fireNodeCreated:function(e,t){for(var n in this.plugins)if(this.plugins[n].nodeCreated(e,t)===!1)return!1},fireCaretPositioned:function(){for(var e in this.plugins)this.plugins[e].caretPositioned()},fireClicked:function(e){var t=!0;for(var n in this.plugins)this.plugins[n].clicked(e)===!1&&(t=!1);return t},fireMouseDown:function(e){var t=!0;for(var n in this.plugins)this.plugins[n].mouseDown(e)===!1&&(t=!1);return t},fireKeyDown:function(e){var t=!0;for(var n in this.plugins)this.plugins[n].keyDown(e)===!1&&(t=!1);return t},fireKeyPress:function(e){var t=!0;for(var n in this.plugins)this.plugins[n].keyPress(e)===!1&&(t=!1);return t},fireEnabled:function(e){for(var t in this.plugins)this.plugins[t].setEnabled(e)},fireDisabled:function(e){for(var t in this.plugins)this.plugins[t].setDisabled(e)},fireCaretUpdated:function(){for(var e in this.plugins)this.plugins[e].caretUpdated&&this.plugins[e].caretUpdated()}},e._plugin={},e.IcePluginManager=t}.call(this.ice),function(){var e,t=this;e=function(e){this._ice=e},e.prototype={nodeCreated:function(e,t){e.setAttribute("title",(t.action||"Modified")+" by "+e.getAttribute(this._ice.userNameAttribute)+" - "+ice.dom.date("m/d/Y h:ia",parseInt(e.getAttribute(this._ice.timeAttribute))))}},ice.dom.noInclusionInherits(e,ice.IcePlugin),t._plugin.IceAddTitlePlugin=e}.call(this.ice),function(){var e,t=this;e=function(e){this._ice=e,this._tmpNode=null,this._tmpNodeTagName="icepaste",this._pasteId="icepastediv";var t=this;this.pasteType="formattedClean",this.preserve="p",this.beforePasteClean=function(e){return e},this.afterPasteClean=function(e){return e},e.element.oncopy=function(){return t.handleCopy.apply(t)}},e.prototype={setSettings:function(e){e=e||{},ice.dom.extend(this,e),this.preserve+=","+this._tmpNodeTagName,this.setupPreserved()},keyDown:function(e){return e.metaKey===!0||e.ctrlKey===!0?(86==e.keyCode?this.handlePaste():88==e.keyCode&&this.handleCut(),!0):void 0},keyPress:function(e){var t=null;null==e.which?t=String.fromCharCode(e.keyCode):e.which>0&&(t=String.fromCharCode(e.which));var n=this;return this.cutElement&&"x"===t?ice.dom.isBrowser("webkit")&&n.cutElement.focus():"v"===t&&ice.dom.isBrowser("webkit")&&this._ice.env.document.getElementById(n._pasteId).focus(),!0},handleCopy:function(){},handlePaste:function(){var e=this._ice.getCurrentRange();if(e.collapsed||(this._ice.isTracking?(this._ice.deleteContents(),e=e.cloneRange()):(e.deleteContents(),e.collapse(!0))),this._ice.isTracking&&this._ice._moveRangeToValidTrackingPos(e),e.startContainer==this._ice.element){var t=ice.dom.find(this._ice.element,this._ice.blockEl)[0];t||(t=ice.dom.create("<"+this._ice.blockEl+" >
    "),this._ice.element.appendChild(t)),e.setStart(t,0),e.collapse(!0),this._ice.env.selection.addRange(e)}switch(this._tmpNode=this._ice.env.document.createElement(this._tmpNodeTagName),e.insertNode(this._tmpNode),this.pasteType){case"formatted":this.setupPaste();break;case"formattedClean":this.setupPaste(!0)}return!0},setupPaste:function(e){var t=this.createDiv(this._pasteId),n=this,i=this._ice.getCurrentRange();return i.selectNodeContents(t),this._ice.selection.addRange(i),t.onpaste=function(){setTimeout(function(){n.handlePasteValue(e)},0)},t.focus(),!0},handlePasteValue:function(e){var t=this._ice.env.document,n=t.getElementById(this._pasteId),i=ice.dom.getHtml(n),r=ice.dom.children("
    "+i+"
    ",this._ice.blockEl);1===r.length&&ice.dom.getNodeTextContent("
    "+i+"
    ")===ice.dom.getNodeTextContent(r)&&(i=ice.dom.getHtml(i)),i=this.beforePasteClean.call(this,i),e&&(i=this._ice.getCleanContent(i),i=this.stripPaste(i)),i=this.afterPasteClean.call(this,i),i=ice.dom.trim(i);var o=this._ice.getCurrentRange();o.setStartAfter(this._tmpNode),o.collapse(!0);var s=null,a=null,c=null,l=o.createContextualFragment(i),d=this._ice.startBatchChange();if(ice.dom.hasBlockChildren(l)){var u=ice.dom.isChildOfTagName(this._tmpNode,this._ice.blockEl);o.setEndAfter(u.lastChild),this._ice.selection.addRange(o);var h=o.extractContents(),f=t.createElement(this._ice.blockEl);f.appendChild(h),ice.dom.insertAfter(u,f),o.setStart(f,0),o.collapse(!0),this._ice.selection.addRange(o);for(var g=o.startContainer;l.firstChild;)if(3!==l.firstChild.nodeType||jQuery.trim(l.firstChild.nodeValue))if(ice.dom.isBlockElement(l.firstChild)){if(""!==l.firstChild.textContent){s=null;var m=null;this._ice.isTracking?(m=this._ice.createIceNode("insertType"),this._ice.addChange("insertType",[m]),c=t.createElement(l.firstChild.tagName),m.innerHTML=l.firstChild.innerHTML,c.appendChild(m)):(m=c=t.createElement(l.firstChild.tagName),c.innerHTML=l.firstChild.innerHTML),a=m,ice.dom.insertBefore(g,c)}l.removeChild(l.firstChild)}else s||(c=t.createElement(this._ice.blockEl),ice.dom.insertBefore(g,c),this._ice.isTracking?(s=this._ice.createIceNode("insertType"),this._ice.addChange("insertType",[s]),c.appendChild(s)):s=c),a=s,s.appendChild(l.removeChild(l.firstChild));else l.removeChild(l.firstChild);f.textContent||f.parentNode.removeChild(f)}else if(this._ice.isTracking)c=this._ice.createIceNode("insertType",l),this._ice.addChange("insertType",[c]),o.insertNode(c),a=c;else for(var p;p=l.firstChild;)o.insertNode(p),o.setStartAfter(p),o.collapse(!0),a=p;this._ice.endBatchChange(d),n.parentNode.removeChild(n),this._cleanup(a)},createDiv:function(e){var t=this._ice.env.document,n=t.getElementById(e);n&&ice.dom.remove(n);var i=t.createElement("div");return i.id=e,i.setAttribute("contentEditable",!0),ice.dom.setStyle(i,"width","1px"),ice.dom.setStyle(i,"height","1px"),ice.dom.setStyle(i,"overflow","hidden"),ice.dom.setStyle(i,"position","fixed"),ice.dom.setStyle(i,"top","10px"),ice.dom.setStyle(i,"left","10px"),i.appendChild(t.createElement("br")),t.body.appendChild(i),i },handleCut:function(){var e=this,t=this._ice.getCurrentRange();if(!t.collapsed){this.cutElement=this.createDiv("icecut"),this.cutElement.innerHTML=t.getHTMLContents().replace(/ /g,"> "),this._ice.isTracking?this._ice.deleteContents():t.deleteContents();var n=this._ice.env.document.createRange();n.setStart(this.cutElement.firstChild,0),n.setEndAfter(this.cutElement.lastChild),setTimeout(function(){e.cutElement.focus(),setTimeout(function(){ice.dom.remove(e.cutElement),t.setStart(t.startContainer,t.startOffset),t.collapse(!1),e._ice.env.selection.addRange(t)},100)},0),e._ice.env.selection.addRange(n)}},stripPaste:function(e){return e=this._cleanWordPaste(e),e=this.cleanPreserved(e)},setupPreserved:function(){var e=this;this._tags="",this._attributesMap=[],ice.dom.each(this.preserve.split(","),function(t,n){n.match(/(\w+)(\[(.+)\])?/);var i=RegExp.$1,r=RegExp.$3;e._tags&&(e._tags+=","),e._tags+=i.toLowerCase(),e._attributesMap[i]=r.split("|")})},cleanPreserved:function(e){var t=this,n=this._ice.env.document.createElement("div");return n.innerHTML=e,n=ice.dom.stripEnclosingTags(n,this._tags),ice.dom.each(ice.dom.find(n,this._tags),function(e,n){if(ice.dom.hasClass(n,"skip-clean"))return!0;var i=n.tagName.toLowerCase(),r=t._attributesMap[i];if(r[0]&&"*"===r[0])return!0;if(n.hasAttributes())for(var o=n.attributes,e=o.length-1;e>=0;e--)ice.dom.inArray(o[e].name,r)||n.removeAttribute(o[e].name)}),n.innerHTML},_cleanWordPaste:function(e){return e=e.replace(/<(meta|link)[^>]+>/g,""),e=e.replace(//g,""),e=e.replace(/