/******************************************************************************* * kindeditor - wysiwyg html editor for internet * copyright (c) 2006-2012 kindsoft.net * * @author roddy * @website http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php * @version 4.1.4 (2012-11-11) *******************************************************************************/ (function (window, undefined) { if (window.kindeditor) { return; } if (!window.console) { window.console = {}; } if (!console.log) { console.log = function () {}; } var _version = '4.1.4 (2012-11-11)', _ua = navigator.useragent.tolowercase(), _ie = _ua.indexof('msie') > -1 && _ua.indexof('opera') == -1, _gecko = _ua.indexof('gecko') > -1 && _ua.indexof('khtml') == -1, _webkit = _ua.indexof('applewebkit') > -1, _opera = _ua.indexof('opera') > -1, _mobile = _ua.indexof('mobile') > -1, _ios = /ipad|iphone|ipod/.test(_ua), _quirks = document.compatmode != 'css1compat', _matches = /(?:msie|firefox|webkit|opera)[\/:\s](\d+)/.exec(_ua), _v = _matches ? _matches[1] : '0', _time = new date().gettime(); function _isarray(val) { if (!val) { return false; } return object.prototype.tostring.call(val) === '[object array]'; } function _isfunction(val) { if (!val) { return false; } return object.prototype.tostring.call(val) === '[object function]'; } function _inarray(val, arr) { for (var i = 0, len = arr.length; i < len; i++) { if (val === arr[i]) { return i; } } return -1; } function _each(obj, fn) { if (_isarray(obj)) { for (var i = 0, len = obj.length; i < len; i++) { if (fn.call(obj[i], i, obj[i]) === false) { break; } } } else { for (var key in obj) { if (obj.hasownproperty(key)) { if (fn.call(obj[key], key, obj[key]) === false) { break; } } } } } function _trim(str) { return str.replace(/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, ''); } function _instring(val, str, delimiter) { delimiter = delimiter === undefined ? ',' : delimiter; return (delimiter + str + delimiter).indexof(delimiter + val + delimiter) >= 0; } function _addunit(val, unit) { unit = unit || 'px'; return val && /^\d+$/.test(val) ? val + unit : val; } function _removeunit(val) { var match; return val && (match = /(\d+)/.exec(val)) ? parseint(match[1], 10) : 0; } function _escape(val) { return val.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); } function _unescape(val) { return val.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&/g, '&'); } function _tocamel(str) { var arr = str.split('-'); str = ''; _each(arr, function(key, val) { str += (key > 0) ? val.charat(0).touppercase() + val.substr(1) : val; }); return str; } function _tohex(val) { function hex(d) { var s = parseint(d, 10).tostring(16).touppercase(); return s.length > 1 ? s : '0' + s; } return val.replace(/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/ig, function($0, $1, $2, $3) { return '#' + hex($1) + hex($2) + hex($3); } ); } function _tomap(val, delimiter) { delimiter = delimiter === undefined ? ',' : delimiter; var map = {}, arr = _isarray(val) ? val : val.split(delimiter), match; _each(arr, function(key, val) { if ((match = /^(\d+)\.\.(\d+)$/.exec(val))) { for (var i = parseint(match[1], 10); i <= parseint(match[2], 10); i++) { map[i.tostring()] = true; } } else { map[val] = true; } }); return map; } function _toarray(obj, offset) { return array.prototype.slice.call(obj, offset || 0); } function _undef(val, defaultval) { return val === undefined ? defaultval : val; } function _invalidurl(url) { return !url || /[<>"]/.test(url); } function _addparam(url, param) { return url.indexof('?') >= 0 ? url + '&' + param : url + '?' + param; } function _extend(child, parent, proto) { if (!proto) { proto = parent; parent = null; } var childproto; if (parent) { var fn = function () {}; fn.prototype = parent.prototype; childproto = new fn(); _each(proto, function(key, val) { childproto[key] = val; }); } else { childproto = proto; } childproto.constructor = child; child.prototype = childproto; child.parent = parent ? parent.prototype : null; } function _json(text) { var match; if ((match = /\{[\s\s]*\}|\[[\s\s]*\]/.exec(text))) { text = match[0]; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; cx.lastindex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charcodeat(0).tostring(16)).slice(-4); }); } if (/^[\],:{}\s]*$/. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fa-f]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[ee][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { return eval('(' + text + ')'); } throw 'json parse error'; } var _round = math.round; var k = { debug : false, version : _version, ie : _ie, gecko : _gecko, webkit : _webkit, opera : _opera, v : _v, time : _time, each : _each, isarray : _isarray, isfunction : _isfunction, inarray : _inarray, instring : _instring, trim : _trim, addunit : _addunit, removeunit : _removeunit, escape : _escape, unescape : _unescape, tocamel : _tocamel, tohex : _tohex, tomap : _tomap, toarray : _toarray, undef : _undef, invalidurl : _invalidurl, addparam : _addparam, extend : _extend, json : _json }; 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'), _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'), _single_tag_map = _tomap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed'), _style_tag_map = _tomap('b,basefont,big,del,em,font,i,s,small,span,strike,strong,sub,sup,u'), _control_tag_map = _tomap('img,table,input,textarea,button'), _pre_tag_map = _tomap('pre,style,script'), _nosplit_tag_map = _tomap('html,head,body,td,tr,table,ol,ul,li'), _autoclose_tag_map = _tomap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'), _fill_attr_map = _tomap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'), _value_tag_map = _tomap('input,button,textarea,select'); function _getbasepath() { var els = document.getelementsbytagname('script'), src; for (var i = 0, len = els.length; i < len; i++) { src = els[i].src || ''; if (/kindeditor[\w\-\.]*\.js/.test(src)) { return src.substring(0, src.lastindexof('/') + 1); } } return ''; } k.basepath = _getbasepath(); k.options = { designmode : true, fullscreenmode : false, filtermode : true, wellformatmode : true, shadowmode : true, loadstylemode : true, basepath : k.basepath, themespath : k.basepath + 'themes/', langpath : k.basepath + 'lang/', pluginspath : k.basepath + 'plugins/', themetype : 'default', langtype : 'zh_cn', urltype : '', newlinetag : 'p', resizetype : 2, synctype : 'form', pastetype : 2, dialogaligntype : 'page', usecontextmenu : true, fullscreenshortcut : false, bodyclass : 'ke-content', indentchar : '\t', csspath : '', cssdata : '', minwidth : 650, minheight : 100, minchangesize : 50, items : [ 'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste', 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript', 'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/', 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage', 'flash', 'flv', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak', 'anchor', 'link', 'unlink', '|', 'about' ], nodisableitems : ['source', 'fullscreen'], colortable : [ ['#e53333', '#e56600', '#ff9900', '#64451d', '#dfc5a4', '#ffe500'], ['#009900', '#006600', '#99bb00', '#b8d100', '#60d978', '#00d5ff'], ['#337fe5', '#003399', '#4c33e5', '#9933e5', '#cc33e5', '#ee33ee'], ['#ffffff', '#cccccc', '#999999', '#666666', '#333333', '#000000'] ], fontsizetable : ['9px', '10px', '12px', '14px', '16px', '18px', '24px', '32px'], htmltags : { font : ['id', 'class', 'color', 'size', 'face', '.background-color'], span : [ 'id', 'class', '.color', '.background-color', '.font-size', '.font-family', '.background', '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.line-height' ], div : [ 'id', 'class', 'align', '.border', '.margin', '.padding', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.font-weight', '.background', '.font-style', '.text-decoration', '.vertical-align', '.margin-left' ], table: [ 'id', 'class', 'border', 'cellspacing', 'cellpadding', 'width', 'height', 'align', 'bordercolor', '.padding', '.margin', '.border', 'bgcolor', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.font-weight', '.font-style', '.text-decoration', '.background', '.width', '.height', '.border-collapse' ], 'td,th': [ 'id', 'class', 'align', 'valign', 'width', 'height', 'colspan', 'rowspan', 'bgcolor', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.background', '.border' ], a : ['id', 'class', 'href', 'target', 'name'], embed: ['id', 'class', 'src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess', "allowfullscreen"], img : ['id', 'class', 'src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'], 'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : [ 'id', 'class', 'align', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.background', '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.text-indent', '.margin-left' ], pre : ['id', 'class'], hr : ['id', 'class', '.page-break-after'], 'br,tbody,tr,strong,b,sub,sup,em,i,u,strike,s,del' : ['id', 'class'], iframe : ['id', 'class', 'src', 'frameborder', 'width', 'height', '.width', '.height'] }, layout : '
' }; var _usecapture = false; var _input_key_map = _tomap('8,9,13,32,46,48..57,59,61,65..90,106,109..111,188,190..192,219..222'); var _cursormove_key_map = _tomap('33..40'); var _change_key_map = {}; _each(_input_key_map, function(key, val) { _change_key_map[key] = val; }); _each(_cursormove_key_map, function(key, val) { _change_key_map[key] = val; }); function _bindevent(el, type, fn) { if (el.addeventlistener){ el.addeventlistener(type, fn, _usecapture); } else if (el.attachevent){ el.attachevent('on' + type, fn); } } function _unbindevent(el, type, fn) { if (el.removeeventlistener){ el.removeeventlistener(type, fn, _usecapture); } else if (el.detachevent){ el.detachevent('on' + type, fn); } } var _event_props = ('altkey,attrchange,attrname,bubbles,button,cancelable,charcode,clientx,clienty,ctrlkey,currenttarget,' + 'data,detail,eventphase,fromelement,handler,keycode,metakey,newvalue,offsetx,offsety,originaltarget,pagex,' + 'pagey,prevvalue,relatednode,relatedtarget,screenx,screeny,shiftkey,srcelement,target,toelement,view,wheeldelta,which').split(','); function kevent(el, event) { this.init(el, event); } _extend(kevent, { init : function(el, event) { var self = this, doc = el.ownerdocument || el.document || el; self.event = event; _each(_event_props, function(key, val) { self[val] = event[val]; }); if (!self.target) { self.target = self.srcelement || doc; } if (self.target.nodetype === 3) { self.target = self.target.parentnode; } if (!self.relatedtarget && self.fromelement) { self.relatedtarget = self.fromelement === self.target ? self.toelement : self.fromelement; } if (self.pagex == null && self.clientx != null) { var d = doc.documentelement, body = doc.body; self.pagex = self.clientx + (d && d.scrollleft || body && body.scrollleft || 0) - (d && d.clientleft || body && body.clientleft || 0); self.pagey = self.clienty + (d && d.scrolltop || body && body.scrolltop || 0) - (d && d.clienttop || body && body.clienttop || 0); } if (!self.which && ((self.charcode || self.charcode === 0) ? self.charcode : self.keycode)) { self.which = self.charcode || self.keycode; } if (!self.metakey && self.ctrlkey) { self.metakey = self.ctrlkey; } if (!self.which && self.button !== undefined) { self.which = (self.button & 1 ? 1 : (self.button & 2 ? 3 : (self.button & 4 ? 2 : 0))); } switch (self.which) { case 186 : self.which = 59; break; case 187 : case 107 : case 43 : self.which = 61; break; case 189 : case 45 : self.which = 109; break; case 42 : self.which = 106; break; case 47 : self.which = 111; break; case 78 : self.which = 110; break; } if (self.which >= 96 && self.which <= 105) { self.which -= 48; } }, preventdefault : function() { var ev = this.event; if (ev.preventdefault) { ev.preventdefault(); } ev.returnvalue = false; }, stoppropagation : function() { var ev = this.event; if (ev.stoppropagation) { ev.stoppropagation(); } ev.cancelbubble = true; }, stop : function() { this.preventdefault(); this.stoppropagation(); } }); var _eventexpendo = 'kindeditor_' + _time, _eventid = 0, _eventdata = {}; function _getid(el) { return el[_eventexpendo] || null; } function _setid(el) { el[_eventexpendo] = ++_eventid; return _eventid; } function _removeid(el) { try { delete el[_eventexpendo]; } catch(e) { if (el.removeattribute) { el.removeattribute(_eventexpendo); } } } function _bind(el, type, fn) { if (type.indexof(',') >= 0) { _each(type.split(','), function() { _bind(el, this, fn); }); return; } var id = _getid(el); if (!id) { id = _setid(el); } if (_eventdata[id] === undefined) { _eventdata[id] = {}; } var events = _eventdata[id][type]; if (events && events.length > 0) { _unbindevent(el, type, events[0]); } else { _eventdata[id][type] = []; _eventdata[id].el = el; } events = _eventdata[id][type]; if (events.length === 0) { events[0] = function(e) { var kevent = e ? new kevent(el, e) : undefined; _each(events, function(i, event) { if (i > 0 && event) { event.call(el, kevent); } }); }; } if (_inarray(fn, events) < 0) { events.push(fn); } _bindevent(el, type, events[0]); } function _unbind(el, type, fn) { if (type && type.indexof(',') >= 0) { _each(type.split(','), function() { _unbind(el, this, fn); }); return; } var id = _getid(el); if (!id) { return; } if (type === undefined) { if (id in _eventdata) { _each(_eventdata[id], function(key, events) { if (key != 'el' && events.length > 0) { _unbindevent(el, key, events[0]); } }); delete _eventdata[id]; _removeid(el); } return; } if (!_eventdata[id]) { return; } var events = _eventdata[id][type]; if (events && events.length > 0) { if (fn === undefined) { _unbindevent(el, type, events[0]); delete _eventdata[id][type]; } else { _each(events, function(i, event) { if (i > 0 && event === fn) { events.splice(i, 1); } }); if (events.length == 1) { _unbindevent(el, type, events[0]); delete _eventdata[id][type]; } } var count = 0; _each(_eventdata[id], function() { count++; }); if (count < 2) { delete _eventdata[id]; _removeid(el); } } } function _fire(el, type) { if (type.indexof(',') >= 0) { _each(type.split(','), function() { _fire(el, this); }); return; } var id = _getid(el); if (!id) { return; } var events = _eventdata[id][type]; if (_eventdata[id] && events && events.length > 0) { events[0](); } } function _ctrl(el, key, fn) { var self = this; key = /^\d{2,}$/.test(key) ? key : key.touppercase().charcodeat(0); _bind(el, 'keydown', function(e) { if (e.ctrlkey && e.which == key && !e.shiftkey && !e.altkey) { fn.call(el); e.stop(); } }); } function _ready(fn) { var loaded = false; function readyfunc() { if (!loaded) { loaded = true; fn(kindeditor); } } function iereadyfunc() { if (!loaded) { try { document.documentelement.doscroll('left'); } catch(e) { settimeout(iereadyfunc, 100); return; } readyfunc(); } } function iereadystatefunc() { if (document.readystate === 'complete') { readyfunc(); } } if (document.addeventlistener) { _bind(document, 'domcontentloaded', readyfunc); } else if (document.attachevent) { _bind(document, 'readystatechange', iereadystatefunc); var toplevel = false; try { toplevel = window.frameelement == null; } catch(e) {} if (document.documentelement.doscroll && toplevel) { iereadyfunc(); } } _bind(window, 'load', readyfunc); } if (_ie) { window.attachevent('onunload', function() { _each(_eventdata, function(key, events) { if (events.el) { _unbind(events.el); } }); }); } k.ctrl = _ctrl; k.ready = _ready; function _getcsslist(css) { var list = {}, reg = /\s*([\w\-]+)\s*:([^;]*)(;|$)/g, match; while ((match = reg.exec(css))) { var key = _trim(match[1].tolowercase()), val = _trim(_tohex(match[2])); list[key] = val; } return list; } function _getattrlist(tag) { var list = {}, reg = /\s+(?:([\w\-:]+)|(?:([\w\-:]+)=([^\s"'<>]+))|(?:([\w\-:"]+)="([^"]*)")|(?:([\w\-:"]+)='([^']*)'))(?=(?:\s|\/|>)+)/g, match; while ((match = reg.exec(tag))) { var key = (match[1] || match[2] || match[4] || match[6]).tolowercase(), val = (match[2] ? match[3] : (match[4] ? match[5] : match[7])) || ''; list[key] = val; } return list; } function _addclasstotag(tag, classname) { if (/\s+class\s*=/.test(tag)) { tag = tag.replace(/(\s+class=["']?)([^"']*)(["']?[\s>])/, function($0, $1, $2, $3) { if ((' ' + $2 + ' ').indexof(' ' + classname + ' ') < 0) { return $2 === '' ? $1 + classname + $3 : $1 + $2 + ' ' + classname + $3; } else { return $0; } }); } else { tag = tag.substr(0, tag.length - 1) + ' class="' + classname + '">'; } return tag; } function _formatcss(css) { var str = ''; _each(_getcsslist(css), function(key, val) { str += key + ':' + val + ';'; }); return str; } function _formaturl(url, mode, host, pathname) { mode = _undef(mode, '').tolowercase(); if (url.substr(0, 5) != 'data:') { url = url.replace(/([^:])\/\//g, '$1/'); } if (_inarray(mode, ['absolute', 'relative', 'domain']) < 0) { return url; } host = host || location.protocol + '//' + location.host; if (pathname === undefined) { var m = location.pathname.match(/^(\/.*)\//); pathname = m ? m[1] : ''; } var match; if ((match = /^(\w+:\/\/[^\/]*)/.exec(url))) { if (match[1] !== host) { return url; } } else if (/^\w+:/.test(url)) { return url; } function getrealpath(path) { var parts = path.split('/'), paths = []; for (var i = 0, len = parts.length; i < len; i++) { var part = parts[i]; if (part == '..') { if (paths.length > 0) { paths.pop(); } } else if (part !== '' && part != '.') { paths.push(part); } } return '/' + paths.join('/'); } if (/^\//.test(url)) { url = host + getrealpath(url.substr(1)); } else if (!/^\w+:\/\//.test(url)) { url = host + getrealpath(pathname + '/' + url); } function getrelativepath(path, depth) { if (url.substr(0, path.length) === path) { var arr = []; for (var i = 0; i < depth; i++) { arr.push('..'); } var prefix = '.'; if (arr.length > 0) { prefix += '/' + arr.join('/'); } if (pathname == '/') { prefix += '/'; } return prefix + url.substr(path.length); } else { if ((match = /^(.*)\//.exec(path))) { return getrelativepath(match[1], ++depth); } } } if (mode === 'relative') { url = getrelativepath(host + pathname, 0).substr(2); } else if (mode === 'absolute') { if (url.substr(0, host.length) === host) { url = url.substr(host.length); } } return url; } function _formathtml(html, htmltags, urltype, wellformatted, indentchar) { urltype = urltype || ''; wellformatted = _undef(wellformatted, false); indentchar = _undef(indentchar, '\t'); var fontsizelist = 'xx-small,x-small,small,medium,large,x-large,xx-large'.split(','); html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\s]*?)(<\/pre>)/ig, function($0, $1, $2, $3) { return $1 + $2.replace(/<(?:br|br\s[^>]*)>/ig, '\n') + $3; }); html = html.replace(/<(?:br|br\s[^>]*)\s*\/?>\s*<\/p>/ig, '

'); html = html.replace(/(<(?:p|p\s[^>]*)>)\s*(<\/p>)/ig, '$1
$2'); html = html.replace(/\u200b/g, ''); html = html.replace(/\u00a9/g, '©'); var htmltagmap = {}; if (htmltags) { _each(htmltags, function(key, val) { var arr = key.split(','); for (var i = 0, len = arr.length; i < len; i++) { htmltagmap[arr[i]] = _tomap(val); } }); if (!htmltagmap.script) { html = html.replace(/(<(?:script|script\s[^>]*)>)([\s\s]*?)(<\/script>)/ig, ''); } if (!htmltagmap.style) { html = html.replace(/(<(?:style|style\s[^>]*)>)([\s\s]*?)(<\/style>)/ig, ''); } } var re = /([ \t\n\r]*)<(\/)?([\w\-:]+)((?:\s+|(?:\s+[\w\-:]+)|(?:\s+[\w\-:]+=[^\s"'<>]+)|(?:\s+[\w\-:"]+="[^"]*")|(?:\s+[\w\-:"]+='[^']*'))*)(\/)?>([ \t\n\r]*)/g; var tagstack = []; html = html.replace(re, function($0, $1, $2, $3, $4, $5, $6) { var full = $0, startnewline = $1 || '', startslash = $2 || '', tagname = $3.tolowercase(), attr = $4 || '', endslash = $5 ? ' ' + $5 : '', endnewline = $6 || ''; if (htmltags && !htmltagmap[tagname]) { return ''; } if (endslash === '' && _single_tag_map[tagname]) { endslash = ' /'; } if (_inline_tag_map[tagname]) { if (startnewline) { startnewline = ' '; } if (endnewline) { endnewline = ' '; } } if (_pre_tag_map[tagname]) { if (startslash) { endnewline = '\n'; } else { startnewline = '\n'; } } if (wellformatted && tagname == 'br') { endnewline = '\n'; } if (_block_tag_map[tagname] && !_pre_tag_map[tagname]) { if (wellformatted) { if (startslash && tagstack.length > 0 && tagstack[tagstack.length - 1] === tagname) { tagstack.pop(); } else { tagstack.push(tagname); } startnewline = '\n'; endnewline = '\n'; for (var i = 0, len = startslash ? tagstack.length : tagstack.length - 1; i < len; i++) { startnewline += indentchar; if (!startslash) { endnewline += indentchar; } } if (endslash) { tagstack.pop(); } else if (!startslash) { endnewline += indentchar; } } else { startnewline = endnewline = ''; } } if (attr !== '') { var attrmap = _getattrlist(full); if (tagname === 'font') { var fontstylemap = {}, fontstyle = ''; _each(attrmap, function(key, val) { if (key === 'color') { fontstylemap.color = val; delete attrmap[key]; } if (key === 'size') { fontstylemap['font-size'] = fontsizelist[parseint(val, 10) - 1] || ''; delete attrmap[key]; } if (key === 'face') { fontstylemap['font-family'] = val; delete attrmap[key]; } if (key === 'style') { fontstyle = val; } }); if (fontstyle && !/;$/.test(fontstyle)) { fontstyle += ';'; } _each(fontstylemap, function(key, val) { if (val === '') { return; } if (/\s/.test(val)) { val = "'" + val + "'"; } fontstyle += key + ':' + val + ';'; }); attrmap.style = fontstyle; } _each(attrmap, function(key, val) { if (_fill_attr_map[key]) { attrmap[key] = key; } if (_inarray(key, ['src', 'href']) >= 0) { attrmap[key] = _formaturl(val, urltype); } if (htmltags && key !== 'style' && !htmltagmap[tagname]['*'] && !htmltagmap[tagname][key] || tagname === 'body' && key === 'contenteditable' || /^kindeditor_\d+$/.test(key)) { delete attrmap[key]; } if (key === 'style' && val !== '') { var stylemap = _getcsslist(val); _each(stylemap, function(k, v) { if (htmltags && !htmltagmap[tagname].style && !htmltagmap[tagname]['.' + k]) { delete stylemap[k]; } }); var style = ''; _each(stylemap, function(k, v) { style += k + ':' + v + ';'; }); attrmap.style = style; } }); attr = ''; _each(attrmap, function(key, val) { if (key === 'style' && val === '') { return; } val = val.replace(/"/g, '"'); attr += ' ' + key + '="' + val + '"'; }); } if (tagname === 'font') { tagname = 'span'; } return startnewline + '<' + startslash + tagname + attr + endslash + '>' + endnewline; }); html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\s]*?)(<\/pre>)/ig, function($0, $1, $2, $3) { return $1 + $2.replace(/\n/g, '\n') + $3; }); html = html.replace(/\n\s*\n/g, '\n'); html = html.replace(/\n/g, '\n'); return _trim(html); } function _clearmsword(html, htmltags) { html = html.replace(//ig, '') .replace(//ig, '') .replace(/]*>[\s\s]*?<\/style>/ig, '') .replace(/]*>[\s\s]*?<\/script>/ig, '') .replace(/]+>[\s\s]*?<\/w:[^>]+>/ig, '') .replace(/]+>[\s\s]*?<\/o:[^>]+>/ig, '') .replace(/[\s\s]*?<\/xml>/ig, '') .replace(/<(?:table|td)[^>]*>/ig, function(full) { return full.replace(/border-bottom:([#\w\s]+)/ig, 'border:$1'); }); return _formathtml(html, htmltags); } function _mediatype(src) { if (/\.(rm|rmvb)(\?|$)/i.test(src)) { return 'audio/x-pn-realaudio-plugin'; } //tangjunping 2012-11-27修改 if (/\.(flv)(\?|$)/i.test(src)) { return 'application/x-shockwave-flv'; } if (/\.(swf)(\?|$)/i.test(src)) { return 'application/x-shockwave-flash'; } // if (/\.(swf|flv)(\?|$)/i.test(src)) { // return 'application/x-shockwave-flash'; // } return 'video/x-ms-asf-plugin'; } function _mediaclass(type) { if (/realaudio/i.test(type)) { return 'ke-rm'; } if (/flash/i.test(type)) { return 'ke-flash'; } //tangjunping 2012-11-27添加 if (/flv/i.test(type)) { return 'ke-flv'; } return 'ke-media'; } function _mediaattrs(srctag) { return _getattrlist(unescape(srctag)); } function _mediaembed(attrs) { var html = ' 0) { style += 'width:' + width + 'px;'; } if (height > 0) { style += 'height:' + height + 'px;'; } var html = ''; return html; } function _tmpl(str, data) { var fn = new function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + "with(obj){p.push('" + str.replace(/[\r\t\n]/g, " ") .split("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');}return p.join('');"); return data ? fn(data) : fn; } k.formaturl = _formaturl; k.formathtml = _formathtml; k.getcsslist = _getcsslist; k.getattrlist = _getattrlist; k.mediatype = _mediatype; k.mediaattrs = _mediaattrs; k.mediaembed = _mediaembed; k.mediaimg = _mediaimg; k.clearmsword = _clearmsword; k.tmpl = _tmpl; function _contains(nodea, nodeb) { if (nodea.nodetype == 9 && nodeb.nodetype != 9) { return true; } while ((nodeb = nodeb.parentnode)) { if (nodeb == nodea) { return true; } } return false; } var _getsetattrdiv = document.createelement('div'); _getsetattrdiv.setattribute('classname', 't'); var _get_set_attribute = _getsetattrdiv.classname !== 't'; function _getattr(el, key) { key = key.tolowercase(); var val = null; if (!_get_set_attribute && el.nodename.tolowercase() != 'script') { var div = el.ownerdocument.createelement('div'); div.appendchild(el.clonenode(false)); var list = _getattrlist(_unescape(div.innerhtml)); if (key in list) { val = list[key]; } } else { try { val = el.getattribute(key, 2); } catch(e) { val = el.getattribute(key, 1); } } if (key === 'style' && val !== null) { val = _formatcss(val); } return val; } function _queryall(expr, root) { var exprlist = expr.split(','); if (exprlist.length > 1) { var mergedresults = []; _each(exprlist, function() { _each(_queryall(this, root), function() { if (_inarray(this, mergedresults) < 0) { mergedresults.push(this); } }); }); return mergedresults; } root = root || document; function escape(str) { if (typeof str != 'string') { return str; } return str.replace(/([^\w\-])/g, '\\$1'); } function stripslashes(str) { return str.replace(/\\/g, ''); } function cmptag(taga, tagb) { return taga === '*' || taga.tolowercase() === escape(tagb.tolowercase()); } function byid(id, tag, root) { var arr = [], doc = root.ownerdocument || root, el = doc.getelementbyid(stripslashes(id)); if (el) { if (cmptag(tag, el.nodename) && _contains(root, el)) { arr.push(el); } } return arr; } function byclass(classname, tag, root) { var doc = root.ownerdocument || root, arr = [], els, i, len, el; if (root.getelementsbyclassname) { els = root.getelementsbyclassname(stripslashes(classname)); for (i = 0, len = els.length; i < len; i++) { el = els[i]; if (cmptag(tag, el.nodename)) { arr.push(el); } } } else if (doc.queryselectorall) { els = doc.queryselectorall((root.nodename !== '#document' ? root.nodename + ' ' : '') + tag + '.' + classname); for (i = 0, len = els.length; i < len; i++) { el = els[i]; if (_contains(root, el)) { arr.push(el); } } } else { els = root.getelementsbytagname(tag); classname = ' ' + classname + ' '; for (i = 0, len = els.length; i < len; i++) { el = els[i]; if (el.nodetype == 1) { var cls = el.classname; if (cls && (' ' + cls + ' ').indexof(classname) > -1) { arr.push(el); } } } } return arr; } function byname(name, tag, root) { var arr = [], doc = root.ownerdocument || root, els = doc.getelementsbyname(stripslashes(name)), el; for (var i = 0, len = els.length; i < len; i++) { el = els[i]; if (cmptag(tag, el.nodename) && _contains(root, el)) { if (el.getattributenode('name')) { arr.push(el); } } } return arr; } function byattr(key, val, tag, root) { var arr = [], els = root.getelementsbytagname(tag), el; for (var i = 0, len = els.length; i < len; i++) { el = els[i]; if (el.nodetype == 1) { if (val === null) { if (_getattr(el, key) !== null) { arr.push(el); } } else { if (val === escape(_getattr(el, key))) { arr.push(el); } } } } return arr; } function select(expr, root) { var arr = [], matches; matches = /^((?:\\.|[^.#\s\[<>])+)/.exec(expr); var tag = matches ? matches[1] : '*'; if ((matches = /#((?:[\w\-]|\\.)+)$/.exec(expr))) { arr = byid(matches[1], tag, root); } else if ((matches = /\.((?:[\w\-]|\\.)+)$/.exec(expr))) { arr = byclass(matches[1], tag, root); } else if ((matches = /\[((?:[\w\-]|\\.)+)\]/.exec(expr))) { arr = byattr(matches[1].tolowercase(), null, tag, root); } else if ((matches = /\[((?:[\w\-]|\\.)+)\s*=\s*['"]?((?:\\.|[^'"]+)+)['"]?\]/.exec(expr))) { var key = matches[1].tolowercase(), val = matches[2]; if (key === 'id') { arr = byid(val, tag, root); } else if (key === 'class') { arr = byclass(val, tag, root); } else if (key === 'name') { arr = byname(val, tag, root); } else { arr = byattr(key, val, tag, root); } } else { var els = root.getelementsbytagname(tag), el; for (var i = 0, len = els.length; i < len; i++) { el = els[i]; if (el.nodetype == 1) { arr.push(el); } } } return arr; } var parts = [], arr, re = /((?:\\.|[^\s>])+|[\s>])/g; while ((arr = re.exec(expr))) { if (arr[1] !== ' ') { parts.push(arr[1]); } } var results = []; if (parts.length == 1) { return select(parts[0], root); } var ischild = false, part, els, subresults, val, v, i, j, k, length, len, l; for (i = 0, lenth = parts.length; i < lenth; i++) { part = parts[i]; if (part === '>') { ischild = true; continue; } if (i > 0) { els = []; for (j = 0, len = results.length; j < len; j++) { val = results[j]; subresults = select(part, val); for (k = 0, l = subresults.length; k < l; k++) { v = subresults[k]; if (ischild) { if (val === v.parentnode) { els.push(v); } } else { els.push(v); } } } results = els; } else { results = select(part, root); } if (results.length === 0) { return []; } } return results; } function _query(expr, root) { var arr = _queryall(expr, root); return arr.length > 0 ? arr[0] : null; } k.query = _query; k.queryall = _queryall; function _get(val) { return k(val)[0]; } function _getdoc(node) { if (!node) { return document; } return node.ownerdocument || node.document || node; } function _getwin(node) { if (!node) { return window; } var doc = _getdoc(node); return doc.parentwindow || doc.defaultview; } function _sethtml(el, html) { if (el.nodetype != 1) { return; } var doc = _getdoc(el); try { el.innerhtml = '' + html; var temp = doc.getelementbyid('__kindeditor_temp_tag__'); temp.parentnode.removechild(temp); } catch(e) { k(el).empty(); k('@' + html, doc).each(function() { el.appendchild(this); }); } } function _hasclass(el, cls) { return _instring(cls, el.classname, ' '); } function _setattr(el, key, val) { if (_ie && _v < 8 && key.tolowercase() == 'class') { key = 'classname'; } el.setattribute(key, '' + val); } function _removeattr(el, key) { if (_ie && _v < 8 && key.tolowercase() == 'class') { key = 'classname'; } _setattr(el, key, ''); el.removeattribute(key); } function _getnodename(node) { if (!node || !node.nodename) { return ''; } return node.nodename.tolowercase(); } function _computedcss(el, key) { var self = this, win = _getwin(el), camelkey = _tocamel(key), val = ''; if (win.getcomputedstyle) { var style = win.getcomputedstyle(el, null); val = style[camelkey] || style.getpropertyvalue(key) || el.style[camelkey]; } else if (el.currentstyle) { val = el.currentstyle[camelkey] || el.style[camelkey]; } return val; } function _hasval(node) { return !!_value_tag_map[_getnodename(node)]; } function _docelement(doc) { doc = doc || document; return _quirks ? doc.body : doc.documentelement; } function _docheight(doc) { var el = _docelement(doc); return math.max(el.scrollheight, el.clientheight); } function _docwidth(doc) { var el = _docelement(doc); return math.max(el.scrollwidth, el.clientwidth); } function _getscrollpos(doc) { doc = doc || document; var x, y; if (_ie || _opera) { x = _docelement(doc).scrollleft; y = _docelement(doc).scrolltop; } else { x = _getwin(doc).scrollx; y = _getwin(doc).scrolly; } return {x : x, y : y}; } function knode(node) { this.init(node); } _extend(knode, { init : function(node) { var self = this; node = _isarray(node) ? node : [node]; var length = 0; for (var i = 0, len = node.length; i < len; i++) { if (node[i]) { self[i] = node[i].constructor === knode ? node[i][0] : node[i]; length++; } } self.length = length; self.doc = _getdoc(self[0]); self.name = _getnodename(self[0]); self.type = self.length > 0 ? self[0].nodetype : null; self.win = _getwin(self[0]); }, each : function(fn) { var self = this; for (var i = 0; i < self.length; i++) { if (fn.call(self[i], i, self[i]) === false) { return self; } } return self; }, bind : function(type, fn) { this.each(function() { _bind(this, type, fn); }); return this; }, unbind : function(type, fn) { this.each(function() { _unbind(this, type, fn); }); return this; }, fire : function(type) { if (this.length < 1) { return this; } _fire(this[0], type); return this; }, hasattr : function(key) { if (this.length < 1) { return false; } return !!_getattr(this[0], key); }, attr : function(key, val) { var self = this; if (key === undefined) { return _getattrlist(self.outer()); } if (typeof key === 'object') { _each(key, function(k, v) { self.attr(k, v); }); return self; } if (val === undefined) { val = self.length < 1 ? null : _getattr(self[0], key); return val === null ? '' : val; } self.each(function() { _setattr(this, key, val); }); return self; }, removeattr : function(key) { this.each(function() { _removeattr(this, key); }); return this; }, get : function(i) { if (this.length < 1) { return null; } return this[i || 0]; }, eq : function(i) { if (this.length < 1) { return null; } return this[i] ? new knode(this[i]) : null; }, hasclass : function(cls) { if (this.length < 1) { return false; } return _hasclass(this[0], cls); }, addclass : function(cls) { this.each(function() { if (!_hasclass(this, cls)) { this.classname = _trim(this.classname + ' ' + cls); } }); return this; }, removeclass : function(cls) { this.each(function() { if (_hasclass(this, cls)) { this.classname = _trim(this.classname.replace(new regexp('(^|\\s)' + cls + '(\\s|$)'), ' ')); } }); return this; }, html : function(val) { var self = this; if (val === undefined) { if (self.length < 1 || self.type != 1) { return ''; } return _formathtml(self[0].innerhtml); } self.each(function() { _sethtml(this, val); }); return self; }, text : function() { var self = this; if (self.length < 1) { return ''; } return _ie ? self[0].innertext : self[0].textcontent; }, hasval : function() { if (this.length < 1) { return false; } return _hasval(this[0]); }, val : function(val) { var self = this; if (val === undefined) { if (self.length < 1) { return ''; } return self.hasval() ? self[0].value : self.attr('value'); } else { self.each(function() { if (_hasval(this)) { this.value = val; } else { _setattr(this, 'value' , val); } }); return self; } }, css : function(key, val) { var self = this; if (key === undefined) { return _getcsslist(self.attr('style')); } if (typeof key === 'object') { _each(key, function(k, v) { self.css(k, v); }); return self; } if (val === undefined) { if (self.length < 1) { return ''; } return self[0].style[_tocamel(key)] || _computedcss(self[0], key) || ''; } self.each(function() { this.style[_tocamel(key)] = val; }); return self; }, width : function(val) { var self = this; if (val === undefined) { if (self.length < 1) { return 0; } return self[0].offsetwidth; } return self.css('width', _addunit(val)); }, height : function(val) { var self = this; if (val === undefined) { if (self.length < 1) { return 0; } return self[0].offsetheight; } return self.css('height', _addunit(val)); }, opacity : function(val) { this.each(function() { if (this.style.opacity === undefined) { this.style.filter = val == 1 ? '' : 'alpha(opacity=' + (val * 100) + ')'; } else { this.style.opacity = val == 1 ? '' : val; } }); return this; }, data : function(key, val) { var self = this; key = 'kindeditor_data_' + key; if (val === undefined) { if (self.length < 1) { return null; } return self[0][key]; } this.each(function() { this[key] = val; }); return self; }, pos : function() { var self = this, node = self[0], x = 0, y = 0; if (node) { if (node.getboundingclientrect) { var box = node.getboundingclientrect(), pos = _getscrollpos(self.doc); x = box.left + pos.x; y = box.top + pos.y; } else { while (node) { x += node.offsetleft; y += node.offsettop; node = node.offsetparent; } } } return {x : _round(x), y : _round(y)}; }, clone : function(bool) { if (this.length < 1) { return new knode([]); } return new knode(this[0].clonenode(bool)); }, append : function(expr) { this.each(function() { if (this.appendchild) { this.appendchild(_get(expr)); } }); return this; }, appendto : function(expr) { this.each(function() { _get(expr).appendchild(this); }); return this; }, before : function(expr) { this.each(function() { this.parentnode.insertbefore(_get(expr), this); }); return this; }, after : function(expr) { this.each(function() { if (this.nextsibling) { this.parentnode.insertbefore(_get(expr), this.nextsibling); } else { this.parentnode.appendchild(_get(expr)); } }); return this; }, replacewith : function(expr) { var nodes = []; this.each(function(i, node) { _unbind(node); var newnode = _get(expr); node.parentnode.replacechild(newnode, node); nodes.push(newnode); }); return k(nodes); }, empty : function() { var self = this; self.each(function(i, node) { var child = node.firstchild; while (child) { if (!node.parentnode) { return; } var next = child.nextsibling; child.parentnode.removechild(child); child = next; } }); return self; }, remove : function(keepchilds) { var self = this; self.each(function(i, node) { if (!node.parentnode) { return; } _unbind(node); if (keepchilds) { var child = node.firstchild; while (child) { var next = child.nextsibling; node.parentnode.insertbefore(child, node); child = next; } } node.parentnode.removechild(node); delete self[i]; }); self.length = 0; return self; }, show : function(val) { var self = this; if (val === undefined) { val = self._origindisplay || ''; } if (self.css('display') != 'none') { return self; } return self.css('display', val); }, hide : function() { var self = this; if (self.length < 1) { return self; } self._origindisplay = self[0].style.display; return self.css('display', 'none'); }, outer : function() { var self = this; if (self.length < 1) { return ''; } var div = self.doc.createelement('div'), html; div.appendchild(self[0].clonenode(true)); html = _formathtml(div.innerhtml); div = null; return html; }, issingle : function() { return !!_single_tag_map[this.name]; }, isinline : function() { return !!_inline_tag_map[this.name]; }, isblock : function() { return !!_block_tag_map[this.name]; }, isstyle : function() { return !!_style_tag_map[this.name]; }, iscontrol : function() { return !!_control_tag_map[this.name]; }, contains : function(othernode) { if (this.length < 1) { return false; } return _contains(this[0], _get(othernode)); }, parent : function() { if (this.length < 1) { return null; } var node = this[0].parentnode; return node ? new knode(node) : null; }, children : function() { if (this.length < 1) { return new knode([]); } var list = [], child = this[0].firstchild; while (child) { if (child.nodetype != 3 || _trim(child.nodevalue) !== '') { list.push(child); } child = child.nextsibling; } return new knode(list); }, first : function() { var list = this.children(); return list.length > 0 ? list.eq(0) : null; }, last : function() { var list = this.children(); return list.length > 0 ? list.eq(list.length - 1) : null; }, index : function() { if (this.length < 1) { return -1; } var i = -1, sibling = this[0]; while (sibling) { i++; sibling = sibling.previoussibling; } return i; }, prev : function() { if (this.length < 1) { return null; } var node = this[0].previoussibling; return node ? new knode(node) : null; }, next : function() { if (this.length < 1) { return null; } var node = this[0].nextsibling; return node ? new knode(node) : null; }, scan : function(fn, order) { if (this.length < 1) { return; } order = (order === undefined) ? true : order; function walk(node) { var n = order ? node.firstchild : node.lastchild; while (n) { var next = order ? n.nextsibling : n.previoussibling; if (fn(n) === false) { return false; } if (walk(n) === false) { return false; } n = next; } } walk(this[0]); return this; } }); _each(('blur,focus,focusin,focusout,load,resize,scroll,unload,click,dblclick,' + 'mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,' + 'change,select,submit,keydown,keypress,keyup,error,contextmenu').split(','), function(i, type) { knode.prototype[type] = function(fn) { return fn ? this.bind(type, fn) : this.fire(type); }; }); var _k = k; k = function(expr, root) { if (expr === undefined || expr === null) { return; } function newnode(node) { if (!node[0]) { node = []; } return new knode(node); } if (typeof expr === 'string') { if (root) { root = _get(root); } var length = expr.length; if (expr.charat(0) === '@') { expr = expr.substr(1); } if (expr.length !== length || /<.+>/.test(expr)) { var doc = root ? root.ownerdocument || root : document, div = doc.createelement('div'), list = []; div.innerhtml = '' + expr; for (var i = 0, len = div.childnodes.length; i < len; i++) { var child = div.childnodes[i]; if (child.id == '__kindeditor_temp_tag__') { continue; } list.push(child); } return newnode(list); } return newnode(_queryall(expr, root)); } if (expr && expr.constructor === knode) { return expr; } if (expr.toarray) { expr = expr.toarray(); } if (_isarray(expr)) { return newnode(expr); } return newnode(_toarray(arguments)); }; _each(_k, function(key, val) { k[key] = val; }); k.nodeclass = knode; window.kindeditor = k; var _start_to_start = 0, _start_to_end = 1, _end_to_end = 2, _end_to_start = 3, _bookmark_id = 0; function _updatecollapsed(range) { range.collapsed = (range.startcontainer === range.endcontainer && range.startoffset === range.endoffset); return range; } function _copyanddelete(range, iscopy, isdelete) { var doc = range.doc, nodelist = []; function splittextnode(node, startoffset, endoffset) { var length = node.nodevalue.length, centernode; if (iscopy) { var clonenode = node.clonenode(true); if (startoffset > 0) { centernode = clonenode.splittext(startoffset); } else { centernode = clonenode; } if (endoffset < length) { centernode.splittext(endoffset - startoffset); } } if (isdelete) { var center = node; if (startoffset > 0) { center = node.splittext(startoffset); range.setstart(node, startoffset); } if (endoffset < length) { var right = center.splittext(endoffset - startoffset); range.setend(right, 0); } nodelist.push(center); } return centernode; } function removenodes() { if (isdelete) { range.up().collapse(true); } for (var i = 0, len = nodelist.length; i < len; i++) { var node = nodelist[i]; if (node.parentnode) { node.parentnode.removechild(node); } } } var copyrange = range.clonerange().down(); var start = -1, incstart = -1, incend = -1, end = -1, ancestor = range.commonancestor(), frag = doc.createdocumentfragment(); if (ancestor.nodetype == 3) { var textnode = splittextnode(ancestor, range.startoffset, range.endoffset); if (iscopy) { frag.appendchild(textnode); } removenodes(); return iscopy ? frag : range; } function extractnodes(parent, frag) { var node = parent.firstchild, nextnode; while (node) { var testrange = new krange(doc).selectnode(node); start = testrange.compareboundarypoints(_start_to_end, range); if (start >= 0 && incstart <= 0) { incstart = testrange.compareboundarypoints(_start_to_start, range); } if (incstart >= 0 && incend <= 0) { incend = testrange.compareboundarypoints(_end_to_end, range); } if (incend >= 0 && end <= 0) { end = testrange.compareboundarypoints(_end_to_start, range); } if (end >= 0) { return false; } nextnode = node.nextsibling; if (start > 0) { if (node.nodetype == 1) { if (incstart >= 0 && incend <= 0) { if (iscopy) { frag.appendchild(node.clonenode(true)); } if (isdelete) { nodelist.push(node); } } else { var childflag; if (iscopy) { childflag = node.clonenode(false); frag.appendchild(childflag); } if (extractnodes(node, childflag) === false) { return false; } } } else if (node.nodetype == 3) { var textnode; if (node == copyrange.startcontainer) { textnode = splittextnode(node, copyrange.startoffset, node.nodevalue.length); } else if (node == copyrange.endcontainer) { textnode = splittextnode(node, 0, copyrange.endoffset); } else { textnode = splittextnode(node, 0, node.nodevalue.length); } if (iscopy) { try { frag.appendchild(textnode); } catch(e) {} } } } node = nextnode; } } extractnodes(ancestor, frag); if (isdelete) { range.up().collapse(true); } for (var i = 0, len = nodelist.length; i < len; i++) { var node = nodelist[i]; if (node.parentnode) { node.parentnode.removechild(node); } } return iscopy ? frag : range; } function _movetoelementtext(range, el) { var node = el; while (node) { var knode = k(node); if (knode.name == 'marquee' || knode.name == 'select') { return; } node = node.parentnode; } try { range.movetoelementtext(el); } catch(e) {} } function _getstartend(rng, isstart) { var doc = rng.parentelement().ownerdocument, pointrange = rng.duplicate(); pointrange.collapse(isstart); var parent = pointrange.parentelement(), nodes = parent.childnodes; if (nodes.length === 0) { return {node: parent.parentnode, offset: k(parent).index()}; } var startnode = doc, startpos = 0, cmp = -1; var testrange = rng.duplicate(); _movetoelementtext(testrange, parent); for (var i = 0, len = nodes.length; i < len; i++) { var node = nodes[i]; cmp = testrange.compareendpoints('starttostart', pointrange); if (cmp === 0) { return {node: node.parentnode, offset: i}; } if (node.nodetype == 1) { var noderange = rng.duplicate(), dummy, knode = k(node), newnode = node; if (knode.iscontrol()) { dummy = doc.createelement('span'); knode.after(dummy); newnode = dummy; startpos += knode.text().replace(/\r\n|\n|\r/g, '').length; } _movetoelementtext(noderange, newnode); testrange.setendpoint('starttoend', noderange); if (cmp > 0) { startpos += noderange.text.replace(/\r\n|\n|\r/g, '').length; } else { startpos = 0; } if (dummy) { k(dummy).remove(); } } else if (node.nodetype == 3) { testrange.movestart('character', node.nodevalue.length); startpos += node.nodevalue.length; } if (cmp < 0) { startnode = node; } } if (cmp < 0 && startnode.nodetype == 1) { return {node: parent, offset: k(parent.lastchild).index() + 1}; } if (cmp > 0) { while (startnode.nextsibling && startnode.nodetype == 1) { startnode = startnode.nextsibling; } } testrange = rng.duplicate(); _movetoelementtext(testrange, parent); testrange.setendpoint('starttoend', pointrange); startpos -= testrange.text.replace(/\r\n|\n|\r/g, '').length; if (cmp > 0 && startnode.nodetype == 3) { var prevnode = startnode.previoussibling; while (prevnode && prevnode.nodetype == 3) { startpos -= prevnode.nodevalue.length; prevnode = prevnode.previoussibling; } } return {node: startnode, offset: startpos}; } function _getendrange(node, offset) { var doc = node.ownerdocument || node, range = doc.body.createtextrange(); if (doc == node) { range.collapse(true); return range; } if (node.nodetype == 1 && node.childnodes.length > 0) { var children = node.childnodes, isstart, child; if (offset === 0) { child = children[0]; isstart = true; } else { child = children[offset - 1]; isstart = false; } if (!child) { return range; } if (k(child).name === 'head') { if (offset === 1) { isstart = true; } if (offset === 2) { isstart = false; } range.collapse(isstart); return range; } if (child.nodetype == 1) { var kchild = k(child), span; if (kchild.iscontrol()) { span = doc.createelement('span'); if (isstart) { kchild.before(span); } else { kchild.after(span); } child = span; } _movetoelementtext(range, child); range.collapse(isstart); if (span) { k(span).remove(); } return range; } node = child; offset = isstart ? 0 : child.nodevalue.length; } var dummy = doc.createelement('span'); k(node).before(dummy); _movetoelementtext(range, dummy); range.movestart('character', offset); k(dummy).remove(); return range; } function _torange(rng) { var doc, range; function tr2td(start) { if (k(start.node).name == 'tr') { start.node = start.node.cells[start.offset]; start.offset = 0; } } if (_ie) { if (rng.item) { doc = _getdoc(rng.item(0)); range = new krange(doc); range.selectnode(rng.item(0)); return range; } doc = rng.parentelement().ownerdocument; var start = _getstartend(rng, true), end = _getstartend(rng, false); tr2td(start); tr2td(end); range = new krange(doc); range.setstart(start.node, start.offset); range.setend(end.node, end.offset); return range; } var startcontainer = rng.startcontainer; doc = startcontainer.ownerdocument || startcontainer; range = new krange(doc); range.setstart(startcontainer, rng.startoffset); range.setend(rng.endcontainer, rng.endoffset); return range; } function krange(doc) { this.init(doc); } _extend(krange, { init : function(doc) { var self = this; self.startcontainer = doc; self.startoffset = 0; self.endcontainer = doc; self.endoffset = 0; self.collapsed = true; self.doc = doc; }, commonancestor : function() { function getparents(node) { var parents = []; while (node) { parents.push(node); node = node.parentnode; } return parents; } var parentsa = getparents(this.startcontainer), parentsb = getparents(this.endcontainer), i = 0, lena = parentsa.length, lenb = parentsb.length, parenta, parentb; while (++i) { parenta = parentsa[lena - i]; parentb = parentsb[lenb - i]; if (!parenta || !parentb || parenta !== parentb) { break; } } return parentsa[lena - i + 1]; }, setstart : function(node, offset) { var self = this, doc = self.doc; self.startcontainer = node; self.startoffset = offset; if (self.endcontainer === doc) { self.endcontainer = node; self.endoffset = offset; } return _updatecollapsed(this); }, setend : function(node, offset) { var self = this, doc = self.doc; self.endcontainer = node; self.endoffset = offset; if (self.startcontainer === doc) { self.startcontainer = node; self.startoffset = offset; } return _updatecollapsed(this); }, setstartbefore : function(node) { return this.setstart(node.parentnode || this.doc, k(node).index()); }, setstartafter : function(node) { return this.setstart(node.parentnode || this.doc, k(node).index() + 1); }, setendbefore : function(node) { return this.setend(node.parentnode || this.doc, k(node).index()); }, setendafter : function(node) { return this.setend(node.parentnode || this.doc, k(node).index() + 1); }, selectnode : function(node) { return this.setstartbefore(node).setendafter(node); }, selectnodecontents : function(node) { var knode = k(node); if (knode.type == 3 || knode.issingle()) { return this.selectnode(node); } var children = knode.children(); if (children.length > 0) { return this.setstartbefore(children[0]).setendafter(children[children.length - 1]); } return this.setstart(node, 0).setend(node, 0); }, collapse : function(tostart) { if (tostart) { return this.setend(this.startcontainer, this.startoffset); } return this.setstart(this.endcontainer, this.endoffset); }, compareboundarypoints : function(how, range) { var rangea = this.get(), rangeb = range.get(); if (_ie) { var arr = {}; arr[_start_to_start] = 'starttostart'; arr[_start_to_end] = 'endtostart'; arr[_end_to_end] = 'endtoend'; arr[_end_to_start] = 'starttoend'; var cmp = rangea.compareendpoints(arr[how], rangeb); if (cmp !== 0) { return cmp; } var nodea, nodeb, nodec, posa, posb; if (how === _start_to_start || how === _end_to_start) { nodea = this.startcontainer; posa = this.startoffset; } if (how === _start_to_end || how === _end_to_end) { nodea = this.endcontainer; posa = this.endoffset; } if (how === _start_to_start || how === _start_to_end) { nodeb = range.startcontainer; posb = range.startoffset; } if (how === _end_to_end || how === _end_to_start) { nodeb = range.endcontainer; posb = range.endoffset; } if (nodea === nodeb) { var diff = posa - posb; return diff > 0 ? 1 : (diff < 0 ? -1 : 0); } nodec = nodeb; while (nodec && nodec.parentnode !== nodea) { nodec = nodec.parentnode; } if (nodec) { return k(nodec).index() >= posa ? -1 : 1; } nodec = nodea; while (nodec && nodec.parentnode !== nodeb) { nodec = nodec.parentnode; } if (nodec) { return k(nodec).index() >= posb ? 1 : -1; } nodec = k(nodeb).next(); if (nodec && nodec.contains(nodea)) { return 1; } nodec = k(nodea).next(); if (nodec && nodec.contains(nodeb)) { return -1; } } else { return rangea.compareboundarypoints(how, rangeb); } }, clonerange : function() { return new krange(this.doc).setstart(this.startcontainer, this.startoffset).setend(this.endcontainer, this.endoffset); }, tostring : function() { var rng = this.get(), str = _ie ? rng.text : rng.tostring(); return str.replace(/\r\n|\n|\r/g, ''); }, clonecontents : function() { return _copyanddelete(this, true, false); }, deletecontents : function() { return _copyanddelete(this, false, true); }, extractcontents : function() { return _copyanddelete(this, true, true); }, insertnode : function(node) { var self = this, sc = self.startcontainer, so = self.startoffset, ec = self.endcontainer, eo = self.endoffset, firstchild, lastchild, c, nodecount = 1; if (node.nodename.tolowercase() === '#document-fragment') { firstchild = node.firstchild; lastchild = node.lastchild; nodecount = node.childnodes.length; } if (sc.nodetype == 1) { c = sc.childnodes[so]; if (c) { sc.insertbefore(node, c); if (sc === ec) { eo += nodecount; } } else { sc.appendchild(node); } } else if (sc.nodetype == 3) { if (so === 0) { sc.parentnode.insertbefore(node, sc); if (sc.parentnode === ec) { eo += nodecount; } } else if (so >= sc.nodevalue.length) { if (sc.nextsibling) { sc.parentnode.insertbefore(node, sc.nextsibling); } else { sc.parentnode.appendchild(node); } } else { if (so > 0) { c = sc.splittext(so); } else { c = sc; } sc.parentnode.insertbefore(node, c); if (sc === ec) { ec = c; eo -= so; } } } if (firstchild) { self.setstartbefore(firstchild).setendafter(lastchild); } else { self.selectnode(node); } if (self.compareboundarypoints(_end_to_end, self.clonerange().setend(ec, eo)) >= 1) { return self; } return self.setend(ec, eo); }, surroundcontents : function(node) { node.appendchild(this.extractcontents()); return this.insertnode(node).selectnode(node); }, iscontrol : function() { var self = this, sc = self.startcontainer, so = self.startoffset, ec = self.endcontainer, eo = self.endoffset, rng; return sc.nodetype == 1 && sc === ec && so + 1 === eo && k(sc.childnodes[so]).iscontrol(); }, get : function(hascontrolrange) { var self = this, doc = self.doc, node, rng; if (!_ie) { rng = doc.createrange(); try { rng.setstart(self.startcontainer, self.startoffset); rng.setend(self.endcontainer, self.endoffset); } catch (e) {} return rng; } if (hascontrolrange && self.iscontrol()) { rng = doc.body.createcontrolrange(); rng.addelement(self.startcontainer.childnodes[self.startoffset]); return rng; } var range = self.clonerange().down(); rng = doc.body.createtextrange(); rng.setendpoint('starttostart', _getendrange(range.startcontainer, range.startoffset)); rng.setendpoint('endtostart', _getendrange(range.endcontainer, range.endoffset)); return rng; }, html : function() { return k(this.clonecontents()).outer(); }, down : function() { var self = this; function downpos(node, pos, isstart) { if (node.nodetype != 1) { return; } var children = k(node).children(); if (children.length === 0) { return; } var left, right, child, offset; if (pos > 0) { left = children.eq(pos - 1); } if (pos < children.length) { right = children.eq(pos); } if (left && left.type == 3) { child = left[0]; offset = child.nodevalue.length; } if (right && right.type == 3) { child = right[0]; offset = 0; } if (!child) { return; } if (isstart) { self.setstart(child, offset); } else { self.setend(child, offset); } } downpos(self.startcontainer, self.startoffset, true); downpos(self.endcontainer, self.endoffset, false); return self; }, up : function() { var self = this; function uppos(node, pos, isstart) { if (node.nodetype != 3) { return; } if (pos === 0) { if (isstart) { self.setstartbefore(node); } else { self.setendbefore(node); } } else if (pos == node.nodevalue.length) { if (isstart) { self.setstartafter(node); } else { self.setendafter(node); } } } uppos(self.startcontainer, self.startoffset, true); uppos(self.endcontainer, self.endoffset, false); return self; }, enlarge : function(toblock) { var self = this; self.up(); function enlargepos(node, pos, isstart) { var knode = k(node), parent; if (knode.type == 3 || _nosplit_tag_map[knode.name] || !toblock && knode.isblock()) { return; } if (pos === 0) { while (!knode.prev()) { parent = knode.parent(); if (!parent || _nosplit_tag_map[parent.name] || !toblock && parent.isblock()) { break; } knode = parent; } if (isstart) { self.setstartbefore(knode[0]); } else { self.setendbefore(knode[0]); } } else if (pos == knode.children().length) { while (!knode.next()) { parent = knode.parent(); if (!parent || _nosplit_tag_map[parent.name] || !toblock && parent.isblock()) { break; } knode = parent; } if (isstart) { self.setstartafter(knode[0]); } else { self.setendafter(knode[0]); } } } enlargepos(self.startcontainer, self.startoffset, true); enlargepos(self.endcontainer, self.endoffset, false); return self; }, shrink : function() { var self = this, child, collapsed = self.collapsed; while (self.startcontainer.nodetype == 1 && (child = self.startcontainer.childnodes[self.startoffset]) && child.nodetype == 1 && !k(child).issingle()) { self.setstart(child, 0); } if (collapsed) { return self.collapse(collapsed); } while (self.endcontainer.nodetype == 1 && self.endoffset > 0 && (child = self.endcontainer.childnodes[self.endoffset - 1]) && child.nodetype == 1 && !k(child).issingle()) { self.setend(child, child.childnodes.length); } return self; }, createbookmark : function(serialize) { var self = this, doc = self.doc, endnode, startnode = k('', doc)[0]; startnode.id = '__kindeditor_bookmark_start_' + (_bookmark_id++) + '__'; if (!self.collapsed) { endnode = startnode.clonenode(true); endnode.id = '__kindeditor_bookmark_end_' + (_bookmark_id++) + '__'; } if (endnode) { self.clonerange().collapse(false).insertnode(endnode).setendbefore(endnode); } self.insertnode(startnode).setstartafter(startnode); return { start : serialize ? '#' + startnode.id : startnode, end : endnode ? (serialize ? '#' + endnode.id : endnode) : null }; }, movetobookmark : function(bookmark) { var self = this, doc = self.doc, start = k(bookmark.start, doc), end = bookmark.end ? k(bookmark.end, doc) : null; if (!start || start.length < 1) { return self; } self.setstartbefore(start[0]); start.remove(); if (end && end.length > 0) { self.setendbefore(end[0]); end.remove(); } else { self.collapse(true); } return self; }, dump : function() { console.log('--------------------'); console.log(this.startcontainer.nodetype == 3 ? this.startcontainer.nodevalue : this.startcontainer, this.startoffset); console.log(this.endcontainer.nodetype == 3 ? this.endcontainer.nodevalue : this.endcontainer, this.endoffset); } }); function _range(mixed) { if (!mixed.nodename) { return mixed.constructor === krange ? mixed : _torange(mixed); } return new krange(mixed); } k.rangeclass = krange; k.range = _range; k.start_to_start = _start_to_start; k.start_to_end = _start_to_end; k.end_to_end = _end_to_end; k.end_to_start = _end_to_start; function _nativecommand(doc, key, val) { try { doc.execcommand(key, false, val); } catch(e) {} } function _nativecommandvalue(doc, key) { var val = ''; try { val = doc.querycommandvalue(key); } catch (e) {} if (typeof val !== 'string') { val = ''; } return val; } function _getsel(doc) { var win = _getwin(doc); return doc.selection || win.getselection(); } function _getrng(doc) { var sel = _getsel(doc), rng; try { if (sel.rangecount > 0) { rng = sel.getrangeat(0); } else { rng = sel.createrange(); } } catch(e) {} if (_ie && (!rng || (!rng.item && rng.parentelement().ownerdocument !== doc))) { return null; } return rng; } function _singlekeymap(map) { var newmap = {}, arr, v; _each(map, function(key, val) { arr = key.split(','); for (var i = 0, len = arr.length; i < len; i++) { v = arr[i]; newmap[v] = val; } }); return newmap; } function _hasattrorcss(knode, map) { return _hasattrorcssbykey(knode, map, '*') || _hasattrorcssbykey(knode, map); } function _hasattrorcssbykey(knode, map, mapkey) { mapkey = mapkey || knode.name; if (knode.type !== 1) { return false; } var newmap = _singlekeymap(map); if (!newmap[mapkey]) { return false; } var arr = newmap[mapkey].split(','); for (var i = 0, len = arr.length; i < len; i++) { var key = arr[i]; if (key === '*') { return true; } var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key); var method = match[1] ? 'css' : 'attr'; key = match[2]; var val = match[3] || ''; if (val === '' && knode[method](key) !== '') { return true; } if (val !== '' && knode[method](key) === val) { return true; } } return false; } function _removeattrorcss(knode, map) { if (knode.type != 1) { return; } _removeattrorcssbykey(knode, map, '*'); _removeattrorcssbykey(knode, map); } function _removeattrorcssbykey(knode, map, mapkey) { mapkey = mapkey || knode.name; if (knode.type !== 1) { return; } var newmap = _singlekeymap(map); if (!newmap[mapkey]) { return; } var arr = newmap[mapkey].split(','), allflag = false; for (var i = 0, len = arr.length; i < len; i++) { var key = arr[i]; if (key === '*') { allflag = true; break; } var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key); key = match[2]; if (match[1]) { key = _tocamel(key); if (knode[0].style[key]) { knode[0].style[key] = ''; } } else { knode.removeattr(key); } } if (allflag) { knode.remove(true); } } function _getinnernode(knode) { var inner = knode; while (inner.first()) { inner = inner.first(); } return inner; } function _isemptynode(knode) { return knode.type == 1 && knode.html().replace(/<[^>]+>/g, '') === ''; } function _mergewrapper(a, b) { a = a.clone(true); var lasta = _getinnernode(a), childa = a, merged = false; while (b) { while (childa) { if (childa.name === b.name) { _mergeattrs(childa, b.attr(), b.css()); merged = true; } childa = childa.first(); } if (!merged) { lasta.append(b.clone(false)); } merged = false; b = b.first(); } return a; } function _wrapnode(knode, wrapper) { wrapper = wrapper.clone(true); if (knode.type == 3) { _getinnernode(wrapper).append(knode.clone(false)); knode.replacewith(wrapper); return wrapper; } var nodewrapper = knode, child; while ((child = knode.first()) && child.children().length == 1) { knode = child; } child = knode.first(); var frag = knode.doc.createdocumentfragment(); while (child) { frag.appendchild(child[0]); child = child.next(); } wrapper = _mergewrapper(nodewrapper, wrapper); if (frag.firstchild) { _getinnernode(wrapper).append(frag); } nodewrapper.replacewith(wrapper); return wrapper; } function _mergeattrs(knode, attrs, styles) { _each(attrs, function(key, val) { if (key !== 'style') { knode.attr(key, val); } }); _each(styles, function(key, val) { knode.css(key, val); }); } function _inpreelement(knode) { while (knode && knode.name != 'body') { if (_pre_tag_map[knode.name] || knode.name == 'div' && knode.hasclass('ke-script')) { return true; } knode = knode.parent(); } return false; } function kcmd(range) { this.init(range); } _extend(kcmd, { init : function(range) { var self = this, doc = range.doc; self.doc = doc; self.win = _getwin(doc); self.sel = _getsel(doc); self.range = range; }, selection : function(forcereset) { var self = this, doc = self.doc, rng = _getrng(doc); self.sel = _getsel(doc); if (rng) { self.range = _range(rng); if (k(self.range.startcontainer).name == 'html') { self.range.selectnodecontents(doc.body).collapse(false); } return self; } if (forcereset) { self.range.selectnodecontents(doc.body).collapse(false); } return self; }, select : function(hasdummy) { hasdummy = _undef(hasdummy, true); var self = this, sel = self.sel, range = self.range.clonerange().shrink(), sc = range.startcontainer, so = range.startoffset, ec = range.endcontainer, eo = range.endoffset, doc = _getdoc(sc), win = self.win, rng, hasu200b = false; if (hasdummy && sc.nodetype == 1 && range.collapsed) { if (_ie) { var dummy = k(' ', doc); range.insertnode(dummy[0]); rng = doc.body.createtextrange(); try { rng.movetoelementtext(dummy[0]); } catch(ex) {} rng.collapse(false); rng.select(); dummy.remove(); win.focus(); return self; } if (_webkit) { var children = sc.childnodes; if (k(sc).isinline() || so > 0 && k(children[so - 1]).isinline() || children[so] && k(children[so]).isinline()) { range.insertnode(doc.createtextnode('\u200b')); hasu200b = true; } } } if (_ie) { try { rng = range.get(true); rng.select(); } catch(e) {} } else { if (hasu200b) { range.collapse(false); } rng = range.get(true); sel.removeallranges(); sel.addrange(rng); } win.focus(); return self; }, wrap : function(val) { var self = this, doc = self.doc, range = self.range, wrapper; wrapper = k(val, doc); if (range.collapsed) { range.shrink(); range.insertnode(wrapper[0]).selectnodecontents(wrapper[0]); return self; } if (wrapper.isblock()) { var copywrapper = wrapper.clone(true), child = copywrapper; while (child.first()) { child = child.first(); } child.append(range.extractcontents()); range.insertnode(copywrapper[0]).selectnode(copywrapper[0]); return self; } range.enlarge(); var bookmark = range.createbookmark(), ancestor = range.commonancestor(), isstart = false; k(ancestor).scan(function(node) { if (!isstart && node == bookmark.start) { isstart = true; return; } if (isstart) { if (node == bookmark.end) { return false; } var knode = k(node); if (_inpreelement(knode)) { return; } if (knode.type == 3 && _trim(node.nodevalue).length > 0) { var parent; while ((parent = knode.parent()) && parent.isstyle() && parent.children().length == 1) { knode = parent; } _wrapnode(knode, wrapper); } } }); range.movetobookmark(bookmark); return self; }, split : function(isstart, map) { var range = this.range, doc = range.doc; var temprange = range.clonerange().collapse(isstart); var node = temprange.startcontainer, pos = temprange.startoffset, parent = node.nodetype == 3 ? node.parentnode : node, needsplit = false, knode; while (parent && parent.parentnode) { knode = k(parent); if (map) { if (!knode.isstyle()) { break; } if (!_hasattrorcss(knode, map)) { break; } } else { if (_nosplit_tag_map[knode.name]) { break; } } needsplit = true; parent = parent.parentnode; } if (needsplit) { var dummy = doc.createelement('span'); range.clonerange().collapse(!isstart).insertnode(dummy); if (isstart) { temprange.setstartbefore(parent.firstchild).setend(node, pos); } else { temprange.setstart(node, pos).setendafter(parent.lastchild); } var frag = temprange.extractcontents(), first = frag.firstchild, last = frag.lastchild; if (isstart) { temprange.insertnode(frag); range.setstartafter(last).setendbefore(dummy); } else { parent.appendchild(frag); range.setstartbefore(dummy).setendbefore(first); } var dummyparent = dummy.parentnode; if (dummyparent == range.endcontainer) { var prev = k(dummy).prev(), next = k(dummy).next(); if (prev && next && prev.type == 3 && next.type == 3) { range.setend(prev[0], prev[0].nodevalue.length); } else if (!isstart) { range.setend(range.endcontainer, range.endoffset - 1); } } dummyparent.removechild(dummy); } return this; }, remove : function(map) { var self = this, doc = self.doc, range = self.range; range.enlarge(); if (range.startoffset === 0) { var ksc = k(range.startcontainer), parent; while ((parent = ksc.parent()) && parent.isstyle() && parent.children().length == 1) { ksc = parent; } range.setstart(ksc[0], 0); ksc = k(range.startcontainer); if (ksc.isblock()) { _removeattrorcss(ksc, map); } var kscp = ksc.parent(); if (kscp && kscp.isblock()) { _removeattrorcss(kscp, map); } } var sc, so; if (range.collapsed) { self.split(true, map); sc = range.startcontainer; so = range.startoffset; if (so > 0) { var sb = k(sc.childnodes[so - 1]); if (sb && _isemptynode(sb)) { sb.remove(); range.setstart(sc, so - 1); } } var sa = k(sc.childnodes[so]); if (sa && _isemptynode(sa)) { sa.remove(); } if (_isemptynode(sc)) { range.startbefore(sc); sc.remove(); } range.collapse(true); return self; } self.split(true, map); self.split(false, map); var startdummy = doc.createelement('span'), enddummy = doc.createelement('span'); range.clonerange().collapse(false).insertnode(enddummy); range.clonerange().collapse(true).insertnode(startdummy); var nodelist = [], cmpstart = false; k(range.commonancestor()).scan(function(node) { if (!cmpstart && node == startdummy) { cmpstart = true; return; } if (node == enddummy) { return false; } if (cmpstart) { nodelist.push(node); } }); k(startdummy).remove(); k(enddummy).remove(); sc = range.startcontainer; so = range.startoffset; var ec = range.endcontainer, eo = range.endoffset; if (so > 0) { var startbefore = k(sc.childnodes[so - 1]); if (startbefore && _isemptynode(startbefore)) { startbefore.remove(); range.setstart(sc, so - 1); if (sc == ec) { range.setend(ec, eo - 1); } } var startafter = k(sc.childnodes[so]); if (startafter && _isemptynode(startafter)) { startafter.remove(); if (sc == ec) { range.setend(ec, eo - 1); } } } var endafter = k(ec.childnodes[range.endoffset]); if (endafter && _isemptynode(endafter)) { endafter.remove(); } var bookmark = range.createbookmark(true); _each(nodelist, function(i, node) { _removeattrorcss(k(node), map); }); range.movetobookmark(bookmark); return self; }, commonnode : function(map) { var range = this.range; var ec = range.endcontainer, eo = range.endoffset, node = (ec.nodetype == 3 || eo === 0) ? ec : ec.childnodes[eo - 1]; function find(node) { var child = node, parent = node; while (parent) { if (_hasattrorcss(k(parent), map)) { return k(parent); } parent = parent.parentnode; } while (child && (child = child.lastchild)) { if (_hasattrorcss(k(child), map)) { return k(child); } } return null; } var cnode = find(node); if (cnode) { return cnode; } if (node.nodetype == 1 || (ec.nodetype == 3 && eo === 0)) { var prev = k(node).prev(); if (prev) { return find(prev); } } return null; }, commonancestor : function(tagname) { var range = this.range, sc = range.startcontainer, so = range.startoffset, ec = range.endcontainer, eo = range.endoffset, startnode = (sc.nodetype == 3 || so === 0) ? sc : sc.childnodes[so - 1], endnode = (ec.nodetype == 3 || eo === 0) ? ec : ec.childnodes[eo - 1]; function find(node) { while (node) { if (node.nodetype == 1) { if (node.tagname.tolowercase() === tagname) { return node; } } node = node.parentnode; } return null; } var start = find(startnode), end = find(endnode); if (start && end && start === end) { return k(start); } return null; }, state : function(key) { var self = this, doc = self.doc, bool = false; try { bool = doc.querycommandstate(key); } catch (e) {} return bool; }, val : function(key) { var self = this, doc = self.doc, range = self.range; function lc(val) { return val.tolowercase(); } key = lc(key); var val = '', knode; if (key === 'fontfamily' || key === 'fontname') { val = _nativecommandvalue(doc, 'fontname'); val = val.replace(/['"]/g, ''); return lc(val); } if (key === 'formatblock') { val = _nativecommandvalue(doc, key); if (val === '') { knode = self.commonnode({'h1,h2,h3,h4,h5,h6,p,div,pre,address' : '*'}); if (knode) { val = knode.name; } } if (val === 'normal') { val = 'p'; } return lc(val); } if (key === 'fontsize') { knode = self.commonnode({'*' : '.font-size'}); if (knode) { val = knode.css('font-size'); } return lc(val); } if (key === 'forecolor') { knode = self.commonnode({'*' : '.color'}); if (knode) { val = knode.css('color'); } val = _tohex(val); if (val === '') { val = 'default'; } return lc(val); } if (key === 'hilitecolor') { knode = self.commonnode({'*' : '.background-color'}); if (knode) { val = knode.css('background-color'); } val = _tohex(val); if (val === '') { val = 'default'; } return lc(val); } return val; }, toggle : function(wrapper, map) { var self = this; if (self.commonnode(map)) { self.remove(map); } else { self.wrap(wrapper); } return self.select(); }, bold : function() { return this.toggle('', { span : '.font-weight=bold', strong : '*', b : '*' }); }, italic : function() { return this.toggle('', { span : '.font-style=italic', em : '*', i : '*' }); }, underline : function() { return this.toggle('', { span : '.text-decoration=underline', u : '*' }); }, strikethrough : function() { return this.toggle('', { span : '.text-decoration=line-through', s : '*' }); }, forecolor : function(val) { return this.toggle('', { span : '.color=' + val, font : 'color' }); }, hilitecolor : function(val) { return this.toggle('', { span : '.background-color=' + val }); }, fontsize : function(val) { return this.toggle('', { span : '.font-size=' + val, font : 'size' }); }, fontname : function(val) { return this.fontfamily(val); }, fontfamily : function(val) { return this.toggle('', { span : '.font-family=' + val, font : 'face' }); }, removeformat : function() { var map = { '*' : '.font-weight,.font-style,.text-decoration,.color,.background-color,.font-size,.font-family,.text-indent' }, tags = _style_tag_map; _each(tags, function(key, val) { map[key] = '*'; }); this.remove(map); return this.select(); }, inserthtml : function(val, quickmode) { var self = this, range = self.range; if (val === '') { return self; } function pastehtml(range, val) { val = '' + val; var rng = range.get(); if (rng.item) { rng.item(0).outerhtml = val; } else { rng.pastehtml(val); } var temp = range.doc.getelementbyid('__kindeditor_temp_tag__'); temp.parentnode.removechild(temp); var newrange = _torange(rng); range.setend(newrange.endcontainer, newrange.endoffset); range.collapse(false); self.select(false); } function inserthtml(range, val) { var doc = range.doc, frag = doc.createdocumentfragment(); k('@' + val, doc).each(function() { frag.appendchild(this); }); range.deletecontents(); range.insertnode(frag); range.collapse(false); self.select(false); } if (_ie && quickmode) { try { pastehtml(range, val); } catch(e) { inserthtml(range, val); } return self; } inserthtml(range, val); return self; }, hr : function() { return this.inserthtml('
'); }, print : function() { this.win.print(); return this; }, insertimage : function(url, title, width, height, border, align) { title = _undef(title, ''); border = _undef(border, 0); var html = ''; return self.inserthtml(html); } if (range.iscontrol()) { var node = k(range.startcontainer.childnodes[range.startoffset]); html += '>'; node.after(k(html, doc)); node.next().append(node); range.selectnode(node[0]); return self.select(); } _nativecommand(doc, 'createlink', '__kindeditor_temp_url__'); k('a[href="__kindeditor_temp_url__"]', doc).each(function() { k(this).attr('href', url).attr('data-ke-src', url); if (type) { k(this).attr('target', type); } else { k(this).removeattr('target'); } }); return self; }, unlink : function() { var self = this, doc = self.doc, range = self.range; self.select(); if (range.collapsed) { var a = self.commonnode({ a : '*' }); if (a) { range.selectnode(a.get()); self.select(); } _nativecommand(doc, 'unlink', null); if (_webkit && k(range.startcontainer).name === 'img') { var parent = k(range.startcontainer).parent(); if (parent.name === 'a') { parent.remove(true); } } } else { _nativecommand(doc, 'unlink', null); } return self; } }); _each(('formatblock,selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' + 'insertunorderedlist,indent,outdent,subscript,superscript').split(','), function(i, name) { kcmd.prototype[name] = function(val) { var self = this; self.select(); _nativecommand(self.doc, name, val); if (!_ie || _inarray(name, 'formatblock,selectall,insertorderedlist,insertunorderedlist'.split(',')) >= 0) { self.selection(); } return self; }; }); _each('cut,copy,paste'.split(','), function(i, name) { kcmd.prototype[name] = function() { var self = this; if (!self.doc.querycommandsupported(name)) { throw 'not supported'; } self.select(); _nativecommand(self.doc, name, null); return self; }; }); function _cmd(mixed) { if (mixed.nodename) { var doc = _getdoc(mixed); mixed = _range(doc).selectnodecontents(doc.body).collapse(false); } return new kcmd(mixed); } k.cmdclass = kcmd; k.cmd = _cmd; function _drag(options) { var moveel = options.moveel, movefn = options.movefn, clickel = options.clickel || moveel, beforedrag = options.beforedrag, iframefix = options.iframefix === undefined ? true : options.iframefix; var docs = [document]; if (iframefix) { k('iframe').each(function() { var src = _formaturl(this.src || '', 'absolute'); if (/^https?:\/\//.test(src)) { return; } var doc; try { doc = _iframedoc(this); } catch(e) {} if (doc) { var pos = k(this).pos(); k(doc).data('pos-x', pos.x); k(doc).data('pos-y', pos.y); docs.push(doc); } }); } clickel.mousedown(function(e) { e.stoppropagation(); var self = clickel.get(), x = _removeunit(moveel.css('left')), y = _removeunit(moveel.css('top')), width = moveel.width(), height = moveel.height(), pagex = e.pagex, pagey = e.pagey; if (beforedrag) { beforedrag(); } function movelistener(e) { e.preventdefault(); var kdoc = k(_getdoc(e.target)); var diffx = _round((kdoc.data('pos-x') || 0) + e.pagex - pagex); var diffy = _round((kdoc.data('pos-y') || 0) + e.pagey - pagey); movefn.call(clickel, x, y, width, height, diffx, diffy); } function selectlistener(e) { e.preventdefault(); } function uplistener(e) { e.preventdefault(); k(docs).unbind('mousemove', movelistener) .unbind('mouseup', uplistener) .unbind('selectstart', selectlistener); if (self.releasecapture) { self.releasecapture(); } } k(docs).mousemove(movelistener) .mouseup(uplistener) .bind('selectstart', selectlistener); if (self.setcapture) { self.setcapture(); } }); } function kwidget(options) { this.init(options); } _extend(kwidget, { init : function(options) { var self = this; self.name = options.name || ''; self.doc = options.doc || document; self.win = _getwin(self.doc); self.x = _addunit(options.x); self.y = _addunit(options.y); self.z = options.z; self.width = _addunit(options.width); self.height = _addunit(options.height); self.div = k('
'); self.options = options; self._alignel = options.alignel; if (self.width) { self.div.css('width', self.width); } if (self.height) { self.div.css('height', self.height); } if (self.z) { self.div.css({ position : 'absolute', left : self.x, top : self.y, 'z-index' : self.z }); } if (self.z && (self.x === undefined || self.y === undefined)) { self.autopos(self.width, self.height); } if (options.cls) { self.div.addclass(options.cls); } if (options.shadowmode) { self.div.addclass('ke-shadow'); } if (options.css) { self.div.css(options.css); } if (options.src) { k(options.src).replacewith(self.div); } else { k(self.doc.body).append(self.div); } if (options.html) { self.div.html(options.html); } if (options.autoscroll) { if (_ie && _v < 7 || _quirks) { var scrollpos = _getscrollpos(); k(self.win).bind('scroll', function(e) { var pos = _getscrollpos(), diffx = pos.x - scrollpos.x, diffy = pos.y - scrollpos.y; self.pos(_removeunit(self.x) + diffx, _removeunit(self.y) + diffy, false); }); } else { self.div.css('position', 'fixed'); } } }, pos : function(x, y, updateprop) { var self = this; updateprop = _undef(updateprop, true); if (x !== null) { x = x < 0 ? 0 : _addunit(x); self.div.css('left', x); if (updateprop) { self.x = x; } } if (y !== null) { y = y < 0 ? 0 : _addunit(y); self.div.css('top', y); if (updateprop) { self.y = y; } } return self; }, autopos : function(width, height) { var self = this, w = _removeunit(width) || 0, h = _removeunit(height) || 0, scrollpos = _getscrollpos(); if (self._alignel) { var knode = k(self._alignel), pos = knode.pos(), diffx = _round(knode[0].clientwidth / 2 - w / 2), diffy = _round(knode[0].clientheight / 2 - h / 2); x = diffx < 0 ? pos.x : pos.x + diffx; y = diffy < 0 ? pos.y : pos.y + diffy; } else { var docel = _docelement(self.doc); x = _round(scrollpos.x + (docel.clientwidth - w) / 2); y = _round(scrollpos.y + (docel.clientheight - h) / 2); } if (!(_ie && _v < 7 || _quirks)) { x -= scrollpos.x; y -= scrollpos.y; } return self.pos(x, y); }, remove : function() { var self = this; if (_ie && _v < 7 || _quirks) { k(self.win).unbind('scroll'); } self.div.remove(); _each(self, function(i) { self[i] = null; }); return this; }, show : function() { this.div.show(); return this; }, hide : function() { this.div.hide(); return this; }, draggable : function(options) { var self = this; options = options || {}; options.moveel = self.div; options.movefn = function(x, y, width, height, diffx, diffy) { if ((x = x + diffx) < 0) { x = 0; } if ((y = y + diffy) < 0) { y = 0; } self.pos(x, y); }; _drag(options); return self; } }); function _widget(options) { return new kwidget(options); } k.widgetclass = kwidget; k.widget = _widget; function _iframedoc(iframe) { iframe = _get(iframe); return iframe.contentdocument || iframe.contentwindow.document; } var html, _direction = ''; if ((html = document.getelementsbytagname('html'))) { _direction = html[0].dir; } function _getinithtml(themespath, bodyclass, csspath, cssdata) { var arr = [ (_direction === '' ? '' : ''), '', '' ]; if (!_isarray(csspath)) { csspath = [csspath]; } _each(csspath, function(i, path) { if (path) { arr.push(''); } }); if (cssdata) { arr.push(''); } arr.push(''); return arr.join('\n'); } function _elementval(knode, val) { if (knode.hasval()) { if (val === undefined) { var html = knode.val(); html = html.replace(/(<(?:p|p\s[^>]*)>) *(<\/p>)/ig, ''); return html; } return knode.val(val); } return knode.html(val); } function kedit(options) { this.init(options); } _extend(kedit, kwidget, { init : function(options) { var self = this; kedit.parent.init.call(self, options); self.srcelement = k(options.srcelement); self.div.addclass('ke-edit'); self.designmode = _undef(options.designmode, true); self.beforegethtml = options.beforegethtml; self.beforesethtml = options.beforesethtml; self.aftersethtml = options.aftersethtml; var themespath = _undef(options.themespath, ''), bodyclass = options.bodyclass, csspath = options.csspath, cssdata = options.cssdata, isdocumentdomain = location.host.replace(/:\d+/, '') !== document.domain, srcscript = ('document.open();' + (isdocumentdomain ? 'document.domain="' + document.domain + '";' : '') + 'document.close();'), iframesrc = _ie ? ' src="javascript:void(function(){' + encodeuricomponent(srcscript) + '}())"' : ''; self.iframe = k('').css('width', '100%'); self.textarea = k('').css('width', '100%'); if (self.width) { self.setwidth(self.width); } if (self.height) { self.setheight(self.height); } if (self.designmode) { self.textarea.hide(); } else { self.iframe.hide(); } function ready() { var doc = _iframedoc(self.iframe); doc.open(); if (isdocumentdomain) { doc.domain = document.domain; } doc.write(_getinithtml(themespath, bodyclass, csspath, cssdata)); doc.close(); self.win = self.iframe[0].contentwindow; self.doc = doc; var cmd = _cmd(doc); self.afterchange(function(e) { cmd.selection(); }); if (_webkit) { k(doc).click(function(e) { if (k(e.target).name === 'img') { cmd.selection(true); cmd.range.selectnode(e.target); cmd.select(); } }); } if (_ie) { k(doc).keydown(function(e) { if (e.which == 8) { cmd.selection(); var rng = cmd.range; if (rng.iscontrol()) { rng.collapse(true); k(rng.startcontainer.childnodes[rng.startoffset]).remove(); e.preventdefault(); } } }); } self.cmd = cmd; self.html(_elementval(self.srcelement)); if (_ie) { doc.body.disabled = true; doc.body.contenteditable = true; doc.body.removeattribute('disabled'); } else { doc.designmode = 'on'; } if (options.aftercreate) { options.aftercreate.call(self); } } if (isdocumentdomain) { self.iframe.bind('load', function(e) { self.iframe.unbind('load'); if (_ie) { ready(); } else { settimeout(ready, 0); } }); } self.div.append(self.iframe); self.div.append(self.textarea); self.srcelement.hide(); !isdocumentdomain && ready(); }, setwidth : function(val) { this.div.css('width', _addunit(val)); return this; }, setheight : function(val) { var self = this; val = _addunit(val); self.div.css('height', val); self.iframe.css('height', val); if ((_ie && _v < 8) || _quirks) { val = _addunit(_removeunit(val) - 2); } self.textarea.css('height', val); return self; }, remove : function() { var self = this, doc = self.doc; k(doc.body).unbind(); k(doc).unbind(); k(self.win).unbind(); _elementval(self.srcelement, self.html()); self.srcelement.show(); doc.write(''); self.iframe.unbind(); self.textarea.unbind(); kedit.parent.remove.call(self); }, html : function(val, isfull) { var self = this, doc = self.doc; if (self.designmode) { var body = doc.body; if (val === undefined) { if (isfull) { val = '' + body.parentnode.innerhtml + ''; } else { val = body.innerhtml; } if (self.beforegethtml) { val = self.beforegethtml(val); } if (_gecko && val == '
') { val = ''; } return val; } if (self.beforesethtml) { val = self.beforesethtml(val); } k(body).html(val); if (self.aftersethtml) { self.aftersethtml(); } return self; } if (val === undefined) { return self.textarea.val(); } self.textarea.val(val); return self; }, design : function(bool) { var self = this, val; if (bool === undefined ? !self.designmode : bool) { if (!self.designmode) { val = self.html(); self.designmode = true; self.html(val); self.textarea.hide(); self.iframe.show(); } } else { if (self.designmode) { val = self.html(); self.designmode = false; self.html(val); self.iframe.hide(); self.textarea.show(); } } return self.focus(); }, focus : function() { var self = this; self.designmode ? self.win.focus() : self.textarea[0].focus(); return self; }, blur : function() { var self = this; if (_ie) { var input = k('', self.div); self.div.append(input); input[0].focus(); input.remove(); } else { self.designmode ? self.win.blur() : self.textarea[0].blur(); } return self; }, afterchange : function(fn) { var self = this, doc = self.doc, body = doc.body; k(doc).keyup(function(e) { if (!e.ctrlkey && !e.altkey && _change_key_map[e.which]) { fn(e); } }); k(doc).mouseup(fn).contextmenu(fn); k(self.win).blur(fn); function timeouthandler(e) { settimeout(function() { fn(e); }, 1); } k(body).bind('paste', timeouthandler); k(body).bind('cut', timeouthandler); return self; } }); function _edit(options) { return new kedit(options); } k.editclass = kedit; k.edit = _edit; k.iframedoc = _iframedoc; function _selecttoolbar(name, fn) { var self = this, knode = self.get(name); if (knode) { if (knode.hasclass('ke-disabled')) { return; } fn(knode); } } function ktoolbar(options) { this.init(options); } _extend(ktoolbar, kwidget, { init : function(options) { var self = this; ktoolbar.parent.init.call(self, options); self.disablemode = _undef(options.disablemode, false); self.nodisableitemmap = _tomap(_undef(options.nodisableitems, [])); self._itemmap = {}; self.div.addclass('ke-toolbar').bind('contextmenu,mousedown,mousemove', function(e) { e.preventdefault(); }).attr('unselectable', 'on'); function find(target) { var knode = k(target); if (knode.hasclass('ke-outline')) { return knode; } if (knode.hasclass('ke-toolbar-icon')) { return knode.parent(); } } function hover(e, method) { var knode = find(e.target); if (knode) { if (knode.hasclass('ke-disabled')) { return; } if (knode.hasclass('ke-selected')) { return; } knode[method]('ke-on'); } } self.div.mouseover(function(e) { hover(e, 'addclass'); }) .mouseout(function(e) { hover(e, 'removeclass'); }) .click(function(e) { var knode = find(e.target); if (knode) { if (knode.hasclass('ke-disabled')) { return; } self.options.click.call(this, e, knode.attr('data-name')); } }); }, get : function(name) { if (this._itemmap[name]) { return this._itemmap[name]; } return (this._itemmap[name] = k('span.ke-icon-' + name, this.div).parent()); }, select : function(name) { _selecttoolbar.call(this, name, function(knode) { knode.addclass('ke-selected'); }); return self; }, unselect : function(name) { _selecttoolbar.call(this, name, function(knode) { knode.removeclass('ke-selected').removeclass('ke-on'); }); return self; }, enable : function(name) { var self = this, knode = name.get ? name : self.get(name); if (knode) { knode.removeclass('ke-disabled'); knode.opacity(1); } return self; }, disable : function(name) { var self = this, knode = name.get ? name : self.get(name); if (knode) { knode.removeclass('ke-selected').addclass('ke-disabled'); knode.opacity(0.5); } return self; }, disableall : function(bool, nodisableitems) { var self = this, map = self.nodisableitemmap, item; if (nodisableitems) { map = _tomap(nodisableitems); } if (bool === undefined ? !self.disablemode : bool) { k('span.ke-outline', self.div).each(function() { var knode = k(this), name = knode[0].getattribute('data-name', 2); if (!map[name]) { self.disable(knode); } }); self.disablemode = true; } else { k('span.ke-outline', self.div).each(function() { var knode = k(this), name = knode[0].getattribute('data-name', 2); if (!map[name]) { self.enable(knode); } }); self.disablemode = false; } return self; } }); function _toolbar(options) { return new ktoolbar(options); } k.toolbarclass = ktoolbar; k.toolbar = _toolbar; function kmenu(options) { this.init(options); } _extend(kmenu, kwidget, { init : function(options) { var self = this; options.z = options.z || 811213; kmenu.parent.init.call(self, options); self.centerlinemode = _undef(options.centerlinemode, true); self.div.addclass('ke-menu').bind('click,mousedown', function(e){ e.stoppropagation(); }).attr('unselectable', 'on'); }, additem : function(item) { var self = this; if (item.title === '-') { self.div.append(k('
')); return; } var itemdiv = k('
'), leftdiv = k('
'), rightdiv = k('
'), height = _addunit(item.height), iconclass = _undef(item.iconclass, ''); self.div.append(itemdiv); if (height) { itemdiv.css('height', height); rightdiv.css('line-height', height); } var centerdiv; if (self.centerlinemode) { centerdiv = k('
'); if (height) { centerdiv.css('height', height); } } itemdiv.mouseover(function(e) { k(this).addclass('ke-menu-item-on'); if (centerdiv) { centerdiv.addclass('ke-menu-item-center-on'); } }) .mouseout(function(e) { k(this).removeclass('ke-menu-item-on'); if (centerdiv) { centerdiv.removeclass('ke-menu-item-center-on'); } }) .click(function(e) { item.click.call(k(this)); e.stoppropagation(); }) .append(leftdiv); if (centerdiv) { itemdiv.append(centerdiv); } itemdiv.append(rightdiv); if (item.checked) { iconclass = 'ke-icon-checked'; } if (iconclass !== '') { leftdiv.html(''); } rightdiv.html(item.title); return self; }, remove : function() { var self = this; if (self.options.beforeremove) { self.options.beforeremove.call(self); } k('.ke-menu-item', self.div[0]).unbind(); kmenu.parent.remove.call(self); return self; } }); function _menu(options) { return new kmenu(options); } k.menuclass = kmenu; k.menu = _menu; function kcolorpicker(options) { this.init(options); } _extend(kcolorpicker, kwidget, { init : function(options) { var self = this; options.z = options.z || 811213; kcolorpicker.parent.init.call(self, options); var colors = options.colors || [ ['#e53333', '#e56600', '#ff9900', '#64451d', '#dfc5a4', '#ffe500'], ['#009900', '#006600', '#99bb00', '#b8d100', '#60d978', '#00d5ff'], ['#337fe5', '#003399', '#4c33e5', '#9933e5', '#cc33e5', '#ee33ee'], ['#ffffff', '#cccccc', '#999999', '#666666', '#333333', '#000000'] ]; self.selectedcolor = (options.selectedcolor || '').tolowercase(); self._cells = []; self.div.addclass('ke-colorpicker').bind('click,mousedown', function(e){ e.stoppropagation(); }).attr('unselectable', 'on'); var table = self.doc.createelement('table'); self.div.append(table); table.classname = 'ke-colorpicker-table'; table.cellpadding = 0; table.cellspacing = 0; table.border = 0; var row = table.insertrow(0), cell = row.insertcell(0); cell.colspan = colors[0].length; self._addattr(cell, '', 'ke-colorpicker-cell-top'); for (var i = 0; i < colors.length; i++) { row = table.insertrow(i + 1); for (var j = 0; j < colors[i].length; j++) { cell = row.insertcell(j); self._addattr(cell, colors[i][j], 'ke-colorpicker-cell'); } } }, _addattr : function(cell, color, cls) { var self = this; cell = k(cell).addclass(cls); if (self.selectedcolor === color.tolowercase()) { cell.addclass('ke-colorpicker-cell-selected'); } cell.attr('title', color || self.options.nocolor); cell.mouseover(function(e) { k(this).addclass('ke-colorpicker-cell-on'); }); cell.mouseout(function(e) { k(this).removeclass('ke-colorpicker-cell-on'); }); cell.click(function(e) { e.stop(); self.options.click.call(k(this), color); }); if (color) { cell.append(k('
').css('background-color', color)); } else { cell.html(self.options.nocolor); } k(cell).attr('unselectable', 'on'); self._cells.push(cell); }, remove : function() { var self = this; _each(self._cells, function() { this.unbind(); }); kcolorpicker.parent.remove.call(self); return self; } }); function _colorpicker(options) { return new kcolorpicker(options); } k.colorpickerclass = kcolorpicker; k.colorpicker = _colorpicker; function kuploadbutton(options) { this.init(options); } _extend(kuploadbutton, { init : function(options) { var self = this, button = k(options.button), fieldname = options.fieldname || 'file', url = options.url || '', title = button.val(), extraparams = options.extraparams || {}, cls = button[0].classname || '', target = options.target || 'kindeditor_upload_iframe_' + new date().gettime(); options.aftererror = options.aftererror || function(str) { alert(str); }; var hiddenelements = []; for(var k in extraparams){ hiddenelements.push(''); } var html = [ '
', (options.target ? '' : ''), (options.form ? '
' : '
'), '', hiddenelements.join(''), '', '', '', (options.form ? '
' : ''), '
'].join(''); var div = k(html, button.doc); button.hide(); button.before(div); self.div = div; self.button = button; self.iframe = options.target ? k('iframe[name="' + target + '"]') : k('iframe', div); self.form = options.form ? k(options.form) : k('form', div); var width = options.width || k('.ke-button-common', div).width(); self.filebox = k('.ke-upload-file', div).width(width); self.options = options; }, submit : function() { var self = this, iframe = self.iframe; iframe.bind('load', function() { iframe.unbind(); var tempform = document.createelement('form'); self.filebox.before(tempform); k(tempform).append(self.filebox); tempform.reset(); k(tempform).remove(true); var doc = k.iframedoc(iframe), pre = doc.getelementsbytagname('pre')[0], str = '', data; if (pre) { str = pre.innerhtml; } else { str = doc.body.innerhtml; } iframe[0].src = 'javascript:false'; try { data = k.json(str); } catch (e) { self.options.aftererror.call(self, '' + doc.body.parentnode.innerhtml + ''); } if (data) { self.options.afterupload.call(self, data); } }); self.form[0].submit(); return self; }, remove : function() { var self = this; if (self.filebox) { self.filebox.unbind(); } self.iframe.remove(); self.div.remove(); self.button.show(); return self; } }); function _uploadbutton(options) { return new kuploadbutton(options); } k.uploadbuttonclass = kuploadbutton; k.uploadbutton = _uploadbutton; function _createbutton(arg) { arg = arg || {}; var name = arg.name || '', span = k(''), btn = k(''); if (arg.click) { btn.click(arg.click); } span.append(btn); return span; } function kdialog(options) { this.init(options); } _extend(kdialog, kwidget, { init : function(options) { var self = this; var shadowmode = _undef(options.shadowmode, true); options.z = options.z || 811213; options.shadowmode = false; options.autoscroll = _undef(options.autoscroll, true); kdialog.parent.init.call(self, options); var title = options.title, body = k(options.body, self.doc), previewbtn = options.previewbtn, yesbtn = options.yesbtn, nobtn = options.nobtn, closebtn = options.closebtn, showmask = _undef(options.showmask, true); self.div.addclass('ke-dialog').bind('click,mousedown', function(e){ e.stoppropagation(); }); var contentdiv = k('
').appendto(self.div); if (_ie && _v < 7) { self.iframemask = k('').appendto(self.div); } else if (shadowmode) { k('
').appendto(self.div); } var headerdiv = k('
'); contentdiv.append(headerdiv); headerdiv.html(title); self.closeicon = k('').click(closebtn.click); headerdiv.append(self.closeicon); self.draggable({ clickel : headerdiv, beforedrag : options.beforedrag }); var bodydiv = k('
'); contentdiv.append(bodydiv); bodydiv.append(body); var footerdiv = k(''); if (previewbtn || yesbtn || nobtn) { contentdiv.append(footerdiv); } _each([ { btn : previewbtn, name : 'preview' }, { btn : yesbtn, name : 'yes' }, { btn : nobtn, name : 'no' } ], function() { if (this.btn) { var button = _createbutton(this.btn); button.addclass('ke-dialog-' + this.name); footerdiv.append(button); } }); if (self.height) { bodydiv.height(_removeunit(self.height) - headerdiv.height() - footerdiv.height()); } self.div.width(self.div.width()); self.div.height(self.div.height()); self.mask = null; if (showmask) { var docel = _docelement(self.doc), docwidth = math.max(docel.scrollwidth, docel.clientwidth), docheight = math.max(docel.scrollheight, docel.clientheight); self.mask = _widget({ x : 0, y : 0, z : self.z - 1, cls : 'ke-dialog-mask', width : docwidth, height : docheight }); } self.autopos(self.div.width(), self.div.height()); self.footerdiv = footerdiv; self.bodydiv = bodydiv; self.headerdiv = headerdiv; self.isloading = false; }, setmaskindex : function(z) { var self = this; self.mask.div.css('z-index', z); }, showloading : function(msg) { msg = _undef(msg, ''); var self = this, body = self.bodydiv; self.loading = k('
' + msg + '
') .width(body.width()).height(body.height()) .css('top', self.headerdiv.height() + 'px'); body.css('visibility', 'hidden').after(self.loading); self.isloading = true; return self; }, hideloading : function() { this.loading && this.loading.remove(); this.bodydiv.css('visibility', 'visible'); this.isloading = false; return this; }, remove : function() { var self = this; if (self.options.beforeremove) { self.options.beforeremove.call(self); } self.mask && self.mask.remove(); self.iframemask && self.iframemask.remove(); self.closeicon.unbind(); k('input', self.div).unbind(); k('button', self.div).unbind(); self.footerdiv.unbind(); self.bodydiv.unbind(); self.headerdiv.unbind(); k('iframe', self.div).each(function() { k(this).remove(); }); kdialog.parent.remove.call(self); return self; } }); function _dialog(options) { return new kdialog(options); } k.dialogclass = kdialog; k.dialog = _dialog; function _tabs(options) { var self = _widget(options), remove = self.remove, afterselect = options.afterselect, div = self.div, lilist = []; div.addclass('ke-tabs') .bind('contextmenu,mousedown,mousemove', function(e) { e.preventdefault(); }); var ul = k('
    '); div.append(ul); self.add = function(tab) { var li = k('
  • ' + tab.title + '
  • '); li.data('tab', tab); lilist.push(li); ul.append(li); }; self.selectedindex = 0; self.select = function(index) { self.selectedindex = index; _each(lilist, function(i, li) { li.unbind(); if (i === index) { li.addclass('ke-tabs-li-selected'); k(li.data('tab').panel).show(''); } else { li.removeclass('ke-tabs-li-selected').removeclass('ke-tabs-li-on') .mouseover(function() { k(this).addclass('ke-tabs-li-on'); }) .mouseout(function() { k(this).removeclass('ke-tabs-li-on'); }) .click(function() { self.select(i); }); k(li.data('tab').panel).hide(); } }); if (afterselect) { afterselect.call(self, index); } }; self.remove = function() { _each(lilist, function() { this.remove(); }); ul.remove(); remove.call(self); }; return self; } k.tabs = _tabs; function _loadscript(url, fn) { var head = document.getelementsbytagname('head')[0] || (_quirks ? document.body : document.documentelement), script = document.createelement('script'); head.appendchild(script); script.src = url; script.charset = 'utf-8'; script.onload = script.onreadystatechange = function() { if (!this.readystate || this.readystate === 'loaded') { if (fn) { fn(); } script.onload = script.onreadystatechange = null; head.removechild(script); } }; } function _chopquery(url) { var index = url.indexof('?'); return index > 0 ? url.substr(0, index) : url; } function _loadstyle(url) { var head = document.getelementsbytagname('head')[0] || (_quirks ? document.body : document.documentelement), link = document.createelement('link'), absoluteurl = _chopquery(_formaturl(url, 'absolute')); var links = k('link[rel="stylesheet"]', head); for (var i = 0, len = links.length; i < len; i++) { if (_chopquery(_formaturl(links[i].href, 'absolute')) === absoluteurl) { return; } } head.appendchild(link); link.href = url; link.rel = 'stylesheet'; } function _ajax(url, fn, method, param, datatype) { method = method || 'get'; datatype = datatype || 'json'; var xhr = window.xmlhttprequest ? new window.xmlhttprequest() : new activexobject('microsoft.xmlhttp'); xhr.open(method, url, true); xhr.onreadystatechange = function () { if (xhr.readystate == 4 && xhr.status == 200) { if (fn) { var data = _trim(xhr.responsetext); if (datatype == 'json') { data = _json(data); } fn(data); } } }; if (method == 'post') { var params = []; _each(param, function(key, val) { params.push(encodeuricomponent(key) + '=' + encodeuricomponent(val)); }); try { xhr.setrequestheader('content-type', 'application/x-www-form-urlencoded'); } catch (e) {} xhr.send(params.join('&')); } else { xhr.send(null); } } k.loadscript = _loadscript; k.loadstyle = _loadstyle; k.ajax = _ajax; var _plugins = {}; function _plugin(name, fn) { if (name === undefined) { return _plugins; } if (!fn) { return _plugins[name]; } _plugins[name] = fn; } var _language = {}; function _parselangkey(key) { var match, ns = 'core'; if ((match = /^(\w+)\.(\w+)$/.exec(key))) { ns = match[1]; key = match[2]; } return { ns : ns, key : key }; } function _lang(mixed, langtype) { langtype = langtype === undefined ? k.options.langtype : langtype; if (typeof mixed === 'string') { if (!_language[langtype]) { return 'no language'; } var pos = mixed.length - 1; if (mixed.substr(pos) === '.') { return _language[langtype][mixed.substr(0, pos)]; } var obj = _parselangkey(mixed); return _language[langtype][obj.ns][obj.key]; } _each(mixed, function(key, val) { var obj = _parselangkey(key); if (!_language[langtype]) { _language[langtype] = {}; } if (!_language[langtype][obj.ns]) { _language[langtype][obj.ns] = {}; } _language[langtype][obj.ns][obj.key] = val; }); } function _getimagefromrange(range, fn) { if (range.collapsed) { return; } range = range.clonerange().up(); var sc = range.startcontainer, so = range.startoffset; if (!_webkit && !range.iscontrol()) { return; } var img = k(sc.childnodes[so]); if (!img || img.name != 'img') { return; } if (fn(img)) { return img; } } function _bindcontextmenuevent() { var self = this, doc = self.edit.doc; k(doc).contextmenu(function(e) { if (self.menu) { self.hidemenu(); } if (!self.usecontextmenu) { e.preventdefault(); return; } if (self._contextmenus.length === 0) { return; } var maxwidth = 0, items = []; _each(self._contextmenus, function() { if (this.title == '-') { items.push(this); return; } if (this.cond && this.cond()) { items.push(this); if (this.width && this.width > maxwidth) { maxwidth = this.width; } } }); while (items.length > 0 && items[0].title == '-') { items.shift(); } while (items.length > 0 && items[items.length - 1].title == '-') { items.pop(); } var previtem = null; _each(items, function(i) { if (this.title == '-' && previtem.title == '-') { delete items[i]; } previtem = this; }); if (items.length > 0) { e.preventdefault(); var pos = k(self.edit.iframe).pos(), menu = _menu({ x : pos.x + e.clientx, y : pos.y + e.clienty, width : maxwidth, css : { visibility: 'hidden' }, shadowmode : self.shadowmode }); _each(items, function() { if (this.title) { menu.additem(this); } }); var docel = _docelement(menu.doc), menuheight = menu.div.height(); if (e.clienty + menuheight >= docel.clientheight - 100) { menu.pos(menu.x, _removeunit(menu.y) - menuheight); } menu.div.css('visibility', 'visible'); self.menu = menu; } }); } function _bindnewlineevent() { var self = this, doc = self.edit.doc, newlinetag = self.newlinetag; if (_ie && newlinetag !== 'br') { return; } if (_gecko && _v < 3 && newlinetag !== 'p') { return; } if (_opera && _v < 9) { return; } var brskiptagmap = _tomap('h1,h2,h3,h4,h5,h6,pre,li'), pskiptagmap = _tomap('p,h1,h2,h3,h4,h5,h6,pre,li,blockquote'); function getancestortagname(range) { var ancestor = k(range.commonancestor()); while (ancestor) { if (ancestor.type == 1 && !ancestor.isstyle()) { break; } ancestor = ancestor.parent(); } return ancestor.name; } k(doc).keydown(function(e) { if (e.which != 13 || e.shiftkey || e.ctrlkey || e.altkey) { return; } self.cmd.selection(); var tagname = getancestortagname(self.cmd.range); if (tagname == 'marquee' || tagname == 'select') { return; } if (newlinetag === 'br' && !brskiptagmap[tagname]) { e.preventdefault(); self.inserthtml('
    ' + (_ie && _v < 9 ? '' : '\u200b')); return; } if (!pskiptagmap[tagname]) { _nativecommand(doc, 'formatblock', '

    '); } }); k(doc).keyup(function(e) { if (e.which != 13 || e.shiftkey || e.ctrlkey || e.altkey) { return; } if (newlinetag == 'br') { return; } if (_gecko) { var root = self.cmd.commonancestor('p'); var a = self.cmd.commonancestor('a'); if (a.text() == '') { a.remove(true); self.cmd.range.selectnodecontents(root[0]).collapse(true); self.cmd.select(); } return; } self.cmd.selection(); var tagname = getancestortagname(self.cmd.range); if (tagname == 'marquee' || tagname == 'select') { return; } if (!pskiptagmap[tagname]) { _nativecommand(doc, 'formatblock', '

    '); } var div = self.cmd.commonancestor('div'); if (div) { var p = k('

    '), child = div[0].firstchild; while (child) { var next = child.nextsibling; p.append(child); child = next; } div.before(p); div.remove(); self.cmd.range.selectnodecontents(p[0]); self.cmd.select(); } }); } function _bindtabevent() { var self = this, doc = self.edit.doc; k(doc).keydown(function(e) { if (e.which == 9) { e.preventdefault(); if (self.aftertab) { self.aftertab.call(self, e); return; } var cmd = self.cmd, range = cmd.range; range.shrink(); if (range.collapsed && range.startcontainer.nodetype == 1) { range.insertnode(k('@ ', doc)[0]); cmd.select(); } self.inserthtml('    '); } }); } function _bindfocusevent() { var self = this; k(self.edit.textarea[0], self.edit.win).focus(function(e) { if (self.afterfocus) { self.afterfocus.call(self, e); } }).blur(function(e) { if (self.afterblur) { self.afterblur.call(self, e); } }); } function _removebookmarktag(html) { return _trim(html.replace(/]*id="?__kindeditor_bookmark_\w+_\d+__"?[^>]*><\/span>/ig, '')); } function _removetemptag(html) { return html.replace(/]+class="?__kindeditor_paste__"?[^>]*>[\s\s]*?<\/div>/ig, ''); } function _addbookmarktostack(stack, bookmark) { if (stack.length === 0) { stack.push(bookmark); return; } var prev = stack[stack.length - 1]; if (_removebookmarktag(bookmark.html) !== _removebookmarktag(prev.html)) { stack.push(bookmark); } } function _undotoredo(fromstack, tostack) { var self = this, edit = self.edit, body = edit.doc.body, range, bookmark; if (fromstack.length === 0) { return self; } if (edit.designmode) { range = self.cmd.range; bookmark = range.createbookmark(true); bookmark.html = body.innerhtml; } else { bookmark = { html : body.innerhtml }; } _addbookmarktostack(tostack, bookmark); var prev = fromstack.pop(); if (_removebookmarktag(bookmark.html) === _removebookmarktag(prev.html) && fromstack.length > 0) { prev = fromstack.pop(); } if (edit.designmode) { edit.html(prev.html); if (prev.start) { range.movetobookmark(prev); self.select(); } } else { k(body).html(_removebookmarktag(prev.html)); } return self; } function keditor(options) { var self = this; self.options = {}; function setoption(key, val) { if (keditor.prototype[key] === undefined) { self[key] = val; } self.options[key] = val; } _each(options, function(key, val) { setoption(key, options[key]); }); _each(k.options, function(key, val) { if (self[key] === undefined) { setoption(key, val); } }); var se = k(self.srcelement || '