网站
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

9902 lines
289 KiB

  1. /*******************************************************************************
  2. * KindEditor - WYSIWYG HTML Editor for Internet
  3. * Copyright (C) 2006-2016 kindsoft.net
  4. *
  5. * @author Roddy <luolonghao@gmail.com>
  6. * @website http://www.kindsoft.net/
  7. * @licence http://www.kindsoft.net/license.php
  8. * @version 4.1.11 (2016-03-31)
  9. *******************************************************************************/
  10. (function (window, undefined) {
  11. if (window.KindEditor) {
  12. return;
  13. }
  14. if (!window.console) {
  15. window.console = {};
  16. }
  17. if (!console.log) {
  18. console.log = function () {};
  19. }
  20. var _VERSION = '4.1.11 (2016-03-31)',
  21. _ua = navigator.userAgent.toLowerCase(),
  22. _IE = _ua.indexOf('msie') > -1 && _ua.indexOf('opera') == -1,
  23. _NEWIE = _ua.indexOf('msie') == -1 && _ua.indexOf('trident') > -1,
  24. _GECKO = _ua.indexOf('gecko') > -1 && _ua.indexOf('khtml') == -1,
  25. _WEBKIT = _ua.indexOf('applewebkit') > -1,
  26. _OPERA = _ua.indexOf('opera') > -1,
  27. _MOBILE = _ua.indexOf('mobile') > -1,
  28. _IOS = /ipad|iphone|ipod/.test(_ua),
  29. _QUIRKS = document.compatMode != 'CSS1Compat',
  30. _IERANGE = !window.getSelection,
  31. _matches = /(?:msie|firefox|webkit|opera)[\/:\s](\d+)/.exec(_ua),
  32. _V = _matches ? _matches[1] : '0',
  33. _TIME = new Date().getTime();
  34. function _isArray(val) {
  35. if (!val) {
  36. return false;
  37. }
  38. return Object.prototype.toString.call(val) === '[object Array]';
  39. }
  40. function _isFunction(val) {
  41. if (!val) {
  42. return false;
  43. }
  44. return Object.prototype.toString.call(val) === '[object Function]';
  45. }
  46. function _inArray(val, arr) {
  47. for (var i = 0, len = arr.length; i < len; i++) {
  48. if (val === arr[i]) {
  49. return i;
  50. }
  51. }
  52. return -1;
  53. }
  54. function _each(obj, fn) {
  55. if (_isArray(obj)) {
  56. for (var i = 0, len = obj.length; i < len; i++) {
  57. if (fn.call(obj[i], i, obj[i]) === false) {
  58. break;
  59. }
  60. }
  61. } else {
  62. for (var key in obj) {
  63. if (obj.hasOwnProperty(key)) {
  64. if (fn.call(obj[key], key, obj[key]) === false) {
  65. break;
  66. }
  67. }
  68. }
  69. }
  70. }
  71. function _trim(str) {
  72. return str.replace(/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '');
  73. }
  74. function _inString(val, str, delimiter) {
  75. delimiter = delimiter === undefined ? ',' : delimiter;
  76. return (delimiter + str + delimiter).indexOf(delimiter + val + delimiter) >= 0;
  77. }
  78. function _addUnit(val, unit) {
  79. unit = unit || 'px';
  80. return val && /^-?\d+(?:\.\d+)?$/.test(val) ? val + unit : val;
  81. }
  82. function _removeUnit(val) {
  83. var match;
  84. return val && (match = /(\d+)/.exec(val)) ? parseInt(match[1], 10) : 0;
  85. }
  86. function _escape(val) {
  87. return val.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  88. }
  89. function _unescape(val) {
  90. return val.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
  91. }
  92. function _toCamel(str) {
  93. var arr = str.split('-');
  94. str = '';
  95. _each(arr, function(key, val) {
  96. str += (key > 0) ? val.charAt(0).toUpperCase() + val.substr(1) : val;
  97. });
  98. return str;
  99. }
  100. function _toHex(val) {
  101. function hex(d) {
  102. var s = parseInt(d, 10).toString(16).toUpperCase();
  103. return s.length > 1 ? s : '0' + s;
  104. }
  105. return val.replace(/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/ig,
  106. function($0, $1, $2, $3) {
  107. return '#' + hex($1) + hex($2) + hex($3);
  108. }
  109. );
  110. }
  111. function _toMap(val, delimiter) {
  112. delimiter = delimiter === undefined ? ',' : delimiter;
  113. var map = {}, arr = _isArray(val) ? val : val.split(delimiter), match;
  114. _each(arr, function(key, val) {
  115. if ((match = /^(\d+)\.\.(\d+)$/.exec(val))) {
  116. for (var i = parseInt(match[1], 10); i <= parseInt(match[2], 10); i++) {
  117. map[i.toString()] = true;
  118. }
  119. } else {
  120. map[val] = true;
  121. }
  122. });
  123. return map;
  124. }
  125. function _toArray(obj, offset) {
  126. return Array.prototype.slice.call(obj, offset || 0);
  127. }
  128. function _undef(val, defaultVal) {
  129. return val === undefined ? defaultVal : val;
  130. }
  131. function _invalidUrl(url) {
  132. return !url || /[<>"]/.test(url);
  133. }
  134. function _addParam(url, param) {
  135. return url.indexOf('?') >= 0 ? url + '&' + param : url + '?' + param;
  136. }
  137. function _extend(child, parent, proto) {
  138. if (!proto) {
  139. proto = parent;
  140. parent = null;
  141. }
  142. var childProto;
  143. if (parent) {
  144. var fn = function () {};
  145. fn.prototype = parent.prototype;
  146. childProto = new fn();
  147. _each(proto, function(key, val) {
  148. childProto[key] = val;
  149. });
  150. } else {
  151. childProto = proto;
  152. }
  153. childProto.constructor = child;
  154. child.prototype = childProto;
  155. child.parent = parent ? parent.prototype : null;
  156. }
  157. function _json(text) {
  158. var match;
  159. if ((match = /\{[\s\S]*\}|\[[\s\S]*\]/.exec(text))) {
  160. text = match[0];
  161. }
  162. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
  163. cx.lastIndex = 0;
  164. if (cx.test(text)) {
  165. text = text.replace(cx, function (a) {
  166. return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  167. });
  168. }
  169. if (/^[\],:{}\s]*$/.
  170. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
  171. replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
  172. replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  173. return eval('(' + text + ')');
  174. }
  175. throw 'JSON parse error';
  176. }
  177. var _round = Math.round;
  178. var K = {
  179. DEBUG : false,
  180. VERSION : _VERSION,
  181. IE : _IE,
  182. GECKO : _GECKO,
  183. WEBKIT : _WEBKIT,
  184. OPERA : _OPERA,
  185. V : _V,
  186. TIME : _TIME,
  187. each : _each,
  188. isArray : _isArray,
  189. isFunction : _isFunction,
  190. inArray : _inArray,
  191. inString : _inString,
  192. trim : _trim,
  193. addUnit : _addUnit,
  194. removeUnit : _removeUnit,
  195. escape : _escape,
  196. unescape : _unescape,
  197. toCamel : _toCamel,
  198. toHex : _toHex,
  199. toMap : _toMap,
  200. toArray : _toArray,
  201. undef : _undef,
  202. invalidUrl : _invalidUrl,
  203. addParam : _addParam,
  204. extend : _extend,
  205. json : _json
  206. };
  207. var _INLINE_TAG_MAP = _toMap('a,abbr,acronym,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,img,input,ins,kbd,label,map,q,s,samp,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'),
  208. _BLOCK_TAG_MAP = _toMap('address,applet,blockquote,body,center,dd,dir,div,dl,dt,fieldset,form,frameset,h1,h2,h3,h4,h5,h6,head,hr,html,iframe,ins,isindex,li,map,menu,meta,noframes,noscript,object,ol,p,pre,script,style,table,tbody,td,tfoot,th,thead,title,tr,ul'),
  209. _SINGLE_TAG_MAP = _toMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed'),
  210. _STYLE_TAG_MAP = _toMap('b,basefont,big,del,em,font,i,s,small,span,strike,strong,sub,sup,u'),
  211. _CONTROL_TAG_MAP = _toMap('img,table,input,textarea,button'),
  212. _PRE_TAG_MAP = _toMap('pre,style,script'),
  213. _NOSPLIT_TAG_MAP = _toMap('html,head,body,td,tr,table,ol,ul,li'),
  214. _AUTOCLOSE_TAG_MAP = _toMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'),
  215. _FILL_ATTR_MAP = _toMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'),
  216. _VALUE_TAG_MAP = _toMap('input,button,textarea,select');
  217. function _getBasePath() {
  218. var els = document.getElementsByTagName('script'), src;
  219. for (var i = 0, len = els.length; i < len; i++) {
  220. src = els[i].src || '';
  221. if (/kindeditor[\w\-\.]*\.js/.test(src)) {
  222. return src.substring(0, src.lastIndexOf('/') + 1);
  223. }
  224. }
  225. return '';
  226. }
  227. K.basePath = _getBasePath();
  228. K.options = {
  229. designMode : true,
  230. fullscreenMode : false,
  231. filterMode : true,
  232. wellFormatMode : true,
  233. shadowMode : true,
  234. loadStyleMode : true,
  235. basePath : K.basePath,
  236. themesPath : K.basePath + 'themes/',
  237. langPath : K.basePath + 'lang/',
  238. pluginsPath : K.basePath + 'plugins/',
  239. themeType : 'default',
  240. langType : 'zh-CN',
  241. urlType : '',
  242. newlineTag : 'p',
  243. resizeType : 2,
  244. syncType : 'form',
  245. pasteType : 2,
  246. dialogAlignType : 'page',
  247. useContextmenu : true,
  248. fullscreenShortcut : false,
  249. bodyClass : 'ke-content',
  250. indentChar : '\t',
  251. cssPath : '',
  252. cssData : '',
  253. minWidth : 650,
  254. minHeight : 100,
  255. minChangeSize : 50,
  256. zIndex : 811213,
  257. items : [
  258. 'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
  259. 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
  260. 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
  261. 'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
  262. 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
  263. 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
  264. 'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
  265. 'anchor', 'link', 'unlink', '|', 'about'
  266. ],
  267. noDisableItems : ['source', 'fullscreen'],
  268. colorTable : [
  269. ['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
  270. ['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
  271. ['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
  272. ['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
  273. ],
  274. fontSizeTable : ['9px', '10px', '12px', '14px', '16px', '18px', '24px', '32px'],
  275. htmlTags : {
  276. font : ['id', 'class', 'color', 'size', 'face', '.background-color'],
  277. span : [
  278. 'id', 'class', '.color', '.background-color', '.font-size', '.font-family', '.background',
  279. '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.line-height'
  280. ],
  281. div : [
  282. 'id', 'class', 'align', '.border', '.margin', '.padding', '.text-align', '.color',
  283. '.background-color', '.font-size', '.font-family', '.font-weight', '.background',
  284. '.font-style', '.text-decoration', '.vertical-align', '.margin-left'
  285. ],
  286. table: [
  287. 'id', 'class', 'border', 'cellspacing', 'cellpadding', 'width', 'height', 'align', 'bordercolor',
  288. '.padding', '.margin', '.border', 'bgcolor', '.text-align', '.color', '.background-color',
  289. '.font-size', '.font-family', '.font-weight', '.font-style', '.text-decoration', '.background',
  290. '.width', '.height', '.border-collapse'
  291. ],
  292. 'td,th': [
  293. 'id', 'class', 'align', 'valign', 'width', 'height', 'colspan', 'rowspan', 'bgcolor',
  294. '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.font-weight',
  295. '.font-style', '.text-decoration', '.vertical-align', '.background', '.border'
  296. ],
  297. a : ['id', 'class', 'href', 'target', 'name'],
  298. embed : ['id', 'class', 'src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess', 'wmode'],
  299. img : ['id', 'class', 'src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'],
  300. 'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : [
  301. 'id', 'class', 'align', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.background',
  302. '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.text-indent', '.margin-left'
  303. ],
  304. pre : ['id', 'class'],
  305. hr : ['id', 'class', '.page-break-after'],
  306. 'br,tbody,tr,strong,b,sub,sup,em,i,u,strike,s,del' : ['id', 'class'],
  307. iframe : ['id', 'class', 'src', 'frameborder', 'width', 'height', '.width', '.height']
  308. },
  309. layout : '<div class="container"><div class="toolbar"></div><div class="edit"></div><div class="statusbar"></div></div>'
  310. };
  311. var _useCapture = false;
  312. var _INPUT_KEY_MAP = _toMap('8,9,13,32,46,48..57,59,61,65..90,106,109..111,188,190..192,219..222');
  313. var _CURSORMOVE_KEY_MAP = _toMap('33..40');
  314. var _CHANGE_KEY_MAP = {};
  315. _each(_INPUT_KEY_MAP, function(key, val) {
  316. _CHANGE_KEY_MAP[key] = val;
  317. });
  318. _each(_CURSORMOVE_KEY_MAP, function(key, val) {
  319. _CHANGE_KEY_MAP[key] = val;
  320. });
  321. function _bindEvent(el, type, fn) {
  322. if (el.addEventListener){
  323. el.addEventListener(type, fn, _useCapture);
  324. } else if (el.attachEvent){
  325. el.attachEvent('on' + type, fn);
  326. }
  327. }
  328. function _unbindEvent(el, type, fn) {
  329. if (el.removeEventListener){
  330. el.removeEventListener(type, fn, _useCapture);
  331. } else if (el.detachEvent){
  332. el.detachEvent('on' + type, fn);
  333. }
  334. }
  335. var _EVENT_PROPS = ('altKey,attrChange,attrName,bubbles,button,cancelable,charCode,clientX,clientY,ctrlKey,currentTarget,' +
  336. 'data,detail,eventPhase,fromElement,handler,keyCode,metaKey,newValue,offsetX,offsetY,originalTarget,pageX,' +
  337. 'pageY,prevValue,relatedNode,relatedTarget,screenX,screenY,shiftKey,srcElement,target,toElement,view,wheelDelta,which').split(',');
  338. function KEvent(el, event) {
  339. this.init(el, event);
  340. }
  341. _extend(KEvent, {
  342. init : function(el, event) {
  343. var self = this, doc = el.ownerDocument || el.document || el;
  344. self.event = event;
  345. _each(_EVENT_PROPS, function(key, val) {
  346. self[val] = event[val];
  347. });
  348. if (!self.target) {
  349. self.target = self.srcElement || doc;
  350. }
  351. if (self.target.nodeType === 3) {
  352. self.target = self.target.parentNode;
  353. }
  354. if (!self.relatedTarget && self.fromElement) {
  355. self.relatedTarget = self.fromElement === self.target ? self.toElement : self.fromElement;
  356. }
  357. if (self.pageX == null && self.clientX != null) {
  358. var d = doc.documentElement, body = doc.body;
  359. self.pageX = self.clientX + (d && d.scrollLeft || body && body.scrollLeft || 0) - (d && d.clientLeft || body && body.clientLeft || 0);
  360. self.pageY = self.clientY + (d && d.scrollTop || body && body.scrollTop || 0) - (d && d.clientTop || body && body.clientTop || 0);
  361. }
  362. if (!self.which && ((self.charCode || self.charCode === 0) ? self.charCode : self.keyCode)) {
  363. self.which = self.charCode || self.keyCode;
  364. }
  365. if (!self.metaKey && self.ctrlKey) {
  366. self.metaKey = self.ctrlKey;
  367. }
  368. if (!self.which && self.button !== undefined) {
  369. self.which = (self.button & 1 ? 1 : (self.button & 2 ? 3 : (self.button & 4 ? 2 : 0)));
  370. }
  371. switch (self.which) {
  372. case 186 :
  373. self.which = 59;
  374. break;
  375. case 187 :
  376. case 107 :
  377. case 43 :
  378. self.which = 61;
  379. break;
  380. case 189 :
  381. case 45 :
  382. self.which = 109;
  383. break;
  384. case 42 :
  385. self.which = 106;
  386. break;
  387. case 47 :
  388. self.which = 111;
  389. break;
  390. case 78 :
  391. self.which = 110;
  392. break;
  393. }
  394. if (self.which >= 96 && self.which <= 105) {
  395. self.which -= 48;
  396. }
  397. },
  398. preventDefault : function() {
  399. var ev = this.event;
  400. if (ev.preventDefault) {
  401. ev.preventDefault();
  402. } else {
  403. ev.returnValue = false;
  404. }
  405. },
  406. stopPropagation : function() {
  407. var ev = this.event;
  408. if (ev.stopPropagation) {
  409. ev.stopPropagation();
  410. } else {
  411. ev.cancelBubble = true;
  412. }
  413. },
  414. stop : function() {
  415. this.preventDefault();
  416. this.stopPropagation();
  417. }
  418. });
  419. var _eventExpendo = 'kindeditor_' + _TIME, _eventId = 0, _eventData = {};
  420. function _getId(el) {
  421. return el[_eventExpendo] || null;
  422. }
  423. function _setId(el) {
  424. el[_eventExpendo] = ++_eventId;
  425. return _eventId;
  426. }
  427. function _removeId(el) {
  428. try {
  429. delete el[_eventExpendo];
  430. } catch(e) {
  431. if (el.removeAttribute) {
  432. el.removeAttribute(_eventExpendo);
  433. }
  434. }
  435. }
  436. function _bind(el, type, fn) {
  437. if (type.indexOf(',') >= 0) {
  438. _each(type.split(','), function() {
  439. _bind(el, this, fn);
  440. });
  441. return;
  442. }
  443. var id = _getId(el);
  444. if (!id) {
  445. id = _setId(el);
  446. }
  447. if (_eventData[id] === undefined) {
  448. _eventData[id] = {};
  449. }
  450. var events = _eventData[id][type];
  451. if (events && events.length > 0) {
  452. _unbindEvent(el, type, events[0]);
  453. } else {
  454. _eventData[id][type] = [];
  455. _eventData[id].el = el;
  456. }
  457. events = _eventData[id][type];
  458. if (events.length === 0) {
  459. events[0] = function(e) {
  460. var kevent = e ? new KEvent(el, e) : undefined;
  461. _each(events, function(i, event) {
  462. if (i > 0 && event) {
  463. event.call(el, kevent);
  464. }
  465. });
  466. };
  467. }
  468. if (_inArray(fn, events) < 0) {
  469. events.push(fn);
  470. }
  471. _bindEvent(el, type, events[0]);
  472. }
  473. function _unbind(el, type, fn) {
  474. if (type && type.indexOf(',') >= 0) {
  475. _each(type.split(','), function() {
  476. _unbind(el, this, fn);
  477. });
  478. return;
  479. }
  480. var id = _getId(el);
  481. if (!id) {
  482. return;
  483. }
  484. if (type === undefined) {
  485. if (id in _eventData) {
  486. _each(_eventData[id], function(key, events) {
  487. if (key != 'el' && events.length > 0) {
  488. _unbindEvent(el, key, events[0]);
  489. }
  490. });
  491. delete _eventData[id];
  492. _removeId(el);
  493. }
  494. return;
  495. }
  496. if (!_eventData[id]) {
  497. return;
  498. }
  499. var events = _eventData[id][type];
  500. if (events && events.length > 0) {
  501. if (fn === undefined) {
  502. _unbindEvent(el, type, events[0]);
  503. delete _eventData[id][type];
  504. } else {
  505. _each(events, function(i, event) {
  506. if (i > 0 && event === fn) {
  507. events.splice(i, 1);
  508. }
  509. });
  510. if (events.length == 1) {
  511. _unbindEvent(el, type, events[0]);
  512. delete _eventData[id][type];
  513. }
  514. }
  515. var count = 0;
  516. _each(_eventData[id], function() {
  517. count++;
  518. });
  519. if (count < 2) {
  520. delete _eventData[id];
  521. _removeId(el);
  522. }
  523. }
  524. }
  525. function _fire(el, type) {
  526. if (type.indexOf(',') >= 0) {
  527. _each(type.split(','), function() {
  528. _fire(el, this);
  529. });
  530. return;
  531. }
  532. var id = _getId(el);
  533. if (!id) {
  534. return;
  535. }
  536. var events = _eventData[id][type];
  537. if (_eventData[id] && events && events.length > 0) {
  538. events[0]();
  539. }
  540. }
  541. function _ctrl(el, key, fn) {
  542. var self = this;
  543. key = /^\d{2,}$/.test(key) ? key : key.toUpperCase().charCodeAt(0);
  544. _bind(el, 'keydown', function(e) {
  545. if (e.ctrlKey && e.which == key && !e.shiftKey && !e.altKey) {
  546. fn.call(el);
  547. e.stop();
  548. }
  549. });
  550. }
  551. var _readyFinished = false;
  552. function _ready(fn) {
  553. console.log(fn)
  554. if (_readyFinished) {
  555. fn(KindEditor);
  556. return;
  557. }
  558. var loaded = false;
  559. function readyFunc() {
  560. if (!loaded) {
  561. loaded = true;
  562. fn(KindEditor);
  563. _readyFinished = true;
  564. }
  565. }
  566. function ieReadyFunc() {
  567. if (!loaded) {
  568. try {
  569. document.documentElement.doScroll('left');
  570. } catch(e) {
  571. setTimeout(ieReadyFunc, 100);
  572. return;
  573. }
  574. readyFunc();
  575. }
  576. }
  577. function ieReadyStateFunc() {
  578. if (document.readyState === 'complete') {
  579. readyFunc();
  580. }
  581. }
  582. if (document.addEventListener) {
  583. _bind(document, 'DOMContentLoaded', readyFunc);
  584. } else if (document.attachEvent) {
  585. _bind(document, 'readystatechange', ieReadyStateFunc);
  586. var toplevel = false;
  587. try {
  588. toplevel = window.frameElement == null;
  589. } catch(e) {}
  590. if (document.documentElement.doScroll && toplevel) {
  591. ieReadyFunc();
  592. }
  593. }
  594. _bind(window, 'load', readyFunc);
  595. }
  596. if (window.attachEvent) {
  597. window.attachEvent('onunload', function() {
  598. _each(_eventData, function(key, events) {
  599. if (events.el) {
  600. _unbind(events.el);
  601. }
  602. });
  603. });
  604. }
  605. K.ctrl = _ctrl;
  606. K.ready = _ready;
  607. function _getCssList(css) {
  608. var list = {},
  609. reg = /\s*([\w\-]+)\s*:([^;]*)(;|$)/g,
  610. match;
  611. while ((match = reg.exec(css))) {
  612. var key = _trim(match[1].toLowerCase()),
  613. val = _trim(_toHex(match[2]));
  614. list[key] = val;
  615. }
  616. return list;
  617. }
  618. function _getAttrList(tag) {
  619. var list = {},
  620. reg = /\s+(?:([\w\-:]+)|(?:([\w\-:]+)=([^\s"'<>]+))|(?:([\w\-:"]+)="([^"]*)")|(?:([\w\-:"]+)='([^']*)'))(?=(?:\s|\/|>)+)/g,
  621. match;
  622. while ((match = reg.exec(tag))) {
  623. var key = (match[1] || match[2] || match[4] || match[6]).toLowerCase(),
  624. val = (match[2] ? match[3] : (match[4] ? match[5] : match[7])) || '';
  625. list[key] = val;
  626. }
  627. return list;
  628. }
  629. function _addClassToTag(tag, className) {
  630. if (/\s+class\s*=/.test(tag)) {
  631. tag = tag.replace(/(\s+class=["']?)([^"']*)(["']?[\s>])/, function($0, $1, $2, $3) {
  632. if ((' ' + $2 + ' ').indexOf(' ' + className + ' ') < 0) {
  633. return $2 === '' ? $1 + className + $3 : $1 + $2 + ' ' + className + $3;
  634. } else {
  635. return $0;
  636. }
  637. });
  638. } else {
  639. tag = tag.substr(0, tag.length - 1) + ' class="' + className + '">';
  640. }
  641. return tag;
  642. }
  643. function _formatCss(css) {
  644. var str = '';
  645. _each(_getCssList(css), function(key, val) {
  646. str += key + ':' + val + ';';
  647. });
  648. return str;
  649. }
  650. function _formatUrl(url, mode, host, pathname) {
  651. mode = _undef(mode, '').toLowerCase();
  652. if (url.substr(0, 5) != 'data:') {
  653. url = url.replace(/([^:])\/\//g, '$1/');
  654. }
  655. if (_inArray(mode, ['absolute', 'relative', 'domain']) < 0) {
  656. return url;
  657. }
  658. host = host || location.protocol + '//' + location.host;
  659. if (pathname === undefined) {
  660. var m = location.pathname.match(/^(\/.*)\//);
  661. pathname = m ? m[1] : '';
  662. }
  663. var match;
  664. if ((match = /^(\w+:\/\/[^\/]*)/.exec(url))) {
  665. if (match[1] !== host) {
  666. return url;
  667. }
  668. } else if (/^\w+:/.test(url)) {
  669. return url;
  670. }
  671. function getRealPath(path) {
  672. var parts = path.split('/'), paths = [];
  673. for (var i = 0, len = parts.length; i < len; i++) {
  674. var part = parts[i];
  675. if (part == '..') {
  676. if (paths.length > 0) {
  677. paths.pop();
  678. }
  679. } else if (part !== '' && part != '.') {
  680. paths.push(part);
  681. }
  682. }
  683. return '/' + paths.join('/');
  684. }
  685. if (/^\//.test(url)) {
  686. url = host + getRealPath(url.substr(1));
  687. } else if (!/^\w+:\/\//.test(url)) {
  688. url = host + getRealPath(pathname + '/' + url);
  689. }
  690. function getRelativePath(path, depth) {
  691. if (url.substr(0, path.length) === path) {
  692. var arr = [];
  693. for (var i = 0; i < depth; i++) {
  694. arr.push('..');
  695. }
  696. var prefix = '.';
  697. if (arr.length > 0) {
  698. prefix += '/' + arr.join('/');
  699. }
  700. if (pathname == '/') {
  701. prefix += '/';
  702. }
  703. return prefix + url.substr(path.length);
  704. } else {
  705. if ((match = /^(.*)\//.exec(path))) {
  706. return getRelativePath(match[1], ++depth);
  707. }
  708. }
  709. }
  710. if (mode === 'relative') {
  711. url = getRelativePath(host + pathname, 0).substr(2);
  712. } else if (mode === 'absolute') {
  713. if (url.substr(0, host.length) === host) {
  714. url = url.substr(host.length);
  715. }
  716. }
  717. return url;
  718. }
  719. function _formatHtml(html, htmlTags, urlType, wellFormatted, indentChar) {
  720. if (html == null) {
  721. html = '';
  722. }
  723. urlType = urlType || '';
  724. wellFormatted = _undef(wellFormatted, false);
  725. indentChar = _undef(indentChar, '\t');
  726. var fontSizeList = 'xx-small,x-small,small,medium,large,x-large,xx-large'.split(',');
  727. html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function($0, $1, $2, $3) {
  728. return $1 + $2.replace(/<(?:br|br\s[^>]*)>/ig, '\n') + $3;
  729. });
  730. html = html.replace(/<(?:br|br\s[^>]*)\s*\/?>\s*<\/p>/ig, '</p>');
  731. html = html.replace(/(<(?:p|p\s[^>]*)>)\s*(<\/p>)/ig, '$1<br />$2');
  732. html = html.replace(/\u200B/g, '');
  733. html = html.replace(/\u00A9/g, '&copy;');
  734. html = html.replace(/\u00AE/g, '&reg;');
  735. html = html.replace(/\u2003/g, '&emsp;');
  736. html = html.replace(/\u3000/g, '&emsp;');
  737. html = html.replace(/<[^>]+/g, function($0) {
  738. return $0.replace(/\s+/g, ' ');
  739. });
  740. var htmlTagMap = {};
  741. if (htmlTags) {
  742. _each(htmlTags, function(key, val) {
  743. var arr = key.split(',');
  744. for (var i = 0, len = arr.length; i < len; i++) {
  745. htmlTagMap[arr[i]] = _toMap(val);
  746. }
  747. });
  748. if (!htmlTagMap.script) {
  749. html = html.replace(/(<(?:script|script\s[^>]*)>)([\s\S]*?)(<\/script>)/ig, '');
  750. }
  751. if (!htmlTagMap.style) {
  752. html = html.replace(/(<(?:style|style\s[^>]*)>)([\s\S]*?)(<\/style>)/ig, '');
  753. }
  754. }
  755. var re = /(\s*)<(\/)?([\w\-:]+)((?:\s+|(?:\s+[\w\-:]+)|(?:\s+[\w\-:]+=[^\s"'<>]+)|(?:\s+[\w\-:"]+="[^"]*")|(?:\s+[\w\-:"]+='[^']*'))*)(\/)?>(\s*)/g;
  756. var tagStack = [];
  757. html = html.replace(re, function($0, $1, $2, $3, $4, $5, $6) {
  758. var full = $0,
  759. startNewline = $1 || '',
  760. startSlash = $2 || '',
  761. tagName = $3.toLowerCase(),
  762. attr = $4 || '',
  763. endSlash = $5 ? ' ' + $5 : '',
  764. endNewline = $6 || '';
  765. if (htmlTags && !htmlTagMap[tagName]) {
  766. return '';
  767. }
  768. if (endSlash === '' && _SINGLE_TAG_MAP[tagName]) {
  769. endSlash = ' /';
  770. }
  771. if (_INLINE_TAG_MAP[tagName]) {
  772. if (startNewline) {
  773. startNewline = ' ';
  774. }
  775. if (endNewline) {
  776. endNewline = ' ';
  777. }
  778. }
  779. if (_PRE_TAG_MAP[tagName]) {
  780. if (startSlash) {
  781. endNewline = '\n';
  782. } else {
  783. startNewline = '\n';
  784. }
  785. }
  786. if (wellFormatted && tagName == 'br') {
  787. endNewline = '\n';
  788. }
  789. if (_BLOCK_TAG_MAP[tagName] && !_PRE_TAG_MAP[tagName]) {
  790. if (wellFormatted) {
  791. if (startSlash && tagStack.length > 0 && tagStack[tagStack.length - 1] === tagName) {
  792. tagStack.pop();
  793. } else {
  794. tagStack.push(tagName);
  795. }
  796. startNewline = '\n';
  797. endNewline = '\n';
  798. for (var i = 0, len = startSlash ? tagStack.length : tagStack.length - 1; i < len; i++) {
  799. startNewline += indentChar;
  800. if (!startSlash) {
  801. endNewline += indentChar;
  802. }
  803. }
  804. if (endSlash) {
  805. tagStack.pop();
  806. } else if (!startSlash) {
  807. endNewline += indentChar;
  808. }
  809. } else {
  810. startNewline = endNewline = '';
  811. }
  812. }
  813. if (attr !== '') {
  814. var attrMap = _getAttrList(full);
  815. if (tagName === 'font') {
  816. var fontStyleMap = {}, fontStyle = '';
  817. _each(attrMap, function(key, val) {
  818. if (key === 'color') {
  819. fontStyleMap.color = val;
  820. delete attrMap[key];
  821. }
  822. if (key === 'size') {
  823. fontStyleMap['font-size'] = fontSizeList[parseInt(val, 10) - 1] || '';
  824. delete attrMap[key];
  825. }
  826. if (key === 'face') {
  827. fontStyleMap['font-family'] = val;
  828. delete attrMap[key];
  829. }
  830. if (key === 'style') {
  831. fontStyle = val;
  832. }
  833. });
  834. if (fontStyle && !/;$/.test(fontStyle)) {
  835. fontStyle += ';';
  836. }
  837. _each(fontStyleMap, function(key, val) {
  838. if (val === '') {
  839. return;
  840. }
  841. if (/\s/.test(val)) {
  842. val = "'" + val + "'";
  843. }
  844. fontStyle += key + ':' + val + ';';
  845. });
  846. attrMap.style = fontStyle;
  847. }
  848. _each(attrMap, function(key, val) {
  849. if (_FILL_ATTR_MAP[key]) {
  850. attrMap[key] = key;
  851. }
  852. if (_inArray(key, ['src', 'href']) >= 0) {
  853. attrMap[key] = _formatUrl(val, urlType);
  854. }
  855. if (htmlTags && key !== 'style' && !htmlTagMap[tagName]['*'] && !htmlTagMap[tagName][key] ||
  856. tagName === 'body' && key === 'contenteditable' ||
  857. /^kindeditor_\d+$/.test(key)) {
  858. delete attrMap[key];
  859. }
  860. if (key === 'style' && val !== '') {
  861. var styleMap = _getCssList(val);
  862. _each(styleMap, function(k, v) {
  863. if (htmlTags && !htmlTagMap[tagName].style && !htmlTagMap[tagName]['.' + k]) {
  864. delete styleMap[k];
  865. }
  866. });
  867. var style = '';
  868. _each(styleMap, function(k, v) {
  869. style += k + ':' + v + ';';
  870. });
  871. attrMap.style = style;
  872. }
  873. });
  874. attr = '';
  875. _each(attrMap, function(key, val) {
  876. if (key === 'style' && val === '') {
  877. return;
  878. }
  879. val = val.replace(/"/g, '&quot;');
  880. attr += ' ' + key + '="' + val + '"';
  881. });
  882. }
  883. if (tagName === 'font') {
  884. tagName = 'span';
  885. }
  886. return startNewline + '<' + startSlash + tagName + attr + endSlash + '>' + endNewline;
  887. });
  888. html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function($0, $1, $2, $3) {
  889. return $1 + $2.replace(/\n/g, '<span id="__kindeditor_pre_newline__">\n') + $3;
  890. });
  891. html = html.replace(/\n\s*\n/g, '\n');
  892. html = html.replace(/<span id="__kindeditor_pre_newline__">\n/g, '\n');
  893. return _trim(html);
  894. }
  895. function _clearMsWord(html, htmlTags) {
  896. html = html.replace(/<meta[\s\S]*?>/ig, '')
  897. .replace(/<![\s\S]*?>/ig, '')
  898. .replace(/<style[^>]*>[\s\S]*?<\/style>/ig, '')
  899. .replace(/<script[^>]*>[\s\S]*?<\/script>/ig, '')
  900. .replace(/<w:[^>]+>[\s\S]*?<\/w:[^>]+>/ig, '')
  901. .replace(/<o:[^>]+>[\s\S]*?<\/o:[^>]+>/ig, '')
  902. .replace(/<xml>[\s\S]*?<\/xml>/ig, '')
  903. .replace(/<(?:table|td)[^>]*>/ig, function(full) {
  904. return full.replace(/border-bottom:([#\w\s]+)/ig, 'border:$1');
  905. });
  906. return _formatHtml(html, htmlTags);
  907. }
  908. function _mediaType(src) {
  909. if (/\.(rm|rmvb)(\?|$)/i.test(src)) {
  910. return 'audio/x-pn-realaudio-plugin';
  911. }
  912. if (/\.(swf|flv)(\?|$)/i.test(src)) {
  913. return 'application/x-shockwave-flash';
  914. }
  915. return 'video/x-ms-asf-plugin';
  916. }
  917. function _mediaClass(type) {
  918. if (/realaudio/i.test(type)) {
  919. return 'ke-rm';
  920. }
  921. if (/flash/i.test(type)) {
  922. return 'ke-flash';
  923. }
  924. return 'ke-media';
  925. }
  926. function _mediaAttrs(srcTag) {
  927. return _getAttrList(unescape(srcTag));
  928. }
  929. function _mediaEmbed(attrs) {
  930. var html = '<embed ';
  931. _each(attrs, function(key, val) {
  932. html += key + '="' + val + '" ';
  933. });
  934. html += '/>';
  935. return html;
  936. }
  937. function _mediaImg(blankPath, attrs) {
  938. var width = attrs.width,
  939. height = attrs.height,
  940. type = attrs.type || _mediaType(attrs.src),
  941. srcTag = _mediaEmbed(attrs),
  942. style = '';
  943. if (/\D/.test(width)) {
  944. style += 'width:' + width + ';';
  945. } else if (width > 0) {
  946. style += 'width:' + width + 'px;';
  947. }
  948. if (/\D/.test(height)) {
  949. style += 'height:' + height + ';';
  950. } else if (height > 0) {
  951. style += 'height:' + height + 'px;';
  952. }
  953. var html = '<img class="' + _mediaClass(type) + '" src="' + blankPath + '" ';
  954. if (style !== '') {
  955. html += 'style="' + style + '" ';
  956. }
  957. html += 'data-ke-tag="' + escape(srcTag) + '" alt="" />';
  958. return html;
  959. }
  960. function _tmpl(str, data) {
  961. var fn = new Function("obj",
  962. "var p=[],print=function(){p.push.apply(p,arguments);};" +
  963. "with(obj){p.push('" +
  964. str.replace(/[\r\t\n]/g, " ")
  965. .split("<%").join("\t")
  966. .replace(/((^|%>)[^\t]*)'/g, "$1\r")
  967. .replace(/\t=(.*?)%>/g, "',$1,'")
  968. .split("\t").join("');")
  969. .split("%>").join("p.push('")
  970. .split("\r").join("\\'") + "');}return p.join('');");
  971. return data ? fn(data) : fn;
  972. }
  973. K.formatUrl = _formatUrl;
  974. K.formatHtml = _formatHtml;
  975. K.getCssList = _getCssList;
  976. K.getAttrList = _getAttrList;
  977. K.mediaType = _mediaType;
  978. K.mediaAttrs = _mediaAttrs;
  979. K.mediaEmbed = _mediaEmbed;
  980. K.mediaImg = _mediaImg;
  981. K.clearMsWord = _clearMsWord;
  982. K.tmpl = _tmpl;
  983. function _contains(nodeA, nodeB) {
  984. if (nodeA.nodeType == 9 && nodeB.nodeType != 9) {
  985. return true;
  986. }
  987. while ((nodeB = nodeB.parentNode)) {
  988. if (nodeB == nodeA) {
  989. return true;
  990. }
  991. }
  992. return false;
  993. }
  994. var _getSetAttrDiv = document.createElement('div');
  995. _getSetAttrDiv.setAttribute('className', 't');
  996. var _GET_SET_ATTRIBUTE = _getSetAttrDiv.className !== 't';
  997. function _getAttr(el, key) {
  998. key = key.toLowerCase();
  999. var val = null;
  1000. if (!_GET_SET_ATTRIBUTE && el.nodeName.toLowerCase() != 'script') {
  1001. var div = el.ownerDocument.createElement('div');
  1002. div.appendChild(el.cloneNode(false));
  1003. var list = _getAttrList(_unescape(div.innerHTML));
  1004. if (key in list) {
  1005. val = list[key];
  1006. }
  1007. } else {
  1008. try {
  1009. val = el.getAttribute(key, 2);
  1010. } catch(e) {
  1011. val = el.getAttribute(key, 1);
  1012. }
  1013. }
  1014. if (key === 'style' && val !== null) {
  1015. val = _formatCss(val);
  1016. }
  1017. return val;
  1018. }
  1019. function _queryAll(expr, root) {
  1020. var exprList = expr.split(',');
  1021. if (exprList.length > 1) {
  1022. var mergedResults = [];
  1023. _each(exprList, function() {
  1024. _each(_queryAll(this, root), function() {
  1025. if (_inArray(this, mergedResults) < 0) {
  1026. mergedResults.push(this);
  1027. }
  1028. });
  1029. });
  1030. return mergedResults;
  1031. }
  1032. root = root || document;
  1033. function escape(str) {
  1034. if (typeof str != 'string') {
  1035. return str;
  1036. }
  1037. return str.replace(/([^\w\-])/g, '\\$1');
  1038. }
  1039. function stripslashes(str) {
  1040. return str.replace(/\\/g, '');
  1041. }
  1042. function cmpTag(tagA, tagB) {
  1043. return tagA === '*' || tagA.toLowerCase() === escape(tagB.toLowerCase());
  1044. }
  1045. function byId(id, tag, root) {
  1046. var arr = [],
  1047. doc = root.ownerDocument || root,
  1048. el = doc.getElementById(stripslashes(id));
  1049. if (el) {
  1050. if (cmpTag(tag, el.nodeName) && _contains(root, el)) {
  1051. arr.push(el);
  1052. }
  1053. }
  1054. return arr;
  1055. }
  1056. function byClass(className, tag, root) {
  1057. var doc = root.ownerDocument || root, arr = [], els, i, len, el;
  1058. if (root.getElementsByClassName) {
  1059. els = root.getElementsByClassName(stripslashes(className));
  1060. for (i = 0, len = els.length; i < len; i++) {
  1061. el = els[i];
  1062. if (cmpTag(tag, el.nodeName)) {
  1063. arr.push(el);
  1064. }
  1065. }
  1066. } else if (doc.querySelectorAll) {
  1067. els = doc.querySelectorAll((root.nodeName !== '#document' ? root.nodeName + ' ' : '') + tag + '.' + className);
  1068. for (i = 0, len = els.length; i < len; i++) {
  1069. el = els[i];
  1070. if (_contains(root, el)) {
  1071. arr.push(el);
  1072. }
  1073. }
  1074. } else {
  1075. els = root.getElementsByTagName(tag);
  1076. className = ' ' + className + ' ';
  1077. for (i = 0, len = els.length; i < len; i++) {
  1078. el = els[i];
  1079. if (el.nodeType == 1) {
  1080. var cls = el.className;
  1081. if (cls && (' ' + cls + ' ').indexOf(className) > -1) {
  1082. arr.push(el);
  1083. }
  1084. }
  1085. }
  1086. }
  1087. return arr;
  1088. }
  1089. function byName(name, tag, root) {
  1090. var arr = [], doc = root.ownerDocument || root,
  1091. els = doc.getElementsByName(stripslashes(name)), el;
  1092. for (var i = 0, len = els.length; i < len; i++) {
  1093. el = els[i];
  1094. if (cmpTag(tag, el.nodeName) && _contains(root, el)) {
  1095. if (el.getAttribute('name') !== null) {
  1096. arr.push(el);
  1097. }
  1098. }
  1099. }
  1100. return arr;
  1101. }
  1102. function byAttr(key, val, tag, root) {
  1103. var arr = [], els = root.getElementsByTagName(tag), el;
  1104. for (var i = 0, len = els.length; i < len; i++) {
  1105. el = els[i];
  1106. if (el.nodeType == 1) {
  1107. if (val === null) {
  1108. if (_getAttr(el, key) !== null) {
  1109. arr.push(el);
  1110. }
  1111. } else {
  1112. if (val === escape(_getAttr(el, key))) {
  1113. arr.push(el);
  1114. }
  1115. }
  1116. }
  1117. }
  1118. return arr;
  1119. }
  1120. function select(expr, root) {
  1121. var arr = [], matches;
  1122. matches = /^((?:\\.|[^.#\s\[<>])+)/.exec(expr);
  1123. var tag = matches ? matches[1] : '*';
  1124. if ((matches = /#((?:[\w\-]|\\.)+)$/.exec(expr))) {
  1125. arr = byId(matches[1], tag, root);
  1126. } else if ((matches = /\.((?:[\w\-]|\\.)+)$/.exec(expr))) {
  1127. arr = byClass(matches[1], tag, root);
  1128. } else if ((matches = /\[((?:[\w\-]|\\.)+)\]/.exec(expr))) {
  1129. arr = byAttr(matches[1].toLowerCase(), null, tag, root);
  1130. } else if ((matches = /\[((?:[\w\-]|\\.)+)\s*=\s*['"]?((?:\\.|[^'"]+)+)['"]?\]/.exec(expr))) {
  1131. var key = matches[1].toLowerCase(), val = matches[2];
  1132. if (key === 'id') {
  1133. arr = byId(val, tag, root);
  1134. } else if (key === 'class') {
  1135. arr = byClass(val, tag, root);
  1136. } else if (key === 'name') {
  1137. arr = byName(val, tag, root);
  1138. } else {
  1139. arr = byAttr(key, val, tag, root);
  1140. }
  1141. } else {
  1142. var els = root.getElementsByTagName(tag), el;
  1143. for (var i = 0, len = els.length; i < len; i++) {
  1144. el = els[i];
  1145. if (el.nodeType == 1) {
  1146. arr.push(el);
  1147. }
  1148. }
  1149. }
  1150. return arr;
  1151. }
  1152. var parts = [], arr, re = /((?:\\.|[^\s>])+|[\s>])/g;
  1153. while ((arr = re.exec(expr))) {
  1154. if (arr[1] !== ' ') {
  1155. parts.push(arr[1]);
  1156. }
  1157. }
  1158. var results = [];
  1159. if (parts.length == 1) {
  1160. return select(parts[0], root);
  1161. }
  1162. var isChild = false, part, els, subResults, val, v, i, j, k, length, len, l;
  1163. for (i = 0, lenth = parts.length; i < lenth; i++) {
  1164. part = parts[i];
  1165. if (part === '>') {
  1166. isChild = true;
  1167. continue;
  1168. }
  1169. if (i > 0) {
  1170. els = [];
  1171. for (j = 0, len = results.length; j < len; j++) {
  1172. val = results[j];
  1173. subResults = select(part, val);
  1174. for (k = 0, l = subResults.length; k < l; k++) {
  1175. v = subResults[k];
  1176. if (isChild) {
  1177. if (val === v.parentNode) {
  1178. els.push(v);
  1179. }
  1180. } else {
  1181. els.push(v);
  1182. }
  1183. }
  1184. }
  1185. results = els;
  1186. } else {
  1187. results = select(part, root);
  1188. }
  1189. if (results.length === 0) {
  1190. return [];
  1191. }
  1192. }
  1193. return results;
  1194. }
  1195. function _query(expr, root) {
  1196. var arr = _queryAll(expr, root);
  1197. return arr.length > 0 ? arr[0] : null;
  1198. }
  1199. K.query = _query;
  1200. K.queryAll = _queryAll;
  1201. function _get(val) {
  1202. return K(val)[0];
  1203. }
  1204. function _getDoc(node) {
  1205. if (!node) {
  1206. return document;
  1207. }
  1208. return node.ownerDocument || node.document || node;
  1209. }
  1210. function _getWin(node) {
  1211. if (!node) {
  1212. return window;
  1213. }
  1214. var doc = _getDoc(node);
  1215. return doc.parentWindow || doc.defaultView;
  1216. }
  1217. function _setHtml(el, html) {
  1218. if (el.nodeType != 1) {
  1219. return;
  1220. }
  1221. var doc = _getDoc(el);
  1222. try {
  1223. el.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + html;
  1224. var temp = doc.getElementById('__kindeditor_temp_tag__');
  1225. temp.parentNode.removeChild(temp);
  1226. } catch(e) {
  1227. K(el).empty();
  1228. K('@' + html, doc).each(function() {
  1229. el.appendChild(this);
  1230. });
  1231. }
  1232. }
  1233. function _hasClass(el, cls) {
  1234. return _inString(cls, el.className, ' ');
  1235. }
  1236. function _setAttr(el, key, val) {
  1237. if (_IE && _V < 8 && key.toLowerCase() == 'class') {
  1238. key = 'className';
  1239. }
  1240. el.setAttribute(key, '' + val);
  1241. }
  1242. function _removeAttr(el, key) {
  1243. if (_IE && _V < 8 && key.toLowerCase() == 'class') {
  1244. key = 'className';
  1245. }
  1246. _setAttr(el, key, '');
  1247. el.removeAttribute(key);
  1248. }
  1249. function _getNodeName(node) {
  1250. if (!node || !node.nodeName) {
  1251. return '';
  1252. }
  1253. return node.nodeName.toLowerCase();
  1254. }
  1255. function _computedCss(el, key) {
  1256. var self = this, win = _getWin(el), camelKey = _toCamel(key), val = '';
  1257. if (win.getComputedStyle) {
  1258. var style = win.getComputedStyle(el, null);
  1259. val = style[camelKey] || style.getPropertyValue(key) || el.style[camelKey];
  1260. } else if (el.currentStyle) {
  1261. val = el.currentStyle[camelKey] || el.style[camelKey];
  1262. }
  1263. return val;
  1264. }
  1265. function _hasVal(node) {
  1266. return !!_VALUE_TAG_MAP[_getNodeName(node)];
  1267. }
  1268. function _docElement(doc) {
  1269. doc = doc || document;
  1270. return _QUIRKS ? doc.body : doc.documentElement;
  1271. }
  1272. function _docHeight(doc) {
  1273. var el = _docElement(doc);
  1274. return Math.max(el.scrollHeight, el.clientHeight);
  1275. }
  1276. function _docWidth(doc) {
  1277. var el = _docElement(doc);
  1278. return Math.max(el.scrollWidth, el.clientWidth);
  1279. }
  1280. function _getScrollPos(doc) {
  1281. doc = doc || document;
  1282. var x, y;
  1283. if (_IE || _NEWIE || _OPERA) {
  1284. x = _docElement(doc).scrollLeft;
  1285. y = _docElement(doc).scrollTop;
  1286. } else {
  1287. x = _getWin(doc).scrollX;
  1288. y = _getWin(doc).scrollY;
  1289. }
  1290. return {x : x, y : y};
  1291. }
  1292. function KNode(node) {
  1293. this.init(node);
  1294. }
  1295. _extend(KNode, {
  1296. init : function(node) {
  1297. var self = this;
  1298. node = _isArray(node) ? node : [node];
  1299. var length = 0;
  1300. for (var i = 0, len = node.length; i < len; i++) {
  1301. if (node[i]) {
  1302. self[i] = node[i].constructor === KNode ? node[i][0] : node[i];
  1303. length++;
  1304. }
  1305. }
  1306. self.length = length;
  1307. self.doc = _getDoc(self[0]);
  1308. self.name = _getNodeName(self[0]);
  1309. self.type = self.length > 0 ? self[0].nodeType : null;
  1310. self.win = _getWin(self[0]);
  1311. },
  1312. each : function(fn) {
  1313. var self = this;
  1314. for (var i = 0; i < self.length; i++) {
  1315. if (fn.call(self[i], i, self[i]) === false) {
  1316. return self;
  1317. }
  1318. }
  1319. return self;
  1320. },
  1321. bind : function(type, fn) {
  1322. this.each(function() {
  1323. _bind(this, type, fn);
  1324. });
  1325. return this;
  1326. },
  1327. unbind : function(type, fn) {
  1328. this.each(function() {
  1329. _unbind(this, type, fn);
  1330. });
  1331. return this;
  1332. },
  1333. fire : function(type) {
  1334. if (this.length < 1) {
  1335. return this;
  1336. }
  1337. _fire(this[0], type);
  1338. return this;
  1339. },
  1340. hasAttr : function(key) {
  1341. if (this.length < 1) {
  1342. return false;
  1343. }
  1344. return !!_getAttr(this[0], key);
  1345. },
  1346. attr : function(key, val) {
  1347. var self = this;
  1348. if (key === undefined) {
  1349. return _getAttrList(self.outer());
  1350. }
  1351. if (typeof key === 'object') {
  1352. _each(key, function(k, v) {
  1353. self.attr(k, v);
  1354. });
  1355. return self;
  1356. }
  1357. if (val === undefined) {
  1358. val = self.length < 1 ? null : _getAttr(self[0], key);
  1359. return val === null ? '' : val;
  1360. }
  1361. self.each(function() {
  1362. _setAttr(this, key, val);
  1363. });
  1364. return self;
  1365. },
  1366. removeAttr : function(key) {
  1367. this.each(function() {
  1368. _removeAttr(this, key);
  1369. });
  1370. return this;
  1371. },
  1372. get : function(i) {
  1373. if (this.length < 1) {
  1374. return null;
  1375. }
  1376. return this[i || 0];
  1377. },
  1378. eq : function(i) {
  1379. if (this.length < 1) {
  1380. return null;
  1381. }
  1382. return this[i] ? new KNode(this[i]) : null;
  1383. },
  1384. hasClass : function(cls) {
  1385. if (this.length < 1) {
  1386. return false;
  1387. }
  1388. return _hasClass(this[0], cls);
  1389. },
  1390. addClass : function(cls) {
  1391. this.each(function() {
  1392. if (!_hasClass(this, cls)) {
  1393. this.className = _trim(this.className + ' ' + cls);
  1394. }
  1395. });
  1396. return this;
  1397. },
  1398. removeClass : function(cls) {
  1399. this.each(function() {
  1400. if (_hasClass(this, cls)) {
  1401. this.className = _trim(this.className.replace(new RegExp('(^|\\s)' + cls + '(\\s|$)'), ' '));
  1402. }
  1403. });
  1404. return this;
  1405. },
  1406. html : function(val) {
  1407. var self = this;
  1408. if (val === undefined) {
  1409. if (self.length < 1 || self.type != 1) {
  1410. return '';
  1411. }
  1412. return _formatHtml(self[0].innerHTML);
  1413. }
  1414. self.each(function() {
  1415. _setHtml(this, val);
  1416. });
  1417. return self;
  1418. },
  1419. text : function() {
  1420. var self = this;
  1421. if (self.length < 1) {
  1422. return '';
  1423. }
  1424. return _IE ? self[0].innerText : self[0].textContent;
  1425. },
  1426. hasVal : function() {
  1427. if (this.length < 1) {
  1428. return false;
  1429. }
  1430. return _hasVal(this[0]);
  1431. },
  1432. val : function(val) {
  1433. var self = this;
  1434. if (val === undefined) {
  1435. if (self.length < 1) {
  1436. return '';
  1437. }
  1438. return self.hasVal() ? self[0].value : self.attr('value');
  1439. } else {
  1440. self.each(function() {
  1441. if (_hasVal(this)) {
  1442. this.value = val;
  1443. } else {
  1444. _setAttr(this, 'value' , val);
  1445. }
  1446. });
  1447. return self;
  1448. }
  1449. },
  1450. css : function(key, val) {
  1451. var self = this;
  1452. if (key === undefined) {
  1453. return _getCssList(self.attr('style'));
  1454. }
  1455. if (typeof key === 'object') {
  1456. _each(key, function(k, v) {
  1457. self.css(k, v);
  1458. });
  1459. return self;
  1460. }
  1461. if (val === undefined) {
  1462. if (self.length < 1) {
  1463. return '';
  1464. }
  1465. return self[0].style[_toCamel(key)] || _computedCss(self[0], key) || '';
  1466. }
  1467. self.each(function() {
  1468. this.style[_toCamel(key)] = val;
  1469. });
  1470. return self;
  1471. },
  1472. width : function(val) {
  1473. var self = this;
  1474. if (val === undefined) {
  1475. if (self.length < 1) {
  1476. return 0;
  1477. }
  1478. return self[0].offsetWidth;
  1479. }
  1480. return self.css('width', _addUnit(val));
  1481. },
  1482. height : function(val) {
  1483. var self = this;
  1484. if (val === undefined) {
  1485. if (self.length < 1) {
  1486. return 0;
  1487. }
  1488. return self[0].offsetHeight;
  1489. }
  1490. return self.css('height', _addUnit(val));
  1491. },
  1492. opacity : function(val) {
  1493. this.each(function() {
  1494. if (this.style.opacity === undefined) {
  1495. this.style.filter = val == 1 ? '' : 'alpha(opacity=' + (val * 100) + ')';
  1496. } else {
  1497. this.style.opacity = val == 1 ? '' : val;
  1498. }
  1499. });
  1500. return this;
  1501. },
  1502. data : function(key, val) {
  1503. var self = this;
  1504. key = 'kindeditor_data_' + key;
  1505. if (val === undefined) {
  1506. if (self.length < 1) {
  1507. return null;
  1508. }
  1509. return self[0][key];
  1510. }
  1511. this.each(function() {
  1512. this[key] = val;
  1513. });
  1514. return self;
  1515. },
  1516. pos : function() {
  1517. var self = this, node = self[0], x = 0, y = 0;
  1518. if (node) {
  1519. if (node.getBoundingClientRect) {
  1520. var box = node.getBoundingClientRect(),
  1521. pos = _getScrollPos(self.doc);
  1522. x = box.left + pos.x;
  1523. y = box.top + pos.y;
  1524. } else {
  1525. while (node) {
  1526. x += node.offsetLeft;
  1527. y += node.offsetTop;
  1528. node = node.offsetParent;
  1529. }
  1530. }
  1531. }
  1532. return {x : _round(x), y : _round(y)};
  1533. },
  1534. clone : function(bool) {
  1535. if (this.length < 1) {
  1536. return new KNode([]);
  1537. }
  1538. return new KNode(this[0].cloneNode(bool));
  1539. },
  1540. append : function(expr) {
  1541. this.each(function() {
  1542. if (this.appendChild) {
  1543. this.appendChild(_get(expr));
  1544. }
  1545. });
  1546. return this;
  1547. },
  1548. appendTo : function(expr) {
  1549. this.each(function() {
  1550. _get(expr).appendChild(this);
  1551. });
  1552. return this;
  1553. },
  1554. before : function(expr) {
  1555. this.each(function() {
  1556. this.parentNode.insertBefore(_get(expr), this);
  1557. });
  1558. return this;
  1559. },
  1560. after : function(expr) {
  1561. this.each(function() {
  1562. if (this.nextSibling) {
  1563. this.parentNode.insertBefore(_get(expr), this.nextSibling);
  1564. } else {
  1565. this.parentNode.appendChild(_get(expr));
  1566. }
  1567. });
  1568. return this;
  1569. },
  1570. replaceWith : function(expr) {
  1571. var nodes = [];
  1572. this.each(function(i, node) {
  1573. _unbind(node);
  1574. var newNode = _get(expr);
  1575. node.parentNode.replaceChild(newNode, node);
  1576. nodes.push(newNode);
  1577. });
  1578. return K(nodes);
  1579. },
  1580. empty : function() {
  1581. var self = this;
  1582. self.each(function(i, node) {
  1583. var child = node.firstChild;
  1584. while (child) {
  1585. if (!node.parentNode) {
  1586. return;
  1587. }
  1588. var next = child.nextSibling;
  1589. child.parentNode.removeChild(child);
  1590. child = next;
  1591. }
  1592. });
  1593. return self;
  1594. },
  1595. remove : function(keepChilds) {
  1596. var self = this;
  1597. self.each(function(i, node) {
  1598. if (!node.parentNode) {
  1599. return;
  1600. }
  1601. _unbind(node);
  1602. if (keepChilds) {
  1603. var child = node.firstChild;
  1604. while (child) {
  1605. var next = child.nextSibling;
  1606. node.parentNode.insertBefore(child, node);
  1607. child = next;
  1608. }
  1609. }
  1610. node.parentNode.removeChild(node);
  1611. delete self[i];
  1612. });
  1613. self.length = 0;
  1614. return self;
  1615. },
  1616. show : function(val) {
  1617. var self = this;
  1618. if (val === undefined) {
  1619. val = self._originDisplay || '';
  1620. }
  1621. if (self.css('display') != 'none') {
  1622. return self;
  1623. }
  1624. return self.css('display', val);
  1625. },
  1626. hide : function() {
  1627. var self = this;
  1628. if (self.length < 1) {
  1629. return self;
  1630. }
  1631. self._originDisplay = self[0].style.display;
  1632. return self.css('display', 'none');
  1633. },
  1634. outer : function() {
  1635. var self = this;
  1636. if (self.length < 1) {
  1637. return '';
  1638. }
  1639. var div = self.doc.createElement('div'), html;
  1640. div.appendChild(self[0].cloneNode(true));
  1641. html = _formatHtml(div.innerHTML);
  1642. div = null;
  1643. return html;
  1644. },
  1645. isSingle : function() {
  1646. return !!_SINGLE_TAG_MAP[this.name];
  1647. },
  1648. isInline : function() {
  1649. return !!_INLINE_TAG_MAP[this.name];
  1650. },
  1651. isBlock : function() {
  1652. return !!_BLOCK_TAG_MAP[this.name];
  1653. },
  1654. isStyle : function() {
  1655. return !!_STYLE_TAG_MAP[this.name];
  1656. },
  1657. isControl : function() {
  1658. return !!_CONTROL_TAG_MAP[this.name];
  1659. },
  1660. contains : function(otherNode) {
  1661. if (this.length < 1) {
  1662. return false;
  1663. }
  1664. return _contains(this[0], _get(otherNode));
  1665. },
  1666. parent : function() {
  1667. if (this.length < 1) {
  1668. return null;
  1669. }
  1670. var node = this[0].parentNode;
  1671. return node ? new KNode(node) : null;
  1672. },
  1673. children : function() {
  1674. if (this.length < 1) {
  1675. return new KNode([]);
  1676. }
  1677. var list = [], child = this[0].firstChild;
  1678. while (child) {
  1679. if (child.nodeType != 3 || _trim(child.nodeValue) !== '') {
  1680. list.push(child);
  1681. }
  1682. child = child.nextSibling;
  1683. }
  1684. return new KNode(list);
  1685. },
  1686. first : function() {
  1687. var list = this.children();
  1688. return list.length > 0 ? list.eq(0) : null;
  1689. },
  1690. last : function() {
  1691. var list = this.children();
  1692. return list.length > 0 ? list.eq(list.length - 1) : null;
  1693. },
  1694. index : function() {
  1695. if (this.length < 1) {
  1696. return -1;
  1697. }
  1698. var i = -1, sibling = this[0];
  1699. while (sibling) {
  1700. i++;
  1701. sibling = sibling.previousSibling;
  1702. }
  1703. return i;
  1704. },
  1705. prev : function() {
  1706. if (this.length < 1) {
  1707. return null;
  1708. }
  1709. var node = this[0].previousSibling;
  1710. return node ? new KNode(node) : null;
  1711. },
  1712. next : function() {
  1713. if (this.length < 1) {
  1714. return null;
  1715. }
  1716. var node = this[0].nextSibling;
  1717. return node ? new KNode(node) : null;
  1718. },
  1719. scan : function(fn, order) {
  1720. if (this.length < 1) {
  1721. return;
  1722. }
  1723. order = (order === undefined) ? true : order;
  1724. function walk(node) {
  1725. var n = order ? node.firstChild : node.lastChild;
  1726. while (n) {
  1727. var next = order ? n.nextSibling : n.previousSibling;
  1728. if (fn(n) === false) {
  1729. return false;
  1730. }
  1731. if (walk(n) === false) {
  1732. return false;
  1733. }
  1734. n = next;
  1735. }
  1736. }
  1737. walk(this[0]);
  1738. return this;
  1739. }
  1740. });
  1741. _each(('blur,focus,focusin,focusout,load,resize,scroll,unload,click,dblclick,' +
  1742. 'mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,' +
  1743. 'change,select,submit,keydown,keypress,keyup,error,contextmenu').split(','), function(i, type) {
  1744. KNode.prototype[type] = function(fn) {
  1745. return fn ? this.bind(type, fn) : this.fire(type);
  1746. };
  1747. });
  1748. var _K = K;
  1749. K = function(expr, root) {
  1750. if (expr === undefined || expr === null) {
  1751. return;
  1752. }
  1753. function newNode(node) {
  1754. if (!node[0]) {
  1755. node = [];
  1756. }
  1757. return new KNode(node);
  1758. }
  1759. if (typeof expr === 'string') {
  1760. if (root) {
  1761. root = _get(root);
  1762. }
  1763. var length = expr.length;
  1764. if (expr.charAt(0) === '@') {
  1765. expr = expr.substr(1);
  1766. }
  1767. if (expr.length !== length || /<.+>/.test(expr)) {
  1768. var doc = root ? root.ownerDocument || root : document,
  1769. div = doc.createElement('div'), list = [];
  1770. div.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + expr;
  1771. for (var i = 0, len = div.childNodes.length; i < len; i++) {
  1772. var child = div.childNodes[i];
  1773. if (child.id == '__kindeditor_temp_tag__') {
  1774. continue;
  1775. }
  1776. list.push(child);
  1777. }
  1778. return newNode(list);
  1779. }
  1780. return newNode(_queryAll(expr, root));
  1781. }
  1782. if (expr && expr.constructor === KNode) {
  1783. return expr;
  1784. }
  1785. if (expr.toArray) {
  1786. expr = expr.toArray();
  1787. }
  1788. if (_isArray(expr)) {
  1789. return newNode(expr);
  1790. }
  1791. return newNode(_toArray(arguments));
  1792. };
  1793. _each(_K, function(key, val) {
  1794. K[key] = val;
  1795. });
  1796. K.NodeClass = KNode;
  1797. window.KindEditor = K;
  1798. var _START_TO_START = 0,
  1799. _START_TO_END = 1,
  1800. _END_TO_END = 2,
  1801. _END_TO_START = 3,
  1802. _BOOKMARK_ID = 0;
  1803. function _updateCollapsed(range) {
  1804. range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
  1805. return range;
  1806. }
  1807. function _copyAndDelete(range, isCopy, isDelete) {
  1808. var doc = range.doc, nodeList = [];
  1809. function splitTextNode(node, startOffset, endOffset) {
  1810. var length = node.nodeValue.length, centerNode;
  1811. if (isCopy) {
  1812. var cloneNode = node.cloneNode(true);
  1813. if (startOffset > 0) {
  1814. centerNode = cloneNode.splitText(startOffset);
  1815. } else {
  1816. centerNode = cloneNode;
  1817. }
  1818. if (endOffset < length) {
  1819. centerNode.splitText(endOffset - startOffset);
  1820. }
  1821. }
  1822. if (isDelete) {
  1823. var center = node;
  1824. if (startOffset > 0) {
  1825. center = node.splitText(startOffset);
  1826. range.setStart(node, startOffset);
  1827. }
  1828. if (endOffset < length) {
  1829. var right = center.splitText(endOffset - startOffset);
  1830. range.setEnd(right, 0);
  1831. }
  1832. nodeList.push(center);
  1833. }
  1834. return centerNode;
  1835. }
  1836. function removeNodes() {
  1837. if (isDelete) {
  1838. range.up().collapse(true);
  1839. }
  1840. for (var i = 0, len = nodeList.length; i < len; i++) {
  1841. var node = nodeList[i];
  1842. if (node.parentNode) {
  1843. node.parentNode.removeChild(node);
  1844. }
  1845. }
  1846. }
  1847. var copyRange = range.cloneRange().down();
  1848. var start = -1, incStart = -1, incEnd = -1, end = -1,
  1849. ancestor = range.commonAncestor(), frag = doc.createDocumentFragment();
  1850. if (ancestor.nodeType == 3) {
  1851. var textNode = splitTextNode(ancestor, range.startOffset, range.endOffset);
  1852. if (isCopy) {
  1853. frag.appendChild(textNode);
  1854. }
  1855. removeNodes();
  1856. return isCopy ? frag : range;
  1857. }
  1858. function extractNodes(parent, frag) {
  1859. var node = parent.firstChild, nextNode;
  1860. while (node) {
  1861. var testRange = new KRange(doc).selectNode(node);
  1862. start = testRange.compareBoundaryPoints(_START_TO_END, range);
  1863. if (start >= 0 && incStart <= 0) {
  1864. incStart = testRange.compareBoundaryPoints(_START_TO_START, range);
  1865. }
  1866. if (incStart >= 0 && incEnd <= 0) {
  1867. incEnd = testRange.compareBoundaryPoints(_END_TO_END, range);
  1868. }
  1869. if (incEnd >= 0 && end <= 0) {
  1870. end = testRange.compareBoundaryPoints(_END_TO_START, range);
  1871. }
  1872. if (end >= 0) {
  1873. return false;
  1874. }
  1875. nextNode = node.nextSibling;
  1876. if (start > 0) {
  1877. if (node.nodeType == 1) {
  1878. if (incStart >= 0 && incEnd <= 0) {
  1879. if (isCopy) {
  1880. frag.appendChild(node.cloneNode(true));
  1881. }
  1882. if (isDelete) {
  1883. nodeList.push(node);
  1884. }
  1885. } else {
  1886. var childFlag;
  1887. if (isCopy) {
  1888. childFlag = node.cloneNode(false);
  1889. frag.appendChild(childFlag);
  1890. }
  1891. if (extractNodes(node, childFlag) === false) {
  1892. return false;
  1893. }
  1894. }
  1895. } else if (node.nodeType == 3) {
  1896. var textNode;
  1897. if (node == copyRange.startContainer) {
  1898. textNode = splitTextNode(node, copyRange.startOffset, node.nodeValue.length);
  1899. } else if (node == copyRange.endContainer) {
  1900. textNode = splitTextNode(node, 0, copyRange.endOffset);
  1901. } else {
  1902. textNode = splitTextNode(node, 0, node.nodeValue.length);
  1903. }
  1904. if (isCopy) {
  1905. try {
  1906. frag.appendChild(textNode);
  1907. } catch(e) {}
  1908. }
  1909. }
  1910. }
  1911. node = nextNode;
  1912. }
  1913. }
  1914. extractNodes(ancestor, frag);
  1915. if (isDelete) {
  1916. range.up().collapse(true);
  1917. }
  1918. for (var i = 0, len = nodeList.length; i < len; i++) {
  1919. var node = nodeList[i];
  1920. if (node.parentNode) {
  1921. node.parentNode.removeChild(node);
  1922. }
  1923. }
  1924. return isCopy ? frag : range;
  1925. }
  1926. function _moveToElementText(range, el) {
  1927. var node = el;
  1928. while (node) {
  1929. var knode = K(node);
  1930. if (knode.name == 'marquee' || knode.name == 'select') {
  1931. return;
  1932. }
  1933. node = node.parentNode;
  1934. }
  1935. try {
  1936. range.moveToElementText(el);
  1937. } catch(e) {}
  1938. }
  1939. function _getStartEnd(rng, isStart) {
  1940. var doc = rng.parentElement().ownerDocument,
  1941. pointRange = rng.duplicate();
  1942. pointRange.collapse(isStart);
  1943. var parent = pointRange.parentElement(),
  1944. nodes = parent.childNodes;
  1945. if (nodes.length === 0) {
  1946. return {node: parent.parentNode, offset: K(parent).index()};
  1947. }
  1948. var startNode = doc, startPos = 0, cmp = -1;
  1949. var testRange = rng.duplicate();
  1950. _moveToElementText(testRange, parent);
  1951. for (var i = 0, len = nodes.length; i < len; i++) {
  1952. var node = nodes[i];
  1953. cmp = testRange.compareEndPoints('StartToStart', pointRange);
  1954. if (cmp === 0) {
  1955. return {node: node.parentNode, offset: i};
  1956. }
  1957. if (node.nodeType == 1) {
  1958. var nodeRange = rng.duplicate(), dummy, knode = K(node), newNode = node;
  1959. if (knode.isControl()) {
  1960. dummy = doc.createElement('span');
  1961. knode.after(dummy);
  1962. newNode = dummy;
  1963. startPos += knode.text().replace(/\r\n|\n|\r/g, '').length;
  1964. }
  1965. _moveToElementText(nodeRange, newNode);
  1966. testRange.setEndPoint('StartToEnd', nodeRange);
  1967. if (cmp > 0) {
  1968. startPos += nodeRange.text.replace(/\r\n|\n|\r/g, '').length;
  1969. } else {
  1970. startPos = 0;
  1971. }
  1972. if (dummy) {
  1973. K(dummy).remove();
  1974. }
  1975. } else if (node.nodeType == 3) {
  1976. testRange.moveStart('character', node.nodeValue.length);
  1977. startPos += node.nodeValue.length;
  1978. }
  1979. if (cmp < 0) {
  1980. startNode = node;
  1981. }
  1982. }
  1983. if (cmp < 0 && startNode.nodeType == 1) {
  1984. return {node: parent, offset: K(parent.lastChild).index() + 1};
  1985. }
  1986. if (cmp > 0) {
  1987. while (startNode.nextSibling && startNode.nodeType == 1) {
  1988. startNode = startNode.nextSibling;
  1989. }
  1990. }
  1991. testRange = rng.duplicate();
  1992. _moveToElementText(testRange, parent);
  1993. testRange.setEndPoint('StartToEnd', pointRange);
  1994. startPos -= testRange.text.replace(/\r\n|\n|\r/g, '').length;
  1995. if (cmp > 0 && startNode.nodeType == 3) {
  1996. var prevNode = startNode.previousSibling;
  1997. while (prevNode && prevNode.nodeType == 3) {
  1998. startPos -= prevNode.nodeValue.length;
  1999. prevNode = prevNode.previousSibling;
  2000. }
  2001. }
  2002. return {node: startNode, offset: startPos};
  2003. }
  2004. function _getEndRange(node, offset) {
  2005. var doc = node.ownerDocument || node,
  2006. range = doc.body.createTextRange();
  2007. if (doc == node) {
  2008. range.collapse(true);
  2009. return range;
  2010. }
  2011. if (node.nodeType == 1 && node.childNodes.length > 0) {
  2012. var children = node.childNodes, isStart, child;
  2013. if (offset === 0) {
  2014. child = children[0];
  2015. isStart = true;
  2016. } else {
  2017. child = children[offset - 1];
  2018. isStart = false;
  2019. }
  2020. if (!child) {
  2021. return range;
  2022. }
  2023. if (K(child).name === 'head') {
  2024. if (offset === 1) {
  2025. isStart = true;
  2026. }
  2027. if (offset === 2) {
  2028. isStart = false;
  2029. }
  2030. range.collapse(isStart);
  2031. return range;
  2032. }
  2033. if (child.nodeType == 1) {
  2034. var kchild = K(child), span;
  2035. if (kchild.isControl()) {
  2036. span = doc.createElement('span');
  2037. if (isStart) {
  2038. kchild.before(span);
  2039. } else {
  2040. kchild.after(span);
  2041. }
  2042. child = span;
  2043. }
  2044. _moveToElementText(range, child);
  2045. range.collapse(isStart);
  2046. if (span) {
  2047. K(span).remove();
  2048. }
  2049. return range;
  2050. }
  2051. node = child;
  2052. offset = isStart ? 0 : child.nodeValue.length;
  2053. }
  2054. var dummy = doc.createElement('span');
  2055. K(node).before(dummy);
  2056. _moveToElementText(range, dummy);
  2057. range.moveStart('character', offset);
  2058. K(dummy).remove();
  2059. return range;
  2060. }
  2061. function _toRange(rng) {
  2062. var doc, range;
  2063. function tr2td(start) {
  2064. if (K(start.node).name == 'tr') {
  2065. start.node = start.node.cells[start.offset];
  2066. start.offset = 0;
  2067. }
  2068. }
  2069. if (_IERANGE) {
  2070. if (rng.item) {
  2071. doc = _getDoc(rng.item(0));
  2072. range = new KRange(doc);
  2073. range.selectNode(rng.item(0));
  2074. return range;
  2075. }
  2076. doc = rng.parentElement().ownerDocument;
  2077. var start = _getStartEnd(rng, true),
  2078. end = _getStartEnd(rng, false);
  2079. tr2td(start);
  2080. tr2td(end);
  2081. range = new KRange(doc);
  2082. range.setStart(start.node, start.offset);
  2083. range.setEnd(end.node, end.offset);
  2084. return range;
  2085. }
  2086. var startContainer = rng.startContainer;
  2087. doc = startContainer.ownerDocument || startContainer;
  2088. range = new KRange(doc);
  2089. range.setStart(startContainer, rng.startOffset);
  2090. range.setEnd(rng.endContainer, rng.endOffset);
  2091. return range;
  2092. }
  2093. function KRange(doc) {
  2094. this.init(doc);
  2095. }
  2096. _extend(KRange, {
  2097. init : function(doc) {
  2098. var self = this;
  2099. self.startContainer = doc;
  2100. self.startOffset = 0;
  2101. self.endContainer = doc;
  2102. self.endOffset = 0;
  2103. self.collapsed = true;
  2104. self.doc = doc;
  2105. },
  2106. commonAncestor : function() {
  2107. function getParents(node) {
  2108. var parents = [];
  2109. while (node) {
  2110. parents.push(node);
  2111. node = node.parentNode;
  2112. }
  2113. return parents;
  2114. }
  2115. var parentsA = getParents(this.startContainer),
  2116. parentsB = getParents(this.endContainer),
  2117. i = 0, lenA = parentsA.length, lenB = parentsB.length, parentA, parentB;
  2118. while (++i) {
  2119. parentA = parentsA[lenA - i];
  2120. parentB = parentsB[lenB - i];
  2121. if (!parentA || !parentB || parentA !== parentB) {
  2122. break;
  2123. }
  2124. }
  2125. return parentsA[lenA - i + 1];
  2126. },
  2127. setStart : function(node, offset) {
  2128. var self = this, doc = self.doc;
  2129. self.startContainer = node;
  2130. self.startOffset = offset;
  2131. if (self.endContainer === doc) {
  2132. self.endContainer = node;
  2133. self.endOffset = offset;
  2134. }
  2135. return _updateCollapsed(this);
  2136. },
  2137. setEnd : function(node, offset) {
  2138. var self = this, doc = self.doc;
  2139. self.endContainer = node;
  2140. self.endOffset = offset;
  2141. if (self.startContainer === doc) {
  2142. self.startContainer = node;
  2143. self.startOffset = offset;
  2144. }
  2145. return _updateCollapsed(this);
  2146. },
  2147. setStartBefore : function(node) {
  2148. return this.setStart(node.parentNode || this.doc, K(node).index());
  2149. },
  2150. setStartAfter : function(node) {
  2151. return this.setStart(node.parentNode || this.doc, K(node).index() + 1);
  2152. },
  2153. setEndBefore : function(node) {
  2154. return this.setEnd(node.parentNode || this.doc, K(node).index());
  2155. },
  2156. setEndAfter : function(node) {
  2157. return this.setEnd(node.parentNode || this.doc, K(node).index() + 1);
  2158. },
  2159. selectNode : function(node) {
  2160. return this.setStartBefore(node).setEndAfter(node);
  2161. },
  2162. selectNodeContents : function(node) {
  2163. var knode = K(node);
  2164. if (knode.type == 3 || knode.isSingle()) {
  2165. return this.selectNode(node);
  2166. }
  2167. var children = knode.children();
  2168. if (children.length > 0) {
  2169. return this.setStartBefore(children[0]).setEndAfter(children[children.length - 1]);
  2170. }
  2171. return this.setStart(node, 0).setEnd(node, 0);
  2172. },
  2173. collapse : function(toStart) {
  2174. if (toStart) {
  2175. return this.setEnd(this.startContainer, this.startOffset);
  2176. }
  2177. return this.setStart(this.endContainer, this.endOffset);
  2178. },
  2179. compareBoundaryPoints : function(how, range) {
  2180. var rangeA = this.get(), rangeB = range.get();
  2181. if (_IERANGE) {
  2182. var arr = {};
  2183. arr[_START_TO_START] = 'StartToStart';
  2184. arr[_START_TO_END] = 'EndToStart';
  2185. arr[_END_TO_END] = 'EndToEnd';
  2186. arr[_END_TO_START] = 'StartToEnd';
  2187. var cmp = rangeA.compareEndPoints(arr[how], rangeB);
  2188. if (cmp !== 0) {
  2189. return cmp;
  2190. }
  2191. var nodeA, nodeB, nodeC, posA, posB;
  2192. if (how === _START_TO_START || how === _END_TO_START) {
  2193. nodeA = this.startContainer;
  2194. posA = this.startOffset;
  2195. }
  2196. if (how === _START_TO_END || how === _END_TO_END) {
  2197. nodeA = this.endContainer;
  2198. posA = this.endOffset;
  2199. }
  2200. if (how === _START_TO_START || how === _START_TO_END) {
  2201. nodeB = range.startContainer;
  2202. posB = range.startOffset;
  2203. }
  2204. if (how === _END_TO_END || how === _END_TO_START) {
  2205. nodeB = range.endContainer;
  2206. posB = range.endOffset;
  2207. }
  2208. if (nodeA === nodeB) {
  2209. var diff = posA - posB;
  2210. return diff > 0 ? 1 : (diff < 0 ? -1 : 0);
  2211. }
  2212. nodeC = nodeB;
  2213. while (nodeC && nodeC.parentNode !== nodeA) {
  2214. nodeC = nodeC.parentNode;
  2215. }
  2216. if (nodeC) {
  2217. return K(nodeC).index() >= posA ? -1 : 1;
  2218. }
  2219. nodeC = nodeA;
  2220. while (nodeC && nodeC.parentNode !== nodeB) {
  2221. nodeC = nodeC.parentNode;
  2222. }
  2223. if (nodeC) {
  2224. return K(nodeC).index() >= posB ? 1 : -1;
  2225. }
  2226. nodeC = K(nodeB).next();
  2227. if (nodeC && nodeC.contains(nodeA)) {
  2228. return 1;
  2229. }
  2230. nodeC = K(nodeA).next();
  2231. if (nodeC && nodeC.contains(nodeB)) {
  2232. return -1;
  2233. }
  2234. } else {
  2235. return rangeA.compareBoundaryPoints(how, rangeB);
  2236. }
  2237. },
  2238. cloneRange : function() {
  2239. return new KRange(this.doc).setStart(this.startContainer, this.startOffset).setEnd(this.endContainer, this.endOffset);
  2240. },
  2241. toString : function() {
  2242. var rng = this.get(), str = _IERANGE ? rng.text : rng.toString();
  2243. return str.replace(/\r\n|\n|\r/g, '');
  2244. },
  2245. cloneContents : function() {
  2246. return _copyAndDelete(this, true, false);
  2247. },
  2248. deleteContents : function() {
  2249. return _copyAndDelete(this, false, true);
  2250. },
  2251. extractContents : function() {
  2252. return _copyAndDelete(this, true, true);
  2253. },
  2254. insertNode : function(node) {
  2255. var self = this,
  2256. sc = self.startContainer, so = self.startOffset,
  2257. ec = self.endContainer, eo = self.endOffset,
  2258. firstChild, lastChild, c, nodeCount = 1;
  2259. if (node.nodeName.toLowerCase() === '#document-fragment') {
  2260. firstChild = node.firstChild;
  2261. lastChild = node.lastChild;
  2262. nodeCount = node.childNodes.length;
  2263. }
  2264. if (sc.nodeType == 1) {
  2265. c = sc.childNodes[so];
  2266. if (c) {
  2267. sc.insertBefore(node, c);
  2268. if (sc === ec) {
  2269. eo += nodeCount;
  2270. }
  2271. } else {
  2272. sc.appendChild(node);
  2273. }
  2274. } else if (sc.nodeType == 3) {
  2275. if (so === 0) {
  2276. sc.parentNode.insertBefore(node, sc);
  2277. if (sc.parentNode === ec) {
  2278. eo += nodeCount;
  2279. }
  2280. } else if (so >= sc.nodeValue.length) {
  2281. if (sc.nextSibling) {
  2282. sc.parentNode.insertBefore(node, sc.nextSibling);
  2283. } else {
  2284. sc.parentNode.appendChild(node);
  2285. }
  2286. } else {
  2287. if (so > 0) {
  2288. c = sc.splitText(so);
  2289. } else {
  2290. c = sc;
  2291. }
  2292. sc.parentNode.insertBefore(node, c);
  2293. if (sc === ec) {
  2294. ec = c;
  2295. eo -= so;
  2296. }
  2297. }
  2298. }
  2299. if (firstChild) {
  2300. self.setStartBefore(firstChild).setEndAfter(lastChild);
  2301. } else {
  2302. self.selectNode(node);
  2303. }
  2304. if (self.compareBoundaryPoints(_END_TO_END, self.cloneRange().setEnd(ec, eo)) >= 1) {
  2305. return self;
  2306. }
  2307. return self.setEnd(ec, eo);
  2308. },
  2309. surroundContents : function(node) {
  2310. node.appendChild(this.extractContents());
  2311. return this.insertNode(node).selectNode(node);
  2312. },
  2313. isControl : function() {
  2314. var self = this,
  2315. sc = self.startContainer, so = self.startOffset,
  2316. ec = self.endContainer, eo = self.endOffset, rng;
  2317. return sc.nodeType == 1 && sc === ec && so + 1 === eo && K(sc.childNodes[so]).isControl();
  2318. },
  2319. get : function(hasControlRange) {
  2320. var self = this, doc = self.doc, node, rng;
  2321. if (!_IERANGE) {
  2322. rng = doc.createRange();
  2323. try {
  2324. rng.setStart(self.startContainer, self.startOffset);
  2325. rng.setEnd(self.endContainer, self.endOffset);
  2326. } catch (e) {}
  2327. return rng;
  2328. }
  2329. if (hasControlRange && self.isControl()) {
  2330. rng = doc.body.createControlRange();
  2331. rng.addElement(self.startContainer.childNodes[self.startOffset]);
  2332. return rng;
  2333. }
  2334. var range = self.cloneRange().down();
  2335. rng = doc.body.createTextRange();
  2336. rng.setEndPoint('StartToStart', _getEndRange(range.startContainer, range.startOffset));
  2337. rng.setEndPoint('EndToStart', _getEndRange(range.endContainer, range.endOffset));
  2338. return rng;
  2339. },
  2340. html : function() {
  2341. return K(this.cloneContents()).outer();
  2342. },
  2343. down : function() {
  2344. var self = this;
  2345. function downPos(node, pos, isStart) {
  2346. if (node.nodeType != 1) {
  2347. return;
  2348. }
  2349. var children = K(node).children();
  2350. if (children.length === 0) {
  2351. return;
  2352. }
  2353. var left, right, child, offset;
  2354. if (pos > 0) {
  2355. left = children.eq(pos - 1);
  2356. }
  2357. if (pos < children.length) {
  2358. right = children.eq(pos);
  2359. }
  2360. if (left && left.type == 3) {
  2361. child = left[0];
  2362. offset = child.nodeValue.length;
  2363. }
  2364. if (right && right.type == 3) {
  2365. child = right[0];
  2366. offset = 0;
  2367. }
  2368. if (!child) {
  2369. return;
  2370. }
  2371. if (isStart) {
  2372. self.setStart(child, offset);
  2373. } else {
  2374. self.setEnd(child, offset);
  2375. }
  2376. }
  2377. downPos(self.startContainer, self.startOffset, true);
  2378. downPos(self.endContainer, self.endOffset, false);
  2379. return self;
  2380. },
  2381. up : function() {
  2382. var self = this;
  2383. function upPos(node, pos, isStart) {
  2384. if (node.nodeType != 3) {
  2385. return;
  2386. }
  2387. if (pos === 0) {
  2388. if (isStart) {
  2389. self.setStartBefore(node);
  2390. } else {
  2391. self.setEndBefore(node);
  2392. }
  2393. } else if (pos == node.nodeValue.length) {
  2394. if (isStart) {
  2395. self.setStartAfter(node);
  2396. } else {
  2397. self.setEndAfter(node);
  2398. }
  2399. }
  2400. }
  2401. upPos(self.startContainer, self.startOffset, true);
  2402. upPos(self.endContainer, self.endOffset, false);
  2403. return self;
  2404. },
  2405. enlarge : function(toBlock) {
  2406. var self = this;
  2407. self.up();
  2408. function enlargePos(node, pos, isStart) {
  2409. var knode = K(node), parent;
  2410. if (knode.type == 3 || _NOSPLIT_TAG_MAP[knode.name] || !toBlock && knode.isBlock()) {
  2411. return;
  2412. }
  2413. if (pos === 0) {
  2414. while (!knode.prev()) {
  2415. parent = knode.parent();
  2416. if (!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
  2417. break;
  2418. }
  2419. knode = parent;
  2420. }
  2421. if (isStart) {
  2422. self.setStartBefore(knode[0]);
  2423. } else {
  2424. self.setEndBefore(knode[0]);
  2425. }
  2426. } else if (pos == knode.children().length) {
  2427. while (!knode.next()) {
  2428. parent = knode.parent();
  2429. if (!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
  2430. break;
  2431. }
  2432. knode = parent;
  2433. }
  2434. if (isStart) {
  2435. self.setStartAfter(knode[0]);
  2436. } else {
  2437. self.setEndAfter(knode[0]);
  2438. }
  2439. }
  2440. }
  2441. enlargePos(self.startContainer, self.startOffset, true);
  2442. enlargePos(self.endContainer, self.endOffset, false);
  2443. return self;
  2444. },
  2445. shrink : function() {
  2446. var self = this, child, collapsed = self.collapsed;
  2447. while (self.startContainer.nodeType == 1 && (child = self.startContainer.childNodes[self.startOffset]) && child.nodeType == 1 && !K(child).isSingle()) {
  2448. self.setStart(child, 0);
  2449. }
  2450. if (collapsed) {
  2451. return self.collapse(collapsed);
  2452. }
  2453. while (self.endContainer.nodeType == 1 && self.endOffset > 0 && (child = self.endContainer.childNodes[self.endOffset - 1]) && child.nodeType == 1 && !K(child).isSingle()) {
  2454. self.setEnd(child, child.childNodes.length);
  2455. }
  2456. return self;
  2457. },
  2458. createBookmark : function(serialize) {
  2459. var self = this, doc = self.doc, endNode,
  2460. startNode = K('<span style="display:none;"></span>', doc)[0];
  2461. startNode.id = '__kindeditor_bookmark_start_' + (_BOOKMARK_ID++) + '__';
  2462. if (!self.collapsed) {
  2463. endNode = startNode.cloneNode(true);
  2464. endNode.id = '__kindeditor_bookmark_end_' + (_BOOKMARK_ID++) + '__';
  2465. }
  2466. if (endNode) {
  2467. self.cloneRange().collapse(false).insertNode(endNode).setEndBefore(endNode);
  2468. }
  2469. self.insertNode(startNode).setStartAfter(startNode);
  2470. return {
  2471. start : serialize ? '#' + startNode.id : startNode,
  2472. end : endNode ? (serialize ? '#' + endNode.id : endNode) : null
  2473. };
  2474. },
  2475. moveToBookmark : function(bookmark) {
  2476. var self = this, doc = self.doc,
  2477. start = K(bookmark.start, doc), end = bookmark.end ? K(bookmark.end, doc) : null;
  2478. if (!start || start.length < 1) {
  2479. return self;
  2480. }
  2481. self.setStartBefore(start[0]);
  2482. start.remove();
  2483. if (end && end.length > 0) {
  2484. self.setEndBefore(end[0]);
  2485. end.remove();
  2486. } else {
  2487. self.collapse(true);
  2488. }
  2489. return self;
  2490. },
  2491. dump : function() {
  2492. console.log('--------------------');
  2493. console.log(this.startContainer.nodeType == 3 ? this.startContainer.nodeValue : this.startContainer, this.startOffset);
  2494. console.log(this.endContainer.nodeType == 3 ? this.endContainer.nodeValue : this.endContainer, this.endOffset);
  2495. }
  2496. });
  2497. function _range(mixed) {
  2498. if (!mixed.nodeName) {
  2499. return mixed.constructor === KRange ? mixed : _toRange(mixed);
  2500. }
  2501. return new KRange(mixed);
  2502. }
  2503. K.RangeClass = KRange;
  2504. K.range = _range;
  2505. K.START_TO_START = _START_TO_START;
  2506. K.START_TO_END = _START_TO_END;
  2507. K.END_TO_END = _END_TO_END;
  2508. K.END_TO_START = _END_TO_START;
  2509. function _nativeCommand(doc, key, val) {
  2510. try {
  2511. doc.execCommand(key, false, val);
  2512. } catch(e) {}
  2513. }
  2514. function _nativeCommandValue(doc, key) {
  2515. var val = '';
  2516. try {
  2517. val = doc.queryCommandValue(key);
  2518. } catch (e) {}
  2519. if (typeof val !== 'string') {
  2520. val = '';
  2521. }
  2522. return val;
  2523. }
  2524. function _getSel(doc) {
  2525. var win = _getWin(doc);
  2526. return _IERANGE ? doc.selection : win.getSelection();
  2527. }
  2528. function _getRng(doc) {
  2529. var sel = _getSel(doc), rng;
  2530. try {
  2531. if (sel.rangeCount > 0) {
  2532. rng = sel.getRangeAt(0);
  2533. } else {
  2534. rng = sel.createRange();
  2535. }
  2536. } catch(e) {}
  2537. if (_IERANGE && (!rng || (!rng.item && rng.parentElement().ownerDocument !== doc))) {
  2538. return null;
  2539. }
  2540. return rng;
  2541. }
  2542. function _singleKeyMap(map) {
  2543. var newMap = {}, arr, v;
  2544. _each(map, function(key, val) {
  2545. arr = key.split(',');
  2546. for (var i = 0, len = arr.length; i < len; i++) {
  2547. v = arr[i];
  2548. newMap[v] = val;
  2549. }
  2550. });
  2551. return newMap;
  2552. }
  2553. function _hasAttrOrCss(knode, map) {
  2554. return _hasAttrOrCssByKey(knode, map, '*') || _hasAttrOrCssByKey(knode, map);
  2555. }
  2556. function _hasAttrOrCssByKey(knode, map, mapKey) {
  2557. mapKey = mapKey || knode.name;
  2558. if (knode.type !== 1) {
  2559. return false;
  2560. }
  2561. var newMap = _singleKeyMap(map);
  2562. if (!newMap[mapKey]) {
  2563. return false;
  2564. }
  2565. var arr = newMap[mapKey].split(',');
  2566. for (var i = 0, len = arr.length; i < len; i++) {
  2567. var key = arr[i];
  2568. if (key === '*') {
  2569. return true;
  2570. }
  2571. var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
  2572. var method = match[1] ? 'css' : 'attr';
  2573. key = match[2];
  2574. var val = match[3] || '';
  2575. if (val === '' && knode[method](key) !== '') {
  2576. return true;
  2577. }
  2578. if (val !== '' && knode[method](key) === val) {
  2579. return true;
  2580. }
  2581. }
  2582. return false;
  2583. }
  2584. function _removeAttrOrCss(knode, map) {
  2585. if (knode.type != 1) {
  2586. return;
  2587. }
  2588. _removeAttrOrCssByKey(knode, map, '*');
  2589. _removeAttrOrCssByKey(knode, map);
  2590. }
  2591. function _removeAttrOrCssByKey(knode, map, mapKey) {
  2592. mapKey = mapKey || knode.name;
  2593. if (knode.type !== 1) {
  2594. return;
  2595. }
  2596. var newMap = _singleKeyMap(map);
  2597. if (!newMap[mapKey]) {
  2598. return;
  2599. }
  2600. var arr = newMap[mapKey].split(','), allFlag = false;
  2601. for (var i = 0, len = arr.length; i < len; i++) {
  2602. var key = arr[i];
  2603. if (key === '*') {
  2604. allFlag = true;
  2605. break;
  2606. }
  2607. var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
  2608. key = match[2];
  2609. if (match[1]) {
  2610. key = _toCamel(key);
  2611. if (knode[0].style[key]) {
  2612. knode[0].style[key] = '';
  2613. }
  2614. } else {
  2615. knode.removeAttr(key);
  2616. }
  2617. }
  2618. if (allFlag) {
  2619. knode.remove(true);
  2620. }
  2621. }
  2622. function _getInnerNode(knode) {
  2623. var inner = knode;
  2624. while (inner.first()) {
  2625. inner = inner.first();
  2626. }
  2627. return inner;
  2628. }
  2629. function _isEmptyNode(knode) {
  2630. if (knode.type != 1 || knode.isSingle()) {
  2631. return false;
  2632. }
  2633. return knode.html().replace(/<[^>]+>/g, '') === '';
  2634. }
  2635. function _mergeWrapper(a, b) {
  2636. a = a.clone(true);
  2637. var lastA = _getInnerNode(a), childA = a, merged = false;
  2638. while (b) {
  2639. while (childA) {
  2640. if (childA.name === b.name) {
  2641. _mergeAttrs(childA, b.attr(), b.css());
  2642. merged = true;
  2643. }
  2644. childA = childA.first();
  2645. }
  2646. if (!merged) {
  2647. lastA.append(b.clone(false));
  2648. }
  2649. merged = false;
  2650. b = b.first();
  2651. }
  2652. return a;
  2653. }
  2654. function _wrapNode(knode, wrapper) {
  2655. wrapper = wrapper.clone(true);
  2656. if (knode.type == 3) {
  2657. _getInnerNode(wrapper).append(knode.clone(false));
  2658. knode.replaceWith(wrapper);
  2659. return wrapper;
  2660. }
  2661. var nodeWrapper = knode, child;
  2662. while ((child = knode.first()) && child.children().length == 1) {
  2663. knode = child;
  2664. }
  2665. child = knode.first();
  2666. var frag = knode.doc.createDocumentFragment();
  2667. while (child) {
  2668. frag.appendChild(child[0]);
  2669. child = child.next();
  2670. }
  2671. wrapper = _mergeWrapper(nodeWrapper, wrapper);
  2672. if (frag.firstChild) {
  2673. _getInnerNode(wrapper).append(frag);
  2674. }
  2675. nodeWrapper.replaceWith(wrapper);
  2676. return wrapper;
  2677. }
  2678. function _mergeAttrs(knode, attrs, styles) {
  2679. _each(attrs, function(key, val) {
  2680. if (key !== 'style') {
  2681. knode.attr(key, val);
  2682. }
  2683. });
  2684. _each(styles, function(key, val) {
  2685. knode.css(key, val);
  2686. });
  2687. }
  2688. function _inPreElement(knode) {
  2689. while (knode && knode.name != 'body') {
  2690. if (_PRE_TAG_MAP[knode.name] || knode.name == 'div' && knode.hasClass('ke-script')) {
  2691. return true;
  2692. }
  2693. knode = knode.parent();
  2694. }
  2695. return false;
  2696. }
  2697. function KCmd(range) {
  2698. this.init(range);
  2699. }
  2700. _extend(KCmd, {
  2701. init : function(range) {
  2702. var self = this, doc = range.doc;
  2703. self.doc = doc;
  2704. self.win = _getWin(doc);
  2705. self.sel = _getSel(doc);
  2706. self.range = range;
  2707. },
  2708. selection : function(forceReset) {
  2709. var self = this, doc = self.doc, rng = _getRng(doc);
  2710. self.sel = _getSel(doc);
  2711. if (rng) {
  2712. self.range = _range(rng);
  2713. if (K(self.range.startContainer).name == 'html') {
  2714. self.range.selectNodeContents(doc.body).collapse(false);
  2715. }
  2716. return self;
  2717. }
  2718. if (forceReset) {
  2719. self.range.selectNodeContents(doc.body).collapse(false);
  2720. }
  2721. return self;
  2722. },
  2723. select : function(hasDummy) {
  2724. hasDummy = _undef(hasDummy, true);
  2725. var self = this, sel = self.sel, range = self.range.cloneRange().shrink(),
  2726. sc = range.startContainer, so = range.startOffset,
  2727. ec = range.endContainer, eo = range.endOffset,
  2728. doc = _getDoc(sc), win = self.win, rng, hasU200b = false;
  2729. if (hasDummy && sc.nodeType == 1 && range.collapsed) {
  2730. if (_IERANGE) {
  2731. var dummy = K('<span>&nbsp;</span>', doc);
  2732. range.insertNode(dummy[0]);
  2733. rng = doc.body.createTextRange();
  2734. try {
  2735. rng.moveToElementText(dummy[0]);
  2736. } catch(ex) {}
  2737. rng.collapse(false);
  2738. rng.select();
  2739. dummy.remove();
  2740. win.focus();
  2741. return self;
  2742. }
  2743. if (_WEBKIT) {
  2744. var children = sc.childNodes;
  2745. if (K(sc).isInline() || so > 0 && K(children[so - 1]).isInline() || children[so] && K(children[so]).isInline()) {
  2746. range.insertNode(doc.createTextNode('\u200B'));
  2747. hasU200b = true;
  2748. }
  2749. }
  2750. }
  2751. if (_IERANGE) {
  2752. try {
  2753. rng = range.get(true);
  2754. rng.select();
  2755. } catch(e) {}
  2756. } else {
  2757. if (hasU200b) {
  2758. range.collapse(false);
  2759. }
  2760. rng = range.get(true);
  2761. sel.removeAllRanges();
  2762. sel.addRange(rng);
  2763. if (doc !== document) {
  2764. var pos = K(rng.endContainer).pos();
  2765. win.scrollTo(pos.x, pos.y);
  2766. }
  2767. }
  2768. win.focus();
  2769. return self;
  2770. },
  2771. wrap : function(val) {
  2772. var self = this, doc = self.doc, range = self.range, wrapper;
  2773. wrapper = K(val, doc);
  2774. if (range.collapsed) {
  2775. range.shrink();
  2776. range.insertNode(wrapper[0]).selectNodeContents(wrapper[0]);
  2777. return self;
  2778. }
  2779. if (wrapper.isBlock()) {
  2780. var copyWrapper = wrapper.clone(true), child = copyWrapper;
  2781. while (child.first()) {
  2782. child = child.first();
  2783. }
  2784. child.append(range.extractContents());
  2785. range.insertNode(copyWrapper[0]).selectNode(copyWrapper[0]);
  2786. return self;
  2787. }
  2788. range.enlarge();
  2789. var bookmark = range.createBookmark(), ancestor = range.commonAncestor(), isStart = false;
  2790. K(ancestor).scan(function(node) {
  2791. if (!isStart && node == bookmark.start) {
  2792. isStart = true;
  2793. return;
  2794. }
  2795. if (isStart) {
  2796. if (node == bookmark.end) {
  2797. return false;
  2798. }
  2799. var knode = K(node);
  2800. if (_inPreElement(knode)) {
  2801. return;
  2802. }
  2803. if (knode.type == 3 && _trim(node.nodeValue).length > 0) {
  2804. var parent;
  2805. while ((parent = knode.parent()) && parent.isStyle() && parent.children().length == 1) {
  2806. knode = parent;
  2807. }
  2808. _wrapNode(knode, wrapper);
  2809. }
  2810. }
  2811. });
  2812. range.moveToBookmark(bookmark);
  2813. return self;
  2814. },
  2815. split : function(isStart, map) {
  2816. var range = this.range, doc = range.doc;
  2817. var tempRange = range.cloneRange().collapse(isStart);
  2818. var node = tempRange.startContainer, pos = tempRange.startOffset,
  2819. parent = node.nodeType == 3 ? node.parentNode : node,
  2820. needSplit = false, knode;
  2821. while (parent && parent.parentNode) {
  2822. knode = K(parent);
  2823. if (map) {
  2824. if (!knode.isStyle()) {
  2825. break;
  2826. }
  2827. if (!_hasAttrOrCss(knode, map)) {
  2828. break;
  2829. }
  2830. } else {
  2831. if (_NOSPLIT_TAG_MAP[knode.name]) {
  2832. break;
  2833. }
  2834. }
  2835. needSplit = true;
  2836. parent = parent.parentNode;
  2837. }
  2838. if (needSplit) {
  2839. var dummy = doc.createElement('span');
  2840. range.cloneRange().collapse(!isStart).insertNode(dummy);
  2841. if (isStart) {
  2842. tempRange.setStartBefore(parent.firstChild).setEnd(node, pos);
  2843. } else {
  2844. tempRange.setStart(node, pos).setEndAfter(parent.lastChild);
  2845. }
  2846. var frag = tempRange.extractContents(),
  2847. first = frag.firstChild, last = frag.lastChild;
  2848. if (isStart) {
  2849. tempRange.insertNode(frag);
  2850. range.setStartAfter(last).setEndBefore(dummy);
  2851. } else {
  2852. parent.appendChild(frag);
  2853. range.setStartBefore(dummy).setEndBefore(first);
  2854. }
  2855. var dummyParent = dummy.parentNode;
  2856. if (dummyParent == range.endContainer) {
  2857. var prev = K(dummy).prev(), next = K(dummy).next();
  2858. if (prev && next && prev.type == 3 && next.type == 3) {
  2859. range.setEnd(prev[0], prev[0].nodeValue.length);
  2860. } else if (!isStart) {
  2861. range.setEnd(range.endContainer, range.endOffset - 1);
  2862. }
  2863. }
  2864. dummyParent.removeChild(dummy);
  2865. }
  2866. return this;
  2867. },
  2868. remove : function(map) {
  2869. var self = this, doc = self.doc, range = self.range;
  2870. range.enlarge();
  2871. if (range.startOffset === 0) {
  2872. var ksc = K(range.startContainer), parent;
  2873. while ((parent = ksc.parent()) && parent.isStyle() && parent.children().length == 1) {
  2874. ksc = parent;
  2875. }
  2876. range.setStart(ksc[0], 0);
  2877. ksc = K(range.startContainer);
  2878. if (ksc.isBlock()) {
  2879. _removeAttrOrCss(ksc, map);
  2880. }
  2881. var kscp = ksc.parent();
  2882. if (kscp && kscp.isBlock()) {
  2883. _removeAttrOrCss(kscp, map);
  2884. }
  2885. }
  2886. var sc, so;
  2887. if (range.collapsed) {
  2888. self.split(true, map);
  2889. sc = range.startContainer;
  2890. so = range.startOffset;
  2891. if (so > 0) {
  2892. var sb = K(sc.childNodes[so - 1]);
  2893. if (sb && _isEmptyNode(sb)) {
  2894. sb.remove();
  2895. range.setStart(sc, so - 1);
  2896. }
  2897. }
  2898. var sa = K(sc.childNodes[so]);
  2899. if (sa && _isEmptyNode(sa)) {
  2900. sa.remove();
  2901. }
  2902. if (_isEmptyNode(sc)) {
  2903. range.startBefore(sc);
  2904. sc.remove();
  2905. }
  2906. range.collapse(true);
  2907. return self;
  2908. }
  2909. self.split(true, map);
  2910. self.split(false, map);
  2911. var startDummy = doc.createElement('span'), endDummy = doc.createElement('span');
  2912. range.cloneRange().collapse(false).insertNode(endDummy);
  2913. range.cloneRange().collapse(true).insertNode(startDummy);
  2914. var nodeList = [], cmpStart = false;
  2915. K(range.commonAncestor()).scan(function(node) {
  2916. if (!cmpStart && node == startDummy) {
  2917. cmpStart = true;
  2918. return;
  2919. }
  2920. if (node == endDummy) {
  2921. return false;
  2922. }
  2923. if (cmpStart) {
  2924. nodeList.push(node);
  2925. }
  2926. });
  2927. K(startDummy).remove();
  2928. K(endDummy).remove();
  2929. sc = range.startContainer;
  2930. so = range.startOffset;
  2931. var ec = range.endContainer, eo = range.endOffset;
  2932. if (so > 0) {
  2933. var startBefore = K(sc.childNodes[so - 1]);
  2934. if (startBefore && _isEmptyNode(startBefore)) {
  2935. startBefore.remove();
  2936. range.setStart(sc, so - 1);
  2937. if (sc == ec) {
  2938. range.setEnd(ec, eo - 1);
  2939. }
  2940. }
  2941. var startAfter = K(sc.childNodes[so]);
  2942. if (startAfter && _isEmptyNode(startAfter)) {
  2943. startAfter.remove();
  2944. if (sc == ec) {
  2945. range.setEnd(ec, eo - 1);
  2946. }
  2947. }
  2948. }
  2949. var endAfter = K(ec.childNodes[range.endOffset]);
  2950. if (endAfter && _isEmptyNode(endAfter)) {
  2951. endAfter.remove();
  2952. }
  2953. var bookmark = range.createBookmark(true);
  2954. _each(nodeList, function(i, node) {
  2955. _removeAttrOrCss(K(node), map);
  2956. });
  2957. range.moveToBookmark(bookmark);
  2958. return self;
  2959. },
  2960. commonNode : function(map) {
  2961. var range = this.range;
  2962. var ec = range.endContainer, eo = range.endOffset,
  2963. node = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
  2964. function find(node) {
  2965. var child = node, parent = node;
  2966. while (parent) {
  2967. if (_hasAttrOrCss(K(parent), map)) {
  2968. return K(parent);
  2969. }
  2970. parent = parent.parentNode;
  2971. }
  2972. while (child && (child = child.lastChild)) {
  2973. if (_hasAttrOrCss(K(child), map)) {
  2974. return K(child);
  2975. }
  2976. }
  2977. return null;
  2978. }
  2979. var cNode = find(node);
  2980. if (cNode) {
  2981. return cNode;
  2982. }
  2983. if (node.nodeType == 1 || (ec.nodeType == 3 && eo === 0)) {
  2984. var prev = K(node).prev();
  2985. if (prev) {
  2986. return find(prev);
  2987. }
  2988. }
  2989. return null;
  2990. },
  2991. commonAncestor : function(tagName) {
  2992. var range = this.range,
  2993. sc = range.startContainer, so = range.startOffset,
  2994. ec = range.endContainer, eo = range.endOffset,
  2995. startNode = (sc.nodeType == 3 || so === 0) ? sc : sc.childNodes[so - 1],
  2996. endNode = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
  2997. function find(node) {
  2998. while (node) {
  2999. if (node.nodeType == 1) {
  3000. if (node.tagName.toLowerCase() === tagName) {
  3001. return node;
  3002. }
  3003. }
  3004. node = node.parentNode;
  3005. }
  3006. return null;
  3007. }
  3008. var start = find(startNode), end = find(endNode);
  3009. if (start && end && start === end) {
  3010. return K(start);
  3011. }
  3012. return null;
  3013. },
  3014. state : function(key) {
  3015. var self = this, doc = self.doc, bool = false;
  3016. try {
  3017. bool = doc.queryCommandState(key);
  3018. } catch (e) {}
  3019. return bool;
  3020. },
  3021. val : function(key) {
  3022. var self = this, doc = self.doc, range = self.range;
  3023. function lc(val) {
  3024. return val.toLowerCase();
  3025. }
  3026. key = lc(key);
  3027. var val = '', knode;
  3028. if (key === 'fontfamily' || key === 'fontname') {
  3029. val = _nativeCommandValue(doc, 'fontname');
  3030. val = val.replace(/['"]/g, '');
  3031. return lc(val);
  3032. }
  3033. if (key === 'formatblock') {
  3034. val = _nativeCommandValue(doc, key);
  3035. if (val === '') {
  3036. knode = self.commonNode({'h1,h2,h3,h4,h5,h6,p,div,pre,address' : '*'});
  3037. if (knode) {
  3038. val = knode.name;
  3039. }
  3040. }
  3041. if (val === 'Normal') {
  3042. val = 'p';
  3043. }
  3044. return lc(val);
  3045. }
  3046. if (key === 'fontsize') {
  3047. knode = self.commonNode({'*' : '.font-size'});
  3048. if (knode) {
  3049. val = knode.css('font-size');
  3050. }
  3051. return lc(val);
  3052. }
  3053. if (key === 'forecolor') {
  3054. knode = self.commonNode({'*' : '.color'});
  3055. if (knode) {
  3056. val = knode.css('color');
  3057. }
  3058. val = _toHex(val);
  3059. if (val === '') {
  3060. val = 'default';
  3061. }
  3062. return lc(val);
  3063. }
  3064. if (key === 'hilitecolor') {
  3065. knode = self.commonNode({'*' : '.background-color'});
  3066. if (knode) {
  3067. val = knode.css('background-color');
  3068. }
  3069. val = _toHex(val);
  3070. if (val === '') {
  3071. val = 'default';
  3072. }
  3073. return lc(val);
  3074. }
  3075. return val;
  3076. },
  3077. toggle : function(wrapper, map) {
  3078. var self = this;
  3079. if (self.commonNode(map)) {
  3080. self.remove(map);
  3081. } else {
  3082. self.wrap(wrapper);
  3083. }
  3084. return self.select();
  3085. },
  3086. bold : function() {
  3087. return this.toggle('<strong></strong>', {
  3088. span : '.font-weight=bold',
  3089. strong : '*',
  3090. b : '*'
  3091. });
  3092. },
  3093. italic : function() {
  3094. return this.toggle('<em></em>', {
  3095. span : '.font-style=italic',
  3096. em : '*',
  3097. i : '*'
  3098. });
  3099. },
  3100. underline : function() {
  3101. return this.toggle('<u></u>', {
  3102. span : '.text-decoration=underline',
  3103. u : '*'
  3104. });
  3105. },
  3106. strikethrough : function() {
  3107. return this.toggle('<s></s>', {
  3108. span : '.text-decoration=line-through',
  3109. s : '*'
  3110. });
  3111. },
  3112. forecolor : function(val) {
  3113. return this.wrap('<span style="color:' + val + ';"></span>').select();
  3114. },
  3115. hilitecolor : function(val) {
  3116. return this.wrap('<span style="background-color:' + val + ';"></span>').select();
  3117. },
  3118. fontsize : function(val) {
  3119. return this.wrap('<span style="font-size:' + val + ';"></span>').select();
  3120. },
  3121. fontname : function(val) {
  3122. return this.fontfamily(val);
  3123. },
  3124. fontfamily : function(val) {
  3125. return this.wrap('<span style="font-family:' + val + ';"></span>').select();
  3126. },
  3127. removeformat : function() {
  3128. var map = {
  3129. '*' : '.font-weight,.font-style,.text-decoration,.color,.background-color,.font-size,.font-family,.text-indent'
  3130. },
  3131. tags = _STYLE_TAG_MAP;
  3132. _each(tags, function(key, val) {
  3133. map[key] = '*';
  3134. });
  3135. this.remove(map);
  3136. return this.select();
  3137. },
  3138. inserthtml : function(val, quickMode) {
  3139. var self = this, range = self.range;
  3140. if (val === '') {
  3141. return self;
  3142. }
  3143. function pasteHtml(range, val) {
  3144. val = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + val;
  3145. var rng = range.get();
  3146. if (rng.item) {
  3147. rng.item(0).outerHTML = val;
  3148. } else {
  3149. rng.pasteHTML(val);
  3150. }
  3151. var temp = range.doc.getElementById('__kindeditor_temp_tag__');
  3152. temp.parentNode.removeChild(temp);
  3153. var newRange = _toRange(rng);
  3154. range.setEnd(newRange.endContainer, newRange.endOffset);
  3155. range.collapse(false);
  3156. self.select(false);
  3157. }
  3158. function insertHtml(range, val) {
  3159. var doc = range.doc,
  3160. frag = doc.createDocumentFragment();
  3161. K('@' + val, doc).each(function() {
  3162. frag.appendChild(this);
  3163. });
  3164. range.deleteContents();
  3165. range.insertNode(frag);
  3166. range.collapse(false);
  3167. self.select(false);
  3168. }
  3169. if (_IERANGE && quickMode) {
  3170. try {
  3171. pasteHtml(range, val);
  3172. } catch(e) {
  3173. insertHtml(range, val);
  3174. }
  3175. return self;
  3176. }
  3177. insertHtml(range, val);
  3178. return self;
  3179. },
  3180. hr : function() {
  3181. return this.inserthtml('<hr />');
  3182. },
  3183. print : function() {
  3184. this.win.print();
  3185. return this;
  3186. },
  3187. insertimage : function(url, title, width, height, border, align) {
  3188. title = _undef(title, '');
  3189. border = _undef(border, 0);
  3190. var html = '<img src="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
  3191. if (width) {
  3192. html += 'width="' + _escape(width) + '" ';
  3193. }
  3194. if (height) {
  3195. html += 'height="' + _escape(height) + '" ';
  3196. }
  3197. if (title) {
  3198. html += 'title="' + _escape(title) + '" ';
  3199. }
  3200. if (align) {
  3201. html += 'align="' + _escape(align) + '" ';
  3202. }
  3203. html += 'alt="' + _escape(title) + '" ';
  3204. html += '/>';
  3205. return this.inserthtml(html);
  3206. },
  3207. createlink : function(url, type) {
  3208. var self = this, doc = self.doc, range = self.range;
  3209. self.select();
  3210. var a = self.commonNode({ a : '*' });
  3211. if (a && !range.isControl()) {
  3212. range.selectNode(a.get());
  3213. self.select();
  3214. }
  3215. var html = '<a href="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
  3216. if (type) {
  3217. html += ' target="' + _escape(type) + '"';
  3218. }
  3219. if (range.collapsed) {
  3220. html += '>' + _escape(url) + '</a>';
  3221. return self.inserthtml(html);
  3222. }
  3223. if (range.isControl()) {
  3224. var node = K(range.startContainer.childNodes[range.startOffset]);
  3225. html += '></a>';
  3226. node.after(K(html, doc));
  3227. node.next().append(node);
  3228. range.selectNode(node[0]);
  3229. return self.select();
  3230. }
  3231. function setAttr(node, url, type) {
  3232. K(node).attr('href', url).attr('data-ke-src', url);
  3233. if (type) {
  3234. K(node).attr('target', type);
  3235. } else {
  3236. K(node).removeAttr('target');
  3237. }
  3238. }
  3239. var sc = range.startContainer, so = range.startOffset,
  3240. ec = range.endContainer, eo = range.endOffset;
  3241. if (sc.nodeType == 1 && sc === ec && so + 1 === eo) {
  3242. var child = sc.childNodes[so];
  3243. if (child.nodeName.toLowerCase() == 'a') {
  3244. setAttr(child, url, type);
  3245. return self;
  3246. }
  3247. }
  3248. _nativeCommand(doc, 'createlink', '__kindeditor_temp_url__');
  3249. K('a[href="__kindeditor_temp_url__"]', doc).each(function() {
  3250. setAttr(this, url, type);
  3251. });
  3252. return self;
  3253. },
  3254. unlink : function() {
  3255. var self = this, doc = self.doc, range = self.range;
  3256. self.select();
  3257. if (range.collapsed) {
  3258. var a = self.commonNode({ a : '*' });
  3259. if (a) {
  3260. range.selectNode(a.get());
  3261. self.select();
  3262. }
  3263. _nativeCommand(doc, 'unlink', null);
  3264. if (_WEBKIT && K(range.startContainer).name === 'img') {
  3265. var parent = K(range.startContainer).parent();
  3266. if (parent.name === 'a') {
  3267. parent.remove(true);
  3268. }
  3269. }
  3270. } else {
  3271. _nativeCommand(doc, 'unlink', null);
  3272. }
  3273. return self;
  3274. }
  3275. });
  3276. _each(('formatblock,selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
  3277. 'insertunorderedlist,indent,outdent,subscript,superscript').split(','), function(i, name) {
  3278. KCmd.prototype[name] = function(val) {
  3279. var self = this;
  3280. self.select();
  3281. _nativeCommand(self.doc, name, val);
  3282. if (_IERANGE && _inArray(name, 'justifyleft,justifycenter,justifyright,justifyfull'.split(',')) >= 0) {
  3283. self.selection();
  3284. }
  3285. if (!_IERANGE || _inArray(name, 'formatblock,selectall,insertorderedlist,insertunorderedlist'.split(',')) >= 0) {
  3286. self.selection();
  3287. }
  3288. return self;
  3289. };
  3290. });
  3291. _each('cut,copy,paste'.split(','), function(i, name) {
  3292. KCmd.prototype[name] = function() {
  3293. var self = this;
  3294. if (!self.doc.queryCommandSupported(name)) {
  3295. throw 'not supported';
  3296. }
  3297. self.select();
  3298. _nativeCommand(self.doc, name, null);
  3299. return self;
  3300. };
  3301. });
  3302. function _cmd(mixed) {
  3303. if (mixed.nodeName) {
  3304. var doc = _getDoc(mixed);
  3305. mixed = _range(doc).selectNodeContents(doc.body).collapse(false);
  3306. }
  3307. return new KCmd(mixed);
  3308. }
  3309. K.CmdClass = KCmd;
  3310. K.cmd = _cmd;
  3311. function _drag(options) {
  3312. var moveEl = options.moveEl,
  3313. moveFn = options.moveFn,
  3314. clickEl = options.clickEl || moveEl,
  3315. beforeDrag = options.beforeDrag,
  3316. iframeFix = options.iframeFix === undefined ? true : options.iframeFix;
  3317. var docs = [document];
  3318. if (iframeFix) {
  3319. K('iframe').each(function() {
  3320. var src = _formatUrl(this.src || '', 'absolute');
  3321. if (/^https?:\/\//.test(src)) {
  3322. return;
  3323. }
  3324. var doc;
  3325. try {
  3326. doc = _iframeDoc(this);
  3327. } catch(e) {}
  3328. if (doc) {
  3329. var pos = K(this).pos();
  3330. K(doc).data('pos-x', pos.x);
  3331. K(doc).data('pos-y', pos.y);
  3332. docs.push(doc);
  3333. }
  3334. });
  3335. }
  3336. clickEl.mousedown(function(e) {
  3337. if(e.button !== 0 && e.button !== 1) {
  3338. return;
  3339. }
  3340. e.stopPropagation();
  3341. var self = clickEl.get(),
  3342. x = _removeUnit(moveEl.css('left')),
  3343. y = _removeUnit(moveEl.css('top')),
  3344. width = moveEl.width(),
  3345. height = moveEl.height(),
  3346. pageX = e.pageX,
  3347. pageY = e.pageY;
  3348. if (beforeDrag) {
  3349. beforeDrag();
  3350. }
  3351. function moveListener(e) {
  3352. e.preventDefault();
  3353. var kdoc = K(_getDoc(e.target));
  3354. var diffX = _round((kdoc.data('pos-x') || 0) + e.pageX - pageX);
  3355. var diffY = _round((kdoc.data('pos-y') || 0) + e.pageY - pageY);
  3356. moveFn.call(clickEl, x, y, width, height, diffX, diffY);
  3357. }
  3358. function selectListener(e) {
  3359. e.preventDefault();
  3360. }
  3361. function upListener(e) {
  3362. e.preventDefault();
  3363. K(docs).unbind('mousemove', moveListener)
  3364. .unbind('mouseup', upListener)
  3365. .unbind('selectstart', selectListener);
  3366. if (self.releaseCapture) {
  3367. self.releaseCapture();
  3368. }
  3369. }
  3370. K(docs).mousemove(moveListener)
  3371. .mouseup(upListener)
  3372. .bind('selectstart', selectListener);
  3373. if (self.setCapture) {
  3374. self.setCapture();
  3375. }
  3376. });
  3377. }
  3378. function KWidget(options) {
  3379. this.init(options);
  3380. }
  3381. _extend(KWidget, {
  3382. init : function(options) {
  3383. var self = this;
  3384. self.name = options.name || '';
  3385. self.doc = options.doc || document;
  3386. self.win = _getWin(self.doc);
  3387. self.x = _addUnit(options.x);
  3388. self.y = _addUnit(options.y);
  3389. self.z = options.z;
  3390. self.width = _addUnit(options.width);
  3391. self.height = _addUnit(options.height);
  3392. self.div = K('<div style="display:block;"></div>');
  3393. self.options = options;
  3394. self._alignEl = options.alignEl;
  3395. if (self.width) {
  3396. self.div.css('width', self.width);
  3397. }
  3398. if (self.height) {
  3399. self.div.css('height', self.height);
  3400. }
  3401. if (self.z) {
  3402. self.div.css({
  3403. position : 'absolute',
  3404. left : self.x,
  3405. top : self.y,
  3406. 'z-index' : self.z
  3407. });
  3408. }
  3409. if (self.z && (self.x === undefined || self.y === undefined)) {
  3410. self.autoPos(self.width, self.height);
  3411. }
  3412. if (options.cls) {
  3413. self.div.addClass(options.cls);
  3414. }
  3415. if (options.shadowMode) {
  3416. self.div.addClass('ke-shadow');
  3417. }
  3418. if (options.css) {
  3419. self.div.css(options.css);
  3420. }
  3421. if (options.src) {
  3422. K(options.src).replaceWith(self.div);
  3423. } else {
  3424. K(self.doc.body).append(self.div);
  3425. }
  3426. if (options.html) {
  3427. self.div.html(options.html);
  3428. }
  3429. if (options.autoScroll) {
  3430. if (_IE && _V < 7 || _QUIRKS) {
  3431. var scrollPos = _getScrollPos();
  3432. K(self.win).bind('scroll', function(e) {
  3433. var pos = _getScrollPos(),
  3434. diffX = pos.x - scrollPos.x,
  3435. diffY = pos.y - scrollPos.y;
  3436. self.pos(_removeUnit(self.x) + diffX, _removeUnit(self.y) + diffY, false);
  3437. });
  3438. } else {
  3439. self.div.css('position', 'fixed');
  3440. }
  3441. }
  3442. },
  3443. pos : function(x, y, updateProp) {
  3444. var self = this;
  3445. updateProp = _undef(updateProp, true);
  3446. if (x !== null) {
  3447. x = x < 0 ? 0 : _addUnit(x);
  3448. self.div.css('left', x);
  3449. if (updateProp) {
  3450. self.x = x;
  3451. }
  3452. }
  3453. if (y !== null) {
  3454. y = y < 0 ? 0 : _addUnit(y);
  3455. self.div.css('top', y);
  3456. if (updateProp) {
  3457. self.y = y;
  3458. }
  3459. }
  3460. return self;
  3461. },
  3462. autoPos : function(width, height) {
  3463. var self = this,
  3464. w = _removeUnit(width) || 0,
  3465. h = _removeUnit(height) || 0,
  3466. scrollPos = _getScrollPos();
  3467. if (self._alignEl) {
  3468. var knode = K(self._alignEl),
  3469. pos = knode.pos(),
  3470. diffX = _round(knode[0].clientWidth / 2 - w / 2),
  3471. diffY = _round(knode[0].clientHeight / 2 - h / 2);
  3472. x = diffX < 0 ? pos.x : pos.x + diffX;
  3473. y = diffY < 0 ? pos.y : pos.y + diffY;
  3474. } else {
  3475. var docEl = _docElement(self.doc);
  3476. x = _round(scrollPos.x + (docEl.clientWidth - w) / 2);
  3477. y = _round(scrollPos.y + (docEl.clientHeight - h) / 2);
  3478. }
  3479. if (!(_IE && _V < 7 || _QUIRKS)) {
  3480. x -= scrollPos.x;
  3481. y -= scrollPos.y;
  3482. }
  3483. return self.pos(x, y);
  3484. },
  3485. remove : function() {
  3486. var self = this;
  3487. if (_IE && _V < 7 || _QUIRKS) {
  3488. K(self.win).unbind('scroll');
  3489. }
  3490. self.div.remove();
  3491. _each(self, function(i) {
  3492. self[i] = null;
  3493. });
  3494. return this;
  3495. },
  3496. show : function() {
  3497. this.div.show();
  3498. return this;
  3499. },
  3500. hide : function() {
  3501. this.div.hide();
  3502. return this;
  3503. },
  3504. draggable : function(options) {
  3505. var self = this;
  3506. options = options || {};
  3507. options.moveEl = self.div;
  3508. options.moveFn = function(x, y, width, height, diffX, diffY) {
  3509. if ((x = x + diffX) < 0) {
  3510. x = 0;
  3511. }
  3512. if ((y = y + diffY) < 0) {
  3513. y = 0;
  3514. }
  3515. self.pos(x, y);
  3516. };
  3517. _drag(options);
  3518. return self;
  3519. }
  3520. });
  3521. function _widget(options) {
  3522. return new KWidget(options);
  3523. }
  3524. K.WidgetClass = KWidget;
  3525. K.widget = _widget;
  3526. function _iframeDoc(iframe) {
  3527. iframe = _get(iframe);
  3528. return iframe.contentDocument || iframe.contentWindow.document;
  3529. }
  3530. var html, _direction = '';
  3531. if ((html = document.getElementsByTagName('html'))) {
  3532. _direction = html[0].dir;
  3533. }
  3534. function _getInitHtml(themesPath, bodyClass, cssPath, cssData) {
  3535. var arr = [
  3536. (_direction === '' ? '<html>' : '<html dir="' + _direction + '">'),
  3537. '<head><meta charset="utf-8" /><title></title>',
  3538. '<style>',
  3539. 'html {margin:0;padding:0;}',
  3540. 'body {margin:0;padding:5px;}',
  3541. 'body, td {font:12px/1.5 "sans serif",tahoma,verdana,helvetica;}',
  3542. 'body, p, div {word-wrap: break-word;}',
  3543. 'p {margin:5px 0;}',
  3544. 'table {border-collapse:collapse;}',
  3545. 'img {border:0;}',
  3546. 'noscript {display:none;}',
  3547. 'table.ke-zeroborder td {border:1px dotted #AAA;}',
  3548. 'img.ke-flash {',
  3549. ' border:1px solid #AAA;',
  3550. ' background-image:url(' + themesPath + 'common/flash.gif);',
  3551. ' background-position:center center;',
  3552. ' background-repeat:no-repeat;',
  3553. ' width:100px;',
  3554. ' height:100px;',
  3555. '}',
  3556. 'img.ke-rm {',
  3557. ' border:1px solid #AAA;',
  3558. ' background-image:url(' + themesPath + 'common/rm.gif);',
  3559. ' background-position:center center;',
  3560. ' background-repeat:no-repeat;',
  3561. ' width:100px;',
  3562. ' height:100px;',
  3563. '}',
  3564. 'img.ke-media {',
  3565. ' border:1px solid #AAA;',
  3566. ' background-image:url(' + themesPath + 'common/media.gif);',
  3567. ' background-position:center center;',
  3568. ' background-repeat:no-repeat;',
  3569. ' width:100px;',
  3570. ' height:100px;',
  3571. '}',
  3572. 'img.ke-anchor {',
  3573. ' border:1px dashed #666;',
  3574. ' width:16px;',
  3575. ' height:16px;',
  3576. '}',
  3577. '.ke-script, .ke-noscript, .ke-display-none {',
  3578. ' display:none;',
  3579. ' font-size:0;',
  3580. ' width:0;',
  3581. ' height:0;',
  3582. '}',
  3583. '.ke-pagebreak {',
  3584. ' border:1px dotted #AAA;',
  3585. ' font-size:0;',
  3586. ' height:2px;',
  3587. '}',
  3588. '</style>'
  3589. ];
  3590. if (!_isArray(cssPath)) {
  3591. cssPath = [cssPath];
  3592. }
  3593. _each(cssPath, function(i, path) {
  3594. if (path) {
  3595. arr.push('<link href="' + path + '" rel="stylesheet" />');
  3596. }
  3597. });
  3598. if (cssData) {
  3599. arr.push('<style>' + cssData + '</style>');
  3600. }
  3601. arr.push('</head><body ' + (bodyClass ? 'class="' + bodyClass + '"' : '') + '></body></html>');
  3602. return arr.join('\n');
  3603. }
  3604. function _elementVal(knode, val) {
  3605. if (knode.hasVal()) {
  3606. if (val === undefined) {
  3607. var html = knode.val();
  3608. html = html.replace(/(<(?:p|p\s[^>]*)>) *(<\/p>)/ig, '');
  3609. return html;
  3610. }
  3611. return knode.val(val);
  3612. }
  3613. return knode.html(val);
  3614. }
  3615. function KEdit(options) {
  3616. this.init(options);
  3617. }
  3618. _extend(KEdit, KWidget, {
  3619. init : function(options) {
  3620. var self = this;
  3621. KEdit.parent.init.call(self, options);
  3622. self.srcElement = K(options.srcElement);
  3623. self.div.addClass('ke-edit');
  3624. self.designMode = _undef(options.designMode, true);
  3625. self.beforeGetHtml = options.beforeGetHtml;
  3626. self.beforeSetHtml = options.beforeSetHtml;
  3627. self.afterSetHtml = options.afterSetHtml;
  3628. var themesPath = _undef(options.themesPath, ''),
  3629. bodyClass = options.bodyClass,
  3630. cssPath = options.cssPath,
  3631. cssData = options.cssData,
  3632. isDocumentDomain = location.protocol != 'res:' && location.host.replace(/:\d+/, '') !== document.domain,
  3633. srcScript = ('document.open();' +
  3634. (isDocumentDomain ? 'document.domain="' + document.domain + '";' : '') +
  3635. 'document.close();'),
  3636. iframeSrc = _IE ? ' src="javascript:void(function(){' + encodeURIComponent(srcScript) + '}())"' : '';
  3637. self.iframe = K('<iframe class="ke-edit-iframe" hidefocus="true" frameborder="0"' + iframeSrc + '></iframe>').css('width', '100%');
  3638. self.textarea = K('<textarea class="ke-edit-textarea" hidefocus="true"></textarea>').css('width', '100%');
  3639. self.tabIndex = isNaN(parseInt(options.tabIndex, 10)) ? self.srcElement.attr('tabindex') : parseInt(options.tabIndex, 10);
  3640. self.iframe.attr('tabindex', self.tabIndex);
  3641. self.textarea.attr('tabindex', self.tabIndex);
  3642. if (self.width) {
  3643. self.setWidth(self.width);
  3644. }
  3645. if (self.height) {
  3646. self.setHeight(self.height);
  3647. }
  3648. if (self.designMode) {
  3649. self.textarea.hide();
  3650. } else {
  3651. self.iframe.hide();
  3652. }
  3653. function ready() {
  3654. var doc = _iframeDoc(self.iframe);
  3655. doc.open();
  3656. if (isDocumentDomain) {
  3657. doc.domain = document.domain;
  3658. }
  3659. doc.write(_getInitHtml(themesPath, bodyClass, cssPath, cssData));
  3660. doc.close();
  3661. self.win = self.iframe[0].contentWindow;
  3662. self.doc = doc;
  3663. var cmd = _cmd(doc);
  3664. self.afterChange(function(e) {
  3665. cmd.selection();
  3666. });
  3667. if (_WEBKIT) {
  3668. K(doc).click(function(e) {
  3669. if (K(e.target).name === 'img') {
  3670. cmd.selection(true);
  3671. cmd.range.selectNode(e.target);
  3672. cmd.select();
  3673. }
  3674. });
  3675. }
  3676. if (_IE) {
  3677. self._mousedownHandler = function() {
  3678. var newRange = cmd.range.cloneRange();
  3679. newRange.shrink();
  3680. if (newRange.isControl()) {
  3681. self.blur();
  3682. }
  3683. };
  3684. K(document).mousedown(self._mousedownHandler);
  3685. K(doc).keydown(function(e) {
  3686. if (e.which == 8) {
  3687. cmd.selection();
  3688. var rng = cmd.range;
  3689. if (rng.isControl()) {
  3690. rng.collapse(true);
  3691. K(rng.startContainer.childNodes[rng.startOffset]).remove();
  3692. e.preventDefault();
  3693. }
  3694. }
  3695. });
  3696. }
  3697. self.cmd = cmd;
  3698. self.html(_elementVal(self.srcElement));
  3699. if (_IE) {
  3700. doc.body.disabled = true;
  3701. doc.body.contentEditable = true;
  3702. doc.body.removeAttribute('disabled');
  3703. } else {
  3704. doc.designMode = 'on';
  3705. }
  3706. if (options.afterCreate) {
  3707. options.afterCreate.call(self);
  3708. }
  3709. }
  3710. if (isDocumentDomain) {
  3711. self.iframe.bind('load', function(e) {
  3712. self.iframe.unbind('load');
  3713. if (_IE) {
  3714. ready();
  3715. } else {
  3716. setTimeout(ready, 0);
  3717. }
  3718. });
  3719. }
  3720. self.div.append(self.iframe);
  3721. self.div.append(self.textarea);
  3722. self.srcElement.hide();
  3723. !isDocumentDomain && ready();
  3724. },
  3725. setWidth : function(val) {
  3726. var self = this;
  3727. val = _addUnit(val);
  3728. self.width = val;
  3729. self.div.css('width', val);
  3730. return self;
  3731. },
  3732. setHeight : function(val) {
  3733. var self = this;
  3734. val = _addUnit(val);
  3735. self.height = val;
  3736. self.div.css('height', val);
  3737. self.iframe.css('height', val);
  3738. if ((_IE && _V < 8) || _QUIRKS) {
  3739. val = _addUnit(_removeUnit(val) - 2);
  3740. }
  3741. self.textarea.css('height', val);
  3742. return self;
  3743. },
  3744. remove : function() {
  3745. var self = this, doc = self.doc;
  3746. K(doc.body).unbind();
  3747. K(doc).unbind();
  3748. K(self.win).unbind();
  3749. if (self._mousedownHandler) {
  3750. K(document).unbind('mousedown', self._mousedownHandler);
  3751. }
  3752. _elementVal(self.srcElement, self.html());
  3753. self.srcElement.show();
  3754. self.iframe.unbind();
  3755. self.textarea.unbind();
  3756. KEdit.parent.remove.call(self);
  3757. },
  3758. html : function(val, isFull) {
  3759. var self = this, doc = self.doc;
  3760. if (self.designMode) {
  3761. var body = doc.body;
  3762. if (val === undefined) {
  3763. if (isFull) {
  3764. val = '<!doctype html><html>' + body.parentNode.innerHTML + '</html>';
  3765. } else {
  3766. val = body.innerHTML;
  3767. }
  3768. if (self.beforeGetHtml) {
  3769. val = self.beforeGetHtml(val);
  3770. }
  3771. if (_GECKO && val == '<br />') {
  3772. val = '';
  3773. }
  3774. return val;
  3775. }
  3776. if (self.beforeSetHtml) {
  3777. val = self.beforeSetHtml(val);
  3778. }
  3779. if (_IE && _V >= 9) {
  3780. val = val.replace(/(<.*?checked=")checked(".*>)/ig, '$1$2');
  3781. }
  3782. K(body).html(val);
  3783. if (self.afterSetHtml) {
  3784. self.afterSetHtml();
  3785. }
  3786. return self;
  3787. }
  3788. if (val === undefined) {
  3789. return self.textarea.val();
  3790. }
  3791. self.textarea.val(val);
  3792. return self;
  3793. },
  3794. design : function(bool) {
  3795. var self = this, val;
  3796. if (bool === undefined ? !self.designMode : bool) {
  3797. if (!self.designMode) {
  3798. val = self.html();
  3799. self.designMode = true;
  3800. self.textarea.hide();
  3801. self.html(val);
  3802. var iframe = self.iframe;
  3803. var height = _removeUnit(self.height);
  3804. iframe.height(height - 2);
  3805. iframe.show();
  3806. setTimeout(function() {
  3807. iframe.height(height);
  3808. }, 0);
  3809. }
  3810. } else {
  3811. if (self.designMode) {
  3812. val = self.html();
  3813. self.designMode = false;
  3814. self.html(val);
  3815. self.iframe.hide();
  3816. self.textarea.show();
  3817. }
  3818. }
  3819. return self.focus();
  3820. },
  3821. focus : function() {
  3822. var self = this;
  3823. self.designMode ? self.win.focus() : self.textarea[0].focus();
  3824. return self;
  3825. },
  3826. blur : function() {
  3827. var self = this;
  3828. if (_IE) {
  3829. var input = K('<input type="text" style="float:left;width:0;height:0;padding:0;margin:0;border:0;" value="" />', self.div);
  3830. self.div.append(input);
  3831. input[0].focus();
  3832. input.remove();
  3833. } else {
  3834. self.designMode ? self.win.blur() : self.textarea[0].blur();
  3835. }
  3836. return self;
  3837. },
  3838. afterChange : function(fn) {
  3839. var self = this, doc = self.doc, body = doc.body;
  3840. K(doc).keyup(function(e) {
  3841. if (!e.ctrlKey && !e.altKey && _CHANGE_KEY_MAP[e.which]) {
  3842. fn(e);
  3843. }
  3844. });
  3845. K(doc).mouseup(fn).contextmenu(fn);
  3846. K(self.win).blur(fn);
  3847. function timeoutHandler(e) {
  3848. setTimeout(function() {
  3849. fn(e);
  3850. }, 1);
  3851. }
  3852. K(body).bind('paste', timeoutHandler);
  3853. K(body).bind('cut', timeoutHandler);
  3854. return self;
  3855. }
  3856. });
  3857. function _edit(options) {
  3858. return new KEdit(options);
  3859. }
  3860. K.EditClass = KEdit;
  3861. K.edit = _edit;
  3862. K.iframeDoc = _iframeDoc;
  3863. function _selectToolbar(name, fn) {
  3864. var self = this,
  3865. knode = self.get(name);
  3866. if (knode) {
  3867. if (knode.hasClass('ke-disabled')) {
  3868. return;
  3869. }
  3870. fn(knode);
  3871. }
  3872. }
  3873. function KToolbar(options) {
  3874. this.init(options);
  3875. }
  3876. _extend(KToolbar, KWidget, {
  3877. init : function(options) {
  3878. var self = this;
  3879. KToolbar.parent.init.call(self, options);
  3880. self.disableMode = _undef(options.disableMode, false);
  3881. self.noDisableItemMap = _toMap(_undef(options.noDisableItems, []));
  3882. self._itemMap = {};
  3883. self.div.addClass('ke-toolbar').bind('contextmenu,mousedown,mousemove', function(e) {
  3884. e.preventDefault();
  3885. }).attr('unselectable', 'on');
  3886. function find(target) {
  3887. var knode = K(target);
  3888. if (knode.hasClass('ke-outline')) {
  3889. return knode;
  3890. }
  3891. if (knode.hasClass('ke-toolbar-icon')) {
  3892. return knode.parent();
  3893. }
  3894. }
  3895. function hover(e, method) {
  3896. var knode = find(e.target);
  3897. if (knode) {
  3898. if (knode.hasClass('ke-disabled')) {
  3899. return;
  3900. }
  3901. if (knode.hasClass('ke-selected')) {
  3902. return;
  3903. }
  3904. knode[method]('ke-on');
  3905. }
  3906. }
  3907. self.div.mouseover(function(e) {
  3908. hover(e, 'addClass');
  3909. })
  3910. .mouseout(function(e) {
  3911. hover(e, 'removeClass');
  3912. })
  3913. .click(function(e) {
  3914. var knode = find(e.target);
  3915. if (knode) {
  3916. if (knode.hasClass('ke-disabled')) {
  3917. return;
  3918. }
  3919. self.options.click.call(this, e, knode.attr('data-name'));
  3920. }
  3921. });
  3922. },
  3923. get : function(name) {
  3924. if (this._itemMap[name]) {
  3925. return this._itemMap[name];
  3926. }
  3927. return (this._itemMap[name] = K('span.ke-icon-' + name, this.div).parent());
  3928. },
  3929. select : function(name) {
  3930. _selectToolbar.call(this, name, function(knode) {
  3931. knode.addClass('ke-selected');
  3932. });
  3933. return self;
  3934. },
  3935. unselect : function(name) {
  3936. _selectToolbar.call(this, name, function(knode) {
  3937. knode.removeClass('ke-selected').removeClass('ke-on');
  3938. });
  3939. return self;
  3940. },
  3941. enable : function(name) {
  3942. var self = this,
  3943. knode = name.get ? name : self.get(name);
  3944. if (knode) {
  3945. knode.removeClass('ke-disabled');
  3946. knode.opacity(1);
  3947. }
  3948. return self;
  3949. },
  3950. disable : function(name) {
  3951. var self = this,
  3952. knode = name.get ? name : self.get(name);
  3953. if (knode) {
  3954. knode.removeClass('ke-selected').addClass('ke-disabled');
  3955. knode.opacity(0.5);
  3956. }
  3957. return self;
  3958. },
  3959. disableAll : function(bool, noDisableItems) {
  3960. var self = this, map = self.noDisableItemMap, item;
  3961. if (noDisableItems) {
  3962. map = _toMap(noDisableItems);
  3963. }
  3964. if (bool === undefined ? !self.disableMode : bool) {
  3965. K('span.ke-outline', self.div).each(function() {
  3966. var knode = K(this),
  3967. name = knode[0].getAttribute('data-name', 2);
  3968. if (!map[name]) {
  3969. self.disable(knode);
  3970. }
  3971. });
  3972. self.disableMode = true;
  3973. } else {
  3974. K('span.ke-outline', self.div).each(function() {
  3975. var knode = K(this),
  3976. name = knode[0].getAttribute('data-name', 2);
  3977. if (!map[name]) {
  3978. self.enable(knode);
  3979. }
  3980. });
  3981. self.disableMode = false;
  3982. }
  3983. return self;
  3984. }
  3985. });
  3986. function _toolbar(options) {
  3987. return new KToolbar(options);
  3988. }
  3989. K.ToolbarClass = KToolbar;
  3990. K.toolbar = _toolbar;
  3991. function KMenu(options) {
  3992. this.init(options);
  3993. }
  3994. _extend(KMenu, KWidget, {
  3995. init : function(options) {
  3996. var self = this;
  3997. options.z = options.z || 811213;
  3998. KMenu.parent.init.call(self, options);
  3999. self.centerLineMode = _undef(options.centerLineMode, true);
  4000. self.div.addClass('ke-menu').bind('click,mousedown', function(e){
  4001. e.stopPropagation();
  4002. }).attr('unselectable', 'on');
  4003. },
  4004. addItem : function(item) {
  4005. var self = this;
  4006. if (item.title === '-') {
  4007. self.div.append(K('<div class="ke-menu-separator"></div>'));
  4008. return;
  4009. }
  4010. var itemDiv = K('<div class="ke-menu-item" unselectable="on"></div>'),
  4011. leftDiv = K('<div class="ke-inline-block ke-menu-item-left"></div>'),
  4012. rightDiv = K('<div class="ke-inline-block ke-menu-item-right"></div>'),
  4013. height = _addUnit(item.height),
  4014. iconClass = _undef(item.iconClass, '');
  4015. self.div.append(itemDiv);
  4016. if (height) {
  4017. itemDiv.css('height', height);
  4018. rightDiv.css('line-height', height);
  4019. }
  4020. var centerDiv;
  4021. if (self.centerLineMode) {
  4022. centerDiv = K('<div class="ke-inline-block ke-menu-item-center"></div>');
  4023. if (height) {
  4024. centerDiv.css('height', height);
  4025. }
  4026. }
  4027. itemDiv.mouseover(function(e) {
  4028. K(this).addClass('ke-menu-item-on');
  4029. if (centerDiv) {
  4030. centerDiv.addClass('ke-menu-item-center-on');
  4031. }
  4032. })
  4033. .mouseout(function(e) {
  4034. K(this).removeClass('ke-menu-item-on');
  4035. if (centerDiv) {
  4036. centerDiv.removeClass('ke-menu-item-center-on');
  4037. }
  4038. })
  4039. .click(function(e) {
  4040. item.click.call(K(this));
  4041. e.stopPropagation();
  4042. })
  4043. .append(leftDiv);
  4044. if (centerDiv) {
  4045. itemDiv.append(centerDiv);
  4046. }
  4047. itemDiv.append(rightDiv);
  4048. if (item.checked) {
  4049. iconClass = 'ke-icon-checked';
  4050. }
  4051. if (iconClass !== '') {
  4052. leftDiv.html('<span class="ke-inline-block ke-toolbar-icon ke-toolbar-icon-url ' + iconClass + '"></span>');
  4053. }
  4054. rightDiv.html(item.title);
  4055. return self;
  4056. },
  4057. remove : function() {
  4058. var self = this;
  4059. if (self.options.beforeRemove) {
  4060. self.options.beforeRemove.call(self);
  4061. }
  4062. K('.ke-menu-item', self.div[0]).unbind();
  4063. KMenu.parent.remove.call(self);
  4064. return self;
  4065. }
  4066. });
  4067. function _menu(options) {
  4068. return new KMenu(options);
  4069. }
  4070. K.MenuClass = KMenu;
  4071. K.menu = _menu;
  4072. function KColorPicker(options) {
  4073. this.init(options);
  4074. }
  4075. _extend(KColorPicker, KWidget, {
  4076. init : function(options) {
  4077. var self = this;
  4078. options.z = options.z || 811213;
  4079. KColorPicker.parent.init.call(self, options);
  4080. var colors = options.colors || [
  4081. ['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
  4082. ['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
  4083. ['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
  4084. ['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
  4085. ];
  4086. self.selectedColor = (options.selectedColor || '').toLowerCase();
  4087. self._cells = [];
  4088. self.div.addClass('ke-colorpicker').bind('click,mousedown', function(e){
  4089. e.stopPropagation();
  4090. }).attr('unselectable', 'on');
  4091. var table = self.doc.createElement('table');
  4092. self.div.append(table);
  4093. table.className = 'ke-colorpicker-table';
  4094. table.cellPadding = 0;
  4095. table.cellSpacing = 0;
  4096. table.border = 0;
  4097. var row = table.insertRow(0), cell = row.insertCell(0);
  4098. cell.colSpan = colors[0].length;
  4099. self._addAttr(cell, '', 'ke-colorpicker-cell-top');
  4100. for (var i = 0; i < colors.length; i++) {
  4101. row = table.insertRow(i + 1);
  4102. for (var j = 0; j < colors[i].length; j++) {
  4103. cell = row.insertCell(j);
  4104. self._addAttr(cell, colors[i][j], 'ke-colorpicker-cell');
  4105. }
  4106. }
  4107. },
  4108. _addAttr : function(cell, color, cls) {
  4109. var self = this;
  4110. cell = K(cell).addClass(cls);
  4111. if (self.selectedColor === color.toLowerCase()) {
  4112. cell.addClass('ke-colorpicker-cell-selected');
  4113. }
  4114. cell.attr('title', color || self.options.noColor);
  4115. cell.mouseover(function(e) {
  4116. K(this).addClass('ke-colorpicker-cell-on');
  4117. });
  4118. cell.mouseout(function(e) {
  4119. K(this).removeClass('ke-colorpicker-cell-on');
  4120. });
  4121. cell.click(function(e) {
  4122. e.stop();
  4123. self.options.click.call(K(this), color);
  4124. });
  4125. if (color) {
  4126. cell.append(K('<div class="ke-colorpicker-cell-color" unselectable="on"></div>').css('background-color', color));
  4127. } else {
  4128. cell.html(self.options.noColor);
  4129. }
  4130. K(cell).attr('unselectable', 'on');
  4131. self._cells.push(cell);
  4132. },
  4133. remove : function() {
  4134. var self = this;
  4135. _each(self._cells, function() {
  4136. this.unbind();
  4137. });
  4138. KColorPicker.parent.remove.call(self);
  4139. return self;
  4140. }
  4141. });
  4142. function _colorpicker(options) {
  4143. return new KColorPicker(options);
  4144. }
  4145. K.ColorPickerClass = KColorPicker;
  4146. K.colorpicker = _colorpicker;
  4147. function KUploadButton(options) {
  4148. this.init(options);
  4149. }
  4150. _extend(KUploadButton, {
  4151. init : function(options) {
  4152. var self = this,
  4153. button = K(options.button),
  4154. fieldName = options.fieldName || 'file',
  4155. url = options.url || '',
  4156. title = button.val(),
  4157. extraParams = options.extraParams || {},
  4158. cls = button[0].className || '',
  4159. target = options.target || 'kindeditor_upload_iframe_' + new Date().getTime();
  4160. options.afterError = options.afterError || function(str) {
  4161. alert(str);
  4162. };
  4163. var hiddenElements = [];
  4164. for(var k in extraParams){
  4165. hiddenElements.push('<input type="hidden" name="' + k + '" value="' + extraParams[k] + '" />');
  4166. }
  4167. var html = [
  4168. '<div class="ke-inline-block ' + cls + '">',
  4169. (options.target ? '' : '<iframe name="' + target + '" style="display:none;"></iframe>'),
  4170. (options.form ? '<div class="ke-upload-area">' : '<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + url + '">'),
  4171. '<span class="ke-button-common">',
  4172. hiddenElements.join(''),
  4173. '<input type="button" class="ke-button-common ke-button" value="' + title + '" />',
  4174. '</span>',
  4175. '<input type="file" class="ke-upload-file" name="' + fieldName + '" tabindex="-1" />',
  4176. (options.form ? '</div>' : '</form>'),
  4177. '</div>'].join('');
  4178. var div = K(html, button.doc);
  4179. button.hide();
  4180. button.before(div);
  4181. self.div = div;
  4182. self.button = button;
  4183. self.iframe = options.target ? K('iframe[name="' + target + '"]') : K('iframe', div);
  4184. self.form = options.form ? K(options.form) : K('form', div);
  4185. self.fileBox = K('.ke-upload-file', div);
  4186. var width = options.width || K('.ke-button-common', div).width();
  4187. K('.ke-upload-area', div).width(width);
  4188. self.options = options;
  4189. },
  4190. submit : function() {
  4191. var self = this,
  4192. iframe = self.iframe;
  4193. iframe.bind('load', function() {
  4194. iframe.unbind();
  4195. var tempForm = document.createElement('form');
  4196. self.fileBox.before(tempForm);
  4197. K(tempForm).append(self.fileBox);
  4198. tempForm.reset();
  4199. K(tempForm).remove(true);
  4200. var doc = K.iframeDoc(iframe),
  4201. pre = doc.getElementsByTagName('pre')[0],
  4202. str = '', data;
  4203. if (pre) {
  4204. str = pre.innerHTML;
  4205. } else {
  4206. str = doc.body.innerHTML;
  4207. }
  4208. str = _unescape(str);
  4209. iframe[0].src = 'javascript:false';
  4210. try {
  4211. data = K.json(str);
  4212. } catch (e) {
  4213. self.options.afterError.call(self, '<!doctype html><html>' + doc.body.parentNode.innerHTML + '</html>');
  4214. }
  4215. if (data) {
  4216. self.options.afterUpload.call(self, data);
  4217. }
  4218. });
  4219. self.form[0].submit();
  4220. return self;
  4221. },
  4222. remove : function() {
  4223. var self = this;
  4224. if (self.fileBox) {
  4225. self.fileBox.unbind();
  4226. }
  4227. self.iframe.remove();
  4228. self.div.remove();
  4229. self.button.show();
  4230. return self;
  4231. }
  4232. });
  4233. function _uploadbutton(options) {
  4234. return new KUploadButton(options);
  4235. }
  4236. K.UploadButtonClass = KUploadButton;
  4237. K.uploadbutton = _uploadbutton;
  4238. function _createButton(arg) {
  4239. arg = arg || {};
  4240. var name = arg.name || '',
  4241. span = K('<span class="ke-button-common ke-button-outer" title="' + name + '"></span>'),
  4242. btn = K('<input class="ke-button-common ke-button" type="button" value="' + name + '" />');
  4243. if (arg.click) {
  4244. btn.click(arg.click);
  4245. }
  4246. span.append(btn);
  4247. return span;
  4248. }
  4249. function KDialog(options) {
  4250. this.init(options);
  4251. }
  4252. _extend(KDialog, KWidget, {
  4253. init : function(options) {
  4254. var self = this;
  4255. var shadowMode = _undef(options.shadowMode, true);
  4256. options.z = options.z || 811213;
  4257. options.shadowMode = false;
  4258. options.autoScroll = _undef(options.autoScroll, true);
  4259. KDialog.parent.init.call(self, options);
  4260. var title = options.title,
  4261. body = K(options.body, self.doc),
  4262. previewBtn = options.previewBtn,
  4263. yesBtn = options.yesBtn,
  4264. noBtn = options.noBtn,
  4265. closeBtn = options.closeBtn,
  4266. showMask = _undef(options.showMask, true);
  4267. self.div.addClass('ke-dialog').bind('click,mousedown', function(e){
  4268. e.stopPropagation();
  4269. });
  4270. var contentDiv = K('<div class="ke-dialog-content"></div>').appendTo(self.div);
  4271. if (_IE && _V < 7) {
  4272. self.iframeMask = K('<iframe src="about:blank" class="ke-dialog-shadow"></iframe>').appendTo(self.div);
  4273. } else if (shadowMode) {
  4274. K('<div class="ke-dialog-shadow"></div>').appendTo(self.div);
  4275. }
  4276. var headerDiv = K('<div class="ke-dialog-header"></div>');
  4277. contentDiv.append(headerDiv);
  4278. headerDiv.html(title);
  4279. self.closeIcon = K('<span class="ke-dialog-icon-close" title="' + closeBtn.name + '"></span>').click(closeBtn.click);
  4280. headerDiv.append(self.closeIcon);
  4281. self.draggable({
  4282. clickEl : headerDiv,
  4283. beforeDrag : options.beforeDrag
  4284. });
  4285. var bodyDiv = K('<div class="ke-dialog-body"></div>');
  4286. contentDiv.append(bodyDiv);
  4287. bodyDiv.append(body);
  4288. var footerDiv = K('<div class="ke-dialog-footer"></div>');
  4289. if (previewBtn || yesBtn || noBtn) {
  4290. contentDiv.append(footerDiv);
  4291. }
  4292. _each([
  4293. { btn : previewBtn, name : 'preview' },
  4294. { btn : yesBtn, name : 'yes' },
  4295. { btn : noBtn, name : 'no' }
  4296. ], function() {
  4297. if (this.btn) {
  4298. var button = _createButton(this.btn);
  4299. button.addClass('ke-dialog-' + this.name);
  4300. footerDiv.append(button);
  4301. }
  4302. });
  4303. if (self.height) {
  4304. bodyDiv.height(_removeUnit(self.height) - headerDiv.height() - footerDiv.height());
  4305. }
  4306. self.div.width(self.div.width());
  4307. self.div.height(self.div.height());
  4308. self.mask = null;
  4309. if (showMask) {
  4310. var docEl = _docElement(self.doc),
  4311. docWidth = Math.max(docEl.scrollWidth, docEl.clientWidth),
  4312. docHeight = Math.max(docEl.scrollHeight, docEl.clientHeight);
  4313. self.mask = _widget({
  4314. x : 0,
  4315. y : 0,
  4316. z : self.z - 1,
  4317. cls : 'ke-dialog-mask',
  4318. width : docWidth,
  4319. height : docHeight
  4320. });
  4321. }
  4322. self.autoPos(self.div.width(), self.div.height());
  4323. self.footerDiv = footerDiv;
  4324. self.bodyDiv = bodyDiv;
  4325. self.headerDiv = headerDiv;
  4326. self.isLoading = false;
  4327. },
  4328. setMaskIndex : function(z) {
  4329. var self = this;
  4330. self.mask.div.css('z-index', z);
  4331. },
  4332. showLoading : function(msg) {
  4333. msg = _undef(msg, '');
  4334. var self = this, body = self.bodyDiv;
  4335. self.loading = K('<div class="ke-dialog-loading"><div class="ke-inline-block ke-dialog-loading-content" style="margin-top:' + Math.round(body.height() / 3) + 'px;">' + msg + '</div></div>')
  4336. .width(body.width()).height(body.height())
  4337. .css('top', self.headerDiv.height() + 'px');
  4338. body.css('visibility', 'hidden').after(self.loading);
  4339. self.isLoading = true;
  4340. return self;
  4341. },
  4342. hideLoading : function() {
  4343. this.loading && this.loading.remove();
  4344. this.bodyDiv.css('visibility', 'visible');
  4345. this.isLoading = false;
  4346. return this;
  4347. },
  4348. remove : function() {
  4349. var self = this;
  4350. if (self.options.beforeRemove) {
  4351. self.options.beforeRemove.call(self);
  4352. }
  4353. self.mask && self.mask.remove();
  4354. self.iframeMask && self.iframeMask.remove();
  4355. self.closeIcon.unbind();
  4356. K('input', self.div).unbind();
  4357. K('button', self.div).unbind();
  4358. self.footerDiv.unbind();
  4359. self.bodyDiv.unbind();
  4360. self.headerDiv.unbind();
  4361. K('iframe', self.div).each(function() {
  4362. K(this).remove();
  4363. });
  4364. KDialog.parent.remove.call(self);
  4365. return self;
  4366. }
  4367. });
  4368. function _dialog(options) {
  4369. return new KDialog(options);
  4370. }
  4371. K.DialogClass = KDialog;
  4372. K.dialog = _dialog;
  4373. function _tabs(options) {
  4374. var self = _widget(options),
  4375. remove = self.remove,
  4376. afterSelect = options.afterSelect,
  4377. div = self.div,
  4378. liList = [];
  4379. div.addClass('ke-tabs')
  4380. .bind('contextmenu,mousedown,mousemove', function(e) {
  4381. e.preventDefault();
  4382. });
  4383. var ul = K('<ul class="ke-tabs-ul ke-clearfix"></ul>');
  4384. div.append(ul);
  4385. self.add = function(tab) {
  4386. var li = K('<li class="ke-tabs-li">' + tab.title + '</li>');
  4387. li.data('tab', tab);
  4388. liList.push(li);
  4389. ul.append(li);
  4390. };
  4391. self.selectedIndex = 0;
  4392. self.select = function(index) {
  4393. self.selectedIndex = index;
  4394. _each(liList, function(i, li) {
  4395. li.unbind();
  4396. if (i === index) {
  4397. li.addClass('ke-tabs-li-selected');
  4398. K(li.data('tab').panel).show('');
  4399. } else {
  4400. li.removeClass('ke-tabs-li-selected').removeClass('ke-tabs-li-on')
  4401. .mouseover(function() {
  4402. K(this).addClass('ke-tabs-li-on');
  4403. })
  4404. .mouseout(function() {
  4405. K(this).removeClass('ke-tabs-li-on');
  4406. })
  4407. .click(function() {
  4408. self.select(i);
  4409. });
  4410. K(li.data('tab').panel).hide();
  4411. }
  4412. });
  4413. if (afterSelect) {
  4414. afterSelect.call(self, index);
  4415. }
  4416. };
  4417. self.remove = function() {
  4418. _each(liList, function() {
  4419. this.remove();
  4420. });
  4421. ul.remove();
  4422. remove.call(self);
  4423. };
  4424. return self;
  4425. }
  4426. K.tabs = _tabs;
  4427. function _loadScript(url, fn) {
  4428. var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
  4429. script = document.createElement('script');
  4430. head.appendChild(script);
  4431. script.src = url;
  4432. script.charset = 'utf-8';
  4433. script.onload = script.onreadystatechange = function() {
  4434. if (!this.readyState || this.readyState === 'loaded') {
  4435. if (fn) {
  4436. fn();
  4437. }
  4438. script.onload = script.onreadystatechange = null;
  4439. head.removeChild(script);
  4440. }
  4441. };
  4442. }
  4443. function _chopQuery(url) {
  4444. var index = url.indexOf('?');
  4445. return index > 0 ? url.substr(0, index) : url;
  4446. }
  4447. function _loadStyle(url) {
  4448. var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
  4449. link = document.createElement('link'),
  4450. absoluteUrl = _chopQuery(_formatUrl(url, 'absolute'));
  4451. var links = K('link[rel="stylesheet"]', head);
  4452. for (var i = 0, len = links.length; i < len; i++) {
  4453. if (_chopQuery(_formatUrl(links[i].href, 'absolute')) === absoluteUrl) {
  4454. return;
  4455. }
  4456. }
  4457. head.appendChild(link);
  4458. link.href = url;
  4459. link.rel = 'stylesheet';
  4460. }
  4461. function _ajax(url, fn, method, param, dataType) {
  4462. method = method || 'GET';
  4463. dataType = dataType || 'json';
  4464. var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
  4465. xhr.open(method, url, true);
  4466. xhr.onreadystatechange = function () {
  4467. if (xhr.readyState == 4 && xhr.status == 200) {
  4468. if (fn) {
  4469. var data = _trim(xhr.responseText);
  4470. if (dataType == 'json') {
  4471. data = _json(data);
  4472. }
  4473. fn(data);
  4474. }
  4475. }
  4476. };
  4477. if (method == 'POST') {
  4478. var params = [];
  4479. _each(param, function(key, val) {
  4480. params.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
  4481. });
  4482. try {
  4483. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  4484. } catch (e) {}
  4485. xhr.send(params.join('&'));
  4486. } else {
  4487. xhr.send(null);
  4488. }
  4489. }
  4490. K.loadScript = _loadScript;
  4491. K.loadStyle = _loadStyle;
  4492. K.ajax = _ajax;
  4493. var _plugins = {};
  4494. function _plugin(name, fn) {
  4495. if (name === undefined) {
  4496. return _plugins;
  4497. }
  4498. if (!fn) {
  4499. return _plugins[name];
  4500. }
  4501. _plugins[name] = fn;
  4502. }
  4503. var _language = {};
  4504. function _parseLangKey(key) {
  4505. var match, ns = 'core';
  4506. if ((match = /^(\w+)\.(\w+)$/.exec(key))) {
  4507. ns = match[1];
  4508. key = match[2];
  4509. }
  4510. return { ns : ns, key : key };
  4511. }
  4512. function _lang(mixed, langType) {
  4513. langType = langType === undefined ? K.options.langType : langType;
  4514. if (typeof mixed === 'string') {
  4515. if (!_language[langType]) {
  4516. return 'no language';
  4517. }
  4518. var pos = mixed.length - 1;
  4519. if (mixed.substr(pos) === '.') {
  4520. return _language[langType][mixed.substr(0, pos)];
  4521. }
  4522. var obj = _parseLangKey(mixed);
  4523. return _language[langType][obj.ns][obj.key];
  4524. }
  4525. _each(mixed, function(key, val) {
  4526. var obj = _parseLangKey(key);
  4527. if (!_language[langType]) {
  4528. _language[langType] = {};
  4529. }
  4530. if (!_language[langType][obj.ns]) {
  4531. _language[langType][obj.ns] = {};
  4532. }
  4533. _language[langType][obj.ns][obj.key] = val;
  4534. });
  4535. }
  4536. function _getImageFromRange(range, fn) {
  4537. if (range.collapsed) {
  4538. return;
  4539. }
  4540. range = range.cloneRange().up();
  4541. var sc = range.startContainer, so = range.startOffset;
  4542. if (!_WEBKIT && !range.isControl()) {
  4543. return;
  4544. }
  4545. var img = K(sc.childNodes[so]);
  4546. if (!img || img.name != 'img') {
  4547. return;
  4548. }
  4549. if (fn(img)) {
  4550. return img;
  4551. }
  4552. }
  4553. function _bindContextmenuEvent() {
  4554. var self = this, doc = self.edit.doc;
  4555. K(doc).contextmenu(function(e) {
  4556. if (self.menu) {
  4557. self.hideMenu();
  4558. }
  4559. if (!self.useContextmenu) {
  4560. e.preventDefault();
  4561. return;
  4562. }
  4563. if (self._contextmenus.length === 0) {
  4564. return;
  4565. }
  4566. var maxWidth = 0, items = [];
  4567. _each(self._contextmenus, function() {
  4568. if (this.title == '-') {
  4569. items.push(this);
  4570. return;
  4571. }
  4572. if (this.cond && this.cond()) {
  4573. items.push(this);
  4574. if (this.width && this.width > maxWidth) {
  4575. maxWidth = this.width;
  4576. }
  4577. }
  4578. });
  4579. while (items.length > 0 && items[0].title == '-') {
  4580. items.shift();
  4581. }
  4582. while (items.length > 0 && items[items.length - 1].title == '-') {
  4583. items.pop();
  4584. }
  4585. var prevItem = null;
  4586. _each(items, function(i) {
  4587. if (this.title == '-' && prevItem.title == '-') {
  4588. delete items[i];
  4589. }
  4590. prevItem = this;
  4591. });
  4592. if (items.length > 0) {
  4593. e.preventDefault();
  4594. var pos = K(self.edit.iframe).pos(),
  4595. menu = _menu({
  4596. x : pos.x + e.clientX,
  4597. y : pos.y + e.clientY,
  4598. width : maxWidth,
  4599. css : { visibility: 'hidden' },
  4600. shadowMode : self.shadowMode
  4601. });
  4602. _each(items, function() {
  4603. if (this.title) {
  4604. menu.addItem(this);
  4605. }
  4606. });
  4607. var docEl = _docElement(menu.doc),
  4608. menuHeight = menu.div.height();
  4609. if (e.clientY + menuHeight >= docEl.clientHeight - 100) {
  4610. menu.pos(menu.x, _removeUnit(menu.y) - menuHeight);
  4611. }
  4612. menu.div.css('visibility', 'visible');
  4613. self.menu = menu;
  4614. }
  4615. });
  4616. }
  4617. function _bindNewlineEvent() {
  4618. var self = this, doc = self.edit.doc, newlineTag = self.newlineTag;
  4619. if (_IE && newlineTag !== 'br') {
  4620. return;
  4621. }
  4622. if (_GECKO && _V < 3 && newlineTag !== 'p') {
  4623. return;
  4624. }
  4625. if (_OPERA && _V < 9) {
  4626. return;
  4627. }
  4628. var brSkipTagMap = _toMap('h1,h2,h3,h4,h5,h6,pre,li'),
  4629. pSkipTagMap = _toMap('p,h1,h2,h3,h4,h5,h6,pre,li,blockquote');
  4630. function getAncestorTagName(range) {
  4631. var ancestor = K(range.commonAncestor());
  4632. while (ancestor) {
  4633. if (ancestor.type == 1 && !ancestor.isStyle()) {
  4634. break;
  4635. }
  4636. ancestor = ancestor.parent();
  4637. }
  4638. return ancestor.name;
  4639. }
  4640. K(doc).keydown(function(e) {
  4641. if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
  4642. return;
  4643. }
  4644. self.cmd.selection();
  4645. var tagName = getAncestorTagName(self.cmd.range);
  4646. if (tagName == 'marquee' || tagName == 'select') {
  4647. return;
  4648. }
  4649. if (newlineTag === 'br' && !brSkipTagMap[tagName]) {
  4650. e.preventDefault();
  4651. self.insertHtml('<br />' + (_IE && _V < 9 ? '' : '\u200B'));
  4652. return;
  4653. }
  4654. if (!pSkipTagMap[tagName]) {
  4655. _nativeCommand(doc, 'formatblock', '<p>');
  4656. }
  4657. });
  4658. K(doc).keyup(function(e) {
  4659. if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
  4660. return;
  4661. }
  4662. if (newlineTag == 'br') {
  4663. return;
  4664. }
  4665. if (_GECKO) {
  4666. var root = self.cmd.commonAncestor('p');
  4667. var a = self.cmd.commonAncestor('a');
  4668. if (a && a.text() == '') {
  4669. a.remove(true);
  4670. self.cmd.range.selectNodeContents(root[0]).collapse(true);
  4671. self.cmd.select();
  4672. }
  4673. return;
  4674. }
  4675. self.cmd.selection();
  4676. var tagName = getAncestorTagName(self.cmd.range);
  4677. if (tagName == 'marquee' || tagName == 'select') {
  4678. return;
  4679. }
  4680. if (!pSkipTagMap[tagName]) {
  4681. _nativeCommand(doc, 'formatblock', '<p>');
  4682. }
  4683. var div = self.cmd.commonAncestor('div');
  4684. if (div) {
  4685. var p = K('<p></p>'),
  4686. child = div[0].firstChild;
  4687. while (child) {
  4688. var next = child.nextSibling;
  4689. p.append(child);
  4690. child = next;
  4691. }
  4692. div.before(p);
  4693. div.remove();
  4694. self.cmd.range.selectNodeContents(p[0]);
  4695. self.cmd.select();
  4696. }
  4697. });
  4698. }
  4699. function _bindTabEvent() {
  4700. var self = this, doc = self.edit.doc;
  4701. K(doc).keydown(function(e) {
  4702. if (e.which == 9) {
  4703. e.preventDefault();
  4704. if (self.afterTab) {
  4705. self.afterTab.call(self, e);
  4706. return;
  4707. }
  4708. var cmd = self.cmd, range = cmd.range;
  4709. range.shrink();
  4710. if (range.collapsed && range.startContainer.nodeType == 1) {
  4711. range.insertNode(K('@&nbsp;', doc)[0]);
  4712. cmd.select();
  4713. }
  4714. self.insertHtml('&nbsp;&nbsp;&nbsp;&nbsp;');
  4715. }
  4716. });
  4717. }
  4718. function _bindFocusEvent() {
  4719. var self = this;
  4720. K(self.edit.textarea[0], self.edit.win).focus(function(e) {
  4721. if (self.afterFocus) {
  4722. self.afterFocus.call(self, e);
  4723. }
  4724. }).blur(function(e) {
  4725. if (self.afterBlur) {
  4726. self.afterBlur.call(self, e);
  4727. }
  4728. });
  4729. }
  4730. function _removeBookmarkTag(html) {
  4731. return _trim(html.replace(/<span [^>]*id="?__kindeditor_bookmark_\w+_\d+__"?[^>]*><\/span>/ig, ''));
  4732. }
  4733. function _removeTempTag(html) {
  4734. return html.replace(/<div[^>]+class="?__kindeditor_paste__"?[^>]*>[\s\S]*?<\/div>/ig, '');
  4735. }
  4736. function _addBookmarkToStack(stack, bookmark) {
  4737. if (stack.length === 0) {
  4738. stack.push(bookmark);
  4739. return;
  4740. }
  4741. var prev = stack[stack.length - 1];
  4742. if (_removeBookmarkTag(bookmark.html) !== _removeBookmarkTag(prev.html)) {
  4743. stack.push(bookmark);
  4744. }
  4745. }
  4746. function _undoToRedo(fromStack, toStack) {
  4747. var self = this, edit = self.edit,
  4748. body = edit.doc.body,
  4749. range, bookmark;
  4750. if (fromStack.length === 0) {
  4751. return self;
  4752. }
  4753. if (edit.designMode) {
  4754. range = self.cmd.range;
  4755. bookmark = range.createBookmark(true);
  4756. bookmark.html = body.innerHTML;
  4757. } else {
  4758. bookmark = {
  4759. html : body.innerHTML
  4760. };
  4761. }
  4762. _addBookmarkToStack(toStack, bookmark);
  4763. var prev = fromStack.pop();
  4764. if (_removeBookmarkTag(bookmark.html) === _removeBookmarkTag(prev.html) && fromStack.length > 0) {
  4765. prev = fromStack.pop();
  4766. }
  4767. if (edit.designMode) {
  4768. edit.html(prev.html);
  4769. if (prev.start) {
  4770. range.moveToBookmark(prev);
  4771. self.select();
  4772. }
  4773. } else {
  4774. K(body).html(_removeBookmarkTag(prev.html));
  4775. }
  4776. return self;
  4777. }
  4778. function KEditor(options) {
  4779. var self = this;
  4780. self.options = {};
  4781. function setOption(key, val) {
  4782. if (KEditor.prototype[key] === undefined) {
  4783. self[key] = val;
  4784. }
  4785. self.options[key] = val;
  4786. }
  4787. _each(options, function(key, val) {
  4788. setOption(key, options[key]);
  4789. });
  4790. _each(K.options, function(key, val) {
  4791. if (self[key] === undefined) {
  4792. setOption(key, val);
  4793. }
  4794. });
  4795. var se = K(self.srcElement || '<textarea/>');
  4796. if (!self.width) {
  4797. self.width = se[0].style.width || se.width();
  4798. }
  4799. if (!self.height) {
  4800. self.height = se[0].style.height || se.height();
  4801. }
  4802. setOption('width', _undef(self.width, self.minWidth));
  4803. setOption('height', _undef(self.height, self.minHeight));
  4804. setOption('width', _addUnit(self.width));
  4805. setOption('height', _addUnit(self.height));
  4806. if (_MOBILE && (!_IOS || _V < 534)) {
  4807. self.designMode = false;
  4808. }
  4809. self.srcElement = se;
  4810. self.initContent = '';
  4811. self.plugin = {};
  4812. self.isCreated = false;
  4813. self._handlers = {};
  4814. self._contextmenus = [];
  4815. self._undoStack = [];
  4816. self._redoStack = [];
  4817. self._firstAddBookmark = true;
  4818. self.menu = self.contextmenu = null;
  4819. self.dialogs = [];
  4820. }
  4821. KEditor.prototype = {
  4822. lang : function(mixed) {
  4823. return _lang(mixed, this.langType);
  4824. },
  4825. loadPlugin : function(name, fn) {
  4826. var self = this;
  4827. var _pluginStatus = this._pluginStatus;
  4828. if (!_pluginStatus) {
  4829. _pluginStatus = this._pluginStatus = {};
  4830. }
  4831. if (_plugins[name]) {
  4832. if (!_isFunction(_plugins[name])) {
  4833. setTimeout(function() {
  4834. self.loadPlugin(name, fn);
  4835. }, 100);
  4836. return self;
  4837. }
  4838. if(!_pluginStatus[name]) {
  4839. _plugins[name].call(self, KindEditor);
  4840. _pluginStatus[name] = 'inited';
  4841. }
  4842. if (fn) {
  4843. fn.call(self);
  4844. }
  4845. return self;
  4846. }
  4847. _plugins[name] = 'loading';
  4848. _loadScript(self.pluginsPath + name + '/' + name + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
  4849. setTimeout(function() {
  4850. if (_plugins[name]) {
  4851. self.loadPlugin(name, fn);
  4852. }
  4853. }, 0);
  4854. });
  4855. return self;
  4856. },
  4857. handler : function(key, fn) {
  4858. var self = this;
  4859. if (!self._handlers[key]) {
  4860. self._handlers[key] = [];
  4861. }
  4862. if (_isFunction(fn)) {
  4863. self._handlers[key].push(fn);
  4864. return self;
  4865. }
  4866. _each(self._handlers[key], function() {
  4867. fn = this.call(self, fn);
  4868. });
  4869. return fn;
  4870. },
  4871. clickToolbar : function(name, fn) {
  4872. var self = this, key = 'clickToolbar' + name;
  4873. if (fn === undefined) {
  4874. if (self._handlers[key]) {
  4875. return self.handler(key);
  4876. }
  4877. self.loadPlugin(name, function() {
  4878. self.handler(key);
  4879. });
  4880. return self;
  4881. }
  4882. return self.handler(key, fn);
  4883. },
  4884. updateState : function() {
  4885. var self = this;
  4886. _each(('justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,insertunorderedlist,' +
  4887. 'subscript,superscript,bold,italic,underline,strikethrough').split(','), function(i, name) {
  4888. self.cmd.state(name) ? self.toolbar.select(name) : self.toolbar.unselect(name);
  4889. });
  4890. return self;
  4891. },
  4892. addContextmenu : function(item) {
  4893. this._contextmenus.push(item);
  4894. return this;
  4895. },
  4896. afterCreate : function(fn) {
  4897. return this.handler('afterCreate', fn);
  4898. },
  4899. beforeRemove : function(fn) {
  4900. return this.handler('beforeRemove', fn);
  4901. },
  4902. beforeGetHtml : function(fn) {
  4903. return this.handler('beforeGetHtml', fn);
  4904. },
  4905. beforeSetHtml : function(fn) {
  4906. return this.handler('beforeSetHtml', fn);
  4907. },
  4908. afterSetHtml : function(fn) {
  4909. return this.handler('afterSetHtml', fn);
  4910. },
  4911. create : function() {
  4912. var self = this, fullscreenMode = self.fullscreenMode;
  4913. if (self.isCreated) {
  4914. return self;
  4915. }
  4916. if (self.srcElement.data('kindeditor')) {
  4917. return self;
  4918. }
  4919. self.srcElement.data('kindeditor', 'true');
  4920. if (fullscreenMode) {
  4921. _docElement().style.overflow = 'hidden';
  4922. } else {
  4923. _docElement().style.overflow = '';
  4924. }
  4925. var width = fullscreenMode ? _docElement().clientWidth + 'px' : self.width,
  4926. height = fullscreenMode ? _docElement().clientHeight + 'px' : self.height;
  4927. if ((_IE && _V < 8) || _QUIRKS) {
  4928. height = _addUnit(_removeUnit(height) + 2);
  4929. }
  4930. var container = self.container = K(self.layout);
  4931. if (fullscreenMode) {
  4932. K(document.body).append(container);
  4933. } else {
  4934. self.srcElement.before(container);
  4935. }
  4936. var toolbarDiv = K('.toolbar', container),
  4937. editDiv = K('.edit', container),
  4938. statusbar = self.statusbar = K('.statusbar', container);
  4939. container.removeClass('container')
  4940. .addClass('ke-container ke-container-' + self.themeType).css('width', width);
  4941. if (fullscreenMode) {
  4942. container.css({
  4943. position : 'absolute',
  4944. left : 0,
  4945. top : 0,
  4946. 'z-index' : 811211
  4947. });
  4948. if (!_GECKO) {
  4949. self._scrollPos = _getScrollPos();
  4950. }
  4951. window.scrollTo(0, 0);
  4952. K(document.body).css({
  4953. 'height' : '1px',
  4954. 'overflow' : 'hidden'
  4955. });
  4956. K(document.body.parentNode).css('overflow', 'hidden');
  4957. self._fullscreenExecuted = true;
  4958. } else {
  4959. if (self._fullscreenExecuted) {
  4960. K(document.body).css({
  4961. 'height' : '',
  4962. 'overflow' : ''
  4963. });
  4964. K(document.body.parentNode).css('overflow', '');
  4965. }
  4966. if (self._scrollPos) {
  4967. window.scrollTo(self._scrollPos.x, self._scrollPos.y);
  4968. }
  4969. }
  4970. var htmlList = [];
  4971. K.each(self.items, function(i, name) {
  4972. if (name == '|') {
  4973. htmlList.push('<span class="ke-inline-block ke-separator"></span>');
  4974. } else if (name == '/') {
  4975. htmlList.push('<div class="ke-hr"></div>');
  4976. } else {
  4977. htmlList.push('<span class="ke-outline" data-name="' + name + '" title="' + self.lang(name) + '" unselectable="on">');
  4978. htmlList.push('<span class="ke-toolbar-icon ke-toolbar-icon-url ke-icon-' + name + '" unselectable="on"></span></span>');
  4979. }
  4980. });
  4981. var toolbar = self.toolbar = _toolbar({
  4982. src : toolbarDiv,
  4983. html : htmlList.join(''),
  4984. noDisableItems : self.noDisableItems,
  4985. click : function(e, name) {
  4986. e.stop();
  4987. if (self.menu) {
  4988. var menuName = self.menu.name;
  4989. self.hideMenu();
  4990. if (menuName === name) {
  4991. return;
  4992. }
  4993. }
  4994. self.clickToolbar(name);
  4995. }
  4996. });
  4997. var editHeight = _removeUnit(height) - toolbar.div.height();
  4998. var edit = self.edit = _edit({
  4999. height : editHeight > 0 && _removeUnit(height) > self.minHeight ? editHeight : self.minHeight,
  5000. src : editDiv,
  5001. srcElement : self.srcElement,
  5002. designMode : self.designMode,
  5003. themesPath : self.themesPath,
  5004. bodyClass : self.bodyClass,
  5005. cssPath : self.cssPath,
  5006. cssData : self.cssData,
  5007. beforeGetHtml : function(html) {
  5008. html = self.beforeGetHtml(html);
  5009. html = _removeBookmarkTag(_removeTempTag(html));
  5010. return _formatHtml(html, self.filterMode ? self.htmlTags : null, self.urlType, self.wellFormatMode, self.indentChar);
  5011. },
  5012. beforeSetHtml : function(html) {
  5013. html = _formatHtml(html, self.filterMode ? self.htmlTags : null, '', false);
  5014. return self.beforeSetHtml(html);
  5015. },
  5016. afterSetHtml : function() {
  5017. self.edit = edit = this;
  5018. self.afterSetHtml();
  5019. },
  5020. afterCreate : function() {
  5021. self.edit = edit = this;
  5022. self.cmd = edit.cmd;
  5023. self._docMousedownFn = function(e) {
  5024. if (self.menu) {
  5025. self.hideMenu();
  5026. }
  5027. };
  5028. K(edit.doc, document).mousedown(self._docMousedownFn);
  5029. _bindContextmenuEvent.call(self);
  5030. _bindNewlineEvent.call(self);
  5031. _bindTabEvent.call(self);
  5032. _bindFocusEvent.call(self);
  5033. edit.afterChange(function(e) {
  5034. if (!edit.designMode) {
  5035. return;
  5036. }
  5037. self.updateState();
  5038. self.addBookmark();
  5039. if (self.options.afterChange) {
  5040. self.options.afterChange.call(self);
  5041. }
  5042. });
  5043. edit.textarea.keyup(function(e) {
  5044. if (!e.ctrlKey && !e.altKey && _INPUT_KEY_MAP[e.which]) {
  5045. if (self.options.afterChange) {
  5046. self.options.afterChange.call(self);
  5047. }
  5048. }
  5049. });
  5050. if (self.readonlyMode) {
  5051. self.readonly();
  5052. }
  5053. self.isCreated = true;
  5054. if (self.initContent === '') {
  5055. self.initContent = self.html();
  5056. }
  5057. if (self._undoStack.length > 0) {
  5058. var prev = self._undoStack.pop();
  5059. if (prev.start) {
  5060. self.html(prev.html);
  5061. edit.cmd.range.moveToBookmark(prev);
  5062. self.select();
  5063. }
  5064. }
  5065. self.afterCreate();
  5066. if (self.options.afterCreate) {
  5067. self.options.afterCreate.call(self);
  5068. }
  5069. }
  5070. });
  5071. statusbar.removeClass('statusbar').addClass('ke-statusbar')
  5072. .append('<span class="ke-inline-block ke-statusbar-center-icon"></span>')
  5073. .append('<span class="ke-inline-block ke-statusbar-right-icon"></span>');
  5074. if (self._fullscreenResizeHandler) {
  5075. K(window).unbind('resize', self._fullscreenResizeHandler);
  5076. self._fullscreenResizeHandler = null;
  5077. }
  5078. function initResize() {
  5079. if (statusbar.height() === 0) {
  5080. setTimeout(initResize, 100);
  5081. return;
  5082. }
  5083. self.resize(width, height, false);
  5084. }
  5085. initResize();
  5086. if (fullscreenMode) {
  5087. self._fullscreenResizeHandler = function(e) {
  5088. if (self.isCreated) {
  5089. self.resize(_docElement().clientWidth, _docElement().clientHeight, false);
  5090. }
  5091. };
  5092. K(window).bind('resize', self._fullscreenResizeHandler);
  5093. toolbar.select('fullscreen');
  5094. statusbar.first().css('visibility', 'hidden');
  5095. statusbar.last().css('visibility', 'hidden');
  5096. } else {
  5097. if (_GECKO) {
  5098. K(window).bind('scroll', function(e) {
  5099. self._scrollPos = _getScrollPos();
  5100. });
  5101. }
  5102. if (self.resizeType > 0) {
  5103. _drag({
  5104. moveEl : container,
  5105. clickEl : statusbar,
  5106. moveFn : function(x, y, width, height, diffX, diffY) {
  5107. height += diffY;
  5108. self.resize(null, height);
  5109. }
  5110. });
  5111. } else {
  5112. statusbar.first().css('visibility', 'hidden');
  5113. }
  5114. if (self.resizeType === 2) {
  5115. _drag({
  5116. moveEl : container,
  5117. clickEl : statusbar.last(),
  5118. moveFn : function(x, y, width, height, diffX, diffY) {
  5119. width += diffX;
  5120. height += diffY;
  5121. self.resize(width, height);
  5122. }
  5123. });
  5124. } else {
  5125. statusbar.last().css('visibility', 'hidden');
  5126. }
  5127. }
  5128. return self;
  5129. },
  5130. remove : function() {
  5131. var self = this;
  5132. if (!self.isCreated) {
  5133. return self;
  5134. }
  5135. self.beforeRemove();
  5136. self.srcElement.data('kindeditor', '');
  5137. if (self.menu) {
  5138. self.hideMenu();
  5139. }
  5140. _each(self.dialogs, function() {
  5141. self.hideDialog();
  5142. });
  5143. K(document).unbind('mousedown', self._docMousedownFn);
  5144. self.toolbar.remove();
  5145. self.edit.remove();
  5146. self.statusbar.last().unbind();
  5147. self.statusbar.unbind();
  5148. self.container.remove();
  5149. self.container = self.toolbar = self.edit = self.menu = null;
  5150. self.dialogs = [];
  5151. self.isCreated = false;
  5152. return self;
  5153. },
  5154. resize : function(width, height, updateProp) {
  5155. var self = this;
  5156. updateProp = _undef(updateProp, true);
  5157. if (width) {
  5158. if (!/%/.test(width)) {
  5159. width = _removeUnit(width);
  5160. width = width < self.minWidth ? self.minWidth : width;
  5161. }
  5162. self.container.css('width', _addUnit(width));
  5163. if (updateProp) {
  5164. self.width = _addUnit(width);
  5165. }
  5166. }
  5167. if (height) {
  5168. height = _removeUnit(height);
  5169. editHeight = _removeUnit(height) - self.toolbar.div.height() - self.statusbar.height();
  5170. editHeight = editHeight < self.minHeight ? self.minHeight : editHeight;
  5171. self.edit.setHeight(editHeight);
  5172. if (updateProp) {
  5173. self.height = _addUnit(height);
  5174. }
  5175. }
  5176. return self;
  5177. },
  5178. select : function() {
  5179. this.isCreated && this.cmd.select();
  5180. return this;
  5181. },
  5182. html : function(val) {
  5183. var self = this;
  5184. if (val === undefined) {
  5185. return self.isCreated ? self.edit.html() : _elementVal(self.srcElement);
  5186. }
  5187. self.isCreated ? self.edit.html(val) : _elementVal(self.srcElement, val);
  5188. if (self.isCreated) {
  5189. self.cmd.selection();
  5190. }
  5191. return self;
  5192. },
  5193. fullHtml : function() {
  5194. return this.isCreated ? this.edit.html(undefined, true) : '';
  5195. },
  5196. text : function(val) {
  5197. var self = this;
  5198. if (val === undefined) {
  5199. return _trim(self.html().replace(/<(?!img|embed).*?>/ig, '').replace(/&nbsp;/ig, ' '));
  5200. } else {
  5201. return self.html(_escape(val));
  5202. }
  5203. },
  5204. isEmpty : function() {
  5205. return _trim(this.text().replace(/\r\n|\n|\r/, '')) === '';
  5206. },
  5207. isDirty : function() {
  5208. return _trim(this.initContent.replace(/\r\n|\n|\r|t/g, '')) !== _trim(this.html().replace(/\r\n|\n|\r|t/g, ''));
  5209. },
  5210. selectedHtml : function() {
  5211. var val = this.isCreated ? this.cmd.range.html() : '';
  5212. val = _removeBookmarkTag(_removeTempTag(val));
  5213. return val;
  5214. },
  5215. count : function(mode) {
  5216. var self = this;
  5217. mode = (mode || 'html').toLowerCase();
  5218. if (mode === 'html') {
  5219. return self.html().length;
  5220. }
  5221. if (mode === 'text') {
  5222. return self.text().replace(/<(?:img|embed).*?>/ig, 'K').replace(/\r\n|\n|\r/g, '').length;
  5223. }
  5224. return 0;
  5225. },
  5226. exec : function(key) {
  5227. key = key.toLowerCase();
  5228. var self = this, cmd = self.cmd,
  5229. changeFlag = _inArray(key, 'selectall,copy,paste,print'.split(',')) < 0;
  5230. if (changeFlag) {
  5231. self.addBookmark(false);
  5232. }
  5233. cmd[key].apply(cmd, _toArray(arguments, 1));
  5234. if (changeFlag) {
  5235. self.updateState();
  5236. self.addBookmark(false);
  5237. if (self.options.afterChange) {
  5238. self.options.afterChange.call(self);
  5239. }
  5240. }
  5241. return self;
  5242. },
  5243. insertHtml : function(val, quickMode) {
  5244. if (!this.isCreated) {
  5245. return this;
  5246. }
  5247. val = this.beforeSetHtml(val);
  5248. this.exec('inserthtml', val, quickMode);
  5249. return this;
  5250. },
  5251. appendHtml : function(val) {
  5252. this.html(this.html() + val);
  5253. if (this.isCreated) {
  5254. var cmd = this.cmd;
  5255. cmd.range.selectNodeContents(cmd.doc.body).collapse(false);
  5256. cmd.select();
  5257. }
  5258. return this;
  5259. },
  5260. sync : function() {
  5261. _elementVal(this.srcElement, this.html());
  5262. return this;
  5263. },
  5264. focus : function() {
  5265. this.isCreated ? this.edit.focus() : this.srcElement[0].focus();
  5266. return this;
  5267. },
  5268. blur : function() {
  5269. this.isCreated ? this.edit.blur() : this.srcElement[0].blur();
  5270. return this;
  5271. },
  5272. addBookmark : function(checkSize) {
  5273. checkSize = _undef(checkSize, true);
  5274. var self = this, edit = self.edit,
  5275. body = edit.doc.body,
  5276. html = _removeTempTag(body.innerHTML), bookmark;
  5277. if (checkSize && self._undoStack.length > 0) {
  5278. var prev = self._undoStack[self._undoStack.length - 1];
  5279. if (Math.abs(html.length - _removeBookmarkTag(prev.html).length) < self.minChangeSize) {
  5280. return self;
  5281. }
  5282. }
  5283. if (edit.designMode && !self._firstAddBookmark) {
  5284. var range = self.cmd.range;
  5285. bookmark = range.createBookmark(true);
  5286. bookmark.html = _removeTempTag(body.innerHTML);
  5287. range.moveToBookmark(bookmark);
  5288. } else {
  5289. bookmark = {
  5290. html : html
  5291. };
  5292. }
  5293. self._firstAddBookmark = false;
  5294. _addBookmarkToStack(self._undoStack, bookmark);
  5295. return self;
  5296. },
  5297. undo : function() {
  5298. return _undoToRedo.call(this, this._undoStack, this._redoStack);
  5299. },
  5300. redo : function() {
  5301. return _undoToRedo.call(this, this._redoStack, this._undoStack);
  5302. },
  5303. fullscreen : function(bool) {
  5304. this.fullscreenMode = (bool === undefined ? !this.fullscreenMode : bool);
  5305. this.addBookmark(false);
  5306. return this.remove().create();
  5307. },
  5308. readonly : function(isReadonly) {
  5309. isReadonly = _undef(isReadonly, true);
  5310. var self = this, edit = self.edit, doc = edit.doc;
  5311. if (self.designMode) {
  5312. self.toolbar.disableAll(isReadonly, []);
  5313. } else {
  5314. _each(self.noDisableItems, function() {
  5315. self.toolbar[isReadonly ? 'disable' : 'enable'](this);
  5316. });
  5317. }
  5318. if (_IE) {
  5319. doc.body.contentEditable = !isReadonly;
  5320. } else {
  5321. doc.designMode = isReadonly ? 'off' : 'on';
  5322. }
  5323. edit.textarea[0].disabled = isReadonly;
  5324. },
  5325. createMenu : function(options) {
  5326. var self = this,
  5327. name = options.name,
  5328. knode = self.toolbar.get(name),
  5329. pos = knode.pos();
  5330. options.x = pos.x;
  5331. options.y = pos.y + knode.height();
  5332. options.z = self.options.zIndex;
  5333. options.shadowMode = _undef(options.shadowMode, self.shadowMode);
  5334. if (options.selectedColor !== undefined) {
  5335. options.cls = 'ke-colorpicker-' + self.themeType;
  5336. options.noColor = self.lang('noColor');
  5337. self.menu = _colorpicker(options);
  5338. } else {
  5339. options.cls = 'ke-menu-' + self.themeType;
  5340. options.centerLineMode = false;
  5341. self.menu = _menu(options);
  5342. }
  5343. return self.menu;
  5344. },
  5345. hideMenu : function() {
  5346. this.menu.remove();
  5347. this.menu = null;
  5348. return this;
  5349. },
  5350. hideContextmenu : function() {
  5351. this.contextmenu.remove();
  5352. this.contextmenu = null;
  5353. return this;
  5354. },
  5355. createDialog : function(options) {
  5356. var self = this, name = options.name;
  5357. options.z = self.options.zIndex;
  5358. options.shadowMode = _undef(options.shadowMode, self.shadowMode);
  5359. options.closeBtn = _undef(options.closeBtn, {
  5360. name : self.lang('close'),
  5361. click : function(e) {
  5362. self.hideDialog();
  5363. if (_IE && self.cmd) {
  5364. self.cmd.select();
  5365. }
  5366. }
  5367. });
  5368. options.noBtn = _undef(options.noBtn, {
  5369. name : self.lang(options.yesBtn ? 'no' : 'close'),
  5370. click : function(e) {
  5371. self.hideDialog();
  5372. if (_IE && self.cmd) {
  5373. self.cmd.select();
  5374. }
  5375. }
  5376. });
  5377. if (self.dialogAlignType != 'page') {
  5378. options.alignEl = self.container;
  5379. }
  5380. options.cls = 'ke-dialog-' + self.themeType;
  5381. if (self.dialogs.length > 0) {
  5382. var firstDialog = self.dialogs[0],
  5383. parentDialog = self.dialogs[self.dialogs.length - 1];
  5384. firstDialog.setMaskIndex(parentDialog.z + 2);
  5385. options.z = parentDialog.z + 3;
  5386. options.showMask = false;
  5387. }
  5388. var dialog = _dialog(options);
  5389. self.dialogs.push(dialog);
  5390. return dialog;
  5391. },
  5392. hideDialog : function() {
  5393. var self = this;
  5394. if (self.dialogs.length > 0) {
  5395. self.dialogs.pop().remove();
  5396. }
  5397. if (self.dialogs.length > 0) {
  5398. var firstDialog = self.dialogs[0],
  5399. parentDialog = self.dialogs[self.dialogs.length - 1];
  5400. firstDialog.setMaskIndex(parentDialog.z - 1);
  5401. }
  5402. return self;
  5403. },
  5404. errorDialog : function(html) {
  5405. var self = this;
  5406. var dialog = self.createDialog({
  5407. width : 750,
  5408. title : self.lang('uploadError'),
  5409. body : '<div style="padding:10px 20px;"><iframe frameborder="0" style="width:708px;height:400px;"></iframe></div>'
  5410. });
  5411. var iframe = K('iframe', dialog.div), doc = K.iframeDoc(iframe);
  5412. doc.open();
  5413. doc.write(html);
  5414. doc.close();
  5415. K(doc.body).css('background-color', '#FFF');
  5416. iframe[0].contentWindow.focus();
  5417. return self;
  5418. }
  5419. };
  5420. function _editor(options) {
  5421. return new KEditor(options);
  5422. }
  5423. _instances = [];
  5424. function _create(expr, options) {
  5425. options = options || {};
  5426. options.basePath = _undef(options.basePath, K.basePath);
  5427. options.themesPath = _undef(options.themesPath, options.basePath + 'themes/');
  5428. options.langPath = _undef(options.langPath, options.basePath + 'lang/');
  5429. options.pluginsPath = _undef(options.pluginsPath, options.basePath + 'plugins/');
  5430. if (_undef(options.loadStyleMode, K.options.loadStyleMode)) {
  5431. var themeType = _undef(options.themeType, K.options.themeType);
  5432. _loadStyle(options.themesPath + 'default/default.css');
  5433. _loadStyle(options.themesPath + themeType + '/' + themeType + '.css');
  5434. }
  5435. function create(editor) {
  5436. _each(_plugins, function(name, fn) {
  5437. if (_isFunction(fn)) {
  5438. fn.call(editor, KindEditor);
  5439. if (!editor._pluginStatus) {
  5440. editor._pluginStatus = {};
  5441. }
  5442. editor._pluginStatus[name] = 'inited';
  5443. }
  5444. });
  5445. return editor.create();
  5446. }
  5447. var knode = K(expr);
  5448. if (!knode || knode.length === 0) {
  5449. return;
  5450. }
  5451. if (knode.length > 1) {
  5452. knode.each(function() {
  5453. _create(this, options);
  5454. });
  5455. return _instances[0];
  5456. }
  5457. options.srcElement = knode[0];
  5458. var editor = new KEditor(options);
  5459. _instances.push(editor);
  5460. if (_language[editor.langType]) {
  5461. return create(editor);
  5462. }
  5463. _loadScript(editor.langPath + editor.langType + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
  5464. create(editor);
  5465. });
  5466. return editor;
  5467. }
  5468. function _eachEditor(expr, fn) {
  5469. K(expr).each(function(i, el) {
  5470. K.each(_instances, function(j, editor) {
  5471. if (editor && editor.srcElement[0] == el) {
  5472. fn.call(editor, j);
  5473. return false;
  5474. }
  5475. });
  5476. });
  5477. }
  5478. K.remove = function(expr) {
  5479. _eachEditor(expr, function(i) {
  5480. this.remove();
  5481. _instances.splice(i, 1);
  5482. });
  5483. };
  5484. K.sync = function(expr) {
  5485. _eachEditor(expr, function() {
  5486. this.sync();
  5487. });
  5488. };
  5489. K.html = function(expr, val) {
  5490. _eachEditor(expr, function() {
  5491. this.html(val);
  5492. });
  5493. };
  5494. K.insertHtml = function(expr, val) {
  5495. _eachEditor(expr, function() {
  5496. this.insertHtml(val);
  5497. });
  5498. };
  5499. K.appendHtml = function(expr, val) {
  5500. _eachEditor(expr, function() {
  5501. this.appendHtml(val);
  5502. });
  5503. };
  5504. if (_IE && _V < 7) {
  5505. _nativeCommand(document, 'BackgroundImageCache', true);
  5506. }
  5507. K.EditorClass = KEditor;
  5508. K.editor = _editor;
  5509. K.create = _create;
  5510. K.instances = _instances;
  5511. K.plugin = _plugin;
  5512. K.lang = _lang;
  5513. _plugin('core', function(K) {
  5514. var self = this,
  5515. shortcutKeys = {
  5516. undo : 'Z', redo : 'Y', bold : 'B', italic : 'I', underline : 'U', print : 'P', selectall : 'A'
  5517. };
  5518. self.afterSetHtml(function() {
  5519. if (self.options.afterChange) {
  5520. self.options.afterChange.call(self);
  5521. }
  5522. });
  5523. self.afterCreate(function() {
  5524. if (self.syncType != 'form') {
  5525. return;
  5526. }
  5527. var el = K(self.srcElement), hasForm = false;
  5528. while ((el = el.parent())) {
  5529. if (el.name == 'form') {
  5530. hasForm = true;
  5531. break;
  5532. }
  5533. }
  5534. if (hasForm) {
  5535. el.bind('submit', function(e) {
  5536. self.sync();
  5537. K(window).bind('unload', function() {
  5538. self.edit.textarea.remove();
  5539. });
  5540. });
  5541. var resetBtn = K('[type="reset"]', el);
  5542. resetBtn.click(function() {
  5543. self.html(self.initContent);
  5544. self.cmd.selection();
  5545. });
  5546. self.beforeRemove(function() {
  5547. el.unbind();
  5548. resetBtn.unbind();
  5549. });
  5550. }
  5551. });
  5552. self.clickToolbar('source', function() {
  5553. if (self.edit.designMode) {
  5554. self.toolbar.disableAll(true);
  5555. self.edit.design(false);
  5556. self.toolbar.select('source');
  5557. } else {
  5558. self.toolbar.disableAll(false);
  5559. self.edit.design(true);
  5560. self.toolbar.unselect('source');
  5561. if (_GECKO) {
  5562. setTimeout(function() {
  5563. self.cmd.selection();
  5564. }, 0);
  5565. } else {
  5566. self.cmd.selection();
  5567. }
  5568. }
  5569. self.designMode = self.edit.designMode;
  5570. });
  5571. self.afterCreate(function() {
  5572. if (!self.designMode) {
  5573. self.toolbar.disableAll(true).select('source');
  5574. }
  5575. });
  5576. self.clickToolbar('fullscreen', function() {
  5577. self.fullscreen();
  5578. });
  5579. if (self.fullscreenShortcut) {
  5580. var loaded = false;
  5581. self.afterCreate(function() {
  5582. K(self.edit.doc, self.edit.textarea).keyup(function(e) {
  5583. if (e.which == 27) {
  5584. setTimeout(function() {
  5585. self.fullscreen();
  5586. }, 0);
  5587. }
  5588. });
  5589. if (loaded) {
  5590. if (_IE && !self.designMode) {
  5591. return;
  5592. }
  5593. self.focus();
  5594. }
  5595. if (!loaded) {
  5596. loaded = true;
  5597. }
  5598. });
  5599. }
  5600. _each('undo,redo'.split(','), function(i, name) {
  5601. if (shortcutKeys[name]) {
  5602. self.afterCreate(function() {
  5603. _ctrl(this.edit.doc, shortcutKeys[name], function() {
  5604. self.clickToolbar(name);
  5605. });
  5606. });
  5607. }
  5608. self.clickToolbar(name, function() {
  5609. self[name]();
  5610. });
  5611. });
  5612. self.clickToolbar('formatblock', function() {
  5613. var blocks = self.lang('formatblock.formatBlock'),
  5614. heights = {
  5615. h1 : 28,
  5616. h2 : 24,
  5617. h3 : 18,
  5618. H4 : 14,
  5619. p : 12
  5620. },
  5621. curVal = self.cmd.val('formatblock'),
  5622. menu = self.createMenu({
  5623. name : 'formatblock',
  5624. width : self.langType == 'en' ? 200 : 150
  5625. });
  5626. _each(blocks, function(key, val) {
  5627. var style = 'font-size:' + heights[key] + 'px;';
  5628. if (key.charAt(0) === 'h') {
  5629. style += 'font-weight:bold;';
  5630. }
  5631. menu.addItem({
  5632. title : '<span style="' + style + '" unselectable="on">' + val + '</span>',
  5633. height : heights[key] + 12,
  5634. checked : (curVal === key || curVal === val),
  5635. click : function() {
  5636. self.select().exec('formatblock', '<' + key + '>').hideMenu();
  5637. }
  5638. });
  5639. });
  5640. });
  5641. self.clickToolbar('fontname', function() {
  5642. var curVal = self.cmd.val('fontname'),
  5643. menu = self.createMenu({
  5644. name : 'fontname',
  5645. width : 150
  5646. });
  5647. _each(self.lang('fontname.fontName'), function(key, val) {
  5648. menu.addItem({
  5649. title : '<span style="font-family: ' + key + ';" unselectable="on">' + val + '</span>',
  5650. checked : (curVal === key.toLowerCase() || curVal === val.toLowerCase()),
  5651. click : function() {
  5652. self.exec('fontname', key).hideMenu();
  5653. }
  5654. });
  5655. });
  5656. });
  5657. self.clickToolbar('fontsize', function() {
  5658. var curVal = self.cmd.val('fontsize'),
  5659. menu = self.createMenu({
  5660. name : 'fontsize',
  5661. width : 150
  5662. });
  5663. _each(self.fontSizeTable, function(i, val) {
  5664. menu.addItem({
  5665. title : '<span style="font-size:' + val + ';" unselectable="on">' + val + '</span>',
  5666. height : _removeUnit(val) + 12,
  5667. checked : curVal === val,
  5668. click : function() {
  5669. self.exec('fontsize', val).hideMenu();
  5670. }
  5671. });
  5672. });
  5673. });
  5674. _each('forecolor,hilitecolor'.split(','), function(i, name) {
  5675. self.clickToolbar(name, function() {
  5676. self.createMenu({
  5677. name : name,
  5678. selectedColor : self.cmd.val(name) || 'default',
  5679. colors : self.colorTable,
  5680. click : function(color) {
  5681. self.exec(name, color).hideMenu();
  5682. }
  5683. });
  5684. });
  5685. });
  5686. _each(('cut,copy,paste').split(','), function(i, name) {
  5687. self.clickToolbar(name, function() {
  5688. self.focus();
  5689. try {
  5690. self.exec(name, null);
  5691. } catch(e) {
  5692. alert(self.lang(name + 'Error'));
  5693. }
  5694. });
  5695. });
  5696. self.clickToolbar('about', function() {
  5697. var html = '<div style="margin:20px;">' +
  5698. '<div>KindEditor ' + _VERSION + '</div>' +
  5699. '<div>Copyright &copy; <a href="http://www.kindsoft.net/" target="_blank">kindsoft.net</a> All rights reserved.</div>' +
  5700. '</div>';
  5701. self.createDialog({
  5702. name : 'about',
  5703. width : 350,
  5704. title : self.lang('about'),
  5705. body : html
  5706. });
  5707. });
  5708. self.plugin.getSelectedLink = function() {
  5709. return self.cmd.commonAncestor('a');
  5710. };
  5711. self.plugin.getSelectedImage = function() {
  5712. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5713. return !/^ke-\w+$/i.test(img[0].className);
  5714. });
  5715. };
  5716. self.plugin.getSelectedFlash = function() {
  5717. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5718. return img[0].className == 'ke-flash';
  5719. });
  5720. };
  5721. self.plugin.getSelectedMedia = function() {
  5722. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5723. return img[0].className == 'ke-media' || img[0].className == 'ke-rm';
  5724. });
  5725. };
  5726. self.plugin.getSelectedAnchor = function() {
  5727. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5728. return img[0].className == 'ke-anchor';
  5729. });
  5730. };
  5731. _each('link,image,flash,media,anchor'.split(','), function(i, name) {
  5732. var uName = name.charAt(0).toUpperCase() + name.substr(1);
  5733. _each('edit,delete'.split(','), function(j, val) {
  5734. self.addContextmenu({
  5735. title : self.lang(val + uName),
  5736. click : function() {
  5737. self.loadPlugin(name, function() {
  5738. self.plugin[name][val]();
  5739. self.hideMenu();
  5740. });
  5741. },
  5742. cond : self.plugin['getSelected' + uName],
  5743. width : 150,
  5744. iconClass : val == 'edit' ? 'ke-icon-' + name : undefined
  5745. });
  5746. });
  5747. self.addContextmenu({ title : '-' });
  5748. });
  5749. self.plugin.getSelectedTable = function() {
  5750. return self.cmd.commonAncestor('table');
  5751. };
  5752. self.plugin.getSelectedRow = function() {
  5753. return self.cmd.commonAncestor('tr');
  5754. };
  5755. self.plugin.getSelectedCell = function() {
  5756. return self.cmd.commonAncestor('td');
  5757. };
  5758. _each(('prop,cellprop,colinsertleft,colinsertright,rowinsertabove,rowinsertbelow,rowmerge,colmerge,' +
  5759. 'rowsplit,colsplit,coldelete,rowdelete,insert,delete').split(','), function(i, val) {
  5760. var cond = _inArray(val, ['prop', 'delete']) < 0 ? self.plugin.getSelectedCell : self.plugin.getSelectedTable;
  5761. self.addContextmenu({
  5762. title : self.lang('table' + val),
  5763. click : function() {
  5764. self.loadPlugin('table', function() {
  5765. self.plugin.table[val]();
  5766. self.hideMenu();
  5767. });
  5768. },
  5769. cond : cond,
  5770. width : 170,
  5771. iconClass : 'ke-icon-table' + val
  5772. });
  5773. });
  5774. self.addContextmenu({ title : '-' });
  5775. _each(('selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
  5776. 'insertunorderedlist,indent,outdent,subscript,superscript,hr,print,' +
  5777. 'bold,italic,underline,strikethrough,removeformat,unlink').split(','), function(i, name) {
  5778. if (shortcutKeys[name]) {
  5779. self.afterCreate(function() {
  5780. _ctrl(this.edit.doc, shortcutKeys[name], function() {
  5781. self.cmd.selection();
  5782. self.clickToolbar(name);
  5783. });
  5784. });
  5785. }
  5786. self.clickToolbar(name, function() {
  5787. self.focus().exec(name, null);
  5788. });
  5789. });
  5790. self.afterCreate(function() {
  5791. var doc = self.edit.doc, cmd, bookmark, div,
  5792. cls = '__kindeditor_paste__', pasting = false;
  5793. function movePastedData() {
  5794. cmd.range.moveToBookmark(bookmark);
  5795. cmd.select();
  5796. if (_WEBKIT) {
  5797. K('div.' + cls, div).each(function() {
  5798. K(this).after('<br />').remove(true);
  5799. });
  5800. K('span.Apple-style-span', div).remove(true);
  5801. K('span.Apple-tab-span', div).remove(true);
  5802. K('span[style]', div).each(function() {
  5803. if (K(this).css('white-space') == 'nowrap') {
  5804. K(this).remove(true);
  5805. }
  5806. });
  5807. K('meta', div).remove();
  5808. }
  5809. var html = div[0].innerHTML;
  5810. div.remove();
  5811. if (html === '') {
  5812. return;
  5813. }
  5814. if (_WEBKIT) {
  5815. html = html.replace(/(<br>)\1/ig, '$1');
  5816. }
  5817. if (self.pasteType === 2) {
  5818. html = html.replace(/(<(?:p|p\s[^>]*)>) *(<\/p>)/ig, '');
  5819. if (/schemas-microsoft-com|worddocument|mso-\w+/i.test(html)) {
  5820. html = _clearMsWord(html, self.filterMode ? self.htmlTags : K.options.htmlTags);
  5821. } else {
  5822. html = _formatHtml(html, self.filterMode ? self.htmlTags : null);
  5823. html = self.beforeSetHtml(html);
  5824. }
  5825. }
  5826. if (self.pasteType === 1) {
  5827. html = html.replace(/&nbsp;/ig, ' ');
  5828. html = html.replace(/\n\s*\n/g, '\n');
  5829. html = html.replace(/<br[^>]*>/ig, '\n');
  5830. html = html.replace(/<\/p><p[^>]*>/ig, '\n');
  5831. html = html.replace(/<[^>]+>/g, '');
  5832. html = html.replace(/ {2}/g, ' &nbsp;');
  5833. if (self.newlineTag == 'p') {
  5834. if (/\n/.test(html)) {
  5835. html = html.replace(/^/, '<p>').replace(/$/, '<br /></p>').replace(/\n/g, '<br /></p><p>');
  5836. }
  5837. } else {
  5838. html = html.replace(/\n/g, '<br />$&');
  5839. }
  5840. }
  5841. self.insertHtml(html, true);
  5842. }
  5843. K(doc.body).bind('paste', function(e){
  5844. if (self.pasteType === 0) {
  5845. e.stop();
  5846. return;
  5847. }
  5848. if (pasting) {
  5849. return;
  5850. }
  5851. pasting = true;
  5852. K('div.' + cls, doc).remove();
  5853. cmd = self.cmd.selection();
  5854. bookmark = cmd.range.createBookmark();
  5855. div = K('<div class="' + cls + '"></div>', doc).css({
  5856. position : 'absolute',
  5857. width : '1px',
  5858. height : '1px',
  5859. overflow : 'hidden',
  5860. left : '-1981px',
  5861. top : K(bookmark.start).pos().y + 'px',
  5862. 'white-space' : 'nowrap'
  5863. });
  5864. K(doc.body).append(div);
  5865. if (_IE) {
  5866. var rng = cmd.range.get(true);
  5867. rng.moveToElementText(div[0]);
  5868. rng.select();
  5869. rng.execCommand('paste');
  5870. e.preventDefault();
  5871. } else {
  5872. cmd.range.selectNodeContents(div[0]);
  5873. cmd.select();
  5874. div[0].tabIndex = -1;
  5875. div[0].focus();
  5876. }
  5877. setTimeout(function() {
  5878. movePastedData();
  5879. pasting = false;
  5880. }, 0);
  5881. });
  5882. });
  5883. self.beforeGetHtml(function(html) {
  5884. if (_IE && _V <= 8) {
  5885. html = html.replace(/<div\s+[^>]*data-ke-input-tag="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, tag) {
  5886. return unescape(tag);
  5887. });
  5888. html = html.replace(/(<input)((?:\s+[^>]*)?>)/ig, function($0, $1, $2) {
  5889. if (!/\s+type="[^"]+"/i.test($0)) {
  5890. return $1 + ' type="text"' + $2;
  5891. }
  5892. return $0;
  5893. });
  5894. }
  5895. return html.replace(/(<(?:noscript|noscript\s[^>]*)>)([\s\S]*?)(<\/noscript>)/ig, function($0, $1, $2, $3) {
  5896. return $1 + _unescape($2).replace(/\s+/g, ' ') + $3;
  5897. })
  5898. .replace(/<img[^>]*class="?ke-(flash|rm|media)"?[^>]*>/ig, function(full) {
  5899. var imgAttrs = _getAttrList(full);
  5900. var styles = _getCssList(imgAttrs.style || '');
  5901. var attrs = _mediaAttrs(imgAttrs['data-ke-tag']);
  5902. var width = _undef(styles.width, '');
  5903. var height = _undef(styles.height, '');
  5904. if (/px/i.test(width)) {
  5905. width = _removeUnit(width);
  5906. }
  5907. if (/px/i.test(height)) {
  5908. height = _removeUnit(height);
  5909. }
  5910. attrs.width = _undef(imgAttrs.width, width);
  5911. attrs.height = _undef(imgAttrs.height, height);
  5912. return _mediaEmbed(attrs);
  5913. })
  5914. .replace(/<img[^>]*class="?ke-anchor"?[^>]*>/ig, function(full) {
  5915. var imgAttrs = _getAttrList(full);
  5916. return '<a name="' + unescape(imgAttrs['data-ke-name']) + '"></a>';
  5917. })
  5918. .replace(/<div\s+[^>]*data-ke-script-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, attr, code) {
  5919. return '<script' + unescape(attr) + '>' + unescape(code) + '</script>';
  5920. })
  5921. .replace(/<div\s+[^>]*data-ke-noscript-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, attr, code) {
  5922. return '<noscript' + unescape(attr) + '>' + unescape(code) + '</noscript>';
  5923. })
  5924. .replace(/(<[^>]*)data-ke-src="([^"]*)"([^>]*>)/ig, function(full, start, src, end) {
  5925. full = full.replace(/(\s+(?:href|src)=")[^"]*(")/i, function($0, $1, $2) {
  5926. return $1 + _unescape(src) + $2;
  5927. });
  5928. full = full.replace(/\s+data-ke-src="[^"]*"/i, '');
  5929. return full;
  5930. })
  5931. .replace(/(<[^>]+\s)data-ke-(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
  5932. return start + end;
  5933. });
  5934. });
  5935. self.beforeSetHtml(function(html) {
  5936. if (_IE && _V <= 8) {
  5937. html = html.replace(/<input[^>]*>|<(select|button)[^>]*>[\s\S]*?<\/\1>/ig, function(full) {
  5938. var attrs = _getAttrList(full);
  5939. var styles = _getCssList(attrs.style || '');
  5940. if (styles.display == 'none') {
  5941. return '<div class="ke-display-none" data-ke-input-tag="' + escape(full) + '"></div>';
  5942. }
  5943. return full;
  5944. });
  5945. }
  5946. return html.replace(/<embed[^>]*type="([^"]+)"[^>]*>(?:<\/embed>)?/ig, function(full) {
  5947. var attrs = _getAttrList(full);
  5948. attrs.src = _undef(attrs.src, '');
  5949. attrs.width = _undef(attrs.width, 0);
  5950. attrs.height = _undef(attrs.height, 0);
  5951. return _mediaImg(self.themesPath + 'common/blank.gif', attrs);
  5952. })
  5953. .replace(/<a[^>]*name="([^"]+)"[^>]*>(?:<\/a>)?/ig, function(full) {
  5954. var attrs = _getAttrList(full);
  5955. if (attrs.href !== undefined) {
  5956. return full;
  5957. }
  5958. return '<img class="ke-anchor" src="' + self.themesPath + 'common/anchor.gif" data-ke-name="' + escape(attrs.name) + '" />';
  5959. })
  5960. .replace(/<script([^>]*)>([\s\S]*?)<\/script>/ig, function(full, attr, code) {
  5961. return '<div class="ke-script" data-ke-script-attr="' + escape(attr) + '">' + escape(code) + '</div>';
  5962. })
  5963. .replace(/<noscript([^>]*)>([\s\S]*?)<\/noscript>/ig, function(full, attr, code) {
  5964. return '<div class="ke-noscript" data-ke-noscript-attr="' + escape(attr) + '">' + escape(code) + '</div>';
  5965. })
  5966. .replace(/(<[^>]*)(href|src)="([^"]*)"([^>]*>)/ig, function(full, start, key, src, end) {
  5967. if (full.match(/\sdata-ke-src="[^"]*"/i)) {
  5968. return full;
  5969. }
  5970. full = start + key + '="' + src + '"' + ' data-ke-src="' + _escape(src) + '"' + end;
  5971. return full;
  5972. })
  5973. .replace(/(<[^>]+\s)(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
  5974. return start + 'data-ke-' + end;
  5975. })
  5976. .replace(/<table[^>]*\s+border="0"[^>]*>/ig, function(full) {
  5977. if (full.indexOf('ke-zeroborder') >= 0) {
  5978. return full;
  5979. }
  5980. return _addClassToTag(full, 'ke-zeroborder');
  5981. });
  5982. });
  5983. });
  5984. })(window);
  5985. /*******************************************************************************
  5986. * KindEditor - WYSIWYG HTML Editor for Internet
  5987. * Copyright (C) 2006-2011 kindsoft.net
  5988. *
  5989. * @author Roddy <luolonghao@gmail.com>
  5990. * @site http://www.kindsoft.net/
  5991. * @licence http://www.kindsoft.net/license.php
  5992. *******************************************************************************/
  5993. KindEditor.lang({
  5994. source : 'HTML代码',
  5995. preview : '预览',
  5996. undo : '后退(Ctrl+Z)',
  5997. redo : '前进(Ctrl+Y)',
  5998. cut : '剪切(Ctrl+X)',
  5999. copy : '复制(Ctrl+C)',
  6000. paste : '粘贴(Ctrl+V)',
  6001. plainpaste : '粘贴为无格式文本',
  6002. wordpaste : '从Word粘贴',
  6003. selectall : '全选(Ctrl+A)',
  6004. justifyleft : '左对齐',
  6005. justifycenter : '居中',
  6006. justifyright : '右对齐',
  6007. justifyfull : '两端对齐',
  6008. insertorderedlist : '编号',
  6009. insertunorderedlist : '项目符号',
  6010. indent : '增加缩进',
  6011. outdent : '减少缩进',
  6012. subscript : '下标',
  6013. superscript : '上标',
  6014. formatblock : '段落',
  6015. fontname : '字体',
  6016. fontsize : '文字大小',
  6017. forecolor : '文字颜色',
  6018. hilitecolor : '文字背景',
  6019. bold : '粗体(Ctrl+B)',
  6020. italic : '斜体(Ctrl+I)',
  6021. underline : '下划线(Ctrl+U)',
  6022. strikethrough : '删除线',
  6023. removeformat : '删除格式',
  6024. image : '图片',
  6025. multiimage : '批量图片上传',
  6026. flash : 'Flash',
  6027. media : '视音频',
  6028. table : '表格',
  6029. tablecell : '单元格',
  6030. hr : '插入横线',
  6031. emoticons : '插入表情',
  6032. link : '超级链接',
  6033. unlink : '取消超级链接',
  6034. fullscreen : '全屏显示',
  6035. about : '关于',
  6036. print : '打印(Ctrl+P)',
  6037. filemanager : '文件空间',
  6038. code : '插入程序代码',
  6039. map : 'Google地图',
  6040. baidumap : '百度地图',
  6041. lineheight : '行距',
  6042. clearhtml : '清理HTML代码',
  6043. pagebreak : '插入分页符',
  6044. quickformat : '一键排版',
  6045. insertfile : '插入文件',
  6046. template : '插入模板',
  6047. anchor : '锚点',
  6048. yes : '确定',
  6049. no : '取消',
  6050. close : '关闭',
  6051. editImage : '图片属性',
  6052. deleteImage : '删除图片',
  6053. editFlash : 'Flash属性',
  6054. deleteFlash : '删除Flash',
  6055. editMedia : '视音频属性',
  6056. deleteMedia : '删除视音频',
  6057. editLink : '超级链接属性',
  6058. deleteLink : '取消超级链接',
  6059. editAnchor : '锚点属性',
  6060. deleteAnchor : '删除锚点',
  6061. tableprop : '表格属性',
  6062. tablecellprop : '单元格属性',
  6063. tableinsert : '插入表格',
  6064. tabledelete : '删除表格',
  6065. tablecolinsertleft : '左侧插入列',
  6066. tablecolinsertright : '右侧插入列',
  6067. tablerowinsertabove : '上方插入行',
  6068. tablerowinsertbelow : '下方插入行',
  6069. tablerowmerge : '向下合并单元格',
  6070. tablecolmerge : '向右合并单元格',
  6071. tablerowsplit : '拆分行',
  6072. tablecolsplit : '拆分列',
  6073. tablecoldelete : '删除列',
  6074. tablerowdelete : '删除行',
  6075. noColor : '无颜色',
  6076. pleaseSelectFile : '请选择文件。',
  6077. invalidImg : "请输入有效的URL地址。\n只允许jpg,gif,bmp,png格式。",
  6078. invalidMedia : "请输入有效的URL地址。\n只允许swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb格式。",
  6079. invalidWidth : "宽度必须为数字。",
  6080. invalidHeight : "高度必须为数字。",
  6081. invalidBorder : "边框必须为数字。",
  6082. invalidUrl : "请输入有效的URL地址。",
  6083. invalidRows : '行数为必选项,只允许输入大于0的数字。',
  6084. invalidCols : '列数为必选项,只允许输入大于0的数字。',
  6085. invalidPadding : '边距必须为数字。',
  6086. invalidSpacing : '间距必须为数字。',
  6087. invalidJson : '服务器发生故障。',
  6088. uploadSuccess : '上传成功。',
  6089. cutError : '您的浏览器安全设置不允许使用剪切操作,请使用快捷键(Ctrl+X)来完成。',
  6090. copyError : '您的浏览器安全设置不允许使用复制操作,请使用快捷键(Ctrl+C)来完成。',
  6091. pasteError : '您的浏览器安全设置不允许使用粘贴操作,请使用快捷键(Ctrl+V)来完成。',
  6092. ajaxLoading : '加载中,请稍候 ...',
  6093. uploadLoading : '上传中,请稍候 ...',
  6094. uploadError : '上传错误',
  6095. 'plainpaste.comment' : '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。',
  6096. 'wordpaste.comment' : '请使用快捷键(Ctrl+V)把内容粘贴到下面的方框里。',
  6097. 'code.pleaseInput' : '请输入程序代码。',
  6098. 'link.url' : 'URL',
  6099. 'link.linkType' : '打开类型',
  6100. 'link.newWindow' : '新窗口',
  6101. 'link.selfWindow' : '当前窗口',
  6102. 'flash.url' : 'URL',
  6103. 'flash.width' : '宽度',
  6104. 'flash.height' : '高度',
  6105. 'flash.upload' : '上传',
  6106. 'flash.viewServer' : '文件空间',
  6107. 'media.url' : 'URL',
  6108. 'media.width' : '宽度',
  6109. 'media.height' : '高度',
  6110. 'media.autostart' : '自动播放',
  6111. 'media.upload' : '上传',
  6112. 'media.viewServer' : '文件空间',
  6113. 'image.remoteImage' : '网络图片',
  6114. 'image.localImage' : '本地上传',
  6115. 'image.remoteUrl' : '图片地址',
  6116. 'image.localUrl' : '上传文件',
  6117. 'image.size' : '图片大小',
  6118. 'image.width' : '宽',
  6119. 'image.height' : '高',
  6120. 'image.resetSize' : '重置大小',
  6121. 'image.align' : '对齐方式',
  6122. 'image.defaultAlign' : '默认方式',
  6123. 'image.leftAlign' : '左对齐',
  6124. 'image.rightAlign' : '右对齐',
  6125. 'image.imgTitle' : '图片说明',
  6126. 'image.upload' : '浏览...',
  6127. 'image.viewServer' : '图片空间',
  6128. 'multiimage.uploadDesc' : '允许用户同时上传<%=uploadLimit%>张图片,单张图片容量不超过<%=sizeLimit%>',
  6129. 'multiimage.startUpload' : '开始上传',
  6130. 'multiimage.clearAll' : '全部清空',
  6131. 'multiimage.insertAll' : '全部插入',
  6132. 'multiimage.queueLimitExceeded' : '文件数量超过限制。',
  6133. 'multiimage.fileExceedsSizeLimit' : '文件大小超过限制。',
  6134. 'multiimage.zeroByteFile' : '无法上传空文件。',
  6135. 'multiimage.invalidFiletype' : '文件类型不正确。',
  6136. 'multiimage.unknownError' : '发生异常,无法上传。',
  6137. 'multiimage.pending' : '等待上传',
  6138. 'multiimage.uploadError' : '上传失败',
  6139. 'filemanager.emptyFolder' : '空文件夹',
  6140. 'filemanager.moveup' : '移到上一级文件夹',
  6141. 'filemanager.viewType' : '显示方式:',
  6142. 'filemanager.viewImage' : '缩略图',
  6143. 'filemanager.listImage' : '详细信息',
  6144. 'filemanager.orderType' : '排序方式:',
  6145. 'filemanager.fileName' : '名称',
  6146. 'filemanager.fileSize' : '大小',
  6147. 'filemanager.fileType' : '类型',
  6148. 'insertfile.url' : 'URL',
  6149. 'insertfile.title' : '文件说明',
  6150. 'insertfile.upload' : '上传',
  6151. 'insertfile.viewServer' : '文件空间',
  6152. 'table.cells' : '单元格数',
  6153. 'table.rows' : '行数',
  6154. 'table.cols' : '列数',
  6155. 'table.size' : '大小',
  6156. 'table.width' : '宽度',
  6157. 'table.height' : '高度',
  6158. 'table.percent' : '%',
  6159. 'table.px' : 'px',
  6160. 'table.space' : '边距间距',
  6161. 'table.padding' : '边距',
  6162. 'table.spacing' : '间距',
  6163. 'table.align' : '对齐方式',
  6164. 'table.textAlign' : '水平对齐',
  6165. 'table.verticalAlign' : '垂直对齐',
  6166. 'table.alignDefault' : '默认',
  6167. 'table.alignLeft' : '左对齐',
  6168. 'table.alignCenter' : '居中',
  6169. 'table.alignRight' : '右对齐',
  6170. 'table.alignTop' : '顶部',
  6171. 'table.alignMiddle' : '中部',
  6172. 'table.alignBottom' : '底部',
  6173. 'table.alignBaseline' : '基线',
  6174. 'table.border' : '边框',
  6175. 'table.borderWidth' : '边框',
  6176. 'table.borderColor' : '颜色',
  6177. 'table.backgroundColor' : '背景颜色',
  6178. 'map.address' : '地址: ',
  6179. 'map.search' : '搜索',
  6180. 'baidumap.address' : '地址: ',
  6181. 'baidumap.search' : '搜索',
  6182. 'baidumap.insertDynamicMap' : '插入动态地图',
  6183. 'anchor.name' : '锚点名称',
  6184. 'formatblock.formatBlock' : {
  6185. h1 : '标题 1',
  6186. h2 : '标题 2',
  6187. h3 : '标题 3',
  6188. h4 : '标题 4',
  6189. p : '正 文'
  6190. },
  6191. 'fontname.fontName' : {
  6192. 'SimSun' : '宋体',
  6193. 'NSimSun' : '新宋体',
  6194. 'FangSong_GB2312' : '仿宋_GB2312',
  6195. 'KaiTi_GB2312' : '楷体_GB2312',
  6196. 'SimHei' : '黑体',
  6197. 'Microsoft YaHei' : '微软雅黑',
  6198. 'Arial' : 'Arial',
  6199. 'Arial Black' : 'Arial Black',
  6200. 'Times New Roman' : 'Times New Roman',
  6201. 'Courier New' : 'Courier New',
  6202. 'Tahoma' : 'Tahoma',
  6203. 'Verdana' : 'Verdana'
  6204. },
  6205. 'lineheight.lineHeight' : [
  6206. {'1' : '单倍行距'},
  6207. {'1.5' : '1.5倍行距'},
  6208. {'2' : '2倍行距'},
  6209. {'2.5' : '2.5倍行距'},
  6210. {'3' : '3倍行距'}
  6211. ],
  6212. 'template.selectTemplate' : '可选模板',
  6213. 'template.replaceContent' : '替换当前内容',
  6214. 'template.fileList' : {
  6215. '1.html' : '图片和文字',
  6216. '2.html' : '表格',
  6217. '3.html' : '项目编号'
  6218. }
  6219. }, 'zh-CN');
  6220. KindEditor.options.langType = 'zh-CN';
  6221. /*******************************************************************************
  6222. * KindEditor - WYSIWYG HTML Editor for Internet
  6223. * Copyright (C) 2006-2011 kindsoft.net
  6224. *
  6225. * @author Roddy <luolonghao@gmail.com>
  6226. * @site http://www.kindsoft.net/
  6227. * @licence http://www.kindsoft.net/license.php
  6228. *******************************************************************************/
  6229. KindEditor.plugin('anchor', function(K) {
  6230. var self = this, name = 'anchor', lang = self.lang(name + '.');
  6231. self.plugin.anchor = {
  6232. edit : function() {
  6233. var html = ['<div style="padding:20px;">',
  6234. '<div class="ke-dialog-row">',
  6235. '<label for="keName">' + lang.name + '</label>',
  6236. '<input class="ke-input-text" type="text" id="keName" name="name" value="" style="width:100px;" />',
  6237. '</div>',
  6238. '</div>'].join('');
  6239. var dialog = self.createDialog({
  6240. name : name,
  6241. width : 300,
  6242. title : self.lang(name),
  6243. body : html,
  6244. yesBtn : {
  6245. name : self.lang('yes'),
  6246. click : function(e) {
  6247. self.insertHtml('<a name="' + nameBox.val() + '">').hideDialog().focus();
  6248. }
  6249. }
  6250. });
  6251. var div = dialog.div,
  6252. nameBox = K('input[name="name"]', div);
  6253. var img = self.plugin.getSelectedAnchor();
  6254. if (img) {
  6255. nameBox.val(unescape(img.attr('data-ke-name')));
  6256. }
  6257. nameBox[0].focus();
  6258. nameBox[0].select();
  6259. },
  6260. 'delete' : function() {
  6261. self.plugin.getSelectedAnchor().remove();
  6262. }
  6263. };
  6264. self.clickToolbar(name, self.plugin.anchor.edit);
  6265. });
  6266. /*******************************************************************************
  6267. * KindEditor - WYSIWYG HTML Editor for Internet
  6268. * Copyright (C) 2006-2011 kindsoft.net
  6269. *
  6270. * @author Roddy <luolonghao@gmail.com>
  6271. * @site http://www.kindsoft.net/
  6272. * @licence http://www.kindsoft.net/license.php
  6273. *******************************************************************************/
  6274. KindEditor.plugin('autoheight', function(K) {
  6275. var self = this;
  6276. if (!self.autoHeightMode) {
  6277. return;
  6278. }
  6279. var minHeight;
  6280. function hideScroll() {
  6281. var edit = self.edit;
  6282. var body = edit.doc.body;
  6283. edit.iframe[0].scroll = 'no';
  6284. body.style.overflowY = 'hidden';
  6285. }
  6286. function resetHeight() {
  6287. var edit = self.edit;
  6288. var body = edit.doc.body;
  6289. edit.iframe.height(minHeight);
  6290. self.resize(null, Math.max((K.IE ? body.scrollHeight : body.offsetHeight) + 76, minHeight));
  6291. }
  6292. function init() {
  6293. minHeight = K.removeUnit(self.height);
  6294. self.edit.afterChange(resetHeight);
  6295. hideScroll();
  6296. resetHeight();
  6297. }
  6298. if (self.isCreated) {
  6299. init();
  6300. } else {
  6301. self.afterCreate(init);
  6302. }
  6303. });
  6304. /*
  6305. * 如何实现真正的自动高度?
  6306. * 修改编辑器高度之后,再次获取body内容高度时,最小值只会是当前iframe的设置高度,这样就导致高度只增不减。
  6307. * 所以每次获取body内容高度之前,先将iframe的高度重置为最小高度,这样就能获取body的实际高度。
  6308. * 由此就实现了真正的自动高度
  6309. * 测试:chrome、firefox、IE9、IE8
  6310. * */
  6311. /*******************************************************************************
  6312. * KindEditor - WYSIWYG HTML Editor for Internet
  6313. * Copyright (C) 2006-2011 kindsoft.net
  6314. *
  6315. * @author Roddy <luolonghao@gmail.com>
  6316. * @site http://www.kindsoft.net/
  6317. * @licence http://www.kindsoft.net/license.php
  6318. *******************************************************************************/
  6319. KindEditor.plugin('baidumap', function(K) {
  6320. var self = this, name = 'baidumap', lang = self.lang(name + '.');
  6321. var mapWidth = K.undef(self.mapWidth, 558);
  6322. var mapHeight = K.undef(self.mapHeight, 360);
  6323. self.clickToolbar(name, function() {
  6324. var html = ['<div style="padding:10px 20px;">',
  6325. '<div class="ke-header">',
  6326. '<div class="ke-left">',
  6327. lang.address + ' <input id="kindeditor_plugin_map_address" name="address" class="ke-input-text" value="" style="width:200px;" /> ',
  6328. '<span class="ke-button-common ke-button-outer">',
  6329. '<input type="button" name="searchBtn" class="ke-button-common ke-button" value="' + lang.search + '" />',
  6330. '</span>',
  6331. '</div>',
  6332. '<div class="ke-right">',
  6333. '<input type="checkbox" id="keInsertDynamicMap" name="insertDynamicMap" value="1" /> <label for="keInsertDynamicMap">' + lang.insertDynamicMap + '</label>',
  6334. '</div>',
  6335. '<div class="ke-clearfix"></div>',
  6336. '</div>',
  6337. '<div class="ke-map" style="width:' + mapWidth + 'px;height:' + mapHeight + 'px;"></div>',
  6338. '</div>'].join('');
  6339. var dialog = self.createDialog({
  6340. name : name,
  6341. width : mapWidth + 42,
  6342. title : self.lang(name),
  6343. body : html,
  6344. yesBtn : {
  6345. name : self.lang('yes'),
  6346. click : function(e) {
  6347. var map = win.map;
  6348. var centerObj = map.getCenter();
  6349. var center = centerObj.lng + ',' + centerObj.lat;
  6350. var zoom = map.getZoom();
  6351. var url = [checkbox[0].checked ? self.pluginsPath + 'baidumap/index.html' : 'http://api.map.baidu.com/staticimage',
  6352. '?center=' + encodeURIComponent(center),
  6353. '&zoom=' + encodeURIComponent(zoom),
  6354. '&width=' + mapWidth,
  6355. '&height=' + mapHeight,
  6356. '&markers=' + encodeURIComponent(center),
  6357. '&markerStyles=' + encodeURIComponent('l,A')].join('');
  6358. if (checkbox[0].checked) {
  6359. self.insertHtml('<iframe src="' + url + '" frameborder="0" style="width:' + (mapWidth + 2) + 'px;height:' + (mapHeight + 2) + 'px;"></iframe>');
  6360. } else {
  6361. self.exec('insertimage', url);
  6362. }
  6363. self.hideDialog().focus();
  6364. }
  6365. },
  6366. beforeRemove : function() {
  6367. searchBtn.remove();
  6368. if (doc) {
  6369. doc.write('');
  6370. }
  6371. iframe.remove();
  6372. }
  6373. });
  6374. var div = dialog.div,
  6375. addressBox = K('[name="address"]', div),
  6376. searchBtn = K('[name="searchBtn"]', div),
  6377. checkbox = K('[name="insertDynamicMap"]', dialog.div),
  6378. win, doc;
  6379. var iframe = K('<iframe class="ke-textarea" frameborder="0" src="' + self.pluginsPath + 'baidumap/map.html" style="width:' + mapWidth + 'px;height:' + mapHeight + 'px;"></iframe>');
  6380. function ready() {
  6381. win = iframe[0].contentWindow;
  6382. doc = K.iframeDoc(iframe);
  6383. }
  6384. iframe.bind('load', function() {
  6385. iframe.unbind('load');
  6386. if (K.IE) {
  6387. ready();
  6388. } else {
  6389. setTimeout(ready, 0);
  6390. }
  6391. });
  6392. K('.ke-map', div).replaceWith(iframe);
  6393. searchBtn.click(function() {
  6394. win.search(addressBox.val());
  6395. });
  6396. });
  6397. });
  6398. /*******************************************************************************
  6399. * KindEditor - WYSIWYG HTML Editor for Internet
  6400. * Copyright (C) 2006-2011 kindsoft.net
  6401. *
  6402. * @author Roddy <luolonghao@gmail.com>
  6403. * @site http://www.kindsoft.net/
  6404. * @licence http://www.kindsoft.net/license.php
  6405. *******************************************************************************/
  6406. KindEditor.plugin('map', function(K) {
  6407. var self = this, name = 'map', lang = self.lang(name + '.');
  6408. self.clickToolbar(name, function() {
  6409. var html = ['<div style="padding:10px 20px;">',
  6410. '<div class="ke-dialog-row">',
  6411. lang.address + ' <input id="kindeditor_plugin_map_address" name="address" class="ke-input-text" value="" style="width:200px;" /> ',
  6412. '<span class="ke-button-common ke-button-outer">',
  6413. '<input type="button" name="searchBtn" class="ke-button-common ke-button" value="' + lang.search + '" />',
  6414. '</span>',
  6415. '</div>',
  6416. '<div class="ke-map" style="width:558px;height:360px;"></div>',
  6417. '</div>'].join('');
  6418. var dialog = self.createDialog({
  6419. name : name,
  6420. width : 600,
  6421. title : self.lang(name),
  6422. body : html,
  6423. yesBtn : {
  6424. name : self.lang('yes'),
  6425. click : function(e) {
  6426. var geocoder = win.geocoder,
  6427. map = win.map,
  6428. center = map.getCenter().lat() + ',' + map.getCenter().lng(),
  6429. zoom = map.getZoom(),
  6430. maptype = map.getMapTypeId(),
  6431. url = 'http://maps.googleapis.com/maps/api/staticmap';
  6432. url += '?center=' + encodeURIComponent(center);
  6433. url += '&zoom=' + encodeURIComponent(zoom);
  6434. url += '&size=558x360';
  6435. url += '&maptype=' + encodeURIComponent(maptype);
  6436. url += '&markers=' + encodeURIComponent(center);
  6437. url += '&language=' + self.langType;
  6438. url += '&sensor=false';
  6439. self.exec('insertimage', url).hideDialog().focus();
  6440. }
  6441. },
  6442. beforeRemove : function() {
  6443. searchBtn.remove();
  6444. if (doc) {
  6445. doc.write('');
  6446. }
  6447. iframe.remove();
  6448. }
  6449. });
  6450. var div = dialog.div,
  6451. addressBox = K('[name="address"]', div),
  6452. searchBtn = K('[name="searchBtn"]', div),
  6453. win, doc;
  6454. var iframeHtml = ['<!doctype html><html><head>',
  6455. '<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />',
  6456. '<style>',
  6457. ' html { height: 100% }',
  6458. ' body { height: 100%; margin: 0; padding: 0; background-color: #FFF }',
  6459. ' #map_canvas { height: 100% }',
  6460. '</style>',
  6461. '<script src="http://maps.googleapis.com/maps/api/js?sensor=false&language=' + self.langType + '"></script>',
  6462. '<script>',
  6463. 'var map, geocoder;',
  6464. 'function initialize() {',
  6465. ' var latlng = new google.maps.LatLng(31.230393, 121.473704);',
  6466. ' var options = {',
  6467. ' zoom: 11,',
  6468. ' center: latlng,',
  6469. ' disableDefaultUI: true,',
  6470. ' panControl: true,',
  6471. ' zoomControl: true,',
  6472. ' mapTypeControl: true,',
  6473. ' scaleControl: true,',
  6474. ' streetViewControl: false,',
  6475. ' overviewMapControl: true,',
  6476. ' mapTypeId: google.maps.MapTypeId.ROADMAP',
  6477. ' };',
  6478. ' map = new google.maps.Map(document.getElementById("map_canvas"), options);',
  6479. ' geocoder = new google.maps.Geocoder();',
  6480. ' geocoder.geocode({latLng: latlng}, function(results, status) {',
  6481. ' if (status == google.maps.GeocoderStatus.OK) {',
  6482. ' if (results[3]) {',
  6483. ' parent.document.getElementById("kindeditor_plugin_map_address").value = results[3].formatted_address;',
  6484. ' }',
  6485. ' }',
  6486. ' });',
  6487. '}',
  6488. 'function search(address) {',
  6489. ' if (!map) return;',
  6490. ' geocoder.geocode({address : address}, function(results, status) {',
  6491. ' if (status == google.maps.GeocoderStatus.OK) {',
  6492. ' map.setZoom(11);',
  6493. ' map.setCenter(results[0].geometry.location);',
  6494. ' var marker = new google.maps.Marker({',
  6495. ' map: map,',
  6496. ' position: results[0].geometry.location',
  6497. ' });',
  6498. ' } else {',
  6499. ' alert("Invalid address: " + address);',
  6500. ' }',
  6501. ' });',
  6502. '}',
  6503. '</script>',
  6504. '</head>',
  6505. '<body onload="initialize();">',
  6506. '<div id="map_canvas" style="width:100%; height:100%"></div>',
  6507. '</body></html>'].join('\n');
  6508. var iframe = K('<iframe class="ke-textarea" frameborder="0" src="' + self.pluginsPath + 'map/map.html" style="width:558px;height:360px;"></iframe>');
  6509. function ready() {
  6510. win = iframe[0].contentWindow;
  6511. doc = K.iframeDoc(iframe);
  6512. }
  6513. iframe.bind('load', function() {
  6514. iframe.unbind('load');
  6515. if (K.IE) {
  6516. ready();
  6517. } else {
  6518. setTimeout(ready, 0);
  6519. }
  6520. });
  6521. K('.ke-map', div).replaceWith(iframe);
  6522. searchBtn.click(function() {
  6523. win.search(addressBox.val());
  6524. });
  6525. });
  6526. });
  6527. /*******************************************************************************
  6528. * KindEditor - WYSIWYG HTML Editor for Internet
  6529. * Copyright (C) 2006-2011 kindsoft.net
  6530. *
  6531. * @author Roddy <luolonghao@gmail.com>
  6532. * @site http://www.kindsoft.net/
  6533. * @licence http://www.kindsoft.net/license.php
  6534. *******************************************************************************/
  6535. KindEditor.plugin('clearhtml', function(K) {
  6536. var self = this, name = 'clearhtml';
  6537. self.clickToolbar(name, function() {
  6538. self.focus();
  6539. var html = self.html();
  6540. html = html.replace(/(<script[^>]*>)([\s\S]*?)(<\/script>)/ig, '');
  6541. html = html.replace(/(<style[^>]*>)([\s\S]*?)(<\/style>)/ig, '');
  6542. html = K.formatHtml(html, {
  6543. a : ['href', 'target'],
  6544. embed : ['src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'],
  6545. img : ['src', 'width', 'height', 'border', 'alt', 'title', '.width', '.height'],
  6546. table : ['border'],
  6547. 'td,th' : ['rowspan', 'colspan'],
  6548. 'div,hr,br,tbody,tr,p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : []
  6549. });
  6550. self.html(html);
  6551. self.cmd.selection(true);
  6552. self.addBookmark();
  6553. });
  6554. });
  6555. /*******************************************************************************
  6556. * KindEditor - WYSIWYG HTML Editor for Internet
  6557. * Copyright (C) 2006-2011 kindsoft.net
  6558. *
  6559. * @author Roddy <luolonghao@gmail.com>
  6560. * @site http://www.kindsoft.net/
  6561. * @licence http://www.kindsoft.net/license.php
  6562. *******************************************************************************/
  6563. KindEditor.plugin('code', function(K) {
  6564. var self = this, name = 'code';
  6565. self.clickToolbar(name, function() {
  6566. var lang = self.lang(name + '.'),
  6567. html = ['<div style="padding:10px 20px;">',
  6568. '<div class="ke-dialog-row">',
  6569. '<select class="ke-code-type">',
  6570. '<option value="js">JavaScript</option>',
  6571. '<option value="html">HTML</option>',
  6572. '<option value="css">CSS</option>',
  6573. '<option value="php">PHP</option>',
  6574. '<option value="pl">Perl</option>',
  6575. '<option value="py">Python</option>',
  6576. '<option value="rb">Ruby</option>',
  6577. '<option value="java">Java</option>',
  6578. '<option value="vb">ASP/VB</option>',
  6579. '<option value="cpp">C/C++</option>',
  6580. '<option value="cs">C#</option>',
  6581. '<option value="xml">XML</option>',
  6582. '<option value="bsh">Shell</option>',
  6583. '<option value="">Other</option>',
  6584. '</select>',
  6585. '</div>',
  6586. '<textarea class="ke-textarea" style="width:408px;height:260px;"></textarea>',
  6587. '</div>'].join(''),
  6588. dialog = self.createDialog({
  6589. name : name,
  6590. width : 450,
  6591. title : self.lang(name),
  6592. body : html,
  6593. yesBtn : {
  6594. name : self.lang('yes'),
  6595. click : function(e) {
  6596. var type = K('.ke-code-type', dialog.div).val(),
  6597. code = textarea.val(),
  6598. cls = type === '' ? '' : ' lang-' + type,
  6599. html = '<pre class="prettyprint' + cls + '">\n' + K.escape(code) + '</pre> ';
  6600. if (K.trim(code) === '') {
  6601. alert(lang.pleaseInput);
  6602. textarea[0].focus();
  6603. return;
  6604. }
  6605. self.insertHtml(html).hideDialog().focus();
  6606. }
  6607. }
  6608. }),
  6609. textarea = K('textarea', dialog.div);
  6610. textarea[0].focus();
  6611. });
  6612. });
  6613. /*******************************************************************************
  6614. * KindEditor - WYSIWYG HTML Editor for Internet
  6615. * Copyright (C) 2006-2011 kindsoft.net
  6616. *
  6617. * @author Roddy <luolonghao@gmail.com>
  6618. * @site http://www.kindsoft.net/
  6619. * @licence http://www.kindsoft.net/license.php
  6620. *******************************************************************************/
  6621. KindEditor.plugin('emoticons', function(K) {
  6622. var self = this, name = 'emoticons',
  6623. path = (self.emoticonsPath || self.pluginsPath + 'emoticons/images/'),
  6624. allowPreview = self.allowPreviewEmoticons === undefined ? true : self.allowPreviewEmoticons,
  6625. currentPageNum = 1;
  6626. self.clickToolbar(name, function() {
  6627. var rows = 5, cols = 9, total = 135, startNum = 0,
  6628. cells = rows * cols, pages = Math.ceil(total / cells),
  6629. colsHalf = Math.floor(cols / 2),
  6630. wrapperDiv = K('<div class="ke-plugin-emoticons"></div>'),
  6631. elements = [],
  6632. menu = self.createMenu({
  6633. name : name,
  6634. beforeRemove : function() {
  6635. removeEvent();
  6636. }
  6637. });
  6638. menu.div.append(wrapperDiv);
  6639. var previewDiv, previewImg;
  6640. if (allowPreview) {
  6641. previewDiv = K('<div class="ke-preview"></div>').css('right', 0);
  6642. previewImg = K('<img class="ke-preview-img" src="' + path + startNum + '.gif" />');
  6643. wrapperDiv.append(previewDiv);
  6644. previewDiv.append(previewImg);
  6645. }
  6646. function bindCellEvent(cell, j, num) {
  6647. if (previewDiv) {
  6648. cell.mouseover(function() {
  6649. if (j > colsHalf) {
  6650. previewDiv.css('left', 0);
  6651. previewDiv.css('right', '');
  6652. } else {
  6653. previewDiv.css('left', '');
  6654. previewDiv.css('right', 0);
  6655. }
  6656. previewImg.attr('src', path + num + '.gif');
  6657. K(this).addClass('ke-on');
  6658. });
  6659. } else {
  6660. cell.mouseover(function() {
  6661. K(this).addClass('ke-on');
  6662. });
  6663. }
  6664. cell.mouseout(function() {
  6665. K(this).removeClass('ke-on');
  6666. });
  6667. cell.click(function(e) {
  6668. self.insertHtml('<img src="' + path + num + '.gif" border="0" alt="" />').hideMenu().focus();
  6669. e.stop();
  6670. });
  6671. }
  6672. function createEmoticonsTable(pageNum, parentDiv) {
  6673. var table = document.createElement('table');
  6674. parentDiv.append(table);
  6675. if (previewDiv) {
  6676. K(table).mouseover(function() {
  6677. previewDiv.show('block');
  6678. });
  6679. K(table).mouseout(function() {
  6680. previewDiv.hide();
  6681. });
  6682. elements.push(K(table));
  6683. }
  6684. table.className = 'ke-table';
  6685. table.cellPadding = 0;
  6686. table.cellSpacing = 0;
  6687. table.border = 0;
  6688. var num = (pageNum - 1) * cells + startNum;
  6689. for (var i = 0; i < rows; i++) {
  6690. var row = table.insertRow(i);
  6691. for (var j = 0; j < cols; j++) {
  6692. var cell = K(row.insertCell(j));
  6693. cell.addClass('ke-cell');
  6694. bindCellEvent(cell, j, num);
  6695. var span = K('<span class="ke-img"></span>')
  6696. .css('background-position', '-' + (24 * num) + 'px 0px')
  6697. .css('background-image', 'url(' + path + 'static.gif)');
  6698. cell.append(span);
  6699. elements.push(cell);
  6700. num++;
  6701. }
  6702. }
  6703. return table;
  6704. }
  6705. var table = createEmoticonsTable(currentPageNum, wrapperDiv);
  6706. function removeEvent() {
  6707. K.each(elements, function() {
  6708. this.unbind();
  6709. });
  6710. }
  6711. var pageDiv;
  6712. function bindPageEvent(el, pageNum) {
  6713. el.click(function(e) {
  6714. removeEvent();
  6715. table.parentNode.removeChild(table);
  6716. pageDiv.remove();
  6717. table = createEmoticonsTable(pageNum, wrapperDiv);
  6718. createPageTable(pageNum);
  6719. currentPageNum = pageNum;
  6720. e.stop();
  6721. });
  6722. }
  6723. function createPageTable(currentPageNum) {
  6724. pageDiv = K('<div class="ke-page"></div>');
  6725. wrapperDiv.append(pageDiv);
  6726. for (var pageNum = 1; pageNum <= pages; pageNum++) {
  6727. if (currentPageNum !== pageNum) {
  6728. var a = K('<a href="javascript:;">[' + pageNum + ']</a>');
  6729. bindPageEvent(a, pageNum);
  6730. pageDiv.append(a);
  6731. elements.push(a);
  6732. } else {
  6733. pageDiv.append(K('@[' + pageNum + ']'));
  6734. }
  6735. pageDiv.append(K('@&nbsp;'));
  6736. }
  6737. }
  6738. createPageTable(currentPageNum);
  6739. });
  6740. });
  6741. /*******************************************************************************
  6742. * KindEditor - WYSIWYG HTML Editor for Internet
  6743. * Copyright (C) 2006-2011 kindsoft.net
  6744. *
  6745. * @author Roddy <luolonghao@gmail.com>
  6746. * @site http://www.kindsoft.net/
  6747. * @licence http://www.kindsoft.net/license.php
  6748. *******************************************************************************/
  6749. KindEditor.plugin('filemanager', function(K) {
  6750. var self = this, name = 'filemanager',
  6751. fileManagerJson = K.undef(self.fileManagerJson, self.basePath + 'php/file_manager_json.php'),
  6752. imgPath = self.pluginsPath + name + '/images/',
  6753. lang = self.lang(name + '.');
  6754. function makeFileTitle(filename, filesize, datetime) {
  6755. return filename + ' (' + Math.ceil(filesize / 1024) + 'KB, ' + datetime + ')';
  6756. }
  6757. function bindTitle(el, data) {
  6758. if (data.is_dir) {
  6759. el.attr('title', data.filename);
  6760. } else {
  6761. el.attr('title', makeFileTitle(data.filename, data.filesize, data.datetime));
  6762. }
  6763. }
  6764. self.plugin.filemanagerDialog = function(options) {
  6765. var width = K.undef(options.width, 650),
  6766. height = K.undef(options.height, 510),
  6767. dirName = K.undef(options.dirName, ''),
  6768. viewType = K.undef(options.viewType, 'VIEW').toUpperCase(),
  6769. clickFn = options.clickFn;
  6770. var html = [
  6771. '<div style="padding:10px 20px;">',
  6772. '<div class="ke-plugin-filemanager-header">',
  6773. '<div class="ke-left">',
  6774. '<img class="ke-inline-block" name="moveupImg" src="' + imgPath + 'go-up.gif" width="16" height="16" border="0" alt="" /> ',
  6775. '<a class="ke-inline-block" name="moveupLink" href="javascript:;">' + lang.moveup + '</a>',
  6776. '</div>',
  6777. '<div class="ke-right">',
  6778. lang.viewType + ' <select class="ke-inline-block" name="viewType">',
  6779. '<option value="VIEW">' + lang.viewImage + '</option>',
  6780. '<option value="LIST">' + lang.listImage + '</option>',
  6781. '</select> ',
  6782. lang.orderType + ' <select class="ke-inline-block" name="orderType">',
  6783. '<option value="NAME">' + lang.fileName + '</option>',
  6784. '<option value="SIZE">' + lang.fileSize + '</option>',
  6785. '<option value="TYPE">' + lang.fileType + '</option>',
  6786. '</select>',
  6787. '</div>',
  6788. '<div class="ke-clearfix"></div>',
  6789. '</div>',
  6790. '<div class="ke-plugin-filemanager-body"></div>',
  6791. '</div>'
  6792. ].join('');
  6793. var dialog = self.createDialog({
  6794. name : name,
  6795. width : width,
  6796. height : height,
  6797. title : self.lang(name),
  6798. body : html
  6799. }),
  6800. div = dialog.div,
  6801. bodyDiv = K('.ke-plugin-filemanager-body', div),
  6802. moveupImg = K('[name="moveupImg"]', div),
  6803. moveupLink = K('[name="moveupLink"]', div),
  6804. viewServerBtn = K('[name="viewServer"]', div),
  6805. viewTypeBox = K('[name="viewType"]', div),
  6806. orderTypeBox = K('[name="orderType"]', div);
  6807. function reloadPage(path, order, func) {
  6808. var param = 'path=' + path + '&order=' + order + '&dir=' + dirName;
  6809. dialog.showLoading(self.lang('ajaxLoading'));
  6810. K.ajax(K.addParam(fileManagerJson, param + '&' + new Date().getTime()), function(data) {
  6811. dialog.hideLoading();
  6812. func(data);
  6813. });
  6814. }
  6815. var elList = [];
  6816. function bindEvent(el, result, data, createFunc) {
  6817. var fileUrl = K.formatUrl(result.current_url + data.filename, 'absolute'),
  6818. dirPath = encodeURIComponent(result.current_dir_path + data.filename + '/');
  6819. if (data.is_dir) {
  6820. el.click(function(e) {
  6821. reloadPage(dirPath, orderTypeBox.val(), createFunc);
  6822. });
  6823. } else if (data.is_photo) {
  6824. el.click(function(e) {
  6825. clickFn.call(this, fileUrl, data.filename);
  6826. });
  6827. } else {
  6828. el.click(function(e) {
  6829. clickFn.call(this, fileUrl, data.filename);
  6830. });
  6831. }
  6832. elList.push(el);
  6833. }
  6834. function createCommon(result, createFunc) {
  6835. K.each(elList, function() {
  6836. this.unbind();
  6837. });
  6838. moveupLink.unbind();
  6839. viewTypeBox.unbind();
  6840. orderTypeBox.unbind();
  6841. if (result.current_dir_path) {
  6842. moveupLink.click(function(e) {
  6843. reloadPage(result.moveup_dir_path, orderTypeBox.val(), createFunc);
  6844. });
  6845. }
  6846. function changeFunc() {
  6847. if (viewTypeBox.val() == 'VIEW') {
  6848. reloadPage(result.current_dir_path, orderTypeBox.val(), createView);
  6849. } else {
  6850. reloadPage(result.current_dir_path, orderTypeBox.val(), createList);
  6851. }
  6852. }
  6853. viewTypeBox.change(changeFunc);
  6854. orderTypeBox.change(changeFunc);
  6855. bodyDiv.html('');
  6856. }
  6857. function createList(result) {
  6858. createCommon(result, createList);
  6859. var table = document.createElement('table');
  6860. table.className = 'ke-table';
  6861. table.cellPadding = 0;
  6862. table.cellSpacing = 0;
  6863. table.border = 0;
  6864. bodyDiv.append(table);
  6865. var fileList = result.file_list;
  6866. for (var i = 0, len = fileList.length; i < len; i++) {
  6867. var data = fileList[i], row = K(table.insertRow(i));
  6868. row.mouseover(function(e) {
  6869. K(this).addClass('ke-on');
  6870. })
  6871. .mouseout(function(e) {
  6872. K(this).removeClass('ke-on');
  6873. });
  6874. var iconUrl = imgPath + (data.is_dir ? 'folder-16.gif' : 'file-16.gif'),
  6875. img = K('<img src="' + iconUrl + '" width="16" height="16" alt="' + data.filename + '" align="absmiddle" />'),
  6876. cell0 = K(row[0].insertCell(0)).addClass('ke-cell ke-name').append(img).append(document.createTextNode(' ' + data.filename));
  6877. if (!data.is_dir || data.has_file) {
  6878. row.css('cursor', 'pointer');
  6879. cell0.attr('title', data.filename);
  6880. bindEvent(cell0, result, data, createList);
  6881. } else {
  6882. cell0.attr('title', lang.emptyFolder);
  6883. }
  6884. K(row[0].insertCell(1)).addClass('ke-cell ke-size').html(data.is_dir ? '-' : Math.ceil(data.filesize / 1024) + 'KB');
  6885. K(row[0].insertCell(2)).addClass('ke-cell ke-datetime').html(data.datetime);
  6886. }
  6887. }
  6888. function createView(result) {
  6889. createCommon(result, createView);
  6890. var fileList = result.file_list;
  6891. for (var i = 0, len = fileList.length; i < len; i++) {
  6892. var data = fileList[i],
  6893. div = K('<div class="ke-inline-block ke-item"></div>');
  6894. bodyDiv.append(div);
  6895. var photoDiv = K('<div class="ke-inline-block ke-photo"></div>')
  6896. .mouseover(function(e) {
  6897. K(this).addClass('ke-on');
  6898. })
  6899. .mouseout(function(e) {
  6900. K(this).removeClass('ke-on');
  6901. });
  6902. div.append(photoDiv);
  6903. var fileUrl = result.current_url + data.filename,
  6904. iconUrl = data.is_dir ? imgPath + 'folder-64.gif' : (data.is_photo ? fileUrl : imgPath + 'file-64.gif');
  6905. var img = K('<img src="' + iconUrl + '" width="80" height="80" alt="' + data.filename + '" />');
  6906. if (!data.is_dir || data.has_file) {
  6907. photoDiv.css('cursor', 'pointer');
  6908. bindTitle(photoDiv, data);
  6909. bindEvent(photoDiv, result, data, createView);
  6910. } else {
  6911. photoDiv.attr('title', lang.emptyFolder);
  6912. }
  6913. photoDiv.append(img);
  6914. div.append('<div class="ke-name" title="' + data.filename + '">' + data.filename + '</div>');
  6915. }
  6916. }
  6917. viewTypeBox.val(viewType);
  6918. reloadPage('', orderTypeBox.val(), viewType == 'VIEW' ? createView : createList);
  6919. return dialog;
  6920. }
  6921. });
  6922. /*******************************************************************************
  6923. * KindEditor - WYSIWYG HTML Editor for Internet
  6924. * Copyright (C) 2006-2011 kindsoft.net
  6925. *
  6926. * @author Roddy <luolonghao@gmail.com>
  6927. * @site http://www.kindsoft.net/
  6928. * @licence http://www.kindsoft.net/license.php
  6929. *******************************************************************************/
  6930. KindEditor.plugin('flash', function(K) {
  6931. var self = this, name = 'flash', lang = self.lang(name + '.'),
  6932. allowFlashUpload = K.undef(self.allowFlashUpload, true),
  6933. allowFileManager = K.undef(self.allowFileManager, false),
  6934. formatUploadUrl = K.undef(self.formatUploadUrl, true),
  6935. extraParams = K.undef(self.extraFileUploadParams, {}),
  6936. filePostName = K.undef(self.filePostName, 'imgFile'),
  6937. uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php');
  6938. self.plugin.flash = {
  6939. edit : function() {
  6940. var html = [
  6941. '<div style="padding:20px;">',
  6942. '<div class="ke-dialog-row">',
  6943. '<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
  6944. '<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:160px;" /> &nbsp;',
  6945. '<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> &nbsp;',
  6946. '<span class="ke-button-common ke-button-outer">',
  6947. '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
  6948. '</span>',
  6949. '</div>',
  6950. '<div class="ke-dialog-row">',
  6951. '<label for="keWidth" style="width:60px;">' + lang.width + '</label>',
  6952. '<input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="550" maxlength="4" /> ',
  6953. '</div>',
  6954. '<div class="ke-dialog-row">',
  6955. '<label for="keHeight" style="width:60px;">' + lang.height + '</label>',
  6956. '<input type="text" id="keHeight" class="ke-input-text ke-input-number" name="height" value="400" maxlength="4" /> ',
  6957. '</div>',
  6958. '</div>'
  6959. ].join('');
  6960. var dialog = self.createDialog({
  6961. name : name,
  6962. width : 450,
  6963. title : self.lang(name),
  6964. body : html,
  6965. yesBtn : {
  6966. name : self.lang('yes'),
  6967. click : function(e) {
  6968. var url = K.trim(urlBox.val()),
  6969. width = widthBox.val(),
  6970. height = heightBox.val();
  6971. if (url == 'http://' || K.invalidUrl(url)) {
  6972. alert(self.lang('invalidUrl'));
  6973. urlBox[0].focus();
  6974. return;
  6975. }
  6976. if (!/^\d*$/.test(width)) {
  6977. alert(self.lang('invalidWidth'));
  6978. widthBox[0].focus();
  6979. return;
  6980. }
  6981. if (!/^\d*$/.test(height)) {
  6982. alert(self.lang('invalidHeight'));
  6983. heightBox[0].focus();
  6984. return;
  6985. }
  6986. var html = K.mediaImg(self.themesPath + 'common/blank.gif', {
  6987. src : url,
  6988. type : K.mediaType('.swf'),
  6989. width : width,
  6990. height : height,
  6991. quality : 'high'
  6992. });
  6993. self.insertHtml(html).hideDialog().focus();
  6994. }
  6995. }
  6996. }),
  6997. div = dialog.div,
  6998. urlBox = K('[name="url"]', div),
  6999. viewServerBtn = K('[name="viewServer"]', div),
  7000. widthBox = K('[name="width"]', div),
  7001. heightBox = K('[name="height"]', div);
  7002. urlBox.val('http://');
  7003. if (allowFlashUpload) {
  7004. var uploadbutton = K.uploadbutton({
  7005. button : K('.ke-upload-button', div)[0],
  7006. fieldName : filePostName,
  7007. extraParams : extraParams,
  7008. url : K.addParam(uploadJson, 'dir=flash'),
  7009. afterUpload : function(data) {
  7010. dialog.hideLoading();
  7011. if (data.error === 0) {
  7012. var url = data.url;
  7013. if (formatUploadUrl) {
  7014. url = K.formatUrl(url, 'absolute');
  7015. }
  7016. urlBox.val(url);
  7017. if (self.afterUpload) {
  7018. self.afterUpload.call(self, url, data, name);
  7019. }
  7020. alert(self.lang('uploadSuccess'));
  7021. } else {
  7022. alert(data.message);
  7023. }
  7024. },
  7025. afterError : function(html) {
  7026. dialog.hideLoading();
  7027. self.errorDialog(html);
  7028. }
  7029. });
  7030. uploadbutton.fileBox.change(function(e) {
  7031. dialog.showLoading(self.lang('uploadLoading'));
  7032. uploadbutton.submit();
  7033. });
  7034. } else {
  7035. K('.ke-upload-button', div).hide();
  7036. }
  7037. if (allowFileManager) {
  7038. viewServerBtn.click(function(e) {
  7039. self.loadPlugin('filemanager', function() {
  7040. self.plugin.filemanagerDialog({
  7041. viewType : 'LIST',
  7042. dirName : 'flash',
  7043. clickFn : function(url, title) {
  7044. if (self.dialogs.length > 1) {
  7045. K('[name="url"]', div).val(url);
  7046. if (self.afterSelectFile) {
  7047. self.afterSelectFile.call(self, url);
  7048. }
  7049. self.hideDialog();
  7050. }
  7051. }
  7052. });
  7053. });
  7054. });
  7055. } else {
  7056. viewServerBtn.hide();
  7057. }
  7058. var img = self.plugin.getSelectedFlash();
  7059. if (img) {
  7060. var attrs = K.mediaAttrs(img.attr('data-ke-tag'));
  7061. urlBox.val(attrs.src);
  7062. widthBox.val(K.removeUnit(img.css('width')) || attrs.width || 0);
  7063. heightBox.val(K.removeUnit(img.css('height')) || attrs.height || 0);
  7064. }
  7065. urlBox[0].focus();
  7066. urlBox[0].select();
  7067. },
  7068. 'delete' : function() {
  7069. self.plugin.getSelectedFlash().remove();
  7070. self.addBookmark();
  7071. }
  7072. };
  7073. self.clickToolbar(name, self.plugin.flash.edit);
  7074. });
  7075. /*******************************************************************************
  7076. * KindEditor - WYSIWYG HTML Editor for Internet
  7077. * Copyright (C) 2006-2011 kindsoft.net
  7078. *
  7079. * @author Roddy <luolonghao@gmail.com>
  7080. * @site http://www.kindsoft.net/
  7081. * @licence http://www.kindsoft.net/license.php
  7082. *******************************************************************************/
  7083. KindEditor.plugin('image', function(K) {
  7084. var self = this, name = 'image',
  7085. allowImageUpload = K.undef(self.allowImageUpload, true),
  7086. allowImageRemote = K.undef(self.allowImageRemote, true),
  7087. formatUploadUrl = K.undef(self.formatUploadUrl, true),
  7088. allowFileManager = K.undef(self.allowFileManager, false),
  7089. uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
  7090. imageTabIndex = K.undef(self.imageTabIndex, 0),
  7091. imgPath = self.pluginsPath + 'image/images/',
  7092. extraParams = K.undef(self.extraFileUploadParams, {}),
  7093. filePostName = K.undef(self.filePostName, 'imgFile'),
  7094. fillDescAfterUploadImage = K.undef(self.fillDescAfterUploadImage, false),
  7095. lang = self.lang(name + '.');
  7096. self.plugin.imageDialog = function(options) {
  7097. var imageUrl = options.imageUrl,
  7098. imageWidth = K.undef(options.imageWidth, ''),
  7099. imageHeight = K.undef(options.imageHeight, ''),
  7100. imageTitle = K.undef(options.imageTitle, ''),
  7101. imageAlign = K.undef(options.imageAlign, ''),
  7102. showRemote = K.undef(options.showRemote, true),
  7103. showLocal = K.undef(options.showLocal, true),
  7104. tabIndex = K.undef(options.tabIndex, 0),
  7105. clickFn = options.clickFn;
  7106. var target = 'kindeditor_upload_iframe_' + new Date().getTime();
  7107. var hiddenElements = [];
  7108. for(var k in extraParams){
  7109. hiddenElements.push('<input type="hidden" name="' + k + '" value="' + extraParams[k] + '" />');
  7110. }
  7111. var html = [
  7112. '<div style="padding:20px;">',
  7113. '<div class="tabs"></div>',
  7114. '<div class="tab1" style="display:none;">',
  7115. '<div class="ke-dialog-row">',
  7116. '<label for="remoteUrl" style="width:60px;">' + lang.remoteUrl + '</label>',
  7117. '<input type="text" id="remoteUrl" class="ke-input-text" name="url" value="" style="width:200px;" /> &nbsp;',
  7118. '<span class="ke-button-common ke-button-outer">',
  7119. '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
  7120. '</span>',
  7121. '</div>',
  7122. '<div class="ke-dialog-row">',
  7123. '<label for="remoteWidth" style="width:60px;">' + lang.size + '</label>',
  7124. lang.width + ' <input type="text" id="remoteWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> ',
  7125. lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> ',
  7126. '<img class="ke-refresh-btn" src="' + imgPath + 'refresh.png" width="16" height="16" alt="" style="cursor:pointer;" title="' + lang.resetSize + '" />',
  7127. '</div>',
  7128. '<div class="ke-dialog-row">',
  7129. '<label style="width:60px;">' + lang.align + '</label>',
  7130. '<input type="radio" name="align" class="ke-inline-block" value="" checked="checked" /> <img name="defaultImg" src="' + imgPath + 'align_top.gif" width="23" height="25" alt="" />',
  7131. ' <input type="radio" name="align" class="ke-inline-block" value="left" /> <img name="leftImg" src="' + imgPath + 'align_left.gif" width="23" height="25" alt="" />',
  7132. ' <input type="radio" name="align" class="ke-inline-block" value="right" /> <img name="rightImg" src="' + imgPath + 'align_right.gif" width="23" height="25" alt="" />',
  7133. '</div>',
  7134. '<div class="ke-dialog-row">',
  7135. '<label for="remoteTitle" style="width:60px;">' + lang.imgTitle + '</label>',
  7136. '<input type="text" id="remoteTitle" class="ke-input-text" name="title" value="" style="width:200px;" />',
  7137. '</div>',
  7138. '</div>',
  7139. '<div class="tab2" style="display:none;">',
  7140. '<iframe name="' + target + '" style="display:none;"></iframe>',
  7141. '<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + K.addParam(uploadJson, 'dir=image') + '">',
  7142. '<div class="ke-dialog-row">',
  7143. hiddenElements.join(''),
  7144. '<label style="width:60px;">' + lang.localUrl + '</label>',
  7145. '<input type="text" name="localUrl" class="ke-input-text" tabindex="-1" style="width:200px;" readonly="true" /> &nbsp;',
  7146. '<input type="button" class="ke-upload-button" value="' + lang.upload + '" />',
  7147. '</div>',
  7148. '</form>',
  7149. '</div>',
  7150. '</div>'
  7151. ].join('');
  7152. var dialogWidth = showLocal || allowFileManager ? 450 : 400,
  7153. dialogHeight = showLocal && showRemote ? 300 : 250;
  7154. var dialog = self.createDialog({
  7155. name : name,
  7156. width : dialogWidth,
  7157. height : dialogHeight,
  7158. title : self.lang(name),
  7159. body : html,
  7160. yesBtn : {
  7161. name : self.lang('yes'),
  7162. click : function(e) {
  7163. if (dialog.isLoading) {
  7164. return;
  7165. }
  7166. if (showLocal && showRemote && tabs && tabs.selectedIndex === 1 || !showRemote) {
  7167. if (uploadbutton.fileBox.val() == '') {
  7168. alert(self.lang('pleaseSelectFile'));
  7169. return;
  7170. }
  7171. dialog.showLoading(self.lang('uploadLoading'));
  7172. uploadbutton.submit();
  7173. localUrlBox.val('');
  7174. return;
  7175. }
  7176. var url = K.trim(urlBox.val()),
  7177. width = widthBox.val(),
  7178. height = heightBox.val(),
  7179. title = titleBox.val(),
  7180. align = '';
  7181. alignBox.each(function() {
  7182. if (this.checked) {
  7183. align = this.value;
  7184. return false;
  7185. }
  7186. });
  7187. if (url == 'http://' || K.invalidUrl(url)) {
  7188. alert(self.lang('invalidUrl'));
  7189. urlBox[0].focus();
  7190. return;
  7191. }
  7192. if (!/^\d*$/.test(width)) {
  7193. alert(self.lang('invalidWidth'));
  7194. widthBox[0].focus();
  7195. return;
  7196. }
  7197. if (!/^\d*$/.test(height)) {
  7198. alert(self.lang('invalidHeight'));
  7199. heightBox[0].focus();
  7200. return;
  7201. }
  7202. clickFn.call(self, url, title, width, height, 0, align);
  7203. }
  7204. },
  7205. beforeRemove : function() {
  7206. viewServerBtn.unbind();
  7207. widthBox.unbind();
  7208. heightBox.unbind();
  7209. refreshBtn.unbind();
  7210. }
  7211. }),
  7212. div = dialog.div;
  7213. var urlBox = K('[name="url"]', div),
  7214. localUrlBox = K('[name="localUrl"]', div),
  7215. viewServerBtn = K('[name="viewServer"]', div),
  7216. widthBox = K('.tab1 [name="width"]', div),
  7217. heightBox = K('.tab1 [name="height"]', div),
  7218. refreshBtn = K('.ke-refresh-btn', div),
  7219. titleBox = K('.tab1 [name="title"]', div),
  7220. alignBox = K('.tab1 [name="align"]', div);
  7221. var tabs;
  7222. if (showRemote && showLocal) {
  7223. tabs = K.tabs({
  7224. src : K('.tabs', div),
  7225. afterSelect : function(i) {}
  7226. });
  7227. tabs.add({
  7228. title : lang.remoteImage,
  7229. panel : K('.tab1', div)
  7230. });
  7231. tabs.add({
  7232. title : lang.localImage,
  7233. panel : K('.tab2', div)
  7234. });
  7235. tabs.select(tabIndex);
  7236. } else if (showRemote) {
  7237. K('.tab1', div).show();
  7238. } else if (showLocal) {
  7239. K('.tab2', div).show();
  7240. }
  7241. var uploadbutton = K.uploadbutton({
  7242. button : K('.ke-upload-button', div)[0],
  7243. fieldName : filePostName,
  7244. form : K('.ke-form', div),
  7245. target : target,
  7246. width: 60,
  7247. afterUpload : function(data) {
  7248. dialog.hideLoading();
  7249. if (data.error === 0) {
  7250. var url = data.url;
  7251. if (formatUploadUrl) {
  7252. url = K.formatUrl(url, 'absolute');
  7253. }
  7254. if (self.afterUpload) {
  7255. self.afterUpload.call(self, url, data, name);
  7256. }
  7257. if (!fillDescAfterUploadImage) {
  7258. clickFn.call(self, url, data.title, data.width, data.height, data.border, data.align);
  7259. } else {
  7260. K(".ke-dialog-row #remoteUrl", div).val(url);
  7261. K(".ke-tabs-li", div)[0].click();
  7262. K(".ke-refresh-btn", div).click();
  7263. }
  7264. } else {
  7265. alert(data.message);
  7266. }
  7267. },
  7268. afterError : function(html) {
  7269. dialog.hideLoading();
  7270. self.errorDialog(html);
  7271. }
  7272. });
  7273. uploadbutton.fileBox.change(function(e) {
  7274. localUrlBox.val(uploadbutton.fileBox.val());
  7275. });
  7276. if (allowFileManager) {
  7277. viewServerBtn.click(function(e) {
  7278. self.loadPlugin('filemanager', function() {
  7279. self.plugin.filemanagerDialog({
  7280. viewType : 'VIEW',
  7281. dirName : 'image',
  7282. clickFn : function(url, title) {
  7283. if (self.dialogs.length > 1) {
  7284. K('[name="url"]', div).val(url);
  7285. if (self.afterSelectFile) {
  7286. self.afterSelectFile.call(self, url);
  7287. }
  7288. self.hideDialog();
  7289. }
  7290. }
  7291. });
  7292. });
  7293. });
  7294. } else {
  7295. viewServerBtn.hide();
  7296. }
  7297. var originalWidth = 0, originalHeight = 0;
  7298. function setSize(width, height) {
  7299. widthBox.val(width);
  7300. heightBox.val(height);
  7301. originalWidth = width;
  7302. originalHeight = height;
  7303. }
  7304. refreshBtn.click(function(e) {
  7305. var tempImg = K('<img src="' + urlBox.val() + '" />', document).css({
  7306. position : 'absolute',
  7307. visibility : 'hidden',
  7308. top : 0,
  7309. left : '-1000px'
  7310. });
  7311. tempImg.bind('load', function() {
  7312. setSize(tempImg.width(), tempImg.height());
  7313. tempImg.remove();
  7314. });
  7315. K(document.body).append(tempImg);
  7316. });
  7317. widthBox.change(function(e) {
  7318. if (originalWidth > 0) {
  7319. heightBox.val(Math.round(originalHeight / originalWidth * parseInt(this.value, 10)));
  7320. }
  7321. });
  7322. heightBox.change(function(e) {
  7323. if (originalHeight > 0) {
  7324. widthBox.val(Math.round(originalWidth / originalHeight * parseInt(this.value, 10)));
  7325. }
  7326. });
  7327. urlBox.val(options.imageUrl);
  7328. setSize(options.imageWidth, options.imageHeight);
  7329. titleBox.val(options.imageTitle);
  7330. alignBox.each(function() {
  7331. if (this.value === options.imageAlign) {
  7332. this.checked = true;
  7333. return false;
  7334. }
  7335. });
  7336. if (showRemote && tabIndex === 0) {
  7337. urlBox[0].focus();
  7338. urlBox[0].select();
  7339. }
  7340. return dialog;
  7341. };
  7342. self.plugin.image = {
  7343. edit : function() {
  7344. var img = self.plugin.getSelectedImage();
  7345. self.plugin.imageDialog({
  7346. imageUrl : img ? img.attr('data-ke-src') : 'http://',
  7347. imageWidth : img ? img.width() : '',
  7348. imageHeight : img ? img.height() : '',
  7349. imageTitle : img ? img.attr('title') : '',
  7350. imageAlign : img ? img.attr('align') : '',
  7351. showRemote : allowImageRemote,
  7352. showLocal : allowImageUpload,
  7353. tabIndex: img ? 0 : imageTabIndex,
  7354. clickFn : function(url, title, width, height, border, align) {
  7355. if (img) {
  7356. img.attr('src', url);
  7357. img.attr('data-ke-src', url);
  7358. img.attr('width', width);
  7359. img.attr('height', height);
  7360. img.attr('title', title);
  7361. img.attr('align', align);
  7362. img.attr('alt', title);
  7363. } else {
  7364. self.exec('insertimage', url, title, width, height, border, align);
  7365. }
  7366. setTimeout(function() {
  7367. self.hideDialog().focus();
  7368. }, 0);
  7369. }
  7370. });
  7371. },
  7372. 'delete' : function() {
  7373. var target = self.plugin.getSelectedImage();
  7374. if (target.parent().name == 'a') {
  7375. target = target.parent();
  7376. }
  7377. target.remove();
  7378. self.addBookmark();
  7379. }
  7380. };
  7381. self.clickToolbar(name, self.plugin.image.edit);
  7382. });
  7383. /*******************************************************************************
  7384. * KindEditor - WYSIWYG HTML Editor for Internet
  7385. * Copyright (C) 2006-2011 kindsoft.net
  7386. *
  7387. * @author Roddy <luolonghao@gmail.com>
  7388. * @site http://www.kindsoft.net/
  7389. * @licence http://www.kindsoft.net/license.php
  7390. *******************************************************************************/
  7391. KindEditor.plugin('insertfile', function(K) {
  7392. var self = this, name = 'insertfile',
  7393. allowFileUpload = K.undef(self.allowFileUpload, true),
  7394. allowFileManager = K.undef(self.allowFileManager, false),
  7395. formatUploadUrl = K.undef(self.formatUploadUrl, true),
  7396. uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
  7397. extraParams = K.undef(self.extraFileUploadParams, {}),
  7398. filePostName = K.undef(self.filePostName, 'imgFile'),
  7399. lang = self.lang(name + '.');
  7400. self.plugin.fileDialog = function(options) {
  7401. var fileUrl = K.undef(options.fileUrl, 'http://'),
  7402. fileTitle = K.undef(options.fileTitle, ''),
  7403. clickFn = options.clickFn;
  7404. var html = [
  7405. '<div style="padding:20px;">',
  7406. '<div class="ke-dialog-row">',
  7407. '<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
  7408. '<input type="text" id="keUrl" name="url" class="ke-input-text" style="width:160px;" /> &nbsp;',
  7409. '<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> &nbsp;',
  7410. '<span class="ke-button-common ke-button-outer">',
  7411. '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
  7412. '</span>',
  7413. '</div>',
  7414. '<div class="ke-dialog-row">',
  7415. '<label for="keTitle" style="width:60px;">' + lang.title + '</label>',
  7416. '<input type="text" id="keTitle" class="ke-input-text" name="title" value="" style="width:160px;" /></div>',
  7417. '</div>',
  7418. '</form>',
  7419. '</div>'
  7420. ].join('');
  7421. var dialog = self.createDialog({
  7422. name : name,
  7423. width : 450,
  7424. title : self.lang(name),
  7425. body : html,
  7426. yesBtn : {
  7427. name : self.lang('yes'),
  7428. click : function(e) {
  7429. var url = K.trim(urlBox.val()),
  7430. title = titleBox.val();
  7431. if (url == 'http://' || K.invalidUrl(url)) {
  7432. alert(self.lang('invalidUrl'));
  7433. urlBox[0].focus();
  7434. return;
  7435. }
  7436. if (K.trim(title) === '') {
  7437. title = url;
  7438. }
  7439. clickFn.call(self, url, title);
  7440. }
  7441. }
  7442. }),
  7443. div = dialog.div;
  7444. var urlBox = K('[name="url"]', div),
  7445. viewServerBtn = K('[name="viewServer"]', div),
  7446. titleBox = K('[name="title"]', div);
  7447. if (allowFileUpload) {
  7448. var uploadbutton = K.uploadbutton({
  7449. button : K('.ke-upload-button', div)[0],
  7450. fieldName : filePostName,
  7451. url : K.addParam(uploadJson, 'dir=file'),
  7452. extraParams : extraParams,
  7453. afterUpload : function(data) {
  7454. dialog.hideLoading();
  7455. if (data.error === 0) {
  7456. var url = data.url;
  7457. if (formatUploadUrl) {
  7458. url = K.formatUrl(url, 'absolute');
  7459. }
  7460. urlBox.val(url);
  7461. if (self.afterUpload) {
  7462. self.afterUpload.call(self, url, data, name);
  7463. }
  7464. alert(self.lang('uploadSuccess'));
  7465. } else {
  7466. alert(data.message);
  7467. }
  7468. },
  7469. afterError : function(html) {
  7470. dialog.hideLoading();
  7471. self.errorDialog(html);
  7472. }
  7473. });
  7474. uploadbutton.fileBox.change(function(e) {
  7475. dialog.showLoading(self.lang('uploadLoading'));
  7476. uploadbutton.submit();
  7477. });
  7478. } else {
  7479. K('.ke-upload-button', div).hide();
  7480. }
  7481. if (allowFileManager) {
  7482. viewServerBtn.click(function(e) {
  7483. self.loadPlugin('filemanager', function() {
  7484. self.plugin.filemanagerDialog({
  7485. viewType : 'LIST',
  7486. dirName : 'file',
  7487. clickFn : function(url, title) {
  7488. if (self.dialogs.length > 1) {
  7489. K('[name="url"]', div).val(url);
  7490. if (self.afterSelectFile) {
  7491. self.afterSelectFile.call(self, url);
  7492. }
  7493. self.hideDialog();
  7494. }
  7495. }
  7496. });
  7497. });
  7498. });
  7499. } else {
  7500. viewServerBtn.hide();
  7501. }
  7502. urlBox.val(fileUrl);
  7503. titleBox.val(fileTitle);
  7504. urlBox[0].focus();
  7505. urlBox[0].select();
  7506. };
  7507. self.clickToolbar(name, function() {
  7508. self.plugin.fileDialog({
  7509. clickFn : function(url, title) {
  7510. var html = '<a class="ke-insertfile" href="' + url + '" data-ke-src="' + url + '" target="_blank">' + title + '</a>';
  7511. self.insertHtml(html).hideDialog().focus();
  7512. }
  7513. });
  7514. });
  7515. });
  7516. /*******************************************************************************
  7517. * KindEditor - WYSIWYG HTML Editor for Internet
  7518. * Copyright (C) 2006-2011 kindsoft.net
  7519. *
  7520. * @author Roddy <luolonghao@gmail.com>
  7521. * @site http://www.kindsoft.net/
  7522. * @licence http://www.kindsoft.net/license.php
  7523. *******************************************************************************/
  7524. KindEditor.plugin('lineheight', function(K) {
  7525. var self = this, name = 'lineheight', lang = self.lang(name + '.');
  7526. self.clickToolbar(name, function() {
  7527. var curVal = '', commonNode = self.cmd.commonNode({'*' : '.line-height'});
  7528. if (commonNode) {
  7529. curVal = commonNode.css('line-height');
  7530. }
  7531. var menu = self.createMenu({
  7532. name : name,
  7533. width : 150
  7534. });
  7535. K.each(lang.lineHeight, function(i, row) {
  7536. K.each(row, function(key, val) {
  7537. menu.addItem({
  7538. title : val,
  7539. checked : curVal === key,
  7540. click : function() {
  7541. self.cmd.toggle('<span style="line-height:' + key + ';"></span>', {
  7542. span : '.line-height=' + key
  7543. });
  7544. self.updateState();
  7545. self.addBookmark();
  7546. self.hideMenu();
  7547. }
  7548. });
  7549. });
  7550. });
  7551. });
  7552. });
  7553. /*******************************************************************************
  7554. * KindEditor - WYSIWYG HTML Editor for Internet
  7555. * Copyright (C) 2006-2011 kindsoft.net
  7556. *
  7557. * @author Roddy <luolonghao@gmail.com>
  7558. * @site http://www.kindsoft.net/
  7559. * @licence http://www.kindsoft.net/license.php
  7560. *******************************************************************************/
  7561. KindEditor.plugin('link', function(K) {
  7562. var self = this, name = 'link';
  7563. self.plugin.link = {
  7564. edit : function() {
  7565. var lang = self.lang(name + '.'),
  7566. html = '<div style="padding:20px;">' +
  7567. '<div class="ke-dialog-row">' +
  7568. '<label for="keUrl" style="width:60px;">' + lang.url + '</label>' +
  7569. '<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:260px;" /></div>' +
  7570. '<div class="ke-dialog-row"">' +
  7571. '<label for="keType" style="width:60px;">' + lang.linkType + '</label>' +
  7572. '<select id="keType" name="type"></select>' +
  7573. '</div>' +
  7574. '</div>',
  7575. dialog = self.createDialog({
  7576. name : name,
  7577. width : 450,
  7578. title : self.lang(name),
  7579. body : html,
  7580. yesBtn : {
  7581. name : self.lang('yes'),
  7582. click : function(e) {
  7583. var url = K.trim(urlBox.val());
  7584. if (url == 'http://' || K.invalidUrl(url)) {
  7585. alert(self.lang('invalidUrl'));
  7586. urlBox[0].focus();
  7587. return;
  7588. }
  7589. self.exec('createlink', url, typeBox.val()).hideDialog().focus();
  7590. }
  7591. }
  7592. }),
  7593. div = dialog.div,
  7594. urlBox = K('input[name="url"]', div),
  7595. typeBox = K('select[name="type"]', div);
  7596. urlBox.val('http://');
  7597. typeBox[0].options[0] = new Option(lang.newWindow, '_blank');
  7598. typeBox[0].options[1] = new Option(lang.selfWindow, '');
  7599. self.cmd.selection();
  7600. var a = self.plugin.getSelectedLink();
  7601. if (a) {
  7602. self.cmd.range.selectNode(a[0]);
  7603. self.cmd.select();
  7604. urlBox.val(a.attr('data-ke-src'));
  7605. typeBox.val(a.attr('target'));
  7606. }
  7607. urlBox[0].focus();
  7608. urlBox[0].select();
  7609. },
  7610. 'delete' : function() {
  7611. self.exec('unlink', null);
  7612. }
  7613. };
  7614. self.clickToolbar(name, self.plugin.link.edit);
  7615. });
  7616. /*******************************************************************************
  7617. * KindEditor - WYSIWYG HTML Editor for Internet
  7618. * Copyright (C) 2006-2011 kindsoft.net
  7619. *
  7620. * @author Roddy <luolonghao@gmail.com>
  7621. * @site http://www.kindsoft.net/
  7622. * @licence http://www.kindsoft.net/license.php
  7623. *******************************************************************************/
  7624. KindEditor.plugin('media', function(K) {
  7625. var self = this, name = 'media', lang = self.lang(name + '.'),
  7626. allowMediaUpload = K.undef(self.allowMediaUpload, true),
  7627. allowFileManager = K.undef(self.allowFileManager, false),
  7628. formatUploadUrl = K.undef(self.formatUploadUrl, true),
  7629. extraParams = K.undef(self.extraFileUploadParams, {}),
  7630. filePostName = K.undef(self.filePostName, 'imgFile'),
  7631. uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php');
  7632. self.plugin.media = {
  7633. edit : function() {
  7634. var html = [
  7635. '<div style="padding:20px;">',
  7636. '<div class="ke-dialog-row">',
  7637. '<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
  7638. '<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:160px;" /> &nbsp;',
  7639. '<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> &nbsp;',
  7640. '<span class="ke-button-common ke-button-outer">',
  7641. '<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
  7642. '</span>',
  7643. '</div>',
  7644. '<div class="ke-dialog-row">',
  7645. '<label for="keWidth" style="width:60px;">' + lang.width + '</label>',
  7646. '<input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="550" maxlength="4" />',
  7647. '</div>',
  7648. '<div class="ke-dialog-row">',
  7649. '<label for="keHeight" style="width:60px;">' + lang.height + '</label>',
  7650. '<input type="text" id="keHeight" class="ke-input-text ke-input-number" name="height" value="400" maxlength="4" />',
  7651. '</div>',
  7652. '<div class="ke-dialog-row">',
  7653. '<label for="keAutostart">' + lang.autostart + '</label>',
  7654. '<input type="checkbox" id="keAutostart" name="autostart" value="" /> ',
  7655. '</div>',
  7656. '</div>'
  7657. ].join('');
  7658. var dialog = self.createDialog({
  7659. name : name,
  7660. width : 450,
  7661. height : 230,
  7662. title : self.lang(name),
  7663. body : html,
  7664. yesBtn : {
  7665. name : self.lang('yes'),
  7666. click : function(e) {
  7667. var url = K.trim(urlBox.val()),
  7668. width = widthBox.val(),
  7669. height = heightBox.val();
  7670. if (url == 'http://' || K.invalidUrl(url)) {
  7671. alert(self.lang('invalidUrl'));
  7672. urlBox[0].focus();
  7673. return;
  7674. }
  7675. if (!/^\d*$/.test(width)) {
  7676. alert(self.lang('invalidWidth'));
  7677. widthBox[0].focus();
  7678. return;
  7679. }
  7680. if (!/^\d*$/.test(height)) {
  7681. alert(self.lang('invalidHeight'));
  7682. heightBox[0].focus();
  7683. return;
  7684. }
  7685. var html = K.mediaImg(self.themesPath + 'common/blank.gif', {
  7686. src : url,
  7687. type : K.mediaType(url),
  7688. width : width,
  7689. height : height,
  7690. autostart : autostartBox[0].checked ? 'true' : 'false',
  7691. loop : 'true'
  7692. });
  7693. self.insertHtml(html).hideDialog().focus();
  7694. }
  7695. }
  7696. }),
  7697. div = dialog.div,
  7698. urlBox = K('[name="url"]', div),
  7699. viewServerBtn = K('[name="viewServer"]', div),
  7700. widthBox = K('[name="width"]', div),
  7701. heightBox = K('[name="height"]', div),
  7702. autostartBox = K('[name="autostart"]', div);
  7703. urlBox.val('http://');
  7704. if (allowMediaUpload) {
  7705. var uploadbutton = K.uploadbutton({
  7706. button : K('.ke-upload-button', div)[0],
  7707. fieldName : filePostName,
  7708. extraParams : extraParams,
  7709. url : K.addParam(uploadJson, 'dir=media'),
  7710. afterUpload : function(data) {
  7711. dialog.hideLoading();
  7712. if (data.error === 0) {
  7713. var url = data.url;
  7714. if (formatUploadUrl) {
  7715. url = K.formatUrl(url, 'absolute');
  7716. }
  7717. urlBox.val(url);
  7718. if (self.afterUpload) {
  7719. self.afterUpload.call(self, url, data, name);
  7720. }
  7721. alert(self.lang('uploadSuccess'));
  7722. } else {
  7723. alert(data.message);
  7724. }
  7725. },
  7726. afterError : function(html) {
  7727. dialog.hideLoading();
  7728. self.errorDialog(html);
  7729. }
  7730. });
  7731. uploadbutton.fileBox.change(function(e) {
  7732. dialog.showLoading(self.lang('uploadLoading'));
  7733. uploadbutton.submit();
  7734. });
  7735. } else {
  7736. K('.ke-upload-button', div).hide();
  7737. }
  7738. if (allowFileManager) {
  7739. viewServerBtn.click(function(e) {
  7740. self.loadPlugin('filemanager', function() {
  7741. self.plugin.filemanagerDialog({
  7742. viewType : 'LIST',
  7743. dirName : 'media',
  7744. clickFn : function(url, title) {
  7745. if (self.dialogs.length > 1) {
  7746. K('[name="url"]', div).val(url);
  7747. if (self.afterSelectFile) {
  7748. self.afterSelectFile.call(self, url);
  7749. }
  7750. self.hideDialog();
  7751. }
  7752. }
  7753. });
  7754. });
  7755. });
  7756. } else {
  7757. viewServerBtn.hide();
  7758. }
  7759. var img = self.plugin.getSelectedMedia();
  7760. if (img) {
  7761. var attrs = K.mediaAttrs(img.attr('data-ke-tag'));
  7762. urlBox.val(attrs.src);
  7763. widthBox.val(K.removeUnit(img.css('width')) || attrs.width || 0);
  7764. heightBox.val(K.removeUnit(img.css('height')) || attrs.height || 0);
  7765. autostartBox[0].checked = (attrs.autostart === 'true');
  7766. }
  7767. urlBox[0].focus();
  7768. urlBox[0].select();
  7769. },
  7770. 'delete' : function() {
  7771. self.plugin.getSelectedMedia().remove();
  7772. self.addBookmark();
  7773. }
  7774. };
  7775. self.clickToolbar(name, self.plugin.media.edit);
  7776. });
  7777. /*******************************************************************************
  7778. * KindEditor - WYSIWYG HTML Editor for Internet
  7779. * Copyright (C) 2006-2011 kindsoft.net
  7780. *
  7781. * @author Roddy <luolonghao@gmail.com>
  7782. * @site http://www.kindsoft.net/
  7783. * @licence http://www.kindsoft.net/license.php
  7784. *******************************************************************************/
  7785. (function(K) {
  7786. function KSWFUpload(options) {
  7787. this.init(options);
  7788. }
  7789. K.extend(KSWFUpload, {
  7790. init : function(options) {
  7791. var self = this;
  7792. options.afterError = options.afterError || function(str) {
  7793. alert(str);
  7794. };
  7795. self.options = options;
  7796. self.progressbars = {};
  7797. self.div = K(options.container).html([
  7798. '<div class="ke-swfupload">',
  7799. '<div class="ke-swfupload-top">',
  7800. '<div class="ke-inline-block ke-swfupload-button">',
  7801. '<input type="button" value="Browse" />',
  7802. '</div>',
  7803. '<div class="ke-inline-block ke-swfupload-desc">' + options.uploadDesc + '</div>',
  7804. '<span class="ke-button-common ke-button-outer ke-swfupload-startupload">',
  7805. '<input type="button" class="ke-button-common ke-button" value="' + options.startButtonValue + '" />',
  7806. '</span>',
  7807. '</div>',
  7808. '<div class="ke-swfupload-body"></div>',
  7809. '</div>'
  7810. ].join(''));
  7811. self.bodyDiv = K('.ke-swfupload-body', self.div);
  7812. function showError(itemDiv, msg) {
  7813. K('.ke-status > div', itemDiv).hide();
  7814. K('.ke-message', itemDiv).addClass('ke-error').show().html(K.escape(msg));
  7815. }
  7816. var settings = {
  7817. debug : false,
  7818. upload_url : options.uploadUrl,
  7819. flash_url : options.flashUrl,
  7820. file_post_name : options.filePostName,
  7821. button_placeholder : K('.ke-swfupload-button > input', self.div)[0],
  7822. button_image_url: options.buttonImageUrl,
  7823. button_width: options.buttonWidth,
  7824. button_height: options.buttonHeight,
  7825. button_cursor : SWFUpload.CURSOR.HAND,
  7826. file_types : options.fileTypes,
  7827. file_types_description : options.fileTypesDesc,
  7828. file_upload_limit : options.fileUploadLimit,
  7829. file_size_limit : options.fileSizeLimit,
  7830. post_params : options.postParams,
  7831. file_queued_handler : function(file) {
  7832. file.url = self.options.fileIconUrl;
  7833. self.appendFile(file);
  7834. },
  7835. file_queue_error_handler : function(file, errorCode, message) {
  7836. var errorName = '';
  7837. switch (errorCode) {
  7838. case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
  7839. errorName = options.queueLimitExceeded;
  7840. break;
  7841. case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
  7842. errorName = options.fileExceedsSizeLimit;
  7843. break;
  7844. case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
  7845. errorName = options.zeroByteFile;
  7846. break;
  7847. case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
  7848. errorName = options.invalidFiletype;
  7849. break;
  7850. default:
  7851. errorName = options.unknownError;
  7852. break;
  7853. }
  7854. K.DEBUG && alert(errorName);
  7855. },
  7856. upload_start_handler : function(file) {
  7857. var self = this;
  7858. var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv);
  7859. K('.ke-status > div', itemDiv).hide();
  7860. K('.ke-progressbar', itemDiv).show();
  7861. },
  7862. upload_progress_handler : function(file, bytesLoaded, bytesTotal) {
  7863. var percent = Math.round(bytesLoaded * 100 / bytesTotal);
  7864. var progressbar = self.progressbars[file.id];
  7865. progressbar.bar.css('width', Math.round(percent * 80 / 100) + 'px');
  7866. progressbar.percent.html(percent + '%');
  7867. },
  7868. upload_error_handler : function(file, errorCode, message) {
  7869. if (file && file.filestatus == SWFUpload.FILE_STATUS.ERROR) {
  7870. var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0);
  7871. showError(itemDiv, self.options.errorMessage);
  7872. }
  7873. },
  7874. upload_success_handler : function(file, serverData) {
  7875. var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0);
  7876. var data = {};
  7877. try {
  7878. data = K.json(serverData);
  7879. } catch (e) {
  7880. self.options.afterError.call(this, '<!doctype html><html>' + serverData + '</html>');
  7881. }
  7882. if (data.error !== 0) {
  7883. showError(itemDiv, K.DEBUG ? data.message : self.options.errorMessage);
  7884. return;
  7885. }
  7886. file.url = data.url;
  7887. K('.ke-img', itemDiv).attr('src', file.url).attr('data-status', file.filestatus).data('data', data);
  7888. K('.ke-status > div', itemDiv).hide();
  7889. }
  7890. };
  7891. self.swfu = new SWFUpload(settings);
  7892. K('.ke-swfupload-startupload input', self.div).click(function() {
  7893. self.swfu.startUpload();
  7894. });
  7895. },
  7896. getUrlList : function() {
  7897. var list = [];
  7898. K('.ke-img', self.bodyDiv).each(function() {
  7899. var img = K(this);
  7900. var status = img.attr('data-status');
  7901. if (status == SWFUpload.FILE_STATUS.COMPLETE) {
  7902. list.push(img.data('data'));
  7903. }
  7904. });
  7905. return list;
  7906. },
  7907. removeFile : function(fileId) {
  7908. var self = this;
  7909. self.swfu.cancelUpload(fileId);
  7910. var itemDiv = K('div[data-id="' + fileId + '"]', self.bodyDiv);
  7911. K('.ke-photo', itemDiv).unbind();
  7912. K('.ke-delete', itemDiv).unbind();
  7913. itemDiv.remove();
  7914. },
  7915. removeFiles : function() {
  7916. var self = this;
  7917. K('.ke-item', self.bodyDiv).each(function() {
  7918. self.removeFile(K(this).attr('data-id'));
  7919. });
  7920. },
  7921. appendFile : function(file) {
  7922. var self = this;
  7923. var itemDiv = K('<div class="ke-inline-block ke-item" data-id="' + file.id + '"></div>');
  7924. self.bodyDiv.append(itemDiv);
  7925. var photoDiv = K('<div class="ke-inline-block ke-photo"></div>')
  7926. .mouseover(function(e) {
  7927. K(this).addClass('ke-on');
  7928. })
  7929. .mouseout(function(e) {
  7930. K(this).removeClass('ke-on');
  7931. });
  7932. itemDiv.append(photoDiv);
  7933. var img = K('<img src="' + file.url + '" class="ke-img" data-status="' + file.filestatus + '" width="80" height="80" alt="' + file.name + '" />');
  7934. photoDiv.append(img);
  7935. K('<span class="ke-delete"></span>').appendTo(photoDiv).click(function() {
  7936. self.removeFile(file.id);
  7937. });
  7938. var statusDiv = K('<div class="ke-status"></div>').appendTo(photoDiv);
  7939. K(['<div class="ke-progressbar">',
  7940. '<div class="ke-progressbar-bar"><div class="ke-progressbar-bar-inner"></div></div>',
  7941. '<div class="ke-progressbar-percent">0%</div></div>'].join('')).hide().appendTo(statusDiv);
  7942. K('<div class="ke-message">' + self.options.pendingMessage + '</div>').appendTo(statusDiv);
  7943. itemDiv.append('<div class="ke-name">' + file.name + '</div>');
  7944. self.progressbars[file.id] = {
  7945. bar : K('.ke-progressbar-bar-inner', photoDiv),
  7946. percent : K('.ke-progressbar-percent', photoDiv)
  7947. };
  7948. },
  7949. remove : function() {
  7950. this.removeFiles();
  7951. this.swfu.destroy();
  7952. this.div.html('');
  7953. }
  7954. });
  7955. K.swfupload = function(element, options) {
  7956. return new KSWFUpload(element, options);
  7957. };
  7958. })(KindEditor);
  7959. KindEditor.plugin('multiimage', function(K) {
  7960. var self = this, name = 'multiimage',
  7961. formatUploadUrl = K.undef(self.formatUploadUrl, true),
  7962. uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
  7963. imgPath = self.pluginsPath + 'multiimage/images/',
  7964. imageSizeLimit = K.undef(self.imageSizeLimit, '1MB'),
  7965. imageFileTypes = K.undef(self.imageFileTypes, '*.jpg;*.gif;*.png'),
  7966. imageUploadLimit = K.undef(self.imageUploadLimit, 20),
  7967. filePostName = K.undef(self.filePostName, 'imgFile'),
  7968. lang = self.lang(name + '.');
  7969. self.plugin.multiImageDialog = function(options) {
  7970. var clickFn = options.clickFn,
  7971. uploadDesc = K.tmpl(lang.uploadDesc, {uploadLimit : imageUploadLimit, sizeLimit : imageSizeLimit});
  7972. var html = [
  7973. '<div style="padding:20px;">',
  7974. '<div class="swfupload">',
  7975. '</div>',
  7976. '</div>'
  7977. ].join('');
  7978. var dialog = self.createDialog({
  7979. name : name,
  7980. width : 650,
  7981. height : 510,
  7982. title : self.lang(name),
  7983. body : html,
  7984. previewBtn : {
  7985. name : lang.insertAll,
  7986. click : function(e) {
  7987. clickFn.call(self, swfupload.getUrlList());
  7988. }
  7989. },
  7990. yesBtn : {
  7991. name : lang.clearAll,
  7992. click : function(e) {
  7993. swfupload.removeFiles();
  7994. }
  7995. },
  7996. beforeRemove : function() {
  7997. if (!K.IE || K.V <= 8) {
  7998. swfupload.remove();
  7999. }
  8000. }
  8001. }),
  8002. div = dialog.div;
  8003. var swfupload = K.swfupload({
  8004. container : K('.swfupload', div),
  8005. buttonImageUrl : imgPath + (self.langType == 'zh-CN' ? 'select-files-zh-CN.png' : 'select-files-en.png'),
  8006. buttonWidth : self.langType == 'zh-CN' ? 72 : 88,
  8007. buttonHeight : 23,
  8008. fileIconUrl : imgPath + 'image.png',
  8009. uploadDesc : uploadDesc,
  8010. startButtonValue : lang.startUpload,
  8011. uploadUrl : K.addParam(uploadJson, 'dir=image'),
  8012. flashUrl : imgPath + 'swfupload.swf',
  8013. filePostName : filePostName,
  8014. fileTypes : '*.jpg;*.jpeg;*.gif;*.png;*.bmp',
  8015. fileTypesDesc : 'Image Files',
  8016. fileUploadLimit : imageUploadLimit,
  8017. fileSizeLimit : imageSizeLimit,
  8018. postParams : K.undef(self.extraFileUploadParams, {}),
  8019. queueLimitExceeded : lang.queueLimitExceeded,
  8020. fileExceedsSizeLimit : lang.fileExceedsSizeLimit,
  8021. zeroByteFile : lang.zeroByteFile,
  8022. invalidFiletype : lang.invalidFiletype,
  8023. unknownError : lang.unknownError,
  8024. pendingMessage : lang.pending,
  8025. errorMessage : lang.uploadError,
  8026. afterError : function(html) {
  8027. self.errorDialog(html);
  8028. }
  8029. });
  8030. return dialog;
  8031. };
  8032. self.clickToolbar(name, function() {
  8033. self.plugin.multiImageDialog({
  8034. clickFn : function (urlList) {
  8035. if (urlList.length === 0) {
  8036. return;
  8037. }
  8038. K.each(urlList, function(i, data) {
  8039. if (self.afterUpload) {
  8040. self.afterUpload.call(self, data.url, data, 'multiimage');
  8041. }
  8042. self.exec('insertimage', data.url, data.title, data.width, data.height, data.border, data.align);
  8043. });
  8044. setTimeout(function() {
  8045. self.hideDialog().focus();
  8046. }, 0);
  8047. }
  8048. });
  8049. });
  8050. });
  8051. /* ******************* */
  8052. /* Constructor & Init */
  8053. /* ******************* */
  8054. (function() {
  8055. window.SWFUpload = function (settings) {
  8056. this.initSWFUpload(settings);
  8057. };
  8058. SWFUpload.prototype.initSWFUpload = function (settings) {
  8059. try {
  8060. this.customSettings = {};
  8061. this.settings = settings;
  8062. this.eventQueue = [];
  8063. this.movieName = "KindEditor_SWFUpload_" + SWFUpload.movieCount++;
  8064. this.movieElement = null;
  8065. SWFUpload.instances[this.movieName] = this;
  8066. this.initSettings();
  8067. this.loadFlash();
  8068. this.displayDebugInfo();
  8069. } catch (ex) {
  8070. delete SWFUpload.instances[this.movieName];
  8071. throw ex;
  8072. }
  8073. };
  8074. /* *************** */
  8075. /* Static Members */
  8076. /* *************** */
  8077. SWFUpload.instances = {};
  8078. SWFUpload.movieCount = 0;
  8079. SWFUpload.version = "2.2.0 2009-03-25";
  8080. SWFUpload.QUEUE_ERROR = {
  8081. QUEUE_LIMIT_EXCEEDED : -100,
  8082. FILE_EXCEEDS_SIZE_LIMIT : -110,
  8083. ZERO_BYTE_FILE : -120,
  8084. INVALID_FILETYPE : -130
  8085. };
  8086. SWFUpload.UPLOAD_ERROR = {
  8087. HTTP_ERROR : -200,
  8088. MISSING_UPLOAD_URL : -210,
  8089. IO_ERROR : -220,
  8090. SECURITY_ERROR : -230,
  8091. UPLOAD_LIMIT_EXCEEDED : -240,
  8092. UPLOAD_FAILED : -250,
  8093. SPECIFIED_FILE_ID_NOT_FOUND : -260,
  8094. FILE_VALIDATION_FAILED : -270,
  8095. FILE_CANCELLED : -280,
  8096. UPLOAD_STOPPED : -290
  8097. };
  8098. SWFUpload.FILE_STATUS = {
  8099. QUEUED : -1,
  8100. IN_PROGRESS : -2,
  8101. ERROR : -3,
  8102. COMPLETE : -4,
  8103. CANCELLED : -5
  8104. };
  8105. SWFUpload.BUTTON_ACTION = {
  8106. SELECT_FILE : -100,
  8107. SELECT_FILES : -110,
  8108. START_UPLOAD : -120
  8109. };
  8110. SWFUpload.CURSOR = {
  8111. ARROW : -1,
  8112. HAND : -2
  8113. };
  8114. SWFUpload.WINDOW_MODE = {
  8115. WINDOW : "window",
  8116. TRANSPARENT : "transparent",
  8117. OPAQUE : "opaque"
  8118. };
  8119. SWFUpload.completeURL = function(url) {
  8120. if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
  8121. return url;
  8122. }
  8123. var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
  8124. var indexSlash = window.location.pathname.lastIndexOf("/");
  8125. if (indexSlash <= 0) {
  8126. path = "/";
  8127. } else {
  8128. path = window.location.pathname.substr(0, indexSlash) + "/";
  8129. }
  8130. return /*currentURL +*/ path + url;
  8131. };
  8132. /* ******************** */
  8133. /* Instance Members */
  8134. /* ******************** */
  8135. SWFUpload.prototype.initSettings = function () {
  8136. this.ensureDefault = function (settingName, defaultValue) {
  8137. this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
  8138. };
  8139. this.ensureDefault("upload_url", "");
  8140. this.ensureDefault("preserve_relative_urls", false);
  8141. this.ensureDefault("file_post_name", "Filedata");
  8142. this.ensureDefault("post_params", {});
  8143. this.ensureDefault("use_query_string", false);
  8144. this.ensureDefault("requeue_on_error", false);
  8145. this.ensureDefault("http_success", []);
  8146. this.ensureDefault("assume_success_timeout", 0);
  8147. this.ensureDefault("file_types", "*.*");
  8148. this.ensureDefault("file_types_description", "All Files");
  8149. this.ensureDefault("file_size_limit", 0);
  8150. this.ensureDefault("file_upload_limit", 0);
  8151. this.ensureDefault("file_queue_limit", 0);
  8152. this.ensureDefault("flash_url", "swfupload.swf");
  8153. this.ensureDefault("prevent_swf_caching", true);
  8154. this.ensureDefault("button_image_url", "");
  8155. this.ensureDefault("button_width", 1);
  8156. this.ensureDefault("button_height", 1);
  8157. this.ensureDefault("button_text", "");
  8158. this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
  8159. this.ensureDefault("button_text_top_padding", 0);
  8160. this.ensureDefault("button_text_left_padding", 0);
  8161. this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
  8162. this.ensureDefault("button_disabled", false);
  8163. this.ensureDefault("button_placeholder_id", "");
  8164. this.ensureDefault("button_placeholder", null);
  8165. this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
  8166. this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
  8167. this.ensureDefault("debug", false);
  8168. this.settings.debug_enabled = this.settings.debug;
  8169. this.settings.return_upload_start_handler = this.returnUploadStart;
  8170. this.ensureDefault("swfupload_loaded_handler", null);
  8171. this.ensureDefault("file_dialog_start_handler", null);
  8172. this.ensureDefault("file_queued_handler", null);
  8173. this.ensureDefault("file_queue_error_handler", null);
  8174. this.ensureDefault("file_dialog_complete_handler", null);
  8175. this.ensureDefault("upload_start_handler", null);
  8176. this.ensureDefault("upload_progress_handler", null);
  8177. this.ensureDefault("upload_error_handler", null);
  8178. this.ensureDefault("upload_success_handler", null);
  8179. this.ensureDefault("upload_complete_handler", null);
  8180. this.ensureDefault("debug_handler", this.debugMessage);
  8181. this.ensureDefault("custom_settings", {});
  8182. this.customSettings = this.settings.custom_settings;
  8183. if (!!this.settings.prevent_swf_caching) {
  8184. this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
  8185. }
  8186. if (!this.settings.preserve_relative_urls) {
  8187. this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
  8188. this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
  8189. }
  8190. delete this.ensureDefault;
  8191. };
  8192. SWFUpload.prototype.loadFlash = function () {
  8193. var targetElement, tempParent;
  8194. if (document.getElementById(this.movieName) !== null) {
  8195. throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
  8196. }
  8197. targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;
  8198. if (targetElement == undefined) {
  8199. throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
  8200. }
  8201. tempParent = document.createElement("div");
  8202. tempParent.innerHTML = this.getFlashHTML();
  8203. targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);
  8204. if (window[this.movieName] == undefined) {
  8205. window[this.movieName] = this.getMovieElement();
  8206. }
  8207. };
  8208. SWFUpload.prototype.getFlashHTML = function () {
  8209. var classid = '';
  8210. if (KindEditor.IE && KindEditor.V > 8) {
  8211. classid = ' classid = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';
  8212. }
  8213. return ['<object id="', this.movieName, '"' + classid + ' type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
  8214. '<param name="wmode" value="', this.settings.button_window_mode, '" />',
  8215. '<param name="movie" value="', this.settings.flash_url, '" />',
  8216. '<param name="quality" value="high" />',
  8217. '<param name="menu" value="false" />',
  8218. '<param name="allowScriptAccess" value="always" />',
  8219. '<param name="flashvars" value="' + this.getFlashVars() + '" />',
  8220. '</object>'].join("");
  8221. };
  8222. SWFUpload.prototype.getFlashVars = function () {
  8223. var paramString = this.buildParamString();
  8224. var httpSuccessString = this.settings.http_success.join(",");
  8225. return ["movieName=", encodeURIComponent(this.movieName),
  8226. "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
  8227. "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
  8228. "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
  8229. "&amp;httpSuccess=", encodeURIComponent(httpSuccessString),
  8230. "&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
  8231. "&amp;params=", encodeURIComponent(paramString),
  8232. "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
  8233. "&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
  8234. "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
  8235. "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
  8236. "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
  8237. "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
  8238. "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
  8239. "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
  8240. "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
  8241. "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
  8242. "&amp;buttonText=", encodeURIComponent(this.settings.button_text),
  8243. "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
  8244. "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
  8245. "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
  8246. "&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
  8247. "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
  8248. "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)
  8249. ].join("");
  8250. };
  8251. SWFUpload.prototype.getMovieElement = function () {
  8252. if (this.movieElement == undefined) {
  8253. this.movieElement = document.getElementById(this.movieName);
  8254. }
  8255. if (this.movieElement === null) {
  8256. throw "Could not find Flash element";
  8257. }
  8258. return this.movieElement;
  8259. };
  8260. SWFUpload.prototype.buildParamString = function () {
  8261. var postParams = this.settings.post_params;
  8262. var paramStringPairs = [];
  8263. if (typeof(postParams) === "object") {
  8264. for (var name in postParams) {
  8265. if (postParams.hasOwnProperty(name)) {
  8266. paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
  8267. }
  8268. }
  8269. }
  8270. return paramStringPairs.join("&amp;");
  8271. };
  8272. SWFUpload.prototype.destroy = function () {
  8273. try {
  8274. this.cancelUpload(null, false);
  8275. var movieElement = null;
  8276. movieElement = this.getMovieElement();
  8277. if (movieElement && typeof(movieElement.CallFunction) === "unknown") {
  8278. for (var i in movieElement) {
  8279. try {
  8280. if (typeof(movieElement[i]) === "function") {
  8281. movieElement[i] = null;
  8282. }
  8283. } catch (ex1) {}
  8284. }
  8285. try {
  8286. movieElement.parentNode.removeChild(movieElement);
  8287. } catch (ex) {}
  8288. }
  8289. window[this.movieName] = null;
  8290. SWFUpload.instances[this.movieName] = null;
  8291. delete SWFUpload.instances[this.movieName];
  8292. this.movieElement = null;
  8293. this.settings = null;
  8294. this.customSettings = null;
  8295. this.eventQueue = null;
  8296. this.movieName = null;
  8297. return true;
  8298. } catch (ex2) {
  8299. return false;
  8300. }
  8301. };
  8302. SWFUpload.prototype.displayDebugInfo = function () {
  8303. this.debug(
  8304. [
  8305. "---SWFUpload Instance Info---\n",
  8306. "Version: ", SWFUpload.version, "\n",
  8307. "Movie Name: ", this.movieName, "\n",
  8308. "Settings:\n",
  8309. "\t", "upload_url: ", this.settings.upload_url, "\n",
  8310. "\t", "flash_url: ", this.settings.flash_url, "\n",
  8311. "\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n",
  8312. "\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n",
  8313. "\t", "http_success: ", this.settings.http_success.join(", "), "\n",
  8314. "\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n",
  8315. "\t", "file_post_name: ", this.settings.file_post_name, "\n",
  8316. "\t", "post_params: ", this.settings.post_params.toString(), "\n",
  8317. "\t", "file_types: ", this.settings.file_types, "\n",
  8318. "\t", "file_types_description: ", this.settings.file_types_description, "\n",
  8319. "\t", "file_size_limit: ", this.settings.file_size_limit, "\n",
  8320. "\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n",
  8321. "\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n",
  8322. "\t", "debug: ", this.settings.debug.toString(), "\n",
  8323. "\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n",
  8324. "\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n",
  8325. "\t", "button_placeholder: ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
  8326. "\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n",
  8327. "\t", "button_width: ", this.settings.button_width.toString(), "\n",
  8328. "\t", "button_height: ", this.settings.button_height.toString(), "\n",
  8329. "\t", "button_text: ", this.settings.button_text.toString(), "\n",
  8330. "\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n",
  8331. "\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n",
  8332. "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
  8333. "\t", "button_action: ", this.settings.button_action.toString(), "\n",
  8334. "\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n",
  8335. "\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n",
  8336. "Event Handlers:\n",
  8337. "\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
  8338. "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
  8339. "\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
  8340. "\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
  8341. "\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
  8342. "\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
  8343. "\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
  8344. "\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
  8345. "\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
  8346. "\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n"
  8347. ].join("")
  8348. );
  8349. };
  8350. /* Note: addSetting and getSetting are no longer used by SWFUpload but are included
  8351. the maintain v2 API compatibility
  8352. */
  8353. SWFUpload.prototype.addSetting = function (name, value, default_value) {
  8354. if (value == undefined) {
  8355. return (this.settings[name] = default_value);
  8356. } else {
  8357. return (this.settings[name] = value);
  8358. }
  8359. };
  8360. SWFUpload.prototype.getSetting = function (name) {
  8361. if (this.settings[name] != undefined) {
  8362. return this.settings[name];
  8363. }
  8364. return "";
  8365. };
  8366. SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
  8367. argumentArray = argumentArray || [];
  8368. var movieElement = this.getMovieElement();
  8369. var returnValue, returnString;
  8370. try {
  8371. returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
  8372. returnValue = eval(returnString);
  8373. } catch (ex) {
  8374. throw "Call to " + functionName + " failed";
  8375. }
  8376. if (returnValue != undefined && typeof returnValue.post === "object") {
  8377. returnValue = this.unescapeFilePostParams(returnValue);
  8378. }
  8379. return returnValue;
  8380. };
  8381. /* *****************************
  8382. -- Flash control methods --
  8383. Your UI should use these
  8384. to operate SWFUpload
  8385. ***************************** */
  8386. SWFUpload.prototype.selectFile = function () {
  8387. this.callFlash("SelectFile");
  8388. };
  8389. SWFUpload.prototype.selectFiles = function () {
  8390. this.callFlash("SelectFiles");
  8391. };
  8392. SWFUpload.prototype.startUpload = function (fileID) {
  8393. this.callFlash("StartUpload", [fileID]);
  8394. };
  8395. SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
  8396. if (triggerErrorEvent !== false) {
  8397. triggerErrorEvent = true;
  8398. }
  8399. this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
  8400. };
  8401. SWFUpload.prototype.stopUpload = function () {
  8402. this.callFlash("StopUpload");
  8403. };
  8404. /* ************************
  8405. * Settings methods
  8406. * These methods change the SWFUpload settings.
  8407. * SWFUpload settings should not be changed directly on the settings object
  8408. * since many of the settings need to be passed to Flash in order to take
  8409. * effect.
  8410. * *********************** */
  8411. SWFUpload.prototype.getStats = function () {
  8412. return this.callFlash("GetStats");
  8413. };
  8414. SWFUpload.prototype.setStats = function (statsObject) {
  8415. this.callFlash("SetStats", [statsObject]);
  8416. };
  8417. SWFUpload.prototype.getFile = function (fileID) {
  8418. if (typeof(fileID) === "number") {
  8419. return this.callFlash("GetFileByIndex", [fileID]);
  8420. } else {
  8421. return this.callFlash("GetFile", [fileID]);
  8422. }
  8423. };
  8424. SWFUpload.prototype.addFileParam = function (fileID, name, value) {
  8425. return this.callFlash("AddFileParam", [fileID, name, value]);
  8426. };
  8427. SWFUpload.prototype.removeFileParam = function (fileID, name) {
  8428. this.callFlash("RemoveFileParam", [fileID, name]);
  8429. };
  8430. SWFUpload.prototype.setUploadURL = function (url) {
  8431. this.settings.upload_url = url.toString();
  8432. this.callFlash("SetUploadURL", [url]);
  8433. };
  8434. SWFUpload.prototype.setPostParams = function (paramsObject) {
  8435. this.settings.post_params = paramsObject;
  8436. this.callFlash("SetPostParams", [paramsObject]);
  8437. };
  8438. SWFUpload.prototype.addPostParam = function (name, value) {
  8439. this.settings.post_params[name] = value;
  8440. this.callFlash("SetPostParams", [this.settings.post_params]);
  8441. };
  8442. SWFUpload.prototype.removePostParam = function (name) {
  8443. delete this.settings.post_params[name];
  8444. this.callFlash("SetPostParams", [this.settings.post_params]);
  8445. };
  8446. SWFUpload.prototype.setFileTypes = function (types, description) {
  8447. this.settings.file_types = types;
  8448. this.settings.file_types_description = description;
  8449. this.callFlash("SetFileTypes", [types, description]);
  8450. };
  8451. SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
  8452. this.settings.file_size_limit = fileSizeLimit;
  8453. this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
  8454. };
  8455. SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
  8456. this.settings.file_upload_limit = fileUploadLimit;
  8457. this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
  8458. };
  8459. SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
  8460. this.settings.file_queue_limit = fileQueueLimit;
  8461. this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
  8462. };
  8463. SWFUpload.prototype.setFilePostName = function (filePostName) {
  8464. this.settings.file_post_name = filePostName;
  8465. this.callFlash("SetFilePostName", [filePostName]);
  8466. };
  8467. SWFUpload.prototype.setUseQueryString = function (useQueryString) {
  8468. this.settings.use_query_string = useQueryString;
  8469. this.callFlash("SetUseQueryString", [useQueryString]);
  8470. };
  8471. SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
  8472. this.settings.requeue_on_error = requeueOnError;
  8473. this.callFlash("SetRequeueOnError", [requeueOnError]);
  8474. };
  8475. SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
  8476. if (typeof http_status_codes === "string") {
  8477. http_status_codes = http_status_codes.replace(" ", "").split(",");
  8478. }
  8479. this.settings.http_success = http_status_codes;
  8480. this.callFlash("SetHTTPSuccess", [http_status_codes]);
  8481. };
  8482. SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
  8483. this.settings.assume_success_timeout = timeout_seconds;
  8484. this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
  8485. };
  8486. SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
  8487. this.settings.debug_enabled = debugEnabled;
  8488. this.callFlash("SetDebugEnabled", [debugEnabled]);
  8489. };
  8490. SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
  8491. if (buttonImageURL == undefined) {
  8492. buttonImageURL = "";
  8493. }
  8494. this.settings.button_image_url = buttonImageURL;
  8495. this.callFlash("SetButtonImageURL", [buttonImageURL]);
  8496. };
  8497. SWFUpload.prototype.setButtonDimensions = function (width, height) {
  8498. this.settings.button_width = width;
  8499. this.settings.button_height = height;
  8500. var movie = this.getMovieElement();
  8501. if (movie != undefined) {
  8502. movie.style.width = width + "px";
  8503. movie.style.height = height + "px";
  8504. }
  8505. this.callFlash("SetButtonDimensions", [width, height]);
  8506. };
  8507. SWFUpload.prototype.setButtonText = function (html) {
  8508. this.settings.button_text = html;
  8509. this.callFlash("SetButtonText", [html]);
  8510. };
  8511. SWFUpload.prototype.setButtonTextPadding = function (left, top) {
  8512. this.settings.button_text_top_padding = top;
  8513. this.settings.button_text_left_padding = left;
  8514. this.callFlash("SetButtonTextPadding", [left, top]);
  8515. };
  8516. SWFUpload.prototype.setButtonTextStyle = function (css) {
  8517. this.settings.button_text_style = css;
  8518. this.callFlash("SetButtonTextStyle", [css]);
  8519. };
  8520. SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
  8521. this.settings.button_disabled = isDisabled;
  8522. this.callFlash("SetButtonDisabled", [isDisabled]);
  8523. };
  8524. SWFUpload.prototype.setButtonAction = function (buttonAction) {
  8525. this.settings.button_action = buttonAction;
  8526. this.callFlash("SetButtonAction", [buttonAction]);
  8527. };
  8528. SWFUpload.prototype.setButtonCursor = function (cursor) {
  8529. this.settings.button_cursor = cursor;
  8530. this.callFlash("SetButtonCursor", [cursor]);
  8531. };
  8532. /* *******************************
  8533. Flash Event Interfaces
  8534. These functions are used by Flash to trigger the various
  8535. events.
  8536. All these functions a Private.
  8537. Because the ExternalInterface library is buggy the event calls
  8538. are added to a queue and the queue then executed by a setTimeout.
  8539. This ensures that events are executed in a determinate order and that
  8540. the ExternalInterface bugs are avoided.
  8541. ******************************* */
  8542. SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
  8543. if (argumentArray == undefined) {
  8544. argumentArray = [];
  8545. } else if (!(argumentArray instanceof Array)) {
  8546. argumentArray = [argumentArray];
  8547. }
  8548. var self = this;
  8549. if (typeof this.settings[handlerName] === "function") {
  8550. this.eventQueue.push(function () {
  8551. this.settings[handlerName].apply(this, argumentArray);
  8552. });
  8553. setTimeout(function () {
  8554. self.executeNextEvent();
  8555. }, 0);
  8556. } else if (this.settings[handlerName] !== null) {
  8557. throw "Event handler " + handlerName + " is unknown or is not a function";
  8558. }
  8559. };
  8560. SWFUpload.prototype.executeNextEvent = function () {
  8561. var f = this.eventQueue ? this.eventQueue.shift() : null;
  8562. if (typeof(f) === "function") {
  8563. f.apply(this);
  8564. }
  8565. };
  8566. SWFUpload.prototype.unescapeFilePostParams = function (file) {
  8567. var reg = /[$]([0-9a-f]{4})/i;
  8568. var unescapedPost = {};
  8569. var uk;
  8570. if (file != undefined) {
  8571. for (var k in file.post) {
  8572. if (file.post.hasOwnProperty(k)) {
  8573. uk = k;
  8574. var match;
  8575. while ((match = reg.exec(uk)) !== null) {
  8576. uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
  8577. }
  8578. unescapedPost[uk] = file.post[k];
  8579. }
  8580. }
  8581. file.post = unescapedPost;
  8582. }
  8583. return file;
  8584. };
  8585. SWFUpload.prototype.testExternalInterface = function () {
  8586. try {
  8587. return this.callFlash("TestExternalInterface");
  8588. } catch (ex) {
  8589. return false;
  8590. }
  8591. };
  8592. SWFUpload.prototype.flashReady = function () {
  8593. var movieElement = this.getMovieElement();
  8594. if (!movieElement) {
  8595. this.debug("Flash called back ready but the flash movie can't be found.");
  8596. return;
  8597. }
  8598. this.cleanUp(movieElement);
  8599. this.queueEvent("swfupload_loaded_handler");
  8600. };
  8601. SWFUpload.prototype.cleanUp = function (movieElement) {
  8602. try {
  8603. if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") {
  8604. this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
  8605. for (var key in movieElement) {
  8606. try {
  8607. if (typeof(movieElement[key]) === "function") {
  8608. movieElement[key] = null;
  8609. }
  8610. } catch (ex) {
  8611. }
  8612. }
  8613. }
  8614. } catch (ex1) {
  8615. }
  8616. window["__flash__removeCallback"] = function (instance, name) {
  8617. try {
  8618. if (instance) {
  8619. instance[name] = null;
  8620. }
  8621. } catch (flashEx) {
  8622. }
  8623. };
  8624. };
  8625. /* This is a chance to do something before the browse window opens */
  8626. SWFUpload.prototype.fileDialogStart = function () {
  8627. this.queueEvent("file_dialog_start_handler");
  8628. };
  8629. /* Called when a file is successfully added to the queue. */
  8630. SWFUpload.prototype.fileQueued = function (file) {
  8631. file = this.unescapeFilePostParams(file);
  8632. this.queueEvent("file_queued_handler", file);
  8633. };
  8634. /* Handle errors that occur when an attempt to queue a file fails. */
  8635. SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
  8636. file = this.unescapeFilePostParams(file);
  8637. this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
  8638. };
  8639. /* Called after the file dialog has closed and the selected files have been queued.
  8640. You could call startUpload here if you want the queued files to begin uploading immediately. */
  8641. SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
  8642. this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
  8643. };
  8644. SWFUpload.prototype.uploadStart = function (file) {
  8645. file = this.unescapeFilePostParams(file);
  8646. this.queueEvent("return_upload_start_handler", file);
  8647. };
  8648. SWFUpload.prototype.returnUploadStart = function (file) {
  8649. var returnValue;
  8650. if (typeof this.settings.upload_start_handler === "function") {
  8651. file = this.unescapeFilePostParams(file);
  8652. returnValue = this.settings.upload_start_handler.call(this, file);
  8653. } else if (this.settings.upload_start_handler != undefined) {
  8654. throw "upload_start_handler must be a function";
  8655. }
  8656. if (returnValue === undefined) {
  8657. returnValue = true;
  8658. }
  8659. returnValue = !!returnValue;
  8660. this.callFlash("ReturnUploadStart", [returnValue]);
  8661. };
  8662. SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
  8663. file = this.unescapeFilePostParams(file);
  8664. this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
  8665. };
  8666. SWFUpload.prototype.uploadError = function (file, errorCode, message) {
  8667. file = this.unescapeFilePostParams(file);
  8668. this.queueEvent("upload_error_handler", [file, errorCode, message]);
  8669. };
  8670. SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
  8671. file = this.unescapeFilePostParams(file);
  8672. this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
  8673. };
  8674. SWFUpload.prototype.uploadComplete = function (file) {
  8675. file = this.unescapeFilePostParams(file);
  8676. this.queueEvent("upload_complete_handler", file);
  8677. };
  8678. /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
  8679. internal debug console. You can override this event and have messages written where you want. */
  8680. SWFUpload.prototype.debug = function (message) {
  8681. this.queueEvent("debug_handler", message);
  8682. };
  8683. /* **********************************
  8684. Debug Console
  8685. The debug console is a self contained, in page location
  8686. for debug message to be sent. The Debug Console adds
  8687. itself to the body if necessary.
  8688. The console is automatically scrolled as messages appear.
  8689. If you are using your own debug handler or when you deploy to production and
  8690. have debug disabled you can remove these functions to reduce the file size
  8691. and complexity.
  8692. ********************************** */
  8693. SWFUpload.prototype.debugMessage = function (message) {
  8694. if (this.settings.debug) {
  8695. var exceptionMessage, exceptionValues = [];
  8696. if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
  8697. for (var key in message) {
  8698. if (message.hasOwnProperty(key)) {
  8699. exceptionValues.push(key + ": " + message[key]);
  8700. }
  8701. }
  8702. exceptionMessage = exceptionValues.join("\n") || "";
  8703. exceptionValues = exceptionMessage.split("\n");
  8704. exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
  8705. SWFUpload.Console.writeLine(exceptionMessage);
  8706. } else {
  8707. SWFUpload.Console.writeLine(message);
  8708. }
  8709. }
  8710. };
  8711. SWFUpload.Console = {};
  8712. SWFUpload.Console.writeLine = function (message) {
  8713. var console, documentForm;
  8714. try {
  8715. console = document.getElementById("SWFUpload_Console");
  8716. if (!console) {
  8717. documentForm = document.createElement("form");
  8718. document.getElementsByTagName("body")[0].appendChild(documentForm);
  8719. console = document.createElement("textarea");
  8720. console.id = "SWFUpload_Console";
  8721. console.style.fontFamily = "monospace";
  8722. console.setAttribute("wrap", "off");
  8723. console.wrap = "off";
  8724. console.style.overflow = "auto";
  8725. console.style.width = "700px";
  8726. console.style.height = "350px";
  8727. console.style.margin = "5px";
  8728. documentForm.appendChild(console);
  8729. }
  8730. console.value += message + "\n";
  8731. console.scrollTop = console.scrollHeight - console.clientHeight;
  8732. } catch (ex) {
  8733. alert("Exception: " + ex.name + " Message: " + ex.message);
  8734. }
  8735. };
  8736. })();
  8737. (function() {
  8738. /*
  8739. Queue Plug-in
  8740. Features:
  8741. *Adds a cancelQueue() method for cancelling the entire queue.
  8742. *All queued files are uploaded when startUpload() is called.
  8743. *If false is returned from uploadComplete then the queue upload is stopped.
  8744. If false is not returned (strict comparison) then the queue upload is continued.
  8745. *Adds a QueueComplete event that is fired when all the queued files have finished uploading.
  8746. Set the event handler with the queue_complete_handler setting.
  8747. */
  8748. if (typeof(SWFUpload) === "function") {
  8749. SWFUpload.queue = {};
  8750. SWFUpload.prototype.initSettings = (function (oldInitSettings) {
  8751. return function () {
  8752. if (typeof(oldInitSettings) === "function") {
  8753. oldInitSettings.call(this);
  8754. }
  8755. this.queueSettings = {};
  8756. this.queueSettings.queue_cancelled_flag = false;
  8757. this.queueSettings.queue_upload_count = 0;
  8758. this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
  8759. this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
  8760. this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
  8761. this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
  8762. this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
  8763. };
  8764. })(SWFUpload.prototype.initSettings);
  8765. SWFUpload.prototype.startUpload = function (fileID) {
  8766. this.queueSettings.queue_cancelled_flag = false;
  8767. this.callFlash("StartUpload", [fileID]);
  8768. };
  8769. SWFUpload.prototype.cancelQueue = function () {
  8770. this.queueSettings.queue_cancelled_flag = true;
  8771. this.stopUpload();
  8772. var stats = this.getStats();
  8773. while (stats.files_queued > 0) {
  8774. this.cancelUpload();
  8775. stats = this.getStats();
  8776. }
  8777. };
  8778. SWFUpload.queue.uploadStartHandler = function (file) {
  8779. var returnValue;
  8780. if (typeof(this.queueSettings.user_upload_start_handler) === "function") {
  8781. returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
  8782. }
  8783. returnValue = (returnValue === false) ? false : true;
  8784. this.queueSettings.queue_cancelled_flag = !returnValue;
  8785. return returnValue;
  8786. };
  8787. SWFUpload.queue.uploadCompleteHandler = function (file) {
  8788. var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
  8789. var continueUpload;
  8790. if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
  8791. this.queueSettings.queue_upload_count++;
  8792. }
  8793. if (typeof(user_upload_complete_handler) === "function") {
  8794. continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
  8795. } else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
  8796. continueUpload = false;
  8797. } else {
  8798. continueUpload = true;
  8799. }
  8800. if (continueUpload) {
  8801. var stats = this.getStats();
  8802. if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
  8803. this.startUpload();
  8804. } else if (this.queueSettings.queue_cancelled_flag === false) {
  8805. this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
  8806. this.queueSettings.queue_upload_count = 0;
  8807. } else {
  8808. this.queueSettings.queue_cancelled_flag = false;
  8809. this.queueSettings.queue_upload_count = 0;
  8810. }
  8811. }
  8812. };
  8813. }
  8814. })();
  8815. /*******************************************************************************
  8816. * KindEditor - WYSIWYG HTML Editor for Internet
  8817. * Copyright (C) 2006-2011 kindsoft.net
  8818. *
  8819. * @author Roddy <luolonghao@gmail.com>
  8820. * @site http://www.kindsoft.net/
  8821. * @licence http://www.kindsoft.net/license.php
  8822. *******************************************************************************/
  8823. KindEditor.plugin('pagebreak', function(K) {
  8824. var self = this;
  8825. var name = 'pagebreak';
  8826. var pagebreakHtml = K.undef(self.pagebreakHtml, '<hr style="page-break-after: always;" class="ke-pagebreak" />');
  8827. self.clickToolbar(name, function() {
  8828. var cmd = self.cmd, range = cmd.range;
  8829. self.focus();
  8830. var tail = self.newlineTag == 'br' || K.WEBKIT ? '' : '<span id="__kindeditor_tail_tag__"></span>';
  8831. self.insertHtml(pagebreakHtml + tail);
  8832. if (tail !== '') {
  8833. var p = K('#__kindeditor_tail_tag__', self.edit.doc);
  8834. range.selectNodeContents(p[0]);
  8835. p.removeAttr('id');
  8836. cmd.select();
  8837. }
  8838. });
  8839. });
  8840. /*******************************************************************************
  8841. * KindEditor - WYSIWYG HTML Editor for Internet
  8842. * Copyright (C) 2006-2011 kindsoft.net
  8843. *
  8844. * @author Roddy <luolonghao@gmail.com>
  8845. * @site http://www.kindsoft.net/
  8846. * @licence http://www.kindsoft.net/license.php
  8847. *******************************************************************************/
  8848. KindEditor.plugin('plainpaste', function(K) {
  8849. var self = this, name = 'plainpaste';
  8850. self.clickToolbar(name, function() {
  8851. var lang = self.lang(name + '.'),
  8852. html = '<div style="padding:10px 20px;">' +
  8853. '<div style="margin-bottom:10px;">' + lang.comment + '</div>' +
  8854. '<textarea class="ke-textarea" style="width:408px;height:260px;"></textarea>' +
  8855. '</div>',
  8856. dialog = self.createDialog({
  8857. name : name,
  8858. width : 450,
  8859. title : self.lang(name),
  8860. body : html,
  8861. yesBtn : {
  8862. name : self.lang('yes'),
  8863. click : function(e) {
  8864. var html = textarea.val();
  8865. html = K.escape(html);
  8866. html = html.replace(/ {2}/g, ' &nbsp;');
  8867. if (self.newlineTag == 'p') {
  8868. html = html.replace(/^/, '<p>').replace(/$/, '</p>').replace(/\n/g, '</p><p>');
  8869. } else {
  8870. html = html.replace(/\n/g, '<br />$&');
  8871. }
  8872. self.insertHtml(html).hideDialog().focus();
  8873. }
  8874. }
  8875. }),
  8876. textarea = K('textarea', dialog.div);
  8877. textarea[0].focus();
  8878. });
  8879. });
  8880. /*******************************************************************************
  8881. * KindEditor - WYSIWYG HTML Editor for Internet
  8882. * Copyright (C) 2006-2011 kindsoft.net
  8883. *
  8884. * @author Roddy <luolonghao@gmail.com>
  8885. * @site http://www.kindsoft.net/
  8886. * @licence http://www.kindsoft.net/license.php
  8887. *******************************************************************************/
  8888. KindEditor.plugin('preview', function(K) {
  8889. var self = this, name = 'preview', undefined;
  8890. self.clickToolbar(name, function() {
  8891. var lang = self.lang(name + '.'),
  8892. html = '<div style="padding:10px 20px;">' +
  8893. '<iframe class="ke-textarea" frameborder="0" style="width:708px;height:400px;"></iframe>' +
  8894. '</div>',
  8895. dialog = self.createDialog({
  8896. name : name,
  8897. width : 750,
  8898. title : self.lang(name),
  8899. body : html
  8900. }),
  8901. iframe = K('iframe', dialog.div),
  8902. doc = K.iframeDoc(iframe);
  8903. doc.open();
  8904. doc.write(self.fullHtml());
  8905. doc.close();
  8906. K(doc.body).css('background-color', '#FFF');
  8907. iframe[0].contentWindow.focus();
  8908. });
  8909. });
  8910. /*******************************************************************************
  8911. * KindEditor - WYSIWYG HTML Editor for Internet
  8912. * Copyright (C) 2006-2011 kindsoft.net
  8913. *
  8914. * @author Roddy <luolonghao@gmail.com>
  8915. * @site http://www.kindsoft.net/
  8916. * @licence http://www.kindsoft.net/license.php
  8917. *******************************************************************************/
  8918. KindEditor.plugin('quickformat', function(K) {
  8919. var self = this, name = 'quickformat',
  8920. blockMap = K.toMap('blockquote,center,div,h1,h2,h3,h4,h5,h6,p');
  8921. function getFirstChild(knode) {
  8922. var child = knode.first();
  8923. while (child && child.first()) {
  8924. child = child.first();
  8925. }
  8926. return child;
  8927. }
  8928. self.clickToolbar(name, function() {
  8929. self.focus();
  8930. var doc = self.edit.doc,
  8931. range = self.cmd.range,
  8932. child = K(doc.body).first(), next,
  8933. nodeList = [], subList = [],
  8934. bookmark = range.createBookmark(true);
  8935. while(child) {
  8936. next = child.next();
  8937. var firstChild = getFirstChild(child);
  8938. if (!firstChild || firstChild.name != 'img') {
  8939. if (blockMap[child.name]) {
  8940. child.html(child.html().replace(/^(\s|&nbsp;| )+/ig, ''));
  8941. child.css('text-indent', '2em');
  8942. } else {
  8943. subList.push(child);
  8944. }
  8945. if (!next || (blockMap[next.name] || blockMap[child.name] && !blockMap[next.name])) {
  8946. if (subList.length > 0) {
  8947. nodeList.push(subList);
  8948. }
  8949. subList = [];
  8950. }
  8951. }
  8952. child = next;
  8953. }
  8954. K.each(nodeList, function(i, subList) {
  8955. var wrapper = K('<p style="text-indent:2em;"></p>', doc);
  8956. subList[0].before(wrapper);
  8957. K.each(subList, function(i, knode) {
  8958. wrapper.append(knode);
  8959. });
  8960. });
  8961. range.moveToBookmark(bookmark);
  8962. self.addBookmark();
  8963. });
  8964. });
  8965. /*******************************************************************************
  8966. * KindEditor - WYSIWYG HTML Editor for Internet
  8967. * Copyright (C) 2006-2011 kindsoft.net
  8968. *
  8969. * @author Roddy <luolonghao@gmail.com>
  8970. * @site http://www.kindsoft.net/
  8971. * @licence http://www.kindsoft.net/license.php
  8972. *******************************************************************************/
  8973. KindEditor.plugin('table', function(K) {
  8974. var self = this, name = 'table', lang = self.lang(name + '.'), zeroborder = 'ke-zeroborder';
  8975. function _setColor(box, color) {
  8976. color = color.toUpperCase();
  8977. box.css('background-color', color);
  8978. box.css('color', color === '#000000' ? '#FFFFFF' : '#000000');
  8979. box.html(color);
  8980. }
  8981. var pickerList = [];
  8982. function _initColorPicker(dialogDiv, colorBox) {
  8983. colorBox.bind('click,mousedown', function(e){
  8984. e.stopPropagation();
  8985. });
  8986. function removePicker() {
  8987. K.each(pickerList, function() {
  8988. this.remove();
  8989. });
  8990. pickerList = [];
  8991. K(document).unbind('click,mousedown', removePicker);
  8992. dialogDiv.unbind('click,mousedown', removePicker);
  8993. }
  8994. colorBox.click(function(e) {
  8995. removePicker();
  8996. var box = K(this),
  8997. pos = box.pos();
  8998. var picker = K.colorpicker({
  8999. x : pos.x,
  9000. y : pos.y + box.height(),
  9001. z : 811214,
  9002. selectedColor : K(this).html(),
  9003. colors : self.colorTable,
  9004. noColor : self.lang('noColor'),
  9005. shadowMode : self.shadowMode,
  9006. click : function(color) {
  9007. _setColor(box, color);
  9008. removePicker();
  9009. }
  9010. });
  9011. pickerList.push(picker);
  9012. K(document).bind('click,mousedown', removePicker);
  9013. dialogDiv.bind('click,mousedown', removePicker);
  9014. });
  9015. }
  9016. function _getCellIndex(table, row, cell) {
  9017. var rowSpanCount = 0;
  9018. for (var i = 0, len = row.cells.length; i < len; i++) {
  9019. if (row.cells[i] == cell) {
  9020. break;
  9021. }
  9022. rowSpanCount += row.cells[i].rowSpan - 1;
  9023. }
  9024. return cell.cellIndex - rowSpanCount;
  9025. }
  9026. self.plugin.table = {
  9027. prop : function(isInsert) {
  9028. var html = [
  9029. '<div style="padding:20px;">',
  9030. '<div class="ke-dialog-row">',
  9031. '<label for="keRows" style="width:90px;">' + lang.cells + '</label>',
  9032. lang.rows + ' <input type="text" id="keRows" class="ke-input-text ke-input-number" name="rows" value="" maxlength="4" /> &nbsp; ',
  9033. lang.cols + ' <input type="text" class="ke-input-text ke-input-number" name="cols" value="" maxlength="4" />',
  9034. '</div>',
  9035. '<div class="ke-dialog-row">',
  9036. '<label for="keWidth" style="width:90px;">' + lang.size + '</label>',
  9037. lang.width + ' <input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> &nbsp; ',
  9038. '<select name="widthType">',
  9039. '<option value="%">' + lang.percent + '</option>',
  9040. '<option value="px">' + lang.px + '</option>',
  9041. '</select> &nbsp; ',
  9042. lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> &nbsp; ',
  9043. '<select name="heightType">',
  9044. '<option value="%">' + lang.percent + '</option>',
  9045. '<option value="px">' + lang.px + '</option>',
  9046. '</select>',
  9047. '</div>',
  9048. '<div class="ke-dialog-row">',
  9049. '<label for="kePadding" style="width:90px;">' + lang.space + '</label>',
  9050. lang.padding + ' <input type="text" id="kePadding" class="ke-input-text ke-input-number" name="padding" value="" maxlength="4" /> &nbsp; ',
  9051. lang.spacing + ' <input type="text" class="ke-input-text ke-input-number" name="spacing" value="" maxlength="4" />',
  9052. '</div>',
  9053. '<div class="ke-dialog-row">',
  9054. '<label for="keAlign" style="width:90px;">' + lang.align + '</label>',
  9055. '<select id="keAlign" name="align">',
  9056. '<option value="">' + lang.alignDefault + '</option>',
  9057. '<option value="left">' + lang.alignLeft + '</option>',
  9058. '<option value="center">' + lang.alignCenter + '</option>',
  9059. '<option value="right">' + lang.alignRight + '</option>',
  9060. '</select>',
  9061. '</div>',
  9062. '<div class="ke-dialog-row">',
  9063. '<label for="keBorder" style="width:90px;">' + lang.border + '</label>',
  9064. lang.borderWidth + ' <input type="text" id="keBorder" class="ke-input-text ke-input-number" name="border" value="" maxlength="4" /> &nbsp; ',
  9065. lang.borderColor + ' <span class="ke-inline-block ke-input-color"></span>',
  9066. '</div>',
  9067. '<div class="ke-dialog-row">',
  9068. '<label for="keBgColor" style="width:90px;">' + lang.backgroundColor + '</label>',
  9069. '<span class="ke-inline-block ke-input-color"></span>',
  9070. '</div>',
  9071. '</div>'
  9072. ].join('');
  9073. var bookmark = self.cmd.range.createBookmark();
  9074. var dialog = self.createDialog({
  9075. name : name,
  9076. width : 500,
  9077. title : self.lang(name),
  9078. body : html,
  9079. beforeRemove : function() {
  9080. colorBox.unbind();
  9081. },
  9082. yesBtn : {
  9083. name : self.lang('yes'),
  9084. click : function(e) {
  9085. var rows = rowsBox.val(),
  9086. cols = colsBox.val(),
  9087. width = widthBox.val(),
  9088. height = heightBox.val(),
  9089. widthType = widthTypeBox.val(),
  9090. heightType = heightTypeBox.val(),
  9091. padding = paddingBox.val(),
  9092. spacing = spacingBox.val(),
  9093. align = alignBox.val(),
  9094. border = borderBox.val(),
  9095. borderColor = K(colorBox[0]).html() || '',
  9096. bgColor = K(colorBox[1]).html() || '';
  9097. if (rows == 0 || !/^\d+$/.test(rows)) {
  9098. alert(self.lang('invalidRows'));
  9099. rowsBox[0].focus();
  9100. return;
  9101. }
  9102. if (cols == 0 || !/^\d+$/.test(cols)) {
  9103. alert(self.lang('invalidRows'));
  9104. colsBox[0].focus();
  9105. return;
  9106. }
  9107. if (!/^\d*$/.test(width)) {
  9108. alert(self.lang('invalidWidth'));
  9109. widthBox[0].focus();
  9110. return;
  9111. }
  9112. if (!/^\d*$/.test(height)) {
  9113. alert(self.lang('invalidHeight'));
  9114. heightBox[0].focus();
  9115. return;
  9116. }
  9117. if (!/^\d*$/.test(padding)) {
  9118. alert(self.lang('invalidPadding'));
  9119. paddingBox[0].focus();
  9120. return;
  9121. }
  9122. if (!/^\d*$/.test(spacing)) {
  9123. alert(self.lang('invalidSpacing'));
  9124. spacingBox[0].focus();
  9125. return;
  9126. }
  9127. if (!/^\d*$/.test(border)) {
  9128. alert(self.lang('invalidBorder'));
  9129. borderBox[0].focus();
  9130. return;
  9131. }
  9132. if (table) {
  9133. if (width !== '') {
  9134. table.width(width + widthType);
  9135. } else {
  9136. table.css('width', '');
  9137. }
  9138. if (table[0].width !== undefined) {
  9139. table.removeAttr('width');
  9140. }
  9141. if (height !== '') {
  9142. table.height(height + heightType);
  9143. } else {
  9144. table.css('height', '');
  9145. }
  9146. if (table[0].height !== undefined) {
  9147. table.removeAttr('height');
  9148. }
  9149. table.css('background-color', bgColor);
  9150. if (table[0].bgColor !== undefined) {
  9151. table.removeAttr('bgColor');
  9152. }
  9153. if (padding !== '') {
  9154. table[0].cellPadding = padding;
  9155. } else {
  9156. table.removeAttr('cellPadding');
  9157. }
  9158. if (spacing !== '') {
  9159. table[0].cellSpacing = spacing;
  9160. } else {
  9161. table.removeAttr('cellSpacing');
  9162. }
  9163. if (align !== '') {
  9164. table[0].align = align;
  9165. } else {
  9166. table.removeAttr('align');
  9167. }
  9168. if (border !== '') {
  9169. table.attr('border', border);
  9170. } else {
  9171. table.removeAttr('border');
  9172. }
  9173. if (border === '' || border === '0') {
  9174. table.addClass(zeroborder);
  9175. } else {
  9176. table.removeClass(zeroborder);
  9177. }
  9178. if (borderColor !== '') {
  9179. table.attr('borderColor', borderColor);
  9180. } else {
  9181. table.removeAttr('borderColor');
  9182. }
  9183. self.hideDialog().focus();
  9184. self.cmd.range.moveToBookmark(bookmark);
  9185. self.cmd.select();
  9186. self.addBookmark();
  9187. return;
  9188. }
  9189. var style = '';
  9190. if (width !== '') {
  9191. style += 'width:' + width + widthType + ';';
  9192. }
  9193. if (height !== '') {
  9194. style += 'height:' + height + heightType + ';';
  9195. }
  9196. if (bgColor !== '') {
  9197. style += 'background-color:' + bgColor + ';';
  9198. }
  9199. var html = '<table';
  9200. if (style !== '') {
  9201. html += ' style="' + style + '"';
  9202. }
  9203. if (padding !== '') {
  9204. html += ' cellpadding="' + padding + '"';
  9205. }
  9206. if (spacing !== '') {
  9207. html += ' cellspacing="' + spacing + '"';
  9208. }
  9209. if (align !== '') {
  9210. html += ' align="' + align + '"';
  9211. }
  9212. if (border !== '') {
  9213. html += ' border="' + border + '"';
  9214. }
  9215. if (border === '' || border === '0') {
  9216. html += ' class="' + zeroborder + '"';
  9217. }
  9218. if (borderColor !== '') {
  9219. html += ' bordercolor="' + borderColor + '"';
  9220. }
  9221. html += '>';
  9222. for (var i = 0; i < rows; i++) {
  9223. html += '<tr>';
  9224. for (var j = 0; j < cols; j++) {
  9225. html += '<td>' + (K.IE ? '&nbsp;' : '<br />') + '</td>';
  9226. }
  9227. html += '</tr>';
  9228. }
  9229. html += '</table>';
  9230. if (!K.IE) {
  9231. html += '<br />';
  9232. }
  9233. self.insertHtml(html);
  9234. self.select().hideDialog().focus();
  9235. self.addBookmark();
  9236. }
  9237. }
  9238. }),
  9239. div = dialog.div,
  9240. rowsBox = K('[name="rows"]', div).val(3),
  9241. colsBox = K('[name="cols"]', div).val(2),
  9242. widthBox = K('[name="width"]', div).val(100),
  9243. heightBox = K('[name="height"]', div),
  9244. widthTypeBox = K('[name="widthType"]', div),
  9245. heightTypeBox = K('[name="heightType"]', div),
  9246. paddingBox = K('[name="padding"]', div).val(2),
  9247. spacingBox = K('[name="spacing"]', div).val(0),
  9248. alignBox = K('[name="align"]', div),
  9249. borderBox = K('[name="border"]', div).val(1),
  9250. colorBox = K('.ke-input-color', div);
  9251. _initColorPicker(div, colorBox.eq(0));
  9252. _initColorPicker(div, colorBox.eq(1));
  9253. _setColor(colorBox.eq(0), '#000000');
  9254. _setColor(colorBox.eq(1), '');
  9255. rowsBox[0].focus();
  9256. rowsBox[0].select();
  9257. var table;
  9258. if (isInsert) {
  9259. return;
  9260. }
  9261. table = self.plugin.getSelectedTable();
  9262. if (table) {
  9263. rowsBox.val(table[0].rows.length);
  9264. colsBox.val(table[0].rows.length > 0 ? table[0].rows[0].cells.length : 0);
  9265. rowsBox.attr('disabled', true);
  9266. colsBox.attr('disabled', true);
  9267. var match,
  9268. tableWidth = table[0].style.width || table[0].width,
  9269. tableHeight = table[0].style.height || table[0].height;
  9270. if (tableWidth !== undefined && (match = /^(\d+)((?:px|%)*)$/.exec(tableWidth))) {
  9271. widthBox.val(match[1]);
  9272. widthTypeBox.val(match[2]);
  9273. } else {
  9274. widthBox.val('');
  9275. }
  9276. if (tableHeight !== undefined && (match = /^(\d+)((?:px|%)*)$/.exec(tableHeight))) {
  9277. heightBox.val(match[1]);
  9278. heightTypeBox.val(match[2]);
  9279. }
  9280. paddingBox.val(table[0].cellPadding || '');
  9281. spacingBox.val(table[0].cellSpacing || '');
  9282. alignBox.val(table[0].align || '');
  9283. borderBox.val(table[0].border === undefined ? '' : table[0].border);
  9284. _setColor(colorBox.eq(0), K.toHex(table.attr('borderColor') || ''));
  9285. _setColor(colorBox.eq(1), K.toHex(table[0].style.backgroundColor || table[0].bgColor || ''));
  9286. widthBox[0].focus();
  9287. widthBox[0].select();
  9288. }
  9289. },
  9290. cellprop : function() {
  9291. var html = [
  9292. '<div style="padding:20px;">',
  9293. '<div class="ke-dialog-row">',
  9294. '<label for="keWidth" style="width:90px;">' + lang.size + '</label>',
  9295. lang.width + ' <input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="" maxlength="4" /> &nbsp; ',
  9296. '<select name="widthType">',
  9297. '<option value="%">' + lang.percent + '</option>',
  9298. '<option value="px">' + lang.px + '</option>',
  9299. '</select> &nbsp; ',
  9300. lang.height + ' <input type="text" class="ke-input-text ke-input-number" name="height" value="" maxlength="4" /> &nbsp; ',
  9301. '<select name="heightType">',
  9302. '<option value="%">' + lang.percent + '</option>',
  9303. '<option value="px">' + lang.px + '</option>',
  9304. '</select>',
  9305. '</div>',
  9306. '<div class="ke-dialog-row">',
  9307. '<label for="keAlign" style="width:90px;">' + lang.align + '</label>',
  9308. lang.textAlign + ' <select id="keAlign" name="textAlign">',
  9309. '<option value="">' + lang.alignDefault + '</option>',
  9310. '<option value="left">' + lang.alignLeft + '</option>',
  9311. '<option value="center">' + lang.alignCenter + '</option>',
  9312. '<option value="right">' + lang.alignRight + '</option>',
  9313. '</select> ',
  9314. lang.verticalAlign + ' <select name="verticalAlign">',
  9315. '<option value="">' + lang.alignDefault + '</option>',
  9316. '<option value="top">' + lang.alignTop + '</option>',
  9317. '<option value="middle">' + lang.alignMiddle + '</option>',
  9318. '<option value="bottom">' + lang.alignBottom + '</option>',
  9319. '<option value="baseline">' + lang.alignBaseline + '</option>',
  9320. '</select>',
  9321. '</div>',
  9322. '<div class="ke-dialog-row">',
  9323. '<label for="keBorder" style="width:90px;">' + lang.border + '</label>',
  9324. lang.borderWidth + ' <input type="text" id="keBorder" class="ke-input-text ke-input-number" name="border" value="" maxlength="4" /> &nbsp; ',
  9325. lang.borderColor + ' <span class="ke-inline-block ke-input-color"></span>',
  9326. '</div>',
  9327. '<div class="ke-dialog-row">',
  9328. '<label for="keBgColor" style="width:90px;">' + lang.backgroundColor + '</label>',
  9329. '<span class="ke-inline-block ke-input-color"></span>',
  9330. '</div>',
  9331. '</div>'
  9332. ].join('');
  9333. var bookmark = self.cmd.range.createBookmark();
  9334. var dialog = self.createDialog({
  9335. name : name,
  9336. width : 500,
  9337. title : self.lang('tablecell'),
  9338. body : html,
  9339. beforeRemove : function() {
  9340. colorBox.unbind();
  9341. },
  9342. yesBtn : {
  9343. name : self.lang('yes'),
  9344. click : function(e) {
  9345. var width = widthBox.val(),
  9346. height = heightBox.val(),
  9347. widthType = widthTypeBox.val(),
  9348. heightType = heightTypeBox.val(),
  9349. padding = paddingBox.val(),
  9350. spacing = spacingBox.val(),
  9351. textAlign = textAlignBox.val(),
  9352. verticalAlign = verticalAlignBox.val(),
  9353. border = borderBox.val(),
  9354. borderColor = K(colorBox[0]).html() || '',
  9355. bgColor = K(colorBox[1]).html() || '';
  9356. if (!/^\d*$/.test(width)) {
  9357. alert(self.lang('invalidWidth'));
  9358. widthBox[0].focus();
  9359. return;
  9360. }
  9361. if (!/^\d*$/.test(height)) {
  9362. alert(self.lang('invalidHeight'));
  9363. heightBox[0].focus();
  9364. return;
  9365. }
  9366. if (!/^\d*$/.test(border)) {
  9367. alert(self.lang('invalidBorder'));
  9368. borderBox[0].focus();
  9369. return;
  9370. }
  9371. cell.css({
  9372. width : width !== '' ? (width + widthType) : '',
  9373. height : height !== '' ? (height + heightType) : '',
  9374. 'background-color' : bgColor,
  9375. 'text-align' : textAlign,
  9376. 'vertical-align' : verticalAlign,
  9377. 'border-width' : border,
  9378. 'border-style' : border !== '' ? 'solid' : '',
  9379. 'border-color' : borderColor
  9380. });
  9381. self.hideDialog().focus();
  9382. self.cmd.range.moveToBookmark(bookmark);
  9383. self.cmd.select();
  9384. self.addBookmark();
  9385. }
  9386. }
  9387. }),
  9388. div = dialog.div,
  9389. widthBox = K('[name="width"]', div).val(100),
  9390. heightBox = K('[name="height"]', div),
  9391. widthTypeBox = K('[name="widthType"]', div),
  9392. heightTypeBox = K('[name="heightType"]', div),
  9393. paddingBox = K('[name="padding"]', div).val(2),
  9394. spacingBox = K('[name="spacing"]', div).val(0),
  9395. textAlignBox = K('[name="textAlign"]', div),
  9396. verticalAlignBox = K('[name="verticalAlign"]', div),
  9397. borderBox = K('[name="border"]', div).val(1),
  9398. colorBox = K('.ke-input-color', div);
  9399. _initColorPicker(div, colorBox.eq(0));
  9400. _initColorPicker(div, colorBox.eq(1));
  9401. _setColor(colorBox.eq(0), '#000000');
  9402. _setColor(colorBox.eq(1), '');
  9403. widthBox[0].focus();
  9404. widthBox[0].select();
  9405. var cell = self.plugin.getSelectedCell();
  9406. var match,
  9407. cellWidth = cell[0].style.width || cell[0].width || '',
  9408. cellHeight = cell[0].style.height || cell[0].height || '';
  9409. if ((match = /^(\d+)((?:px|%)*)$/.exec(cellWidth))) {
  9410. widthBox.val(match[1]);
  9411. widthTypeBox.val(match[2]);
  9412. } else {
  9413. widthBox.val('');
  9414. }
  9415. if ((match = /^(\d+)((?:px|%)*)$/.exec(cellHeight))) {
  9416. heightBox.val(match[1]);
  9417. heightTypeBox.val(match[2]);
  9418. }
  9419. textAlignBox.val(cell[0].style.textAlign || '');
  9420. verticalAlignBox.val(cell[0].style.verticalAlign || '');
  9421. var border = cell[0].style.borderWidth || '';
  9422. if (border) {
  9423. border = parseInt(border);
  9424. }
  9425. borderBox.val(border);
  9426. _setColor(colorBox.eq(0), K.toHex(cell[0].style.borderColor || ''));
  9427. _setColor(colorBox.eq(1), K.toHex(cell[0].style.backgroundColor || ''));
  9428. widthBox[0].focus();
  9429. widthBox[0].select();
  9430. },
  9431. insert : function() {
  9432. this.prop(true);
  9433. },
  9434. 'delete' : function() {
  9435. var table = self.plugin.getSelectedTable();
  9436. self.cmd.range.setStartBefore(table[0]).collapse(true);
  9437. self.cmd.select();
  9438. table.remove();
  9439. self.addBookmark();
  9440. },
  9441. colinsert : function(offset) {
  9442. var table = self.plugin.getSelectedTable()[0],
  9443. row = self.plugin.getSelectedRow()[0],
  9444. cell = self.plugin.getSelectedCell()[0],
  9445. index = cell.cellIndex + offset;
  9446. index += table.rows[0].cells.length - row.cells.length;
  9447. for (var i = 0, len = table.rows.length; i < len; i++) {
  9448. var newRow = table.rows[i],
  9449. newCell = newRow.insertCell(index);
  9450. newCell.innerHTML = K.IE ? '' : '<br />';
  9451. index = _getCellIndex(table, newRow, newCell);
  9452. }
  9453. self.cmd.range.selectNodeContents(cell).collapse(true);
  9454. self.cmd.select();
  9455. self.addBookmark();
  9456. },
  9457. colinsertleft : function() {
  9458. this.colinsert(0);
  9459. },
  9460. colinsertright : function() {
  9461. this.colinsert(1);
  9462. },
  9463. rowinsert : function(offset) {
  9464. var table = self.plugin.getSelectedTable()[0],
  9465. row = self.plugin.getSelectedRow()[0],
  9466. cell = self.plugin.getSelectedCell()[0];
  9467. var rowIndex = row.rowIndex;
  9468. if (offset === 1) {
  9469. rowIndex = row.rowIndex + (cell.rowSpan - 1) + offset;
  9470. }
  9471. var newRow = table.insertRow(rowIndex);
  9472. for (var i = 0, len = row.cells.length; i < len; i++) {
  9473. if (row.cells[i].rowSpan > 1) {
  9474. len -= row.cells[i].rowSpan - 1;
  9475. }
  9476. var newCell = newRow.insertCell(i);
  9477. if (offset === 1 && row.cells[i].colSpan > 1) {
  9478. newCell.colSpan = row.cells[i].colSpan;
  9479. }
  9480. newCell.innerHTML = K.IE ? '' : '<br />';
  9481. }
  9482. for (var j = rowIndex; j >= 0; j--) {
  9483. var cells = table.rows[j].cells;
  9484. if (cells.length > i) {
  9485. for (var k = cell.cellIndex; k >= 0; k--) {
  9486. if (cells[k].rowSpan > 1) {
  9487. cells[k].rowSpan += 1;
  9488. }
  9489. }
  9490. break;
  9491. }
  9492. }
  9493. self.cmd.range.selectNodeContents(cell).collapse(true);
  9494. self.cmd.select();
  9495. self.addBookmark();
  9496. },
  9497. rowinsertabove : function() {
  9498. this.rowinsert(0);
  9499. },
  9500. rowinsertbelow : function() {
  9501. this.rowinsert(1);
  9502. },
  9503. rowmerge : function() {
  9504. var table = self.plugin.getSelectedTable()[0],
  9505. row = self.plugin.getSelectedRow()[0],
  9506. cell = self.plugin.getSelectedCell()[0],
  9507. rowIndex = row.rowIndex,
  9508. nextRowIndex = rowIndex + cell.rowSpan,
  9509. nextRow = table.rows[nextRowIndex];
  9510. if (table.rows.length <= nextRowIndex) {
  9511. return;
  9512. }
  9513. var cellIndex = cell.cellIndex;
  9514. if (nextRow.cells.length <= cellIndex) {
  9515. return;
  9516. }
  9517. var nextCell = nextRow.cells[cellIndex];
  9518. if (cell.colSpan !== nextCell.colSpan) {
  9519. return;
  9520. }
  9521. cell.rowSpan += nextCell.rowSpan;
  9522. nextRow.deleteCell(cellIndex);
  9523. self.cmd.range.selectNodeContents(cell).collapse(true);
  9524. self.cmd.select();
  9525. self.addBookmark();
  9526. },
  9527. colmerge : function() {
  9528. var table = self.plugin.getSelectedTable()[0],
  9529. row = self.plugin.getSelectedRow()[0],
  9530. cell = self.plugin.getSelectedCell()[0],
  9531. rowIndex = row.rowIndex,
  9532. cellIndex = cell.cellIndex,
  9533. nextCellIndex = cellIndex + 1;
  9534. if (row.cells.length <= nextCellIndex) {
  9535. return;
  9536. }
  9537. var nextCell = row.cells[nextCellIndex];
  9538. if (cell.rowSpan !== nextCell.rowSpan) {
  9539. return;
  9540. }
  9541. cell.colSpan += nextCell.colSpan;
  9542. row.deleteCell(nextCellIndex);
  9543. self.cmd.range.selectNodeContents(cell).collapse(true);
  9544. self.cmd.select();
  9545. self.addBookmark();
  9546. },
  9547. rowsplit : function() {
  9548. var table = self.plugin.getSelectedTable()[0],
  9549. row = self.plugin.getSelectedRow()[0],
  9550. cell = self.plugin.getSelectedCell()[0],
  9551. rowIndex = row.rowIndex;
  9552. if (cell.rowSpan === 1) {
  9553. return;
  9554. }
  9555. var cellIndex = _getCellIndex(table, row, cell);
  9556. for (var i = 1, len = cell.rowSpan; i < len; i++) {
  9557. var newRow = table.rows[rowIndex + i],
  9558. newCell = newRow.insertCell(cellIndex);
  9559. if (cell.colSpan > 1) {
  9560. newCell.colSpan = cell.colSpan;
  9561. }
  9562. newCell.innerHTML = K.IE ? '' : '<br />';
  9563. cellIndex = _getCellIndex(table, newRow, newCell);
  9564. }
  9565. K(cell).removeAttr('rowSpan');
  9566. self.cmd.range.selectNodeContents(cell).collapse(true);
  9567. self.cmd.select();
  9568. self.addBookmark();
  9569. },
  9570. colsplit : function() {
  9571. var table = self.plugin.getSelectedTable()[0],
  9572. row = self.plugin.getSelectedRow()[0],
  9573. cell = self.plugin.getSelectedCell()[0],
  9574. cellIndex = cell.cellIndex;
  9575. if (cell.colSpan === 1) {
  9576. return;
  9577. }
  9578. for (var i = 1, len = cell.colSpan; i < len; i++) {
  9579. var newCell = row.insertCell(cellIndex + i);
  9580. if (cell.rowSpan > 1) {
  9581. newCell.rowSpan = cell.rowSpan;
  9582. }
  9583. newCell.innerHTML = K.IE ? '' : '<br />';
  9584. }
  9585. K(cell).removeAttr('colSpan');
  9586. self.cmd.range.selectNodeContents(cell).collapse(true);
  9587. self.cmd.select();
  9588. self.addBookmark();
  9589. },
  9590. coldelete : function() {
  9591. var table = self.plugin.getSelectedTable()[0],
  9592. row = self.plugin.getSelectedRow()[0],
  9593. cell = self.plugin.getSelectedCell()[0],
  9594. index = cell.cellIndex;
  9595. for (var i = 0, len = table.rows.length; i < len; i++) {
  9596. var newRow = table.rows[i],
  9597. newCell = newRow.cells[index];
  9598. if (newCell.colSpan > 1) {
  9599. newCell.colSpan -= 1;
  9600. if (newCell.colSpan === 1) {
  9601. K(newCell).removeAttr('colSpan');
  9602. }
  9603. } else {
  9604. newRow.deleteCell(index);
  9605. }
  9606. if (newCell.rowSpan > 1) {
  9607. i += newCell.rowSpan - 1;
  9608. }
  9609. }
  9610. if (row.cells.length === 0) {
  9611. self.cmd.range.setStartBefore(table).collapse(true);
  9612. self.cmd.select();
  9613. K(table).remove();
  9614. } else {
  9615. self.cmd.selection(true);
  9616. }
  9617. self.addBookmark();
  9618. },
  9619. rowdelete : function() {
  9620. var table = self.plugin.getSelectedTable()[0],
  9621. row = self.plugin.getSelectedRow()[0],
  9622. cell = self.plugin.getSelectedCell()[0],
  9623. rowIndex = row.rowIndex;
  9624. for (var i = cell.rowSpan - 1; i >= 0; i--) {
  9625. table.deleteRow(rowIndex + i);
  9626. }
  9627. if (table.rows.length === 0) {
  9628. self.cmd.range.setStartBefore(table).collapse(true);
  9629. self.cmd.select();
  9630. K(table).remove();
  9631. } else {
  9632. self.cmd.selection(true);
  9633. }
  9634. self.addBookmark();
  9635. }
  9636. };
  9637. self.clickToolbar(name, self.plugin.table.prop);
  9638. });
  9639. /*******************************************************************************
  9640. * KindEditor - WYSIWYG HTML Editor for Internet
  9641. * Copyright (C) 2006-2011 kindsoft.net
  9642. *
  9643. * @author Roddy <luolonghao@gmail.com>
  9644. * @site http://www.kindsoft.net/
  9645. * @licence http://www.kindsoft.net/license.php
  9646. *******************************************************************************/
  9647. KindEditor.plugin('template', function(K) {
  9648. var self = this, name = 'template', lang = self.lang(name + '.'),
  9649. htmlPath = self.pluginsPath + name + '/html/';
  9650. function getFilePath(fileName) {
  9651. return htmlPath + fileName + '?ver=' + encodeURIComponent(K.DEBUG ? K.TIME : K.VERSION);
  9652. }
  9653. self.clickToolbar(name, function() {
  9654. var lang = self.lang(name + '.'),
  9655. arr = ['<div style="padding:10px 20px;">',
  9656. '<div class="ke-header">',
  9657. '<div class="ke-left">',
  9658. lang. selectTemplate + ' <select>'];
  9659. K.each(lang.fileList, function(key, val) {
  9660. arr.push('<option value="' + key + '">' + val + '</option>');
  9661. });
  9662. html = [arr.join(''),
  9663. '</select></div>',
  9664. '<div class="ke-right">',
  9665. '<input type="checkbox" id="keReplaceFlag" name="replaceFlag" value="1" /> <label for="keReplaceFlag">' + lang.replaceContent + '</label>',
  9666. '</div>',
  9667. '<div class="ke-clearfix"></div>',
  9668. '</div>',
  9669. '<iframe class="ke-textarea" frameborder="0" style="width:458px;height:260px;background-color:#FFF;"></iframe>',
  9670. '</div>'].join('');
  9671. var dialog = self.createDialog({
  9672. name : name,
  9673. width : 500,
  9674. title : self.lang(name),
  9675. body : html,
  9676. yesBtn : {
  9677. name : self.lang('yes'),
  9678. click : function(e) {
  9679. var doc = K.iframeDoc(iframe);
  9680. self[checkbox[0].checked ? 'html' : 'insertHtml'](doc.body.innerHTML).hideDialog().focus();
  9681. }
  9682. }
  9683. });
  9684. var selectBox = K('select', dialog.div),
  9685. checkbox = K('[name="replaceFlag"]', dialog.div),
  9686. iframe = K('iframe', dialog.div);
  9687. checkbox[0].checked = true;
  9688. iframe.attr('src', getFilePath(selectBox.val()));
  9689. selectBox.change(function() {
  9690. iframe.attr('src', getFilePath(this.value));
  9691. });
  9692. });
  9693. });
  9694. /*******************************************************************************
  9695. * KindEditor - WYSIWYG HTML Editor for Internet
  9696. * Copyright (C) 2006-2011 kindsoft.net
  9697. *
  9698. * @author Roddy <luolonghao@gmail.com>
  9699. * @site http://www.kindsoft.net/
  9700. * @licence http://www.kindsoft.net/license.php
  9701. *******************************************************************************/
  9702. KindEditor.plugin('wordpaste', function(K) {
  9703. var self = this, name = 'wordpaste';
  9704. self.clickToolbar(name, function() {
  9705. var lang = self.lang(name + '.'),
  9706. html = '<div style="padding:10px 20px;">' +
  9707. '<div style="margin-bottom:10px;">' + lang.comment + '</div>' +
  9708. '<iframe class="ke-textarea" frameborder="0" style="width:408px;height:260px;"></iframe>' +
  9709. '</div>',
  9710. dialog = self.createDialog({
  9711. name : name,
  9712. width : 450,
  9713. title : self.lang(name),
  9714. body : html,
  9715. yesBtn : {
  9716. name : self.lang('yes'),
  9717. click : function(e) {
  9718. var str = doc.body.innerHTML;
  9719. str = K.clearMsWord(str, self.filterMode ? self.htmlTags : K.options.htmlTags);
  9720. self.insertHtml(str).hideDialog().focus();
  9721. }
  9722. }
  9723. }),
  9724. div = dialog.div,
  9725. iframe = K('iframe', div),
  9726. doc = K.iframeDoc(iframe);
  9727. if (!K.IE) {
  9728. doc.designMode = 'on';
  9729. }
  9730. doc.open();
  9731. doc.write('<!doctype html><html><head><title>WordPaste</title></head>');
  9732. doc.write('<body style="background-color:#FFF;font-size:12px;margin:2px;">');
  9733. if (!K.IE) {
  9734. doc.write('<br />');
  9735. }
  9736. doc.write('</body></html>');
  9737. doc.close();
  9738. if (K.IE) {
  9739. doc.body.contentEditable = 'true';
  9740. }
  9741. iframe[0].contentWindow.focus();
  9742. });
  9743. });
  9744. KindEditor.plugin('fixtoolbar', function (K) {
  9745. var self = this;
  9746. if (!self.fixToolBar) {
  9747. return;
  9748. }
  9749. function init() {
  9750. var toolbar = K('.ke-toolbar');
  9751. var originY = toolbar.pos().y;
  9752. K(window).bind('scroll', function () {
  9753. if (toolbar.css('position') == 'fixed') {
  9754. if(document.body.scrollTop - originY < 0){
  9755. toolbar.css('position', 'static');
  9756. toolbar.css('top', 'auto');
  9757. }
  9758. } else {
  9759. if (toolbar.pos().y - document.body.scrollTop < 0) {
  9760. toolbar.css('position', 'fixed');
  9761. toolbar.css('top', 0);
  9762. }
  9763. }
  9764. });
  9765. }
  9766. if (self.isCreated) {
  9767. init();
  9768. } else {
  9769. self.afterCreate(init);
  9770. }
  9771. });