-pg电子官方网址入口

/******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2013 kindsoft.net * * @author roddy * @website http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php * @version 4.1.10 (2013-11-23) *******************************************************************************/ (function (window, undefined) { if (window.kindeditor) { return; } if (!window.console) { window.console = {}; } if (!console.log) { console.log = function () {}; } var _version = '4.1.10 (2013-11-23)', _ua = navigator.useragent.tolowercase(), _ie = _ua.indexof('msie') > -1 && _ua.indexof('opera') == -1, _newie = _ua.indexof('msie') == -1 && _ua.indexof('trident') > -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', _ierange = !window.getselection, _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, '&'); } 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 _invalid { 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, zindex : 811213, 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', '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'], 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(); } else { ev.returnvalue = false; } }, stoppropagation : function() { var ev = this.event; if (ev.stoppropagation) { ev.stoppropagation(); } else { 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(); } }); } var _readyfinished = false; function _ready(fn) { if (_readyfinished) { fn(kindeditor); return; } var loaded = false; function readyfunc() { if (!loaded) { loaded = true; fn(kindeditor); _readyfinished = true; } } 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 _format { 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) { if (html == null) { html = ''; } 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, '©'); html = html.replace(/\u00ae/g, '®'); html = html.replace(/<[^>] /g, function($0) { return $0.replace(/\s /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 = /(\s*)<(\/)?([\w\-:] )((?:\s |(?:\s [\w\-:] )|(?:\s [\w\-:] =[^\s"'<>] )|(?:\s [\w\-:"] ="[^"]*")|(?:\s [\w\-:"] ='[^']*'))*)(\/)?>(\s*)/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] = _format; } 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'; } 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'; } return 'ke-media'; } function _mediaattrs(srctag) { return _getattrlist(unescape(srctag)); } function _mediaembed(attrs) { var html = ' 0) { style = 'width:' width 'px;'; } if (/\d/.test(height)) { style = 'height:' height ';'; } else 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.getattribute('name') !== null) { 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 || _newie || _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 (_ierange) { 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 (_ierange) { 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 = _ierange ? 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 (!_ierange) { 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 _ierange ? 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 (_ierange && (!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) { if (knode.type != 1 || knode.issingle()) { return false; } return 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 (_ierange) { 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 (_ierange) { try { rng = range.get(true); rng.select(); } catch(e) {} } else { if (hasu200b) { range.collapse(false); } rng = range.get(true); sel.removeallranges(); sel.addrange(rng); if (doc !== document) { var pos = k(rng.endcontainer).pos(); win.scrollto(pos.x, pos.y); } } 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.wrap('').select(); }, hilitecolor : function(val) { return this.wrap('').select(); }, fontsize : function(val) { return this.wrap('').select(); }, fontname : function(val) { return this.fontfamily(val); }, fontfamily : function(val) { return this.wrap('').select(); }, 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 (_ierange && 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(); } function setattr(node, url, type) { k(node).attr('href', url).attr('data-ke-src', url); if (type) { k(node).attr('target', type); } else { k(node).removeattr('target'); } } var sc = range.startcontainer, so = range.startoffset, ec = range.endcontainer, eo = range.endoffset; if (sc.nodetype == 1 && sc === ec && so 1 === eo) { var child = sc.childnodes[so]; if (child.nodename.tolowercase() == 'a') { setattr(child, url, type); return self; } } _nativecommand(doc, 'createlink', '__kindeditor_temp_url__'); k('a[href="__kindeditor_temp_url__"]', doc).each(function() { setattr(this, url, type); }); 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 (_ierange && _inarray(name, 'justifyleft,justifycenter,justifyright,justifyfull'.split(',')) >= 0) { self.selection(); } if (!_ierange || _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 = _format; 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 === '' ? '' : ''), '-pg电子官方网址入口', '' ]; 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.protocol != 'res:' && 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%'); self.tabindex = isnan(parseint(options.tabindex, 10)) ? self.srcelement.attr('tabindex') : parseint(options.tabindex, 10); self.iframe.attr('tabindex', self.tabindex); self.textarea.attr('tabindex', self.tabindex); 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) { self._mousedownhandler = function() { var newrange = cmd.range.clonerange(); newrange.shrink(); if (newrange.iscontrol()) { self.blur(); } }; k(document).mousedown(self._mousedownhandler); 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) { var self = this; val = _addunit(val); self.width = val; self.div.css('width', val); return self; }, setheight : function(val) { var self = this; val = _addunit(val); self.height = 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(); if (self._mousedownhandler) { k(document).unbind('mousedown', self._mousedownhandler); } _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); } if (_ie && _v >= 9) { val = val.replace(/(<.*?checked=")checked(".*>)/ig, '$1$2'); } 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); self.filebox = k('.ke-upload-file', div); var width = options.width || k('.ke-button-common', div).width(); k('.ke-upload-area', 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; } str = _unescape(str); 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(_format); var links = k('link[rel="stylesheet"]', head); for (var i = 0, len = links.length; i < len; i ) { if (_chopquery(_format) === 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 && 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 || '', ''].join(''), dialog = self.createdialog({ name : name, width : 450, title : self.lang(name), body : html, yesbtn : { name : self.lang('yes'), click : function(e) { var type = k('.ke-code-type', dialog.div).val(), code = textarea.val(), cls = type === '' ? '' : ' lang-' type, html = '
    \n'   k.escape(code)   '
    '; if (k.trim(code) === '') { alert(lang.pleaseinput); textarea[0].focus(); return; } self.inserthtml(html).hidedialog().focus(); } } }), textarea = k('textarea', dialog.div); textarea[0].focus(); }); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('emoticons', function(k) { var self = this, name = 'emoticons', path = (self.emoticonspath || self.pluginspath 'emoticons/images/'), allowpreview = self.allowpreviewemoticons === undefined ? true : self.allowpreviewemoticons, currentpagenum = 1; self.clicktoolbar(name, function() { var rows = 5, cols = 9, total = 135, startnum = 0, cells = rows * cols, pages = math.ceil(total / cells), colshalf = math.floor(cols / 2), wrapperdiv = k('
    '), elements = [], menu = self.createmenu({ name : name, beforeremove : function() { removeevent(); } }); menu.div.append(wrapperdiv); var previewdiv, previewimg; if (allowpreview) { previewdiv = k('
    ').css('right', 0); previewimg = k(''); wrapperdiv.append(previewdiv); previewdiv.append(previewimg); } function bindcellevent(cell, j, num) { if (previewdiv) { cell.mouseover(function() { if (j > colshalf) { previewdiv.css('left', 0); previewdiv.css('right', ''); } else { previewdiv.css('left', ''); previewdiv.css('right', 0); } previewimg.attr('src', path num '.gif'); k(this).addclass('ke-on'); }); } else { cell.mouseover(function() { k(this).addclass('ke-on'); }); } cell.mouseout(function() { k(this).removeclass('ke-on'); }); cell.click(function(e) { self.inserthtml('').hidemenu().focus(); e.stop(); }); } function createemoticonstable(pagenum, parentdiv) { var table = document.createelement('table'); parentdiv.append(table); if (previewdiv) { k(table).mouseover(function() { previewdiv.show('block'); }); k(table).mouseout(function() { previewdiv.hide(); }); elements.push(k(table)); } table.classname = 'ke-table'; table.cellpadding = 0; table.cellspacing = 0; table.border = 0; var num = (pagenum - 1) * cells startnum; for (var i = 0; i < rows; i ) { var row = table.insertrow(i); for (var j = 0; j < cols; j ) { var cell = k(row.insertcell(j)); cell.addclass('ke-cell'); bindcellevent(cell, j, num); var span = k('') .css('background-position', '-' (24 * num) 'px 0px') .css('background-image', ''); cell.append(span); elements.push(cell); num ; } } return table; } var table = createemoticonstable(currentpagenum, wrapperdiv); function removeevent() { k.each(elements, function() { this.unbind(); }); } var pagediv; function bindpageevent(el, pagenum) { el.click(function(e) { removeevent(); table.parentnode.removechild(table); pagediv.remove(); table = createemoticonstable(pagenum, wrapperdiv); createpagetable(pagenum); currentpagenum = pagenum; e.stop(); }); } function createpagetable(currentpagenum) { pagediv = k('
    '); wrapperdiv.append(pagediv); for (var pagenum = 1; pagenum <= pages; pagenum ) { if (currentpagenum !== pagenum) { var a = k(''); bindpageevent(a, pagenum); pagediv.append(a); elements.push(a); } else { pagediv.append(k('@[' pagenum ']')); } pagediv.append(k('@ ')); } } createpagetable(currentpagenum); }); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('filemanager', function(k) { var self = this, name = 'filemanager', filemanagerjson = k.undef(self.filemanagerjson, self.basepath 'php/file_manager_json.php'), imgpath = self.pluginspath name '/images/', lang = self.lang(name '.'); function makefiletitle(filename, filesize, datetime) { return filename ' (' math.ceil(filesize / 1024) 'kb, ' datetime ')'; } function bindtitle(el, data) { if (data.is_dir) { el.attr('title', data.filename); } else { el.attr('title', makefiletitle(data.filename, data.filesize, data.datetime)); } } self.plugin.filemanagerdialog = function(options) { var width = k.undef(options.width, 650), height = k.undef(options.height, 510), dirname = k.undef(options.dirname, ''), viewtype = k.undef(options.viewtype, 'view').touppercase(), // "list" or "view" clickfn = options.clickfn; var html = [ '
    ', // header start '
    ', // left start '
    ', ' ', '', '
    ', // right start '
    ', lang.viewtype ' ', lang.ordertype ' ', '
    ', '
    ', '
    ', // body start '
    ', '
    ' ].join(''); var dialog = self.createdialog({ name : name, width : width, height : height, title : self.lang(name), body : html }), div = dialog.div, bodydiv = k('.ke-plugin-filemanager-body', div), moveupimg = k('[name="moveupimg"]', div), moveuplink = k('[name="moveuplink"]', div), viewserverbtn = k('[name="viewserver"]', div), viewtypebox = k('[name="viewtype"]', div), ordertypebox = k('[name="ordertype"]', div); function reloadpage(path, order, func) { var param = 'path=' path '&order=' order '&dir=' dirname; dialog.showloading(self.lang('ajaxloading')); k.ajax(k.addparam(filemanagerjson, param '&' new date().gettime()), function(data) { dialog.hideloading(); func(data); }); } var ellist = []; function bindevent(el, result, data, createfunc) { var fileurl = k.format, dirpath = encodeuricomponent(result.current_dir_path data.filename '/'); if (data.is_dir) { el.click(function(e) { reloadpage(dirpath, ordertypebox.val(), createfunc); }); } else if (data.is_photo) { el.click(function(e) { clickfn.call(this, fileurl, data.filename); }); } else { el.click(function(e) { clickfn.call(this, fileurl, data.filename); }); } ellist.push(el); } function createcommon(result, createfunc) { // remove events k.each(ellist, function() { this.unbind(); }); moveuplink.unbind(); viewtypebox.unbind(); ordertypebox.unbind(); // add events if (result.current_dir_path) { moveuplink.click(function(e) { reloadpage(result.moveup_dir_path, ordertypebox.val(), createfunc); }); } function changefunc() { if (viewtypebox.val() == 'view') { reloadpage(result.current_dir_path, ordertypebox.val(), createview); } else { reloadpage(result.current_dir_path, ordertypebox.val(), createlist); } } viewtypebox.change(changefunc); ordertypebox.change(changefunc); bodydiv.html(''); } function createlist(result) { createcommon(result, createlist); var table = document.createelement('table'); table.classname = 'ke-table'; table.cellpadding = 0; table.cellspacing = 0; table.border = 0; bodydiv.append(table); var filelist = result.file_list; for (var i = 0, len = filelist.length; i < len; i ) { var data = filelist[i], row = k(table.insertrow(i)); row.mouseover(function(e) { k(this).addclass('ke-on'); }) .mouseout(function(e) { k(this).removeclass('ke-on'); }); var iconurl = imgpath (data.is_dir ? 'folder-16.gif' : 'file-16.gif'), img = k(''), cell0 = k(row[0].insertcell(0)).addclass('ke-cell ke-name').append(img).append(document.createtextnode(' ' data.filename)); if (!data.is_dir || data.has_file) { row.css('cursor', 'pointer'); cell0.attr('title', data.filename); bindevent(cell0, result, data, createlist); } else { cell0.attr('title', lang.emptyfolder); } k(row[0].insertcell(1)).addclass('ke-cell ke-size').html(data.is_dir ? '-' : math.ceil(data.filesize / 1024) 'kb'); k(row[0].insertcell(2)).addclass('ke-cell ke-datetime').html(data.datetime); } } function createview(result) { createcommon(result, createview); var filelist = result.file_list; for (var i = 0, len = filelist.length; i < len; i ) { var data = filelist[i], div = k('
    '); bodydiv.append(div); var photodiv = k('
    ') .mouseover(function(e) { k(this).addclass('ke-on'); }) .mouseout(function(e) { k(this).removeclass('ke-on'); }); div.append(photodiv); var fileurl = result.current_url data.filename, iconurl = data.is_dir ? imgpath 'folder-64.gif' : (data.is_photo ? fileurl : imgpath 'file-64.gif'); var img = k(''); if (!data.is_dir || data.has_file) { photodiv.css('cursor', 'pointer'); bindtitle(photodiv, data); bindevent(photodiv, result, data, createview); } else { photodiv.attr('title', lang.emptyfolder); } photodiv.append(img); div.append('
    ' data.filename '
    '); } } viewtypebox.val(viewtype); reloadpage('', ordertypebox.val(), viewtype == 'view' ? createview : createlist); return dialog; } }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('flash', function(k) { var self = this, name = 'flash', lang = self.lang(name '.'), allowflashupload = k.undef(self.allowflashupload, true), allowfilemanager = k.undef(self.allowfilemanager, false), formatuploadurl = k.undef(self.formatuploadurl, true), extraparams = k.undef(self.extrafileuploadparams, {}), filepostname = k.undef(self.filepostname, 'imgfile'), uploadjson = k.undef(self.uploadjson, self.basepath 'php/upload_json.php'); self.plugin.flash = { edit : function() { var html = [ '
    ', //url '
    ', '', '  ', '  ', '', '', '', '
    ', //width '
    ', '', ' ', '
    ', //height '
    ', '', ' ', '
    ', '
    ' ].join(''); var dialog = self.createdialog({ name : name, width : 450, title : self.lang(name), body : html, yesbtn : { name : self.lang('yes'), click : function(e) { var url = k.trim(urlbox.val()), width = widthbox.val(), height = heightbox.val(); if (url == 'http://' || k.invalid) { alert(self.lang('invalidurl')); urlbox[0].focus(); return; } if (!/^\d*$/.test(width)) { alert(self.lang('invalidwidth')); widthbox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidheight')); heightbox[0].focus(); return; } var html = k.mediaimg(self.themespath 'common/blank.gif', { src : url, type : k.mediatype('.swf'), width : width, height : height, quality : 'high' }); self.inserthtml(html).hidedialog().focus(); } } }), div = dialog.div, urlbox = k('[name="url"]', div), viewserverbtn = k('[name="viewserver"]', div), widthbox = k('[name="width"]', div), heightbox = k('[name="height"]', div); urlbox.val('http://'); if (allowflashupload) { var uploadbutton = k.uploadbutton({ button : k('.ke-upload-button', div)[0], fieldname : filepostname, extraparams : extraparams, url : k.addparam(uploadjson, 'dir=flash'), afterupload : function(data) { dialog.hideloading(); if (data.error === 0) { var url = data.url; if (formatuploadurl) { url = k.format; } urlbox.val(url); if (self.afterupload) { self.afterupload.call(self, url, data, name); } alert(self.lang('uploadsuccess')); } else { alert(data.message); } }, aftererror : function(html) { dialog.hideloading(); self.errordialog(html); } }); uploadbutton.filebox.change(function(e) { dialog.showloading(self.lang('uploadloading')); uploadbutton.submit(); }); } else { k('.ke-upload-button', div).hide(); } if (allowfilemanager) { viewserverbtn.click(function(e) { self.loadplugin('filemanager', function() { self.plugin.filemanagerdialog({ viewtype : 'list', dirname : 'flash', clickfn : function(url, title) { if (self.dialogs.length > 1) { k('[name="url"]', div).val(url); if (self.afterselectfile) { self.afterselectfile.call(self, url); } self.hidedialog(); } } }); }); }); } else { viewserverbtn.hide(); } var img = self.plugin.getselectedflash(); if (img) { var attrs = k.mediaattrs(img.attr('data-ke-tag')); urlbox.val(attrs.src); widthbox.val(k.removeunit(img.css('width')) || attrs.width || 0); heightbox.val(k.removeunit(img.css('height')) || attrs.height || 0); } urlbox[0].focus(); urlbox[0].select(); }, 'delete' : function() { self.plugin.getselectedflash().remove(); // [ie] 删除图片后立即点击图片按钮出错 self.addbookmark(); } }; self.clicktoolbar(name, self.plugin.flash.edit); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('image', function(k) { var self = this, name = 'image', allowimageupload = k.undef(self.allowimageupload, true), allowimageremote = k.undef(self.allowimageremote, true), formatuploadurl = k.undef(self.formatuploadurl, true), allowfilemanager = k.undef(self.allowfilemanager, false), uploadjson = k.undef(self.uploadjson, self.basepath 'php/upload_json.php'), imagetabindex = k.undef(self.imagetabindex, 0), imgpath = self.pluginspath 'image/images/', extraparams = k.undef(self.extrafileuploadparams, {}), filepostname = k.undef(self.filepostname, 'imgfile'), filldescafteruploadimage = k.undef(self.filldescafteruploadimage, false), lang = self.lang(name '.'); self.plugin.imagedialog = function(options) { var imageurl = options.imageurl, imagewidth = k.undef(options.imagewidth, ''), imageheight = k.undef(options.imageheight, ''), imagetitle = k.undef(options.imagetitle, ''), imagealign = k.undef(options.imagealign, ''), showremote = k.undef(options.showremote, true), showlocal = k.undef(options.showlocal, true), tabindex = k.undef(options.tabindex, 0), clickfn = options.clickfn; var target = 'kindeditor_upload_iframe_' new date().gettime(); var hiddenelements = []; for(var k in extraparams){ hiddenelements.push(''); } var html = [ '
    ', //tabs '
    ', //remote image - start '', //remote image - end //local upload - start '', //local upload - end '
    ' ].join(''); var dialogwidth = showlocal || allowfilemanager ? 450 : 400, dialogheight = showlocal && showremote ? 300 : 250; var dialog = self.createdialog({ name : name, width : dialogwidth, height : dialogheight, title : self.lang(name), body : html, yesbtn : { name : self.lang('yes'), click : function(e) { // bugfix: http://code.google.com/p/kindeditor/issues/detail?id=319 if (dialog.isloading) { return; } // insert local image if (showlocal && showremote && tabs && tabs.selectedindex === 1 || !showremote) { if (uploadbutton.filebox.val() == '') { alert(self.lang('pleaseselectfile')); return; } dialog.showloading(self.lang('uploadloading')); uploadbutton.submit(); localurlbox.val(''); return; } // insert remote image var url = k.trim(urlbox.val()), width = widthbox.val(), height = heightbox.val(), title = titlebox.val(), align = ''; alignbox.each(function() { if (this.checked) { align = this.value; return false; } }); if (url == 'http://' || k.invalid) { alert(self.lang('invalidurl')); urlbox[0].focus(); return; } if (!/^\d*$/.test(width)) { alert(self.lang('invalidwidth')); widthbox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidheight')); heightbox[0].focus(); return; } clickfn.call(self, url, title, width, height, 0, align); } }, beforeremove : function() { viewserverbtn.unbind(); widthbox.unbind(); heightbox.unbind(); refreshbtn.unbind(); } }), div = dialog.div; var urlbox = k('[name="url"]', div), localurlbox = k('[name="localurl"]', div), viewserverbtn = k('[name="viewserver"]', div), widthbox = k('.tab1 [name="width"]', div), heightbox = k('.tab1 [name="height"]', div), refreshbtn = k('.ke-refresh-btn', div), titlebox = k('.tab1 [name="title"]', div), alignbox = k('.tab1 [name="align"]', div); var tabs; if (showremote && showlocal) { tabs = k.tabs({ src : k('.tabs', div), afterselect : function(i) {} }); tabs.add({ title : lang.remoteimage, panel : k('.tab1', div) }); tabs.add({ title : lang.localimage, panel : k('.tab2', div) }); tabs.select(tabindex); } else if (showremote) { k('.tab1', div).show(); } else if (showlocal) { k('.tab2', div).show(); } var uploadbutton = k.uploadbutton({ button : k('.ke-upload-button', div)[0], fieldname : filepostname, form : k('.ke-form', div), target : target, width: 60, afterupload : function(data) { dialog.hideloading(); if (data.error === 0) { var url = data.url; if (formatuploadurl) { url = k.format; } if (self.afterupload) { self.afterupload.call(self, url, data, name); } if (!filldescafteruploadimage) { clickfn.call(self, url, data.title, data.width, data.height, data.border, data.align); } else { k(".ke-dialog-row #remoteurl", div).val(url); k(".ke-tabs-li", div)[0].click(); k(".ke-refresh-btn", div).click(); } } else { alert(data.message); } }, aftererror : function(html) { dialog.hideloading(); self.errordialog(html); } }); uploadbutton.filebox.change(function(e) { localurlbox.val(uploadbutton.filebox.val()); }); if (allowfilemanager) { viewserverbtn.click(function(e) { self.loadplugin('filemanager', function() { self.plugin.filemanagerdialog({ viewtype : 'view', dirname : 'image', clickfn : function(url, title) { if (self.dialogs.length > 1) { k('[name="url"]', div).val(url); if (self.afterselectfile) { self.afterselectfile.call(self, url); } self.hidedialog(); } } }); }); }); } else { viewserverbtn.hide(); } var originalwidth = 0, originalheight = 0; function setsize(width, height) { widthbox.val(width); heightbox.val(height); originalwidth = width; originalheight = height; } refreshbtn.click(function(e) { var tempimg = k('', document).css({ position : 'absolute', visibility : 'hidden', top : 0, left : '-1000px' }); tempimg.bind('load', function() { setsize(tempimg.width(), tempimg.height()); tempimg.remove(); }); k(document.body).append(tempimg); }); widthbox.change(function(e) { if (originalwidth > 0) { heightbox.val(math.round(originalheight / originalwidth * parseint(this.value, 10))); } }); heightbox.change(function(e) { if (originalheight > 0) { widthbox.val(math.round(originalwidth / originalheight * parseint(this.value, 10))); } }); urlbox.val(options.imageurl); setsize(options.imagewidth, options.imageheight); titlebox.val(options.imagetitle); alignbox.each(function() { if (this.value === options.imagealign) { this.checked = true; return false; } }); if (showremote && tabindex === 0) { urlbox[0].focus(); urlbox[0].select(); } return dialog; }; self.plugin.image = { edit : function() { var img = self.plugin.getselectedimage(); self.plugin.imagedialog({ imageurl : img ? img.attr('data-ke-src') : 'http://', imagewidth : img ? img.width() : '', imageheight : img ? img.height() : '', imagetitle : img ? img.attr('title') : '', imagealign : img ? img.attr('align') : '', showremote : allowimageremote, showlocal : allowimageupload, tabindex: img ? 0 : imagetabindex, clickfn : function(url, title, width, height, border, align) { if (img) { img.attr('src', url); img.attr('data-ke-src', url); img.attr('width', width); img.attr('height', height); img.attr('title', title); img.attr('align', align); img.attr('alt', title); } else { self.exec('insertimage', url, title, width, height, border, align); } // bugfix: [firefox] 上传图片后,总是出现正在加载的样式,需要延迟执行hidedialog settimeout(function() { self.hidedialog().focus(); }, 0); } }); }, 'delete' : function() { var target = self.plugin.getselectedimage(); if (target.parent().name == 'a') { target = target.parent(); } target.remove(); // [ie] 删除图片后立即点击图片按钮出错 self.addbookmark(); } }; self.clicktoolbar(name, self.plugin.image.edit); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('insertfile', function(k) { var self = this, name = 'insertfile', allowfileupload = k.undef(self.allowfileupload, true), allowfilemanager = k.undef(self.allowfilemanager, false), formatuploadurl = k.undef(self.formatuploadurl, true), uploadjson = k.undef(self.uploadjson, self.basepath 'php/upload_json.php'), extraparams = k.undef(self.extrafileuploadparams, {}), filepostname = k.undef(self.filepostname, 'imgfile'), lang = self.lang(name '.'); self.plugin.filedialog = function(options) { var fileurl = k.undef(options.fileurl, 'http://'), filetitle = k.undef(options.filetitle, ''), clickfn = options.clickfn; var html = [ '
    ', '
    ', '', '  ', '  ', '', '', '', '
    ', //title '
    ', '', '
    ', '
    ', //form end '', '' ].join(''); var dialog = self.createdialog({ name : name, width : 450, title : self.lang(name), body : html, yesbtn : { name : self.lang('yes'), click : function(e) { var url = k.trim(urlbox.val()), title = titlebox.val(); if (url == 'http://' || k.invalid) { alert(self.lang('invalidurl')); urlbox[0].focus(); return; } if (k.trim(title) === '') { title = url; } clickfn.call(self, url, title); } } }), div = dialog.div; var urlbox = k('[name="url"]', div), viewserverbtn = k('[name="viewserver"]', div), titlebox = k('[name="title"]', div); if (allowfileupload) { var uploadbutton = k.uploadbutton({ button : k('.ke-upload-button', div)[0], fieldname : filepostname, url : k.addparam(uploadjson, 'dir=file'), extraparams : extraparams, afterupload : function(data) { dialog.hideloading(); if (data.error === 0) { var url = data.url; if (formatuploadurl) { url = k.format; } urlbox.val(url); if (self.afterupload) { self.afterupload.call(self, url, data, name); } alert(self.lang('uploadsuccess')); } else { alert(data.message); } }, aftererror : function(html) { dialog.hideloading(); self.errordialog(html); } }); uploadbutton.filebox.change(function(e) { dialog.showloading(self.lang('uploadloading')); uploadbutton.submit(); }); } else { k('.ke-upload-button', div).hide(); } if (allowfilemanager) { viewserverbtn.click(function(e) { self.loadplugin('filemanager', function() { self.plugin.filemanagerdialog({ viewtype : 'list', dirname : 'file', clickfn : function(url, title) { if (self.dialogs.length > 1) { k('[name="url"]', div).val(url); if (self.afterselectfile) { self.afterselectfile.call(self, url); } self.hidedialog(); } } }); }); }); } else { viewserverbtn.hide(); } urlbox.val(fileurl); titlebox.val(filetitle); urlbox[0].focus(); urlbox[0].select(); }; self.clicktoolbar(name, function() { self.plugin.filedialog({ clickfn : function(url, title) { var html = ''; self.inserthtml(html).hidedialog().focus(); } }); }); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('lineheight', function(k) { var self = this, name = 'lineheight', lang = self.lang(name '.'); self.clicktoolbar(name, function() { var curval = '', commonnode = self.cmd.commonnode({'*' : '.line-height'}); if (commonnode) { curval = commonnode.css('line-height'); } var menu = self.createmenu({ name : name, width : 150 }); k.each(lang.lineheight, function(i, row) { k.each(row, function(key, val) { menu.additem({ title : val, checked : curval === key, click : function() { self.cmd.toggle('', { span : '.line-height=' key }); self.updatestate(); self.addbookmark(); self.hidemenu(); } }); }); }); }); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('link', function(k) { var self = this, name = 'link'; self.plugin.link = { edit : function() { var lang = self.lang(name '.'), html = '
    ' //url '
    ' '' '
    ' //type '
    ' '' '' '
    ' '
    ', dialog = self.createdialog({ name : name, width : 450, title : self.lang(name), body : html, yesbtn : { name : self.lang('yes'), click : function(e) { var url = k.trim(urlbox.val()); if (url == 'http://' || k.invalid) { alert(self.lang('invalidurl')); urlbox[0].focus(); return; } self.exec('createlink', url, typebox.val()).hidedialog().focus(); } } }), div = dialog.div, urlbox = k('input[name="url"]', div), typebox = k('select[name="type"]', div); urlbox.val('http://'); typebox[0].options[0] = new option(lang.newwindow, '_blank'); typebox[0].options[1] = new option(lang.selfwindow, ''); self.cmd.selection(); var a = self.plugin.getselectedlink(); if (a) { self.cmd.range.selectnode(a[0]); self.cmd.select(); urlbox.val(a.attr('data-ke-src')); typebox.val(a.attr('target')); } urlbox[0].focus(); urlbox[0].select(); }, 'delete' : function() { self.exec('unlink', null); } }; self.clicktoolbar(name, self.plugin.link.edit); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ // google maps: http://code.google.com/apis/maps/index.html kindeditor.plugin('map', function(k) { var self = this, name = 'map', lang = self.lang(name '.'); self.clicktoolbar(name, function() { var html = ['
    ', '
    ', lang.address ' ', '', '', '', '
    ', '
    ', '
    '].join(''); var dialog = self.createdialog({ name : name, width : 600, title : self.lang(name), body : html, yesbtn : { name : self.lang('yes'), click : function(e) { var geocoder = win.geocoder, map = win.map, center = map.getcenter().lat() ',' map.getcenter().lng(), zoom = map.getzoom(), maptype = map.getmaptypeid(), url = 'http://maps.googleapis.com/maps/api/staticmap'; url = '?center=' encodeuricomponent(center); url = '&zoom=' encodeuricomponent(zoom); url = '&size=558x360'; url = '&maptype=' encodeuricomponent(maptype); url = '&markers=' encodeuricomponent(center); url = '&language=' self.langtype; url = '&sensor=false'; self.exec('insertimage', url).hidedialog().focus(); } }, beforeremove : function() { searchbtn.remove(); if (doc) { doc.write(''); } iframe.remove(); } }); var div = dialog.div, addressbox = k('[name="address"]', div), searchbtn = k('[name="searchbtn"]', div), win, doc; var iframehtml = ['', '', '', '', '', '', '', '
    ', ''].join('\n'); // todo:用doc.write(iframehtml)方式加载时,在ie6上第一次加载报错,暂时使用src方式 var iframe = k(''); function ready() { win = iframe[0].contentwindow; doc = k.iframedoc(iframe); //doc.open(); //doc.write(iframehtml); //doc.close(); } iframe.bind('load', function() { iframe.unbind('load'); if (k.ie) { ready(); } else { settimeout(ready, 0); } }); k('.ke-map', div).replacewith(iframe); // search map searchbtn.click(function() { win.search(addressbox.val()); }); }); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('media', function(k) { var self = this, name = 'media', lang = self.lang(name '.'), allowmediaupload = k.undef(self.allowmediaupload, true), allowfilemanager = k.undef(self.allowfilemanager, false), formatuploadurl = k.undef(self.formatuploadurl, true), extraparams = k.undef(self.extrafileuploadparams, {}), filepostname = k.undef(self.filepostname, 'imgfile'), uploadjson = k.undef(self.uploadjson, self.basepath 'php/upload_json.php'); self.plugin.media = { edit : function() { var html = [ '
    ', //url '
    ', '', '  ', '  ', '', '', '', '
    ', //width '
    ', '', '', '
    ', //height '
    ', '', '', '
    ', //autostart '
    ', '', ' ', '
    ', '
    ' ].join(''); var dialog = self.createdialog({ name : name, width : 450, height : 230, title : self.lang(name), body : html, yesbtn : { name : self.lang('yes'), click : function(e) { var url = k.trim(urlbox.val()), width = widthbox.val(), height = heightbox.val(); if (url == 'http://' || k.invalid) { alert(self.lang('invalidurl')); urlbox[0].focus(); return; } if (!/^\d*$/.test(width)) { alert(self.lang('invalidwidth')); widthbox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidheight')); heightbox[0].focus(); return; } var html = k.mediaimg(self.themespath 'common/blank.gif', { src : url, type : k.mediatype(url), width : width, height : height, autostart : autostartbox[0].checked ? 'true' : 'false', loop : 'true' }); self.inserthtml(html).hidedialog().focus(); } } }), div = dialog.div, urlbox = k('[name="url"]', div), viewserverbtn = k('[name="viewserver"]', div), widthbox = k('[name="width"]', div), heightbox = k('[name="height"]', div), autostartbox = k('[name="autostart"]', div); urlbox.val('http://'); if (allowmediaupload) { var uploadbutton = k.uploadbutton({ button : k('.ke-upload-button', div)[0], fieldname : filepostname, extraparams : extraparams, url : k.addparam(uploadjson, 'dir=media'), afterupload : function(data) { dialog.hideloading(); if (data.error === 0) { var url = data.url; if (formatuploadurl) { url = k.format; } urlbox.val(url); if (self.afterupload) { self.afterupload.call(self, url, data, name); } alert(self.lang('uploadsuccess')); } else { alert(data.message); } }, aftererror : function(html) { dialog.hideloading(); self.errordialog(html); } }); uploadbutton.filebox.change(function(e) { dialog.showloading(self.lang('uploadloading')); uploadbutton.submit(); }); } else { k('.ke-upload-button', div).hide(); } if (allowfilemanager) { viewserverbtn.click(function(e) { self.loadplugin('filemanager', function() { self.plugin.filemanagerdialog({ viewtype : 'list', dirname : 'media', clickfn : function(url, title) { if (self.dialogs.length > 1) { k('[name="url"]', div).val(url); if (self.afterselectfile) { self.afterselectfile.call(self, url); } self.hidedialog(); } } }); }); }); } else { viewserverbtn.hide(); } var img = self.plugin.getselectedmedia(); if (img) { var attrs = k.mediaattrs(img.attr('data-ke-tag')); urlbox.val(attrs.src); widthbox.val(k.removeunit(img.css('width')) || attrs.width || 0); heightbox.val(k.removeunit(img.css('height')) || attrs.height || 0); autostartbox[0].checked = (attrs.autostart === 'true'); } urlbox[0].focus(); urlbox[0].select(); }, 'delete' : function() { self.plugin.getselectedmedia().remove(); // [ie] 删除图片后立即点击图片按钮出错 self.addbookmark(); } }; self.clicktoolbar(name, self.plugin.media.edit); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ (function(k) { function kswfupload(options) { this.init(options); } k.extend(kswfupload, { init : function(options) { var self = this; options.aftererror = options.aftererror || function(str) { alert(str); }; self.options = options; self.progressbars = {}; // template self.div = k(options.container).html([ '
    ', '
    ', '
    ', '', '
    ', '
    ' options.uploaddesc '
    ', '', '', '', '
    ', '
    ', '
    ' ].join('')); self.bodydiv = k('.ke-swfupload-body', self.div); function showerror(itemdiv, msg) { k('.ke-status > div', itemdiv).hide(); k('.ke-message', itemdiv).addclass('ke-error').show().html(k.escape(msg)); } var settings = { debug : false, upload_url : options.uploadurl, flash_url : options.flashurl, file_post_name : options.filepostname, button_placeholder : k('.ke-swfupload-button > input', self.div)[0], button_image_url: options.buttonimageurl, button_width: options.buttonwidth, button_height: options.buttonheight, button_cursor : swfupload.cursor.hand, file_types : options.filetypes, file_types_description : options.filetypesdesc, file_upload_limit : options.fileuploadlimit, file_size_limit : options.filesizelimit, post_params : options.postparams, file_queued_handler : function(file) { file.url = self.options.fileiconurl; self.appendfile(file); }, file_queue_error_handler : function(file, errorcode, message) { var errorname = ''; switch (errorcode) { case swfupload.queue_error.queue_limit_exceeded: errorname = options.queuelimitexceeded; break; case swfupload.queue_error.file_exceeds_size_limit: errorname = options.fileexceedssizelimit; break; case swfupload.queue_error.zero_byte_file: errorname = options.zerobytefile; break; case swfupload.queue_error.invalid_filetype: errorname = options.invalidfiletype; break; default: errorname = options.unknownerror; break; } k.debug && alert(errorname); }, upload_start_handler : function(file) { var self = this; var itemdiv = k('div[data-id="' file.id '"]', self.bodydiv); k('.ke-status > div', itemdiv).hide(); k('.ke-progressbar', itemdiv).show(); }, upload_progress_handler : function(file, bytesloaded, bytestotal) { var percent = math.round(bytesloaded * 100 / bytestotal); var progressbar = self.progressbars[file.id]; progressbar.bar.css('width', math.round(percent * 80 / 100) 'px'); progressbar.percent.html(percent '%'); }, upload_error_handler : function(file, errorcode, message) { if (file && file.filestatus == swfupload.file_status.error) { var itemdiv = k('div[data-id="' file.id '"]', self.bodydiv).eq(0); showerror(itemdiv, self.options.errormessage); } }, upload_success_handler : function(file, serverdata) { var itemdiv = k('div[data-id="' file.id '"]', self.bodydiv).eq(0); var data = {}; try { data = k.json(serverdata); } catch (e) { self.options.aftererror.call(this, '' serverdata ''); } if (data.error !== 0) { showerror(itemdiv, k.debug ? data.message : self.options.errormessage); return; } file.url = data.url; k('.ke-img', itemdiv).attr('src', file.url).attr('data-status', file.filestatus).data('data', data); k('.ke-status > div', itemdiv).hide(); } }; self.swfu = new swfupload(settings); k('.ke-swfupload-startupload input', self.div).click(function() { self.swfu.startupload(); }); }, geturllist : function() { var list = []; k('.ke-img', self.bodydiv).each(function() { var img = k(this); var status = img.attr('data-status'); if (status == swfupload.file_status.complete) { list.push(img.data('data')); } }); return list; }, removefile : function(fileid) { var self = this; self.swfu.cancelupload(fileid); var itemdiv = k('div[data-id="' fileid '"]', self.bodydiv); k('.ke-photo', itemdiv).unbind(); k('.ke-delete', itemdiv).unbind(); itemdiv.remove(); }, removefiles : function() { var self = this; k('.ke-item', self.bodydiv).each(function() { self.removefile(k(this).attr('data-id')); }); }, appendfile : function(file) { var self = this; var itemdiv = k('
    '); self.bodydiv.append(itemdiv); var photodiv = k('
    ') .mouseover(function(e) { k(this).addclass('ke-on'); }) .mouseout(function(e) { k(this).removeclass('ke-on'); }); itemdiv.append(photodiv); var img = k(''); photodiv.append(img); k('').appendto(photodiv).click(function() { self.removefile(file.id); }); var statusdiv = k('
    ').appendto(photodiv); // progressbar k(['
    ', '
    ', '
    0%
    '].join('')).hide().appendto(statusdiv); // message k('
    ' self.options.pendingmessage '
    ').appendto(statusdiv); itemdiv.append('
    ' file.name '
    '); self.progressbars[file.id] = { bar : k('.ke-progressbar-bar-inner', photodiv), percent : k('.ke-progressbar-percent', photodiv) }; }, remove : function() { this.removefiles(); this.swfu.destroy(); this.div.html(''); } }); k.swfupload = function(element, options) { return new kswfupload(element, options); }; })(kindeditor); kindeditor.plugin('multiimage', function(k) { var self = this, name = 'multiimage', formatuploadurl = k.undef(self.formatuploadurl, true), uploadjson = k.undef(self.uploadjson, self.basepath 'php/upload_json.php'), imgpath = self.pluginspath 'multiimage/images/', imagesizelimit = k.undef(self.imagesizelimit, '1mb'), imagefiletypes = k.undef(self.imagefiletypes, '*.jpg;*.gif;*.png'), imageuploadlimit = k.undef(self.imageuploadlimit, 20), filepostname = k.undef(self.filepostname, 'imgfile'), lang = self.lang(name '.'); self.plugin.multiimagedialog = function(options) { var clickfn = options.clickfn, uploaddesc = k.tmpl(lang.uploaddesc, {uploadlimit : imageuploadlimit, sizelimit : imagesizelimit}); var html = [ '
    ', '
    ', '
    ', '
    ' ].join(''); var dialog = self.createdialog({ name : name, width : 650, height : 510, title : self.lang(name), body : html, previewbtn : { name : lang.insertall, click : function(e) { clickfn.call(self, swfupload.geturllist()); } }, yesbtn : { name : lang.clearall, click : function(e) { swfupload.removefiles(); } }, beforeremove : function() { // ie9 bugfix: https://github.com/kindsoft/kindeditor/issues/72 if (!k.ie || k.v <= 8) { swfupload.remove(); } } }), div = dialog.div; var swfupload = k.swfupload({ container : k('.swfupload', div), buttonimageurl : imgpath (self.langtype == 'zh_cn' ? 'select-files-zh_cn.png' : 'select-files-en.png'), buttonwidth : self.langtype == 'zh_cn' ? 72 : 88, buttonheight : 23, fileiconurl : imgpath 'image.png', uploaddesc : uploaddesc, startbuttonvalue : lang.startupload, uploadurl : k.addparam(uploadjson, 'dir=image'), flashurl : imgpath 'swfupload.swf', filepostname : filepostname, filetypes : '*.jpg;*.jpeg;*.gif;*.png;*.bmp', filetypesdesc : 'image files', fileuploadlimit : imageuploadlimit, filesizelimit : imagesizelimit, postparams : k.undef(self.extrafileuploadparams, {}), queuelimitexceeded : lang.queuelimitexceeded, fileexceedssizelimit : lang.fileexceedssizelimit, zerobytefile : lang.zerobytefile, invalidfiletype : lang.invalidfiletype, unknownerror : lang.unknownerror, pendingmessage : lang.pending, errormessage : lang.uploaderror, aftererror : function(html) { self.errordialog(html); } }); return dialog; }; self.clicktoolbar(name, function() { self.plugin.multiimagedialog({ clickfn : function (urllist) { if (urllist.length === 0) { return; } k.each(urllist, function(i, data) { if (self.afterupload) { self.afterupload.call(self, data.url, data, 'multiimage'); } self.exec('insertimage', data.url, data.title, data.width, data.height, data.border, data.align); }); // bugfix: [firefox] 上传图片后,总是出现正在加载的样式,需要延迟执行hidedialog settimeout(function() { self.hidedialog().focus(); }, 0); } }); }); }); /** * swfupload: http://www.swfupload.org, http://swfupload.googlecode.com * * mmswfupload 1.0: flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/ * * swfupload is (c) 2006-2007 lars huring, olov nilz閚 and mammon media and is released under the mit license: * http://www.opensource.org/licenses/mit-license.php * * swfupload 2 is (c) 2007-2008 jake roberts and is released under the mit license: * http://www.opensource.org/licenses/mit-license.php * */ /* ******************* */ /* constructor & init */ /* ******************* */ (function() { window.swfupload = function (settings) { this.initswfupload(settings); }; swfupload.prototype.initswfupload = function (settings) { try { this.customsettings = {}; // a container where developers can place their own settings associated with this instance. this.settings = settings; this.eventqueue = []; this.moviename = "kindeditor_swfupload_" swfupload.moviecount ; this.movieelement = null; // setup global control tracking swfupload.instances[this.moviename] = this; // load the settings. load the flash movie. this.initsettings(); this.loadflash(); this.displaydebuginfo(); } catch (ex) { delete swfupload.instances[this.moviename]; throw ex; } }; /* *************** */ /* static members */ /* *************** */ swfupload.instances = {}; swfupload.moviecount = 0; swfupload.version = "2.2.0 2009-03-25"; swfupload.queue_error = { queue_limit_exceeded : -100, file_exceeds_size_limit : -110, zero_byte_file : -120, invalid_filetype : -130 }; swfupload.upload_error = { http_error : -200, missing_upload_url : -210, io_error : -220, security_error : -230, upload_limit_exceeded : -240, upload_failed : -250, specified_file_id_not_found : -260, file_validation_failed : -270, file_cancelled : -280, upload_stopped : -290 }; swfupload.file_status = { queued : -1, in_progress : -2, error : -3, complete : -4, cancelled : -5 }; swfupload.button_action = { select_file : -100, select_files : -110, start_upload : -120 }; swfupload.cursor = { arrow : -1, hand : -2 }; swfupload.window_mode = { window : "window", transparent : "transparent", opaque : "opaque" }; // private: takes a url, determines if it is relative and converts to an absolute url // using the current site. only processes the url if it can, otherwise returns the url untouched swfupload.completeurl = function(url) { if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) { return url; } var currenturl = window.location.protocol "//" window.location.hostname (window.location.port ? ":" window.location.port : ""); var indexslash = window.location.pathname.lastindexof("/"); if (indexslash <= 0) { path = "/"; } else { path = window.location.pathname.substr(0, indexslash) "/"; } return /*currenturl */ path url; }; /* ******************** */ /* instance members */ /* ******************** */ // private: initsettings ensures that all the // settings are set, getting a default value if one was not assigned. swfupload.prototype.initsettings = function () { this.ensuredefault = function (settingname, defaultvalue) { this.settings[settingname] = (this.settings[settingname] == undefined) ? defaultvalue : this.settings[settingname]; }; // upload backend settings this.ensuredefault("upload_url", ""); this.ensuredefault("preserve_relative_urls", false); this.ensuredefault("file_post_name", "filedata"); this.ensuredefault("post_params", {}); this.ensuredefault("use_query_string", false); this.ensuredefault("requeue_on_error", false); this.ensuredefault("http_success", []); this.ensuredefault("assume_success_timeout", 0); // file settings this.ensuredefault("file_types", "*.*"); this.ensuredefault("file_types_description", "all files"); this.ensuredefault("file_size_limit", 0); // default zero means "unlimited" this.ensuredefault("file_upload_limit", 0); this.ensuredefault("file_queue_limit", 0); // flash settings this.ensuredefault("flash_url", "swfupload.swf"); this.ensuredefault("prevent_swf_caching", true); // button settings this.ensuredefault("button_image_url", ""); this.ensuredefault("button_width", 1); this.ensuredefault("button_height", 1); this.ensuredefault("button_text", ""); this.ensuredefault("button_text_style", "color: #000000; font-size: 16pt;"); this.ensuredefault("button_text_top_padding", 0); this.ensuredefault("button_text_left_padding", 0); this.ensuredefault("button_action", swfupload.button_action.select_files); this.ensuredefault("button_disabled", false); this.ensuredefault("button_placeholder_id", ""); this.ensuredefault("button_placeholder", null); this.ensuredefault("button_cursor", swfupload.cursor.arrow); this.ensuredefault("button_window_mode", swfupload.window_mode.window); // debug settings this.ensuredefault("debug", false); this.settings.debug_enabled = this.settings.debug; // here to maintain v2 api // event handlers this.settings.return_upload_start_handler = this.returnuploadstart; this.ensuredefault("swfupload_loaded_handler", null); this.ensuredefault("file_dialog_start_handler", null); this.ensuredefault("file_queued_handler", null); this.ensuredefault("file_queue_error_handler", null); this.ensuredefault("file_dialog_complete_handler", null); this.ensuredefault("upload_start_handler", null); this.ensuredefault("upload_progress_handler", null); this.ensuredefault("upload_error_handler", null); this.ensuredefault("upload_success_handler", null); this.ensuredefault("upload_complete_handler", null); this.ensuredefault("debug_handler", this.debugmessage); this.ensuredefault("custom_settings", {}); // other settings this.customsettings = this.settings.custom_settings; // update the flash url if needed if (!!this.settings.prevent_swf_caching) { this.settings.flash_url = this.settings.flash_url (this.settings.flash_url.indexof("?") < 0 ? "?" : "&") "preventswfcaching=" new date().gettime(); } if (!this.settings.preserve_relative_urls) { //this.settings.flash_url = swfupload.complete; // don't need to do this one since flash doesn't look at it this.settings.upload_url = swfupload.complete; this.settings.button_image_url = swfupload.complete; } delete this.ensuredefault; }; // private: loadflash replaces the button_placeholder element with the flash movie. swfupload.prototype.loadflash = function () { var targetelement, tempparent; // make sure an element with the id we are going to use doesn't already exist if (document.getelementbyid(this.moviename) !== null) { throw "id " this.moviename " is already in use. the flash object could not be added"; } // get the element where we will be placing the flash movie targetelement = document.getelementbyid(this.settings.button_placeholder_id) || this.settings.button_placeholder; if (targetelement == undefined) { throw "could not find the placeholder element: " this.settings.button_placeholder_id; } // append the container and load the flash tempparent = document.createelement("div"); tempparent.innerhtml = this.getflashhtml(); // using innerhtml is non-standard but the only sensible way to dynamically add flash in ie (and maybe other browsers) targetelement.parentnode.replacechild(tempparent.firstchild, targetelement); // fix ie flash/form bug if (window[this.moviename] == undefined) { window[this.moviename] = this.getmovieelement(); } }; // private: getflashhtml generates the object tag needed to embed the flash in to the document swfupload.prototype.getflashhtml = function () { // flash satay object syntax: http://www.alistapart.com/articles/flashsatay // fix bug for ie9 // http://www.kindsoft.net/view.php?bbsid=7&postid=5825&pagenum=1 var classid = ''; if (kindeditor.ie && kindeditor.v > 8) { classid = ' classid = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"'; } return [''].join(""); }; // private: getflashvars builds the parameter string that will be passed // to flash in the flashvars param. swfupload.prototype.getflashvars = function () { // build a string from the post param object var paramstring = this.buildparamstring(); var httpsuccessstring = this.settings.http_success.join(","); // build the parameter string return ["moviename=", encodeuricomponent(this.moviename), "&uploadurl=", encodeuricomponent(this.settings.upload_url), "&usequerystring=", encodeuricomponent(this.settings.use_query_string), "&requeueonerror=", encodeuricomponent(this.settings.requeue_on_error), "&httpsuccess=", encodeuricomponent(httpsuccessstring), "&assumesuccesstimeout=", encodeuricomponent(this.settings.assume_success_timeout), "¶ms=", encodeuricomponent(paramstring), "&filepostname=", encodeuricomponent(this.settings.file_post_name), "&filetypes=", encodeuricomponent(this.settings.file_types), "&filetypesdescription=", encodeuricomponent(this.settings.file_types_description), "&filesizelimit=", encodeuricomponent(this.settings.file_size_limit), "&fileuploadlimit=", encodeuricomponent(this.settings.file_upload_limit), "&filequeuelimit=", encodeuricomponent(this.settings.file_queue_limit), "&debugenabled=", encodeuricomponent(this.settings.debug_enabled), "&buttonimageurl=", encodeuricomponent(this.settings.button_image_url), "&buttonwidth=", encodeuricomponent(this.settings.button_width), "&buttonheight=", encodeuricomponent(this.settings.button_height), "&buttontext=", encodeuricomponent(this.settings.button_text), "&buttontexttoppadding=", encodeuricomponent(this.settings.button_text_top_padding), "&buttontextleftpadding=", encodeuricomponent(this.settings.button_text_left_padding), "&buttontextstyle=", encodeuricomponent(this.settings.button_text_style), "&buttonaction=", encodeuricomponent(this.settings.button_action), "&buttondisabled=", encodeuricomponent(this.settings.button_disabled), "&buttoncursor=", encodeuricomponent(this.settings.button_cursor) ].join(""); }; // public: getmovieelement retrieves the dom reference to the flash element added by swfupload // the element is cached after the first lookup swfupload.prototype.getmovieelement = function () { if (this.movieelement == undefined) { this.movieelement = document.getelementbyid(this.moviename); } if (this.movieelement === null) { throw "could not find flash element"; } return this.movieelement; }; // private: buildparamstring takes the name/value pairs in the post_params setting object // and joins them up in to a string formatted "name=value&name=value" swfupload.prototype.buildparamstring = function () { var postparams = this.settings.post_params; var paramstringpairs = []; if (typeof(postparams) === "object") { for (var name in postparams) { if (postparams.hasownproperty(name)) { paramstringpairs.push(encodeuricomponent(name.tostring()) "=" encodeuricomponent(postparams[name].tostring())); } } } return paramstringpairs.join("&"); }; // public: used to remove a swfupload instance from the page. this method strives to remove // all references to the swf, and other objects so memory is properly freed. // returns true if everything was destroyed. returns a false if a failure occurs leaving swfupload in an inconsistant state. // credits: major improvements provided by steffen swfupload.prototype.destroy = function () { try { // make sure flash is done before we try to remove it this.cancelupload(null, false); // remove the swfupload dom nodes var movieelement = null; movieelement = this.getmovieelement(); if (movieelement && typeof(movieelement.callfunction) === "unknown") { // we only want to do this in ie // loop through all the movie's properties and remove all function references (dom/js ie 6/7 memory leak workaround) for (var i in movieelement) { try { if (typeof(movieelement[i]) === "function") { movieelement[i] = null; } } catch (ex1) {} } // remove the movie element from the page try { movieelement.parentnode.removechild(movieelement); } catch (ex) {} } // remove ie form fix reference window[this.moviename] = null; // destroy other references swfupload.instances[this.moviename] = null; delete swfupload.instances[this.moviename]; this.movieelement = null; this.settings = null; this.customsettings = null; this.eventqueue = null; this.moviename = null; return true; } catch (ex2) { return false; } }; // public: displaydebuginfo prints out settings and configuration // information about this swfupload instance. // this function (and any references to it) can be deleted when placing // swfupload in production. swfupload.prototype.displaydebuginfo = function () { this.debug( [ "---swfupload instance info---\n", "version: ", swfupload.version, "\n", "movie name: ", this.moviename, "\n", "settings:\n", "\t", "upload_url: ", this.settings.upload_url, "\n", "\t", "flash_url: ", this.settings.flash_url, "\n", "\t", "use_query_string: ", this.settings.use_query_string.tostring(), "\n", "\t", "requeue_on_error: ", this.settings.requeue_on_error.tostring(), "\n", "\t", "http_success: ", this.settings.http_success.join(", "), "\n", "\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n", "\t", "file_post_name: ", this.settings.file_post_name, "\n", "\t", "post_params: ", this.settings.post_params.tostring(), "\n", "\t", "file_types: ", this.settings.file_types, "\n", "\t", "file_types_description: ", this.settings.file_types_description, "\n", "\t", "file_size_limit: ", this.settings.file_size_limit, "\n", "\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n", "\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n", "\t", "debug: ", this.settings.debug.tostring(), "\n", "\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.tostring(), "\n", "\t", "button_placeholder_id: ", this.settings.button_placeholder_id.tostring(), "\n", "\t", "button_placeholder: ", (this.settings.button_placeholder ? "set" : "not set"), "\n", "\t", "button_image_url: ", this.settings.button_image_url.tostring(), "\n", "\t", "button_width: ", this.settings.button_width.tostring(), "\n", "\t", "button_height: ", this.settings.button_height.tostring(), "\n", "\t", "button_text: ", this.settings.button_text.tostring(), "\n", "\t", "button_text_style: ", this.settings.button_text_style.tostring(), "\n", "\t", "button_text_top_padding: ", this.settings.button_text_top_padding.tostring(), "\n", "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.tostring(), "\n", "\t", "button_action: ", this.settings.button_action.tostring(), "\n", "\t", "button_disabled: ", this.settings.button_disabled.tostring(), "\n", "\t", "custom_settings: ", this.settings.custom_settings.tostring(), "\n", "event handlers:\n", "\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").tostring(), "\n", "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").tostring(), "\n", "\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").tostring(), "\n", "\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").tostring(), "\n", "\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").tostring(), "\n", "\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").tostring(), "\n", "\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").tostring(), "\n", "\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").tostring(), "\n", "\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").tostring(), "\n", "\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").tostring(), "\n" ].join("") ); }; /* note: addsetting and getsetting are no longer used by swfupload but are included the maintain v2 api compatibility */ // public: (deprecated) addsetting adds a setting value. if the value given is undefined or null then the default_value is used. swfupload.prototype.addsetting = function (name, value, default_value) { if (value == undefined) { return (this.settings[name] = default_value); } else { return (this.settings[name] = value); } }; // public: (deprecated) getsetting gets a setting. returns an empty string if the setting was not found. swfupload.prototype.getsetting = function (name) { if (this.settings[name] != undefined) { return this.settings[name]; } return ""; }; // private: callflash handles function calls made to the flash element. // calls are made with a settimeout for some functions to work around // bugs in the externalinterface library. swfupload.prototype.callflash = function (functionname, argumentarray) { argumentarray = argumentarray || []; var movieelement = this.getmovieelement(); var returnvalue, returnstring; // flash's method if calling externalinterface methods (code adapted from mootools). try { returnstring = movieelement.callfunction('' __flash__argumentstoxml(argumentarray, 0) ''); returnvalue = eval(returnstring); } catch (ex) { throw "call to " functionname " failed"; } // unescape file post param values if (returnvalue != undefined && typeof returnvalue.post === "object") { returnvalue = this.unescapefilepostparams(returnvalue); } return returnvalue; }; /* ***************************** -- flash control methods -- your ui should use these to operate swfupload ***************************** */ // warning: this function does not work in flash player 10 // public: selectfile causes a file selection dialog window to appear. this // dialog only allows 1 file to be selected. swfupload.prototype.selectfile = function () { this.callflash("selectfile"); }; // warning: this function does not work in flash player 10 // public: selectfiles causes a file selection dialog window to appear/ this // dialog allows the user to select any number of files // flash bug warning: flash limits the number of selectable files based on the combined length of the file names. // if the selection name length is too long the dialog will fail in an unpredictable manner. there is no work-around // for this bug. swfupload.prototype.selectfiles = function () { this.callflash("selectfiles"); }; // public: startupload starts uploading the first file in the queue unless // the optional parameter 'fileid' specifies the id swfupload.prototype.startupload = function (fileid) { this.callflash("startupload", [fileid]); }; // public: cancelupload cancels any queued file. the fileid parameter may be the file id or index. // if you do not specify a fileid the current uploading file or first file in the queue is cancelled. // if you do not want the uploaderror event to trigger you can specify false for the triggererrorevent parameter. swfupload.prototype.cancelupload = function (fileid, triggererrorevent) { if (triggererrorevent !== false) { triggererrorevent = true; } this.callflash("cancelupload", [fileid, triggererrorevent]); }; // public: stopupload stops the current upload and requeues the file at the beginning of the queue. // if nothing is currently uploading then nothing happens. swfupload.prototype.stopupload = function () { this.callflash("stopupload"); }; /* ************************ * settings methods * these methods change the swfupload settings. * swfupload settings should not be changed directly on the settings object * since many of the settings need to be passed to flash in order to take * effect. * *********************** */ // public: getstats gets the file statistics object. swfupload.prototype.getstats = function () { return this.callflash("getstats"); }; // public: setstats changes the swfupload statistics. you shouldn't need to // change the statistics but you can. changing the statistics does not // affect swfupload accept for the successful_uploads count which is used // by the upload_limit setting to determine how many files the user may upload. swfupload.prototype.setstats = function (statsobject) { this.callflash("setstats", [statsobject]); }; // public: getfile retrieves a file object by id or index. if the file is // not found then 'null' is returned. swfupload.prototype.getfile = function (fileid) { if (typeof(fileid) === "number") { return this.callflash("getfilebyindex", [fileid]); } else { return this.callflash("getfile", [fileid]); } }; // public: addfileparam sets a name/value pair that will be posted with the // file specified by the files id. if the name already exists then the // exiting value will be overwritten. swfupload.prototype.addfileparam = function (fileid, name, value) { return this.callflash("addfileparam", [fileid, name, value]); }; // public: removefileparam removes a previously set (by addfileparam) name/value // pair from the specified file. swfupload.prototype.removefileparam = function (fileid, name) { this.callflash("removefileparam", [fileid, name]); }; // public: setuploadurl changes the upload_url setting. swfupload.prototype.setuploadurl = function (url) { this.settings.upload_url = url.tostring(); this.callflash("setuploadurl", [url]); }; // public: setpostparams changes the post_params setting swfupload.prototype.setpostparams = function (paramsobject) { this.settings.post_params = paramsobject; this.callflash("setpostparams", [paramsobject]); }; // public: addpostparam adds post name/value pair. each name can have only one value. swfupload.prototype.addpostparam = function (name, value) { this.settings.post_params[name] = value; this.callflash("setpostparams", [this.settings.post_params]); }; // public: removepostparam deletes post name/value pair. swfupload.prototype.removepostparam = function (name) { delete this.settings.post_params[name]; this.callflash("setpostparams", [this.settings.post_params]); }; // public: setfiletypes changes the file_types setting and the file_types_description setting swfupload.prototype.setfiletypes = function (types, description) { this.settings.file_types = types; this.settings.file_types_description = description; this.callflash("setfiletypes", [types, description]); }; // public: setfilesizelimit changes the file_size_limit setting swfupload.prototype.setfilesizelimit = function (filesizelimit) { this.settings.file_size_limit = filesizelimit; this.callflash("setfilesizelimit", [filesizelimit]); }; // public: setfileuploadlimit changes the file_upload_limit setting swfupload.prototype.setfileuploadlimit = function (fileuploadlimit) { this.settings.file_upload_limit = fileuploadlimit; this.callflash("setfileuploadlimit", [fileuploadlimit]); }; // public: setfilequeuelimit changes the file_queue_limit setting swfupload.prototype.setfilequeuelimit = function (filequeuelimit) { this.settings.file_queue_limit = filequeuelimit; this.callflash("setfilequeuelimit", [filequeuelimit]); }; // public: setfilepostname changes the file_post_name setting swfupload.prototype.setfilepostname = function (filepostname) { this.settings.file_post_name = filepostname; this.callflash("setfilepostname", [filepostname]); }; // public: setusequerystring changes the use_query_string setting swfupload.prototype.setusequerystring = function (usequerystring) { this.settings.use_query_string = usequerystring; this.callflash("setusequerystring", [usequerystring]); }; // public: setrequeueonerror changes the requeue_on_error setting swfupload.prototype.setrequeueonerror = function (requeueonerror) { this.settings.requeue_on_error = requeueonerror; this.callflash("setrequeueonerror", [requeueonerror]); }; // public: sethttpsuccess changes the http_success setting swfupload.prototype.sethttpsuccess = function (http_status_codes) { if (typeof http_status_codes === "string") { http_status_codes = http_status_codes.replace(" ", "").split(","); } this.settings.http_success = http_status_codes; this.callflash("sethttpsuccess", [http_status_codes]); }; // public: sethttpsuccess changes the http_success setting swfupload.prototype.setassumesuccesstimeout = function (timeout_seconds) { this.settings.assume_success_timeout = timeout_seconds; this.callflash("setassumesuccesstimeout", [timeout_seconds]); }; // public: setdebugenabled changes the debug_enabled setting swfupload.prototype.setdebugenabled = function (debugenabled) { this.settings.debug_enabled = debugenabled; this.callflash("setdebugenabled", [debugenabled]); }; // public: setbuttonimageurl loads a button image sprite swfupload.prototype.setbuttonimageurl = function (buttonimageurl) { if (buttonimageurl == undefined) { buttonimageurl = ""; } this.settings.button_image_url = buttonimageurl; this.callflash("setbuttonimageurl", [buttonimageurl]); }; // public: setbuttondimensions resizes the flash movie and button swfupload.prototype.setbuttondimensions = function (width, height) { this.settings.button_width = width; this.settings.button_height = height; var movie = this.getmovieelement(); if (movie != undefined) { movie.style.width = width "px"; movie.style.height = height "px"; } this.callflash("setbuttondimensions", [width, height]); }; // public: setbuttontext changes the text overlaid on the button swfupload.prototype.setbuttontext = function (html) { this.settings.button_text = html; this.callflash("setbuttontext", [html]); }; // public: setbuttontextpadding changes the top and left padding of the text overlay swfupload.prototype.setbuttontextpadding = function (left, top) { this.settings.button_text_top_padding = top; this.settings.button_text_left_padding = left; this.callflash("setbuttontextpadding", [left, top]); }; // public: setbuttontextstyle changes the css used to style the html/text overlaid on the button swfupload.prototype.setbuttontextstyle = function (css) { this.settings.button_text_style = css; this.callflash("setbuttontextstyle", [css]); }; // public: setbuttondisabled disables/enables the button swfupload.prototype.setbuttondisabled = function (isdisabled) { this.settings.button_disabled = isdisabled; this.callflash("setbuttondisabled", [isdisabled]); }; // public: setbuttonaction sets the action that occurs when the button is clicked swfupload.prototype.setbuttonaction = function (buttonaction) { this.settings.button_action = buttonaction; this.callflash("setbuttonaction", [buttonaction]); }; // public: setbuttoncursor changes the mouse cursor displayed when hovering over the button swfupload.prototype.setbuttoncursor = function (cursor) { this.settings.button_cursor = cursor; this.callflash("setbuttoncursor", [cursor]); }; /* ******************************* flash event interfaces these functions are used by flash to trigger the various events. all these functions a private. because the externalinterface library is buggy the event calls are added to a queue and the queue then executed by a settimeout. this ensures that events are executed in a determinate order and that the externalinterface bugs are avoided. ******************************* */ swfupload.prototype.queueevent = function (handlername, argumentarray) { // warning: don't call this.debug inside here or you'll create an infinite loop if (argumentarray == undefined) { argumentarray = []; } else if (!(argumentarray instanceof array)) { argumentarray = [argumentarray]; } var self = this; if (typeof this.settings[handlername] === "function") { // queue the event this.eventqueue.push(function () { this.settings[handlername].apply(this, argumentarray); }); // execute the next queued event settimeout(function () { self.executenextevent(); }, 0); } else if (this.settings[handlername] !== null) { throw "event handler " handlername " is unknown or is not a function"; } }; // private: causes the next event in the queue to be executed. since events are queued using a settimeout // we must queue them in order to garentee that they are executed in order. swfupload.prototype.executenextevent = function () { // warning: don't call this.debug inside here or you'll create an infinite loop var f = this.eventqueue ? this.eventqueue.shift() : null; if (typeof(f) === "function") { f.apply(this); } }; // private: unescapefileparams is part of a workaround for a flash bug where objects passed through externalinterface cannot have // properties that contain characters that are not valid for javascript identifiers. to work around this // the flash component escapes the parameter names and we must unescape again before passing them along. swfupload.prototype.unescapefilepostparams = function (file) { var reg = /[$]([0-9a-f]{4})/i; var unescapedpost = {}; var uk; if (file != undefined) { for (var k in file.post) { if (file.post.hasownproperty(k)) { uk = k; var match; while ((match = reg.exec(uk)) !== null) { uk = uk.replace(match[0], string.fromcharcode(parseint("0x" match[1], 16))); } unescapedpost[uk] = file.post[k]; } } file.post = unescapedpost; } return file; }; // private: called by flash to see if js can call in to flash (test if external interface is working) swfupload.prototype.testexternalinterface = function () { try { return this.callflash("testexternalinterface"); } catch (ex) { return false; } }; // private: this event is called by flash when it has finished loading. don't modify this. // use the swfupload_loaded_handler event setting to execute custom code when swfupload has loaded. swfupload.prototype.flashready = function () { // check that the movie element is loaded correctly with its externalinterface methods defined var movieelement = this.getmovieelement(); if (!movieelement) { this.debug("flash called back ready but the flash movie can't be found."); return; } this.cleanup(movieelement); this.queueevent("swfupload_loaded_handler"); }; // private: removes flash added fuctions to the dom node to prevent memory leaks in ie. // this function is called by flash each time the externalinterface functions are created. swfupload.prototype.cleanup = function (movieelement) { // pro-actively unhook all the flash functions try { if (this.movieelement && typeof(movieelement.callfunction) === "unknown") { // we only want to do this in ie this.debug("removing flash functions hooks (this should only run in ie and should prevent memory leaks)"); for (var key in movieelement) { try { if (typeof(movieelement[key]) === "function") { movieelement[key] = null; } } catch (ex) { } } } } catch (ex1) { } // fix flashes own cleanup code so if the swfmovie was removed from the page // it doesn't display errors. window["__flash__removecallback"] = function (instance, name) { try { if (instance) { instance[name] = null; } } catch (flashex) { } }; }; /* this is a chance to do something before the browse window opens */ swfupload.prototype.filedialogstart = function () { this.queueevent("file_dialog_start_handler"); }; /* called when a file is successfully added to the queue. */ swfupload.prototype.filequeued = function (file) { file = this.unescapefilepostparams(file); this.queueevent("file_queued_handler", file); }; /* handle errors that occur when an attempt to queue a file fails. */ swfupload.prototype.filequeueerror = function (file, errorcode, message) { file = this.unescapefilepostparams(file); this.queueevent("file_queue_error_handler", [file, errorcode, message]); }; /* called after the file dialog has closed and the selected files have been queued. you could call startupload here if you want the queued files to begin uploading immediately. */ swfupload.prototype.filedialogcomplete = function (numfilesselected, numfilesqueued, numfilesinqueue) { this.queueevent("file_dialog_complete_handler", [numfilesselected, numfilesqueued, numfilesinqueue]); }; swfupload.prototype.uploadstart = function (file) { file = this.unescapefilepostparams(file); this.queueevent("return_upload_start_handler", file); }; swfupload.prototype.returnuploadstart = function (file) { var returnvalue; if (typeof this.settings.upload_start_handler === "function") { file = this.unescapefilepostparams(file); returnvalue = this.settings.upload_start_handler.call(this, file); } else if (this.settings.upload_start_handler != undefined) { throw "upload_start_handler must be a function"; } // convert undefined to true so if nothing is returned from the upload_start_handler it is // interpretted as 'true'. if (returnvalue === undefined) { returnvalue = true; } returnvalue = !!returnvalue; this.callflash("returnuploadstart", [returnvalue]); }; swfupload.prototype.uploadprogress = function (file, bytescomplete, bytestotal) { file = this.unescapefilepostparams(file); this.queueevent("upload_progress_handler", [file, bytescomplete, bytestotal]); }; swfupload.prototype.uploaderror = function (file, errorcode, message) { file = this.unescapefilepostparams(file); this.queueevent("upload_error_handler", [file, errorcode, message]); }; swfupload.prototype.uploadsuccess = function (file, serverdata, responsereceived) { file = this.unescapefilepostparams(file); this.queueevent("upload_success_handler", [file, serverdata, responsereceived]); }; swfupload.prototype.uploadcomplete = function (file) { file = this.unescapefilepostparams(file); this.queueevent("upload_complete_handler", file); }; /* called by swfupload javascript and flash functions when debug is enabled. by default it writes messages to the internal debug console. you can override this event and have messages written where you want. */ swfupload.prototype.debug = function (message) { this.queueevent("debug_handler", message); }; /* ********************************** debug console the debug console is a self contained, in page location for debug message to be sent. the debug console adds itself to the body if necessary. the console is automatically scrolled as messages appear. if you are using your own debug handler or when you deploy to production and have debug disabled you can remove these functions to reduce the file size and complexity. ********************************** */ // private: debugmessage is the default debug_handler. if you want to print debug messages // call the debug() function. when overriding the function your own function should // check to see if the debug setting is true before outputting debug information. swfupload.prototype.debugmessage = function (message) { if (this.settings.debug) { var exceptionmessage, exceptionvalues = []; // check for an exception object and print it nicely if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") { for (var key in message) { if (message.hasownproperty(key)) { exceptionvalues.push(key ": " message[key]); } } exceptionmessage = exceptionvalues.join("\n") || ""; exceptionvalues = exceptionmessage.split("\n"); exceptionmessage = "exception: " exceptionvalues.join("\nexception: "); swfupload.console.writeline(exceptionmessage); } else { swfupload.console.writeline(message); } } }; swfupload.console = {}; swfupload.console.writeline = function (message) { var console, documentform; try { console = document.getelementbyid("swfupload_console"); if (!console) { documentform = document.createelement("form"); document.getelementsbytagname("body")[0].appendchild(documentform); console = document.createelement("textarea"); console.id = "swfupload_console"; console.style.fontfamily = "monospace"; console.setattribute("wrap", "off"); console.wrap = "off"; console.style.overflow = "auto"; console.style.width = "700px"; console.style.height = "350px"; console.style.margin = "5px"; documentform.appendchild(console); } console.value = message "\n"; console.scrolltop = console.scrollheight - console.clientheight; } catch (ex) { alert("exception: " ex.name " message: " ex.message); } }; })(); (function() { /* queue plug-in features: *adds a cancelqueue() method for cancelling the entire queue. *all queued files are uploaded when startupload() is called. *if false is returned from uploadcomplete then the queue upload is stopped. if false is not returned (strict comparison) then the queue upload is continued. *adds a queuecomplete event that is fired when all the queued files have finished uploading. set the event handler with the queue_complete_handler setting. */ if (typeof(swfupload) === "function") { swfupload.queue = {}; swfupload.prototype.initsettings = (function (oldinitsettings) { return function () { if (typeof(oldinitsettings) === "function") { oldinitsettings.call(this); } this.queuesettings = {}; this.queuesettings.queue_cancelled_flag = false; this.queuesettings.queue_upload_count = 0; this.queuesettings.user_upload_complete_handler = this.settings.upload_complete_handler; this.queuesettings.user_upload_start_handler = this.settings.upload_start_handler; this.settings.upload_complete_handler = swfupload.queue.uploadcompletehandler; this.settings.upload_start_handler = swfupload.queue.uploadstarthandler; this.settings.queue_complete_handler = this.settings.queue_complete_handler || null; }; })(swfupload.prototype.initsettings); swfupload.prototype.startupload = function (fileid) { this.queuesettings.queue_cancelled_flag = false; this.callflash("startupload", [fileid]); }; swfupload.prototype.cancelqueue = function () { this.queuesettings.queue_cancelled_flag = true; this.stopupload(); var stats = this.getstats(); while (stats.files_queued > 0) { this.cancelupload(); stats = this.getstats(); } }; swfupload.queue.uploadstarthandler = function (file) { var returnvalue; if (typeof(this.queuesettings.user_upload_start_handler) === "function") { returnvalue = this.queuesettings.user_upload_start_handler.call(this, file); } // to prevent upload a real "false" value must be returned, otherwise default to a real "true" value. returnvalue = (returnvalue === false) ? false : true; this.queuesettings.queue_cancelled_flag = !returnvalue; return returnvalue; }; swfupload.queue.uploadcompletehandler = function (file) { var user_upload_complete_handler = this.queuesettings.user_upload_complete_handler; var continueupload; if (file.filestatus === swfupload.file_status.complete) { this.queuesettings.queue_upload_count ; } if (typeof(user_upload_complete_handler) === "function") { continueupload = (user_upload_complete_handler.call(this, file) === false) ? false : true; } else if (file.filestatus === swfupload.file_status.queued) { // if the file was stopped and re-queued don't restart the upload continueupload = false; } else { continueupload = true; } if (continueupload) { var stats = this.getstats(); if (stats.files_queued > 0 && this.queuesettings.queue_cancelled_flag === false) { this.startupload(); } else if (this.queuesettings.queue_cancelled_flag === false) { this.queueevent("queue_complete_handler", [this.queuesettings.queue_upload_count]); this.queuesettings.queue_upload_count = 0; } else { this.queuesettings.queue_cancelled_flag = false; this.queuesettings.queue_upload_count = 0; } } }; } })(); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('pagebreak', function(k) { var self = this; var name = 'pagebreak'; var pagebreakhtml = k.undef(self.pagebreakhtml, '
    '); self.clicktoolbar(name, function() { var cmd = self.cmd, range = cmd.range; self.focus(); var tail = self.newlinetag == 'br' || k.webkit ? '' : ''; self.inserthtml(pagebreakhtml tail); if (tail !== '') { var p = k('#__kindeditor_tail_tag__', self.edit.doc); range.selectnodecontents(p[0]); p.removeattr('id'); cmd.select(); } }); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('plainpaste', function(k) { var self = this, name = 'plainpaste'; self.clicktoolbar(name, function() { var lang = self.lang(name '.'), html = '
    ' '
    ' lang.comment '
    ' '' '
    ', dialog = self.createdialog({ name : name, width : 450, title : self.lang(name), body : html, yesbtn : { name : self.lang('yes'), click : function(e) { var html = textarea.val(); html = k.escape(html); html = html.replace(/ {2}/g, '  '); if (self.newlinetag == 'p') { html = html.replace(/^/, '

    ').replace(/$/, '

    ').replace(/\n/g, '

    '); } else { html = html.replace(/\n/g, '
    $&'); } self.inserthtml(html).hidedialog().focus(); } } }), textarea = k('textarea', dialog.div); textarea[0].focus(); }); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('preview', function(k) { var self = this, name = 'preview', undefined; self.clicktoolbar(name, function() { var lang = self.lang(name '.'), html = '

    ' '' '
    ', dialog = self.createdialog({ name : name, width : 750, title : self.lang(name), body : html }), iframe = k('iframe', dialog.div), doc = k.iframedoc(iframe); doc.open(); doc.write(self.fullhtml()); doc.close(); k(doc.body).css('background-color', '#fff'); iframe[0].contentwindow.focus(); }); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('quickformat', function(k) { var self = this, name = 'quickformat', blockmap = k.tomap('blockquote,center,div,h1,h2,h3,h4,h5,h6,p'); function getfirstchild(knode) { var child = knode.first(); while (child && child.first()) { child = child.first(); } return child; } self.clicktoolbar(name, function() { self.focus(); var doc = self.edit.doc, range = self.cmd.range, child = k(doc.body).first(), next, nodelist = [], sublist = [], bookmark = range.createbookmark(true); while(child) { next = child.next(); var firstchild = getfirstchild(child); if (!firstchild || firstchild.name != 'img') { if (blockmap[child.name]) { child.html(child.html().replace(/^(\s| | ) /ig, '')); child.css('text-indent', '2em'); } else { sublist.push(child); } if (!next || (blockmap[next.name] || blockmap[child.name] && !blockmap[next.name])) { if (sublist.length > 0) { nodelist.push(sublist); } sublist = []; } } child = next; } k.each(nodelist, function(i, sublist) { var wrapper = k('', doc); sublist[0].before(wrapper); k.each(sublist, function(i, knode) { wrapper.append(knode); }); }); range.movetobookmark(bookmark); self.addbookmark(); }); }); /** -------------------------- abcd
    1234
    to

    abcd
    1234

    --------------------------   abcd1233

    1234

    to

    abcd1233

    1234

    -------------------------- *//******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('table', function(k) { var self = this, name = 'table', lang = self.lang(name '.'), zeroborder = 'ke-zeroborder'; // 设置颜色 function _setcolor(box, color) { color = color.touppercase(); box.css('background-color', color); box.css('color', color === '#000000' ? '#ffffff' : '#000000'); box.html(color); } // 初始化取色器 var pickerlist = []; function _initcolorpicker(dialogdiv, colorbox) { colorbox.bind('click,mousedown', function(e){ e.stoppropagation(); }); function removepicker() { k.each(pickerlist, function() { this.remove(); }); pickerlist = []; k(document).unbind('click,mousedown', removepicker); dialogdiv.unbind('click,mousedown', removepicker); } colorbox.click(function(e) { removepicker(); var box = k(this), pos = box.pos(); var picker = k.colorpicker({ x : pos.x, y : pos.y box.height(), z : 811214, selectedcolor : k(this).html(), colors : self.colortable, nocolor : self.lang('nocolor'), shadowmode : self.shadowmode, click : function(color) { _setcolor(box, color); removepicker(); } }); pickerlist.push(picker); k(document).bind('click,mousedown', removepicker); dialogdiv.bind('click,mousedown', removepicker); }); } // 取得下一行cell的index function _getcellindex(table, row, cell) { var rowspancount = 0; for (var i = 0, len = row.cells.length; i < len; i ) { if (row.cells[i] == cell) { break; } rowspancount = row.cells[i].rowspan - 1; } return cell.cellindex - rowspancount; } self.plugin.table = { //insert or modify table prop : function(isinsert) { var html = [ '
    ', //rows, cols '
    ', '', lang.rows '   ', lang.cols ' ', '
    ', //width, height '
    ', '', lang.width '   ', '   ', lang.height '   ', '', '
    ', //space, padding '
    ', '', lang.padding '   ', lang.spacing ' ', '
    ', //align '
    ', '', '', '
    ', //border '
    ', '', lang.borderwidth '   ', lang.bordercolor ' ', '
    ', //background color '
    ', '', '', '
    ', '
    ' ].join(''); var bookmark = self.cmd.range.createbookmark(); var dialog = self.createdialog({ name : name, width : 500, title : self.lang(name), body : html, beforeremove : function() { colorbox.unbind(); }, yesbtn : { name : self.lang('yes'), click : function(e) { var rows = rowsbox.val(), cols = colsbox.val(), width = widthbox.val(), height = heightbox.val(), widthtype = widthtypebox.val(), heighttype = heighttypebox.val(), padding = paddingbox.val(), spacing = spacingbox.val(), align = alignbox.val(), border = borderbox.val(), bordercolor = k(colorbox[0]).html() || '', bgcolor = k(colorbox[1]).html() || ''; if (rows == 0 || !/^\d $/.test(rows)) { alert(self.lang('invalidrows')); rowsbox[0].focus(); return; } if (cols == 0 || !/^\d $/.test(cols)) { alert(self.lang('invalidrows')); colsbox[0].focus(); return; } if (!/^\d*$/.test(width)) { alert(self.lang('invalidwidth')); widthbox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidheight')); heightbox[0].focus(); return; } if (!/^\d*$/.test(padding)) { alert(self.lang('invalidpadding')); paddingbox[0].focus(); return; } if (!/^\d*$/.test(spacing)) { alert(self.lang('invalidspacing')); spacingbox[0].focus(); return; } if (!/^\d*$/.test(border)) { alert(self.lang('invalidborder')); borderbox[0].focus(); return; } //modify table if (table) { if (width !== '') { table.width(width widthtype); } else { table.css('width', ''); } if (table[0].width !== undefined) { table.removeattr('width'); } if (height !== '') { table.height(height heighttype); } else { table.css('height', ''); } if (table[0].height !== undefined) { table.removeattr('height'); } table.css('background-color', bgcolor); if (table[0].bgcolor !== undefined) { table.removeattr('bgcolor'); } if (padding !== '') { table[0].cellpadding = padding; } else { table.removeattr('cellpadding'); } if (spacing !== '') { table[0].cellspacing = spacing; } else { table.removeattr('cellspacing'); } if (align !== '') { table[0].align = align; } else { table.removeattr('align'); } if (border !== '') { table.attr('border', border); } else { table.removeattr('border'); } if (border === '' || border === '0') { table.addclass(zeroborder); } else { table.removeclass(zeroborder); } if (bordercolor !== '') { table.attr('bordercolor', bordercolor); } else { table.removeattr('bordercolor'); } self.hidedialog().focus(); self.cmd.range.movetobookmark(bookmark); self.cmd.select(); self.addbookmark(); return; } //insert new table var style = ''; if (width !== '') { style = 'width:' width widthtype ';'; } if (height !== '') { style = 'height:' height heighttype ';'; } if (bgcolor !== '') { style = 'background-color:' bgcolor ';'; } var html = '') ''; } html = ''; } html = ''; if (!k.ie) { html = '
    '; } self.inserthtml(html); self.select().hidedialog().focus(); self.addbookmark(); } } }), div = dialog.div, rowsbox = k('[name="rows"]', div).val(3), colsbox = k('[name="cols"]', div).val(2), widthbox = k('[name="width"]', div).val(100), heightbox = k('[name="height"]', div), widthtypebox = k('[name="widthtype"]', div), heighttypebox = k('[name="heighttype"]', div), paddingbox = k('[name="padding"]', div).val(2), spacingbox = k('[name="spacing"]', div).val(0), alignbox = k('[name="align"]', div), borderbox = k('[name="border"]', div).val(1), colorbox = k('.ke-input-color', div); _initcolorpicker(div, colorbox.eq(0)); _initcolorpicker(div, colorbox.eq(1)); _setcolor(colorbox.eq(0), '#000000'); _setcolor(colorbox.eq(1), ''); // foucs and select rowsbox[0].focus(); rowsbox[0].select(); var table; if (isinsert) { return; } //get selected table node table = self.plugin.getselectedtable(); if (table) { rowsbox.val(table[0].rows.length); colsbox.val(table[0].rows.length > 0 ? table[0].rows[0].cells.length : 0); rowsbox.attr('disabled', true); colsbox.attr('disabled', true); var match, tablewidth = table[0].style.width || table[0].width, tableheight = table[0].style.height || table[0].height; if (tablewidth !== undefined && (match = /^(\d )((?:px|%)*)$/.exec(tablewidth))) { widthbox.val(match[1]); widthtypebox.val(match[2]); } else { widthbox.val(''); } if (tableheight !== undefined && (match = /^(\d )((?:px|%)*)$/.exec(tableheight))) { heightbox.val(match[1]); heighttypebox.val(match[2]); } paddingbox.val(table[0].cellpadding || ''); spacingbox.val(table[0].cellspacing || ''); alignbox.val(table[0].align || ''); borderbox.val(table[0].border === undefined ? '' : table[0].border); _setcolor(colorbox.eq(0), k.tohex(table.attr('bordercolor') || '')); _setcolor(colorbox.eq(1), k.tohex(table[0].style.backgroundcolor || table[0].bgcolor || '')); widthbox[0].focus(); widthbox[0].select(); } }, //modify cell cellprop : function() { var html = [ '
    ', //width, height '
    ', '', lang.width '   ', '   ', lang.height '   ', '', '
    ', //align '
    ', '', lang.textalign ' ', lang.verticalalign ' ', '
    ', //border '
    ', '', lang.borderwidth '   ', lang.bordercolor ' ', '
    ', //background color '
    ', '', '', '
    ', '
    ' ].join(''); var bookmark = self.cmd.range.createbookmark(); var dialog = self.createdialog({ name : name, width : 500, title : self.lang('tablecell'), body : html, beforeremove : function() { colorbox.unbind(); }, yesbtn : { name : self.lang('yes'), click : function(e) { var width = widthbox.val(), height = heightbox.val(), widthtype = widthtypebox.val(), heighttype = heighttypebox.val(), padding = paddingbox.val(), spacing = spacingbox.val(), textalign = textalignbox.val(), verticalalign = verticalalignbox.val(), border = borderbox.val(), bordercolor = k(colorbox[0]).html() || '', bgcolor = k(colorbox[1]).html() || ''; if (!/^\d*$/.test(width)) { alert(self.lang('invalidwidth')); widthbox[0].focus(); return; } if (!/^\d*$/.test(height)) { alert(self.lang('invalidheight')); heightbox[0].focus(); return; } if (!/^\d*$/.test(border)) { alert(self.lang('invalidborder')); borderbox[0].focus(); return; } cell.css({ width : width !== '' ? (width widthtype) : '', height : height !== '' ? (height heighttype) : '', 'background-color' : bgcolor, 'text-align' : textalign, 'vertical-align' : verticalalign, 'border-width' : border, 'border-style' : border !== '' ? 'solid' : '', 'border-color' : bordercolor }); self.hidedialog().focus(); self.cmd.range.movetobookmark(bookmark); self.cmd.select(); self.addbookmark(); } } }), div = dialog.div, widthbox = k('[name="width"]', div).val(100), heightbox = k('[name="height"]', div), widthtypebox = k('[name="widthtype"]', div), heighttypebox = k('[name="heighttype"]', div), paddingbox = k('[name="padding"]', div).val(2), spacingbox = k('[name="spacing"]', div).val(0), textalignbox = k('[name="textalign"]', div), verticalalignbox = k('[name="verticalalign"]', div), borderbox = k('[name="border"]', div).val(1), colorbox = k('.ke-input-color', div); _initcolorpicker(div, colorbox.eq(0)); _initcolorpicker(div, colorbox.eq(1)); _setcolor(colorbox.eq(0), '#000000'); _setcolor(colorbox.eq(1), ''); // foucs and select widthbox[0].focus(); widthbox[0].select(); // get selected cell var cell = self.plugin.getselectedcell(); var match, cellwidth = cell[0].style.width || cell[0].width || '', cellheight = cell[0].style.height || cell[0].height || ''; if ((match = /^(\d )((?:px|%)*)$/.exec(cellwidth))) { widthbox.val(match[1]); widthtypebox.val(match[2]); } else { widthbox.val(''); } if ((match = /^(\d )((?:px|%)*)$/.exec(cellheight))) { heightbox.val(match[1]); heighttypebox.val(match[2]); } textalignbox.val(cell[0].style.textalign || ''); verticalalignbox.val(cell[0].style.verticalalign || ''); var border = cell[0].style.borderwidth || ''; if (border) { border = parseint(border); } borderbox.val(border); _setcolor(colorbox.eq(0), k.tohex(cell[0].style.bordercolor || '')); _setcolor(colorbox.eq(1), k.tohex(cell[0].style.backgroundcolor || '')); widthbox[0].focus(); widthbox[0].select(); }, insert : function() { this.prop(true); }, 'delete' : function() { var table = self.plugin.getselectedtable(); self.cmd.range.setstartbefore(table[0]).collapse(true); self.cmd.select(); table.remove(); self.addbookmark(); }, colinsert : function(offset) { var table = self.plugin.getselectedtable()[0], row = self.plugin.getselectedrow()[0], cell = self.plugin.getselectedcell()[0], index = cell.cellindex offset; // 取得第一行的index index = table.rows[0].cells.length - row.cells.length; for (var i = 0, len = table.rows.length; i < len; i ) { var newrow = table.rows[i], newcell = newrow.insertcell(index); newcell.innerhtml = k.ie ? '' : '
    '; // 调整下一行的单元格index index = _getcellindex(table, newrow, newcell); } self.cmd.range.selectnodecontents(cell).collapse(true); self.cmd.select(); self.addbookmark(); }, colinsertleft : function() { this.colinsert(0); }, colinsertright : function() { this.colinsert(1); }, rowinsert : function(offset) { var table = self.plugin.getselectedtable()[0], row = self.plugin.getselectedrow()[0], cell = self.plugin.getselectedcell()[0]; var rowindex = row.rowindex; if (offset === 1) { rowindex = row.rowindex (cell.rowspan - 1) offset; } var newrow = table.insertrow(rowindex); for (var i = 0, len = row.cells.length; i < len; i ) { // 调整cell个数 if (row.cells[i].rowspan > 1) { len -= row.cells[i].rowspan - 1; } var newcell = newrow.insertcell(i); // copy colspan if (offset === 1 && row.cells[i].colspan > 1) { newcell.colspan = row.cells[i].colspan; } newcell.innerhtml = k.ie ? '' : '
    '; } // 调整rowspan for (var j = rowindex; j >= 0; j--) { var cells = table.rows[j].cells; if (cells.length > i) { for (var k = cell.cellindex; k >= 0; k--) { if (cells[k].rowspan > 1) { cells[k].rowspan = 1; } } break; } } self.cmd.range.selectnodecontents(cell).collapse(true); self.cmd.select(); self.addbookmark(); }, rowinsertabove : function() { this.rowinsert(0); }, rowinsertbelow : function() { this.rowinsert(1); }, rowmerge : function() { var table = self.plugin.getselectedtable()[0], row = self.plugin.getselectedrow()[0], cell = self.plugin.getselectedcell()[0], rowindex = row.rowindex, // 当前行的index nextrowindex = rowindex cell.rowspan, // 下一行的index nextrow = table.rows[nextrowindex]; // 下一行 // 最后一行不能合并 if (table.rows.length <= nextrowindex) { return; } var cellindex = cell.cellindex; // 下一行单元格的index if (nextrow.cells.length <= cellindex) { return; } var nextcell = nextrow.cells[cellindex]; // 下一行单元格 // 上下行的colspan不一致时不能合并 if (cell.colspan !== nextcell.colspan) { return; } cell.rowspan = nextcell.rowspan; nextrow.deletecell(cellindex); self.cmd.range.selectnodecontents(cell).collapse(true); self.cmd.select(); self.addbookmark(); }, colmerge : function() { var table = self.plugin.getselectedtable()[0], row = self.plugin.getselectedrow()[0], cell = self.plugin.getselectedcell()[0], rowindex = row.rowindex, // 当前行的index cellindex = cell.cellindex, nextcellindex = cellindex 1; // 最后一列不能合并 if (row.cells.length <= nextcellindex) { return; } var nextcell = row.cells[nextcellindex]; // 左右列的rowspan不一致时不能合并 if (cell.rowspan !== nextcell.rowspan) { return; } cell.colspan = nextcell.colspan; row.deletecell(nextcellindex); self.cmd.range.selectnodecontents(cell).collapse(true); self.cmd.select(); self.addbookmark(); }, rowsplit : function() { var table = self.plugin.getselectedtable()[0], row = self.plugin.getselectedrow()[0], cell = self.plugin.getselectedcell()[0], rowindex = row.rowindex; // 不是可分割单元格 if (cell.rowspan === 1) { return; } var cellindex = _getcellindex(table, row, cell); for (var i = 1, len = cell.rowspan; i < len; i ) { var newrow = table.rows[rowindex i], newcell = newrow.insertcell(cellindex); if (cell.colspan > 1) { newcell.colspan = cell.colspan; } newcell.innerhtml = k.ie ? '' : '
    '; // 调整下一行的单元格index cellindex = _getcellindex(table, newrow, newcell); } k(cell).removeattr('rowspan'); self.cmd.range.selectnodecontents(cell).collapse(true); self.cmd.select(); self.addbookmark(); }, colsplit : function() { var table = self.plugin.getselectedtable()[0], row = self.plugin.getselectedrow()[0], cell = self.plugin.getselectedcell()[0], cellindex = cell.cellindex; // 不是可分割单元格 if (cell.colspan === 1) { return; } for (var i = 1, len = cell.colspan; i < len; i ) { var newcell = row.insertcell(cellindex i); if (cell.rowspan > 1) { newcell.rowspan = cell.rowspan; } newcell.innerhtml = k.ie ? '' : '
    '; } k(cell).removeattr('colspan'); self.cmd.range.selectnodecontents(cell).collapse(true); self.cmd.select(); self.addbookmark(); }, coldelete : function() { var table = self.plugin.getselectedtable()[0], row = self.plugin.getselectedrow()[0], cell = self.plugin.getselectedcell()[0], index = cell.cellindex; for (var i = 0, len = table.rows.length; i < len; i ) { var newrow = table.rows[i], newcell = newrow.cells[index]; if (newcell.colspan > 1) { newcell.colspan -= 1; if (newcell.colspan === 1) { k(newcell).removeattr('colspan'); } } else { newrow.deletecell(index); } // 跳过不需要删除的行 if (newcell.rowspan > 1) { i = newcell.rowspan - 1; } } if (row.cells.length === 0) { self.cmd.range.setstartbefore(table).collapse(true); self.cmd.select(); k(table).remove(); } else { self.cmd.selection(true); } self.addbookmark(); }, rowdelete : function() { var table = self.plugin.getselectedtable()[0], row = self.plugin.getselectedrow()[0], cell = self.plugin.getselectedcell()[0], rowindex = row.rowindex; // 从下到上删除 for (var i = cell.rowspan - 1; i >= 0; i--) { table.deleterow(rowindex i); } if (table.rows.length === 0) { self.cmd.range.setstartbefore(table).collapse(true); self.cmd.select(); k(table).remove(); } else { self.cmd.selection(true); } self.addbookmark(); } }; self.clicktoolbar(name, self.plugin.table.prop); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('template', function(k) { var self = this, name = 'template', lang = self.lang(name '.'), htmlpath = self.pluginspath name '/html/'; function getfilepath(filename) { return htmlpath filename '?ver=' encodeuricomponent(k.debug ? k.time : k.version); } self.clicktoolbar(name, function() { var lang = self.lang(name '.'), arr = ['
    ', '
    ', // left start '
    ', lang. selecttemplate '
    ', // right start '
    ', ' ', '
    ', '
    ', '
    ', '', '
    '].join(''); var dialog = self.createdialog({ name : name, width : 500, title : self.lang(name), body : html, yesbtn : { name : self.lang('yes'), click : function(e) { var doc = k.iframedoc(iframe); self[checkbox[0].checked ? 'html' : 'inserthtml'](doc.body.innerhtml).hidedialog().focus(); } } }); var selectbox = k('select', dialog.div), checkbox = k('[name="replaceflag"]', dialog.div), iframe = k('iframe', dialog.div); checkbox[0].checked = true; iframe.attr('src', getfilepath(selectbox.val())); selectbox.change(function() { iframe.attr('src', getfilepath(this.value)); }); }); }); /******************************************************************************* * kindeditor - wysiwyg html editor for internet * pg电子平台网站 copyright (c) 2006-2011 kindsoft.net * * @author roddy * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ kindeditor.plugin('wordpaste', function(k) { var self = this, name = 'wordpaste'; self.clicktoolbar(name, function() { var lang = self.lang(name '.'), html = '
    ' '
    ' lang.comment '
    ' '' '
    ', dialog = self.createdialog({ name : name, width : 450, title : self.lang(name), body : html, yesbtn : { name : self.lang('yes'), click : function(e) { var str = doc.body.innerhtml; str = k.clearmsword(str, self.filtermode ? self.htmltags : k.options.htmltags); self.inserthtml(str).hidedialog().focus(); } } }), div = dialog.div, iframe = k('iframe', div), doc = k.iframedoc(iframe); if (!k.ie) { doc.designmode = 'on'; } doc.open(); doc.write('wordpaste'); doc.write(''); if (!k.ie) { doc.write('
    '); } doc.write(''); doc.close(); if (k.ie) { doc.body.contenteditable = 'true'; } iframe[0].contentwindow.focus(); }); });
    网站地图