code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/**
* 客户选择器
*/
var CustomerSelector = {
/**
* @param callback
* 回调函数
* @param isSingle
* 是否单选
*/
getView : function(callback, isSingle) {
var treeCustomer = new Ext.tree.TreePanel({
title : '客户地区',
region : 'west',
width : 180,
height : 300,
split : true,
collapsible : true,
autoScroll : true,
bbar : new Ext.Toolbar({
items : [{
xtype : 'button',
text : '展开',
iconCls : 'btn-expand',
handler : function() {
treeCustomer.expandAll();
}
}, {
xtype : 'button',
text : '收起',
iconCls : 'btn-collapse',
handler : function() {
treeCustomer.collapseAll();
}
}]
}),
loader : new Ext.tree.TreeLoader({
url : __ctxPath
+ '/system/treeRegion.do'
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : function(node) {
if (node != null) {
var Customers = Ext.getCmp('CustomerSelectorGrid');
var store = Customers.getStore();
store.proxy.conn.url = __ctxPath
+ '/customer/listCustomer.do';
if(node.leaf&&node.id>4){
store.baseParams = {
'Q_city_S_EQ' : node.text
};
}else {
if(node.id !=0){
store.baseParams = {
'Q_state_S_EQ' : node.text
};
}else{
store.baseParams = {
'Q_state_S_EQ' : null,
'Q_city_S_EQ' : null
}
}
}
store.load({
params : {
start : 0,
limit : 12
}
});
}
}
}
});
// ---------------------------------start grid
// -------------------------------- panel start
var sm = null;
if (isSingle) {
var sm = new Ext.grid.CheckboxSelectionModel({
singleSelect : true
});
} else {
sm = new Ext.grid.CheckboxSelectionModel();
}
var cm = new Ext.grid.ColumnModel({
columns : [sm, new Ext.grid.RowNumberer(), {
header : 'customerId',
dataIndex : 'customerId',
hidden : true
}, {
header : "客户号",
dataIndex : 'customerNo',
width : 60
}, {
header : '客户名称',
dataIndex : 'customerName',
width : 60
}]
});
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : __ctxPath + '/customer/listCustomer.do'
}),
reader : new Ext.data.JsonReader({
root : 'result',
totalProperty : 'totalCounts',
id : 'customerId',
fields : [{
name : 'customerId',
type : 'int'
}, 'customerNo'
,'customerName'
]
})
//remoteSort : true
});
var gridPanel = new Ext.grid.GridPanel({
id : 'CustomerSelectorGrid',
width : 400,
height : 300,
region : 'center',
title : '客户列表',
store : store,
shim : true,
trackMouseOver : true,
disableSelection : false,
loadMask : true,
cm : cm,
sm : sm,
viewConfig : {
forceFit : true,
enableRowBody : false,
showPreview : false
},
// paging bar on the bottom
bbar : new Ext.PagingToolbar({
pageSize : 25,
store : store,
displayInfo : true,
displayMsg : '当前显示从{0}至{1}, 共{2}条记录',
emptyMsg : "当前没有记录"
})
});
store.load({
params : {
start : 0,
limit : 25
}
});
// --------------------------------end panel
// --------------------------------form panel start
var formPanel = new Ext.FormPanel({
width : 400,
height : 35,
region : 'north',
frame : true,
id : 'CustomerForm',
layout : 'column',
defaults : {
xtype : 'label'
},
items : [{
text : '请输入查询条件:'
},{
text : '客户号'
},{
xtype: 'textfield',
name : 'Q_customerNo_S_LK'
},{
text : '客户名称'
}, {
xtype : 'textfield',
name : 'Q_customerName_S_LK'
}, {
xtype : 'button',
text : '查询',
iconCls : 'search',
handler : function() {
var searchPanel = Ext.getCmp('CustomerForm');
var grid = Ext.getCmp('CustomerSelectorGrid');
if (searchPanel.getForm().isValid()) {
searchPanel.getForm().submit({
waitMsg : '正在提交查询',
url : __ctxPath
+ '/customer/listCustomer.do',
success : function(formPanel, action) {
var result = Ext.util.JSON
.decode(action.response.responseText);
grid.getStore().loadData(result);
}
});
}
}
}]
});
// --------------------------------form panel end
// --------------------------------window start
var window = new Ext.Window({
title : '客户选择器',
width : 630,
height : 380,
layout : 'border',
border : false,
items : [treeCustomer, formPanel, gridPanel],
modal : true,
buttonAlign : 'center',
buttons : [{
iconCls : 'btn-ok',
text : '确定',
handler : function() {
var grid = Ext.getCmp('CustomerSelectorGrid');
var rows = grid.getSelectionModel().getSelections();
var CustomerIds = '';
var CustomerNames = '';
for (var i = 0; i < rows.length; i++) {
if (i > 0) {
CustomerIds += ',';
CustomerNames += ',';
}
CustomerIds += rows[i].data.customerId;
CustomerNames += rows[i].data.customerName;
}
if (callback != null) {
callback.call(this, CustomerIds, CustomerNames);
}
window.close();
}
}, {
text : '取消',
iconCls : 'btn-cancel',
handler : function() {
window.close();
}
}]
});
// --------------------------------window end
return window;
}
}; | JavaScript |
/**
* 商品选择器
*/
var GoodsSelector = {
/**
* @param callback
* 回调函数
* @param isSingle
* 是否单选
*/
getView : function(callback, isSingle) {
var treeGoods = new Ext.tree.TreePanel({
title : '商品显示',
region : 'west',
width : 180,
height : 300,
split : true,
collapsible : true,
autoScroll : true,
bbar : new Ext.Toolbar({
items : [{
xtype : 'button',
iconCls : 'btn-refresh',
text : '刷新',
handler : function() {
treeGoods.root.reload();
}
}, {
xtype : 'button',
text : '展开',
iconCls : 'btn-expand',
handler : function() {
treeGoods.expandAll();
}
}, {
xtype : 'button',
text : '收起',
iconCls : 'btn-collapse',
handler : function() {
treeGoods.collapseAll();
}
}]
}),
loader : new Ext.tree.TreeLoader({
url : __ctxPath
+ '/admin/treeOfficeGoodsType.do'
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : function(node) {
if (node != null) {
var goodss = Ext.getCmp('GoodsSelectorGrid');
var store = goodss.getStore();
store.proxy.conn.url = __ctxPath
+ '/admin/listOfficeGoods.do';
store.baseParams = {
'Q_officeGoodsType.typeId_L_EQ' : node.id == 0
? null
: node.id
};
store.load({
params : {
start : 0,
limit : 12
}
});
}
}
}
});
// ---------------------------------start grid
// panel--------------------------------
var sm = null;
if (isSingle) {
var sm = new Ext.grid.CheckboxSelectionModel({
singleSelect : true
});
} else {
sm = new Ext.grid.CheckboxSelectionModel();
}
var cm = new Ext.grid.ColumnModel({
columns : [sm, new Ext.grid.RowNumberer(), {
header : 'typeId',
dataIndex : 'typeId',
hidden : true
}, {
header : "商品名称",
dataIndex : 'goodsName',
width : 60
}, {
header : '库存数',
dataIndex : 'stockCounts',
width : 60,
renderer : function(value, metadata, record, rowIndex,
colIndex) {
var warnCounts = record.data.warnCounts;
var isWarning = record.data.isWarning;
if (value <= warnCounts && isWarning == '1') {
return '<a style="color:red;" title="已少于警报库存!">'
+ value + '</a>';
} else {
return value;
}
}
}]
});
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : __ctxPath + '/admin/listOfficeGoods.do'
}),
reader : new Ext.data.JsonReader({
root : 'result',
totalProperty : 'totalCounts',
id : 'goodsId',
fields : [{
name : 'goodsId',
type : 'int'
}, 'goodsName', {
name : 'stockCounts',
type : 'int'
}, {
name : 'warnCounts',
type : 'int'
},'isWarning']
}),
remoteSort : true
});
var gridPanel = new Ext.grid.GridPanel({
id : 'GoodsSelectorGrid',
width : 400,
height : 300,
region : 'center',
title : '办公用品列表',
store : store,
shim : true,
trackMouseOver : true,
disableSelection : false,
loadMask : true,
cm : cm,
sm : sm,
viewConfig : {
forceFit : true,
enableRowBody : false,
showPreview : false
},
// paging bar on the bottom
bbar : new Ext.PagingToolbar({
pageSize : 25,
store : store,
displayInfo : true,
displayMsg : '当前显示从{0}至{1}, 共{2}条记录',
emptyMsg : "当前没有记录"
})
});
store.load({
params : {
start : 0,
limit : 25
}
});
// --------------------------------end grid
// panel-------------------------------------
var formPanel = new Ext.FormPanel({
width : 400,
height : 30,
region : 'north',
frame : true,
id : 'GoodsForm',
layout : 'column',
defaults : {
xtype : 'label'
},
items : [{
text : '请输入查询条件:'
}, {
text : '商品名称'
}, {
xtype : 'textfield',
name : 'Q_goodsName_S_LK'
}, {
xtype : 'button',
text : '查询',
iconCls : 'search',
handler : function() {
var searchPanel = Ext.getCmp('GoodsForm');
var grid = Ext.getCmp('GoodsSelectorGrid');
if (searchPanel.getForm().isValid()) {
searchPanel.getForm().submit({
waitMsg : '正在提交查询',
url : __ctxPath
+ '/admin/listOfficeGoods.do',
success : function(formPanel, action) {
var result = Ext.util.JSON
.decode(action.response.responseText);
grid.getStore().loadData(result);
}
});
}
}
}]
});
var window = new Ext.Window({
title : '办公用品选择器',
width : 630,
height : 380,
layout : 'border',
border : false,
items : [treeGoods, formPanel, gridPanel],
modal : true,
buttonAlign : 'center',
buttons : [{
iconCls : 'btn-ok',
text : '确定',
handler : function() {
var grid = Ext.getCmp('GoodsSelectorGrid');
var rows = grid.getSelectionModel().getSelections();
var goodsIds = '';
var goodsNames = '';
for (var i = 0; i < rows.length; i++) {
if (i > 0) {
goodsIds += ',';
goodsNames += ',';
}
goodsIds += rows[i].data.goodsId;
goodsNames += rows[i].data.goodsName;
}
if (callback != null) {
callback.call(this, goodsIds, goodsNames);
}
window.close();
}
}, {
text : '取消',
iconCls : 'btn-cancel',
handler : function() {
window.close();
}
}]
});
return window;
}
}; | JavaScript |
/**
* 用户选择器
*/
var OnlineUserSelector = {
getView : function(callback,isSingle) {
var panel=this.initPanel(isSingle);
var window = new Ext.Window({
title : '选择在线用户',
width : 440,
height : 420,
layout:'fit',
items : [panel],
modal:true,
buttonAlign : 'center',
buttons : [{
text : '确认',
iconCls:'btn-ok',
scope:'true',
handler : function(){
var grid = Ext.getCmp('contactGrid');
var rows = grid.getSelectionModel().getSelections();
var userIds = '';
var fullnames = '';
for (var i = 0; i < rows.length; i++) {
if (i > 0) {
userIds += ',';
fullnames += ',';
}
userIds += rows[i].data.userId;
fullnames += rows[i].data.fullname;
}
if (callback != null) {
callback.call(this, userIds, fullnames);
}
window.close();
}
}, {
text : '关闭',
iconCls:'btn-cancel',
handler : function() {
window.close();
}
}]
});
return window;
},
initPanel : function(isSingle) {
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : __ctxPath + '/system/onlineAppUser.do'
}),
reader : new Ext.data.JsonReader({
root : 'result',
totalProperty : 'totalCounts',
id : 'id',
fields : [{
name : 'userId',
type : 'int'
}, 'fullname','title']
}),
remoteSort : true
});
store.setDefaultSort('id', 'desc');
store.load({
params : {
start : 0,
limit : 12
}
});
var sm=null;
if(isSingle){
var sm=new Ext.grid.CheckboxSelectionModel({singleSelect: true});
}else{
sm = new Ext.grid.CheckboxSelectionModel();
}
var cm = new Ext.grid.ColumnModel({
columns : [sm, new Ext.grid.RowNumberer(), {
header : "用户名",
dataIndex : 'fullname',
renderer:function(value,meta,record){
var title=record.data.title;
if(title=='1'){
return '<img src="'+__ctxPath+'/images/flag/man.png"/> '+value;
}else{
return '<img src="'+__ctxPath+'/images/flag/women.png"/> '+value;
}
},
width : 60
}],
defaults : {
sortable : true,
menuDisabled : true,
width : 120
},
listeners : {
hiddenchange : function(cm, colIndex, hidden) {
saveConfig(colIndex, hidden);
}
}
});
var treePanel = new Ext.tree.TreePanel({
id : 'treePanels',
title : '按部门分类 ',
iconCls:'dep-user',
loader : new Ext.tree.TreeLoader({
url : __ctxPath + '/system/listDepartment.do'
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : this.clickNode
}
});
var rolePanel = new Ext.tree.TreePanel({
id : 'rolePanel',
iconCls:'role-user',
title : '按角色分类 ',
loader : new Ext.tree.TreeLoader({
url : __ctxPath + '/system/treeAppRole.do'
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : this.clickRoleNode
}
});
var onlinePanel = new Ext.Panel({
id : 'onlinePanel',
iconCls:'online-user',
title : '所有在线人员 ',
listeners:{
'expand':this.clickOnlinePanel
}
});
var contactGrid = new Ext.grid.GridPanel({
id : 'contactGrid',
height : 345,
store : store,
shim : true,
trackMouseOver : true,
disableSelection : false,
loadMask : true,
cm : cm,
sm : sm,
viewConfig : {
forceFit : true,
enableRowBody : false,
showPreview : false
},
bbar : new Ext.PagingToolbar({
pageSize : 12,
store : store,
displayInfo : true,
displayMsg : '当前显示从{0}至{1}, 共{2}条记录',
emptyMsg : "当前没有记录"
})
});
var contactPanel = new Ext.Panel({
id : 'contactPanel',
width : 400,
height : 400,
layout : 'border',
border : false,
items : [{
region : 'west',
split : true,
collapsible : true,
width : 130,
margins : '5 0 5 5',
layout : 'accordion',
items : [treePanel, rolePanel,onlinePanel]
}, {
region : 'center',
margins : '5 0 5 5',
width : 220,
items : [contactGrid]
}]
});
return contactPanel;
},
clickNode : function(node) {
if (node != null) {
var users = Ext.getCmp('contactGrid');
var store = users.getStore();
store.proxy.conn.url = __ctxPath + '/system/onlineAppUser.do';
store.baseParams = {
depId : node.id
};
store.load({
params : {
start : 0,
limit : 12
}
});
}
},
clickRoleNode : function(node) {
if (node != null) {
var users = Ext.getCmp('contactGrid');
var store = users.getStore();
store.baseParams = {
roleId : node.id
};
store.proxy.conn.url =__ctxPath + '/system/onlineAppUser.do';
store.load({
params : {
start : 0,
limit : 12
}
});
}
},
clickOnlinePanel:function(){
var users = Ext.getCmp('contactGrid');
var store = users.getStore();
store.baseParams = {depId : null,roleId : null};
store.proxy.conn.url =__ctxPath + '/system/onlineAppUser.do';
store.load({
params : {
start : 0,
limit : 200
}
});
}
};
| JavaScript |
/**
* 用户选择器
*/
var UserSelector = {
getView : function(callback,isSingle) {
var panel=this.initPanel(isSingle);
var window = new Ext.Window({
title : '选择联系人',
width : 440,
height : 420,
layout:'fit',
items : [panel],
modal:true,
buttonAlign : 'center',
buttons : [{
text : '确认',
iconCls:'btn-ok',
scope:'true',
handler : function(){
var grid = Ext.getCmp('contactGrid');
var rows = grid.getSelectionModel().getSelections();
var userIds = '';
var fullnames = '';
for (var i = 0; i < rows.length; i++) {
if (i > 0) {
userIds += ',';
fullnames += ',';
}
userIds += rows[i].data.userId;
fullnames += rows[i].data.fullname;
}
if (callback != null) {
callback.call(this, userIds, fullnames);
}
window.close();
}
}, {
text : '关闭',
iconCls:'btn-cancel',
handler : function() {
window.close();
}
}]
});
return window;
},
initPanel : function(isSingle) {
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : __ctxPath + '/system/selectAppUser.do'
}),
reader : new Ext.data.JsonReader({
root : 'result',
totalProperty : 'totalCounts',
id : 'id',
fields : [{
name : 'userId',
type : 'int'
}, 'fullname','title']
}),
remoteSort : true
});
store.setDefaultSort('id', 'desc');
store.load({
params : {
start : 0,
limit : 12
}
});
var sm=null;
if(isSingle){
var sm=new Ext.grid.CheckboxSelectionModel({singleSelect: true});
}else{
sm = new Ext.grid.CheckboxSelectionModel();
}
var cm = new Ext.grid.ColumnModel({
columns : [sm, new Ext.grid.RowNumberer(), {
header : "用户名",
dataIndex : 'fullname',
renderer:function(value,meta,record){
var title=record.data.title;
if(title==1){
return '<img src="'+__ctxPath+'/images/flag/man.png"/> '+value;
}else{
return '<img src="'+__ctxPath+'/images/flag/women.png"/> '+value;
}
},
width : 60
}],
defaults : {
sortable : true,
menuDisabled : true,
width : 120
},
listeners : {
hiddenchange : function(cm, colIndex, hidden) {
saveConfig(colIndex, hidden);
}
}
});
var treePanel = new Ext.tree.TreePanel({
id : 'treePanels',
title : '按部门分类 ',
iconCls:'dep-user',
loader : new Ext.tree.TreeLoader({
url : __ctxPath + '/system/listDepartment.do'
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : this.clickNode
}
});
var rolePanel = new Ext.tree.TreePanel({
id : 'rolePanel',
iconCls:'role-user',
title : '按角色分类 ',
loader : new Ext.tree.TreeLoader({
url : __ctxPath + '/system/treeAppRole.do'
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : this.clickRoleNode
}
});
var onlinePanel = new Ext.Panel({
id : 'onlinePanel',
iconCls:'online-user',
title : '在线人员 ',
listeners:{
'expand':this.clickOnlinePanel
}
});
var contactGrid = new Ext.grid.GridPanel({
id : 'contactGrid',
height : 345,
store : store,
shim : true,
trackMouseOver : true,
disableSelection : false,
loadMask : true,
cm : cm,
sm : sm,
viewConfig : {
forceFit : true,
enableRowBody : false,
showPreview : false
},
bbar : new Ext.PagingToolbar({
pageSize : 12,
store : store,
displayInfo : true,
displayMsg : '当前显示从{0}至{1}, 共{2}条记录',
emptyMsg : "当前没有记录"
})
});
var contactPanel = new Ext.Panel({
id : 'contactPanel',
width : 400,
height : 400,
layout : 'border',
border : false,
items : [{
region : 'west',
split : true,
collapsible : true,
width : 120,
margins : '5 0 5 5',
layout : 'accordion',
items : [treePanel, rolePanel, onlinePanel]
}, {
region : 'center',
margins : '5 0 5 5',
width : 230,
items : [contactGrid]
}]
});
return contactPanel;
},
clickNode : function(node) {
if (node != null) {
var users = Ext.getCmp('contactGrid');
var store = users.getStore();
store.proxy.conn.url = __ctxPath + '/system/selectAppUser.do';
store.baseParams = {
depId : node.id
};
store.load({
params : {
start : 0,
limit : 12
}
});
}
},
clickRoleNode : function(node) {
if (node != null) {
var users = Ext.getCmp('contactGrid');
var store = users.getStore();
store.baseParams = {
roleId : node.id
};
store.proxy.conn.url =__ctxPath + '/system/findAppUser.do';
store.load({
params : {
start : 0,
limit : 12
}
});
}
},
clickOnlinePanel:function(){
var users = Ext.getCmp('contactGrid');
var store = users.getStore();
store.proxy.conn.url =__ctxPath + '/system/onlineAppUser.do';
store.load({
params : {
start : 0,
limit : 200
}
});
}
};
| JavaScript |
Ext.ns('PublicDocumentView');
var PublicDocumentView = function() {
};
PublicDocumentView.prototype.getView=function(){
return new Ext.Panel({
id:'PublicDocumentView',
title:'公共文档列表',
autoScroll : true,
region:'center',
anchor:'100%',
items:[new Ext.FormPanel({
height : 35,
frame : true,
id : 'PublicDocumentSearchForm',
layout : 'column',
defaults : {
xtype : 'label'
},
items : [{
text : '文档名称'
}, {
xtype : 'textfield',
name : 'document.docName',
width:90
}, {
text : '创建时间 从'
}, {
xtype : 'datefield',
format:'Y-m-d',
name : 'from'
},{
text : '至'
},{
xtype : 'datefield',
format:'Y-m-d',
name : 'to'
},{
xtype : 'button',
text : '查询',
iconCls : 'btn-search',
handler : function() {
var searchPanel = Ext.getCmp('PublicDocumentSearchForm');
var grid = Ext.getCmp('PublicDocumentGrid');
if (searchPanel.getForm().isValid()) {
searchPanel.getForm().submit({
waitMsg : '正在提交查询',
url : __ctxPath
+ '/document/publicListDocument.do',
params:{folderId:DocumentView.folderId},
success : function(formPanel, action) {
var result = Ext.util.JSON
.decode(action.response.responseText);
grid.getStore().loadData(result);
}
});
}
}
},{
xtype:'button',
text:'重置',
iconCls:'btn-reset',
hander:function(){
var searchPanel = Ext.getCmp('PublicDocumentSearchForm');
searchPanel.getForm().reset();
}
}]
}),this.setup()]
});
}
PublicDocumentView.prototype.setFolderId=function(folderId){
this.folderId=folderId;
PublicDocumentView.folderId=folderId;
};
PublicDocumentView.prototype.getFolderId=function(){
return this.folderId;
};
PublicDocumentView.prototype.setup=function(){
return this.grid();
}
PublicDocumentView.prototype.grid=function(){
var sm = new Ext.grid.CheckboxSelectionModel();
var cm = new Ext.grid.ColumnModel({
columns : [sm, new Ext.grid.RowNumberer(), {
header : 'docId',
dataIndex : 'docId',
hidden : true
}, {
header : '文档名称',
dataIndex : 'docName',
width:120
}, {
header : '创建 人',
dataIndex : 'creator',
width:120
}, {
header : '修改时间',
dataIndex : 'createtime'
},{
header : '文件夹',
dataIndex : 'forlderName'
},{
header : '附件',
dataIndex : 'haveAttach',
renderer:function(value,metadata,record){
if(value=='' || value=='0'){
return '无附件';
}else{
var attachFiles=record.data.attachFiles;
var str='';
for(var i=0;i<attachFiles.length;i++){
str+='<a href="#" onclick="FileAttachDetail.show('+attachFiles[i].fileId+');" class="attachment">'+attachFiles[i].fileName+'</a>';
str+=' ';
}
return str;
}
}
}
, {
header : '管理',
dataIndex : 'docId',
width : 50,
renderer : function(value, metadata, record, rowIndex,
colIndex) {
var editId = record.data.docId;
var str = '<button title="查看" value="" class="btn-readdocument" onclick="PublicDocumentView.detail('
+ editId + ')"> </button>';
return str;
}
}
],
defaults : {
sortable : true,
menuDisabled : false,
width : 100
}
});
var store = this.store();
store.load({
params : {
start : 0,
limit : 25
}
});
var grid=new Ext.grid.GridPanel({
id:'PublicDocumentGrid',
store : store,
trackMouseOver : true,
disableSelection : false,
loadMask : true,
autoHeight:true,
maxHeight:600,
cm : cm,
sm : sm,
viewConfig : {
forceFit : true,
enableRowBody : false,
showPreview : false
},
bbar : new Ext.PagingToolbar({
pageSize : 25,
store : store,
displayInfo : true,
displayMsg : '当前显示从{0}至{1}, 共{2}条记录',
emptyMsg : "当前没有记录"
})
});
grid.addListener('rowdblclick', function(grid, rowindex, e) {
grid.getSelectionModel().each(function(rec) {
PublicDocumentView.detail(rec.data.docId);
});
});
return grid;
}
PublicDocumentView.prototype.store = function() {
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : __ctxPath + '/document/publicListDocument.do'
}),
reader : new Ext.data.JsonReader({
root : 'result',
totalProperty : 'totalCounts',
id : 'id',
fields : [{
name : 'docId',
type : 'int'
},{
name:'forlderName',
mapping:'docFolder.folderName'
},{
name:'creator',
mapping:'appUser.fullname'
},'docName', 'content', 'createtime','haveAttach','attachFiles','isShared'
]
}),
remoteSort : true
});
store.setDefaultSort('docId', 'desc');
return store;
};
PublicDocumentView.detail=function(id){
Ext.Ajax.request({
url : __ctxPath + '/document/rightDocument.do',
params:{docId:id},
method : 'POST',
success : function(response, options) {
var result = Ext.util.JSON
.decode(response.responseText);
var rightM = result.rightM;
var rightD=result.rightD;
var docName=result.docName;
if(id!=null){
new PublicDocumentDetailWin(id,docName);
}
if(rightM==1){
var publicDocumentTopBar=Ext.getCmp('PublicDocumentTopBar');
publicDocumentTopBar.add(new Ext.Button({
iconCls : 'btn-add',
text : '修改公共文档 ',
xtype : 'button',
handler : function() {
var tabs = Ext.getCmp('centerTabPanel');
var newPublicDocumentForm=Ext.getCmp('NewPublicDocumentForm');
var publicDocumentDetailWin=Ext.getCmp('PulicDocumentDetailWin');
publicDocumentDetailWin.close();
if(newPublicDocumentForm==null){
newPublicDocumentForm=new NewPublicDocumentForm(id,docName+'-文档信息');
tabs.add(newPublicDocumentForm);
tabs.activate(newPublicDocumentForm);
}else{
tabs.remove('NewPublicDocumentForm');
newPublicDocumentForm=new NewPublicDocumentForm(id,docName+'-文档信息')
tabs.add(newPublicDocumentForm);
tabs.activate(newPublicDocumentForm);
}
}
}));
publicDocumentTopBar.doLayout(true);
}
if(rightD==1){
var publicDocumentTopBar=Ext.getCmp('PublicDocumentTopBar');
publicDocumentTopBar.add(new Ext.Button({
iconCls : 'btn-del',
text : '删除公共文档',
xtype : 'button',
handler : function() {
Ext.Msg.confirm('信息确认', '您确认要删除该文档吗?', function(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url : __ctxPath
+ '/document/multiDelDocument.do',
params : {
ids : id
},
method : 'post',
success : function() {
var publicDocumentDetailWin=Ext.getCmp('PulicDocumentDetailWin');
publicDocumentDetailWin.close();
Ext.Msg.alert("信息提示", "成功删除所选记录!");
var grid=Ext.getCmp('PublicDocumentGrid');
grid.getStore().reload({
params : {
start : 0,
limit : 25
}
});
}
});
}
});
}
}));
publicDocumentTopBar.doLayout(true);
}
},
failure : function(response, options) {
},
scope : this
});
}
| JavaScript |
var PublicDocumentDetailWin=function(docId,docName){
this.docId = docId;
this.docName=docName;
var pa=this.setup();
var window=new Ext.Window({
id : 'PulicDocumentDetailWin',
title : ''+docName,
autoHeight :true,
width:510,
modal : true,
autoScroll:true,
layout : 'anchor',
plain : true,
bodyStyle : 'padding:5px;',
buttonAlign : 'center',
items : [this.setup()],
buttons : [{
text : '关闭',
handler : function() {
window.close();
}
}]
});
window.show();
}
PublicDocumentDetailWin.prototype.setup=function(){
var topbar=this.topbar();
var panel=new Ext.Panel({
id:'PublicDocumentDetailWinPanel',
modal : true,
tbar:topbar,
autoScroll:true,
aotuHeight:true,
width:479,
autoLoad:{url:__ctxPath+'/document/publicDetailDocument.do?docId='+this.docId}
});
return panel;
}
PublicDocumentDetailWin.prototype.topbar=function() {
var toolbar = new Ext.Toolbar({
id : 'PublicDocumentTopBar',
height : 25,
bodyStyle:'text-align:center',
items : []
});
return toolbar;
}; | JavaScript |
Ext.ns('FindPublicDocumentView');
var FindPublicDocumentView=function(){
var selectedNode;
var publicDocumentView=new PublicDocumentView();
var treePanel = new Ext.tree.TreePanel({
region : 'west',
id : 'leftPublicDocumentPanel',
title : '公共文档目录',
collapsible : true,
split : true,
width : 200,
height : 800,
tbar:new Ext.Toolbar({items:[{
xtype:'button',
iconCls:'btn-refresh',
text:'刷新',
handler:function(){
treePanel.root.reload();
}
},
{
xtype:'button',
text:'展开',
iconCls:'btn-expand',
handler:function(){
treePanel.expandAll();
}
},
{
xtype:'button',
text:'收起',
iconCls:'btn-collapse',
handler:function(){
treePanel.collapseAll();
}
}
]}),
loader : new Ext.tree.TreeLoader({
url : __ctxPath + '/document/treeDocFolder.do'
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : function(node){
if (node != null) {
publicDocumentView.setFolderId(node.id);
var docView=Ext.getCmp('PublicDocumentView');
if(node.id==0){
docView.setTitle('所有文档');
}else{
docView.setTitle('['+node.text+']文档列表');
}
var documentGrid = Ext.getCmp('PublicDocumentGrid');
var store=documentGrid.getStore();
store.url=__ctxPath+'/document/publicListDocument.do';
store.baseParams={folderId:node.id};
store.params={start:0,limit:25};
store.reload({params:{start:0,limit:25}});
}
}
}
});
var panel = new Ext.Panel({
id:'FindPublicDocumentView',
title : '公共文档',
iconCls:'menu-find-doc',
layout : 'border',
height : 800,
items : [treePanel,publicDocumentView.getView()]
});
return panel;
};
| JavaScript |
var DocumentForm = function(docId) {
this.docId = docId;
var fp = this.setup();
var window = new Ext.Window({
id : 'DocumentFormWin',
title : '文档详细信息',
width : 680,
height : 500,
modal : true,
minWidth : 300,
minHeight : 200,
layout : 'anchor',
plain : true,
bodyStyle : 'padding:5px;',
buttonAlign : 'center',
items : [this.setup()],
buttons : [{
text : '保存',
iconCls:'btn-save',
handler : function() {
var fp = Ext.getCmp('DocumentForm');
if (fp.getForm().isValid()) {
fp.getForm().submit({
method : 'post',
waitMsg : '正在提交数据...',
success : function(fp, action) {
Ext.Msg.alert('操作信息', '成功信息保存!');
Ext.getCmp('DocumentGrid').getStore().reload();
window.close();
},
failure : function(fp, action) {
Ext.MessageBox.show({
title : '操作信息',
msg : '信息保存出错,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
window.close();
}
});
}
}
}, {
text : '取消',
iconCls:'btn-cancel',
handler : function() {
window.close();
}
}]
});
window.show();
};
DocumentForm.prototype.setup = function() {
var _url = __ctxPath+'/document/listDocFolder.do?method=1';//不把根目录显示出来
var folderSelector = new TreeSelector('folderSelect',_url,'文件夹*','folderId');
var formPanel = new Ext.FormPanel({
url : __ctxPath + '/document/saveDocument.do',
id : 'DocumentForm',
width : 600,
frame : true,
formId : 'DocumentFormId',
items : [
{
name: 'folderId',
id:'folderId',
xtype:'hidden'
},
{
name : 'document.docId',
id : 'docId',
xtype : 'hidden',
value : this.docId == null ? '' : this.docId
},folderSelector, {
xtype : 'textfield',
fieldLabel : '文档名称',
name : 'document.docName',
id : 'docName',
anchor : '98%'
}, {
height : 280,
anchor : '98%',
xtype : 'htmleditor',
fieldLabel : '内容',
name : 'document.content',
id : 'content'
}, {
layout : 'column',
items : [{
columnWidth : .7,
layout : 'form',
items : [
{
fieldLabel : '附件',
xtype : 'panel',
id:'filePanel',
frame:true,
height:80,
autoScroll:true,
html:''
}]
}, {
columnWidth : .3,
items : [{
xtype : 'button',
text : '添加附件',
handler : function() {
var dialog=App.createUploadDialog({
file_cat:'document',
callback:function(data){
var fileIds=Ext.getCmp("fileIds");
var filePanel=Ext.getCmp('filePanel');
for(var i=0;i<data.length;i++){
if(fileIds.getValue()!=''){
fileIds.setValue(fileIds.getValue()+',');
}
fileIds.setValue(fileIds.getValue()+data[i].fileId);
Ext.DomHelper.append(filePanel.body,'<span><a href="#" onclick="FileAttachDetail.show('+data[i].fileId+')">'+data[i].filename+'</a> <img class="img-delete" src="'+__ctxPath+'/images/system/delete.gif" onclick="removeFile(this,'+data[i].fileId+')"/> | </span>');
}
}
});
dialog.show(this);
}
}, {
xtype : 'button',
text : '清除附件',
handler : function() {
var fileAttaches=Ext.getCmp("fileAttaches");
var filePanel=Ext.getCmp('filePanel');
filePanel.body.update('');
fileAttaches.setValue('');
}
},{
xtype:'hidden',
id:'fileIds',
name:'fileIds'
}]
}]
}]
});
if (this.docId != null && this.docId != 'undefined') {
formPanel.getForm().load({
deferredRender : false,
url : __ctxPath + '/document/getDocument.do?docId='
+ this.docId,
waitMsg : '正在载入数据...',
success : function(form, action) {
var folderId=action.result.data.docFolder.folderId;
var folderName=action.result.data.docFolder.folderName;
Ext.getCmp('folderId').setValue(folderId);
Ext.getCmp('folderSelect').setValue(folderName);
var af=action.result.data.attachFiles;
var filePanel=Ext.getCmp('filePanel');
var fileIds=Ext.getCmp("fileIds");
for(var i=0;i<af.length;i++){
if(fileIds.getValue()!=''){
fileIds.setValue(fileIds.getValue()+',');
}
fileIds.setValue(fileIds.getValue()+af[i].fileId);
Ext.DomHelper.append(filePanel.body,'<span><a href="#" onclick="FileAttachDetail.show('+af[i].fileId+')">'+af[i].fileName+'</a><img class="img-delete" src="'+__ctxPath+'/images/system/delete.gif" onclick="removeFile(this,'+af[i].fileId+')"/> | </span>');
}
},
failure : function(form, action) {
Ext.MessageBox.show({
title : '操作信息',
msg : '载入信息失败,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
}
});
}
return formPanel;
};
function removeFile(obj,fileId){
var fileIds=Ext.getCmp("fileIds");
var value=fileIds.getValue();
if(value.indexOf(',')<0){//仅有一个附件
fileIds.setValue('');
}else{
value=value.replace(',' + fileId,'').replace(fileId+',','');
fileIds.setValue(value);
}
var el=Ext.get(obj.parentNode);
el.remove();
};
| JavaScript |
var DocFolderForm = function(folderId,parentId,isShared) {
this.folderId = folderId;
this.parentId=parentId;
this.isShared=isShared;
var fp = this.setup();
var window = new Ext.Window({
id : 'DocFolderFormWin',
title : '目录详细信息',
width : 400,
height : 150,
modal : true,
minWidth : 300,
minHeight : 200,
layout : 'anchor',
plain : true,
bodyStyle : 'padding:5px;',
buttonAlign : 'center',
items : [this.setup()],
buttons : [{
text : '保存',
handler : function() {
var fp = Ext.getCmp('DocFolderForm');
if (fp.getForm().isValid()) {
fp.getForm().submit({
method : 'post',
waitMsg : '正在提交数据...',
success : function(fp, action) {
Ext.Msg.alert('操作信息', '成功信息保存!');
//左树重新reload
var leftFolderPanel=Ext.getCmp("leftFolderPanel");
var leftPublicFolder=Ext.getCmp('leftDocFolderSharedPanel');
var grid=Ext.getCmp('DocFolderGrid');
if(grid!=null){
grid.getStore().reload();
}
if(leftFolderPanel!=null){
leftFolderPanel.root.reload();
}
if(leftPublicFolder!=null){
leftPublicFolder.root.reload();
}
window.close();
},
failure : function(fp, action) {
Ext.MessageBox.show({
title : '操作信息',
msg : '信息保存出错,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
window.close();
}
});
}
}
}, {
text : '取消',
handler : function() {
window.close();
}
}]
});
window.show();
};
DocFolderForm.prototype.setup = function() {
var formPanel = new Ext.FormPanel({
url : __ctxPath + '/document/saveDocFolder.do',
layout : 'form',
id : 'DocFolderForm',
frame : true,
defaults : {
widht : 400,
anchor : '100%,100%'
},
formId : 'DocFolderFormId',
defaultType : 'textfield',
items : [{
name : 'docFolder.folderId',
id : 'folderId',
xtype : 'hidden',
value : this.folderId == null ? '' : this.folderId
}, {
fieldLabel : '目录名称',
name : 'docFolder.folderName',
id : 'folderName'
},{
xtype:'hidden',
name : 'docFolder.parentId',
id : 'parentId',
value:this.parentId
},{
xtype:'hidden',
name : 'docFolder.isShared',
id : 'isShared',
value :this.isShared
}
]
});
if (this.folderId != null && this.folderId != 'undefined') {
formPanel.getForm().load({
deferredRender : false,
url : __ctxPath + '/document/getDocFolder.do?folderId='
+ this.folderId,
waitMsg : '正在载入数据...',
success : function(form, action) {
// Ext.Msg.alert('编辑', '载入成功!');
},
failure : function(form, action) {
// Ext.Msg.alert('编辑', '载入失败');
}
});
}
return formPanel;
};
| JavaScript |
var PersonalDocFolderSelector = {
getView : function(callback) {
var nodeValue;
var clickNode = function(node) {
if (node != null) {
if(!node.disabled){
nodeValue=node;
return nodeValue;
}
}
};
var treePanel = new Ext.tree.TreePanel({
id : 'docFolderTreePanel',
title : '目录列表 ',
loader : new Ext.tree.TreeLoader({
url : __ctxPath + '/document/listDocFolder.do'
// url:this.url
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : clickNode
}
});
var window = new Ext.Window({
title : '请选择目录',
width : 440,
height : 420,
layout:'fit',
items : [treePanel],
modal:true,
buttonAlign : 'center',
buttons : [{
text : '确认',
iconCls:'btn-ok',
scope:'true',
handler : function(){
if(nodeValue!=null){
if (callback != null) {
callback.call(this, nodeValue.id, nodeValue.text);
}
window.close();
}else{
Ext.Msg.alert('提示','你无权插文档入该目录!');
}
}
}, {
text : '关闭',
iconCls:'btn-cancel',
handler : function() {
window.close();
}
}]
});
return window;
}
};
| JavaScript |
Ext.ns('DocPrivilegeView');
/**
* ������������������������������������������������������������列表
*/
var DocPrivilegeView = function(){
}
DocPrivilegeView.prototype.getView=function(){
return new Ext.Panel({
id:'DocPrivilegeView',
title:'权限列表',
region:'center',
autoScroll:true,
items:[
new Ext.FormPanel({
height:35,
frame:true,
id:'DocPrivilegeSearchForm',
layout:'column',
defaults:{xtype:'label'},
items:[{text:'请输入查询条件:'}
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_folderId_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_docId_S_LK'
// }
// ,{
// text : '权限'
// }, {
// xtype : 'textfield',
// name : 'Q_rights_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_udrId_S_LK'
// }
,{
text : '名称'
}, {
xtype : 'textfield',
name : 'docPrivilege.udrName'
}
,{
text : '属性'
}, {
xtype : 'combo',
anchor:'95%',
hiddenName : 'docPrivilege.flag',
id:'title',
mode : 'local',
editable : false,
triggerAction : 'all',
store : [['1','用户'],['2','部门'],['3','角色']]
},{
xtype:'button',
text:'查询',
iconCls:'search',
handler:function(){
var searchPanel=Ext.getCmp('DocPrivilegeSearchForm');
var grid=Ext.getCmp('DocPrivilegeGrid');
if(searchPanel.getForm().isValid()){
searchPanel.getForm().submit({
waitMsg:'正在提交查询',
url:__ctxPath+'/document/listDocPrivilege.do',
method:'post',
params:{start:0,limit:25},
success:function(formPanel,action){
var result=Ext.util.JSON.decode(action.response.responseText);
grid.getStore().loadData(result);
}
});
}
}
}
]
}),
this.setup()
]
});
};
/**
* 建立视图
*/
DocPrivilegeView.prototype.setup = function() {
return this.grid();
};
DocPrivilegeView.prototype.setFolderId=function(folderId){
this.folderId=folderId;
DocPrivilegeView.folderId=folderId;
};
DocPrivilegeView.prototype.getFolderId=function(){
return this.folderId;
};
/**
* 建立DataGrid
*/
DocPrivilegeView.prototype.grid = function() {
var sm = new Ext.grid.CheckboxSelectionModel();
var onMouseDown=function(e,t){
if (t.className && t.className.indexOf('x-grid3-cc-' + this.id) != -1) {
e.stopEvent();
var index = this.grid.getView().findRowIndex(t);
var cindex = this.grid.getView().findCellIndex(t);
var record = this.grid.store.getAt(index);
var field = this.grid.colModel.getDataIndex(cindex);
var e = {
grid : this.grid,
record : record,
field : field,
originalValue : record.data[this.dataIndex],
value : !record.data[this.dataIndex],
row : index,
column : cindex,
cancel : false
};
if (this.grid.fireEvent("validateedit", e) !== false && !e.cancel) {
delete e.cancel;
record.set(this.dataIndex, !record.data[this.dataIndex]);
this.grid.fireEvent("afteredit", e);
}
}
}
var checkColumnR = new Ext.grid.CheckColumn({
id:'read',
header: '可读',
dataIndex: 'rightR',
width: 55,
onMouseDown:onMouseDown
});
var checkColumnM = new Ext.grid.CheckColumn({
header: '可修改',
dataIndex: 'rightU',
width: 55,
onMouseDown:onMouseDown
});
var checkColumnD = new Ext.grid.CheckColumn({
header: '可删除',
dataIndex: 'rightD',
width: 55,
onMouseDown:onMouseDown
});
var cm = new Ext.grid.ColumnModel({
columns : [sm, new Ext.grid.RowNumberer(), {
header : 'privilegeId',
dataIndex : 'privilegeId',
hidden : true
}
,{
header : '名称',
dataIndex : 'udrName'
}
,{
header : '属性',
dataIndex : 'flag',
renderer:function(value,metadata,record){
if(value==1){
return '<img title="员工" src="'+ __ctxPath +'/images/flag/user.jpg"/>';
}
if(value==2){
return '<img title="部门" src="'+ __ctxPath +'/images/flag/department.jpg"/>';
}
if(value==3){
return '<img title="角色" src="'+ __ctxPath +'/images/flag/role.jpg"/>';
}
}
},checkColumnR,checkColumnM,checkColumnD,
{
header : '管理',
dataIndex : 'privilegeId',
width : 50,
renderer : function(value, metadata, record, rowIndex,
colIndex) {
var editId = record.data.privilegeId;
var str = '<button title="删除" value=" " class="btn-del" onclick="DocPrivilegeView.remove('
+ editId + ')"> </button>';
return str;
}
}],
defaults : {
sortable : true,
menuDisabled : false,
width : 100
}
});
var store = this.store();
store.load({
params : {
start : 0,
limit : 25
}
});
var grid = new Ext.grid.EditorGridPanel({
id : 'DocPrivilegeGrid',
tbar : this.topbar(this),
trackMouseOver:true,
store : store,
trackMouseOver : true,
disableSelection : false,
loadMask : true,
autoHeight:true,
cm : cm,
sm : sm,
plugins:[checkColumnR,checkColumnM,checkColumnD],
clicksToEdit: 1,
viewConfig : {
forceFit : true,
enableRowBody : false,
showPreview : false
},
bbar : new Ext.PagingToolbar({
pageSize : 25,
store : store,
displayInfo : true,
displayMsg : '当前显示从{0}至{1}, 共{2}条记录',
emptyMsg : "当前没有记录"
})
});
grid.addListener('afteredit',function(e){
Ext.Ajax.request({
url:__ctxPath + '/document/changeDocPrivilege.do',
params:{
field:e.field,
fieldValue:e.value,
privilegeId:e.record.data.privilegeId
},
success:function(){},
failure:function(){
Ext.Msg.show({
title : '错误提示',
msg : '修改数据发生错误,操作将被回滚!',
fn : function() {
e.record.set(e.field, e.originalValue);
},
buttons : Ext.Msg.OK,
icon : Ext.Msg.ERROR
});
}
});
});
// grid.addListener('rowdblclick', function(grid, rowindex, e) {
// grid.getSelectionModel().each(function(rec) {
// DocPrivilegeView.edit(rec.data.privilegeId);
// });
// });
return grid;
};
/**
* 初始化数据
*/
DocPrivilegeView.prototype.store = function() {
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : __ctxPath + '/document/listDocPrivilege.do'
}),
reader : new Ext.data.JsonReader({
root : 'result',
totalProperty : 'totalCounts',
id : 'id',
fields : [{
name : 'privilegeId',
type : 'int'
}
// ,'folderId'
// ,'docId'
,'rightR'
,'rightU'
,'rightD'
,'udrId'
,'udrName'
,'flag'
]
}),
remoteSort : true
});
store.setDefaultSort('privilegeId', 'desc');
return store;
};
/**
* 建立操作的Toolbar
*/
DocPrivilegeView.prototype.topbar = function(docFolderObject) {
var toolbar = new Ext.Toolbar({
id : 'DocPrivilegeFootBar',
height : 30,
bodyStyle:'text-align:left',
items : [
{
iconCls : 'btn-add',
text : '添加文件夹权限',
xtype : 'button',
handler : function() {
var forlderId=docFolderObject.getFolderId();
if(forlderId!=null&&forlderId>0){
new DocFolderSharedForm(null,forlderId);
}else{
Ext.Msg.alert('提示','请选择文件夹!');
}
}
}, {
iconCls : 'btn-del',
text : '删除文件夹权限',
xtype : 'button',
handler : function() {
var grid=Ext.getCmp("DocPrivilegeGrid");
var selectRecords=grid.getSelectionModel().getSelections();
if(selectRecords.length==0){
Ext.Msg.alert("信息","请选择要删除的记录!");
return;
}
var ids=Array();
for(var i=0;i<selectRecords.length;i++){
ids.push(selectRecords[i].data.privilegeId);
}
DocPrivilegeView.remove(ids);
}
}
]
});
return toolbar;
};
/**
* 删除单个记录
*/
DocPrivilegeView.remove=function(id){
var grid=Ext.getCmp("DocPrivilegeGrid");
Ext.Msg.confirm('信息确认','您确认要删除该记录吗?',function(btn){
if(btn=='yes'){
Ext.Ajax.request({
url:__ctxPath+'/document/multiDelDocPrivilege.do',
params:{
ids:id
},
method:'post',
success:function(){
Ext.Msg.alert("信息提示","成功删除所选记录!");
grid.getStore().reload({params:{
start : 0,
limit : 25
}});
}
});
}
});
};
/**
*
*/
DocPrivilegeView.edit=function(id){
new DocPrivilegeForm(id);
}
| JavaScript |
Ext.ns('DocFolderView');
/**
* TODO: add class/table comments列表
*/
var DocFolderView = function() {
return new Ext.Panel({
id:'DocFolderView',
title:'公共文件夹列表',
autoScroll:true,
items:[
new Ext.FormPanel({
height:35,
frame:true,
id:'DocFolderSearchForm',
layout:'column',
defaults:{xtype:'label'},
items:[{text:'请输入查询条件:'}
,{
text : '主键'
}, {
xtype : 'textfield',
name : 'Q_userId_S_LK'
}
,{
text : '目录名称'
}, {
xtype : 'textfield',
name : 'Q_folderName_S_LK'
}
,{
text : '父目录'
}, {
xtype : 'textfield',
name : 'Q_parentId_S_LK'
}
,{
text : ''
}, {
xtype : 'textfield',
name : 'Q_isShared_S_LK'
}
,{
xtype:'button',
text:'查询',
iconCls:'search',
handler:function(){
var searchPanel=Ext.getCmp('DocFolderSearchForm');
var grid=Ext.getCmp('DocFolderGrid');
if(searchPanel.getForm().isValid()){
searchPanel.getForm().submit({
waitMsg:'正在提交查询',
url:__ctxPath+'/document/shareDocFolder.do',
success:function(formPanel,action){
var result=Ext.util.JSON.decode(action.response.responseText);
grid.getStore().loadData(result);
}
});
}
}
}
]
}),
this.setup()
]
});
};
/**
* 建立视图
*/
DocFolderView.prototype.setup = function() {
return this.grid();
};
/**
* 建立DataGrid
*/
DocFolderView.prototype.grid = function() {
var sm = new Ext.grid.CheckboxSelectionModel();
var cm = new Ext.grid.ColumnModel({
columns : [sm, new Ext.grid.RowNumberer(), {
header : 'folderId',
dataIndex : 'folderId',
hidden : true
},
{
header : '文件夹名称',
dataIndex : 'folderName'
}
,{
header : '父目录',
dataIndex : 'parentId'
}
,{
header : '管理',
dataIndex : 'folderId',
width : 50,
renderer : function(value, metadata, record, rowIndex,
colIndex) {
var editId = record.data.folderId;
var str = '<button title="删除" value=" " class="btn-del" onclick="DocFolderView.remove('
+ editId + ')"> </button>';
str += ' <button title="编辑" value=" " class="btn-edit" onclick="DocFolderView.edit('
+ editId + ')"> </button>';
str+= ' <button title="授权" value=" " class="btn-shared" onclick="DocFolderView.right('+editId+')"> </button>';
return str;
}
}],
defaults : {
sortable : true,
menuDisabled : false,
width : 100
}
});
var store = this.store();
store.load({
params : {
start : 0,
limit : 25
}
});
var grid = new Ext.grid.GridPanel({
id : 'DocFolderGrid',
tbar : this.topbar(),
store : store,
trackMouseOver : true,
disableSelection : false,
loadMask : true,
autoHeight:true,
cm : cm,
sm : sm,
viewConfig : {
forceFit : true,
enableRowBody : false,
showPreview : false
},
bbar : new Ext.PagingToolbar({
pageSize : 25,
store : store,
displayInfo : true,
displayMsg : '当前显示从{0}至{1}, 共{2}条记录',
emptyMsg : "当前没有记录"
})
});
grid.addListener('rowdblclick', function(grid, rowindex, e) {
grid.getSelectionModel().each(function(rec) {
DocFolderView.edit(rec.data.folderId);
});
});
return grid;
};
/**
* 初始化数据
*/
DocFolderView.prototype.store = function() {
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : __ctxPath + '/document/shareDocFolder.do'
}),
reader : new Ext.data.JsonReader({
root : 'result',
totalProperty : 'totalCounts',
id : 'id',
fields : [{
name : 'folderId',
type : 'int'
}
,'userId'
,'folderName'
,'parentId'
,'path'
,'isShared'
]
}),
remoteSort : true
});
store.setDefaultSort('folderId', 'desc');
return store;
};
/**
* 建立操作的Toolbar
*/
DocFolderView.prototype.topbar = function() {
var toolbar = new Ext.Toolbar({
id : 'DocFolderFootBar',
height : 30,
bodyStyle:'text-align:left',
items : [
{
iconCls : 'btn-add',
text : '添加DocFolder',
xtype : 'button',
handler : function() {
new DocFolderForm(null,null,1);
}
}, {
iconCls : 'btn-del',
text : '删除DocFolder',
xtype : 'button',
handler : function() {
var grid=Ext.getCmp("DocFolderGrid");
var selectRecords=grid.getSelectionModel().getSelections();
if(selectRecords.length==0){
Ext.Msg.alert("信息","请选择要删除的记录!");
return;
}
var ids=Array();
for(var i=0;i<selectRecords.length;i++){
ids.push(selectRecords[i].data.folderId);
}
DocFolderView.remove(ids);
}
}
]
});
return toolbar;
};
/**
* 删除单个记录
*/
DocFolderView.remove=function(id){
var grid=Ext.getCmp("DocFolderGrid");
Ext.Msg.confirm('信息确认','您确认要删除该记录吗?',function(btn){
if(btn=='yes'){
Ext.Ajax.request({
url:__ctxPath+'/document/multiDelDocFolder.do',
params:{
ids:id
},
method:'post',
success:function(){
Ext.Msg.alert("信息提示","成功删除所选记录!");
grid.getStore().reload({params:{
start : 0,
limit : 25
}});
}
});
}
});
};
/**
*
*/
DocFolderView.edit=function(id){
new DocFolderForm(id);
}
DocFolderView.right=function(id){
new DocFolderSharedForm(id).getView().show();
}
| JavaScript |
var DocPrivilegeForm = function(privilegeId) {
this.privilegeId = privilegeId;
var fp = this.setup();
var window = new Ext.Window({
id : 'DocPrivilegeFormWin',
title : '文档权限详细信息',
width : 500,
height : 420,
modal: true,
layout : 'anchor',
plain : true,
bodyStyle : 'padding:5px;',
buttonAlign : 'center',
items : [this.setup()],
buttons : [{
text : '保存',
handler : function() {
var fp=Ext.getCmp('DocPrivilegeForm');
if (fp.getForm().isValid()) {
fp.getForm().submit({
method: 'post',
waitMsg : '正在提交数据...',
success : function(fp,action) {
Ext.Msg.alert('操作信息', '成功保存信息!');
Ext.getCmp('DocPrivilegeGrid').getStore().reload();
window.close();
},
failure : function(fp,action) {
Ext.MessageBox.show({
title: '操作信息',
msg: '信息保存出错,请联系管理员!',
buttons: Ext.MessageBox.OK,
icon:'ext-mb-error'
});
window.close();
}
});
}
}
}, {
text : '取消',
handler : function() {
window.close();
}
}]
});
window.show();
};
DocPrivilegeForm.prototype.setup = function() {
var formPanel = new Ext.FormPanel({
url : __ctxPath+ '/document/saveDocPrivilege.do',
layout : 'form',
id:'DocPrivilegeForm',
frame : true,
defaults : {
widht : 400,
anchor : '100%,100%'
},
formId:'DocPrivilegeFormId',
defaultType : 'textfield',
items : [{
name : 'docPrivilege.privilegeId',
id : 'privilegeId',
xtype:'hidden',
value : this.privilegeId == null ? '' : this.privilegeId
}
,{
fieldLabel : '',
name : 'docPrivilege.folderId',
id : 'folderId'
}
,{
fieldLabel : '',
name : 'docPrivilege.docId',
id : 'docId'
}
,{
fieldLabel : '权限',
name : 'docPrivilege.rights',
id : 'rights'
}
,{
fieldLabel : '',
name : 'docPrivilege.udrId',
id : 'udrId'
}
,{
fieldLabel : '',
name : 'docPrivilege.udrName',
id : 'udrName'
}
,{
fieldLabel : '1=user',
name : 'docPrivilege.flag',
id : 'flag'
}
]
});
if(this.privilegeId!=null&&this.privilegeId!='undefined'){
formPanel.getForm().load({
deferredRender :false,
url : __ctxPath + '/document/getDocPrivilege.do?privilegeId=' + this.privilegeId,
waitMsg : '正在载入数据...',
success : function(form, action) {
// Ext.Msg.alert('编辑', '载入成功!');
},
failure : function(form, action) {
// Ext.Msg.alert('编辑', '载入失败');
}
});
}
return formPanel;
};
| JavaScript |
Ext.ns("DocFolder");
/**
* 个人文档目录视图
*/
var PersonalDocumentView = function() {
var selectedNode;
var documentView=new DocumentView();
var treePanel = new Ext.tree.TreePanel({
region : 'west',
id : 'leftFolderPanel',
title : '我的文档目录',
collapsible : true,
split : true,
width : 200,
height : 800,
tbar:new Ext.Toolbar({items:[{
xtype:'button',
iconCls:'btn-refresh',
text:'刷新',
handler:function(){
treePanel.root.reload();
}
},
{
xtype:'button',
text:'展开',
iconCls:'btn-expand',
handler:function(){
treePanel.expandAll();
}
},
{
xtype:'button',
text:'收起',
iconCls:'btn-collapse',
handler:function(){
treePanel.collapseAll();
}
}
]}),
loader : new Ext.tree.TreeLoader({
url : __ctxPath + '/document/listDocFolder.do'
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : function(node){
if (node != null) {
documentView.setFolderId(node.id);
var docView=Ext.getCmp('DocumentView');
if(node.id==0){
docView.setTitle('所有文档');
}else{
docView.setTitle('['+node.text+']文档列表');
}
var documentGrid = Ext.getCmp('DocumentGrid');
var store=documentGrid.getStore();
store.url=__ctxPath+'/system/listDocument.do';
store.baseParams={folderId:node.id};
store.params={start:0,limit:25};
store.reload({params:{start:0,limit:25}});
}
}
}
});
function contextmenu(node, e) {
selectedNode = new Ext.tree.TreeNode({
id : node.id,
text : node.text
});
treeMenu.showAt(e.getXY());
}
//树的右键菜单的
treePanel.on('contextmenu', contextmenu, treePanel);
// 创建右键菜单
var treeMenu = new Ext.menu.Menu({
tbar : new Ext.Toolbar({
items : [{
text : '刷新',
handler : function() {
alert('refresh');
}
}]
}),
id : 'treeMenu',
items : [{
text : '新建目录',
scope : this,
iconCls:'btn-add',
handler : createNode
}, {
text : '修改目录',
scope : this,
iconCls:'btn-edit',
handler : editNode
}, {
text : '删除目录',
scope : this,
iconCls:'btn-delete',
handler : deleteNode
}]
});
//新建目录
function createNode(nodeId) {
var parentId=selectedNode.id;
new DocFolderForm(null,parentId,null);
};
//编辑目录
function editNode() {
var folderId=selectedNode.id;
new DocFolderForm(folderId,null,null);
};
//删除目录,子目录也一并删除
function deleteNode() {
var folderId=selectedNode.id;
Ext.Ajax.request({
url:__ctxPath+'/document/removeDocFolder.do',
params:{folderId:folderId},
method:'post',
success:function(result,request){
Ext.Msg.alert('操作信息','成功删除目录!');
treePanel.root.reload();
},
failure:function(result,request){
Ext.MessageBox.show({
title : '操作信息',
msg : '信息保存出错,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
}
});
};
var panel = new Ext.Panel({
title : '我的文档',
iconCls:'menu-personal-doc',
layout : 'border',
id:'PersonalDocumentView',
height : 800,
items : [treePanel,documentView.getView()]
});
return panel;
};
| JavaScript |
var DocFolderMoveForm=function(){
return this.setup();
}
DocFolderMoveForm.prototype.setup = function() {
var toolbar = this.initToolbar();
var formPanel = new Ext.FormPanel({
url : __ctxPath + '/document/moveDocFolder.do',
title:'文件夹转移',
iconCls:'menu-folder-go',
layout : 'form',
id : 'DocFolderMoveForm',
tbar:toolbar,
frame : true,
formId : 'DocFolderMoveFormId',
items : [
{
xtype:'hidden',
id:'folderIdOld',
name:'folderIdOld'
},
{
xtype:'hidden',
id:'folderIdNew',
name:'folderIdNew'
},
{
layout:'column',
height:28,
items:[
{text : '选择文件夹:',
xtype:'label',
width:98
},{
name : 'docFolderNameOld',
id : 'docFolderNameOld',
xtype:'textfield',
width:165,
allowBlank:false
},{
xtype:'button',
text:'请选择目录',
iconCls:'btn-select',
handler:function(){
PersonalDocFolderSelector.getView(
function(id, name){
if(id==0){
Ext.Msg.alert('操作错误','不能转移该文件!');
}else{
var docF=Ext.getCmp('docFolderNameOld');
var docFolderId=Ext.getCmp('folderIdOld');
docF.setValue(name);
docFolderId.setValue(id);
}
}
).show();
}
},{
xtype:'button',
text:'清除目录',
inconCls:'btn-clear',
handler:function(){
var docFolderName=Ext.getCmp('docFolderNameOld');
var folderId=Ext.getCmp('folderIdOld');
docFolderName.setValue('');
folderId.setValue('');
}
}]},
{
layout:'column',
height:28,
items:[
{text : '转移到:',
xtype:'label',
width:98
},{
name : 'docFolderNameNew',
id : 'docFolderNameNew',
xtype:'textfield',
width:165,
allowBlank:false
},{
xtype:'button',
text:'请选择目录',
iconCls:'btn-select',
handler:function(){
PersonalDocFolderSelector.getView(
function(id, name){
var docF=Ext.getCmp('docFolderNameNew');
var docFolderId=Ext.getCmp('folderIdNew');
docF.setValue(name);
docFolderId.setValue(id);
}
).show();
}
},{
xtype:'button',
text:'清除目录',
inconCls:'btn-clear',
handler:function(){
var docFolderName=Ext.getCmp('docFolderNameNew');
var folderId=Ext.getCmp('folderIdNew');
docFolderName.setValue('');
folderId.setValue('');
}
}]}
]
});
return formPanel;
};
/**
*
* @return {}
*/
DocFolderMoveForm.prototype.initToolbar = function() {
var toolbar = new Ext.Toolbar({
width : '100%',
height : 30,
items : [{
text : '提交',
iconCls:'btn-save',
handler : function() {
var folderIdOld=Ext.getCmp('folderIdOld');
var folderIdNew=Ext.getCmp('folderIdNew');
if(folderIdOld.getValue()==folderIdNew.getValue()){
Ext.Msg.alert('错误信息','不能转移到自己的目录下!');
}else{
var docForm = Ext.getCmp('DocFolderMoveForm');
if(docForm.getForm().isValid()){
docForm.getForm().submit({
waitMsg : '正在提交,请稍候...',
success : function(docForm, o) {
Ext.Msg.confirm('操作信息','提交成功!');
var docForm = Ext.getCmp('DocFolderMoveForm');
docForm.getForm().reset();
},
failure : function(docForm,o){
Ext.Msg.alert('错误信息',o.result.msg);
}
});
}
}
}
}, {
text : '重置',
iconCls:'reset',
handler : function() {
var docForm = Ext.getCmp('DocFolderMoveForm');
docForm.getForm().reset();
}
}]
});
return toolbar;
};
| JavaScript |
var DocFolderSelector = {
getView : function(callback) {
var nodeValue;
var clickNode = function(node) {
if (node != null) {
if(!node.disabled){
nodeValue=node;
return nodeValue;
}
}
};
var treePanel = new Ext.tree.TreePanel({
id : 'docFolderTreePanel',
title : '目录列表 ',
loader : new Ext.tree.TreeLoader({
url : __ctxPath + '/document/selectDocFolder.do'
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : clickNode
}
});
var window = new Ext.Window({
title : '请选择目录',
width : 440,
height : 420,
layout:'fit',
items : [treePanel],
modal:true,
buttonAlign : 'center',
buttons : [{
text : '确认',
iconCls:'btn-ok',
scope:'true',
handler : function(){
if(nodeValue!=null&&nodeValue.id>0){
if (callback != null) {
callback.call(this, nodeValue.id, nodeValue.text);
}
window.close();
}else{
Ext.Msg.alert('提示','你无权插文档入该目录!');
}
}
}, {
text : '关闭',
iconCls:'btn-cancel',
handler : function() {
window.close();
}
}]
});
return window;
}
};
| JavaScript |
Ext.ns('DocFolderSharedView');
var DocFolderSharedView=function(){
var selectedNode;
var docPrivilegeView=new DocPrivilegeView();
var treePanel = new Ext.tree.TreePanel({
region : 'west',
id : 'leftDocFolderSharedPanel',
title : '文件夹目录',
collapsible : true,
split : true,
width : 200,
height : 800,
tbar:new Ext.Toolbar({items:[{
xtype:'button',
iconCls:'btn-refresh',
text:'刷新',
handler:function(){
treePanel.root.reload();
}
},
{
xtype:'button',
text:'展开',
iconCls:'btn-expand',
handler:function(){
treePanel.expandAll();
}
},
{
xtype:'button',
text:'收起',
iconCls:'btn-collapse',
handler:function(){
treePanel.collapseAll();
}
}
]}),
loader : new Ext.tree.TreeLoader({
url : __ctxPath + '/document/treeDocFolder.do'
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : function(node){
if (node != null) {
docPrivilegeView.setFolderId(node.id);
var docPView=Ext.getCmp('DocPrivilegeView');
if(node.id==0){
docPView.setTitle('文件夹授权');
}else{
docPView.setTitle('文件夹['+node.text+']授权情况');
}
var privilegeGrid = Ext.getCmp('DocPrivilegeGrid');
var store=privilegeGrid.getStore();
store.url=__ctxPath+'/document/listDocPrivilege.do';
store.baseParams={folderId:node.id};
store.params={start:0,limit:25};
store.reload();
}
}
}
});
function contextmenu(node, e) {
selectedNode = new Ext.tree.TreeNode({
id : node.id,
text : node.text
});
treeMenu.showAt(e.getXY());
}
//树的右键菜单的
treePanel.on('contextmenu', contextmenu, treePanel);
// 创建右键菜单
var treeMenu = new Ext.menu.Menu({
tbar : new Ext.Toolbar({
items : [{
text : '刷新',
handler : function() {
alert('refresh');
}
}]
}),
id : 'treeMenu',
items : [{
text : '新建目录',
scope : this,
iconCls:'btn-add',
handler : createNode
}, {
text : '修改目录',
scope : this,
iconCls:'btn-edit',
handler : editNode
}, {
text : '删除目录',
scope : this,
iconCls:'btn-delete',
handler : deleteNode
}]
});
//新建目录
function createNode(nodeId) {
var parentId=selectedNode.id;
new DocFolderForm(null,parentId,1);//表示增加公共文件夹
};
//编辑目录
function editNode() {
var folderId=selectedNode.id;
new DocFolderForm(folderId,null,null);
};
//删除目录,子目录也一并删除
function deleteNode() {
var folderId=selectedNode.id;
Ext.Ajax.request({
url:__ctxPath+'/document/removeDocFolder.do',
params:{folderId:folderId},
method:'post',
success:function(result,request){
Ext.Msg.alert('操作信息','成功删除目录!');
treePanel.root.reload();
},
failure:function(result,request){
Ext.MessageBox.show({
title : '操作信息',
msg : '信息保存出错,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
}
});
};
var panel = new Ext.Panel({
id:'DocFolderSharedView',
title : '公共文件夹管理',
iconCls:'menu-public-fol',
layout : 'border',
height : 800,
items : [treePanel,docPrivilegeView.getView()]
});
return panel;
};
| JavaScript |
/**
* 文档共享表单
*
*/
var DocumentSharedForm = function(docId) {
this.docId = docId;
};
/**
* 显示视图
*
* @return {}
*/
DocumentSharedForm.prototype.getView = function() {
var docId = this.docId;
var formPanel = new Ext.FormPanel({
id : 'documentSharedForm',
bodyStyle : 'padding:4px 10px 4px 10px',
items : [{
xtype : 'hidden',
name : 'docId',
value : docId
}, {
xtype : 'fieldset',
border : false,
layout : 'column',
items : [{
xtype : 'label',
text : '共享人员',
width : 100
}, {
xtype : 'hidden',
name : 'sharedUserIds',
id : 'sharedUserIds'
}, {
xtype : 'textarea',
name : 'sharedUserNames',
id : 'sharedUserNames',
width : 300
}, {
xtype : 'button',
text : '选择',
iconCls:'btn-select',
width : 80,
handler : function() {
//显示选择器,并且设置用户
UserSelector.getView(
function(uIds, fnames) {
var sharedUserIds = Ext
.getCmp('sharedUserIds');
var sharedUserNames = Ext
.getCmp('sharedUserNames');
if (sharedUserIds.getValue() == '') {//若原没有值,则直接设置
sharedUserIds.setValue(','+uIds+',');
sharedUserNames.setValue(fnames);
return;
}else{
//去掉重复的人员
var vIds = sharedUserIds.getValue()
.split(',');
var fnms = sharedUserNames.getValue()
.split(',');
sharedUserIds
.setValue(uniqueArray(vIds
.concat(uIds
.split(',')))+',');
alert
sharedUserNames
.setValue(uniqueArray(fnms
.concat(fnames
.split(','))));
}
}).show();
}
}, {
xtype : 'button',
iconCls:'btn-clear',
text : '清空',
handler:function(){
var sharedUserIds = Ext.getCmp('sharedUserIds');
var sharedUserNames = Ext.getCmp('sharedUserNames');
sharedUserIds.setValue('');
sharedUserNames.setValue('');
},
width : 80
}]
}, {
xtype : 'fieldset',
border : false,
layout : 'column',
items : [{
xtype : 'label',
text : '共享部门',
width : 100
}, {
name : 'sharedDepIds',
id : 'sharedDepIds',
xtype : 'hidden'
}, {
name : 'sharedDepNames',
id : 'sharedDepNames',
xtype : 'textarea',
width : 300
}, {
xtype : 'button',
text : '选择',
iconCls:'btn-select',
width : 80,
handler : function() {
DepSelector.getView(function(ids, names) {
var sharedDepIds = Ext.getCmp('sharedDepIds');
var sharedDepNames = Ext.getCmp('sharedDepNames');
if (sharedDepIds.getValue() == '') {//若原没有值,则直接设置
sharedDepIds.setValue(','+ids+',');
sharedDepNames.setValue(names);
return;
}
//去掉重复的部门
var vIds = sharedDepIds.getValue().split(',');
var fnms = sharedDepNames.getValue().split(',');
sharedDepIds.setValue(uniqueArray(vIds
.concat(ids.split(',')))+',');
sharedDepNames.setValue(uniqueArray(fnms
.concat(names.split(','))));
}).show();
}
}, {
xtype : 'button',
text : '清空',
iconCls:'btn-clear',
handler:function(){
var sharedDepIds = Ext.getCmp('sharedDepIds');
var sharedDepNames = Ext.getCmp('sharedDepNames');
sharedDepIds.setValue('');
sharedDepNames.setValue('');
},
width : 80
}]
}, {
xtype : 'fieldset',
border : false,
layout : 'column',
items : [{
xtype : 'label',
text : '共享角色',
width : 100
}, {
xtype : 'hidden',
id : 'sharedRoleIds',
name : 'sharedRoleIds'
}, {
name : 'sharedRoleNames',
id : 'sharedRoleNames',
xtype : 'textarea',
width : 300
}, {
xtype : 'button',
text : '选择',
iconCls:'btn-select',
width : 80,
handler : function() {
RoleSelector.getView(function(ids, names) {
var sharedRoleIds = Ext.getCmp('sharedRoleIds');
var sharedRoleNames = Ext.getCmp('sharedRoleNames');
if (sharedRoleIds.getValue() == '') {//若原没有值,则直接设置
sharedRoleIds.setValue(','+ids+',');
sharedRoleNames.setValue(names);
return;
}
//去掉重复的部门
var vIds = sharedRoleIds.getValue().split(',');
var fnms = sharedRoleNames.getValue().split(',');
sharedRoleIds.setValue(uniqueArray(vIds.concat(ids.split(',')))+',');
sharedRoleNames.setValue(uniqueArray(fnms.concat(names.split(','))));
}).show();
}
}, {
xtype : 'button',
text : '清空',
iconCls:'btn-clear',
handler:function(){
var sharedRoleIds = Ext.getCmp('sharedRoleIds');
var sharedRoleNames = Ext.getCmp('sharedRoleNames');
sharedRoleIds.setValue('');
sharedRoleNames.setValue('');
},
width : 80
}]
}]
});
formPanel.getForm().load({
deferredRender : false,
url : __ctxPath + '/document/getDocument.do?docId='
+ docId,
waitMsg : '正在载入数据...',
success : function(form, action) {
},
failure : function(form, action) {
Ext.MessageBox.show({
title : '操作信息',
msg : '载入信息失败,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
}
});
var window = new Ext.Window({
title : '文档详细信息',
width : 620,
height : 380,
modal : true,
layout : 'anchor',
plain : true,
bodyStyle : 'padding:5px;',
scope : this,
buttonAlign : 'center',
items : formPanel,
buttons : [{
xtype : 'button',
text : '共享',
iconCls:'btn-ok',
handler : function() {
formPanel.getForm().submit({
url:__ctxPath+'/document/shareDocument.do',
method:'post',
waitMsg:'正在提交...',
success:function(fp,action){
window.close();
}
}
);
}
},{
xtype:'button',
iconCls:'btn-cancel',
text:'关闭',
handler:function(){
window.close();
}
}]
});
return window;
}; | JavaScript |
var NewPublicDocumentForm = function(dId,dName) {
return this.setup(dId,dName);
};
NewPublicDocumentForm.prototype.setup = function(dId,dName) {
var docId;
this.docId=dId;
var toolbar = this.initToolbar();
var formPanel = new Ext.FormPanel({
url : __ctxPath + '/document/saveDocument.do',
title:dName==null?'新建公共文档':dName,
iconCls:'menu-new-document',
layout : 'form',
id : 'NewPublicDocumentForm',
tbar:toolbar,
frame : true,
formId : 'NewPublicDocumentFormId',
items : [
{
xtype:'hidden',
id:'folderId',
name:'document.folderId'
},
{
layout:'column',
height:28,
items:[
{text : '选择目录:',
xtype:'label',
width:98
},{
name : 'docFolderName',
id : 'docFolderName',
xtype:'textfield',
width:165,
allowBlank:false
},{
xtype:'button',
text:'请选择目录',
iconCls:'btn-select',
handler:function(){
DocFolderSelector.getView(
function(id, name){
var docF=Ext.getCmp('docFolderName');
var docFolderId=Ext.getCmp('folderId');
docF.setValue(name);
docFolderId.setValue(id);
}
).show();
}
},{
xtype:'button',
text:'清除目录',
inconCls:'btn-clear',
handler:function(){
var docFolderName=Ext.getCmp('docFolderName');
var folderId=Ext.getCmp('folderId');
docFolderName.setValue('');
folderId.setValue('');
}
}]},
{
fieldLabel : '文档名称',
name : 'document.docName',
id : 'docName',
xtype:'textfield',
width:165,
allowBlank:false
},{
height : 250,
xtype : 'htmleditor',
fieldLabel : '内容',
name : 'document.content',
id : 'content'
}, {
layout : 'column',
items : [{
columnWidth : .7,
layout : 'form',
items : [
{
fieldLabel : '附件',
xtype : 'panel',
id:'filePanel',
frame:true,
height:80,
autoScroll:true,
html:''
}]
}, {
columnWidth : .3,
items : [{
xtype : 'button',
text : '添加附件',
handler : function() {
var dialog=App.createUploadDialog({
file_cat:'document',
callback:function(data){
var fileIds=Ext.getCmp("fileIds");
var filePanel=Ext.getCmp('filePanel');
for(var i=0;i<data.length;i++){
if(fileIds.getValue()!=''){
fileIds.setValue(fileIds.getValue()+',');
}
fileIds.setValue(fileIds.getValue()+data[i].fileId);
Ext.DomHelper.append(filePanel.body,'<span><a href="#" onclick="FileAttachDetail.show('+data[i].fileId+')">'+data[i].filename+'</a> <img class="img-delete" src="'+__ctxPath+'/images/system/delete.gif" onclick="removeFile(this,'+data[i].fileId+')"/> | </span>');
}
}
});
dialog.show(this);
}
}, {
xtype : 'button',
text : '清除附件',
handler : function() {
var fileAttaches=Ext.getCmp("fileAttaches");
var filePanel=Ext.getCmp('filePanel');
filePanel.body.update('');
fileAttaches.setValue('');
}
},{
xtype:'hidden',
id:'fileIds',
name:'fileIds'
}]
}
]
}]
});
if (this.docId != null && this.docId != 'undefined') {
formPanel.getForm().load({
deferredRender : false,
url : __ctxPath + '/document/getDocument.do?docId='
+ this.docId,
waitMsg : '正在载入数据...',
success : function(form, action) {
var folder=action.result.data.docFolder;
var af=action.result.data.attachFiles;
var filePanel=Ext.getCmp('filePanel');
var fileIds=Ext.getCmp("fileIds");
for(var i=0;i<af.length;i++){
if(fileIds.getValue()!=''){
fileIds.setValue(fileIds.getValue()+',');
}
fileIds.setValue(fileIds.getValue()+af[i].fileId);
Ext.DomHelper.append(filePanel.body,'<span><a href="#" onclick="FileAttachDetail.show('+af[i].fileId+')">'+af[i].fileName+'</a><img class="img-delete" src="'+__ctxPath+'/images/system/delete.gif" onclick="removeFile(this,'+af[i].fileId+')"/> | </span>');
}
var folderId=folder.folderId;
var folderName=folder.folderName;
var folderIdField=Ext.getCmp('folderId');
var folderNameField=Ext.getCmp('docFolderName');
folderIdField.setValue(folderId);
folderNameField.setValue(folderName);
},
failure : function(form, action) {
Ext.MessageBox.show({
title : '操作信息',
msg : '载入信息失败,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
}
});
}
return formPanel;
};
/**
*
* @return {}
*/
NewPublicDocumentForm.prototype.initToolbar = function() {
var toolbar = new Ext.Toolbar({
width : '100%',
height : 30,
items : [{
text : '提交',
iconCls:'btn-save',
handler : function() {
var docForm = Ext.getCmp('NewPublicDocumentForm');
if(docForm.getForm().isValid()){
docForm.getForm().submit({
waitMsg : '正在提交,请稍候...',
success : function(docForm, o) {
Ext.Msg.alert('操作信息','提交成功!');
var docForm = Ext.getCmp('NewPublicDocumentForm');
docForm.getForm().reset();
var fileAttaches=Ext.getCmp("fileAttaches");
var filePanel=Ext.getCmp('filePanel');
filePanel.body.update('');
fileAttaches.setValue('');
},
failure : function(mailform,o){
Ext.Msg.alert('错误信息',o.result.msg);
}
});
}
}
}, {
text : '重置',
iconCls:'reset',
handler : function() {
var docForm = Ext.getCmp('NewPublicDocumentForm');
docForm.getForm().reset();
var fileAttaches=Ext.getCmp("fileAttaches");
var filePanel=Ext.getCmp('filePanel');
filePanel.body.update('');
fileAttaches.setValue('');
}
}]
});
return toolbar;
};
/**
* 附件上传,可多附件
* @param {} data
*/
function uploadMailAttach(data){
var ids = null
var fileIds = Ext.getCmp('fileIds');
var filenames = Ext.getCmp('filenames');
for(var i=0;i<data.length;i++){
if(fileIds.getValue()!=''){
fileIds.setValue(fileIds.getValue()+',');
filenames.setValue(filenames.getValue()+',');
}
fileIds.setValue(fileIds.getValue()+data[i].fileId);
filenames.setValue(filenames.getValue()+data[i].filename)
}
}
| JavaScript |
Ext.ns('DocumentSharedView');
var DocumentSharedView=function(){
return new Ext.Panel({
id:'DocumentSharedView',
title:'共享文档列表',
iconCls:'menu-folder-shared',
autoScroll:true,
items : [
new Ext.FormPanel({
height : 35,
frame : true,
id : 'SharedDocumentForm',
layout : 'column',
defaults : {
xtype : 'label'
},
items : [
{
text : '文档名称'
}, {
xtype : 'textfield',
name : 'document.docName'
}, {
text : '共享人'
}, {
xtype : 'textfield',
name : 'document.appUser.fullname'
}, {
text : '创建时间 从'
}, {
xtype : 'datefield',
format:'Y-m-d',
name : 'from'
},{
text : '至'
},{
xtype : 'datefield',
format:'Y-m-d',
name : 'to'
},{
xtype : 'button',
text : '查询',
iconCls : 'search',
handler : function() {
var searchPanel = Ext.getCmp('SharedDocumentForm');
var grid = Ext.getCmp('DocumentSharedGrid');
if (searchPanel.getForm().isValid()) {
searchPanel.getForm().submit({
waitMsg : '正在提交查询',
url : __ctxPath
+ '/document/shareListDocument.do',
method:'post',
params:{start:0,limit:25},
// params:{folderId:DocumentView.folderId},
success : function(searchPanel, action) {
var result = Ext.util.JSON
.decode(action.response.responseText);
grid.getStore().loadData(result);
}
});
}
}
},{
xtype:'button',
text:'重置',
iconCls:'reset',
handler:function(){
var searchPanel = Ext.getCmp('SharedDocumentForm');
searchPanel.getForm().reset();
}
}]
}),
this.setup()]
});
};
/**
* 建立视图
*/
DocumentSharedView.prototype.setup = function() {
return this.grid();
};
/**
* 建立DataGrid
*/
DocumentSharedView.prototype.grid = function() {
var sm = new Ext.grid.CheckboxSelectionModel();
var cm = new Ext.grid.ColumnModel({
columns : [sm, new Ext.grid.RowNumberer(), {
header : 'docId',
dataIndex : 'docId',
hidden : true
}, {
header : '文档名称',
dataIndex : 'docName',
width:120
}, {
header : '内容',
dataIndex : 'content',
width:120
}, {
header : '创建时间',
dataIndex : 'createtime'
},{
header:'共享人',
detaIndex:'sharefullname'
},{
header : '附件',
dataIndex : 'haveAttach',
renderer:function(value,metadata,record){
if(value=='' || value=='0'){
return '无附件';
}else{
var attachFiles=record.data.attachFiles;
var str='';
for(var i=0;i<attachFiles.length;i++){
str+='<a href="#" onclick="FileAttachDetail.show('+attachFiles[i].fileId+');" class="attachment">'+attachFiles[i].fileName+'</a>';
str+=' ';
}
return str;
}
}
}, {
header : '查看',
dataIndex : 'docId',
width : 50,
renderer : function(value, metadata, record, rowIndex,
colIndex) {
var editId = record.data.docId;
var str = '<button title="查看" value=" " class="btn-edit" onclick="DocumentSharedView.read('
+ editId + ')"> </button>';
return str;
}
}],
defaults : {
sortable : true,
menuDisabled : false,
width : 100
}
});
var store = this.store();
store.load({
params : {
start : 0,
limit : 25
}
});
var grid = new Ext.grid.GridPanel({
id : 'DocumentSharedGrid',
store : store,
trackMouseOver : true,
disableSelection : false,
loadMask : true,
autoHeight:true,
maxHeight:600,
cm : cm,
sm : sm,
viewConfig : {
forceFit : true,
enableRowBody : false,
showPreview : false
},
bbar : new Ext.PagingToolbar({
pageSize : 25,
store : store,
displayInfo : true,
displayMsg : '当前显示从{0}至{1}, 共{2}条记录',
emptyMsg : "当前没有记录"
})
});
grid.addListener('rowdblclick', function(grid, rowindex, e) {
grid.getSelectionModel().each(function(rec) {
DocumentSharedView.read(rec.data.docId);
});
});
return grid;
};
/**
* 初始化数据
*/
DocumentSharedView.prototype.store = function() {
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : __ctxPath + '/document/shareListDocument.do'
}),
reader : new Ext.data.JsonReader({
root : 'result',
totalProperty : 'totalCounts',
id : 'id',
fields : [{
name : 'docId',
type : 'int'
},'docName', 'content', 'createtime','haveAttach','attachFiles'
,{
name:'sharefullname',
mapping:'appUser.fullname'
}]
}),
remoteSort : true
});
store.setDefaultSort('docId', 'desc');
return store;
};
DocumentSharedView.read=function(docId){
new DocumentSharedWin(docId);
}
| JavaScript |
/**
* 文档共享表单
*
*/
var DocFolderSharedForm = function(privilegeId, folderId) {
this.folderId = folderId;
// var folderId = this.folderId;
this.privilegeId = privilegeId;
var checkRead=function(){
alert('ffdf');
}
var formPanel = new Ext.FormPanel({
id : 'DocFolderSharedForm',
bodyStyle : 'padding:4px 10px 4px 10px',
items : [{
xtype : 'hidden',
name : 'privilegeId',
value : this.privilegeId
}, {
xtype : 'hidden',
name : 'folderId',
value : this.folderId
}, {
xtype : 'fieldset',
border : false,
layout : 'column',
items : [{
xtype : 'label',
text : '共享人员',
width : 100
}, {
xtype : 'hidden',
name : 'userIds',
id : 'userIds'
}, {
xtype : 'textarea',
name : 'userNames',
id : 'userNames',
width : 300
}, {
xtype : 'button',
text : '选择',
iconCls : 'btn-select',
width : 80,
handler : function() {
// 显示选择器,并且设置用户
UserSelector.getView(
function(uIds, fnames) {
var sharedUserIds = Ext
.getCmp('userIds');
var sharedUserNames = Ext
.getCmp('userNames');
if (sharedUserIds.getValue() == '') {// 若原没有值,则直接设置
sharedUserIds
.setValue(uIds);
sharedUserNames
.setValue(fnames);
return;
}
// 去掉重复的人员
var vIds = sharedUserIds
.getValue().split(',');
var fnms = sharedUserNames
.getValue().split(',');
sharedUserIds
.setValue(uniqueArray(vIds
.concat(uIds
.split(','))));
sharedUserNames
.setValue(uniqueArray(fnms
.concat(fnames
.split(','))));
}).show();
}
}, {
xtype : 'button',
iconCls : 'btn-clear',
text : '清空',
handler : function() {
var sharedUserIds = Ext.getCmp('userIds');
var sharedUserNames = Ext
.getCmp('userNames');
sharedUserIds.setValue('');
sharedUserNames.setValue('');
},
width : 80
}]
}, {
xtype : 'fieldset',
border : false,
layout : 'column',
items : [{
xtype : 'label',
text : '共享部门',
width : 100
}, {
name : 'depIds',
id : 'depIds',
xtype : 'hidden'
}, {
name : 'depNames',
id : 'depNames',
xtype : 'textarea',
width : 300
}, {
xtype : 'button',
text : '选择',
iconCls : 'btn-select',
width : 80,
handler : function() {
DepSelector.getView(function(ids, names) {
var sharedDepIds = Ext.getCmp('depIds');
var sharedDepNames = Ext
.getCmp('depNames');
if (sharedDepIds.getValue() == '') {// 若原没有值,则直接设置
sharedDepIds.setValue(ids);
sharedDepNames.setValue(names);
return;
}
// 去掉重复的部门
var vIds = sharedDepIds.getValue()
.split(',');
var fnms = sharedDepNames.getValue()
.split(',');
sharedDepIds.setValue(uniqueArray(vIds
.concat(ids.split(','))));
sharedDepNames
.setValue(uniqueArray(fnms
.concat(names
.split(','))));
}).show();
}
}, {
xtype : 'button',
text : '清空',
iconCls : 'btn-clear',
handler : function() {
var sharedDepIds = Ext.getCmp('depIds');
var sharedDepNames = Ext.getCmp('depNames');
sharedDepIds.setValue('');
sharedDepNames.setValue('');
},
width : 80
}]
}, {
xtype : 'fieldset',
border : false,
layout : 'column',
items : [{
xtype : 'label',
text : '共享角色',
width : 100
}, {
xtype : 'hidden',
id : 'roleIds',
name : 'roleIds'
}, {
name : 'roleNames',
id : 'roleNames',
xtype : 'textarea',
width : 300
}, {
xtype : 'button',
text : '选择',
iconCls : 'btn-select',
width : 80,
handler : function() {
RoleSelector.getView(function(ids, names) {
var sharedRoleIds = Ext
.getCmp('roleIds');
var sharedRoleNames = Ext
.getCmp('roleNames');
if (sharedRoleIds.getValue() == '') {// 若原没有值,则直接设置
sharedRoleIds.setValue(ids);
sharedRoleNames.setValue(names);
return;
}
// 去掉重复的部门
var vIds = sharedRoleIds.getValue()
.split(',');
var fnms = sharedRoleNames.getValue()
.split(',');
sharedRoleIds.setValue(uniqueArray(vIds
.concat(ids.split(','))));
sharedRoleNames
.setValue(uniqueArray(fnms
.concat(names
.split(','))));
}).show();
}
}, {
xtype : 'button',
text : '清空',
iconCls : 'btn-clear',
handler : function() {
var sharedRoleIds = Ext.getCmp('roleIds');
var sharedRoleNames = Ext
.getCmp('roleNames');
sharedRoleIds.setValue('');
sharedRoleNames.setValue('');
},
width : 80
}]
}, {
xtype : 'fieldset',
border : false,
layout : 'column',
items : [{
xtype : 'label',
text : '权限选择:',
width : 100
}, {
xtype : 'checkbox',
name : 'rightR',
id : 'rightR'
}, {
xtype : 'label',
text : '可读',
width : 60
}, {
xtype : 'checkbox',
name : 'rightU',
id : 'rightU',
listeners:{
"check":function(){
var rightU=Ext.getCmp('rightU');
var rightD=Ext.getCmp('rightD');
var rightR=Ext.getCmp('rightR');
if(rightU.getValue()){
rightR.setValue(true);
rightR.disable();
}else if(!rightD.getValue()){
rightR.enable();
}
}
}
}, {
xtype : 'label',
text : '可修改',
width : 60
}, {
xtype : 'checkbox',
name : 'rightD',
id : 'rightD',
listeners:{
"check":function(){
var rightD=Ext.getCmp('rightD');
var rightU=Ext.getCmp('rightU');
var rightR=Ext.getCmp('rightR');
if(rightD.getValue()){
rightR.setValue(true);
rightR.disable();
}else if(!rightU.getValue()){
rightR.enable();
}
}
}
}, {
xtype : 'label',
text : '可删除',
width : 60
}]
}]
});
if (this.privilegeId != null && this.privilegeId != '') {
formPanel.getForm().load({
deferredRender : false,
url : __ctxPath + '/document/getDocPrivilegeView.do?privilegeId='
+ privilegeId,
waitMsg : '正在载入数据...',
success : function(form, action) {
},
failure : function(form, action) {
Ext.MessageBox.show({
title : '操作信息',
msg : '载入信息失败,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
}
});
}
var window = new Ext.Window({
title : '文件夹授权',
width : 620,
height : 420,
modal : true,
layout : 'anchor',
plain : true,
bodyStyle : 'padding:5px;',
scope : this,
buttonAlign : 'center',
items : formPanel,
buttons : [{
xtype : 'button',
text : '共享',
iconCls : 'btn-ok',
handler : function() {
var userIds = Ext.getCmp('userIds').getValue();
var depIds = Ext.getCmp('depIds').getValue();
var roleIds = Ext.getCmp('roleIds').getValue();
var rightR = Ext.getCmp('rightR').getValue();
if (userIds != '' || depIds != '' || roleIds != '') {
if (rightR == true) {
var rightRC = Ext.getCmp('rightR');
rightRC.enable();
formPanel.getForm().submit({
url : __ctxPath
+ '/document/addDocPrivilege.do',
method : 'post',
waitMsg : '正在提交...',
success : function(fp, action) {
Ext.Msg.alert('提示', '保存成功!');
Ext.getCmp('DocPrivilegeGrid')
.getStore().reload();
window.close();
},
failure : function(fp, action) {
Ext.Msg.alert('出错', '请与管理员联系!');
}
});
} else {
Ext.Msg.alert('提示', '读权限为基本权限!');
}
} else {
Ext.Msg.alert('提示', '请选择!');
}
}
}, {
xtype : 'button',
iconCls : 'btn-cancel',
text : '关闭',
handler : function() {
window.close();
}
}]
});
window.show();
}; | JavaScript |
var DocumentSharedWin=function(docId){
this.docId = docId;
var pa=this.setup();
var window=new Ext.Window({
id : 'DocumentSharedWin',
title : '文档信息',
width : 510,
autoHeight :true,
modal : true,
autoScroll:true,
layout : 'anchor',
plain : true,
bodyStyle : 'padding:5px;',
buttonAlign : 'center',
items : [this.setup()],
buttons : [{
text : '关闭',
handler : function() {
window.close();
}
}]
});
window.show();
}
DocumentSharedWin.prototype.setup=function(){
var panel=new Ext.Panel({
id:'DocumentSharedWinPanel',
modal : true,
autoScroll:true,
aotuHeight:true,
width:479,
autoLoad:{url:__ctxPath+'/document/detailDocument.do?docId='+this.docId}
});
return panel;
} | JavaScript |
Ext.ns('DocumentView');
/**
* 文档列表
*/
var DocumentView = function() {
};
/**
* 显示列表
* @return {}
*/
DocumentView.prototype.getView=function(){
return new Ext.Panel({
id : 'DocumentView',
title : '所有文档',
autoScroll : true,
region:'center',
anchor:'100%',
items : [new Ext.FormPanel({
height : 35,
frame : true,
id : 'DocumentSearchForm',
layout : 'column',
defaults : {
xtype : 'label'
},
items : [{
text : '文档名称'
}, {
xtype : 'textfield',
name : 'document.docName'
}, {
text : '创建时间 从'
}, {
xtype : 'datefield',
format:'Y-m-d',
name : 'from'
},{
text : '至'
},{
xtype : 'datefield',
format:'Y-m-d',
name : 'to'
},{
xtype : 'button',
text : '查询',
iconCls : 'search',
handler : function() {
var searchPanel = Ext.getCmp('DocumentSearchForm');
var grid = Ext.getCmp('DocumentGrid');
if (searchPanel.getForm().isValid()) {
searchPanel.getForm().submit({
waitMsg : '正在提交查询',
url : __ctxPath
+ '/document/listDocument.do',
params:{folderId:DocumentView.folderId},
success : function(formPanel, action) {
var result = Ext.util.JSON
.decode(action.response.responseText);
grid.getStore().loadData(result);
}
});
}
}
},{
xtype:'button',
text:'重置',
iconCls:'reset',
hander:function(){
var searchPanel = Ext.getCmp('DocumentSearchForm');
searchPanel.getForm().reset();
}
}]
}), this.setup()]
});
};
DocumentView.prototype.setFolderId=function(folderId){
this.folderId=folderId;
DocumentView.folderId=folderId;
};
DocumentView.prototype.getFolderId=function(){
return this.folderId;
};
/**
* 建立视图
*/
DocumentView.prototype.setup = function() {
return this.grid();
};
/**
* 建立DataGrid
*/
DocumentView.prototype.grid = function() {
var sm = new Ext.grid.CheckboxSelectionModel();
var cm = new Ext.grid.ColumnModel({
columns : [sm, new Ext.grid.RowNumberer(), {
header : 'docId',
dataIndex : 'docId',
hidden : true
}, {
header : '文档名称',
dataIndex : 'docName',
width:120
}, {
header : '内容',
dataIndex : 'content',
width:120
}, {
header : '创建时间',
dataIndex : 'createtime'
},{
header : '共享',
width:40,
dataIndex : 'isShared',
renderer:function(value){
if(value==1){
return '<img src="'+__ctxPath+'/images/flag/shared.png" alt="共享" title="共享" />';
}else{
return '<img src="'+__ctxPath+'/images/flag/lock.png" alt="私有" title="私有" />';
}
}
},{
header : '附件',
dataIndex : 'haveAttach',
renderer:function(value,metadata,record){
if(value=='' || value=='0'){
return '无附件';
}else{
var attachFiles=record.data.attachFiles;
var str='';
for(var i=0;i<attachFiles.length;i++){
str+='<a href="#" onclick="FileAttachDetail.show('+attachFiles[i].fileId+');" class="attachment">'+attachFiles[i].fileName+'</a>';
str+=' ';
}
return str;
}
}
}, {
header : '管理',
dataIndex : 'docId',
width : 50,
renderer : function(value, metadata, record, rowIndex,
colIndex) {
var editId = record.data.docId;
var str = '<button title="删除" value=" " class="btn-del" onclick="DocumentView.remove('
+ editId + ')"> </button>';
str += ' <button title="编辑" value=" " class="btn-edit" onclick="DocumentView.edit('
+ editId + ')"> </button>';
str+= ' <button title="共享" value=" " class="btn-shared" onclick="DocumentView.shared('+editId+')"> </button>';
return str;
}
}],
defaults : {
sortable : true,
menuDisabled : false,
width : 100
}
});
var store = this.store();
store.load({
params : {
start : 0,
limit : 25
}
});
var grid = new Ext.grid.GridPanel({
id : 'DocumentGrid',
tbar : this.topbar(this),
store : store,
trackMouseOver : true,
disableSelection : false,
loadMask : true,
autoHeight:true,
maxHeight:600,
cm : cm,
sm : sm,
viewConfig : {
forceFit : true,
enableRowBody : false,
showPreview : false
},
bbar : new Ext.PagingToolbar({
pageSize : 25,
store : store,
displayInfo : true,
displayMsg : '当前显示从{0}至{1}, 共{2}条记录',
emptyMsg : "当前没有记录"
})
});
grid.addListener('rowdblclick', function(grid, rowindex, e) {
grid.getSelectionModel().each(function(rec) {
DocumentView.edit(rec.data.docId);
});
});
return grid;
};
/**
* 初始化数据
*/
DocumentView.prototype.store = function() {
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : __ctxPath + '/document/listDocument.do'
}),
reader : new Ext.data.JsonReader({
root : 'result',
totalProperty : 'totalCounts',
id : 'id',
fields : [{
name : 'docId',
type : 'int'
},'docName', 'content', 'createtime','haveAttach','attachFiles','isShared'
]
}),
remoteSort : true
});
store.setDefaultSort('docId', 'desc');
return store;
};
/**
* 建立操作的Toolbar
*/
DocumentView.prototype.topbar = function(docViewObj) {
var toolbar = new Ext.Toolbar({
id : 'DocumentFootBar',
height : 30,
bodyStyle : 'text-align:left',
items : [{
iconCls : 'btn-add',
text : '添加文档',
xtype : 'button',
handler : function() {
new DocumentForm(null);
}
}, {
iconCls : 'btn-del',
text : '删除文档',
xtype : 'button',
handler : function() {
var grid = Ext.getCmp("DocumentGrid");
var selectRecords = grid.getSelectionModel().getSelections();
if (selectRecords.length == 0) {
Ext.Msg.alert("信息", "请选择要删除的记录!");
return;
}
var ids = Array();
for (var i = 0; i < selectRecords.length; i++) {
ids.push(selectRecords[i].data.docId);
}
DocumentView.remove(ids);
}
}]
});
return toolbar;
};
/**
* 删除单个记录
*/
DocumentView.remove = function(id) {
var grid = Ext.getCmp("DocumentGrid");
Ext.Msg.confirm('信息确认', '您确认要删除该记录吗?', function(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url : __ctxPath
+ '/document/multiDelDocument.do',
params : {
ids : id
},
method : 'post',
success : function() {
Ext.Msg.alert("信息提示", "成功删除所选记录!");
grid.getStore().reload({
params : {
start : 0,
limit : 25
}
});
}
});
}
});
};
/**
*
*/
DocumentView.edit = function(id) {
new DocumentForm(id);
};
/**
* 文档共享
* @param {} id
*/
DocumentView.shared=function(id){
new DocumentSharedForm(id).getView().show();
};
| JavaScript |
var SharedPhoneBookWin=function(phoneId){
this.phoneId = phoneId;
var pa=this.setup();
var window=new Ext.Window({
id : 'SharedPhoneBookWin',
title : '联系人信息',
width : 600,
height :520,
modal : true,
autoScroll:true,
layout : 'anchor',
plain : true,
bodyStyle : 'padding:5px;',
buttonAlign : 'center',
items : [this.setup()],
buttons : [{
text : '关闭',
handler : function() {
window.close();
}
}]
});
window.show();
}
SharedPhoneBookWin.prototype.setup=function(){
var panel=new Ext.Panel({
id:'SharedPhoneBookPanel',
modal : true,
autoScroll:true,
autoLoad:{url:__ctxPath+'/communicate/detailPhoneBook.do?phoneId='+this.phoneId}
});
return panel;
} | JavaScript |
Ext.ns('PhoneBookView');
/**
* 联系人列表
*/
var PhoneBookView = function() {
};
PhoneBookView.prototype.getStore = function() {
var store = PhoneBookView.store;
return store;
};
PhoneBookView.prototype.getView = function() {
return new Ext.Panel({
id : 'PhoneBookView',
region : 'center',
title : '联系人列表',
autoScroll : true,
items : [new Ext.FormPanel({
height : 35,
frame : true,
id : 'PhoneBookSearchForm',
layout : 'column',
defaults : {
xtype : 'label'
},
items : [{
text : '请输入查询条件:'
}, {
text : '姓名'
}, {
xtype : 'textfield',
name : 'Q_fullname_S_LK'
}, {
text : '称谓'
}, {
xtype : 'textfield',
name : 'Q_title_S_LK'
}
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_birthday_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_nickName_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_duty_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_spouse_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_childs_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_companyName_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_companyAddress_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_companyPhone_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_companyFax_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_homeAddress_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_homeZip_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_mobile_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_phone_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_email_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_QQ_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_MSN_S_LK'
// }
// ,{
// text : ''
// }, {
// xtype : 'textfield',
// name : 'Q_note_S_LK'
// }
, {
xtype : 'button',
text : '查询',
iconCls : 'search',
handler : function() {
var searchPanel = Ext.getCmp('PhoneBookSearchForm');
if (searchPanel.getForm().isValid()) {
searchPanel.getForm().submit({
waitMsg : '正在提交查询',
url : __ctxPath
+ '/communicate/listPhoneBook.do',
success : function(formPanel, action) {
var result = Ext.util.JSON
.decode(action.response.responseText);
PhoneBookView.store.loadData(result);
}
});
}
}
}]
}), this.setup()]
});
};
PhoneBookView.prototype.setPhoneId = function(phoneId) {
this.phoneId = phoneId;
PhoneBookView.phoneId = phoneId;
};
PhoneBookView.prototype.getPhoneId = function() {
return this.phoneId;
};
/**
* 建立视图
*/
PhoneBookView.prototype.setup = function() {
return this.panel();
};
/**
* 建立DataPanel
*/
PhoneBookView.prototype.panel = function() {
this.store = this.store();
var store = this.store;
var a = new Array(6);
store.load({
params : {
start : 0,
limit : 6
}
});
store.on('load', AJAX_Loaded, store, true);// 这里需要注意
var phoneBookPanel = new Ext.Panel({
id : 'phoneBookView',
closable : true,
tbar : this.topbar(),
autoHeight : true,
// title : '联系人详细信息',
layout : 'column',
bbar : new Ext.PagingToolbar({
pageSize : 6,
store : store,
displayInfo : true,
displayMsg : '当前显示从{0}至{1}, 共{2}条记录',
emptyMsg : "当前没有记录"
}),
height : 500,
width : 600,
defaults : {
// 应用到每个包含的panel
bodyStyle : 'padding:15px'
},
layoutConfig : {
// layout-specific configs go here
titleCollapse : false,
animate : true,
activeOnTop : true,
region : 'center',
margins : '35 5 5 0'
},
items : []
});
return phoneBookPanel;
function AJAX_Loaded() {
var phoneBookPanel = Ext.getCmp('phoneBookView');
phoneBookPanel.removeAll();
for (var i = 0; i < store.getCount(); i++) {
var rec = store.getAt(i);
idd = rec.get("phoneId");
var nickName = rec.get("nickName");
var name = rec.get("fullname");
var mobile = rec.get("mobile");
var email = rec.get("email");
var qq = rec.get("qqNumber");
var handlerWrapper = function(button, event, idd) {
// Fetch additional data
};
panel = new Ext.Panel({
id : 'aa' + idd,
title : '' + idd,
columnWidth : .33,
height : 150,
bodyStyle : '',
width : 160,
html : '<p>姓名:' + name + '</p><p>手机:' + mobile
+ '</p><p>Email:' + email + '</p><p>qq:' + qq
+ '</p>',
bbar : [new Ext.Toolbar.TextItem(''), {
xtype : "button"
}, {
pressed : true,
text : '编辑',
iconCls : 'btn-edit',
handler : edit.createDelegate(this, [idd])
}, {
xtype : "button"
}, {
pressed : true,
text : '删除',
iconCls : 'delete-info',
handler : remove
.createDelegate(this, [idd])
}]
});
phoneBookPanel.add(panel);
phoneBookPanel.doLayout();
}
}
};
var edit = function(phoneId) {
PhoneBookView.edit(phoneId);
};
var remove = function(phoneId) {
PhoneBookView.remove(phoneId);
}
/**
* 初始化数据
*/
PhoneBookView.prototype.store = function() {
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : __ctxPath + '/communicate/listPhoneBook.do'
}),
reader : new Ext.data.JsonReader({
root : 'result',
totalProperty : 'totalCounts',
id : 'id',
fields : [{
name : 'phoneId',
type : 'int'
}
, 'fullname', 'title', 'birthday',
'nickName', 'duty', 'spouse', 'childs',
'companyName', 'companyAddress',
'companyPhone', 'companyFax',
'homeAddress', 'homeZip', 'mobile',
'phone', 'email', 'qqNumber', 'msn',
'note', 'userId', 'groupId', 'isShared']
}),
remoteSort : true
});
store.setDefaultSort('phoneId', 'desc');
PhoneBookView.store = store;
return store;
};
/**
* 建立操作的Toolbar
*/
PhoneBookView.prototype.topbar = function() {
var toolbar = new Ext.Toolbar({
id : 'PhoneBookFootBar',
height : 30,
bodyStyle : 'text-align:left',
items : [{
iconCls : 'btn-add',
text : '添加联系人',
xtype : 'button',
handler : function() {
new PhoneBookForm();
}
}, {
iconCls : 'btn-del',
text : '删除联系人',
xtype : 'button',
handler : function() {
var grid = Ext.getCmp("PhoneBookGrid");
var selectRecords = grid.getSelectionModel()
.getSelections();
if (selectRecords.length == 0) {
Ext.Msg.alert("信息", "请选择要删除的记录!");
return;
}
var ids = Array();
for (var i = 0; i < selectRecords.length; i++) {
ids.push(selectRecords[i].data.phoneId);
}
PhoneBookView.remove(ids);
}
}]
});
return toolbar;
};
/**
* 删除单个记录
*/
PhoneBookView.remove = function(id) {
Ext.Msg.confirm('信息确认', '您确认要删除该记录吗?', function(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url : __ctxPath
+ '/communicate/multiDelPhoneBook.do',
params : {
ids : id
},
method : 'post',
success : function() {
Ext.Msg.alert("信息提示", "成功删除所选记录!");
PhoneBookView.store.reload({
params : {
start : 0,
limit : 6
}
});
}
});
}
});
};
/**
*
*/
PhoneBookView.edit = function(id) {
new PhoneBookForm(id);
}
| JavaScript |
Ext.ns('SharedPhoneBookView');
var SharedPhoneBookView=function(){
return new Ext.Panel({
id:'SharedPhoneBookView',
iconCls:"menu-phonebook-shared",
title:'共享联系人列表',
autoScroll:true,
items:[
new Ext.FormPanel({
height:35,
frame:true,
id:'PhoneSearchForm',
layout:'column',
defaults:{xtype:'label'},
items:[{text:'请输入查询条件:'}
,{
text : '姓名'
}, {
xtype : 'textfield',
name : 'Q_fullname_S_LK'
}
,{
text : '共享人'
}, {
xtype : 'textfield',
name : 'Q_appUser.fullname_S_LK'
},{
xtype:'button',
text:'查询',
iconCls:'search',
handler:function(){
var searchPanel=Ext.getCmp('PhoneSearchForm');
var grid=Ext.getCmp('PhoneBookGrid');
if(searchPanel.getForm().isValid()){
searchPanel.getForm().submit({
waitMsg:'正在提交查询',
url:__ctxPath+'/communicate/sharePhoneBook.do',
success:function(formPanel,action){
var result=Ext.util.JSON.decode(action.response.responseText);
grid.getStore().loadData(result);
}
});
}
}
}]
})
,
this.setup()
]
});
};
/**
* 建立视图
*/
SharedPhoneBookView.prototype.setup = function() {
return this.grid();
};
/**
* 建立DataGrid
*/
SharedPhoneBookView.prototype.grid = function() {
var cm = new Ext.grid.ColumnModel({
columns : [new Ext.grid.RowNumberer(), {
header : 'phoneId',
dataIndex : 'phoneId',
hidden : true
},{
header : '名字',
dataIndex : 'fullname'
},{
header : '职位',
dataIndex : 'duty'
},{
header : '电话',
dataIndex : 'mobile'
},{
header : '共享人',
dataIndex : 'sharefullname'
}],
defaults : {
sortable : true,
menuDisabled : false,
width : 100
}
});
var store = this.store();
store.load({
params : {
start : 0,
limit : 25
}
});
var grid = new Ext.grid.GridPanel({
id : 'PhoneBookGrid',
store : store,
trackMouseOver : true,
disableSelection : false,
loadMask : true,
autoHeight:true,
cm : cm,
viewConfig : {
forceFit : true,
enableRowBody : false,
showPreview : false
},
bbar : new Ext.PagingToolbar({
pageSize : 25,
store : store,
displayInfo : true,
displayMsg : '当前显示从{0}至{1}, 共{2}条记录',
emptyMsg : "当前没有记录"
})
});
grid.addListener('rowdblclick', function(grid, rowindex, e) {
grid.getSelectionModel().each(function(rec) {
var sharedPhoneBookWin=Ext.getCmp('SharedPhoneBookWin');
if(sharedPhoneBookWin==null){
SharedPhoneBookView.read(rec.data.phoneId);
}
});
});
return grid;
};
/**
* 初始化数据
*/
SharedPhoneBookView.prototype.store = function() {
var store = new Ext.data.Store( {
proxy : new Ext.data.HttpProxy( {
url : __ctxPath + '/communicate/sharePhoneBook.do'
}),
reader : new Ext.data.JsonReader( {
root : 'result',
totalProperty : 'totalCounts',
id : 'id',
fields : [ {
name : 'phoneId',
type : 'int'
}
, 'fullname', 'title', 'birthday', 'nickName', 'duty', 'spouse',
'childs', 'companyName', 'companyAddress', 'companyPhone',
'companyFax', 'homeAddress', 'homeZip', 'mobile', 'phone',
'email', 'qqNumber', 'msn', 'note',
{
name:'sharefullname',
mapping:'appUser.fullname'
}, 'groupId',
'isShared' ]
}),
remoteSort : true
});
store.setDefaultSort('phoneId', 'desc');
return store;
};
SharedPhoneBookView.read=function(id){
new SharedPhoneBookWin(id);
} | JavaScript |
var PhoneBookForm = function(phoneId) {
this.phoneId = phoneId;
var fp = this.setup();
var window = new Ext.Window( {
id : 'PhoneBookFormWin',
title : '联系人详细信息',
width : 600,
height : 330,
modal : true,
minWidth : 600,
minHeight : 330,
layout : 'anchor',
plain : true,
bodyStyle : 'padding:5px;',
buttonAlign : 'center',
items : [ this.setup() ],
buttons : [ {
text : '保存',
iconCls:'btn-save',
handler : function() {
var fp = Ext.getCmp('PhoneBookForm');
if (fp.getForm().isValid()) {
fp.getForm().submit( {
method : 'post',
waitMsg : '正在提交数据...',
success : function(fp, action) {
Ext.Msg.alert('操作信息', '成功信息保存!');
var phoneBookView=new PhoneBookView();
var store=phoneBookView.getStore();
store.reload( {
params : {
start : 0,
limit : 6
}
});
window.close();
},
failure : function(fp, action) {
Ext.MessageBox.show( {
title : '操作信息',
msg : '信息保存出错,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
window.close();
}
});
}
}
}, {
text : '取消',
iconCls:'btn-cancel',
handler : function() {
window.close();
}
} ]
});
window.show();
};
PhoneBookForm.prototype.setup = function() {
var _url = __ctxPath+'/communicate/listPhoneGroup.do';
var phoneGroupSelector = new TreeSelector('phoneGroupSelect',_url,'分组*','groupId');
var formPanel = new Ext.FormPanel( {
url : __ctxPath + '/communicate/savePhoneBook.do',
layout : 'form',
id : 'PhoneBookForm',
frame : true,
formId : 'PhoneBookFormId',
items: [{
xtype:'hidden',
name:'phoneBook.phoneId',
id:'phoneId'
},{
layout: 'column',
border:false,
items: [{
layout:'form',
columnWidth:.6,
items:[phoneGroupSelector,
{
xtype:'hidden',
id:'groupId',
allowBlank:false,
name:'phoneBook.phoneGroup.groupId'
},{
xtype:'textfield',
fieldLabel: '姓名*',
allowBlank:false,
width:162,
name: 'phoneBook.fullname',
id:'fullname'
},{
xtype:'datefield',
fieldLabel: '出生时间',
name:'phoneBook.birthday',
id:'birthday',
readOnly : true,
format : 'Y-m-d',
length : 50,
width:162
}]},{
layout:'form',
columnWidth:.4,
items:[
{
fieldLabel : '称谓*',
xtype : 'combo',
anchor:'95%',
allowBlank:false,
name : 'phoneBook.title',
id:'title',
mode : 'local',
editable : false,
triggerAction : 'all',
store : ['先生', '女士']
},{
xtype : 'combo',
fieldLabel: '是否共享*',
allowBlank:false,
hiddenName: 'phoneBook.isShared',
id:'isShared',
mode : 'local',
editable : false,
triggerAction : 'all',
store : [['0','否'],['1','是']],
anchor:'95%'
},{
xtype:'textfield',
fieldLabel: '妮称',
anchor:'95%',
name: 'phoneBook.nickName',
id:'nickName'
}]}]
},{
xtype:'tabpanel',
plain:true,
activeTab: 0,
height:170,
defaults:{bodyStyle:'padding:10px'},
items:[{
title:'联系方式',
layout:'form',
defaults: {width: 300},
defaultType: 'textfield',
items: [{
fieldLabel: '手机号码',
name: 'phoneBook.mobile',
id:'mobile'
},{
fieldLabel: '固定电话',
name: 'phoneBook.phone',
id:'phone'
},{
fieldLabel: 'Email',
name: 'phoneBook.email',
id:'email'
}, {
fieldLabel: 'QQ',
name: 'phoneBook.qqNumber',
id:'qqNumber'
},
{
fieldLabel: 'MSN',
name: 'phoneBook.msn',
id:'msn'
}]
},{
title:'公司',
layout:'form',
defaults: {width: 300},
defaultType: 'textfield',
items: [{
fieldLabel: '职务',
name: 'phoneBook.duty',
id:'duty'
},{
fieldLabel: '单位名称',
name: 'phoneBook.companyName',
id:'companyName'
},{
fieldLabel: '单位地址',
name: 'phoneBook.companyAddress',
id:'companyAddress'
},{
fieldLabel: '单位电话',
name: 'phoneBook.companyPhone',
id:'companyPhone'
},{
fieldLabel: '单位传真',
name: 'phoneBook.companyFax',
id:'companyFax'
}]
},{
title:'家庭',
layout:'form',
defaults: {width: 300},
defaultType: 'textfield',
items: [{
fieldLabel: '家庭住址',
name: 'phoneBook.homeAddress',
id:'homeAddress'
},{
fieldLabel: '家庭邮编',
name: 'phoneBook.homeZip',
id:'homeZip'
},{
fieldLabel: '配偶',
name: 'phoneBook.spouse',
id:'spouse'
},{
fieldLabel: '子女',
name: 'phoneBook.childs',
id:'childs'
}]
},{
cls:'x-plain',
title:'备注',
layout:'fit',
items: {
xtype:'textarea',
id:'note',
fieldLabel:'备注',
name:'phoneBook.note'
}
}]
}]
});
if (this.phoneId != null && this.phoneId != 'undefined') {
formPanel.getForm().load(
{
deferredRender : false,
url : __ctxPath + '/communicate/getPhoneBook.do?phoneId='
+ this.phoneId,
method:'post',
waitMsg : '正在载入数据...',
success : function(form, action) {
var birthday=action.result.data.birthday;
var birthdayField=Ext.getCmp('birthday');
birthdayField.setValue(new Date(getDateFromFormat(birthday, "yyyy-MM-dd HH:mm:ss")));
var groupNameField=Ext.getCmp('phoneGroupSelect');
var groupIdField=Ext.getCmp('groupId');
var groupName=action.result.data.phoneGroup.groupName;
var groupId=action.result.data.phoneGroup.groupId;
if(groupName!=null&&groupId!=null){
groupNameField.setValue(groupName);
groupIdField.setValue(groupId);
}
// Ext.Msg.alert('编辑', '载入成功!');
},
failure : function(form, action) {
// Ext.Msg.alert('编辑', '载入失败');
}
});
}
return formPanel;
};
| JavaScript |
var MailForm = function(mailId,boxId,opt) {
return this.setup(mailId,boxId,opt);
};
MailForm.prototype.setup = function(mailId,boxId,opt) {
var toolbar = this.initToolbar();
var copyFieldItem = new copyFieldItems();
var formPanel = new Ext.FormPanel({
url : __ctxPath + '/communicate/saveMail.do',
title:'发送邮件',
iconCls:'menu-mail_send',
layout : 'form',
id : 'MailForm',
tbar:toolbar,
frame : true,
formId : 'MailFormId',
autoScroll:true,
defaultType : 'textfield',
reader : new Ext.data.JsonReader({
root : 'data'
}, [{
name : 'mail.recipientIDs',
mapping : 'recipientIDs'
},{
name : 'mail.copyToIDs',
mapping : 'copyToIDs'
},{
name : 'mail.mailStatus',
mapping : 'mailStatus'
},{
name : 'mail.fileIds',
mapping : 'fileIds'
},{
name : 'mail.mailId',
mapping : 'mailId'
},{
name : 'mail.recipientNames',
mapping : 'recipientNames'
},{
name : 'mail.subject',
mapping : 'subject'
},{
name : 'mailImportantFlag',
mapping : 'importantFlag'
},{
name : 'mail.filenames',
mapping : 'filenames'
},{
name : 'mail.content',
mapping : 'content'
},{
name : 'mail.copyToNames',
mapping : 'copyToNames'
}
]),
items : [
//-----------------------------------------hidden 的属性
{
fieldLabel : '收件人ID列表用,分隔',
name : 'mail.recipientIDs',
id : 'mail.recipientIDs',
xtype:'hidden'
},{
fieldLabel : '抄送人ID列表用,分开',
name : 'mail.copyToIDs',
id : 'mail.copyToIDs',
xtype:'hidden'
},{
fieldLabel : '邮件状态',
name : 'mail.mailStatus',
id : 'mail.mailStatus',
xtype:'hidden',
value:1
},{
fieldLabel : '附件IDs',
name: 'mail.fileIds',
xtype:'hidden',
id:'mail.fileIds'
},{
fieldLabel : 'BOXID',
name:'boxId',
xtype:'hidden',
id:'mailBoxId'
},{
fieldLabel : 'MailId',
name: 'mail.mailId',
xtype : 'hidden',
id : 'mail.mailId'
},{
fieldLabel : '操作',
name: 'replyBoxId',
xtype : 'hidden',
id : 'mail.replyBoxId'
},{
fieldLabel : '附件名称列表',
name:'mail.filenames',
xtype:'hidden',
id : 'mail.filenames'
},
//------------------------------------------ hidden end
{
xtype:'container',
layout:'column',
height:26,
defaultType:'textfield',
items:[
{
xtype:'label',
text:'收件人:',
width:97
},{
width:500,
fieldLabel : '收件人姓名列表',
name : 'mail.recipientNames',
id : 'mail.recipientNames',
emptyText:'请选择收件人',
readOnly:true
},{
xtype:'button',
text:'选择收件人',
iconCls : 'btn-mail_recipient',
handler:function(){
UserSelector.getView(
function(userIds, fullnames) {
var recipientIDs = Ext.getCmp('mail.recipientIDs');
var recipientNames = Ext.getCmp('mail.recipientNames');
recipientIDs.setValue(userIds);
recipientNames.setValue(fullnames);
}).show();
}
},{
xtype:'button',
text:'我要抄送',
iconCls : 'btn-mail_copy',
handler:function(){
var copyField = Ext.getCmp('copyField');
copyField.show();
}
}
]
},
{
xtype:'container',//抄送人container
id:'copyField',
layout:'column',
height:26,
hidden:true,
defaultType:'textfield',
items:[copyFieldItem]
},{
width:500,
fieldLabel : '主题',
name : 'mail.subject',
id : 'mail.subject',
emptyText:'邮件主题为必填'
}, {
xtype : 'container',
layout : 'column',
height : 25,
defaultType : 'textfield',
items : [{
xtype : 'label',
text : '优先级:',
width : 93
}, {
width : 500,
fieldLabel : '邮件优先级',
hiddenName : 'mail.importantFlag',
id : 'mailImportantFlag',
xtype : 'combo',
mode : 'local',
editable : false,
value : '1',
triggerAction : 'all',
store : [['1', '一般'], ['2', '重要'],
['3', '非常重要']]
}, {
xtype : 'checkbox',
name : 'sendMessage',
boxLabel : '告诉他有信'
}]
},{
xtype:'container',
layout:'column',
autoHeight:true,
defaultType:'textfield',
items:[{
xtype:'label',
text:'附件:',
width:97
},{
//autoWidth:true,
autoHeight:true,
xtype:'panel',
width:505,
layout:'column',
name:'filenames.display',
id:'filenames.display',
items:[{
columnWidth:1,
xtype:'fieldset',
height:26,
id:'placeholder'
}]
},{
xtype:'button',
text:'上传',
iconCls : 'btn-upload',
handler:function(){
var dialog = App.createUploadDialog({
file_cat : 'communicate/mail',
callback : uploadMailAttach
});
dialog.show('queryBtn');
}
}]
},{
fieldLabel : '内容',
name : 'mail.content',
id : 'mail.content',
xtype:'htmleditor',
width:680,
height:280
}]//form items
});
if (mailId != null && mailId != 'undefined') {
var _mailId = Ext.getCmp('mail.mailId');
_mailId.setValue(mailId);
if(opt=='draft'){//重载草稿
formPanel.getForm().load({
deferredRender : false,
url : __ctxPath + '/communicate/getMail.do',
method:'post',
params:{mailId:mailId,folderId:3,boxId:boxId},
waitMsg : '正在载入数据...',
success : function(form, action) {
var copyToIDs = Ext.getCmp('mail.copyToIDs');
if(copyToIDs.value!=''){//假如草稿有抄送人,激活抄送人控件
var copyField= Ext.getCmp('copyField');
copyField.show();
}
var filenames = Ext.getCmp('mail.filenames').value;
if(filenames!=''){
var display = Ext.getCmp('filenames.display');
var placeholder = Ext.getCmp('placeholder');
if(placeholder!=null){//载入草稿并有附件时,点位行隐藏
placeholder.hide();
}
var fnames = filenames.split(',');
var fids = Ext.getCmp('mail.fileIds').value.split(',');
for(var i=0;i<fnames.length;i++){//显示附件
display.add(new Ext.form.FieldSet({
id:'mailAttachDisplay'+fids[i],
columnWidth:1,
html:'<img src="'+ __ctxPath +'/images/flag/attachment.png"/> '+fnames[i] + ' <a href="javascript:deleteAttach('+fids[i]+')" >删除</a>'
}));
}
display.doLayout(true);
}
},
failure : function(form, action) {
}
});
}else if(opt=='reply'){//回复
formPanel.getForm().load({
deferredRender : false,
url : __ctxPath + '/communicate/optMail.do',
method:'post',
params:{mailId:mailId,opt:'回复'},
waitMsg : '正在载入数据...',
success : function(form, action) {
Ext.getCmp('mail.replyBoxId').setValue(boxId);
// Ext.Msg.alert('编辑', '载入成功!');
},
failure : function(form, action) {
// Ext.Msg.alert('编辑', '载入失败');
}
});
}else if(opt=='forward'){
formPanel.getForm().load({
deferredRender : false,
url : __ctxPath + '/communicate/optMail.do',
method:'post',
params:{mailId:mailId,opt:'转发'},
waitMsg : '正在载入数据...',
success : function(form, action) {
// Ext.Msg.alert('编辑', '载入成功!');
},
failure : function(form, action) {
// Ext.Msg.alert('编辑', '载入失败');
}
});
}
}
if(boxId !=null && boxId != 'undefined'){
var mailBoxId = Ext.getCmp('mailBoxId');
mailBoxId.setValue(boxId);
}
return formPanel;
};
/**
*
* @return {}
*/
MailForm.prototype.initToolbar = function() {
var toolbar = new Ext.Toolbar({
width : '100%',
height : 30,
items : [{
text : '立即发送',
iconCls:'btn-mail_send',
handler : function() {
var mailform = Ext.getCmp('MailForm');
var mailStatus = Ext.getCmp('mail.mailStatus');
mailStatus.setValue(1);
mailform.getForm().submit({
waitMsg : '正在发送邮件,请稍候...',
success : function(mailform, o) {
Ext.Msg.confirm('操作信息','邮件发送成功!继续发邮件?',function(btn){
if(btn=='yes'){
var mailform = Ext.getCmp('MailForm');
mailform.getForm().reset();
}else{
var tabs = Ext.getCmp('centerTabPanel');
tabs.remove('MailForm');
}
});
},
failure : function(mailform,o){
Ext.Msg.alert('错误信息',o.result.msg);
}
});
}
}, {
text : '存草稿',
iconCls:'btn-mail_save',
handler : function() {
var mailStatus = Ext.getCmp('mail.mailStatus');
mailStatus.setValue(0);
var mailform = Ext.getCmp('MailForm');
mailform.getForm().submit({
waitMsg:'正在保存草稿,请稍候...',
success: function(mailform, o){
Ext.Msg.confirm('操作信息','草稿保存成功!继续发邮件?',function(btn){
if(btn=='yes'){
var mailform = Ext.getCmp('MailForm');
mailform.getForm().reset();
}else{
var tabs = Ext.getCmp('centerTabPanel');
tabs.remove('MailForm');
}
});
},
failure : function(mailform,o){
Ext.Msg.alert('错误信息',o.result.msg);
}
})
}
}, {
text : '重置',
iconCls:'reset',
handler : function() {
var mailForm = Ext.getCmp('MailForm');
mailForm.getForm().reset();
}
},{
text : '取消',
iconCls:'btn-mail_remove',
handler : function() {
var tabs = Ext.getCmp('centerTabPanel');
tabs.remove('MailForm');
}
}]
});
return toolbar;
};
/**
* 增加抄送控件
* @return {}
*/
function copyFieldItems(){
var items = [{
xtype:'label',
text:'抄送人:',
width:97
},{
width:500,
fieldLabel : '抄送人姓名列表',
name : 'mail.copyToNames',
id : 'mail.copyToNames',
emptyText:'请选择抄送人',
readOnly:true
},{
xtype:'button',
text:'选择抄送人',
iconCls : 'btn-mail_recipient',
handler:function(){
UserSelector.getView(
function(userIds, fullnames) {
var copyToIDs = Ext.getCmp('mail.copyToIDs');
var copyToNames = Ext.getCmp('mail.copyToNames')
copyToIDs.setValue(userIds);
copyToNames.setValue(fullnames);
}).show();
}
},{
xtype:'button',
text:'取消抄送',
iconCls : 'btn-delete_copy',
handler:function(){//取消抄送时设置为空
var copyField = Ext.getCmp('copyField');
var mailForm = Ext.getCmp('MailForm');
mailForm.getForm().findField('mail.copyToIDs').setValue('');
mailForm.getForm().findField('mail.copyToNames').setValue('');
copyField.hide();
}
}];
return items;
}
/**
* 附件上传,可多附件
* @param {} data
*/
function uploadMailAttach(data){
var ids = null
var fileIds = Ext.getCmp('mail.fileIds');
var filenames = Ext.getCmp('mail.filenames');
var display = Ext.getCmp('filenames.display');
var placeholder = Ext.getCmp('placeholder');
if(placeholder!=null){//隐藏点位符
placeholder.hide();
}
for(var i=0;i<data.length;i++){
if(fileIds.getValue()!=''){
fileIds.setValue(fileIds.getValue()+',');
filenames.setValue(filenames.getValue()+',');
}
fileIds.setValue(fileIds.getValue()+data[i].fileId);
filenames.setValue(filenames.getValue()+data[i].filename)
display.add(new Ext.form.FieldSet({//显示附件
id:'mailAttachDisplay'+data[i].fileId,
columnWidth:1,
html:'<img src="'+ __ctxPath +'/images/flag/attachment.png"/> '+data[i].filename + ' <a href="javascript:deleteAttach('+data[i].fileId+')">删除</a>'
}));
}
display.doLayout(true);
}
/*
* 附件删除
*/
function deleteAttach(_fileId){
//alert('_fileId'+_fileId);
//删除隐藏域中的附件信息
var fids = Ext.getCmp('mail.fileIds').value.split(',');
var fnames = Ext.getCmp('mail.filenames').value.split(',');
var fileIds ='';
var filenames = '';
for(var i=0;i<fids.length;i++){
if(fids[i]!=_fileId){
fileIds += fids[i]+','
filenames += fnames[i]+','
}
}
if(fileIds!=''){
fileIds = fileIds.substring(0,fileIds.length-1)
filenames = filenames.substring(0,filenames.length-1)
}
Ext.getCmp('mail.fileIds').setValue(fileIds);
Ext.getCmp('mail.filenames').setValue(filenames);
var display = Ext.getCmp('filenames.display')
var deleteField = Ext.getCmp('mailAttachDisplay'+_fileId);
display.remove(deleteField);//删除附件显示
if(Ext.getCmp('mail.fileIds').value==''){//假如没有附件,则显示占位行
Ext.getCmp('placeholder').show();
}
display.doLayout(true);
var _mailId = Ext.getCmp('mail.mailId').value;
if(_mailId !='' && _mailId != 'undefined'){//假如是草稿,则存草稿
Ext.Ajax.request({
url:__ctxPath+'/communicate/attachMail.do',
method:'post',
params:{mailId:_mailId,fileId:_fileId,fileIds:fileIds,filenames:filenames},
success:function(){
}
})
}else{//新邮件的时候
Ext.Ajax.request({
url:__ctxPath+'/system/multiDelFileAttach.do',
params:{ids:_fileId},
method : 'post',
success : function() {
Ext.Msg.alert("信息提示", "成功删除所选记录!");
}
})
}
}
| JavaScript |
Ext.ns("PersonalPhoneBookView");
/**
* 个人通讯薄目录视图
*/
var PersonalPhoneBookView = function() {
var selectedNode;
var phoneBookView=new PhoneBookView();
var treePanel = new Ext.tree.TreePanel({
region : 'west',
id : 'leftBookPanel',
title : '我的通讯分组',
collapsible : true,
split : true,
width : 200,
height : 800,
tbar:new Ext.Toolbar({items:[{
xtype:'button',
iconCls:'btn-refresh',
text:'刷新',
handler:function(){
treePanel.root.reload();
}
},
{
xtype:'button',
text:'展开',
iconCls:'btn-expand',
handler:function(){
treePanel.expandAll();
}
},
{
xtype:'button',
text:'收起',
iconCls:'btn-collapse',
handler:function(){
treePanel.collapseAll();
}
}
]}),
loader : new Ext.tree.TreeLoader({
url : __ctxPath + '/communicate/listPhoneGroup.do'
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : function(node){
if (node != null) {
phoneBookView.setPhoneId(node.id);
var bookView=Ext.getCmp('PhoneBookView');
if(node.id==0){
bookView.setTitle('所有联系人');
}else{
bookView.setTitle(node.text+'组列表');
}
var store=phoneBookView.getStore();
store.url=__ctxPath+'/communicate/listPhoneBook.do';
store.baseParams={groupId:node.id};
store.params={start:0,limit:6};
store.reload({params:{start:0,limit:6}});
}
}
}
});
function contextmenu(node, e) {
selectedNode = new Ext.tree.TreeNode({
id : node.id,
text : node.text
});
treeMenu.showAt(e.getXY());
}
//树的右键菜单的
treePanel.on('contextmenu', contextmenu, treePanel);
// 创建右键菜单
var treeMenu = new Ext.menu.Menu({
tbar : new Ext.Toolbar({
items : [{
text : '刷新',
handler : function() {
alert('refresh');
}
}]
}),
id : 'treeMenu',
items : [
{
text : '新建组',
scope : this,
iconCls:'btn-add',
handler : createNode
},{
text : '修改组',
scope : this,
iconCls:'btn-edit',
handler : editNode
},{
text : '删除组',
scope : this,
iconCls:'btn-delete',
handler : deleteNode
}
,{
text : '上移',
scope : this,
iconCls:'btn-up',
handler : upMove
}
,{
text : '下移',
scope : this,
iconCls:'btn-last',
handler : downMove
},{
text : '置顶',
scope : this,
iconCls:'btn-top',
handler : topMove
},{
text : '置底',
scope : this,
iconCls:'btn-down',
handler : underMove
}
]
});
//新建目录
function createNode() {
new PhoneGroupForm(null);
};
//编辑目录
function editNode() {
var groupId=selectedNode.id;
if(groupId>0){
new PhoneGroupForm(groupId);
}else{
Ext.MessageBox.show({
title : '操作信息',
msg : '该处不能被修改',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
}
};
//删除目录,子目录也一并删除
function deleteNode() {
var groupId=selectedNode.id;
Ext.Ajax.request({
url:__ctxPath+'/communicate/multiDelPhoneGroup.do',
params:{ids:groupId},
method:'post',
success:function(result,request){
Ext.Msg.alert('操作信息','成功删除目录!');
treePanel.root.reload();
},
failure:function(result,request){
Ext.MessageBox.show({
title : '操作信息',
msg : '信息保存出错,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
}
});
};
function upMove(){
var groupId=selectedNode.id;
Ext.Ajax.request({
url:__ctxPath+'/communicate/movePhoneGroup.do',
params:{groupId:groupId,optId:1},
method:'post',
success:function(result,request){
treePanel.root.reload();
},
failure:function(result,request){
}
});
};
function downMove(){
var groupId=selectedNode.id;
Ext.Ajax.request({
url:__ctxPath+'/communicate/movePhoneGroup.do',
params:{groupId:groupId,optId:2},
method:'post',
success:function(result,request){
treePanel.root.reload();
},
failure:function(result,request){
}
});
};
function topMove(){
var groupId=selectedNode.id;
Ext.Ajax.request({
url:__ctxPath+'/communicate/movePhoneGroup.do',
params:{groupId:groupId,optId:3},
method:'post',
success:function(result,request){
treePanel.root.reload();
},
failure:function(result,request){
}
});
};
function underMove(){
var groupId=selectedNode.id;
Ext.Ajax.request({
url:__ctxPath+'/communicate/movePhoneGroup.do',
params:{groupId:groupId,optId:4},
method:'post',
success:function(result,request){
treePanel.root.reload();
},
failure:function(result,request){
}
});
};
var panel = new Ext.Panel({
title : '我的通讯薄',
iconCls:"menu-personal-phoneBook",
layout : 'border',
id:'PersonalPhoneBookView',
height : 800,
items : [treePanel,phoneBookView.getView()]
});
return panel;
};
| JavaScript |
var PhoneGroupForm = function(groupId) {
this.groupId = groupId;
var fp = this.setup();
var window = new Ext.Window( {
id : 'PhoneGroupFormWin',
title : '通讯分组详细信息',
width : 300,
height : 170,
modal : true,
minWidth : 280,
minHeight : 160,
layout : 'form',
plain : true,
bodyStyle : 'padding:5px;',
buttonAlign : 'center',
items : [ this.setup() ],
buttons : [ {
text : '保存',
iconCls : 'btn-save',
handler : function() {
var fp = Ext.getCmp('PhoneGroupForm');
if (fp.getForm().isValid()) {
fp.getForm().submit( {
method : 'post',
waitMsg : '正在提交数据...',
success : function(fp, action) {
Ext.Msg.alert('操作信息', '成功信息保存!');
var phoneGroupTree = Ext.getCmp('leftBookPanel');
if (phoneGroupTree != null) {
phoneGroupTree.root.reload();
}
window.close();
},
failure : function(fp, action) {
Ext.MessageBox.show( {
title : '操作信息',
msg : '信息保存出错,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
window.close();
}
});
}
}
}, {
text : '取消',
iconCls : 'btn-cancel',
handler : function() {
window.close();
}
} ]
});
window.show();
};
PhoneGroupForm.prototype.setup = function() {
var formPanel = new Ext.FormPanel( {
url : __ctxPath + '/communicate/savePhoneGroup.do',
layout : 'form',
id : 'PhoneGroupForm',
frame : true,
formId : 'PhoneGroupFormId',
defaultType : 'textfield',
items : [ {
name : 'phoneGroup.groupId',
id : 'groupId',
xtype : 'hidden',
value : this.groupId == null ? '' : this.groupId
}, {
fieldLabel : '分组名称*',
name : 'phoneGroup.groupName',
id : 'groupName',
allowBlank:false,
width : 140
}, {
xtype : 'combo',
fieldLabel : '是否共享*',
hiddenName : 'phoneGroup.isShared',
id : 'isShared',
mode : 'local',
editable : false,
triggerAction : 'all',
store : [ [ '0', '是' ], [ '1', '否' ] ],
allowBlank:false,
width : 80
}, {
xtype : 'hidden',
name : 'phoneGroup.sn',
id : 'sn',
width : 80
} ]
});
if (this.groupId != null && this.groupId != 'undefined') {
formPanel.getForm().load(
{
deferredRender : false,
url : __ctxPath + '/communicate/getPhoneGroup.do?groupId='
+ this.groupId,
method : 'post',
waitMsg : '正在载入数据...',
success : function(form, action) {
// Ext.Msg.alert('编辑', '载入成功!');
},
failure : function(form, action) {
// Ext.Msg.alert('编辑', '载入失败');
}
});
}
return formPanel;
};
| JavaScript |
Ext.ns('MailView');
/**
* 邮件列表
*/
var MailView = function() {
}
MailView.prototype.getView=function(){
return new Ext.Panel({
id : 'MailView',
//region:'center',
title : '[收件箱]',
autoScroll : true,
items : [new Ext.FormPanel({
height : 35,
frame : true,
id : 'MailSearchForm',
layout : 'column',
defaults : {
xtype : 'label'
},
items : [{
text : '查询条件:'
},{
text : '邮件标题'
},{
width:80,
xtype : 'textfield',
name : 'Q_mail.subject_S_LK'
},{
text : '发件人'
},{
width:80,
xtype : 'textfield',
name : 'Q_mail.sender_S_LK'
},{
text : '收件人'
},{
width:80,
xtype : 'textfield',
name : 'Q_appUser.fullname_S_LK'
},{
xtype : 'button',
text : '查询',
iconCls : 'search',
handler : function() {
var searchPanel = Ext.getCmp('MailSearchForm');
var grid = Ext.getCmp('MailGrid');
if (searchPanel.getForm().isValid()) {
searchPanel.getForm().submit({
waitMsg : '正在提交查询',
url : __ctxPath
+ '/communicate/listMail.do',
success : function(formPanel, action) {
var result = Ext.util.JSON
.decode(action.response.responseText);
grid.getStore().loadData(result);
}
});
}
}
},{
//这里打算弹出一个windows,多条件查询
xtype : 'button',
text : '高级查询',
iconCls : 'search',
handler : function(){
Ext.Msg.alert('信息','待实现!');
}
}]
}), this.setup()]
});
};
MailView.prototype.setFolderId=function(folderId){
this.folderId=folderId;
MailView.folderId=folderId;
};
MailView.prototype.getFolderId=function(){
return this.folderId;
};
/**
* 建立视图
*/
MailView.prototype.setup = function() {
return this.grid();
};
/**
* 建立DataGrid
*/
MailView.prototype.grid = function() {
var sm = new Ext.grid.CheckboxSelectionModel();
var cm = new Ext.grid.ColumnModel({
columns : [sm, new Ext.grid.RowNumberer(), {
header : 'mailId',
dataIndex : 'mailId',
hidden : true
},
{
header : '优先级',
dataIndex : 'mail',
width:30,
renderer:function(value, metadata, record, rowIndex,colIndex){
var str = '';
//优先级标识
if(value.importantFlag == 2){
str += '<img title="重要" src="'+ __ctxPath +'/images/flag/mail/important.png"/>'
}else if(value.importantFlag == 3){
str += '<img title="非常重要" src="'+ __ctxPath +'/images/flag/mail/veryImportant.png"/>'
}else{
str += '<img title="一般" src="'+ __ctxPath +'/images/flag/mail/common.png"/>'
}
return str;//考虑所有图标都在这里显示
}
},{
header : '阅读',
dataIndex : 'mail',
width:30,
renderer:function(value, metadata, record, rowIndex,colIndex){
var str = '';
//阅读标识
if(value.mailStatus != 0){
if(record.data.readFlag == 0){
str += '<img title="未读" src="'+ __ctxPath +'/images/flag/mail/mail.png"/>'
}else{
str += '<img title="已读" src="'+ __ctxPath +'/images/flag/mail/mail_open.png"/>'
}
}else{//草稿
str += '<img title="草稿" src="'+ __ctxPath +'/images/flag/mail/mail_draft.png"/>'
}
return str ;
}
},{
header : '附件',
dataIndex : 'mail',
width:30,
renderer:function(value, metadata, record, rowIndex,colIndex){
var str = '';
//附件标识
if(value.fileIds !=''){
str += '<img title="附件" src="'+ __ctxPath +'/images/flag/attachment.png"/>'
}
return str ;
}
},{
header : '回复',
dataIndex : 'mail',
width:30,
renderer:function(value, metadata, record, rowIndex,colIndex){
var str = '';
//回复标识
if(record.data.replyFlag == 1){
str += '<img title="已回复" src="'+ __ctxPath +'/images/flag/mail/replyed.png" style="background: white;"/>'
}
return str ;
}
},
{
header : '邮件主题',
dataIndex : 'mail',
renderer:function(value){
return value.subject;
}
},{
header : '发件人',
dataIndex : 'mail',
renderer:function(value){
return value.sender;
}
},{
header : '收件人',
dataIndex : 'mail',
renderer:function(value){
if(value.recipientNames!=''){
return value.recipientNames
}
else{
return '(收信人未写)';
}
}
},
{
header : '发信时间',
dataIndex : 'sendTime'
},{
header : '管理',
dataIndex : 'mail',
width : 50,
renderer : function(value, metadata, record, rowIndex,
colIndex) {
var _folderId = MailView.folderId;
var editId = value.mailId;
var boxId = record.data.boxId;
var status = value.mailStatus;
var str = '<button title="删除" value=" " class="btn-del" onclick="MailView.remove('
+ boxId + ','+_folderId+')"> </button>';
str += ' <button title="查看" value=" " class="btn-mail_link" onclick="MailView.edit('
+ editId + ',' +boxId+ ','+_folderId+','+status+','+rowIndex+')"> </button>';
return str;
}
}],
defaults : {
sortable : true,
menuDisabled : false,
width : 100
}
});
var store = this.store();
store.load({
params : {
start : 0,
limit : 25
}
});
var grid = new Ext.grid.GridPanel({
id : 'MailGrid',
height:390,
tbar : this.topbar(),
store : store,
trackMouseOver : true,
disableSelection : false,
loadMask : true,
//autoHeight : true,
cm : cm,
sm : sm,
viewConfig : {
forceFit : true,
enableRowBody : false,
showPreview : false
},
bbar : new Ext.PagingToolbar({
pageSize : 25,
store : store,
displayInfo : true,
displayMsg : '当前显示从{0}至{1}, 共{2}条记录',
emptyMsg : "当前没有记录"
})
});
grid.addListener('rowdblclick', function(grid, rowIndex, e) {
grid.getSelectionModel().each(function(rec) {
var _folderId = MailView.folderId;
MailView.edit(rec.data.mail.mailId,rec.data.boxId,_folderId,rec.data.mail.mailStatus,rowIndex);
});
});
return grid;
};
/**
* 初始化数据
*/
MailView.prototype.store = function() {
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : __ctxPath + '/communicate/listMail.do'
}),
reader : new Ext.data.JsonReader({
root : 'result',
totalProperty : 'totalCounts',
id : 'id',
fields : [{
name : 'boxId',
type : 'int'
},{
name : 'mailId',
type : 'int'
},{
name : 'delFlag',
type : 'int'
},
{
name : 'readFlag',
type : 'int'
},{
name : 'replyFlag',
type : 'int'
},
'mail',
'appUser',
'mailFolder',
'sendTime',
'note'
]
}),
remoteSort : true
});
store.setDefaultSort('boxId', 'desc');
return store;
};
/**
* 建立操作的Toolbar
*/
MailView.prototype.topbar = function() {
var toolbar = new Ext.Toolbar({
id : 'MailFootBar',
height : 30,
bodyStyle : 'text-align:left',
items : [{
iconCls : 'btn-mail_remove',
text : '删除',
xtype : 'button',
handler : function() {
var grid = Ext.getCmp("MailGrid");
var selectRecords = grid.getSelectionModel()
.getSelections();
if (selectRecords.length == 0) {
Ext.Msg.alert("信息", "请选择要删除的记录!");
return;
}
var ids = Array();
for (var i = 0; i < selectRecords.length; i++) {
ids.push(selectRecords[i].data.boxId);
}
var _folderId = MailView.folderId;
MailView.remove(ids,_folderId);
}
},{
iconCls:'btn-mail_move',
text:'移至',
handler:function(){
var grid = Ext.getCmp("MailGrid");
var selectRecords = grid.getSelectionModel()
.getSelections();
if (selectRecords.length == 0) {
Ext.Msg.alert("信息", "请选择要移动的邮件!");
return;
}
var ids = Array();
for (var i = 0; i < selectRecords.length; i++) {
ids.push(selectRecords[i].data.boxId);
}
MailView.moveTo(ids);
}
},{
iconCls:'btn-mail_refresh',
text:'刷新',
handler:function(){
Ext.getCmp('MailGrid').getStore().reload({params:{start:0,limit:25}});
}
}]
});
return toolbar;
};
/**
* 删除单个记录
*/
MailView.remove = function(_id,_folderId) {
if(_folderId == null || _folderId == 'undefined'){
_folderId = 1;
}
var grid = Ext.getCmp("MailGrid");
var msg = '';
if(_folderId==4){
msg = '删除箱的记录一旦删除,将不可恢复!';
}
Ext.Msg.confirm('信息确认', msg+'您确认要删除该记录吗?', function(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url : __ctxPath
+ '/communicate/multiDelMail.do',
params : {
ids : _id,
folderId:_folderId
},
method : 'post',
success : function() {
Ext.Msg.alert("信息提示", "成功删除所选记录!");
grid.getStore().reload({
params : {
start : 0,
limit : 25
}
});
}
});
var mailCenterView = Ext.getCmp('MailCenterView');
mailCenterView.remove('ShowMailDetail');
var mailView = Ext.getCmp('MailView');
mailView.show();
mailCenterView.doLayout();
}
});
};
/**
* 显示邮件,或载入草稿
*/
MailView.edit = function(mailId,boxId,folderId,status,rowIndex) {
var detailToolbar = new MailView.centerViewToolbar(mailId,boxId,folderId,rowIndex);
if(status == 0){
var tab = Ext.getCmp('centerTabPanel');
var mailForm = Ext.getCmp('MailForm');
if(mailForm==null){
mailForm = new MailForm(mailId,boxId,'draft');
tab.add(mailForm);
tab.activate(mailForm);
}else{
tab.remove(mailForm);
mailForm = new MailForm(mailId,boxId,'draft');
tab.add(mailForm);
tab.activate(mailForm);
}
}else{
var mailCenterView = Ext.getCmp('MailCenterView');
var mailView = Ext.getCmp('MailView');
mailView.hide();
var showDetail = new Ext.Panel({
id:'ShowMailDetail',
title:'[邮件信息]',
tbar:detailToolbar,
autoLoad:{
url:__ctxPath+'/communicate/getMail.do?',
params:{mailId:mailId,boxId:boxId},
method:'Post'
}
})
mailCenterView.add(showDetail);
mailCenterView.doLayout();
}//else
}
/**
* 显示邮件信息时功能栏
* @param {} mailId
* @param {} boxId
* @return {}
*/
MailView.centerViewToolbar = function(mailId,boxId,_folderId,rowIndex){
var toolbar = new Ext.Toolbar({
height : 30,
defaultType : 'button',
bodyStyle : 'text-align:left',
items : [{
iconCls : 'btn-mail_back',
text : '返回',
handler : function() {
var mailCenterView = Ext
.getCmp('MailCenterView');
mailCenterView.remove('ShowMailDetail');
var mailView = Ext.getCmp('MailView');
mailView.show();
mailCenterView.doLayout();
}
},{
iconCls : 'btn-mail_reply',
text : '回复',
handler : function(){
var tab = Ext.getCmp('centerTabPanel');
var mailForm = Ext.getCmp('MailForm');
if(mailForm==null){
mailForm = new MailForm(mailId,boxId,'reply');
tab.add(mailForm);
tab.activate(mailForm);
}else{
tab.remove(mailForm);
mailForm = new MailForm(mailId,boxId,'reply');
tab.add(mailForm);
tab.activate(mailForm);
}
}
},{
iconCls : 'btn-mail_resend',
text : '转发',
handler : function(){
var tab = Ext.getCmp('centerTabPanel');
var mailForm = Ext.getCmp('MailForm');
if(mailForm==null){
mailForm = new MailForm(mailId,boxId,'forward');
tab.add(mailForm);
tab.activate(mailForm);
}else{
tab.remove(mailForm);
mailForm = new MailForm(mailId,boxId,'forward');
tab.add(mailForm);
tab.activate(mailForm);
}
}
},{
iconCls : 'btn-mail_remove',
text : '删除',
handler : function(){
MailView.remove(boxId,_folderId);
}
},{
iconCls : 'btn-mail_move',
text : '移至',
handler : function(){
MailView.moveTo(boxId);
}
},
// {
// iconCls : '',
// text : '更多',//这里给个下拉选择功能,如"打印邮件,下载邮件,保存联系人等等"
// handler : function(){
// Ext.Msg.alert('','待实现!');
// }
// },
'->',{
iconCls : 'btn-up',
text : '较早一封',
handler : function(){
if(rowIndex-1<0){
Ext.Mag.alert('提示信息','这里已经是第一封邮件了!');
}
Ext.Msg.alert('','待实现'+rowIndex);
}
},{
iconCls : 'btn-last',
text : '较老一封',
handler : function(){
Ext.Msg.alert('','待实现'+rowIndex);
}
}]
})
return toolbar;
}
MailView.moveTo = function(id) {
var _moveFormPanel = new MailView.moveFormPanel(id);
var selectFolder = new Ext.Window({
width:300,
height:300,
autoHeight:true,
tilte:'移动邮件',
modal:true,
buttonAlign : 'center',
plain : true,
bodyStyle : 'padding:5px;',
items:[_moveFormPanel],
buttons:[{
text:'确定移动',
handler:function(){
var folderId = Ext.getCmp('folderId');
if(folderId=='' && folderId!=null && folderId!='undefined'){
Ext.Msg.alert('操作信息','请先选择文件夹');
}else{
var moveFolderForm = Ext.getCmp("moveFolderForm");
moveFolderForm.getForm().submit({
waitMsg : '正在提交用户信息',
success : function(moveFolderForm, o) {
//成功之后关闭窗口,显示邮件列表Panel,reload()
Ext.Msg.alert('操作信息', '移动成功!');
selectFolder.close();
var mailCenterView = Ext.getCmp('MailCenterView');
mailCenterView.remove('ShowMailDetail');
var mailView = Ext.getCmp('MailView');
Ext.getCmp('MailGrid').getStore().reload({params:{start:0,limit:25}});
mailView.show();
mailCenterView.doLayout();
},
failure : function(moveFolderForm, o){
//移动失败后提示失败原因
Ext.Msg.alert('提示信息',o.result.msg);
}
});
}
}
},{
text:'取消',
handler:function(){
selectFolder.close();
}
}]
})
selectFolder.show();
};
MailView.moveFormPanel = function(_id){
var treePanel = new Ext.tree.TreePanel({
//id:'',
title:'请选择文件夹',
loader : new Ext.tree.TreeLoader({
url : __ctxPath + '/communicate/listMailFolder.do'
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : function(node){
if(node!=null&&node.id!=0){
Ext.getCmp('dispalyFolderName').setValue(node.text);
Ext.getCmp('folderId').setValue(node.id);
}
}
}
})
var formPanel = new Ext.FormPanel({
url : __ctxPath + '/communicate/moveMail.do',
layout : 'table',
id : 'moveFolderForm',
frame : true,
defaultType : 'textfield',
layoutConfig : {
columns : 1
},
defaults : {
width : 296
},
items : [{
xtype : 'label',
text : '移至:'
}, {
id : 'dispalyFolderName',
readOnly:true
}, {
xtype : 'hidden',
id : 'folderId',
name : 'folderId'
}, {
id : 'boxIds',
name : 'boxIds',
xtype : 'hidden',
value : _id
}, {
xtype : 'panel',
items : [treePanel]
}]
});
return formPanel;
}
| JavaScript |
Ext.ns("MailFolder");
/**
* 个人文档目录视图
*/
var PersonalMailBoxView = function() {
var selectedNode;
var mailView=new MailView();
//var mailBoxView = new MailBoxView();
var treePanel = new Ext.tree.TreePanel({
//region : 'west',
id : 'leftMailBoxTree',
//title : '我的邮箱目录',
//collapsible : true,
split : true,
width : 158,
height : 405,
tbar:new Ext.Toolbar({items:[{
xtype:'button',
iconCls:'btn-refresh',
text:'刷新',
handler:function(){
treePanel.root.reload();
}
},
{
xtype:'button',
text:'展开',
iconCls:'btn-expand',
handler:function(){
treePanel.expandAll();
}
},
{
xtype:'button',
text:'收起',
iconCls:'btn-collapse',
handler:function(){
treePanel.collapseAll();
}
}
]}),
loader : new Ext.tree.TreeLoader({
url : __ctxPath + '/communicate/listMailFolder.do'
}),
root : new Ext.tree.AsyncTreeNode({
expanded : true
}),
rootVisible : false,
listeners : {
'click' : function(node){
if (node != null) {
mailView.setFolderId(node.id);
var mailCenterView = Ext.getCmp('MailCenterView');
var mail = Ext.getCmp('MailView');
var showMailDetail = Ext.getCmp('ShowMailDetail');
if(showMailDetail!=null){
mailCenterView.remove('ShowMailDetail')
mail.show();
mailCenterView.doLayout();
}
if (node.id != 0) {
Ext.getCmp('MailView').setTitle('[' + node.text + ']');
var mailGrid = Ext.getCmp('MailGrid');
var store = mailGrid.getStore();
store.url = __ctxPath+ '/communicate/listMail.do';
store.baseParams = {
folderId : node.id
};
store.reload({
params : {
start : 0,
limit : 25
}
});
}
}
}
}
});
function contextmenu(node, e) {
selectedNode = new Ext.tree.TreeNode({
id : node.id,
text : node.text
});
treeMenu.showAt(e.getXY());
}
//树的右键菜单的
treePanel.on('contextmenu', contextmenu, treePanel);
// 创建右键菜单
var treeMenu = new Ext.menu.Menu({
tbar : new Ext.Toolbar({
items : [{
text : '刷新',
handler : function() {
alert('refresh');
}
}]
}),
id : 'treeMenu',
items : [{
text : '新建目录',
scope : this,
iconCls:'btn-add',
handler : createNode
}, {
text : '修改目录',
scope : this,
iconCls:'btn-edit',
handler : editNode
}, {
text : '删除目录',
scope : this,
iconCls:'btn-delete',
handler : deleteNode
}]
});
//新建目录
function createNode(nodeId) {
var parentId=selectedNode.id;
new MailFolderForm(null,parentId);
};
//编辑目录
function editNode() {
var folderId=selectedNode.id;
if(folderId > 4){//禁止用户对默认文件夹进行修改操作
new MailFolderForm(folderId);
}
};
//删除目录,子目录也一并删除
function deleteNode() {
var folderId=selectedNode.id;
if(folderId > 4){//禁止用户对默认文件夹进行删除操作
Ext.Ajax.request({
url:__ctxPath+'/communicate/countMailFolder.do',
params:{folderId:folderId},
method:'post',
success:function(result,request){
var res = Ext.util.JSON.decode(result.responseText);
if (res.count == 0) {
Ext.Ajax.request({
url : __ctxPath
+ '/communicate/removeMailFolder.do',
params : {
folderId : folderId
},
method : 'post',
success : function(result, request) {
Ext.Msg.alert('操作信息', '成功删除目录!');
treePanel.root.reload();
},
failure : function(result, request) {
Ext.MessageBox.show({
title : '操作信息',
msg : '信息保存出错,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
}
});
}//if count == 0
//文件夹中存在邮件
else{
Ext.Msg.confirm('警告信息','该文件夹及其子目录下还有'+res.count+'封邮件,确定要删除吗?',function(btn){
if(btn == 'yes'){
Ext.Ajax.request({
url : __ctxPath
+ '/communicate/removeMailFolder.do',
params : {
folderId : folderId,
count : res.count
},
method : 'post',
success : function(result, request) {
Ext.Msg.alert('操作信息', '成功删除目录!');
treePanel.root.reload();
},
failure : function(result, request) {
Ext.MessageBox.show({
title : '操作信息',
msg : '信息保存出错,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
}
});
}
});
}
},
failure:function(result,request){
Ext.MessageBox.show({
title : '操作信息',
msg : '信息保存出错,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
}
});
}
};
var leftMailBoxPanel = new Ext.Panel({
//id : 'leftMailBoxPanel',
collapsible : true,
width : 160,
height : 800,
region : 'west',
title : '我的邮箱目录',
autoScroll : true,
items :[new Ext.Container({
layout:'table',
height:23,
layoutConfig:{columns:2},
items:[new Ext.Button({
width:78,
text:'收邮件',
iconCls : 'btn-mail_receive',
handler:function(){//这里把列表显示为收件箱
mailView.setFolderId(1);//收件箱folderId==1
Ext.getCmp('MailView').setTitle('[收件箱]');
var mailGrid = Ext.getCmp('MailGrid');
var store = mailGrid.getStore();
store.url = __ctxPath+ '/communicate/listMail.do';
store.baseParams = {folderId : 1};
store.reload({params : {start : 0,limit : 25}});
}
}),new Ext.Button({
width:79,
text:'发邮件',
iconCls : 'btn-mail_send',
handler:function(){//发邮件功能
var tab = Ext.getCmp('centerTabPanel');
var mailForm = Ext.getCmp('MailForm');
if(mailForm==null){
mailForm = new MailForm('','','');
tab.add(mailForm);
tab.activate(mailForm);
}else{
tab.remove(mailForm);
mailForm = new MailForm('','','');
tab.add(mailForm);
tab.activate(mailForm);
}
}
})]
}),treePanel]
});
var centerPanel = new Ext.Panel({
id : 'MailCenterView',
region:'center',
//title : '[收件箱]',
autoScroll : true,
items:[mailView.getView()]
})
var panel = new Ext.Panel({
title : '我的邮箱',
iconCls:'menu-mail_box',
layout : 'border',
id:'PersonalMailBoxView',
height : 800,
items : [leftMailBoxPanel,centerPanel]
});
return panel;
};
| JavaScript |
var MailFolderForm = function(folderId,parentId) {
this.folderId = folderId;
this.parentId = parentId;
var fp = this.setup();
var window = new Ext.Window({
id : 'MailFolderFormWin',
title : 'MailFolder详细信息',
width : 300,
height : 160,
modal : true,
minWidth : 200,
minHeight : 100,
layout : 'anchor',
plain : true,
bodyStyle : 'padding:5px;',
buttonAlign : 'center',
items : [this.setup()],
buttons : [{
text : '保存',
handler : function() {
var fp = Ext.getCmp('MailFolderForm');
if (fp.getForm().isValid()) {
fp.getForm().submit({
method : 'post',
waitMsg : '正在提交数据...',
success : function(fp, action) {
Ext.Msg.alert('操作信息', '成功信息保存!');
Ext.getCmp('leftMailBoxTree').root.reload();
window.close();
},
failure : function(fp, action) {
Ext.MessageBox.show({
title : '操作信息',
msg : '信息保存出错,请联系管理员!',
buttons : Ext.MessageBox.OK,
icon : 'ext-mb-error'
});
window.close();
}
});
}
}
}, {
text : '取消',
handler : function() {
window.close();
}
}]
});
window.show();
};
MailFolderForm.prototype.setup = function() {
var formPanel = new Ext.FormPanel({
url : __ctxPath + '/communicate/saveMailFolder.do',
layout : 'form',
id : 'MailFolderForm',
frame : true,
defaults : {
widht : 300,
anchor : '100%,100%'
},
formId : 'MailFolderFormId',
defaultType : 'textfield',
items : [
{
name : 'mailFolder.folderId',
id : 'folderId',
xtype : 'hidden',
value : this.folderId == null ? '' : this.folderId
},
{
fieldLabel : '父目录',
name : 'mailFolder.parentId',
xtype:'hidden',
id : 'parentId',
value:this.parentId == null ? '' : this.parentId
},
// {
// fieldLabel : '目录层',
// name : 'mailFolder.level',
// id : 'level',
// xtype:'hidden'
// },
// {
// fieldLabel : '主键',
// name : 'mailFolder.userId',
// id : 'userId'
// },
{
fieldLabel : '文件夹名称',
name : 'mailFolder.folderName',
id : 'folderName'
},{
fieldLabel :'是否共享', //'1=表示共享,则所有的员工均可以使用该文件夹 0=私人文件夹',
hiddenName : 'mailFolder.isPublic',
id : 'isPublic',
xtype:'combo',
mode : 'local',
editable : false,
triggerAction : 'all',
store:[['1','是'], ['0','否']],
value:0
}
// {
// fieldLabel : '文件夹类型 ',//1=收信箱 2=发信箱 3=草稿箱 4=删除箱 10=其他'
// name : 'mailFolder.folderType',
// id : 'folderType'
// }
]
});
if (this.folderId != null && this.folderId != 'undefined') {
formPanel.getForm().load({
deferredRender : false,
url : __ctxPath + '/communicate/getMailFolder.do?folderId='
+ this.folderId,
waitMsg : '正在载入数据...',
success : function(form, action) {
// Ext.Msg.alert('编辑', '载入成功!');
},
failure : function(form, action) {
// Ext.Msg.alert('编辑', '载入失败');
}
});
}
return formPanel;
};
| JavaScript |
Ext.ns('PhoneGroupView');
/**
* TODO: add class/table comments列表
*/
var PhoneGroupView = function() {
return new Ext.Panel({
id : 'PhoneGroupView',
title : '通讯组列表',
autoScroll : true,
items : [new Ext.FormPanel({
height : 35,
frame : true,
id : 'PhoneGroupSearchForm',
layout : 'column',
defaults : {
xtype : 'label'
},
items : [{
text : '请输入查询条件:'
}, {
text : '分组名称'
}, {
xtype : 'textfield',
name : 'Q_groupName_S_LK'
}, {
text : '1=共享0=私有'
}, {
xtype : 'textfield',
name : 'Q_isShared_S_LK'
}, {
text : ''
}, {
xtype : 'textfield',
name : 'Q_SN_S_LK'
}, {
text : ''
}, {
xtype : 'textfield',
name : 'Q_userId_S_LK'
}, {
xtype : 'button',
text : '查询',
iconCls : 'search',
handler : function() {
var searchPanel = Ext
.getCmp('PhoneGroupSearchForm');
var grid = Ext.getCmp('PhoneGroupGrid');
if (searchPanel.getForm().isValid()) {
searchPanel.getForm().submit({
waitMsg : '正在提交查询',
url : __ctxPath
+ '/communicate/listPhoneGroup.do',
success : function(formPanel, action) {
var result = Ext.util.JSON
.decode(action.response.responseText);
grid.getStore().loadData(result);
}
});
}
}
}]
}), this.setup()]
});
};
/**
* 建立视图
*/
PhoneGroupView.prototype.setup = function() {
return this.grid();
};
/**
* 建立DataGrid
*/
PhoneGroupView.prototype.grid = function() {
var sm = new Ext.grid.CheckboxSelectionModel();
var cm = new Ext.grid.ColumnModel({
columns : [sm, new Ext.grid.RowNumberer(), {
header : 'groupId',
dataIndex : 'groupId',
hidden : true
}, {
header : '分组名称',
dataIndex : 'groupName'
}, {
header : '1=共享0=私有',
dataIndex : 'isShared'
}, {
header : '',
dataIndex : 'SN'
}, {
header : '',
dataIndex : 'userId'
}, {
header : '管理',
dataIndex : 'groupId',
width : 50,
renderer : function(value, metadata, record, rowIndex,
colIndex) {
var editId = record.data.groupId;
var str = '<button title="删除" value=" " class="btn-del" onclick="PhoneGroupView.remove('
+ editId + ')"> </button>';
str += ' <button title="编辑" value=" " class="btn-edit" onclick="PhoneGroupView.edit('
+ editId + ')"> </button>';
return str;
}
}],
defaults : {
sortable : true,
menuDisabled : false,
width : 100
}
});
var store = this.store();
store.load({
params : {
start : 0,
limit : 25
}
});
var grid = new Ext.grid.GridPanel({
id : 'PhoneGroupGrid',
tbar : this.topbar(),
store : store,
trackMouseOver : true,
disableSelection : false,
loadMask : true,
autoHeight : true,
cm : cm,
sm : sm,
viewConfig : {
forceFit : true,
enableRowBody : false,
showPreview : false
},
bbar : new Ext.PagingToolbar({
pageSize : 25,
store : store,
displayInfo : true,
displayMsg : '当前显示从{0}至{1}, 共{2}条记录',
emptyMsg : "当前没有记录"
})
});
grid.addListener('rowdblclick', function(grid, rowindex, e) {
grid.getSelectionModel().each(function(rec) {
PhoneGroupView.edit(rec.data.groupId);
});
});
return grid;
};
/**
* 初始化数据
*/
PhoneGroupView.prototype.store = function() {
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : __ctxPath + '/communicate/listPhoneGroup.do'
}),
reader : new Ext.data.JsonReader({
root : 'result',
totalProperty : 'totalCounts',
id : 'id',
fields : [{
name : 'groupId',
type : 'int'
}
, 'groupName', 'isShared', 'SN', 'userId']
}),
remoteSort : true
});
store.setDefaultSort('groupId', 'desc');
return store;
};
/**
* 建立操作的Toolbar
*/
PhoneGroupView.prototype.topbar = function() {
var toolbar = new Ext.Toolbar({
id : 'PhoneGroupFootBar',
height : 30,
bodyStyle : 'text-align:left',
items : [{
iconCls : 'btn-add',
text : '添加PhoneGroup',
xtype : 'button',
handler : function() {
new PhoneGroupForm();
}
}, {
iconCls : 'btn-del',
text : '删除PhoneGroup',
xtype : 'button',
handler : function() {
var grid = Ext.getCmp("PhoneGroupGrid");
var selectRecords = grid.getSelectionModel()
.getSelections();
if (selectRecords.length == 0) {
Ext.Msg.alert("信息", "请选择要删除的记录!");
return;
}
var ids = Array();
for (var i = 0; i < selectRecords.length; i++) {
ids.push(selectRecords[i].data.groupId);
}
PhoneGroupView.remove(ids);
}
}]
});
return toolbar;
};
/**
* 删除单个记录
*/
PhoneGroupView.remove = function(id) {
var grid = Ext.getCmp("PhoneGroupGrid");
Ext.Msg.confirm('信息确认', '您确认要删除该记录吗?', function(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url : __ctxPath
+ '/communicate/multiDelPhoneGroup.do',
params : {
ids : id
},
method : 'post',
success : function() {
Ext.Msg.alert("信息提示", "成功删除所选记录!");
grid.getStore().reload({
params : {
start : 0,
limit : 25
}
});
}
});
}
});
};
/**
*
*/
PhoneGroupView.edit = function(id) {
new PhoneGroupForm(id);
}
| JavaScript |
// Define Button Object
function edButton(id, display, tagStart, tagEnd, access, title, sve, open) {
this.id = id; // used to name the toolbar button
this.display = display; // label on button
this.tagStart = tagStart; // open tag
this.tagEnd = tagEnd; // close tag
this.access = access; // set to -1 if tag does not need to be closed
this.title = title; // sets the title attribute of the button to give 'tool tips'
this.sve = sve; // sve = simple vs. extended. add an 's' to make it show up in the simple toolbar
this.open = open; // set to -1 if tag does not need to be closed
}
var theButtons = new Array();
var edOpenTags = new Array();
theButtons[theButtons.length] = new edButton('ed_strong','str','*','*','b','Bold','s');
theButtons[theButtons.length] = new edButton('ed_emphasis','em','_','_','i','Italicize','s');
theButtons[theButtons.length] = new edButton('ed_underline','u','+','+','u','Underline','s');
theButtons[theButtons.length] = new edButton('ed_strike','S','-','-','s','Strikethrough','s');
theButtons[theButtons.length] = new edButton('ed_ol','OL',' # ','\n',',','Numbered List');
theButtons[theButtons.length] = new edButton('ed_ul','UL',' * ','\n','.','Bulleted List');
theButtons[theButtons.length] = new edButton('ed_p','P','p','\n','p','Paragraph');
theButtons[theButtons.length] = new edButton('ed_h1','h1','h1','\n','1','Header 1');
theButtons[theButtons.length] = new edButton('ed_h2','h2','h2','\n','2','Header 2');
theButtons[theButtons.length] = new edButton('ed_h3','h3','h3','\n','3','Header 3');
theButtons[theButtons.length] = new edButton('ed_h4','h4','h4','\n','4','Header 4');
theButtons[theButtons.length] = new edButton('ed_block','b-quote','bq','\n','q','Blockquote');
theButtons[theButtons.length] = new edButton('ed_outdent','OUT',')','\n',']','Outdent');
theButtons[theButtons.length] = new edButton('ed_indent','IN','(','\n','[','Indent');
theButtons[theButtons.length] = new edButton('ed_justifyl','JL','<','\n','l','Left Justify');
theButtons[theButtons.length] = new edButton('ed_justifyc','JC','=','\n','e','Center Text');
theButtons[theButtons.length] = new edButton('ed_justifyr','JR','>','\n','r','Right Justify');
theButtons[theButtons.length] = new edButton('ed_justify','J','<>','\n','j','Justify');
/*
theButtons[theButtons.length] = new edButton('ed_code','code','@','@','c','Code');
*/ | JavaScript |
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
| JavaScript |
/**
* WYSIWYG HTML Editor for Internet
*
* @author Roddy <luolonghao@gmail.com>
* @version 2.5.3
*/
var KE_VERSION = "2.5.4";
var KE_EDITOR_TYPE = "full"; //full or simple
var KE_SAFE_MODE = false; // true or false
var KE_UPLOAD_MODE = true; // true or false
var KE_FONT_FAMILY = "Courier New";
var KE_WIDTH = "700px";
var KE_HEIGHT = "400px";
var KE_SITE_DOMAIN = "";
var KE_SKIN_PATH = "./skins/default/";
var KE_ICON_PATH = "./icons/";
var KE_IMAGE_ATTACH_PATH = "./attached/";
var KE_IMAGE_UPLOAD_CGI = "./upload_cgi/upload.php";
var KE_CSS_PATH = "/editor/common.css";
var KE_MENU_BORDER_COLOR = '#AAAAAA';
var KE_MENU_BG_COLOR = '#EFEFEF';
var KE_MENU_TEXT_COLOR = '#222222';
var KE_MENU_SELECTED_COLOR = '#CCCCCC';
var KE_TOOLBAR_BORDER_COLOR = '#DDDDDD';
var KE_TOOLBAR_BG_COLOR = '#EFEFEF';
var KE_FORM_BORDER_COLOR = '#DDDDDD';
var KE_FORM_BG_COLOR = '#FFFFFF';
var KE_BUTTON_COLOR = '#AAAAAA';
var KE_LANG = {
INPUT_URL : "请输入正确的URL地址。",
SELECT_IMAGE : "请选择图片。",
INVALID_IMAGE : "只能选择GIF,JPG,PNG,BMP格式的图片,请重新选择。",
INVALID_FLASH : "只能选择SWF格式的文件,请重新选择。",
INVALID_MEDIA : "只能选择MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF格式的文件,请重新选择。",
INVALID_REAL : "只能选择RM,RMVB格式的文件,请重新选择。",
INVALID_WIDTH : "宽度不是数字,请重新输入。",
INVALID_HEIGHT : "高度不是数字,请重新输入。",
INVALID_BORDER : "边框不是数字,请重新输入。",
INVALID_HSPACE : "横隔不是数字,请重新输入。",
INVALID_VSPACE : "竖隔不是数字,请重新输入。",
INPUT_CONTENT : "请输入内容",
TITLE : "描述",
WIDTH : "宽",
HEIGHT : "高",
BORDER : "边",
ALIGN : "对齐方式",
HSPACE : "横隔",
VSPACE : "竖隔",
CONFIRM : "确定",
CANCEL : "取消",
PREVIEW : "预览",
LISTENING : "试听",
LOCAL : "本地",
REMOTE : "远程",
NEW_WINDOW : "新窗口",
CURRENT_WINDOW : "当前窗口",
TARGET : "目标",
ABOUT : "访问技术支持网站",
SUBJECT : "标题"
}
var KE_FONT_NAME = Array(
Array('SimSun', '宋体'),
Array('SimHei', '黑体'),
Array('FangSong_GB2312', '仿宋体'),
Array('KaiTi_GB2312', '楷体'),
Array('NSimSun', '新宋体'),
Array('Arial', 'Arial'),
Array('Arial Black', 'Arial Black'),
Array('Times New Roman', 'Times New Roman'),
Array('Courier New', 'Courier New'),
Array('Tahoma', 'Tahoma'),
Array('Verdana', 'Verdana'),
Array('GulimChe', 'GulimChe'),
Array('MS Gothic', 'MS Gothic')
);
var KE_SPECIAL_CHARACTER = Array(
'§','№','☆','★','○','●','◎','◇','◆','□','℃','‰','■','△','▲','※',
'→','←','↑','↓','〓','¤','°','#','&','@','\','︿','_',' ̄','―','α',
'β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ',
'σ','τ','υ','φ','χ','ψ','ω','≈','≡','≠','=','≤','≥','<','>','≮',
'≯','∷','±','+','-','×','÷','/','∫','∮','∝','∞','∧','∨','∑','∏',
'∪','∩','∈','∵','∴','⊥','∥','∠','⌒','⊙','≌','∽','〖','〗',
'【','】','(',')','[',']'
);
var KE_TOP_TOOLBAR_ICON = Array(
Array('KE_SOURCE', 'source.gif', '视图转换'),
Array('KE_PREVIEW', 'preview.gif', '预览'),
Array('KE_ZOOM', 'zoom.gif', '显示比例'),
Array('KE_PRINT', 'print.gif', '打印'),
Array('KE_UNDO', 'undo.gif', '回退'),
Array('KE_REDO', 'redo.gif', '前进'),
Array('KE_CUT', 'cut.gif', '剪切'),
Array('KE_COPY', 'copy.gif', '复制'),
Array('KE_PASTE', 'paste.gif', '粘贴'),
Array('KE_SELECTALL', 'selectall.gif', '全选'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_JUSTIFYFULL', 'justifyfull.gif', '两端对齐'),
Array('KE_NUMBEREDLIST', 'numberedlist.gif', '编号'),
Array('KE_UNORDERLIST', 'unorderedlist.gif', '项目符号'),
Array('KE_INDENT', 'indent.gif', '减少缩进'),
Array('KE_OUTDENT', 'outdent.gif', '增加缩进'),
Array('KE_SUBSCRIPT', 'subscript.gif', '下标'),
Array('KE_SUPERSCRIPT', 'superscript.gif', '上标'),
Array('KE_DATE', 'date.gif', '日期'),
Array('KE_TIME', 'time.gif', '时间')
);
var KE_BOTTOM_TOOLBAR_ICON = Array(
Array('KE_TITLE', 'title.gif', '标题'),
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_STRIKE', 'strikethrough.gif', '删除线'),
Array('KE_REMOVE', 'removeformat.gif', '删除格式'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_FLASH', 'flash.gif', 'Flash'),
Array('KE_MEDIA', 'media.gif', 'Windows Media Player'),
Array('KE_REAL', 'real.gif', 'Real Player'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_TABLE', 'table.gif', '表格'),
Array('KE_SPECIALCHAR', 'specialchar.gif', '特殊字符'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_UNLINK', 'unlink.gif', '删除超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_SIMPLE_TOOLBAR_ICON = Array(
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_TITLE_TABLE = Array(
Array('H1', KE_LANG['SUBJECT'] + ' 1'),
Array('H2', KE_LANG['SUBJECT'] + ' 2'),
Array('H3', KE_LANG['SUBJECT'] + ' 3'),
Array('H4', KE_LANG['SUBJECT'] + ' 4'),
Array('H5', KE_LANG['SUBJECT'] + ' 5'),
Array('H6', KE_LANG['SUBJECT'] + ' 6')
);
var KE_ZOOM_TABLE = Array('250%', '200%', '150%', '120%', '100%', '80%', '50%');
var KE_FONT_SIZE = Array(
Array(1,'8pt'),
Array(2,'10pt'),
Array(3,'12pt'),
Array(4,'14pt'),
Array(5,'18pt'),
Array(6,'24pt'),
Array(7,'36pt')
);
var KE_POPUP_MENU_TABLE = Array(
"KE_ZOOM", "KE_TITLE", "KE_FONTNAME", "KE_FONTSIZE", "KE_TEXTCOLOR", "KE_BGCOLOR",
"KE_LAYER", "KE_TABLE", "KE_HR", "KE_ICON", "KE_SPECIALCHAR", "KE_ABOUT",
"KE_IMAGE", "KE_FLASH", "KE_MEDIA", "KE_REAL", "KE_LINK"
);
var KE_COLOR_TABLE = Array(
"#FF0000", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#FF00FF", "#FFFFFF", "#F5F5F5", "#DCDCDC", "#FFFAFA",
"#D3D3D3", "#C0C0C0", "#A9A9A9", "#808080", "#696969", "#000000", "#2F4F4F", "#708090", "#778899", "#4682B4",
"#4169E1", "#6495ED", "#B0C4DE", "#7B68EE", "#6A5ACD", "#483D8B", "#191970", "#000080", "#00008B", "#0000CD",
"#1E90FF", "#00BFFF", "#87CEFA", "#87CEEB", "#ADD8E6", "#B0E0E6", "#F0FFFF", "#E0FFFF", "#AFEEEE", "#00CED1",
"#5F9EA0", "#48D1CC", "#00FFFF", "#40E0D0", "#20B2AA", "#008B8B", "#008080", "#7FFFD4", "#66CDAA", "#8FBC8F",
"#3CB371", "#2E8B57", "#006400", "#008000", "#228B22", "#32CD32", "#00FF00", "#7FFF00", "#7CFC00", "#ADFF2F",
"#98FB98", "#90EE90", "#00FF7F", "#00FA9A", "#556B2F", "#6B8E23", "#808000", "#BDB76B", "#B8860B", "#DAA520",
"#FFD700", "#F0E68C", "#EEE8AA", "#FFEBCD", "#FFE4B5", "#F5DEB3", "#FFDEAD", "#DEB887", "#D2B48C", "#BC8F8F",
"#A0522D", "#8B4513", "#D2691E", "#CD853F", "#F4A460", "#8B0000", "#800000", "#A52A2A", "#B22222", "#CD5C5C",
"#F08080", "#FA8072", "#E9967A", "#FFA07A", "#FF7F50", "#FF6347", "#FF8C00", "#FFA500", "#FF4500", "#DC143C",
"#FF0000", "#FF1493", "#FF00FF", "#FF69B4", "#FFB6C1", "#FFC0CB", "#DB7093", "#C71585", "#800080", "#8B008B",
"#9370DB", "#8A2BE2", "#4B0082", "#9400D3", "#9932CC", "#BA55D3", "#DA70D6", "#EE82EE", "#DDA0DD", "#D8BFD8",
"#E6E6FA", "#F8F8FF", "#F0F8FF", "#F5FFFA", "#F0FFF0", "#FAFAD2", "#FFFACD", "#FFF8DC", "#FFFFE0", "#FFFFF0",
"#FFFAF0", "#FAF0E6", "#FDF5E6", "#FAEBD7", "#FFE4C4", "#FFDAB9", "#FFEFD5", "#FFF5EE", "#FFF0F5", "#FFE4E1"
);
var KE_IMAGE_ALIGN_TABLE = Array(
"baseline", "top", "middle", "bottom", "texttop", "absmiddle", "absbottom", "left", "right"
);
var KE_OBJ_NAME;
var KE_SELECTION;
var KE_RANGE;
var KE_RANGE_TEXT;
var KE_EDITFORM_DOCUMENT;
var KE_IMAGE_DOCUMENT;
var KE_FLASH_DOCUMENT;
var KE_MEDIA_DOCUMENT;
var KE_REAL_DOCUMENT;
var KE_LINK_DOCUMENT;
var KE_BROWSER;
var KE_TOOLBAR_ICON;
function KindGetBrowser()
{
var browser = '';
var agentInfo = navigator.userAgent.toLowerCase();
if (agentInfo.indexOf("msie") > -1) {
var re = new RegExp("msie\\s?([\\d\\.]+)","ig");
var arr = re.exec(agentInfo);
if (parseInt(RegExp.$1) >= 5.5) {
browser = 'IE';
}
} else if (agentInfo.indexOf("firefox") > -1) {
browser = 'FF';
} else if (agentInfo.indexOf("netscape") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[temp1.length-1].split('/');
if (parseInt(temp2[1]) >= 7) {
browser = 'NS';
}
} else if (agentInfo.indexOf("gecko") > -1) {
browser = 'ML';
} else if (agentInfo.indexOf("opera") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[0].split('/');
if (parseInt(temp2[1]) >= 9) {
browser = 'OPERA';
}
}
return browser;
}
function KindGetFileName(file, separator)
{
var temp = file.split(separator);
var len = temp.length;
var fileName = temp[len-1];
return fileName;
}
function KindGetFileExt(fileName)
{
var temp = fileName.split(".");
var len = temp.length;
var fileExt = temp[len-1].toLowerCase();
return fileExt;
}
function KindCheckImageFileType(file, separator)
{
if (separator == "/" && file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, separator);
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'gif' && fileExt != 'jpg' && fileExt != 'png' && fileExt != 'bmp') {
alert(KE_LANG['INVALID_IMAGE']);
return false;
}
return true;
}
function KindCheckFlashFileType(file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'swf') {
alert(KE_LANG['INVALID_FLASH']);
return false;
}
return true;
}
function KindCheckMediaFileType(cmd, file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (cmd == 'KE_REAL') {
if (fileExt != 'rm' && fileExt != 'rmvb') {
alert(KE_LANG['INVALID_REAL']);
return false;
}
} else {
if (fileExt != 'mp3' && fileExt != 'wav' && fileExt != 'wma' && fileExt != 'wmv' && fileExt != 'mid' && fileExt != 'avi' && fileExt != 'mpg' && fileExt != 'asf') {
alert(KE_LANG['INVALID_MEDIA']);
return false;
}
}
return true;
}
function KindHtmlToXhtml(str)
{
str = str.replace(/<br.*?>/gi, "<br />");
str = str.replace(/(<hr\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<img\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<\w+)(.*?>)/gi, function ($0,$1,$2) {
return($1.toLowerCase() + KindConvertAttribute($2));
}
);
str = str.replace(/(<\/\w+>)/gi, function ($0,$1) {
return($1.toLowerCase());
}
);
return str;
}
function KindConvertAttribute(str)
{
if (KE_SAFE_MODE == true) {
str = KindClearAttributeScriptTag(str);
}
return str;
}
function KindClearAttributeScriptTag(str)
{
var re = new RegExp("(\\son[a-z]+=)[\"']?[^>]*?[^\\\\\>][\"']?([\\s>])","ig");
str = str.replace(re, function ($0,$1,$2) {
return($1.toLowerCase() + "\"\"" + $2);
}
);
return str;
}
function KindClearScriptTag(str)
{
if (KE_SAFE_MODE == false) {
return str;
}
str = str.replace(/<(script.*?)>/gi, "[$1]");
str = str.replace(/<\/script>/gi, "[/script]");
return str;
}
function KindHtmlentities(str)
{
str = str.replace(/&/g,'&');
str = str.replace(/</g,'<');
str = str.replace(/>/g,'>');
str = str.replace(/"/g,'"');
return str;
}
function KindGetTop(id)
{
var top = 28;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
top += eval("obj" + tmp).offsetTop;
}
return top;
}
function KindGetLeft(id)
{
var left = 2;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
left += eval("obj" + tmp).offsetLeft;
}
return left;
}
function KindDisplayMenu(cmd)
{
KindEditorForm.focus();
if (cmd != 'KE_ABOUT') {
KindSelection();
}
KindDisableMenu();
var top, left;
top = KindGetTop(cmd);
left = KindGetLeft(cmd);
if (cmd == 'KE_ABOUT') {
left -= 200;
} else if (cmd == 'KE_LINK') {
left -= 220;
}
document.getElementById('POPUP_'+cmd).style.top = top.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.left = left.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.display = 'block';
}
function KindDisableMenu()
{
for (i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
document.getElementById('POPUP_'+KE_POPUP_MENU_TABLE[i]).style.display = 'none';
}
}
function KindReloadIframe()
{
var str = '';
str += KindPopupMenu('KE_IMAGE');
str += KindPopupMenu('KE_FLASH');
str += KindPopupMenu('KE_MEDIA');
str += KindPopupMenu('KE_REAL');
document.getElementById('InsertIframe').innerHTML = str;
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
}
function KindGetMenuCommonStyle()
{
var str = 'position:absolute;top:1px;left:1px;font-size:12px;color:'+KE_MENU_TEXT_COLOR+
';background-color:'+KE_MENU_BG_COLOR+';border:solid 1px '+KE_MENU_BORDER_COLOR+';z-index:1;display:none;';
return str;
}
function KindGetCommonMenu(cmd, content)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="'+KindGetMenuCommonStyle()+'">';
str += content;
str += '</div>';
return str;
}
function KindCreateColorTable(cmd, eventStr)
{
var str = '';
str += '<table cellpadding="0" cellspacing="2" border="0">';
for (i = 0; i < KE_COLOR_TABLE.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="width:12px;height:12px;border:1px solid #AAAAAA;font-size:1px;cursor:pointer;background-color:' +
KE_COLOR_TABLE[i] + ';" onmouseover="javascript:this.style.borderColor=\'#000000\';' + ((eventStr) ? eventStr : '') + '" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onclick="javascript:KindExecute(\''+cmd+'_END\', \'' + KE_COLOR_TABLE[i] + '\');"> </td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
}
function KindDrawColorTable(cmd)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;padding:2px;'+KindGetMenuCommonStyle()+'">';
str += KindCreateColorTable(cmd);
str += '</div>';
return str;
}
function KindDrawMedia(cmd)
{
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="'+cmd+'preview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="'+cmd+'link" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['LISTENING']+'" onclick="javascript:parent.KindMediaPreview(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawMediaEnd(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
return str;
}
function KindPopupMenu(cmd)
{
switch (cmd)
{
case 'KE_ZOOM':
var str = '';
for (i = 0; i < KE_ZOOM_TABLE.length; i++) {
str += '<div style="padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ZOOM_END\', \'' + KE_ZOOM_TABLE[i] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_ZOOM_TABLE[i] + '</div>';
}
str = KindGetCommonMenu('KE_ZOOM', str);
return str;
break;
case 'KE_TITLE':
var str = '';
for (i = 0; i < KE_TITLE_TABLE.length; i++) {
str += '<div style="width:140px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TITLE_END\', \'' + KE_TITLE_TABLE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';"><' + KE_TITLE_TABLE[i][0] + ' style="margin:2px;">' +
KE_TITLE_TABLE[i][1] + '</' + KE_TITLE_TABLE[i][0] + '></div>';
}
str = KindGetCommonMenu('KE_TITLE', str);
return str;
break;
case 'KE_FONTNAME':
var str = '';
for (i = 0; i < KE_FONT_NAME.length; i++) {
str += '<div style="font-family:' + KE_FONT_NAME[i][0] +
';padding:2px;width:160px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTNAME_END\', \'' + KE_FONT_NAME[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_NAME[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTNAME', str);
return str;
break;
case 'KE_FONTSIZE':
var str = '';
for (i = 0; i < KE_FONT_SIZE.length; i++) {
str += '<div style="font-size:' + KE_FONT_SIZE[i][1] +
';padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTSIZE_END\', \'' + KE_FONT_SIZE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_SIZE[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTSIZE', str);
return str;
break;
case 'KE_TEXTCOLOR':
var str = '';
str = KindDrawColorTable('KE_TEXTCOLOR');
return str;
break;
case 'KE_BGCOLOR':
var str = '';
str = KindDrawColorTable('KE_BGCOLOR');
return str;
break;
case 'KE_HR':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="hrPreview" style="margin:10px 2px 10px 2px;height:1px;border:0;font-size:0;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'hrPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_LAYER':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="divPreview" style="margin:5px 2px 5px 2px;height:20px;border:1px solid #AAAAAA;font-size:1px;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'divPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_ICON':
var str = '';
var iconNum = 36;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < iconNum; i++) {
if (i == 0 || (i >= 6 && i%6 == 0)) {
str += '<tr>';
}
var num;
if ((i+1).toString(10).length < 2) {
num = '0' + (i+1);
} else {
num = (i+1).toString(10);
}
var iconUrl = KE_ICON_PATH + 'etc_' + num + '.gif';
str += '<td style="padding:2px;border:0;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ICON_END\', \'' + iconUrl + '\');">' +
'<img src="' + iconUrl + '" style="border:1px solid #EEEEEE;" onmouseover="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#EEEEEE\';">' + '</td>';
if (i >= 5 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_SPECIALCHAR':
var str = '';
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < KE_SPECIAL_CHARACTER.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="padding:2px;border:1px solid #AAAAAA;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_SPECIALCHAR_END\', \'' + KE_SPECIAL_CHARACTER[i] + '\');" ' +
'onmouseover="javascript:this.style.borderColor=\'#000000\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';">' + KE_SPECIAL_CHARACTER[i] + '</td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_TABLE':
var str = '';
var num = 10;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="0" style="'+KindGetMenuCommonStyle()+'">';
for (i = 1; i <= num; i++) {
str += '<tr>';
for (j = 1; j <= num; j++) {
var value = i.toString(10) + ',' + j.toString(10);
str += '<td id="kindTableTd' + i.toString(10) + '_' + j.toString(10) +
'" style="width:15px;height:15px;background-color:#FFFFFF;border:1px solid #DDDDDD;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TABLE_END\', \'' + value + '\');" ' +
'onmouseover="javascript:KindDrawTableSelected(\''+i.toString(10)+'\', \''+j.toString(10)+'\');" ' +
'onmouseout="javascript:;"> </td>';
}
str += '</tr>';
}
str += '<tr><td colspan="10" id="tableLocation" style="text-align:center;height:20px;"></td></tr>';
str += '</table>';
return str;
break;
case 'KE_IMAGE':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindImageIframe" id="KindImageIframe" frameborder="0" style="width:250px;height:390px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_FLASH':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindFlashIframe" id="KindFlashIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_MEDIA':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindMediaIframe" id="KindMediaIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_REAL':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindRealIframe" id="KindRealIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_LINK':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindLinkIframe" id="KindLinkIframe" frameborder="0" style="width:250px;height:85px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_ABOUT':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:230px;'+KindGetMenuCommonStyle()+';padding:5px;">';
str += '<span style="margin-right:10px;">KindEditor ' + KE_VERSION + '</span>' +
'<a href="http://www.kindsoft.net/" target="_blank" style="color:#4169e1;" onclick="javascript:KindDisableMenu();">'+KE_LANG['ABOUT']+'</a><br />';
str += '</div>';
return str;
break;
default:
break;
}
}
function KindDrawIframe(cmd)
{
if (KE_BROWSER == 'IE') {
KE_IMAGE_DOCUMENT = document.frames("KindImageIframe").document;
KE_FLASH_DOCUMENT = document.frames("KindFlashIframe").document;
KE_MEDIA_DOCUMENT = document.frames("KindMediaIframe").document;
KE_REAL_DOCUMENT = document.frames("KindRealIframe").document;
KE_LINK_DOCUMENT = document.frames("KindLinkIframe").document;
} else {
KE_IMAGE_DOCUMENT = document.getElementById('KindImageIframe').contentDocument;
KE_FLASH_DOCUMENT = document.getElementById('KindFlashIframe').contentDocument;
KE_MEDIA_DOCUMENT = document.getElementById('KindMediaIframe').contentDocument;
KE_REAL_DOCUMENT = document.getElementById('KindRealIframe').contentDocument;
KE_LINK_DOCUMENT = document.getElementById('KindLinkIframe').contentDocument;
}
switch (cmd)
{
case 'KE_IMAGE':
var str = '';
str += '<div align="center">' +
'<form name="uploadForm" style="margin:0;padding:0;" method="post" enctype="multipart/form-data" ' +
'action="' + KE_IMAGE_UPLOAD_CGI + '" onsubmit="javascript:if(parent.KindDrawImageEnd()==false){return false;};">' +
'<input type="hidden" name="fileName" id="fileName" value="" />' +
'<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0" style="margin-bottom:3px;"><tr><td id="imgPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:50px;padding-left:5px;">';
if (KE_UPLOAD_MODE == true) {
str += '<select id="imageType" onchange="javascript:parent.KindImageType(this.value);document.getElementById(\''+cmd+'submitButton\').focus();"><option value="1" selected="selected">'+KE_LANG['LOCAL']+'</option><option value="2">'+KE_LANG['REMOTE']+'</option></select>';
} else {
str += KE_LANG['REMOTE'];
}
str += '</td><td style="width:200px;padding-bottom:3px;">';
if (KE_UPLOAD_MODE == true) {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;display:none;" />' +
'<input type="file" name="fileData" id="imgFile" size="14" style="border:1px solid #555555;" onclick="javascript:document.getElementById(\'imgLink\').value=\'http://\';" />';
} else {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;" />' +
'<input type="hidden" name="imageType" id="imageType" value="2"><input type="hidden" name="fileData" id="imgFile" value="" />';
}
str += '</td></tr><tr><td colspan="2" style="padding-bottom:3px;">' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="18%" style="padding:2px 2px 2px 5px;">'+KE_LANG['TITLE']+'</td><td width="82%"><input type="text" name="imgTitle" id="imgTitle" value="" maxlength="100" style="width:95%;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="10%" style="padding:2px 2px 2px 5px;">'+KE_LANG['WIDTH']+'</td><td width="23%"><input type="text" name="imgWidth" id="imgWidth" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['HEIGHT']+'</td><td width="23%"><input type="text" name="imgHeight" id="imgHeight" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['BORDER']+'</td><td width="23%"><input type="text" name="imgBorder" id="imgBorder" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="39%" style="padding:2px 2px 2px 5px;"><select id="imgAlign" name="imgAlign"><option value="">'+KE_LANG['ALIGN']+'</option>';
for (var i = 0; i < KE_IMAGE_ALIGN_TABLE.length; i++) {
str += '<option value="' + KE_IMAGE_ALIGN_TABLE[i] + '">' + KE_IMAGE_ALIGN_TABLE[i] + '</option>';
}
str += '</select></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['HSPACE']+'</td><td width="15%"><input type="text" name="imgHspace" id="imgHspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['VSPACE']+'</td><td width="15%"><input type="text" name="imgVspace" id="imgVspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'</td></tr><tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindImagePreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table></form></div>';
KindDrawMenuIframe(KE_IMAGE_DOCUMENT, str);
break;
case 'KE_FLASH':
var str = '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="flashPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="flashLink" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindFlashPreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawFlashEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
KindDrawMenuIframe(KE_FLASH_DOCUMENT, str);
break;
case 'KE_MEDIA':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_MEDIA_DOCUMENT, str);
break;
case 'KE_REAL':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_REAL_DOCUMENT, str);
break;
case 'KE_LINK':
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td style="width:50px;padding:5px;">URL</td>' +
'<td style="width:200px;padding-top:5px;padding-bottom:5px;"><input type="text" id="hyperLink" value="http://" style="width:190px;border:1px solid #555555;background-color:#FFFFFF;"></td>' +
'<tr><td style="padding:5px;">'+KE_LANG['TARGET']+'</td>' +
'<td style="padding-bottom:5px;"><select id="hyperLinkTarget"><option value="_blank" selected="selected">'+KE_LANG['NEW_WINDOW']+'</option><option value="">'+KE_LANG['CURRENT_WINDOW']+'</option></select></td></tr>' +
'<tr><td colspan="2" style="padding-bottom:5px;" align="center">' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawLinkEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>';
str += '</table>';
KindDrawMenuIframe(KE_LINK_DOCUMENT, str);
break;
default:
break;
}
}
function KindDrawMenuIframe(obj, str)
{
obj.open();
obj.write(str);
obj.close();
obj.body.style.color = KE_MENU_TEXT_COLOR;
obj.body.style.backgroundColor = KE_MENU_BG_COLOR;
obj.body.style.margin = 0;
obj.body.scroll = 'no';
}
function KindDrawTableSelected(i, j)
{
var text = i.toString(10) + ' by ' + j.toString(10) + ' Table';
document.getElementById('tableLocation').innerHTML = text;
var num = 10;
for (m = 1; m <= num; m++) {
for (n = 1; n <= num; n++) {
var obj = document.getElementById('kindTableTd' + m.toString(10) + '_' + n.toString(10) + '');
if (m <= i && n <= j) {
obj.style.backgroundColor = KE_MENU_SELECTED_COLOR;
} else {
obj.style.backgroundColor = '#FFFFFF';
}
}
}
}
function KindImageType(type)
{
if (type == 1) {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'block';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').value = 'http://';
} else {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'block';
}
KE_IMAGE_DOCUMENT.getElementById('imgPreview').innerHTML = " ";
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = 0;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = 0;
}
function KindImagePreview()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
if (type == 1) {
if (KE_BROWSER != 'IE') {
return false;
}
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
url = 'file:///' + file;
if (KindCheckImageFileType(url, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
var imgObj = KE_IMAGE_DOCUMENT.createElement("IMG");
imgObj.src = url;
var width = parseInt(imgObj.width);
var height = parseInt(imgObj.height);
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = width;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = height;
var rate = parseInt(width/height);
if (width >230 && height <= 230) {
width = 230;
height = parseInt(width/rate);
} else if (width <=230 && height > 230) {
height = 230;
width = parseInt(height*rate);
} else if (width >230 && height > 230) {
if (width >= height) {
width = 230;
height = parseInt(width/rate);
} else {
height = 230;
width = parseInt(height*rate);
}
}
imgObj.style.width = width;
imgObj.style.height = height;
var el = KE_IMAGE_DOCUMENT.getElementById('imgPreview');
if (el.hasChildNodes()) {
el.removeChild(el.childNodes[0]);
}
el.appendChild(imgObj);
return imgObj;
}
function KindDrawImageEnd()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
var width = KE_IMAGE_DOCUMENT.getElementById('imgWidth').value;
var height = KE_IMAGE_DOCUMENT.getElementById('imgHeight').value;
var border = KE_IMAGE_DOCUMENT.getElementById('imgBorder').value;
var title = KE_IMAGE_DOCUMENT.getElementById('imgTitle').value;
var align = KE_IMAGE_DOCUMENT.getElementById('imgAlign').value;
var hspace = KE_IMAGE_DOCUMENT.getElementById('imgHspace').value;
var vspace = KE_IMAGE_DOCUMENT.getElementById('imgVspace').value;
if (type == 1) {
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
if (KindCheckImageFileType(file, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
if (width.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_WIDTH']);
return false;
}
if (height.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HEIGHT']);
return false;
}
if (border.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_BORDER']);
return false;
}
if (hspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HSPACE']);
return false;
}
if (vspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_VSPACE']);
return false;
}
var fileName;
KindEditorForm.focus();
if (type == 1) {
fileName = KindGetFileName(file, "\\");
var fileExt = KindGetFileExt(fileName);
var dateObj = new Date();
var year = dateObj.getFullYear().toString(10);
var month = (dateObj.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = dateObj.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var ymd = year + month + day;
fileName = ymd + dateObj.getTime().toString(10) + '.' + fileExt;
KE_IMAGE_DOCUMENT.getElementById('fileName').value = fileName;
} else {
KindInsertImage(url, width, height, border, title, align, hspace, vspace);
}
}
function KindInsertImage(url, width, height, border, title, align, hspace, vspace)
{
var element = document.createElement("img");
element.src = url;
if (width > 0) {
element.style.width = width;
}
if (height > 0) {
element.style.height = height;
}
if (align != "") {
element.align = align;
}
if (hspace > 0) {
element.hspace = hspace;
}
if (vspace > 0) {
element.vspace = vspace;
}
element.border = border;
element.alt = KindHtmlentities(title);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
KindReloadIframe();
}
function KindGetFlashHtmlTag(url)
{
var str = '<embed src="'+url+'" type="application/x-shockwave-flash" quality="high"></embed>';
return str;
}
function KindFlashPreview()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
var el = KE_FLASH_DOCUMENT.getElementById('flashPreview');
el.innerHTML = KindGetFlashHtmlTag(url);
}
function KindDrawFlashEnd()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
obj.type = "application/x-shockwave-flash";
obj.quality = "high";
KindInsertItem(obj);
KindDisableMenu();
}
function KindGetMediaHtmlTag(cmd, url)
{
var str = '<embed src="'+url+'" type="';
if (cmd == "KE_REAL") {
str += 'audio/x-pn-realaudio-plugin';
} else {
str += 'video/x-ms-asf-plugin';
}
str += '" width="230" height="230" loop="true" autostart="true">';
return str;
}
function KindMediaPreview(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
var el = mediaDocument.getElementById(cmd+'preview');
el.innerHTML = KindGetMediaHtmlTag(cmd, url);
}
function KindDrawMediaEnd(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
if (cmd == 'KE_REAL') {
obj.type = 'audio/x-pn-realaudio-plugin';
} else {
obj.type = 'video/x-ms-asf-plugin';
}
obj.loop = 'true';
obj.autostart = 'true';
KindInsertItem(obj);
KindDisableMenu(cmd);
}
function KindDrawLinkEnd()
{
var range;
var url = KE_LINK_DOCUMENT.getElementById('hyperLink').value;
var target = KE_LINK_DOCUMENT.getElementById('hyperLinkTarget').value;
if (url.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
KindEditorForm.focus();
KindSelect();
var element;
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
var el = document.createElement("a");
el.href = url;
if (target) {
el.target = target;
}
KE_RANGE.item(0).applyElement(el);
} else if (KE_SELECTION.type.toLowerCase() == 'text') {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.parentElement();
if (target) {
element.target = target;
}
}
} else {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.startContainer.previousSibling;
element.target = target;
if (target) {
element.target = target;
}
}
KindDisableMenu();
}
function KindSelection()
{
if (KE_BROWSER == 'IE') {
KE_SELECTION = KE_EDITFORM_DOCUMENT.selection;
KE_RANGE = KE_SELECTION.createRange();
KE_RANGE_TEXT = KE_RANGE.text;
} else {
KE_SELECTION = document.getElementById("KindEditorForm").contentWindow.getSelection();
KE_RANGE = KE_SELECTION.getRangeAt(0);
KE_RANGE_TEXT = KE_RANGE.toString();
}
}
function KindSelect()
{
if (KE_BROWSER == 'IE') {
KE_RANGE.select();
}
}
function KindInsertItem(insertNode)
{
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
KE_RANGE.item(0).outerHTML = insertNode.outerHTML;
} else {
KE_RANGE.pasteHTML(insertNode.outerHTML);
}
} else {
KE_SELECTION.removeAllRanges();
KE_RANGE.deleteContents();
var startRangeNode = KE_RANGE.startContainer;
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
if (startRangeNode.nodeType == 3 && insertNode.nodeType == 3) {
startRangeNode.insertData(startRangeOffset, insertNode.nodeValue);
newRange.setEnd(startRangeNode, startRangeOffset + insertNode.length);
newRange.setStart(startRangeNode, startRangeOffset + insertNode.length);
} else {
var afterNode;
if (startRangeNode.nodeType == 3) {
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(insertNode, afterNode);
startRangeNode.insertBefore(beforeNode, insertNode);
startRangeNode.removeChild(textNode);
} else {
if (startRangeNode.tagName.toLowerCase() == 'html') {
startRangeNode = startRangeNode.childNodes[0].nextSibling;
afterNode = startRangeNode.childNodes[0];
} else {
afterNode = startRangeNode.childNodes[startRangeOffset];
}
startRangeNode.insertBefore(insertNode, afterNode);
}
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
}
KE_SELECTION.addRange(newRange);
}
}
function KindExecuteValue(cmd, value)
{
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, value);
}
function KindSimpleExecute(cmd)
{
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, null);
KindDisableMenu();
}
function KindExecute(cmd, value)
{
switch (cmd)
{
case 'KE_SOURCE':
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
document.getElementById("KindCodeForm").value = KindHtmlToXhtml(KE_EDITFORM_DOCUMENT.body.innerHTML);
document.getElementById("KindEditorIframe").style.display = 'none';
document.getElementById("KindEditTextarea").style.display = 'block';
KindDisableToolbar(true);
} else {
KE_EDITFORM_DOCUMENT.body.innerHTML = KindClearScriptTag(document.getElementById("KindCodeForm").value);
document.getElementById("KindEditTextarea").style.display = 'none';
document.getElementById("KindEditorIframe").style.display = 'block';
KindDisableToolbar(false);
}
KindDisableMenu();
break;
case 'KE_PRINT':
KindSimpleExecute('print');
break;
case 'KE_UNDO':
KindSimpleExecute('undo');
break;
case 'KE_REDO':
KindSimpleExecute('redo');
break;
case 'KE_CUT':
KindSimpleExecute('cut');
break;
case 'KE_COPY':
KindSimpleExecute('copy');
break;
case 'KE_PASTE':
KindSimpleExecute('paste');
break;
case 'KE_SELECTALL':
KindSimpleExecute('selectall');
break;
case 'KE_SUBSCRIPT':
KindSimpleExecute('subscript');
break;
case 'KE_SUPERSCRIPT':
KindSimpleExecute('superscript');
break;
case 'KE_BOLD':
KindSimpleExecute('bold');
break;
case 'KE_ITALIC':
KindSimpleExecute('italic');
break;
case 'KE_UNDERLINE':
KindSimpleExecute('underline');
break;
case 'KE_STRIKE':
KindSimpleExecute('strikethrough');
break;
case 'KE_JUSTIFYLEFT':
KindSimpleExecute('justifyleft');
break;
case 'KE_JUSTIFYCENTER':
KindSimpleExecute('justifycenter');
break;
case 'KE_JUSTIFYRIGHT':
KindSimpleExecute('justifyright');
break;
case 'KE_JUSTIFYFULL':
KindSimpleExecute('justifyfull');
break;
case 'KE_NUMBEREDLIST':
KindSimpleExecute('insertorderedlist');
break;
case 'KE_UNORDERLIST':
KindSimpleExecute('insertunorderedlist');
break;
case 'KE_INDENT':
KindSimpleExecute('indent');
break;
case 'KE_OUTDENT':
KindSimpleExecute('outdent');
break;
case 'KE_REMOVE':
KindSimpleExecute('removeformat');
break;
case 'KE_ZOOM':
KindDisplayMenu(cmd);
break;
case 'KE_ZOOM_END':
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.body.style.zoom = value;
KindDisableMenu();
break;
case 'KE_TITLE':
KindDisplayMenu(cmd);
break;
case 'KE_TITLE_END':
KindEditorForm.focus();
value = '<' + value + '>';
KindSelect();
KindExecuteValue('FormatBlock', value);
KindDisableMenu();
break;
case 'KE_FONTNAME':
KindDisplayMenu(cmd);
break;
case 'KE_FONTNAME_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('fontname', value);
KindDisableMenu();
break;
case 'KE_FONTSIZE':
KindDisplayMenu(cmd);
break;
case 'KE_FONTSIZE_END':
KindEditorForm.focus();
value = value.substr(0, 1);
KindSelect();
KindExecuteValue('fontsize', value);
KindDisableMenu();
break;
case 'KE_TEXTCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_TEXTCOLOR_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('ForeColor', value);
KindDisableMenu();
break;
case 'KE_BGCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_BGCOLOR_END':
KindEditorForm.focus();
if (KE_BROWSER == 'IE') {
KindSelect();
KindExecuteValue('BackColor', value);
} else {
var startRangeNode = KE_RANGE.startContainer;
if (startRangeNode.nodeType == 3) {
var parent = startRangeNode.parentNode;
var element = document.createElement("font");
element.style.backgroundColor = value;
element.appendChild(KE_RANGE.extractContents());
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
var afterNode;
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(element, afterNode);
startRangeNode.insertBefore(beforeNode, element);
startRangeNode.removeChild(textNode);
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
KE_SELECTION.addRange(newRange);
}
}
KindDisableMenu();
break;
case 'KE_ICON':
KindDisplayMenu(cmd);
break;
case 'KE_ICON_END':
KindEditorForm.focus();
var element = document.createElement("img");
element.src = value;
element.border = 0;
element.alt = "";
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_IMAGE':
KindDisplayMenu(cmd);
KindImageIframe.focus();
KE_IMAGE_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_FLASH':
KindDisplayMenu(cmd);
KindFlashIframe.focus();
KE_FLASH_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_MEDIA':
KindDisplayMenu(cmd);
KindMediaIframe.focus();
KE_MEDIA_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_REAL':
KindDisplayMenu(cmd);
KindRealIframe.focus();
KE_REAL_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_LINK':
KindDisplayMenu(cmd);
KindLinkIframe.focus();
KE_LINK_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_UNLINK':
KindSimpleExecute('unlink');
break;
case 'KE_SPECIALCHAR':
KindDisplayMenu(cmd);
break;
case 'KE_SPECIALCHAR_END':
KindEditorForm.focus();
KindSelect();
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_LAYER':
KindDisplayMenu(cmd);
break;
case 'KE_LAYER_END':
KindEditorForm.focus();
var element = document.createElement("div");
element.style.padding = "5px";
element.style.border = "1px solid #AAAAAA";
element.style.backgroundColor = value;
var childElement = document.createElement("div");
childElement.innerHTML = KE_LANG['INPUT_CONTENT'];
element.appendChild(childElement);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TABLE':
KindDisplayMenu(cmd);
break;
case 'KE_TABLE_END':
KindEditorForm.focus();
var location = value.split(',');
var element = document.createElement("table");
element.cellPadding = 0;
element.cellSpacing = 0;
element.border = 1;
element.style.width = "100px";
element.style.height = "100px";
for (var i = 0; i < location[0]; i++) {
var rowElement = element.insertRow(i);
for (var j = 0; j < location[1]; j++) {
var cellElement = rowElement.insertCell(j);
cellElement.innerHTML = " ";
}
}
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_HR':
KindDisplayMenu(cmd);
break;
case 'KE_HR_END':
KindEditorForm.focus();
var element = document.createElement("hr");
element.width = "100%";
element.color = value;
element.size = 1;
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_DATE':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var year = date.getFullYear().toString(10);
var month = (date.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = date.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var value = year + '-' + month + '-' + day;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TIME':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var hour = date.getHours().toString(10);
hour = hour.length < 2 ? '0' + hour : hour;
var minute = date.getMinutes().toString(10);
minute = minute.length < 2 ? '0' + minute : minute;
var second = date.getSeconds().toString(10);
second = second.length < 2 ? '0' + second : second;
var value = hour + ':' + minute + ':' + second;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_PREVIEW':
eval(KE_OBJ_NAME).data();
var newWin = window.open('', 'kindPreview','width=800,height=600,left=30,top=30,resizable=yes,scrollbars=yes');
KindWriteFullHtml(newWin.document, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
KindDisableMenu();
break;
case 'KE_ABOUT':
KindDisplayMenu(cmd);
break;
default:
break;
}
}
function KindDisableToolbar(flag)
{
if (flag == true) {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'design.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
if (KE_TOOLBAR_ICON[i][0] == 'KE_SOURCE' || KE_TOOLBAR_ICON[i][0] == 'KE_PREVIEW' || KE_TOOLBAR_ICON[i][0] == 'KE_ABOUT') {
continue;
}
el.style.visibility = 'hidden';
}
} else {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'source.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
el.style.visibility = 'visible';
KE_EDITFORM_DOCUMENT.designMode = 'On';
}
}
}
function KindCreateIcon(icon)
{
var str = '<img id="'+ icon[0] +'" src="' + KE_SKIN_PATH + icon[1] + '" alt="' + icon[2] + '" title="' + icon[2] +
'" align="absmiddle" style="border:1px solid ' + KE_TOOLBAR_BG_COLOR +';cursor:pointer;height:20px;';
str += '" onclick="javascript:KindExecute(\''+ icon[0] +'\');" '+
'onmouseover="javascript:this.style.border=\'1px solid ' + KE_MENU_BORDER_COLOR + '\';" ' +
'onmouseout="javascript:this.style.border=\'1px solid ' + KE_TOOLBAR_BG_COLOR + '\';" ';
str += '>';
return str;
}
function KindCreateToolbar()
{
var htmlData = '<table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
if (KE_EDITOR_TYPE == 'full') {
for (i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_TOP_TOOLBAR_ICON[i]) + '</td>';
}
htmlData += '</tr></table><table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
for (i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_BOTTOM_TOOLBAR_ICON[i]) + '</td>';
}
} else {
for (i = 0; i < KE_SIMPLE_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_SIMPLE_TOOLBAR_ICON[i]) + '</td>';
}
}
htmlData += '</tr></table>';
return htmlData;
}
function KindWriteFullHtml(documentObj, content)
{
var editHtmlData = '';
editHtmlData += '<html>\r\n<head>\r\n<title>KindEditor</title>\r\n';
editHtmlData += '<link href="'+KE_CSS_PATH+'" rel="stylesheet" type="text/css">\r\n</head>\r\n<body>\r\n';
editHtmlData += content;
editHtmlData += '\r\n</body>\r\n</html>\r\n';
documentObj.open();
documentObj.write(editHtmlData);
documentObj.close();
}
function KindEditor(objName)
{
this.objName = objName;
this.hiddenName = objName;
this.siteDomain;
this.editorType;
this.safeMode;
this.uploadMode;
this.editorWidth;
this.editorHeight;
this.skinPath;
this.iconPath;
this.imageAttachPath;
this.imageUploadCgi;
this.cssPath;
this.menuBorderColor;
this.menuBgColor;
this.menuTextColor;
this.menuSelectedColor;
this.toolbarBorderColor;
this.toolbarBgColor;
this.formBorderColor;
this.formBgColor;
this.buttonColor;
this.init = function()
{
if (this.siteDomain) KE_SITE_DOMAIN = this.siteDomain;
if (this.editorType) KE_EDITOR_TYPE = this.editorType.toLowerCase();
if (this.safeMode) KE_SAFE_MODE = this.safeMode;
if (this.uploadMode) KE_UPLOAD_MODE = this.uploadMode;
if (this.editorWidth) KE_WIDTH = this.editorWidth;
if (this.editorHeight) KE_HEIGHT = this.editorHeight;
if (this.skinPath) KE_SKIN_PATH = this.skinPath;
if (this.iconPath) KE_ICON_PATH = this.iconPath;
if (this.imageAttachPath) KE_IMAGE_ATTACH_PATH = this.imageAttachPath;
if (this.imageUploadCgi) KE_IMAGE_UPLOAD_CGI = this.imageUploadCgi;
if (this.cssPath) KE_CSS_PATH = this.cssPath;
if (this.menuBorderColor) KE_MENU_BORDER_COLOR = this.menuBorderColor;
if (this.menuBgColor) KE_MENU_BG_COLOR = this.menuBgColor;
if (this.menuTextColor) KE_MENU_TEXT_COLOR = this.menuTextColor;
if (this.menuSelectedColor) KE_MENU_SELECTED_COLOR = this.menuSelectedColor;
if (this.toolbarBorderColor) KE_TOOLBAR_BORDER_COLOR = this.toolbarBorderColor;
if (this.toolbarBgColor) KE_TOOLBAR_BG_COLOR = this.toolbarBgColor;
if (this.formBorderColor) KE_FORM_BORDER_COLOR = this.formBorderColor;
if (this.formBgColor) KE_FORM_BG_COLOR = this.formBgColor;
if (this.buttonColor) KE_BUTTON_COLOR = this.buttonColor;
KE_OBJ_NAME = this.objName;
KE_BROWSER = KindGetBrowser();
KE_TOOLBAR_ICON = Array();
for (var i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_TOP_TOOLBAR_ICON[i]);
}
for (var i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_BOTTOM_TOOLBAR_ICON[i]);
}
}
this.show = function()
{
this.init();
var widthStyle = 'width:' + KE_WIDTH + ';';
var widthArr = KE_WIDTH.match(/(\d+)([px%]{1,2})/);
var iframeWidthStyle = 'width:' + (parseInt(widthArr[1]) - 2).toString(10) + widthArr[2] + ';';
var heightStyle = 'height:' + KE_HEIGHT + ';';
var heightArr = KE_HEIGHT.match(/(\d+)([px%]{1,2})/);
var iframeHeightStyle = 'height:' + (parseInt(heightArr[1]) - 3).toString(10) + heightArr[2] + ';';
if (KE_BROWSER == '') {
var htmlData = '<div id="KindEditTextarea" style="' + widthStyle + heightStyle + '">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + widthStyle + heightStyle +
'padding:0;margin:0;border:1px solid '+ KE_FORM_BORDER_COLOR +
';font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';">' + document.getElementsByName(this.hiddenName)[0].value + '</textarea></div>';
document.open();
document.write(htmlData);
document.close();
return;
}
var htmlData = '<div style="font-family:'+KE_FONT_FAMILY+';">';
htmlData += '<div style="'+widthStyle+';border:1px solid ' + KE_TOOLBAR_BORDER_COLOR + ';background-color:'+ KE_TOOLBAR_BG_COLOR +'">';
htmlData += KindCreateToolbar();
htmlData += '</div><div id="KindEditorIframe" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';border-top:0;">' +
'<iframe name="KindEditorForm" id="KindEditorForm" frameborder="0" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;"></iframe></div>';
if (KE_EDITOR_TYPE == 'full') {
htmlData += '<div id="KindEditTextarea" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';background-color:'+
KE_FORM_BG_COLOR +';border-top:0;display:none;">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';" onclick="javascirit:parent.KindDisableMenu();"></textarea></div>';
}
htmlData += '</div>';
for (var i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
if (KE_POPUP_MENU_TABLE[i] == 'KE_IMAGE') {
htmlData += '<span id="InsertIframe">';
}
htmlData += KindPopupMenu(KE_POPUP_MENU_TABLE[i]);
if (KE_POPUP_MENU_TABLE[i] == 'KE_REAL') {
htmlData += '</span>';
}
}
document.open();
document.write(htmlData);
document.close();
if (KE_BROWSER == 'IE') {
KE_EDITFORM_DOCUMENT = document.frames("KindEditorForm").document;
} else {
KE_EDITFORM_DOCUMENT = document.getElementById('KindEditorForm').contentDocument;
}
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
KindDrawIframe('KE_LINK');
KE_EDITFORM_DOCUMENT.designMode = 'On';
KindWriteFullHtml(KE_EDITFORM_DOCUMENT, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
var el = KE_EDITFORM_DOCUMENT.body;
if (KE_EDITFORM_DOCUMENT.addEventListener){
KE_EDITFORM_DOCUMENT.addEventListener('click', KindDisableMenu, false);
} else if (el.attachEvent){
el.attachEvent('onclick', KindDisableMenu);
}
}
this.data = function()
{
var htmlResult;
if (KE_BROWSER == '') {
htmlResult = document.getElementById("KindCodeForm").value;
} else {
if (KE_EDITOR_TYPE == 'full') {
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
} else {
htmlResult = document.getElementById("KindCodeForm").value;
}
} else {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
}
}
KindDisableMenu();
htmlResult = KindHtmlToXhtml(htmlResult);
htmlResult = KindClearScriptTag(htmlResult);
document.getElementsByName(this.hiddenName)[0].value = htmlResult;
return htmlResult;
}
}
| JavaScript |
/*
Textile Editor v0.1
created by: dave olsen, wvu web services
created on: march 17, 2007
project page: slateinfo.blogs.wvu.edu
inspired by:
- Patrick Woods, http://www.hakjoon.com/code/38/textile-quicktags-redirect &
- Alex King, http://alexking.org/projects/js-quicktags
features:
- supports: IE7, FF2, Safari2
- ability to use "simple" vs. "extended" editor
- supports all block elements in textile except footnote
- supports all block modifier elements in textile
- supports simple ordered and unordered lists
- supports most of the phrase modifiers, very easy to add the missing ones
- supports multiple-paragraph modification
- can have multiple "editors" on one page, access key use in this environment is flaky
- access key support
- select text to add and remove tags, selection stays highlighted
- seamlessly change between tags and modifiers
- doesn't need to be in the body onload tag
- can supply your own, custom IDs for the editor to be drawn around
todo:
- a clean way of providing image and link inserts
- get the selection to properly show in IE
more on textile:
- Textism, http://www.textism.com/tools/textile/index.php
- Textile Reference, http://hobix.com/textile/
*/
document.write('<script src="/javascripts/textile-editor-config.js" type="text/javascript"></script>');
// // initiliaze the quicktags
// function initQuicktags(canvasi) {
// for (var i = 0; i < canvasi.length; i++) {
// edToolbar(document.getElementById(canvasi[i]),canvasi[i]);
// }
// }
// draw the toolbar
function edToolbar(canvas, view) {
var toolbar = document.createElement("div");
toolbar.id = "textile-toolbar-" + canvas;
toolbar.className = 'textile-toolbar';
canvas = document.getElementById(canvas);
canvas.parentNode.insertBefore(toolbar, canvas);
// Create the local Button array by assigning theButtons array to edButtons
var edButtons = new Array();
edButtons = theButtons;
for (var i = 0; i < edButtons.length; i++) {
var thisButton = edShowButton(edButtons[i], canvas);
if (view == 's') {
if (edButtons[i].sve == 's') {
toolbar.appendChild(thisButton);
}
}
else {
toolbar.appendChild(thisButton);
}
}
}
// draw individual buttons
function edShowButton(button, edCanvas) {
var theButton = document.createElement("button");
theButton.id = button.id;
theButton.className = 'ed_button';
theButton.className += 'selected';
theButton.tagStart = button.tagStart;
theButton.tagEnd = button.tagEnd;
theButton.accessKey = button.access;
theButton.title = button.title;
theButton.open = button.open;
theButton.onclick = function() { edInsertTag(edCanvas,this); return false; }
return theButton;
}
// if clicked, no selected text, tag not open highlight button
function edAddTag(button) {
if (button.tagEnd != '') {
edOpenTags[edOpenTags.length] = button;
var el = document.getElementById(button.id);
el.className = 'selected';
}
}
// if clicked, no selected text, tag open lowlight button
function edRemoveTag(button) {
for (i = 0; i < edOpenTags.length; i++) {
if (edOpenTags[i] == button) {
edOpenTags.splice(button, 1);
var el = document.getElementById(button.id);
el.className = 'unselected';
}
}
}
// see if there are open tags. for the remove tag bit...
function edCheckOpenTags(button) {
var tag = 0;
for (i = 0; i < edOpenTags.length; i++) {
if (edOpenTags[i] == button) {
tag++;
}
}
if (tag > 0) {
return true; // tag found
}
else {
return false; // tag not found
}
}
// insert the tag. this is the bulk of the code.
function edInsertTag(myField, button) {
myField.focus();
var textSelected = false;
var finalText = '';
var FF = false;
// grab the text that's going to be manipulated, by browser
if (document.selection) { // IE support
sel = document.selection.createRange();
// set-up the text vars
var beginningText = '';
var followupText = '';
var selectedText = sel.text;
// check if text has been selected
if (sel.text.length > 0) {
textSelected = true;
}
// set-up newline regex's so we can swap tags across multiple paragraphs
var newlineReplaceRegexClean = /\r\n\s\n/g;
var newlineReplaceRegexDirty = '\\r\\n\\s\\n';
var newlineReplaceClean = '\r\n\n';
}
else if (myField.selectionStart || myField.selectionStart == '0') { // MOZ/FF/NS/S support
// figure out cursor and selection positions
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
var cursorPos = endPos;
var scrollTop = myField.scrollTop;
FF = true; // note that is is a FF/MOZ/NS/S browser
// set-up the text vars
var beginningText = myField.value.substring(0, startPos);
var followupText = myField.value.substring(endPos, myField.value.length);
// check if text has been selected
if (startPos != endPos) {
textSelected = true;
var selectedText = myField.value.substring(startPos, endPos);
}
// set-up newline regex's so we can swap tags across multiple paragraphs
var newlineReplaceRegexClean = /\n\n/g;
var newlineReplaceRegexDirty = '\\n\\n';
var newlineReplaceClean = '\n\n';
}
// if there is text that has been highlighted...
if (textSelected) {
// set-up some defaults for how to handle bad new line characters
var newlineStart = '';
var newlineStartPos = 0;
var newlineEnd = '';
var newlineEndPos = 0;
var newlineFollowup = '';
// set-up some defaults for how to handle placing the beginning and end of selection
var posDiffPos = 0;
var posDiffNeg = 0;
var mplier = 1;
// remove newline from the beginning of the selectedText.
if (selectedText.match(/^\n/)) {
selectedText = selectedText.replace(/^\n/,'');
newlineStart = '\n';
newlineStartpos = 1;
}
// remove newline from the end of the selectedText.
if (selectedText.match(/\n$/g)) {
selectedText = selectedText.replace(/\n$/g,'');
newlineEnd = '\n';
newlineEndPos = 1;
}
// no clue, i'm sure it made sense at the time i wrote it
if (followupText.match(/^\n/)) {
newlineFollowup = '';
}
else {
newlineFollowup = '\n\n';
}
// first off let's check if the user is trying to mess with lists
if ((button.tagStart == ' * ') || (button.tagStart == ' # ')) {
listItems = 0; // sets up a default to be able to properly manipulate final selection
// set-up all of the regex's
re_start = new RegExp('^ (\\*|\\#) ','g');
if (button.tagStart == ' # ') {
re_tag = new RegExp(' \\# ','g'); // because of JS regex stupidity i need an if/else to properly set it up, could have done it with a regex replace though
}
else {
re_tag = new RegExp(' \\* ','g');
}
re_replace = new RegExp(' (\\*|\\#) ','g');
// try to remove bullets in text copied from ms word **Mac Only!**
re_word_bullet_m_s = new RegExp('• ','g'); // mac/safari
re_word_bullet_m_f = new RegExp('∑ ','g'); // mac/firefox
selectedText = selectedText.replace(re_word_bullet_m_s,'').replace(re_word_bullet_m_f,'');
// if the selected text starts with one of the tags we're working with...
if (selectedText.match(re_start)) {
// if tag that begins the selection matches the one clicked, remove them all
if (selectedText.match(re_tag)) {
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_replace,'')
+ newlineEnd
+ followupText;
if (matches = selectedText.match(/ (\*|\#) /g)) {
listItems = matches.length;
}
posDiffNeg = listItems*3; // how many list items were there because that's 3 spaces to remove from final selection
}
// else replace the current tag type with the selected tag type
else {
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_replace,button.tagStart)
+ newlineEnd
+ followupText;
}
}
// else try to create the list type
// NOTE: the items in a list will only be replaced if a newline starts with some character, not a space
else {
finalText = beginningText
+ newlineStart
+ button.tagStart
+ selectedText.replace(newlineReplaceRegexClean,newlineReplaceClean + button.tagStart).replace(/\n(\S)/g,'\n' + button.tagStart + '$1')
+ newlineEnd
+ followupText;
if (matches = selectedText.match(/\n(\S)/g)) {
listItems = matches.length;
}
posDiffPos = 3 + listItems*3;
}
}
// now lets look and see if the user is trying to muck with a block or block modifier
else if (button.tagStart.match(/^(h1|h2|h3|h4|bq|p|\>|\<\>|\<|\=|\(|\))/g)) {
var insertTag = '';
var insertModifier = '';
var tagPartBlock = '';
var tagPartModifier = '';
var tagPartModifierOrig = ''; // ugly hack but it's late
var drawSwitch = '';
var captureIndentStart = false;
var captureListStart = false;
var periodAddition = '\\. ';
var periodAdditionClean = '. ';
var listItemsAddition = 0;
var re_list_items = new RegExp('(\\*+|\\#+)','g'); // need this regex later on when checking indentation of lists
var re_block_modifier = new RegExp('^(h1|h2|h3|h4|bq|p| [\\*]{1,} | [\\#]{1,} |)(\\>|\\<\\>|\\<|\\=|[\\(]{1,}|[\\)]{1,6}|)','g');
if (tagPartMatches = re_block_modifier.exec(selectedText)) {
tagPartBlock = tagPartMatches[1];
tagPartModifier = tagPartMatches[2];
tagPartModifierOrig = tagPartMatches[2];
tagPartModifierOrig = tagPartModifierOrig.replace(/\(/g,"\\(");
}
// if tag already up is the same as the tag provided replace the whole tag
if (tagPartBlock == button.tagStart) {
insertTag = tagPartBlock + tagPartModifierOrig; // use Orig because it's escaped for regex
drawSwitch = 0;
}
// else if let's check to add/remove block modifier
else if ((tagPartModifier == button.tagStart) || (newm = tagPartModifier.match(/[\(]{2,}/g))) {
if ((button.tagStart == '(') || (button.tagStart == ')')) {
var indentLength = tagPartModifier.length;
if (button.tagStart == '(') {
indentLength = indentLength + 1;
}
else {
indentLength = indentLength - 1;
}
for (var i = 0; i < indentLength; i++) {
insertModifier = insertModifier + '(';
}
insertTag = tagPartBlock + insertModifier;
}
else {
if (button.tagStart == tagPartModifier) {
insertTag = tagPartBlock;
} // going to rely on the default empty insertModifier
else {
if (button.tagStart.match(/(\>|\<\>|\<|\=)/g)) {
insertTag = tagPartBlock + button.tagStart;
}
else {
insertTag = button.tagStart + tagPartModifier;
}
}
}
drawSwitch = 1;
}
// indentation of list items
else if (listPartMatches = re_list_items.exec(tagPartBlock)) {
var listTypeMatch = listPartMatches[1];
var indentLength = tagPartBlock.length - 2;
var listInsert = '';
if (button.tagStart == '(') {
indentLength = indentLength + 1;
}
else {
indentLength = indentLength - 1;
}
if (listTypeMatch.match(/[\*]{1,}/g)) {
var listType = '*';
var listReplace = '\\*';
}
else {
var listType = '#';
var listReplace = '\\#';
}
for (var i = 0; i < indentLength; i++) {
listInsert = listInsert + listType;
}
if (listInsert != '') {
insertTag = ' ' + listInsert + ' ';
}
else {
insertTag = '';
}
tagPartBlock = tagPartBlock.replace(/(\*|\#)/g,listReplace);
drawSwitch = 1;
captureListStart = true;
periodAddition = '';
periodAdditionClean = '';
if (matches = selectedText.match(/\n\s/g)) {
listItemsAddition = matches.length;
}
}
// must be a block modification e.g. p>. to p<.
else {
// if this is a block modification/addition
if (button.tagStart.match(/(h1|h2|h3|h4|bq|p)/g)) {
if (tagPartBlock == '') {
drawSwitch = 2;
}
else {
drawSwitch = 1;
}
insertTag = button.tagStart + tagPartModifier;
}
// else this is a modifier modification/addition
else {
if ((tagPartModifier == '') && (tagPartBlock != '')) {
drawSwitch = 1;
}
else if (tagPartModifier == '') {
drawSwitch = 2;
}
else {
drawSwitch = 1;
}
// if no tag part block but a modifier we need at least the p tag
if (tagPartBlock == '') {
tagPartBlock = 'p';
}
//make sure to swap out outdent
if (button.tagStart == ')') {
tagPartModifier = '';
}
else {
tagPartModifier = button.tagStart;
captureIndentStart = true; // ugly hack to fix issue with proper selection handling
}
insertTag = tagPartBlock + tagPartModifier;
}
}
mplier = 0;
if (captureListStart || (tagPartModifier.match(/[\(\)]{1,}/g))) {
re_start = new RegExp(insertTag.escape + periodAddition,'g'); // for tags that mimic regex properties, parens + list tags
}
else {
re_start = new RegExp(insertTag + periodAddition,'g'); // for tags that don't, why i can't just escape everything i have no clue
}
re_old = new RegExp(tagPartBlock + tagPartModifierOrig + periodAddition,'g');
re_middle = new RegExp(newlineReplaceRegexDirty + insertTag.escape + periodAddition.escape,'g');
re_tag = new RegExp(insertTag.escape + periodAddition.escape,'g');
// *************************************************************************************************************************
// this is where everything gets swapped around or inserted, bullets and single options have their own if/else statements
// *************************************************************************************************************************
if ((drawSwitch == 0) || (drawSwitch == 1)) {
if (drawSwitch == 0) { // completely removing a tag
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_start,'').replace(re_middle,newlineReplaceClean)
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffNeg = insertTag.length + 2 + (mplier*4);
}
else { // modifying a tag, though we do delete bullets here
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_old,insertTag + periodAdditionClean)
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
// figure out the length of various elements to modify the selection position
if (captureIndentStart) { // need to double-check that this wasn't the first indent
tagPreviousLength = tagPartBlock.length;
tagCurrentLength = insertTag.length;
}
else if (captureListStart) { // if this is a list we're manipulating
if (button.tagStart == '(') { // if indenting
tagPreviousLength = listTypeMatch.length + 2;
tagCurrentLength = insertTag.length + listItemsAddition;
}
else if (insertTag.match(/(\*|\#)/g)) { // if removing but still has bullets
tagPreviousLength = insertTag.length + listItemsAddition;
tagCurrentLength = listTypeMatch.length;
}
else { // if removing last bullet
tagPreviousLength = insertTag.length + listItemsAddition;
tagCurrentLength = listTypeMatch.length - (3*listItemsAddition) - 1;
}
}
else { // everything else
tagPreviousLength = tagPartBlock.length + tagPartModifier.length;
tagCurrentLength = insertTag.length;
}
if (tagCurrentLength > tagPreviousLength) {
posDiffPos = (tagCurrentLength - tagPreviousLength) + (mplier*(tagCurrentLength - tagPreviousLength));
}
else {
posDiffNeg = (tagPreviousLength - tagCurrentLength) + (mplier*(tagPreviousLength - tagCurrentLength));
}
}
}
else { // for adding tags other then bullets (have their own statement)
finalText = beginningText
+ newlineStart
+ insertTag + '. '
+ selectedText.replace(newlineReplaceRegexClean,button.tagEnd + '\n' + insertTag + '. ')
+ newlineFollowup
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffPos = insertTag.length + 2 + (mplier*4);
}
}
// swap in and out the simple tags around a selection like bold
else {
mplier = 1; // the multiplier for the tag length
re_start = new RegExp('^\\' + button.tagStart,'g');
re_end = new RegExp('\\' + button.tagEnd + '$','g');
re_middle = new RegExp('\\' + button.tagEnd + newlineReplaceRegexDirty + '\\' + button.tagStart,'g');
if (selectedText.match(re_start) && selectedText.match(re_end)) {
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_start,'').replace(re_end,'').replace(re_middle,newlineReplaceClean)
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffNeg = button.tagStart.length*mplier + button.tagEnd.length*mplier;
}
else {
finalText = beginningText
+ newlineStart
+ button.tagStart
+ selectedText.replace(newlineReplaceRegexClean,button.tagEnd + newlineReplaceClean + button.tagStart)
+ button.tagEnd
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffPos = (button.tagStart.length*mplier) + (button.tagEnd.length*mplier);
}
}
cursorPos += button.tagStart.length + button.tagEnd.length;
}
// just swap in and out single values, e.g. someone clicks b they'll get a *
else {
var buttonStart = '';
var buttonEnd = '';
var re_p = new RegExp('(\\<|\\>|\\=|\\<\\>|\\(|\\))','g');
var re_h = new RegExp('^(h1|h2|h3|h4|p|bq)','g');
if (!edCheckOpenTags(button) || button.tagEnd == '') { // opening tag
if (button.tagStart.match(re_h)) {
buttonStart = button.tagStart + '. ';
}
else {
buttonStart = button.tagStart;
}
if (button.tagStart.match(re_p)) { // make sure that invoking block modifiers don't do anything
finalText = beginningText
+ followupText;
cursorPos = startPos;
}
else {
finalText = beginningText
+ buttonStart
+ followupText;
edAddTag(button);
cursorPos = startPos + buttonStart.length;
}
}
else { // closing tag
if (button.tagStart.match(re_p)) {
buttonEnd = '\n\n';
}
else if (button.tagStart.match(re_h)) {
buttonEnd = '\n\n';
}
else {
buttonEnd = button.tagEnd
}
finalText = beginningText
+ button.tagEnd
+ followupText;
edRemoveTag(button);
cursorPos = startPos + button.tagEnd.length;
}
}
// set the appropriate DOM value with the final text
if (FF == true) {
myField.value = finalText;
myField.scrollTop = scrollTop;
}
else {
sel.text = finalText;
}
// build up the selection capture, doesn't work in IE
if (textSelected) {
myField.selectionStart = startPos + newlineStartPos;
myField.selectionEnd = endPos + posDiffPos - posDiffNeg - newlineEndPos;
//alert('s: ' + myField.selectionStart + ' e: ' + myField.selectionEnd + ' sp: ' + startPos + ' ep: ' + endPos + ' pdp: ' + posDiffPos + ' pdn: ' + posDiffNeg)
}
else {
myField.selectionStart = cursorPos;
myField.selectionEnd = cursorPos;
}
} | JavaScript |
/**
* WYSIWYG HTML Editor for Internet
*
* @author Roddy <luolonghao@gmail.com>
* @version 2.5.3
*/
var KE_VERSION = "2.5.4";
var KE_EDITOR_TYPE = "full"; //full or simple
var KE_SAFE_MODE = false; // true or false
var KE_UPLOAD_MODE = true; // true or false
var KE_FONT_FAMILY = "Courier New";
var KE_WIDTH = "700px";
var KE_HEIGHT = "400px";
var KE_SITE_DOMAIN = "";
var KE_SKIN_PATH = "./skins/default/";
var KE_ICON_PATH = "./icons/";
var KE_IMAGE_ATTACH_PATH = "./attached/";
var KE_IMAGE_UPLOAD_CGI = "./upload_cgi/upload.php";
var KE_CSS_PATH = "/editor/common.css";
var KE_MENU_BORDER_COLOR = '#AAAAAA';
var KE_MENU_BG_COLOR = '#EFEFEF';
var KE_MENU_TEXT_COLOR = '#222222';
var KE_MENU_SELECTED_COLOR = '#CCCCCC';
var KE_TOOLBAR_BORDER_COLOR = '#DDDDDD';
var KE_TOOLBAR_BG_COLOR = '#EFEFEF';
var KE_FORM_BORDER_COLOR = '#DDDDDD';
var KE_FORM_BG_COLOR = '#FFFFFF';
var KE_BUTTON_COLOR = '#AAAAAA';
var KE_LANG = {
INPUT_URL : "请输入正确的URL地址。",
SELECT_IMAGE : "请选择图片。",
INVALID_IMAGE : "只能选择GIF,JPG,PNG,BMP格式的图片,请重新选择。",
INVALID_FLASH : "只能选择SWF格式的文件,请重新选择。",
INVALID_MEDIA : "只能选择MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF格式的文件,请重新选择。",
INVALID_REAL : "只能选择RM,RMVB格式的文件,请重新选择。",
INVALID_WIDTH : "宽度不是数字,请重新输入。",
INVALID_HEIGHT : "高度不是数字,请重新输入。",
INVALID_BORDER : "边框不是数字,请重新输入。",
INVALID_HSPACE : "横隔不是数字,请重新输入。",
INVALID_VSPACE : "竖隔不是数字,请重新输入。",
INPUT_CONTENT : "请输入内容",
TITLE : "描述",
WIDTH : "宽",
HEIGHT : "高",
BORDER : "边",
ALIGN : "对齐方式",
HSPACE : "横隔",
VSPACE : "竖隔",
CONFIRM : "确定",
CANCEL : "取消",
PREVIEW : "预览",
LISTENING : "试听",
LOCAL : "本地",
REMOTE : "远程",
NEW_WINDOW : "新窗口",
CURRENT_WINDOW : "当前窗口",
TARGET : "目标",
ABOUT : "访问技术支持网站",
SUBJECT : "标题"
}
var KE_FONT_NAME = Array(
Array('SimSun', '宋体'),
Array('SimHei', '黑体'),
Array('FangSong_GB2312', '仿宋体'),
Array('KaiTi_GB2312', '楷体'),
Array('NSimSun', '新宋体'),
Array('Arial', 'Arial'),
Array('Arial Black', 'Arial Black'),
Array('Times New Roman', 'Times New Roman'),
Array('Courier New', 'Courier New'),
Array('Tahoma', 'Tahoma'),
Array('Verdana', 'Verdana'),
Array('GulimChe', 'GulimChe'),
Array('MS Gothic', 'MS Gothic')
);
var KE_SPECIAL_CHARACTER = Array(
'§','№','☆','★','○','●','◎','◇','◆','□','℃','‰','■','△','▲','※',
'→','←','↑','↓','〓','¤','°','#','&','@','\','︿','_',' ̄','―','α',
'β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ',
'σ','τ','υ','φ','χ','ψ','ω','≈','≡','≠','=','≤','≥','<','>','≮',
'≯','∷','±','+','-','×','÷','/','∫','∮','∝','∞','∧','∨','∑','∏',
'∪','∩','∈','∵','∴','⊥','∥','∠','⌒','⊙','≌','∽','〖','〗',
'【','】','(',')','[',']'
);
var KE_TOP_TOOLBAR_ICON = Array(
Array('KE_SOURCE', 'source.gif', '视图转换'),
Array('KE_PREVIEW', 'preview.gif', '预览'),
Array('KE_ZOOM', 'zoom.gif', '显示比例'),
Array('KE_PRINT', 'print.gif', '打印'),
Array('KE_UNDO', 'undo.gif', '回退'),
Array('KE_REDO', 'redo.gif', '前进'),
Array('KE_CUT', 'cut.gif', '剪切'),
Array('KE_COPY', 'copy.gif', '复制'),
Array('KE_PASTE', 'paste.gif', '粘贴'),
Array('KE_SELECTALL', 'selectall.gif', '全选'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_JUSTIFYFULL', 'justifyfull.gif', '两端对齐'),
Array('KE_NUMBEREDLIST', 'numberedlist.gif', '编号'),
Array('KE_UNORDERLIST', 'unorderedlist.gif', '项目符号'),
Array('KE_INDENT', 'indent.gif', '减少缩进'),
Array('KE_OUTDENT', 'outdent.gif', '增加缩进'),
Array('KE_SUBSCRIPT', 'subscript.gif', '下标'),
Array('KE_SUPERSCRIPT', 'superscript.gif', '上标'),
Array('KE_DATE', 'date.gif', '日期'),
Array('KE_TIME', 'time.gif', '时间')
);
var KE_BOTTOM_TOOLBAR_ICON = Array(
Array('KE_TITLE', 'title.gif', '标题'),
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_STRIKE', 'strikethrough.gif', '删除线'),
Array('KE_REMOVE', 'removeformat.gif', '删除格式'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_FLASH', 'flash.gif', 'Flash'),
Array('KE_MEDIA', 'media.gif', 'Windows Media Player'),
Array('KE_REAL', 'real.gif', 'Real Player'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_TABLE', 'table.gif', '表格'),
Array('KE_SPECIALCHAR', 'specialchar.gif', '特殊字符'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_UNLINK', 'unlink.gif', '删除超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_SIMPLE_TOOLBAR_ICON = Array(
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_TITLE_TABLE = Array(
Array('H1', KE_LANG['SUBJECT'] + ' 1'),
Array('H2', KE_LANG['SUBJECT'] + ' 2'),
Array('H3', KE_LANG['SUBJECT'] + ' 3'),
Array('H4', KE_LANG['SUBJECT'] + ' 4'),
Array('H5', KE_LANG['SUBJECT'] + ' 5'),
Array('H6', KE_LANG['SUBJECT'] + ' 6')
);
var KE_ZOOM_TABLE = Array('250%', '200%', '150%', '120%', '100%', '80%', '50%');
var KE_FONT_SIZE = Array(
Array(1,'8pt'),
Array(2,'10pt'),
Array(3,'12pt'),
Array(4,'14pt'),
Array(5,'18pt'),
Array(6,'24pt'),
Array(7,'36pt')
);
var KE_POPUP_MENU_TABLE = Array(
"KE_ZOOM", "KE_TITLE", "KE_FONTNAME", "KE_FONTSIZE", "KE_TEXTCOLOR", "KE_BGCOLOR",
"KE_LAYER", "KE_TABLE", "KE_HR", "KE_ICON", "KE_SPECIALCHAR", "KE_ABOUT",
"KE_IMAGE", "KE_FLASH", "KE_MEDIA", "KE_REAL", "KE_LINK"
);
var KE_COLOR_TABLE = Array(
"#FF0000", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#FF00FF", "#FFFFFF", "#F5F5F5", "#DCDCDC", "#FFFAFA",
"#D3D3D3", "#C0C0C0", "#A9A9A9", "#808080", "#696969", "#000000", "#2F4F4F", "#708090", "#778899", "#4682B4",
"#4169E1", "#6495ED", "#B0C4DE", "#7B68EE", "#6A5ACD", "#483D8B", "#191970", "#000080", "#00008B", "#0000CD",
"#1E90FF", "#00BFFF", "#87CEFA", "#87CEEB", "#ADD8E6", "#B0E0E6", "#F0FFFF", "#E0FFFF", "#AFEEEE", "#00CED1",
"#5F9EA0", "#48D1CC", "#00FFFF", "#40E0D0", "#20B2AA", "#008B8B", "#008080", "#7FFFD4", "#66CDAA", "#8FBC8F",
"#3CB371", "#2E8B57", "#006400", "#008000", "#228B22", "#32CD32", "#00FF00", "#7FFF00", "#7CFC00", "#ADFF2F",
"#98FB98", "#90EE90", "#00FF7F", "#00FA9A", "#556B2F", "#6B8E23", "#808000", "#BDB76B", "#B8860B", "#DAA520",
"#FFD700", "#F0E68C", "#EEE8AA", "#FFEBCD", "#FFE4B5", "#F5DEB3", "#FFDEAD", "#DEB887", "#D2B48C", "#BC8F8F",
"#A0522D", "#8B4513", "#D2691E", "#CD853F", "#F4A460", "#8B0000", "#800000", "#A52A2A", "#B22222", "#CD5C5C",
"#F08080", "#FA8072", "#E9967A", "#FFA07A", "#FF7F50", "#FF6347", "#FF8C00", "#FFA500", "#FF4500", "#DC143C",
"#FF0000", "#FF1493", "#FF00FF", "#FF69B4", "#FFB6C1", "#FFC0CB", "#DB7093", "#C71585", "#800080", "#8B008B",
"#9370DB", "#8A2BE2", "#4B0082", "#9400D3", "#9932CC", "#BA55D3", "#DA70D6", "#EE82EE", "#DDA0DD", "#D8BFD8",
"#E6E6FA", "#F8F8FF", "#F0F8FF", "#F5FFFA", "#F0FFF0", "#FAFAD2", "#FFFACD", "#FFF8DC", "#FFFFE0", "#FFFFF0",
"#FFFAF0", "#FAF0E6", "#FDF5E6", "#FAEBD7", "#FFE4C4", "#FFDAB9", "#FFEFD5", "#FFF5EE", "#FFF0F5", "#FFE4E1"
);
var KE_IMAGE_ALIGN_TABLE = Array(
"baseline", "top", "middle", "bottom", "texttop", "absmiddle", "absbottom", "left", "right"
);
var KE_OBJ_NAME;
var KE_SELECTION;
var KE_RANGE;
var KE_RANGE_TEXT;
var KE_EDITFORM_DOCUMENT;
var KE_IMAGE_DOCUMENT;
var KE_FLASH_DOCUMENT;
var KE_MEDIA_DOCUMENT;
var KE_REAL_DOCUMENT;
var KE_LINK_DOCUMENT;
var KE_BROWSER;
var KE_TOOLBAR_ICON;
function KindGetBrowser()
{
var browser = '';
var agentInfo = navigator.userAgent.toLowerCase();
if (agentInfo.indexOf("msie") > -1) {
var re = new RegExp("msie\\s?([\\d\\.]+)","ig");
var arr = re.exec(agentInfo);
if (parseInt(RegExp.$1) >= 5.5) {
browser = 'IE';
}
} else if (agentInfo.indexOf("firefox") > -1) {
browser = 'FF';
} else if (agentInfo.indexOf("netscape") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[temp1.length-1].split('/');
if (parseInt(temp2[1]) >= 7) {
browser = 'NS';
}
} else if (agentInfo.indexOf("gecko") > -1) {
browser = 'ML';
} else if (agentInfo.indexOf("opera") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[0].split('/');
if (parseInt(temp2[1]) >= 9) {
browser = 'OPERA';
}
}
return browser;
}
function KindGetFileName(file, separator)
{
var temp = file.split(separator);
var len = temp.length;
var fileName = temp[len-1];
return fileName;
}
function KindGetFileExt(fileName)
{
var temp = fileName.split(".");
var len = temp.length;
var fileExt = temp[len-1].toLowerCase();
return fileExt;
}
function KindCheckImageFileType(file, separator)
{
if (separator == "/" && file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, separator);
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'gif' && fileExt != 'jpg' && fileExt != 'png' && fileExt != 'bmp') {
alert(KE_LANG['INVALID_IMAGE']);
return false;
}
return true;
}
function KindCheckFlashFileType(file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'swf') {
alert(KE_LANG['INVALID_FLASH']);
return false;
}
return true;
}
function KindCheckMediaFileType(cmd, file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (cmd == 'KE_REAL') {
if (fileExt != 'rm' && fileExt != 'rmvb') {
alert(KE_LANG['INVALID_REAL']);
return false;
}
} else {
if (fileExt != 'mp3' && fileExt != 'wav' && fileExt != 'wma' && fileExt != 'wmv' && fileExt != 'mid' && fileExt != 'avi' && fileExt != 'mpg' && fileExt != 'asf') {
alert(KE_LANG['INVALID_MEDIA']);
return false;
}
}
return true;
}
function KindHtmlToXhtml(str)
{
str = str.replace(/<br.*?>/gi, "<br />");
str = str.replace(/(<hr\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<img\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<\w+)(.*?>)/gi, function ($0,$1,$2) {
return($1.toLowerCase() + KindConvertAttribute($2));
}
);
str = str.replace(/(<\/\w+>)/gi, function ($0,$1) {
return($1.toLowerCase());
}
);
return str;
}
function KindConvertAttribute(str)
{
if (KE_SAFE_MODE == true) {
str = KindClearAttributeScriptTag(str);
}
return str;
}
function KindClearAttributeScriptTag(str)
{
var re = new RegExp("(\\son[a-z]+=)[\"']?[^>]*?[^\\\\\>][\"']?([\\s>])","ig");
str = str.replace(re, function ($0,$1,$2) {
return($1.toLowerCase() + "\"\"" + $2);
}
);
return str;
}
function KindClearScriptTag(str)
{
if (KE_SAFE_MODE == false) {
return str;
}
str = str.replace(/<(script.*?)>/gi, "[$1]");
str = str.replace(/<\/script>/gi, "[/script]");
return str;
}
function KindHtmlentities(str)
{
str = str.replace(/&/g,'&');
str = str.replace(/</g,'<');
str = str.replace(/>/g,'>');
str = str.replace(/"/g,'"');
return str;
}
function KindGetTop(id)
{
var top = 28;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
top += eval("obj" + tmp).offsetTop;
}
return top;
}
function KindGetLeft(id)
{
var left = 2;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
left += eval("obj" + tmp).offsetLeft;
}
return left;
}
function KindDisplayMenu(cmd)
{
KindEditorForm.focus();
if (cmd != 'KE_ABOUT') {
KindSelection();
}
KindDisableMenu();
var top, left;
top = KindGetTop(cmd);
left = KindGetLeft(cmd);
if (cmd == 'KE_ABOUT') {
left -= 200;
} else if (cmd == 'KE_LINK') {
left -= 220;
}
document.getElementById('POPUP_'+cmd).style.top = top.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.left = left.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.display = 'block';
}
function KindDisableMenu()
{
for (i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
document.getElementById('POPUP_'+KE_POPUP_MENU_TABLE[i]).style.display = 'none';
}
}
function KindReloadIframe()
{
var str = '';
str += KindPopupMenu('KE_IMAGE');
str += KindPopupMenu('KE_FLASH');
str += KindPopupMenu('KE_MEDIA');
str += KindPopupMenu('KE_REAL');
document.getElementById('InsertIframe').innerHTML = str;
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
}
function KindGetMenuCommonStyle()
{
var str = 'position:absolute;top:1px;left:1px;font-size:12px;color:'+KE_MENU_TEXT_COLOR+
';background-color:'+KE_MENU_BG_COLOR+';border:solid 1px '+KE_MENU_BORDER_COLOR+';z-index:1;display:none;';
return str;
}
function KindGetCommonMenu(cmd, content)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="'+KindGetMenuCommonStyle()+'">';
str += content;
str += '</div>';
return str;
}
function KindCreateColorTable(cmd, eventStr)
{
var str = '';
str += '<table cellpadding="0" cellspacing="2" border="0">';
for (i = 0; i < KE_COLOR_TABLE.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="width:12px;height:12px;border:1px solid #AAAAAA;font-size:1px;cursor:pointer;background-color:' +
KE_COLOR_TABLE[i] + ';" onmouseover="javascript:this.style.borderColor=\'#000000\';' + ((eventStr) ? eventStr : '') + '" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onclick="javascript:KindExecute(\''+cmd+'_END\', \'' + KE_COLOR_TABLE[i] + '\');"> </td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
}
function KindDrawColorTable(cmd)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;padding:2px;'+KindGetMenuCommonStyle()+'">';
str += KindCreateColorTable(cmd);
str += '</div>';
return str;
}
function KindDrawMedia(cmd)
{
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="'+cmd+'preview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="'+cmd+'link" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['LISTENING']+'" onclick="javascript:parent.KindMediaPreview(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawMediaEnd(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
return str;
}
function KindPopupMenu(cmd)
{
switch (cmd)
{
case 'KE_ZOOM':
var str = '';
for (i = 0; i < KE_ZOOM_TABLE.length; i++) {
str += '<div style="padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ZOOM_END\', \'' + KE_ZOOM_TABLE[i] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_ZOOM_TABLE[i] + '</div>';
}
str = KindGetCommonMenu('KE_ZOOM', str);
return str;
break;
case 'KE_TITLE':
var str = '';
for (i = 0; i < KE_TITLE_TABLE.length; i++) {
str += '<div style="width:140px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TITLE_END\', \'' + KE_TITLE_TABLE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';"><' + KE_TITLE_TABLE[i][0] + ' style="margin:2px;">' +
KE_TITLE_TABLE[i][1] + '</' + KE_TITLE_TABLE[i][0] + '></div>';
}
str = KindGetCommonMenu('KE_TITLE', str);
return str;
break;
case 'KE_FONTNAME':
var str = '';
for (i = 0; i < KE_FONT_NAME.length; i++) {
str += '<div style="font-family:' + KE_FONT_NAME[i][0] +
';padding:2px;width:160px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTNAME_END\', \'' + KE_FONT_NAME[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_NAME[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTNAME', str);
return str;
break;
case 'KE_FONTSIZE':
var str = '';
for (i = 0; i < KE_FONT_SIZE.length; i++) {
str += '<div style="font-size:' + KE_FONT_SIZE[i][1] +
';padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTSIZE_END\', \'' + KE_FONT_SIZE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_SIZE[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTSIZE', str);
return str;
break;
case 'KE_TEXTCOLOR':
var str = '';
str = KindDrawColorTable('KE_TEXTCOLOR');
return str;
break;
case 'KE_BGCOLOR':
var str = '';
str = KindDrawColorTable('KE_BGCOLOR');
return str;
break;
case 'KE_HR':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="hrPreview" style="margin:10px 2px 10px 2px;height:1px;border:0;font-size:0;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'hrPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_LAYER':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="divPreview" style="margin:5px 2px 5px 2px;height:20px;border:1px solid #AAAAAA;font-size:1px;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'divPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_ICON':
var str = '';
var iconNum = 36;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < iconNum; i++) {
if (i == 0 || (i >= 6 && i%6 == 0)) {
str += '<tr>';
}
var num;
if ((i+1).toString(10).length < 2) {
num = '0' + (i+1);
} else {
num = (i+1).toString(10);
}
var iconUrl = KE_ICON_PATH + 'etc_' + num + '.gif';
str += '<td style="padding:2px;border:0;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ICON_END\', \'' + iconUrl + '\');">' +
'<img src="' + iconUrl + '" style="border:1px solid #EEEEEE;" onmouseover="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#EEEEEE\';">' + '</td>';
if (i >= 5 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_SPECIALCHAR':
var str = '';
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < KE_SPECIAL_CHARACTER.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="padding:2px;border:1px solid #AAAAAA;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_SPECIALCHAR_END\', \'' + KE_SPECIAL_CHARACTER[i] + '\');" ' +
'onmouseover="javascript:this.style.borderColor=\'#000000\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';">' + KE_SPECIAL_CHARACTER[i] + '</td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_TABLE':
var str = '';
var num = 10;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="0" style="'+KindGetMenuCommonStyle()+'">';
for (i = 1; i <= num; i++) {
str += '<tr>';
for (j = 1; j <= num; j++) {
var value = i.toString(10) + ',' + j.toString(10);
str += '<td id="kindTableTd' + i.toString(10) + '_' + j.toString(10) +
'" style="width:15px;height:15px;background-color:#FFFFFF;border:1px solid #DDDDDD;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TABLE_END\', \'' + value + '\');" ' +
'onmouseover="javascript:KindDrawTableSelected(\''+i.toString(10)+'\', \''+j.toString(10)+'\');" ' +
'onmouseout="javascript:;"> </td>';
}
str += '</tr>';
}
str += '<tr><td colspan="10" id="tableLocation" style="text-align:center;height:20px;"></td></tr>';
str += '</table>';
return str;
break;
case 'KE_IMAGE':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindImageIframe" id="KindImageIframe" frameborder="0" style="width:250px;height:390px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_FLASH':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindFlashIframe" id="KindFlashIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_MEDIA':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindMediaIframe" id="KindMediaIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_REAL':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindRealIframe" id="KindRealIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_LINK':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindLinkIframe" id="KindLinkIframe" frameborder="0" style="width:250px;height:85px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_ABOUT':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:230px;'+KindGetMenuCommonStyle()+';padding:5px;">';
str += '<span style="margin-right:10px;">KindEditor ' + KE_VERSION + '</span>' +
'<a href="http://www.kindsoft.net/" target="_blank" style="color:#4169e1;" onclick="javascript:KindDisableMenu();">'+KE_LANG['ABOUT']+'</a><br />';
str += '</div>';
return str;
break;
default:
break;
}
}
function KindDrawIframe(cmd)
{
if (KE_BROWSER == 'IE') {
KE_IMAGE_DOCUMENT = document.frames("KindImageIframe").document;
KE_FLASH_DOCUMENT = document.frames("KindFlashIframe").document;
KE_MEDIA_DOCUMENT = document.frames("KindMediaIframe").document;
KE_REAL_DOCUMENT = document.frames("KindRealIframe").document;
KE_LINK_DOCUMENT = document.frames("KindLinkIframe").document;
} else {
KE_IMAGE_DOCUMENT = document.getElementById('KindImageIframe').contentDocument;
KE_FLASH_DOCUMENT = document.getElementById('KindFlashIframe').contentDocument;
KE_MEDIA_DOCUMENT = document.getElementById('KindMediaIframe').contentDocument;
KE_REAL_DOCUMENT = document.getElementById('KindRealIframe').contentDocument;
KE_LINK_DOCUMENT = document.getElementById('KindLinkIframe').contentDocument;
}
switch (cmd)
{
case 'KE_IMAGE':
var str = '';
str += '<div align="center">' +
'<form name="uploadForm" style="margin:0;padding:0;" method="post" enctype="multipart/form-data" ' +
'action="' + KE_IMAGE_UPLOAD_CGI + '" onsubmit="javascript:if(parent.KindDrawImageEnd()==false){return false;};">' +
'<input type="hidden" name="fileName" id="fileName" value="" />' +
'<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0" style="margin-bottom:3px;"><tr><td id="imgPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:50px;padding-left:5px;">';
if (KE_UPLOAD_MODE == true) {
str += '<select id="imageType" onchange="javascript:parent.KindImageType(this.value);document.getElementById(\''+cmd+'submitButton\').focus();"><option value="1" selected="selected">'+KE_LANG['LOCAL']+'</option><option value="2">'+KE_LANG['REMOTE']+'</option></select>';
} else {
str += KE_LANG['REMOTE'];
}
str += '</td><td style="width:200px;padding-bottom:3px;">';
if (KE_UPLOAD_MODE == true) {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;display:none;" />' +
'<input type="file" name="fileData" id="imgFile" size="14" style="border:1px solid #555555;" onclick="javascript:document.getElementById(\'imgLink\').value=\'http://\';" />';
} else {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;" />' +
'<input type="hidden" name="imageType" id="imageType" value="2"><input type="hidden" name="fileData" id="imgFile" value="" />';
}
str += '</td></tr><tr><td colspan="2" style="padding-bottom:3px;">' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="18%" style="padding:2px 2px 2px 5px;">'+KE_LANG['TITLE']+'</td><td width="82%"><input type="text" name="imgTitle" id="imgTitle" value="" maxlength="100" style="width:95%;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="10%" style="padding:2px 2px 2px 5px;">'+KE_LANG['WIDTH']+'</td><td width="23%"><input type="text" name="imgWidth" id="imgWidth" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['HEIGHT']+'</td><td width="23%"><input type="text" name="imgHeight" id="imgHeight" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['BORDER']+'</td><td width="23%"><input type="text" name="imgBorder" id="imgBorder" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="39%" style="padding:2px 2px 2px 5px;"><select id="imgAlign" name="imgAlign"><option value="">'+KE_LANG['ALIGN']+'</option>';
for (var i = 0; i < KE_IMAGE_ALIGN_TABLE.length; i++) {
str += '<option value="' + KE_IMAGE_ALIGN_TABLE[i] + '">' + KE_IMAGE_ALIGN_TABLE[i] + '</option>';
}
str += '</select></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['HSPACE']+'</td><td width="15%"><input type="text" name="imgHspace" id="imgHspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['VSPACE']+'</td><td width="15%"><input type="text" name="imgVspace" id="imgVspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'</td></tr><tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindImagePreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table></form></div>';
KindDrawMenuIframe(KE_IMAGE_DOCUMENT, str);
break;
case 'KE_FLASH':
var str = '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="flashPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="flashLink" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindFlashPreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawFlashEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
KindDrawMenuIframe(KE_FLASH_DOCUMENT, str);
break;
case 'KE_MEDIA':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_MEDIA_DOCUMENT, str);
break;
case 'KE_REAL':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_REAL_DOCUMENT, str);
break;
case 'KE_LINK':
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td style="width:50px;padding:5px;">URL</td>' +
'<td style="width:200px;padding-top:5px;padding-bottom:5px;"><input type="text" id="hyperLink" value="http://" style="width:190px;border:1px solid #555555;background-color:#FFFFFF;"></td>' +
'<tr><td style="padding:5px;">'+KE_LANG['TARGET']+'</td>' +
'<td style="padding-bottom:5px;"><select id="hyperLinkTarget"><option value="_blank" selected="selected">'+KE_LANG['NEW_WINDOW']+'</option><option value="">'+KE_LANG['CURRENT_WINDOW']+'</option></select></td></tr>' +
'<tr><td colspan="2" style="padding-bottom:5px;" align="center">' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawLinkEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>';
str += '</table>';
KindDrawMenuIframe(KE_LINK_DOCUMENT, str);
break;
default:
break;
}
}
function KindDrawMenuIframe(obj, str)
{
obj.open();
obj.write(str);
obj.close();
obj.body.style.color = KE_MENU_TEXT_COLOR;
obj.body.style.backgroundColor = KE_MENU_BG_COLOR;
obj.body.style.margin = 0;
obj.body.scroll = 'no';
}
function KindDrawTableSelected(i, j)
{
var text = i.toString(10) + ' by ' + j.toString(10) + ' Table';
document.getElementById('tableLocation').innerHTML = text;
var num = 10;
for (m = 1; m <= num; m++) {
for (n = 1; n <= num; n++) {
var obj = document.getElementById('kindTableTd' + m.toString(10) + '_' + n.toString(10) + '');
if (m <= i && n <= j) {
obj.style.backgroundColor = KE_MENU_SELECTED_COLOR;
} else {
obj.style.backgroundColor = '#FFFFFF';
}
}
}
}
function KindImageType(type)
{
if (type == 1) {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'block';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').value = 'http://';
} else {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'block';
}
KE_IMAGE_DOCUMENT.getElementById('imgPreview').innerHTML = " ";
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = 0;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = 0;
}
function KindImagePreview()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
if (type == 1) {
if (KE_BROWSER != 'IE') {
return false;
}
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
url = 'file:///' + file;
if (KindCheckImageFileType(url, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
var imgObj = KE_IMAGE_DOCUMENT.createElement("IMG");
imgObj.src = url;
var width = parseInt(imgObj.width);
var height = parseInt(imgObj.height);
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = width;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = height;
var rate = parseInt(width/height);
if (width >230 && height <= 230) {
width = 230;
height = parseInt(width/rate);
} else if (width <=230 && height > 230) {
height = 230;
width = parseInt(height*rate);
} else if (width >230 && height > 230) {
if (width >= height) {
width = 230;
height = parseInt(width/rate);
} else {
height = 230;
width = parseInt(height*rate);
}
}
imgObj.style.width = width;
imgObj.style.height = height;
var el = KE_IMAGE_DOCUMENT.getElementById('imgPreview');
if (el.hasChildNodes()) {
el.removeChild(el.childNodes[0]);
}
el.appendChild(imgObj);
return imgObj;
}
function KindDrawImageEnd()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
var width = KE_IMAGE_DOCUMENT.getElementById('imgWidth').value;
var height = KE_IMAGE_DOCUMENT.getElementById('imgHeight').value;
var border = KE_IMAGE_DOCUMENT.getElementById('imgBorder').value;
var title = KE_IMAGE_DOCUMENT.getElementById('imgTitle').value;
var align = KE_IMAGE_DOCUMENT.getElementById('imgAlign').value;
var hspace = KE_IMAGE_DOCUMENT.getElementById('imgHspace').value;
var vspace = KE_IMAGE_DOCUMENT.getElementById('imgVspace').value;
if (type == 1) {
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
if (KindCheckImageFileType(file, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
if (width.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_WIDTH']);
return false;
}
if (height.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HEIGHT']);
return false;
}
if (border.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_BORDER']);
return false;
}
if (hspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HSPACE']);
return false;
}
if (vspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_VSPACE']);
return false;
}
var fileName;
KindEditorForm.focus();
if (type == 1) {
fileName = KindGetFileName(file, "\\");
var fileExt = KindGetFileExt(fileName);
var dateObj = new Date();
var year = dateObj.getFullYear().toString(10);
var month = (dateObj.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = dateObj.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var ymd = year + month + day;
fileName = ymd + dateObj.getTime().toString(10) + '.' + fileExt;
KE_IMAGE_DOCUMENT.getElementById('fileName').value = fileName;
} else {
KindInsertImage(url, width, height, border, title, align, hspace, vspace);
}
}
function KindInsertImage(url, width, height, border, title, align, hspace, vspace)
{
var element = document.createElement("img");
element.src = url;
if (width > 0) {
element.style.width = width;
}
if (height > 0) {
element.style.height = height;
}
if (align != "") {
element.align = align;
}
if (hspace > 0) {
element.hspace = hspace;
}
if (vspace > 0) {
element.vspace = vspace;
}
element.border = border;
element.alt = KindHtmlentities(title);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
KindReloadIframe();
}
function KindGetFlashHtmlTag(url)
{
var str = '<embed src="'+url+'" type="application/x-shockwave-flash" quality="high"></embed>';
return str;
}
function KindFlashPreview()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
var el = KE_FLASH_DOCUMENT.getElementById('flashPreview');
el.innerHTML = KindGetFlashHtmlTag(url);
}
function KindDrawFlashEnd()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
obj.type = "application/x-shockwave-flash";
obj.quality = "high";
KindInsertItem(obj);
KindDisableMenu();
}
function KindGetMediaHtmlTag(cmd, url)
{
var str = '<embed src="'+url+'" type="';
if (cmd == "KE_REAL") {
str += 'audio/x-pn-realaudio-plugin';
} else {
str += 'video/x-ms-asf-plugin';
}
str += '" width="230" height="230" loop="true" autostart="true">';
return str;
}
function KindMediaPreview(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
var el = mediaDocument.getElementById(cmd+'preview');
el.innerHTML = KindGetMediaHtmlTag(cmd, url);
}
function KindDrawMediaEnd(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
if (cmd == 'KE_REAL') {
obj.type = 'audio/x-pn-realaudio-plugin';
} else {
obj.type = 'video/x-ms-asf-plugin';
}
obj.loop = 'true';
obj.autostart = 'true';
KindInsertItem(obj);
KindDisableMenu(cmd);
}
function KindDrawLinkEnd()
{
var range;
var url = KE_LINK_DOCUMENT.getElementById('hyperLink').value;
var target = KE_LINK_DOCUMENT.getElementById('hyperLinkTarget').value;
if (url.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
KindEditorForm.focus();
KindSelect();
var element;
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
var el = document.createElement("a");
el.href = url;
if (target) {
el.target = target;
}
KE_RANGE.item(0).applyElement(el);
} else if (KE_SELECTION.type.toLowerCase() == 'text') {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.parentElement();
if (target) {
element.target = target;
}
}
} else {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.startContainer.previousSibling;
element.target = target;
if (target) {
element.target = target;
}
}
KindDisableMenu();
}
function KindSelection()
{
if (KE_BROWSER == 'IE') {
KE_SELECTION = KE_EDITFORM_DOCUMENT.selection;
KE_RANGE = KE_SELECTION.createRange();
KE_RANGE_TEXT = KE_RANGE.text;
} else {
KE_SELECTION = document.getElementById("KindEditorForm").contentWindow.getSelection();
KE_RANGE = KE_SELECTION.getRangeAt(0);
KE_RANGE_TEXT = KE_RANGE.toString();
}
}
function KindSelect()
{
if (KE_BROWSER == 'IE') {
KE_RANGE.select();
}
}
function KindInsertItem(insertNode)
{
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
KE_RANGE.item(0).outerHTML = insertNode.outerHTML;
} else {
KE_RANGE.pasteHTML(insertNode.outerHTML);
}
} else {
KE_SELECTION.removeAllRanges();
KE_RANGE.deleteContents();
var startRangeNode = KE_RANGE.startContainer;
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
if (startRangeNode.nodeType == 3 && insertNode.nodeType == 3) {
startRangeNode.insertData(startRangeOffset, insertNode.nodeValue);
newRange.setEnd(startRangeNode, startRangeOffset + insertNode.length);
newRange.setStart(startRangeNode, startRangeOffset + insertNode.length);
} else {
var afterNode;
if (startRangeNode.nodeType == 3) {
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(insertNode, afterNode);
startRangeNode.insertBefore(beforeNode, insertNode);
startRangeNode.removeChild(textNode);
} else {
if (startRangeNode.tagName.toLowerCase() == 'html') {
startRangeNode = startRangeNode.childNodes[0].nextSibling;
afterNode = startRangeNode.childNodes[0];
} else {
afterNode = startRangeNode.childNodes[startRangeOffset];
}
startRangeNode.insertBefore(insertNode, afterNode);
}
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
}
KE_SELECTION.addRange(newRange);
}
}
function KindExecuteValue(cmd, value)
{
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, value);
}
function KindSimpleExecute(cmd)
{
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, null);
KindDisableMenu();
}
function KindExecute(cmd, value)
{
switch (cmd)
{
case 'KE_SOURCE':
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
document.getElementById("KindCodeForm").value = KindHtmlToXhtml(KE_EDITFORM_DOCUMENT.body.innerHTML);
document.getElementById("KindEditorIframe").style.display = 'none';
document.getElementById("KindEditTextarea").style.display = 'block';
KindDisableToolbar(true);
} else {
KE_EDITFORM_DOCUMENT.body.innerHTML = KindClearScriptTag(document.getElementById("KindCodeForm").value);
document.getElementById("KindEditTextarea").style.display = 'none';
document.getElementById("KindEditorIframe").style.display = 'block';
KindDisableToolbar(false);
}
KindDisableMenu();
break;
case 'KE_PRINT':
KindSimpleExecute('print');
break;
case 'KE_UNDO':
KindSimpleExecute('undo');
break;
case 'KE_REDO':
KindSimpleExecute('redo');
break;
case 'KE_CUT':
KindSimpleExecute('cut');
break;
case 'KE_COPY':
KindSimpleExecute('copy');
break;
case 'KE_PASTE':
KindSimpleExecute('paste');
break;
case 'KE_SELECTALL':
KindSimpleExecute('selectall');
break;
case 'KE_SUBSCRIPT':
KindSimpleExecute('subscript');
break;
case 'KE_SUPERSCRIPT':
KindSimpleExecute('superscript');
break;
case 'KE_BOLD':
KindSimpleExecute('bold');
break;
case 'KE_ITALIC':
KindSimpleExecute('italic');
break;
case 'KE_UNDERLINE':
KindSimpleExecute('underline');
break;
case 'KE_STRIKE':
KindSimpleExecute('strikethrough');
break;
case 'KE_JUSTIFYLEFT':
KindSimpleExecute('justifyleft');
break;
case 'KE_JUSTIFYCENTER':
KindSimpleExecute('justifycenter');
break;
case 'KE_JUSTIFYRIGHT':
KindSimpleExecute('justifyright');
break;
case 'KE_JUSTIFYFULL':
KindSimpleExecute('justifyfull');
break;
case 'KE_NUMBEREDLIST':
KindSimpleExecute('insertorderedlist');
break;
case 'KE_UNORDERLIST':
KindSimpleExecute('insertunorderedlist');
break;
case 'KE_INDENT':
KindSimpleExecute('indent');
break;
case 'KE_OUTDENT':
KindSimpleExecute('outdent');
break;
case 'KE_REMOVE':
KindSimpleExecute('removeformat');
break;
case 'KE_ZOOM':
KindDisplayMenu(cmd);
break;
case 'KE_ZOOM_END':
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.body.style.zoom = value;
KindDisableMenu();
break;
case 'KE_TITLE':
KindDisplayMenu(cmd);
break;
case 'KE_TITLE_END':
KindEditorForm.focus();
value = '<' + value + '>';
KindSelect();
KindExecuteValue('FormatBlock', value);
KindDisableMenu();
break;
case 'KE_FONTNAME':
KindDisplayMenu(cmd);
break;
case 'KE_FONTNAME_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('fontname', value);
KindDisableMenu();
break;
case 'KE_FONTSIZE':
KindDisplayMenu(cmd);
break;
case 'KE_FONTSIZE_END':
KindEditorForm.focus();
value = value.substr(0, 1);
KindSelect();
KindExecuteValue('fontsize', value);
KindDisableMenu();
break;
case 'KE_TEXTCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_TEXTCOLOR_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('ForeColor', value);
KindDisableMenu();
break;
case 'KE_BGCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_BGCOLOR_END':
KindEditorForm.focus();
if (KE_BROWSER == 'IE') {
KindSelect();
KindExecuteValue('BackColor', value);
} else {
var startRangeNode = KE_RANGE.startContainer;
if (startRangeNode.nodeType == 3) {
var parent = startRangeNode.parentNode;
var element = document.createElement("font");
element.style.backgroundColor = value;
element.appendChild(KE_RANGE.extractContents());
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
var afterNode;
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(element, afterNode);
startRangeNode.insertBefore(beforeNode, element);
startRangeNode.removeChild(textNode);
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
KE_SELECTION.addRange(newRange);
}
}
KindDisableMenu();
break;
case 'KE_ICON':
KindDisplayMenu(cmd);
break;
case 'KE_ICON_END':
KindEditorForm.focus();
var element = document.createElement("img");
element.src = value;
element.border = 0;
element.alt = "";
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_IMAGE':
KindDisplayMenu(cmd);
KindImageIframe.focus();
KE_IMAGE_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_FLASH':
KindDisplayMenu(cmd);
KindFlashIframe.focus();
KE_FLASH_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_MEDIA':
KindDisplayMenu(cmd);
KindMediaIframe.focus();
KE_MEDIA_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_REAL':
KindDisplayMenu(cmd);
KindRealIframe.focus();
KE_REAL_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_LINK':
KindDisplayMenu(cmd);
KindLinkIframe.focus();
KE_LINK_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_UNLINK':
KindSimpleExecute('unlink');
break;
case 'KE_SPECIALCHAR':
KindDisplayMenu(cmd);
break;
case 'KE_SPECIALCHAR_END':
KindEditorForm.focus();
KindSelect();
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_LAYER':
KindDisplayMenu(cmd);
break;
case 'KE_LAYER_END':
KindEditorForm.focus();
var element = document.createElement("div");
element.style.padding = "5px";
element.style.border = "1px solid #AAAAAA";
element.style.backgroundColor = value;
var childElement = document.createElement("div");
childElement.innerHTML = KE_LANG['INPUT_CONTENT'];
element.appendChild(childElement);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TABLE':
KindDisplayMenu(cmd);
break;
case 'KE_TABLE_END':
KindEditorForm.focus();
var location = value.split(',');
var element = document.createElement("table");
element.cellPadding = 0;
element.cellSpacing = 0;
element.border = 1;
element.style.width = "100px";
element.style.height = "100px";
for (var i = 0; i < location[0]; i++) {
var rowElement = element.insertRow(i);
for (var j = 0; j < location[1]; j++) {
var cellElement = rowElement.insertCell(j);
cellElement.innerHTML = " ";
}
}
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_HR':
KindDisplayMenu(cmd);
break;
case 'KE_HR_END':
KindEditorForm.focus();
var element = document.createElement("hr");
element.width = "100%";
element.color = value;
element.size = 1;
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_DATE':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var year = date.getFullYear().toString(10);
var month = (date.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = date.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var value = year + '-' + month + '-' + day;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TIME':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var hour = date.getHours().toString(10);
hour = hour.length < 2 ? '0' + hour : hour;
var minute = date.getMinutes().toString(10);
minute = minute.length < 2 ? '0' + minute : minute;
var second = date.getSeconds().toString(10);
second = second.length < 2 ? '0' + second : second;
var value = hour + ':' + minute + ':' + second;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_PREVIEW':
eval(KE_OBJ_NAME).data();
var newWin = window.open('', 'kindPreview','width=800,height=600,left=30,top=30,resizable=yes,scrollbars=yes');
KindWriteFullHtml(newWin.document, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
KindDisableMenu();
break;
case 'KE_ABOUT':
KindDisplayMenu(cmd);
break;
default:
break;
}
}
function KindDisableToolbar(flag)
{
if (flag == true) {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'design.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
if (KE_TOOLBAR_ICON[i][0] == 'KE_SOURCE' || KE_TOOLBAR_ICON[i][0] == 'KE_PREVIEW' || KE_TOOLBAR_ICON[i][0] == 'KE_ABOUT') {
continue;
}
el.style.visibility = 'hidden';
}
} else {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'source.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
el.style.visibility = 'visible';
KE_EDITFORM_DOCUMENT.designMode = 'On';
}
}
}
function KindCreateIcon(icon)
{
var str = '<img id="'+ icon[0] +'" src="' + KE_SKIN_PATH + icon[1] + '" alt="' + icon[2] + '" title="' + icon[2] +
'" align="absmiddle" style="border:1px solid ' + KE_TOOLBAR_BG_COLOR +';cursor:pointer;height:20px;';
str += '" onclick="javascript:KindExecute(\''+ icon[0] +'\');" '+
'onmouseover="javascript:this.style.border=\'1px solid ' + KE_MENU_BORDER_COLOR + '\';" ' +
'onmouseout="javascript:this.style.border=\'1px solid ' + KE_TOOLBAR_BG_COLOR + '\';" ';
str += '>';
return str;
}
function KindCreateToolbar()
{
var htmlData = '<table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
if (KE_EDITOR_TYPE == 'full') {
for (i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_TOP_TOOLBAR_ICON[i]) + '</td>';
}
htmlData += '</tr></table><table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
for (i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_BOTTOM_TOOLBAR_ICON[i]) + '</td>';
}
} else {
for (i = 0; i < KE_SIMPLE_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_SIMPLE_TOOLBAR_ICON[i]) + '</td>';
}
}
htmlData += '</tr></table>';
return htmlData;
}
function KindWriteFullHtml(documentObj, content)
{
var editHtmlData = '';
editHtmlData += '<html>\r\n<head>\r\n<title>KindEditor</title>\r\n';
editHtmlData += '<link href="'+KE_CSS_PATH+'" rel="stylesheet" type="text/css">\r\n</head>\r\n<body>\r\n';
editHtmlData += content;
editHtmlData += '\r\n</body>\r\n</html>\r\n';
documentObj.open();
documentObj.write(editHtmlData);
documentObj.close();
}
function KindEditor(objName)
{
this.objName = objName;
this.hiddenName = objName;
this.siteDomain;
this.editorType;
this.safeMode;
this.uploadMode;
this.editorWidth;
this.editorHeight;
this.skinPath;
this.iconPath;
this.imageAttachPath;
this.imageUploadCgi;
this.cssPath;
this.menuBorderColor;
this.menuBgColor;
this.menuTextColor;
this.menuSelectedColor;
this.toolbarBorderColor;
this.toolbarBgColor;
this.formBorderColor;
this.formBgColor;
this.buttonColor;
this.init = function()
{
if (this.siteDomain) KE_SITE_DOMAIN = this.siteDomain;
if (this.editorType) KE_EDITOR_TYPE = this.editorType.toLowerCase();
if (this.safeMode) KE_SAFE_MODE = this.safeMode;
if (this.uploadMode) KE_UPLOAD_MODE = this.uploadMode;
if (this.editorWidth) KE_WIDTH = this.editorWidth;
if (this.editorHeight) KE_HEIGHT = this.editorHeight;
if (this.skinPath) KE_SKIN_PATH = this.skinPath;
if (this.iconPath) KE_ICON_PATH = this.iconPath;
if (this.imageAttachPath) KE_IMAGE_ATTACH_PATH = this.imageAttachPath;
if (this.imageUploadCgi) KE_IMAGE_UPLOAD_CGI = this.imageUploadCgi;
if (this.cssPath) KE_CSS_PATH = this.cssPath;
if (this.menuBorderColor) KE_MENU_BORDER_COLOR = this.menuBorderColor;
if (this.menuBgColor) KE_MENU_BG_COLOR = this.menuBgColor;
if (this.menuTextColor) KE_MENU_TEXT_COLOR = this.menuTextColor;
if (this.menuSelectedColor) KE_MENU_SELECTED_COLOR = this.menuSelectedColor;
if (this.toolbarBorderColor) KE_TOOLBAR_BORDER_COLOR = this.toolbarBorderColor;
if (this.toolbarBgColor) KE_TOOLBAR_BG_COLOR = this.toolbarBgColor;
if (this.formBorderColor) KE_FORM_BORDER_COLOR = this.formBorderColor;
if (this.formBgColor) KE_FORM_BG_COLOR = this.formBgColor;
if (this.buttonColor) KE_BUTTON_COLOR = this.buttonColor;
KE_OBJ_NAME = this.objName;
KE_BROWSER = KindGetBrowser();
KE_TOOLBAR_ICON = Array();
for (var i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_TOP_TOOLBAR_ICON[i]);
}
for (var i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_BOTTOM_TOOLBAR_ICON[i]);
}
}
this.show = function()
{
this.init();
var widthStyle = 'width:' + KE_WIDTH + ';';
var widthArr = KE_WIDTH.match(/(\d+)([px%]{1,2})/);
var iframeWidthStyle = 'width:' + (parseInt(widthArr[1]) - 2).toString(10) + widthArr[2] + ';';
var heightStyle = 'height:' + KE_HEIGHT + ';';
var heightArr = KE_HEIGHT.match(/(\d+)([px%]{1,2})/);
var iframeHeightStyle = 'height:' + (parseInt(heightArr[1]) - 3).toString(10) + heightArr[2] + ';';
if (KE_BROWSER == '') {
var htmlData = '<div id="KindEditTextarea" style="' + widthStyle + heightStyle + '">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + widthStyle + heightStyle +
'padding:0;margin:0;border:1px solid '+ KE_FORM_BORDER_COLOR +
';font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';">' + document.getElementsByName(this.hiddenName)[0].value + '</textarea></div>';
document.open();
document.write(htmlData);
document.close();
return;
}
var htmlData = '<div style="font-family:'+KE_FONT_FAMILY+';">';
htmlData += '<div style="'+widthStyle+';border:1px solid ' + KE_TOOLBAR_BORDER_COLOR + ';background-color:'+ KE_TOOLBAR_BG_COLOR +'">';
htmlData += KindCreateToolbar();
htmlData += '</div><div id="KindEditorIframe" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';border-top:0;">' +
'<iframe name="KindEditorForm" id="KindEditorForm" frameborder="0" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;"></iframe></div>';
if (KE_EDITOR_TYPE == 'full') {
htmlData += '<div id="KindEditTextarea" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';background-color:'+
KE_FORM_BG_COLOR +';border-top:0;display:none;">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';" onclick="javascirit:parent.KindDisableMenu();"></textarea></div>';
}
htmlData += '</div>';
for (var i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
if (KE_POPUP_MENU_TABLE[i] == 'KE_IMAGE') {
htmlData += '<span id="InsertIframe">';
}
htmlData += KindPopupMenu(KE_POPUP_MENU_TABLE[i]);
if (KE_POPUP_MENU_TABLE[i] == 'KE_REAL') {
htmlData += '</span>';
}
}
document.open();
document.write(htmlData);
document.close();
if (KE_BROWSER == 'IE') {
KE_EDITFORM_DOCUMENT = document.frames("KindEditorForm").document;
} else {
KE_EDITFORM_DOCUMENT = document.getElementById('KindEditorForm').contentDocument;
}
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
KindDrawIframe('KE_LINK');
KE_EDITFORM_DOCUMENT.designMode = 'On';
KindWriteFullHtml(KE_EDITFORM_DOCUMENT, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
var el = KE_EDITFORM_DOCUMENT.body;
if (KE_EDITFORM_DOCUMENT.addEventListener){
KE_EDITFORM_DOCUMENT.addEventListener('click', KindDisableMenu, false);
} else if (el.attachEvent){
el.attachEvent('onclick', KindDisableMenu);
}
}
this.data = function()
{
var htmlResult;
if (KE_BROWSER == '') {
htmlResult = document.getElementById("KindCodeForm").value;
} else {
if (KE_EDITOR_TYPE == 'full') {
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
} else {
htmlResult = document.getElementById("KindCodeForm").value;
}
} else {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
}
}
KindDisableMenu();
htmlResult = KindHtmlToXhtml(htmlResult);
htmlResult = KindClearScriptTag(htmlResult);
document.getElementsByName(this.hiddenName)[0].value = htmlResult;
return htmlResult;
}
}
| JavaScript |
var teButtons = TextileEditor.buttons;
teButtons.push(new TextileEditorButton('ed_strong', 'bold.png', '*', '*', 'b', 'Bold','s'));
teButtons.push(new TextileEditorButton('ed_emphasis', 'italic.png', '_', '_', 'i', 'Italicize','s'));
teButtons.push(new TextileEditorButton('ed_underline', 'underline.png', '+', '+', 'u', 'Underline','s'));
teButtons.push(new TextileEditorButton('ed_strike', 'strikethrough.png', '-', '-', 's', 'Strikethrough','s'));
teButtons.push(new TextileEditorButton('ed_ol', 'list_numbers.png', ' # ', '\n', ',', 'Numbered List'));
teButtons.push(new TextileEditorButton('ed_ul', 'list_bullets.png', ' * ', '\n', '.', 'Bulleted List'));
teButtons.push(new TextileEditorButton('ed_p', 'paragraph.png', 'p', '\n', 'p', 'Paragraph'));
teButtons.push(new TextileEditorButton('ed_h1', 'h1.png', 'h1', '\n', '1', 'Header 1'));
teButtons.push(new TextileEditorButton('ed_h2', 'h2.png', 'h2', '\n', '2', 'Header 2'));
teButtons.push(new TextileEditorButton('ed_h3', 'h3.png', 'h3', '\n', '3', 'Header 3'));
teButtons.push(new TextileEditorButton('ed_h4', 'h4.png', 'h4', '\n', '4', 'Header 4'));
teButtons.push(new TextileEditorButton('ed_block', 'blockquote.png', 'bq', '\n', 'q', 'Blockquote'));
teButtons.push(new TextileEditorButton('ed_outdent', 'outdent.png', ')', '\n', ']', 'Outdent'));
teButtons.push(new TextileEditorButton('ed_indent', 'indent.png', '(', '\n', '[', 'Indent'));
teButtons.push(new TextileEditorButton('ed_justifyl', 'left.png', '<', '\n', 'l', 'Left Justify'));
teButtons.push(new TextileEditorButton('ed_justifyc', 'center.png', '=', '\n', 'e', 'Center Text'));
teButtons.push(new TextileEditorButton('ed_justifyr', 'right.png', '>', '\n', 'r', 'Right Justify'));
teButtons.push(new TextileEditorButton('ed_justify', 'justify.png', '<>', '\n', 'j', 'Justify'));
// teButtons.push(new TextileEditorButton('ed_code','code','@','@','c','Code')); | JavaScript |
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
| JavaScript |
/**
* WYSIWYG HTML Editor for Internet
*
* @author Roddy <luolonghao@gmail.com>
* @version 2.5.3
*/
var KE_VERSION = "2.5.4";
var KE_EDITOR_TYPE = "full"; //full or simple
var KE_SAFE_MODE = false; // true or false
var KE_UPLOAD_MODE = true; // true or false
var KE_FONT_FAMILY = "Courier New";
var KE_WIDTH = "700px";
var KE_HEIGHT = "400px";
var KE_SITE_DOMAIN = "";
var KE_SKIN_PATH = "./skins/default/";
var KE_ICON_PATH = "./icons/";
var KE_IMAGE_ATTACH_PATH = "./attached/";
var KE_IMAGE_UPLOAD_CGI = "./upload_cgi/upload.php";
var KE_CSS_PATH = "/editor/common.css";
var KE_MENU_BORDER_COLOR = '#AAAAAA';
var KE_MENU_BG_COLOR = '#EFEFEF';
var KE_MENU_TEXT_COLOR = '#222222';
var KE_MENU_SELECTED_COLOR = '#CCCCCC';
var KE_TOOLBAR_BORDER_COLOR = '#DDDDDD';
var KE_TOOLBAR_BG_COLOR = '#EFEFEF';
var KE_FORM_BORDER_COLOR = '#DDDDDD';
var KE_FORM_BG_COLOR = '#FFFFFF';
var KE_BUTTON_COLOR = '#AAAAAA';
var KE_LANG = {
INPUT_URL : "请输入正确的URL地址。",
SELECT_IMAGE : "请选择图片。",
INVALID_IMAGE : "只能选择GIF,JPG,PNG,BMP格式的图片,请重新选择。",
INVALID_FLASH : "只能选择SWF格式的文件,请重新选择。",
INVALID_MEDIA : "只能选择MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF格式的文件,请重新选择。",
INVALID_REAL : "只能选择RM,RMVB格式的文件,请重新选择。",
INVALID_WIDTH : "宽度不是数字,请重新输入。",
INVALID_HEIGHT : "高度不是数字,请重新输入。",
INVALID_BORDER : "边框不是数字,请重新输入。",
INVALID_HSPACE : "横隔不是数字,请重新输入。",
INVALID_VSPACE : "竖隔不是数字,请重新输入。",
INPUT_CONTENT : "请输入内容",
TITLE : "描述",
WIDTH : "宽",
HEIGHT : "高",
BORDER : "边",
ALIGN : "对齐方式",
HSPACE : "横隔",
VSPACE : "竖隔",
CONFIRM : "确定",
CANCEL : "取消",
PREVIEW : "预览",
LISTENING : "试听",
LOCAL : "本地",
REMOTE : "远程",
NEW_WINDOW : "新窗口",
CURRENT_WINDOW : "当前窗口",
TARGET : "目标",
ABOUT : "访问技术支持网站",
SUBJECT : "标题"
}
var KE_FONT_NAME = Array(
Array('SimSun', '宋体'),
Array('SimHei', '黑体'),
Array('FangSong_GB2312', '仿宋体'),
Array('KaiTi_GB2312', '楷体'),
Array('NSimSun', '新宋体'),
Array('Arial', 'Arial'),
Array('Arial Black', 'Arial Black'),
Array('Times New Roman', 'Times New Roman'),
Array('Courier New', 'Courier New'),
Array('Tahoma', 'Tahoma'),
Array('Verdana', 'Verdana'),
Array('GulimChe', 'GulimChe'),
Array('MS Gothic', 'MS Gothic')
);
var KE_SPECIAL_CHARACTER = Array(
'§','№','☆','★','○','●','◎','◇','◆','□','℃','‰','■','△','▲','※',
'→','←','↑','↓','〓','¤','°','#','&','@','\','︿','_',' ̄','―','α',
'β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ',
'σ','τ','υ','φ','χ','ψ','ω','≈','≡','≠','=','≤','≥','<','>','≮',
'≯','∷','±','+','-','×','÷','/','∫','∮','∝','∞','∧','∨','∑','∏',
'∪','∩','∈','∵','∴','⊥','∥','∠','⌒','⊙','≌','∽','〖','〗',
'【','】','(',')','[',']'
);
var KE_TOP_TOOLBAR_ICON = Array(
Array('KE_SOURCE', 'source.gif', '视图转换'),
Array('KE_PREVIEW', 'preview.gif', '预览'),
Array('KE_ZOOM', 'zoom.gif', '显示比例'),
Array('KE_PRINT', 'print.gif', '打印'),
Array('KE_UNDO', 'undo.gif', '回退'),
Array('KE_REDO', 'redo.gif', '前进'),
Array('KE_CUT', 'cut.gif', '剪切'),
Array('KE_COPY', 'copy.gif', '复制'),
Array('KE_PASTE', 'paste.gif', '粘贴'),
Array('KE_SELECTALL', 'selectall.gif', '全选'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_JUSTIFYFULL', 'justifyfull.gif', '两端对齐'),
Array('KE_NUMBEREDLIST', 'numberedlist.gif', '编号'),
Array('KE_UNORDERLIST', 'unorderedlist.gif', '项目符号'),
Array('KE_INDENT', 'indent.gif', '减少缩进'),
Array('KE_OUTDENT', 'outdent.gif', '增加缩进'),
Array('KE_SUBSCRIPT', 'subscript.gif', '下标'),
Array('KE_SUPERSCRIPT', 'superscript.gif', '上标'),
Array('KE_DATE', 'date.gif', '日期'),
Array('KE_TIME', 'time.gif', '时间')
);
var KE_BOTTOM_TOOLBAR_ICON = Array(
Array('KE_TITLE', 'title.gif', '标题'),
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_STRIKE', 'strikethrough.gif', '删除线'),
Array('KE_REMOVE', 'removeformat.gif', '删除格式'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_FLASH', 'flash.gif', 'Flash'),
Array('KE_MEDIA', 'media.gif', 'Windows Media Player'),
Array('KE_REAL', 'real.gif', 'Real Player'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_TABLE', 'table.gif', '表格'),
Array('KE_SPECIALCHAR', 'specialchar.gif', '特殊字符'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_UNLINK', 'unlink.gif', '删除超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_SIMPLE_TOOLBAR_ICON = Array(
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_TITLE_TABLE = Array(
Array('H1', KE_LANG['SUBJECT'] + ' 1'),
Array('H2', KE_LANG['SUBJECT'] + ' 2'),
Array('H3', KE_LANG['SUBJECT'] + ' 3'),
Array('H4', KE_LANG['SUBJECT'] + ' 4'),
Array('H5', KE_LANG['SUBJECT'] + ' 5'),
Array('H6', KE_LANG['SUBJECT'] + ' 6')
);
var KE_ZOOM_TABLE = Array('250%', '200%', '150%', '120%', '100%', '80%', '50%');
var KE_FONT_SIZE = Array(
Array(1,'8pt'),
Array(2,'10pt'),
Array(3,'12pt'),
Array(4,'14pt'),
Array(5,'18pt'),
Array(6,'24pt'),
Array(7,'36pt')
);
var KE_POPUP_MENU_TABLE = Array(
"KE_ZOOM", "KE_TITLE", "KE_FONTNAME", "KE_FONTSIZE", "KE_TEXTCOLOR", "KE_BGCOLOR",
"KE_LAYER", "KE_TABLE", "KE_HR", "KE_ICON", "KE_SPECIALCHAR", "KE_ABOUT",
"KE_IMAGE", "KE_FLASH", "KE_MEDIA", "KE_REAL", "KE_LINK"
);
var KE_COLOR_TABLE = Array(
"#FF0000", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#FF00FF", "#FFFFFF", "#F5F5F5", "#DCDCDC", "#FFFAFA",
"#D3D3D3", "#C0C0C0", "#A9A9A9", "#808080", "#696969", "#000000", "#2F4F4F", "#708090", "#778899", "#4682B4",
"#4169E1", "#6495ED", "#B0C4DE", "#7B68EE", "#6A5ACD", "#483D8B", "#191970", "#000080", "#00008B", "#0000CD",
"#1E90FF", "#00BFFF", "#87CEFA", "#87CEEB", "#ADD8E6", "#B0E0E6", "#F0FFFF", "#E0FFFF", "#AFEEEE", "#00CED1",
"#5F9EA0", "#48D1CC", "#00FFFF", "#40E0D0", "#20B2AA", "#008B8B", "#008080", "#7FFFD4", "#66CDAA", "#8FBC8F",
"#3CB371", "#2E8B57", "#006400", "#008000", "#228B22", "#32CD32", "#00FF00", "#7FFF00", "#7CFC00", "#ADFF2F",
"#98FB98", "#90EE90", "#00FF7F", "#00FA9A", "#556B2F", "#6B8E23", "#808000", "#BDB76B", "#B8860B", "#DAA520",
"#FFD700", "#F0E68C", "#EEE8AA", "#FFEBCD", "#FFE4B5", "#F5DEB3", "#FFDEAD", "#DEB887", "#D2B48C", "#BC8F8F",
"#A0522D", "#8B4513", "#D2691E", "#CD853F", "#F4A460", "#8B0000", "#800000", "#A52A2A", "#B22222", "#CD5C5C",
"#F08080", "#FA8072", "#E9967A", "#FFA07A", "#FF7F50", "#FF6347", "#FF8C00", "#FFA500", "#FF4500", "#DC143C",
"#FF0000", "#FF1493", "#FF00FF", "#FF69B4", "#FFB6C1", "#FFC0CB", "#DB7093", "#C71585", "#800080", "#8B008B",
"#9370DB", "#8A2BE2", "#4B0082", "#9400D3", "#9932CC", "#BA55D3", "#DA70D6", "#EE82EE", "#DDA0DD", "#D8BFD8",
"#E6E6FA", "#F8F8FF", "#F0F8FF", "#F5FFFA", "#F0FFF0", "#FAFAD2", "#FFFACD", "#FFF8DC", "#FFFFE0", "#FFFFF0",
"#FFFAF0", "#FAF0E6", "#FDF5E6", "#FAEBD7", "#FFE4C4", "#FFDAB9", "#FFEFD5", "#FFF5EE", "#FFF0F5", "#FFE4E1"
);
var KE_IMAGE_ALIGN_TABLE = Array(
"baseline", "top", "middle", "bottom", "texttop", "absmiddle", "absbottom", "left", "right"
);
var KE_OBJ_NAME;
var KE_SELECTION;
var KE_RANGE;
var KE_RANGE_TEXT;
var KE_EDITFORM_DOCUMENT;
var KE_IMAGE_DOCUMENT;
var KE_FLASH_DOCUMENT;
var KE_MEDIA_DOCUMENT;
var KE_REAL_DOCUMENT;
var KE_LINK_DOCUMENT;
var KE_BROWSER;
var KE_TOOLBAR_ICON;
function KindGetBrowser()
{
var browser = '';
var agentInfo = navigator.userAgent.toLowerCase();
if (agentInfo.indexOf("msie") > -1) {
var re = new RegExp("msie\\s?([\\d\\.]+)","ig");
var arr = re.exec(agentInfo);
if (parseInt(RegExp.$1) >= 5.5) {
browser = 'IE';
}
} else if (agentInfo.indexOf("firefox") > -1) {
browser = 'FF';
} else if (agentInfo.indexOf("netscape") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[temp1.length-1].split('/');
if (parseInt(temp2[1]) >= 7) {
browser = 'NS';
}
} else if (agentInfo.indexOf("gecko") > -1) {
browser = 'ML';
} else if (agentInfo.indexOf("opera") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[0].split('/');
if (parseInt(temp2[1]) >= 9) {
browser = 'OPERA';
}
}
return browser;
}
function KindGetFileName(file, separator)
{
var temp = file.split(separator);
var len = temp.length;
var fileName = temp[len-1];
return fileName;
}
function KindGetFileExt(fileName)
{
var temp = fileName.split(".");
var len = temp.length;
var fileExt = temp[len-1].toLowerCase();
return fileExt;
}
function KindCheckImageFileType(file, separator)
{
if (separator == "/" && file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, separator);
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'gif' && fileExt != 'jpg' && fileExt != 'png' && fileExt != 'bmp') {
alert(KE_LANG['INVALID_IMAGE']);
return false;
}
return true;
}
function KindCheckFlashFileType(file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'swf') {
alert(KE_LANG['INVALID_FLASH']);
return false;
}
return true;
}
function KindCheckMediaFileType(cmd, file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (cmd == 'KE_REAL') {
if (fileExt != 'rm' && fileExt != 'rmvb') {
alert(KE_LANG['INVALID_REAL']);
return false;
}
} else {
if (fileExt != 'mp3' && fileExt != 'wav' && fileExt != 'wma' && fileExt != 'wmv' && fileExt != 'mid' && fileExt != 'avi' && fileExt != 'mpg' && fileExt != 'asf') {
alert(KE_LANG['INVALID_MEDIA']);
return false;
}
}
return true;
}
function KindHtmlToXhtml(str)
{
str = str.replace(/<br.*?>/gi, "<br />");
str = str.replace(/(<hr\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<img\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<\w+)(.*?>)/gi, function ($0,$1,$2) {
return($1.toLowerCase() + KindConvertAttribute($2));
}
);
str = str.replace(/(<\/\w+>)/gi, function ($0,$1) {
return($1.toLowerCase());
}
);
return str;
}
function KindConvertAttribute(str)
{
if (KE_SAFE_MODE == true) {
str = KindClearAttributeScriptTag(str);
}
return str;
}
function KindClearAttributeScriptTag(str)
{
var re = new RegExp("(\\son[a-z]+=)[\"']?[^>]*?[^\\\\\>][\"']?([\\s>])","ig");
str = str.replace(re, function ($0,$1,$2) {
return($1.toLowerCase() + "\"\"" + $2);
}
);
return str;
}
function KindClearScriptTag(str)
{
if (KE_SAFE_MODE == false) {
return str;
}
str = str.replace(/<(script.*?)>/gi, "[$1]");
str = str.replace(/<\/script>/gi, "[/script]");
return str;
}
function KindHtmlentities(str)
{
str = str.replace(/&/g,'&');
str = str.replace(/</g,'<');
str = str.replace(/>/g,'>');
str = str.replace(/"/g,'"');
return str;
}
function KindGetTop(id)
{
var top = 28;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
top += eval("obj" + tmp).offsetTop;
}
return top;
}
function KindGetLeft(id)
{
var left = 2;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
left += eval("obj" + tmp).offsetLeft;
}
return left;
}
function KindDisplayMenu(cmd)
{
KindEditorForm.focus();
if (cmd != 'KE_ABOUT') {
KindSelection();
}
KindDisableMenu();
var top, left;
top = KindGetTop(cmd);
left = KindGetLeft(cmd);
if (cmd == 'KE_ABOUT') {
left -= 200;
} else if (cmd == 'KE_LINK') {
left -= 220;
}
document.getElementById('POPUP_'+cmd).style.top = top.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.left = left.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.display = 'block';
}
function KindDisableMenu()
{
for (i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
document.getElementById('POPUP_'+KE_POPUP_MENU_TABLE[i]).style.display = 'none';
}
}
function KindReloadIframe()
{
var str = '';
str += KindPopupMenu('KE_IMAGE');
str += KindPopupMenu('KE_FLASH');
str += KindPopupMenu('KE_MEDIA');
str += KindPopupMenu('KE_REAL');
document.getElementById('InsertIframe').innerHTML = str;
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
}
function KindGetMenuCommonStyle()
{
var str = 'position:absolute;top:1px;left:1px;font-size:12px;color:'+KE_MENU_TEXT_COLOR+
';background-color:'+KE_MENU_BG_COLOR+';border:solid 1px '+KE_MENU_BORDER_COLOR+';z-index:1;display:none;';
return str;
}
function KindGetCommonMenu(cmd, content)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="'+KindGetMenuCommonStyle()+'">';
str += content;
str += '</div>';
return str;
}
function KindCreateColorTable(cmd, eventStr)
{
var str = '';
str += '<table cellpadding="0" cellspacing="2" border="0">';
for (i = 0; i < KE_COLOR_TABLE.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="width:12px;height:12px;border:1px solid #AAAAAA;font-size:1px;cursor:pointer;background-color:' +
KE_COLOR_TABLE[i] + ';" onmouseover="javascript:this.style.borderColor=\'#000000\';' + ((eventStr) ? eventStr : '') + '" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onclick="javascript:KindExecute(\''+cmd+'_END\', \'' + KE_COLOR_TABLE[i] + '\');"> </td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
}
function KindDrawColorTable(cmd)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;padding:2px;'+KindGetMenuCommonStyle()+'">';
str += KindCreateColorTable(cmd);
str += '</div>';
return str;
}
function KindDrawMedia(cmd)
{
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="'+cmd+'preview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="'+cmd+'link" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['LISTENING']+'" onclick="javascript:parent.KindMediaPreview(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawMediaEnd(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
return str;
}
function KindPopupMenu(cmd)
{
switch (cmd)
{
case 'KE_ZOOM':
var str = '';
for (i = 0; i < KE_ZOOM_TABLE.length; i++) {
str += '<div style="padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ZOOM_END\', \'' + KE_ZOOM_TABLE[i] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_ZOOM_TABLE[i] + '</div>';
}
str = KindGetCommonMenu('KE_ZOOM', str);
return str;
break;
case 'KE_TITLE':
var str = '';
for (i = 0; i < KE_TITLE_TABLE.length; i++) {
str += '<div style="width:140px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TITLE_END\', \'' + KE_TITLE_TABLE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';"><' + KE_TITLE_TABLE[i][0] + ' style="margin:2px;">' +
KE_TITLE_TABLE[i][1] + '</' + KE_TITLE_TABLE[i][0] + '></div>';
}
str = KindGetCommonMenu('KE_TITLE', str);
return str;
break;
case 'KE_FONTNAME':
var str = '';
for (i = 0; i < KE_FONT_NAME.length; i++) {
str += '<div style="font-family:' + KE_FONT_NAME[i][0] +
';padding:2px;width:160px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTNAME_END\', \'' + KE_FONT_NAME[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_NAME[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTNAME', str);
return str;
break;
case 'KE_FONTSIZE':
var str = '';
for (i = 0; i < KE_FONT_SIZE.length; i++) {
str += '<div style="font-size:' + KE_FONT_SIZE[i][1] +
';padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTSIZE_END\', \'' + KE_FONT_SIZE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_SIZE[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTSIZE', str);
return str;
break;
case 'KE_TEXTCOLOR':
var str = '';
str = KindDrawColorTable('KE_TEXTCOLOR');
return str;
break;
case 'KE_BGCOLOR':
var str = '';
str = KindDrawColorTable('KE_BGCOLOR');
return str;
break;
case 'KE_HR':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="hrPreview" style="margin:10px 2px 10px 2px;height:1px;border:0;font-size:0;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'hrPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_LAYER':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="divPreview" style="margin:5px 2px 5px 2px;height:20px;border:1px solid #AAAAAA;font-size:1px;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'divPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_ICON':
var str = '';
var iconNum = 36;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < iconNum; i++) {
if (i == 0 || (i >= 6 && i%6 == 0)) {
str += '<tr>';
}
var num;
if ((i+1).toString(10).length < 2) {
num = '0' + (i+1);
} else {
num = (i+1).toString(10);
}
var iconUrl = KE_ICON_PATH + 'etc_' + num + '.gif';
str += '<td style="padding:2px;border:0;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ICON_END\', \'' + iconUrl + '\');">' +
'<img src="' + iconUrl + '" style="border:1px solid #EEEEEE;" onmouseover="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#EEEEEE\';">' + '</td>';
if (i >= 5 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_SPECIALCHAR':
var str = '';
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < KE_SPECIAL_CHARACTER.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="padding:2px;border:1px solid #AAAAAA;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_SPECIALCHAR_END\', \'' + KE_SPECIAL_CHARACTER[i] + '\');" ' +
'onmouseover="javascript:this.style.borderColor=\'#000000\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';">' + KE_SPECIAL_CHARACTER[i] + '</td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_TABLE':
var str = '';
var num = 10;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="0" style="'+KindGetMenuCommonStyle()+'">';
for (i = 1; i <= num; i++) {
str += '<tr>';
for (j = 1; j <= num; j++) {
var value = i.toString(10) + ',' + j.toString(10);
str += '<td id="kindTableTd' + i.toString(10) + '_' + j.toString(10) +
'" style="width:15px;height:15px;background-color:#FFFFFF;border:1px solid #DDDDDD;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TABLE_END\', \'' + value + '\');" ' +
'onmouseover="javascript:KindDrawTableSelected(\''+i.toString(10)+'\', \''+j.toString(10)+'\');" ' +
'onmouseout="javascript:;"> </td>';
}
str += '</tr>';
}
str += '<tr><td colspan="10" id="tableLocation" style="text-align:center;height:20px;"></td></tr>';
str += '</table>';
return str;
break;
case 'KE_IMAGE':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindImageIframe" id="KindImageIframe" frameborder="0" style="width:250px;height:390px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_FLASH':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindFlashIframe" id="KindFlashIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_MEDIA':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindMediaIframe" id="KindMediaIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_REAL':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindRealIframe" id="KindRealIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_LINK':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindLinkIframe" id="KindLinkIframe" frameborder="0" style="width:250px;height:85px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_ABOUT':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:230px;'+KindGetMenuCommonStyle()+';padding:5px;">';
str += '<span style="margin-right:10px;">KindEditor ' + KE_VERSION + '</span>' +
'<a href="http://www.kindsoft.net/" target="_blank" style="color:#4169e1;" onclick="javascript:KindDisableMenu();">'+KE_LANG['ABOUT']+'</a><br />';
str += '</div>';
return str;
break;
default:
break;
}
}
function KindDrawIframe(cmd)
{
if (KE_BROWSER == 'IE') {
KE_IMAGE_DOCUMENT = document.frames("KindImageIframe").document;
KE_FLASH_DOCUMENT = document.frames("KindFlashIframe").document;
KE_MEDIA_DOCUMENT = document.frames("KindMediaIframe").document;
KE_REAL_DOCUMENT = document.frames("KindRealIframe").document;
KE_LINK_DOCUMENT = document.frames("KindLinkIframe").document;
} else {
KE_IMAGE_DOCUMENT = document.getElementById('KindImageIframe').contentDocument;
KE_FLASH_DOCUMENT = document.getElementById('KindFlashIframe').contentDocument;
KE_MEDIA_DOCUMENT = document.getElementById('KindMediaIframe').contentDocument;
KE_REAL_DOCUMENT = document.getElementById('KindRealIframe').contentDocument;
KE_LINK_DOCUMENT = document.getElementById('KindLinkIframe').contentDocument;
}
switch (cmd)
{
case 'KE_IMAGE':
var str = '';
str += '<div align="center">' +
'<form name="uploadForm" style="margin:0;padding:0;" method="post" enctype="multipart/form-data" ' +
'action="' + KE_IMAGE_UPLOAD_CGI + '" onsubmit="javascript:if(parent.KindDrawImageEnd()==false){return false;};">' +
'<input type="hidden" name="fileName" id="fileName" value="" />' +
'<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0" style="margin-bottom:3px;"><tr><td id="imgPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:50px;padding-left:5px;">';
if (KE_UPLOAD_MODE == true) {
str += '<select id="imageType" onchange="javascript:parent.KindImageType(this.value);document.getElementById(\''+cmd+'submitButton\').focus();"><option value="1" selected="selected">'+KE_LANG['LOCAL']+'</option><option value="2">'+KE_LANG['REMOTE']+'</option></select>';
} else {
str += KE_LANG['REMOTE'];
}
str += '</td><td style="width:200px;padding-bottom:3px;">';
if (KE_UPLOAD_MODE == true) {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;display:none;" />' +
'<input type="file" name="fileData" id="imgFile" size="14" style="border:1px solid #555555;" onclick="javascript:document.getElementById(\'imgLink\').value=\'http://\';" />';
} else {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;" />' +
'<input type="hidden" name="imageType" id="imageType" value="2"><input type="hidden" name="fileData" id="imgFile" value="" />';
}
str += '</td></tr><tr><td colspan="2" style="padding-bottom:3px;">' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="18%" style="padding:2px 2px 2px 5px;">'+KE_LANG['TITLE']+'</td><td width="82%"><input type="text" name="imgTitle" id="imgTitle" value="" maxlength="100" style="width:95%;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="10%" style="padding:2px 2px 2px 5px;">'+KE_LANG['WIDTH']+'</td><td width="23%"><input type="text" name="imgWidth" id="imgWidth" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['HEIGHT']+'</td><td width="23%"><input type="text" name="imgHeight" id="imgHeight" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['BORDER']+'</td><td width="23%"><input type="text" name="imgBorder" id="imgBorder" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="39%" style="padding:2px 2px 2px 5px;"><select id="imgAlign" name="imgAlign"><option value="">'+KE_LANG['ALIGN']+'</option>';
for (var i = 0; i < KE_IMAGE_ALIGN_TABLE.length; i++) {
str += '<option value="' + KE_IMAGE_ALIGN_TABLE[i] + '">' + KE_IMAGE_ALIGN_TABLE[i] + '</option>';
}
str += '</select></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['HSPACE']+'</td><td width="15%"><input type="text" name="imgHspace" id="imgHspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['VSPACE']+'</td><td width="15%"><input type="text" name="imgVspace" id="imgVspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'</td></tr><tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindImagePreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table></form></div>';
KindDrawMenuIframe(KE_IMAGE_DOCUMENT, str);
break;
case 'KE_FLASH':
var str = '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="flashPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="flashLink" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindFlashPreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawFlashEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
KindDrawMenuIframe(KE_FLASH_DOCUMENT, str);
break;
case 'KE_MEDIA':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_MEDIA_DOCUMENT, str);
break;
case 'KE_REAL':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_REAL_DOCUMENT, str);
break;
case 'KE_LINK':
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td style="width:50px;padding:5px;">URL</td>' +
'<td style="width:200px;padding-top:5px;padding-bottom:5px;"><input type="text" id="hyperLink" value="http://" style="width:190px;border:1px solid #555555;background-color:#FFFFFF;"></td>' +
'<tr><td style="padding:5px;">'+KE_LANG['TARGET']+'</td>' +
'<td style="padding-bottom:5px;"><select id="hyperLinkTarget"><option value="_blank" selected="selected">'+KE_LANG['NEW_WINDOW']+'</option><option value="">'+KE_LANG['CURRENT_WINDOW']+'</option></select></td></tr>' +
'<tr><td colspan="2" style="padding-bottom:5px;" align="center">' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawLinkEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>';
str += '</table>';
KindDrawMenuIframe(KE_LINK_DOCUMENT, str);
break;
default:
break;
}
}
function KindDrawMenuIframe(obj, str)
{
obj.open();
obj.write(str);
obj.close();
obj.body.style.color = KE_MENU_TEXT_COLOR;
obj.body.style.backgroundColor = KE_MENU_BG_COLOR;
obj.body.style.margin = 0;
obj.body.scroll = 'no';
}
function KindDrawTableSelected(i, j)
{
var text = i.toString(10) + ' by ' + j.toString(10) + ' Table';
document.getElementById('tableLocation').innerHTML = text;
var num = 10;
for (m = 1; m <= num; m++) {
for (n = 1; n <= num; n++) {
var obj = document.getElementById('kindTableTd' + m.toString(10) + '_' + n.toString(10) + '');
if (m <= i && n <= j) {
obj.style.backgroundColor = KE_MENU_SELECTED_COLOR;
} else {
obj.style.backgroundColor = '#FFFFFF';
}
}
}
}
function KindImageType(type)
{
if (type == 1) {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'block';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').value = 'http://';
} else {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'block';
}
KE_IMAGE_DOCUMENT.getElementById('imgPreview').innerHTML = " ";
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = 0;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = 0;
}
function KindImagePreview()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
if (type == 1) {
if (KE_BROWSER != 'IE') {
return false;
}
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
url = 'file:///' + file;
if (KindCheckImageFileType(url, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
var imgObj = KE_IMAGE_DOCUMENT.createElement("IMG");
imgObj.src = url;
var width = parseInt(imgObj.width);
var height = parseInt(imgObj.height);
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = width;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = height;
var rate = parseInt(width/height);
if (width >230 && height <= 230) {
width = 230;
height = parseInt(width/rate);
} else if (width <=230 && height > 230) {
height = 230;
width = parseInt(height*rate);
} else if (width >230 && height > 230) {
if (width >= height) {
width = 230;
height = parseInt(width/rate);
} else {
height = 230;
width = parseInt(height*rate);
}
}
imgObj.style.width = width;
imgObj.style.height = height;
var el = KE_IMAGE_DOCUMENT.getElementById('imgPreview');
if (el.hasChildNodes()) {
el.removeChild(el.childNodes[0]);
}
el.appendChild(imgObj);
return imgObj;
}
function KindDrawImageEnd()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
var width = KE_IMAGE_DOCUMENT.getElementById('imgWidth').value;
var height = KE_IMAGE_DOCUMENT.getElementById('imgHeight').value;
var border = KE_IMAGE_DOCUMENT.getElementById('imgBorder').value;
var title = KE_IMAGE_DOCUMENT.getElementById('imgTitle').value;
var align = KE_IMAGE_DOCUMENT.getElementById('imgAlign').value;
var hspace = KE_IMAGE_DOCUMENT.getElementById('imgHspace').value;
var vspace = KE_IMAGE_DOCUMENT.getElementById('imgVspace').value;
if (type == 1) {
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
if (KindCheckImageFileType(file, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
if (width.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_WIDTH']);
return false;
}
if (height.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HEIGHT']);
return false;
}
if (border.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_BORDER']);
return false;
}
if (hspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HSPACE']);
return false;
}
if (vspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_VSPACE']);
return false;
}
var fileName;
KindEditorForm.focus();
if (type == 1) {
fileName = KindGetFileName(file, "\\");
var fileExt = KindGetFileExt(fileName);
var dateObj = new Date();
var year = dateObj.getFullYear().toString(10);
var month = (dateObj.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = dateObj.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var ymd = year + month + day;
fileName = ymd + dateObj.getTime().toString(10) + '.' + fileExt;
KE_IMAGE_DOCUMENT.getElementById('fileName').value = fileName;
} else {
KindInsertImage(url, width, height, border, title, align, hspace, vspace);
}
}
function KindInsertImage(url, width, height, border, title, align, hspace, vspace)
{
var element = document.createElement("img");
element.src = url;
if (width > 0) {
element.style.width = width;
}
if (height > 0) {
element.style.height = height;
}
if (align != "") {
element.align = align;
}
if (hspace > 0) {
element.hspace = hspace;
}
if (vspace > 0) {
element.vspace = vspace;
}
element.border = border;
element.alt = KindHtmlentities(title);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
KindReloadIframe();
}
function KindGetFlashHtmlTag(url)
{
var str = '<embed src="'+url+'" type="application/x-shockwave-flash" quality="high"></embed>';
return str;
}
function KindFlashPreview()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
var el = KE_FLASH_DOCUMENT.getElementById('flashPreview');
el.innerHTML = KindGetFlashHtmlTag(url);
}
function KindDrawFlashEnd()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
obj.type = "application/x-shockwave-flash";
obj.quality = "high";
KindInsertItem(obj);
KindDisableMenu();
}
function KindGetMediaHtmlTag(cmd, url)
{
var str = '<embed src="'+url+'" type="';
if (cmd == "KE_REAL") {
str += 'audio/x-pn-realaudio-plugin';
} else {
str += 'video/x-ms-asf-plugin';
}
str += '" width="230" height="230" loop="true" autostart="true">';
return str;
}
function KindMediaPreview(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
var el = mediaDocument.getElementById(cmd+'preview');
el.innerHTML = KindGetMediaHtmlTag(cmd, url);
}
function KindDrawMediaEnd(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
if (cmd == 'KE_REAL') {
obj.type = 'audio/x-pn-realaudio-plugin';
} else {
obj.type = 'video/x-ms-asf-plugin';
}
obj.loop = 'true';
obj.autostart = 'true';
KindInsertItem(obj);
KindDisableMenu(cmd);
}
function KindDrawLinkEnd()
{
var range;
var url = KE_LINK_DOCUMENT.getElementById('hyperLink').value;
var target = KE_LINK_DOCUMENT.getElementById('hyperLinkTarget').value;
if (url.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
KindEditorForm.focus();
KindSelect();
var element;
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
var el = document.createElement("a");
el.href = url;
if (target) {
el.target = target;
}
KE_RANGE.item(0).applyElement(el);
} else if (KE_SELECTION.type.toLowerCase() == 'text') {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.parentElement();
if (target) {
element.target = target;
}
}
} else {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.startContainer.previousSibling;
element.target = target;
if (target) {
element.target = target;
}
}
KindDisableMenu();
}
function KindSelection()
{
if (KE_BROWSER == 'IE') {
KE_SELECTION = KE_EDITFORM_DOCUMENT.selection;
KE_RANGE = KE_SELECTION.createRange();
KE_RANGE_TEXT = KE_RANGE.text;
} else {
KE_SELECTION = document.getElementById("KindEditorForm").contentWindow.getSelection();
KE_RANGE = KE_SELECTION.getRangeAt(0);
KE_RANGE_TEXT = KE_RANGE.toString();
}
}
function KindSelect()
{
if (KE_BROWSER == 'IE') {
KE_RANGE.select();
}
}
function KindInsertItem(insertNode)
{
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
KE_RANGE.item(0).outerHTML = insertNode.outerHTML;
} else {
KE_RANGE.pasteHTML(insertNode.outerHTML);
}
} else {
KE_SELECTION.removeAllRanges();
KE_RANGE.deleteContents();
var startRangeNode = KE_RANGE.startContainer;
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
if (startRangeNode.nodeType == 3 && insertNode.nodeType == 3) {
startRangeNode.insertData(startRangeOffset, insertNode.nodeValue);
newRange.setEnd(startRangeNode, startRangeOffset + insertNode.length);
newRange.setStart(startRangeNode, startRangeOffset + insertNode.length);
} else {
var afterNode;
if (startRangeNode.nodeType == 3) {
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(insertNode, afterNode);
startRangeNode.insertBefore(beforeNode, insertNode);
startRangeNode.removeChild(textNode);
} else {
if (startRangeNode.tagName.toLowerCase() == 'html') {
startRangeNode = startRangeNode.childNodes[0].nextSibling;
afterNode = startRangeNode.childNodes[0];
} else {
afterNode = startRangeNode.childNodes[startRangeOffset];
}
startRangeNode.insertBefore(insertNode, afterNode);
}
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
}
KE_SELECTION.addRange(newRange);
}
}
function KindExecuteValue(cmd, value)
{
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, value);
}
function KindSimpleExecute(cmd)
{
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, null);
KindDisableMenu();
}
function KindExecute(cmd, value)
{
switch (cmd)
{
case 'KE_SOURCE':
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
document.getElementById("KindCodeForm").value = KindHtmlToXhtml(KE_EDITFORM_DOCUMENT.body.innerHTML);
document.getElementById("KindEditorIframe").style.display = 'none';
document.getElementById("KindEditTextarea").style.display = 'block';
KindDisableToolbar(true);
} else {
KE_EDITFORM_DOCUMENT.body.innerHTML = KindClearScriptTag(document.getElementById("KindCodeForm").value);
document.getElementById("KindEditTextarea").style.display = 'none';
document.getElementById("KindEditorIframe").style.display = 'block';
KindDisableToolbar(false);
}
KindDisableMenu();
break;
case 'KE_PRINT':
KindSimpleExecute('print');
break;
case 'KE_UNDO':
KindSimpleExecute('undo');
break;
case 'KE_REDO':
KindSimpleExecute('redo');
break;
case 'KE_CUT':
KindSimpleExecute('cut');
break;
case 'KE_COPY':
KindSimpleExecute('copy');
break;
case 'KE_PASTE':
KindSimpleExecute('paste');
break;
case 'KE_SELECTALL':
KindSimpleExecute('selectall');
break;
case 'KE_SUBSCRIPT':
KindSimpleExecute('subscript');
break;
case 'KE_SUPERSCRIPT':
KindSimpleExecute('superscript');
break;
case 'KE_BOLD':
KindSimpleExecute('bold');
break;
case 'KE_ITALIC':
KindSimpleExecute('italic');
break;
case 'KE_UNDERLINE':
KindSimpleExecute('underline');
break;
case 'KE_STRIKE':
KindSimpleExecute('strikethrough');
break;
case 'KE_JUSTIFYLEFT':
KindSimpleExecute('justifyleft');
break;
case 'KE_JUSTIFYCENTER':
KindSimpleExecute('justifycenter');
break;
case 'KE_JUSTIFYRIGHT':
KindSimpleExecute('justifyright');
break;
case 'KE_JUSTIFYFULL':
KindSimpleExecute('justifyfull');
break;
case 'KE_NUMBEREDLIST':
KindSimpleExecute('insertorderedlist');
break;
case 'KE_UNORDERLIST':
KindSimpleExecute('insertunorderedlist');
break;
case 'KE_INDENT':
KindSimpleExecute('indent');
break;
case 'KE_OUTDENT':
KindSimpleExecute('outdent');
break;
case 'KE_REMOVE':
KindSimpleExecute('removeformat');
break;
case 'KE_ZOOM':
KindDisplayMenu(cmd);
break;
case 'KE_ZOOM_END':
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.body.style.zoom = value;
KindDisableMenu();
break;
case 'KE_TITLE':
KindDisplayMenu(cmd);
break;
case 'KE_TITLE_END':
KindEditorForm.focus();
value = '<' + value + '>';
KindSelect();
KindExecuteValue('FormatBlock', value);
KindDisableMenu();
break;
case 'KE_FONTNAME':
KindDisplayMenu(cmd);
break;
case 'KE_FONTNAME_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('fontname', value);
KindDisableMenu();
break;
case 'KE_FONTSIZE':
KindDisplayMenu(cmd);
break;
case 'KE_FONTSIZE_END':
KindEditorForm.focus();
value = value.substr(0, 1);
KindSelect();
KindExecuteValue('fontsize', value);
KindDisableMenu();
break;
case 'KE_TEXTCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_TEXTCOLOR_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('ForeColor', value);
KindDisableMenu();
break;
case 'KE_BGCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_BGCOLOR_END':
KindEditorForm.focus();
if (KE_BROWSER == 'IE') {
KindSelect();
KindExecuteValue('BackColor', value);
} else {
var startRangeNode = KE_RANGE.startContainer;
if (startRangeNode.nodeType == 3) {
var parent = startRangeNode.parentNode;
var element = document.createElement("font");
element.style.backgroundColor = value;
element.appendChild(KE_RANGE.extractContents());
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
var afterNode;
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(element, afterNode);
startRangeNode.insertBefore(beforeNode, element);
startRangeNode.removeChild(textNode);
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
KE_SELECTION.addRange(newRange);
}
}
KindDisableMenu();
break;
case 'KE_ICON':
KindDisplayMenu(cmd);
break;
case 'KE_ICON_END':
KindEditorForm.focus();
var element = document.createElement("img");
element.src = value;
element.border = 0;
element.alt = "";
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_IMAGE':
KindDisplayMenu(cmd);
KindImageIframe.focus();
KE_IMAGE_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_FLASH':
KindDisplayMenu(cmd);
KindFlashIframe.focus();
KE_FLASH_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_MEDIA':
KindDisplayMenu(cmd);
KindMediaIframe.focus();
KE_MEDIA_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_REAL':
KindDisplayMenu(cmd);
KindRealIframe.focus();
KE_REAL_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_LINK':
KindDisplayMenu(cmd);
KindLinkIframe.focus();
KE_LINK_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_UNLINK':
KindSimpleExecute('unlink');
break;
case 'KE_SPECIALCHAR':
KindDisplayMenu(cmd);
break;
case 'KE_SPECIALCHAR_END':
KindEditorForm.focus();
KindSelect();
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_LAYER':
KindDisplayMenu(cmd);
break;
case 'KE_LAYER_END':
KindEditorForm.focus();
var element = document.createElement("div");
element.style.padding = "5px";
element.style.border = "1px solid #AAAAAA";
element.style.backgroundColor = value;
var childElement = document.createElement("div");
childElement.innerHTML = KE_LANG['INPUT_CONTENT'];
element.appendChild(childElement);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TABLE':
KindDisplayMenu(cmd);
break;
case 'KE_TABLE_END':
KindEditorForm.focus();
var location = value.split(',');
var element = document.createElement("table");
element.cellPadding = 0;
element.cellSpacing = 0;
element.border = 1;
element.style.width = "100px";
element.style.height = "100px";
for (var i = 0; i < location[0]; i++) {
var rowElement = element.insertRow(i);
for (var j = 0; j < location[1]; j++) {
var cellElement = rowElement.insertCell(j);
cellElement.innerHTML = " ";
}
}
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_HR':
KindDisplayMenu(cmd);
break;
case 'KE_HR_END':
KindEditorForm.focus();
var element = document.createElement("hr");
element.width = "100%";
element.color = value;
element.size = 1;
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_DATE':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var year = date.getFullYear().toString(10);
var month = (date.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = date.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var value = year + '-' + month + '-' + day;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TIME':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var hour = date.getHours().toString(10);
hour = hour.length < 2 ? '0' + hour : hour;
var minute = date.getMinutes().toString(10);
minute = minute.length < 2 ? '0' + minute : minute;
var second = date.getSeconds().toString(10);
second = second.length < 2 ? '0' + second : second;
var value = hour + ':' + minute + ':' + second;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_PREVIEW':
eval(KE_OBJ_NAME).data();
var newWin = window.open('', 'kindPreview','width=800,height=600,left=30,top=30,resizable=yes,scrollbars=yes');
KindWriteFullHtml(newWin.document, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
KindDisableMenu();
break;
case 'KE_ABOUT':
KindDisplayMenu(cmd);
break;
default:
break;
}
}
function KindDisableToolbar(flag)
{
if (flag == true) {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'design.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
if (KE_TOOLBAR_ICON[i][0] == 'KE_SOURCE' || KE_TOOLBAR_ICON[i][0] == 'KE_PREVIEW' || KE_TOOLBAR_ICON[i][0] == 'KE_ABOUT') {
continue;
}
el.style.visibility = 'hidden';
}
} else {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'source.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
el.style.visibility = 'visible';
KE_EDITFORM_DOCUMENT.designMode = 'On';
}
}
}
function KindCreateIcon(icon)
{
var str = '<img id="'+ icon[0] +'" src="' + KE_SKIN_PATH + icon[1] + '" alt="' + icon[2] + '" title="' + icon[2] +
'" align="absmiddle" style="border:1px solid ' + KE_TOOLBAR_BG_COLOR +';cursor:pointer;height:20px;';
str += '" onclick="javascript:KindExecute(\''+ icon[0] +'\');" '+
'onmouseover="javascript:this.style.border=\'1px solid ' + KE_MENU_BORDER_COLOR + '\';" ' +
'onmouseout="javascript:this.style.border=\'1px solid ' + KE_TOOLBAR_BG_COLOR + '\';" ';
str += '>';
return str;
}
function KindCreateToolbar()
{
var htmlData = '<table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
if (KE_EDITOR_TYPE == 'full') {
for (i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_TOP_TOOLBAR_ICON[i]) + '</td>';
}
htmlData += '</tr></table><table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
for (i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_BOTTOM_TOOLBAR_ICON[i]) + '</td>';
}
} else {
for (i = 0; i < KE_SIMPLE_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_SIMPLE_TOOLBAR_ICON[i]) + '</td>';
}
}
htmlData += '</tr></table>';
return htmlData;
}
function KindWriteFullHtml(documentObj, content)
{
var editHtmlData = '';
editHtmlData += '<html>\r\n<head>\r\n<title>KindEditor</title>\r\n';
editHtmlData += '<link href="'+KE_CSS_PATH+'" rel="stylesheet" type="text/css">\r\n</head>\r\n<body>\r\n';
editHtmlData += content;
editHtmlData += '\r\n</body>\r\n</html>\r\n';
documentObj.open();
documentObj.write(editHtmlData);
documentObj.close();
}
function KindEditor(objName)
{
this.objName = objName;
this.hiddenName = objName;
this.siteDomain;
this.editorType;
this.safeMode;
this.uploadMode;
this.editorWidth;
this.editorHeight;
this.skinPath;
this.iconPath;
this.imageAttachPath;
this.imageUploadCgi;
this.cssPath;
this.menuBorderColor;
this.menuBgColor;
this.menuTextColor;
this.menuSelectedColor;
this.toolbarBorderColor;
this.toolbarBgColor;
this.formBorderColor;
this.formBgColor;
this.buttonColor;
this.init = function()
{
if (this.siteDomain) KE_SITE_DOMAIN = this.siteDomain;
if (this.editorType) KE_EDITOR_TYPE = this.editorType.toLowerCase();
if (this.safeMode) KE_SAFE_MODE = this.safeMode;
if (this.uploadMode) KE_UPLOAD_MODE = this.uploadMode;
if (this.editorWidth) KE_WIDTH = this.editorWidth;
if (this.editorHeight) KE_HEIGHT = this.editorHeight;
if (this.skinPath) KE_SKIN_PATH = this.skinPath;
if (this.iconPath) KE_ICON_PATH = this.iconPath;
if (this.imageAttachPath) KE_IMAGE_ATTACH_PATH = this.imageAttachPath;
if (this.imageUploadCgi) KE_IMAGE_UPLOAD_CGI = this.imageUploadCgi;
if (this.cssPath) KE_CSS_PATH = this.cssPath;
if (this.menuBorderColor) KE_MENU_BORDER_COLOR = this.menuBorderColor;
if (this.menuBgColor) KE_MENU_BG_COLOR = this.menuBgColor;
if (this.menuTextColor) KE_MENU_TEXT_COLOR = this.menuTextColor;
if (this.menuSelectedColor) KE_MENU_SELECTED_COLOR = this.menuSelectedColor;
if (this.toolbarBorderColor) KE_TOOLBAR_BORDER_COLOR = this.toolbarBorderColor;
if (this.toolbarBgColor) KE_TOOLBAR_BG_COLOR = this.toolbarBgColor;
if (this.formBorderColor) KE_FORM_BORDER_COLOR = this.formBorderColor;
if (this.formBgColor) KE_FORM_BG_COLOR = this.formBgColor;
if (this.buttonColor) KE_BUTTON_COLOR = this.buttonColor;
KE_OBJ_NAME = this.objName;
KE_BROWSER = KindGetBrowser();
KE_TOOLBAR_ICON = Array();
for (var i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_TOP_TOOLBAR_ICON[i]);
}
for (var i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_BOTTOM_TOOLBAR_ICON[i]);
}
}
this.show = function()
{
this.init();
var widthStyle = 'width:' + KE_WIDTH + ';';
var widthArr = KE_WIDTH.match(/(\d+)([px%]{1,2})/);
var iframeWidthStyle = 'width:' + (parseInt(widthArr[1]) - 2).toString(10) + widthArr[2] + ';';
var heightStyle = 'height:' + KE_HEIGHT + ';';
var heightArr = KE_HEIGHT.match(/(\d+)([px%]{1,2})/);
var iframeHeightStyle = 'height:' + (parseInt(heightArr[1]) - 3).toString(10) + heightArr[2] + ';';
if (KE_BROWSER == '') {
var htmlData = '<div id="KindEditTextarea" style="' + widthStyle + heightStyle + '">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + widthStyle + heightStyle +
'padding:0;margin:0;border:1px solid '+ KE_FORM_BORDER_COLOR +
';font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';">' + document.getElementsByName(this.hiddenName)[0].value + '</textarea></div>';
document.open();
document.write(htmlData);
document.close();
return;
}
var htmlData = '<div style="font-family:'+KE_FONT_FAMILY+';">';
htmlData += '<div style="'+widthStyle+';border:1px solid ' + KE_TOOLBAR_BORDER_COLOR + ';background-color:'+ KE_TOOLBAR_BG_COLOR +'">';
htmlData += KindCreateToolbar();
htmlData += '</div><div id="KindEditorIframe" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';border-top:0;">' +
'<iframe name="KindEditorForm" id="KindEditorForm" frameborder="0" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;"></iframe></div>';
if (KE_EDITOR_TYPE == 'full') {
htmlData += '<div id="KindEditTextarea" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';background-color:'+
KE_FORM_BG_COLOR +';border-top:0;display:none;">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';" onclick="javascirit:parent.KindDisableMenu();"></textarea></div>';
}
htmlData += '</div>';
for (var i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
if (KE_POPUP_MENU_TABLE[i] == 'KE_IMAGE') {
htmlData += '<span id="InsertIframe">';
}
htmlData += KindPopupMenu(KE_POPUP_MENU_TABLE[i]);
if (KE_POPUP_MENU_TABLE[i] == 'KE_REAL') {
htmlData += '</span>';
}
}
document.open();
document.write(htmlData);
document.close();
if (KE_BROWSER == 'IE') {
KE_EDITFORM_DOCUMENT = document.frames("KindEditorForm").document;
} else {
KE_EDITFORM_DOCUMENT = document.getElementById('KindEditorForm').contentDocument;
}
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
KindDrawIframe('KE_LINK');
KE_EDITFORM_DOCUMENT.designMode = 'On';
KindWriteFullHtml(KE_EDITFORM_DOCUMENT, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
var el = KE_EDITFORM_DOCUMENT.body;
if (KE_EDITFORM_DOCUMENT.addEventListener){
KE_EDITFORM_DOCUMENT.addEventListener('click', KindDisableMenu, false);
} else if (el.attachEvent){
el.attachEvent('onclick', KindDisableMenu);
}
}
this.data = function()
{
var htmlResult;
if (KE_BROWSER == '') {
htmlResult = document.getElementById("KindCodeForm").value;
} else {
if (KE_EDITOR_TYPE == 'full') {
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
} else {
htmlResult = document.getElementById("KindCodeForm").value;
}
} else {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
}
}
KindDisableMenu();
htmlResult = KindHtmlToXhtml(htmlResult);
htmlResult = KindClearScriptTag(htmlResult);
document.getElementsByName(this.hiddenName)[0].value = htmlResult;
return htmlResult;
}
}
| JavaScript |
/*
Textile Editor v0.2
created by: dave olsen, wvu web services
created on: march 17, 2007
project page: slateinfo.blogs.wvu.edu
inspired by:
- Patrick Woods, http://www.hakjoon.com/code/38/textile-quicktags-redirect &
- Alex King, http://alexking.org/projects/js-quicktags
features:
- supports: IE7, FF2, Safari2
- ability to use "simple" vs. "extended" editor
- supports all block elements in textile except footnote
- supports all block modifier elements in textile
- supports simple ordered and unordered lists
- supports most of the phrase modifiers, very easy to add the missing ones
- supports multiple-paragraph modification
- can have multiple "editors" on one page, access key use in this environment is flaky
- access key support
- select text to add and remove tags, selection stays highlighted
- seamlessly change between tags and modifiers
- doesn't need to be in the body onload tag
- can supply your own, custom IDs for the editor to be drawn around
todo:
- a clean way of providing image and link inserts
- get the selection to properly show in IE
more on textile:
- Textism, http://www.textism.com/tools/textile/index.php
- Textile Reference, http://hobix.com/textile/
*/
// Define Button Object
function TextileEditorButton(id, display, tagStart, tagEnd, access, title, sve, open) {
this.id = id; // used to name the toolbar button
this.display = display; // label on button
this.tagStart = tagStart; // open tag
this.tagEnd = tagEnd; // close tag
this.access = access; // set to -1 if tag does not need to be closed
this.title = title; // sets the title attribute of the button to give 'tool tips'
this.sve = sve; // sve = simple vs. extended. add an 's' to make it show up in the simple toolbar
this.open = open; // set to -1 if tag does not need to be closed
this.standard = true; // this is a standard button
}
function TextileEditorButtonSeparator(sve) {
this.separator = true;
this.sve = sve;
}
var TextileEditor = Class.create();
TextileEditor.buttons = new Array();
TextileEditor.Methods = {
// class methods
// create the toolbar (edToolbar)
initialize: function(canvas, view) {
var toolbar = document.createElement("div");
toolbar.id = "textile-toolbar-" + canvas;
toolbar.className = 'textile-toolbar';
this.canvas = document.getElementById(canvas);
this.canvas.parentNode.insertBefore(toolbar, this.canvas);
this.openTags = new Array();
// Create the local Button array by assigning theButtons array to edButtons
var edButtons = new Array();
edButtons = this.buttons;
var standardButtons = new Array();
for(var i = 0; i < edButtons.length; i++) {
var thisButton = this.prepareButton(edButtons[i]);
if (view == 's') {
if (edButtons[i].sve == 's') {
toolbar.appendChild(thisButton);
standardButtons.push(thisButton);
}
} else {
if (typeof thisButton == 'string') {
toolbar.innerHTML += thisButton;
} else {
toolbar.appendChild(thisButton);
standardButtons.push(thisButton);
}
}
} // end for
var te = this;
$A(toolbar.getElementsByTagName('button')).each(function(button) {
if (!button.onclick) {
button.onclick = function() { te.insertTag(button); return false; }
} // end if
button.tagStart = button.getAttribute('tagStart');
button.tagEnd = button.getAttribute('tagEnd');
button.open = button.getAttribute('open');
button.textile_editor = te;
button.canvas = te.canvas;
});
}, // end initialize
// draw individual buttons (edShowButton)
prepareButton: function(button) {
if (button.separator) {
var theButton = document.createElement('span');
theButton.className = 'ed_sep';
return theButton;
}
if (button.standard) {
var theButton = document.createElement("button");
theButton.id = button.id;
theButton.setAttribute('class', 'standard');
theButton.setAttribute('tagStart', button.tagStart);
theButton.setAttribute('tagEnd', button.tagEnd);
theButton.setAttribute('open', button.open);
var img = document.createElement('img');
img.src = '/images/textile-editor/' + button.display;
theButton.appendChild(img);
} else {
return button;
} // end if !custom
theButton.accessKey = button.access;
theButton.title = button.title;
return theButton;
}, // end prepareButton
// if clicked, no selected text, tag not open highlight button
// (edAddTag)
addTag: function(button) {
if (button.tagEnd != '') {
this.openTags[this.openTags.length] = button;
//var el = document.getElementById(button.id);
//el.className = 'selected';
button.className = 'selected';
}
}, // end addTag
// if clicked, no selected text, tag open lowlight button
// (edRemoveTag)
removeTag: function(button) {
for (i = 0; i < this.openTags.length; i++) {
if (this.openTags[i] == button) {
this.openTags.splice(button, 1);
//var el = document.getElementById(button.id);
//el.className = 'unselected';
button.className = 'unselected';
}
}
}, // end removeTag
// see if there are open tags. for the remove tag bit...
// (edCheckOpenTags)
checkOpenTags: function(button) {
var tag = 0;
for (i = 0; i < this.openTags.length; i++) {
if (this.openTags[i] == button) {
tag++;
}
}
if (tag > 0) {
return true; // tag found
}
else {
return false; // tag not found
}
}, // end checkOpenTags
// insert the tag. this is the bulk of the code.
// (edInsertTag)
insertTag: function(button, tagStart, tagEnd) {
var myField = button.canvas;
myField.focus();
if (tagStart) {
button.tagStart = tagStart;
button.tagEnd = tagEnd ? tagEnd : '\n';
}
var textSelected = false;
var finalText = '';
var FF = false;
// grab the text that's going to be manipulated, by browser
if (document.selection) { // IE support
sel = document.selection.createRange();
// set-up the text vars
var beginningText = '';
var followupText = '';
var selectedText = sel.text;
// check if text has been selected
if (sel.text.length > 0) {
textSelected = true;
}
// set-up newline regex's so we can swap tags across multiple paragraphs
var newlineReplaceRegexClean = /\r\n\s\n/g;
var newlineReplaceRegexDirty = '\\r\\n\\s\\n';
var newlineReplaceClean = '\r\n\n';
}
else if (myField.selectionStart || myField.selectionStart == '0') { // MOZ/FF/NS/S support
// figure out cursor and selection positions
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
var cursorPos = endPos;
var scrollTop = myField.scrollTop;
FF = true; // note that is is a FF/MOZ/NS/S browser
// set-up the text vars
var beginningText = myField.value.substring(0, startPos);
var followupText = myField.value.substring(endPos, myField.value.length);
// check if text has been selected
if (startPos != endPos) {
textSelected = true;
var selectedText = myField.value.substring(startPos, endPos);
}
// set-up newline regex's so we can swap tags across multiple paragraphs
var newlineReplaceRegexClean = /\n\n/g;
var newlineReplaceRegexDirty = '\\n\\n';
var newlineReplaceClean = '\n\n';
}
// if there is text that has been highlighted...
if (textSelected) {
// set-up some defaults for how to handle bad new line characters
var newlineStart = '';
var newlineStartPos = 0;
var newlineEnd = '';
var newlineEndPos = 0;
var newlineFollowup = '';
// set-up some defaults for how to handle placing the beginning and end of selection
var posDiffPos = 0;
var posDiffNeg = 0;
var mplier = 1;
// remove newline from the beginning of the selectedText.
if (selectedText.match(/^\n/)) {
selectedText = selectedText.replace(/^\n/,'');
newlineStart = '\n';
newlineStartpos = 1;
}
// remove newline from the end of the selectedText.
if (selectedText.match(/\n$/g)) {
selectedText = selectedText.replace(/\n$/g,'');
newlineEnd = '\n';
newlineEndPos = 1;
}
// no clue, i'm sure it made sense at the time i wrote it
if (followupText.match(/^\n/)) {
newlineFollowup = '';
}
else {
newlineFollowup = '\n\n';
}
// first off let's check if the user is trying to mess with lists
if ((button.tagStart == ' * ') || (button.tagStart == ' # ')) {
listItems = 0; // sets up a default to be able to properly manipulate final selection
// set-up all of the regex's
re_start = new RegExp('^ (\\*|\\#) ','g');
if (button.tagStart == ' # ') {
re_tag = new RegExp(' \\# ','g'); // because of JS regex stupidity i need an if/else to properly set it up, could have done it with a regex replace though
}
else {
re_tag = new RegExp(' \\* ','g');
}
re_replace = new RegExp(' (\\*|\\#) ','g');
// try to remove bullets in text copied from ms word **Mac Only!**
re_word_bullet_m_s = new RegExp('• ','g'); // mac/safari
re_word_bullet_m_f = new RegExp('∑ ','g'); // mac/firefox
selectedText = selectedText.replace(re_word_bullet_m_s,'').replace(re_word_bullet_m_f,'');
// if the selected text starts with one of the tags we're working with...
if (selectedText.match(re_start)) {
// if tag that begins the selection matches the one clicked, remove them all
if (selectedText.match(re_tag)) {
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_replace,'')
+ newlineEnd
+ followupText;
if (matches = selectedText.match(/ (\*|\#) /g)) {
listItems = matches.length;
}
posDiffNeg = listItems*3; // how many list items were there because that's 3 spaces to remove from final selection
}
// else replace the current tag type with the selected tag type
else {
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_replace,button.tagStart)
+ newlineEnd
+ followupText;
}
}
// else try to create the list type
// NOTE: the items in a list will only be replaced if a newline starts with some character, not a space
else {
finalText = beginningText
+ newlineStart
+ button.tagStart
+ selectedText.replace(newlineReplaceRegexClean,newlineReplaceClean + button.tagStart).replace(/\n(\S)/g,'\n' + button.tagStart + '$1')
+ newlineEnd
+ followupText;
if (matches = selectedText.match(/\n(\S)/g)) {
listItems = matches.length;
}
posDiffPos = 3 + listItems*3;
}
}
// now lets look and see if the user is trying to muck with a block or block modifier
else if (button.tagStart.match(/^(h1|h2|h3|h4|h5|h6|bq|p|\>|\<\>|\<|\=|\(|\))/g)) {
var insertTag = '';
var insertModifier = '';
var tagPartBlock = '';
var tagPartModifier = '';
var tagPartModifierOrig = ''; // ugly hack but it's late
var drawSwitch = '';
var captureIndentStart = false;
var captureListStart = false;
var periodAddition = '\\. ';
var periodAdditionClean = '. ';
var listItemsAddition = 0;
var re_list_items = new RegExp('(\\*+|\\#+)','g'); // need this regex later on when checking indentation of lists
var re_block_modifier = new RegExp('^(h1|h2|h3|h4|h5|h6|bq|p| [\\*]{1,} | [\\#]{1,} |)(\\>|\\<\\>|\\<|\\=|[\\(]{1,}|[\\)]{1,6}|)','g');
if (tagPartMatches = re_block_modifier.exec(selectedText)) {
tagPartBlock = tagPartMatches[1];
tagPartModifier = tagPartMatches[2];
tagPartModifierOrig = tagPartMatches[2];
tagPartModifierOrig = tagPartModifierOrig.replace(/\(/g,"\\(");
}
// if tag already up is the same as the tag provided replace the whole tag
if (tagPartBlock == button.tagStart) {
insertTag = tagPartBlock + tagPartModifierOrig; // use Orig because it's escaped for regex
drawSwitch = 0;
}
// else if let's check to add/remove block modifier
else if ((tagPartModifier == button.tagStart) || (newm = tagPartModifier.match(/[\(]{2,}/g))) {
if ((button.tagStart == '(') || (button.tagStart == ')')) {
var indentLength = tagPartModifier.length;
if (button.tagStart == '(') {
indentLength = indentLength + 1;
}
else {
indentLength = indentLength - 1;
}
for (var i = 0; i < indentLength; i++) {
insertModifier = insertModifier + '(';
}
insertTag = tagPartBlock + insertModifier;
}
else {
if (button.tagStart == tagPartModifier) {
insertTag = tagPartBlock;
} // going to rely on the default empty insertModifier
else {
if (button.tagStart.match(/(\>|\<\>|\<|\=)/g)) {
insertTag = tagPartBlock + button.tagStart;
}
else {
insertTag = button.tagStart + tagPartModifier;
}
}
}
drawSwitch = 1;
}
// indentation of list items
else if (listPartMatches = re_list_items.exec(tagPartBlock)) {
var listTypeMatch = listPartMatches[1];
var indentLength = tagPartBlock.length - 2;
var listInsert = '';
if (button.tagStart == '(') {
indentLength = indentLength + 1;
}
else {
indentLength = indentLength - 1;
}
if (listTypeMatch.match(/[\*]{1,}/g)) {
var listType = '*';
var listReplace = '\\*';
}
else {
var listType = '#';
var listReplace = '\\#';
}
for (var i = 0; i < indentLength; i++) {
listInsert = listInsert + listType;
}
if (listInsert != '') {
insertTag = ' ' + listInsert + ' ';
}
else {
insertTag = '';
}
tagPartBlock = tagPartBlock.replace(/(\*|\#)/g,listReplace);
drawSwitch = 1;
captureListStart = true;
periodAddition = '';
periodAdditionClean = '';
if (matches = selectedText.match(/\n\s/g)) {
listItemsAddition = matches.length;
}
}
// must be a block modification e.g. p>. to p<.
else {
// if this is a block modification/addition
if (button.tagStart.match(/(h1|h2|h3|h4|h5|h6|bq|p)/g)) {
if (tagPartBlock == '') {
drawSwitch = 2;
}
else {
drawSwitch = 1;
}
insertTag = button.tagStart + tagPartModifier;
}
// else this is a modifier modification/addition
else {
if ((tagPartModifier == '') && (tagPartBlock != '')) {
drawSwitch = 1;
}
else if (tagPartModifier == '') {
drawSwitch = 2;
}
else {
drawSwitch = 1;
}
// if no tag part block but a modifier we need at least the p tag
if (tagPartBlock == '') {
tagPartBlock = 'p';
}
//make sure to swap out outdent
if (button.tagStart == ')') {
tagPartModifier = '';
}
else {
tagPartModifier = button.tagStart;
captureIndentStart = true; // ugly hack to fix issue with proper selection handling
}
insertTag = tagPartBlock + tagPartModifier;
}
}
mplier = 0;
if (captureListStart || (tagPartModifier.match(/[\(\)]{1,}/g))) {
re_start = new RegExp(insertTag.escape + periodAddition,'g'); // for tags that mimic regex properties, parens + list tags
}
else {
re_start = new RegExp(insertTag + periodAddition,'g'); // for tags that don't, why i can't just escape everything i have no clue
}
re_old = new RegExp(tagPartBlock + tagPartModifierOrig + periodAddition,'g');
re_middle = new RegExp(newlineReplaceRegexDirty + insertTag.escape + periodAddition.escape,'g');
re_tag = new RegExp(insertTag.escape + periodAddition.escape,'g');
// *************************************************************************************************************************
// this is where everything gets swapped around or inserted, bullets and single options have their own if/else statements
// *************************************************************************************************************************
if ((drawSwitch == 0) || (drawSwitch == 1)) {
if (drawSwitch == 0) { // completely removing a tag
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_start,'').replace(re_middle,newlineReplaceClean)
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffNeg = insertTag.length + 2 + (mplier*4);
}
else { // modifying a tag, though we do delete bullets here
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_old,insertTag + periodAdditionClean)
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
// figure out the length of various elements to modify the selection position
if (captureIndentStart) { // need to double-check that this wasn't the first indent
tagPreviousLength = tagPartBlock.length;
tagCurrentLength = insertTag.length;
}
else if (captureListStart) { // if this is a list we're manipulating
if (button.tagStart == '(') { // if indenting
tagPreviousLength = listTypeMatch.length + 2;
tagCurrentLength = insertTag.length + listItemsAddition;
}
else if (insertTag.match(/(\*|\#)/g)) { // if removing but still has bullets
tagPreviousLength = insertTag.length + listItemsAddition;
tagCurrentLength = listTypeMatch.length;
}
else { // if removing last bullet
tagPreviousLength = insertTag.length + listItemsAddition;
tagCurrentLength = listTypeMatch.length - (3*listItemsAddition) - 1;
}
}
else { // everything else
tagPreviousLength = tagPartBlock.length + tagPartModifier.length;
tagCurrentLength = insertTag.length;
}
if (tagCurrentLength > tagPreviousLength) {
posDiffPos = (tagCurrentLength - tagPreviousLength) + (mplier*(tagCurrentLength - tagPreviousLength));
}
else {
posDiffNeg = (tagPreviousLength - tagCurrentLength) + (mplier*(tagPreviousLength - tagCurrentLength));
}
}
}
else { // for adding tags other then bullets (have their own statement)
finalText = beginningText
+ newlineStart
+ insertTag + '. '
+ selectedText.replace(newlineReplaceRegexClean,button.tagEnd + '\n' + insertTag + '. ')
+ newlineFollowup
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffPos = insertTag.length + 2 + (mplier*4);
}
}
// swap in and out the simple tags around a selection like bold
else {
mplier = 1; // the multiplier for the tag length
re_start = new RegExp('^\\' + button.tagStart,'g');
re_end = new RegExp('\\' + button.tagEnd + '$','g');
re_middle = new RegExp('\\' + button.tagEnd + newlineReplaceRegexDirty + '\\' + button.tagStart,'g');
if (selectedText.match(re_start) && selectedText.match(re_end)) {
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_start,'').replace(re_end,'').replace(re_middle,newlineReplaceClean)
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffNeg = button.tagStart.length*mplier + button.tagEnd.length*mplier;
}
else {
finalText = beginningText
+ newlineStart
+ button.tagStart
+ selectedText.replace(newlineReplaceRegexClean,button.tagEnd + newlineReplaceClean + button.tagStart)
+ button.tagEnd
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffPos = (button.tagStart.length*mplier) + (button.tagEnd.length*mplier);
}
}
cursorPos += button.tagStart.length + button.tagEnd.length;
}
// just swap in and out single values, e.g. someone clicks b they'll get a *
else {
var buttonStart = '';
var buttonEnd = '';
var re_p = new RegExp('(\\<|\\>|\\=|\\<\\>|\\(|\\))','g');
var re_h = new RegExp('^(h1|h2|h3|h4|h5|h6|p|bq)','g');
if (!this.checkOpenTags(button) || button.tagEnd == '') { // opening tag
if (button.tagStart.match(re_h)) {
buttonStart = button.tagStart + '. ';
}
else {
buttonStart = button.tagStart;
}
if (button.tagStart.match(re_p)) { // make sure that invoking block modifiers don't do anything
finalText = beginningText
+ followupText;
cursorPos = startPos;
}
else {
finalText = beginningText
+ buttonStart
+ followupText;
this.addTag(button);
cursorPos = startPos + buttonStart.length;
}
}
else { // closing tag
if (button.tagStart.match(re_p)) {
buttonEnd = '\n\n';
}
else if (button.tagStart.match(re_h)) {
buttonEnd = '\n\n';
}
else {
buttonEnd = button.tagEnd
}
finalText = beginningText
+ button.tagEnd
+ followupText;
this.removeTag(button);
cursorPos = startPos + button.tagEnd.length;
}
}
// set the appropriate DOM value with the final text
if (FF == true) {
myField.value = finalText;
myField.scrollTop = scrollTop;
}
else {
sel.text = finalText;
}
// build up the selection capture, doesn't work in IE
if (textSelected) {
myField.selectionStart = startPos + newlineStartPos;
myField.selectionEnd = endPos + posDiffPos - posDiffNeg - newlineEndPos;
//alert('s: ' + myField.selectionStart + ' e: ' + myField.selectionEnd + ' sp: ' + startPos + ' ep: ' + endPos + ' pdp: ' + posDiffPos + ' pdn: ' + posDiffNeg)
}
else {
myField.selectionStart = cursorPos;
myField.selectionEnd = cursorPos;
}
} // end insertTag
}; // end class
// add class methods
Object.extend(TextileEditor, TextileEditor.Methods);
document.write('<script src="/javascripts/textile-editor-config.js" type="text/javascript"></script>'); | JavaScript |
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
| JavaScript |
/**
* WYSIWYG HTML Editor for Internet
*
* @author Roddy <luolonghao@gmail.com>
* @version 2.5.3
*/
var KE_VERSION = "2.5.4";
var KE_EDITOR_TYPE = "full"; //full or simple
var KE_SAFE_MODE = false; // true or false
var KE_UPLOAD_MODE = true; // true or false
var KE_FONT_FAMILY = "Courier New";
var KE_WIDTH = "700px";
var KE_HEIGHT = "400px";
var KE_SITE_DOMAIN = "";
var KE_SKIN_PATH = "./skins/default/";
var KE_ICON_PATH = "./icons/";
var KE_IMAGE_ATTACH_PATH = "./attached/";
var KE_IMAGE_UPLOAD_CGI = "./upload_cgi/upload.php";
var KE_CSS_PATH = "/editor/common.css";
var KE_MENU_BORDER_COLOR = '#AAAAAA';
var KE_MENU_BG_COLOR = '#EFEFEF';
var KE_MENU_TEXT_COLOR = '#222222';
var KE_MENU_SELECTED_COLOR = '#CCCCCC';
var KE_TOOLBAR_BORDER_COLOR = '#DDDDDD';
var KE_TOOLBAR_BG_COLOR = '#EFEFEF';
var KE_FORM_BORDER_COLOR = '#DDDDDD';
var KE_FORM_BG_COLOR = '#FFFFFF';
var KE_BUTTON_COLOR = '#AAAAAA';
var KE_LANG = {
INPUT_URL : "请输入正确的URL地址。",
SELECT_IMAGE : "请选择图片。",
INVALID_IMAGE : "只能选择GIF,JPG,PNG,BMP格式的图片,请重新选择。",
INVALID_FLASH : "只能选择SWF格式的文件,请重新选择。",
INVALID_MEDIA : "只能选择MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF格式的文件,请重新选择。",
INVALID_REAL : "只能选择RM,RMVB格式的文件,请重新选择。",
INVALID_WIDTH : "宽度不是数字,请重新输入。",
INVALID_HEIGHT : "高度不是数字,请重新输入。",
INVALID_BORDER : "边框不是数字,请重新输入。",
INVALID_HSPACE : "横隔不是数字,请重新输入。",
INVALID_VSPACE : "竖隔不是数字,请重新输入。",
INPUT_CONTENT : "请输入内容",
TITLE : "描述",
WIDTH : "宽",
HEIGHT : "高",
BORDER : "边",
ALIGN : "对齐方式",
HSPACE : "横隔",
VSPACE : "竖隔",
CONFIRM : "确定",
CANCEL : "取消",
PREVIEW : "预览",
LISTENING : "试听",
LOCAL : "本地",
REMOTE : "远程",
NEW_WINDOW : "新窗口",
CURRENT_WINDOW : "当前窗口",
TARGET : "目标",
ABOUT : "访问技术支持网站",
SUBJECT : "标题"
}
var KE_FONT_NAME = Array(
Array('SimSun', '宋体'),
Array('SimHei', '黑体'),
Array('FangSong_GB2312', '仿宋体'),
Array('KaiTi_GB2312', '楷体'),
Array('NSimSun', '新宋体'),
Array('Arial', 'Arial'),
Array('Arial Black', 'Arial Black'),
Array('Times New Roman', 'Times New Roman'),
Array('Courier New', 'Courier New'),
Array('Tahoma', 'Tahoma'),
Array('Verdana', 'Verdana'),
Array('GulimChe', 'GulimChe'),
Array('MS Gothic', 'MS Gothic')
);
var KE_SPECIAL_CHARACTER = Array(
'§','№','☆','★','○','●','◎','◇','◆','□','℃','‰','■','△','▲','※',
'→','←','↑','↓','〓','¤','°','#','&','@','\','︿','_',' ̄','―','α',
'β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ',
'σ','τ','υ','φ','χ','ψ','ω','≈','≡','≠','=','≤','≥','<','>','≮',
'≯','∷','±','+','-','×','÷','/','∫','∮','∝','∞','∧','∨','∑','∏',
'∪','∩','∈','∵','∴','⊥','∥','∠','⌒','⊙','≌','∽','〖','〗',
'【','】','(',')','[',']'
);
var KE_TOP_TOOLBAR_ICON = Array(
Array('KE_SOURCE', 'source.gif', '视图转换'),
Array('KE_PREVIEW', 'preview.gif', '预览'),
Array('KE_ZOOM', 'zoom.gif', '显示比例'),
Array('KE_PRINT', 'print.gif', '打印'),
Array('KE_UNDO', 'undo.gif', '回退'),
Array('KE_REDO', 'redo.gif', '前进'),
Array('KE_CUT', 'cut.gif', '剪切'),
Array('KE_COPY', 'copy.gif', '复制'),
Array('KE_PASTE', 'paste.gif', '粘贴'),
Array('KE_SELECTALL', 'selectall.gif', '全选'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_JUSTIFYFULL', 'justifyfull.gif', '两端对齐'),
Array('KE_NUMBEREDLIST', 'numberedlist.gif', '编号'),
Array('KE_UNORDERLIST', 'unorderedlist.gif', '项目符号'),
Array('KE_INDENT', 'indent.gif', '减少缩进'),
Array('KE_OUTDENT', 'outdent.gif', '增加缩进'),
Array('KE_SUBSCRIPT', 'subscript.gif', '下标'),
Array('KE_SUPERSCRIPT', 'superscript.gif', '上标'),
Array('KE_DATE', 'date.gif', '日期'),
Array('KE_TIME', 'time.gif', '时间')
);
var KE_BOTTOM_TOOLBAR_ICON = Array(
Array('KE_TITLE', 'title.gif', '标题'),
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_STRIKE', 'strikethrough.gif', '删除线'),
Array('KE_REMOVE', 'removeformat.gif', '删除格式'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_FLASH', 'flash.gif', 'Flash'),
Array('KE_MEDIA', 'media.gif', 'Windows Media Player'),
Array('KE_REAL', 'real.gif', 'Real Player'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_TABLE', 'table.gif', '表格'),
Array('KE_SPECIALCHAR', 'specialchar.gif', '特殊字符'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_UNLINK', 'unlink.gif', '删除超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_SIMPLE_TOOLBAR_ICON = Array(
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_TITLE_TABLE = Array(
Array('H1', KE_LANG['SUBJECT'] + ' 1'),
Array('H2', KE_LANG['SUBJECT'] + ' 2'),
Array('H3', KE_LANG['SUBJECT'] + ' 3'),
Array('H4', KE_LANG['SUBJECT'] + ' 4'),
Array('H5', KE_LANG['SUBJECT'] + ' 5'),
Array('H6', KE_LANG['SUBJECT'] + ' 6')
);
var KE_ZOOM_TABLE = Array('250%', '200%', '150%', '120%', '100%', '80%', '50%');
var KE_FONT_SIZE = Array(
Array(1,'8pt'),
Array(2,'10pt'),
Array(3,'12pt'),
Array(4,'14pt'),
Array(5,'18pt'),
Array(6,'24pt'),
Array(7,'36pt')
);
var KE_POPUP_MENU_TABLE = Array(
"KE_ZOOM", "KE_TITLE", "KE_FONTNAME", "KE_FONTSIZE", "KE_TEXTCOLOR", "KE_BGCOLOR",
"KE_LAYER", "KE_TABLE", "KE_HR", "KE_ICON", "KE_SPECIALCHAR", "KE_ABOUT",
"KE_IMAGE", "KE_FLASH", "KE_MEDIA", "KE_REAL", "KE_LINK"
);
var KE_COLOR_TABLE = Array(
"#FF0000", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#FF00FF", "#FFFFFF", "#F5F5F5", "#DCDCDC", "#FFFAFA",
"#D3D3D3", "#C0C0C0", "#A9A9A9", "#808080", "#696969", "#000000", "#2F4F4F", "#708090", "#778899", "#4682B4",
"#4169E1", "#6495ED", "#B0C4DE", "#7B68EE", "#6A5ACD", "#483D8B", "#191970", "#000080", "#00008B", "#0000CD",
"#1E90FF", "#00BFFF", "#87CEFA", "#87CEEB", "#ADD8E6", "#B0E0E6", "#F0FFFF", "#E0FFFF", "#AFEEEE", "#00CED1",
"#5F9EA0", "#48D1CC", "#00FFFF", "#40E0D0", "#20B2AA", "#008B8B", "#008080", "#7FFFD4", "#66CDAA", "#8FBC8F",
"#3CB371", "#2E8B57", "#006400", "#008000", "#228B22", "#32CD32", "#00FF00", "#7FFF00", "#7CFC00", "#ADFF2F",
"#98FB98", "#90EE90", "#00FF7F", "#00FA9A", "#556B2F", "#6B8E23", "#808000", "#BDB76B", "#B8860B", "#DAA520",
"#FFD700", "#F0E68C", "#EEE8AA", "#FFEBCD", "#FFE4B5", "#F5DEB3", "#FFDEAD", "#DEB887", "#D2B48C", "#BC8F8F",
"#A0522D", "#8B4513", "#D2691E", "#CD853F", "#F4A460", "#8B0000", "#800000", "#A52A2A", "#B22222", "#CD5C5C",
"#F08080", "#FA8072", "#E9967A", "#FFA07A", "#FF7F50", "#FF6347", "#FF8C00", "#FFA500", "#FF4500", "#DC143C",
"#FF0000", "#FF1493", "#FF00FF", "#FF69B4", "#FFB6C1", "#FFC0CB", "#DB7093", "#C71585", "#800080", "#8B008B",
"#9370DB", "#8A2BE2", "#4B0082", "#9400D3", "#9932CC", "#BA55D3", "#DA70D6", "#EE82EE", "#DDA0DD", "#D8BFD8",
"#E6E6FA", "#F8F8FF", "#F0F8FF", "#F5FFFA", "#F0FFF0", "#FAFAD2", "#FFFACD", "#FFF8DC", "#FFFFE0", "#FFFFF0",
"#FFFAF0", "#FAF0E6", "#FDF5E6", "#FAEBD7", "#FFE4C4", "#FFDAB9", "#FFEFD5", "#FFF5EE", "#FFF0F5", "#FFE4E1"
);
var KE_IMAGE_ALIGN_TABLE = Array(
"baseline", "top", "middle", "bottom", "texttop", "absmiddle", "absbottom", "left", "right"
);
var KE_OBJ_NAME;
var KE_SELECTION;
var KE_RANGE;
var KE_RANGE_TEXT;
var KE_EDITFORM_DOCUMENT;
var KE_IMAGE_DOCUMENT;
var KE_FLASH_DOCUMENT;
var KE_MEDIA_DOCUMENT;
var KE_REAL_DOCUMENT;
var KE_LINK_DOCUMENT;
var KE_BROWSER;
var KE_TOOLBAR_ICON;
function KindGetBrowser()
{
var browser = '';
var agentInfo = navigator.userAgent.toLowerCase();
if (agentInfo.indexOf("msie") > -1) {
var re = new RegExp("msie\\s?([\\d\\.]+)","ig");
var arr = re.exec(agentInfo);
if (parseInt(RegExp.$1) >= 5.5) {
browser = 'IE';
}
} else if (agentInfo.indexOf("firefox") > -1) {
browser = 'FF';
} else if (agentInfo.indexOf("netscape") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[temp1.length-1].split('/');
if (parseInt(temp2[1]) >= 7) {
browser = 'NS';
}
} else if (agentInfo.indexOf("gecko") > -1) {
browser = 'ML';
} else if (agentInfo.indexOf("opera") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[0].split('/');
if (parseInt(temp2[1]) >= 9) {
browser = 'OPERA';
}
}
return browser;
}
function KindGetFileName(file, separator)
{
var temp = file.split(separator);
var len = temp.length;
var fileName = temp[len-1];
return fileName;
}
function KindGetFileExt(fileName)
{
var temp = fileName.split(".");
var len = temp.length;
var fileExt = temp[len-1].toLowerCase();
return fileExt;
}
function KindCheckImageFileType(file, separator)
{
if (separator == "/" && file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, separator);
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'gif' && fileExt != 'jpg' && fileExt != 'png' && fileExt != 'bmp') {
alert(KE_LANG['INVALID_IMAGE']);
return false;
}
return true;
}
function KindCheckFlashFileType(file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'swf') {
alert(KE_LANG['INVALID_FLASH']);
return false;
}
return true;
}
function KindCheckMediaFileType(cmd, file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (cmd == 'KE_REAL') {
if (fileExt != 'rm' && fileExt != 'rmvb') {
alert(KE_LANG['INVALID_REAL']);
return false;
}
} else {
if (fileExt != 'mp3' && fileExt != 'wav' && fileExt != 'wma' && fileExt != 'wmv' && fileExt != 'mid' && fileExt != 'avi' && fileExt != 'mpg' && fileExt != 'asf') {
alert(KE_LANG['INVALID_MEDIA']);
return false;
}
}
return true;
}
function KindHtmlToXhtml(str)
{
str = str.replace(/<br.*?>/gi, "<br />");
str = str.replace(/(<hr\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<img\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<\w+)(.*?>)/gi, function ($0,$1,$2) {
return($1.toLowerCase() + KindConvertAttribute($2));
}
);
str = str.replace(/(<\/\w+>)/gi, function ($0,$1) {
return($1.toLowerCase());
}
);
return str;
}
function KindConvertAttribute(str)
{
if (KE_SAFE_MODE == true) {
str = KindClearAttributeScriptTag(str);
}
return str;
}
function KindClearAttributeScriptTag(str)
{
var re = new RegExp("(\\son[a-z]+=)[\"']?[^>]*?[^\\\\\>][\"']?([\\s>])","ig");
str = str.replace(re, function ($0,$1,$2) {
return($1.toLowerCase() + "\"\"" + $2);
}
);
return str;
}
function KindClearScriptTag(str)
{
if (KE_SAFE_MODE == false) {
return str;
}
str = str.replace(/<(script.*?)>/gi, "[$1]");
str = str.replace(/<\/script>/gi, "[/script]");
return str;
}
function KindHtmlentities(str)
{
str = str.replace(/&/g,'&');
str = str.replace(/</g,'<');
str = str.replace(/>/g,'>');
str = str.replace(/"/g,'"');
return str;
}
function KindGetTop(id)
{
var top = 28;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
top += eval("obj" + tmp).offsetTop;
}
return top;
}
function KindGetLeft(id)
{
var left = 2;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
left += eval("obj" + tmp).offsetLeft;
}
return left;
}
function KindDisplayMenu(cmd)
{
KindEditorForm.focus();
if (cmd != 'KE_ABOUT') {
KindSelection();
}
KindDisableMenu();
var top, left;
top = KindGetTop(cmd);
left = KindGetLeft(cmd);
if (cmd == 'KE_ABOUT') {
left -= 200;
} else if (cmd == 'KE_LINK') {
left -= 220;
}
document.getElementById('POPUP_'+cmd).style.top = top.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.left = left.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.display = 'block';
}
function KindDisableMenu()
{
for (i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
document.getElementById('POPUP_'+KE_POPUP_MENU_TABLE[i]).style.display = 'none';
}
}
function KindReloadIframe()
{
var str = '';
str += KindPopupMenu('KE_IMAGE');
str += KindPopupMenu('KE_FLASH');
str += KindPopupMenu('KE_MEDIA');
str += KindPopupMenu('KE_REAL');
document.getElementById('InsertIframe').innerHTML = str;
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
}
function KindGetMenuCommonStyle()
{
var str = 'position:absolute;top:1px;left:1px;font-size:12px;color:'+KE_MENU_TEXT_COLOR+
';background-color:'+KE_MENU_BG_COLOR+';border:solid 1px '+KE_MENU_BORDER_COLOR+';z-index:1;display:none;';
return str;
}
function KindGetCommonMenu(cmd, content)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="'+KindGetMenuCommonStyle()+'">';
str += content;
str += '</div>';
return str;
}
function KindCreateColorTable(cmd, eventStr)
{
var str = '';
str += '<table cellpadding="0" cellspacing="2" border="0">';
for (i = 0; i < KE_COLOR_TABLE.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="width:12px;height:12px;border:1px solid #AAAAAA;font-size:1px;cursor:pointer;background-color:' +
KE_COLOR_TABLE[i] + ';" onmouseover="javascript:this.style.borderColor=\'#000000\';' + ((eventStr) ? eventStr : '') + '" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onclick="javascript:KindExecute(\''+cmd+'_END\', \'' + KE_COLOR_TABLE[i] + '\');"> </td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
}
function KindDrawColorTable(cmd)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;padding:2px;'+KindGetMenuCommonStyle()+'">';
str += KindCreateColorTable(cmd);
str += '</div>';
return str;
}
function KindDrawMedia(cmd)
{
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="'+cmd+'preview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="'+cmd+'link" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['LISTENING']+'" onclick="javascript:parent.KindMediaPreview(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawMediaEnd(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
return str;
}
function KindPopupMenu(cmd)
{
switch (cmd)
{
case 'KE_ZOOM':
var str = '';
for (i = 0; i < KE_ZOOM_TABLE.length; i++) {
str += '<div style="padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ZOOM_END\', \'' + KE_ZOOM_TABLE[i] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_ZOOM_TABLE[i] + '</div>';
}
str = KindGetCommonMenu('KE_ZOOM', str);
return str;
break;
case 'KE_TITLE':
var str = '';
for (i = 0; i < KE_TITLE_TABLE.length; i++) {
str += '<div style="width:140px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TITLE_END\', \'' + KE_TITLE_TABLE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';"><' + KE_TITLE_TABLE[i][0] + ' style="margin:2px;">' +
KE_TITLE_TABLE[i][1] + '</' + KE_TITLE_TABLE[i][0] + '></div>';
}
str = KindGetCommonMenu('KE_TITLE', str);
return str;
break;
case 'KE_FONTNAME':
var str = '';
for (i = 0; i < KE_FONT_NAME.length; i++) {
str += '<div style="font-family:' + KE_FONT_NAME[i][0] +
';padding:2px;width:160px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTNAME_END\', \'' + KE_FONT_NAME[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_NAME[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTNAME', str);
return str;
break;
case 'KE_FONTSIZE':
var str = '';
for (i = 0; i < KE_FONT_SIZE.length; i++) {
str += '<div style="font-size:' + KE_FONT_SIZE[i][1] +
';padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTSIZE_END\', \'' + KE_FONT_SIZE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_SIZE[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTSIZE', str);
return str;
break;
case 'KE_TEXTCOLOR':
var str = '';
str = KindDrawColorTable('KE_TEXTCOLOR');
return str;
break;
case 'KE_BGCOLOR':
var str = '';
str = KindDrawColorTable('KE_BGCOLOR');
return str;
break;
case 'KE_HR':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="hrPreview" style="margin:10px 2px 10px 2px;height:1px;border:0;font-size:0;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'hrPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_LAYER':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="divPreview" style="margin:5px 2px 5px 2px;height:20px;border:1px solid #AAAAAA;font-size:1px;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'divPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_ICON':
var str = '';
var iconNum = 36;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < iconNum; i++) {
if (i == 0 || (i >= 6 && i%6 == 0)) {
str += '<tr>';
}
var num;
if ((i+1).toString(10).length < 2) {
num = '0' + (i+1);
} else {
num = (i+1).toString(10);
}
var iconUrl = KE_ICON_PATH + 'etc_' + num + '.gif';
str += '<td style="padding:2px;border:0;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ICON_END\', \'' + iconUrl + '\');">' +
'<img src="' + iconUrl + '" style="border:1px solid #EEEEEE;" onmouseover="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#EEEEEE\';">' + '</td>';
if (i >= 5 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_SPECIALCHAR':
var str = '';
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < KE_SPECIAL_CHARACTER.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="padding:2px;border:1px solid #AAAAAA;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_SPECIALCHAR_END\', \'' + KE_SPECIAL_CHARACTER[i] + '\');" ' +
'onmouseover="javascript:this.style.borderColor=\'#000000\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';">' + KE_SPECIAL_CHARACTER[i] + '</td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_TABLE':
var str = '';
var num = 10;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="0" style="'+KindGetMenuCommonStyle()+'">';
for (i = 1; i <= num; i++) {
str += '<tr>';
for (j = 1; j <= num; j++) {
var value = i.toString(10) + ',' + j.toString(10);
str += '<td id="kindTableTd' + i.toString(10) + '_' + j.toString(10) +
'" style="width:15px;height:15px;background-color:#FFFFFF;border:1px solid #DDDDDD;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TABLE_END\', \'' + value + '\');" ' +
'onmouseover="javascript:KindDrawTableSelected(\''+i.toString(10)+'\', \''+j.toString(10)+'\');" ' +
'onmouseout="javascript:;"> </td>';
}
str += '</tr>';
}
str += '<tr><td colspan="10" id="tableLocation" style="text-align:center;height:20px;"></td></tr>';
str += '</table>';
return str;
break;
case 'KE_IMAGE':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindImageIframe" id="KindImageIframe" frameborder="0" style="width:250px;height:390px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_FLASH':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindFlashIframe" id="KindFlashIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_MEDIA':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindMediaIframe" id="KindMediaIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_REAL':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindRealIframe" id="KindRealIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_LINK':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindLinkIframe" id="KindLinkIframe" frameborder="0" style="width:250px;height:85px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_ABOUT':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:230px;'+KindGetMenuCommonStyle()+';padding:5px;">';
str += '<span style="margin-right:10px;">KindEditor ' + KE_VERSION + '</span>' +
'<a href="http://www.kindsoft.net/" target="_blank" style="color:#4169e1;" onclick="javascript:KindDisableMenu();">'+KE_LANG['ABOUT']+'</a><br />';
str += '</div>';
return str;
break;
default:
break;
}
}
function KindDrawIframe(cmd)
{
if (KE_BROWSER == 'IE') {
KE_IMAGE_DOCUMENT = document.frames("KindImageIframe").document;
KE_FLASH_DOCUMENT = document.frames("KindFlashIframe").document;
KE_MEDIA_DOCUMENT = document.frames("KindMediaIframe").document;
KE_REAL_DOCUMENT = document.frames("KindRealIframe").document;
KE_LINK_DOCUMENT = document.frames("KindLinkIframe").document;
} else {
KE_IMAGE_DOCUMENT = document.getElementById('KindImageIframe').contentDocument;
KE_FLASH_DOCUMENT = document.getElementById('KindFlashIframe').contentDocument;
KE_MEDIA_DOCUMENT = document.getElementById('KindMediaIframe').contentDocument;
KE_REAL_DOCUMENT = document.getElementById('KindRealIframe').contentDocument;
KE_LINK_DOCUMENT = document.getElementById('KindLinkIframe').contentDocument;
}
switch (cmd)
{
case 'KE_IMAGE':
var str = '';
str += '<div align="center">' +
'<form name="uploadForm" style="margin:0;padding:0;" method="post" enctype="multipart/form-data" ' +
'action="' + KE_IMAGE_UPLOAD_CGI + '" onsubmit="javascript:if(parent.KindDrawImageEnd()==false){return false;};">' +
'<input type="hidden" name="fileName" id="fileName" value="" />' +
'<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0" style="margin-bottom:3px;"><tr><td id="imgPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:50px;padding-left:5px;">';
if (KE_UPLOAD_MODE == true) {
str += '<select id="imageType" onchange="javascript:parent.KindImageType(this.value);document.getElementById(\''+cmd+'submitButton\').focus();"><option value="1" selected="selected">'+KE_LANG['LOCAL']+'</option><option value="2">'+KE_LANG['REMOTE']+'</option></select>';
} else {
str += KE_LANG['REMOTE'];
}
str += '</td><td style="width:200px;padding-bottom:3px;">';
if (KE_UPLOAD_MODE == true) {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;display:none;" />' +
'<input type="file" name="fileData" id="imgFile" size="14" style="border:1px solid #555555;" onclick="javascript:document.getElementById(\'imgLink\').value=\'http://\';" />';
} else {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;" />' +
'<input type="hidden" name="imageType" id="imageType" value="2"><input type="hidden" name="fileData" id="imgFile" value="" />';
}
str += '</td></tr><tr><td colspan="2" style="padding-bottom:3px;">' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="18%" style="padding:2px 2px 2px 5px;">'+KE_LANG['TITLE']+'</td><td width="82%"><input type="text" name="imgTitle" id="imgTitle" value="" maxlength="100" style="width:95%;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="10%" style="padding:2px 2px 2px 5px;">'+KE_LANG['WIDTH']+'</td><td width="23%"><input type="text" name="imgWidth" id="imgWidth" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['HEIGHT']+'</td><td width="23%"><input type="text" name="imgHeight" id="imgHeight" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['BORDER']+'</td><td width="23%"><input type="text" name="imgBorder" id="imgBorder" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="39%" style="padding:2px 2px 2px 5px;"><select id="imgAlign" name="imgAlign"><option value="">'+KE_LANG['ALIGN']+'</option>';
for (var i = 0; i < KE_IMAGE_ALIGN_TABLE.length; i++) {
str += '<option value="' + KE_IMAGE_ALIGN_TABLE[i] + '">' + KE_IMAGE_ALIGN_TABLE[i] + '</option>';
}
str += '</select></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['HSPACE']+'</td><td width="15%"><input type="text" name="imgHspace" id="imgHspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['VSPACE']+'</td><td width="15%"><input type="text" name="imgVspace" id="imgVspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'</td></tr><tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindImagePreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table></form></div>';
KindDrawMenuIframe(KE_IMAGE_DOCUMENT, str);
break;
case 'KE_FLASH':
var str = '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="flashPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="flashLink" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindFlashPreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawFlashEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
KindDrawMenuIframe(KE_FLASH_DOCUMENT, str);
break;
case 'KE_MEDIA':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_MEDIA_DOCUMENT, str);
break;
case 'KE_REAL':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_REAL_DOCUMENT, str);
break;
case 'KE_LINK':
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td style="width:50px;padding:5px;">URL</td>' +
'<td style="width:200px;padding-top:5px;padding-bottom:5px;"><input type="text" id="hyperLink" value="http://" style="width:190px;border:1px solid #555555;background-color:#FFFFFF;"></td>' +
'<tr><td style="padding:5px;">'+KE_LANG['TARGET']+'</td>' +
'<td style="padding-bottom:5px;"><select id="hyperLinkTarget"><option value="_blank" selected="selected">'+KE_LANG['NEW_WINDOW']+'</option><option value="">'+KE_LANG['CURRENT_WINDOW']+'</option></select></td></tr>' +
'<tr><td colspan="2" style="padding-bottom:5px;" align="center">' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawLinkEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>';
str += '</table>';
KindDrawMenuIframe(KE_LINK_DOCUMENT, str);
break;
default:
break;
}
}
function KindDrawMenuIframe(obj, str)
{
obj.open();
obj.write(str);
obj.close();
obj.body.style.color = KE_MENU_TEXT_COLOR;
obj.body.style.backgroundColor = KE_MENU_BG_COLOR;
obj.body.style.margin = 0;
obj.body.scroll = 'no';
}
function KindDrawTableSelected(i, j)
{
var text = i.toString(10) + ' by ' + j.toString(10) + ' Table';
document.getElementById('tableLocation').innerHTML = text;
var num = 10;
for (m = 1; m <= num; m++) {
for (n = 1; n <= num; n++) {
var obj = document.getElementById('kindTableTd' + m.toString(10) + '_' + n.toString(10) + '');
if (m <= i && n <= j) {
obj.style.backgroundColor = KE_MENU_SELECTED_COLOR;
} else {
obj.style.backgroundColor = '#FFFFFF';
}
}
}
}
function KindImageType(type)
{
if (type == 1) {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'block';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').value = 'http://';
} else {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'block';
}
KE_IMAGE_DOCUMENT.getElementById('imgPreview').innerHTML = " ";
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = 0;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = 0;
}
function KindImagePreview()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
if (type == 1) {
if (KE_BROWSER != 'IE') {
return false;
}
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
url = 'file:///' + file;
if (KindCheckImageFileType(url, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
var imgObj = KE_IMAGE_DOCUMENT.createElement("IMG");
imgObj.src = url;
var width = parseInt(imgObj.width);
var height = parseInt(imgObj.height);
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = width;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = height;
var rate = parseInt(width/height);
if (width >230 && height <= 230) {
width = 230;
height = parseInt(width/rate);
} else if (width <=230 && height > 230) {
height = 230;
width = parseInt(height*rate);
} else if (width >230 && height > 230) {
if (width >= height) {
width = 230;
height = parseInt(width/rate);
} else {
height = 230;
width = parseInt(height*rate);
}
}
imgObj.style.width = width;
imgObj.style.height = height;
var el = KE_IMAGE_DOCUMENT.getElementById('imgPreview');
if (el.hasChildNodes()) {
el.removeChild(el.childNodes[0]);
}
el.appendChild(imgObj);
return imgObj;
}
function KindDrawImageEnd()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
var width = KE_IMAGE_DOCUMENT.getElementById('imgWidth').value;
var height = KE_IMAGE_DOCUMENT.getElementById('imgHeight').value;
var border = KE_IMAGE_DOCUMENT.getElementById('imgBorder').value;
var title = KE_IMAGE_DOCUMENT.getElementById('imgTitle').value;
var align = KE_IMAGE_DOCUMENT.getElementById('imgAlign').value;
var hspace = KE_IMAGE_DOCUMENT.getElementById('imgHspace').value;
var vspace = KE_IMAGE_DOCUMENT.getElementById('imgVspace').value;
if (type == 1) {
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
if (KindCheckImageFileType(file, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
if (width.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_WIDTH']);
return false;
}
if (height.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HEIGHT']);
return false;
}
if (border.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_BORDER']);
return false;
}
if (hspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HSPACE']);
return false;
}
if (vspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_VSPACE']);
return false;
}
var fileName;
KindEditorForm.focus();
if (type == 1) {
fileName = KindGetFileName(file, "\\");
var fileExt = KindGetFileExt(fileName);
var dateObj = new Date();
var year = dateObj.getFullYear().toString(10);
var month = (dateObj.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = dateObj.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var ymd = year + month + day;
fileName = ymd + dateObj.getTime().toString(10) + '.' + fileExt;
KE_IMAGE_DOCUMENT.getElementById('fileName').value = fileName;
} else {
KindInsertImage(url, width, height, border, title, align, hspace, vspace);
}
}
function KindInsertImage(url, width, height, border, title, align, hspace, vspace)
{
var element = document.createElement("img");
element.src = url;
if (width > 0) {
element.style.width = width;
}
if (height > 0) {
element.style.height = height;
}
if (align != "") {
element.align = align;
}
if (hspace > 0) {
element.hspace = hspace;
}
if (vspace > 0) {
element.vspace = vspace;
}
element.border = border;
element.alt = KindHtmlentities(title);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
KindReloadIframe();
}
function KindGetFlashHtmlTag(url)
{
var str = '<embed src="'+url+'" type="application/x-shockwave-flash" quality="high"></embed>';
return str;
}
function KindFlashPreview()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
var el = KE_FLASH_DOCUMENT.getElementById('flashPreview');
el.innerHTML = KindGetFlashHtmlTag(url);
}
function KindDrawFlashEnd()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
obj.type = "application/x-shockwave-flash";
obj.quality = "high";
KindInsertItem(obj);
KindDisableMenu();
}
function KindGetMediaHtmlTag(cmd, url)
{
var str = '<embed src="'+url+'" type="';
if (cmd == "KE_REAL") {
str += 'audio/x-pn-realaudio-plugin';
} else {
str += 'video/x-ms-asf-plugin';
}
str += '" width="230" height="230" loop="true" autostart="true">';
return str;
}
function KindMediaPreview(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
var el = mediaDocument.getElementById(cmd+'preview');
el.innerHTML = KindGetMediaHtmlTag(cmd, url);
}
function KindDrawMediaEnd(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
if (cmd == 'KE_REAL') {
obj.type = 'audio/x-pn-realaudio-plugin';
} else {
obj.type = 'video/x-ms-asf-plugin';
}
obj.loop = 'true';
obj.autostart = 'true';
KindInsertItem(obj);
KindDisableMenu(cmd);
}
function KindDrawLinkEnd()
{
var range;
var url = KE_LINK_DOCUMENT.getElementById('hyperLink').value;
var target = KE_LINK_DOCUMENT.getElementById('hyperLinkTarget').value;
if (url.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
KindEditorForm.focus();
KindSelect();
var element;
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
var el = document.createElement("a");
el.href = url;
if (target) {
el.target = target;
}
KE_RANGE.item(0).applyElement(el);
} else if (KE_SELECTION.type.toLowerCase() == 'text') {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.parentElement();
if (target) {
element.target = target;
}
}
} else {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.startContainer.previousSibling;
element.target = target;
if (target) {
element.target = target;
}
}
KindDisableMenu();
}
function KindSelection()
{
if (KE_BROWSER == 'IE') {
KE_SELECTION = KE_EDITFORM_DOCUMENT.selection;
KE_RANGE = KE_SELECTION.createRange();
KE_RANGE_TEXT = KE_RANGE.text;
} else {
KE_SELECTION = document.getElementById("KindEditorForm").contentWindow.getSelection();
KE_RANGE = KE_SELECTION.getRangeAt(0);
KE_RANGE_TEXT = KE_RANGE.toString();
}
}
function KindSelect()
{
if (KE_BROWSER == 'IE') {
KE_RANGE.select();
}
}
function KindInsertItem(insertNode)
{
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
KE_RANGE.item(0).outerHTML = insertNode.outerHTML;
} else {
KE_RANGE.pasteHTML(insertNode.outerHTML);
}
} else {
KE_SELECTION.removeAllRanges();
KE_RANGE.deleteContents();
var startRangeNode = KE_RANGE.startContainer;
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
if (startRangeNode.nodeType == 3 && insertNode.nodeType == 3) {
startRangeNode.insertData(startRangeOffset, insertNode.nodeValue);
newRange.setEnd(startRangeNode, startRangeOffset + insertNode.length);
newRange.setStart(startRangeNode, startRangeOffset + insertNode.length);
} else {
var afterNode;
if (startRangeNode.nodeType == 3) {
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(insertNode, afterNode);
startRangeNode.insertBefore(beforeNode, insertNode);
startRangeNode.removeChild(textNode);
} else {
if (startRangeNode.tagName.toLowerCase() == 'html') {
startRangeNode = startRangeNode.childNodes[0].nextSibling;
afterNode = startRangeNode.childNodes[0];
} else {
afterNode = startRangeNode.childNodes[startRangeOffset];
}
startRangeNode.insertBefore(insertNode, afterNode);
}
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
}
KE_SELECTION.addRange(newRange);
}
}
function KindExecuteValue(cmd, value)
{
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, value);
}
function KindSimpleExecute(cmd)
{
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, null);
KindDisableMenu();
}
function KindExecute(cmd, value)
{
switch (cmd)
{
case 'KE_SOURCE':
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
document.getElementById("KindCodeForm").value = KindHtmlToXhtml(KE_EDITFORM_DOCUMENT.body.innerHTML);
document.getElementById("KindEditorIframe").style.display = 'none';
document.getElementById("KindEditTextarea").style.display = 'block';
KindDisableToolbar(true);
} else {
KE_EDITFORM_DOCUMENT.body.innerHTML = KindClearScriptTag(document.getElementById("KindCodeForm").value);
document.getElementById("KindEditTextarea").style.display = 'none';
document.getElementById("KindEditorIframe").style.display = 'block';
KindDisableToolbar(false);
}
KindDisableMenu();
break;
case 'KE_PRINT':
KindSimpleExecute('print');
break;
case 'KE_UNDO':
KindSimpleExecute('undo');
break;
case 'KE_REDO':
KindSimpleExecute('redo');
break;
case 'KE_CUT':
KindSimpleExecute('cut');
break;
case 'KE_COPY':
KindSimpleExecute('copy');
break;
case 'KE_PASTE':
KindSimpleExecute('paste');
break;
case 'KE_SELECTALL':
KindSimpleExecute('selectall');
break;
case 'KE_SUBSCRIPT':
KindSimpleExecute('subscript');
break;
case 'KE_SUPERSCRIPT':
KindSimpleExecute('superscript');
break;
case 'KE_BOLD':
KindSimpleExecute('bold');
break;
case 'KE_ITALIC':
KindSimpleExecute('italic');
break;
case 'KE_UNDERLINE':
KindSimpleExecute('underline');
break;
case 'KE_STRIKE':
KindSimpleExecute('strikethrough');
break;
case 'KE_JUSTIFYLEFT':
KindSimpleExecute('justifyleft');
break;
case 'KE_JUSTIFYCENTER':
KindSimpleExecute('justifycenter');
break;
case 'KE_JUSTIFYRIGHT':
KindSimpleExecute('justifyright');
break;
case 'KE_JUSTIFYFULL':
KindSimpleExecute('justifyfull');
break;
case 'KE_NUMBEREDLIST':
KindSimpleExecute('insertorderedlist');
break;
case 'KE_UNORDERLIST':
KindSimpleExecute('insertunorderedlist');
break;
case 'KE_INDENT':
KindSimpleExecute('indent');
break;
case 'KE_OUTDENT':
KindSimpleExecute('outdent');
break;
case 'KE_REMOVE':
KindSimpleExecute('removeformat');
break;
case 'KE_ZOOM':
KindDisplayMenu(cmd);
break;
case 'KE_ZOOM_END':
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.body.style.zoom = value;
KindDisableMenu();
break;
case 'KE_TITLE':
KindDisplayMenu(cmd);
break;
case 'KE_TITLE_END':
KindEditorForm.focus();
value = '<' + value + '>';
KindSelect();
KindExecuteValue('FormatBlock', value);
KindDisableMenu();
break;
case 'KE_FONTNAME':
KindDisplayMenu(cmd);
break;
case 'KE_FONTNAME_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('fontname', value);
KindDisableMenu();
break;
case 'KE_FONTSIZE':
KindDisplayMenu(cmd);
break;
case 'KE_FONTSIZE_END':
KindEditorForm.focus();
value = value.substr(0, 1);
KindSelect();
KindExecuteValue('fontsize', value);
KindDisableMenu();
break;
case 'KE_TEXTCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_TEXTCOLOR_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('ForeColor', value);
KindDisableMenu();
break;
case 'KE_BGCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_BGCOLOR_END':
KindEditorForm.focus();
if (KE_BROWSER == 'IE') {
KindSelect();
KindExecuteValue('BackColor', value);
} else {
var startRangeNode = KE_RANGE.startContainer;
if (startRangeNode.nodeType == 3) {
var parent = startRangeNode.parentNode;
var element = document.createElement("font");
element.style.backgroundColor = value;
element.appendChild(KE_RANGE.extractContents());
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
var afterNode;
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(element, afterNode);
startRangeNode.insertBefore(beforeNode, element);
startRangeNode.removeChild(textNode);
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
KE_SELECTION.addRange(newRange);
}
}
KindDisableMenu();
break;
case 'KE_ICON':
KindDisplayMenu(cmd);
break;
case 'KE_ICON_END':
KindEditorForm.focus();
var element = document.createElement("img");
element.src = value;
element.border = 0;
element.alt = "";
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_IMAGE':
KindDisplayMenu(cmd);
KindImageIframe.focus();
KE_IMAGE_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_FLASH':
KindDisplayMenu(cmd);
KindFlashIframe.focus();
KE_FLASH_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_MEDIA':
KindDisplayMenu(cmd);
KindMediaIframe.focus();
KE_MEDIA_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_REAL':
KindDisplayMenu(cmd);
KindRealIframe.focus();
KE_REAL_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_LINK':
KindDisplayMenu(cmd);
KindLinkIframe.focus();
KE_LINK_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_UNLINK':
KindSimpleExecute('unlink');
break;
case 'KE_SPECIALCHAR':
KindDisplayMenu(cmd);
break;
case 'KE_SPECIALCHAR_END':
KindEditorForm.focus();
KindSelect();
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_LAYER':
KindDisplayMenu(cmd);
break;
case 'KE_LAYER_END':
KindEditorForm.focus();
var element = document.createElement("div");
element.style.padding = "5px";
element.style.border = "1px solid #AAAAAA";
element.style.backgroundColor = value;
var childElement = document.createElement("div");
childElement.innerHTML = KE_LANG['INPUT_CONTENT'];
element.appendChild(childElement);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TABLE':
KindDisplayMenu(cmd);
break;
case 'KE_TABLE_END':
KindEditorForm.focus();
var location = value.split(',');
var element = document.createElement("table");
element.cellPadding = 0;
element.cellSpacing = 0;
element.border = 1;
element.style.width = "100px";
element.style.height = "100px";
for (var i = 0; i < location[0]; i++) {
var rowElement = element.insertRow(i);
for (var j = 0; j < location[1]; j++) {
var cellElement = rowElement.insertCell(j);
cellElement.innerHTML = " ";
}
}
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_HR':
KindDisplayMenu(cmd);
break;
case 'KE_HR_END':
KindEditorForm.focus();
var element = document.createElement("hr");
element.width = "100%";
element.color = value;
element.size = 1;
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_DATE':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var year = date.getFullYear().toString(10);
var month = (date.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = date.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var value = year + '-' + month + '-' + day;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TIME':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var hour = date.getHours().toString(10);
hour = hour.length < 2 ? '0' + hour : hour;
var minute = date.getMinutes().toString(10);
minute = minute.length < 2 ? '0' + minute : minute;
var second = date.getSeconds().toString(10);
second = second.length < 2 ? '0' + second : second;
var value = hour + ':' + minute + ':' + second;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_PREVIEW':
eval(KE_OBJ_NAME).data();
var newWin = window.open('', 'kindPreview','width=800,height=600,left=30,top=30,resizable=yes,scrollbars=yes');
KindWriteFullHtml(newWin.document, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
KindDisableMenu();
break;
case 'KE_ABOUT':
KindDisplayMenu(cmd);
break;
default:
break;
}
}
function KindDisableToolbar(flag)
{
if (flag == true) {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'design.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
if (KE_TOOLBAR_ICON[i][0] == 'KE_SOURCE' || KE_TOOLBAR_ICON[i][0] == 'KE_PREVIEW' || KE_TOOLBAR_ICON[i][0] == 'KE_ABOUT') {
continue;
}
el.style.visibility = 'hidden';
}
} else {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'source.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
el.style.visibility = 'visible';
KE_EDITFORM_DOCUMENT.designMode = 'On';
}
}
}
function KindCreateIcon(icon)
{
var str = '<img id="'+ icon[0] +'" src="' + KE_SKIN_PATH + icon[1] + '" alt="' + icon[2] + '" title="' + icon[2] +
'" align="absmiddle" style="border:1px solid ' + KE_TOOLBAR_BG_COLOR +';cursor:pointer;height:20px;';
str += '" onclick="javascript:KindExecute(\''+ icon[0] +'\');" '+
'onmouseover="javascript:this.style.border=\'1px solid ' + KE_MENU_BORDER_COLOR + '\';" ' +
'onmouseout="javascript:this.style.border=\'1px solid ' + KE_TOOLBAR_BG_COLOR + '\';" ';
str += '>';
return str;
}
function KindCreateToolbar()
{
var htmlData = '<table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
if (KE_EDITOR_TYPE == 'full') {
for (i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_TOP_TOOLBAR_ICON[i]) + '</td>';
}
htmlData += '</tr></table><table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
for (i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_BOTTOM_TOOLBAR_ICON[i]) + '</td>';
}
} else {
for (i = 0; i < KE_SIMPLE_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_SIMPLE_TOOLBAR_ICON[i]) + '</td>';
}
}
htmlData += '</tr></table>';
return htmlData;
}
function KindWriteFullHtml(documentObj, content)
{
var editHtmlData = '';
editHtmlData += '<html>\r\n<head>\r\n<title>KindEditor</title>\r\n';
editHtmlData += '<link href="'+KE_CSS_PATH+'" rel="stylesheet" type="text/css">\r\n</head>\r\n<body>\r\n';
editHtmlData += content;
editHtmlData += '\r\n</body>\r\n</html>\r\n';
documentObj.open();
documentObj.write(editHtmlData);
documentObj.close();
}
function KindEditor(objName)
{
this.objName = objName;
this.hiddenName = objName;
this.siteDomain;
this.editorType;
this.safeMode;
this.uploadMode;
this.editorWidth;
this.editorHeight;
this.skinPath;
this.iconPath;
this.imageAttachPath;
this.imageUploadCgi;
this.cssPath;
this.menuBorderColor;
this.menuBgColor;
this.menuTextColor;
this.menuSelectedColor;
this.toolbarBorderColor;
this.toolbarBgColor;
this.formBorderColor;
this.formBgColor;
this.buttonColor;
this.init = function()
{
if (this.siteDomain) KE_SITE_DOMAIN = this.siteDomain;
if (this.editorType) KE_EDITOR_TYPE = this.editorType.toLowerCase();
if (this.safeMode) KE_SAFE_MODE = this.safeMode;
if (this.uploadMode) KE_UPLOAD_MODE = this.uploadMode;
if (this.editorWidth) KE_WIDTH = this.editorWidth;
if (this.editorHeight) KE_HEIGHT = this.editorHeight;
if (this.skinPath) KE_SKIN_PATH = this.skinPath;
if (this.iconPath) KE_ICON_PATH = this.iconPath;
if (this.imageAttachPath) KE_IMAGE_ATTACH_PATH = this.imageAttachPath;
if (this.imageUploadCgi) KE_IMAGE_UPLOAD_CGI = this.imageUploadCgi;
if (this.cssPath) KE_CSS_PATH = this.cssPath;
if (this.menuBorderColor) KE_MENU_BORDER_COLOR = this.menuBorderColor;
if (this.menuBgColor) KE_MENU_BG_COLOR = this.menuBgColor;
if (this.menuTextColor) KE_MENU_TEXT_COLOR = this.menuTextColor;
if (this.menuSelectedColor) KE_MENU_SELECTED_COLOR = this.menuSelectedColor;
if (this.toolbarBorderColor) KE_TOOLBAR_BORDER_COLOR = this.toolbarBorderColor;
if (this.toolbarBgColor) KE_TOOLBAR_BG_COLOR = this.toolbarBgColor;
if (this.formBorderColor) KE_FORM_BORDER_COLOR = this.formBorderColor;
if (this.formBgColor) KE_FORM_BG_COLOR = this.formBgColor;
if (this.buttonColor) KE_BUTTON_COLOR = this.buttonColor;
KE_OBJ_NAME = this.objName;
KE_BROWSER = KindGetBrowser();
KE_TOOLBAR_ICON = Array();
for (var i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_TOP_TOOLBAR_ICON[i]);
}
for (var i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_BOTTOM_TOOLBAR_ICON[i]);
}
}
this.show = function()
{
this.init();
var widthStyle = 'width:' + KE_WIDTH + ';';
var widthArr = KE_WIDTH.match(/(\d+)([px%]{1,2})/);
var iframeWidthStyle = 'width:' + (parseInt(widthArr[1]) - 2).toString(10) + widthArr[2] + ';';
var heightStyle = 'height:' + KE_HEIGHT + ';';
var heightArr = KE_HEIGHT.match(/(\d+)([px%]{1,2})/);
var iframeHeightStyle = 'height:' + (parseInt(heightArr[1]) - 3).toString(10) + heightArr[2] + ';';
if (KE_BROWSER == '') {
var htmlData = '<div id="KindEditTextarea" style="' + widthStyle + heightStyle + '">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + widthStyle + heightStyle +
'padding:0;margin:0;border:1px solid '+ KE_FORM_BORDER_COLOR +
';font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';">' + document.getElementsByName(this.hiddenName)[0].value + '</textarea></div>';
document.open();
document.write(htmlData);
document.close();
return;
}
var htmlData = '<div style="font-family:'+KE_FONT_FAMILY+';">';
htmlData += '<div style="'+widthStyle+';border:1px solid ' + KE_TOOLBAR_BORDER_COLOR + ';background-color:'+ KE_TOOLBAR_BG_COLOR +'">';
htmlData += KindCreateToolbar();
htmlData += '</div><div id="KindEditorIframe" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';border-top:0;">' +
'<iframe name="KindEditorForm" id="KindEditorForm" frameborder="0" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;"></iframe></div>';
if (KE_EDITOR_TYPE == 'full') {
htmlData += '<div id="KindEditTextarea" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';background-color:'+
KE_FORM_BG_COLOR +';border-top:0;display:none;">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';" onclick="javascirit:parent.KindDisableMenu();"></textarea></div>';
}
htmlData += '</div>';
for (var i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
if (KE_POPUP_MENU_TABLE[i] == 'KE_IMAGE') {
htmlData += '<span id="InsertIframe">';
}
htmlData += KindPopupMenu(KE_POPUP_MENU_TABLE[i]);
if (KE_POPUP_MENU_TABLE[i] == 'KE_REAL') {
htmlData += '</span>';
}
}
document.open();
document.write(htmlData);
document.close();
if (KE_BROWSER == 'IE') {
KE_EDITFORM_DOCUMENT = document.frames("KindEditorForm").document;
} else {
KE_EDITFORM_DOCUMENT = document.getElementById('KindEditorForm').contentDocument;
}
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
KindDrawIframe('KE_LINK');
KE_EDITFORM_DOCUMENT.designMode = 'On';
KindWriteFullHtml(KE_EDITFORM_DOCUMENT, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
var el = KE_EDITFORM_DOCUMENT.body;
if (KE_EDITFORM_DOCUMENT.addEventListener){
KE_EDITFORM_DOCUMENT.addEventListener('click', KindDisableMenu, false);
} else if (el.attachEvent){
el.attachEvent('onclick', KindDisableMenu);
}
}
this.data = function()
{
var htmlResult;
if (KE_BROWSER == '') {
htmlResult = document.getElementById("KindCodeForm").value;
} else {
if (KE_EDITOR_TYPE == 'full') {
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
} else {
htmlResult = document.getElementById("KindCodeForm").value;
}
} else {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
}
}
KindDisableMenu();
htmlResult = KindHtmlToXhtml(htmlResult);
htmlResult = KindClearScriptTag(htmlResult);
document.getElementsByName(this.hiddenName)[0].value = htmlResult;
return htmlResult;
}
}
| JavaScript |
var teButtons = TextileEditor.buttons;
teButtons.push(new TextileEditorButton('ed_strong', 'bold.png', '*', '*', 'b', 'Bold','s'));
teButtons.push(new TextileEditorButton('ed_emphasis', 'italic.png', '_', '_', 'i', 'Italicize','s'));
teButtons.push(new TextileEditorButton('ed_underline', 'underline.png', '+', '+', 'u', 'Underline','s'));
teButtons.push(new TextileEditorButton('ed_strike', 'strikethrough.png', '-', '-', 's', 'Strikethrough','s'));
teButtons.push(new TextileEditorButton('ed_ol', 'list_numbers.png', ' # ', '\n', ',', 'Numbered List'));
teButtons.push(new TextileEditorButton('ed_ul', 'list_bullets.png', ' * ', '\n', '.', 'Bulleted List'));
teButtons.push(new TextileEditorButton('ed_p', 'paragraph.png', 'p', '\n', 'p', 'Paragraph'));
teButtons.push(new TextileEditorButton('ed_h1', 'h1.png', 'h1', '\n', '1', 'Header 1'));
teButtons.push(new TextileEditorButton('ed_h2', 'h2.png', 'h2', '\n', '2', 'Header 2'));
teButtons.push(new TextileEditorButton('ed_h3', 'h3.png', 'h3', '\n', '3', 'Header 3'));
teButtons.push(new TextileEditorButton('ed_h4', 'h4.png', 'h4', '\n', '4', 'Header 4'));
teButtons.push(new TextileEditorButton('ed_block', 'blockquote.png', 'bq', '\n', 'q', 'Blockquote'));
teButtons.push(new TextileEditorButton('ed_outdent', 'outdent.png', ')', '\n', ']', 'Outdent'));
teButtons.push(new TextileEditorButton('ed_indent', 'indent.png', '(', '\n', '[', 'Indent'));
teButtons.push(new TextileEditorButton('ed_justifyl', 'left.png', '<', '\n', 'l', 'Left Justify'));
teButtons.push(new TextileEditorButton('ed_justifyc', 'center.png', '=', '\n', 'e', 'Center Text'));
teButtons.push(new TextileEditorButton('ed_justifyr', 'right.png', '>', '\n', 'r', 'Right Justify'));
teButtons.push(new TextileEditorButton('ed_justify', 'justify.png', '<>', '\n', 'j', 'Justify'));
// teButtons.push(new TextileEditorButton('ed_code','code','@','@','c','Code')); | JavaScript |
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
| JavaScript |
/**
* WYSIWYG HTML Editor for Internet
*
* @author Roddy <luolonghao@gmail.com>
* @version 2.5.3
*/
var KE_VERSION = "2.5.4";
var KE_EDITOR_TYPE = "full"; //full or simple
var KE_SAFE_MODE = false; // true or false
var KE_UPLOAD_MODE = true; // true or false
var KE_FONT_FAMILY = "Courier New";
var KE_WIDTH = "700px";
var KE_HEIGHT = "400px";
var KE_SITE_DOMAIN = "";
var KE_SKIN_PATH = "./skins/default/";
var KE_ICON_PATH = "./icons/";
var KE_IMAGE_ATTACH_PATH = "./attached/";
var KE_IMAGE_UPLOAD_CGI = "./upload_cgi/upload.php";
var KE_CSS_PATH = "/editor/common.css";
var KE_MENU_BORDER_COLOR = '#AAAAAA';
var KE_MENU_BG_COLOR = '#EFEFEF';
var KE_MENU_TEXT_COLOR = '#222222';
var KE_MENU_SELECTED_COLOR = '#CCCCCC';
var KE_TOOLBAR_BORDER_COLOR = '#DDDDDD';
var KE_TOOLBAR_BG_COLOR = '#EFEFEF';
var KE_FORM_BORDER_COLOR = '#DDDDDD';
var KE_FORM_BG_COLOR = '#FFFFFF';
var KE_BUTTON_COLOR = '#AAAAAA';
var KE_LANG = {
INPUT_URL : "请输入正确的URL地址。",
SELECT_IMAGE : "请选择图片。",
INVALID_IMAGE : "只能选择GIF,JPG,PNG,BMP格式的图片,请重新选择。",
INVALID_FLASH : "只能选择SWF格式的文件,请重新选择。",
INVALID_MEDIA : "只能选择MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF格式的文件,请重新选择。",
INVALID_REAL : "只能选择RM,RMVB格式的文件,请重新选择。",
INVALID_WIDTH : "宽度不是数字,请重新输入。",
INVALID_HEIGHT : "高度不是数字,请重新输入。",
INVALID_BORDER : "边框不是数字,请重新输入。",
INVALID_HSPACE : "横隔不是数字,请重新输入。",
INVALID_VSPACE : "竖隔不是数字,请重新输入。",
INPUT_CONTENT : "请输入内容",
TITLE : "描述",
WIDTH : "宽",
HEIGHT : "高",
BORDER : "边",
ALIGN : "对齐方式",
HSPACE : "横隔",
VSPACE : "竖隔",
CONFIRM : "确定",
CANCEL : "取消",
PREVIEW : "预览",
LISTENING : "试听",
LOCAL : "本地",
REMOTE : "远程",
NEW_WINDOW : "新窗口",
CURRENT_WINDOW : "当前窗口",
TARGET : "目标",
ABOUT : "访问技术支持网站",
SUBJECT : "标题"
}
var KE_FONT_NAME = Array(
Array('SimSun', '宋体'),
Array('SimHei', '黑体'),
Array('FangSong_GB2312', '仿宋体'),
Array('KaiTi_GB2312', '楷体'),
Array('NSimSun', '新宋体'),
Array('Arial', 'Arial'),
Array('Arial Black', 'Arial Black'),
Array('Times New Roman', 'Times New Roman'),
Array('Courier New', 'Courier New'),
Array('Tahoma', 'Tahoma'),
Array('Verdana', 'Verdana'),
Array('GulimChe', 'GulimChe'),
Array('MS Gothic', 'MS Gothic')
);
var KE_SPECIAL_CHARACTER = Array(
'§','№','☆','★','○','●','◎','◇','◆','□','℃','‰','■','△','▲','※',
'→','←','↑','↓','〓','¤','°','#','&','@','\','︿','_',' ̄','―','α',
'β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ',
'σ','τ','υ','φ','χ','ψ','ω','≈','≡','≠','=','≤','≥','<','>','≮',
'≯','∷','±','+','-','×','÷','/','∫','∮','∝','∞','∧','∨','∑','∏',
'∪','∩','∈','∵','∴','⊥','∥','∠','⌒','⊙','≌','∽','〖','〗',
'【','】','(',')','[',']'
);
var KE_TOP_TOOLBAR_ICON = Array(
Array('KE_SOURCE', 'source.gif', '视图转换'),
Array('KE_PREVIEW', 'preview.gif', '预览'),
Array('KE_ZOOM', 'zoom.gif', '显示比例'),
Array('KE_PRINT', 'print.gif', '打印'),
Array('KE_UNDO', 'undo.gif', '回退'),
Array('KE_REDO', 'redo.gif', '前进'),
Array('KE_CUT', 'cut.gif', '剪切'),
Array('KE_COPY', 'copy.gif', '复制'),
Array('KE_PASTE', 'paste.gif', '粘贴'),
Array('KE_SELECTALL', 'selectall.gif', '全选'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_JUSTIFYFULL', 'justifyfull.gif', '两端对齐'),
Array('KE_NUMBEREDLIST', 'numberedlist.gif', '编号'),
Array('KE_UNORDERLIST', 'unorderedlist.gif', '项目符号'),
Array('KE_INDENT', 'indent.gif', '减少缩进'),
Array('KE_OUTDENT', 'outdent.gif', '增加缩进'),
Array('KE_SUBSCRIPT', 'subscript.gif', '下标'),
Array('KE_SUPERSCRIPT', 'superscript.gif', '上标'),
Array('KE_DATE', 'date.gif', '日期'),
Array('KE_TIME', 'time.gif', '时间')
);
var KE_BOTTOM_TOOLBAR_ICON = Array(
Array('KE_TITLE', 'title.gif', '标题'),
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_STRIKE', 'strikethrough.gif', '删除线'),
Array('KE_REMOVE', 'removeformat.gif', '删除格式'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_FLASH', 'flash.gif', 'Flash'),
Array('KE_MEDIA', 'media.gif', 'Windows Media Player'),
Array('KE_REAL', 'real.gif', 'Real Player'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_TABLE', 'table.gif', '表格'),
Array('KE_SPECIALCHAR', 'specialchar.gif', '特殊字符'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_UNLINK', 'unlink.gif', '删除超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_SIMPLE_TOOLBAR_ICON = Array(
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_TITLE_TABLE = Array(
Array('H1', KE_LANG['SUBJECT'] + ' 1'),
Array('H2', KE_LANG['SUBJECT'] + ' 2'),
Array('H3', KE_LANG['SUBJECT'] + ' 3'),
Array('H4', KE_LANG['SUBJECT'] + ' 4'),
Array('H5', KE_LANG['SUBJECT'] + ' 5'),
Array('H6', KE_LANG['SUBJECT'] + ' 6')
);
var KE_ZOOM_TABLE = Array('250%', '200%', '150%', '120%', '100%', '80%', '50%');
var KE_FONT_SIZE = Array(
Array(1,'8pt'),
Array(2,'10pt'),
Array(3,'12pt'),
Array(4,'14pt'),
Array(5,'18pt'),
Array(6,'24pt'),
Array(7,'36pt')
);
var KE_POPUP_MENU_TABLE = Array(
"KE_ZOOM", "KE_TITLE", "KE_FONTNAME", "KE_FONTSIZE", "KE_TEXTCOLOR", "KE_BGCOLOR",
"KE_LAYER", "KE_TABLE", "KE_HR", "KE_ICON", "KE_SPECIALCHAR", "KE_ABOUT",
"KE_IMAGE", "KE_FLASH", "KE_MEDIA", "KE_REAL", "KE_LINK"
);
var KE_COLOR_TABLE = Array(
"#FF0000", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#FF00FF", "#FFFFFF", "#F5F5F5", "#DCDCDC", "#FFFAFA",
"#D3D3D3", "#C0C0C0", "#A9A9A9", "#808080", "#696969", "#000000", "#2F4F4F", "#708090", "#778899", "#4682B4",
"#4169E1", "#6495ED", "#B0C4DE", "#7B68EE", "#6A5ACD", "#483D8B", "#191970", "#000080", "#00008B", "#0000CD",
"#1E90FF", "#00BFFF", "#87CEFA", "#87CEEB", "#ADD8E6", "#B0E0E6", "#F0FFFF", "#E0FFFF", "#AFEEEE", "#00CED1",
"#5F9EA0", "#48D1CC", "#00FFFF", "#40E0D0", "#20B2AA", "#008B8B", "#008080", "#7FFFD4", "#66CDAA", "#8FBC8F",
"#3CB371", "#2E8B57", "#006400", "#008000", "#228B22", "#32CD32", "#00FF00", "#7FFF00", "#7CFC00", "#ADFF2F",
"#98FB98", "#90EE90", "#00FF7F", "#00FA9A", "#556B2F", "#6B8E23", "#808000", "#BDB76B", "#B8860B", "#DAA520",
"#FFD700", "#F0E68C", "#EEE8AA", "#FFEBCD", "#FFE4B5", "#F5DEB3", "#FFDEAD", "#DEB887", "#D2B48C", "#BC8F8F",
"#A0522D", "#8B4513", "#D2691E", "#CD853F", "#F4A460", "#8B0000", "#800000", "#A52A2A", "#B22222", "#CD5C5C",
"#F08080", "#FA8072", "#E9967A", "#FFA07A", "#FF7F50", "#FF6347", "#FF8C00", "#FFA500", "#FF4500", "#DC143C",
"#FF0000", "#FF1493", "#FF00FF", "#FF69B4", "#FFB6C1", "#FFC0CB", "#DB7093", "#C71585", "#800080", "#8B008B",
"#9370DB", "#8A2BE2", "#4B0082", "#9400D3", "#9932CC", "#BA55D3", "#DA70D6", "#EE82EE", "#DDA0DD", "#D8BFD8",
"#E6E6FA", "#F8F8FF", "#F0F8FF", "#F5FFFA", "#F0FFF0", "#FAFAD2", "#FFFACD", "#FFF8DC", "#FFFFE0", "#FFFFF0",
"#FFFAF0", "#FAF0E6", "#FDF5E6", "#FAEBD7", "#FFE4C4", "#FFDAB9", "#FFEFD5", "#FFF5EE", "#FFF0F5", "#FFE4E1"
);
var KE_IMAGE_ALIGN_TABLE = Array(
"baseline", "top", "middle", "bottom", "texttop", "absmiddle", "absbottom", "left", "right"
);
var KE_OBJ_NAME;
var KE_SELECTION;
var KE_RANGE;
var KE_RANGE_TEXT;
var KE_EDITFORM_DOCUMENT;
var KE_IMAGE_DOCUMENT;
var KE_FLASH_DOCUMENT;
var KE_MEDIA_DOCUMENT;
var KE_REAL_DOCUMENT;
var KE_LINK_DOCUMENT;
var KE_BROWSER;
var KE_TOOLBAR_ICON;
function KindGetBrowser()
{
var browser = '';
var agentInfo = navigator.userAgent.toLowerCase();
if (agentInfo.indexOf("msie") > -1) {
var re = new RegExp("msie\\s?([\\d\\.]+)","ig");
var arr = re.exec(agentInfo);
if (parseInt(RegExp.$1) >= 5.5) {
browser = 'IE';
}
} else if (agentInfo.indexOf("firefox") > -1) {
browser = 'FF';
} else if (agentInfo.indexOf("netscape") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[temp1.length-1].split('/');
if (parseInt(temp2[1]) >= 7) {
browser = 'NS';
}
} else if (agentInfo.indexOf("gecko") > -1) {
browser = 'ML';
} else if (agentInfo.indexOf("opera") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[0].split('/');
if (parseInt(temp2[1]) >= 9) {
browser = 'OPERA';
}
}
return browser;
}
function KindGetFileName(file, separator)
{
var temp = file.split(separator);
var len = temp.length;
var fileName = temp[len-1];
return fileName;
}
function KindGetFileExt(fileName)
{
var temp = fileName.split(".");
var len = temp.length;
var fileExt = temp[len-1].toLowerCase();
return fileExt;
}
function KindCheckImageFileType(file, separator)
{
if (separator == "/" && file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, separator);
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'gif' && fileExt != 'jpg' && fileExt != 'png' && fileExt != 'bmp') {
alert(KE_LANG['INVALID_IMAGE']);
return false;
}
return true;
}
function KindCheckFlashFileType(file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'swf') {
alert(KE_LANG['INVALID_FLASH']);
return false;
}
return true;
}
function KindCheckMediaFileType(cmd, file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (cmd == 'KE_REAL') {
if (fileExt != 'rm' && fileExt != 'rmvb') {
alert(KE_LANG['INVALID_REAL']);
return false;
}
} else {
if (fileExt != 'mp3' && fileExt != 'wav' && fileExt != 'wma' && fileExt != 'wmv' && fileExt != 'mid' && fileExt != 'avi' && fileExt != 'mpg' && fileExt != 'asf') {
alert(KE_LANG['INVALID_MEDIA']);
return false;
}
}
return true;
}
function KindHtmlToXhtml(str)
{
str = str.replace(/<br.*?>/gi, "<br />");
str = str.replace(/(<hr\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<img\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<\w+)(.*?>)/gi, function ($0,$1,$2) {
return($1.toLowerCase() + KindConvertAttribute($2));
}
);
str = str.replace(/(<\/\w+>)/gi, function ($0,$1) {
return($1.toLowerCase());
}
);
return str;
}
function KindConvertAttribute(str)
{
if (KE_SAFE_MODE == true) {
str = KindClearAttributeScriptTag(str);
}
return str;
}
function KindClearAttributeScriptTag(str)
{
var re = new RegExp("(\\son[a-z]+=)[\"']?[^>]*?[^\\\\\>][\"']?([\\s>])","ig");
str = str.replace(re, function ($0,$1,$2) {
return($1.toLowerCase() + "\"\"" + $2);
}
);
return str;
}
function KindClearScriptTag(str)
{
if (KE_SAFE_MODE == false) {
return str;
}
str = str.replace(/<(script.*?)>/gi, "[$1]");
str = str.replace(/<\/script>/gi, "[/script]");
return str;
}
function KindHtmlentities(str)
{
str = str.replace(/&/g,'&');
str = str.replace(/</g,'<');
str = str.replace(/>/g,'>');
str = str.replace(/"/g,'"');
return str;
}
function KindGetTop(id)
{
var top = 28;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
top += eval("obj" + tmp).offsetTop;
}
return top;
}
function KindGetLeft(id)
{
var left = 2;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
left += eval("obj" + tmp).offsetLeft;
}
return left;
}
function KindDisplayMenu(cmd)
{
KindEditorForm.focus();
if (cmd != 'KE_ABOUT') {
KindSelection();
}
KindDisableMenu();
var top, left;
top = KindGetTop(cmd);
left = KindGetLeft(cmd);
if (cmd == 'KE_ABOUT') {
left -= 200;
} else if (cmd == 'KE_LINK') {
left -= 220;
}
document.getElementById('POPUP_'+cmd).style.top = top.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.left = left.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.display = 'block';
}
function KindDisableMenu()
{
for (i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
document.getElementById('POPUP_'+KE_POPUP_MENU_TABLE[i]).style.display = 'none';
}
}
function KindReloadIframe()
{
var str = '';
str += KindPopupMenu('KE_IMAGE');
str += KindPopupMenu('KE_FLASH');
str += KindPopupMenu('KE_MEDIA');
str += KindPopupMenu('KE_REAL');
document.getElementById('InsertIframe').innerHTML = str;
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
}
function KindGetMenuCommonStyle()
{
var str = 'position:absolute;top:1px;left:1px;font-size:12px;color:'+KE_MENU_TEXT_COLOR+
';background-color:'+KE_MENU_BG_COLOR+';border:solid 1px '+KE_MENU_BORDER_COLOR+';z-index:1;display:none;';
return str;
}
function KindGetCommonMenu(cmd, content)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="'+KindGetMenuCommonStyle()+'">';
str += content;
str += '</div>';
return str;
}
function KindCreateColorTable(cmd, eventStr)
{
var str = '';
str += '<table cellpadding="0" cellspacing="2" border="0">';
for (i = 0; i < KE_COLOR_TABLE.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="width:12px;height:12px;border:1px solid #AAAAAA;font-size:1px;cursor:pointer;background-color:' +
KE_COLOR_TABLE[i] + ';" onmouseover="javascript:this.style.borderColor=\'#000000\';' + ((eventStr) ? eventStr : '') + '" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onclick="javascript:KindExecute(\''+cmd+'_END\', \'' + KE_COLOR_TABLE[i] + '\');"> </td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
}
function KindDrawColorTable(cmd)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;padding:2px;'+KindGetMenuCommonStyle()+'">';
str += KindCreateColorTable(cmd);
str += '</div>';
return str;
}
function KindDrawMedia(cmd)
{
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="'+cmd+'preview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="'+cmd+'link" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['LISTENING']+'" onclick="javascript:parent.KindMediaPreview(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawMediaEnd(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
return str;
}
function KindPopupMenu(cmd)
{
switch (cmd)
{
case 'KE_ZOOM':
var str = '';
for (i = 0; i < KE_ZOOM_TABLE.length; i++) {
str += '<div style="padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ZOOM_END\', \'' + KE_ZOOM_TABLE[i] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_ZOOM_TABLE[i] + '</div>';
}
str = KindGetCommonMenu('KE_ZOOM', str);
return str;
break;
case 'KE_TITLE':
var str = '';
for (i = 0; i < KE_TITLE_TABLE.length; i++) {
str += '<div style="width:140px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TITLE_END\', \'' + KE_TITLE_TABLE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';"><' + KE_TITLE_TABLE[i][0] + ' style="margin:2px;">' +
KE_TITLE_TABLE[i][1] + '</' + KE_TITLE_TABLE[i][0] + '></div>';
}
str = KindGetCommonMenu('KE_TITLE', str);
return str;
break;
case 'KE_FONTNAME':
var str = '';
for (i = 0; i < KE_FONT_NAME.length; i++) {
str += '<div style="font-family:' + KE_FONT_NAME[i][0] +
';padding:2px;width:160px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTNAME_END\', \'' + KE_FONT_NAME[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_NAME[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTNAME', str);
return str;
break;
case 'KE_FONTSIZE':
var str = '';
for (i = 0; i < KE_FONT_SIZE.length; i++) {
str += '<div style="font-size:' + KE_FONT_SIZE[i][1] +
';padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTSIZE_END\', \'' + KE_FONT_SIZE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_SIZE[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTSIZE', str);
return str;
break;
case 'KE_TEXTCOLOR':
var str = '';
str = KindDrawColorTable('KE_TEXTCOLOR');
return str;
break;
case 'KE_BGCOLOR':
var str = '';
str = KindDrawColorTable('KE_BGCOLOR');
return str;
break;
case 'KE_HR':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="hrPreview" style="margin:10px 2px 10px 2px;height:1px;border:0;font-size:0;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'hrPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_LAYER':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="divPreview" style="margin:5px 2px 5px 2px;height:20px;border:1px solid #AAAAAA;font-size:1px;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'divPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_ICON':
var str = '';
var iconNum = 36;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < iconNum; i++) {
if (i == 0 || (i >= 6 && i%6 == 0)) {
str += '<tr>';
}
var num;
if ((i+1).toString(10).length < 2) {
num = '0' + (i+1);
} else {
num = (i+1).toString(10);
}
var iconUrl = KE_ICON_PATH + 'etc_' + num + '.gif';
str += '<td style="padding:2px;border:0;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ICON_END\', \'' + iconUrl + '\');">' +
'<img src="' + iconUrl + '" style="border:1px solid #EEEEEE;" onmouseover="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#EEEEEE\';">' + '</td>';
if (i >= 5 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_SPECIALCHAR':
var str = '';
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < KE_SPECIAL_CHARACTER.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="padding:2px;border:1px solid #AAAAAA;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_SPECIALCHAR_END\', \'' + KE_SPECIAL_CHARACTER[i] + '\');" ' +
'onmouseover="javascript:this.style.borderColor=\'#000000\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';">' + KE_SPECIAL_CHARACTER[i] + '</td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_TABLE':
var str = '';
var num = 10;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="0" style="'+KindGetMenuCommonStyle()+'">';
for (i = 1; i <= num; i++) {
str += '<tr>';
for (j = 1; j <= num; j++) {
var value = i.toString(10) + ',' + j.toString(10);
str += '<td id="kindTableTd' + i.toString(10) + '_' + j.toString(10) +
'" style="width:15px;height:15px;background-color:#FFFFFF;border:1px solid #DDDDDD;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TABLE_END\', \'' + value + '\');" ' +
'onmouseover="javascript:KindDrawTableSelected(\''+i.toString(10)+'\', \''+j.toString(10)+'\');" ' +
'onmouseout="javascript:;"> </td>';
}
str += '</tr>';
}
str += '<tr><td colspan="10" id="tableLocation" style="text-align:center;height:20px;"></td></tr>';
str += '</table>';
return str;
break;
case 'KE_IMAGE':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindImageIframe" id="KindImageIframe" frameborder="0" style="width:250px;height:390px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_FLASH':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindFlashIframe" id="KindFlashIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_MEDIA':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindMediaIframe" id="KindMediaIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_REAL':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindRealIframe" id="KindRealIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_LINK':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindLinkIframe" id="KindLinkIframe" frameborder="0" style="width:250px;height:85px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_ABOUT':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:230px;'+KindGetMenuCommonStyle()+';padding:5px;">';
str += '<span style="margin-right:10px;">KindEditor ' + KE_VERSION + '</span>' +
'<a href="http://www.kindsoft.net/" target="_blank" style="color:#4169e1;" onclick="javascript:KindDisableMenu();">'+KE_LANG['ABOUT']+'</a><br />';
str += '</div>';
return str;
break;
default:
break;
}
}
function KindDrawIframe(cmd)
{
if (KE_BROWSER == 'IE') {
KE_IMAGE_DOCUMENT = document.frames("KindImageIframe").document;
KE_FLASH_DOCUMENT = document.frames("KindFlashIframe").document;
KE_MEDIA_DOCUMENT = document.frames("KindMediaIframe").document;
KE_REAL_DOCUMENT = document.frames("KindRealIframe").document;
KE_LINK_DOCUMENT = document.frames("KindLinkIframe").document;
} else {
KE_IMAGE_DOCUMENT = document.getElementById('KindImageIframe').contentDocument;
KE_FLASH_DOCUMENT = document.getElementById('KindFlashIframe').contentDocument;
KE_MEDIA_DOCUMENT = document.getElementById('KindMediaIframe').contentDocument;
KE_REAL_DOCUMENT = document.getElementById('KindRealIframe').contentDocument;
KE_LINK_DOCUMENT = document.getElementById('KindLinkIframe').contentDocument;
}
switch (cmd)
{
case 'KE_IMAGE':
var str = '';
str += '<div align="center">' +
'<form name="uploadForm" style="margin:0;padding:0;" method="post" enctype="multipart/form-data" ' +
'action="' + KE_IMAGE_UPLOAD_CGI + '" onsubmit="javascript:if(parent.KindDrawImageEnd()==false){return false;};">' +
'<input type="hidden" name="fileName" id="fileName" value="" />' +
'<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0" style="margin-bottom:3px;"><tr><td id="imgPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:50px;padding-left:5px;">';
if (KE_UPLOAD_MODE == true) {
str += '<select id="imageType" onchange="javascript:parent.KindImageType(this.value);document.getElementById(\''+cmd+'submitButton\').focus();"><option value="1" selected="selected">'+KE_LANG['LOCAL']+'</option><option value="2">'+KE_LANG['REMOTE']+'</option></select>';
} else {
str += KE_LANG['REMOTE'];
}
str += '</td><td style="width:200px;padding-bottom:3px;">';
if (KE_UPLOAD_MODE == true) {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;display:none;" />' +
'<input type="file" name="fileData" id="imgFile" size="14" style="border:1px solid #555555;" onclick="javascript:document.getElementById(\'imgLink\').value=\'http://\';" />';
} else {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;" />' +
'<input type="hidden" name="imageType" id="imageType" value="2"><input type="hidden" name="fileData" id="imgFile" value="" />';
}
str += '</td></tr><tr><td colspan="2" style="padding-bottom:3px;">' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="18%" style="padding:2px 2px 2px 5px;">'+KE_LANG['TITLE']+'</td><td width="82%"><input type="text" name="imgTitle" id="imgTitle" value="" maxlength="100" style="width:95%;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="10%" style="padding:2px 2px 2px 5px;">'+KE_LANG['WIDTH']+'</td><td width="23%"><input type="text" name="imgWidth" id="imgWidth" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['HEIGHT']+'</td><td width="23%"><input type="text" name="imgHeight" id="imgHeight" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['BORDER']+'</td><td width="23%"><input type="text" name="imgBorder" id="imgBorder" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="39%" style="padding:2px 2px 2px 5px;"><select id="imgAlign" name="imgAlign"><option value="">'+KE_LANG['ALIGN']+'</option>';
for (var i = 0; i < KE_IMAGE_ALIGN_TABLE.length; i++) {
str += '<option value="' + KE_IMAGE_ALIGN_TABLE[i] + '">' + KE_IMAGE_ALIGN_TABLE[i] + '</option>';
}
str += '</select></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['HSPACE']+'</td><td width="15%"><input type="text" name="imgHspace" id="imgHspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['VSPACE']+'</td><td width="15%"><input type="text" name="imgVspace" id="imgVspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'</td></tr><tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindImagePreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table></form></div>';
KindDrawMenuIframe(KE_IMAGE_DOCUMENT, str);
break;
case 'KE_FLASH':
var str = '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="flashPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="flashLink" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindFlashPreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawFlashEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
KindDrawMenuIframe(KE_FLASH_DOCUMENT, str);
break;
case 'KE_MEDIA':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_MEDIA_DOCUMENT, str);
break;
case 'KE_REAL':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_REAL_DOCUMENT, str);
break;
case 'KE_LINK':
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td style="width:50px;padding:5px;">URL</td>' +
'<td style="width:200px;padding-top:5px;padding-bottom:5px;"><input type="text" id="hyperLink" value="http://" style="width:190px;border:1px solid #555555;background-color:#FFFFFF;"></td>' +
'<tr><td style="padding:5px;">'+KE_LANG['TARGET']+'</td>' +
'<td style="padding-bottom:5px;"><select id="hyperLinkTarget"><option value="_blank" selected="selected">'+KE_LANG['NEW_WINDOW']+'</option><option value="">'+KE_LANG['CURRENT_WINDOW']+'</option></select></td></tr>' +
'<tr><td colspan="2" style="padding-bottom:5px;" align="center">' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawLinkEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>';
str += '</table>';
KindDrawMenuIframe(KE_LINK_DOCUMENT, str);
break;
default:
break;
}
}
function KindDrawMenuIframe(obj, str)
{
obj.open();
obj.write(str);
obj.close();
obj.body.style.color = KE_MENU_TEXT_COLOR;
obj.body.style.backgroundColor = KE_MENU_BG_COLOR;
obj.body.style.margin = 0;
obj.body.scroll = 'no';
}
function KindDrawTableSelected(i, j)
{
var text = i.toString(10) + ' by ' + j.toString(10) + ' Table';
document.getElementById('tableLocation').innerHTML = text;
var num = 10;
for (m = 1; m <= num; m++) {
for (n = 1; n <= num; n++) {
var obj = document.getElementById('kindTableTd' + m.toString(10) + '_' + n.toString(10) + '');
if (m <= i && n <= j) {
obj.style.backgroundColor = KE_MENU_SELECTED_COLOR;
} else {
obj.style.backgroundColor = '#FFFFFF';
}
}
}
}
function KindImageType(type)
{
if (type == 1) {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'block';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').value = 'http://';
} else {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'block';
}
KE_IMAGE_DOCUMENT.getElementById('imgPreview').innerHTML = " ";
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = 0;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = 0;
}
function KindImagePreview()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
if (type == 1) {
if (KE_BROWSER != 'IE') {
return false;
}
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
url = 'file:///' + file;
if (KindCheckImageFileType(url, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
var imgObj = KE_IMAGE_DOCUMENT.createElement("IMG");
imgObj.src = url;
var width = parseInt(imgObj.width);
var height = parseInt(imgObj.height);
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = width;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = height;
var rate = parseInt(width/height);
if (width >230 && height <= 230) {
width = 230;
height = parseInt(width/rate);
} else if (width <=230 && height > 230) {
height = 230;
width = parseInt(height*rate);
} else if (width >230 && height > 230) {
if (width >= height) {
width = 230;
height = parseInt(width/rate);
} else {
height = 230;
width = parseInt(height*rate);
}
}
imgObj.style.width = width;
imgObj.style.height = height;
var el = KE_IMAGE_DOCUMENT.getElementById('imgPreview');
if (el.hasChildNodes()) {
el.removeChild(el.childNodes[0]);
}
el.appendChild(imgObj);
return imgObj;
}
function KindDrawImageEnd()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
var width = KE_IMAGE_DOCUMENT.getElementById('imgWidth').value;
var height = KE_IMAGE_DOCUMENT.getElementById('imgHeight').value;
var border = KE_IMAGE_DOCUMENT.getElementById('imgBorder').value;
var title = KE_IMAGE_DOCUMENT.getElementById('imgTitle').value;
var align = KE_IMAGE_DOCUMENT.getElementById('imgAlign').value;
var hspace = KE_IMAGE_DOCUMENT.getElementById('imgHspace').value;
var vspace = KE_IMAGE_DOCUMENT.getElementById('imgVspace').value;
if (type == 1) {
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
if (KindCheckImageFileType(file, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
if (width.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_WIDTH']);
return false;
}
if (height.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HEIGHT']);
return false;
}
if (border.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_BORDER']);
return false;
}
if (hspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HSPACE']);
return false;
}
if (vspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_VSPACE']);
return false;
}
var fileName;
KindEditorForm.focus();
if (type == 1) {
fileName = KindGetFileName(file, "\\");
var fileExt = KindGetFileExt(fileName);
var dateObj = new Date();
var year = dateObj.getFullYear().toString(10);
var month = (dateObj.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = dateObj.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var ymd = year + month + day;
fileName = ymd + dateObj.getTime().toString(10) + '.' + fileExt;
KE_IMAGE_DOCUMENT.getElementById('fileName').value = fileName;
} else {
KindInsertImage(url, width, height, border, title, align, hspace, vspace);
}
}
function KindInsertImage(url, width, height, border, title, align, hspace, vspace)
{
var element = document.createElement("img");
element.src = url;
if (width > 0) {
element.style.width = width;
}
if (height > 0) {
element.style.height = height;
}
if (align != "") {
element.align = align;
}
if (hspace > 0) {
element.hspace = hspace;
}
if (vspace > 0) {
element.vspace = vspace;
}
element.border = border;
element.alt = KindHtmlentities(title);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
KindReloadIframe();
}
function KindGetFlashHtmlTag(url)
{
var str = '<embed src="'+url+'" type="application/x-shockwave-flash" quality="high"></embed>';
return str;
}
function KindFlashPreview()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
var el = KE_FLASH_DOCUMENT.getElementById('flashPreview');
el.innerHTML = KindGetFlashHtmlTag(url);
}
function KindDrawFlashEnd()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
obj.type = "application/x-shockwave-flash";
obj.quality = "high";
KindInsertItem(obj);
KindDisableMenu();
}
function KindGetMediaHtmlTag(cmd, url)
{
var str = '<embed src="'+url+'" type="';
if (cmd == "KE_REAL") {
str += 'audio/x-pn-realaudio-plugin';
} else {
str += 'video/x-ms-asf-plugin';
}
str += '" width="230" height="230" loop="true" autostart="true">';
return str;
}
function KindMediaPreview(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
var el = mediaDocument.getElementById(cmd+'preview');
el.innerHTML = KindGetMediaHtmlTag(cmd, url);
}
function KindDrawMediaEnd(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
if (cmd == 'KE_REAL') {
obj.type = 'audio/x-pn-realaudio-plugin';
} else {
obj.type = 'video/x-ms-asf-plugin';
}
obj.loop = 'true';
obj.autostart = 'true';
KindInsertItem(obj);
KindDisableMenu(cmd);
}
function KindDrawLinkEnd()
{
var range;
var url = KE_LINK_DOCUMENT.getElementById('hyperLink').value;
var target = KE_LINK_DOCUMENT.getElementById('hyperLinkTarget').value;
if (url.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
KindEditorForm.focus();
KindSelect();
var element;
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
var el = document.createElement("a");
el.href = url;
if (target) {
el.target = target;
}
KE_RANGE.item(0).applyElement(el);
} else if (KE_SELECTION.type.toLowerCase() == 'text') {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.parentElement();
if (target) {
element.target = target;
}
}
} else {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.startContainer.previousSibling;
element.target = target;
if (target) {
element.target = target;
}
}
KindDisableMenu();
}
function KindSelection()
{
if (KE_BROWSER == 'IE') {
KE_SELECTION = KE_EDITFORM_DOCUMENT.selection;
KE_RANGE = KE_SELECTION.createRange();
KE_RANGE_TEXT = KE_RANGE.text;
} else {
KE_SELECTION = document.getElementById("KindEditorForm").contentWindow.getSelection();
KE_RANGE = KE_SELECTION.getRangeAt(0);
KE_RANGE_TEXT = KE_RANGE.toString();
}
}
function KindSelect()
{
if (KE_BROWSER == 'IE') {
KE_RANGE.select();
}
}
function KindInsertItem(insertNode)
{
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
KE_RANGE.item(0).outerHTML = insertNode.outerHTML;
} else {
KE_RANGE.pasteHTML(insertNode.outerHTML);
}
} else {
KE_SELECTION.removeAllRanges();
KE_RANGE.deleteContents();
var startRangeNode = KE_RANGE.startContainer;
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
if (startRangeNode.nodeType == 3 && insertNode.nodeType == 3) {
startRangeNode.insertData(startRangeOffset, insertNode.nodeValue);
newRange.setEnd(startRangeNode, startRangeOffset + insertNode.length);
newRange.setStart(startRangeNode, startRangeOffset + insertNode.length);
} else {
var afterNode;
if (startRangeNode.nodeType == 3) {
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(insertNode, afterNode);
startRangeNode.insertBefore(beforeNode, insertNode);
startRangeNode.removeChild(textNode);
} else {
if (startRangeNode.tagName.toLowerCase() == 'html') {
startRangeNode = startRangeNode.childNodes[0].nextSibling;
afterNode = startRangeNode.childNodes[0];
} else {
afterNode = startRangeNode.childNodes[startRangeOffset];
}
startRangeNode.insertBefore(insertNode, afterNode);
}
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
}
KE_SELECTION.addRange(newRange);
}
}
function KindExecuteValue(cmd, value)
{
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, value);
}
function KindSimpleExecute(cmd)
{
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, null);
KindDisableMenu();
}
function KindExecute(cmd, value)
{
switch (cmd)
{
case 'KE_SOURCE':
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
document.getElementById("KindCodeForm").value = KindHtmlToXhtml(KE_EDITFORM_DOCUMENT.body.innerHTML);
document.getElementById("KindEditorIframe").style.display = 'none';
document.getElementById("KindEditTextarea").style.display = 'block';
KindDisableToolbar(true);
} else {
KE_EDITFORM_DOCUMENT.body.innerHTML = KindClearScriptTag(document.getElementById("KindCodeForm").value);
document.getElementById("KindEditTextarea").style.display = 'none';
document.getElementById("KindEditorIframe").style.display = 'block';
KindDisableToolbar(false);
}
KindDisableMenu();
break;
case 'KE_PRINT':
KindSimpleExecute('print');
break;
case 'KE_UNDO':
KindSimpleExecute('undo');
break;
case 'KE_REDO':
KindSimpleExecute('redo');
break;
case 'KE_CUT':
KindSimpleExecute('cut');
break;
case 'KE_COPY':
KindSimpleExecute('copy');
break;
case 'KE_PASTE':
KindSimpleExecute('paste');
break;
case 'KE_SELECTALL':
KindSimpleExecute('selectall');
break;
case 'KE_SUBSCRIPT':
KindSimpleExecute('subscript');
break;
case 'KE_SUPERSCRIPT':
KindSimpleExecute('superscript');
break;
case 'KE_BOLD':
KindSimpleExecute('bold');
break;
case 'KE_ITALIC':
KindSimpleExecute('italic');
break;
case 'KE_UNDERLINE':
KindSimpleExecute('underline');
break;
case 'KE_STRIKE':
KindSimpleExecute('strikethrough');
break;
case 'KE_JUSTIFYLEFT':
KindSimpleExecute('justifyleft');
break;
case 'KE_JUSTIFYCENTER':
KindSimpleExecute('justifycenter');
break;
case 'KE_JUSTIFYRIGHT':
KindSimpleExecute('justifyright');
break;
case 'KE_JUSTIFYFULL':
KindSimpleExecute('justifyfull');
break;
case 'KE_NUMBEREDLIST':
KindSimpleExecute('insertorderedlist');
break;
case 'KE_UNORDERLIST':
KindSimpleExecute('insertunorderedlist');
break;
case 'KE_INDENT':
KindSimpleExecute('indent');
break;
case 'KE_OUTDENT':
KindSimpleExecute('outdent');
break;
case 'KE_REMOVE':
KindSimpleExecute('removeformat');
break;
case 'KE_ZOOM':
KindDisplayMenu(cmd);
break;
case 'KE_ZOOM_END':
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.body.style.zoom = value;
KindDisableMenu();
break;
case 'KE_TITLE':
KindDisplayMenu(cmd);
break;
case 'KE_TITLE_END':
KindEditorForm.focus();
value = '<' + value + '>';
KindSelect();
KindExecuteValue('FormatBlock', value);
KindDisableMenu();
break;
case 'KE_FONTNAME':
KindDisplayMenu(cmd);
break;
case 'KE_FONTNAME_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('fontname', value);
KindDisableMenu();
break;
case 'KE_FONTSIZE':
KindDisplayMenu(cmd);
break;
case 'KE_FONTSIZE_END':
KindEditorForm.focus();
value = value.substr(0, 1);
KindSelect();
KindExecuteValue('fontsize', value);
KindDisableMenu();
break;
case 'KE_TEXTCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_TEXTCOLOR_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('ForeColor', value);
KindDisableMenu();
break;
case 'KE_BGCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_BGCOLOR_END':
KindEditorForm.focus();
if (KE_BROWSER == 'IE') {
KindSelect();
KindExecuteValue('BackColor', value);
} else {
var startRangeNode = KE_RANGE.startContainer;
if (startRangeNode.nodeType == 3) {
var parent = startRangeNode.parentNode;
var element = document.createElement("font");
element.style.backgroundColor = value;
element.appendChild(KE_RANGE.extractContents());
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
var afterNode;
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(element, afterNode);
startRangeNode.insertBefore(beforeNode, element);
startRangeNode.removeChild(textNode);
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
KE_SELECTION.addRange(newRange);
}
}
KindDisableMenu();
break;
case 'KE_ICON':
KindDisplayMenu(cmd);
break;
case 'KE_ICON_END':
KindEditorForm.focus();
var element = document.createElement("img");
element.src = value;
element.border = 0;
element.alt = "";
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_IMAGE':
KindDisplayMenu(cmd);
KindImageIframe.focus();
KE_IMAGE_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_FLASH':
KindDisplayMenu(cmd);
KindFlashIframe.focus();
KE_FLASH_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_MEDIA':
KindDisplayMenu(cmd);
KindMediaIframe.focus();
KE_MEDIA_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_REAL':
KindDisplayMenu(cmd);
KindRealIframe.focus();
KE_REAL_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_LINK':
KindDisplayMenu(cmd);
KindLinkIframe.focus();
KE_LINK_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_UNLINK':
KindSimpleExecute('unlink');
break;
case 'KE_SPECIALCHAR':
KindDisplayMenu(cmd);
break;
case 'KE_SPECIALCHAR_END':
KindEditorForm.focus();
KindSelect();
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_LAYER':
KindDisplayMenu(cmd);
break;
case 'KE_LAYER_END':
KindEditorForm.focus();
var element = document.createElement("div");
element.style.padding = "5px";
element.style.border = "1px solid #AAAAAA";
element.style.backgroundColor = value;
var childElement = document.createElement("div");
childElement.innerHTML = KE_LANG['INPUT_CONTENT'];
element.appendChild(childElement);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TABLE':
KindDisplayMenu(cmd);
break;
case 'KE_TABLE_END':
KindEditorForm.focus();
var location = value.split(',');
var element = document.createElement("table");
element.cellPadding = 0;
element.cellSpacing = 0;
element.border = 1;
element.style.width = "100px";
element.style.height = "100px";
for (var i = 0; i < location[0]; i++) {
var rowElement = element.insertRow(i);
for (var j = 0; j < location[1]; j++) {
var cellElement = rowElement.insertCell(j);
cellElement.innerHTML = " ";
}
}
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_HR':
KindDisplayMenu(cmd);
break;
case 'KE_HR_END':
KindEditorForm.focus();
var element = document.createElement("hr");
element.width = "100%";
element.color = value;
element.size = 1;
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_DATE':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var year = date.getFullYear().toString(10);
var month = (date.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = date.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var value = year + '-' + month + '-' + day;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TIME':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var hour = date.getHours().toString(10);
hour = hour.length < 2 ? '0' + hour : hour;
var minute = date.getMinutes().toString(10);
minute = minute.length < 2 ? '0' + minute : minute;
var second = date.getSeconds().toString(10);
second = second.length < 2 ? '0' + second : second;
var value = hour + ':' + minute + ':' + second;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_PREVIEW':
eval(KE_OBJ_NAME).data();
var newWin = window.open('', 'kindPreview','width=800,height=600,left=30,top=30,resizable=yes,scrollbars=yes');
KindWriteFullHtml(newWin.document, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
KindDisableMenu();
break;
case 'KE_ABOUT':
KindDisplayMenu(cmd);
break;
default:
break;
}
}
function KindDisableToolbar(flag)
{
if (flag == true) {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'design.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
if (KE_TOOLBAR_ICON[i][0] == 'KE_SOURCE' || KE_TOOLBAR_ICON[i][0] == 'KE_PREVIEW' || KE_TOOLBAR_ICON[i][0] == 'KE_ABOUT') {
continue;
}
el.style.visibility = 'hidden';
}
} else {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'source.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
el.style.visibility = 'visible';
KE_EDITFORM_DOCUMENT.designMode = 'On';
}
}
}
function KindCreateIcon(icon)
{
var str = '<img id="'+ icon[0] +'" src="' + KE_SKIN_PATH + icon[1] + '" alt="' + icon[2] + '" title="' + icon[2] +
'" align="absmiddle" style="border:1px solid ' + KE_TOOLBAR_BG_COLOR +';cursor:pointer;height:20px;';
str += '" onclick="javascript:KindExecute(\''+ icon[0] +'\');" '+
'onmouseover="javascript:this.style.border=\'1px solid ' + KE_MENU_BORDER_COLOR + '\';" ' +
'onmouseout="javascript:this.style.border=\'1px solid ' + KE_TOOLBAR_BG_COLOR + '\';" ';
str += '>';
return str;
}
function KindCreateToolbar()
{
var htmlData = '<table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
if (KE_EDITOR_TYPE == 'full') {
for (i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_TOP_TOOLBAR_ICON[i]) + '</td>';
}
htmlData += '</tr></table><table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
for (i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_BOTTOM_TOOLBAR_ICON[i]) + '</td>';
}
} else {
for (i = 0; i < KE_SIMPLE_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_SIMPLE_TOOLBAR_ICON[i]) + '</td>';
}
}
htmlData += '</tr></table>';
return htmlData;
}
function KindWriteFullHtml(documentObj, content)
{
var editHtmlData = '';
editHtmlData += '<html>\r\n<head>\r\n<title>KindEditor</title>\r\n';
editHtmlData += '<link href="'+KE_CSS_PATH+'" rel="stylesheet" type="text/css">\r\n</head>\r\n<body>\r\n';
editHtmlData += content;
editHtmlData += '\r\n</body>\r\n</html>\r\n';
documentObj.open();
documentObj.write(editHtmlData);
documentObj.close();
}
function KindEditor(objName)
{
this.objName = objName;
this.hiddenName = objName;
this.siteDomain;
this.editorType;
this.safeMode;
this.uploadMode;
this.editorWidth;
this.editorHeight;
this.skinPath;
this.iconPath;
this.imageAttachPath;
this.imageUploadCgi;
this.cssPath;
this.menuBorderColor;
this.menuBgColor;
this.menuTextColor;
this.menuSelectedColor;
this.toolbarBorderColor;
this.toolbarBgColor;
this.formBorderColor;
this.formBgColor;
this.buttonColor;
this.init = function()
{
if (this.siteDomain) KE_SITE_DOMAIN = this.siteDomain;
if (this.editorType) KE_EDITOR_TYPE = this.editorType.toLowerCase();
if (this.safeMode) KE_SAFE_MODE = this.safeMode;
if (this.uploadMode) KE_UPLOAD_MODE = this.uploadMode;
if (this.editorWidth) KE_WIDTH = this.editorWidth;
if (this.editorHeight) KE_HEIGHT = this.editorHeight;
if (this.skinPath) KE_SKIN_PATH = this.skinPath;
if (this.iconPath) KE_ICON_PATH = this.iconPath;
if (this.imageAttachPath) KE_IMAGE_ATTACH_PATH = this.imageAttachPath;
if (this.imageUploadCgi) KE_IMAGE_UPLOAD_CGI = this.imageUploadCgi;
if (this.cssPath) KE_CSS_PATH = this.cssPath;
if (this.menuBorderColor) KE_MENU_BORDER_COLOR = this.menuBorderColor;
if (this.menuBgColor) KE_MENU_BG_COLOR = this.menuBgColor;
if (this.menuTextColor) KE_MENU_TEXT_COLOR = this.menuTextColor;
if (this.menuSelectedColor) KE_MENU_SELECTED_COLOR = this.menuSelectedColor;
if (this.toolbarBorderColor) KE_TOOLBAR_BORDER_COLOR = this.toolbarBorderColor;
if (this.toolbarBgColor) KE_TOOLBAR_BG_COLOR = this.toolbarBgColor;
if (this.formBorderColor) KE_FORM_BORDER_COLOR = this.formBorderColor;
if (this.formBgColor) KE_FORM_BG_COLOR = this.formBgColor;
if (this.buttonColor) KE_BUTTON_COLOR = this.buttonColor;
KE_OBJ_NAME = this.objName;
KE_BROWSER = KindGetBrowser();
KE_TOOLBAR_ICON = Array();
for (var i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_TOP_TOOLBAR_ICON[i]);
}
for (var i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_BOTTOM_TOOLBAR_ICON[i]);
}
}
this.show = function()
{
this.init();
var widthStyle = 'width:' + KE_WIDTH + ';';
var widthArr = KE_WIDTH.match(/(\d+)([px%]{1,2})/);
var iframeWidthStyle = 'width:' + (parseInt(widthArr[1]) - 2).toString(10) + widthArr[2] + ';';
var heightStyle = 'height:' + KE_HEIGHT + ';';
var heightArr = KE_HEIGHT.match(/(\d+)([px%]{1,2})/);
var iframeHeightStyle = 'height:' + (parseInt(heightArr[1]) - 3).toString(10) + heightArr[2] + ';';
if (KE_BROWSER == '') {
var htmlData = '<div id="KindEditTextarea" style="' + widthStyle + heightStyle + '">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + widthStyle + heightStyle +
'padding:0;margin:0;border:1px solid '+ KE_FORM_BORDER_COLOR +
';font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';">' + document.getElementsByName(this.hiddenName)[0].value + '</textarea></div>';
document.open();
document.write(htmlData);
document.close();
return;
}
var htmlData = '<div style="font-family:'+KE_FONT_FAMILY+';">';
htmlData += '<div style="'+widthStyle+';border:1px solid ' + KE_TOOLBAR_BORDER_COLOR + ';background-color:'+ KE_TOOLBAR_BG_COLOR +'">';
htmlData += KindCreateToolbar();
htmlData += '</div><div id="KindEditorIframe" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';border-top:0;">' +
'<iframe name="KindEditorForm" id="KindEditorForm" frameborder="0" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;"></iframe></div>';
if (KE_EDITOR_TYPE == 'full') {
htmlData += '<div id="KindEditTextarea" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';background-color:'+
KE_FORM_BG_COLOR +';border-top:0;display:none;">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';" onclick="javascirit:parent.KindDisableMenu();"></textarea></div>';
}
htmlData += '</div>';
for (var i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
if (KE_POPUP_MENU_TABLE[i] == 'KE_IMAGE') {
htmlData += '<span id="InsertIframe">';
}
htmlData += KindPopupMenu(KE_POPUP_MENU_TABLE[i]);
if (KE_POPUP_MENU_TABLE[i] == 'KE_REAL') {
htmlData += '</span>';
}
}
document.open();
document.write(htmlData);
document.close();
if (KE_BROWSER == 'IE') {
KE_EDITFORM_DOCUMENT = document.frames("KindEditorForm").document;
} else {
KE_EDITFORM_DOCUMENT = document.getElementById('KindEditorForm').contentDocument;
}
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
KindDrawIframe('KE_LINK');
KE_EDITFORM_DOCUMENT.designMode = 'On';
KindWriteFullHtml(KE_EDITFORM_DOCUMENT, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
var el = KE_EDITFORM_DOCUMENT.body;
if (KE_EDITFORM_DOCUMENT.addEventListener){
KE_EDITFORM_DOCUMENT.addEventListener('click', KindDisableMenu, false);
} else if (el.attachEvent){
el.attachEvent('onclick', KindDisableMenu);
}
}
this.data = function()
{
var htmlResult;
if (KE_BROWSER == '') {
htmlResult = document.getElementById("KindCodeForm").value;
} else {
if (KE_EDITOR_TYPE == 'full') {
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
} else {
htmlResult = document.getElementById("KindCodeForm").value;
}
} else {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
}
}
KindDisableMenu();
htmlResult = KindHtmlToXhtml(htmlResult);
htmlResult = KindClearScriptTag(htmlResult);
document.getElementsByName(this.hiddenName)[0].value = htmlResult;
return htmlResult;
}
}
| JavaScript |
/*
Textile Editor v0.2
created by: dave olsen, wvu web services
created on: march 17, 2007
project page: slateinfo.blogs.wvu.edu
inspired by:
- Patrick Woods, http://www.hakjoon.com/code/38/textile-quicktags-redirect &
- Alex King, http://alexking.org/projects/js-quicktags
features:
- supports: IE7, FF2, Safari2
- ability to use "simple" vs. "extended" editor
- supports all block elements in textile except footnote
- supports all block modifier elements in textile
- supports simple ordered and unordered lists
- supports most of the phrase modifiers, very easy to add the missing ones
- supports multiple-paragraph modification
- can have multiple "editors" on one page, access key use in this environment is flaky
- access key support
- select text to add and remove tags, selection stays highlighted
- seamlessly change between tags and modifiers
- doesn't need to be in the body onload tag
- can supply your own, custom IDs for the editor to be drawn around
todo:
- a clean way of providing image and link inserts
- get the selection to properly show in IE
more on textile:
- Textism, http://www.textism.com/tools/textile/index.php
- Textile Reference, http://hobix.com/textile/
*/
// Define Button Object
function TextileEditorButton(id, display, tagStart, tagEnd, access, title, sve, open) {
this.id = id; // used to name the toolbar button
this.display = display; // label on button
this.tagStart = tagStart; // open tag
this.tagEnd = tagEnd; // close tag
this.access = access; // set to -1 if tag does not need to be closed
this.title = title; // sets the title attribute of the button to give 'tool tips'
this.sve = sve; // sve = simple vs. extended. add an 's' to make it show up in the simple toolbar
this.open = open; // set to -1 if tag does not need to be closed
this.standard = true; // this is a standard button
}
function TextileEditorButtonSeparator(sve) {
this.separator = true;
this.sve = sve;
}
var TextileEditor = Class.create();
TextileEditor.buttons = new Array();
TextileEditor.Methods = {
// class methods
// create the toolbar (edToolbar)
initialize: function(canvas, view) {
var toolbar = document.createElement("div");
toolbar.id = "textile-toolbar-" + canvas;
toolbar.className = 'textile-toolbar';
this.canvas = document.getElementById(canvas);
this.canvas.parentNode.insertBefore(toolbar, this.canvas);
this.openTags = new Array();
// Create the local Button array by assigning theButtons array to edButtons
var edButtons = new Array();
edButtons = this.buttons;
var standardButtons = new Array();
for(var i = 0; i < edButtons.length; i++) {
var thisButton = this.prepareButton(edButtons[i]);
if (view == 's') {
if (edButtons[i].sve == 's') {
toolbar.appendChild(thisButton);
standardButtons.push(thisButton);
}
} else {
if (typeof thisButton == 'string') {
toolbar.innerHTML += thisButton;
} else {
toolbar.appendChild(thisButton);
standardButtons.push(thisButton);
}
}
} // end for
var te = this;
$A(toolbar.getElementsByTagName('button')).each(function(button) {
if (!button.onclick) {
button.onclick = function() { te.insertTag(button); return false; }
} // end if
button.tagStart = button.getAttribute('tagStart');
button.tagEnd = button.getAttribute('tagEnd');
button.open = button.getAttribute('open');
button.textile_editor = te;
button.canvas = te.canvas;
});
}, // end initialize
// draw individual buttons (edShowButton)
prepareButton: function(button) {
if (button.separator) {
var theButton = document.createElement('span');
theButton.className = 'ed_sep';
return theButton;
}
if (button.standard) {
var theButton = document.createElement("button");
theButton.id = button.id;
theButton.setAttribute('class', 'standard');
theButton.setAttribute('tagStart', button.tagStart);
theButton.setAttribute('tagEnd', button.tagEnd);
theButton.setAttribute('open', button.open);
var img = document.createElement('img');
img.src = '/images/textile-editor/' + button.display;
theButton.appendChild(img);
} else {
return button;
} // end if !custom
theButton.accessKey = button.access;
theButton.title = button.title;
return theButton;
}, // end prepareButton
// if clicked, no selected text, tag not open highlight button
// (edAddTag)
addTag: function(button) {
if (button.tagEnd != '') {
this.openTags[this.openTags.length] = button;
//var el = document.getElementById(button.id);
//el.className = 'selected';
button.className = 'selected';
}
}, // end addTag
// if clicked, no selected text, tag open lowlight button
// (edRemoveTag)
removeTag: function(button) {
for (i = 0; i < this.openTags.length; i++) {
if (this.openTags[i] == button) {
this.openTags.splice(button, 1);
//var el = document.getElementById(button.id);
//el.className = 'unselected';
button.className = 'unselected';
}
}
}, // end removeTag
// see if there are open tags. for the remove tag bit...
// (edCheckOpenTags)
checkOpenTags: function(button) {
var tag = 0;
for (i = 0; i < this.openTags.length; i++) {
if (this.openTags[i] == button) {
tag++;
}
}
if (tag > 0) {
return true; // tag found
}
else {
return false; // tag not found
}
}, // end checkOpenTags
// insert the tag. this is the bulk of the code.
// (edInsertTag)
insertTag: function(button, tagStart, tagEnd) {
var myField = button.canvas;
myField.focus();
if (tagStart) {
button.tagStart = tagStart;
button.tagEnd = tagEnd ? tagEnd : '\n';
}
var textSelected = false;
var finalText = '';
var FF = false;
// grab the text that's going to be manipulated, by browser
if (document.selection) { // IE support
sel = document.selection.createRange();
// set-up the text vars
var beginningText = '';
var followupText = '';
var selectedText = sel.text;
// check if text has been selected
if (sel.text.length > 0) {
textSelected = true;
}
// set-up newline regex's so we can swap tags across multiple paragraphs
var newlineReplaceRegexClean = /\r\n\s\n/g;
var newlineReplaceRegexDirty = '\\r\\n\\s\\n';
var newlineReplaceClean = '\r\n\n';
}
else if (myField.selectionStart || myField.selectionStart == '0') { // MOZ/FF/NS/S support
// figure out cursor and selection positions
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
var cursorPos = endPos;
var scrollTop = myField.scrollTop;
FF = true; // note that is is a FF/MOZ/NS/S browser
// set-up the text vars
var beginningText = myField.value.substring(0, startPos);
var followupText = myField.value.substring(endPos, myField.value.length);
// check if text has been selected
if (startPos != endPos) {
textSelected = true;
var selectedText = myField.value.substring(startPos, endPos);
}
// set-up newline regex's so we can swap tags across multiple paragraphs
var newlineReplaceRegexClean = /\n\n/g;
var newlineReplaceRegexDirty = '\\n\\n';
var newlineReplaceClean = '\n\n';
}
// if there is text that has been highlighted...
if (textSelected) {
// set-up some defaults for how to handle bad new line characters
var newlineStart = '';
var newlineStartPos = 0;
var newlineEnd = '';
var newlineEndPos = 0;
var newlineFollowup = '';
// set-up some defaults for how to handle placing the beginning and end of selection
var posDiffPos = 0;
var posDiffNeg = 0;
var mplier = 1;
// remove newline from the beginning of the selectedText.
if (selectedText.match(/^\n/)) {
selectedText = selectedText.replace(/^\n/,'');
newlineStart = '\n';
newlineStartpos = 1;
}
// remove newline from the end of the selectedText.
if (selectedText.match(/\n$/g)) {
selectedText = selectedText.replace(/\n$/g,'');
newlineEnd = '\n';
newlineEndPos = 1;
}
// no clue, i'm sure it made sense at the time i wrote it
if (followupText.match(/^\n/)) {
newlineFollowup = '';
}
else {
newlineFollowup = '\n\n';
}
// first off let's check if the user is trying to mess with lists
if ((button.tagStart == ' * ') || (button.tagStart == ' # ')) {
listItems = 0; // sets up a default to be able to properly manipulate final selection
// set-up all of the regex's
re_start = new RegExp('^ (\\*|\\#) ','g');
if (button.tagStart == ' # ') {
re_tag = new RegExp(' \\# ','g'); // because of JS regex stupidity i need an if/else to properly set it up, could have done it with a regex replace though
}
else {
re_tag = new RegExp(' \\* ','g');
}
re_replace = new RegExp(' (\\*|\\#) ','g');
// try to remove bullets in text copied from ms word **Mac Only!**
re_word_bullet_m_s = new RegExp('• ','g'); // mac/safari
re_word_bullet_m_f = new RegExp('∑ ','g'); // mac/firefox
selectedText = selectedText.replace(re_word_bullet_m_s,'').replace(re_word_bullet_m_f,'');
// if the selected text starts with one of the tags we're working with...
if (selectedText.match(re_start)) {
// if tag that begins the selection matches the one clicked, remove them all
if (selectedText.match(re_tag)) {
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_replace,'')
+ newlineEnd
+ followupText;
if (matches = selectedText.match(/ (\*|\#) /g)) {
listItems = matches.length;
}
posDiffNeg = listItems*3; // how many list items were there because that's 3 spaces to remove from final selection
}
// else replace the current tag type with the selected tag type
else {
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_replace,button.tagStart)
+ newlineEnd
+ followupText;
}
}
// else try to create the list type
// NOTE: the items in a list will only be replaced if a newline starts with some character, not a space
else {
finalText = beginningText
+ newlineStart
+ button.tagStart
+ selectedText.replace(newlineReplaceRegexClean,newlineReplaceClean + button.tagStart).replace(/\n(\S)/g,'\n' + button.tagStart + '$1')
+ newlineEnd
+ followupText;
if (matches = selectedText.match(/\n(\S)/g)) {
listItems = matches.length;
}
posDiffPos = 3 + listItems*3;
}
}
// now lets look and see if the user is trying to muck with a block or block modifier
else if (button.tagStart.match(/^(h1|h2|h3|h4|h5|h6|bq|p|\>|\<\>|\<|\=|\(|\))/g)) {
var insertTag = '';
var insertModifier = '';
var tagPartBlock = '';
var tagPartModifier = '';
var tagPartModifierOrig = ''; // ugly hack but it's late
var drawSwitch = '';
var captureIndentStart = false;
var captureListStart = false;
var periodAddition = '\\. ';
var periodAdditionClean = '. ';
var listItemsAddition = 0;
var re_list_items = new RegExp('(\\*+|\\#+)','g'); // need this regex later on when checking indentation of lists
var re_block_modifier = new RegExp('^(h1|h2|h3|h4|h5|h6|bq|p| [\\*]{1,} | [\\#]{1,} |)(\\>|\\<\\>|\\<|\\=|[\\(]{1,}|[\\)]{1,6}|)','g');
if (tagPartMatches = re_block_modifier.exec(selectedText)) {
tagPartBlock = tagPartMatches[1];
tagPartModifier = tagPartMatches[2];
tagPartModifierOrig = tagPartMatches[2];
tagPartModifierOrig = tagPartModifierOrig.replace(/\(/g,"\\(");
}
// if tag already up is the same as the tag provided replace the whole tag
if (tagPartBlock == button.tagStart) {
insertTag = tagPartBlock + tagPartModifierOrig; // use Orig because it's escaped for regex
drawSwitch = 0;
}
// else if let's check to add/remove block modifier
else if ((tagPartModifier == button.tagStart) || (newm = tagPartModifier.match(/[\(]{2,}/g))) {
if ((button.tagStart == '(') || (button.tagStart == ')')) {
var indentLength = tagPartModifier.length;
if (button.tagStart == '(') {
indentLength = indentLength + 1;
}
else {
indentLength = indentLength - 1;
}
for (var i = 0; i < indentLength; i++) {
insertModifier = insertModifier + '(';
}
insertTag = tagPartBlock + insertModifier;
}
else {
if (button.tagStart == tagPartModifier) {
insertTag = tagPartBlock;
} // going to rely on the default empty insertModifier
else {
if (button.tagStart.match(/(\>|\<\>|\<|\=)/g)) {
insertTag = tagPartBlock + button.tagStart;
}
else {
insertTag = button.tagStart + tagPartModifier;
}
}
}
drawSwitch = 1;
}
// indentation of list items
else if (listPartMatches = re_list_items.exec(tagPartBlock)) {
var listTypeMatch = listPartMatches[1];
var indentLength = tagPartBlock.length - 2;
var listInsert = '';
if (button.tagStart == '(') {
indentLength = indentLength + 1;
}
else {
indentLength = indentLength - 1;
}
if (listTypeMatch.match(/[\*]{1,}/g)) {
var listType = '*';
var listReplace = '\\*';
}
else {
var listType = '#';
var listReplace = '\\#';
}
for (var i = 0; i < indentLength; i++) {
listInsert = listInsert + listType;
}
if (listInsert != '') {
insertTag = ' ' + listInsert + ' ';
}
else {
insertTag = '';
}
tagPartBlock = tagPartBlock.replace(/(\*|\#)/g,listReplace);
drawSwitch = 1;
captureListStart = true;
periodAddition = '';
periodAdditionClean = '';
if (matches = selectedText.match(/\n\s/g)) {
listItemsAddition = matches.length;
}
}
// must be a block modification e.g. p>. to p<.
else {
// if this is a block modification/addition
if (button.tagStart.match(/(h1|h2|h3|h4|h5|h6|bq|p)/g)) {
if (tagPartBlock == '') {
drawSwitch = 2;
}
else {
drawSwitch = 1;
}
insertTag = button.tagStart + tagPartModifier;
}
// else this is a modifier modification/addition
else {
if ((tagPartModifier == '') && (tagPartBlock != '')) {
drawSwitch = 1;
}
else if (tagPartModifier == '') {
drawSwitch = 2;
}
else {
drawSwitch = 1;
}
// if no tag part block but a modifier we need at least the p tag
if (tagPartBlock == '') {
tagPartBlock = 'p';
}
//make sure to swap out outdent
if (button.tagStart == ')') {
tagPartModifier = '';
}
else {
tagPartModifier = button.tagStart;
captureIndentStart = true; // ugly hack to fix issue with proper selection handling
}
insertTag = tagPartBlock + tagPartModifier;
}
}
mplier = 0;
if (captureListStart || (tagPartModifier.match(/[\(\)]{1,}/g))) {
re_start = new RegExp(insertTag.escape + periodAddition,'g'); // for tags that mimic regex properties, parens + list tags
}
else {
re_start = new RegExp(insertTag + periodAddition,'g'); // for tags that don't, why i can't just escape everything i have no clue
}
re_old = new RegExp(tagPartBlock + tagPartModifierOrig + periodAddition,'g');
re_middle = new RegExp(newlineReplaceRegexDirty + insertTag.escape + periodAddition.escape,'g');
re_tag = new RegExp(insertTag.escape + periodAddition.escape,'g');
// *************************************************************************************************************************
// this is where everything gets swapped around or inserted, bullets and single options have their own if/else statements
// *************************************************************************************************************************
if ((drawSwitch == 0) || (drawSwitch == 1)) {
if (drawSwitch == 0) { // completely removing a tag
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_start,'').replace(re_middle,newlineReplaceClean)
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffNeg = insertTag.length + 2 + (mplier*4);
}
else { // modifying a tag, though we do delete bullets here
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_old,insertTag + periodAdditionClean)
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
// figure out the length of various elements to modify the selection position
if (captureIndentStart) { // need to double-check that this wasn't the first indent
tagPreviousLength = tagPartBlock.length;
tagCurrentLength = insertTag.length;
}
else if (captureListStart) { // if this is a list we're manipulating
if (button.tagStart == '(') { // if indenting
tagPreviousLength = listTypeMatch.length + 2;
tagCurrentLength = insertTag.length + listItemsAddition;
}
else if (insertTag.match(/(\*|\#)/g)) { // if removing but still has bullets
tagPreviousLength = insertTag.length + listItemsAddition;
tagCurrentLength = listTypeMatch.length;
}
else { // if removing last bullet
tagPreviousLength = insertTag.length + listItemsAddition;
tagCurrentLength = listTypeMatch.length - (3*listItemsAddition) - 1;
}
}
else { // everything else
tagPreviousLength = tagPartBlock.length + tagPartModifier.length;
tagCurrentLength = insertTag.length;
}
if (tagCurrentLength > tagPreviousLength) {
posDiffPos = (tagCurrentLength - tagPreviousLength) + (mplier*(tagCurrentLength - tagPreviousLength));
}
else {
posDiffNeg = (tagPreviousLength - tagCurrentLength) + (mplier*(tagPreviousLength - tagCurrentLength));
}
}
}
else { // for adding tags other then bullets (have their own statement)
finalText = beginningText
+ newlineStart
+ insertTag + '. '
+ selectedText.replace(newlineReplaceRegexClean,button.tagEnd + '\n' + insertTag + '. ')
+ newlineFollowup
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffPos = insertTag.length + 2 + (mplier*4);
}
}
// swap in and out the simple tags around a selection like bold
else {
mplier = 1; // the multiplier for the tag length
re_start = new RegExp('^\\' + button.tagStart,'g');
re_end = new RegExp('\\' + button.tagEnd + '$','g');
re_middle = new RegExp('\\' + button.tagEnd + newlineReplaceRegexDirty + '\\' + button.tagStart,'g');
if (selectedText.match(re_start) && selectedText.match(re_end)) {
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_start,'').replace(re_end,'').replace(re_middle,newlineReplaceClean)
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffNeg = button.tagStart.length*mplier + button.tagEnd.length*mplier;
}
else {
finalText = beginningText
+ newlineStart
+ button.tagStart
+ selectedText.replace(newlineReplaceRegexClean,button.tagEnd + newlineReplaceClean + button.tagStart)
+ button.tagEnd
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffPos = (button.tagStart.length*mplier) + (button.tagEnd.length*mplier);
}
}
cursorPos += button.tagStart.length + button.tagEnd.length;
}
// just swap in and out single values, e.g. someone clicks b they'll get a *
else {
var buttonStart = '';
var buttonEnd = '';
var re_p = new RegExp('(\\<|\\>|\\=|\\<\\>|\\(|\\))','g');
var re_h = new RegExp('^(h1|h2|h3|h4|h5|h6|p|bq)','g');
if (!this.checkOpenTags(button) || button.tagEnd == '') { // opening tag
if (button.tagStart.match(re_h)) {
buttonStart = button.tagStart + '. ';
}
else {
buttonStart = button.tagStart;
}
if (button.tagStart.match(re_p)) { // make sure that invoking block modifiers don't do anything
finalText = beginningText
+ followupText;
cursorPos = startPos;
}
else {
finalText = beginningText
+ buttonStart
+ followupText;
this.addTag(button);
cursorPos = startPos + buttonStart.length;
}
}
else { // closing tag
if (button.tagStart.match(re_p)) {
buttonEnd = '\n\n';
}
else if (button.tagStart.match(re_h)) {
buttonEnd = '\n\n';
}
else {
buttonEnd = button.tagEnd
}
finalText = beginningText
+ button.tagEnd
+ followupText;
this.removeTag(button);
cursorPos = startPos + button.tagEnd.length;
}
}
// set the appropriate DOM value with the final text
if (FF == true) {
myField.value = finalText;
myField.scrollTop = scrollTop;
}
else {
sel.text = finalText;
}
// build up the selection capture, doesn't work in IE
if (textSelected) {
myField.selectionStart = startPos + newlineStartPos;
myField.selectionEnd = endPos + posDiffPos - posDiffNeg - newlineEndPos;
//alert('s: ' + myField.selectionStart + ' e: ' + myField.selectionEnd + ' sp: ' + startPos + ' ep: ' + endPos + ' pdp: ' + posDiffPos + ' pdn: ' + posDiffNeg)
}
else {
myField.selectionStart = cursorPos;
myField.selectionEnd = cursorPos;
}
} // end insertTag
}; // end class
// add class methods
Object.extend(TextileEditor, TextileEditor.Methods);
document.write('<script src="/javascripts/textile-editor-config.js" type="text/javascript"></script>'); | JavaScript |
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
| JavaScript |
/**
* WYSIWYG HTML Editor for Internet
*
* @author Roddy <luolonghao@gmail.com>
* @version 2.5.3
*/
var KE_VERSION = "2.5.4";
var KE_EDITOR_TYPE = "full"; //full or simple
var KE_SAFE_MODE = false; // true or false
var KE_UPLOAD_MODE = true; // true or false
var KE_FONT_FAMILY = "Courier New";
var KE_WIDTH = "700px";
var KE_HEIGHT = "400px";
var KE_SITE_DOMAIN = "";
var KE_SKIN_PATH = "./skins/default/";
var KE_ICON_PATH = "./icons/";
var KE_IMAGE_ATTACH_PATH = "./attached/";
var KE_IMAGE_UPLOAD_CGI = "./upload_cgi/upload.php";
var KE_CSS_PATH = "/editor/common.css";
var KE_MENU_BORDER_COLOR = '#AAAAAA';
var KE_MENU_BG_COLOR = '#EFEFEF';
var KE_MENU_TEXT_COLOR = '#222222';
var KE_MENU_SELECTED_COLOR = '#CCCCCC';
var KE_TOOLBAR_BORDER_COLOR = '#DDDDDD';
var KE_TOOLBAR_BG_COLOR = '#EFEFEF';
var KE_FORM_BORDER_COLOR = '#DDDDDD';
var KE_FORM_BG_COLOR = '#FFFFFF';
var KE_BUTTON_COLOR = '#AAAAAA';
var KE_LANG = {
INPUT_URL : "请输入正确的URL地址。",
SELECT_IMAGE : "请选择图片。",
INVALID_IMAGE : "只能选择GIF,JPG,PNG,BMP格式的图片,请重新选择。",
INVALID_FLASH : "只能选择SWF格式的文件,请重新选择。",
INVALID_MEDIA : "只能选择MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF格式的文件,请重新选择。",
INVALID_REAL : "只能选择RM,RMVB格式的文件,请重新选择。",
INVALID_WIDTH : "宽度不是数字,请重新输入。",
INVALID_HEIGHT : "高度不是数字,请重新输入。",
INVALID_BORDER : "边框不是数字,请重新输入。",
INVALID_HSPACE : "横隔不是数字,请重新输入。",
INVALID_VSPACE : "竖隔不是数字,请重新输入。",
INPUT_CONTENT : "请输入内容",
TITLE : "描述",
WIDTH : "宽",
HEIGHT : "高",
BORDER : "边",
ALIGN : "对齐方式",
HSPACE : "横隔",
VSPACE : "竖隔",
CONFIRM : "确定",
CANCEL : "取消",
PREVIEW : "预览",
LISTENING : "试听",
LOCAL : "本地",
REMOTE : "远程",
NEW_WINDOW : "新窗口",
CURRENT_WINDOW : "当前窗口",
TARGET : "目标",
ABOUT : "访问技术支持网站",
SUBJECT : "标题"
}
var KE_FONT_NAME = Array(
Array('SimSun', '宋体'),
Array('SimHei', '黑体'),
Array('FangSong_GB2312', '仿宋体'),
Array('KaiTi_GB2312', '楷体'),
Array('NSimSun', '新宋体'),
Array('Arial', 'Arial'),
Array('Arial Black', 'Arial Black'),
Array('Times New Roman', 'Times New Roman'),
Array('Courier New', 'Courier New'),
Array('Tahoma', 'Tahoma'),
Array('Verdana', 'Verdana'),
Array('GulimChe', 'GulimChe'),
Array('MS Gothic', 'MS Gothic')
);
var KE_SPECIAL_CHARACTER = Array(
'§','№','☆','★','○','●','◎','◇','◆','□','℃','‰','■','△','▲','※',
'→','←','↑','↓','〓','¤','°','#','&','@','\','︿','_',' ̄','―','α',
'β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ',
'σ','τ','υ','φ','χ','ψ','ω','≈','≡','≠','=','≤','≥','<','>','≮',
'≯','∷','±','+','-','×','÷','/','∫','∮','∝','∞','∧','∨','∑','∏',
'∪','∩','∈','∵','∴','⊥','∥','∠','⌒','⊙','≌','∽','〖','〗',
'【','】','(',')','[',']'
);
var KE_TOP_TOOLBAR_ICON = Array(
Array('KE_SOURCE', 'source.gif', '视图转换'),
Array('KE_PREVIEW', 'preview.gif', '预览'),
Array('KE_ZOOM', 'zoom.gif', '显示比例'),
Array('KE_PRINT', 'print.gif', '打印'),
Array('KE_UNDO', 'undo.gif', '回退'),
Array('KE_REDO', 'redo.gif', '前进'),
Array('KE_CUT', 'cut.gif', '剪切'),
Array('KE_COPY', 'copy.gif', '复制'),
Array('KE_PASTE', 'paste.gif', '粘贴'),
Array('KE_SELECTALL', 'selectall.gif', '全选'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_JUSTIFYFULL', 'justifyfull.gif', '两端对齐'),
Array('KE_NUMBEREDLIST', 'numberedlist.gif', '编号'),
Array('KE_UNORDERLIST', 'unorderedlist.gif', '项目符号'),
Array('KE_INDENT', 'indent.gif', '减少缩进'),
Array('KE_OUTDENT', 'outdent.gif', '增加缩进'),
Array('KE_SUBSCRIPT', 'subscript.gif', '下标'),
Array('KE_SUPERSCRIPT', 'superscript.gif', '上标'),
Array('KE_DATE', 'date.gif', '日期'),
Array('KE_TIME', 'time.gif', '时间')
);
var KE_BOTTOM_TOOLBAR_ICON = Array(
Array('KE_TITLE', 'title.gif', '标题'),
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_STRIKE', 'strikethrough.gif', '删除线'),
Array('KE_REMOVE', 'removeformat.gif', '删除格式'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_FLASH', 'flash.gif', 'Flash'),
Array('KE_MEDIA', 'media.gif', 'Windows Media Player'),
Array('KE_REAL', 'real.gif', 'Real Player'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_TABLE', 'table.gif', '表格'),
Array('KE_SPECIALCHAR', 'specialchar.gif', '特殊字符'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_UNLINK', 'unlink.gif', '删除超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_SIMPLE_TOOLBAR_ICON = Array(
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_TITLE_TABLE = Array(
Array('H1', KE_LANG['SUBJECT'] + ' 1'),
Array('H2', KE_LANG['SUBJECT'] + ' 2'),
Array('H3', KE_LANG['SUBJECT'] + ' 3'),
Array('H4', KE_LANG['SUBJECT'] + ' 4'),
Array('H5', KE_LANG['SUBJECT'] + ' 5'),
Array('H6', KE_LANG['SUBJECT'] + ' 6')
);
var KE_ZOOM_TABLE = Array('250%', '200%', '150%', '120%', '100%', '80%', '50%');
var KE_FONT_SIZE = Array(
Array(1,'8pt'),
Array(2,'10pt'),
Array(3,'12pt'),
Array(4,'14pt'),
Array(5,'18pt'),
Array(6,'24pt'),
Array(7,'36pt')
);
var KE_POPUP_MENU_TABLE = Array(
"KE_ZOOM", "KE_TITLE", "KE_FONTNAME", "KE_FONTSIZE", "KE_TEXTCOLOR", "KE_BGCOLOR",
"KE_LAYER", "KE_TABLE", "KE_HR", "KE_ICON", "KE_SPECIALCHAR", "KE_ABOUT",
"KE_IMAGE", "KE_FLASH", "KE_MEDIA", "KE_REAL", "KE_LINK"
);
var KE_COLOR_TABLE = Array(
"#FF0000", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#FF00FF", "#FFFFFF", "#F5F5F5", "#DCDCDC", "#FFFAFA",
"#D3D3D3", "#C0C0C0", "#A9A9A9", "#808080", "#696969", "#000000", "#2F4F4F", "#708090", "#778899", "#4682B4",
"#4169E1", "#6495ED", "#B0C4DE", "#7B68EE", "#6A5ACD", "#483D8B", "#191970", "#000080", "#00008B", "#0000CD",
"#1E90FF", "#00BFFF", "#87CEFA", "#87CEEB", "#ADD8E6", "#B0E0E6", "#F0FFFF", "#E0FFFF", "#AFEEEE", "#00CED1",
"#5F9EA0", "#48D1CC", "#00FFFF", "#40E0D0", "#20B2AA", "#008B8B", "#008080", "#7FFFD4", "#66CDAA", "#8FBC8F",
"#3CB371", "#2E8B57", "#006400", "#008000", "#228B22", "#32CD32", "#00FF00", "#7FFF00", "#7CFC00", "#ADFF2F",
"#98FB98", "#90EE90", "#00FF7F", "#00FA9A", "#556B2F", "#6B8E23", "#808000", "#BDB76B", "#B8860B", "#DAA520",
"#FFD700", "#F0E68C", "#EEE8AA", "#FFEBCD", "#FFE4B5", "#F5DEB3", "#FFDEAD", "#DEB887", "#D2B48C", "#BC8F8F",
"#A0522D", "#8B4513", "#D2691E", "#CD853F", "#F4A460", "#8B0000", "#800000", "#A52A2A", "#B22222", "#CD5C5C",
"#F08080", "#FA8072", "#E9967A", "#FFA07A", "#FF7F50", "#FF6347", "#FF8C00", "#FFA500", "#FF4500", "#DC143C",
"#FF0000", "#FF1493", "#FF00FF", "#FF69B4", "#FFB6C1", "#FFC0CB", "#DB7093", "#C71585", "#800080", "#8B008B",
"#9370DB", "#8A2BE2", "#4B0082", "#9400D3", "#9932CC", "#BA55D3", "#DA70D6", "#EE82EE", "#DDA0DD", "#D8BFD8",
"#E6E6FA", "#F8F8FF", "#F0F8FF", "#F5FFFA", "#F0FFF0", "#FAFAD2", "#FFFACD", "#FFF8DC", "#FFFFE0", "#FFFFF0",
"#FFFAF0", "#FAF0E6", "#FDF5E6", "#FAEBD7", "#FFE4C4", "#FFDAB9", "#FFEFD5", "#FFF5EE", "#FFF0F5", "#FFE4E1"
);
var KE_IMAGE_ALIGN_TABLE = Array(
"baseline", "top", "middle", "bottom", "texttop", "absmiddle", "absbottom", "left", "right"
);
var KE_OBJ_NAME;
var KE_SELECTION;
var KE_RANGE;
var KE_RANGE_TEXT;
var KE_EDITFORM_DOCUMENT;
var KE_IMAGE_DOCUMENT;
var KE_FLASH_DOCUMENT;
var KE_MEDIA_DOCUMENT;
var KE_REAL_DOCUMENT;
var KE_LINK_DOCUMENT;
var KE_BROWSER;
var KE_TOOLBAR_ICON;
function KindGetBrowser()
{
var browser = '';
var agentInfo = navigator.userAgent.toLowerCase();
if (agentInfo.indexOf("msie") > -1) {
var re = new RegExp("msie\\s?([\\d\\.]+)","ig");
var arr = re.exec(agentInfo);
if (parseInt(RegExp.$1) >= 5.5) {
browser = 'IE';
}
} else if (agentInfo.indexOf("firefox") > -1) {
browser = 'FF';
} else if (agentInfo.indexOf("netscape") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[temp1.length-1].split('/');
if (parseInt(temp2[1]) >= 7) {
browser = 'NS';
}
} else if (agentInfo.indexOf("gecko") > -1) {
browser = 'ML';
} else if (agentInfo.indexOf("opera") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[0].split('/');
if (parseInt(temp2[1]) >= 9) {
browser = 'OPERA';
}
}
return browser;
}
function KindGetFileName(file, separator)
{
var temp = file.split(separator);
var len = temp.length;
var fileName = temp[len-1];
return fileName;
}
function KindGetFileExt(fileName)
{
var temp = fileName.split(".");
var len = temp.length;
var fileExt = temp[len-1].toLowerCase();
return fileExt;
}
function KindCheckImageFileType(file, separator)
{
if (separator == "/" && file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, separator);
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'gif' && fileExt != 'jpg' && fileExt != 'png' && fileExt != 'bmp') {
alert(KE_LANG['INVALID_IMAGE']);
return false;
}
return true;
}
function KindCheckFlashFileType(file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'swf') {
alert(KE_LANG['INVALID_FLASH']);
return false;
}
return true;
}
function KindCheckMediaFileType(cmd, file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (cmd == 'KE_REAL') {
if (fileExt != 'rm' && fileExt != 'rmvb') {
alert(KE_LANG['INVALID_REAL']);
return false;
}
} else {
if (fileExt != 'mp3' && fileExt != 'wav' && fileExt != 'wma' && fileExt != 'wmv' && fileExt != 'mid' && fileExt != 'avi' && fileExt != 'mpg' && fileExt != 'asf') {
alert(KE_LANG['INVALID_MEDIA']);
return false;
}
}
return true;
}
function KindHtmlToXhtml(str)
{
str = str.replace(/<br.*?>/gi, "<br />");
str = str.replace(/(<hr\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<img\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<\w+)(.*?>)/gi, function ($0,$1,$2) {
return($1.toLowerCase() + KindConvertAttribute($2));
}
);
str = str.replace(/(<\/\w+>)/gi, function ($0,$1) {
return($1.toLowerCase());
}
);
return str;
}
function KindConvertAttribute(str)
{
if (KE_SAFE_MODE == true) {
str = KindClearAttributeScriptTag(str);
}
return str;
}
function KindClearAttributeScriptTag(str)
{
var re = new RegExp("(\\son[a-z]+=)[\"']?[^>]*?[^\\\\\>][\"']?([\\s>])","ig");
str = str.replace(re, function ($0,$1,$2) {
return($1.toLowerCase() + "\"\"" + $2);
}
);
return str;
}
function KindClearScriptTag(str)
{
if (KE_SAFE_MODE == false) {
return str;
}
str = str.replace(/<(script.*?)>/gi, "[$1]");
str = str.replace(/<\/script>/gi, "[/script]");
return str;
}
function KindHtmlentities(str)
{
str = str.replace(/&/g,'&');
str = str.replace(/</g,'<');
str = str.replace(/>/g,'>');
str = str.replace(/"/g,'"');
return str;
}
function KindGetTop(id)
{
var top = 28;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
top += eval("obj" + tmp).offsetTop;
}
return top;
}
function KindGetLeft(id)
{
var left = 2;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
left += eval("obj" + tmp).offsetLeft;
}
return left;
}
function KindDisplayMenu(cmd)
{
KindEditorForm.focus();
if (cmd != 'KE_ABOUT') {
KindSelection();
}
KindDisableMenu();
var top, left;
top = KindGetTop(cmd);
left = KindGetLeft(cmd);
if (cmd == 'KE_ABOUT') {
left -= 200;
} else if (cmd == 'KE_LINK') {
left -= 220;
}
document.getElementById('POPUP_'+cmd).style.top = top.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.left = left.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.display = 'block';
}
function KindDisableMenu()
{
for (i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
document.getElementById('POPUP_'+KE_POPUP_MENU_TABLE[i]).style.display = 'none';
}
}
function KindReloadIframe()
{
var str = '';
str += KindPopupMenu('KE_IMAGE');
str += KindPopupMenu('KE_FLASH');
str += KindPopupMenu('KE_MEDIA');
str += KindPopupMenu('KE_REAL');
document.getElementById('InsertIframe').innerHTML = str;
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
}
function KindGetMenuCommonStyle()
{
var str = 'position:absolute;top:1px;left:1px;font-size:12px;color:'+KE_MENU_TEXT_COLOR+
';background-color:'+KE_MENU_BG_COLOR+';border:solid 1px '+KE_MENU_BORDER_COLOR+';z-index:1;display:none;';
return str;
}
function KindGetCommonMenu(cmd, content)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="'+KindGetMenuCommonStyle()+'">';
str += content;
str += '</div>';
return str;
}
function KindCreateColorTable(cmd, eventStr)
{
var str = '';
str += '<table cellpadding="0" cellspacing="2" border="0">';
for (i = 0; i < KE_COLOR_TABLE.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="width:12px;height:12px;border:1px solid #AAAAAA;font-size:1px;cursor:pointer;background-color:' +
KE_COLOR_TABLE[i] + ';" onmouseover="javascript:this.style.borderColor=\'#000000\';' + ((eventStr) ? eventStr : '') + '" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onclick="javascript:KindExecute(\''+cmd+'_END\', \'' + KE_COLOR_TABLE[i] + '\');"> </td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
}
function KindDrawColorTable(cmd)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;padding:2px;'+KindGetMenuCommonStyle()+'">';
str += KindCreateColorTable(cmd);
str += '</div>';
return str;
}
function KindDrawMedia(cmd)
{
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="'+cmd+'preview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="'+cmd+'link" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['LISTENING']+'" onclick="javascript:parent.KindMediaPreview(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawMediaEnd(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
return str;
}
function KindPopupMenu(cmd)
{
switch (cmd)
{
case 'KE_ZOOM':
var str = '';
for (i = 0; i < KE_ZOOM_TABLE.length; i++) {
str += '<div style="padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ZOOM_END\', \'' + KE_ZOOM_TABLE[i] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_ZOOM_TABLE[i] + '</div>';
}
str = KindGetCommonMenu('KE_ZOOM', str);
return str;
break;
case 'KE_TITLE':
var str = '';
for (i = 0; i < KE_TITLE_TABLE.length; i++) {
str += '<div style="width:140px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TITLE_END\', \'' + KE_TITLE_TABLE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';"><' + KE_TITLE_TABLE[i][0] + ' style="margin:2px;">' +
KE_TITLE_TABLE[i][1] + '</' + KE_TITLE_TABLE[i][0] + '></div>';
}
str = KindGetCommonMenu('KE_TITLE', str);
return str;
break;
case 'KE_FONTNAME':
var str = '';
for (i = 0; i < KE_FONT_NAME.length; i++) {
str += '<div style="font-family:' + KE_FONT_NAME[i][0] +
';padding:2px;width:160px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTNAME_END\', \'' + KE_FONT_NAME[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_NAME[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTNAME', str);
return str;
break;
case 'KE_FONTSIZE':
var str = '';
for (i = 0; i < KE_FONT_SIZE.length; i++) {
str += '<div style="font-size:' + KE_FONT_SIZE[i][1] +
';padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTSIZE_END\', \'' + KE_FONT_SIZE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_SIZE[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTSIZE', str);
return str;
break;
case 'KE_TEXTCOLOR':
var str = '';
str = KindDrawColorTable('KE_TEXTCOLOR');
return str;
break;
case 'KE_BGCOLOR':
var str = '';
str = KindDrawColorTable('KE_BGCOLOR');
return str;
break;
case 'KE_HR':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="hrPreview" style="margin:10px 2px 10px 2px;height:1px;border:0;font-size:0;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'hrPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_LAYER':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="divPreview" style="margin:5px 2px 5px 2px;height:20px;border:1px solid #AAAAAA;font-size:1px;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'divPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_ICON':
var str = '';
var iconNum = 36;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < iconNum; i++) {
if (i == 0 || (i >= 6 && i%6 == 0)) {
str += '<tr>';
}
var num;
if ((i+1).toString(10).length < 2) {
num = '0' + (i+1);
} else {
num = (i+1).toString(10);
}
var iconUrl = KE_ICON_PATH + 'etc_' + num + '.gif';
str += '<td style="padding:2px;border:0;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ICON_END\', \'' + iconUrl + '\');">' +
'<img src="' + iconUrl + '" style="border:1px solid #EEEEEE;" onmouseover="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#EEEEEE\';">' + '</td>';
if (i >= 5 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_SPECIALCHAR':
var str = '';
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < KE_SPECIAL_CHARACTER.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="padding:2px;border:1px solid #AAAAAA;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_SPECIALCHAR_END\', \'' + KE_SPECIAL_CHARACTER[i] + '\');" ' +
'onmouseover="javascript:this.style.borderColor=\'#000000\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';">' + KE_SPECIAL_CHARACTER[i] + '</td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_TABLE':
var str = '';
var num = 10;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="0" style="'+KindGetMenuCommonStyle()+'">';
for (i = 1; i <= num; i++) {
str += '<tr>';
for (j = 1; j <= num; j++) {
var value = i.toString(10) + ',' + j.toString(10);
str += '<td id="kindTableTd' + i.toString(10) + '_' + j.toString(10) +
'" style="width:15px;height:15px;background-color:#FFFFFF;border:1px solid #DDDDDD;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TABLE_END\', \'' + value + '\');" ' +
'onmouseover="javascript:KindDrawTableSelected(\''+i.toString(10)+'\', \''+j.toString(10)+'\');" ' +
'onmouseout="javascript:;"> </td>';
}
str += '</tr>';
}
str += '<tr><td colspan="10" id="tableLocation" style="text-align:center;height:20px;"></td></tr>';
str += '</table>';
return str;
break;
case 'KE_IMAGE':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindImageIframe" id="KindImageIframe" frameborder="0" style="width:250px;height:390px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_FLASH':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindFlashIframe" id="KindFlashIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_MEDIA':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindMediaIframe" id="KindMediaIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_REAL':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindRealIframe" id="KindRealIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_LINK':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindLinkIframe" id="KindLinkIframe" frameborder="0" style="width:250px;height:85px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_ABOUT':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:230px;'+KindGetMenuCommonStyle()+';padding:5px;">';
str += '<span style="margin-right:10px;">KindEditor ' + KE_VERSION + '</span>' +
'<a href="http://www.kindsoft.net/" target="_blank" style="color:#4169e1;" onclick="javascript:KindDisableMenu();">'+KE_LANG['ABOUT']+'</a><br />';
str += '</div>';
return str;
break;
default:
break;
}
}
function KindDrawIframe(cmd)
{
if (KE_BROWSER == 'IE') {
KE_IMAGE_DOCUMENT = document.frames("KindImageIframe").document;
KE_FLASH_DOCUMENT = document.frames("KindFlashIframe").document;
KE_MEDIA_DOCUMENT = document.frames("KindMediaIframe").document;
KE_REAL_DOCUMENT = document.frames("KindRealIframe").document;
KE_LINK_DOCUMENT = document.frames("KindLinkIframe").document;
} else {
KE_IMAGE_DOCUMENT = document.getElementById('KindImageIframe').contentDocument;
KE_FLASH_DOCUMENT = document.getElementById('KindFlashIframe').contentDocument;
KE_MEDIA_DOCUMENT = document.getElementById('KindMediaIframe').contentDocument;
KE_REAL_DOCUMENT = document.getElementById('KindRealIframe').contentDocument;
KE_LINK_DOCUMENT = document.getElementById('KindLinkIframe').contentDocument;
}
switch (cmd)
{
case 'KE_IMAGE':
var str = '';
str += '<div align="center">' +
'<form name="uploadForm" style="margin:0;padding:0;" method="post" enctype="multipart/form-data" ' +
'action="' + KE_IMAGE_UPLOAD_CGI + '" onsubmit="javascript:if(parent.KindDrawImageEnd()==false){return false;};">' +
'<input type="hidden" name="fileName" id="fileName" value="" />' +
'<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0" style="margin-bottom:3px;"><tr><td id="imgPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:50px;padding-left:5px;">';
if (KE_UPLOAD_MODE == true) {
str += '<select id="imageType" onchange="javascript:parent.KindImageType(this.value);document.getElementById(\''+cmd+'submitButton\').focus();"><option value="1" selected="selected">'+KE_LANG['LOCAL']+'</option><option value="2">'+KE_LANG['REMOTE']+'</option></select>';
} else {
str += KE_LANG['REMOTE'];
}
str += '</td><td style="width:200px;padding-bottom:3px;">';
if (KE_UPLOAD_MODE == true) {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;display:none;" />' +
'<input type="file" name="fileData" id="imgFile" size="14" style="border:1px solid #555555;" onclick="javascript:document.getElementById(\'imgLink\').value=\'http://\';" />';
} else {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;" />' +
'<input type="hidden" name="imageType" id="imageType" value="2"><input type="hidden" name="fileData" id="imgFile" value="" />';
}
str += '</td></tr><tr><td colspan="2" style="padding-bottom:3px;">' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="18%" style="padding:2px 2px 2px 5px;">'+KE_LANG['TITLE']+'</td><td width="82%"><input type="text" name="imgTitle" id="imgTitle" value="" maxlength="100" style="width:95%;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="10%" style="padding:2px 2px 2px 5px;">'+KE_LANG['WIDTH']+'</td><td width="23%"><input type="text" name="imgWidth" id="imgWidth" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['HEIGHT']+'</td><td width="23%"><input type="text" name="imgHeight" id="imgHeight" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['BORDER']+'</td><td width="23%"><input type="text" name="imgBorder" id="imgBorder" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="39%" style="padding:2px 2px 2px 5px;"><select id="imgAlign" name="imgAlign"><option value="">'+KE_LANG['ALIGN']+'</option>';
for (var i = 0; i < KE_IMAGE_ALIGN_TABLE.length; i++) {
str += '<option value="' + KE_IMAGE_ALIGN_TABLE[i] + '">' + KE_IMAGE_ALIGN_TABLE[i] + '</option>';
}
str += '</select></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['HSPACE']+'</td><td width="15%"><input type="text" name="imgHspace" id="imgHspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['VSPACE']+'</td><td width="15%"><input type="text" name="imgVspace" id="imgVspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'</td></tr><tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindImagePreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table></form></div>';
KindDrawMenuIframe(KE_IMAGE_DOCUMENT, str);
break;
case 'KE_FLASH':
var str = '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="flashPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="flashLink" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindFlashPreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawFlashEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
KindDrawMenuIframe(KE_FLASH_DOCUMENT, str);
break;
case 'KE_MEDIA':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_MEDIA_DOCUMENT, str);
break;
case 'KE_REAL':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_REAL_DOCUMENT, str);
break;
case 'KE_LINK':
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td style="width:50px;padding:5px;">URL</td>' +
'<td style="width:200px;padding-top:5px;padding-bottom:5px;"><input type="text" id="hyperLink" value="http://" style="width:190px;border:1px solid #555555;background-color:#FFFFFF;"></td>' +
'<tr><td style="padding:5px;">'+KE_LANG['TARGET']+'</td>' +
'<td style="padding-bottom:5px;"><select id="hyperLinkTarget"><option value="_blank" selected="selected">'+KE_LANG['NEW_WINDOW']+'</option><option value="">'+KE_LANG['CURRENT_WINDOW']+'</option></select></td></tr>' +
'<tr><td colspan="2" style="padding-bottom:5px;" align="center">' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawLinkEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>';
str += '</table>';
KindDrawMenuIframe(KE_LINK_DOCUMENT, str);
break;
default:
break;
}
}
function KindDrawMenuIframe(obj, str)
{
obj.open();
obj.write(str);
obj.close();
obj.body.style.color = KE_MENU_TEXT_COLOR;
obj.body.style.backgroundColor = KE_MENU_BG_COLOR;
obj.body.style.margin = 0;
obj.body.scroll = 'no';
}
function KindDrawTableSelected(i, j)
{
var text = i.toString(10) + ' by ' + j.toString(10) + ' Table';
document.getElementById('tableLocation').innerHTML = text;
var num = 10;
for (m = 1; m <= num; m++) {
for (n = 1; n <= num; n++) {
var obj = document.getElementById('kindTableTd' + m.toString(10) + '_' + n.toString(10) + '');
if (m <= i && n <= j) {
obj.style.backgroundColor = KE_MENU_SELECTED_COLOR;
} else {
obj.style.backgroundColor = '#FFFFFF';
}
}
}
}
function KindImageType(type)
{
if (type == 1) {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'block';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').value = 'http://';
} else {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'block';
}
KE_IMAGE_DOCUMENT.getElementById('imgPreview').innerHTML = " ";
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = 0;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = 0;
}
function KindImagePreview()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
if (type == 1) {
if (KE_BROWSER != 'IE') {
return false;
}
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
url = 'file:///' + file;
if (KindCheckImageFileType(url, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
var imgObj = KE_IMAGE_DOCUMENT.createElement("IMG");
imgObj.src = url;
var width = parseInt(imgObj.width);
var height = parseInt(imgObj.height);
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = width;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = height;
var rate = parseInt(width/height);
if (width >230 && height <= 230) {
width = 230;
height = parseInt(width/rate);
} else if (width <=230 && height > 230) {
height = 230;
width = parseInt(height*rate);
} else if (width >230 && height > 230) {
if (width >= height) {
width = 230;
height = parseInt(width/rate);
} else {
height = 230;
width = parseInt(height*rate);
}
}
imgObj.style.width = width;
imgObj.style.height = height;
var el = KE_IMAGE_DOCUMENT.getElementById('imgPreview');
if (el.hasChildNodes()) {
el.removeChild(el.childNodes[0]);
}
el.appendChild(imgObj);
return imgObj;
}
function KindDrawImageEnd()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
var width = KE_IMAGE_DOCUMENT.getElementById('imgWidth').value;
var height = KE_IMAGE_DOCUMENT.getElementById('imgHeight').value;
var border = KE_IMAGE_DOCUMENT.getElementById('imgBorder').value;
var title = KE_IMAGE_DOCUMENT.getElementById('imgTitle').value;
var align = KE_IMAGE_DOCUMENT.getElementById('imgAlign').value;
var hspace = KE_IMAGE_DOCUMENT.getElementById('imgHspace').value;
var vspace = KE_IMAGE_DOCUMENT.getElementById('imgVspace').value;
if (type == 1) {
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
if (KindCheckImageFileType(file, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
if (width.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_WIDTH']);
return false;
}
if (height.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HEIGHT']);
return false;
}
if (border.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_BORDER']);
return false;
}
if (hspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HSPACE']);
return false;
}
if (vspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_VSPACE']);
return false;
}
var fileName;
KindEditorForm.focus();
if (type == 1) {
fileName = KindGetFileName(file, "\\");
var fileExt = KindGetFileExt(fileName);
var dateObj = new Date();
var year = dateObj.getFullYear().toString(10);
var month = (dateObj.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = dateObj.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var ymd = year + month + day;
fileName = ymd + dateObj.getTime().toString(10) + '.' + fileExt;
KE_IMAGE_DOCUMENT.getElementById('fileName').value = fileName;
} else {
KindInsertImage(url, width, height, border, title, align, hspace, vspace);
}
}
function KindInsertImage(url, width, height, border, title, align, hspace, vspace)
{
var element = document.createElement("img");
element.src = url;
if (width > 0) {
element.style.width = width;
}
if (height > 0) {
element.style.height = height;
}
if (align != "") {
element.align = align;
}
if (hspace > 0) {
element.hspace = hspace;
}
if (vspace > 0) {
element.vspace = vspace;
}
element.border = border;
element.alt = KindHtmlentities(title);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
KindReloadIframe();
}
function KindGetFlashHtmlTag(url)
{
var str = '<embed src="'+url+'" type="application/x-shockwave-flash" quality="high"></embed>';
return str;
}
function KindFlashPreview()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
var el = KE_FLASH_DOCUMENT.getElementById('flashPreview');
el.innerHTML = KindGetFlashHtmlTag(url);
}
function KindDrawFlashEnd()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
obj.type = "application/x-shockwave-flash";
obj.quality = "high";
KindInsertItem(obj);
KindDisableMenu();
}
function KindGetMediaHtmlTag(cmd, url)
{
var str = '<embed src="'+url+'" type="';
if (cmd == "KE_REAL") {
str += 'audio/x-pn-realaudio-plugin';
} else {
str += 'video/x-ms-asf-plugin';
}
str += '" width="230" height="230" loop="true" autostart="true">';
return str;
}
function KindMediaPreview(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
var el = mediaDocument.getElementById(cmd+'preview');
el.innerHTML = KindGetMediaHtmlTag(cmd, url);
}
function KindDrawMediaEnd(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
if (cmd == 'KE_REAL') {
obj.type = 'audio/x-pn-realaudio-plugin';
} else {
obj.type = 'video/x-ms-asf-plugin';
}
obj.loop = 'true';
obj.autostart = 'true';
KindInsertItem(obj);
KindDisableMenu(cmd);
}
function KindDrawLinkEnd()
{
var range;
var url = KE_LINK_DOCUMENT.getElementById('hyperLink').value;
var target = KE_LINK_DOCUMENT.getElementById('hyperLinkTarget').value;
if (url.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
KindEditorForm.focus();
KindSelect();
var element;
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
var el = document.createElement("a");
el.href = url;
if (target) {
el.target = target;
}
KE_RANGE.item(0).applyElement(el);
} else if (KE_SELECTION.type.toLowerCase() == 'text') {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.parentElement();
if (target) {
element.target = target;
}
}
} else {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.startContainer.previousSibling;
element.target = target;
if (target) {
element.target = target;
}
}
KindDisableMenu();
}
function KindSelection()
{
if (KE_BROWSER == 'IE') {
KE_SELECTION = KE_EDITFORM_DOCUMENT.selection;
KE_RANGE = KE_SELECTION.createRange();
KE_RANGE_TEXT = KE_RANGE.text;
} else {
KE_SELECTION = document.getElementById("KindEditorForm").contentWindow.getSelection();
KE_RANGE = KE_SELECTION.getRangeAt(0);
KE_RANGE_TEXT = KE_RANGE.toString();
}
}
function KindSelect()
{
if (KE_BROWSER == 'IE') {
KE_RANGE.select();
}
}
function KindInsertItem(insertNode)
{
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
KE_RANGE.item(0).outerHTML = insertNode.outerHTML;
} else {
KE_RANGE.pasteHTML(insertNode.outerHTML);
}
} else {
KE_SELECTION.removeAllRanges();
KE_RANGE.deleteContents();
var startRangeNode = KE_RANGE.startContainer;
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
if (startRangeNode.nodeType == 3 && insertNode.nodeType == 3) {
startRangeNode.insertData(startRangeOffset, insertNode.nodeValue);
newRange.setEnd(startRangeNode, startRangeOffset + insertNode.length);
newRange.setStart(startRangeNode, startRangeOffset + insertNode.length);
} else {
var afterNode;
if (startRangeNode.nodeType == 3) {
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(insertNode, afterNode);
startRangeNode.insertBefore(beforeNode, insertNode);
startRangeNode.removeChild(textNode);
} else {
if (startRangeNode.tagName.toLowerCase() == 'html') {
startRangeNode = startRangeNode.childNodes[0].nextSibling;
afterNode = startRangeNode.childNodes[0];
} else {
afterNode = startRangeNode.childNodes[startRangeOffset];
}
startRangeNode.insertBefore(insertNode, afterNode);
}
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
}
KE_SELECTION.addRange(newRange);
}
}
function KindExecuteValue(cmd, value)
{
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, value);
}
function KindSimpleExecute(cmd)
{
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, null);
KindDisableMenu();
}
function KindExecute(cmd, value)
{
switch (cmd)
{
case 'KE_SOURCE':
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
document.getElementById("KindCodeForm").value = KindHtmlToXhtml(KE_EDITFORM_DOCUMENT.body.innerHTML);
document.getElementById("KindEditorIframe").style.display = 'none';
document.getElementById("KindEditTextarea").style.display = 'block';
KindDisableToolbar(true);
} else {
KE_EDITFORM_DOCUMENT.body.innerHTML = KindClearScriptTag(document.getElementById("KindCodeForm").value);
document.getElementById("KindEditTextarea").style.display = 'none';
document.getElementById("KindEditorIframe").style.display = 'block';
KindDisableToolbar(false);
}
KindDisableMenu();
break;
case 'KE_PRINT':
KindSimpleExecute('print');
break;
case 'KE_UNDO':
KindSimpleExecute('undo');
break;
case 'KE_REDO':
KindSimpleExecute('redo');
break;
case 'KE_CUT':
KindSimpleExecute('cut');
break;
case 'KE_COPY':
KindSimpleExecute('copy');
break;
case 'KE_PASTE':
KindSimpleExecute('paste');
break;
case 'KE_SELECTALL':
KindSimpleExecute('selectall');
break;
case 'KE_SUBSCRIPT':
KindSimpleExecute('subscript');
break;
case 'KE_SUPERSCRIPT':
KindSimpleExecute('superscript');
break;
case 'KE_BOLD':
KindSimpleExecute('bold');
break;
case 'KE_ITALIC':
KindSimpleExecute('italic');
break;
case 'KE_UNDERLINE':
KindSimpleExecute('underline');
break;
case 'KE_STRIKE':
KindSimpleExecute('strikethrough');
break;
case 'KE_JUSTIFYLEFT':
KindSimpleExecute('justifyleft');
break;
case 'KE_JUSTIFYCENTER':
KindSimpleExecute('justifycenter');
break;
case 'KE_JUSTIFYRIGHT':
KindSimpleExecute('justifyright');
break;
case 'KE_JUSTIFYFULL':
KindSimpleExecute('justifyfull');
break;
case 'KE_NUMBEREDLIST':
KindSimpleExecute('insertorderedlist');
break;
case 'KE_UNORDERLIST':
KindSimpleExecute('insertunorderedlist');
break;
case 'KE_INDENT':
KindSimpleExecute('indent');
break;
case 'KE_OUTDENT':
KindSimpleExecute('outdent');
break;
case 'KE_REMOVE':
KindSimpleExecute('removeformat');
break;
case 'KE_ZOOM':
KindDisplayMenu(cmd);
break;
case 'KE_ZOOM_END':
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.body.style.zoom = value;
KindDisableMenu();
break;
case 'KE_TITLE':
KindDisplayMenu(cmd);
break;
case 'KE_TITLE_END':
KindEditorForm.focus();
value = '<' + value + '>';
KindSelect();
KindExecuteValue('FormatBlock', value);
KindDisableMenu();
break;
case 'KE_FONTNAME':
KindDisplayMenu(cmd);
break;
case 'KE_FONTNAME_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('fontname', value);
KindDisableMenu();
break;
case 'KE_FONTSIZE':
KindDisplayMenu(cmd);
break;
case 'KE_FONTSIZE_END':
KindEditorForm.focus();
value = value.substr(0, 1);
KindSelect();
KindExecuteValue('fontsize', value);
KindDisableMenu();
break;
case 'KE_TEXTCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_TEXTCOLOR_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('ForeColor', value);
KindDisableMenu();
break;
case 'KE_BGCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_BGCOLOR_END':
KindEditorForm.focus();
if (KE_BROWSER == 'IE') {
KindSelect();
KindExecuteValue('BackColor', value);
} else {
var startRangeNode = KE_RANGE.startContainer;
if (startRangeNode.nodeType == 3) {
var parent = startRangeNode.parentNode;
var element = document.createElement("font");
element.style.backgroundColor = value;
element.appendChild(KE_RANGE.extractContents());
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
var afterNode;
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(element, afterNode);
startRangeNode.insertBefore(beforeNode, element);
startRangeNode.removeChild(textNode);
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
KE_SELECTION.addRange(newRange);
}
}
KindDisableMenu();
break;
case 'KE_ICON':
KindDisplayMenu(cmd);
break;
case 'KE_ICON_END':
KindEditorForm.focus();
var element = document.createElement("img");
element.src = value;
element.border = 0;
element.alt = "";
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_IMAGE':
KindDisplayMenu(cmd);
KindImageIframe.focus();
KE_IMAGE_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_FLASH':
KindDisplayMenu(cmd);
KindFlashIframe.focus();
KE_FLASH_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_MEDIA':
KindDisplayMenu(cmd);
KindMediaIframe.focus();
KE_MEDIA_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_REAL':
KindDisplayMenu(cmd);
KindRealIframe.focus();
KE_REAL_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_LINK':
KindDisplayMenu(cmd);
KindLinkIframe.focus();
KE_LINK_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_UNLINK':
KindSimpleExecute('unlink');
break;
case 'KE_SPECIALCHAR':
KindDisplayMenu(cmd);
break;
case 'KE_SPECIALCHAR_END':
KindEditorForm.focus();
KindSelect();
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_LAYER':
KindDisplayMenu(cmd);
break;
case 'KE_LAYER_END':
KindEditorForm.focus();
var element = document.createElement("div");
element.style.padding = "5px";
element.style.border = "1px solid #AAAAAA";
element.style.backgroundColor = value;
var childElement = document.createElement("div");
childElement.innerHTML = KE_LANG['INPUT_CONTENT'];
element.appendChild(childElement);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TABLE':
KindDisplayMenu(cmd);
break;
case 'KE_TABLE_END':
KindEditorForm.focus();
var location = value.split(',');
var element = document.createElement("table");
element.cellPadding = 0;
element.cellSpacing = 0;
element.border = 1;
element.style.width = "100px";
element.style.height = "100px";
for (var i = 0; i < location[0]; i++) {
var rowElement = element.insertRow(i);
for (var j = 0; j < location[1]; j++) {
var cellElement = rowElement.insertCell(j);
cellElement.innerHTML = " ";
}
}
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_HR':
KindDisplayMenu(cmd);
break;
case 'KE_HR_END':
KindEditorForm.focus();
var element = document.createElement("hr");
element.width = "100%";
element.color = value;
element.size = 1;
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_DATE':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var year = date.getFullYear().toString(10);
var month = (date.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = date.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var value = year + '-' + month + '-' + day;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TIME':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var hour = date.getHours().toString(10);
hour = hour.length < 2 ? '0' + hour : hour;
var minute = date.getMinutes().toString(10);
minute = minute.length < 2 ? '0' + minute : minute;
var second = date.getSeconds().toString(10);
second = second.length < 2 ? '0' + second : second;
var value = hour + ':' + minute + ':' + second;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_PREVIEW':
eval(KE_OBJ_NAME).data();
var newWin = window.open('', 'kindPreview','width=800,height=600,left=30,top=30,resizable=yes,scrollbars=yes');
KindWriteFullHtml(newWin.document, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
KindDisableMenu();
break;
case 'KE_ABOUT':
KindDisplayMenu(cmd);
break;
default:
break;
}
}
function KindDisableToolbar(flag)
{
if (flag == true) {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'design.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
if (KE_TOOLBAR_ICON[i][0] == 'KE_SOURCE' || KE_TOOLBAR_ICON[i][0] == 'KE_PREVIEW' || KE_TOOLBAR_ICON[i][0] == 'KE_ABOUT') {
continue;
}
el.style.visibility = 'hidden';
}
} else {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'source.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
el.style.visibility = 'visible';
KE_EDITFORM_DOCUMENT.designMode = 'On';
}
}
}
function KindCreateIcon(icon)
{
var str = '<img id="'+ icon[0] +'" src="' + KE_SKIN_PATH + icon[1] + '" alt="' + icon[2] + '" title="' + icon[2] +
'" align="absmiddle" style="border:1px solid ' + KE_TOOLBAR_BG_COLOR +';cursor:pointer;height:20px;';
str += '" onclick="javascript:KindExecute(\''+ icon[0] +'\');" '+
'onmouseover="javascript:this.style.border=\'1px solid ' + KE_MENU_BORDER_COLOR + '\';" ' +
'onmouseout="javascript:this.style.border=\'1px solid ' + KE_TOOLBAR_BG_COLOR + '\';" ';
str += '>';
return str;
}
function KindCreateToolbar()
{
var htmlData = '<table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
if (KE_EDITOR_TYPE == 'full') {
for (i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_TOP_TOOLBAR_ICON[i]) + '</td>';
}
htmlData += '</tr></table><table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
for (i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_BOTTOM_TOOLBAR_ICON[i]) + '</td>';
}
} else {
for (i = 0; i < KE_SIMPLE_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_SIMPLE_TOOLBAR_ICON[i]) + '</td>';
}
}
htmlData += '</tr></table>';
return htmlData;
}
function KindWriteFullHtml(documentObj, content)
{
var editHtmlData = '';
editHtmlData += '<html>\r\n<head>\r\n<title>KindEditor</title>\r\n';
editHtmlData += '<link href="'+KE_CSS_PATH+'" rel="stylesheet" type="text/css">\r\n</head>\r\n<body>\r\n';
editHtmlData += content;
editHtmlData += '\r\n</body>\r\n</html>\r\n';
documentObj.open();
documentObj.write(editHtmlData);
documentObj.close();
}
function KindEditor(objName)
{
this.objName = objName;
this.hiddenName = objName;
this.siteDomain;
this.editorType;
this.safeMode;
this.uploadMode;
this.editorWidth;
this.editorHeight;
this.skinPath;
this.iconPath;
this.imageAttachPath;
this.imageUploadCgi;
this.cssPath;
this.menuBorderColor;
this.menuBgColor;
this.menuTextColor;
this.menuSelectedColor;
this.toolbarBorderColor;
this.toolbarBgColor;
this.formBorderColor;
this.formBgColor;
this.buttonColor;
this.init = function()
{
if (this.siteDomain) KE_SITE_DOMAIN = this.siteDomain;
if (this.editorType) KE_EDITOR_TYPE = this.editorType.toLowerCase();
if (this.safeMode) KE_SAFE_MODE = this.safeMode;
if (this.uploadMode) KE_UPLOAD_MODE = this.uploadMode;
if (this.editorWidth) KE_WIDTH = this.editorWidth;
if (this.editorHeight) KE_HEIGHT = this.editorHeight;
if (this.skinPath) KE_SKIN_PATH = this.skinPath;
if (this.iconPath) KE_ICON_PATH = this.iconPath;
if (this.imageAttachPath) KE_IMAGE_ATTACH_PATH = this.imageAttachPath;
if (this.imageUploadCgi) KE_IMAGE_UPLOAD_CGI = this.imageUploadCgi;
if (this.cssPath) KE_CSS_PATH = this.cssPath;
if (this.menuBorderColor) KE_MENU_BORDER_COLOR = this.menuBorderColor;
if (this.menuBgColor) KE_MENU_BG_COLOR = this.menuBgColor;
if (this.menuTextColor) KE_MENU_TEXT_COLOR = this.menuTextColor;
if (this.menuSelectedColor) KE_MENU_SELECTED_COLOR = this.menuSelectedColor;
if (this.toolbarBorderColor) KE_TOOLBAR_BORDER_COLOR = this.toolbarBorderColor;
if (this.toolbarBgColor) KE_TOOLBAR_BG_COLOR = this.toolbarBgColor;
if (this.formBorderColor) KE_FORM_BORDER_COLOR = this.formBorderColor;
if (this.formBgColor) KE_FORM_BG_COLOR = this.formBgColor;
if (this.buttonColor) KE_BUTTON_COLOR = this.buttonColor;
KE_OBJ_NAME = this.objName;
KE_BROWSER = KindGetBrowser();
KE_TOOLBAR_ICON = Array();
for (var i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_TOP_TOOLBAR_ICON[i]);
}
for (var i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_BOTTOM_TOOLBAR_ICON[i]);
}
}
this.show = function()
{
this.init();
var widthStyle = 'width:' + KE_WIDTH + ';';
var widthArr = KE_WIDTH.match(/(\d+)([px%]{1,2})/);
var iframeWidthStyle = 'width:' + (parseInt(widthArr[1]) - 2).toString(10) + widthArr[2] + ';';
var heightStyle = 'height:' + KE_HEIGHT + ';';
var heightArr = KE_HEIGHT.match(/(\d+)([px%]{1,2})/);
var iframeHeightStyle = 'height:' + (parseInt(heightArr[1]) - 3).toString(10) + heightArr[2] + ';';
if (KE_BROWSER == '') {
var htmlData = '<div id="KindEditTextarea" style="' + widthStyle + heightStyle + '">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + widthStyle + heightStyle +
'padding:0;margin:0;border:1px solid '+ KE_FORM_BORDER_COLOR +
';font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';">' + document.getElementsByName(this.hiddenName)[0].value + '</textarea></div>';
document.open();
document.write(htmlData);
document.close();
return;
}
var htmlData = '<div style="font-family:'+KE_FONT_FAMILY+';">';
htmlData += '<div style="'+widthStyle+';border:1px solid ' + KE_TOOLBAR_BORDER_COLOR + ';background-color:'+ KE_TOOLBAR_BG_COLOR +'">';
htmlData += KindCreateToolbar();
htmlData += '</div><div id="KindEditorIframe" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';border-top:0;">' +
'<iframe name="KindEditorForm" id="KindEditorForm" frameborder="0" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;"></iframe></div>';
if (KE_EDITOR_TYPE == 'full') {
htmlData += '<div id="KindEditTextarea" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';background-color:'+
KE_FORM_BG_COLOR +';border-top:0;display:none;">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';" onclick="javascirit:parent.KindDisableMenu();"></textarea></div>';
}
htmlData += '</div>';
for (var i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
if (KE_POPUP_MENU_TABLE[i] == 'KE_IMAGE') {
htmlData += '<span id="InsertIframe">';
}
htmlData += KindPopupMenu(KE_POPUP_MENU_TABLE[i]);
if (KE_POPUP_MENU_TABLE[i] == 'KE_REAL') {
htmlData += '</span>';
}
}
document.open();
document.write(htmlData);
document.close();
if (KE_BROWSER == 'IE') {
KE_EDITFORM_DOCUMENT = document.frames("KindEditorForm").document;
} else {
KE_EDITFORM_DOCUMENT = document.getElementById('KindEditorForm').contentDocument;
}
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
KindDrawIframe('KE_LINK');
KE_EDITFORM_DOCUMENT.designMode = 'On';
KindWriteFullHtml(KE_EDITFORM_DOCUMENT, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
var el = KE_EDITFORM_DOCUMENT.body;
if (KE_EDITFORM_DOCUMENT.addEventListener){
KE_EDITFORM_DOCUMENT.addEventListener('click', KindDisableMenu, false);
} else if (el.attachEvent){
el.attachEvent('onclick', KindDisableMenu);
}
}
this.data = function()
{
var htmlResult;
if (KE_BROWSER == '') {
htmlResult = document.getElementById("KindCodeForm").value;
} else {
if (KE_EDITOR_TYPE == 'full') {
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
} else {
htmlResult = document.getElementById("KindCodeForm").value;
}
} else {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
}
}
KindDisableMenu();
htmlResult = KindHtmlToXhtml(htmlResult);
htmlResult = KindClearScriptTag(htmlResult);
document.getElementsByName(this.hiddenName)[0].value = htmlResult;
return htmlResult;
}
}
| JavaScript |
var teButtons = TextileEditor.buttons;
teButtons.push(new TextileEditorButton('ed_strong', 'bold.png', '*', '*', 'b', 'Bold','s'));
teButtons.push(new TextileEditorButton('ed_emphasis', 'italic.png', '_', '_', 'i', 'Italicize','s'));
teButtons.push(new TextileEditorButton('ed_underline', 'underline.png', '+', '+', 'u', 'Underline','s'));
teButtons.push(new TextileEditorButton('ed_strike', 'strikethrough.png', '-', '-', 's', 'Strikethrough','s'));
teButtons.push(new TextileEditorButton('ed_ol', 'list_numbers.png', ' # ', '\n', ',', 'Numbered List'));
teButtons.push(new TextileEditorButton('ed_ul', 'list_bullets.png', ' * ', '\n', '.', 'Bulleted List'));
teButtons.push(new TextileEditorButton('ed_p', 'paragraph.png', 'p', '\n', 'p', 'Paragraph'));
teButtons.push(new TextileEditorButton('ed_h1', 'h1.png', 'h1', '\n', '1', 'Header 1'));
teButtons.push(new TextileEditorButton('ed_h2', 'h2.png', 'h2', '\n', '2', 'Header 2'));
teButtons.push(new TextileEditorButton('ed_h3', 'h3.png', 'h3', '\n', '3', 'Header 3'));
teButtons.push(new TextileEditorButton('ed_h4', 'h4.png', 'h4', '\n', '4', 'Header 4'));
teButtons.push(new TextileEditorButton('ed_block', 'blockquote.png', 'bq', '\n', 'q', 'Blockquote'));
teButtons.push(new TextileEditorButton('ed_outdent', 'outdent.png', ')', '\n', ']', 'Outdent'));
teButtons.push(new TextileEditorButton('ed_indent', 'indent.png', '(', '\n', '[', 'Indent'));
teButtons.push(new TextileEditorButton('ed_justifyl', 'left.png', '<', '\n', 'l', 'Left Justify'));
teButtons.push(new TextileEditorButton('ed_justifyc', 'center.png', '=', '\n', 'e', 'Center Text'));
teButtons.push(new TextileEditorButton('ed_justifyr', 'right.png', '>', '\n', 'r', 'Right Justify'));
teButtons.push(new TextileEditorButton('ed_justify', 'justify.png', '<>', '\n', 'j', 'Justify'));
// teButtons.push(new TextileEditorButton('ed_code','code','@','@','c','Code')); | JavaScript |
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
| JavaScript |
/**
* WYSIWYG HTML Editor for Internet
*
* @author Roddy <luolonghao@gmail.com>
* @version 2.5.3
*/
var KE_VERSION = "2.5.4";
var KE_EDITOR_TYPE = "full"; //full or simple
var KE_SAFE_MODE = false; // true or false
var KE_UPLOAD_MODE = true; // true or false
var KE_FONT_FAMILY = "Courier New";
var KE_WIDTH = "700px";
var KE_HEIGHT = "400px";
var KE_SITE_DOMAIN = "";
var KE_SKIN_PATH = "./skins/default/";
var KE_ICON_PATH = "./icons/";
var KE_IMAGE_ATTACH_PATH = "./attached/";
var KE_IMAGE_UPLOAD_CGI = "./upload_cgi/upload.php";
var KE_CSS_PATH = "/editor/common.css";
var KE_MENU_BORDER_COLOR = '#AAAAAA';
var KE_MENU_BG_COLOR = '#EFEFEF';
var KE_MENU_TEXT_COLOR = '#222222';
var KE_MENU_SELECTED_COLOR = '#CCCCCC';
var KE_TOOLBAR_BORDER_COLOR = '#DDDDDD';
var KE_TOOLBAR_BG_COLOR = '#EFEFEF';
var KE_FORM_BORDER_COLOR = '#DDDDDD';
var KE_FORM_BG_COLOR = '#FFFFFF';
var KE_BUTTON_COLOR = '#AAAAAA';
var KE_LANG = {
INPUT_URL : "请输入正确的URL地址。",
SELECT_IMAGE : "请选择图片。",
INVALID_IMAGE : "只能选择GIF,JPG,PNG,BMP格式的图片,请重新选择。",
INVALID_FLASH : "只能选择SWF格式的文件,请重新选择。",
INVALID_MEDIA : "只能选择MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF格式的文件,请重新选择。",
INVALID_REAL : "只能选择RM,RMVB格式的文件,请重新选择。",
INVALID_WIDTH : "宽度不是数字,请重新输入。",
INVALID_HEIGHT : "高度不是数字,请重新输入。",
INVALID_BORDER : "边框不是数字,请重新输入。",
INVALID_HSPACE : "横隔不是数字,请重新输入。",
INVALID_VSPACE : "竖隔不是数字,请重新输入。",
INPUT_CONTENT : "请输入内容",
TITLE : "描述",
WIDTH : "宽",
HEIGHT : "高",
BORDER : "边",
ALIGN : "对齐方式",
HSPACE : "横隔",
VSPACE : "竖隔",
CONFIRM : "确定",
CANCEL : "取消",
PREVIEW : "预览",
LISTENING : "试听",
LOCAL : "本地",
REMOTE : "远程",
NEW_WINDOW : "新窗口",
CURRENT_WINDOW : "当前窗口",
TARGET : "目标",
ABOUT : "访问技术支持网站",
SUBJECT : "标题"
}
var KE_FONT_NAME = Array(
Array('SimSun', '宋体'),
Array('SimHei', '黑体'),
Array('FangSong_GB2312', '仿宋体'),
Array('KaiTi_GB2312', '楷体'),
Array('NSimSun', '新宋体'),
Array('Arial', 'Arial'),
Array('Arial Black', 'Arial Black'),
Array('Times New Roman', 'Times New Roman'),
Array('Courier New', 'Courier New'),
Array('Tahoma', 'Tahoma'),
Array('Verdana', 'Verdana'),
Array('GulimChe', 'GulimChe'),
Array('MS Gothic', 'MS Gothic')
);
var KE_SPECIAL_CHARACTER = Array(
'§','№','☆','★','○','●','◎','◇','◆','□','℃','‰','■','△','▲','※',
'→','←','↑','↓','〓','¤','°','#','&','@','\','︿','_',' ̄','―','α',
'β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ',
'σ','τ','υ','φ','χ','ψ','ω','≈','≡','≠','=','≤','≥','<','>','≮',
'≯','∷','±','+','-','×','÷','/','∫','∮','∝','∞','∧','∨','∑','∏',
'∪','∩','∈','∵','∴','⊥','∥','∠','⌒','⊙','≌','∽','〖','〗',
'【','】','(',')','[',']'
);
var KE_TOP_TOOLBAR_ICON = Array(
Array('KE_SOURCE', 'source.gif', '视图转换'),
Array('KE_PREVIEW', 'preview.gif', '预览'),
Array('KE_ZOOM', 'zoom.gif', '显示比例'),
Array('KE_PRINT', 'print.gif', '打印'),
Array('KE_UNDO', 'undo.gif', '回退'),
Array('KE_REDO', 'redo.gif', '前进'),
Array('KE_CUT', 'cut.gif', '剪切'),
Array('KE_COPY', 'copy.gif', '复制'),
Array('KE_PASTE', 'paste.gif', '粘贴'),
Array('KE_SELECTALL', 'selectall.gif', '全选'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_JUSTIFYFULL', 'justifyfull.gif', '两端对齐'),
Array('KE_NUMBEREDLIST', 'numberedlist.gif', '编号'),
Array('KE_UNORDERLIST', 'unorderedlist.gif', '项目符号'),
Array('KE_INDENT', 'indent.gif', '减少缩进'),
Array('KE_OUTDENT', 'outdent.gif', '增加缩进'),
Array('KE_SUBSCRIPT', 'subscript.gif', '下标'),
Array('KE_SUPERSCRIPT', 'superscript.gif', '上标'),
Array('KE_DATE', 'date.gif', '日期'),
Array('KE_TIME', 'time.gif', '时间')
);
var KE_BOTTOM_TOOLBAR_ICON = Array(
Array('KE_TITLE', 'title.gif', '标题'),
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_STRIKE', 'strikethrough.gif', '删除线'),
Array('KE_REMOVE', 'removeformat.gif', '删除格式'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_FLASH', 'flash.gif', 'Flash'),
Array('KE_MEDIA', 'media.gif', 'Windows Media Player'),
Array('KE_REAL', 'real.gif', 'Real Player'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_TABLE', 'table.gif', '表格'),
Array('KE_SPECIALCHAR', 'specialchar.gif', '特殊字符'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_UNLINK', 'unlink.gif', '删除超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_SIMPLE_TOOLBAR_ICON = Array(
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_TITLE_TABLE = Array(
Array('H1', KE_LANG['SUBJECT'] + ' 1'),
Array('H2', KE_LANG['SUBJECT'] + ' 2'),
Array('H3', KE_LANG['SUBJECT'] + ' 3'),
Array('H4', KE_LANG['SUBJECT'] + ' 4'),
Array('H5', KE_LANG['SUBJECT'] + ' 5'),
Array('H6', KE_LANG['SUBJECT'] + ' 6')
);
var KE_ZOOM_TABLE = Array('250%', '200%', '150%', '120%', '100%', '80%', '50%');
var KE_FONT_SIZE = Array(
Array(1,'8pt'),
Array(2,'10pt'),
Array(3,'12pt'),
Array(4,'14pt'),
Array(5,'18pt'),
Array(6,'24pt'),
Array(7,'36pt')
);
var KE_POPUP_MENU_TABLE = Array(
"KE_ZOOM", "KE_TITLE", "KE_FONTNAME", "KE_FONTSIZE", "KE_TEXTCOLOR", "KE_BGCOLOR",
"KE_LAYER", "KE_TABLE", "KE_HR", "KE_ICON", "KE_SPECIALCHAR", "KE_ABOUT",
"KE_IMAGE", "KE_FLASH", "KE_MEDIA", "KE_REAL", "KE_LINK"
);
var KE_COLOR_TABLE = Array(
"#FF0000", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#FF00FF", "#FFFFFF", "#F5F5F5", "#DCDCDC", "#FFFAFA",
"#D3D3D3", "#C0C0C0", "#A9A9A9", "#808080", "#696969", "#000000", "#2F4F4F", "#708090", "#778899", "#4682B4",
"#4169E1", "#6495ED", "#B0C4DE", "#7B68EE", "#6A5ACD", "#483D8B", "#191970", "#000080", "#00008B", "#0000CD",
"#1E90FF", "#00BFFF", "#87CEFA", "#87CEEB", "#ADD8E6", "#B0E0E6", "#F0FFFF", "#E0FFFF", "#AFEEEE", "#00CED1",
"#5F9EA0", "#48D1CC", "#00FFFF", "#40E0D0", "#20B2AA", "#008B8B", "#008080", "#7FFFD4", "#66CDAA", "#8FBC8F",
"#3CB371", "#2E8B57", "#006400", "#008000", "#228B22", "#32CD32", "#00FF00", "#7FFF00", "#7CFC00", "#ADFF2F",
"#98FB98", "#90EE90", "#00FF7F", "#00FA9A", "#556B2F", "#6B8E23", "#808000", "#BDB76B", "#B8860B", "#DAA520",
"#FFD700", "#F0E68C", "#EEE8AA", "#FFEBCD", "#FFE4B5", "#F5DEB3", "#FFDEAD", "#DEB887", "#D2B48C", "#BC8F8F",
"#A0522D", "#8B4513", "#D2691E", "#CD853F", "#F4A460", "#8B0000", "#800000", "#A52A2A", "#B22222", "#CD5C5C",
"#F08080", "#FA8072", "#E9967A", "#FFA07A", "#FF7F50", "#FF6347", "#FF8C00", "#FFA500", "#FF4500", "#DC143C",
"#FF0000", "#FF1493", "#FF00FF", "#FF69B4", "#FFB6C1", "#FFC0CB", "#DB7093", "#C71585", "#800080", "#8B008B",
"#9370DB", "#8A2BE2", "#4B0082", "#9400D3", "#9932CC", "#BA55D3", "#DA70D6", "#EE82EE", "#DDA0DD", "#D8BFD8",
"#E6E6FA", "#F8F8FF", "#F0F8FF", "#F5FFFA", "#F0FFF0", "#FAFAD2", "#FFFACD", "#FFF8DC", "#FFFFE0", "#FFFFF0",
"#FFFAF0", "#FAF0E6", "#FDF5E6", "#FAEBD7", "#FFE4C4", "#FFDAB9", "#FFEFD5", "#FFF5EE", "#FFF0F5", "#FFE4E1"
);
var KE_IMAGE_ALIGN_TABLE = Array(
"baseline", "top", "middle", "bottom", "texttop", "absmiddle", "absbottom", "left", "right"
);
var KE_OBJ_NAME;
var KE_SELECTION;
var KE_RANGE;
var KE_RANGE_TEXT;
var KE_EDITFORM_DOCUMENT;
var KE_IMAGE_DOCUMENT;
var KE_FLASH_DOCUMENT;
var KE_MEDIA_DOCUMENT;
var KE_REAL_DOCUMENT;
var KE_LINK_DOCUMENT;
var KE_BROWSER;
var KE_TOOLBAR_ICON;
function KindGetBrowser()
{
var browser = '';
var agentInfo = navigator.userAgent.toLowerCase();
if (agentInfo.indexOf("msie") > -1) {
var re = new RegExp("msie\\s?([\\d\\.]+)","ig");
var arr = re.exec(agentInfo);
if (parseInt(RegExp.$1) >= 5.5) {
browser = 'IE';
}
} else if (agentInfo.indexOf("firefox") > -1) {
browser = 'FF';
} else if (agentInfo.indexOf("netscape") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[temp1.length-1].split('/');
if (parseInt(temp2[1]) >= 7) {
browser = 'NS';
}
} else if (agentInfo.indexOf("gecko") > -1) {
browser = 'ML';
} else if (agentInfo.indexOf("opera") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[0].split('/');
if (parseInt(temp2[1]) >= 9) {
browser = 'OPERA';
}
}
return browser;
}
function KindGetFileName(file, separator)
{
var temp = file.split(separator);
var len = temp.length;
var fileName = temp[len-1];
return fileName;
}
function KindGetFileExt(fileName)
{
var temp = fileName.split(".");
var len = temp.length;
var fileExt = temp[len-1].toLowerCase();
return fileExt;
}
function KindCheckImageFileType(file, separator)
{
if (separator == "/" && file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, separator);
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'gif' && fileExt != 'jpg' && fileExt != 'png' && fileExt != 'bmp') {
alert(KE_LANG['INVALID_IMAGE']);
return false;
}
return true;
}
function KindCheckFlashFileType(file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'swf') {
alert(KE_LANG['INVALID_FLASH']);
return false;
}
return true;
}
function KindCheckMediaFileType(cmd, file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (cmd == 'KE_REAL') {
if (fileExt != 'rm' && fileExt != 'rmvb') {
alert(KE_LANG['INVALID_REAL']);
return false;
}
} else {
if (fileExt != 'mp3' && fileExt != 'wav' && fileExt != 'wma' && fileExt != 'wmv' && fileExt != 'mid' && fileExt != 'avi' && fileExt != 'mpg' && fileExt != 'asf') {
alert(KE_LANG['INVALID_MEDIA']);
return false;
}
}
return true;
}
function KindHtmlToXhtml(str)
{
str = str.replace(/<br.*?>/gi, "<br />");
str = str.replace(/(<hr\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<img\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<\w+)(.*?>)/gi, function ($0,$1,$2) {
return($1.toLowerCase() + KindConvertAttribute($2));
}
);
str = str.replace(/(<\/\w+>)/gi, function ($0,$1) {
return($1.toLowerCase());
}
);
return str;
}
function KindConvertAttribute(str)
{
if (KE_SAFE_MODE == true) {
str = KindClearAttributeScriptTag(str);
}
return str;
}
function KindClearAttributeScriptTag(str)
{
var re = new RegExp("(\\son[a-z]+=)[\"']?[^>]*?[^\\\\\>][\"']?([\\s>])","ig");
str = str.replace(re, function ($0,$1,$2) {
return($1.toLowerCase() + "\"\"" + $2);
}
);
return str;
}
function KindClearScriptTag(str)
{
if (KE_SAFE_MODE == false) {
return str;
}
str = str.replace(/<(script.*?)>/gi, "[$1]");
str = str.replace(/<\/script>/gi, "[/script]");
return str;
}
function KindHtmlentities(str)
{
str = str.replace(/&/g,'&');
str = str.replace(/</g,'<');
str = str.replace(/>/g,'>');
str = str.replace(/"/g,'"');
return str;
}
function KindGetTop(id)
{
var top = 28;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
top += eval("obj" + tmp).offsetTop;
}
return top;
}
function KindGetLeft(id)
{
var left = 2;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
left += eval("obj" + tmp).offsetLeft;
}
return left;
}
function KindDisplayMenu(cmd)
{
KindEditorForm.focus();
if (cmd != 'KE_ABOUT') {
KindSelection();
}
KindDisableMenu();
var top, left;
top = KindGetTop(cmd);
left = KindGetLeft(cmd);
if (cmd == 'KE_ABOUT') {
left -= 200;
} else if (cmd == 'KE_LINK') {
left -= 220;
}
document.getElementById('POPUP_'+cmd).style.top = top.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.left = left.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.display = 'block';
}
function KindDisableMenu()
{
for (i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
document.getElementById('POPUP_'+KE_POPUP_MENU_TABLE[i]).style.display = 'none';
}
}
function KindReloadIframe()
{
var str = '';
str += KindPopupMenu('KE_IMAGE');
str += KindPopupMenu('KE_FLASH');
str += KindPopupMenu('KE_MEDIA');
str += KindPopupMenu('KE_REAL');
document.getElementById('InsertIframe').innerHTML = str;
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
}
function KindGetMenuCommonStyle()
{
var str = 'position:absolute;top:1px;left:1px;font-size:12px;color:'+KE_MENU_TEXT_COLOR+
';background-color:'+KE_MENU_BG_COLOR+';border:solid 1px '+KE_MENU_BORDER_COLOR+';z-index:1;display:none;';
return str;
}
function KindGetCommonMenu(cmd, content)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="'+KindGetMenuCommonStyle()+'">';
str += content;
str += '</div>';
return str;
}
function KindCreateColorTable(cmd, eventStr)
{
var str = '';
str += '<table cellpadding="0" cellspacing="2" border="0">';
for (i = 0; i < KE_COLOR_TABLE.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="width:12px;height:12px;border:1px solid #AAAAAA;font-size:1px;cursor:pointer;background-color:' +
KE_COLOR_TABLE[i] + ';" onmouseover="javascript:this.style.borderColor=\'#000000\';' + ((eventStr) ? eventStr : '') + '" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onclick="javascript:KindExecute(\''+cmd+'_END\', \'' + KE_COLOR_TABLE[i] + '\');"> </td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
}
function KindDrawColorTable(cmd)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;padding:2px;'+KindGetMenuCommonStyle()+'">';
str += KindCreateColorTable(cmd);
str += '</div>';
return str;
}
function KindDrawMedia(cmd)
{
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="'+cmd+'preview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="'+cmd+'link" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['LISTENING']+'" onclick="javascript:parent.KindMediaPreview(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawMediaEnd(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
return str;
}
function KindPopupMenu(cmd)
{
switch (cmd)
{
case 'KE_ZOOM':
var str = '';
for (i = 0; i < KE_ZOOM_TABLE.length; i++) {
str += '<div style="padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ZOOM_END\', \'' + KE_ZOOM_TABLE[i] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_ZOOM_TABLE[i] + '</div>';
}
str = KindGetCommonMenu('KE_ZOOM', str);
return str;
break;
case 'KE_TITLE':
var str = '';
for (i = 0; i < KE_TITLE_TABLE.length; i++) {
str += '<div style="width:140px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TITLE_END\', \'' + KE_TITLE_TABLE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';"><' + KE_TITLE_TABLE[i][0] + ' style="margin:2px;">' +
KE_TITLE_TABLE[i][1] + '</' + KE_TITLE_TABLE[i][0] + '></div>';
}
str = KindGetCommonMenu('KE_TITLE', str);
return str;
break;
case 'KE_FONTNAME':
var str = '';
for (i = 0; i < KE_FONT_NAME.length; i++) {
str += '<div style="font-family:' + KE_FONT_NAME[i][0] +
';padding:2px;width:160px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTNAME_END\', \'' + KE_FONT_NAME[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_NAME[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTNAME', str);
return str;
break;
case 'KE_FONTSIZE':
var str = '';
for (i = 0; i < KE_FONT_SIZE.length; i++) {
str += '<div style="font-size:' + KE_FONT_SIZE[i][1] +
';padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTSIZE_END\', \'' + KE_FONT_SIZE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_SIZE[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTSIZE', str);
return str;
break;
case 'KE_TEXTCOLOR':
var str = '';
str = KindDrawColorTable('KE_TEXTCOLOR');
return str;
break;
case 'KE_BGCOLOR':
var str = '';
str = KindDrawColorTable('KE_BGCOLOR');
return str;
break;
case 'KE_HR':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="hrPreview" style="margin:10px 2px 10px 2px;height:1px;border:0;font-size:0;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'hrPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_LAYER':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="divPreview" style="margin:5px 2px 5px 2px;height:20px;border:1px solid #AAAAAA;font-size:1px;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'divPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_ICON':
var str = '';
var iconNum = 36;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < iconNum; i++) {
if (i == 0 || (i >= 6 && i%6 == 0)) {
str += '<tr>';
}
var num;
if ((i+1).toString(10).length < 2) {
num = '0' + (i+1);
} else {
num = (i+1).toString(10);
}
var iconUrl = KE_ICON_PATH + 'etc_' + num + '.gif';
str += '<td style="padding:2px;border:0;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ICON_END\', \'' + iconUrl + '\');">' +
'<img src="' + iconUrl + '" style="border:1px solid #EEEEEE;" onmouseover="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#EEEEEE\';">' + '</td>';
if (i >= 5 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_SPECIALCHAR':
var str = '';
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < KE_SPECIAL_CHARACTER.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="padding:2px;border:1px solid #AAAAAA;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_SPECIALCHAR_END\', \'' + KE_SPECIAL_CHARACTER[i] + '\');" ' +
'onmouseover="javascript:this.style.borderColor=\'#000000\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';">' + KE_SPECIAL_CHARACTER[i] + '</td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_TABLE':
var str = '';
var num = 10;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="0" style="'+KindGetMenuCommonStyle()+'">';
for (i = 1; i <= num; i++) {
str += '<tr>';
for (j = 1; j <= num; j++) {
var value = i.toString(10) + ',' + j.toString(10);
str += '<td id="kindTableTd' + i.toString(10) + '_' + j.toString(10) +
'" style="width:15px;height:15px;background-color:#FFFFFF;border:1px solid #DDDDDD;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TABLE_END\', \'' + value + '\');" ' +
'onmouseover="javascript:KindDrawTableSelected(\''+i.toString(10)+'\', \''+j.toString(10)+'\');" ' +
'onmouseout="javascript:;"> </td>';
}
str += '</tr>';
}
str += '<tr><td colspan="10" id="tableLocation" style="text-align:center;height:20px;"></td></tr>';
str += '</table>';
return str;
break;
case 'KE_IMAGE':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindImageIframe" id="KindImageIframe" frameborder="0" style="width:250px;height:390px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_FLASH':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindFlashIframe" id="KindFlashIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_MEDIA':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindMediaIframe" id="KindMediaIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_REAL':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindRealIframe" id="KindRealIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_LINK':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindLinkIframe" id="KindLinkIframe" frameborder="0" style="width:250px;height:85px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_ABOUT':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:230px;'+KindGetMenuCommonStyle()+';padding:5px;">';
str += '<span style="margin-right:10px;">KindEditor ' + KE_VERSION + '</span>' +
'<a href="http://www.kindsoft.net/" target="_blank" style="color:#4169e1;" onclick="javascript:KindDisableMenu();">'+KE_LANG['ABOUT']+'</a><br />';
str += '</div>';
return str;
break;
default:
break;
}
}
function KindDrawIframe(cmd)
{
if (KE_BROWSER == 'IE') {
KE_IMAGE_DOCUMENT = document.frames("KindImageIframe").document;
KE_FLASH_DOCUMENT = document.frames("KindFlashIframe").document;
KE_MEDIA_DOCUMENT = document.frames("KindMediaIframe").document;
KE_REAL_DOCUMENT = document.frames("KindRealIframe").document;
KE_LINK_DOCUMENT = document.frames("KindLinkIframe").document;
} else {
KE_IMAGE_DOCUMENT = document.getElementById('KindImageIframe').contentDocument;
KE_FLASH_DOCUMENT = document.getElementById('KindFlashIframe').contentDocument;
KE_MEDIA_DOCUMENT = document.getElementById('KindMediaIframe').contentDocument;
KE_REAL_DOCUMENT = document.getElementById('KindRealIframe').contentDocument;
KE_LINK_DOCUMENT = document.getElementById('KindLinkIframe').contentDocument;
}
switch (cmd)
{
case 'KE_IMAGE':
var str = '';
str += '<div align="center">' +
'<form name="uploadForm" style="margin:0;padding:0;" method="post" enctype="multipart/form-data" ' +
'action="' + KE_IMAGE_UPLOAD_CGI + '" onsubmit="javascript:if(parent.KindDrawImageEnd()==false){return false;};">' +
'<input type="hidden" name="fileName" id="fileName" value="" />' +
'<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0" style="margin-bottom:3px;"><tr><td id="imgPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:50px;padding-left:5px;">';
if (KE_UPLOAD_MODE == true) {
str += '<select id="imageType" onchange="javascript:parent.KindImageType(this.value);document.getElementById(\''+cmd+'submitButton\').focus();"><option value="1" selected="selected">'+KE_LANG['LOCAL']+'</option><option value="2">'+KE_LANG['REMOTE']+'</option></select>';
} else {
str += KE_LANG['REMOTE'];
}
str += '</td><td style="width:200px;padding-bottom:3px;">';
if (KE_UPLOAD_MODE == true) {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;display:none;" />' +
'<input type="file" name="fileData" id="imgFile" size="14" style="border:1px solid #555555;" onclick="javascript:document.getElementById(\'imgLink\').value=\'http://\';" />';
} else {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;" />' +
'<input type="hidden" name="imageType" id="imageType" value="2"><input type="hidden" name="fileData" id="imgFile" value="" />';
}
str += '</td></tr><tr><td colspan="2" style="padding-bottom:3px;">' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="18%" style="padding:2px 2px 2px 5px;">'+KE_LANG['TITLE']+'</td><td width="82%"><input type="text" name="imgTitle" id="imgTitle" value="" maxlength="100" style="width:95%;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="10%" style="padding:2px 2px 2px 5px;">'+KE_LANG['WIDTH']+'</td><td width="23%"><input type="text" name="imgWidth" id="imgWidth" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['HEIGHT']+'</td><td width="23%"><input type="text" name="imgHeight" id="imgHeight" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['BORDER']+'</td><td width="23%"><input type="text" name="imgBorder" id="imgBorder" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="39%" style="padding:2px 2px 2px 5px;"><select id="imgAlign" name="imgAlign"><option value="">'+KE_LANG['ALIGN']+'</option>';
for (var i = 0; i < KE_IMAGE_ALIGN_TABLE.length; i++) {
str += '<option value="' + KE_IMAGE_ALIGN_TABLE[i] + '">' + KE_IMAGE_ALIGN_TABLE[i] + '</option>';
}
str += '</select></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['HSPACE']+'</td><td width="15%"><input type="text" name="imgHspace" id="imgHspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['VSPACE']+'</td><td width="15%"><input type="text" name="imgVspace" id="imgVspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'</td></tr><tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindImagePreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table></form></div>';
KindDrawMenuIframe(KE_IMAGE_DOCUMENT, str);
break;
case 'KE_FLASH':
var str = '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="flashPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="flashLink" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindFlashPreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawFlashEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
KindDrawMenuIframe(KE_FLASH_DOCUMENT, str);
break;
case 'KE_MEDIA':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_MEDIA_DOCUMENT, str);
break;
case 'KE_REAL':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_REAL_DOCUMENT, str);
break;
case 'KE_LINK':
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td style="width:50px;padding:5px;">URL</td>' +
'<td style="width:200px;padding-top:5px;padding-bottom:5px;"><input type="text" id="hyperLink" value="http://" style="width:190px;border:1px solid #555555;background-color:#FFFFFF;"></td>' +
'<tr><td style="padding:5px;">'+KE_LANG['TARGET']+'</td>' +
'<td style="padding-bottom:5px;"><select id="hyperLinkTarget"><option value="_blank" selected="selected">'+KE_LANG['NEW_WINDOW']+'</option><option value="">'+KE_LANG['CURRENT_WINDOW']+'</option></select></td></tr>' +
'<tr><td colspan="2" style="padding-bottom:5px;" align="center">' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawLinkEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>';
str += '</table>';
KindDrawMenuIframe(KE_LINK_DOCUMENT, str);
break;
default:
break;
}
}
function KindDrawMenuIframe(obj, str)
{
obj.open();
obj.write(str);
obj.close();
obj.body.style.color = KE_MENU_TEXT_COLOR;
obj.body.style.backgroundColor = KE_MENU_BG_COLOR;
obj.body.style.margin = 0;
obj.body.scroll = 'no';
}
function KindDrawTableSelected(i, j)
{
var text = i.toString(10) + ' by ' + j.toString(10) + ' Table';
document.getElementById('tableLocation').innerHTML = text;
var num = 10;
for (m = 1; m <= num; m++) {
for (n = 1; n <= num; n++) {
var obj = document.getElementById('kindTableTd' + m.toString(10) + '_' + n.toString(10) + '');
if (m <= i && n <= j) {
obj.style.backgroundColor = KE_MENU_SELECTED_COLOR;
} else {
obj.style.backgroundColor = '#FFFFFF';
}
}
}
}
function KindImageType(type)
{
if (type == 1) {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'block';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').value = 'http://';
} else {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'block';
}
KE_IMAGE_DOCUMENT.getElementById('imgPreview').innerHTML = " ";
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = 0;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = 0;
}
function KindImagePreview()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
if (type == 1) {
if (KE_BROWSER != 'IE') {
return false;
}
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
url = 'file:///' + file;
if (KindCheckImageFileType(url, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
var imgObj = KE_IMAGE_DOCUMENT.createElement("IMG");
imgObj.src = url;
var width = parseInt(imgObj.width);
var height = parseInt(imgObj.height);
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = width;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = height;
var rate = parseInt(width/height);
if (width >230 && height <= 230) {
width = 230;
height = parseInt(width/rate);
} else if (width <=230 && height > 230) {
height = 230;
width = parseInt(height*rate);
} else if (width >230 && height > 230) {
if (width >= height) {
width = 230;
height = parseInt(width/rate);
} else {
height = 230;
width = parseInt(height*rate);
}
}
imgObj.style.width = width;
imgObj.style.height = height;
var el = KE_IMAGE_DOCUMENT.getElementById('imgPreview');
if (el.hasChildNodes()) {
el.removeChild(el.childNodes[0]);
}
el.appendChild(imgObj);
return imgObj;
}
function KindDrawImageEnd()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
var width = KE_IMAGE_DOCUMENT.getElementById('imgWidth').value;
var height = KE_IMAGE_DOCUMENT.getElementById('imgHeight').value;
var border = KE_IMAGE_DOCUMENT.getElementById('imgBorder').value;
var title = KE_IMAGE_DOCUMENT.getElementById('imgTitle').value;
var align = KE_IMAGE_DOCUMENT.getElementById('imgAlign').value;
var hspace = KE_IMAGE_DOCUMENT.getElementById('imgHspace').value;
var vspace = KE_IMAGE_DOCUMENT.getElementById('imgVspace').value;
if (type == 1) {
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
if (KindCheckImageFileType(file, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
if (width.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_WIDTH']);
return false;
}
if (height.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HEIGHT']);
return false;
}
if (border.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_BORDER']);
return false;
}
if (hspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HSPACE']);
return false;
}
if (vspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_VSPACE']);
return false;
}
var fileName;
KindEditorForm.focus();
if (type == 1) {
fileName = KindGetFileName(file, "\\");
var fileExt = KindGetFileExt(fileName);
var dateObj = new Date();
var year = dateObj.getFullYear().toString(10);
var month = (dateObj.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = dateObj.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var ymd = year + month + day;
fileName = ymd + dateObj.getTime().toString(10) + '.' + fileExt;
KE_IMAGE_DOCUMENT.getElementById('fileName').value = fileName;
} else {
KindInsertImage(url, width, height, border, title, align, hspace, vspace);
}
}
function KindInsertImage(url, width, height, border, title, align, hspace, vspace)
{
var element = document.createElement("img");
element.src = url;
if (width > 0) {
element.style.width = width;
}
if (height > 0) {
element.style.height = height;
}
if (align != "") {
element.align = align;
}
if (hspace > 0) {
element.hspace = hspace;
}
if (vspace > 0) {
element.vspace = vspace;
}
element.border = border;
element.alt = KindHtmlentities(title);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
KindReloadIframe();
}
function KindGetFlashHtmlTag(url)
{
var str = '<embed src="'+url+'" type="application/x-shockwave-flash" quality="high"></embed>';
return str;
}
function KindFlashPreview()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
var el = KE_FLASH_DOCUMENT.getElementById('flashPreview');
el.innerHTML = KindGetFlashHtmlTag(url);
}
function KindDrawFlashEnd()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
obj.type = "application/x-shockwave-flash";
obj.quality = "high";
KindInsertItem(obj);
KindDisableMenu();
}
function KindGetMediaHtmlTag(cmd, url)
{
var str = '<embed src="'+url+'" type="';
if (cmd == "KE_REAL") {
str += 'audio/x-pn-realaudio-plugin';
} else {
str += 'video/x-ms-asf-plugin';
}
str += '" width="230" height="230" loop="true" autostart="true">';
return str;
}
function KindMediaPreview(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
var el = mediaDocument.getElementById(cmd+'preview');
el.innerHTML = KindGetMediaHtmlTag(cmd, url);
}
function KindDrawMediaEnd(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
if (cmd == 'KE_REAL') {
obj.type = 'audio/x-pn-realaudio-plugin';
} else {
obj.type = 'video/x-ms-asf-plugin';
}
obj.loop = 'true';
obj.autostart = 'true';
KindInsertItem(obj);
KindDisableMenu(cmd);
}
function KindDrawLinkEnd()
{
var range;
var url = KE_LINK_DOCUMENT.getElementById('hyperLink').value;
var target = KE_LINK_DOCUMENT.getElementById('hyperLinkTarget').value;
if (url.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
KindEditorForm.focus();
KindSelect();
var element;
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
var el = document.createElement("a");
el.href = url;
if (target) {
el.target = target;
}
KE_RANGE.item(0).applyElement(el);
} else if (KE_SELECTION.type.toLowerCase() == 'text') {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.parentElement();
if (target) {
element.target = target;
}
}
} else {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.startContainer.previousSibling;
element.target = target;
if (target) {
element.target = target;
}
}
KindDisableMenu();
}
function KindSelection()
{
if (KE_BROWSER == 'IE') {
KE_SELECTION = KE_EDITFORM_DOCUMENT.selection;
KE_RANGE = KE_SELECTION.createRange();
KE_RANGE_TEXT = KE_RANGE.text;
} else {
KE_SELECTION = document.getElementById("KindEditorForm").contentWindow.getSelection();
KE_RANGE = KE_SELECTION.getRangeAt(0);
KE_RANGE_TEXT = KE_RANGE.toString();
}
}
function KindSelect()
{
if (KE_BROWSER == 'IE') {
KE_RANGE.select();
}
}
function KindInsertItem(insertNode)
{
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
KE_RANGE.item(0).outerHTML = insertNode.outerHTML;
} else {
KE_RANGE.pasteHTML(insertNode.outerHTML);
}
} else {
KE_SELECTION.removeAllRanges();
KE_RANGE.deleteContents();
var startRangeNode = KE_RANGE.startContainer;
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
if (startRangeNode.nodeType == 3 && insertNode.nodeType == 3) {
startRangeNode.insertData(startRangeOffset, insertNode.nodeValue);
newRange.setEnd(startRangeNode, startRangeOffset + insertNode.length);
newRange.setStart(startRangeNode, startRangeOffset + insertNode.length);
} else {
var afterNode;
if (startRangeNode.nodeType == 3) {
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(insertNode, afterNode);
startRangeNode.insertBefore(beforeNode, insertNode);
startRangeNode.removeChild(textNode);
} else {
if (startRangeNode.tagName.toLowerCase() == 'html') {
startRangeNode = startRangeNode.childNodes[0].nextSibling;
afterNode = startRangeNode.childNodes[0];
} else {
afterNode = startRangeNode.childNodes[startRangeOffset];
}
startRangeNode.insertBefore(insertNode, afterNode);
}
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
}
KE_SELECTION.addRange(newRange);
}
}
function KindExecuteValue(cmd, value)
{
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, value);
}
function KindSimpleExecute(cmd)
{
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, null);
KindDisableMenu();
}
function KindExecute(cmd, value)
{
switch (cmd)
{
case 'KE_SOURCE':
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
document.getElementById("KindCodeForm").value = KindHtmlToXhtml(KE_EDITFORM_DOCUMENT.body.innerHTML);
document.getElementById("KindEditorIframe").style.display = 'none';
document.getElementById("KindEditTextarea").style.display = 'block';
KindDisableToolbar(true);
} else {
KE_EDITFORM_DOCUMENT.body.innerHTML = KindClearScriptTag(document.getElementById("KindCodeForm").value);
document.getElementById("KindEditTextarea").style.display = 'none';
document.getElementById("KindEditorIframe").style.display = 'block';
KindDisableToolbar(false);
}
KindDisableMenu();
break;
case 'KE_PRINT':
KindSimpleExecute('print');
break;
case 'KE_UNDO':
KindSimpleExecute('undo');
break;
case 'KE_REDO':
KindSimpleExecute('redo');
break;
case 'KE_CUT':
KindSimpleExecute('cut');
break;
case 'KE_COPY':
KindSimpleExecute('copy');
break;
case 'KE_PASTE':
KindSimpleExecute('paste');
break;
case 'KE_SELECTALL':
KindSimpleExecute('selectall');
break;
case 'KE_SUBSCRIPT':
KindSimpleExecute('subscript');
break;
case 'KE_SUPERSCRIPT':
KindSimpleExecute('superscript');
break;
case 'KE_BOLD':
KindSimpleExecute('bold');
break;
case 'KE_ITALIC':
KindSimpleExecute('italic');
break;
case 'KE_UNDERLINE':
KindSimpleExecute('underline');
break;
case 'KE_STRIKE':
KindSimpleExecute('strikethrough');
break;
case 'KE_JUSTIFYLEFT':
KindSimpleExecute('justifyleft');
break;
case 'KE_JUSTIFYCENTER':
KindSimpleExecute('justifycenter');
break;
case 'KE_JUSTIFYRIGHT':
KindSimpleExecute('justifyright');
break;
case 'KE_JUSTIFYFULL':
KindSimpleExecute('justifyfull');
break;
case 'KE_NUMBEREDLIST':
KindSimpleExecute('insertorderedlist');
break;
case 'KE_UNORDERLIST':
KindSimpleExecute('insertunorderedlist');
break;
case 'KE_INDENT':
KindSimpleExecute('indent');
break;
case 'KE_OUTDENT':
KindSimpleExecute('outdent');
break;
case 'KE_REMOVE':
KindSimpleExecute('removeformat');
break;
case 'KE_ZOOM':
KindDisplayMenu(cmd);
break;
case 'KE_ZOOM_END':
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.body.style.zoom = value;
KindDisableMenu();
break;
case 'KE_TITLE':
KindDisplayMenu(cmd);
break;
case 'KE_TITLE_END':
KindEditorForm.focus();
value = '<' + value + '>';
KindSelect();
KindExecuteValue('FormatBlock', value);
KindDisableMenu();
break;
case 'KE_FONTNAME':
KindDisplayMenu(cmd);
break;
case 'KE_FONTNAME_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('fontname', value);
KindDisableMenu();
break;
case 'KE_FONTSIZE':
KindDisplayMenu(cmd);
break;
case 'KE_FONTSIZE_END':
KindEditorForm.focus();
value = value.substr(0, 1);
KindSelect();
KindExecuteValue('fontsize', value);
KindDisableMenu();
break;
case 'KE_TEXTCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_TEXTCOLOR_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('ForeColor', value);
KindDisableMenu();
break;
case 'KE_BGCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_BGCOLOR_END':
KindEditorForm.focus();
if (KE_BROWSER == 'IE') {
KindSelect();
KindExecuteValue('BackColor', value);
} else {
var startRangeNode = KE_RANGE.startContainer;
if (startRangeNode.nodeType == 3) {
var parent = startRangeNode.parentNode;
var element = document.createElement("font");
element.style.backgroundColor = value;
element.appendChild(KE_RANGE.extractContents());
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
var afterNode;
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(element, afterNode);
startRangeNode.insertBefore(beforeNode, element);
startRangeNode.removeChild(textNode);
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
KE_SELECTION.addRange(newRange);
}
}
KindDisableMenu();
break;
case 'KE_ICON':
KindDisplayMenu(cmd);
break;
case 'KE_ICON_END':
KindEditorForm.focus();
var element = document.createElement("img");
element.src = value;
element.border = 0;
element.alt = "";
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_IMAGE':
KindDisplayMenu(cmd);
KindImageIframe.focus();
KE_IMAGE_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_FLASH':
KindDisplayMenu(cmd);
KindFlashIframe.focus();
KE_FLASH_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_MEDIA':
KindDisplayMenu(cmd);
KindMediaIframe.focus();
KE_MEDIA_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_REAL':
KindDisplayMenu(cmd);
KindRealIframe.focus();
KE_REAL_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_LINK':
KindDisplayMenu(cmd);
KindLinkIframe.focus();
KE_LINK_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_UNLINK':
KindSimpleExecute('unlink');
break;
case 'KE_SPECIALCHAR':
KindDisplayMenu(cmd);
break;
case 'KE_SPECIALCHAR_END':
KindEditorForm.focus();
KindSelect();
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_LAYER':
KindDisplayMenu(cmd);
break;
case 'KE_LAYER_END':
KindEditorForm.focus();
var element = document.createElement("div");
element.style.padding = "5px";
element.style.border = "1px solid #AAAAAA";
element.style.backgroundColor = value;
var childElement = document.createElement("div");
childElement.innerHTML = KE_LANG['INPUT_CONTENT'];
element.appendChild(childElement);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TABLE':
KindDisplayMenu(cmd);
break;
case 'KE_TABLE_END':
KindEditorForm.focus();
var location = value.split(',');
var element = document.createElement("table");
element.cellPadding = 0;
element.cellSpacing = 0;
element.border = 1;
element.style.width = "100px";
element.style.height = "100px";
for (var i = 0; i < location[0]; i++) {
var rowElement = element.insertRow(i);
for (var j = 0; j < location[1]; j++) {
var cellElement = rowElement.insertCell(j);
cellElement.innerHTML = " ";
}
}
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_HR':
KindDisplayMenu(cmd);
break;
case 'KE_HR_END':
KindEditorForm.focus();
var element = document.createElement("hr");
element.width = "100%";
element.color = value;
element.size = 1;
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_DATE':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var year = date.getFullYear().toString(10);
var month = (date.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = date.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var value = year + '-' + month + '-' + day;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TIME':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var hour = date.getHours().toString(10);
hour = hour.length < 2 ? '0' + hour : hour;
var minute = date.getMinutes().toString(10);
minute = minute.length < 2 ? '0' + minute : minute;
var second = date.getSeconds().toString(10);
second = second.length < 2 ? '0' + second : second;
var value = hour + ':' + minute + ':' + second;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_PREVIEW':
eval(KE_OBJ_NAME).data();
var newWin = window.open('', 'kindPreview','width=800,height=600,left=30,top=30,resizable=yes,scrollbars=yes');
KindWriteFullHtml(newWin.document, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
KindDisableMenu();
break;
case 'KE_ABOUT':
KindDisplayMenu(cmd);
break;
default:
break;
}
}
function KindDisableToolbar(flag)
{
if (flag == true) {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'design.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
if (KE_TOOLBAR_ICON[i][0] == 'KE_SOURCE' || KE_TOOLBAR_ICON[i][0] == 'KE_PREVIEW' || KE_TOOLBAR_ICON[i][0] == 'KE_ABOUT') {
continue;
}
el.style.visibility = 'hidden';
}
} else {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'source.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
el.style.visibility = 'visible';
KE_EDITFORM_DOCUMENT.designMode = 'On';
}
}
}
function KindCreateIcon(icon)
{
var str = '<img id="'+ icon[0] +'" src="' + KE_SKIN_PATH + icon[1] + '" alt="' + icon[2] + '" title="' + icon[2] +
'" align="absmiddle" style="border:1px solid ' + KE_TOOLBAR_BG_COLOR +';cursor:pointer;height:20px;';
str += '" onclick="javascript:KindExecute(\''+ icon[0] +'\');" '+
'onmouseover="javascript:this.style.border=\'1px solid ' + KE_MENU_BORDER_COLOR + '\';" ' +
'onmouseout="javascript:this.style.border=\'1px solid ' + KE_TOOLBAR_BG_COLOR + '\';" ';
str += '>';
return str;
}
function KindCreateToolbar()
{
var htmlData = '<table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
if (KE_EDITOR_TYPE == 'full') {
for (i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_TOP_TOOLBAR_ICON[i]) + '</td>';
}
htmlData += '</tr></table><table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
for (i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_BOTTOM_TOOLBAR_ICON[i]) + '</td>';
}
} else {
for (i = 0; i < KE_SIMPLE_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_SIMPLE_TOOLBAR_ICON[i]) + '</td>';
}
}
htmlData += '</tr></table>';
return htmlData;
}
function KindWriteFullHtml(documentObj, content)
{
var editHtmlData = '';
editHtmlData += '<html>\r\n<head>\r\n<title>KindEditor</title>\r\n';
editHtmlData += '<link href="'+KE_CSS_PATH+'" rel="stylesheet" type="text/css">\r\n</head>\r\n<body>\r\n';
editHtmlData += content;
editHtmlData += '\r\n</body>\r\n</html>\r\n';
documentObj.open();
documentObj.write(editHtmlData);
documentObj.close();
}
function KindEditor(objName)
{
this.objName = objName;
this.hiddenName = objName;
this.siteDomain;
this.editorType;
this.safeMode;
this.uploadMode;
this.editorWidth;
this.editorHeight;
this.skinPath;
this.iconPath;
this.imageAttachPath;
this.imageUploadCgi;
this.cssPath;
this.menuBorderColor;
this.menuBgColor;
this.menuTextColor;
this.menuSelectedColor;
this.toolbarBorderColor;
this.toolbarBgColor;
this.formBorderColor;
this.formBgColor;
this.buttonColor;
this.init = function()
{
if (this.siteDomain) KE_SITE_DOMAIN = this.siteDomain;
if (this.editorType) KE_EDITOR_TYPE = this.editorType.toLowerCase();
if (this.safeMode) KE_SAFE_MODE = this.safeMode;
if (this.uploadMode) KE_UPLOAD_MODE = this.uploadMode;
if (this.editorWidth) KE_WIDTH = this.editorWidth;
if (this.editorHeight) KE_HEIGHT = this.editorHeight;
if (this.skinPath) KE_SKIN_PATH = this.skinPath;
if (this.iconPath) KE_ICON_PATH = this.iconPath;
if (this.imageAttachPath) KE_IMAGE_ATTACH_PATH = this.imageAttachPath;
if (this.imageUploadCgi) KE_IMAGE_UPLOAD_CGI = this.imageUploadCgi;
if (this.cssPath) KE_CSS_PATH = this.cssPath;
if (this.menuBorderColor) KE_MENU_BORDER_COLOR = this.menuBorderColor;
if (this.menuBgColor) KE_MENU_BG_COLOR = this.menuBgColor;
if (this.menuTextColor) KE_MENU_TEXT_COLOR = this.menuTextColor;
if (this.menuSelectedColor) KE_MENU_SELECTED_COLOR = this.menuSelectedColor;
if (this.toolbarBorderColor) KE_TOOLBAR_BORDER_COLOR = this.toolbarBorderColor;
if (this.toolbarBgColor) KE_TOOLBAR_BG_COLOR = this.toolbarBgColor;
if (this.formBorderColor) KE_FORM_BORDER_COLOR = this.formBorderColor;
if (this.formBgColor) KE_FORM_BG_COLOR = this.formBgColor;
if (this.buttonColor) KE_BUTTON_COLOR = this.buttonColor;
KE_OBJ_NAME = this.objName;
KE_BROWSER = KindGetBrowser();
KE_TOOLBAR_ICON = Array();
for (var i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_TOP_TOOLBAR_ICON[i]);
}
for (var i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_BOTTOM_TOOLBAR_ICON[i]);
}
}
this.show = function()
{
this.init();
var widthStyle = 'width:' + KE_WIDTH + ';';
var widthArr = KE_WIDTH.match(/(\d+)([px%]{1,2})/);
var iframeWidthStyle = 'width:' + (parseInt(widthArr[1]) - 2).toString(10) + widthArr[2] + ';';
var heightStyle = 'height:' + KE_HEIGHT + ';';
var heightArr = KE_HEIGHT.match(/(\d+)([px%]{1,2})/);
var iframeHeightStyle = 'height:' + (parseInt(heightArr[1]) - 3).toString(10) + heightArr[2] + ';';
if (KE_BROWSER == '') {
var htmlData = '<div id="KindEditTextarea" style="' + widthStyle + heightStyle + '">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + widthStyle + heightStyle +
'padding:0;margin:0;border:1px solid '+ KE_FORM_BORDER_COLOR +
';font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';">' + document.getElementsByName(this.hiddenName)[0].value + '</textarea></div>';
document.open();
document.write(htmlData);
document.close();
return;
}
var htmlData = '<div style="font-family:'+KE_FONT_FAMILY+';">';
htmlData += '<div style="'+widthStyle+';border:1px solid ' + KE_TOOLBAR_BORDER_COLOR + ';background-color:'+ KE_TOOLBAR_BG_COLOR +'">';
htmlData += KindCreateToolbar();
htmlData += '</div><div id="KindEditorIframe" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';border-top:0;">' +
'<iframe name="KindEditorForm" id="KindEditorForm" frameborder="0" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;"></iframe></div>';
if (KE_EDITOR_TYPE == 'full') {
htmlData += '<div id="KindEditTextarea" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';background-color:'+
KE_FORM_BG_COLOR +';border-top:0;display:none;">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';" onclick="javascirit:parent.KindDisableMenu();"></textarea></div>';
}
htmlData += '</div>';
for (var i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
if (KE_POPUP_MENU_TABLE[i] == 'KE_IMAGE') {
htmlData += '<span id="InsertIframe">';
}
htmlData += KindPopupMenu(KE_POPUP_MENU_TABLE[i]);
if (KE_POPUP_MENU_TABLE[i] == 'KE_REAL') {
htmlData += '</span>';
}
}
document.open();
document.write(htmlData);
document.close();
if (KE_BROWSER == 'IE') {
KE_EDITFORM_DOCUMENT = document.frames("KindEditorForm").document;
} else {
KE_EDITFORM_DOCUMENT = document.getElementById('KindEditorForm').contentDocument;
}
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
KindDrawIframe('KE_LINK');
KE_EDITFORM_DOCUMENT.designMode = 'On';
KindWriteFullHtml(KE_EDITFORM_DOCUMENT, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
var el = KE_EDITFORM_DOCUMENT.body;
if (KE_EDITFORM_DOCUMENT.addEventListener){
KE_EDITFORM_DOCUMENT.addEventListener('click', KindDisableMenu, false);
} else if (el.attachEvent){
el.attachEvent('onclick', KindDisableMenu);
}
}
this.data = function()
{
var htmlResult;
if (KE_BROWSER == '') {
htmlResult = document.getElementById("KindCodeForm").value;
} else {
if (KE_EDITOR_TYPE == 'full') {
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
} else {
htmlResult = document.getElementById("KindCodeForm").value;
}
} else {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
}
}
KindDisableMenu();
htmlResult = KindHtmlToXhtml(htmlResult);
htmlResult = KindClearScriptTag(htmlResult);
document.getElementsByName(this.hiddenName)[0].value = htmlResult;
return htmlResult;
}
}
| JavaScript |
/*
Textile Editor v0.2
created by: dave olsen, wvu web services
created on: march 17, 2007
project page: slateinfo.blogs.wvu.edu
inspired by:
- Patrick Woods, http://www.hakjoon.com/code/38/textile-quicktags-redirect &
- Alex King, http://alexking.org/projects/js-quicktags
features:
- supports: IE7, FF2, Safari2
- ability to use "simple" vs. "extended" editor
- supports all block elements in textile except footnote
- supports all block modifier elements in textile
- supports simple ordered and unordered lists
- supports most of the phrase modifiers, very easy to add the missing ones
- supports multiple-paragraph modification
- can have multiple "editors" on one page, access key use in this environment is flaky
- access key support
- select text to add and remove tags, selection stays highlighted
- seamlessly change between tags and modifiers
- doesn't need to be in the body onload tag
- can supply your own, custom IDs for the editor to be drawn around
todo:
- a clean way of providing image and link inserts
- get the selection to properly show in IE
more on textile:
- Textism, http://www.textism.com/tools/textile/index.php
- Textile Reference, http://hobix.com/textile/
*/
// Define Button Object
function TextileEditorButton(id, display, tagStart, tagEnd, access, title, sve, open) {
this.id = id; // used to name the toolbar button
this.display = display; // label on button
this.tagStart = tagStart; // open tag
this.tagEnd = tagEnd; // close tag
this.access = access; // set to -1 if tag does not need to be closed
this.title = title; // sets the title attribute of the button to give 'tool tips'
this.sve = sve; // sve = simple vs. extended. add an 's' to make it show up in the simple toolbar
this.open = open; // set to -1 if tag does not need to be closed
this.standard = true; // this is a standard button
}
function TextileEditorButtonSeparator(sve) {
this.separator = true;
this.sve = sve;
}
var TextileEditor = Class.create();
TextileEditor.buttons = new Array();
TextileEditor.Methods = {
// class methods
// create the toolbar (edToolbar)
initialize: function(canvas, view) {
var toolbar = document.createElement("div");
toolbar.id = "textile-toolbar-" + canvas;
toolbar.className = 'textile-toolbar';
this.canvas = document.getElementById(canvas);
this.canvas.parentNode.insertBefore(toolbar, this.canvas);
this.openTags = new Array();
// Create the local Button array by assigning theButtons array to edButtons
var edButtons = new Array();
edButtons = this.buttons;
var standardButtons = new Array();
for(var i = 0; i < edButtons.length; i++) {
var thisButton = this.prepareButton(edButtons[i]);
if (view == 's') {
if (edButtons[i].sve == 's') {
toolbar.appendChild(thisButton);
standardButtons.push(thisButton);
}
} else {
if (typeof thisButton == 'string') {
toolbar.innerHTML += thisButton;
} else {
toolbar.appendChild(thisButton);
standardButtons.push(thisButton);
}
}
} // end for
var te = this;
$A(toolbar.getElementsByTagName('button')).each(function(button) {
if (!button.onclick) {
button.onclick = function() { te.insertTag(button); return false; }
} // end if
button.tagStart = button.getAttribute('tagStart');
button.tagEnd = button.getAttribute('tagEnd');
button.open = button.getAttribute('open');
button.textile_editor = te;
button.canvas = te.canvas;
});
}, // end initialize
// draw individual buttons (edShowButton)
prepareButton: function(button) {
if (button.separator) {
var theButton = document.createElement('span');
theButton.className = 'ed_sep';
return theButton;
}
if (button.standard) {
var theButton = document.createElement("button");
theButton.id = button.id;
theButton.setAttribute('class', 'standard');
theButton.setAttribute('tagStart', button.tagStart);
theButton.setAttribute('tagEnd', button.tagEnd);
theButton.setAttribute('open', button.open);
var img = document.createElement('img');
img.src = '/images/textile-editor/' + button.display;
theButton.appendChild(img);
} else {
return button;
} // end if !custom
theButton.accessKey = button.access;
theButton.title = button.title;
return theButton;
}, // end prepareButton
// if clicked, no selected text, tag not open highlight button
// (edAddTag)
addTag: function(button) {
if (button.tagEnd != '') {
this.openTags[this.openTags.length] = button;
//var el = document.getElementById(button.id);
//el.className = 'selected';
button.className = 'selected';
}
}, // end addTag
// if clicked, no selected text, tag open lowlight button
// (edRemoveTag)
removeTag: function(button) {
for (i = 0; i < this.openTags.length; i++) {
if (this.openTags[i] == button) {
this.openTags.splice(button, 1);
//var el = document.getElementById(button.id);
//el.className = 'unselected';
button.className = 'unselected';
}
}
}, // end removeTag
// see if there are open tags. for the remove tag bit...
// (edCheckOpenTags)
checkOpenTags: function(button) {
var tag = 0;
for (i = 0; i < this.openTags.length; i++) {
if (this.openTags[i] == button) {
tag++;
}
}
if (tag > 0) {
return true; // tag found
}
else {
return false; // tag not found
}
}, // end checkOpenTags
// insert the tag. this is the bulk of the code.
// (edInsertTag)
insertTag: function(button, tagStart, tagEnd) {
var myField = button.canvas;
myField.focus();
if (tagStart) {
button.tagStart = tagStart;
button.tagEnd = tagEnd ? tagEnd : '\n';
}
var textSelected = false;
var finalText = '';
var FF = false;
// grab the text that's going to be manipulated, by browser
if (document.selection) { // IE support
sel = document.selection.createRange();
// set-up the text vars
var beginningText = '';
var followupText = '';
var selectedText = sel.text;
// check if text has been selected
if (sel.text.length > 0) {
textSelected = true;
}
// set-up newline regex's so we can swap tags across multiple paragraphs
var newlineReplaceRegexClean = /\r\n\s\n/g;
var newlineReplaceRegexDirty = '\\r\\n\\s\\n';
var newlineReplaceClean = '\r\n\n';
}
else if (myField.selectionStart || myField.selectionStart == '0') { // MOZ/FF/NS/S support
// figure out cursor and selection positions
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
var cursorPos = endPos;
var scrollTop = myField.scrollTop;
FF = true; // note that is is a FF/MOZ/NS/S browser
// set-up the text vars
var beginningText = myField.value.substring(0, startPos);
var followupText = myField.value.substring(endPos, myField.value.length);
// check if text has been selected
if (startPos != endPos) {
textSelected = true;
var selectedText = myField.value.substring(startPos, endPos);
}
// set-up newline regex's so we can swap tags across multiple paragraphs
var newlineReplaceRegexClean = /\n\n/g;
var newlineReplaceRegexDirty = '\\n\\n';
var newlineReplaceClean = '\n\n';
}
// if there is text that has been highlighted...
if (textSelected) {
// set-up some defaults for how to handle bad new line characters
var newlineStart = '';
var newlineStartPos = 0;
var newlineEnd = '';
var newlineEndPos = 0;
var newlineFollowup = '';
// set-up some defaults for how to handle placing the beginning and end of selection
var posDiffPos = 0;
var posDiffNeg = 0;
var mplier = 1;
// remove newline from the beginning of the selectedText.
if (selectedText.match(/^\n/)) {
selectedText = selectedText.replace(/^\n/,'');
newlineStart = '\n';
newlineStartpos = 1;
}
// remove newline from the end of the selectedText.
if (selectedText.match(/\n$/g)) {
selectedText = selectedText.replace(/\n$/g,'');
newlineEnd = '\n';
newlineEndPos = 1;
}
// no clue, i'm sure it made sense at the time i wrote it
if (followupText.match(/^\n/)) {
newlineFollowup = '';
}
else {
newlineFollowup = '\n\n';
}
// first off let's check if the user is trying to mess with lists
if ((button.tagStart == ' * ') || (button.tagStart == ' # ')) {
listItems = 0; // sets up a default to be able to properly manipulate final selection
// set-up all of the regex's
re_start = new RegExp('^ (\\*|\\#) ','g');
if (button.tagStart == ' # ') {
re_tag = new RegExp(' \\# ','g'); // because of JS regex stupidity i need an if/else to properly set it up, could have done it with a regex replace though
}
else {
re_tag = new RegExp(' \\* ','g');
}
re_replace = new RegExp(' (\\*|\\#) ','g');
// try to remove bullets in text copied from ms word **Mac Only!**
re_word_bullet_m_s = new RegExp('• ','g'); // mac/safari
re_word_bullet_m_f = new RegExp('∑ ','g'); // mac/firefox
selectedText = selectedText.replace(re_word_bullet_m_s,'').replace(re_word_bullet_m_f,'');
// if the selected text starts with one of the tags we're working with...
if (selectedText.match(re_start)) {
// if tag that begins the selection matches the one clicked, remove them all
if (selectedText.match(re_tag)) {
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_replace,'')
+ newlineEnd
+ followupText;
if (matches = selectedText.match(/ (\*|\#) /g)) {
listItems = matches.length;
}
posDiffNeg = listItems*3; // how many list items were there because that's 3 spaces to remove from final selection
}
// else replace the current tag type with the selected tag type
else {
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_replace,button.tagStart)
+ newlineEnd
+ followupText;
}
}
// else try to create the list type
// NOTE: the items in a list will only be replaced if a newline starts with some character, not a space
else {
finalText = beginningText
+ newlineStart
+ button.tagStart
+ selectedText.replace(newlineReplaceRegexClean,newlineReplaceClean + button.tagStart).replace(/\n(\S)/g,'\n' + button.tagStart + '$1')
+ newlineEnd
+ followupText;
if (matches = selectedText.match(/\n(\S)/g)) {
listItems = matches.length;
}
posDiffPos = 3 + listItems*3;
}
}
// now lets look and see if the user is trying to muck with a block or block modifier
else if (button.tagStart.match(/^(h1|h2|h3|h4|h5|h6|bq|p|\>|\<\>|\<|\=|\(|\))/g)) {
var insertTag = '';
var insertModifier = '';
var tagPartBlock = '';
var tagPartModifier = '';
var tagPartModifierOrig = ''; // ugly hack but it's late
var drawSwitch = '';
var captureIndentStart = false;
var captureListStart = false;
var periodAddition = '\\. ';
var periodAdditionClean = '. ';
var listItemsAddition = 0;
var re_list_items = new RegExp('(\\*+|\\#+)','g'); // need this regex later on when checking indentation of lists
var re_block_modifier = new RegExp('^(h1|h2|h3|h4|h5|h6|bq|p| [\\*]{1,} | [\\#]{1,} |)(\\>|\\<\\>|\\<|\\=|[\\(]{1,}|[\\)]{1,6}|)','g');
if (tagPartMatches = re_block_modifier.exec(selectedText)) {
tagPartBlock = tagPartMatches[1];
tagPartModifier = tagPartMatches[2];
tagPartModifierOrig = tagPartMatches[2];
tagPartModifierOrig = tagPartModifierOrig.replace(/\(/g,"\\(");
}
// if tag already up is the same as the tag provided replace the whole tag
if (tagPartBlock == button.tagStart) {
insertTag = tagPartBlock + tagPartModifierOrig; // use Orig because it's escaped for regex
drawSwitch = 0;
}
// else if let's check to add/remove block modifier
else if ((tagPartModifier == button.tagStart) || (newm = tagPartModifier.match(/[\(]{2,}/g))) {
if ((button.tagStart == '(') || (button.tagStart == ')')) {
var indentLength = tagPartModifier.length;
if (button.tagStart == '(') {
indentLength = indentLength + 1;
}
else {
indentLength = indentLength - 1;
}
for (var i = 0; i < indentLength; i++) {
insertModifier = insertModifier + '(';
}
insertTag = tagPartBlock + insertModifier;
}
else {
if (button.tagStart == tagPartModifier) {
insertTag = tagPartBlock;
} // going to rely on the default empty insertModifier
else {
if (button.tagStart.match(/(\>|\<\>|\<|\=)/g)) {
insertTag = tagPartBlock + button.tagStart;
}
else {
insertTag = button.tagStart + tagPartModifier;
}
}
}
drawSwitch = 1;
}
// indentation of list items
else if (listPartMatches = re_list_items.exec(tagPartBlock)) {
var listTypeMatch = listPartMatches[1];
var indentLength = tagPartBlock.length - 2;
var listInsert = '';
if (button.tagStart == '(') {
indentLength = indentLength + 1;
}
else {
indentLength = indentLength - 1;
}
if (listTypeMatch.match(/[\*]{1,}/g)) {
var listType = '*';
var listReplace = '\\*';
}
else {
var listType = '#';
var listReplace = '\\#';
}
for (var i = 0; i < indentLength; i++) {
listInsert = listInsert + listType;
}
if (listInsert != '') {
insertTag = ' ' + listInsert + ' ';
}
else {
insertTag = '';
}
tagPartBlock = tagPartBlock.replace(/(\*|\#)/g,listReplace);
drawSwitch = 1;
captureListStart = true;
periodAddition = '';
periodAdditionClean = '';
if (matches = selectedText.match(/\n\s/g)) {
listItemsAddition = matches.length;
}
}
// must be a block modification e.g. p>. to p<.
else {
// if this is a block modification/addition
if (button.tagStart.match(/(h1|h2|h3|h4|h5|h6|bq|p)/g)) {
if (tagPartBlock == '') {
drawSwitch = 2;
}
else {
drawSwitch = 1;
}
insertTag = button.tagStart + tagPartModifier;
}
// else this is a modifier modification/addition
else {
if ((tagPartModifier == '') && (tagPartBlock != '')) {
drawSwitch = 1;
}
else if (tagPartModifier == '') {
drawSwitch = 2;
}
else {
drawSwitch = 1;
}
// if no tag part block but a modifier we need at least the p tag
if (tagPartBlock == '') {
tagPartBlock = 'p';
}
//make sure to swap out outdent
if (button.tagStart == ')') {
tagPartModifier = '';
}
else {
tagPartModifier = button.tagStart;
captureIndentStart = true; // ugly hack to fix issue with proper selection handling
}
insertTag = tagPartBlock + tagPartModifier;
}
}
mplier = 0;
if (captureListStart || (tagPartModifier.match(/[\(\)]{1,}/g))) {
re_start = new RegExp(insertTag.escape + periodAddition,'g'); // for tags that mimic regex properties, parens + list tags
}
else {
re_start = new RegExp(insertTag + periodAddition,'g'); // for tags that don't, why i can't just escape everything i have no clue
}
re_old = new RegExp(tagPartBlock + tagPartModifierOrig + periodAddition,'g');
re_middle = new RegExp(newlineReplaceRegexDirty + insertTag.escape + periodAddition.escape,'g');
re_tag = new RegExp(insertTag.escape + periodAddition.escape,'g');
// *************************************************************************************************************************
// this is where everything gets swapped around or inserted, bullets and single options have their own if/else statements
// *************************************************************************************************************************
if ((drawSwitch == 0) || (drawSwitch == 1)) {
if (drawSwitch == 0) { // completely removing a tag
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_start,'').replace(re_middle,newlineReplaceClean)
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffNeg = insertTag.length + 2 + (mplier*4);
}
else { // modifying a tag, though we do delete bullets here
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_old,insertTag + periodAdditionClean)
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
// figure out the length of various elements to modify the selection position
if (captureIndentStart) { // need to double-check that this wasn't the first indent
tagPreviousLength = tagPartBlock.length;
tagCurrentLength = insertTag.length;
}
else if (captureListStart) { // if this is a list we're manipulating
if (button.tagStart == '(') { // if indenting
tagPreviousLength = listTypeMatch.length + 2;
tagCurrentLength = insertTag.length + listItemsAddition;
}
else if (insertTag.match(/(\*|\#)/g)) { // if removing but still has bullets
tagPreviousLength = insertTag.length + listItemsAddition;
tagCurrentLength = listTypeMatch.length;
}
else { // if removing last bullet
tagPreviousLength = insertTag.length + listItemsAddition;
tagCurrentLength = listTypeMatch.length - (3*listItemsAddition) - 1;
}
}
else { // everything else
tagPreviousLength = tagPartBlock.length + tagPartModifier.length;
tagCurrentLength = insertTag.length;
}
if (tagCurrentLength > tagPreviousLength) {
posDiffPos = (tagCurrentLength - tagPreviousLength) + (mplier*(tagCurrentLength - tagPreviousLength));
}
else {
posDiffNeg = (tagPreviousLength - tagCurrentLength) + (mplier*(tagPreviousLength - tagCurrentLength));
}
}
}
else { // for adding tags other then bullets (have their own statement)
finalText = beginningText
+ newlineStart
+ insertTag + '. '
+ selectedText.replace(newlineReplaceRegexClean,button.tagEnd + '\n' + insertTag + '. ')
+ newlineFollowup
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffPos = insertTag.length + 2 + (mplier*4);
}
}
// swap in and out the simple tags around a selection like bold
else {
mplier = 1; // the multiplier for the tag length
re_start = new RegExp('^\\' + button.tagStart,'g');
re_end = new RegExp('\\' + button.tagEnd + '$','g');
re_middle = new RegExp('\\' + button.tagEnd + newlineReplaceRegexDirty + '\\' + button.tagStart,'g');
if (selectedText.match(re_start) && selectedText.match(re_end)) {
finalText = beginningText
+ newlineStart
+ selectedText.replace(re_start,'').replace(re_end,'').replace(re_middle,newlineReplaceClean)
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffNeg = button.tagStart.length*mplier + button.tagEnd.length*mplier;
}
else {
finalText = beginningText
+ newlineStart
+ button.tagStart
+ selectedText.replace(newlineReplaceRegexClean,button.tagEnd + newlineReplaceClean + button.tagStart)
+ button.tagEnd
+ newlineEnd
+ followupText;
if (matches = selectedText.match(newlineReplaceRegexClean)) {
mplier = mplier + matches.length;
}
posDiffPos = (button.tagStart.length*mplier) + (button.tagEnd.length*mplier);
}
}
cursorPos += button.tagStart.length + button.tagEnd.length;
}
// just swap in and out single values, e.g. someone clicks b they'll get a *
else {
var buttonStart = '';
var buttonEnd = '';
var re_p = new RegExp('(\\<|\\>|\\=|\\<\\>|\\(|\\))','g');
var re_h = new RegExp('^(h1|h2|h3|h4|h5|h6|p|bq)','g');
if (!this.checkOpenTags(button) || button.tagEnd == '') { // opening tag
if (button.tagStart.match(re_h)) {
buttonStart = button.tagStart + '. ';
}
else {
buttonStart = button.tagStart;
}
if (button.tagStart.match(re_p)) { // make sure that invoking block modifiers don't do anything
finalText = beginningText
+ followupText;
cursorPos = startPos;
}
else {
finalText = beginningText
+ buttonStart
+ followupText;
this.addTag(button);
cursorPos = startPos + buttonStart.length;
}
}
else { // closing tag
if (button.tagStart.match(re_p)) {
buttonEnd = '\n\n';
}
else if (button.tagStart.match(re_h)) {
buttonEnd = '\n\n';
}
else {
buttonEnd = button.tagEnd
}
finalText = beginningText
+ button.tagEnd
+ followupText;
this.removeTag(button);
cursorPos = startPos + button.tagEnd.length;
}
}
// set the appropriate DOM value with the final text
if (FF == true) {
myField.value = finalText;
myField.scrollTop = scrollTop;
}
else {
sel.text = finalText;
}
// build up the selection capture, doesn't work in IE
if (textSelected) {
myField.selectionStart = startPos + newlineStartPos;
myField.selectionEnd = endPos + posDiffPos - posDiffNeg - newlineEndPos;
//alert('s: ' + myField.selectionStart + ' e: ' + myField.selectionEnd + ' sp: ' + startPos + ' ep: ' + endPos + ' pdp: ' + posDiffPos + ' pdn: ' + posDiffNeg)
}
else {
myField.selectionStart = cursorPos;
myField.selectionEnd = cursorPos;
}
} // end insertTag
}; // end class
// add class methods
Object.extend(TextileEditor, TextileEditor.Methods);
document.write('<script src="/javascripts/textile-editor-config.js" type="text/javascript"></script>'); | JavaScript |
function $(id) {
return document.getElementById(id);
}
function resizeup(obj) {
var newheight = parseInt($(obj).style.height, 10) + 50;
$(obj).style.height = newheight + 'px';
}
function resizedown(obj) {
var newheight = parseInt($(obj).style.height, 10) - 50;
if(newheight > 0) {
$(obj).style.height = newheight + 'px';
}
}
function addattachfrom() {
var newnode = $('attachbodyhidden').firstChild.cloneNode(true);
$('attachbody').appendChild(newnode);
}
function removeattachfrom() {
$('attachbody').childNodes.length > 1 && $('attachbody').lastChild ? $('attachbody').removeChild($('attachbody').lastChild) : 0;
}
function checkall(form) {
for (var i=0;i<form.elements.length;i++) {
var e = form.elements[i];
if (e.name != 'chkall')
e.checked = form.chkall.checked;
}
} | JavaScript |
/**
* WYSIWYG HTML Editor for Internet
*
* @author Roddy <luolonghao@gmail.com>
* @version 2.5.3
*/
var KE_VERSION = "2.5.4";
var KE_EDITOR_TYPE = "full"; //full or simple
var KE_SAFE_MODE = false; // true or false
var KE_UPLOAD_MODE = true; // true or false
var KE_FONT_FAMILY = "Courier New";
var KE_WIDTH = "700px";
var KE_HEIGHT = "400px";
var KE_SITE_DOMAIN = "";
var KE_SKIN_PATH = "./skins/default/";
var KE_ICON_PATH = "./icons/";
var KE_IMAGE_ATTACH_PATH = "./attached/";
var KE_IMAGE_UPLOAD_CGI = "./upload_cgi/upload.php";
var KE_CSS_PATH = "/editor/common.css";
var KE_MENU_BORDER_COLOR = '#AAAAAA';
var KE_MENU_BG_COLOR = '#EFEFEF';
var KE_MENU_TEXT_COLOR = '#222222';
var KE_MENU_SELECTED_COLOR = '#CCCCCC';
var KE_TOOLBAR_BORDER_COLOR = '#DDDDDD';
var KE_TOOLBAR_BG_COLOR = '#EFEFEF';
var KE_FORM_BORDER_COLOR = '#DDDDDD';
var KE_FORM_BG_COLOR = '#FFFFFF';
var KE_BUTTON_COLOR = '#AAAAAA';
var KE_LANG = {
INPUT_URL : "请输入正确的URL地址。",
SELECT_IMAGE : "请选择图片。",
INVALID_IMAGE : "只能选择GIF,JPG,PNG,BMP格式的图片,请重新选择。",
INVALID_FLASH : "只能选择SWF格式的文件,请重新选择。",
INVALID_MEDIA : "只能选择MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF格式的文件,请重新选择。",
INVALID_REAL : "只能选择RM,RMVB格式的文件,请重新选择。",
INVALID_WIDTH : "宽度不是数字,请重新输入。",
INVALID_HEIGHT : "高度不是数字,请重新输入。",
INVALID_BORDER : "边框不是数字,请重新输入。",
INVALID_HSPACE : "横隔不是数字,请重新输入。",
INVALID_VSPACE : "竖隔不是数字,请重新输入。",
INPUT_CONTENT : "请输入内容",
TITLE : "描述",
WIDTH : "宽",
HEIGHT : "高",
BORDER : "边",
ALIGN : "对齐方式",
HSPACE : "横隔",
VSPACE : "竖隔",
CONFIRM : "确定",
CANCEL : "取消",
PREVIEW : "预览",
LISTENING : "试听",
LOCAL : "本地",
REMOTE : "远程",
NEW_WINDOW : "新窗口",
CURRENT_WINDOW : "当前窗口",
TARGET : "目标",
ABOUT : "访问技术支持网站",
SUBJECT : "标题"
}
var KE_FONT_NAME = Array(
Array('SimSun', '宋体'),
Array('SimHei', '黑体'),
Array('FangSong_GB2312', '仿宋体'),
Array('KaiTi_GB2312', '楷体'),
Array('NSimSun', '新宋体'),
Array('Arial', 'Arial'),
Array('Arial Black', 'Arial Black'),
Array('Times New Roman', 'Times New Roman'),
Array('Courier New', 'Courier New'),
Array('Tahoma', 'Tahoma'),
Array('Verdana', 'Verdana'),
Array('GulimChe', 'GulimChe'),
Array('MS Gothic', 'MS Gothic')
);
var KE_SPECIAL_CHARACTER = Array(
'§','№','☆','★','○','●','◎','◇','◆','□','℃','‰','■','△','▲','※',
'→','←','↑','↓','〓','¤','°','#','&','@','\','︿','_',' ̄','―','α',
'β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ',
'σ','τ','υ','φ','χ','ψ','ω','≈','≡','≠','=','≤','≥','<','>','≮',
'≯','∷','±','+','-','×','÷','/','∫','∮','∝','∞','∧','∨','∑','∏',
'∪','∩','∈','∵','∴','⊥','∥','∠','⌒','⊙','≌','∽','〖','〗',
'【','】','(',')','[',']'
);
var KE_TOP_TOOLBAR_ICON = Array(
Array('KE_SOURCE', 'source.gif', '视图转换'),
Array('KE_PREVIEW', 'preview.gif', '预览'),
Array('KE_ZOOM', 'zoom.gif', '显示比例'),
Array('KE_PRINT', 'print.gif', '打印'),
Array('KE_UNDO', 'undo.gif', '回退'),
Array('KE_REDO', 'redo.gif', '前进'),
Array('KE_CUT', 'cut.gif', '剪切'),
Array('KE_COPY', 'copy.gif', '复制'),
Array('KE_PASTE', 'paste.gif', '粘贴'),
Array('KE_SELECTALL', 'selectall.gif', '全选'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_JUSTIFYFULL', 'justifyfull.gif', '两端对齐'),
Array('KE_NUMBEREDLIST', 'numberedlist.gif', '编号'),
Array('KE_UNORDERLIST', 'unorderedlist.gif', '项目符号'),
Array('KE_INDENT', 'indent.gif', '减少缩进'),
Array('KE_OUTDENT', 'outdent.gif', '增加缩进'),
Array('KE_SUBSCRIPT', 'subscript.gif', '下标'),
Array('KE_SUPERSCRIPT', 'superscript.gif', '上标'),
Array('KE_DATE', 'date.gif', '日期'),
Array('KE_TIME', 'time.gif', '时间')
);
var KE_BOTTOM_TOOLBAR_ICON = Array(
Array('KE_TITLE', 'title.gif', '标题'),
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_STRIKE', 'strikethrough.gif', '删除线'),
Array('KE_REMOVE', 'removeformat.gif', '删除格式'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_FLASH', 'flash.gif', 'Flash'),
Array('KE_MEDIA', 'media.gif', 'Windows Media Player'),
Array('KE_REAL', 'real.gif', 'Real Player'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_TABLE', 'table.gif', '表格'),
Array('KE_SPECIALCHAR', 'specialchar.gif', '特殊字符'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_UNLINK', 'unlink.gif', '删除超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_SIMPLE_TOOLBAR_ICON = Array(
Array('KE_FONTNAME', 'font.gif', '字体'),
Array('KE_FONTSIZE', 'fontsize.gif', '文字大小'),
Array('KE_TEXTCOLOR', 'textcolor.gif', '文字颜色'),
Array('KE_BGCOLOR', 'bgcolor.gif', '文字背景'),
Array('KE_BOLD', 'bold.gif', '粗体'),
Array('KE_ITALIC', 'italic.gif', '斜体'),
Array('KE_UNDERLINE', 'underline.gif', '下划线'),
Array('KE_JUSTIFYLEFT', 'justifyleft.gif', '左对齐'),
Array('KE_JUSTIFYCENTER', 'justifycenter.gif', '居中'),
Array('KE_JUSTIFYRIGHT', 'justifyright.gif', '右对齐'),
Array('KE_IMAGE', 'image.gif', '图片'),
Array('KE_LAYER', 'layer.gif', '层'),
Array('KE_HR', 'hr.gif', '横线'),
Array('KE_ICON', 'emoticons.gif', '笑脸'),
Array('KE_LINK', 'link.gif', '创建超级连接'),
Array('KE_ABOUT', 'about.gif', '关于')
);
var KE_TITLE_TABLE = Array(
Array('H1', KE_LANG['SUBJECT'] + ' 1'),
Array('H2', KE_LANG['SUBJECT'] + ' 2'),
Array('H3', KE_LANG['SUBJECT'] + ' 3'),
Array('H4', KE_LANG['SUBJECT'] + ' 4'),
Array('H5', KE_LANG['SUBJECT'] + ' 5'),
Array('H6', KE_LANG['SUBJECT'] + ' 6')
);
var KE_ZOOM_TABLE = Array('250%', '200%', '150%', '120%', '100%', '80%', '50%');
var KE_FONT_SIZE = Array(
Array(1,'8pt'),
Array(2,'10pt'),
Array(3,'12pt'),
Array(4,'14pt'),
Array(5,'18pt'),
Array(6,'24pt'),
Array(7,'36pt')
);
var KE_POPUP_MENU_TABLE = Array(
"KE_ZOOM", "KE_TITLE", "KE_FONTNAME", "KE_FONTSIZE", "KE_TEXTCOLOR", "KE_BGCOLOR",
"KE_LAYER", "KE_TABLE", "KE_HR", "KE_ICON", "KE_SPECIALCHAR", "KE_ABOUT",
"KE_IMAGE", "KE_FLASH", "KE_MEDIA", "KE_REAL", "KE_LINK"
);
var KE_COLOR_TABLE = Array(
"#FF0000", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#FF00FF", "#FFFFFF", "#F5F5F5", "#DCDCDC", "#FFFAFA",
"#D3D3D3", "#C0C0C0", "#A9A9A9", "#808080", "#696969", "#000000", "#2F4F4F", "#708090", "#778899", "#4682B4",
"#4169E1", "#6495ED", "#B0C4DE", "#7B68EE", "#6A5ACD", "#483D8B", "#191970", "#000080", "#00008B", "#0000CD",
"#1E90FF", "#00BFFF", "#87CEFA", "#87CEEB", "#ADD8E6", "#B0E0E6", "#F0FFFF", "#E0FFFF", "#AFEEEE", "#00CED1",
"#5F9EA0", "#48D1CC", "#00FFFF", "#40E0D0", "#20B2AA", "#008B8B", "#008080", "#7FFFD4", "#66CDAA", "#8FBC8F",
"#3CB371", "#2E8B57", "#006400", "#008000", "#228B22", "#32CD32", "#00FF00", "#7FFF00", "#7CFC00", "#ADFF2F",
"#98FB98", "#90EE90", "#00FF7F", "#00FA9A", "#556B2F", "#6B8E23", "#808000", "#BDB76B", "#B8860B", "#DAA520",
"#FFD700", "#F0E68C", "#EEE8AA", "#FFEBCD", "#FFE4B5", "#F5DEB3", "#FFDEAD", "#DEB887", "#D2B48C", "#BC8F8F",
"#A0522D", "#8B4513", "#D2691E", "#CD853F", "#F4A460", "#8B0000", "#800000", "#A52A2A", "#B22222", "#CD5C5C",
"#F08080", "#FA8072", "#E9967A", "#FFA07A", "#FF7F50", "#FF6347", "#FF8C00", "#FFA500", "#FF4500", "#DC143C",
"#FF0000", "#FF1493", "#FF00FF", "#FF69B4", "#FFB6C1", "#FFC0CB", "#DB7093", "#C71585", "#800080", "#8B008B",
"#9370DB", "#8A2BE2", "#4B0082", "#9400D3", "#9932CC", "#BA55D3", "#DA70D6", "#EE82EE", "#DDA0DD", "#D8BFD8",
"#E6E6FA", "#F8F8FF", "#F0F8FF", "#F5FFFA", "#F0FFF0", "#FAFAD2", "#FFFACD", "#FFF8DC", "#FFFFE0", "#FFFFF0",
"#FFFAF0", "#FAF0E6", "#FDF5E6", "#FAEBD7", "#FFE4C4", "#FFDAB9", "#FFEFD5", "#FFF5EE", "#FFF0F5", "#FFE4E1"
);
var KE_IMAGE_ALIGN_TABLE = Array(
"baseline", "top", "middle", "bottom", "texttop", "absmiddle", "absbottom", "left", "right"
);
var KE_OBJ_NAME;
var KE_SELECTION;
var KE_RANGE;
var KE_RANGE_TEXT;
var KE_EDITFORM_DOCUMENT;
var KE_IMAGE_DOCUMENT;
var KE_FLASH_DOCUMENT;
var KE_MEDIA_DOCUMENT;
var KE_REAL_DOCUMENT;
var KE_LINK_DOCUMENT;
var KE_BROWSER;
var KE_TOOLBAR_ICON;
function KindGetBrowser()
{
var browser = '';
var agentInfo = navigator.userAgent.toLowerCase();
if (agentInfo.indexOf("msie") > -1) {
var re = new RegExp("msie\\s?([\\d\\.]+)","ig");
var arr = re.exec(agentInfo);
if (parseInt(RegExp.$1) >= 5.5) {
browser = 'IE';
}
} else if (agentInfo.indexOf("firefox") > -1) {
browser = 'FF';
} else if (agentInfo.indexOf("netscape") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[temp1.length-1].split('/');
if (parseInt(temp2[1]) >= 7) {
browser = 'NS';
}
} else if (agentInfo.indexOf("gecko") > -1) {
browser = 'ML';
} else if (agentInfo.indexOf("opera") > -1) {
var temp1 = agentInfo.split(' ');
var temp2 = temp1[0].split('/');
if (parseInt(temp2[1]) >= 9) {
browser = 'OPERA';
}
}
return browser;
}
function KindGetFileName(file, separator)
{
var temp = file.split(separator);
var len = temp.length;
var fileName = temp[len-1];
return fileName;
}
function KindGetFileExt(fileName)
{
var temp = fileName.split(".");
var len = temp.length;
var fileExt = temp[len-1].toLowerCase();
return fileExt;
}
function KindCheckImageFileType(file, separator)
{
if (separator == "/" && file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, separator);
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'gif' && fileExt != 'jpg' && fileExt != 'png' && fileExt != 'bmp') {
alert(KE_LANG['INVALID_IMAGE']);
return false;
}
return true;
}
function KindCheckFlashFileType(file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (fileExt != 'swf') {
alert(KE_LANG['INVALID_FLASH']);
return false;
}
return true;
}
function KindCheckMediaFileType(cmd, file, separator)
{
if (file.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
var fileName = KindGetFileName(file, "/");
var fileExt = KindGetFileExt(fileName);
if (cmd == 'KE_REAL') {
if (fileExt != 'rm' && fileExt != 'rmvb') {
alert(KE_LANG['INVALID_REAL']);
return false;
}
} else {
if (fileExt != 'mp3' && fileExt != 'wav' && fileExt != 'wma' && fileExt != 'wmv' && fileExt != 'mid' && fileExt != 'avi' && fileExt != 'mpg' && fileExt != 'asf') {
alert(KE_LANG['INVALID_MEDIA']);
return false;
}
}
return true;
}
function KindHtmlToXhtml(str)
{
str = str.replace(/<br.*?>/gi, "<br />");
str = str.replace(/(<hr\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<img\s+[^>]*[^\/])(>)/gi, "$1 />");
str = str.replace(/(<\w+)(.*?>)/gi, function ($0,$1,$2) {
return($1.toLowerCase() + KindConvertAttribute($2));
}
);
str = str.replace(/(<\/\w+>)/gi, function ($0,$1) {
return($1.toLowerCase());
}
);
return str;
}
function KindConvertAttribute(str)
{
if (KE_SAFE_MODE == true) {
str = KindClearAttributeScriptTag(str);
}
return str;
}
function KindClearAttributeScriptTag(str)
{
var re = new RegExp("(\\son[a-z]+=)[\"']?[^>]*?[^\\\\\>][\"']?([\\s>])","ig");
str = str.replace(re, function ($0,$1,$2) {
return($1.toLowerCase() + "\"\"" + $2);
}
);
return str;
}
function KindClearScriptTag(str)
{
if (KE_SAFE_MODE == false) {
return str;
}
str = str.replace(/<(script.*?)>/gi, "[$1]");
str = str.replace(/<\/script>/gi, "[/script]");
return str;
}
function KindHtmlentities(str)
{
str = str.replace(/&/g,'&');
str = str.replace(/</g,'<');
str = str.replace(/>/g,'>');
str = str.replace(/"/g,'"');
return str;
}
function KindGetTop(id)
{
var top = 28;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
top += eval("obj" + tmp).offsetTop;
}
return top;
}
function KindGetLeft(id)
{
var left = 2;
var tmp = '';
var obj = document.getElementById(id);
while (eval("obj" + tmp).tagName != "BODY") {
tmp += ".offsetParent";
left += eval("obj" + tmp).offsetLeft;
}
return left;
}
function KindDisplayMenu(cmd)
{
KindEditorForm.focus();
if (cmd != 'KE_ABOUT') {
KindSelection();
}
KindDisableMenu();
var top, left;
top = KindGetTop(cmd);
left = KindGetLeft(cmd);
if (cmd == 'KE_ABOUT') {
left -= 200;
} else if (cmd == 'KE_LINK') {
left -= 220;
}
document.getElementById('POPUP_'+cmd).style.top = top.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.left = left.toString(10) + 'px';
document.getElementById('POPUP_'+cmd).style.display = 'block';
}
function KindDisableMenu()
{
for (i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
document.getElementById('POPUP_'+KE_POPUP_MENU_TABLE[i]).style.display = 'none';
}
}
function KindReloadIframe()
{
var str = '';
str += KindPopupMenu('KE_IMAGE');
str += KindPopupMenu('KE_FLASH');
str += KindPopupMenu('KE_MEDIA');
str += KindPopupMenu('KE_REAL');
document.getElementById('InsertIframe').innerHTML = str;
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
}
function KindGetMenuCommonStyle()
{
var str = 'position:absolute;top:1px;left:1px;font-size:12px;color:'+KE_MENU_TEXT_COLOR+
';background-color:'+KE_MENU_BG_COLOR+';border:solid 1px '+KE_MENU_BORDER_COLOR+';z-index:1;display:none;';
return str;
}
function KindGetCommonMenu(cmd, content)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="'+KindGetMenuCommonStyle()+'">';
str += content;
str += '</div>';
return str;
}
function KindCreateColorTable(cmd, eventStr)
{
var str = '';
str += '<table cellpadding="0" cellspacing="2" border="0">';
for (i = 0; i < KE_COLOR_TABLE.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="width:12px;height:12px;border:1px solid #AAAAAA;font-size:1px;cursor:pointer;background-color:' +
KE_COLOR_TABLE[i] + ';" onmouseover="javascript:this.style.borderColor=\'#000000\';' + ((eventStr) ? eventStr : '') + '" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onclick="javascript:KindExecute(\''+cmd+'_END\', \'' + KE_COLOR_TABLE[i] + '\');"> </td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
}
function KindDrawColorTable(cmd)
{
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;padding:2px;'+KindGetMenuCommonStyle()+'">';
str += KindCreateColorTable(cmd);
str += '</div>';
return str;
}
function KindDrawMedia(cmd)
{
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="'+cmd+'preview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="'+cmd+'link" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['LISTENING']+'" onclick="javascript:parent.KindMediaPreview(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawMediaEnd(\''+cmd+'\');" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
return str;
}
function KindPopupMenu(cmd)
{
switch (cmd)
{
case 'KE_ZOOM':
var str = '';
for (i = 0; i < KE_ZOOM_TABLE.length; i++) {
str += '<div style="padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ZOOM_END\', \'' + KE_ZOOM_TABLE[i] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_ZOOM_TABLE[i] + '</div>';
}
str = KindGetCommonMenu('KE_ZOOM', str);
return str;
break;
case 'KE_TITLE':
var str = '';
for (i = 0; i < KE_TITLE_TABLE.length; i++) {
str += '<div style="width:140px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TITLE_END\', \'' + KE_TITLE_TABLE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';"><' + KE_TITLE_TABLE[i][0] + ' style="margin:2px;">' +
KE_TITLE_TABLE[i][1] + '</' + KE_TITLE_TABLE[i][0] + '></div>';
}
str = KindGetCommonMenu('KE_TITLE', str);
return str;
break;
case 'KE_FONTNAME':
var str = '';
for (i = 0; i < KE_FONT_NAME.length; i++) {
str += '<div style="font-family:' + KE_FONT_NAME[i][0] +
';padding:2px;width:160px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTNAME_END\', \'' + KE_FONT_NAME[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_NAME[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTNAME', str);
return str;
break;
case 'KE_FONTSIZE':
var str = '';
for (i = 0; i < KE_FONT_SIZE.length; i++) {
str += '<div style="font-size:' + KE_FONT_SIZE[i][1] +
';padding:2px;width:120px;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_FONTSIZE_END\', \'' + KE_FONT_SIZE[i][0] + '\');" ' +
'onmouseover="javascript:this.style.backgroundColor=\''+KE_MENU_SELECTED_COLOR+'\';" ' +
'onmouseout="javascript:this.style.backgroundColor=\''+KE_MENU_BG_COLOR+'\';">' +
KE_FONT_SIZE[i][1] + '</div>';
}
str = KindGetCommonMenu('KE_FONTSIZE', str);
return str;
break;
case 'KE_TEXTCOLOR':
var str = '';
str = KindDrawColorTable('KE_TEXTCOLOR');
return str;
break;
case 'KE_BGCOLOR':
var str = '';
str = KindDrawColorTable('KE_BGCOLOR');
return str;
break;
case 'KE_HR':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="hrPreview" style="margin:10px 2px 10px 2px;height:1px;border:0;font-size:0;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'hrPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_LAYER':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:160px;'+KindGetMenuCommonStyle()+'">';
str += '<div id="divPreview" style="margin:5px 2px 5px 2px;height:20px;border:1px solid #AAAAAA;font-size:1px;background-color:#FFFFFF;"></div>';
str += KindCreateColorTable(cmd, 'document.getElementById(\'divPreview\').style.backgroundColor = this.style.backgroundColor;');
str += '</div>';
return str;
break;
case 'KE_ICON':
var str = '';
var iconNum = 36;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < iconNum; i++) {
if (i == 0 || (i >= 6 && i%6 == 0)) {
str += '<tr>';
}
var num;
if ((i+1).toString(10).length < 2) {
num = '0' + (i+1);
} else {
num = (i+1).toString(10);
}
var iconUrl = KE_ICON_PATH + 'etc_' + num + '.gif';
str += '<td style="padding:2px;border:0;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_ICON_END\', \'' + iconUrl + '\');">' +
'<img src="' + iconUrl + '" style="border:1px solid #EEEEEE;" onmouseover="javascript:this.style.borderColor=\'#AAAAAA\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#EEEEEE\';">' + '</td>';
if (i >= 5 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_SPECIALCHAR':
var str = '';
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="2" style="'+KindGetMenuCommonStyle()+'">';
for (i = 0; i < KE_SPECIAL_CHARACTER.length; i++) {
if (i == 0 || (i >= 10 && i%10 == 0)) {
str += '<tr>';
}
str += '<td style="padding:2px;border:1px solid #AAAAAA;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_SPECIALCHAR_END\', \'' + KE_SPECIAL_CHARACTER[i] + '\');" ' +
'onmouseover="javascript:this.style.borderColor=\'#000000\';" ' +
'onmouseout="javascript:this.style.borderColor=\'#AAAAAA\';">' + KE_SPECIAL_CHARACTER[i] + '</td>';
if (i >= 9 && i%(i-1) == 0) {
str += '</tr>';
}
}
str += '</table>';
return str;
break;
case 'KE_TABLE':
var str = '';
var num = 10;
str += '<table id="POPUP_'+cmd+'" cellpadding="0" cellspacing="0" style="'+KindGetMenuCommonStyle()+'">';
for (i = 1; i <= num; i++) {
str += '<tr>';
for (j = 1; j <= num; j++) {
var value = i.toString(10) + ',' + j.toString(10);
str += '<td id="kindTableTd' + i.toString(10) + '_' + j.toString(10) +
'" style="width:15px;height:15px;background-color:#FFFFFF;border:1px solid #DDDDDD;cursor:pointer;" ' +
'onclick="javascript:KindExecute(\'KE_TABLE_END\', \'' + value + '\');" ' +
'onmouseover="javascript:KindDrawTableSelected(\''+i.toString(10)+'\', \''+j.toString(10)+'\');" ' +
'onmouseout="javascript:;"> </td>';
}
str += '</tr>';
}
str += '<tr><td colspan="10" id="tableLocation" style="text-align:center;height:20px;"></td></tr>';
str += '</table>';
return str;
break;
case 'KE_IMAGE':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindImageIframe" id="KindImageIframe" frameborder="0" style="width:250px;height:390px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_FLASH':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindFlashIframe" id="KindFlashIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_MEDIA':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindMediaIframe" id="KindMediaIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_REAL':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindRealIframe" id="KindRealIframe" frameborder="0" style="width:250px;height:300px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_LINK':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:250px;'+KindGetMenuCommonStyle()+'">';
str += '<iframe name="KindLinkIframe" id="KindLinkIframe" frameborder="0" style="width:250px;height:85px;padding:0;margin:0;border:0;">';
str += '</iframe></div>';
return str;
break;
case 'KE_ABOUT':
var str = '';
str += '<div id="POPUP_'+cmd+'" style="width:230px;'+KindGetMenuCommonStyle()+';padding:5px;">';
str += '<span style="margin-right:10px;">KindEditor ' + KE_VERSION + '</span>' +
'<a href="http://www.kindsoft.net/" target="_blank" style="color:#4169e1;" onclick="javascript:KindDisableMenu();">'+KE_LANG['ABOUT']+'</a><br />';
str += '</div>';
return str;
break;
default:
break;
}
}
function KindDrawIframe(cmd)
{
if (KE_BROWSER == 'IE') {
KE_IMAGE_DOCUMENT = document.frames("KindImageIframe").document;
KE_FLASH_DOCUMENT = document.frames("KindFlashIframe").document;
KE_MEDIA_DOCUMENT = document.frames("KindMediaIframe").document;
KE_REAL_DOCUMENT = document.frames("KindRealIframe").document;
KE_LINK_DOCUMENT = document.frames("KindLinkIframe").document;
} else {
KE_IMAGE_DOCUMENT = document.getElementById('KindImageIframe').contentDocument;
KE_FLASH_DOCUMENT = document.getElementById('KindFlashIframe').contentDocument;
KE_MEDIA_DOCUMENT = document.getElementById('KindMediaIframe').contentDocument;
KE_REAL_DOCUMENT = document.getElementById('KindRealIframe').contentDocument;
KE_LINK_DOCUMENT = document.getElementById('KindLinkIframe').contentDocument;
}
switch (cmd)
{
case 'KE_IMAGE':
var str = '';
str += '<div align="center">' +
'<form name="uploadForm" style="margin:0;padding:0;" method="post" enctype="multipart/form-data" ' +
'action="' + KE_IMAGE_UPLOAD_CGI + '" onsubmit="javascript:if(parent.KindDrawImageEnd()==false){return false;};">' +
'<input type="hidden" name="fileName" id="fileName" value="" />' +
'<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0" style="margin-bottom:3px;"><tr><td id="imgPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:50px;padding-left:5px;">';
if (KE_UPLOAD_MODE == true) {
str += '<select id="imageType" onchange="javascript:parent.KindImageType(this.value);document.getElementById(\''+cmd+'submitButton\').focus();"><option value="1" selected="selected">'+KE_LANG['LOCAL']+'</option><option value="2">'+KE_LANG['REMOTE']+'</option></select>';
} else {
str += KE_LANG['REMOTE'];
}
str += '</td><td style="width:200px;padding-bottom:3px;">';
if (KE_UPLOAD_MODE == true) {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;display:none;" />' +
'<input type="file" name="fileData" id="imgFile" size="14" style="border:1px solid #555555;" onclick="javascript:document.getElementById(\'imgLink\').value=\'http://\';" />';
} else {
str += '<input type="text" id="imgLink" value="http://" maxlength="255" style="width:95%;border:1px solid #555555;" />' +
'<input type="hidden" name="imageType" id="imageType" value="2"><input type="hidden" name="fileData" id="imgFile" value="" />';
}
str += '</td></tr><tr><td colspan="2" style="padding-bottom:3px;">' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="18%" style="padding:2px 2px 2px 5px;">'+KE_LANG['TITLE']+'</td><td width="82%"><input type="text" name="imgTitle" id="imgTitle" value="" maxlength="100" style="width:95%;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="10%" style="padding:2px 2px 2px 5px;">'+KE_LANG['WIDTH']+'</td><td width="23%"><input type="text" name="imgWidth" id="imgWidth" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['HEIGHT']+'</td><td width="23%"><input type="text" name="imgHeight" id="imgHeight" value="0" maxlength="4" style="width:40px;border:1px solid #555555;" /></td>' +
'<td width="10%" style="padding:2px;">'+KE_LANG['BORDER']+'</td><td width="23%"><input type="text" name="imgBorder" id="imgBorder" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'<table border="0" style="width:100%;font-size:12px;"><tr>' +
'<td width="39%" style="padding:2px 2px 2px 5px;"><select id="imgAlign" name="imgAlign"><option value="">'+KE_LANG['ALIGN']+'</option>';
for (var i = 0; i < KE_IMAGE_ALIGN_TABLE.length; i++) {
str += '<option value="' + KE_IMAGE_ALIGN_TABLE[i] + '">' + KE_IMAGE_ALIGN_TABLE[i] + '</option>';
}
str += '</select></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['HSPACE']+'</td><td width="15%"><input type="text" name="imgHspace" id="imgHspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td>' +
'<td width="15%" style="padding:2px;">'+KE_LANG['VSPACE']+'</td><td width="15%"><input type="text" name="imgVspace" id="imgVspace" value="0" maxlength="1" style="width:20px;border:1px solid #555555;" /></td></tr></table>' +
'</td></tr><tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindImagePreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table></form></div>';
KindDrawMenuIframe(KE_IMAGE_DOCUMENT, str);
break;
case 'KE_FLASH':
var str = '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td colspan="2"><table border="0"><tr><td id="flashPreview" style="width:240px;height:240px;border:1px solid #AAAAAA;background-color:#FFFFFF;" align="center" valign="middle"> </td></tr></table></td></tr>' +
'<tr><td style="width:40px;padding:5px;">'+KE_LANG['REMOTE']+'</td>' +
'<td style="width:210px;padding-bottom:5px;"><input type="text" id="flashLink" value="http://" style="width:190px;border:1px solid #555555;" /></td></tr>' +
'<tr><td colspan="2" style="margin:5px;padding-bottom:5px;" align="center">' +
'<input type="button" name="button" value="'+KE_LANG['PREVIEW']+'" onclick="javascript:parent.KindFlashPreview();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawFlashEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();parent.KindReloadIframe();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>' +
'</table>';
KindDrawMenuIframe(KE_FLASH_DOCUMENT, str);
break;
case 'KE_MEDIA':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_MEDIA_DOCUMENT, str);
break;
case 'KE_REAL':
var str = KindDrawMedia(cmd);
KindDrawMenuIframe(KE_REAL_DOCUMENT, str);
break;
case 'KE_LINK':
var str = '';
str += '<table cellpadding="0" cellspacing="0" style="width:100%;font-size:12px;">' +
'<tr><td style="width:50px;padding:5px;">URL</td>' +
'<td style="width:200px;padding-top:5px;padding-bottom:5px;"><input type="text" id="hyperLink" value="http://" style="width:190px;border:1px solid #555555;background-color:#FFFFFF;"></td>' +
'<tr><td style="padding:5px;">'+KE_LANG['TARGET']+'</td>' +
'<td style="padding-bottom:5px;"><select id="hyperLinkTarget"><option value="_blank" selected="selected">'+KE_LANG['NEW_WINDOW']+'</option><option value="">'+KE_LANG['CURRENT_WINDOW']+'</option></select></td></tr>' +
'<tr><td colspan="2" style="padding-bottom:5px;" align="center">' +
'<input type="submit" name="button" id="'+cmd+'submitButton" value="'+KE_LANG['CONFIRM']+'" onclick="javascript:parent.KindDrawLinkEnd();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /> ' +
'<input type="button" name="button" value="'+KE_LANG['CANCEL']+'" onclick="javascript:parent.KindDisableMenu();" style="border:1px solid #555555;background-color:'+KE_BUTTON_COLOR+';" /></td></tr>';
str += '</table>';
KindDrawMenuIframe(KE_LINK_DOCUMENT, str);
break;
default:
break;
}
}
function KindDrawMenuIframe(obj, str)
{
obj.open();
obj.write(str);
obj.close();
obj.body.style.color = KE_MENU_TEXT_COLOR;
obj.body.style.backgroundColor = KE_MENU_BG_COLOR;
obj.body.style.margin = 0;
obj.body.scroll = 'no';
}
function KindDrawTableSelected(i, j)
{
var text = i.toString(10) + ' by ' + j.toString(10) + ' Table';
document.getElementById('tableLocation').innerHTML = text;
var num = 10;
for (m = 1; m <= num; m++) {
for (n = 1; n <= num; n++) {
var obj = document.getElementById('kindTableTd' + m.toString(10) + '_' + n.toString(10) + '');
if (m <= i && n <= j) {
obj.style.backgroundColor = KE_MENU_SELECTED_COLOR;
} else {
obj.style.backgroundColor = '#FFFFFF';
}
}
}
}
function KindImageType(type)
{
if (type == 1) {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'block';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').value = 'http://';
} else {
KE_IMAGE_DOCUMENT.getElementById('imgFile').style.display = 'none';
KE_IMAGE_DOCUMENT.getElementById('imgLink').style.display = 'block';
}
KE_IMAGE_DOCUMENT.getElementById('imgPreview').innerHTML = " ";
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = 0;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = 0;
}
function KindImagePreview()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
if (type == 1) {
if (KE_BROWSER != 'IE') {
return false;
}
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
url = 'file:///' + file;
if (KindCheckImageFileType(url, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
var imgObj = KE_IMAGE_DOCUMENT.createElement("IMG");
imgObj.src = url;
var width = parseInt(imgObj.width);
var height = parseInt(imgObj.height);
KE_IMAGE_DOCUMENT.getElementById('imgWidth').value = width;
KE_IMAGE_DOCUMENT.getElementById('imgHeight').value = height;
var rate = parseInt(width/height);
if (width >230 && height <= 230) {
width = 230;
height = parseInt(width/rate);
} else if (width <=230 && height > 230) {
height = 230;
width = parseInt(height*rate);
} else if (width >230 && height > 230) {
if (width >= height) {
width = 230;
height = parseInt(width/rate);
} else {
height = 230;
width = parseInt(height*rate);
}
}
imgObj.style.width = width;
imgObj.style.height = height;
var el = KE_IMAGE_DOCUMENT.getElementById('imgPreview');
if (el.hasChildNodes()) {
el.removeChild(el.childNodes[0]);
}
el.appendChild(imgObj);
return imgObj;
}
function KindDrawImageEnd()
{
var type = KE_IMAGE_DOCUMENT.getElementById('imageType').value;
var url = KE_IMAGE_DOCUMENT.getElementById('imgLink').value;
var file = KE_IMAGE_DOCUMENT.getElementById('imgFile').value;
var width = KE_IMAGE_DOCUMENT.getElementById('imgWidth').value;
var height = KE_IMAGE_DOCUMENT.getElementById('imgHeight').value;
var border = KE_IMAGE_DOCUMENT.getElementById('imgBorder').value;
var title = KE_IMAGE_DOCUMENT.getElementById('imgTitle').value;
var align = KE_IMAGE_DOCUMENT.getElementById('imgAlign').value;
var hspace = KE_IMAGE_DOCUMENT.getElementById('imgHspace').value;
var vspace = KE_IMAGE_DOCUMENT.getElementById('imgVspace').value;
if (type == 1) {
if (file == '') {
alert(KE_LANG['SELECT_IMAGE']);
return false;
}
if (KindCheckImageFileType(file, "\\") == false) {
return false;
}
} else {
if (KindCheckImageFileType(url, "/") == false) {
return false;
}
}
if (width.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_WIDTH']);
return false;
}
if (height.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HEIGHT']);
return false;
}
if (border.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_BORDER']);
return false;
}
if (hspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_HSPACE']);
return false;
}
if (vspace.match(/^\d+$/) == null) {
alert(KE_LANG['INVALID_VSPACE']);
return false;
}
var fileName;
KindEditorForm.focus();
if (type == 1) {
fileName = KindGetFileName(file, "\\");
var fileExt = KindGetFileExt(fileName);
var dateObj = new Date();
var year = dateObj.getFullYear().toString(10);
var month = (dateObj.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = dateObj.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var ymd = year + month + day;
fileName = ymd + dateObj.getTime().toString(10) + '.' + fileExt;
KE_IMAGE_DOCUMENT.getElementById('fileName').value = fileName;
} else {
KindInsertImage(url, width, height, border, title, align, hspace, vspace);
}
}
function KindInsertImage(url, width, height, border, title, align, hspace, vspace)
{
var element = document.createElement("img");
element.src = url;
if (width > 0) {
element.style.width = width;
}
if (height > 0) {
element.style.height = height;
}
if (align != "") {
element.align = align;
}
if (hspace > 0) {
element.hspace = hspace;
}
if (vspace > 0) {
element.vspace = vspace;
}
element.border = border;
element.alt = KindHtmlentities(title);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
KindReloadIframe();
}
function KindGetFlashHtmlTag(url)
{
var str = '<embed src="'+url+'" type="application/x-shockwave-flash" quality="high"></embed>';
return str;
}
function KindFlashPreview()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
var el = KE_FLASH_DOCUMENT.getElementById('flashPreview');
el.innerHTML = KindGetFlashHtmlTag(url);
}
function KindDrawFlashEnd()
{
var url = KE_FLASH_DOCUMENT.getElementById('flashLink').value;
if (KindCheckFlashFileType(url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
obj.type = "application/x-shockwave-flash";
obj.quality = "high";
KindInsertItem(obj);
KindDisableMenu();
}
function KindGetMediaHtmlTag(cmd, url)
{
var str = '<embed src="'+url+'" type="';
if (cmd == "KE_REAL") {
str += 'audio/x-pn-realaudio-plugin';
} else {
str += 'video/x-ms-asf-plugin';
}
str += '" width="230" height="230" loop="true" autostart="true">';
return str;
}
function KindMediaPreview(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
var el = mediaDocument.getElementById(cmd+'preview');
el.innerHTML = KindGetMediaHtmlTag(cmd, url);
}
function KindDrawMediaEnd(cmd)
{
var mediaDocument;
if (cmd == 'KE_REAL') {
mediaDocument = KE_REAL_DOCUMENT;
} else {
mediaDocument = KE_MEDIA_DOCUMENT;
}
var url = mediaDocument.getElementById(cmd+'link').value;
if (KindCheckMediaFileType(cmd, url, "/") == false) {
return false;
}
KindEditorForm.focus();
KindSelect();
var obj = document.createElement("EMBED");
obj.src = url;
if (cmd == 'KE_REAL') {
obj.type = 'audio/x-pn-realaudio-plugin';
} else {
obj.type = 'video/x-ms-asf-plugin';
}
obj.loop = 'true';
obj.autostart = 'true';
KindInsertItem(obj);
KindDisableMenu(cmd);
}
function KindDrawLinkEnd()
{
var range;
var url = KE_LINK_DOCUMENT.getElementById('hyperLink').value;
var target = KE_LINK_DOCUMENT.getElementById('hyperLinkTarget').value;
if (url.match(/http:\/\/.{3,}/) == null) {
alert(KE_LANG['INPUT_URL']);
return false;
}
KindEditorForm.focus();
KindSelect();
var element;
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
var el = document.createElement("a");
el.href = url;
if (target) {
el.target = target;
}
KE_RANGE.item(0).applyElement(el);
} else if (KE_SELECTION.type.toLowerCase() == 'text') {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.parentElement();
if (target) {
element.target = target;
}
}
} else {
KindExecuteValue('CreateLink', url);
element = KE_RANGE.startContainer.previousSibling;
element.target = target;
if (target) {
element.target = target;
}
}
KindDisableMenu();
}
function KindSelection()
{
if (KE_BROWSER == 'IE') {
KE_SELECTION = KE_EDITFORM_DOCUMENT.selection;
KE_RANGE = KE_SELECTION.createRange();
KE_RANGE_TEXT = KE_RANGE.text;
} else {
KE_SELECTION = document.getElementById("KindEditorForm").contentWindow.getSelection();
KE_RANGE = KE_SELECTION.getRangeAt(0);
KE_RANGE_TEXT = KE_RANGE.toString();
}
}
function KindSelect()
{
if (KE_BROWSER == 'IE') {
KE_RANGE.select();
}
}
function KindInsertItem(insertNode)
{
if (KE_BROWSER == 'IE') {
if (KE_SELECTION.type.toLowerCase() == 'control') {
KE_RANGE.item(0).outerHTML = insertNode.outerHTML;
} else {
KE_RANGE.pasteHTML(insertNode.outerHTML);
}
} else {
KE_SELECTION.removeAllRanges();
KE_RANGE.deleteContents();
var startRangeNode = KE_RANGE.startContainer;
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
if (startRangeNode.nodeType == 3 && insertNode.nodeType == 3) {
startRangeNode.insertData(startRangeOffset, insertNode.nodeValue);
newRange.setEnd(startRangeNode, startRangeOffset + insertNode.length);
newRange.setStart(startRangeNode, startRangeOffset + insertNode.length);
} else {
var afterNode;
if (startRangeNode.nodeType == 3) {
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(insertNode, afterNode);
startRangeNode.insertBefore(beforeNode, insertNode);
startRangeNode.removeChild(textNode);
} else {
if (startRangeNode.tagName.toLowerCase() == 'html') {
startRangeNode = startRangeNode.childNodes[0].nextSibling;
afterNode = startRangeNode.childNodes[0];
} else {
afterNode = startRangeNode.childNodes[startRangeOffset];
}
startRangeNode.insertBefore(insertNode, afterNode);
}
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
}
KE_SELECTION.addRange(newRange);
}
}
function KindExecuteValue(cmd, value)
{
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, value);
}
function KindSimpleExecute(cmd)
{
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.execCommand(cmd, false, null);
KindDisableMenu();
}
function KindExecute(cmd, value)
{
switch (cmd)
{
case 'KE_SOURCE':
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
document.getElementById("KindCodeForm").value = KindHtmlToXhtml(KE_EDITFORM_DOCUMENT.body.innerHTML);
document.getElementById("KindEditorIframe").style.display = 'none';
document.getElementById("KindEditTextarea").style.display = 'block';
KindDisableToolbar(true);
} else {
KE_EDITFORM_DOCUMENT.body.innerHTML = KindClearScriptTag(document.getElementById("KindCodeForm").value);
document.getElementById("KindEditTextarea").style.display = 'none';
document.getElementById("KindEditorIframe").style.display = 'block';
KindDisableToolbar(false);
}
KindDisableMenu();
break;
case 'KE_PRINT':
KindSimpleExecute('print');
break;
case 'KE_UNDO':
KindSimpleExecute('undo');
break;
case 'KE_REDO':
KindSimpleExecute('redo');
break;
case 'KE_CUT':
KindSimpleExecute('cut');
break;
case 'KE_COPY':
KindSimpleExecute('copy');
break;
case 'KE_PASTE':
KindSimpleExecute('paste');
break;
case 'KE_SELECTALL':
KindSimpleExecute('selectall');
break;
case 'KE_SUBSCRIPT':
KindSimpleExecute('subscript');
break;
case 'KE_SUPERSCRIPT':
KindSimpleExecute('superscript');
break;
case 'KE_BOLD':
KindSimpleExecute('bold');
break;
case 'KE_ITALIC':
KindSimpleExecute('italic');
break;
case 'KE_UNDERLINE':
KindSimpleExecute('underline');
break;
case 'KE_STRIKE':
KindSimpleExecute('strikethrough');
break;
case 'KE_JUSTIFYLEFT':
KindSimpleExecute('justifyleft');
break;
case 'KE_JUSTIFYCENTER':
KindSimpleExecute('justifycenter');
break;
case 'KE_JUSTIFYRIGHT':
KindSimpleExecute('justifyright');
break;
case 'KE_JUSTIFYFULL':
KindSimpleExecute('justifyfull');
break;
case 'KE_NUMBEREDLIST':
KindSimpleExecute('insertorderedlist');
break;
case 'KE_UNORDERLIST':
KindSimpleExecute('insertunorderedlist');
break;
case 'KE_INDENT':
KindSimpleExecute('indent');
break;
case 'KE_OUTDENT':
KindSimpleExecute('outdent');
break;
case 'KE_REMOVE':
KindSimpleExecute('removeformat');
break;
case 'KE_ZOOM':
KindDisplayMenu(cmd);
break;
case 'KE_ZOOM_END':
KindEditorForm.focus();
KE_EDITFORM_DOCUMENT.body.style.zoom = value;
KindDisableMenu();
break;
case 'KE_TITLE':
KindDisplayMenu(cmd);
break;
case 'KE_TITLE_END':
KindEditorForm.focus();
value = '<' + value + '>';
KindSelect();
KindExecuteValue('FormatBlock', value);
KindDisableMenu();
break;
case 'KE_FONTNAME':
KindDisplayMenu(cmd);
break;
case 'KE_FONTNAME_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('fontname', value);
KindDisableMenu();
break;
case 'KE_FONTSIZE':
KindDisplayMenu(cmd);
break;
case 'KE_FONTSIZE_END':
KindEditorForm.focus();
value = value.substr(0, 1);
KindSelect();
KindExecuteValue('fontsize', value);
KindDisableMenu();
break;
case 'KE_TEXTCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_TEXTCOLOR_END':
KindEditorForm.focus();
KindSelect();
KindExecuteValue('ForeColor', value);
KindDisableMenu();
break;
case 'KE_BGCOLOR':
KindDisplayMenu(cmd);
break;
case 'KE_BGCOLOR_END':
KindEditorForm.focus();
if (KE_BROWSER == 'IE') {
KindSelect();
KindExecuteValue('BackColor', value);
} else {
var startRangeNode = KE_RANGE.startContainer;
if (startRangeNode.nodeType == 3) {
var parent = startRangeNode.parentNode;
var element = document.createElement("font");
element.style.backgroundColor = value;
element.appendChild(KE_RANGE.extractContents());
var startRangeOffset = KE_RANGE.startOffset;
var newRange = document.createRange();
var afterNode;
var textNode = startRangeNode;
startRangeNode = textNode.parentNode;
var text = textNode.nodeValue;
var textBefore = text.substr(0, startRangeOffset);
var textAfter = text.substr(startRangeOffset);
var beforeNode = document.createTextNode(textBefore);
var afterNode = document.createTextNode(textAfter);
startRangeNode.insertBefore(afterNode, textNode);
startRangeNode.insertBefore(element, afterNode);
startRangeNode.insertBefore(beforeNode, element);
startRangeNode.removeChild(textNode);
newRange.setEnd(afterNode, 0);
newRange.setStart(afterNode, 0);
KE_SELECTION.addRange(newRange);
}
}
KindDisableMenu();
break;
case 'KE_ICON':
KindDisplayMenu(cmd);
break;
case 'KE_ICON_END':
KindEditorForm.focus();
var element = document.createElement("img");
element.src = value;
element.border = 0;
element.alt = "";
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_IMAGE':
KindDisplayMenu(cmd);
KindImageIframe.focus();
KE_IMAGE_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_FLASH':
KindDisplayMenu(cmd);
KindFlashIframe.focus();
KE_FLASH_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_MEDIA':
KindDisplayMenu(cmd);
KindMediaIframe.focus();
KE_MEDIA_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_REAL':
KindDisplayMenu(cmd);
KindRealIframe.focus();
KE_REAL_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_LINK':
KindDisplayMenu(cmd);
KindLinkIframe.focus();
KE_LINK_DOCUMENT.getElementById(cmd+'submitButton').focus();
break;
case 'KE_UNLINK':
KindSimpleExecute('unlink');
break;
case 'KE_SPECIALCHAR':
KindDisplayMenu(cmd);
break;
case 'KE_SPECIALCHAR_END':
KindEditorForm.focus();
KindSelect();
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_LAYER':
KindDisplayMenu(cmd);
break;
case 'KE_LAYER_END':
KindEditorForm.focus();
var element = document.createElement("div");
element.style.padding = "5px";
element.style.border = "1px solid #AAAAAA";
element.style.backgroundColor = value;
var childElement = document.createElement("div");
childElement.innerHTML = KE_LANG['INPUT_CONTENT'];
element.appendChild(childElement);
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TABLE':
KindDisplayMenu(cmd);
break;
case 'KE_TABLE_END':
KindEditorForm.focus();
var location = value.split(',');
var element = document.createElement("table");
element.cellPadding = 0;
element.cellSpacing = 0;
element.border = 1;
element.style.width = "100px";
element.style.height = "100px";
for (var i = 0; i < location[0]; i++) {
var rowElement = element.insertRow(i);
for (var j = 0; j < location[1]; j++) {
var cellElement = rowElement.insertCell(j);
cellElement.innerHTML = " ";
}
}
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_HR':
KindDisplayMenu(cmd);
break;
case 'KE_HR_END':
KindEditorForm.focus();
var element = document.createElement("hr");
element.width = "100%";
element.color = value;
element.size = 1;
KindSelect();
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_DATE':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var year = date.getFullYear().toString(10);
var month = (date.getMonth() + 1).toString(10);
month = month.length < 2 ? '0' + month : month;
var day = date.getDate().toString(10);
day = day.length < 2 ? '0' + day : day;
var value = year + '-' + month + '-' + day;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_TIME':
KindEditorForm.focus();
KindSelection();
var date = new Date();
var hour = date.getHours().toString(10);
hour = hour.length < 2 ? '0' + hour : hour;
var minute = date.getMinutes().toString(10);
minute = minute.length < 2 ? '0' + minute : minute;
var second = date.getSeconds().toString(10);
second = second.length < 2 ? '0' + second : second;
var value = hour + ':' + minute + ':' + second;
var element = document.createElement("span");
element.appendChild(document.createTextNode(value));
KindInsertItem(element);
KindDisableMenu();
break;
case 'KE_PREVIEW':
eval(KE_OBJ_NAME).data();
var newWin = window.open('', 'kindPreview','width=800,height=600,left=30,top=30,resizable=yes,scrollbars=yes');
KindWriteFullHtml(newWin.document, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
KindDisableMenu();
break;
case 'KE_ABOUT':
KindDisplayMenu(cmd);
break;
default:
break;
}
}
function KindDisableToolbar(flag)
{
if (flag == true) {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'design.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
if (KE_TOOLBAR_ICON[i][0] == 'KE_SOURCE' || KE_TOOLBAR_ICON[i][0] == 'KE_PREVIEW' || KE_TOOLBAR_ICON[i][0] == 'KE_ABOUT') {
continue;
}
el.style.visibility = 'hidden';
}
} else {
document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src = KE_SKIN_PATH + 'source.gif';
for (i = 0; i < KE_TOOLBAR_ICON.length; i++) {
var el = document.getElementById(KE_TOOLBAR_ICON[i][0]);
el.style.visibility = 'visible';
KE_EDITFORM_DOCUMENT.designMode = 'On';
}
}
}
function KindCreateIcon(icon)
{
var str = '<img id="'+ icon[0] +'" src="' + KE_SKIN_PATH + icon[1] + '" alt="' + icon[2] + '" title="' + icon[2] +
'" align="absmiddle" style="border:1px solid ' + KE_TOOLBAR_BG_COLOR +';cursor:pointer;height:20px;';
str += '" onclick="javascript:KindExecute(\''+ icon[0] +'\');" '+
'onmouseover="javascript:this.style.border=\'1px solid ' + KE_MENU_BORDER_COLOR + '\';" ' +
'onmouseout="javascript:this.style.border=\'1px solid ' + KE_TOOLBAR_BG_COLOR + '\';" ';
str += '>';
return str;
}
function KindCreateToolbar()
{
var htmlData = '<table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
if (KE_EDITOR_TYPE == 'full') {
for (i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_TOP_TOOLBAR_ICON[i]) + '</td>';
}
htmlData += '</tr></table><table cellpadding="0" cellspacing="0" border="0" height="26"><tr>';
for (i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_BOTTOM_TOOLBAR_ICON[i]) + '</td>';
}
} else {
for (i = 0; i < KE_SIMPLE_TOOLBAR_ICON.length; i++) {
htmlData += '<td style="padding:2px;">' + KindCreateIcon(KE_SIMPLE_TOOLBAR_ICON[i]) + '</td>';
}
}
htmlData += '</tr></table>';
return htmlData;
}
function KindWriteFullHtml(documentObj, content)
{
var editHtmlData = '';
editHtmlData += '<html>\r\n<head>\r\n<title>KindEditor</title>\r\n';
editHtmlData += '<link href="'+KE_CSS_PATH+'" rel="stylesheet" type="text/css">\r\n</head>\r\n<body>\r\n';
editHtmlData += content;
editHtmlData += '\r\n</body>\r\n</html>\r\n';
documentObj.open();
documentObj.write(editHtmlData);
documentObj.close();
}
function KindEditor(objName)
{
this.objName = objName;
this.hiddenName = objName;
this.siteDomain;
this.editorType;
this.safeMode;
this.uploadMode;
this.editorWidth;
this.editorHeight;
this.skinPath;
this.iconPath;
this.imageAttachPath;
this.imageUploadCgi;
this.cssPath;
this.menuBorderColor;
this.menuBgColor;
this.menuTextColor;
this.menuSelectedColor;
this.toolbarBorderColor;
this.toolbarBgColor;
this.formBorderColor;
this.formBgColor;
this.buttonColor;
this.init = function()
{
if (this.siteDomain) KE_SITE_DOMAIN = this.siteDomain;
if (this.editorType) KE_EDITOR_TYPE = this.editorType.toLowerCase();
if (this.safeMode) KE_SAFE_MODE = this.safeMode;
if (this.uploadMode) KE_UPLOAD_MODE = this.uploadMode;
if (this.editorWidth) KE_WIDTH = this.editorWidth;
if (this.editorHeight) KE_HEIGHT = this.editorHeight;
if (this.skinPath) KE_SKIN_PATH = this.skinPath;
if (this.iconPath) KE_ICON_PATH = this.iconPath;
if (this.imageAttachPath) KE_IMAGE_ATTACH_PATH = this.imageAttachPath;
if (this.imageUploadCgi) KE_IMAGE_UPLOAD_CGI = this.imageUploadCgi;
if (this.cssPath) KE_CSS_PATH = this.cssPath;
if (this.menuBorderColor) KE_MENU_BORDER_COLOR = this.menuBorderColor;
if (this.menuBgColor) KE_MENU_BG_COLOR = this.menuBgColor;
if (this.menuTextColor) KE_MENU_TEXT_COLOR = this.menuTextColor;
if (this.menuSelectedColor) KE_MENU_SELECTED_COLOR = this.menuSelectedColor;
if (this.toolbarBorderColor) KE_TOOLBAR_BORDER_COLOR = this.toolbarBorderColor;
if (this.toolbarBgColor) KE_TOOLBAR_BG_COLOR = this.toolbarBgColor;
if (this.formBorderColor) KE_FORM_BORDER_COLOR = this.formBorderColor;
if (this.formBgColor) KE_FORM_BG_COLOR = this.formBgColor;
if (this.buttonColor) KE_BUTTON_COLOR = this.buttonColor;
KE_OBJ_NAME = this.objName;
KE_BROWSER = KindGetBrowser();
KE_TOOLBAR_ICON = Array();
for (var i = 0; i < KE_TOP_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_TOP_TOOLBAR_ICON[i]);
}
for (var i = 0; i < KE_BOTTOM_TOOLBAR_ICON.length; i++) {
KE_TOOLBAR_ICON.push(KE_BOTTOM_TOOLBAR_ICON[i]);
}
}
this.show = function()
{
this.init();
var widthStyle = 'width:' + KE_WIDTH + ';';
var widthArr = KE_WIDTH.match(/(\d+)([px%]{1,2})/);
var iframeWidthStyle = 'width:' + (parseInt(widthArr[1]) - 2).toString(10) + widthArr[2] + ';';
var heightStyle = 'height:' + KE_HEIGHT + ';';
var heightArr = KE_HEIGHT.match(/(\d+)([px%]{1,2})/);
var iframeHeightStyle = 'height:' + (parseInt(heightArr[1]) - 3).toString(10) + heightArr[2] + ';';
if (KE_BROWSER == '') {
var htmlData = '<div id="KindEditTextarea" style="' + widthStyle + heightStyle + '">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + widthStyle + heightStyle +
'padding:0;margin:0;border:1px solid '+ KE_FORM_BORDER_COLOR +
';font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';">' + document.getElementsByName(this.hiddenName)[0].value + '</textarea></div>';
document.open();
document.write(htmlData);
document.close();
return;
}
var htmlData = '<div style="font-family:'+KE_FONT_FAMILY+';">';
htmlData += '<div style="'+widthStyle+';border:1px solid ' + KE_TOOLBAR_BORDER_COLOR + ';background-color:'+ KE_TOOLBAR_BG_COLOR +'">';
htmlData += KindCreateToolbar();
htmlData += '</div><div id="KindEditorIframe" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';border-top:0;">' +
'<iframe name="KindEditorForm" id="KindEditorForm" frameborder="0" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;"></iframe></div>';
if (KE_EDITOR_TYPE == 'full') {
htmlData += '<div id="KindEditTextarea" style="' + widthStyle + heightStyle +
'border:1px solid '+ KE_FORM_BORDER_COLOR +';background-color:'+
KE_FORM_BG_COLOR +';border-top:0;display:none;">' +
'<textarea name="KindCodeForm" id="KindCodeForm" style="' + iframeWidthStyle + iframeHeightStyle +
'padding:0;margin:0;border:0;font-size:12px;line-height:16px;font-family:'+KE_FONT_FAMILY+';background-color:'+
KE_FORM_BG_COLOR +';" onclick="javascirit:parent.KindDisableMenu();"></textarea></div>';
}
htmlData += '</div>';
for (var i = 0; i < KE_POPUP_MENU_TABLE.length; i++) {
if (KE_POPUP_MENU_TABLE[i] == 'KE_IMAGE') {
htmlData += '<span id="InsertIframe">';
}
htmlData += KindPopupMenu(KE_POPUP_MENU_TABLE[i]);
if (KE_POPUP_MENU_TABLE[i] == 'KE_REAL') {
htmlData += '</span>';
}
}
document.open();
document.write(htmlData);
document.close();
if (KE_BROWSER == 'IE') {
KE_EDITFORM_DOCUMENT = document.frames("KindEditorForm").document;
} else {
KE_EDITFORM_DOCUMENT = document.getElementById('KindEditorForm').contentDocument;
}
KindDrawIframe('KE_IMAGE');
KindDrawIframe('KE_FLASH');
KindDrawIframe('KE_MEDIA');
KindDrawIframe('KE_REAL');
KindDrawIframe('KE_LINK');
KE_EDITFORM_DOCUMENT.designMode = 'On';
KindWriteFullHtml(KE_EDITFORM_DOCUMENT, document.getElementsByName(eval(KE_OBJ_NAME).hiddenName)[0].value);
var el = KE_EDITFORM_DOCUMENT.body;
if (KE_EDITFORM_DOCUMENT.addEventListener){
KE_EDITFORM_DOCUMENT.addEventListener('click', KindDisableMenu, false);
} else if (el.attachEvent){
el.attachEvent('onclick', KindDisableMenu);
}
}
this.data = function()
{
var htmlResult;
if (KE_BROWSER == '') {
htmlResult = document.getElementById("KindCodeForm").value;
} else {
if (KE_EDITOR_TYPE == 'full') {
var length = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.length - 10;
var image = document.getElementById(KE_TOP_TOOLBAR_ICON[0][0]).src.substr(length,10);
if (image == 'source.gif') {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
} else {
htmlResult = document.getElementById("KindCodeForm").value;
}
} else {
htmlResult = KE_EDITFORM_DOCUMENT.body.innerHTML;
}
}
KindDisableMenu();
htmlResult = KindHtmlToXhtml(htmlResult);
htmlResult = KindClearScriptTag(htmlResult);
document.getElementsByName(this.hiddenName)[0].value = htmlResult;
return htmlResult;
}
}
| JavaScript |
jQuery
.extend( {
createUploadIframe : function(id, uri) {
// create frame
var frameId = 'jUploadFrame' + id;
if (window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId
+ '" name="' + frameId + '" />');
if (typeof uri == 'boolean') {
io.src = 'javascript:false';
} else if (typeof uri == 'string') {
io.src = uri;
}
} else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io;
},
createUploadForm : function(id, fileElementId) {
// create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId
+ '" id="' + formId
+ '" enctype="multipart/form-data"></form>');
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
// set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload : function(s) {
// TODO introduce global settings, allowing the client to modify
// them for all requests, not only timeout
s = jQuery.extend( {}, jQuery.ajaxSettings, s);
var id = s.fileElementId;
var form = jQuery.createUploadForm(id, s.fileElementId);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
if (s.global && !jQuery.active++) {
// Watch for a new set of requests
jQuery.event.trigger("ajaxStart");
}
var requestDone = false;
// Create the request object
var xml = {};
if (s.global) {
jQuery.event.trigger("ajaxSend", [ xml, s ]);
}
var uploadCallback = function(isTimeout) {
// Wait for a response to come back
var io = document.getElementById(frameId);
try {
if (io.contentWindow) {
xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML
: null;
xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument
: io.contentWindow.document;
} else if (io.contentDocument) {
xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML
: null;
xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument
: io.contentDocument.document;
}
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
if (xml || isTimeout == "timeout") {
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or
// notmodified
if (status != "error") {
// process the data (runs the xml through httpData
// regardless of callback)
var data = jQuery.uploadHttpData(xml, s.dataType);
if (s.success) {
// ifa local callback was specified, fire it and
// pass it the data
s.success(data, status);
}
;
if (s.global) {
// Fire the global callback
jQuery.event.trigger("ajaxSuccess", [ xml, s ]);
}
;
} else {
jQuery.handleError(s, xml, status);
}
} catch (e) {
status = "error";
jQuery.handleError(s, xml, status, e);
}
;
if (s.global) {
// The request was completed
jQuery.event.trigger("ajaxComplete", [ xml, s ]);
}
;
// Handle the global AJAX counter
if (s.global && !--jQuery.active) {
jQuery.event.trigger("ajaxStop");
}
;
if (s.complete) {
s.complete(xml, status);
}
;
jQuery(io).unbind();
setTimeout(function() {
try {
jQuery(io).remove();
jQuery(form).remove();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
}, 100);
xml = null;
}
;
}
// Timeout checker
if (s.timeout > 0) {
setTimeout(function() {
if (!requestDone) {
// Check to see ifthe request is still happening
uploadCallback("timeout");
}
}, s.timeout);
}
try {
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if (form.encoding) {
form.encoding = 'multipart/form-data';
} else {
form.enctype = 'multipart/form-data';
}
jQuery(form).submit();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
if (window.attachEvent) {
document.getElementById(frameId).attachEvent('onload',
uploadCallback);
} else {
document.getElementById(frameId).addEventListener('load',
uploadCallback, false);
}
return {
abort : function() {
}
};
},
uploadHttpData : function(r, type) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// ifthe type is "script", eval it in global context
if (type == "script") {
jQuery.globalEval(data);
}
// Get the JavaScript object, ifJSON is used.
if (type == "json") {
eval("data = " + data);
}
// evaluate scripts within html
if (type == "html") {
jQuery("<div>").html(data).evalScripts();
}
return data;
}
});
| JavaScript |
/*!
* MultiUpload for xheditor
* @requires xhEditor
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 0.9.2 (build 100505)
*/
var swfu,selQueue=[],selectID,arrMsg=[],allSize=0,uploadSize=0;
function removeFile()
{
var file;
if(!selectID)return;
for(var i in selQueue)
{
file=selQueue[i];
if(file.id==selectID)
{
selQueue.splice(i,1);
allSize-=file.size;
swfu.cancelUpload(file.id);
$('#'+file.id).remove();
selectID=null;
break;
}
}
$('#btnClear').hide();
if(selQueue.length==0)$('#controlBtns').hide();
}
function startUploadFiles()
{
if(swfu.getStats().files_queued>0)
{
$('#controlBtns').hide();
swfu.startUpload();
}
else alert('上传前请先添加文件');
}
function setFileState(fileid,txt)
{
$('#'+fileid+'_state').text(txt);
}
function fileQueued(file)//队列添加成功
{
for(var i in selQueue)if(selQueue[i].name==file.name){swfu.cancelUpload(file.id);return false;}//防止同名文件重复添加
if(selQueue.length==0)$('#controlBtns').show();
selQueue.push(file);
allSize+=file.size;
$('#listBody').append('<tr id="'+file.id+'"><td>'+file.name+'</td><td>'+formatBytes(file.size)+'</td><td id="'+file.id+'_state">就绪</td></tr>');
$('#'+file.id).hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');})
.click(function(){selectID=file.id;$('#listBody tr').removeClass('select');$(this).removeClass('hover').addClass('select');$('#btnClear').show();})
}
function fileQueueError(file, errorCode, message)//队列添加失败
{
var errorName='';
switch (errorCode)
{
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
errorName = "只能同时上传 "+this.settings.file_upload_limit+" 个文件";
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
errorName = "选择的文件超过了当前大小限制:"+this.settings.file_size_limit;
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
errorName = "零大小文件";
break;
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
errorName = "文件扩展名必需为:"+this.settings.file_types_description+" ("+this.settings.file_types+")";
break;
default:
errorName = "未知错误";
break;
}
alert(errorName);
}
function uploadStart(file)//单文件上传开始
{
setFileState(file.id,'上传中…');
}
function uploadProgress(file, bytesLoaded, bytesTotal)//单文件上传进度
{
var percent=Math.ceil((uploadSize+bytesLoaded)/allSize*100);
$('#progressBar span').text(percent+'% ('+formatBytes(uploadSize+bytesLoaded)+' / '+formatBytes(allSize)+')');
$('#progressBar div').css('width',percent+'%');
}
function uploadSuccess(file, serverData)//单文件上传成功
{
var data=Object;
try{eval("data=" + serverData);}catch(ex){};
if(data.err!=undefined&&data.msg!=undefined)
{
if(!data.err)
{
uploadSize+=file.size;
arrMsg.push(data.msg);
setFileState(file.id,'上传成功');
}
else
{
setFileState(file.id,'上传失败');
alert(data.err);
}
}
else setFileState(file.id,'上传失败!');
}
function uploadError(file, errorCode, message)//单文件上传错误
{
setFileState(file.id,'上传失败!');
}
function uploadComplete(file)//文件上传周期结束
{
if(swfu.getStats().files_queued>0)swfu.startUpload();
else uploadAllComplete();
}
function uploadAllComplete()//全部文件上传成功
{
callback(arrMsg);
}
function formatBytes(bytes) {
var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
} | JavaScript |
/*!
* xhEditor - WYSIWYG XHTML Editor
* @requires jQuery v1.4.2
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 1.1.1 (build 101002)
*/
(function($){
if($.xheditor)return false;//防止JS重复加载
$.fn.xheditor=function(options)
{
var arrSuccess=[];
this.each(function(){
if(!$.nodeName(this,'TEXTAREA'))return;
if(options===false)//卸载
{
if(this.xheditor)
{
this.xheditor.remove();
this.xheditor=null;
}
}
else//初始化
{
if(!this.xheditor)
{
var tOptions=/({.*})/.exec($(this).attr('class'));
if(tOptions)
{
try{tOptions=eval('('+tOptions[1]+')');}catch(ex){};
options=$.extend({},tOptions,options );
}
var editor=new $.xheditor(this,options);
if(editor.init())
{
this.xheditor=editor;
arrSuccess.push(editor);
}
else editor=null;
}
else arrSuccess.push(this.xheditor);
}
});
if(arrSuccess.length==0)arrSuccess=false;
if(arrSuccess.length==1)arrSuccess=arrSuccess[0];
return arrSuccess;
}
var xCount=0,browerVer=$.browser.version,isIE=$.browser.msie,isMozilla=$.browser.mozilla,isSafari=$.browser.safari,isOpera=$.browser.opera,bShowPanel=false,bClickCancel=true,bShowModal=false,bCheckEscInit=false;
var _jPanel,_jShadow,_jCntLine,_jPanelButton;
var jModal,jModalShadow,layerShadow,jOverlay,jHideSelect,onModalRemove;
var editorRoot;
$('script[src*=xheditor]').each(function(){
var s=this.src;
if(s.match(/xheditor[^\/]*\.js/i)){editorRoot=s.replace(/[\?#].*$/, '').replace(/(^|[\/\\])[^\/]*$/, '$1');return false;}
});
var specialKeys={ 27: 'esc', 9: 'tab', 32:'space', 13: 'enter', 8:'backspace', 145: 'scroll',
20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',
35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down',
112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12' };
var itemColors=['#FFFFFF','#CCCCCC','#C0C0C0','#999999','#666666','#333333','#000000','#FFCCCC','#FF6666','#FF0000','#CC0000','#990000','#660000','#330000','#FFCC99','#FF9966','#FF9900','#FF6600','#CC6600','#993300','#663300','#FFFF99','#FFFF66','#FFCC66','#FFCC33','#CC9933','#996633','#663333','#FFFFCC','#FFFF33','#FFFF00','#FFCC00','#999900','#666600','#333300','#99FF99','#66FF99','#33FF33','#33CC00','#009900','#006600','#003300','#99FFFF','#33FFFF','#66CCCC','#00CCCC','#339999','#336666','#003333','#CCFFFF','#66FFFF','#33CCFF','#3366FF','#3333FF','#000099','#000066','#CCCCFF','#9999FF','#6666CC','#6633FF','#6600CC','#333399','#330099','#FFCCFF','#FF99FF','#CC66CC','#CC33CC','#993399','#663366','#330033'];
var arrBlocktag=[{n:'p',t:'普通段落'},{n:'h1',t:'标题1'},{n:'h2',t:'标题2'},{n:'h3',t:'标题3'},{n:'h4',t:'标题4'},{n:'h5',t:'标题5'},{n:'h6',t:'标题6'},{n:'pre',t:'已编排格式'},{n:'address',t:'地址'}];
var arrFontname=[{n:'宋体',c:'SimSun'},{n:'仿宋体',c:'FangSong_GB2312'},{n:'黑体',c:'SimHei'},{n:'楷体',c:'KaiTi_GB2312'},{n:'微软雅黑',c:'Microsoft YaHei'},{n:'Arial'},{n:'Arial Narrow'},{n:'Arial Black'},{n:'Comic Sans MS'},{n:'Courier New'},{n:'System'},{n:'Times New Roman'},{n:'Tahoma'},{n:'Verdana'}];
var arrFontsize=[{n:'xx-small',wkn:'x-small',s:'8pt',t:'极小'},{n:'x-small',wkn:'small',s:'10pt',t:'特小'},{n:'small',wkn:'medium',s:'12pt',t:'小'},{n:'medium',wkn:'large',s:'14pt',t:'中'},{n:'large',wkn:'x-large',s:'18pt',t:'大'},{n:'x-large',wkn:'xx-large',s:'24pt',t:'特大'},{n:'xx-large',wkn:'-webkit-xxx-large',s:'36pt',t:'极大'}];
var menuAlign=[{s:'左对齐',v:'justifyleft'},{s:'居中',v:'justifycenter'},{s:'右对齐',v:'justifyright'},{s:'两端对齐',v:'justifyfull'}],menuList=[{s:'数字列表',v:'insertOrderedList'},{s:'符号列表',v:'insertUnorderedList'}];
var htmlPastetext='<div>使用键盘快捷键(Ctrl+V)把内容粘贴到方框里,按 确定</div><div><textarea id="xhePastetextValue" wrap="soft" spellcheck="false" style="width:300px;height:100px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlLink='<div>链接地址: <input type="text" id="xheLinkUrl" value="http://" class="xheText" /></div><div>打开方式: <select id="xheLinkTarget"><option selected="selected" value="">默认</option><option value="_blank">新窗口</option><option value="_self">当前窗口</option><option value="_parent">父窗口</option></select></div><div style="display:none">链接文字: <input type="text" id="xheLinkText" value="" class="xheText" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlImg='<div>图片文件: <input type="text" id="xheImgUrl" value="http://" class="xheText" /></div><div>替换文本: <input type="text" id="xheImgAlt" /></div><div>对齐方式: <select id="xheImgAlign"><option selected="selected" value="">默认</option><option value="left">左对齐</option><option value="right">右对齐</option><option value="top">顶端</option><option value="middle">居中</option><option value="baseline">基线</option><option value="bottom">底边</option></select></div><div>宽度高度: <input type="text" id="xheImgWidth" style="width:40px;" /> x <input type="text" id="xheImgHeight" style="width:40px;" /></div><div>边框大小: <input type="text" id="xheImgBorder" style="width:40px;" /></div><div>水平间距: <input type="text" id="xheImgHspace" style="width:40px;" /> 垂直间距: <input type="text" id="xheImgVspace" style="width:40px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlFlash='<div>动画文件: <input type="text" id="xheFlashUrl" value="http://" class="xheText" /></div><div>宽度高度: <input type="text" id="xheFlashWidth" style="width:40px;" value="480" /> x <input type="text" id="xheFlashHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlMedia='<div>媒体文件: <input type="text" id="xheMediaUrl" value="http://" class="xheText" /></div><div>宽度高度: <input type="text" id="xheMediaWidth" style="width:40px;" value="480" /> x <input type="text" id="xheMediaHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlTable='<div>行数列数: <input type="text" id="xheTableRows" style="width:40px;" value="3" /> x <input type="text" id="xheTableColumns" style="width:40px;" value="2" /></div><div>标题单元: <select id="xheTableHeaders"><option selected="selected" value="">无</option><option value="row">第一行</option><option value="col">第一列</option><option value="both">第一行和第一列</option></select></div><div>宽度高度: <input type="text" id="xheTableWidth" style="width:40px;" value="200" /> x <input type="text" id="xheTableHeight" style="width:40px;" value="" /></div><div>边框大小: <input type="text" id="xheTableBorder" style="width:40px;" value="1" /></div><div>表格间距: <input type="text" id="xheTableCellSpacing" style="width:40px;" value="1" /> 表格填充: <input type="text" id="xheTableCellPadding" style="width:40px;" value="1" /></div><div>对齐方式: <select id="xheTableAlign"><option selected="selected" value="">默认</option><option value="left">左对齐</option><option value="center">居中</option><option value="right">右对齐</option></select></div><div>表格标题: <input type="text" id="xheTableCaption" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlAbout='<div style="font:12px Arial;width:245px;word-wrap:break-word;word-break:break-all;"><p><span style="font-size:20px;color:#1997DF;">xhEditor</span><br />v1.1.1 (build 101002)</p><p>xhEditor是基于jQuery开发的跨平台轻量XHTML编辑器,基于<a href="http://www.gnu.org/licenses/lgpl.html" target="_blank">LGPL</a>开源协议发布。</p><p>Copyright © <a href="http://xheditor.com/" target="_blank">xhEditor.com</a>. All rights reserved.</p></div>';
var itemEmots={'default':{name:'默认',width:24,height:24,line:7,list:{'smile':'微笑','tongue':'吐舌头','titter':'偷笑','laugh':'大笑','sad':'难过','wronged':'委屈','fastcry':'快哭了','cry':'哭','wail':'大哭','mad':'生气','knock':'敲打','curse':'骂人','crazy':'抓狂','angry':'发火','ohmy':'惊讶','awkward':'尴尬','panic':'惊恐','shy':'害羞','cute':'可怜','envy':'羡慕','proud':'得意','struggle':'奋斗','quiet':'安静','shutup':'闭嘴','doubt':'疑问','despise':'鄙视','sleep':'睡觉','bye':'再见'}}};
var arrTools={Cut:{t:'剪切 (Ctrl+X)'},Copy:{t:'复制 (Ctrl+C)'},Paste:{t:'粘贴 (Ctrl+V)'},Pastetext:{t:'粘贴文本',h:isIE?0:1},Blocktag:{t:'段落标签',h:1},Fontface:{t:'字体',h:1},FontSize:{t:'字体大小',h:1},Bold:{t:'加粗 (Ctrl+B)',s:'Ctrl+B'},Italic:{t:'斜体 (Ctrl+I)',s:'Ctrl+I'},Underline:{t:'下划线 (Ctrl+U)',s:'Ctrl+U'},Strikethrough:{t:'删除线 (Ctrl+S)',s:'Ctrl+S'},FontColor:{t:'字体颜色',h:1},BackColor:{t:'背景颜色',h:1},SelectAll:{t:'全选 (Ctrl+A)'},Removeformat:{t:'删除文字格式'},Align:{t:'对齐',h:1},List:{t:'列表',h:1},Outdent:{t:'减少缩进 (Shift+Tab)',s:'Shift+Tab'},Indent:{t:'增加缩进 (Tab)',s:'Tab'},Link:{t:'超链接 (Ctrl+K)',s:'Ctrl+K',h:1},Unlink:{t:'取消超链接'},Img:{t:'图片',h:1},Flash:{t:'Flash动画',h:1},Media:{t:'多媒体文件',h:1},Emot:{t:'表情',s:'ctrl+e',h:1},Table:{t:'表格',h:1},Source:{t:'源代码'},Preview:{t:'预览'},Print:{t:'打印 (Ctrl+P)',s:'Ctrl+P'},Fullscreen:{t:'全屏编辑 (Esc)',s:'Esc'},About:{t:'关于 xhEditor'}};
var toolsThemes={
mini:'Bold,Italic,Underline,Strikethrough,|,Align,List,|,Link,Img',
simple:'Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,|,Align,List,Outdent,Indent,|,Link,Img,Emot',
full:'Cut,Copy,Paste,Pastetext,|,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,SelectAll,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Img,Flash,Media,Emot,Table,|,Source,Preview,Print,Fullscreen'};
toolsThemes.mfull=toolsThemes.full.replace(/\|(,Align)/i,'/$1');
var arrDbClick={'a':'Link','img':'Img','embed':'Embed'},uploadInputname='filedata';
$.xheditor=function(textarea,options)
{
var defaults={skin:'default',tools:'full',clickCancelDialog:true,linkTag:false,internalScript:false,inlineScript:false,internalStyle:true,inlineStyle:true,showBlocktag:false,forcePtag:true,upLinkExt:"zip,rar,txt",upImgExt:"jpg,jpeg,gif,png",upFlashExt:"swf",upMediaExt:"wmv,avi,wma,mp3,mid",modalWidth:350,modalHeight:220,modalTitle:true,defLinkText:'点击打开链接',layerShadow:3,emotMark:false,upBtnText:'上传',wordDeepClean:true,hoverExecDelay:100,html5Upload:true,upMultiple:99};
var _this=this,_text=textarea,_jText=$(_text),_jForm=_jText.closest('form'),_jTools,_jArea,_win,_jWin,_doc,_jDoc;
var bookmark;
var bInit=false,bSource=false,bFullscreen=false,bCleanPaste=false,outerScroll,bShowBlocktag=false,sLayoutStyle='',ev=null,timer,bDisableHoverExec=false,bQuickHoverExec=false;
var lastPoint=null,lastAngle=null;//鼠标悬停显示
var editorHeight=0;
var settings=_this.settings=$.extend({},defaults,options );
var plugins=settings.plugins,strPlugins=[];
if(plugins)
{
arrTools=$.extend({},arrTools,plugins);
$.each(plugins,function(n){strPlugins.push(n);});
strPlugins=strPlugins.join(',');
}
if(settings.tools.match(/^\s*(m?full|simple|mini)\s*$/i))
{
var toolsTheme=toolsThemes[$.trim(settings.tools)];
settings.tools=(settings.tools.match(/m?full/i)&&plugins)?toolsTheme.replace('Table','Table,'+strPlugins):toolsTheme;//插件接在full的Table后面
}
if(!settings.tools.match(/(^|,)\s*About\s*(,|$)/i))settings.tools+=',About';
settings.tools=settings.tools.split(',');
if(settings.editorRoot)editorRoot=settings.editorRoot;
editorRoot=getLocalUrl(editorRoot,'abs');
//基本控件名
var idCSS='xheCSS_'+settings.skin,idContainer='xhe'+xCount+'_container',idTools='xhe'+xCount+'_Tool',idIframeArea='xhe'+xCount+'_iframearea',idIframe='xhe'+xCount+'_iframe',idFixFFCursor='xhe'+xCount+'_fixffcursor';
var headHTML='',bodyClass='',skinPath=editorRoot+'xheditor_skin/'+settings.skin+'/',arrEmots=itemEmots,urlType=settings.urlType,urlBase=settings.urlBase,emotPath=settings.emotPath,emotPath=emotPath?emotPath:editorRoot+'xheditor_emot/',selEmotGroup='';
arrEmots=$.extend({},arrEmots,settings.emots);
emotPath=getLocalUrl(emotPath,'rel',urlBase?urlBase:null);//返回最短表情路径
bShowBlocktag=settings.showBlocktag;
if(bShowBlocktag)bodyClass+=' showBlocktag';
var arrShortCuts=[];
this.init=function()
{
//加载样式表
if($('#'+idCSS).length==0)$('head').append('<link id="'+idCSS+'" rel="stylesheet" type="text/css" href="'+skinPath+'ui.css" />');
//初始化编辑器
var cw = settings.width || _text.style.width || _jText.outerWidth();
editorHeight = settings.height || _text.style.height || _jText.outerHeight();
if(is(editorHeight,'string'))editorHeight=editorHeight.replace(/[^\d]+/g,'');
if(cw<=0||editorHeight<=0)//禁止对隐藏区域里的textarea初始化编辑器
{
alert('当前textarea处于隐藏状态,请将之显示后再初始化xhEditor,或者直接设置textarea的width和height样式');
return false;
}
if(/^[0-9\.]+$/i.test(''+cw))cw+='px';
//编辑器CSS背景
var editorBackground=settings.background || _text.style.background;
//工具栏内容初始化
var arrToolsHtml=['<span class="xheGStart"/>'],tool,cn,regSeparator=/\||\//i;
$.each(settings.tools,function(i,n)
{
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGEnd"/>');
if(n=='|')arrToolsHtml.push('<span class="xheSeparator"/>');
else if(n=='/')arrToolsHtml.push('<br />');
else
{
tool=arrTools[n];
if(!tool)return;
if(tool.c)cn=tool.c;
else cn='xheIcon xheBtn'+n;
arrToolsHtml.push('<span><a href="javascript:void(0);" title="'+tool.t+'" name="'+n+'" class="xheButton xheEnabled" tabindex="-1"><span class="'+cn+'" unselectable="on" /></a></span>');
if(tool.s)_this.addShortcuts(tool.s,n);
}
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGStart"/>');
});
arrToolsHtml.push('<span class="xheGEnd"/><br />');
_jText.after($('<input type="text" id="'+idFixFFCursor+'" style="position:absolute;display:none;" /><span id="'+idContainer+'" class="xhe_'+settings.skin+'" style="display:none"><table cellspacing="0" cellpadding="0" class="xheLayout" style="width:'+cw+';height:'+editorHeight+'px;"><tbody><tr><td id="'+idTools+'" class="xheTool" unselectable="on" style="height:1px;"></td></tr><tr><td id="'+idIframeArea+'" class="xheIframeArea"><iframe frameborder="0" id="'+idIframe+'" src="javascript:;" style="width:100%;"></iframe></td></tr></tbody></table></span>'));
_jTools=$('#'+idTools);_jArea=$('#'+idIframeArea);
headHTML='<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><link rel="stylesheet" href="'+skinPath+'iframe.css"/>';
var loadCSS=settings.loadCSS;
if(loadCSS)
{
if(is(loadCSS,'array'))for(var i in loadCSS)headHTML+='<link rel="stylesheet" href="'+loadCSS[i]+'"/>';
else
{
if(loadCSS.match(/\s*<style(\s+[^>]*?)?>[\s\S]+?<\/style>\s*/i))headHTML+=loadCSS;
else headHTML+='<link rel="stylesheet" href="'+loadCSS+'"/>';
}
}
var iframeHTML='<html><head>'+headHTML;
if(editorBackground)iframeHTML+='<style>body{background:'+editorBackground+';}</style>';
iframeHTML+='</head><body spellcheck="false" class="editMode'+bodyClass+'"></body></html>';
_this.win=_win=$('#'+idIframe)[0].contentWindow;
_jWin=$(_win);
try{
this.doc=_doc = _win.document;_jDoc=$(_doc);
_doc.open();
_doc.write(iframeHTML);
_doc.close();
if(isIE)_doc.body.contentEditable='true';
else _doc.designMode = 'On';
}catch(e){}
setTimeout(setOpts,300);
_this.setSource();
_win.setInterval=null;//针对jquery 1.3无法操作iframe window问题的hack
//添加工具栏
_jTools.append(arrToolsHtml.join('')).bind('mousedown contextmenu',returnFalse).click(function(event)
{
var jButton=$(event.target).closest('a');
if(jButton.is('.xheEnabled'))
{
ev=event;
_this.exec(jButton.attr('name'));
}
return false;
});
_jTools.find('.xheButton').hover(function(event){//鼠标悬停执行
var jButton=$(this),delay=settings.hoverExecDelay;
var tAngle=lastAngle;lastAngle=null;
if(delay==-1||bDisableHoverExec||!jButton.is('.xheEnabled'))return false;
if(tAngle&&tAngle>10)//检测误操作
{
bDisableHoverExec=true;
setTimeout(function(){bDisableHoverExec=false;},100);
return false;
}
var cmd=jButton.attr('name'),bHover=arrTools[cmd].h==1;
if(!bHover)
{
_this.hidePanel();//移到非悬停按钮上隐藏面板
return false;
}
if(bQuickHoverExec)delay=0;
if(delay>=0)timer=setTimeout(function(){
ev=event;
lastPoint={x:ev.clientX,y:ev.clientY};
_this.exec(cmd);
},delay);
},function(event){lastPoint=null;if(timer)clearTimeout(timer);}).mousemove(function(event){
if(lastPoint)
{
var diff={x:event.clientX-lastPoint.x,y:event.clientY-lastPoint.y};
if(Math.abs(diff.x)>1||Math.abs(diff.y)>1)
{
if(diff.x>0&&diff.y>0)
{
var tAngle=Math.round(Math.atan(diff.y/diff.x)/0.017453293);
if(lastAngle)lastAngle=(lastAngle+tAngle)/2
else lastAngle=tAngle;
}
else lastAngle=null;
lastPoint={x:event.clientX,y:event.clientY};
}
}
});
//初始化面板
_jPanel=$('#xhePanel');
_jShadow=$('#xheShadow');
_jCntLine=$('#xheCntLine');
if(_jPanel.length==0)
{
_jPanel=$('<div id="xhePanel"></div>').mousedown(function(ev){ev.stopPropagation()});
_jShadow=$('<div id="xheShadow"></div>');
_jCntLine=$('<div id="xheCntLine"></div>');
setTimeout(function(){
$(document.body).append(_jPanel).append(_jShadow).append(_jCntLine);
},10);
}
//切换显示区域
$('#'+idContainer).show();
_jText.hide();
_jArea.css('height',editorHeight-_jTools.outerHeight());
//绑定内核事件
_jText.focus(_this.focus);
_jForm.submit(saveResult).bind('reset', loadReset);
$(window).bind('unload beforeunload',saveResult).bind('resize',fixFullHeight);
$(document).mousedown(clickCancelPanel);
if(!bCheckEscInit){$(document).keydown(checkEsc);bCheckEscInit=true;}
_jWin.focus(function(){if(settings.focus)settings.focus();}).blur(function(){if(settings.blur)settings.blur();});
if(isSafari)_jWin.click(fixAppleSel);
_jDoc.mousedown(clickCancelPanel).keydown(checkShortcuts).keypress(forcePtag).dblclick(checkDblClick).bind('mousedown click',function(ev){_jText.trigger(ev.type);});
if(isIE)
{
//IE控件上Backspace会导致页面后退
_jDoc.keydown(function(ev){var rng=_this.getRng();if(ev.which==8&&rng.item){$(rng.item(0)).remove();return false;}});
//修正IE拖动img大小不更新width和height属性值的问题
function fixResize(ev)
{
var jImg=$(ev.target),v;
if(v=jImg.css('width'))jImg.css('width','').attr('width',v.replace(/[^0-9%]+/g, ''));
if(v=jImg.css('height'))jImg.css('height','').attr('height',v.replace(/[^0-9%]+/g, ''));
}
_jDoc.bind('controlselect',function(ev){
ev=ev.target;if(!$.nodeName(ev,'IMG'))return;
$(ev).unbind('resizeend',fixResize).bind('resizeend',fixResize);
});
}
var jBody=$(_doc.documentElement);
jBody.bind('paste',cleanPaste);
if(settings.disableContextmenu)jBody.bind('contextmenu',returnFalse);
//HTML5编辑区域直接拖放上传
if(settings.html5Upload)jBody.bind('dragenter dragover',function(ev){var types;if((types=ev.originalEvent.dataTransfer.types)&&$.inArray('Files', types)!=-1)return false;}).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0){
var i,cmd,arrCmd=['Link','Img','Flash','Media'],arrExt=[],strExt;
for(i in arrCmd){
cmd=arrCmd[i];
if(settings['up'+cmd+'Url']&&settings['up'+cmd+'Url'].match(/^[^!].*/i))arrExt.push(cmd+':,'+settings['up'+cmd+'Ext']);//允许上传
}
if(arrExt.length==0)return false;//禁止上传
else strExt=arrExt.join(',');
function getCmd(fileList){
var match,fileExt,cmd;
for(i=0;i<fileList.length;i++){
fileExt=fileList[i].fileName.replace(/.+\./,'');
if(match=strExt.match(new RegExp('(\\w+):[^:]*,'+fileExt+'(?:,|$)','i'))){
if(!cmd)cmd=match[1];
else if(cmd!=match[1])return 2;
}
else return 1;
}
return cmd;
}
cmd=getCmd(fileList);
if(cmd==1)alert('上传文件的扩展名必需为:'+strExt.replace(/\w+:,/g,''));
else if(cmd==2)alert('每次只能拖放上传同一类型文件');
else if(cmd){
_this.startUpload(fileList,settings['up'+cmd+'Url'],'*',function(arrMsg){
var arrUrl=[],msg,onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用户上传回调
for(i in arrMsg){
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!')url=url.substr(1);
arrUrl.push(url);
}
_this.exec(cmd);
$('#xhe'+cmd+'Url').val(arrUrl.join(' '));
$('#xheSave').click();
});
}
return false;
}
});
//添加用户快捷键
var shortcuts=settings.shortcuts;
if(shortcuts)$.each(shortcuts,function(key,func){_this.addShortcuts(key,func);});
xCount++;
bInit=true;
if(settings.fullscreen)_this.toggleFullscreen();
else if(settings.sourceMode)setTimeout(_this.toggleSource,20);
return true;
}
this.remove=function()
{
_this.hidePanel();
saveResult();//卸载前同步最新内容到textarea
//取消绑定事件
_jText.unbind('focus',_this.focus);
_jForm.unbind('submit',saveResult).unbind('reset', loadReset);
$(window).unbind('unload beforeunload',saveResult).unbind('resize',fixFullHeight);
$(document).unbind('mousedown',clickCancelPanel);
$('#'+idContainer+','+'#'+idFixFFCursor).remove();
_jText.show();
bInit=false;
}
this.saveBookmark=function(){
if(!bSource){
var rng=_this.getRng();
rng=rng.cloneRange?rng.cloneRange():rng;
bookmark={'top':_jWin.scrollTop(),'rng':rng};
}
}
this.loadBookmark=function()
{
if(bSource||!bookmark)return;
_this.focus();
var rng=bookmark.rng;
if(isIE)rng.select();
else
{
var sel=_this.getSel();
sel.removeAllRanges();
sel.addRange(rng);
}
_jWin.scrollTop(bookmark.top);
bookmark=null;
}
this.focus=function()
{
if(!bSource)_jWin.focus();
else $('#sourceCode',_doc).focus();
return false;
}
this.setCursorFirst=function(firstBlock)
{
_this.focus();_win.scrollTo(0,0);
var rng=_this.getRng(),_body=_doc.body,firstNode=_body,firstTag;
if(firstBlock&&firstNode.firstChild&&(firstTag=firstNode.firstChild.tagName)&&firstTag.match(/^p|div|h[1-6]$/i))firstNode=_body.firstChild;
isIE?rng.moveToElementText(firstNode):rng.setStart(firstNode,0);
rng.collapse(true);
if(isIE)rng.select();
else{var sel=_this.getSel();sel.removeAllRanges();sel.addRange(rng);}
}
this.getSel=function()
{
return _win.getSelection ? _win.getSelection() : _doc.selection;
}
this.getRng=function()
{
var sel=_this.getSel(),rng;
try{
rng = sel.rangeCount > 0 ? sel.getRangeAt(0) : (sel.createRange ? sel.createRange() : (_doc.createRange?_doc.createRange():_doc.body.createTextRange()));
}catch (ex){}
return rng;
}
this.getParent=function(tag)
{
var rng=_this.getRng(),p;
if(!isIE)
{
p = rng.commonAncestorContainer;
if(!rng.collapsed)if(rng.startContainer == rng.endContainer&&rng.startOffset - rng.endOffset < 2&&rng.startContainer.hasChildNodes())p = rng.startContainer.childNodes[rng.startOffset];
}
else p=rng.item?rng.item(0):rng.parentElement();
tag=tag?tag:'*';p=$(p);
if(!p.is(tag))p=$(p).closest(tag);
return p;
}
this.getSelect=function(format)
{
var sel=_this.getSel(),rng=_this.getRng(),isCollapsed=true;
if (!rng || rng.item)isCollapsed=false
else isCollapsed=!sel || rng.boundingWidth == 0 || rng.collapsed;
if(format=='text')return isCollapsed ? '' : (rng.text || (sel.toString ? sel.toString() : ''));
var sHtml;
if(rng.cloneContents)
{
var tmp=$('<div></div>'),c;
c = rng.cloneContents();
if(c)tmp.append(c);
sHtml=tmp.html();
}
else if(is(rng.item))sHtml=rng.item(0).outerHTML;
else if(is(rng.htmlText))sHtml=rng.htmlText;
else sHtml=rng.toString();
if(isCollapsed)sHtml='';
sHtml=_this.processHTML(sHtml,'read');
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
return sHtml;
}
this.pasteHTML=function(sHtml,bStart)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
var sel=_this.getSel(),rng=_this.getRng();
if(bStart!=undefined)//非覆盖式插入
{
if(rng.item)
{
var n=rng.item(0);
rng=_doc.body.createTextRange();
rng.moveToElementText(n);
rng.select();
}
rng.collapse(bStart);
}
sHtml+='<'+(isIE?'img':'span')+' id="_xhe_temp" style="display:none" />';
if(rng.insertNode)
{
rng.deleteContents();
rng.insertNode(rng.createContextualFragment(sHtml));
}
else
{
if(sel.type.toLowerCase()=='control'){sel.clear();rng=_this.getRng();};
rng.pasteHTML(sHtml);
}
var jTemp=$('#_xhe_temp',_doc),temp=jTemp[0];
if(isIE)
{
rng.moveToElementText(temp);
rng.select();
}
else
{
rng.selectNode(temp);
sel.removeAllRanges();
sel.addRange(rng);
}
jTemp.remove();
}
this.pasteText=function(text,bStart)
{
if(!text)text='';
text=_this.domEncode(text);
text = text.replace(/\r?\n/g, '<br />');
_this.pasteHTML(text,bStart);
}
this.appendHTML=function(sHtml)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
$(_doc.body).append(sHtml);
}
this.domEncode=function(str)
{
return str.replace(/[<>]/g,function(c){return {'<':'<','>':'>'}[c];});
}
this.setSource=function(sHtml)
{
bookmark=null;
if(typeof sHtml!='string'&&sHtml!='')sHtml=_text.value;
if(bSource)$('#sourceCode',_doc).val(sHtml);
else
{
if(settings.beforeSetSource)sHtml=settings.beforeSetSource(sHtml);
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
sHtml=_this.cleanWord(sHtml);
sHtml=_this.processHTML(sHtml,'write');
if(isIE){//修正IE会删除可视内容前的script,style,<!--
_doc.body.innerHTML='<img id="_xhe_temp" style="display:none" />'+sHtml;
$('#_xhe_temp',_doc).remove();
}
else _doc.body.innerHTML=sHtml;
}
}
this.processHTML=function(sHtml,mode)
{
var appleClass=' class="Apple-style-span"';
if(mode=='write')
{//write
//恢复emot
function restoreEmot(all,attr,q,emot)
{
emot=emot.split(',');
if(!emot[1]){emot[1]=emot[0];emot[0]=''}
if(emot[0]=='default')emot[0]='';
return all.replace(/\s+src\s*=\s*(["']?).*?\1(\s|$|\/|>)/i,'$2').replace(attr,' src="'+emotPath+(emot[0]?emot[0]:'default')+'/'+emot[1]+'.gif"'+(settings.emotMark?' emot="'+(emot[0]?emot[0]+',':'')+emot[1]+'"'+(all.match(/\s+alt\s*=\s*(["']?)\s*(.*?)\s*\1[\s\/>]/i)?'':' alt="'+emot[1]+'"'):''));
}
sHtml = sHtml.replace(/<img(?:\s+[^>]*?)?(\s+emot\s*=\s*(["']?)\s*(.*?)\s*\2)(?:\s+[^>]*?)?\/?>/ig,restoreEmot);
//保存属性值:src,href
function saveValue(all,tag,attr,n,q,v){return all.replace(attr,(urlBase?(' '+n+'="'+getLocalUrl(v,'abs',urlBase)+'"'):attr)+' _xhe_'+n+'="'+v+'"');}
sHtml = sHtml.replace(/<(\w+(?:\:\w+)?)(?:\s+[^>]*?)?(\s+(src|href)\s*=\s*(["']?)\s*(.*?)\s*\4)(?:\s+[^>]*?)?\/?>/ig,saveValue);
sHtml = sHtml.replace(/<(\/?)del(\s+[^>]*?)?>/ig,'<$1strike$2>');//编辑状态统一转为strike
if(isMozilla)
{
sHtml = sHtml.replace(/<(\/?)strong(\s+[^>]*?)?>/ig,'<$1b$2>');
sHtml = sHtml.replace(/<(\/?)em(\s+[^>]*?)?>/ig,'<$1i$2>');
}
else if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.n){s=t.wkn;break;}
}
return pre+'font-size:'+s+aft;
});
sHtml = sHtml.replace(/<strong(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-weight: bold;"$1>');
sHtml = sHtml.replace(/<em(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-style: italic;"$1>');
sHtml = sHtml.replace(/<u(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: underline;"$1>');
sHtml = sHtml.replace(/<strike(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: line-through;"$1>');
sHtml = sHtml.replace(/<\/(strong|em|u|strike)>/ig,'</span>');
sHtml = sHtml.replace(/<span((?:\s+[^>]*?)?\s+style="([^"]*;)*\s*(font-family|font-size|color|background-color)\s*:\s*[^;"]+\s*;?"[^>]*)>/ig,'<span'+appleClass+'$1>');
}
else if(isIE)
{
sHtml = sHtml.replace(/'/ig, ''');
sHtml = sHtml.replace(/\s+(disabled|checked|readonly|selected)\s*=\s*[\"\']?(false|0)[\"\']?/ig, '');
}
sHtml = sHtml.replace(/<a(\s+[^>]*?)?\/>/,'<a$1></a>');
if(!isSafari)
{
//style转font
function style2font(all,tag,style,content)
{
var attrs='',f,s1,s2,c;
f=style.match(/font-family\s*:\s*([^;"]+)/i);
if(f)attrs+=' face="'+f[1]+'"';
s1=style.match(/font-size\s*:\s*([^;"]+)/i);
if(s1)
{
s1=s1[1].toLowerCase();
for(var j=0;j<arrFontsize.length;j++)if(s1==arrFontsize[j].n||s1==arrFontsize[j].s){s2=j+1;break;}
if(s2)
{
attrs+=' size="'+s2+'"';
style=style.replace(/(^|;)(\s*font-size\s*:\s*[^;"]+;?)+/ig,'$1');
}
}
c=style.match(/(?:^|[\s;])color\s*:\s*([^;"]+)/i);
if(c)
{
var rgb;
if(rgb=c[1].match(/\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)){c[1]='#';for(var i=1;i<=3;i++)c[1]+=(rgb[i]-0).toString(16);}
c[1]=c[1].replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,'#$1$1$2$2$3$3');
attrs+=' color="'+c[1]+'"';
}
style=style.replace(/(^|;)(\s*(font-family|color)\s*:\s*[^;"]+;?)+/ig,'$1');
if(attrs!='')
{
if(style)attrs+=' style="'+style+'"';
return '<font'+attrs+'>'+content+"</font>";
}
else return all;
}
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,style2font);//最里层
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,style2font);//第2层
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,style2font);//第3层
}
}
else
{//read
//恢复属性值src,href
function restoreValue(all,n,q,v)
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
return all.replace(new RegExp('\\s+'+n+'\\s*=\\s*(["\']?).*?\\1(\\s|/?>)','ig'),' '+n+'="'+v.replace(/\$/g,'$$$$')+'"$2');
}
sHtml = sHtml.replace(/<(?:\w+(?:\:\w+)?)(?:\s+[^>]*?)?\s+_xhe_(src|href)\s*=\s*(["']?)\s*(.*?)\s*\2(?:\s+[^>]*?)?\/?>/ig,restoreValue);
if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.wkn){s=t.n;break;}
}
return pre+'font-size:'+s+aft;
});
var arrAppleSpan=[{r:/font-weight:\sbold/ig,t:'strong'},{r:/font-style:\sitalic/ig,t:'em'},{r:/text-decoration:\sunderline/ig,t:'u'},{r:/text-decoration:\sline-through/ig,t:'strike'}];
function replaceAppleSpan(all,tag,attr1,attr2,content)
{
var attr=attr1+attr2,newTag='';
if(!attr)return content;
for(var i=0;i<arrAppleSpan.length;i++)
{
if(attr.match(arrAppleSpan[i].r))
{
newTag=arrAppleSpan[i].t;
break;
}
}
if(newTag)return '<'+newTag+'>'+content+'</'+newTag+'>';
else return all;
}
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,replaceAppleSpan);//最里层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第2层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第3层
}
if(!isIE){//字符间的文本换行强制转br
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/([^<>\r\n]?)((?:\r?\n)+)([^<>\r\n]?)/ig,function(all,left,br,right){if(left||right)return left+br.replace(/\r?\n/g,'<br />')+right;else return all;});
});
}
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+(?:_xhe_|_moz_|_webkit_)[^=]+?\s*=\s*(["']?).*?\2(\s|\/?>)/ig,'$1$3');
sHtml = sHtml.replace(/(<\w+[^>]*?)\s+class\s*=\s*(["']?)\s*(?:apple|webkit)\-.+?\s*\2(\s|\/?>)/ig, "$1$3");
sHtml = sHtml.replace(/<img(\s+[^>]+?)\/?>/ig,function(all,attr){if(!attr.match(/\s+alt\s*(["']?).*?\1(\s|$)/i))attr+=' alt=""';return '<img'+attr+' />';});//img强制加alt
sHtml = sHtml.replace(/\s+jquery\d+="\d+"/ig,'');
}
return sHtml;
}
this.getSource=function(bFormat)
{
var sHtml,beforeGetSource=settings.beforeGetSource;
if(bSource)
{
sHtml=$('#sourceCode',_doc).val();
if(!beforeGetSource){
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/(\t*\r?\n\t*)+/g,'')//标准HTML模式清理缩进和换行
});
}
}
else
{
sHtml=_this.processHTML(_doc.body.innerHTML,'read');
sHtml=sHtml.replace(/^\s*(?:<(p|div)(?:\s+[^>]*?)?>)?\s*(<br(?:\s+[^>]*?)?>)*\s*(?:<\/\1>)?\s*$/i, '');//修正Firefox在空内容情况下多出来的代码
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml,bFormat);
sHtml=_this.cleanWord(sHtml);
if(beforeGetSource)sHtml=beforeGetSource(sHtml);
}
_text.value=sHtml;
return sHtml;
}
this.cleanWord=function(sHtml)
{
if(sHtml.match(/mso(-|normal)|WordDocument/i))
{
var deepClean=settings.wordDeepClean;
//格式化
sHtml = sHtml.replace(/(<link(?:\s+[^>]*?)?)\s+href\s*=\s*(["']?)\s*file:\/\/.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, '');
//区块标签清理
sHtml = sHtml.replace(/<!--[\s\S]*?-->|<!(--)?\[[\s\S]+?\](--)?>|<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
sHtml = sHtml.replace(/<\/?\w+:[^>]*>/ig, '');
if(deepClean)sHtml = sHtml.replace(/<\/?(span|a|img)(\s+[^>]*?)?>/ig,'');
//属性清理
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+class\s*=\s*(["']?)\s*mso.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//删除所有mso开头的样式
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+lang\s*=\s*(["']?)\s*.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//删除lang属性
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+align\s*=\s*(["']?)\s*left\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//取消align=left
//样式清理
sHtml = sHtml.replace(/<\w+(?:\s+[^>]*?)?(\s+style\s*=\s*(["']?)\s*([\s\S]*?)\s*\2)(?:\s+[^>]*?)?\s*\/?>/ig,function(all,attr,p,styles){
styles=$.trim(styles.replace(/\s*(mso-[^:]+:.+?|margin\s*:\s*0cm 0cm 0pt\s*|(text-align|font-variant|line-height)\s*:\s*.+?)(;|$)\s*/ig,''));
return all.replace(attr,deepClean?'':styles?' style="'+styles+'"':'');
});
}
return sHtml;
}
this.cleanHTML=function(sHtml)
{
sHtml = sHtml.replace(/<!?\/?(DOCTYPE|html|body|meta)(\s+[^>]*?)?>/ig, '');
var arrHeadSave;sHtml = sHtml.replace(/<head(?:\s+[^>]*?)?>([\s\S]*?)<\/head>/i, function(all,content){arrHeadSave=content.match(/<(script|style)(\s+[^>]*?)?>[\s\S]*?<\/\1>/ig);return '';});
if(arrHeadSave)sHtml=arrHeadSave.join('')+sHtml;
sHtml = sHtml.replace(/<\??xml(:\w+)?(\s+[^>]*?)?>([\s\S]*?<\/xml>)?/ig, '');
if(!settings.linkTag)sHtml = sHtml.replace(/<link(\s+[^>]*?)?>/ig, '');
if(!settings.internalScript)sHtml = sHtml.replace(/<script(\s+[^>]*?)?>[\s\S]*?<\/script>/ig, '');
if(!settings.inlineScript)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+on(?:click|dblclick|mousedown|mouseup|mousemove|mouseover|mouseout|mouseenter|mouseleave|keydown|keypress|keyup|change|select|submit|reset|blur|focus|load|unload)\s*=\s*(["']?)[\s\S]*?\3((?:\s+[^>]*?)?\/?>)/ig,'$1$2$4');
if(!settings.internalStyle)sHtml = sHtml.replace(/<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
if(!settings.inlineStyle)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+(style|class)\s*=\s*(["']?)[\s\S]*?\4((?:\s+[^>]*?)?\/?>)/ig,'$1$2$5');
sHtml=sHtml.replace(/<\/(strong|b|u|strike|em|i)>((?:\s|<br\/?>| )*?)<\1(\s+[^>]*?)?>/ig,'$2');//连续相同标签
return sHtml;
}
this.formatXHTML=function(sHtml,bFormat)
{
var emptyTags = makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");//HTML 4.01
var blockTags = makeMap("address,applet,blockquote,button,center,dd,dir,div,dl,dt,fieldset,form,frameset,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");//HTML 4.01
var inlineTags = makeMap("a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");//HTML 4.01
var closeSelfTags = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
var fillAttrsTags = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
var specialTags = makeMap("script,style");
var tagReplac={'b':'strong','i':'em','s':'del','strike':'del'};
var startTag = /^<\??(\w+(?:\:\w+)?)((?:\s+[\w-\:]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/(\w+(?:\:\w+)?)[^>]*>/;
var attr = /\s+([\w-]+(?:\:\w+)?)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s]+)))?/g;
var skip=0,stack=[],last=sHtml,results=Array(),lvl=-1,lastTag='body',lastTagStart;
stack.last = function(){return this[ this.length - 1 ];};
while(last.length>0)
{
if(!stack.last()||!specialTags[stack.last()])
{
skip=0;
if(last.substring(0, 4)=='<!--')
{//注释标签
skip=last.indexOf("-->");
if(skip!=-1)
{
skip+=3;
addHtmlFrag(last.substring(0,skip));
}
}
else if(last.substring(0, 2)=='</')
{//结束标签
match = last.match( endTag );
if(match)
{
parseEndTag(match[1]);
skip = match[0].length;
}
}
else if(last.charAt(0)=='<')
{//开始标签
match = last.match( startTag );
if(match)
{
parseStartTag(match[1],match[2],match[3]);
skip = match[0].length;
}
}
if(skip==0)//普通文本
{
skip=last.indexOf('<');
if(skip==0)skip=1;
else if(skip<0)skip=last.length;
addHtmlFrag(_this.domEncode(last.substring(0,skip)));
}
last=last.substring(skip);
}
else
{//处理style和script
last=last.replace(/^([\s\S]*?)<\/(style|script)>/i, function(all, script,tagName){
results.push(script);
return ''
});
parseEndTag(stack.last());
}
}
parseEndTag();
sHtml=results.join('');
results=null;
function makeMap(str)
{
var obj = {}, items = str.split(",");
for ( var i = 0; i < items.length; i++ )obj[ items[i] ] = true;
return obj;
}
function processTag(tagName)
{
if(tagName)
{
tagName=tagName.toLowerCase();
var tag=tagReplac[tagName];
if(tag)tagName=tag;
}
else tagName='';
return tagName;
}
function parseStartTag(tagName,rest,unary)
{
tagName=processTag(tagName);
if(blockTags[tagName])while(stack.last()&&inlineTags[stack.last()])parseEndTag(stack.last());
if(closeSelfTags[tagName]&&stack.last()==tagName)parseEndTag(tagName);
unary = emptyTags[ tagName ] || !!unary;
if (!unary)stack.push(tagName);
var all=Array();
all.push('<' + tagName);
rest.replace(attr, function(match, name)
{
name=name.toLowerCase();
var value = arguments[2] ? arguments[2] :
arguments[3] ? arguments[3] :
arguments[4] ? arguments[4] :
fillAttrsTags[name] ? name : "";
all.push(' '+name+'="'+value+'"');
});
all.push((unary ? " /" : "") + ">");
addHtmlFrag(all.join(''),tagName,true);
}
function parseEndTag(tagName)
{
if(!tagName)var pos=0;//清空栈
else
{
tagName=processTag(tagName);
for(var pos=stack.length-1;pos>=0;pos--)if(stack[pos]==tagName)break;//向上寻找匹配的开始标签
}
if(pos>=0)
{
for(var i=stack.length-1;i>=pos;i--)addHtmlFrag("</" + stack[i] + ">",stack[i]);
stack.length=pos;
}
}
function addHtmlFrag(html,tagName,bStart)
{
if(bFormat==true)
{
html=html.replace(/(\t*\r?\n\t*)+/g,'');//清理换行符和相邻的制表符
if(html.match(/^\s*$/))return;//不格式化空内容的标签
var bBlock=blockTags[tagName],tag=bBlock?tagName:'';
if(bBlock)
{
if(bStart)lvl++;//块开始
if(lastTag=='')lvl--;//补文本结束
}
else if(lastTag)lvl++;//文本开始
if(tag!=lastTag||bBlock)addIndent();
results.push(html);
if(tagName=='br')addIndent();//回车强制换行
if(bBlock&&(emptyTags[tagName]||!bStart))lvl--;//块结束
lastTag=bBlock?tagName:'';lastTagStart=bStart;
}
else results.push(html);
}
function addIndent(){results.push('\r\n');if(lvl>0){var tabs=lvl;while(tabs--)results.push("\t");}}
//font转style
function font2style(all,tag,attrs,content)
{
if(!attrs)return content;
var styles='',f,s,c,style;
f=attrs.match(/ face\s*=\s*"\s*([^"]+)\s*"/i);
if(f)styles+='font-family:'+f[1]+';';
s=attrs.match(/ size\s*=\s*"\s*(\d+)\s*"/i);
if(s)styles+='font-size:'+arrFontsize[(s[1]>7?7:(s[1]<1?1:s[1]))-1].n+';';
c=attrs.match(/ color\s*=\s*"\s*([^"]+)\s*"/i);
if(c)styles+='color:'+c[1]+';';
style=attrs.match(/ style\s*=\s*"\s*([^"]+)\s*"/i);
if(style)styles+=style[1];
if(styles)content='<span style="'+styles+'">'+content+'</span>';
return content;
}
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,font2style);//最里层
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,font2style);//第2层
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,font2style);//第3层
sHtml = sHtml.replace(/^(\s*\r?\n)+|(\s*\r?\n)+$/g,'');//清理首尾换行
sHtml = sHtml.replace(/(\t*\r?\n)+/g,'\r\n');//多行变一行
return sHtml;
}
this.toggleShowBlocktag=function(state)
{
if(bShowBlocktag===state)return;
bShowBlocktag=!bShowBlocktag;
var _jBody=$(_doc.body);
if(bShowBlocktag)
{
bodyClass+=' showBlocktag';
_jBody.addClass('showBlocktag');
}
else
{
bodyClass=bodyClass.replace(' showBlocktag','');
_jBody.removeClass('showBlocktag');
}
}
this.toggleSource=function(state)
{
if(bSource===state)return;
_jTools.find('[name=Source]').toggleClass('xheEnabled').toggleClass('xheActive');
var _body=_doc.body,jBody=$(_body),sHtml;
var sourceCode,cursorMark='<span id="_xhe_cursor'+new Date().getTime()+'"></span>',cursorPos=0;
if(!bSource)
{//转为源代码模式
_this.pasteHTML(cursorMark,true);//标记当前位置
sHtml=_this.getSource(true);
cursorPos=sHtml.indexOf(cursorMark);
if(!isOpera)cursorPos=sHtml.substring(0,cursorPos).replace(/\r/g,'').length;//修正非opera光标定位点
sHtml=sHtml.replace(cursorMark,'');
if(isIE)_body.contentEditable='false';
else _doc.designMode = 'Off';
jBody.attr('scroll','no').attr('class','sourceMode').html('<textarea id="sourceCode" wrap="soft" spellcheck="false" height="100%" />');
sourceCode=$('#sourceCode',jBody).blur(_this.getSource)[0];
}
else
{//转为编辑模式
sHtml=_this.getSource();
jBody.html('').removeAttr('scroll').attr('class','editMode'+bodyClass);
if(isIE)_body.contentEditable='true';
else _doc.designMode = 'On';
if(isMozilla)
{
_this._exec("inserthtml","-");//修正firefox源代码切换回来无法删除文字的问题
$('#'+idFixFFCursor).show().focus().hide();//临时修正Firefox 3.6光标丢失问题
}
}
bSource=!bSource;
_this.setSource(sHtml);
if(bSource)//光标定位源码
{
_this.focus();
if(sourceCode.setSelectionRange)sourceCode.setSelectionRange(cursorPos, cursorPos);
else
{
var rng = sourceCode.createTextRange();
rng.move("character",cursorPos);
rng.select();
}
}
else _this.setCursorFirst(true);//定位最前面
_jTools.find('[name=Source],[name=Preview]').toggleClass('xheEnabled');
_jTools.find('.xheButton').not('[name=Source],[name=Fullscreen],[name=About]').toggleClass('xheEnabled');
setTimeout(setOpts,300);
}
this.showPreview=function()
{
var beforeSetSource=settings.beforeSetSource,sContent=_this.getSource();
if(beforeSetSource)sContent=beforeSetSource(sContent);
var sHTML='<html><head>'+headHTML+'<title>预览</title>'+(urlBase?'<base href="'+urlBase+'"/>':'')+'</head><body>' + sContent + '</body></html>';
var screen=window.screen,oWindow=window.open('', 'xhePreview', 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+Math.round(screen.width*0.9)+',height='+Math.round(screen.height*0.8)+',left='+Math.round(screen.width*0.05)),oDoc=oWindow.document;
oDoc.open();
oDoc.write(sHTML);
oDoc.close();
oWindow.focus();
}
this.toggleFullscreen=function(state)
{
if(bFullscreen===state)return;
var jLayout=$('#'+idContainer).find('.xheLayout'),jContainer=$('#'+idContainer);
if(bFullscreen)
{//取消全屏
jLayout.attr('style',sLayoutStyle);
_jArea.height(editorHeight-_jTools.outerHeight());
setTimeout(function(){$(window).scrollTop(outerScroll);},10);
}
else
{//显示全屏
outerScroll=$(window).scrollTop();
sLayoutStyle=jLayout.attr('style');
jLayout.removeAttr('style');
_jArea.height('100%');
setTimeout(fixFullHeight,100);
}
if(isMozilla)//临时修正Firefox 3.6源代码光标丢失问题
{
$('#'+idFixFFCursor).show().focus().hide();
setTimeout(_this.focus,1);
}
bFullscreen=!bFullscreen;
jContainer.toggleClass('xhe_Fullscreen');
$('html').toggleClass('xhe_Fullfix');
_jTools.find('[name=Fullscreen]').toggleClass('xheActive');
setTimeout(setOpts,300);
}
this.showMenu=function(menuitems,callback)
{
var jMenu=$('<div class="xheMenu"></div>'),arrItem=[];
$.each(menuitems,function(n,v){arrItem.push('<a href="javascript:void(0);" title="'+(v.t?v.t:v.s)+'" v="'+v.v+'">'+v.s+'</a>');});
jMenu.append(arrItem.join(''));
jMenu.click(function(ev){callback($(ev.target).closest('a').attr('v'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jMenu);
}
this.showColor=function(callback)
{
var jColor=$('<div class="xheColor"></div>'),arrItem=[],count=0;
$.each(itemColors,function(n,v)
{
if(count%7==0)arrItem.push((count>0?'</div>':'')+'<div>');
arrItem.push('<a href="javascript:void(0);" xhev="'+v+'" title="'+v+'" style="background:'+v+'"></a>');
count++;
});
arrItem.push('</div>');
jColor.append(arrItem.join(''));
jColor.click(function(ev){ev=ev.target;if(!$.nodeName(ev,'A'))return;callback($(ev).attr('xhev'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jColor);
}
this.showPastetext=function()
{
var jPastetext=$(htmlPastetext),jValue=$('#xhePastetextValue',jPastetext),jSave=$('#xheSave',jPastetext);
jSave.click(function(){
_this.loadBookmark();
var sValue=jValue.val();
if(sValue)_this.pasteText(sValue);
_this.hidePanel();
return false;
});
_this.showDialog(jPastetext);
}
this.showLink=function()
{
var jLink=$(htmlLink),jParent=_this.getParent('a'),jText=$('#xheLinkText',jLink),jUrl=$('#xheLinkUrl',jLink),jTarget=$('#xheLinkTarget',jLink),jSave=$('#xheSave',jLink),selHtml=_this.getSelect();
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'href'));
jTarget.attr('value',jParent.attr('target'));
}
else if(selHtml=='')jText.val(settings.defLinkText).closest('div').show();
if(settings.upLinkUrl)_this.uploadInit(jUrl,settings.upLinkUrl,settings.upLinkExt);
jSave.click(function(){
var url=jUrl.val();
_this.loadBookmark();
if(url==''||jParent.length==0)_this._exec('unlink');
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sTarget=jTarget.val(),sText=jText.val();
if(aUrl.length>1)
{//批量插入
_this._exec('unlink');//批量前删除当前链接并重新获取选择内容
selHtml=_this.getSelect();
var sTemplate='<a href="xhe_tmpurl"',sLink,arrLink=[];
if(sTarget!='')sTemplate+=' target="'+sTarget+'"';
sTemplate+='>xhe_tmptext</a>';
sText=(selHtml!=''?selHtml:(sText?sText:url));
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sLink=sTemplate;
sLink=sLink.replace('xhe_tmpurl',url[0]);
sLink=sLink.replace('xhe_tmptext',url[1]?url[1]:sText);
arrLink.push(sLink);
}
}
_this.pasteHTML(arrLink.join(' '));
}
else
{//单url模式
url=aUrl[0].split('||');
if(!sText)sText=url[0];
sText=url[1]?url[1]:(selHtml!='')?'':sText?sText:url[0];
if(jParent.length==0)
{
if(sText)_this.pasteHTML('<a href="#xhe_tmpurl">'+sText+'</a>');
else _this._exec('createlink','#xhe_tmpurl');
jParent=$('a[href$="#xhe_tmpurl"]',_doc);
}
else if(sText&&!isSafari)jParent.text(sText);//safari改写文本会导致光标丢失
xheAttr(jParent,'href',url[0]);
if(sTarget!='')jParent.attr('target',sTarget);
else jParent.removeAttr('target');
}
}
_this.hidePanel();
return false;
});
_this.showDialog(jLink);
}
this.showImg=function()
{
var jImg=$(htmlImg),jParent=_this.getParent('img'),jUrl=$('#xheImgUrl',jImg),jAlt=$('#xheImgAlt',jImg),jAlign=$('#xheImgAlign',jImg),jWidth=$('#xheImgWidth',jImg),jHeight=$('#xheImgHeight',jImg),jBorder=$('#xheImgBorder',jImg),jVspace=$('#xheImgVspace',jImg),jHspace=$('#xheImgHspace',jImg),jSave=$('#xheSave',jImg);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jAlt.val(jParent.attr('alt'));
jAlign.val(jParent.attr('align'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
jBorder.val(jParent.attr('border'));
var vspace=jParent.attr('vspace'),hspace=jParent.attr('hspace');
jVspace.val(vspace<=0?'':vspace);
jHspace.val(hspace<=0?'':hspace);
}
if(settings.upImgUrl)_this.uploadInit(jUrl,settings.upImgUrl,settings.upImgExt);
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sAlt=jAlt.val(),sAlign=jAlign.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sBorder=jBorder.val(),sVspace=jVspace.val(),sHspace=jHspace.val();;
if(aUrl.length>1)
{//批量插入
var sTemplate='<img src="xhe_tmpurl"',sImg,arrImg=[];
if(sAlt!='')sTemplate+=' alt="'+sAlt+'"';
if(sAlign!='')sTemplate+=' align="'+sAlign+'"';
if(sWidth!='')sTemplate+=' width="'+sWidth+'"';
if(sHeight!='')sTemplate+=' height="'+sHeight+'"';
if(sBorder!='')sTemplate+=' border="'+sBorder+'"';
if(sVspace!='')sTemplate+=' vspace="'+sVspace+'"';
if(sHspace!='')sTemplate+=' hspace="'+sHspace+'"';
sTemplate+=' />';
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sImg=sTemplate;
sImg=sImg.replace('xhe_tmpurl',url[0]);
if(url[1])sImg='<a href="'+url[1]+'" target="_blank">'+sImg+'</a>'
arrImg.push(sImg);
}
}
_this.pasteHTML(arrImg.join(' '));
}
else if(aUrl.length==1)
{//单URL模式
url=aUrl[0];
if(url!='')
{
url=url.split('||');
if(jParent.length==0)
{
_this.pasteHTML('<img src="'+url[0]+'#xhe_tmpurl" />');
jParent=$('img[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0])
if(sAlt!='')jParent.attr('alt',sAlt);
if(sAlign!='')jParent.attr('align',sAlign);
else jParent.removeAttr('align');
if(sWidth!='')jParent.attr('width',sWidth);
else jParent.removeAttr('width');
if(sHeight!='')jParent.attr('height',sHeight);
else jParent.removeAttr('height');
if(sBorder!='')jParent.attr('border',sBorder);
else jParent.removeAttr('border');
if(sVspace!='')jParent.attr('vspace',sVspace);
else jParent.removeAttr('vspace');
if(sHspace!='')jParent.attr('hspace',sHspace);
else jParent.removeAttr('hspace');
if(url[1])
{
var jLink=jParent.parent('a');
if(jLink.length==0)
{
jParent.wrap('<a></a>');
jLink=jParent.parent('a');
}
xheAttr(jLink,'href',url[1]);
jLink.attr('target','_blank');
}
}
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
_this.showDialog(jImg);
}
this.showEmbed=function(sType,sHtml,sMime,sClsID,sBaseAttrs,sUploadUrl,sUploadExt)
{
var jEmbed=$(sHtml),jParent=_this.getParent('embed[type="'+sMime+'"],embed[classid="'+sClsID+'"]'),jUrl=$('#xhe'+sType+'Url',jEmbed),jWidth=$('#xhe'+sType+'Width',jEmbed),jHeight=$('#xhe'+sType+'Height',jEmbed),jSave=$('#xheSave',jEmbed);
if(sUploadUrl)_this.uploadInit(jUrl,sUploadUrl,sUploadExt);
_this.showDialog(jEmbed);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
}
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var w=jWidth.val(),h=jHeight.val(),reg=/^[0-9]+$/;
if(!reg.test(w))w=412;if(!reg.test(h))h=300;
var sBaseCode='<embed type="'+sMime+'" classid="'+sClsID+'" src="xhe_tmpurl"'+sBaseAttrs;
var aUrl=url.split(' ');
if(aUrl.length>1)
{//批量插入
var sTemplate=sBaseCode+'',sEmbed,arrEmbed=[];
sTemplate+=' width="xhe_width" height="xhe_height" />';
for(var i in aUrl)
{
url=aUrl[i].split('||');
sEmbed=sTemplate;
sEmbed=sEmbed.replace('xhe_tmpurl',url[0])
sEmbed=sEmbed.replace('xhe_width',url[1]?url[1]:w)
sEmbed=sEmbed.replace('xhe_height',url[2]?url[2]:h)
if(url!='')arrEmbed.push(sEmbed);
}
_this.pasteHTML(arrEmbed.join(' '));
}
else if(aUrl.length==1)
{//单URL模式
url=aUrl[0].split('||');
if(jParent.length==0)
{
_this.pasteHTML(sBaseCode.replace('xhe_tmpurl',url[0]+'#xhe_tmpurl')+' />');
jParent=$('embed[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0]);
jParent.attr('width',url[1]?url[1]:w);
jParent.attr('height',url[2]?url[2]:h);
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
}
this.showEmot=function(group)
{
var jEmot=$('<div class="xheEmot"></div>');
group=group?group:(selEmotGroup?selEmotGroup:'default');
var arrEmot=arrEmots[group];
var sEmotPath=emotPath+group+'/',n=0,arrList=[],jList='';
var ew=arrEmot.width,eh=arrEmot.height,line=arrEmot.line,count=arrEmot.count,list=arrEmot.list;
if(count)
{
for(var i=1;i<=count;i++)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+i+'.gif);" emot="'+group+','+i+'" xhev=""> </a>');
if(n%line==0)arrList.push('<br />');
}
}
else
{
$.each(list,function(id,title)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+id+'.gif);" emot="'+group+','+id+'" title="'+title+'" xhev="'+title+'"> </a>');
if(n%line==0)arrList.push('<br />');
});
}
var w=line*(ew+12),h=Math.ceil(n/line)*(eh+12),mh=w*0.75;
if(h<=mh)mh='';
jList=$('<style>'+(mh?'.xheEmot div{width:'+(w+20)+'px;height:'+mh+'px;}':'')+'.xheEmot div a{width:'+ew+'px;height:'+eh+'px;}</style><div>'+arrList.join('')+'</div>').click(function(ev){ev=ev.target;var jA=$(ev);if(!$.nodeName(ev,'A'))return;_this.pasteHTML('<img emot="'+jA.attr('emot')+'" alt="'+jA.attr('xhev')+'">');_this.hidePanel();return false;}).mousedown(returnFalse);
jEmot.append(jList);
var gcount=0,arrGroup=['<ul>'],jGroup;//表情分类
$.each(arrEmots,function(g,v){
gcount++;
arrGroup.push('<li'+(group==g?' class="cur"':'')+'><a href="javascript:void(0);" group="'+g+'">'+v.name+'</a></li>');
});
if(gcount>1)
{
arrGroup.push('</ul><br style="clear:both;" />');
jGroup=$(arrGroup.join('')).click(function(ev){selEmotGroup=$(ev.target).attr('group');_this.exec('Emot');return false;}).mousedown(returnFalse);
jEmot.append(jGroup);
}
_this.showPanel(jEmot);
}
this.showTable=function()
{
var jTable=$(htmlTable),jRows=$('#xheTableRows',jTable),jColumns=$('#xheTableColumns',jTable),jHeaders=$('#xheTableHeaders',jTable),jWidth=$('#xheTableWidth',jTable),jHeight=$('#xheTableHeight',jTable),jBorder=$('#xheTableBorder',jTable),jCellSpacing=$('#xheTableCellSpacing',jTable),jCellPadding=$('#xheTableCellPadding',jTable),jAlign=$('#xheTableAlign',jTable),jCaption=$('#xheTableCaption',jTable),jSave=$('#xheSave',jTable);
jSave.click(function(){
_this.loadBookmark();
var sCaption=jCaption.val(),sBorder=jBorder.val(),sRows=jRows.val(),sCols=jColumns.val(),sHeaders=jHeaders.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sCellSpacing=jCellSpacing.val(),sCellPadding=jCellPadding.val(),sAlign=jAlign.val();
var i,j,htmlTable='<table'+(sBorder!=''?' border="'+sBorder+'"':'')+(sWidth!=''?' width="'+sWidth+'"':'')+(sHeight!=''?' width="'+sHeight+'"':'')+(sCellSpacing!=''?' cellspacing="'+sCellSpacing+'"':'')+(sCellPadding!=''?' cellpadding="'+sCellPadding+'"':'')+(sAlign!=''?' align="'+sAlign+'"':'')+'>';
if(sCaption!='')htmlTable+='<caption>'+sCaption+'</caption>';
if(sHeaders=='row'||sHeaders=='both')
{
htmlTable+='<tr>';
for(i=0;i<sCols;i++)htmlTable+='<th scope="col"> </th>';
htmlTable+='</tr>';
sRows--;
}
htmlTable+='<tbody>';
for(i=0;i<sRows;i++)
{
htmlTable+='<tr>';
for(j=0;j<sCols;j++)
{
if(j==0&&(sHeaders=='col'||sHeaders=='both'))htmlTable+='<th scope="row"> </th>';
else htmlTable+='<td> </td>';
}
htmlTable+='</tr>';
}
htmlTable+='</tbody></table>';
_this.pasteHTML(htmlTable);
_this.hidePanel();
return false;
});
_this.showDialog(jTable);
}
this.showAbout=function()
{
var jAbout=$(htmlAbout);
_this.showDialog(jAbout);
}
this.addShortcuts=function(key,cmd)
{
key=key.toLowerCase();
if(arrShortCuts[key]==undefined)arrShortCuts[key]=Array();
arrShortCuts[key].push(cmd);
}
this.delShortcuts=function(key){delete arrShortCuts[key];}
this.uploadInit=function(jText,toUrl,upext)
{
var jUpload=$('<span class="xheUpload"><input type="text" style="visibility:hidden;" tabindex="-1" /><input type="button" value="'+settings.upBtnText+'" class="xheBtn" tabindex="-1" /></span>'),jUpBtn=$('.xheBtn',jUpload);
var bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
jText.after(jUpload);jUpBtn.before(jText);
toUrl=toUrl.replace(/{editorRoot}/ig,editorRoot);
if(toUrl.substr(0,1)=='!')//自定义上传管理页
{
jUpBtn.click(function(){
bShowPanel=false;//防止按钮面板被关闭
_this.showIframeModal('上传文件',toUrl.substr(1),setUploadMsg,null,null,function(){bShowPanel=true;});
});
}
else
{//系统默认ajax上传
jUpload.append('<input type="file"'+(upMultiple>1?' multiple=""':'')+' class="xheFile" size="13" name="'+uploadInputname+'" tabindex="-1" />');
var jFile=$('.xheFile',jUpload),arrMsg;
jFile.change(function(){arrMsg=[];_this.startUpload(jFile[0],toUrl,upext,setUploadMsg);});
setTimeout(function(){//拖放上传
jText.closest('.xheDialog').bind('dragenter dragover',returnFalse).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(bHtml5Upload&&dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0)_this.startUpload(fileList,toUrl,upext,setUploadMsg);
return false;
});
},10);
}
function setUploadMsg(arrMsg)
{
if(is(arrMsg,'string'))arrMsg=[arrMsg];//允许单URL传递
var bImmediate=false,i,count=arrMsg.length,msg,url,arrUrl=[],onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用户上传回调
for(i=0;i<count;i++)
{
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!'){bImmediate=true;url=url.substr(1);}
arrUrl.push(url);
}
jText.val(arrUrl.join(' '));
if(bImmediate)jText.closest('.xheDialog').find('#xheSave').click();
}
}
this.startUpload=function(fromFiles,toUrl,limitExt,onUploadComplete)
{
var arrMsg=[],bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
var upload,fileList,filename,jUploadTip=$('<div style="padding:22px 0;text-align:center;line-height:30px;">文件上传中,请稍候……<br /></div>'),sLoading='<img src="'+skinPath+'img/loading.gif">';
if(!bHtml5Upload||(fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0])))
{
if(!checkFileExt(fromFiles.value,limitExt))return;
jUploadTip.append(sLoading);
upload=new _this.html4Upload(fromFiles,toUrl,onUploadCallback);
}
else
{
if(!fileList)fileList=fromFiles;//拖放文件列表
var i,len=fileList.length;
if(len>upMultiple){alert('请不要一次上传超过'+upMultiple+'个文件');return;}
for(i=0;i<len;i++)if(!checkFileExt(fileList[i].fileName,limitExt))return;
var jProgress=$('<div class="xheProgress"><div><span>0%</span></div></div>');
jUploadTip.append(jProgress);
upload=new _this.html5Upload(uploadInputname,fileList,toUrl,onUploadCallback,function(ev){
if(ev.loaded>=0)
{
var sPercent=Math.round((ev.loaded * 100) / ev.total)+'%';
$('div',jProgress).css('width',sPercent);
$('span',jProgress).text(sPercent+' ( '+formatBytes(ev.loaded)+' / '+formatBytes(ev.total)+' )');
}
else jProgress.replaceWith(sLoading);//不支持进度
});
}
var panelState=bShowPanel;
if(panelState)bShowPanel=false;//防止面板被关闭
_this.showModal('文件上传中(Esc取消上传)',jUploadTip,320,150,function(){bShowPanel=panelState;upload.remove();});
upload.start();
function onUploadCallback(sText,bFinish)
{
var data=Object,bOK=false;
try{data=eval('('+sText+')');}catch(ex){};
if(data.err==undefined||data.msg==undefined)alert(toUrl+' 上传接口发生错误!\r\n\r\n返回的错误内容为: \r\n\r\n'+sText);
else
{
if(data.err)alert(data.err);
else
{
arrMsg.push(data.msg);
bOK=true;//继续下一个文件上传
}
}
if(!bOK||bFinish)_this.removeModal();
if(bFinish&&bOK)onUploadComplete(arrMsg);//全部上传完成
return bOK;
}
}
this.html4Upload=function(fromfile,toUrl,callback)
{
var uid = new Date().getTime(),idIO='jUploadFrame'+uid,_this=this;
var jIO=$('<iframe name="'+idIO+'" class="xheHideArea" />').appendTo('body');
var jForm=$('<form action="'+toUrl+'" target="'+idIO+'" method="post" enctype="multipart/form-data" class="xheHideArea"></form>').appendTo('body');
var jOldFile = $(fromfile),jNewFile = jOldFile.clone().attr('disabled','true');
jOldFile.before(jNewFile).appendTo(jForm);
this.remove=function()
{
if(_this!=null)
{
jNewFile.before(jOldFile).remove();
jIO.remove();jForm.remove();
_this=null;
}
}
this.onLoad=function(){callback($(jIO[0].contentWindow.document.body).text(),true);}
this.start=function(){jForm.submit();jIO.load(_this.onLoad);}
return this;
}
this.html5Upload=function(inputname,fromFiles,toUrl,callback,onProgress)
{
var xhr,i=0,count=fromFiles.length,allLoaded=0,allSize=0,_this=this;
for(var j=0;j<count;j++)allSize+=fromFiles[j].fileSize;
this.remove=function(){if(xhr){xhr.abort();xhr=null;}}
this.uploadNext=function(sText)
{
if(sText)//当前文件上传完成
{
allLoaded+=fromFiles[i-1].fileSize;
returnProgress(0);
}
if((!sText||(sText&&callback(sText,i==count)==true))&&i<count)postFile(fromFiles[i++],toUrl,_this.uploadNext,function(loaded){returnProgress(loaded);});
}
this.start=function(){_this.uploadNext();}
function postFile(fromfile,toUrl,callback,onProgress)
{
xhr = new XMLHttpRequest(),upload=xhr.upload;
xhr.onreadystatechange=function(){if(xhr.readyState==4)callback(xhr.responseText);};
if(upload)upload.onprogress=function(ev){onProgress(ev.loaded);};
else onProgress(-1);//不支持进度
xhr.open("POST", toUrl);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Content-Disposition', 'attachment; name="'+inputname+'"; filename="'+fromfile.fileName+'"');
if(xhr.sendAsBinary)xhr.sendAsBinary(fromfile.getAsBinary());
else xhr.send(fromfile);
}
function returnProgress(loaded){if(onProgress)onProgress({'loaded':allLoaded+loaded,'total':allSize});}
}
this.showIframeModal=function(title,ifmurl,callback,w,h,onRemove)
{
var jContent=$('<iframe frameborder="0" src="'+ifmurl.replace(/{editorRoot}/ig,editorRoot)+'" style="width:100%;height:100%;display:none;" /><div class="xheModalIfmWait"></div>'),jIframe=$(jContent[0]),jWait=$(jContent[1]);
_this.showModal(title,jContent,w,h,onRemove);
jIframe.load(function(){
var modalWin=jIframe[0].contentWindow,jModalDoc=$(modalWin.document);
modalWin.callback=function(v){_this.removeModal();callback(v);};
modalWin.unloadme=_this.removeModal;
jModalDoc.keydown(_this.checkEsc);
jIframe.show();jWait.remove();
});
}
this.showModal=function(title,content,w,h,onRemove)
{
if(bShowModal)return false;//只能弹出一个模式窗口
layerShadow=settings.layerShadow;
w=w?w:settings.modalWidth;h=h?h:settings.modalHeight;
jModal=$('<div class="xheModal" style="width:'+(w-1)+'px;height:'+h+'px;margin-left:-'+Math.ceil(w/2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+Math.ceil(h/2)+'px')+'">'+(settings.modalTitle?'<div class="xheModalTitle"><span class="xheModalClose" title="关闭 (Esc)"></span>'+title+'</div>':'')+'<div class="xheModalContent"></div></div>').appendTo('body');
jOverlay=$('<div class="xheModalOverlay"></div>').appendTo('body');
if(layerShadow>0)jModalShadow=$('<div class="xheModalShadow" style="width:'+jModal.outerWidth()+'px;height:'+jModal.outerHeight()+'px;margin-left:-'+(Math.ceil(w/2)-layerShadow-2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+(Math.ceil(h/2)-layerShadow-2)+'px')+'"></div>').appendTo('body');
$('.xheModalContent',jModal).css('height',h-(settings.modalTitle?$('.xheModalTitle').outerHeight():0)).html(content);
if(isIE&&browerVer==6.0)jHideSelect=$('select:visible').css('visibility','hidden');//隐藏覆盖的select
$('.xheModalClose',jModal).click(_this.removeModal);
jOverlay.show();if(layerShadow>0)jModalShadow.show();jModal.show();
bShowModal=true;
onModalRemove=onRemove;
}
this.removeModal=function(){if(jHideSelect)jHideSelect.css('visibility','visible');jModal.html('').remove();if(layerShadow>0)jModalShadow.remove();jOverlay.remove();if(onModalRemove)onModalRemove();bShowModal=false;};
this.showDialog=function(content)
{
var jDialog=$('<div class="xheDialog"></div>'),jContent=$(content),jSave=$('#xheSave',jContent);
if(jSave.length==1)
{
jContent.find('input[type=text],select').keypress(function(ev){if(ev.which==13){jSave.click();return false;}});
jContent.find('textarea').keydown(function(ev){if(ev.ctrlKey&&ev.which==13){jSave.click();return false;}});
jSave.after(' <input type="button" id="xheCancel" value="取消" />');
$('#xheCancel',jContent).click(_this.hidePanel);
if(!settings.clickCancelDialog)
{
bClickCancel=false;//关闭点击隐藏
var jFixCancel=$('<div class="xheFixCancel"></div>').appendTo('body').mousedown(returnFalse);
var xy=_jArea.offset();
jFixCancel.css({'left':xy.left,'top':xy.top,width:_jArea.outerWidth(),height:_jArea.outerHeight()})
}
jDialog.mousedown(function(){bDisableHoverExec=true;})//点击对话框禁止悬停执行
}
jDialog.append(jContent);
_this.showPanel(jDialog);
if(!isIE)setTimeout(function(){jDialog.find('input[type=text],textarea').filter(':visible').filter(function(){return $(this).css('visibility')!='hidden';}).eq(0).focus();},10);//定位首个可见输入表单项,延迟解决opera无法设置焦点
}
this.showPanel=function(content)
{
if(!ev.target)return false;
_jPanel.html('').append(content).css('left',-999).css('top',-999);
_jPanelButton=$(ev.target).closest('a').addClass('xheActive');
var xy=_jPanelButton.offset();
var x=xy.left,y=xy.top;y+=_jPanelButton.outerHeight()-1;
_jCntLine.css({'left':x+1,'top':y,'width':_jPanelButton.width()}).show();
if((x+_jPanel.outerWidth())>document.body.clientWidth)x-=(_jPanel.outerWidth()-_jPanelButton.outerWidth());//向左显示面板
var layerShadow=settings.layerShadow;
if(layerShadow>0)_jShadow.css({'left':x+layerShadow,'top':y+layerShadow,'width':_jPanel.outerWidth(),'height':_jPanel.outerHeight()}).show();
_jPanel.css({'left':x,'top':y}).show();
bQuickHoverExec=bShowPanel=true;
}
this.hidePanel=function(){if(bShowPanel){_jPanelButton.removeClass('xheActive');_jShadow.hide();_jCntLine.hide();_jPanel.hide();bShowPanel=false;if(!bClickCancel){$('.xheFixCancel').remove();bClickCancel=true;};bQuickHoverExec=bDisableHoverExec=false;lastAngle=null;}}
this.exec=function(cmd)
{
_this.hidePanel();
_this.saveBookmark();
var tool=arrTools[cmd];
if(!tool)return false;//无效命令
if(ev==null)//非鼠标点击
{
ev={};
var btn=_jTools.find('.xheButton[name='+cmd+']');
if(btn.length==1)ev.target=btn;//设置当前事件焦点
}
if(tool.e)tool.e.call(_this)//插件事件
else//内置工具
{
cmd=cmd.toLowerCase();
switch(cmd)
{
case 'cut':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的浏览器安全设置不允许使用剪切操作,请使用键盘快捷键(Ctrl + X)来完成');};
break;
case 'copy':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的浏览器安全设置不允许使用复制操作,请使用键盘快捷键(Ctrl + C)来完成');}
break;
case 'paste':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的浏览器安全设置不允许使用粘贴操作,请使用键盘快捷键(Ctrl + V)来完成');}
break;
case 'pastetext':
if(window.clipboardData)_this.pasteText(window.clipboardData.getData('Text', true));
else _this.showPastetext();
break;
case 'blocktag':
var menuBlocktag=[];
$.each(arrBlocktag,function(n,v){menuBlocktag.push({s:'<'+v.n+'>'+v.t+'</'+v.n+'>',v:'<'+v.n+'>',t:v.t});});
_this.showMenu(menuBlocktag,function(v){_this._exec('formatblock',v);});
break;
case 'fontface':
var menuFontname=[];
$.each(arrFontname,function(n,v){v.c=v.c?v.c:v.n;menuFontname.push({s:'<span style="font-family:'+v.c+'">'+v.n+'</span>',v:v.c,t:v.n});});
_this.showMenu(menuFontname,function(v){_this._exec('fontname',v);});
break;
case 'fontsize':
var menuFontsize=[];
$.each(arrFontsize,function(n,v){menuFontsize.push({s:'<span style="font-size:'+v.s+';">'+v.t+'('+v.s+')</span>',v:n+1,t:v.t});});
_this.showMenu(menuFontsize,function(v){_this._exec('fontsize',v);});
break;
case 'fontcolor':
_this.showColor(function(v){_this._exec('forecolor',v);});
break;
case 'backcolor':
_this.showColor(function(v){if(isIE)_this._exec('backcolor',v);else{setCSS(true);_this._exec('hilitecolor',v);setCSS(false);}});
break;
case 'align':
_this.showMenu(menuAlign,function(v){_this._exec(v);});
break;
case 'list':
_this.showMenu(menuList,function(v){_this._exec(v);});
break;
case 'link':
_this.showLink();
break;
case 'img':
_this.showImg();
break;
case 'flash':
_this.showEmbed('Flash',htmlFlash,'application/x-shockwave-flash','clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000',' wmode="opaque" quality="high" menu="false" play="true" loop="true" allowfullscreen="true"',settings.upFlashUrl,settings.upFlashExt);
break;
case 'media':
_this.showEmbed('Media',htmlMedia,'application/x-mplayer2','clsid:6bf52a52-394a-11d3-b153-00c04f79faa6',' enablecontextmenu="false" autostart="false"',settings.upMediaUrl,settings.upMediaExt);
break;
case 'emot':
_this.showEmot();
break;
case 'table':
_this.showTable();
break;
case 'source':
_this.toggleSource();
break;
case 'preview':
_this.showPreview();
break;
case 'print':
_win.print();
break;
case 'fullscreen':
_this.toggleFullscreen();
break;
case 'about':
_this.showAbout();
break;
default:
_this._exec(cmd);
break;
}
}
ev=null;
}
this._exec=function(cmd,param,noFocus)
{
if(!noFocus)_this.focus();
var state;
if(param!=undefined)state=_doc.execCommand(cmd,false,param);
else state=_doc.execCommand(cmd,false,null);
return state;
}
function checkDblClick(ev)
{
var target=ev.target,tool=arrDbClick[target.tagName.toLowerCase()];
if(tool)
{
if(tool=='Embed')//自动识别Flash和多媒体
{
var arrEmbed={'application/x-shockwave-flash':'Flash','application/x-mplayer2':'Media'};
tool=arrEmbed[target.type.toLowerCase()];
}
_this.exec(tool);
}
}
function checkEsc(ev)
{
if(ev.which==27)
{
if(bShowModal)_this.removeModal();
else if(bShowPanel)_this.hidePanel();
return false;
}
}
function loadReset(){setTimeout(_this.setSource,10);}
function saveResult(){_this.getSource();};
function cleanPaste(ev){
if(bSource||bCleanPaste)return true;
bCleanPaste=true;//解决IE右键粘贴重复产生paste的问题
_this.saveBookmark();
var jDiv=$('<div style="position:absolute;left:-1000px;top:'+_jWin.scrollTop()+'px;overflow:hidden;width:1px;height:1px;" />',_doc),div=jDiv[0],sel=_this.getSel(),rng=_this.getRng();
$(_doc.body).append(jDiv);
if(isIE){
rng.moveToElementText(div);
rng.execCommand('Paste');
ev.preventDefault();
}
else{
rng.selectNodeContents(div);
sel.removeAllRanges();
sel.addRange(rng);
}
setTimeout(function(){
var sPaste;
if(settings.forcePasteText===true)sPaste=jDiv.text();
else{
sPaste=div.innerHTML;
sPaste=_this.cleanHTML(sPaste);
sPaste=_this.formatXHTML(sPaste);
sPaste=_this.cleanWord(sPaste);
}
jDiv.remove();
_this.loadBookmark();
_this.pasteHTML(sPaste);
bCleanPaste=false;
},0);
}
function setCSS(css)
{
try{_this._exec('styleWithCSS',css,true);}
catch(e)
{try{_this._exec('useCSS',!css,true);}catch(e){}}
}
function setOpts()
{
if(bInit&&!bSource)
{
setCSS(false);
try{_this._exec('enableObjectResizing',true,true);}catch(e){}
//try{_this._exec('enableInlineTableEditing',false,true);}catch(e){}
if(isIE)try{_this._exec('BackgroundImageCache',true,true);}catch(e){}
}
}
function forcePtag(ev)
{
if(bSource||ev.which!=13||ev.shiftKey||ev.ctrlKey||ev.altKey)return true;
var pNode=_this.getParent('p,h1,h2,h3,h4,h5,h6,pre,address,div,li');
if(pNode.is('li'))return true;
if(settings.forcePtag){if(pNode.length==0)_this._exec('formatblock','<p>');}
else
{
_this.pasteHTML('<br />');
if(isIE&&pNode.length>0&&_this.getRng().parentElement().childNodes.length==2)_this.pasteHTML('<br />');
return false;
}
}
function fixFullHeight()
{
if(!isMozilla&&!isSafari)
{
if(bFullscreen)_jArea.height('100%').css('height',_jArea.outerHeight()-_jTools.outerHeight());
if(isIE)_jTools.hide().show();
}
}
function fixAppleSel(e)
{
e=e.target;
if(e.tagName.match(/(img|embed)/i))
{
var sel=_this.getSel(),rng=_this.getRng();
rng.selectNode(e);
sel.removeAllRanges();
sel.addRange(rng);
}
}
function xheAttr(jObj,n,v)
{
if(!n)return false;
var kn='_xhe_'+n;
if(v)//设置属性
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
jObj.attr(n,urlBase?getLocalUrl(v,'abs',urlBase):v).removeAttr(kn).attr(kn,v);
}
return jObj.attr(kn)||jObj.attr(n);
}
function clickCancelPanel(){if(bClickCancel)_this.hidePanel();}
function checkShortcuts(event)
{
if(bSource)return true;
var code=event.which,special=specialKeys[code],sChar=special?special:String.fromCharCode(code).toLowerCase();
sKey='';
sKey+=event.ctrlKey?'ctrl+':'';sKey+=event.altKey?'alt+':'';sKey+=event.shiftKey?'shift+':'';sKey+=sChar;
var cmd=arrShortCuts[sKey],c;
for(c in cmd)
{
c=cmd[c];
if($.isFunction(c)){if(c.call(_this)===false)return false;}
else{_this.exec(c);return false;}//按钮独占快捷键
}
}
function is(o,t)
{
var n = typeof(o);
if (!t)return n != 'undefined';
if (t == 'array' && (o.hasOwnProperty && o instanceof Array))return true;
return n == t;
}
function getLocalUrl(url,urlType,urlBase)//绝对地址:abs,根地址:root,相对地址:rel
{
var baseUrl=urlBase?$('<a href="'+urlBase+'" />')[0]:location,protocol=baseUrl.protocol,host=baseUrl.hostname,port=baseUrl.port,path=baseUrl.pathname.replace(/\\/g,'/').replace(/[^\/]+$/i,'');
port=(port=='')?'80':port;
url=$.trim(url);
if(urlType!='abs')url=url.replace(new RegExp(protocol+'\\/\\/'+host.replace(/\./g,'\\.')+'(?::'+port+')'+(port=='80'?'?':'')+'(\/|$)','i'),'/');
if(urlType=='rel')url=url.replace(new RegExp('^'+path.replace(/([\/\.\+\[\]\(\)])/g,'\\$1'),'i'),'');
if(urlType!='rel')
{
if(!url.match(/^((https?|file):\/\/|\/)/i))url=path+url;
if(url.charAt(0)=='/')//处理..
{
var arrPath=[],arrFolder = url.split('/'),folder,i,l=arrFolder.length;
for(i=0;i<l;i++)
{
folder=arrFolder[i];
if(folder=='..')arrPath.pop();
else if(folder!==''&&folder!='.')arrPath.push(folder);
}
if(arrFolder[l-1]=='')arrPath.push('');
url='/'+arrPath.join('/');
}
}
if(urlType=='abs')if(!url.match(/(https?|file):\/\//i))url=protocol+'//'+location.host+url;
return url;
}
function checkFileExt(filename,limitExt)
{
if(limitExt=='*'||filename.match(new RegExp('\.('+limitExt.replace(/,/g,'|')+')$','i')))return true;
else
{
alert('上传文件扩展名必需为: '+limitExt);
return false;
}
}
function formatBytes(bytes)
{
var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+s[e];
}
function returnFalse(){return false;}
}
$(function(){
$.fn.oldVal=$.fn.val;
$.fn.val=function(value)
{
var _this=this,editor;
if(value===undefined)if(this[0]&&(editor=this[0].xheditor))return editor.getSource();else return _this.oldVal(value);//读
return this.each(function(){if(editor=this.xheditor)editor.setSource(value);else _this.oldVal(value);});//写
}
$('textarea').each(function(){
var self=$(this),xhClass=self.attr('class').match(/(?:^|\s)xheditor(?:\-(m?full|simple|mini))?(?:\s|$)/i);
if(xhClass)self.xheditor(xhClass[1]?{tools:xhClass[1]}:null);
});
});
})(jQuery); | JavaScript |
/*!
* xhEditor - WYSIWYG XHTML Editor
* @requires jQuery v1.4.2
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 1.1.1 (build 101002)
*/
(function($){
if($.xheditor)return false;//防止JS重複加載
$.fn.xheditor=function(options)
{
var arrSuccess=[];
this.each(function(){
if(!$.nodeName(this,'TEXTAREA'))return;
if(options===false)//卸載
{
if(this.xheditor)
{
this.xheditor.remove();
this.xheditor=null;
}
}
else//初始化
{
if(!this.xheditor)
{
var tOptions=/({.*})/.exec($(this).attr('class'));
if(tOptions)
{
try{tOptions=eval('('+tOptions[1]+')');}catch(ex){};
options=$.extend({},tOptions,options );
}
var editor=new $.xheditor(this,options);
if(editor.init())
{
this.xheditor=editor;
arrSuccess.push(editor);
}
else editor=null;
}
else arrSuccess.push(this.xheditor);
}
});
if(arrSuccess.length==0)arrSuccess=false;
if(arrSuccess.length==1)arrSuccess=arrSuccess[0];
return arrSuccess;
}
var xCount=0,browerVer=$.browser.version,isIE=$.browser.msie,isMozilla=$.browser.mozilla,isSafari=$.browser.safari,isOpera=$.browser.opera,bShowPanel=false,bClickCancel=true,bShowModal=false,bCheckEscInit=false;
var _jPanel,_jShadow,_jCntLine,_jPanelButton;
var jModal,jModalShadow,layerShadow,jOverlay,jHideSelect,onModalRemove;
var editorRoot;
$('script[src*=xheditor]').each(function(){
var s=this.src;
if(s.match(/xheditor[^\/]*\.js/i)){editorRoot=s.replace(/[\?#].*$/, '').replace(/(^|[\/\\])[^\/]*$/, '$1');return false;}
});
var specialKeys={ 27: 'esc', 9: 'tab', 32:'space', 13: 'enter', 8:'backspace', 145: 'scroll',
20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',
35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down',
112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12' };
var itemColors=['#FFFFFF','#CCCCCC','#C0C0C0','#999999','#666666','#333333','#000000','#FFCCCC','#FF6666','#FF0000','#CC0000','#990000','#660000','#330000','#FFCC99','#FF9966','#FF9900','#FF6600','#CC6600','#993300','#663300','#FFFF99','#FFFF66','#FFCC66','#FFCC33','#CC9933','#996633','#663333','#FFFFCC','#FFFF33','#FFFF00','#FFCC00','#999900','#666600','#333300','#99FF99','#66FF99','#33FF33','#33CC00','#009900','#006600','#003300','#99FFFF','#33FFFF','#66CCCC','#00CCCC','#339999','#336666','#003333','#CCFFFF','#66FFFF','#33CCFF','#3366FF','#3333FF','#000099','#000066','#CCCCFF','#9999FF','#6666CC','#6633FF','#6600CC','#333399','#330099','#FFCCFF','#FF99FF','#CC66CC','#CC33CC','#993399','#663366','#330033'];
var arrBlocktag=[{n:'p',t:'普通段落'},{n:'h1',t:'標題1'},{n:'h2',t:'標題2'},{n:'h3',t:'標題3'},{n:'h4',t:'標題4'},{n:'h5',t:'標題5'},{n:'h6',t:'標題6'},{n:'pre',t:'已編排格式'},{n:'address',t:'地址'}];
var arrFontname=[{n:'新細明體',c:'PMingLiu'},{n:'細明體',c:'mingliu'},{n:'標楷體',c:'DFKai-SB'},{n:'微軟正黑體',c:'Microsoft JhengHei'},{n:'Arial'},{n:'Arial Narrow'},{n:'Arial Black'},{n:'Comic Sans MS'},{n:'Courier New'},{n:'System'},{n:'Times New Roman'},{n:'Tahoma'},{n:'Verdana'}];
var arrFontsize=[{n:'xx-small',wkn:'x-small',s:'8pt',t:'極小'},{n:'x-small',wkn:'small',s:'10pt',t:'特小'},{n:'small',wkn:'medium',s:'12pt',t:'小'},{n:'medium',wkn:'large',s:'14pt',t:'中'},{n:'large',wkn:'x-large',s:'18pt',t:'大'},{n:'x-large',wkn:'xx-large',s:'24pt',t:'特大'},{n:'xx-large',wkn:'-webkit-xxx-large',s:'36pt',t:'極大'}];
var menuAlign=[{s:'靠左對齊',v:'justifyleft'},{s:'置中',v:'justifycenter'},{s:'靠右對齊',v:'justifyright'},{s:'左右對齊',v:'justifyfull'}],menuList=[{s:'數字列表',v:'insertOrderedList'},{s:'符號列表',v:'insertUnorderedList'}];
var htmlPastetext='<div>使用鍵盤快捷鍵(Ctrl+V)把內容貼上到方框裡,按 確定</div><div><textarea id="xhePastetextValue" wrap="soft" spellcheck="false" style="width:300px;height:100px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlLink='<div>鏈接地址: <input type="text" id="xheLinkUrl" value="http://" class="xheText" /></div><div>打開方式: <select id="xheLinkTarget"><option selected="selected" value="">預設</option><option value="_blank">新窗口</option><option value="_self">當前窗口</option><option value="_parent">父窗口</option></select></div><div style="display:none">鏈接文字: <input type="text" id="xheLinkText" value="" class="xheText" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlImg='<div>圖片文件: <input type="text" id="xheImgUrl" value="http://" class="xheText" /></div><div>替換文本: <input type="text" id="xheImgAlt" /></div><div>對齊方式: <select id="xheImgAlign"><option selected="selected" value="">預設</option><option value="left">靠左對齊</option><option value="right">靠右對齊</option><option value="top">頂端</option><option value="middle">置中</option><option value="baseline">基線</option><option value="bottom">底邊</option></select></div><div>寬度高度: <input type="text" id="xheImgWidth" style="width:40px;" /> x <input type="text" id="xheImgHeight" style="width:40px;" /></div><div>邊框大小: <input type="text" id="xheImgBorder" style="width:40px;" /></div><div>水平間距: <input type="text" id="xheImgHspace" style="width:40px;" /> 垂直間距: <input type="text" id="xheImgVspace" style="width:40px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlFlash='<div>動畫文件: <input type="text" id="xheFlashUrl" value="http://" class="xheText" /></div><div>寬度高度: <input type="text" id="xheFlashWidth" style="width:40px;" value="480" /> x <input type="text" id="xheFlashHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlMedia='<div>媒體文件: <input type="text" id="xheMediaUrl" value="http://" class="xheText" /></div><div>寬度高度: <input type="text" id="xheMediaWidth" style="width:40px;" value="480" /> x <input type="text" id="xheMediaHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlTable='<div>行數列數: <input type="text" id="xheTableRows" style="width:40px;" value="3" /> x <input type="text" id="xheTableColumns" style="width:40px;" value="2" /></div><div>標題單元: <select id="xheTableHeaders"><option selected="selected" value="">無</option><option value="row">第一行</option><option value="col">第一列</option><option value="both">第一行和第一列</option></select></div><div>寬度高度: <input type="text" id="xheTableWidth" style="width:40px;" value="200" /> x <input type="text" id="xheTableHeight" style="width:40px;" value="" /></div><div>邊框大小: <input type="text" id="xheTableBorder" style="width:40px;" value="1" /></div><div>表格間距: <input type="text" id="xheTableCellSpacing" style="width:40px;" value="1" /> 表格填充: <input type="text" id="xheTableCellPadding" style="width:40px;" value="1" /></div><div>對齊方式: <select id="xheTableAlign"><option selected="selected" value="">預設</option><option value="left">靠左對齊</option><option value="center">置中</option><option value="right">靠右對齊</option></select></div><div>表格標題: <input type="text" id="xheTableCaption" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlAbout='<div style="font:12px Arial;width:245px;word-wrap:break-word;word-break:break-all;"><p><span style="font-size:20px;color:#1997DF;">xhEditor</span><br />v1.1.1 (build 101002)</p><p>xhEditor是基於jQuery開發的跨平台輕量XHTML編輯器,基於<a href="http://www.gnu.org/licenses/lgpl.html" target="_blank">LGPL</a>開源協議發佈。</p><p>Copyright c <a href="http://xheditor.com/" target="_blank">xhEditor.com</a>. All rights reserved.</p></div>';
var itemEmots={'default':{name:'預設',width:24,height:24,line:7,list:{'smile':'微笑','tongue':'吐舌頭','titter':'偷笑','laugh':'大笑','sad':'難過','wronged':'委屈','fastcry':'快哭了','cry':'哭','wail':'大哭','mad':'生氣','knock':'敲打','curse':'罵人','crazy':'抓狂','angry':'發火','ohmy':'驚訝','awkward':'尷尬','panic':'驚恐','shy':'害羞','cute':'可憐','envy':'羨慕','proud':'得意','struggle':'奮鬥','quiet':'安靜','shutup':'閉嘴','doubt':'疑問','despise':'鄙視','sleep':'睡覺','bye':'再見'}}};
var arrTools={Cut:{t:'剪下 (Ctrl+X)'},Copy:{t:'複製 (Ctrl+C)'},Paste:{t:'貼上 (Ctrl+V)'},Pastetext:{t:'貼上文本',h:isIE?0:1},Blocktag:{t:'段落標籤',h:1},Fontface:{t:'字型',h:1},FontSize:{t:'字型大小',h:1},Bold:{t:'粗體 (Ctrl+B)',s:'Ctrl+B'},Italic:{t:'斜體 (Ctrl+I)',s:'Ctrl+I'},Underline:{t:'底線 (Ctrl+U)',s:'Ctrl+U'},Strikethrough:{t:'刪除線 (Ctrl+S)',s:'Ctrl+S'},FontColor:{t:'字型顏色',h:1},BackColor:{t:'背景顏色',h:1},SelectAll:{t:'全選 (Ctrl+A)'},Removeformat:{t:'刪除文字格式'},Align:{t:'對齊',h:1},List:{t:'列表',h:1},Outdent:{t:'減少縮排 (Shift+Tab)',s:'Shift+Tab'},Indent:{t:'增加縮排 (Tab)',s:'Tab'},Link:{t:'超連結 (Ctrl+K)',s:'Ctrl+K',h:1},Unlink:{t:'取消超連結'},Img:{t:'圖片',h:1},Flash:{t:'Flash動畫',h:1},Media:{t:'多媒體文件',h:1},Emot:{t:'表情',s:'ctrl+e',h:1},Table:{t:'表格',h:1},Source:{t:'原始碼'},Preview:{t:'預覽'},Print:{t:'打印 (Ctrl+P)',s:'Ctrl+P'},Fullscreen:{t:'全螢幕編輯 (Esc)',s:'Esc'},About:{t:'關於 xhEditor'}};
var toolsThemes={
mini:'Bold,Italic,Underline,Strikethrough,|,Align,List,|,Link,Img',
simple:'Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,|,Align,List,Outdent,Indent,|,Link,Img,Emot',
full:'Cut,Copy,Paste,Pastetext,|,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,SelectAll,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Img,Flash,Media,Emot,Table,|,Source,Preview,Print,Fullscreen'};
toolsThemes.mfull=toolsThemes.full.replace(/\|(,Align)/i,'/$1');
var arrDbClick={'a':'Link','img':'Img','embed':'Embed'},uploadInputname='filedata';
$.xheditor=function(textarea,options)
{
var defaults={skin:'default',tools:'full',clickCancelDialog:true,linkTag:false,internalScript:false,inlineScript:false,internalStyle:true,inlineStyle:true,showBlocktag:false,forcePtag:true,upLinkExt:"zip,rar,txt",upImgExt:"jpg,jpeg,gif,png",upFlashExt:"swf",upMediaExt:"wmv,avi,wma,mp3,mid",modalWidth:350,modalHeight:220,modalTitle:true,defLinkText:'點擊打開鏈接',layerShadow:3,emotMark:false,upBtnText:'上傳',wordDeepClean:true,hoverExecDelay:100,html5Upload:true,upMultiple:99};
var _this=this,_text=textarea,_jText=$(_text),_jForm=_jText.closest('form'),_jTools,_jArea,_win,_jWin,_doc,_jDoc;
var bookmark;
var bInit=false,bSource=false,bFullscreen=false,bCleanPaste=false,outerScroll,bShowBlocktag=false,sLayoutStyle='',ev=null,timer,bDisableHoverExec=false,bQuickHoverExec=false;
var lastPoint=null,lastAngle=null;//鼠標懸停顯示
var editorHeight=0;
var settings=_this.settings=$.extend({},defaults,options );
var plugins=settings.plugins,strPlugins=[];
if(plugins)
{
arrTools=$.extend({},arrTools,plugins);
$.each(plugins,function(n){strPlugins.push(n);});
strPlugins=strPlugins.join(',');
}
if(settings.tools.match(/^\s*(m?full|simple|mini)\s*$/i))
{
var toolsTheme=toolsThemes[$.trim(settings.tools)];
settings.tools=(settings.tools.match(/m?full/i)&&plugins)?toolsTheme.replace('Table','Table,'+strPlugins):toolsTheme;//插件接在full的Table後面
}
if(!settings.tools.match(/(^|,)\s*About\s*(,|$)/i))settings.tools+=',About';
settings.tools=settings.tools.split(',');
if(settings.editorRoot)editorRoot=settings.editorRoot;
editorRoot=getLocalUrl(editorRoot,'abs');
//基本控件名
var idCSS='xheCSS_'+settings.skin,idContainer='xhe'+xCount+'_container',idTools='xhe'+xCount+'_Tool',idIframeArea='xhe'+xCount+'_iframearea',idIframe='xhe'+xCount+'_iframe',idFixFFCursor='xhe'+xCount+'_fixffcursor';
var headHTML='',bodyClass='',skinPath=editorRoot+'xheditor_skin/'+settings.skin+'/',arrEmots=itemEmots,urlType=settings.urlType,urlBase=settings.urlBase,emotPath=settings.emotPath,emotPath=emotPath?emotPath:editorRoot+'xheditor_emot/',selEmotGroup='';
arrEmots=$.extend({},arrEmots,settings.emots);
emotPath=getLocalUrl(emotPath,'rel',urlBase?urlBase:null);//返回最短表情路徑
bShowBlocktag=settings.showBlocktag;
if(bShowBlocktag)bodyClass+=' showBlocktag';
var arrShortCuts=[];
this.init=function()
{
//加載樣式表
if($('#'+idCSS).length==0)$('head').append('<link id="'+idCSS+'" rel="stylesheet" type="text/css" href="'+skinPath+'ui.css" />');
//初始化編輯器
var cw = settings.width || _text.style.width || _jText.outerWidth();
editorHeight = settings.height || _text.style.height || _jText.outerHeight();
if(is(editorHeight,'string'))editorHeight=editorHeight.replace(/[^\d]+/g,'');
if(cw<=0||editorHeight<=0)//禁止對隱藏區域裡的textarea初始化編輯器
{
alert('當前textarea處於隱藏狀態,請將之顯示後再初始化xhEditor,或者直接設置textarea的width和height樣式');
return false;
}
if(/^[0-9\.]+$/i.test(''+cw))cw+='px';
//編輯器CSS背景
var editorBackground=settings.background || _text.style.background;
//工具欄內容初始化
var arrToolsHtml=['<span class="xheGStart"/>'],tool,cn,regSeparator=/\||\//i;
$.each(settings.tools,function(i,n)
{
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGEnd"/>');
if(n=='|')arrToolsHtml.push('<span class="xheSeparator"/>');
else if(n=='/')arrToolsHtml.push('<br />');
else
{
tool=arrTools[n];
if(!tool)return;
if(tool.c)cn=tool.c;
else cn='xheIcon xheBtn'+n;
arrToolsHtml.push('<span><a href="javascript:void(0);" title="'+tool.t+'" name="'+n+'" class="xheButton xheEnabled" tabindex="-1"><span class="'+cn+'" unselectable="on" /></a></span>');
if(tool.s)_this.addShortcuts(tool.s,n);
}
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGStart"/>');
});
arrToolsHtml.push('<span class="xheGEnd"/><br />');
_jText.after($('<input type="text" id="'+idFixFFCursor+'" style="position:absolute;display:none;" /><span id="'+idContainer+'" class="xhe_'+settings.skin+'" style="display:none"><table cellspacing="0" cellpadding="0" class="xheLayout" style="width:'+cw+';height:'+editorHeight+'px;"><tbody><tr><td id="'+idTools+'" class="xheTool" unselectable="on" style="height:1px;"></td></tr><tr><td id="'+idIframeArea+'" class="xheIframeArea"><iframe frameborder="0" id="'+idIframe+'" src="javascript:;" style="width:100%;"></iframe></td></tr></tbody></table></span>'));
_jTools=$('#'+idTools);_jArea=$('#'+idIframeArea);
headHTML='<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><link rel="stylesheet" href="'+skinPath+'iframe.css"/>';
var loadCSS=settings.loadCSS;
if(loadCSS)
{
if(is(loadCSS,'array'))for(var i in loadCSS)headHTML+='<link rel="stylesheet" href="'+loadCSS[i]+'"/>';
else
{
if(loadCSS.match(/\s*<style(\s+[^>]*?)?>[\s\S]+?<\/style>\s*/i))headHTML+=loadCSS;
else headHTML+='<link rel="stylesheet" href="'+loadCSS+'"/>';
}
}
var iframeHTML='<html><head>'+headHTML;
if(editorBackground)iframeHTML+='<style>body{background:'+editorBackground+';}</style>';
iframeHTML+='</head><body spellcheck="false" class="editMode'+bodyClass+'"></body></html>';
_this.win=_win=$('#'+idIframe)[0].contentWindow;
_jWin=$(_win);
try{
this.doc=_doc = _win.document;_jDoc=$(_doc);
_doc.open();
_doc.write(iframeHTML);
_doc.close();
if(isIE)_doc.body.contentEditable='true';
else _doc.designMode = 'On';
}catch(e){}
setTimeout(setOpts,300);
_this.setSource();
_win.setInterval=null;//針對jquery 1.3無法操作iframe window問題的hack
//添加工具欄
_jTools.append(arrToolsHtml.join('')).bind('mousedown contextmenu',returnFalse).click(function(event)
{
var jButton=$(event.target).closest('a');
if(jButton.is('.xheEnabled'))
{
ev=event;
_this.exec(jButton.attr('name'));
}
return false;
});
_jTools.find('.xheButton').hover(function(event){//鼠標懸停執行
var jButton=$(this),delay=settings.hoverExecDelay;
var tAngle=lastAngle;lastAngle=null;
if(delay==-1||bDisableHoverExec||!jButton.is('.xheEnabled'))return false;
if(tAngle&&tAngle>10)//檢測誤操作
{
bDisableHoverExec=true;
setTimeout(function(){bDisableHoverExec=false;},100);
return false;
}
var cmd=jButton.attr('name'),bHover=arrTools[cmd].h==1;
if(!bHover)
{
_this.hidePanel();//移到非懸停按鈕上隱藏面板
return false;
}
if(bQuickHoverExec)delay=0;
if(delay>=0)timer=setTimeout(function(){
ev=event;
lastPoint={x:ev.clientX,y:ev.clientY};
_this.exec(cmd);
},delay);
},function(event){lastPoint=null;if(timer)clearTimeout(timer);}).mousemove(function(event){
if(lastPoint)
{
var diff={x:event.clientX-lastPoint.x,y:event.clientY-lastPoint.y};
if(Math.abs(diff.x)>1||Math.abs(diff.y)>1)
{
if(diff.x>0&&diff.y>0)
{
var tAngle=Math.round(Math.atan(diff.y/diff.x)/0.017453293);
if(lastAngle)lastAngle=(lastAngle+tAngle)/2
else lastAngle=tAngle;
}
else lastAngle=null;
lastPoint={x:event.clientX,y:event.clientY};
}
}
});
//初始化面板
_jPanel=$('#xhePanel');
_jShadow=$('#xheShadow');
_jCntLine=$('#xheCntLine');
if(_jPanel.length==0)
{
_jPanel=$('<div id="xhePanel"></div>').mousedown(function(ev){ev.stopPropagation()});
_jShadow=$('<div id="xheShadow"></div>');
_jCntLine=$('<div id="xheCntLine"></div>');
setTimeout(function(){
$(document.body).append(_jPanel).append(_jShadow).append(_jCntLine);
},10);
}
//切換顯示區域
$('#'+idContainer).show();
_jText.hide();
_jArea.css('height',editorHeight-_jTools.outerHeight());
//綁定內核事件
_jText.focus(_this.focus);
_jForm.submit(saveResult).bind('reset', loadReset);
$(window).bind('unload beforeunload',saveResult).bind('resize',fixFullHeight);
$(document).mousedown(clickCancelPanel);
if(!bCheckEscInit){$(document).keydown(checkEsc);bCheckEscInit=true;}
_jWin.focus(function(){if(settings.focus)settings.focus();}).blur(function(){if(settings.blur)settings.blur();});
if(isSafari)_jWin.click(fixAppleSel);
_jDoc.mousedown(clickCancelPanel).keydown(checkShortcuts).keypress(forcePtag).dblclick(checkDblClick).bind('mousedown click',function(ev){_jText.trigger(ev.type);});
if(isIE)
{
//IE控件上Backspace會導致頁面後退
_jDoc.keydown(function(ev){var rng=_this.getRng();if(ev.which==8&&rng.item){$(rng.item(0)).remove();return false;}});
//修正IE拖動img大小不更新width和height屬性值的問題
function fixResize(ev)
{
var jImg=$(ev.target),v;
if(v=jImg.css('width'))jImg.css('width','').attr('width',v.replace(/[^0-9%]+/g, ''));
if(v=jImg.css('height'))jImg.css('height','').attr('height',v.replace(/[^0-9%]+/g, ''));
}
_jDoc.bind('controlselect',function(ev){
ev=ev.target;if(!$.nodeName(ev,'IMG'))return;
$(ev).unbind('resizeend',fixResize).bind('resizeend',fixResize);
});
}
var jBody=$(_doc.documentElement);
jBody.bind('paste',cleanPaste);
if(settings.disableContextmenu)jBody.bind('contextmenu',returnFalse);
//HTML5編輯區域直接拖放上傳
if(settings.html5Upload)jBody.bind('dragenter dragover',function(ev){var types;if((types=ev.originalEvent.dataTransfer.types)&&$.inArray('Files', types)!=-1)return false;}).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0){
var i,cmd,arrCmd=['Link','Img','Flash','Media'],arrExt=[],strExt;
for(i in arrCmd){
cmd=arrCmd[i];
if(settings['up'+cmd+'Url']&&settings['up'+cmd+'Url'].match(/^[^!].*/i))arrExt.push(cmd+':,'+settings['up'+cmd+'Ext']);//允許上傳
}
if(arrExt.length==0)return false;//禁止上傳
else strExt=arrExt.join(',');
function getCmd(fileList){
var match,fileExt,cmd;
for(i=0;i<fileList.length;i++){
fileExt=fileList[i].fileName.replace(/.+\./,'');
if(match=strExt.match(new RegExp('(\\w+):[^:]*,'+fileExt+'(?:,|$)','i'))){
if(!cmd)cmd=match[1];
else if(cmd!=match[1])return 2;
}
else return 1;
}
return cmd;
}
cmd=getCmd(fileList);
if(cmd==1)alert('上傳文件的擴展名必需為:'+strExt.replace(/\w+:,/g,''));
else if(cmd==2)alert('每次只能拖放上傳同一類型文件');
else if(cmd){
_this.startUpload(fileList,settings['up'+cmd+'Url'],'*',function(arrMsg){
var arrUrl=[],msg,onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用戶上傳回調
for(i in arrMsg){
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!')url=url.substr(1);
arrUrl.push(url);
}
_this.exec(cmd);
$('#xhe'+cmd+'Url').val(arrUrl.join(' '));
$('#xheSave').click();
});
}
return false;
}
});
//添加用戶快捷鍵
var shortcuts=settings.shortcuts;
if(shortcuts)$.each(shortcuts,function(key,func){_this.addShortcuts(key,func);});
xCount++;
bInit=true;
if(settings.fullscreen)_this.toggleFullscreen();
else if(settings.sourceMode)setTimeout(_this.toggleSource,20);
return true;
}
this.remove=function()
{
_this.hidePanel();
saveResult();//卸載前同步最新內容到textarea
//取消綁定事件
_jText.unbind('focus',_this.focus);
_jForm.unbind('submit',saveResult).unbind('reset', loadReset);
$(window).unbind('unload beforeunload',saveResult).unbind('resize',fixFullHeight);
$(document).unbind('mousedown',clickCancelPanel);
$('#'+idContainer+','+'#'+idFixFFCursor).remove();
_jText.show();
bInit=false;
}
this.saveBookmark=function(){
if(!bSource){
var rng=_this.getRng();
rng=rng.cloneRange?rng.cloneRange():rng;
bookmark={'top':_jWin.scrollTop(),'rng':rng};
}
}
this.loadBookmark=function()
{
if(bSource||!bookmark)return;
_this.focus();
var rng=bookmark.rng;
if(isIE)rng.select();
else
{
var sel=_this.getSel();
sel.removeAllRanges();
sel.addRange(rng);
}
_jWin.scrollTop(bookmark.top);
bookmark=null;
}
this.focus=function()
{
if(!bSource)_jWin.focus();
else $('#sourceCode',_doc).focus();
return false;
}
this.setCursorFirst=function(firstBlock)
{
_this.focus();_win.scrollTo(0,0);
var rng=_this.getRng(),_body=_doc.body,firstNode=_body,firstTag;
if(firstBlock&&firstNode.firstChild&&(firstTag=firstNode.firstChild.tagName)&&firstTag.match(/^p|div|h[1-6]$/i))firstNode=_body.firstChild;
isIE?rng.moveToElementText(firstNode):rng.setStart(firstNode,0);
rng.collapse(true);
if(isIE)rng.select();
else{var sel=_this.getSel();sel.removeAllRanges();sel.addRange(rng);}
}
this.getSel=function()
{
return _win.getSelection ? _win.getSelection() : _doc.selection;
}
this.getRng=function()
{
var sel=_this.getSel(),rng;
try{
rng = sel.rangeCount > 0 ? sel.getRangeAt(0) : (sel.createRange ? sel.createRange() : (_doc.createRange?_doc.createRange():_doc.body.createTextRange()));
}catch (ex){}
return rng;
}
this.getParent=function(tag)
{
var rng=_this.getRng(),p;
if(!isIE)
{
p = rng.commonAncestorContainer;
if(!rng.collapsed)if(rng.startContainer == rng.endContainer&&rng.startOffset - rng.endOffset < 2&&rng.startContainer.hasChildNodes())p = rng.startContainer.childNodes[rng.startOffset];
}
else p=rng.item?rng.item(0):rng.parentElement();
tag=tag?tag:'*';p=$(p);
if(!p.is(tag))p=$(p).closest(tag);
return p;
}
this.getSelect=function(format)
{
var sel=_this.getSel(),rng=_this.getRng(),isCollapsed=true;
if (!rng || rng.item)isCollapsed=false
else isCollapsed=!sel || rng.boundingWidth == 0 || rng.collapsed;
if(format=='text')return isCollapsed ? '' : (rng.text || (sel.toString ? sel.toString() : ''));
var sHtml;
if(rng.cloneContents)
{
var tmp=$('<div></div>'),c;
c = rng.cloneContents();
if(c)tmp.append(c);
sHtml=tmp.html();
}
else if(is(rng.item))sHtml=rng.item(0).outerHTML;
else if(is(rng.htmlText))sHtml=rng.htmlText;
else sHtml=rng.toString();
if(isCollapsed)sHtml='';
sHtml=_this.processHTML(sHtml,'read');
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
return sHtml;
}
this.pasteHTML=function(sHtml,bStart)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
var sel=_this.getSel(),rng=_this.getRng();
if(bStart!=undefined)//非覆蓋式插入
{
if(rng.item)
{
var n=rng.item(0);
rng=_doc.body.createTextRange();
rng.moveToElementText(n);
rng.select();
}
rng.collapse(bStart);
}
sHtml+='<'+(isIE?'img':'span')+' id="_xhe_temp" style="display:none" />';
if(rng.insertNode)
{
rng.deleteContents();
rng.insertNode(rng.createContextualFragment(sHtml));
}
else
{
if(sel.type.toLowerCase()=='control'){sel.clear();rng=_this.getRng();};
rng.pasteHTML(sHtml);
}
var jTemp=$('#_xhe_temp',_doc),temp=jTemp[0];
if(isIE)
{
rng.moveToElementText(temp);
rng.select();
}
else
{
rng.selectNode(temp);
sel.removeAllRanges();
sel.addRange(rng);
}
jTemp.remove();
}
this.pasteText=function(text,bStart)
{
if(!text)text='';
text=_this.domEncode(text);
text = text.replace(/\r?\n/g, '<br />');
_this.pasteHTML(text,bStart);
}
this.appendHTML=function(sHtml)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
$(_doc.body).append(sHtml);
}
this.domEncode=function(str)
{
return str.replace(/[<>]/g,function(c){return {'<':'<','>':'>'}[c];});
}
this.setSource=function(sHtml)
{
bookmark=null;
if(typeof sHtml!='string'&&sHtml!='')sHtml=_text.value;
if(bSource)$('#sourceCode',_doc).val(sHtml);
else
{
if(settings.beforeSetSource)sHtml=settings.beforeSetSource(sHtml);
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
sHtml=_this.cleanWord(sHtml);
sHtml=_this.processHTML(sHtml,'write');
if(isIE){//修正IE會刪除可視內容前的script,style,<!--
_doc.body.innerHTML='<img id="_xhe_temp" style="display:none" />'+sHtml;
$('#_xhe_temp',_doc).remove();
}
else _doc.body.innerHTML=sHtml;
}
}
this.processHTML=function(sHtml,mode)
{
var appleClass=' class="Apple-style-span"';
if(mode=='write')
{//write
//恢復emot
function restoreEmot(all,attr,q,emot)
{
emot=emot.split(',');
if(!emot[1]){emot[1]=emot[0];emot[0]=''}
if(emot[0]=='default')emot[0]='';
return all.replace(/\s+src\s*=\s*(["']?).*?\1(\s|$|\/|>)/i,'$2').replace(attr,' src="'+emotPath+(emot[0]?emot[0]:'default')+'/'+emot[1]+'.gif"'+(settings.emotMark?' emot="'+(emot[0]?emot[0]+',':'')+emot[1]+'"'+(all.match(/\s+alt\s*=\s*(["']?)\s*(.*?)\s*\1[\s\/>]/i)?'':' alt="'+emot[1]+'"'):''));
}
sHtml = sHtml.replace(/<img(?:\s+[^>]*?)?(\s+emot\s*=\s*(["']?)\s*(.*?)\s*\2)(?:\s+[^>]*?)?\/?>/ig,restoreEmot);
//保存屬性值:src,href
function saveValue(all,tag,attr,n,q,v){return all.replace(attr,(urlBase?(' '+n+'="'+getLocalUrl(v,'abs',urlBase)+'"'):attr)+' _xhe_'+n+'="'+v+'"');}
sHtml = sHtml.replace(/<(\w+(?:\:\w+)?)(?:\s+[^>]*?)?(\s+(src|href)\s*=\s*(["']?)\s*(.*?)\s*\4)(?:\s+[^>]*?)?\/?>/ig,saveValue);
sHtml = sHtml.replace(/<(\/?)del(\s+[^>]*?)?>/ig,'<$1strike$2>');//編輯狀態統一轉為strike
if(isMozilla)
{
sHtml = sHtml.replace(/<(\/?)strong(\s+[^>]*?)?>/ig,'<$1b$2>');
sHtml = sHtml.replace(/<(\/?)em(\s+[^>]*?)?>/ig,'<$1i$2>');
}
else if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.n){s=t.wkn;break;}
}
return pre+'font-size:'+s+aft;
});
sHtml = sHtml.replace(/<strong(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-weight: bold;"$1>');
sHtml = sHtml.replace(/<em(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-style: italic;"$1>');
sHtml = sHtml.replace(/<u(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: underline;"$1>');
sHtml = sHtml.replace(/<strike(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: line-through;"$1>');
sHtml = sHtml.replace(/<\/(strong|em|u|strike)>/ig,'</span>');
sHtml = sHtml.replace(/<span((?:\s+[^>]*?)?\s+style="([^"]*;)*\s*(font-family|font-size|color|background-color)\s*:\s*[^;"]+\s*;?"[^>]*)>/ig,'<span'+appleClass+'$1>');
}
else if(isIE)
{
sHtml = sHtml.replace(/'/ig, ''');
sHtml = sHtml.replace(/\s+(disabled|checked|readonly|selected)\s*=\s*[\"\']?(false|0)[\"\']?/ig, '');
}
sHtml = sHtml.replace(/<a(\s+[^>]*?)?\/>/,'<a$1></a>');
if(!isSafari)
{
//style轉font
function style2font(all,tag,style,content)
{
var attrs='',f,s1,s2,c;
f=style.match(/font-family\s*:\s*([^;"]+)/i);
if(f)attrs+=' face="'+f[1]+'"';
s1=style.match(/font-size\s*:\s*([^;"]+)/i);
if(s1)
{
s1=s1[1].toLowerCase();
for(var j=0;j<arrFontsize.length;j++)if(s1==arrFontsize[j].n||s1==arrFontsize[j].s){s2=j+1;break;}
if(s2)
{
attrs+=' size="'+s2+'"';
style=style.replace(/(^|;)(\s*font-size\s*:\s*[^;"]+;?)+/ig,'$1');
}
}
c=style.match(/(?:^|[\s;])color\s*:\s*([^;"]+)/i);
if(c)
{
var rgb;
if(rgb=c[1].match(/\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)){c[1]='#';for(var i=1;i<=3;i++)c[1]+=(rgb[i]-0).toString(16);}
c[1]=c[1].replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,'#$1$1$2$2$3$3');
attrs+=' color="'+c[1]+'"';
}
style=style.replace(/(^|;)(\s*(font-family|color)\s*:\s*[^;"]+;?)+/ig,'$1');
if(attrs!='')
{
if(style)attrs+=' style="'+style+'"';
return '<font'+attrs+'>'+content+"</font>";
}
else return all;
}
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,style2font);//最裡層
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,style2font);//第2層
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,style2font);//第3層
}
}
else
{//read
//恢復屬性值src,href
function restoreValue(all,n,q,v)
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
return all.replace(new RegExp('\\s+'+n+'\\s*=\\s*(["\']?).*?\\1(\\s|/?>)','ig'),' '+n+'="'+v.replace(/\$/g,'$$$$')+'"$2');
}
sHtml = sHtml.replace(/<(?:\w+(?:\:\w+)?)(?:\s+[^>]*?)?\s+_xhe_(src|href)\s*=\s*(["']?)\s*(.*?)\s*\2(?:\s+[^>]*?)?\/?>/ig,restoreValue);
if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.wkn){s=t.n;break;}
}
return pre+'font-size:'+s+aft;
});
var arrAppleSpan=[{r:/font-weight:\sbold/ig,t:'strong'},{r:/font-style:\sitalic/ig,t:'em'},{r:/text-decoration:\sunderline/ig,t:'u'},{r:/text-decoration:\sline-through/ig,t:'strike'}];
function replaceAppleSpan(all,tag,attr1,attr2,content)
{
var attr=attr1+attr2,newTag='';
if(!attr)return content;
for(var i=0;i<arrAppleSpan.length;i++)
{
if(attr.match(arrAppleSpan[i].r))
{
newTag=arrAppleSpan[i].t;
break;
}
}
if(newTag)return '<'+newTag+'>'+content+'</'+newTag+'>';
else return all;
}
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,replaceAppleSpan);//最裡層
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第2層
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第3層
}
if(!isIE){//字符間的文本換行強制轉br
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/([^<>\r\n]?)((?:\r?\n)+)([^<>\r\n]?)/ig,function(all,left,br,right){if(left||right)return left+br.replace(/\r?\n/g,'<br />')+right;else return all;});
});
}
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+(?:_xhe_|_moz_|_webkit_)[^=]+?\s*=\s*(["']?).*?\2(\s|\/?>)/ig,'$1$3');
sHtml = sHtml.replace(/(<\w+[^>]*?)\s+class\s*=\s*(["']?)\s*(?:apple|webkit)\-.+?\s*\2(\s|\/?>)/ig, "$1$3");
sHtml = sHtml.replace(/<img(\s+[^>]+?)\/?>/ig,function(all,attr){if(!attr.match(/\s+alt\s*(["']?).*?\1(\s|$)/i))attr+=' alt=""';return '<img'+attr+' />';});//img強制加alt
sHtml = sHtml.replace(/\s+jquery\d+="\d+"/ig,'');
}
return sHtml;
}
this.getSource=function(bFormat)
{
var sHtml,beforeGetSource=settings.beforeGetSource;
if(bSource)
{
sHtml=$('#sourceCode',_doc).val();
if(!beforeGetSource){
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/(\t*\r?\n\t*)+/g,'')//標準HTML模式清理縮排和換行
});
}
}
else
{
sHtml=_this.processHTML(_doc.body.innerHTML,'read');
sHtml=sHtml.replace(/^\s*(?:<(p|div)(?:\s+[^>]*?)?>)?\s*(<br(?:\s+[^>]*?)?>)*\s*(?:<\/\1>)?\s*$/i, '');//修正Firefox在空內容情況下多出來的代碼
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml,bFormat);
sHtml=_this.cleanWord(sHtml);
if(beforeGetSource)sHtml=beforeGetSource(sHtml);
}
_text.value=sHtml;
return sHtml;
}
this.cleanWord=function(sHtml)
{
if(sHtml.match(/mso(-|normal)|WordDocument/i))
{
var deepClean=settings.wordDeepClean;
//格式化
sHtml = sHtml.replace(/(<link(?:\s+[^>]*?)?)\s+href\s*=\s*(["']?)\s*file:\/\/.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, '');
//區塊標籤清理
sHtml = sHtml.replace(/<!--[\s\S]*?-->|<!(--)?\[[\s\S]+?\](--)?>|<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
sHtml = sHtml.replace(/<\/?\w+:[^>]*>/ig, '');
if(deepClean)sHtml = sHtml.replace(/<\/?(span|a|img)(\s+[^>]*?)?>/ig,'');
//屬性清理
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+class\s*=\s*(["']?)\s*mso.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//刪除所有mso開頭的樣式
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+lang\s*=\s*(["']?)\s*.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//刪除lang屬性
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+align\s*=\s*(["']?)\s*left\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//取消align=left
//樣式清理
sHtml = sHtml.replace(/<\w+(?:\s+[^>]*?)?(\s+style\s*=\s*(["']?)\s*([\s\S]*?)\s*\2)(?:\s+[^>]*?)?\s*\/?>/ig,function(all,attr,p,styles){
styles=$.trim(styles.replace(/\s*(mso-[^:]+:.+?|margin\s*:\s*0cm 0cm 0pt\s*|(text-align|font-variant|line-height)\s*:\s*.+?)(;|$)\s*/ig,''));
return all.replace(attr,deepClean?'':styles?' style="'+styles+'"':'');
});
}
return sHtml;
}
this.cleanHTML=function(sHtml)
{
sHtml = sHtml.replace(/<!?\/?(DOCTYPE|html|body|meta)(\s+[^>]*?)?>/ig, '');
var arrHeadSave;sHtml = sHtml.replace(/<head(?:\s+[^>]*?)?>([\s\S]*?)<\/head>/i, function(all,content){arrHeadSave=content.match(/<(script|style)(\s+[^>]*?)?>[\s\S]*?<\/\1>/ig);return '';});
if(arrHeadSave)sHtml=arrHeadSave.join('')+sHtml;
sHtml = sHtml.replace(/<\??xml(:\w+)?(\s+[^>]*?)?>([\s\S]*?<\/xml>)?/ig, '');
if(!settings.linkTag)sHtml = sHtml.replace(/<link(\s+[^>]*?)?>/ig, '');
if(!settings.internalScript)sHtml = sHtml.replace(/<script(\s+[^>]*?)?>[\s\S]*?<\/script>/ig, '');
if(!settings.inlineScript)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+on(?:click|dblclick|mousedown|mouseup|mousemove|mouseover|mouseout|mouseenter|mouseleave|keydown|keypress|keyup|change|select|submit|reset|blur|focus|load|unload)\s*=\s*(["']?)[\s\S]*?\3((?:\s+[^>]*?)?\/?>)/ig,'$1$2$4');
if(!settings.internalStyle)sHtml = sHtml.replace(/<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
if(!settings.inlineStyle)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+(style|class)\s*=\s*(["']?)[\s\S]*?\4((?:\s+[^>]*?)?\/?>)/ig,'$1$2$5');
sHtml=sHtml.replace(/<\/(strong|b|u|strike|em|i)>((?:\s|<br\/?>| )*?)<\1(\s+[^>]*?)?>/ig,'$2');//連續相同標籤
return sHtml;
}
this.formatXHTML=function(sHtml,bFormat)
{
var emptyTags = makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");//HTML 4.01
var blockTags = makeMap("address,applet,blockquote,button,center,dd,dir,div,dl,dt,fieldset,form,frameset,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");//HTML 4.01
var inlineTags = makeMap("a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");//HTML 4.01
var closeSelfTags = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
var fillAttrsTags = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
var specialTags = makeMap("script,style");
var tagReplac={'b':'strong','i':'em','s':'del','strike':'del'};
var startTag = /^<\??(\w+(?:\:\w+)?)((?:\s+[\w-\:]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/(\w+(?:\:\w+)?)[^>]*>/;
var attr = /\s+([\w-]+(?:\:\w+)?)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s]+)))?/g;
var skip=0,stack=[],last=sHtml,results=Array(),lvl=-1,lastTag='body',lastTagStart;
stack.last = function(){return this[ this.length - 1 ];};
while(last.length>0)
{
if(!stack.last()||!specialTags[stack.last()])
{
skip=0;
if(last.substring(0, 4)=='<!--')
{//註釋標籤
skip=last.indexOf("-->");
if(skip!=-1)
{
skip+=3;
addHtmlFrag(last.substring(0,skip));
}
}
else if(last.substring(0, 2)=='</')
{//結束標籤
match = last.match( endTag );
if(match)
{
parseEndTag(match[1]);
skip = match[0].length;
}
}
else if(last.charAt(0)=='<')
{//開始標籤
match = last.match( startTag );
if(match)
{
parseStartTag(match[1],match[2],match[3]);
skip = match[0].length;
}
}
if(skip==0)//普通文本
{
skip=last.indexOf('<');
if(skip==0)skip=1;
else if(skip<0)skip=last.length;
addHtmlFrag(_this.domEncode(last.substring(0,skip)));
}
last=last.substring(skip);
}
else
{//處理style和script
last=last.replace(/^([\s\S]*?)<\/(style|script)>/i, function(all, script,tagName){
results.push(script);
return ''
});
parseEndTag(stack.last());
}
}
parseEndTag();
sHtml=results.join('');
results=null;
function makeMap(str)
{
var obj = {}, items = str.split(",");
for ( var i = 0; i < items.length; i++ )obj[ items[i] ] = true;
return obj;
}
function processTag(tagName)
{
if(tagName)
{
tagName=tagName.toLowerCase();
var tag=tagReplac[tagName];
if(tag)tagName=tag;
}
else tagName='';
return tagName;
}
function parseStartTag(tagName,rest,unary)
{
tagName=processTag(tagName);
if(blockTags[tagName])while(stack.last()&&inlineTags[stack.last()])parseEndTag(stack.last());
if(closeSelfTags[tagName]&&stack.last()==tagName)parseEndTag(tagName);
unary = emptyTags[ tagName ] || !!unary;
if (!unary)stack.push(tagName);
var all=Array();
all.push('<' + tagName);
rest.replace(attr, function(match, name)
{
name=name.toLowerCase();
var value = arguments[2] ? arguments[2] :
arguments[3] ? arguments[3] :
arguments[4] ? arguments[4] :
fillAttrsTags[name] ? name : "";
all.push(' '+name+'="'+value+'"');
});
all.push((unary ? " /" : "") + ">");
addHtmlFrag(all.join(''),tagName,true);
}
function parseEndTag(tagName)
{
if(!tagName)var pos=0;//清空棧
else
{
tagName=processTag(tagName);
for(var pos=stack.length-1;pos>=0;pos--)if(stack[pos]==tagName)break;//向上尋找匹配的開始標籤
}
if(pos>=0)
{
for(var i=stack.length-1;i>=pos;i--)addHtmlFrag("</" + stack[i] + ">",stack[i]);
stack.length=pos;
}
}
function addHtmlFrag(html,tagName,bStart)
{
if(bFormat==true)
{
html=html.replace(/(\t*\r?\n\t*)+/g,'');//清理換行符和相鄰的製表符
if(html.match(/^\s*$/))return;//不格式化空內容的標籤
var bBlock=blockTags[tagName],tag=bBlock?tagName:'';
if(bBlock)
{
if(bStart)lvl++;//塊開始
if(lastTag=='')lvl--;//補文本結束
}
else if(lastTag)lvl++;//文本開始
if(tag!=lastTag||bBlock)addIndent();
results.push(html);
if(tagName=='br')addIndent();//回車強制換行
if(bBlock&&(emptyTags[tagName]||!bStart))lvl--;//塊結束
lastTag=bBlock?tagName:'';lastTagStart=bStart;
}
else results.push(html);
}
function addIndent(){results.push('\r\n');if(lvl>0){var tabs=lvl;while(tabs--)results.push("\t");}}
//font轉style
function font2style(all,tag,attrs,content)
{
if(!attrs)return content;
var styles='',f,s,c,style;
f=attrs.match(/ face\s*=\s*"\s*([^"]+)\s*"/i);
if(f)styles+='font-family:'+f[1]+';';
s=attrs.match(/ size\s*=\s*"\s*(\d+)\s*"/i);
if(s)styles+='font-size:'+arrFontsize[(s[1]>7?7:(s[1]<1?1:s[1]))-1].n+';';
c=attrs.match(/ color\s*=\s*"\s*([^"]+)\s*"/i);
if(c)styles+='color:'+c[1]+';';
style=attrs.match(/ style\s*=\s*"\s*([^"]+)\s*"/i);
if(style)styles+=style[1];
if(styles)content='<span style="'+styles+'">'+content+'</span>';
return content;
}
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,font2style);//最裡層
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,font2style);//第2層
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,font2style);//第3層
sHtml = sHtml.replace(/^(\s*\r?\n)+|(\s*\r?\n)+$/g,'');//清理首尾換行
sHtml = sHtml.replace(/(\t*\r?\n)+/g,'\r\n');//多行變一行
return sHtml;
}
this.toggleShowBlocktag=function(state)
{
if(bShowBlocktag===state)return;
bShowBlocktag=!bShowBlocktag;
var _jBody=$(_doc.body);
if(bShowBlocktag)
{
bodyClass+=' showBlocktag';
_jBody.addClass('showBlocktag');
}
else
{
bodyClass=bodyClass.replace(' showBlocktag','');
_jBody.removeClass('showBlocktag');
}
}
this.toggleSource=function(state)
{
if(bSource===state)return;
_jTools.find('[name=Source]').toggleClass('xheEnabled').toggleClass('xheActive');
var _body=_doc.body,jBody=$(_body),sHtml;
var sourceCode,cursorMark='<span id="_xhe_cursor'+new Date().getTime()+'"></span>',cursorPos=0;
if(!bSource)
{//轉為原始碼模式
_this.pasteHTML(cursorMark,true);//標記當前位置
sHtml=_this.getSource(true);
cursorPos=sHtml.indexOf(cursorMark);
if(!isOpera)cursorPos=sHtml.substring(0,cursorPos).replace(/\r/g,'').length;//修正非opera光標定位點
sHtml=sHtml.replace(cursorMark,'');
if(isIE)_body.contentEditable='false';
else _doc.designMode = 'Off';
jBody.attr('scroll','no').attr('class','sourceMode').html('<textarea id="sourceCode" wrap="soft" spellcheck="false" height="100%" />');
sourceCode=$('#sourceCode',jBody).blur(_this.getSource)[0];
}
else
{//轉為編輯模式
sHtml=_this.getSource();
jBody.html('').removeAttr('scroll').attr('class','editMode'+bodyClass);
if(isIE)_body.contentEditable='true';
else _doc.designMode = 'On';
if(isMozilla)
{
_this._exec("inserthtml","-");//修正firefox原始碼切換回來無法刪除文字的問題
$('#'+idFixFFCursor).show().focus().hide();//臨時修正Firefox 3.6光標丟失問題
}
}
bSource=!bSource;
_this.setSource(sHtml);
if(bSource)//光標定位源碼
{
_this.focus();
if(sourceCode.setSelectionRange)sourceCode.setSelectionRange(cursorPos, cursorPos);
else
{
var rng = sourceCode.createTextRange();
rng.move("character",cursorPos);
rng.select();
}
}
else _this.setCursorFirst(true);//定位最前面
_jTools.find('[name=Source],[name=Preview]').toggleClass('xheEnabled');
_jTools.find('.xheButton').not('[name=Source],[name=Fullscreen],[name=About]').toggleClass('xheEnabled');
setTimeout(setOpts,300);
}
this.showPreview=function()
{
var beforeSetSource=settings.beforeSetSource,sContent=_this.getSource();
if(beforeSetSource)sContent=beforeSetSource(sContent);
var sHTML='<html><head>'+headHTML+'<title>預覽</title>'+(urlBase?'<base href="'+urlBase+'"/>':'')+'</head><body>' + sContent + '</body></html>';
var screen=window.screen,oWindow=window.open('', 'xhePreview', 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+Math.round(screen.width*0.9)+',height='+Math.round(screen.height*0.8)+',left='+Math.round(screen.width*0.05)),oDoc=oWindow.document;
oDoc.open();
oDoc.write(sHTML);
oDoc.close();
oWindow.focus();
}
this.toggleFullscreen=function(state)
{
if(bFullscreen===state)return;
var jLayout=$('#'+idContainer).find('.xheLayout'),jContainer=$('#'+idContainer);
if(bFullscreen)
{//取消全屏
jLayout.attr('style',sLayoutStyle);
_jArea.height(editorHeight-_jTools.outerHeight());
setTimeout(function(){$(window).scrollTop(outerScroll);},10);
}
else
{//顯示全屏
outerScroll=$(window).scrollTop();
sLayoutStyle=jLayout.attr('style');
jLayout.removeAttr('style');
_jArea.height('100%');
setTimeout(fixFullHeight,100);
}
if(isMozilla)//臨時修正Firefox 3.6原始碼光標丟失問題
{
$('#'+idFixFFCursor).show().focus().hide();
setTimeout(_this.focus,1);
}
bFullscreen=!bFullscreen;
jContainer.toggleClass('xhe_Fullscreen');
$('html').toggleClass('xhe_Fullfix');
_jTools.find('[name=Fullscreen]').toggleClass('xheActive');
setTimeout(setOpts,300);
}
this.showMenu=function(menuitems,callback)
{
var jMenu=$('<div class="xheMenu"></div>'),arrItem=[];
$.each(menuitems,function(n,v){arrItem.push('<a href="javascript:void(0);" title="'+(v.t?v.t:v.s)+'" v="'+v.v+'">'+v.s+'</a>');});
jMenu.append(arrItem.join(''));
jMenu.click(function(ev){callback($(ev.target).closest('a').attr('v'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jMenu);
}
this.showColor=function(callback)
{
var jColor=$('<div class="xheColor"></div>'),arrItem=[],count=0;
$.each(itemColors,function(n,v)
{
if(count%7==0)arrItem.push((count>0?'</div>':'')+'<div>');
arrItem.push('<a href="javascript:void(0);" xhev="'+v+'" title="'+v+'" style="background:'+v+'"></a>');
count++;
});
arrItem.push('</div>');
jColor.append(arrItem.join(''));
jColor.click(function(ev){ev=ev.target;if(!$.nodeName(ev,'A'))return;callback($(ev).attr('xhev'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jColor);
}
this.showPastetext=function()
{
var jPastetext=$(htmlPastetext),jValue=$('#xhePastetextValue',jPastetext),jSave=$('#xheSave',jPastetext);
jSave.click(function(){
_this.loadBookmark();
var sValue=jValue.val();
if(sValue)_this.pasteText(sValue);
_this.hidePanel();
return false;
});
_this.showDialog(jPastetext);
}
this.showLink=function()
{
var jLink=$(htmlLink),jParent=_this.getParent('a'),jText=$('#xheLinkText',jLink),jUrl=$('#xheLinkUrl',jLink),jTarget=$('#xheLinkTarget',jLink),jSave=$('#xheSave',jLink),selHtml=_this.getSelect();
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'href'));
jTarget.attr('value',jParent.attr('target'));
}
else if(selHtml=='')jText.val(settings.defLinkText).closest('div').show();
if(settings.upLinkUrl)_this.uploadInit(jUrl,settings.upLinkUrl,settings.upLinkExt);
jSave.click(function(){
var url=jUrl.val();
_this.loadBookmark();
if(url==''||jParent.length==0)_this._exec('unlink');
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sTarget=jTarget.val(),sText=jText.val();
if(aUrl.length>1)
{//批量插入
_this._exec('unlink');//批量前刪除當前鏈接並重新獲取選擇內容
selHtml=_this.getSelect();
var sTemplate='<a href="xhe_tmpurl"',sLink,arrLink=[];
if(sTarget!='')sTemplate+=' target="'+sTarget+'"';
sTemplate+='>xhe_tmptext</a>';
sText=(selHtml!=''?selHtml:(sText?sText:url));
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sLink=sTemplate;
sLink=sLink.replace('xhe_tmpurl',url[0]);
sLink=sLink.replace('xhe_tmptext',url[1]?url[1]:sText);
arrLink.push(sLink);
}
}
_this.pasteHTML(arrLink.join(' '));
}
else
{//單url模式
url=aUrl[0].split('||');
if(!sText)sText=url[0];
sText=url[1]?url[1]:(selHtml!='')?'':sText?sText:url[0];
if(jParent.length==0)
{
if(sText)_this.pasteHTML('<a href="#xhe_tmpurl">'+sText+'</a>');
else _this._exec('createlink','#xhe_tmpurl');
jParent=$('a[href$="#xhe_tmpurl"]',_doc);
}
else if(sText&&!isSafari)jParent.text(sText);//safari改寫文本會導致光標丟失
xheAttr(jParent,'href',url[0]);
if(sTarget!='')jParent.attr('target',sTarget);
else jParent.removeAttr('target');
}
}
_this.hidePanel();
return false;
});
_this.showDialog(jLink);
}
this.showImg=function()
{
var jImg=$(htmlImg),jParent=_this.getParent('img'),jUrl=$('#xheImgUrl',jImg),jAlt=$('#xheImgAlt',jImg),jAlign=$('#xheImgAlign',jImg),jWidth=$('#xheImgWidth',jImg),jHeight=$('#xheImgHeight',jImg),jBorder=$('#xheImgBorder',jImg),jVspace=$('#xheImgVspace',jImg),jHspace=$('#xheImgHspace',jImg),jSave=$('#xheSave',jImg);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jAlt.val(jParent.attr('alt'));
jAlign.val(jParent.attr('align'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
jBorder.val(jParent.attr('border'));
var vspace=jParent.attr('vspace'),hspace=jParent.attr('hspace');
jVspace.val(vspace<=0?'':vspace);
jHspace.val(hspace<=0?'':hspace);
}
if(settings.upImgUrl)_this.uploadInit(jUrl,settings.upImgUrl,settings.upImgExt);
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sAlt=jAlt.val(),sAlign=jAlign.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sBorder=jBorder.val(),sVspace=jVspace.val(),sHspace=jHspace.val();;
if(aUrl.length>1)
{//批量插入
var sTemplate='<img src="xhe_tmpurl"',sImg,arrImg=[];
if(sAlt!='')sTemplate+=' alt="'+sAlt+'"';
if(sAlign!='')sTemplate+=' align="'+sAlign+'"';
if(sWidth!='')sTemplate+=' width="'+sWidth+'"';
if(sHeight!='')sTemplate+=' height="'+sHeight+'"';
if(sBorder!='')sTemplate+=' border="'+sBorder+'"';
if(sVspace!='')sTemplate+=' vspace="'+sVspace+'"';
if(sHspace!='')sTemplate+=' hspace="'+sHspace+'"';
sTemplate+=' />';
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sImg=sTemplate;
sImg=sImg.replace('xhe_tmpurl',url[0]);
if(url[1])sImg='<a href="'+url[1]+'" target="_blank">'+sImg+'</a>'
arrImg.push(sImg);
}
}
_this.pasteHTML(arrImg.join(' '));
}
else if(aUrl.length==1)
{//單URL模式
url=aUrl[0];
if(url!='')
{
url=url.split('||');
if(jParent.length==0)
{
_this.pasteHTML('<img src="'+url[0]+'#xhe_tmpurl" />');
jParent=$('img[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0])
if(sAlt!='')jParent.attr('alt',sAlt);
if(sAlign!='')jParent.attr('align',sAlign);
else jParent.removeAttr('align');
if(sWidth!='')jParent.attr('width',sWidth);
else jParent.removeAttr('width');
if(sHeight!='')jParent.attr('height',sHeight);
else jParent.removeAttr('height');
if(sBorder!='')jParent.attr('border',sBorder);
else jParent.removeAttr('border');
if(sVspace!='')jParent.attr('vspace',sVspace);
else jParent.removeAttr('vspace');
if(sHspace!='')jParent.attr('hspace',sHspace);
else jParent.removeAttr('hspace');
if(url[1])
{
var jLink=jParent.parent('a');
if(jLink.length==0)
{
jParent.wrap('<a></a>');
jLink=jParent.parent('a');
}
xheAttr(jLink,'href',url[1]);
jLink.attr('target','_blank');
}
}
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
_this.showDialog(jImg);
}
this.showEmbed=function(sType,sHtml,sMime,sClsID,sBaseAttrs,sUploadUrl,sUploadExt)
{
var jEmbed=$(sHtml),jParent=_this.getParent('embed[type="'+sMime+'"],embed[classid="'+sClsID+'"]'),jUrl=$('#xhe'+sType+'Url',jEmbed),jWidth=$('#xhe'+sType+'Width',jEmbed),jHeight=$('#xhe'+sType+'Height',jEmbed),jSave=$('#xheSave',jEmbed);
if(sUploadUrl)_this.uploadInit(jUrl,sUploadUrl,sUploadExt);
_this.showDialog(jEmbed);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
}
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var w=jWidth.val(),h=jHeight.val(),reg=/^[0-9]+$/;
if(!reg.test(w))w=412;if(!reg.test(h))h=300;
var sBaseCode='<embed type="'+sMime+'" classid="'+sClsID+'" src="xhe_tmpurl"'+sBaseAttrs;
var aUrl=url.split(' ');
if(aUrl.length>1)
{//批量插入
var sTemplate=sBaseCode+'',sEmbed,arrEmbed=[];
sTemplate+=' width="xhe_width" height="xhe_height" />';
for(var i in aUrl)
{
url=aUrl[i].split('||');
sEmbed=sTemplate;
sEmbed=sEmbed.replace('xhe_tmpurl',url[0])
sEmbed=sEmbed.replace('xhe_width',url[1]?url[1]:w)
sEmbed=sEmbed.replace('xhe_height',url[2]?url[2]:h)
if(url!='')arrEmbed.push(sEmbed);
}
_this.pasteHTML(arrEmbed.join(' '));
}
else if(aUrl.length==1)
{//單URL模式
url=aUrl[0].split('||');
if(jParent.length==0)
{
_this.pasteHTML(sBaseCode.replace('xhe_tmpurl',url[0]+'#xhe_tmpurl')+' />');
jParent=$('embed[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0]);
jParent.attr('width',url[1]?url[1]:w);
jParent.attr('height',url[2]?url[2]:h);
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
}
this.showEmot=function(group)
{
var jEmot=$('<div class="xheEmot"></div>');
group=group?group:(selEmotGroup?selEmotGroup:'default');
var arrEmot=arrEmots[group];
var sEmotPath=emotPath+group+'/',n=0,arrList=[],jList='';
var ew=arrEmot.width,eh=arrEmot.height,line=arrEmot.line,count=arrEmot.count,list=arrEmot.list;
if(count)
{
for(var i=1;i<=count;i++)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+i+'.gif);" emot="'+group+','+i+'" xhev=""> </a>');
if(n%line==0)arrList.push('<br />');
}
}
else
{
$.each(list,function(id,title)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+id+'.gif);" emot="'+group+','+id+'" title="'+title+'" xhev="'+title+'"> </a>');
if(n%line==0)arrList.push('<br />');
});
}
var w=line*(ew+12),h=Math.ceil(n/line)*(eh+12),mh=w*0.75;
if(h<=mh)mh='';
jList=$('<style>'+(mh?'.xheEmot div{width:'+(w+20)+'px;height:'+mh+'px;}':'')+'.xheEmot div a{width:'+ew+'px;height:'+eh+'px;}</style><div>'+arrList.join('')+'</div>').click(function(ev){ev=ev.target;var jA=$(ev);if(!$.nodeName(ev,'A'))return;_this.pasteHTML('<img emot="'+jA.attr('emot')+'" alt="'+jA.attr('xhev')+'">');_this.hidePanel();return false;}).mousedown(returnFalse);
jEmot.append(jList);
var gcount=0,arrGroup=['<ul>'],jGroup;//表情分類
$.each(arrEmots,function(g,v){
gcount++;
arrGroup.push('<li'+(group==g?' class="cur"':'')+'><a href="javascript:void(0);" group="'+g+'">'+v.name+'</a></li>');
});
if(gcount>1)
{
arrGroup.push('</ul><br style="clear:both;" />');
jGroup=$(arrGroup.join('')).click(function(ev){selEmotGroup=$(ev.target).attr('group');_this.exec('Emot');return false;}).mousedown(returnFalse);
jEmot.append(jGroup);
}
_this.showPanel(jEmot);
}
this.showTable=function()
{
var jTable=$(htmlTable),jRows=$('#xheTableRows',jTable),jColumns=$('#xheTableColumns',jTable),jHeaders=$('#xheTableHeaders',jTable),jWidth=$('#xheTableWidth',jTable),jHeight=$('#xheTableHeight',jTable),jBorder=$('#xheTableBorder',jTable),jCellSpacing=$('#xheTableCellSpacing',jTable),jCellPadding=$('#xheTableCellPadding',jTable),jAlign=$('#xheTableAlign',jTable),jCaption=$('#xheTableCaption',jTable),jSave=$('#xheSave',jTable);
jSave.click(function(){
_this.loadBookmark();
var sCaption=jCaption.val(),sBorder=jBorder.val(),sRows=jRows.val(),sCols=jColumns.val(),sHeaders=jHeaders.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sCellSpacing=jCellSpacing.val(),sCellPadding=jCellPadding.val(),sAlign=jAlign.val();
var i,j,htmlTable='<table'+(sBorder!=''?' border="'+sBorder+'"':'')+(sWidth!=''?' width="'+sWidth+'"':'')+(sHeight!=''?' width="'+sHeight+'"':'')+(sCellSpacing!=''?' cellspacing="'+sCellSpacing+'"':'')+(sCellPadding!=''?' cellpadding="'+sCellPadding+'"':'')+(sAlign!=''?' align="'+sAlign+'"':'')+'>';
if(sCaption!='')htmlTable+='<caption>'+sCaption+'</caption>';
if(sHeaders=='row'||sHeaders=='both')
{
htmlTable+='<tr>';
for(i=0;i<sCols;i++)htmlTable+='<th scope="col"> </th>';
htmlTable+='</tr>';
sRows--;
}
htmlTable+='<tbody>';
for(i=0;i<sRows;i++)
{
htmlTable+='<tr>';
for(j=0;j<sCols;j++)
{
if(j==0&&(sHeaders=='col'||sHeaders=='both'))htmlTable+='<th scope="row"> </th>';
else htmlTable+='<td> </td>';
}
htmlTable+='</tr>';
}
htmlTable+='</tbody></table>';
_this.pasteHTML(htmlTable);
_this.hidePanel();
return false;
});
_this.showDialog(jTable);
}
this.showAbout=function()
{
var jAbout=$(htmlAbout);
_this.showDialog(jAbout);
}
this.addShortcuts=function(key,cmd)
{
key=key.toLowerCase();
if(arrShortCuts[key]==undefined)arrShortCuts[key]=Array();
arrShortCuts[key].push(cmd);
}
this.delShortcuts=function(key){delete arrShortCuts[key];}
this.uploadInit=function(jText,toUrl,upext)
{
var jUpload=$('<span class="xheUpload"><input type="text" style="visibility:hidden;" tabindex="-1" /><input type="button" value="'+settings.upBtnText+'" class="xheBtn" tabindex="-1" /></span>'),jUpBtn=$('.xheBtn',jUpload);
var bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
jText.after(jUpload);jUpBtn.before(jText);
toUrl=toUrl.replace(/{editorRoot}/ig,editorRoot);
if(toUrl.substr(0,1)=='!')//自定義上傳管理頁
{
jUpBtn.click(function(){
bShowPanel=false;//防止按鈕面板被關閉
_this.showIframeModal('上傳文件',toUrl.substr(1),setUploadMsg,null,null,function(){bShowPanel=true;});
});
}
else
{//系統預設ajax上傳
jUpload.append('<input type="file"'+(upMultiple>1?' multiple=""':'')+' class="xheFile" size="13" name="'+uploadInputname+'" tabindex="-1" />');
var jFile=$('.xheFile',jUpload),arrMsg;
jFile.change(function(){arrMsg=[];_this.startUpload(jFile[0],toUrl,upext,setUploadMsg);});
setTimeout(function(){//拖放上傳
jText.closest('.xheDialog').bind('dragenter dragover',returnFalse).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(bHtml5Upload&&dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0)_this.startUpload(fileList,toUrl,upext,setUploadMsg);
return false;
});
},10);
}
function setUploadMsg(arrMsg)
{
if(is(arrMsg,'string'))arrMsg=[arrMsg];//允許單URL傳遞
var bImmediate=false,i,count=arrMsg.length,msg,url,arrUrl=[],onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用戶上傳回調
for(i=0;i<count;i++)
{
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!'){bImmediate=true;url=url.substr(1);}
arrUrl.push(url);
}
jText.val(arrUrl.join(' '));
if(bImmediate)jText.closest('.xheDialog').find('#xheSave').click();
}
}
this.startUpload=function(fromFiles,toUrl,limitExt,onUploadComplete)
{
var arrMsg=[],bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
var upload,fileList,filename,jUploadTip=$('<div style="padding:22px 0;text-align:center;line-height:30px;">文件上傳中,請稍候……<br /></div>'),sLoading='<img src="'+skinPath+'img/loading.gif">';
if(!bHtml5Upload||(fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0])))
{
if(!checkFileExt(fromFiles.value,limitExt))return;
jUploadTip.append(sLoading);
upload=new _this.html4Upload(fromFiles,toUrl,onUploadCallback);
}
else
{
if(!fileList)fileList=fromFiles;//拖放文件列表
var i,len=fileList.length;
if(len>upMultiple){alert('請不要一次上傳超過'+upMultiple+'個文件');return;}
for(i=0;i<len;i++)if(!checkFileExt(fileList[i].fileName,limitExt))return;
var jProgress=$('<div class="xheProgress"><div><span>0%</span></div></div>');
jUploadTip.append(jProgress);
upload=new _this.html5Upload(uploadInputname,fileList,toUrl,onUploadCallback,function(ev){
if(ev.loaded>=0)
{
var sPercent=Math.round((ev.loaded * 100) / ev.total)+'%';
$('div',jProgress).css('width',sPercent);
$('span',jProgress).text(sPercent+' ( '+formatBytes(ev.loaded)+' / '+formatBytes(ev.total)+' )');
}
else jProgress.replaceWith(sLoading);//不支持進度
});
}
var panelState=bShowPanel;
if(panelState)bShowPanel=false;//防止面板被關閉
_this.showModal('文件上傳中(Esc取消上傳)',jUploadTip,320,150,function(){bShowPanel=panelState;upload.remove();});
upload.start();
function onUploadCallback(sText,bFinish)
{
var data=Object,bOK=false;
try{data=eval('('+sText+')');}catch(ex){};
if(data.err==undefined||data.msg==undefined)alert(toUrl+' 上傳接口發生錯誤!\r\n\r\n返回的錯誤內容為: \r\n\r\n'+sText);
else
{
if(data.err)alert(data.err);
else
{
arrMsg.push(data.msg);
bOK=true;//繼續下一個文件上傳
}
}
if(!bOK||bFinish)_this.removeModal();
if(bFinish&&bOK)onUploadComplete(arrMsg);//全部上傳完成
return bOK;
}
}
this.html4Upload=function(fromfile,toUrl,callback)
{
var uid = new Date().getTime(),idIO='jUploadFrame'+uid,_this=this;
var jIO=$('<iframe name="'+idIO+'" class="xheHideArea" />').appendTo('body');
var jForm=$('<form action="'+toUrl+'" target="'+idIO+'" method="post" enctype="multipart/form-data" class="xheHideArea"></form>').appendTo('body');
var jOldFile = $(fromfile),jNewFile = jOldFile.clone().attr('disabled','true');
jOldFile.before(jNewFile).appendTo(jForm);
this.remove=function()
{
if(_this!=null)
{
jNewFile.before(jOldFile).remove();
jIO.remove();jForm.remove();
_this=null;
}
}
this.onLoad=function(){callback($(jIO[0].contentWindow.document.body).text(),true);}
this.start=function(){jForm.submit();jIO.load(_this.onLoad);}
return this;
}
this.html5Upload=function(inputname,fromFiles,toUrl,callback,onProgress)
{
var xhr,i=0,count=fromFiles.length,allLoaded=0,allSize=0,_this=this;
for(var j=0;j<count;j++)allSize+=fromFiles[j].fileSize;
this.remove=function(){if(xhr){xhr.abort();xhr=null;}}
this.uploadNext=function(sText)
{
if(sText)//當前文件上傳完成
{
allLoaded+=fromFiles[i-1].fileSize;
returnProgress(0);
}
if((!sText||(sText&&callback(sText,i==count)==true))&&i<count)postFile(fromFiles[i++],toUrl,_this.uploadNext,function(loaded){returnProgress(loaded);});
}
this.start=function(){_this.uploadNext();}
function postFile(fromfile,toUrl,callback,onProgress)
{
xhr = new XMLHttpRequest(),upload=xhr.upload;
xhr.onreadystatechange=function(){if(xhr.readyState==4)callback(xhr.responseText);};
if(upload)upload.onprogress=function(ev){onProgress(ev.loaded);};
else onProgress(-1);//不支持進度
xhr.open("POST", toUrl);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Content-Disposition', 'attachment; name="'+inputname+'"; filename="'+fromfile.fileName+'"');
if(xhr.sendAsBinary)xhr.sendAsBinary(fromfile.getAsBinary());
else xhr.send(fromfile);
}
function returnProgress(loaded){if(onProgress)onProgress({'loaded':allLoaded+loaded,'total':allSize});}
}
this.showIframeModal=function(title,ifmurl,callback,w,h,onRemove)
{
var jContent=$('<iframe frameborder="0" src="'+ifmurl.replace(/{editorRoot}/ig,editorRoot)+'" style="width:100%;height:100%;display:none;" /><div class="xheModalIfmWait"></div>'),jIframe=$(jContent[0]),jWait=$(jContent[1]);
_this.showModal(title,jContent,w,h,onRemove);
jIframe.load(function(){
var modalWin=jIframe[0].contentWindow,jModalDoc=$(modalWin.document);
modalWin.callback=function(v){_this.removeModal();callback(v);};
modalWin.unloadme=_this.removeModal;
jModalDoc.keydown(_this.checkEsc);
jIframe.show();jWait.remove();
});
}
this.showModal=function(title,content,w,h,onRemove)
{
if(bShowModal)return false;//只能彈出一個模式窗口
layerShadow=settings.layerShadow;
w=w?w:settings.modalWidth;h=h?h:settings.modalHeight;
jModal=$('<div class="xheModal" style="width:'+(w-1)+'px;height:'+h+'px;margin-left:-'+Math.ceil(w/2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+Math.ceil(h/2)+'px')+'">'+(settings.modalTitle?'<div class="xheModalTitle"><span class="xheModalClose" title="關閉 (Esc)"></span>'+title+'</div>':'')+'<div class="xheModalContent"></div></div>').appendTo('body');
jOverlay=$('<div class="xheModalOverlay"></div>').appendTo('body');
if(layerShadow>0)jModalShadow=$('<div class="xheModalShadow" style="width:'+jModal.outerWidth()+'px;height:'+jModal.outerHeight()+'px;margin-left:-'+(Math.ceil(w/2)-layerShadow-2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+(Math.ceil(h/2)-layerShadow-2)+'px')+'"></div>').appendTo('body');
$('.xheModalContent',jModal).css('height',h-(settings.modalTitle?$('.xheModalTitle').outerHeight():0)).html(content);
if(isIE&&browerVer==6.0)jHideSelect=$('select:visible').css('visibility','hidden');//隱藏覆蓋的select
$('.xheModalClose',jModal).click(_this.removeModal);
jOverlay.show();if(layerShadow>0)jModalShadow.show();jModal.show();
bShowModal=true;
onModalRemove=onRemove;
}
this.removeModal=function(){if(jHideSelect)jHideSelect.css('visibility','visible');jModal.html('').remove();if(layerShadow>0)jModalShadow.remove();jOverlay.remove();if(onModalRemove)onModalRemove();bShowModal=false;};
this.showDialog=function(content)
{
var jDialog=$('<div class="xheDialog"></div>'),jContent=$(content),jSave=$('#xheSave',jContent);
if(jSave.length==1)
{
jContent.find('input[type=text],select').keypress(function(ev){if(ev.which==13){jSave.click();return false;}});
jContent.find('textarea').keydown(function(ev){if(ev.ctrlKey&&ev.which==13){jSave.click();return false;}});
jSave.after(' <input type="button" id="xheCancel" value="取消" />');
$('#xheCancel',jContent).click(_this.hidePanel);
if(!settings.clickCancelDialog)
{
bClickCancel=false;//關閉點擊隱藏
var jFixCancel=$('<div class="xheFixCancel"></div>').appendTo('body').mousedown(returnFalse);
var xy=_jArea.offset();
jFixCancel.css({'left':xy.left,'top':xy.top,width:_jArea.outerWidth(),height:_jArea.outerHeight()})
}
jDialog.mousedown(function(){bDisableHoverExec=true;})//點擊對話框禁止懸停執行
}
jDialog.append(jContent);
_this.showPanel(jDialog);
if(!isIE)setTimeout(function(){jDialog.find('input[type=text],textarea').filter(':visible').filter(function(){return $(this).css('visibility')!='hidden';}).eq(0).focus();},10);//定位首個可見輸入表單項,延遲解決opera無法設置焦點
}
this.showPanel=function(content)
{
if(!ev.target)return false;
_jPanel.html('').append(content).css('left',-999).css('top',-999);
_jPanelButton=$(ev.target).closest('a').addClass('xheActive');
var xy=_jPanelButton.offset();
var x=xy.left,y=xy.top;y+=_jPanelButton.outerHeight()-1;
_jCntLine.css({'left':x+1,'top':y,'width':_jPanelButton.width()}).show();
if((x+_jPanel.outerWidth())>document.body.clientWidth)x-=(_jPanel.outerWidth()-_jPanelButton.outerWidth());//向左顯示面板
var layerShadow=settings.layerShadow;
if(layerShadow>0)_jShadow.css({'left':x+layerShadow,'top':y+layerShadow,'width':_jPanel.outerWidth(),'height':_jPanel.outerHeight()}).show();
_jPanel.css({'left':x,'top':y}).show();
bQuickHoverExec=bShowPanel=true;
}
this.hidePanel=function(){if(bShowPanel){_jPanelButton.removeClass('xheActive');_jShadow.hide();_jCntLine.hide();_jPanel.hide();bShowPanel=false;if(!bClickCancel){$('.xheFixCancel').remove();bClickCancel=true;};bQuickHoverExec=bDisableHoverExec=false;lastAngle=null;}}
this.exec=function(cmd)
{
_this.hidePanel();
_this.saveBookmark();
var tool=arrTools[cmd];
if(!tool)return false;//無效命令
if(ev==null)//非鼠標點擊
{
ev={};
var btn=_jTools.find('.xheButton[name='+cmd+']');
if(btn.length==1)ev.target=btn;//設置當前事件焦點
}
if(tool.e)tool.e.call(_this)//插件事件
else//內置工具
{
cmd=cmd.toLowerCase();
switch(cmd)
{
case 'cut':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的瀏覽器安全設置不允許使用剪下操作,請使用鍵盤快捷鍵(Ctrl + X)來完成');};
break;
case 'copy':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的瀏覽器安全設置不允許使用複製操作,請使用鍵盤快捷鍵(Ctrl + C)來完成');}
break;
case 'paste':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的瀏覽器安全設置不允許使用貼上操作,請使用鍵盤快捷鍵(Ctrl + V)來完成');}
break;
case 'pastetext':
if(window.clipboardData)_this.pasteText(window.clipboardData.getData('Text', true));
else _this.showPastetext();
break;
case 'blocktag':
var menuBlocktag=[];
$.each(arrBlocktag,function(n,v){menuBlocktag.push({s:'<'+v.n+'>'+v.t+'</'+v.n+'>',v:'<'+v.n+'>',t:v.t});});
_this.showMenu(menuBlocktag,function(v){_this._exec('formatblock',v);});
break;
case 'fontface':
var menuFontname=[];
$.each(arrFontname,function(n,v){v.c=v.c?v.c:v.n;menuFontname.push({s:'<span style="font-family:'+v.c+'">'+v.n+'</span>',v:v.c,t:v.n});});
_this.showMenu(menuFontname,function(v){_this._exec('fontname',v);});
break;
case 'fontsize':
var menuFontsize=[];
$.each(arrFontsize,function(n,v){menuFontsize.push({s:'<span style="font-size:'+v.s+';">'+v.t+'('+v.s+')</span>',v:n+1,t:v.t});});
_this.showMenu(menuFontsize,function(v){_this._exec('fontsize',v);});
break;
case 'fontcolor':
_this.showColor(function(v){_this._exec('forecolor',v);});
break;
case 'backcolor':
_this.showColor(function(v){if(isIE)_this._exec('backcolor',v);else{setCSS(true);_this._exec('hilitecolor',v);setCSS(false);}});
break;
case 'align':
_this.showMenu(menuAlign,function(v){_this._exec(v);});
break;
case 'list':
_this.showMenu(menuList,function(v){_this._exec(v);});
break;
case 'link':
_this.showLink();
break;
case 'img':
_this.showImg();
break;
case 'flash':
_this.showEmbed('Flash',htmlFlash,'application/x-shockwave-flash','clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000',' wmode="opaque" quality="high" menu="false" play="true" loop="true" allowfullscreen="true"',settings.upFlashUrl,settings.upFlashExt);
break;
case 'media':
_this.showEmbed('Media',htmlMedia,'application/x-mplayer2','clsid:6bf52a52-394a-11d3-b153-00c04f79faa6',' enablecontextmenu="false" autostart="false"',settings.upMediaUrl,settings.upMediaExt);
break;
case 'emot':
_this.showEmot();
break;
case 'table':
_this.showTable();
break;
case 'source':
_this.toggleSource();
break;
case 'preview':
_this.showPreview();
break;
case 'print':
_win.print();
break;
case 'fullscreen':
_this.toggleFullscreen();
break;
case 'about':
_this.showAbout();
break;
default:
_this._exec(cmd);
break;
}
}
ev=null;
}
this._exec=function(cmd,param,noFocus)
{
if(!noFocus)_this.focus();
var state;
if(param!=undefined)state=_doc.execCommand(cmd,false,param);
else state=_doc.execCommand(cmd,false,null);
return state;
}
function checkDblClick(ev)
{
var target=ev.target,tool=arrDbClick[target.tagName.toLowerCase()];
if(tool)
{
if(tool=='Embed')//自動識別Flash和多媒體
{
var arrEmbed={'application/x-shockwave-flash':'Flash','application/x-mplayer2':'Media'};
tool=arrEmbed[target.type.toLowerCase()];
}
_this.exec(tool);
}
}
function checkEsc(ev)
{
if(ev.which==27)
{
if(bShowModal)_this.removeModal();
else if(bShowPanel)_this.hidePanel();
return false;
}
}
function loadReset(){setTimeout(_this.setSource,10);}
function saveResult(){_this.getSource();};
function cleanPaste(ev){
if(bSource||bCleanPaste)return true;
bCleanPaste=true;//解決IE右鍵貼上重複產生paste的問題
_this.saveBookmark();
var jDiv=$('<div style="position:absolute;left:-1000px;top:'+_jWin.scrollTop()+'px;overflow:hidden;width:1px;height:1px;" />',_doc),div=jDiv[0],sel=_this.getSel(),rng=_this.getRng();
$(_doc.body).append(jDiv);
if(isIE){
rng.moveToElementText(div);
rng.execCommand('Paste');
ev.preventDefault();
}
else{
rng.selectNodeContents(div);
sel.removeAllRanges();
sel.addRange(rng);
}
setTimeout(function(){
var sPaste;
if(settings.forcePasteText===true)sPaste=jDiv.text();
else{
sPaste=div.innerHTML;
sPaste=_this.cleanHTML(sPaste);
sPaste=_this.formatXHTML(sPaste);
sPaste=_this.cleanWord(sPaste);
}
jDiv.remove();
_this.loadBookmark();
_this.pasteHTML(sPaste);
bCleanPaste=false;
},0);
}
function setCSS(css)
{
try{_this._exec('styleWithCSS',css,true);}
catch(e)
{try{_this._exec('useCSS',!css,true);}catch(e){}}
}
function setOpts()
{
if(bInit&&!bSource)
{
setCSS(false);
try{_this._exec('enableObjectResizing',true,true);}catch(e){}
//try{_this._exec('enableInlineTableEditing',false,true);}catch(e){}
if(isIE)try{_this._exec('BackgroundImageCache',true,true);}catch(e){}
}
}
function forcePtag(ev)
{
if(bSource||ev.which!=13||ev.shiftKey||ev.ctrlKey||ev.altKey)return true;
var pNode=_this.getParent('p,h1,h2,h3,h4,h5,h6,pre,address,div,li');
if(pNode.is('li'))return true;
if(settings.forcePtag){if(pNode.length==0)_this._exec('formatblock','<p>');}
else
{
_this.pasteHTML('<br />');
if(isIE&&pNode.length>0&&_this.getRng().parentElement().childNodes.length==2)_this.pasteHTML('<br />');
return false;
}
}
function fixFullHeight()
{
if(!isMozilla&&!isSafari)
{
if(bFullscreen)_jArea.height('100%').css('height',_jArea.outerHeight()-_jTools.outerHeight());
if(isIE)_jTools.hide().show();
}
}
function fixAppleSel(e)
{
e=e.target;
if(e.tagName.match(/(img|embed)/i))
{
var sel=_this.getSel(),rng=_this.getRng();
rng.selectNode(e);
sel.removeAllRanges();
sel.addRange(rng);
}
}
function xheAttr(jObj,n,v)
{
if(!n)return false;
var kn='_xhe_'+n;
if(v)//設置屬性
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
jObj.attr(n,urlBase?getLocalUrl(v,'abs',urlBase):v).removeAttr(kn).attr(kn,v);
}
return jObj.attr(kn)||jObj.attr(n);
}
function clickCancelPanel(){if(bClickCancel)_this.hidePanel();}
function checkShortcuts(event)
{
if(bSource)return true;
var code=event.which,special=specialKeys[code],sChar=special?special:String.fromCharCode(code).toLowerCase();
sKey='';
sKey+=event.ctrlKey?'ctrl+':'';sKey+=event.altKey?'alt+':'';sKey+=event.shiftKey?'shift+':'';sKey+=sChar;
var cmd=arrShortCuts[sKey],c;
for(c in cmd)
{
c=cmd[c];
if($.isFunction(c)){if(c.call(_this)===false)return false;}
else{_this.exec(c);return false;}//按鈕獨佔快捷鍵
}
}
function is(o,t)
{
var n = typeof(o);
if (!t)return n != 'undefined';
if (t == 'array' && (o.hasOwnProperty && o instanceof Array))return true;
return n == t;
}
function getLocalUrl(url,urlType,urlBase)//絕對地址:abs,根地址:root,相對地址:rel
{
var baseUrl=urlBase?$('<a href="'+urlBase+'" />')[0]:location,protocol=baseUrl.protocol,host=baseUrl.hostname,port=baseUrl.port,path=baseUrl.pathname.replace(/\\/g,'/').replace(/[^\/]+$/i,'');
port=(port=='')?'80':port;
url=$.trim(url);
if(urlType!='abs')url=url.replace(new RegExp(protocol+'\\/\\/'+host.replace(/\./g,'\\.')+'(?::'+port+')'+(port=='80'?'?':'')+'(\/|$)','i'),'/');
if(urlType=='rel')url=url.replace(new RegExp('^'+path.replace(/([\/\.\+\[\]\(\)])/g,'\\$1'),'i'),'');
if(urlType!='rel')
{
if(!url.match(/^((https?|file):\/\/|\/)/i))url=path+url;
if(url.charAt(0)=='/')//處理..
{
var arrPath=[],arrFolder = url.split('/'),folder,i,l=arrFolder.length;
for(i=0;i<l;i++)
{
folder=arrFolder[i];
if(folder=='..')arrPath.pop();
else if(folder!==''&&folder!='.')arrPath.push(folder);
}
if(arrFolder[l-1]=='')arrPath.push('');
url='/'+arrPath.join('/');
}
}
if(urlType=='abs')if(!url.match(/(https?|file):\/\//i))url=protocol+'//'+location.host+url;
return url;
}
function checkFileExt(filename,limitExt)
{
if(limitExt=='*'||filename.match(new RegExp('\.('+limitExt.replace(/,/g,'|')+')$','i')))return true;
else
{
alert('上傳文件擴展名必需為: '+limitExt);
return false;
}
}
function formatBytes(bytes)
{
var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+s[e];
}
function returnFalse(){return false;}
}
$(function(){
$.fn.oldVal=$.fn.val;
$.fn.val=function(value)
{
var _this=this,editor;
if(value===undefined)if(this[0]&&(editor=this[0].xheditor))return editor.getSource();else return _this.oldVal(value);//讀
return this.each(function(){if(editor=this.xheditor)editor.setSource(value);else _this.oldVal(value);});//寫
}
$('textarea').each(function(){
var self=$(this),xhClass=self.attr('class').match(/(?:^|\s)xheditor(?:\-(m?full|simple|mini))?(?:\s|$)/i);
if(xhClass)self.xheditor(xhClass[1]?{tools:xhClass[1]}:null);
});
});
})(jQuery); | JavaScript |
/*!
* WYSIWYG UBB Editor support for xhEditor
* @requires xhEditor
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 0.9.6 (build 100513)
*/
function ubb2html(sUBB)
{
var i,sHtml=String(sUBB),arrcode=new Array(),cnum=0;
sHtml=sHtml.replace(/&/ig, '&');
sHtml=sHtml.replace(/[<>]/g,function(c){return {'<':'<','>':'>'}[c];});
sHtml=sHtml.replace(/\r?\n/g,"<br />");
sHtml=sHtml.replace(/\[code\s*(?:=\s*([^\]]+?))?\]([\s\S]*?)\[\/code\]/ig,function(all,t,c){//code特殊处理
cnum++;arrcode[cnum]=all;
return "[\tubbcodeplace_"+cnum+"\t]";
});
sHtml=sHtml.replace(/\[(\/?)(b|u|i|s|sup|sub)\]/ig,'<$1$2>');
sHtml=sHtml.replace(/\[color\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/ig,'<font color="$1">');
sHtml=sHtml.replace(/\[size\s*=\s*(\d+?)\s*\]/ig,'<font size="$1">');
sHtml=sHtml.replace(/\[font\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/ig,'<font face="$1">');
sHtml=sHtml.replace(/\[\/(color|size|font)\]/ig,'</font>');
sHtml=sHtml.replace(/\[back\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/ig,'<span style="background-color:$1;">');
sHtml=sHtml.replace(/\[\/back\]/ig,'</span>');
for(i=0;i<3;i++)sHtml=sHtml.replace(/\[align\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\](((?!\[align(?:\s+[^\]]+)?\])[\s\S])*?)\[\/align\]/ig,'<p align="$1">$2</p>');
sHtml=sHtml.replace(/\[img\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/img\]/ig,'<img src="$1" alt="" />');
sHtml=sHtml.replace(/\[img\s*=([^,\]]*)(?:\s*,\s*(\d*%?)\s*,\s*(\d*%?)\s*)?(?:,?\s*(\w+))?\s*\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*)?\s*\[\/img\]/ig,function(all,alt,p1,p2,p3,src){
var str='<img src="'+src+'" alt="'+alt+'"',a=p3?p3:(!isNum(p1)?p1:'');
if(isNum(p1))str+=' width="'+p1+'"';
if(isNum(p2))str+=' height="'+p2+'"'
if(a)str+=' align="'+a+'"';
str+=' />';
return str;
});
sHtml=sHtml.replace(/\[emot\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\/\]/ig,'<img emot="$1" />');
sHtml=sHtml.replace(/\[url\]\s*(((?!")[\s\S])*?)(?:"[\s\S]*?)?\s*\[\/url\]/ig,'<a href="$1">$1</a>');
sHtml=sHtml.replace(/\[url\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]*?)\s*\[\/url\]/ig,'<a href="$1">$2</a>');
sHtml=sHtml.replace(/\[email\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/email\]/ig,'<a href="mailto:$1">$1</a>');
sHtml=sHtml.replace(/\[email\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]+?)\s*\[\/email\]/ig,'<a href="mailto:$1">$2</a>');
sHtml=sHtml.replace(/\[quote\]([\s\S]*?)\[\/quote\]/ig,'<blockquote>$1</blockquote>');
sHtml=sHtml.replace(/\[flash\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/flash\]/ig,function(all,w,h,url){
if(!w)w=480;if(!h)h=400;
return '<embed type="application/x-shockwave-flash" src="'+url+'" wmode="opaque" quality="high" bgcolor="#ffffff" menu="false" play="true" loop="true" width="'+w+'" height="'+h+'"/>';
});
sHtml=sHtml.replace(/\[media\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+)\s*)?)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/media\]/ig,function(all,w,h,play,url){
if(!w)w=480;if(!h)h=400;
return '<embed type="application/x-mplayer2" src="'+url+'" enablecontextmenu="false" autostart="'+(play=='1'?'true':'false')+'" width="'+w+'" height="'+h+'"/>';
});
sHtml=sHtml.replace(/\[table\s*(?:=\s*(\d{1,4}%?)\s*(?:,\s*([^\]"]+)(?:"[^\]]*?)?)?)?\s*\]/ig,function(all,w,b){
var str='<table';
if(w)str+=' width="'+w+'"';
if(b)str+=' bgcolor="'+b+'"';
return str+'>';
});
sHtml=sHtml.replace(/\[tr\s*(?:=\s*([^\]"]+?)(?:"[^\]]*?)?)?\s*\]/ig,function(all,bg){
return '<tr'+(bg?' bgcolor="'+bg+'"':'')+'>';
});
sHtml=sHtml.replace(/\[td\s*(?:=\s*(\d{1,2})\s*,\s*(\d{1,2})\s*(?:,\s*(\d{1,4}%?))?)?\s*\]/ig,function(all,col,row,w){
return '<td'+(col>1?' colspan="'+col+'"':'')+(row>1?' rowspan="'+row+'"':'')+(w?' width="'+w+'"':'')+'>';
});
sHtml=sHtml.replace(/\[\/(table|tr|td)\]/ig,'</$1>');
sHtml=sHtml.replace(/\[\*\]((?:(?!\[\*\]|\[\/list\]|\[list\s*(?:=[^\]]+)?\])[\s\S])+)/ig,'<li>$1</li>');
sHtml=sHtml.replace(/\[list\s*(?:=\s*([^\]"]+?)(?:"[^\]]*?)?)?\s*\]/ig,function(all,type){
var str='<ul';
if(type)str+=' type="'+type+'"';
return str+'>';
});
sHtml=sHtml.replace(/\[\/list\]/ig,'</ul>');
for(i=1;i<=cnum;i++)sHtml=sHtml.replace("[\tubbcodeplace_"+i+"\t]", arrcode[i]);
sHtml=sHtml.replace(/(^|<\/?\w+(?:\s+[^>]*?)?>)([^<$]+)/ig, function(all,tag,text){
return tag+text.replace(/[\t ]/g,function(c){return {'\t':' ',' ':' '}[c];});
});
function isNum(s){if(s!=null&&s!='')return !isNaN(s);else return false;}
return sHtml;
}
function html2ubb(sHtml)
{
var mapSize={'xx-small':1,'8pt':1,'x-small':2,'10pt':2,'small':3,'12pt':3,'medium':4,'14pt':4,'large':5,'18pt':5,'x-large':6,'24pt':6,'xx-large':7,'36pt':7};
var regSrc=/\s+src\s*=\s*(["']?)\s*(.+?)\s*\1(\s|$)/i,regWidth=/\s+width\s*=\s*(["']?)\s*(\d+(?:\.\d+)?%?)\s*\1(\s|$)/i,regHeight=/\s+height\s*=\s*(["']?)\s*(\d+(?:\.\d+)?%?)\s*\1(\s|$)/i,regBg=/(?:background|background-color|bgcolor)\s*[:=]\s*(["']?)\s*((rgb\s*\(\s*\d{1,3}%?,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*\))|(#[0-9a-f]{3,6})|([a-z]{1,20}))\s*\1/i
var i,sUBB=String(sHtml),arrcode=new Array(),cnum=0;
sUBB=sUBB.replace(/\s*\r?\n\s*/g,'');
sUBB = sUBB.replace(/<(script|style)(\s+[^>]*?)?>[\s\S]*?<\/\1>/ig, '');
sUBB = sUBB.replace(/<!--[\s\S]*?-->/ig,'');
sUBB=sUBB.replace(/<br\s*?\/?>/ig,"\r\n");
sUBB=sUBB.replace(/\[code\s*(=\s*([^\]]+?))?\]([\s\S]*?)\[\/code\]/ig,function(all,t,c){//code特殊处理
cnum++;arrcode[cnum]=all;
return "[\tubbcodeplace_"+cnum+"\t]";
});
sUBB=sUBB.replace(/<(\/?)(b|u|i|s)(\s+[^>]*?)?>/ig,'[$1$2]');
sUBB=sUBB.replace(/<(\/?)strong(\s+[^>]*?)?>/ig,'[$1b]');
sUBB=sUBB.replace(/<(\/?)em(\s+[^>]*?)?>/ig,'[$1i]');
sUBB=sUBB.replace(/<(\/?)(strike|del)(\s+[^>]*?)?>/ig,'[$1s]');
sUBB=sUBB.replace(/<(\/?)(sup|sub)(\s+[^>]*?)?>/ig,'[$1$2]');
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color|background|background-color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,function(all,tag,style,content){
var face=style.match(/(?:^|;)\s*font-family\s*:\s*([^;]+)/i),size=style.match(/(?:^|;)\s*font-size\s*:\s*([^;]+)/i),color=style.match(/(?:^|;)\s*color\s*:\s*([^;]+)/i),back=style.match(/(?:^|;)\s*(?:background|background-color)\s*:\s*([^;]+)/i),str=content;
if(face)str='[font='+face[1]+']'+str+'[/font]';
if(size)
{
size=mapSize[size[1].toLowerCase()];
if(size)str='[size='+size+']'+str+'[/size]';
}
if(color)str='[color='+formatColor(color[1])+']'+str+'[/color]';
if(back)str='[back='+formatColor(back[1])+']'+str+'[/back]';
return str;
});
function formatColor(c)
{
var matchs;
if(matchs=c.match(/\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)){c=(matchs[1]*65536+matchs[2]*256+matchs[3]*1).toString(16);while(c.length<6)c='0'+c;c='#'+c;}
c=c.replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,'#$1$1$2$2$3$3');
return c;
}
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(div|p)(?:\s+[^>]*?)?[\s"';]\s*(?:text-)?align\s*[=:]\s*(["']?)\s*(left|center|right)\s*\2[^>]*>(((?!<\1(\s+[^>]*?)?>)[\s\S])+?)<\/\1>/ig,'[align=$3]$4[/align]');
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(center)(?:\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,'[align=center]$2[/align]');
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(p|div)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*text-align\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,function(all,tag,style,content){
});
sUBB=sUBB.replace(/<a(?:\s+[^>]*?)?\s+href=(["'])\s*(.+?)\s*\1[^>]*>\s*([\s\S]*?)\s*<\/a>/ig,function(all,q,url,text){
if(!(url&&text))return '';
var tag='url',str;
if(url.match(/^mailto:/i))
{
tag='email';
url=url.replace(/mailto:(.+?)/i,'$1');
}
str='['+tag;
if(url!=text)str+='='+url;
return str+']'+text+'[/'+tag+']';
});
sUBB=sUBB.replace(/<img(\s+[^>]*?)\/?>/ig,function(all,attr){
var emot=attr.match(/\s+emot\s*=\s*(["']?)\s*(.+?)\s*\1(\s|$)/i);
if(emot)return '[emot='+emot[2]+'/]';
var url=attr.match(regSrc),alt=attr.match(/\s+alt\s*=\s*(["']?)\s*(.*?)\s*\1(\s|$)/i),w=attr.match(regWidth),h=attr.match(regHeight),align=attr.match(/\s+align\s*=\s*(["']?)\s*(\w+)\s*\1(\s|$)/i),str='[img',p='';
if(!url)return '';
p+=alt[2];
if(w||h)p+=','+(w?w[2]:'')+','+(h?h[2]:'');
if(align)p+=','+align[2];
if(p)str+='='+p;
str+=']'+url[2]+'[/img]';
return str;
});
sUBB=sUBB.replace(/<blockquote(?:\s+[^>]*?)?>([\s\S]+?)<\/blockquote>/ig,'[quote]$1[/quote]');
sUBB=sUBB.replace(/<embed((?:\s+[^>]*?)?(?:\s+type\s*=\s*"\s*application\/x-shockwave-flash\s*"|\s+classid\s*=\s*"\s*clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000\s*")[^>]*?)\/>/ig,function(all,attr){
var url=attr.match(regSrc),w=attr.match(regWidth),h=attr.match(regHeight),str='[flash';
if(!url)return '';
if(w&&h)str+='='+w[2]+','+h[2];
str+=']'+url[2];
return str+'[/flash]';
});
sUBB=sUBB.replace(/<embed((?:\s+[^>]*?)?(?:\s+type\s*=\s*"\s*application\/x-mplayer2\s*"|\s+classid\s*=\s*"\s*clsid:6bf52a52-394a-11d3-b153-00c04f79faa6\s*")[^>]*?)\/>/ig,function(all,attr){
var url=attr.match(regSrc),w=attr.match(regWidth),h=attr.match(regHeight),p=attr.match(/\s+autostart\s*=\s*(["']?)\s*(.+?)\s*\1(\s|$)/i),str='[media',auto='0';
if(!url)return '';
if(p)if(p[2]=='true')auto='1';
if(w&&h)str+='='+w[2]+','+h[2]+','+auto;
str+=']'+url[2];
return str+'[/media]';
});
sUBB=sUBB.replace(/<table(\s+[^>]*?)?>/ig,function(all,attr){
var str='[table';
if(attr)
{
var w=attr.match(regWidth),b=attr.match(regBg);
if(w)
{
str+='='+w[2];
if(b)str+=','+b[2];
}
}
return str+']';
});
sUBB=sUBB.replace(/<tr(\s+[^>]*?)?>/ig,function(all,attr){
var str='[tr';
if(attr)
{
var bg=attr.match(regBg)
if(bg)str+='='+bg[2];
}
return str+']';
});
sUBB=sUBB.replace(/<(?:th|td)(\s+[^>]*?)?>/ig,function(all,attr){
var str='[td';
if(attr)
{
var col=attr.match(/\s+colspan\s*=\s*(["']?)\s*(\d+)\s*\1(\s|$)/i),row=attr.match(/\s+rowspan\s*=\s*(["']?)\s*(\d+)\s*\1(\s|$)/i),w=attr.match(regWidth);
col=col?col[2]:1;
row=row?row[2]:1;
if(col>1||row>1||w)str+='='+col+','+row;
if(w)str+=','+w[2];
}
return str+']';
});
sUBB=sUBB.replace(/<\/(table|tr)>/ig,'[/$1]');
sUBB=sUBB.replace(/<\/(th|td)>/ig,'[/td]');
sUBB=sUBB.replace(/<ul(\s+[^>]*?)?>/ig,function(all,attr){
var t;
if(attr)t=attr.match(/\s+type\s*=\s*(["']?)\s*(.+?)\s*\1(\s|$)/i);
return '[list'+(t?'='+t[2]:'')+']';
});
sUBB=sUBB.replace(/<ol(\s+[^>]*?)?>/ig,'[list=1]');
sUBB=sUBB.replace(/<li(\s+[^>]*?)?>/ig,'[*]');
sUBB=sUBB.replace(/<\/li>/ig,'');
sUBB=sUBB.replace(/<\/(ul|ol)>/ig,'[/list]');
sUBB=sUBB.replace(/<h([1-6])(\s+[^>]*?)?>/ig,function(all,n){return '\r\n\r\n[size='+(7-n)+'][b]'});
sUBB=sUBB.replace(/<\/h[1-6]>/ig,'[/b][/size]\r\n\r\n');
sUBB=sUBB.replace(/<address(\s+[^>]*?)?>/ig,'\r\n[i]');
sUBB=sUBB.replace(/<\/address>/ig,'[i]\r\n');
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(p)(?:\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,"\r\n\r\n$2\r\n\r\n");
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(div)(?:\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,"\r\n$2\r\n");
sUBB=sUBB.replace(/((\s| )*\r?\n){3,}/g,"\r\n\r\n");//限制最多2次换行
sUBB=sUBB.replace(/^((\s| )*\r?\n)+/g,'');//清除开头换行
sUBB=sUBB.replace(/((\s| )*\r?\n)+$/g,'');//清除结尾换行
for(i=1;i<=cnum;i++)sUBB=sUBB.replace("[\tubbcodeplace_"+i+"\t]", arrcode[i]);
sUBB=sUBB.replace(/<[^<>]+?>/g,'');//删除所有HTML标签
sUBB=sUBB.replace(/</ig, '<');
sUBB=sUBB.replace(/>/ig, '>');
sUBB=sUBB.replace(/ /ig, ' ');
sUBB=sUBB.replace(/&/ig, '&');
return sUBB;
} | JavaScript |
/*!
* xhEditor - WYSIWYG XHTML Editor
* @requires jQuery v1.4.2
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 1.1.1 (build 101002)
*/
(function($){
if($.xheditor)return false;//防止JS重复加载
$.fn.xheditor=function(options)
{
var arrSuccess=[];
this.each(function(){
if(!$.nodeName(this,'TEXTAREA'))return;
if(options===false)//卸载
{
if(this.xheditor)
{
this.xheditor.remove();
this.xheditor=null;
}
}
else//初始化
{
if(!this.xheditor)
{
var tOptions=/({.*})/.exec($(this).attr('class'));
if(tOptions)
{
try{tOptions=eval('('+tOptions[1]+')');}catch(ex){};
options=$.extend({},tOptions,options );
}
var editor=new $.xheditor(this,options);
if(editor.init())
{
this.xheditor=editor;
arrSuccess.push(editor);
}
else editor=null;
}
else arrSuccess.push(this.xheditor);
}
});
if(arrSuccess.length==0)arrSuccess=false;
if(arrSuccess.length==1)arrSuccess=arrSuccess[0];
return arrSuccess;
}
var xCount=0,browerVer=$.browser.version,isIE=$.browser.msie,isMozilla=$.browser.mozilla,isSafari=$.browser.safari,isOpera=$.browser.opera,bShowPanel=false,bClickCancel=true,bShowModal=false,bCheckEscInit=false;
var _jPanel,_jShadow,_jCntLine,_jPanelButton;
var jModal,jModalShadow,layerShadow,jOverlay,jHideSelect,onModalRemove;
var editorRoot;
$('script[src*=xheditor]').each(function(){
var s=this.src;
if(s.match(/xheditor[^\/]*\.js/i)){editorRoot=s.replace(/[\?#].*$/, '').replace(/(^|[\/\\])[^\/]*$/, '$1');return false;}
});
var specialKeys={ 27: 'esc', 9: 'tab', 32:'space', 13: 'enter', 8:'backspace', 145: 'scroll',
20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',
35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down',
112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12' };
var itemColors=['#FFFFFF','#CCCCCC','#C0C0C0','#999999','#666666','#333333','#000000','#FFCCCC','#FF6666','#FF0000','#CC0000','#990000','#660000','#330000','#FFCC99','#FF9966','#FF9900','#FF6600','#CC6600','#993300','#663300','#FFFF99','#FFFF66','#FFCC66','#FFCC33','#CC9933','#996633','#663333','#FFFFCC','#FFFF33','#FFFF00','#FFCC00','#999900','#666600','#333300','#99FF99','#66FF99','#33FF33','#33CC00','#009900','#006600','#003300','#99FFFF','#33FFFF','#66CCCC','#00CCCC','#339999','#336666','#003333','#CCFFFF','#66FFFF','#33CCFF','#3366FF','#3333FF','#000099','#000066','#CCCCFF','#9999FF','#6666CC','#6633FF','#6600CC','#333399','#330099','#FFCCFF','#FF99FF','#CC66CC','#CC33CC','#993399','#663366','#330033'];
var arrBlocktag=[{n:'p',t:'Paragraph'},{n:'h1',t:'Heading 1'},{n:'h2',t:'Heading 2'},{n:'h3',t:'Heading 3'},{n:'h4',t:'Heading 4'},{n:'h5',t:'Heading 5'},{n:'h6',t:'Heading 6'},{n:'pre',t:'Preformatted'},{n:'address',t:'Address'}];
var arrFontname=[{n:'Arial'},{n:'Arial Narrow'},{n:'Arial Black'},{n:'Comic Sans MS'},{n:'Courier New'},{n:'System'},{n:'Times New Roman'},{n:'Tahoma'},{n:'Verdana'}];
var arrFontsize=[{n:'xx-small',wkn:'x-small',s:'8pt',t:'xx-small'},{n:'x-small',wkn:'small',s:'10pt',t:'x-small'},{n:'small',wkn:'medium',s:'12pt',t:'small'},{n:'medium',wkn:'large',s:'14pt',t:'medium'},{n:'large',wkn:'x-large',s:'18pt',t:'large'},{n:'x-large',wkn:'xx-large',s:'24pt',t:'x-large'},{n:'xx-large',wkn:'-webkit-xxx-large',s:'36pt',t:'xx-large'}];
var menuAlign=[{s:'Align left',v:'justifyleft',t:'Align left'},{s:'Align center',v:'justifycenter',t:'Align center'},{s:'Align right',v:'justifyright',t:'Align right'},{s:'Align full',v:'justifyfull',t:'Align full'}],menuList=[{s:'Ordered list',v:'insertOrderedList',t:'Ordered list'},{s:'Unordered list',v:'insertUnorderedList',t:'Unordered list'}];
var htmlPastetext='<div>Use Ctrl+V on your keyboard to paste the text.</div><div><textarea id="xhePastetextValue" wrap="soft" spellcheck="false" style="width:300px;height:100px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlLink='<div>Link URL: <input type="text" id="xheLinkUrl" value="http://" class="xheText" /></div><div>Target: <select id="xheLinkTarget"><option selected="selected" value="">Default</option><option value="_blank">New window</option><option value="_self">Same window</option><option value="_parent">Parent window</option></select></div><div style="display:none">Link Text:<input type="text" id="xheLinkText" value="" class="xheText" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlImg='<div>Img URL: <input type="text" id="xheImgUrl" value="http://" class="xheText" /></div><div>Alt text: <input type="text" id="xheImgAlt" /></div><div>Alignment:<select id="xheImgAlign"><option selected="selected" value="">Default</option><option value="left">Left</option><option value="right">Right</option><option value="top">Top</option><option value="middle">Middle</option><option value="baseline">Baseline</option><option value="bottom">Bottom</option></select></div><div>Dimension:<input type="text" id="xheImgWidth" style="width:40px;" /> x <input type="text" id="xheImgHeight" style="width:40px;" /></div><div>Border: <input type="text" id="xheImgBorder" style="width:40px;" /></div><div>Hspace: <input type="text" id="xheImgHspace" style="width:40px;" /> Vspace:<input type="text" id="xheImgVspace" style="width:40px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlFlash='<div>Flash URL:<input type="text" id="xheFlashUrl" value="http://" class="xheText" /></div><div>Dimension:<input type="text" id="xheFlashWidth" style="width:40px;" value="480" /> x <input type="text" id="xheFlashHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlMedia='<div>Media URL:<input type="text" id="xheMediaUrl" value="http://" class="xheText" /></div><div>Dimension:<input type="text" id="xheMediaWidth" style="width:40px;" value="480" /> x <input type="text" id="xheMediaHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlTable='<div>Rows&Cols: <input type="text" id="xheTableRows" style="width:40px;" value="3" /> x <input type="text" id="xheTableColumns" style="width:40px;" value="2" /></div><div>Headers: <select id="xheTableHeaders"><option selected="selected" value="">None</option><option value="row">First row</option><option value="col">First column</option><option value="both">Both</option></select></div><div>Dimension: <input type="text" id="xheTableWidth" style="width:40px;" value="200" /> x <input type="text" id="xheTableHeight" style="width:40px;" value="" /></div><div>Border: <input type="text" id="xheTableBorder" style="width:40px;" value="1" /></div><div>CellSpacing:<input type="text" id="xheTableCellSpacing" style="width:40px;" value="1" /> CellPadding:<input type="text" id="xheTableCellPadding" style="width:40px;" value="1" /></div><div>Align: <select id="xheTableAlign"><option selected="selected" value="">Default</option><option value="left">Left</option><option value="center">Center</option><option value="right">Right</option></select></div><div>Caption: <input type="text" id="xheTableCaption" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlAbout='<div style="font:12px Arial;width:245px;word-wrap:break-word;word-break:break-all;"><p><span style="font-size:20px;color:#1997DF;">xhEditor</span><br />v1.1.1 (build 101002)</p><p>xhEditor is a platform independent WYSWYG XHTML editor based by jQuery,released as Open Source under <a href="http://www.gnu.org/licenses/lgpl.html" target="_blank">LGPL</a>.</p><p>Copyright © <a href="http://xheditor.com/" target="_blank">xhEditor.com</a>. All rights reserved.</p></div>';
var itemEmots={'default':{name:'Default',width:24,height:24,line:7,list:{'smile':'Smile','tongue':'Tongue','titter':'Titter','laugh':'Laugh','sad':'Sad','wronged':'Wronged','fastcry':'Fast cry','cry':'Cry','wail':'Wail','mad':'Mad','knock':'Knock','curse':'Curse','crazy':'Crazy','angry':'Angry','ohmy':'Oh my','awkward':'Awkward','panic':'Panic','shy':'Shy','cute':'Cute','envy':'Envy','proud':'Proud','struggle':'Struggle','quiet':'Quiet','shutup':'Shut up','doubt':'Doubt','despise':'Despise','sleep':'Sleep','bye':'Bye'}}};
var arrTools={Cut:{t:'Cut (Ctrl+X)'},Copy:{t:'Copy (Ctrl+C)'},Paste:{t:'Paste (Ctrl+V)'},Pastetext:{t:'Paste as plain text',h:isIE?0:1},Blocktag:{t:'Block tag',h:1},Fontface:{t:'Font family',h:1},FontSize:{t:'Font size',h:1},Bold:{t:'Bold (Ctrl+B)',s:'Ctrl+B'},Italic:{t:'Italic (Ctrl+I)',s:'Ctrl+I'},Underline:{t:'Underline (Ctrl+U)',s:'Ctrl+U'},Strikethrough:{t:'Strikethrough (Ctrl+S)',s:'Ctrl+S'},FontColor:{t:'Select text color',h:1},BackColor:{t:'Select background color',h:1},SelectAll:{t:'SelectAll (Ctrl+A)'},Removeformat:{t:'Remove formatting'},Align:{t:'Align',h:1},List:{t:'List',h:1},Outdent:{t:'Outdent (Shift+Tab)',s:'Shift+Tab'},Indent:{t:'Indent (Tab)',s:'Tab'},Link:{t:'Insert/edit link (Ctrl+K)',s:'Ctrl+K',h:1},Unlink:{t:'Unlink'},Img:{t:'Insert/edit image',h:1},Flash:{t:'Insert/edit flash',h:1},Media:{t:'Insert/edit media',h:1},Emot:{t:'Emotions',s:'ctrl+e',h:1},Table:{t:'Insert a new table',h:1},Source:{t:'Edit source code'},Preview:{t:'Preview'},Print:{t:'Print (Ctrl+P)',s:'Ctrl+P'},Fullscreen:{t:'Toggle fullscreen (Esc)',s:'Esc'},About:{t:'About xhEditor'}};
var toolsThemes={
mini:'Bold,Italic,Underline,Strikethrough,|,Align,List,|,Link,Img',
simple:'Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,|,Align,List,Outdent,Indent,|,Link,Img,Emot',
full:'Cut,Copy,Paste,Pastetext,|,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,SelectAll,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Img,Flash,Media,Emot,Table,|,Source,Preview,Print,Fullscreen'};
toolsThemes.mfull=toolsThemes.full.replace(/\|(,Align)/i,'/$1');
var arrDbClick={'a':'Link','img':'Img','embed':'Embed'},uploadInputname='filedata';
$.xheditor=function(textarea,options)
{
var defaults={skin:'default',tools:'full',clickCancelDialog:true,linkTag:false,internalScript:false,inlineScript:false,internalStyle:true,inlineStyle:true,showBlocktag:false,forcePtag:true,upLinkExt:"zip,rar,txt",upImgExt:"jpg,jpeg,gif,png",upFlashExt:"swf",upMediaExt:"wmv,avi,wma,mp3,mid",modalWidth:350,modalHeight:220,modalTitle:true,defLinkText:'Click to open link',layerShadow:3,emotMark:false,upBtnText:'Upload',wordDeepClean:true,hoverExecDelay:100,html5Upload:true,upMultiple:99};
var _this=this,_text=textarea,_jText=$(_text),_jForm=_jText.closest('form'),_jTools,_jArea,_win,_jWin,_doc,_jDoc;
var bookmark;
var bInit=false,bSource=false,bFullscreen=false,bCleanPaste=false,outerScroll,bShowBlocktag=false,sLayoutStyle='',ev=null,timer,bDisableHoverExec=false,bQuickHoverExec=false;
var lastPoint=null,lastAngle=null;//鼠标悬停显示
var editorHeight=0;
var settings=_this.settings=$.extend({},defaults,options );
var plugins=settings.plugins,strPlugins=[];
if(plugins)
{
arrTools=$.extend({},arrTools,plugins);
$.each(plugins,function(n){strPlugins.push(n);});
strPlugins=strPlugins.join(',');
}
if(settings.tools.match(/^\s*(m?full|simple|mini)\s*$/i))
{
var toolsTheme=toolsThemes[$.trim(settings.tools)];
settings.tools=(settings.tools.match(/m?full/i)&&plugins)?toolsTheme.replace('Table','Table,'+strPlugins):toolsTheme;//插件接在full的Table后面
}
if(!settings.tools.match(/(^|,)\s*About\s*(,|$)/i))settings.tools+=',About';
settings.tools=settings.tools.split(',');
if(settings.editorRoot)editorRoot=settings.editorRoot;
editorRoot=getLocalUrl(editorRoot,'abs');
//基本控件名
var idCSS='xheCSS_'+settings.skin,idContainer='xhe'+xCount+'_container',idTools='xhe'+xCount+'_Tool',idIframeArea='xhe'+xCount+'_iframearea',idIframe='xhe'+xCount+'_iframe',idFixFFCursor='xhe'+xCount+'_fixffcursor';
var headHTML='',bodyClass='',skinPath=editorRoot+'xheditor_skin/'+settings.skin+'/',arrEmots=itemEmots,urlType=settings.urlType,urlBase=settings.urlBase,emotPath=settings.emotPath,emotPath=emotPath?emotPath:editorRoot+'xheditor_emot/',selEmotGroup='';
arrEmots=$.extend({},arrEmots,settings.emots);
emotPath=getLocalUrl(emotPath,'rel',urlBase?urlBase:null);//返回最短表情路径
bShowBlocktag=settings.showBlocktag;
if(bShowBlocktag)bodyClass+=' showBlocktag';
var arrShortCuts=[];
this.init=function()
{
//加载样式表
if($('#'+idCSS).length==0)$('head').append('<link id="'+idCSS+'" rel="stylesheet" type="text/css" href="'+skinPath+'ui.css" />');
//初始化编辑器
var cw = settings.width || _text.style.width || _jText.outerWidth();
editorHeight = settings.height || _text.style.height || _jText.outerHeight();
if(is(editorHeight,'string'))editorHeight=editorHeight.replace(/[^\d]+/g,'');
if(cw<=0||editorHeight<=0)//禁止对隐藏区域里的textarea初始化编辑器
{
alert('Current textarea is hidden, please make it show before initialization xhEditor, or directly initialize the height.');
return false;
}
if(/^[0-9\.]+$/i.test(''+cw))cw+='px';
//编辑器CSS背景
var editorBackground=settings.background || _text.style.background;
//工具栏内容初始化
var arrToolsHtml=['<span class="xheGStart"/>'],tool,cn,regSeparator=/\||\//i;
$.each(settings.tools,function(i,n)
{
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGEnd"/>');
if(n=='|')arrToolsHtml.push('<span class="xheSeparator"/>');
else if(n=='/')arrToolsHtml.push('<br />');
else
{
tool=arrTools[n];
if(!tool)return;
if(tool.c)cn=tool.c;
else cn='xheIcon xheBtn'+n;
arrToolsHtml.push('<span><a href="javascript:void(0);" title="'+tool.t+'" name="'+n+'" class="xheButton xheEnabled" tabindex="-1"><span class="'+cn+'" unselectable="on" /></a></span>');
if(tool.s)_this.addShortcuts(tool.s,n);
}
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGStart"/>');
});
arrToolsHtml.push('<span class="xheGEnd"/><br />');
_jText.after($('<input type="text" id="'+idFixFFCursor+'" style="position:absolute;display:none;" /><span id="'+idContainer+'" class="xhe_'+settings.skin+'" style="display:none"><table cellspacing="0" cellpadding="0" class="xheLayout" style="width:'+cw+';height:'+editorHeight+'px;"><tbody><tr><td id="'+idTools+'" class="xheTool" unselectable="on" style="height:1px;"></td></tr><tr><td id="'+idIframeArea+'" class="xheIframeArea"><iframe frameborder="0" id="'+idIframe+'" src="javascript:;" style="width:100%;"></iframe></td></tr></tbody></table></span>'));
_jTools=$('#'+idTools);_jArea=$('#'+idIframeArea);
headHTML='<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><link rel="stylesheet" href="'+skinPath+'iframe.css"/>';
var loadCSS=settings.loadCSS;
if(loadCSS)
{
if(is(loadCSS,'array'))for(var i in loadCSS)headHTML+='<link rel="stylesheet" href="'+loadCSS[i]+'"/>';
else
{
if(loadCSS.match(/\s*<style(\s+[^>]*?)?>[\s\S]+?<\/style>\s*/i))headHTML+=loadCSS;
else headHTML+='<link rel="stylesheet" href="'+loadCSS+'"/>';
}
}
var iframeHTML='<html><head>'+headHTML;
if(editorBackground)iframeHTML+='<style>body{background:'+editorBackground+';}</style>';
iframeHTML+='</head><body spellcheck="false" class="editMode'+bodyClass+'"></body></html>';
_this.win=_win=$('#'+idIframe)[0].contentWindow;
_jWin=$(_win);
try{
this.doc=_doc = _win.document;_jDoc=$(_doc);
_doc.open();
_doc.write(iframeHTML);
_doc.close();
if(isIE)_doc.body.contentEditable='true';
else _doc.designMode = 'On';
}catch(e){}
setTimeout(setOpts,300);
_this.setSource();
_win.setInterval=null;//针对jquery 1.3无法操作iframe window问题的hack
//添加工具栏
_jTools.append(arrToolsHtml.join('')).bind('mousedown contextmenu',returnFalse).click(function(event)
{
var jButton=$(event.target).closest('a');
if(jButton.is('.xheEnabled'))
{
ev=event;
_this.exec(jButton.attr('name'));
}
return false;
});
_jTools.find('.xheButton').hover(function(event){//鼠标悬停执行
var jButton=$(this),delay=settings.hoverExecDelay;
var tAngle=lastAngle;lastAngle=null;
if(delay==-1||bDisableHoverExec||!jButton.is('.xheEnabled'))return false;
if(tAngle&&tAngle>10)//检测误操作
{
bDisableHoverExec=true;
setTimeout(function(){bDisableHoverExec=false;},100);
return false;
}
var cmd=jButton.attr('name'),bHover=arrTools[cmd].h==1;
if(!bHover)
{
_this.hidePanel();//移到非悬停按钮上隐藏面板
return false;
}
if(bQuickHoverExec)delay=0;
if(delay>=0)timer=setTimeout(function(){
ev=event;
lastPoint={x:ev.clientX,y:ev.clientY};
_this.exec(cmd);
},delay);
},function(event){lastPoint=null;if(timer)clearTimeout(timer);}).mousemove(function(event){
if(lastPoint)
{
var diff={x:event.clientX-lastPoint.x,y:event.clientY-lastPoint.y};
if(Math.abs(diff.x)>1||Math.abs(diff.y)>1)
{
if(diff.x>0&&diff.y>0)
{
var tAngle=Math.round(Math.atan(diff.y/diff.x)/0.017453293);
if(lastAngle)lastAngle=(lastAngle+tAngle)/2
else lastAngle=tAngle;
}
else lastAngle=null;
lastPoint={x:event.clientX,y:event.clientY};
}
}
});
//初始化面板
_jPanel=$('#xhePanel');
_jShadow=$('#xheShadow');
_jCntLine=$('#xheCntLine');
if(_jPanel.length==0)
{
_jPanel=$('<div id="xhePanel"></div>').mousedown(function(ev){ev.stopPropagation()});
_jShadow=$('<div id="xheShadow"></div>');
_jCntLine=$('<div id="xheCntLine"></div>');
setTimeout(function(){
$(document.body).append(_jPanel).append(_jShadow).append(_jCntLine);
},10);
}
//切换显示区域
$('#'+idContainer).show();
_jText.hide();
_jArea.css('height',editorHeight-_jTools.outerHeight());
//绑定内核事件
_jText.focus(_this.focus);
_jForm.submit(saveResult).bind('reset', loadReset);
$(window).bind('unload beforeunload',saveResult).bind('resize',fixFullHeight);
$(document).mousedown(clickCancelPanel);
if(!bCheckEscInit){$(document).keydown(checkEsc);bCheckEscInit=true;}
_jWin.focus(function(){if(settings.focus)settings.focus();}).blur(function(){if(settings.blur)settings.blur();});
if(isSafari)_jWin.click(fixAppleSel);
_jDoc.mousedown(clickCancelPanel).keydown(checkShortcuts).keypress(forcePtag).dblclick(checkDblClick).bind('mousedown click',function(ev){_jText.trigger(ev.type);});
if(isIE)
{
//IE控件上Backspace会导致页面后退
_jDoc.keydown(function(ev){var rng=_this.getRng();if(ev.which==8&&rng.item){$(rng.item(0)).remove();return false;}});
//修正IE拖动img大小不更新width和height属性值的问题
function fixResize(ev)
{
var jImg=$(ev.target),v;
if(v=jImg.css('width'))jImg.css('width','').attr('width',v.replace(/[^0-9%]+/g, ''));
if(v=jImg.css('height'))jImg.css('height','').attr('height',v.replace(/[^0-9%]+/g, ''));
}
_jDoc.bind('controlselect',function(ev){
ev=ev.target;if(!$.nodeName(ev,'IMG'))return;
$(ev).unbind('resizeend',fixResize).bind('resizeend',fixResize);
});
}
var jBody=$(_doc.documentElement);
jBody.bind('paste',cleanPaste);
if(settings.disableContextmenu)jBody.bind('contextmenu',returnFalse);
//HTML5编辑区域直接拖放上传
if(settings.html5Upload)jBody.bind('dragenter dragover',function(ev){var types;if((types=ev.originalEvent.dataTransfer.types)&&$.inArray('Files', types)!=-1)return false;}).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0){
var i,cmd,arrCmd=['Link','Img','Flash','Media'],arrExt=[],strExt;
for(i in arrCmd){
cmd=arrCmd[i];
if(settings['up'+cmd+'Url']&&settings['up'+cmd+'Url'].match(/^[^!].*/i))arrExt.push(cmd+':,'+settings['up'+cmd+'Ext']);//允许上传
}
if(arrExt.length==0)return false;//禁止上传
else strExt=arrExt.join(',');
function getCmd(fileList){
var match,fileExt,cmd;
for(i=0;i<fileList.length;i++){
fileExt=fileList[i].fileName.replace(/.+\./,'');
if(match=strExt.match(new RegExp('(\\w+):[^:]*,'+fileExt+'(?:,|$)','i'))){
if(!cmd)cmd=match[1];
else if(cmd!=match[1])return 2;
}
else return 1;
}
return cmd;
}
cmd=getCmd(fileList);
if(cmd==1)alert('Upload file extension required for this: '+strExt.replace(/\w+:,/g,''));
else if(cmd==2)alert('You can only drag and drop the same type of file.');
else if(cmd){
_this.startUpload(fileList,settings['up'+cmd+'Url'],'*',function(arrMsg){
var arrUrl=[],msg,onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用户上传回调
for(i in arrMsg){
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!')url=url.substr(1);
arrUrl.push(url);
}
_this.exec(cmd);
$('#xhe'+cmd+'Url').val(arrUrl.join(' '));
$('#xheSave').click();
});
}
return false;
}
});
//添加用户快捷键
var shortcuts=settings.shortcuts;
if(shortcuts)$.each(shortcuts,function(key,func){_this.addShortcuts(key,func);});
xCount++;
bInit=true;
if(settings.fullscreen)_this.toggleFullscreen();
else if(settings.sourceMode)setTimeout(_this.toggleSource,20);
return true;
}
this.remove=function()
{
_this.hidePanel();
saveResult();//卸载前同步最新内容到textarea
//取消绑定事件
_jText.unbind('focus',_this.focus);
_jForm.unbind('submit',saveResult).unbind('reset', loadReset);
$(window).unbind('unload beforeunload',saveResult).unbind('resize',fixFullHeight);
$(document).unbind('mousedown',clickCancelPanel);
$('#'+idContainer+','+'#'+idFixFFCursor).remove();
_jText.show();
bInit=false;
}
this.saveBookmark=function(){
if(!bSource){
var rng=_this.getRng();
rng=rng.cloneRange?rng.cloneRange():rng;
bookmark={'top':_jWin.scrollTop(),'rng':rng};
}
}
this.loadBookmark=function()
{
if(bSource||!bookmark)return;
_this.focus();
var rng=bookmark.rng;
if(isIE)rng.select();
else
{
var sel=_this.getSel();
sel.removeAllRanges();
sel.addRange(rng);
}
_jWin.scrollTop(bookmark.top);
bookmark=null;
}
this.focus=function()
{
if(!bSource)_jWin.focus();
else $('#sourceCode',_doc).focus();
return false;
}
this.setCursorFirst=function(firstBlock)
{
_this.focus();_win.scrollTo(0,0);
var rng=_this.getRng(),_body=_doc.body,firstNode=_body,firstTag;
if(firstBlock&&firstNode.firstChild&&(firstTag=firstNode.firstChild.tagName)&&firstTag.match(/^p|div|h[1-6]$/i))firstNode=_body.firstChild;
isIE?rng.moveToElementText(firstNode):rng.setStart(firstNode,0);
rng.collapse(true);
if(isIE)rng.select();
else{var sel=_this.getSel();sel.removeAllRanges();sel.addRange(rng);}
}
this.getSel=function()
{
return _win.getSelection ? _win.getSelection() : _doc.selection;
}
this.getRng=function()
{
var sel=_this.getSel(),rng;
try{
rng = sel.rangeCount > 0 ? sel.getRangeAt(0) : (sel.createRange ? sel.createRange() : (_doc.createRange?_doc.createRange():_doc.body.createTextRange()));
}catch (ex){}
return rng;
}
this.getParent=function(tag)
{
var rng=_this.getRng(),p;
if(!isIE)
{
p = rng.commonAncestorContainer;
if(!rng.collapsed)if(rng.startContainer == rng.endContainer&&rng.startOffset - rng.endOffset < 2&&rng.startContainer.hasChildNodes())p = rng.startContainer.childNodes[rng.startOffset];
}
else p=rng.item?rng.item(0):rng.parentElement();
tag=tag?tag:'*';p=$(p);
if(!p.is(tag))p=$(p).closest(tag);
return p;
}
this.getSelect=function(format)
{
var sel=_this.getSel(),rng=_this.getRng(),isCollapsed=true;
if (!rng || rng.item)isCollapsed=false
else isCollapsed=!sel || rng.boundingWidth == 0 || rng.collapsed;
if(format=='text')return isCollapsed ? '' : (rng.text || (sel.toString ? sel.toString() : ''));
var sHtml;
if(rng.cloneContents)
{
var tmp=$('<div></div>'),c;
c = rng.cloneContents();
if(c)tmp.append(c);
sHtml=tmp.html();
}
else if(is(rng.item))sHtml=rng.item(0).outerHTML;
else if(is(rng.htmlText))sHtml=rng.htmlText;
else sHtml=rng.toString();
if(isCollapsed)sHtml='';
sHtml=_this.processHTML(sHtml,'read');
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
return sHtml;
}
this.pasteHTML=function(sHtml,bStart)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
var sel=_this.getSel(),rng=_this.getRng();
if(bStart!=undefined)//非覆盖式插入
{
if(rng.item)
{
var n=rng.item(0);
rng=_doc.body.createTextRange();
rng.moveToElementText(n);
rng.select();
}
rng.collapse(bStart);
}
sHtml+='<'+(isIE?'img':'span')+' id="_xhe_temp" style="display:none" />';
if(rng.insertNode)
{
rng.deleteContents();
rng.insertNode(rng.createContextualFragment(sHtml));
}
else
{
if(sel.type.toLowerCase()=='control'){sel.clear();rng=_this.getRng();};
rng.pasteHTML(sHtml);
}
var jTemp=$('#_xhe_temp',_doc),temp=jTemp[0];
if(isIE)
{
rng.moveToElementText(temp);
rng.select();
}
else
{
rng.selectNode(temp);
sel.removeAllRanges();
sel.addRange(rng);
}
jTemp.remove();
}
this.pasteText=function(text,bStart)
{
if(!text)text='';
text=_this.domEncode(text);
text = text.replace(/\r?\n/g, '<br />');
_this.pasteHTML(text,bStart);
}
this.appendHTML=function(sHtml)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
$(_doc.body).append(sHtml);
}
this.domEncode=function(str)
{
return str.replace(/[<>]/g,function(c){return {'<':'<','>':'>'}[c];});
}
this.setSource=function(sHtml)
{
bookmark=null;
if(typeof sHtml!='string'&&sHtml!='')sHtml=_text.value;
if(bSource)$('#sourceCode',_doc).val(sHtml);
else
{
if(settings.beforeSetSource)sHtml=settings.beforeSetSource(sHtml);
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
sHtml=_this.cleanWord(sHtml);
sHtml=_this.processHTML(sHtml,'write');
if(isIE){//修正IE会删除可视内容前的script,style,<!--
_doc.body.innerHTML='<img id="_xhe_temp" style="display:none" />'+sHtml;
$('#_xhe_temp',_doc).remove();
}
else _doc.body.innerHTML=sHtml;
}
}
this.processHTML=function(sHtml,mode)
{
var appleClass=' class="Apple-style-span"';
if(mode=='write')
{//write
//恢复emot
function restoreEmot(all,attr,q,emot)
{
emot=emot.split(',');
if(!emot[1]){emot[1]=emot[0];emot[0]=''}
if(emot[0]=='default')emot[0]='';
return all.replace(/\s+src\s*=\s*(["']?).*?\1(\s|$|\/|>)/i,'$2').replace(attr,' src="'+emotPath+(emot[0]?emot[0]:'default')+'/'+emot[1]+'.gif"'+(settings.emotMark?' emot="'+(emot[0]?emot[0]+',':'')+emot[1]+'"'+(all.match(/\s+alt\s*=\s*(["']?)\s*(.*?)\s*\1[\s\/>]/i)?'':' alt="'+emot[1]+'"'):''));
}
sHtml = sHtml.replace(/<img(?:\s+[^>]*?)?(\s+emot\s*=\s*(["']?)\s*(.*?)\s*\2)(?:\s+[^>]*?)?\/?>/ig,restoreEmot);
//保存属性值:src,href
function saveValue(all,tag,attr,n,q,v){return all.replace(attr,(urlBase?(' '+n+'="'+getLocalUrl(v,'abs',urlBase)+'"'):attr)+' _xhe_'+n+'="'+v+'"');}
sHtml = sHtml.replace(/<(\w+(?:\:\w+)?)(?:\s+[^>]*?)?(\s+(src|href)\s*=\s*(["']?)\s*(.*?)\s*\4)(?:\s+[^>]*?)?\/?>/ig,saveValue);
sHtml = sHtml.replace(/<(\/?)del(\s+[^>]*?)?>/ig,'<$1strike$2>');//编辑状态统一转为strike
if(isMozilla)
{
sHtml = sHtml.replace(/<(\/?)strong(\s+[^>]*?)?>/ig,'<$1b$2>');
sHtml = sHtml.replace(/<(\/?)em(\s+[^>]*?)?>/ig,'<$1i$2>');
}
else if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.n){s=t.wkn;break;}
}
return pre+'font-size:'+s+aft;
});
sHtml = sHtml.replace(/<strong(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-weight: bold;"$1>');
sHtml = sHtml.replace(/<em(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-style: italic;"$1>');
sHtml = sHtml.replace(/<u(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: underline;"$1>');
sHtml = sHtml.replace(/<strike(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: line-through;"$1>');
sHtml = sHtml.replace(/<\/(strong|em|u|strike)>/ig,'</span>');
sHtml = sHtml.replace(/<span((?:\s+[^>]*?)?\s+style="([^"]*;)*\s*(font-family|font-size|color|background-color)\s*:\s*[^;"]+\s*;?"[^>]*)>/ig,'<span'+appleClass+'$1>');
}
else if(isIE)
{
sHtml = sHtml.replace(/'/ig, ''');
sHtml = sHtml.replace(/\s+(disabled|checked|readonly|selected)\s*=\s*[\"\']?(false|0)[\"\']?/ig, '');
}
sHtml = sHtml.replace(/<a(\s+[^>]*?)?\/>/,'<a$1></a>');
if(!isSafari)
{
//style转font
function style2font(all,tag,style,content)
{
var attrs='',f,s1,s2,c;
f=style.match(/font-family\s*:\s*([^;"]+)/i);
if(f)attrs+=' face="'+f[1]+'"';
s1=style.match(/font-size\s*:\s*([^;"]+)/i);
if(s1)
{
s1=s1[1].toLowerCase();
for(var j=0;j<arrFontsize.length;j++)if(s1==arrFontsize[j].n||s1==arrFontsize[j].s){s2=j+1;break;}
if(s2)
{
attrs+=' size="'+s2+'"';
style=style.replace(/(^|;)(\s*font-size\s*:\s*[^;"]+;?)+/ig,'$1');
}
}
c=style.match(/(?:^|[\s;])color\s*:\s*([^;"]+)/i);
if(c)
{
var rgb;
if(rgb=c[1].match(/\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)){c[1]='#';for(var i=1;i<=3;i++)c[1]+=(rgb[i]-0).toString(16);}
c[1]=c[1].replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,'#$1$1$2$2$3$3');
attrs+=' color="'+c[1]+'"';
}
style=style.replace(/(^|;)(\s*(font-family|color)\s*:\s*[^;"]+;?)+/ig,'$1');
if(attrs!='')
{
if(style)attrs+=' style="'+style+'"';
return '<font'+attrs+'>'+content+"</font>";
}
else return all;
}
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,style2font);//最里层
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,style2font);//第2层
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,style2font);//第3层
}
}
else
{//read
//恢复属性值src,href
function restoreValue(all,n,q,v)
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
return all.replace(new RegExp('\\s+'+n+'\\s*=\\s*(["\']?).*?\\1(\\s|/?>)','ig'),' '+n+'="'+v.replace(/\$/g,'$$$$')+'"$2');
}
sHtml = sHtml.replace(/<(?:\w+(?:\:\w+)?)(?:\s+[^>]*?)?\s+_xhe_(src|href)\s*=\s*(["']?)\s*(.*?)\s*\2(?:\s+[^>]*?)?\/?>/ig,restoreValue);
if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.wkn){s=t.n;break;}
}
return pre+'font-size:'+s+aft;
});
var arrAppleSpan=[{r:/font-weight:\sbold/ig,t:'strong'},{r:/font-style:\sitalic/ig,t:'em'},{r:/text-decoration:\sunderline/ig,t:'u'},{r:/text-decoration:\sline-through/ig,t:'strike'}];
function replaceAppleSpan(all,tag,attr1,attr2,content)
{
var attr=attr1+attr2,newTag='';
if(!attr)return content;
for(var i=0;i<arrAppleSpan.length;i++)
{
if(attr.match(arrAppleSpan[i].r))
{
newTag=arrAppleSpan[i].t;
break;
}
}
if(newTag)return '<'+newTag+'>'+content+'</'+newTag+'>';
else return all;
}
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,replaceAppleSpan);//最里层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第2层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第3层
}
if(!isIE){//字符间的文本换行强制转br
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/([^<>\r\n]?)((?:\r?\n)+)([^<>\r\n]?)/ig,function(all,left,br,right){if(left||right)return left+br.replace(/\r?\n/g,'<br />')+right;else return all;});
});
}
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+(?:_xhe_|_moz_|_webkit_)[^=]+?\s*=\s*(["']?).*?\2(\s|\/?>)/ig,'$1$3');
sHtml = sHtml.replace(/(<\w+[^>]*?)\s+class\s*=\s*(["']?)\s*(?:apple|webkit)\-.+?\s*\2(\s|\/?>)/ig, "$1$3");
sHtml = sHtml.replace(/<img(\s+[^>]+?)\/?>/ig,function(all,attr){if(!attr.match(/\s+alt\s*(["']?).*?\1(\s|$)/i))attr+=' alt=""';return '<img'+attr+' />';});//img强制加alt
sHtml = sHtml.replace(/\s+jquery\d+="\d+"/ig,'');
}
return sHtml;
}
this.getSource=function(bFormat)
{
var sHtml,beforeGetSource=settings.beforeGetSource;
if(bSource)
{
sHtml=$('#sourceCode',_doc).val();
if(!beforeGetSource){
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/(\t*\r?\n\t*)+/g,'')//标准HTML模式清理缩进和换行
});
}
}
else
{
sHtml=_this.processHTML(_doc.body.innerHTML,'read');
sHtml=sHtml.replace(/^\s*(?:<(p|div)(?:\s+[^>]*?)?>)?\s*(<br(?:\s+[^>]*?)?>)*\s*(?:<\/\1>)?\s*$/i, '');//修正Firefox在空内容情况下多出来的代码
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml,bFormat);
sHtml=_this.cleanWord(sHtml);
if(beforeGetSource)sHtml=beforeGetSource(sHtml);
}
_text.value=sHtml;
return sHtml;
}
this.cleanWord=function(sHtml)
{
if(sHtml.match(/mso(-|normal)|WordDocument/i))
{
var deepClean=settings.wordDeepClean;
//格式化
sHtml = sHtml.replace(/(<link(?:\s+[^>]*?)?)\s+href\s*=\s*(["']?)\s*file:\/\/.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, '');
//区块标签清理
sHtml = sHtml.replace(/<!--[\s\S]*?-->|<!(--)?\[[\s\S]+?\](--)?>|<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
sHtml = sHtml.replace(/<\/?\w+:[^>]*>/ig, '');
if(deepClean)sHtml = sHtml.replace(/<\/?(span|a|img)(\s+[^>]*?)?>/ig,'');
//属性清理
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+class\s*=\s*(["']?)\s*mso.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//删除所有mso开头的样式
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+lang\s*=\s*(["']?)\s*.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//删除lang属性
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+align\s*=\s*(["']?)\s*left\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//取消align=left
//样式清理
sHtml = sHtml.replace(/<\w+(?:\s+[^>]*?)?(\s+style\s*=\s*(["']?)\s*([\s\S]*?)\s*\2)(?:\s+[^>]*?)?\s*\/?>/ig,function(all,attr,p,styles){
styles=$.trim(styles.replace(/\s*(mso-[^:]+:.+?|margin\s*:\s*0cm 0cm 0pt\s*|(text-align|font-variant|line-height)\s*:\s*.+?)(;|$)\s*/ig,''));
return all.replace(attr,deepClean?'':styles?' style="'+styles+'"':'');
});
}
return sHtml;
}
this.cleanHTML=function(sHtml)
{
sHtml = sHtml.replace(/<!?\/?(DOCTYPE|html|body|meta)(\s+[^>]*?)?>/ig, '');
var arrHeadSave;sHtml = sHtml.replace(/<head(?:\s+[^>]*?)?>([\s\S]*?)<\/head>/i, function(all,content){arrHeadSave=content.match(/<(script|style)(\s+[^>]*?)?>[\s\S]*?<\/\1>/ig);return '';});
if(arrHeadSave)sHtml=arrHeadSave.join('')+sHtml;
sHtml = sHtml.replace(/<\??xml(:\w+)?(\s+[^>]*?)?>([\s\S]*?<\/xml>)?/ig, '');
if(!settings.linkTag)sHtml = sHtml.replace(/<link(\s+[^>]*?)?>/ig, '');
if(!settings.internalScript)sHtml = sHtml.replace(/<script(\s+[^>]*?)?>[\s\S]*?<\/script>/ig, '');
if(!settings.inlineScript)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+on(?:click|dblclick|mousedown|mouseup|mousemove|mouseover|mouseout|mouseenter|mouseleave|keydown|keypress|keyup|change|select|submit|reset|blur|focus|load|unload)\s*=\s*(["']?)[\s\S]*?\3((?:\s+[^>]*?)?\/?>)/ig,'$1$2$4');
if(!settings.internalStyle)sHtml = sHtml.replace(/<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
if(!settings.inlineStyle)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+(style|class)\s*=\s*(["']?)[\s\S]*?\4((?:\s+[^>]*?)?\/?>)/ig,'$1$2$5');
sHtml=sHtml.replace(/<\/(strong|b|u|strike|em|i)>((?:\s|<br\/?>| )*?)<\1(\s+[^>]*?)?>/ig,'$2');//连续相同标签
return sHtml;
}
this.formatXHTML=function(sHtml,bFormat)
{
var emptyTags = makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");//HTML 4.01
var blockTags = makeMap("address,applet,blockquote,button,center,dd,dir,div,dl,dt,fieldset,form,frameset,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");//HTML 4.01
var inlineTags = makeMap("a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");//HTML 4.01
var closeSelfTags = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
var fillAttrsTags = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
var specialTags = makeMap("script,style");
var tagReplac={'b':'strong','i':'em','s':'del','strike':'del'};
var startTag = /^<\??(\w+(?:\:\w+)?)((?:\s+[\w-\:]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/(\w+(?:\:\w+)?)[^>]*>/;
var attr = /\s+([\w-]+(?:\:\w+)?)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s]+)))?/g;
var skip=0,stack=[],last=sHtml,results=Array(),lvl=-1,lastTag='body',lastTagStart;
stack.last = function(){return this[ this.length - 1 ];};
while(last.length>0)
{
if(!stack.last()||!specialTags[stack.last()])
{
skip=0;
if(last.substring(0, 4)=='<!--')
{//注释标签
skip=last.indexOf("-->");
if(skip!=-1)
{
skip+=3;
addHtmlFrag(last.substring(0,skip));
}
}
else if(last.substring(0, 2)=='</')
{//结束标签
match = last.match( endTag );
if(match)
{
parseEndTag(match[1]);
skip = match[0].length;
}
}
else if(last.charAt(0)=='<')
{//开始标签
match = last.match( startTag );
if(match)
{
parseStartTag(match[1],match[2],match[3]);
skip = match[0].length;
}
}
if(skip==0)//普通文本
{
skip=last.indexOf('<');
if(skip==0)skip=1;
else if(skip<0)skip=last.length;
addHtmlFrag(_this.domEncode(last.substring(0,skip)));
}
last=last.substring(skip);
}
else
{//处理style和script
last=last.replace(/^([\s\S]*?)<\/(style|script)>/i, function(all, script,tagName){
results.push(script);
return ''
});
parseEndTag(stack.last());
}
}
parseEndTag();
sHtml=results.join('');
results=null;
function makeMap(str)
{
var obj = {}, items = str.split(",");
for ( var i = 0; i < items.length; i++ )obj[ items[i] ] = true;
return obj;
}
function processTag(tagName)
{
if(tagName)
{
tagName=tagName.toLowerCase();
var tag=tagReplac[tagName];
if(tag)tagName=tag;
}
else tagName='';
return tagName;
}
function parseStartTag(tagName,rest,unary)
{
tagName=processTag(tagName);
if(blockTags[tagName])while(stack.last()&&inlineTags[stack.last()])parseEndTag(stack.last());
if(closeSelfTags[tagName]&&stack.last()==tagName)parseEndTag(tagName);
unary = emptyTags[ tagName ] || !!unary;
if (!unary)stack.push(tagName);
var all=Array();
all.push('<' + tagName);
rest.replace(attr, function(match, name)
{
name=name.toLowerCase();
var value = arguments[2] ? arguments[2] :
arguments[3] ? arguments[3] :
arguments[4] ? arguments[4] :
fillAttrsTags[name] ? name : "";
all.push(' '+name+'="'+value+'"');
});
all.push((unary ? " /" : "") + ">");
addHtmlFrag(all.join(''),tagName,true);
}
function parseEndTag(tagName)
{
if(!tagName)var pos=0;//清空栈
else
{
tagName=processTag(tagName);
for(var pos=stack.length-1;pos>=0;pos--)if(stack[pos]==tagName)break;//向上寻找匹配的开始标签
}
if(pos>=0)
{
for(var i=stack.length-1;i>=pos;i--)addHtmlFrag("</" + stack[i] + ">",stack[i]);
stack.length=pos;
}
}
function addHtmlFrag(html,tagName,bStart)
{
if(bFormat==true)
{
html=html.replace(/(\t*\r?\n\t*)+/g,'');//清理换行符和相邻的制表符
if(html.match(/^\s*$/))return;//不格式化空内容的标签
var bBlock=blockTags[tagName],tag=bBlock?tagName:'';
if(bBlock)
{
if(bStart)lvl++;//块开始
if(lastTag=='')lvl--;//补文本结束
}
else if(lastTag)lvl++;//文本开始
if(tag!=lastTag||bBlock)addIndent();
results.push(html);
if(tagName=='br')addIndent();//回车强制换行
if(bBlock&&(emptyTags[tagName]||!bStart))lvl--;//块结束
lastTag=bBlock?tagName:'';lastTagStart=bStart;
}
else results.push(html);
}
function addIndent(){results.push('\r\n');if(lvl>0){var tabs=lvl;while(tabs--)results.push("\t");}}
//font转style
function font2style(all,tag,attrs,content)
{
if(!attrs)return content;
var styles='',f,s,c,style;
f=attrs.match(/ face\s*=\s*"\s*([^"]+)\s*"/i);
if(f)styles+='font-family:'+f[1]+';';
s=attrs.match(/ size\s*=\s*"\s*(\d+)\s*"/i);
if(s)styles+='font-size:'+arrFontsize[(s[1]>7?7:(s[1]<1?1:s[1]))-1].n+';';
c=attrs.match(/ color\s*=\s*"\s*([^"]+)\s*"/i);
if(c)styles+='color:'+c[1]+';';
style=attrs.match(/ style\s*=\s*"\s*([^"]+)\s*"/i);
if(style)styles+=style[1];
if(styles)content='<span style="'+styles+'">'+content+'</span>';
return content;
}
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,font2style);//最里层
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,font2style);//第2层
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,font2style);//第3层
sHtml = sHtml.replace(/^(\s*\r?\n)+|(\s*\r?\n)+$/g,'');//清理首尾换行
sHtml = sHtml.replace(/(\t*\r?\n)+/g,'\r\n');//多行变一行
return sHtml;
}
this.toggleShowBlocktag=function(state)
{
if(bShowBlocktag===state)return;
bShowBlocktag=!bShowBlocktag;
var _jBody=$(_doc.body);
if(bShowBlocktag)
{
bodyClass+=' showBlocktag';
_jBody.addClass('showBlocktag');
}
else
{
bodyClass=bodyClass.replace(' showBlocktag','');
_jBody.removeClass('showBlocktag');
}
}
this.toggleSource=function(state)
{
if(bSource===state)return;
_jTools.find('[name=Source]').toggleClass('xheEnabled').toggleClass('xheActive');
var _body=_doc.body,jBody=$(_body),sHtml;
var sourceCode,cursorMark='<span id="_xhe_cursor'+new Date().getTime()+'"></span>',cursorPos=0;
if(!bSource)
{//转为源代码模式
_this.pasteHTML(cursorMark,true);//标记当前位置
sHtml=_this.getSource(true);
cursorPos=sHtml.indexOf(cursorMark);
if(!isOpera)cursorPos=sHtml.substring(0,cursorPos).replace(/\r/g,'').length;//修正非opera光标定位点
sHtml=sHtml.replace(cursorMark,'');
if(isIE)_body.contentEditable='false';
else _doc.designMode = 'Off';
jBody.attr('scroll','no').attr('class','sourceMode').html('<textarea id="sourceCode" wrap="soft" spellcheck="false" height="100%" />');
sourceCode=$('#sourceCode',jBody).blur(_this.getSource)[0];
}
else
{//转为编辑模式
sHtml=_this.getSource();
jBody.html('').removeAttr('scroll').attr('class','editMode'+bodyClass);
if(isIE)_body.contentEditable='true';
else _doc.designMode = 'On';
if(isMozilla)
{
_this._exec("inserthtml","-");//修正firefox源代码切换回来无法删除文字的问题
$('#'+idFixFFCursor).show().focus().hide();//临时修正Firefox 3.6光标丢失问题
}
}
bSource=!bSource;
_this.setSource(sHtml);
if(bSource)//光标定位源码
{
_this.focus();
if(sourceCode.setSelectionRange)sourceCode.setSelectionRange(cursorPos, cursorPos);
else
{
var rng = sourceCode.createTextRange();
rng.move("character",cursorPos);
rng.select();
}
}
else _this.setCursorFirst(true);//定位最前面
_jTools.find('[name=Source],[name=Preview]').toggleClass('xheEnabled');
_jTools.find('.xheButton').not('[name=Source],[name=Fullscreen],[name=About]').toggleClass('xheEnabled');
setTimeout(setOpts,300);
}
this.showPreview=function()
{
var beforeSetSource=settings.beforeSetSource,sContent=_this.getSource();
if(beforeSetSource)sContent=beforeSetSource(sContent);
var sHTML='<html><head>'+headHTML+'<title>Preview</title>'+(urlBase?'<base href="'+urlBase+'"/>':'')+'</head><body>' + sContent + '</body></html>';
var screen=window.screen,oWindow=window.open('', 'xhePreview', 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+Math.round(screen.width*0.9)+',height='+Math.round(screen.height*0.8)+',left='+Math.round(screen.width*0.05)),oDoc=oWindow.document;
oDoc.open();
oDoc.write(sHTML);
oDoc.close();
oWindow.focus();
}
this.toggleFullscreen=function(state)
{
if(bFullscreen===state)return;
var jLayout=$('#'+idContainer).find('.xheLayout'),jContainer=$('#'+idContainer);
if(bFullscreen)
{//取消全屏
jLayout.attr('style',sLayoutStyle);
_jArea.height(editorHeight-_jTools.outerHeight());
setTimeout(function(){$(window).scrollTop(outerScroll);},10);
}
else
{//显示全屏
outerScroll=$(window).scrollTop();
sLayoutStyle=jLayout.attr('style');
jLayout.removeAttr('style');
_jArea.height('100%');
setTimeout(fixFullHeight,100);
}
if(isMozilla)//临时修正Firefox 3.6源代码光标丢失问题
{
$('#'+idFixFFCursor).show().focus().hide();
setTimeout(_this.focus,1);
}
bFullscreen=!bFullscreen;
jContainer.toggleClass('xhe_Fullscreen');
$('html').toggleClass('xhe_Fullfix');
_jTools.find('[name=Fullscreen]').toggleClass('xheActive');
setTimeout(setOpts,300);
}
this.showMenu=function(menuitems,callback)
{
var jMenu=$('<div class="xheMenu"></div>'),arrItem=[];
$.each(menuitems,function(n,v){arrItem.push('<a href="javascript:void(0);" title="'+(v.t?v.t:v.s)+'" v="'+v.v+'">'+v.s+'</a>');});
jMenu.append(arrItem.join(''));
jMenu.click(function(ev){callback($(ev.target).closest('a').attr('v'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jMenu);
}
this.showColor=function(callback)
{
var jColor=$('<div class="xheColor"></div>'),arrItem=[],count=0;
$.each(itemColors,function(n,v)
{
if(count%7==0)arrItem.push((count>0?'</div>':'')+'<div>');
arrItem.push('<a href="javascript:void(0);" xhev="'+v+'" title="'+v+'" style="background:'+v+'"></a>');
count++;
});
arrItem.push('</div>');
jColor.append(arrItem.join(''));
jColor.click(function(ev){ev=ev.target;if(!$.nodeName(ev,'A'))return;callback($(ev).attr('xhev'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jColor);
}
this.showPastetext=function()
{
var jPastetext=$(htmlPastetext),jValue=$('#xhePastetextValue',jPastetext),jSave=$('#xheSave',jPastetext);
jSave.click(function(){
_this.loadBookmark();
var sValue=jValue.val();
if(sValue)_this.pasteText(sValue);
_this.hidePanel();
return false;
});
_this.showDialog(jPastetext);
}
this.showLink=function()
{
var jLink=$(htmlLink),jParent=_this.getParent('a'),jText=$('#xheLinkText',jLink),jUrl=$('#xheLinkUrl',jLink),jTarget=$('#xheLinkTarget',jLink),jSave=$('#xheSave',jLink),selHtml=_this.getSelect();
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'href'));
jTarget.attr('value',jParent.attr('target'));
}
else if(selHtml=='')jText.val(settings.defLinkText).closest('div').show();
if(settings.upLinkUrl)_this.uploadInit(jUrl,settings.upLinkUrl,settings.upLinkExt);
jSave.click(function(){
var url=jUrl.val();
_this.loadBookmark();
if(url==''||jParent.length==0)_this._exec('unlink');
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sTarget=jTarget.val(),sText=jText.val();
if(aUrl.length>1)
{//批量插入
_this._exec('unlink');//批量前删除当前链接并重新获取选择内容
selHtml=_this.getSelect();
var sTemplate='<a href="xhe_tmpurl"',sLink,arrLink=[];
if(sTarget!='')sTemplate+=' target="'+sTarget+'"';
sTemplate+='>xhe_tmptext</a>';
sText=(selHtml!=''?selHtml:(sText?sText:url));
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sLink=sTemplate;
sLink=sLink.replace('xhe_tmpurl',url[0]);
sLink=sLink.replace('xhe_tmptext',url[1]?url[1]:sText);
arrLink.push(sLink);
}
}
_this.pasteHTML(arrLink.join(' '));
}
else
{//单url模式
url=aUrl[0].split('||');
if(!sText)sText=url[0];
sText=url[1]?url[1]:(selHtml!='')?'':sText?sText:url[0];
if(jParent.length==0)
{
if(sText)_this.pasteHTML('<a href="#xhe_tmpurl">'+sText+'</a>');
else _this._exec('createlink','#xhe_tmpurl');
jParent=$('a[href$="#xhe_tmpurl"]',_doc);
}
else if(sText&&!isSafari)jParent.text(sText);//safari改写文本会导致光标丢失
xheAttr(jParent,'href',url[0]);
if(sTarget!='')jParent.attr('target',sTarget);
else jParent.removeAttr('target');
}
}
_this.hidePanel();
return false;
});
_this.showDialog(jLink);
}
this.showImg=function()
{
var jImg=$(htmlImg),jParent=_this.getParent('img'),jUrl=$('#xheImgUrl',jImg),jAlt=$('#xheImgAlt',jImg),jAlign=$('#xheImgAlign',jImg),jWidth=$('#xheImgWidth',jImg),jHeight=$('#xheImgHeight',jImg),jBorder=$('#xheImgBorder',jImg),jVspace=$('#xheImgVspace',jImg),jHspace=$('#xheImgHspace',jImg),jSave=$('#xheSave',jImg);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jAlt.val(jParent.attr('alt'));
jAlign.val(jParent.attr('align'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
jBorder.val(jParent.attr('border'));
var vspace=jParent.attr('vspace'),hspace=jParent.attr('hspace');
jVspace.val(vspace<=0?'':vspace);
jHspace.val(hspace<=0?'':hspace);
}
if(settings.upImgUrl)_this.uploadInit(jUrl,settings.upImgUrl,settings.upImgExt);
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sAlt=jAlt.val(),sAlign=jAlign.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sBorder=jBorder.val(),sVspace=jVspace.val(),sHspace=jHspace.val();;
if(aUrl.length>1)
{//批量插入
var sTemplate='<img src="xhe_tmpurl"',sImg,arrImg=[];
if(sAlt!='')sTemplate+=' alt="'+sAlt+'"';
if(sAlign!='')sTemplate+=' align="'+sAlign+'"';
if(sWidth!='')sTemplate+=' width="'+sWidth+'"';
if(sHeight!='')sTemplate+=' height="'+sHeight+'"';
if(sBorder!='')sTemplate+=' border="'+sBorder+'"';
if(sVspace!='')sTemplate+=' vspace="'+sVspace+'"';
if(sHspace!='')sTemplate+=' hspace="'+sHspace+'"';
sTemplate+=' />';
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sImg=sTemplate;
sImg=sImg.replace('xhe_tmpurl',url[0]);
if(url[1])sImg='<a href="'+url[1]+'" target="_blank">'+sImg+'</a>'
arrImg.push(sImg);
}
}
_this.pasteHTML(arrImg.join(' '));
}
else if(aUrl.length==1)
{//单URL模式
url=aUrl[0];
if(url!='')
{
url=url.split('||');
if(jParent.length==0)
{
_this.pasteHTML('<img src="'+url[0]+'#xhe_tmpurl" />');
jParent=$('img[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0])
if(sAlt!='')jParent.attr('alt',sAlt);
if(sAlign!='')jParent.attr('align',sAlign);
else jParent.removeAttr('align');
if(sWidth!='')jParent.attr('width',sWidth);
else jParent.removeAttr('width');
if(sHeight!='')jParent.attr('height',sHeight);
else jParent.removeAttr('height');
if(sBorder!='')jParent.attr('border',sBorder);
else jParent.removeAttr('border');
if(sVspace!='')jParent.attr('vspace',sVspace);
else jParent.removeAttr('vspace');
if(sHspace!='')jParent.attr('hspace',sHspace);
else jParent.removeAttr('hspace');
if(url[1])
{
var jLink=jParent.parent('a');
if(jLink.length==0)
{
jParent.wrap('<a></a>');
jLink=jParent.parent('a');
}
xheAttr(jLink,'href',url[1]);
jLink.attr('target','_blank');
}
}
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
_this.showDialog(jImg);
}
this.showEmbed=function(sType,sHtml,sMime,sClsID,sBaseAttrs,sUploadUrl,sUploadExt)
{
var jEmbed=$(sHtml),jParent=_this.getParent('embed[type="'+sMime+'"],embed[classid="'+sClsID+'"]'),jUrl=$('#xhe'+sType+'Url',jEmbed),jWidth=$('#xhe'+sType+'Width',jEmbed),jHeight=$('#xhe'+sType+'Height',jEmbed),jSave=$('#xheSave',jEmbed);
if(sUploadUrl)_this.uploadInit(jUrl,sUploadUrl,sUploadExt);
_this.showDialog(jEmbed);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
}
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var w=jWidth.val(),h=jHeight.val(),reg=/^[0-9]+$/;
if(!reg.test(w))w=412;if(!reg.test(h))h=300;
var sBaseCode='<embed type="'+sMime+'" classid="'+sClsID+'" src="xhe_tmpurl"'+sBaseAttrs;
var aUrl=url.split(' ');
if(aUrl.length>1)
{//批量插入
var sTemplate=sBaseCode+'',sEmbed,arrEmbed=[];
sTemplate+=' width="xhe_width" height="xhe_height" />';
for(var i in aUrl)
{
url=aUrl[i].split('||');
sEmbed=sTemplate;
sEmbed=sEmbed.replace('xhe_tmpurl',url[0])
sEmbed=sEmbed.replace('xhe_width',url[1]?url[1]:w)
sEmbed=sEmbed.replace('xhe_height',url[2]?url[2]:h)
if(url!='')arrEmbed.push(sEmbed);
}
_this.pasteHTML(arrEmbed.join(' '));
}
else if(aUrl.length==1)
{//单URL模式
url=aUrl[0].split('||');
if(jParent.length==0)
{
_this.pasteHTML(sBaseCode.replace('xhe_tmpurl',url[0]+'#xhe_tmpurl')+' />');
jParent=$('embed[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0]);
jParent.attr('width',url[1]?url[1]:w);
jParent.attr('height',url[2]?url[2]:h);
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
}
this.showEmot=function(group)
{
var jEmot=$('<div class="xheEmot"></div>');
group=group?group:(selEmotGroup?selEmotGroup:'default');
var arrEmot=arrEmots[group];
var sEmotPath=emotPath+group+'/',n=0,arrList=[],jList='';
var ew=arrEmot.width,eh=arrEmot.height,line=arrEmot.line,count=arrEmot.count,list=arrEmot.list;
if(count)
{
for(var i=1;i<=count;i++)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+i+'.gif);" emot="'+group+','+i+'" xhev=""> </a>');
if(n%line==0)arrList.push('<br />');
}
}
else
{
$.each(list,function(id,title)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+id+'.gif);" emot="'+group+','+id+'" title="'+title+'" xhev="'+title+'"> </a>');
if(n%line==0)arrList.push('<br />');
});
}
var w=line*(ew+12),h=Math.ceil(n/line)*(eh+12),mh=w*0.75;
if(h<=mh)mh='';
jList=$('<style>'+(mh?'.xheEmot div{width:'+(w+20)+'px;height:'+mh+'px;}':'')+'.xheEmot div a{width:'+ew+'px;height:'+eh+'px;}</style><div>'+arrList.join('')+'</div>').click(function(ev){ev=ev.target;var jA=$(ev);if(!$.nodeName(ev,'A'))return;_this.pasteHTML('<img emot="'+jA.attr('emot')+'" alt="'+jA.attr('xhev')+'">');_this.hidePanel();return false;}).mousedown(returnFalse);
jEmot.append(jList);
var gcount=0,arrGroup=['<ul>'],jGroup;//表情分类
$.each(arrEmots,function(g,v){
gcount++;
arrGroup.push('<li'+(group==g?' class="cur"':'')+'><a href="javascript:void(0);" group="'+g+'">'+v.name+'</a></li>');
});
if(gcount>1)
{
arrGroup.push('</ul><br style="clear:both;" />');
jGroup=$(arrGroup.join('')).click(function(ev){selEmotGroup=$(ev.target).attr('group');_this.exec('Emot');return false;}).mousedown(returnFalse);
jEmot.append(jGroup);
}
_this.showPanel(jEmot);
}
this.showTable=function()
{
var jTable=$(htmlTable),jRows=$('#xheTableRows',jTable),jColumns=$('#xheTableColumns',jTable),jHeaders=$('#xheTableHeaders',jTable),jWidth=$('#xheTableWidth',jTable),jHeight=$('#xheTableHeight',jTable),jBorder=$('#xheTableBorder',jTable),jCellSpacing=$('#xheTableCellSpacing',jTable),jCellPadding=$('#xheTableCellPadding',jTable),jAlign=$('#xheTableAlign',jTable),jCaption=$('#xheTableCaption',jTable),jSave=$('#xheSave',jTable);
jSave.click(function(){
_this.loadBookmark();
var sCaption=jCaption.val(),sBorder=jBorder.val(),sRows=jRows.val(),sCols=jColumns.val(),sHeaders=jHeaders.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sCellSpacing=jCellSpacing.val(),sCellPadding=jCellPadding.val(),sAlign=jAlign.val();
var i,j,htmlTable='<table'+(sBorder!=''?' border="'+sBorder+'"':'')+(sWidth!=''?' width="'+sWidth+'"':'')+(sHeight!=''?' width="'+sHeight+'"':'')+(sCellSpacing!=''?' cellspacing="'+sCellSpacing+'"':'')+(sCellPadding!=''?' cellpadding="'+sCellPadding+'"':'')+(sAlign!=''?' align="'+sAlign+'"':'')+'>';
if(sCaption!='')htmlTable+='<caption>'+sCaption+'</caption>';
if(sHeaders=='row'||sHeaders=='both')
{
htmlTable+='<tr>';
for(i=0;i<sCols;i++)htmlTable+='<th scope="col"> </th>';
htmlTable+='</tr>';
sRows--;
}
htmlTable+='<tbody>';
for(i=0;i<sRows;i++)
{
htmlTable+='<tr>';
for(j=0;j<sCols;j++)
{
if(j==0&&(sHeaders=='col'||sHeaders=='both'))htmlTable+='<th scope="row"> </th>';
else htmlTable+='<td> </td>';
}
htmlTable+='</tr>';
}
htmlTable+='</tbody></table>';
_this.pasteHTML(htmlTable);
_this.hidePanel();
return false;
});
_this.showDialog(jTable);
}
this.showAbout=function()
{
var jAbout=$(htmlAbout);
_this.showDialog(jAbout);
}
this.addShortcuts=function(key,cmd)
{
key=key.toLowerCase();
if(arrShortCuts[key]==undefined)arrShortCuts[key]=Array();
arrShortCuts[key].push(cmd);
}
this.delShortcuts=function(key){delete arrShortCuts[key];}
this.uploadInit=function(jText,toUrl,upext)
{
var jUpload=$('<span class="xheUpload"><input type="text" style="visibility:hidden;" tabindex="-1" /><input type="button" value="'+settings.upBtnText+'" class="xheBtn" tabindex="-1" /></span>'),jUpBtn=$('.xheBtn',jUpload);
var bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
jText.after(jUpload);jUpBtn.before(jText);
toUrl=toUrl.replace(/{editorRoot}/ig,editorRoot);
if(toUrl.substr(0,1)=='!')//自定义上传管理页
{
jUpBtn.click(function(){
bShowPanel=false;//防止按钮面板被关闭
_this.showIframeModal('Upload file',toUrl.substr(1),setUploadMsg,null,null,function(){bShowPanel=true;});
});
}
else
{//系统默认ajax上传
jUpload.append('<input type="file"'+(upMultiple>1?' multiple=""':'')+' class="xheFile" size="13" name="'+uploadInputname+'" tabindex="-1" />');
var jFile=$('.xheFile',jUpload),arrMsg;
jFile.change(function(){arrMsg=[];_this.startUpload(jFile[0],toUrl,upext,setUploadMsg);});
setTimeout(function(){//拖放上传
jText.closest('.xheDialog').bind('dragenter dragover',returnFalse).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(bHtml5Upload&&dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0)_this.startUpload(fileList,toUrl,upext,setUploadMsg);
return false;
});
},10);
}
function setUploadMsg(arrMsg)
{
if(is(arrMsg,'string'))arrMsg=[arrMsg];//允许单URL传递
var bImmediate=false,i,count=arrMsg.length,msg,url,arrUrl=[],onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用户上传回调
for(i=0;i<count;i++)
{
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!'){bImmediate=true;url=url.substr(1);}
arrUrl.push(url);
}
jText.val(arrUrl.join(' '));
if(bImmediate)jText.closest('.xheDialog').find('#xheSave').click();
}
}
this.startUpload=function(fromFiles,toUrl,limitExt,onUploadComplete)
{
var arrMsg=[],bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
var upload,fileList,filename,jUploadTip=$('<div style="padding:22px 0;text-align:center;line-height:30px;">File uploading,please wait...<br /></div>'),sLoading='<img src="'+skinPath+'img/loading.gif">';
if(!bHtml5Upload||(fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0])))
{
if(!checkFileExt(fromFiles.value,limitExt))return;
jUploadTip.append(sLoading);
upload=new _this.html4Upload(fromFiles,toUrl,onUploadCallback);
}
else
{
if(!fileList)fileList=fromFiles;//拖放文件列表
var i,len=fileList.length;
if(len>upMultiple){alert('Please do not upload more then '+upMultiple+' files.');return;}
for(i=0;i<len;i++)if(!checkFileExt(fileList[i].fileName,limitExt))return;
var jProgress=$('<div class="xheProgress"><div><span>0%</span></div></div>');
jUploadTip.append(jProgress);
upload=new _this.html5Upload(uploadInputname,fileList,toUrl,onUploadCallback,function(ev){
if(ev.loaded>=0)
{
var sPercent=Math.round((ev.loaded * 100) / ev.total)+'%';
$('div',jProgress).css('width',sPercent);
$('span',jProgress).text(sPercent+' ( '+formatBytes(ev.loaded)+' / '+formatBytes(ev.total)+' )');
}
else jProgress.replaceWith(sLoading);//不支持进度
});
}
var panelState=bShowPanel;
if(panelState)bShowPanel=false;//防止面板被关闭
_this.showModal('File uploading(Esc cancel)',jUploadTip,320,150,function(){bShowPanel=panelState;upload.remove();});
upload.start();
function onUploadCallback(sText,bFinish)
{
var data=Object,bOK=false;
try{data=eval('('+sText+')');}catch(ex){};
if(data.err==undefined||data.msg==undefined)alert(toUrl+' upload interface error!\r\n\r\nreturn error:\r\n\r\n'+sText);
else
{
if(data.err)alert(data.err);
else
{
arrMsg.push(data.msg);
bOK=true;//继续下一个文件上传
}
}
if(!bOK||bFinish)_this.removeModal();
if(bFinish&&bOK)onUploadComplete(arrMsg);//全部上传完成
return bOK;
}
}
this.html4Upload=function(fromfile,toUrl,callback)
{
var uid = new Date().getTime(),idIO='jUploadFrame'+uid,_this=this;
var jIO=$('<iframe name="'+idIO+'" class="xheHideArea" />').appendTo('body');
var jForm=$('<form action="'+toUrl+'" target="'+idIO+'" method="post" enctype="multipart/form-data" class="xheHideArea"></form>').appendTo('body');
var jOldFile = $(fromfile),jNewFile = jOldFile.clone().attr('disabled','true');
jOldFile.before(jNewFile).appendTo(jForm);
this.remove=function()
{
if(_this!=null)
{
jNewFile.before(jOldFile).remove();
jIO.remove();jForm.remove();
_this=null;
}
}
this.onLoad=function(){callback($(jIO[0].contentWindow.document.body).text(),true);}
this.start=function(){jForm.submit();jIO.load(_this.onLoad);}
return this;
}
this.html5Upload=function(inputname,fromFiles,toUrl,callback,onProgress)
{
var xhr,i=0,count=fromFiles.length,allLoaded=0,allSize=0,_this=this;
for(var j=0;j<count;j++)allSize+=fromFiles[j].fileSize;
this.remove=function(){if(xhr){xhr.abort();xhr=null;}}
this.uploadNext=function(sText)
{
if(sText)//当前文件上传完成
{
allLoaded+=fromFiles[i-1].fileSize;
returnProgress(0);
}
if((!sText||(sText&&callback(sText,i==count)==true))&&i<count)postFile(fromFiles[i++],toUrl,_this.uploadNext,function(loaded){returnProgress(loaded);});
}
this.start=function(){_this.uploadNext();}
function postFile(fromfile,toUrl,callback,onProgress)
{
xhr = new XMLHttpRequest(),upload=xhr.upload;
xhr.onreadystatechange=function(){if(xhr.readyState==4)callback(xhr.responseText);};
if(upload)upload.onprogress=function(ev){onProgress(ev.loaded);};
else onProgress(-1);//不支持进度
xhr.open("POST", toUrl);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Content-Disposition', 'attachment; name="'+inputname+'"; filename="'+fromfile.fileName+'"');
if(xhr.sendAsBinary)xhr.sendAsBinary(fromfile.getAsBinary());
else xhr.send(fromfile);
}
function returnProgress(loaded){if(onProgress)onProgress({'loaded':allLoaded+loaded,'total':allSize});}
}
this.showIframeModal=function(title,ifmurl,callback,w,h,onRemove)
{
var jContent=$('<iframe frameborder="0" src="'+ifmurl.replace(/{editorRoot}/ig,editorRoot)+'" style="width:100%;height:100%;display:none;" /><div class="xheModalIfmWait"></div>'),jIframe=$(jContent[0]),jWait=$(jContent[1]);
_this.showModal(title,jContent,w,h,onRemove);
jIframe.load(function(){
var modalWin=jIframe[0].contentWindow,jModalDoc=$(modalWin.document);
modalWin.callback=function(v){_this.removeModal();callback(v);};
modalWin.unloadme=_this.removeModal;
jModalDoc.keydown(_this.checkEsc);
jIframe.show();jWait.remove();
});
}
this.showModal=function(title,content,w,h,onRemove)
{
if(bShowModal)return false;//只能弹出一个模式窗口
layerShadow=settings.layerShadow;
w=w?w:settings.modalWidth;h=h?h:settings.modalHeight;
jModal=$('<div class="xheModal" style="width:'+(w-1)+'px;height:'+h+'px;margin-left:-'+Math.ceil(w/2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+Math.ceil(h/2)+'px')+'">'+(settings.modalTitle?'<div class="xheModalTitle"><span class="xheModalClose" title="Close (Esc)"></span>'+title+'</div>':'')+'<div class="xheModalContent"></div></div>').appendTo('body');
jOverlay=$('<div class="xheModalOverlay"></div>').appendTo('body');
if(layerShadow>0)jModalShadow=$('<div class="xheModalShadow" style="width:'+jModal.outerWidth()+'px;height:'+jModal.outerHeight()+'px;margin-left:-'+(Math.ceil(w/2)-layerShadow-2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+(Math.ceil(h/2)-layerShadow-2)+'px')+'"></div>').appendTo('body');
$('.xheModalContent',jModal).css('height',h-(settings.modalTitle?$('.xheModalTitle').outerHeight():0)).html(content);
if(isIE&&browerVer==6.0)jHideSelect=$('select:visible').css('visibility','hidden');//隐藏覆盖的select
$('.xheModalClose',jModal).click(_this.removeModal);
jOverlay.show();if(layerShadow>0)jModalShadow.show();jModal.show();
bShowModal=true;
onModalRemove=onRemove;
}
this.removeModal=function(){if(jHideSelect)jHideSelect.css('visibility','visible');jModal.html('').remove();if(layerShadow>0)jModalShadow.remove();jOverlay.remove();if(onModalRemove)onModalRemove();bShowModal=false;};
this.showDialog=function(content)
{
var jDialog=$('<div class="xheDialog"></div>'),jContent=$(content),jSave=$('#xheSave',jContent);
if(jSave.length==1)
{
jContent.find('input[type=text],select').keypress(function(ev){if(ev.which==13){jSave.click();return false;}});
jContent.find('textarea').keydown(function(ev){if(ev.ctrlKey&&ev.which==13){jSave.click();return false;}});
jSave.after(' <input type="button" id="xheCancel" value="Cancel" />');
$('#xheCancel',jContent).click(_this.hidePanel);
if(!settings.clickCancelDialog)
{
bClickCancel=false;//关闭点击隐藏
var jFixCancel=$('<div class="xheFixCancel"></div>').appendTo('body').mousedown(returnFalse);
var xy=_jArea.offset();
jFixCancel.css({'left':xy.left,'top':xy.top,width:_jArea.outerWidth(),height:_jArea.outerHeight()})
}
jDialog.mousedown(function(){bDisableHoverExec=true;})//点击对话框禁止悬停执行
}
jDialog.append(jContent);
_this.showPanel(jDialog);
if(!isIE)setTimeout(function(){jDialog.find('input[type=text],textarea').filter(':visible').filter(function(){return $(this).css('visibility')!='hidden';}).eq(0).focus();},10);//定位首个可见输入表单项,延迟解决opera无法设置焦点
}
this.showPanel=function(content)
{
if(!ev.target)return false;
_jPanel.html('').append(content).css('left',-999).css('top',-999);
_jPanelButton=$(ev.target).closest('a').addClass('xheActive');
var xy=_jPanelButton.offset();
var x=xy.left,y=xy.top;y+=_jPanelButton.outerHeight()-1;
_jCntLine.css({'left':x+1,'top':y,'width':_jPanelButton.width()}).show();
if((x+_jPanel.outerWidth())>document.body.clientWidth)x-=(_jPanel.outerWidth()-_jPanelButton.outerWidth());//向左显示面板
var layerShadow=settings.layerShadow;
if(layerShadow>0)_jShadow.css({'left':x+layerShadow,'top':y+layerShadow,'width':_jPanel.outerWidth(),'height':_jPanel.outerHeight()}).show();
_jPanel.css({'left':x,'top':y}).show();
bQuickHoverExec=bShowPanel=true;
}
this.hidePanel=function(){if(bShowPanel){_jPanelButton.removeClass('xheActive');_jShadow.hide();_jCntLine.hide();_jPanel.hide();bShowPanel=false;if(!bClickCancel){$('.xheFixCancel').remove();bClickCancel=true;};bQuickHoverExec=bDisableHoverExec=false;lastAngle=null;}}
this.exec=function(cmd)
{
_this.hidePanel();
_this.saveBookmark();
var tool=arrTools[cmd];
if(!tool)return false;//无效命令
if(ev==null)//非鼠标点击
{
ev={};
var btn=_jTools.find('.xheButton[name='+cmd+']');
if(btn.length==1)ev.target=btn;//设置当前事件焦点
}
if(tool.e)tool.e.call(_this)//插件事件
else//内置工具
{
cmd=cmd.toLowerCase();
switch(cmd)
{
case 'cut':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('Currently not supported by your browser, use keyboard shortcuts(Ctrl+X) instead.');};
break;
case 'copy':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('Currently not supported by your browser, use keyboard shortcuts(Ctrl+C) instead.');}
break;
case 'paste':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('Currently not supported by your browser, use keyboard shortcuts(Ctrl+V) instead.');}
break;
case 'pastetext':
if(window.clipboardData)_this.pasteText(window.clipboardData.getData('Text', true));
else _this.showPastetext();
break;
case 'blocktag':
var menuBlocktag=[];
$.each(arrBlocktag,function(n,v){menuBlocktag.push({s:'<'+v.n+'>'+v.t+'</'+v.n+'>',v:'<'+v.n+'>',t:v.t});});
_this.showMenu(menuBlocktag,function(v){_this._exec('formatblock',v);});
break;
case 'fontface':
var menuFontname=[];
$.each(arrFontname,function(n,v){v.c=v.c?v.c:v.n;menuFontname.push({s:'<span style="font-family:'+v.c+'">'+v.n+'</span>',v:v.c,t:v.n});});
_this.showMenu(menuFontname,function(v){_this._exec('fontname',v);});
break;
case 'fontsize':
var menuFontsize=[];
$.each(arrFontsize,function(n,v){menuFontsize.push({s:'<span style="font-size:'+v.s+';">'+v.t+'('+v.s+')</span>',v:n+1,t:v.t});});
_this.showMenu(menuFontsize,function(v){_this._exec('fontsize',v);});
break;
case 'fontcolor':
_this.showColor(function(v){_this._exec('forecolor',v);});
break;
case 'backcolor':
_this.showColor(function(v){if(isIE)_this._exec('backcolor',v);else{setCSS(true);_this._exec('hilitecolor',v);setCSS(false);}});
break;
case 'align':
_this.showMenu(menuAlign,function(v){_this._exec(v);});
break;
case 'list':
_this.showMenu(menuList,function(v){_this._exec(v);});
break;
case 'link':
_this.showLink();
break;
case 'img':
_this.showImg();
break;
case 'flash':
_this.showEmbed('Flash',htmlFlash,'application/x-shockwave-flash','clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000',' wmode="opaque" quality="high" menu="false" play="true" loop="true" allowfullscreen="true"',settings.upFlashUrl,settings.upFlashExt);
break;
case 'media':
_this.showEmbed('Media',htmlMedia,'application/x-mplayer2','clsid:6bf52a52-394a-11d3-b153-00c04f79faa6',' enablecontextmenu="false" autostart="false"',settings.upMediaUrl,settings.upMediaExt);
break;
case 'emot':
_this.showEmot();
break;
case 'table':
_this.showTable();
break;
case 'source':
_this.toggleSource();
break;
case 'preview':
_this.showPreview();
break;
case 'print':
_win.print();
break;
case 'fullscreen':
_this.toggleFullscreen();
break;
case 'about':
_this.showAbout();
break;
default:
_this._exec(cmd);
break;
}
}
ev=null;
}
this._exec=function(cmd,param,noFocus)
{
if(!noFocus)_this.focus();
var state;
if(param!=undefined)state=_doc.execCommand(cmd,false,param);
else state=_doc.execCommand(cmd,false,null);
return state;
}
function checkDblClick(ev)
{
var target=ev.target,tool=arrDbClick[target.tagName.toLowerCase()];
if(tool)
{
if(tool=='Embed')//自动识别Flash和多媒体
{
var arrEmbed={'application/x-shockwave-flash':'Flash','application/x-mplayer2':'Media'};
tool=arrEmbed[target.type.toLowerCase()];
}
_this.exec(tool);
}
}
function checkEsc(ev)
{
if(ev.which==27)
{
if(bShowModal)_this.removeModal();
else if(bShowPanel)_this.hidePanel();
return false;
}
}
function loadReset(){setTimeout(_this.setSource,10);}
function saveResult(){_this.getSource();};
function cleanPaste(ev){
if(bSource||bCleanPaste)return true;
bCleanPaste=true;//解决IE右键粘贴重复产生paste的问题
_this.saveBookmark();
var jDiv=$('<div style="position:absolute;left:-1000px;top:'+_jWin.scrollTop()+'px;overflow:hidden;width:1px;height:1px;" />',_doc),div=jDiv[0],sel=_this.getSel(),rng=_this.getRng();
$(_doc.body).append(jDiv);
if(isIE){
rng.moveToElementText(div);
rng.execCommand('Paste');
ev.preventDefault();
}
else{
rng.selectNodeContents(div);
sel.removeAllRanges();
sel.addRange(rng);
}
setTimeout(function(){
var sPaste;
if(settings.forcePasteText===true)sPaste=jDiv.text();
else{
sPaste=div.innerHTML;
sPaste=_this.cleanHTML(sPaste);
sPaste=_this.formatXHTML(sPaste);
sPaste=_this.cleanWord(sPaste);
}
jDiv.remove();
_this.loadBookmark();
_this.pasteHTML(sPaste);
bCleanPaste=false;
},0);
}
function setCSS(css)
{
try{_this._exec('styleWithCSS',css,true);}
catch(e)
{try{_this._exec('useCSS',!css,true);}catch(e){}}
}
function setOpts()
{
if(bInit&&!bSource)
{
setCSS(false);
try{_this._exec('enableObjectResizing',true,true);}catch(e){}
//try{_this._exec('enableInlineTableEditing',false,true);}catch(e){}
if(isIE)try{_this._exec('BackgroundImageCache',true,true);}catch(e){}
}
}
function forcePtag(ev)
{
if(bSource||ev.which!=13||ev.shiftKey||ev.ctrlKey||ev.altKey)return true;
var pNode=_this.getParent('p,h1,h2,h3,h4,h5,h6,pre,address,div,li');
if(pNode.is('li'))return true;
if(settings.forcePtag){if(pNode.length==0)_this._exec('formatblock','<p>');}
else
{
_this.pasteHTML('<br />');
if(isIE&&pNode.length>0&&_this.getRng().parentElement().childNodes.length==2)_this.pasteHTML('<br />');
return false;
}
}
function fixFullHeight()
{
if(!isMozilla&&!isSafari)
{
if(bFullscreen)_jArea.height('100%').css('height',_jArea.outerHeight()-_jTools.outerHeight());
if(isIE)_jTools.hide().show();
}
}
function fixAppleSel(e)
{
e=e.target;
if(e.tagName.match(/(img|embed)/i))
{
var sel=_this.getSel(),rng=_this.getRng();
rng.selectNode(e);
sel.removeAllRanges();
sel.addRange(rng);
}
}
function xheAttr(jObj,n,v)
{
if(!n)return false;
var kn='_xhe_'+n;
if(v)//设置属性
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
jObj.attr(n,urlBase?getLocalUrl(v,'abs',urlBase):v).removeAttr(kn).attr(kn,v);
}
return jObj.attr(kn)||jObj.attr(n);
}
function clickCancelPanel(){if(bClickCancel)_this.hidePanel();}
function checkShortcuts(event)
{
if(bSource)return true;
var code=event.which,special=specialKeys[code],sChar=special?special:String.fromCharCode(code).toLowerCase();
sKey='';
sKey+=event.ctrlKey?'ctrl+':'';sKey+=event.altKey?'alt+':'';sKey+=event.shiftKey?'shift+':'';sKey+=sChar;
var cmd=arrShortCuts[sKey],c;
for(c in cmd)
{
c=cmd[c];
if($.isFunction(c)){if(c.call(_this)===false)return false;}
else{_this.exec(c);return false;}//按钮独占快捷键
}
}
function is(o,t)
{
var n = typeof(o);
if (!t)return n != 'undefined';
if (t == 'array' && (o.hasOwnProperty && o instanceof Array))return true;
return n == t;
}
function getLocalUrl(url,urlType,urlBase)//绝对地址:abs,根地址:root,相对地址:rel
{
var baseUrl=urlBase?$('<a href="'+urlBase+'" />')[0]:location,protocol=baseUrl.protocol,host=baseUrl.hostname,port=baseUrl.port,path=baseUrl.pathname.replace(/\\/g,'/').replace(/[^\/]+$/i,'');
port=(port=='')?'80':port;
url=$.trim(url);
if(urlType!='abs')url=url.replace(new RegExp(protocol+'\\/\\/'+host.replace(/\./g,'\\.')+'(?::'+port+')'+(port=='80'?'?':'')+'(\/|$)','i'),'/');
if(urlType=='rel')url=url.replace(new RegExp('^'+path.replace(/([\/\.\+\[\]\(\)])/g,'\\$1'),'i'),'');
if(urlType!='rel')
{
if(!url.match(/^((https?|file):\/\/|\/)/i))url=path+url;
if(url.charAt(0)=='/')//处理..
{
var arrPath=[],arrFolder = url.split('/'),folder,i,l=arrFolder.length;
for(i=0;i<l;i++)
{
folder=arrFolder[i];
if(folder=='..')arrPath.pop();
else if(folder!==''&&folder!='.')arrPath.push(folder);
}
if(arrFolder[l-1]=='')arrPath.push('');
url='/'+arrPath.join('/');
}
}
if(urlType=='abs')if(!url.match(/(https?|file):\/\//i))url=protocol+'//'+location.host+url;
return url;
}
function checkFileExt(filename,limitExt)
{
if(limitExt=='*'||filename.match(new RegExp('\.('+limitExt.replace(/,/g,'|')+')$','i')))return true;
else
{
alert('Upload file extension required for this: '+limitExt);
return false;
}
}
function formatBytes(bytes)
{
var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+s[e];
}
function returnFalse(){return false;}
}
$(function(){
$.fn.oldVal=$.fn.val;
$.fn.val=function(value)
{
var _this=this,editor;
if(value===undefined)if(this[0]&&(editor=this[0].xheditor))return editor.getSource();else return _this.oldVal(value);//读
return this.each(function(){if(editor=this.xheditor)editor.setSource(value);else _this.oldVal(value);});//写
}
$('textarea').each(function(){
var self=$(this),xhClass=self.attr('class').match(/(?:^|\s)xheditor(?:\-(m?full|simple|mini))?(?:\s|$)/i);
if(xhClass)self.xheditor(xhClass[1]?{tools:xhClass[1]}:null);
});
});
})(jQuery); | JavaScript |
function codeImg(b) {
b.src = "getCodeImg?" + Math.random();
}
function clearApplication() {
$.ajax( {
type : "get",
url : "clearApplication.jsp?" + Math.random(),
error : function() {
alert("加载错误");
},
success : function() {
}
});
}
function clearSelect() {
$.ajax( {
type : "get",
url : "clearSelect.do?" + Math.random(),
error : function() {
alert("加载错误");
},
success : function() {
}
});
}
| JavaScript |
/*!
* jQuery Form Plugin
* version: 2.49 (18-OCT-2010)
* @requires jQuery v1.3.2 or later
*
* Examples and documentation at: http://malsup.com/jquery/form/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;
(function($) {
/*
* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the
* same form. These functions are intended to be exclusive. Use ajaxSubmit
* if you want to bind your own submit handler to the form. For example,
*
* $(document).ready(function() { $('#myForm').bind('submit', function(e) {
* e.preventDefault(); // <-- important $(this).ajaxSubmit({ target:
* '#output' }); }); });
*
* Use ajaxForm when you want the plugin to manage all the event binding for
* you. For example,
*
* $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output'
* }); });
*
* When using ajaxForm, the ajaxSubmit function will be invoked for you at
* the appropriate time.
*/
/**
* ajaxSubmit() provides a mechanism for immediately submitting an HTML form
* using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
if (typeof options == 'function') {
options = {
success : options
};
}
var url = $.trim(this.attr('action'));
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/) || [])[1];
}
url = url || window.location.href || '';
options = $
.extend(
true,
{
url : url,
type : this.attr('method') || 'GET',
iframeSrc : /^https/i
.test(window.location.href || '') ? 'javascript:false'
: 'about:blank'
}, options);
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [ this, options, veto ]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize
&& options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var n, v, a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (n in options.data) {
if (options.data[n] instanceof Array) {
for ( var k in options.data[n]) {
a.push( {
name : n,
value : options.data[n][k]
});
}
} else {
v = options.data[n];
v = $.isFunction(v) ? v() : v; // if value is fn, invoke it
a.push( {
name : n,
value : v
});
}
}
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit
&& options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [ a, this, options, veto ]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
} else {
options.data = q; // data is the query string for 'post'
}
var $form = this, callbacks = [];
if (options.resetForm) {
callbacks.push(function() {
$form.resetForm();
});
}
if (options.clearForm) {
callbacks.push(function() {
$form.clearForm();
});
}
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function() {
};
callbacks.push(function(data) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
} else if (options.success) {
callbacks.push(options.success);
}
options.success = function(data, status, xhr) { // jQuery 1.4+ passes
// xhr as 3rd arg
var context = options.context || options; // jQuery 1.4+ supports
// scope context
for ( var i = 0, max = callbacks.length; i < max; i++) {
callbacks[i].apply(context,
[ data, status, xhr || $form, $form ]);
}
};
// are there files to upload?
var fileInputs = $('input:file', this).length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false
&& (fileInputs || options.iframe || multipart)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see:
// http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, fileUpload);
} else {
fileUpload();
}
} else {
$.ajax(options);
}
// fire 'notify' event
this.trigger('form-submit-notify', [ this, options ]);
return this;
// private function for handling file uploads (hat tip to YAHOO!)
function fileUpload() {
var form = $form[0];
if ($(':input[name=submit],:input[id=submit]', form).length) {
// if there is an input with a name or id of 'submit' then we
// won't be
// able to invoke the submit fn on the form (at least not
// x-browser)
alert('Error: Form elements must not have name or id of "submit".');
return;
}
var s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
var id = 'jqFormIO' + (new Date().getTime()), fn = '_' + id;
window[fn] = function() {
var f = $io.data('form-plugin-onload');
if (f) {
f();
window[fn] = undefined;
try {
delete window[fn];
} catch (e) {
}
}
}
var $io = $('<iframe id="' + id + '" name="' + id + '" src="'
+ s.iframeSrc + '" onload="window[\'_\'+this.id]()" />');
var io = $io[0];
$io.css( {
position : 'absolute',
top : '-1000px',
left : '-1000px'
});
var xhr = { // mock object
aborted : 0,
responseText : null,
responseXML : null,
status : 0,
statusText : 'n/a',
getAllResponseHeaders : function() {
},
getResponseHeader : function() {
},
setRequestHeader : function() {
},
abort : function() {
this.aborted = 1;
$io.attr('src', s.iframeSrc); // abort op in progress
}
};
var g = s.global;
// trigger ajax global events so that activity/block indicators work
// like normal
if (g && !$.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [ xhr, s ]);
}
if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active--;
}
return;
}
if (xhr.aborted) {
return;
}
var cbInvoked = false;
var timedOut = 0;
// add submitting element to data if we know it
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData[n] = sub.value;
if (sub.type == "image") {
s.extraData[n + '.x'] = form.clk_x;
s.extraData[n + '.y'] = form.clk_y;
}
}
}
// take a breath so that pending repaints get some cpu time before
// the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');
// update form attrs in IE friendly way
form.setAttribute('target', id);
if (form.getAttribute('method') != 'POST') {
form.setAttribute('method', 'POST');
}
if (form.getAttribute('action') != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (!s.skipEncodingOverride) {
$form.attr( {
encoding : 'multipart/form-data',
enctype : 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
setTimeout(function() {
timedOut = true;
cb();
}, s.timeout);
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for ( var n in s.extraData) {
extraInputs.push($(
'<input type="hidden" name="' + n
+ '" value="' + s.extraData[n]
+ '" />').appendTo(form)[0]);
}
}
// add iframe to doc and submit the form
$io.appendTo('body');
$io.data('form-plugin-onload', cb);
form.submit();
} finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action', a);
if (t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
if (s.forceSync) {
doSubmit();
} else {
setTimeout(doSubmit, 10); // this lets dom updates render
}
var data, doc, domCheckCount = 50;
function cb() {
if (cbInvoked) {
return;
}
$io.removeData('form-plugin-onload');
var ok = true;
try {
if (timedOut) {
throw 'timeout';
}
// extract the server response from the iframe
doc = io.contentWindow ? io.contentWindow.document
: io.contentDocument ? io.contentDocument
: io.document;
var isXml = s.dataType == 'xml' || doc.XMLDocument
|| $.isXMLDoc(doc);
log('isXml=' + isXml);
if (!isXml && window.opera
&& (doc.body == null || doc.body.innerHTML == '')) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not
// always traversable when
// the onload callback fires, so we loop a bit to
// accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could
// be an empty document
// log('Could not access iframe DOM after mutiple
// tries.');
// throw 'DOMException: not available';
}
// log('response detected');
cbInvoked = true;
xhr.responseText = doc.documentElement ? doc.documentElement.innerHTML
: null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
xhr.getResponseHeader = function(header) {
var headers = {
'content-type' : s.dataType
};
return headers[header];
};
var scr = /(json|script)/.test(s.dataType);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
} else if (scr) {
// account for browsers injecting pre around json
// response
var pre = doc.getElementsByTagName('pre')[0];
var b = doc.getElementsByTagName('body')[0];
if (pre) {
xhr.responseText = pre.innerHTML;
} else if (b) {
xhr.responseText = b.innerHTML;
}
}
} else if (s.dataType == 'xml' && !xhr.responseXML
&& xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = $.httpData(xhr, s.dataType);
} catch (e) {
log('error caught:', e);
ok = false;
xhr.error = e;
$.handleError(s, xhr, 'error', e);
}
// ordering of these callbacks/triggers is odd, but that's how
// $.ajax does it
if (ok) {
s.success.call(s.context, data, 'success', xhr);
if (g) {
$.event.trigger("ajaxSuccess", [ xhr, s ]);
}
}
if (g) {
$.event.trigger("ajaxComplete", [ xhr, s ]);
}
if (g && !--$.active) {
$.event.trigger("ajaxStop");
}
if (s.complete) {
s.complete.call(s.context, xhr, ok ? 'success' : 'error');
}
// clean up
setTimeout(function() {
$io.removeData('form-plugin-onload');
$io.remove();
xhr.responseXML = null;
}, 100);
}
function toXml(s, doc) {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
} else {
doc = (new DOMParser()).parseFromString(s, 'text/xml');
}
return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc
: null;
}
}
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" />
* elements (if the element is used to submit the form). 2. This method will
* include the submit element's name/value data (for the element that was
* used to submit the form). 3. This method binds the submit() method to the
* form for you.
*
* The options argument for ajaxForm works exactly as it does for
* ajaxSubmit. ajaxForm merely passes the options argument along after
* properly binding events for submit elements and the form itself.
*/
$.fn.ajaxForm = function(options) {
// in jQuery 1.3+ we can fix mistakes with the ready state
if (this.length === 0) {
var o = {
s : this.selector,
c : this.context
};
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function() {
$(o.s, o.c).ajaxForm(options);
});
return this;
}
// is your DOM ready?
// http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? ''
: ' (DOM not ready)'));
return this;
}
return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
if (!e.isDefaultPrevented()) { // if event has been canceled, don't
// proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
}).bind('click.form-plugin', function(e) {
var target = e.target;
var $el = $(target);
if (!($el.is(":submit,input:image"))) {
// is this a child element of the submit el? (ex: a span within
// a button)
var t = $el.closest(':submit');
if (t.length == 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use
// dimensions
// plugin
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function() {
form.clk = form.clk_x = form.clk_y = null;
}, 100);
});
};
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An
* example of an array for a simple login form might be:
* [ { name: 'username', value: 'jresig' }, { name: 'password', value:
* 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided
* to the ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length === 0) {
return a;
}
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) {
return a;
}
var i, j, n, v, el, max, jmax;
for (i = 0, max = els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n) {
continue;
}
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if (!el.disabled && form.clk == el) {
a.push( {
name : n,
value : $(el).val()
});
a.push( {
name : n + '.x',
value : form.clk_x
}, {
name : n + '.y',
value : form.clk_y
});
}
continue;
}
v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for (j = 0, jmax = v.length; j < jmax; j++) {
a.push( {
name : n,
value : v[j]
});
}
} else if (v !== null && typeof v != 'undefined') {
a.push( {
name : n,
value : v
});
}
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it
// here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push( {
name : n,
value : $input.val()
});
a.push( {
name : n + '.x',
value : form.clk_x
}, {
name : n + '.y',
value : form.clk_y
});
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return
* a string in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function(semantic) {
// hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format:
* name1=value1&name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) {
return;
}
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for ( var i = 0, max = v.length; i < max; i++) {
a.push( {
name : n,
value : v[i]
});
}
} else if (v !== null && typeof v != 'undefined') {
a.push( {
name : this.name,
value : v
});
}
});
// hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example,
* consider the following form:
*
* <form><fieldset> <input name="A" type="text" /> <input name="A"
* type="text" /> <input name="B" type="checkbox" value="B1" /> <input
* name="B" type="checkbox" value="B2"/> <input name="C" type="radio"
* value="C1" /> <input name="C" type="radio" value="C2" /> </fieldset></form>
*
* var v = $(':text').fieldValue(); // if no values are entered into the
* text inputs v == ['',''] // if values entered into the text inputs are
* 'foo' and 'bar' v == ['foo','bar']
*
* var v = $(':checkbox').fieldValue(); // if neither checkbox is checked v
* === undefined // if both checkboxes are checked v == ['B1', 'B2']
*
* var v = $(':radio').fieldValue(); // if neither radio is checked v ===
* undefined // if first radio is checked v == ['C1']
*
* The successful argument controls whether or not the field element must be
* 'successful' (per
* http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The
* default value of the successful argument is true. If this value is false
* the value(s) for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be
* determined the array will be empty, otherwise it will contain one or more
* values.
*/
$.fn.fieldValue = function(successful) {
for ( var val = [], i = 0, max = this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined'
|| (v.constructor == Array && !v.length)) {
continue;
}
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (successful === undefined) {
successful = true;
}
if (successful
&& (!n || el.disabled || t == 'reset' || t == 'button'
|| (t == 'checkbox' || t == 'radio') && !el.checked
|| (t == 'submit' || t == 'image') && el.form
&& el.form.clk != el || tag == 'select'
&& el.selectedIndex == -1)) {
return null;
}
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) {
return null;
}
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index + 1 : ops.length);
for ( var i = (one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text
: op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};
/**
* Clears the form data. Takes the following actions on the form's input
* fields: - input text fields will have their 'value' property set to the
* empty string - select elements will have their 'selectedIndex' property
* set to -1 - checkbox and radio inputs will have their 'checked' property
* set to false - inputs of type submit, button, reset, and hidden will
* *not* be effected - button elements will *not* be effected
*/
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea') {
this.value = '';
} else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
} else if (tag == 'select') {
this.selectedIndex = -1;
}
});
};
/**
* Resets the form data. Causes all form elements to be reset to their
* original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function'
|| (typeof this.reset == 'object' && !this.reset.nodeType)) {
this.reset();
}
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) {
if (b === undefined) {
b = true;
}
return this.each(function() {
this.disabled = !b;
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function(select) {
if (select === undefined) {
select = true;
}
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio') {
this.checked = select;
} else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
}) ;
};
// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
if ($.fn.ajaxSubmit.debug) {
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,
'');
if (window.console && window.console.log) {
window.console.log(msg);
} else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
}
}
;
})(jQuery);
| JavaScript |
//**********************图片上传预览插件************************
//作者:IDDQD(2009-07-01)
//Email:iddqd5376@163.com
//http://iddqd5376.blog.163.com
//版本:1.0
//说明:图片上传预览插件
//上传的时候可以生成固定宽高范围内的等比例缩放图
//参数设置:
//width 存放图片固定大小容器的宽
//height 存放图片固定大小容器的高
//imgDiv 页面DIV的JQuery的id
//imgType 数组后缀名
//**********************图片上传预览插件*************************
(function($) {
jQuery.fn.extend({
uploadPreview: function(opts) {
opts = jQuery.extend({
width: 0,
height: 0,
imgDiv: "#imgDiv",
imgType: ["gif", "jpeg", "jpg", "bmp", "png"],
callback: function() { return false; }
}, opts || {});
var _self = this;
var _this = $(this);
var imgDiv = $(opts.imgDiv);
imgDiv.width(opts.width);
imgDiv.height(opts.height);
autoScaling = function() {
if ($.browser.version == "7.0" || $.browser.version == "8.0") imgDiv.get(0).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = "image";
var img_width = imgDiv.width();
var img_height = imgDiv.height();
if (img_width > 0 && img_height > 0) {
var rate = (opts.width / img_width < opts.height / img_height) ? opts.width / img_width : opts.height / img_height;
if (rate <= 1) {
if ($.browser.version == "7.0" || $.browser.version == "8.0") imgDiv.get(0).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = "scale";
imgDiv.width(img_width * rate);
imgDiv.height(img_height * rate);
} else {
imgDiv.width(img_width);
imgDiv.height(img_height);
}
var left = (opts.width - imgDiv.width()) * 0.5;
var top = (opts.height - imgDiv.height()) * 0.5;
imgDiv.css({ "margin-left": left, "margin-top": top });
imgDiv.show();
}
}
_this.change(function() {
if (this.value) {
if (!RegExp("\.(" + opts.imgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
alert("图片类型必须是" + opts.imgType.join(",") + "中的一种");
this.value = "";
return false;
}
imgDiv.hide();
if ($.browser.msie) {
if ($.browser.version == "6.0") {
var img = $("<img />");
imgDiv.replaceWith(img);
imgDiv = img;
var image = new Image();
image.src = 'file:///' + this.value;
imgDiv.attr('src', image.src);
autoScaling();
}
else {
imgDiv.css({ filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image)" });
imgDiv.get(0).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = "image";
try {
imgDiv.get(0).filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = this.value;
} catch (e) {
alert("无效的图片文件!");
return;
}
setTimeout("autoScaling()", 100);
}
}
else {
var img = $("<img />");
imgDiv.replaceWith(img);
imgDiv = img;
imgDiv.attr('src', this.files.item(0).getAsDataURL());
imgDiv.css({ "vertical-align": "middle" });
setTimeout("autoScaling()", 100);
}
}
});
}
});
})(jQuery); | JavaScript |
/**
* jQuery Checkbox Tree
*
* @author Valerio Galano <valerio.galano@gmail.com>
*
* @see http://checkboxtree.googlecode.com
*
* @version 0.3.1
*/
(function($){
var checkboxTree = 0;
$.fn.checkboxTree = function(options) {
// build main options before element iteration
var options = $.extend({
checkChildren: true,
checkParents: true,
collapsable: true,
collapseAllButton: '',
collapsed: false,
collapseDuration: 500,
collapseEffect: 'blind',
collapseImage: '',
container: 'checkboxTree'+'['+ checkboxTree++ +']',
cssClass: 'checkboxTree',
expandAllButton: '',
expandDuration: 500,
expandEffect: 'blind',
expandImage: '',
leafImage: ''
}, options);
options.collapseAnchor = (options.collapseImage.length > 0) ? '<img src="'+options.collapseImage+'" />' : '-';
options.expandAnchor = (options.expandImage.length > 0) ? '<img src="'+options.expandImage+'" />' : '+';
options.leafAnchor = (options.leafImage.length > 0) ? '<img src="'+options.leafImage+'" />' : '';
// build collapse all button
if (options.collapseAllButton.length > 0) {
$collapseAllButton = $('<a/>', {
'class': options.cssClass+' all',
id: options.container+'collapseAll',
href: 'javascript:void(0);',
html: options.collapseAllButton,
click: function(){
$('[class*=' + options.container + '] span').each(function(){
if ($(this).hasClass("expanded")) {
collapse($(this), options);
}
});
}
});
this.parent().prepend($collapseAllButton);
}
// build expand all button
if (options.expandAllButton.length > 0) {
$expandAllButton = $('<a/>', {
'class': options.cssClass+' all',
id: options.container+'expandAll',
href: 'javascript:void(0);',
html: options.expandAllButton,
click: function(){
$('[class*=' + options.container + '] span').each(function(){
if ($(this).hasClass("collapsed")) {
expand($(this), options);
}
});
}
});
this.parent().prepend($expandAllButton);
}
// setup tree
$("li", this).each(function() {
if (options.collapsable) {
var $a;
if ($(this).is(":has(ul)")) {
if (options.collapsed) {
$(this).find("ul").hide();
$a = $('<span></span>').html(options.expandAnchor).addClass("collapsed");
} else {
$a = $('<span></span>').html(options.collapseAnchor).addClass("expanded");
}
} else {
$a = $('<span></span>').html(options.leafAnchor).addClass("leaf");
}
$(this).prepend($a);
}
});
// handle single expand/collapse
this.find('span').bind("click", function(e, a){
if ($(this).hasClass("leaf") == undefined) {
return;
}
if ($(this).hasClass("collapsed")) {
expand($(this), options);
} else {
collapse($(this), options);
}
});
// handle tree select/unselect
this.find(':checkbox').bind("click", function(e, a) {
if (options.checkChildren) {
toggleChildren($(this));
}
if (options.checkParents && $(this).is(":checked")) {
checkParents($(this), options);
}
});
// add container class
this.addClass(options.container);
// add css class
this.addClass(options.cssClass);
return this;
};
/**
* Recursively check parents of passed checkbox
*/
this.checkParents = function(checkbox, options)
{
var parentCheckbox = checkbox.parents("li:first").parents("li:first").find(" :checkbox:first");
if (!parentCheckbox.is(":checked")) {
parentCheckbox.attr("checked","checked");
}
if (parentCheckbox.parents('[class*=' + options.container + ']').attr('class') != undefined) {
checkParents(parentCheckbox, options);
}
}
/**
* Collapse tree element
*/
this.collapse = function(img, options)
{
var listItem = img.parents("li:first");
if ($.ui !== undefined) {
listItem.children("ul").hide(options.collapseEffect, {}, options.collapseDuration);
} else {
listItem.children("ul").hide(options.collapseDuration);
}
listItem.children("span").html(options.expandAnchor).addClass("collapsed").removeClass("expanded");
}
/**
* Expand tree element
*/
this.expand = function(img, options)
{
var listItem = img.parents("li:first");
if ($.ui !== undefined) {
listItem.children("ul").show(options.expandEffect, {}, options.expandDuration);
} else {
listItem.children("ul").show(options.expandDuration);
}
listItem.children("span").html(options.collapseAnchor).addClass("expanded").removeClass("collapsed");
}
/**
* Check/uncheck children of passed checkbox
*/
this.toggleChildren = function(checkbox)
{
checkbox.parents('li:first').find('li :checkbox').attr('checked',checkbox.attr('checked') ? 'checked' : '');
}
})(jQuery);
| JavaScript |
function Node(id, pid, name, url, title, target, icon, iconOpen, open) {
this.id = id;
this.pid = pid;
this.name = name;
this.url = url;
this.title = title;
this.target = target;
this.icon = icon;
this.iconOpen = iconOpen;
this._io = open || false;
this._is = false;
this._ls = false;
this._hc = false;
this._ai = 0;
this._p;
}
// Tree object
function dTree(objName) {
this.config = {target:null, folderLinks:true, useSelection:true, useCookies:true, useLines:true, useIcons:true, useStatusText:false, closeSameLevel:false, inOrder:false};
this.icon = {root:"lib/dTree/img/base.gif", folder:"lib/dTree/img/folder.gif", folderOpen:"lib/dTree/img/folderopen.gif", node:"lib/dTree/img/page.gif", empty:"lib/dTree/img/empty.gif", line:"lib/dTree/img/line.gif", join:"lib/dTree/img/join.gif", joinBottom:"lib/dTree/img/joinbottom.gif", plus:"lib/dTree/img/plus.gif", plusBottom:"lib/dTree/img/plusbottom.gif", minus:"lib/dTree/img/minus.gif", minusBottom:"lib/dTree/img/minusbottom.gif", nlPlus:"lib/dTree/img/nolines_plus.gif", nlMinus:"lib/dTree/img/nolines_minus.gif"};
this.obj = objName;
this.aNodes = [];
this.aIndent = [];
this.root = new Node(-1);
this.selectedNode = null;
this.selectedFound = false;
this.completed = false;
}
// Adds a new node to the node array
dTree.prototype.add = function (id, pid, name, url, title, target, icon, iconOpen, open) {
this.aNodes[this.aNodes.length] = new Node(id, pid, name, url, title, target, icon, iconOpen, open);
};
// Open/close all nodes
dTree.prototype.openAll = function () {
this.oAll(true);
};
dTree.prototype.closeAll = function () {
this.oAll(false);
};
// Outputs the tree to the page
dTree.prototype.toString = function () {
var str = "<div class=\"dtree\">\n";
if (document.getElementById) {
if (this.config.useCookies) {
this.selectedNode = this.getSelected();
}
str += this.addNode(this.root);
} else {
str += "Browser not supported.";
}
str += "</div>";
if (!this.selectedFound) {
this.selectedNode = null;
}
this.completed = true;
return str;
};
// Creates the tree structure
dTree.prototype.addNode = function (pNode) {
var str = "";
var n = 0;
if (this.config.inOrder) {
n = pNode._ai;
}
for (n; n < this.aNodes.length; n++) {
if (this.aNodes[n].pid == pNode.id) {
var cn = this.aNodes[n];
cn._p = pNode;
cn._ai = n;
this.setCS(cn);
if (!cn.target && this.config.target) {
cn.target = this.config.target;
}
if (cn._hc && !cn._io && this.config.useCookies) {
cn._io = this.isOpen(cn.id);
}
if (!this.config.folderLinks && cn._hc) {
cn.url = null;
}
if (this.config.useSelection && cn.id == this.selectedNode && !this.selectedFound) {
cn._is = true;
this.selectedNode = n;
this.selectedFound = true;
}
str += this.node(cn, n);
if (cn._ls) {
break;
}
}
}
return str;
};
// Creates the node icon, url and text
dTree.prototype.node = function (node, nodeId) {
var str = "<div class=\"dTreeNode\">" + this.indent(node, nodeId);
if (this.config.useIcons) {
if (!node.icon) {
node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hc) ? this.icon.folder : this.icon.node);
}
if (!node.iconOpen) {
node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node;
}
if (this.root.id == node.pid) {
node.icon = this.icon.root;
node.iconOpen = this.icon.root;
}
str += "<img id=\"i" + this.obj + nodeId + "\" src=\"" + ((node._io) ? node.iconOpen : node.icon) + "\" alt=\"\" />";
}
if (node.url) {
str += "<a id=\"s" + this.obj + nodeId + "\" class=\"" + ((this.config.useSelection) ? ((node._is ? "nodeSel" : "node")) : "node") + "\" href=\"" + node.url + "\"";
if (node.title) {
str += " title=\"" + node.title + "\"";
}
if (node.target) {
str += " target=\"" + node.target + "\"";
}
if (this.config.useStatusText) {
str += " onmouseover=\"window.status='" + node.name + "';return true;\" onmouseout=\"window.status='';return true;\" ";
}
if (this.config.useSelection && ((node._hc && this.config.folderLinks) || !node._hc)) {
str += " onclick=\"javascript: " + this.obj + ".s(" + nodeId + ");\"";
}
str += ">";
} else {
if ((!this.config.folderLinks || !node.url) && node._hc && node.pid != this.root.id) {
str += "<a href=\"javascript: " + this.obj + ".o(" + nodeId + ");\" class=\"node\">";
}
}
str += node.name;
if (node.url || ((!this.config.folderLinks || !node.url) && node._hc)) {
str += "</a>";
}
str += "</div>";
if (node._hc) {
str += "<div id=\"d" + this.obj + nodeId + "\" class=\"clip\" style=\"display:" + ((this.root.id == node.pid || node._io) ? "block" : "none") + ";\">";
str += this.addNode(node);
str += "</div>";
}
this.aIndent.pop();
return str;
};
// Adds the empty and line icons
dTree.prototype.indent = function (node, nodeId) {
var str = "";
if (this.root.id != node.pid) {
for (var n = 0; n < this.aIndent.length; n++) {
str += "<img src=\"" + ((this.aIndent[n] == 1 && this.config.useLines) ? this.icon.line : this.icon.empty) + "\" alt=\"\" />";
}
(node._ls) ? this.aIndent.push(0) : this.aIndent.push(1);
if (node._hc) {
str += "<a href=\"javascript: " + this.obj + ".o(" + nodeId + ");\"><img id=\"j" + this.obj + nodeId + "\" src=\"";
if (!this.config.useLines) {
str += (node._io) ? this.icon.nlMinus : this.icon.nlPlus;
} else {
str += ((node._io) ? ((node._ls && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._ls && this.config.useLines) ? this.icon.plusBottom : this.icon.plus));
}
str += "\" alt=\"\" /></a>";
} else {
str += "<img src=\"" + ((this.config.useLines) ? ((node._ls) ? this.icon.joinBottom : this.icon.join) : this.icon.empty) + "\" alt=\"\" />";
}
}
return str;
};
// Checks if a node has any children and if it is the last sibling
dTree.prototype.setCS = function (node) {
var lastId;
for (var n = 0; n < this.aNodes.length; n++) {
if (this.aNodes[n].pid == node.id) {
node._hc = true;
}
if (this.aNodes[n].pid == node.pid) {
lastId = this.aNodes[n].id;
}
}
if (lastId == node.id) {
node._ls = true;
}
};
// Returns the selected node
dTree.prototype.getSelected = function () {
var sn = this.getCookie("cs" + this.obj);
return (sn) ? sn : null;
};
// Highlights the selected node
dTree.prototype.s = function (id) {
if (!this.config.useSelection) {
return;
}
var cn = this.aNodes[id];
if (cn._hc && !this.config.folderLinks) {
return;
}
if (this.selectedNode != id) {
if (this.selectedNode || this.selectedNode == 0) {
eOld = document.getElementById("s" + this.obj + this.selectedNode);
eOld.className = "node";
}
eNew = document.getElementById("s" + this.obj + id);
eNew.className = "nodeSel";
this.selectedNode = id;
if (this.config.useCookies) {
this.setCookie("cs" + this.obj, cn.id);
}
}
};
// Toggle Open or close
dTree.prototype.o = function (id) {
var cn = this.aNodes[id];
this.nodeStatus(!cn._io, id, cn._ls);
cn._io = !cn._io;
if (this.config.closeSameLevel) {
this.closeLevel(cn);
}
if (this.config.useCookies) {
this.updateCookie();
}
};
// Open or close all nodes
dTree.prototype.oAll = function (status) {
for (var n = 0; n < this.aNodes.length; n++) {
if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.id) {
this.nodeStatus(status, n, this.aNodes[n]._ls);
this.aNodes[n]._io = status;
}
}
if (this.config.useCookies) {
this.updateCookie();
}
};
// Opens the tree to a specific node
dTree.prototype.openTo = function (nId, bSelect, bFirst) {
if (!bFirst) {
for (var n = 0; n < this.aNodes.length; n++) {
if (this.aNodes[n].id == nId) {
nId = n;
break;
}
}
}
var cn = this.aNodes[nId];
if (cn.pid == this.root.id || !cn._p) {
return;
}
cn._io = true;
cn._is = bSelect;
if (this.completed && cn._hc) {
this.nodeStatus(true, cn._ai, cn._ls);
}
if (this.completed && bSelect) {
this.s(cn._ai);
} else {
if (bSelect) {
this._sn = cn._ai;
}
}
this.openTo(cn._p._ai, false, true);
};
// Closes all nodes on the same level as certain node
dTree.prototype.closeLevel = function (node) {
for (var n = 0; n < this.aNodes.length; n++) {
if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hc) {
this.nodeStatus(false, n, this.aNodes[n]._ls);
this.aNodes[n]._io = false;
this.closeAllChildren(this.aNodes[n]);
}
}
};
// Closes all children of a node
dTree.prototype.closeAllChildren = function (node) {
for (var n = 0; n < this.aNodes.length; n++) {
if (this.aNodes[n].pid == node.id && this.aNodes[n]._hc) {
if (this.aNodes[n]._io) {
this.nodeStatus(false, n, this.aNodes[n]._ls);
}
this.aNodes[n]._io = false;
this.closeAllChildren(this.aNodes[n]);
}
}
};
// Change the status of a node(open or closed)
dTree.prototype.nodeStatus = function (status, id, bottom) {
eDiv = document.getElementById("d" + this.obj + id);
eJoin = document.getElementById("j" + this.obj + id);
if (this.config.useIcons) {
eIcon = document.getElementById("i" + this.obj + id);
eIcon.src = (status) ? this.aNodes[id].iconOpen : this.aNodes[id].icon;
}
eJoin.src = (this.config.useLines) ? ((status) ? ((bottom) ? this.icon.minusBottom : this.icon.minus) : ((bottom) ? this.icon.plusBottom : this.icon.plus)) : ((status) ? this.icon.nlMinus : this.icon.nlPlus);
eDiv.style.display = (status) ? "block" : "none";
};
// [Cookie] Clears a cookie
dTree.prototype.clearCookie = function () {
var now = new Date();
var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
this.setCookie("co" + this.obj, "cookieValue", yesterday);
this.setCookie("cs" + this.obj, "cookieValue", yesterday);
};
// [Cookie] Sets value in a cookie
dTree.prototype.setCookie = function (cookieName, cookieValue, expires, path, domain, secure) {
document.cookie = escape(cookieName) + "=" + escape(cookieValue) + (expires ? "; expires=" + expires.toGMTString() : "") + (path ? "; path=" + path : "") + (domain ? "; domain=" + domain : "") + (secure ? "; secure" : "");
};
// [Cookie] Gets a value from a cookie
dTree.prototype.getCookie = function (cookieName) {
var cookieValue = "";
var posName = document.cookie.indexOf(escape(cookieName) + "=");
if (posName != -1) {
var posValue = posName + (escape(cookieName) + "=").length;
var endPos = document.cookie.indexOf(";", posValue);
if (endPos != -1) {
cookieValue = unescape(document.cookie.substring(posValue, endPos));
} else {
cookieValue = unescape(document.cookie.substring(posValue));
}
}
return (cookieValue);
};
// [Cookie] Returns ids of open nodes as a string
dTree.prototype.updateCookie = function () {
var str = "";
for (var n = 0; n < this.aNodes.length; n++) {
if (this.aNodes[n]._io && this.aNodes[n].pid != this.root.id) {
if (str) {
str += ".";
}
str += this.aNodes[n].id;
}
}
this.setCookie("co" + this.obj, str);
};
// [Cookie] Checks if a node id is in a cookie
dTree.prototype.isOpen = function (id) {
var aOpen = this.getCookie("co" + this.obj).split(".");
for (var n = 0; n < aOpen.length; n++) {
if (aOpen[n] == id) {
return true;
}
}
return false;
};
// If Push and pop is not implemented by the browser
if (!Array.prototype.push) {
Array.prototype.push = function array_push() {
for (var i = 0; i < arguments.length; i++) {
this[this.length] = arguments[i];
}
return this.length;
};
}
if (!Array.prototype.pop) {
Array.prototype.pop = function array_pop() {
lastElement = this[this.length - 1];
this.length = Math.max(this.length - 1, 0);
return lastElement;
};
}
| JavaScript |
/*!
* MultiUpload for xheditor
* @requires xhEditor
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 0.9.2 (build 100505)
*/
var swfu,selQueue=[],selectID,arrMsg=[],allSize=0,uploadSize=0;
function removeFile()
{
var file;
if(!selectID)return;
for(var i in selQueue)
{
file=selQueue[i];
if(file.id==selectID)
{
selQueue.splice(i,1);
allSize-=file.size;
swfu.cancelUpload(file.id);
$('#'+file.id).remove();
selectID=null;
break;
}
}
$('#btnClear').hide();
if(selQueue.length==0)$('#controlBtns').hide();
}
function startUploadFiles()
{
if(swfu.getStats().files_queued>0)
{
$('#controlBtns').hide();
swfu.startUpload();
}
else alert('上传前请先添加文件');
}
function setFileState(fileid,txt)
{
$('#'+fileid+'_state').text(txt);
}
function fileQueued(file)//队列添加成功
{
for(var i in selQueue)if(selQueue[i].name==file.name){swfu.cancelUpload(file.id);return false;}//防止同名文件重复添加
if(selQueue.length==0)$('#controlBtns').show();
selQueue.push(file);
allSize+=file.size;
$('#listBody').append('<tr id="'+file.id+'"><td>'+file.name+'</td><td>'+formatBytes(file.size)+'</td><td id="'+file.id+'_state">就绪</td></tr>');
$('#'+file.id).hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');})
.click(function(){selectID=file.id;$('#listBody tr').removeClass('select');$(this).removeClass('hover').addClass('select');$('#btnClear').show();})
}
function fileQueueError(file, errorCode, message)//队列添加失败
{
var errorName='';
switch (errorCode)
{
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
errorName = "只能同时上传 "+this.settings.file_upload_limit+" 个文件";
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
errorName = "选择的文件超过了当前大小限制:"+this.settings.file_size_limit;
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
errorName = "零大小文件";
break;
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
errorName = "文件扩展名必需为:"+this.settings.file_types_description+" ("+this.settings.file_types+")";
break;
default:
errorName = "未知错误";
break;
}
alert(errorName);
}
function uploadStart(file)//单文件上传开始
{
setFileState(file.id,'上传中…');
}
function uploadProgress(file, bytesLoaded, bytesTotal)//单文件上传进度
{
var percent=Math.ceil((uploadSize+bytesLoaded)/allSize*100);
$('#progressBar span').text(percent+'% ('+formatBytes(uploadSize+bytesLoaded)+' / '+formatBytes(allSize)+')');
$('#progressBar div').css('width',percent+'%');
}
function uploadSuccess(file, serverData)//单文件上传成功
{
var data=Object;
try{eval("data=" + serverData);}catch(ex){};
if(data.err!=undefined&&data.msg!=undefined)
{
if(!data.err)
{
uploadSize+=file.size;
arrMsg.push(data.msg);
setFileState(file.id,'上传成功');
}
else
{
setFileState(file.id,'上传失败');
alert(data.err);
}
}
else setFileState(file.id,'上传失败!');
}
function uploadError(file, errorCode, message)//单文件上传错误
{
setFileState(file.id,'上传失败!');
}
function uploadComplete(file)//文件上传周期结束
{
if(swfu.getStats().files_queued>0)swfu.startUpload();
else uploadAllComplete();
}
function uploadAllComplete()//全部文件上传成功
{
callback(arrMsg);
}
function formatBytes(bytes) {
var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
} | JavaScript |
/*!
* xhEditor - WYSIWYG XHTML Editor
* @requires jQuery v1.4.2
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 1.1.1 (build 101002)
*/
(function($){
if($.xheditor)return false;//防止JS重复加载
$.fn.xheditor=function(options)
{
var arrSuccess=[];
this.each(function(){
if(!$.nodeName(this,'TEXTAREA'))return;
if(options===false)//卸载
{
if(this.xheditor)
{
this.xheditor.remove();
this.xheditor=null;
}
}
else//初始化
{
if(!this.xheditor)
{
var tOptions=/({.*})/.exec($(this).attr('class'));
if(tOptions)
{
try{tOptions=eval('('+tOptions[1]+')');}catch(ex){};
options=$.extend({},tOptions,options );
}
var editor=new $.xheditor(this,options);
if(editor.init())
{
this.xheditor=editor;
arrSuccess.push(editor);
}
else editor=null;
}
else arrSuccess.push(this.xheditor);
}
});
if(arrSuccess.length==0)arrSuccess=false;
if(arrSuccess.length==1)arrSuccess=arrSuccess[0];
return arrSuccess;
}
var xCount=0,browerVer=$.browser.version,isIE=$.browser.msie,isMozilla=$.browser.mozilla,isSafari=$.browser.safari,isOpera=$.browser.opera,bShowPanel=false,bClickCancel=true,bShowModal=false,bCheckEscInit=false;
var _jPanel,_jShadow,_jCntLine,_jPanelButton;
var jModal,jModalShadow,layerShadow,jOverlay,jHideSelect,onModalRemove;
var editorRoot;
$('script[src*=xheditor]').each(function(){
var s=this.src;
if(s.match(/xheditor[^\/]*\.js/i)){editorRoot=s.replace(/[\?#].*$/, '').replace(/(^|[\/\\])[^\/]*$/, '$1');return false;}
});
var specialKeys={ 27: 'esc', 9: 'tab', 32:'space', 13: 'enter', 8:'backspace', 145: 'scroll',
20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',
35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down',
112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12' };
var itemColors=['#FFFFFF','#CCCCCC','#C0C0C0','#999999','#666666','#333333','#000000','#FFCCCC','#FF6666','#FF0000','#CC0000','#990000','#660000','#330000','#FFCC99','#FF9966','#FF9900','#FF6600','#CC6600','#993300','#663300','#FFFF99','#FFFF66','#FFCC66','#FFCC33','#CC9933','#996633','#663333','#FFFFCC','#FFFF33','#FFFF00','#FFCC00','#999900','#666600','#333300','#99FF99','#66FF99','#33FF33','#33CC00','#009900','#006600','#003300','#99FFFF','#33FFFF','#66CCCC','#00CCCC','#339999','#336666','#003333','#CCFFFF','#66FFFF','#33CCFF','#3366FF','#3333FF','#000099','#000066','#CCCCFF','#9999FF','#6666CC','#6633FF','#6600CC','#333399','#330099','#FFCCFF','#FF99FF','#CC66CC','#CC33CC','#993399','#663366','#330033'];
var arrBlocktag=[{n:'p',t:'普通段落'},{n:'h1',t:'标题1'},{n:'h2',t:'标题2'},{n:'h3',t:'标题3'},{n:'h4',t:'标题4'},{n:'h5',t:'标题5'},{n:'h6',t:'标题6'},{n:'pre',t:'已编排格式'},{n:'address',t:'地址'}];
var arrFontname=[{n:'宋体',c:'SimSun'},{n:'仿宋体',c:'FangSong_GB2312'},{n:'黑体',c:'SimHei'},{n:'楷体',c:'KaiTi_GB2312'},{n:'微软雅黑',c:'Microsoft YaHei'},{n:'Arial'},{n:'Arial Narrow'},{n:'Arial Black'},{n:'Comic Sans MS'},{n:'Courier New'},{n:'System'},{n:'Times New Roman'},{n:'Tahoma'},{n:'Verdana'}];
var arrFontsize=[{n:'xx-small',wkn:'x-small',s:'8pt',t:'极小'},{n:'x-small',wkn:'small',s:'10pt',t:'特小'},{n:'small',wkn:'medium',s:'12pt',t:'小'},{n:'medium',wkn:'large',s:'14pt',t:'中'},{n:'large',wkn:'x-large',s:'18pt',t:'大'},{n:'x-large',wkn:'xx-large',s:'24pt',t:'特大'},{n:'xx-large',wkn:'-webkit-xxx-large',s:'36pt',t:'极大'}];
var menuAlign=[{s:'左对齐',v:'justifyleft'},{s:'居中',v:'justifycenter'},{s:'右对齐',v:'justifyright'},{s:'两端对齐',v:'justifyfull'}],menuList=[{s:'数字列表',v:'insertOrderedList'},{s:'符号列表',v:'insertUnorderedList'}];
var htmlPastetext='<div>使用键盘快捷键(Ctrl+V)把内容粘贴到方框里,按 确定</div><div><textarea id="xhePastetextValue" wrap="soft" spellcheck="false" style="width:300px;height:100px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlLink='<div>链接地址: <input type="text" id="xheLinkUrl" value="http://" class="xheText" /></div><div>打开方式: <select id="xheLinkTarget"><option selected="selected" value="">默认</option><option value="_blank">新窗口</option><option value="_self">当前窗口</option><option value="_parent">父窗口</option></select></div><div style="display:none">链接文字: <input type="text" id="xheLinkText" value="" class="xheText" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlImg='<div>图片文件: <input type="text" id="xheImgUrl" value="http://" class="xheText" /></div><div>替换文本: <input type="text" id="xheImgAlt" /></div><div>对齐方式: <select id="xheImgAlign"><option selected="selected" value="">默认</option><option value="left">左对齐</option><option value="right">右对齐</option><option value="top">顶端</option><option value="middle">居中</option><option value="baseline">基线</option><option value="bottom">底边</option></select></div><div>宽度高度: <input type="text" id="xheImgWidth" style="width:40px;" /> x <input type="text" id="xheImgHeight" style="width:40px;" /></div><div>边框大小: <input type="text" id="xheImgBorder" style="width:40px;" /></div><div>水平间距: <input type="text" id="xheImgHspace" style="width:40px;" /> 垂直间距: <input type="text" id="xheImgVspace" style="width:40px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlFlash='<div>动画文件: <input type="text" id="xheFlashUrl" value="http://" class="xheText" /></div><div>宽度高度: <input type="text" id="xheFlashWidth" style="width:40px;" value="480" /> x <input type="text" id="xheFlashHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlMedia='<div>媒体文件: <input type="text" id="xheMediaUrl" value="http://" class="xheText" /></div><div>宽度高度: <input type="text" id="xheMediaWidth" style="width:40px;" value="480" /> x <input type="text" id="xheMediaHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlTable='<div>行数列数: <input type="text" id="xheTableRows" style="width:40px;" value="3" /> x <input type="text" id="xheTableColumns" style="width:40px;" value="2" /></div><div>标题单元: <select id="xheTableHeaders"><option selected="selected" value="">无</option><option value="row">第一行</option><option value="col">第一列</option><option value="both">第一行和第一列</option></select></div><div>宽度高度: <input type="text" id="xheTableWidth" style="width:40px;" value="200" /> x <input type="text" id="xheTableHeight" style="width:40px;" value="" /></div><div>边框大小: <input type="text" id="xheTableBorder" style="width:40px;" value="1" /></div><div>表格间距: <input type="text" id="xheTableCellSpacing" style="width:40px;" value="1" /> 表格填充: <input type="text" id="xheTableCellPadding" style="width:40px;" value="1" /></div><div>对齐方式: <select id="xheTableAlign"><option selected="selected" value="">默认</option><option value="left">左对齐</option><option value="center">居中</option><option value="right">右对齐</option></select></div><div>表格标题: <input type="text" id="xheTableCaption" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlAbout='<div style="font:12px Arial;width:245px;word-wrap:break-word;word-break:break-all;"><p><span style="font-size:20px;color:#1997DF;">xhEditor</span><br />v1.1.1 (build 101002)</p><p>xhEditor是基于jQuery开发的跨平台轻量XHTML编辑器,基于<a href="http://www.gnu.org/licenses/lgpl.html" target="_blank">LGPL</a>开源协议发布。</p><p>Copyright © <a href="http://xheditor.com/" target="_blank">xhEditor.com</a>. All rights reserved.</p></div>';
var itemEmots={'default':{name:'默认',width:24,height:24,line:7,list:{'smile':'微笑','tongue':'吐舌头','titter':'偷笑','laugh':'大笑','sad':'难过','wronged':'委屈','fastcry':'快哭了','cry':'哭','wail':'大哭','mad':'生气','knock':'敲打','curse':'骂人','crazy':'抓狂','angry':'发火','ohmy':'惊讶','awkward':'尴尬','panic':'惊恐','shy':'害羞','cute':'可怜','envy':'羡慕','proud':'得意','struggle':'奋斗','quiet':'安静','shutup':'闭嘴','doubt':'疑问','despise':'鄙视','sleep':'睡觉','bye':'再见'}}};
var arrTools={Cut:{t:'剪切 (Ctrl+X)'},Copy:{t:'复制 (Ctrl+C)'},Paste:{t:'粘贴 (Ctrl+V)'},Pastetext:{t:'粘贴文本',h:isIE?0:1},Blocktag:{t:'段落标签',h:1},Fontface:{t:'字体',h:1},FontSize:{t:'字体大小',h:1},Bold:{t:'加粗 (Ctrl+B)',s:'Ctrl+B'},Italic:{t:'斜体 (Ctrl+I)',s:'Ctrl+I'},Underline:{t:'下划线 (Ctrl+U)',s:'Ctrl+U'},Strikethrough:{t:'删除线 (Ctrl+S)',s:'Ctrl+S'},FontColor:{t:'字体颜色',h:1},BackColor:{t:'背景颜色',h:1},SelectAll:{t:'全选 (Ctrl+A)'},Removeformat:{t:'删除文字格式'},Align:{t:'对齐',h:1},List:{t:'列表',h:1},Outdent:{t:'减少缩进 (Shift+Tab)',s:'Shift+Tab'},Indent:{t:'增加缩进 (Tab)',s:'Tab'},Link:{t:'超链接 (Ctrl+K)',s:'Ctrl+K',h:1},Unlink:{t:'取消超链接'},Img:{t:'图片',h:1},Flash:{t:'Flash动画',h:1},Media:{t:'多媒体文件',h:1},Emot:{t:'表情',s:'ctrl+e',h:1},Table:{t:'表格',h:1},Source:{t:'源代码'},Preview:{t:'预览'},Print:{t:'打印 (Ctrl+P)',s:'Ctrl+P'},Fullscreen:{t:'全屏编辑 (Esc)',s:'Esc'},About:{t:'关于 xhEditor'}};
var toolsThemes={
mini:'Bold,Italic,Underline,Strikethrough,|,Align,List,|,Link,Img',
simple:'Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,|,Align,List,Outdent,Indent,|,Link,Img,Emot',
full:'Cut,Copy,Paste,Pastetext,|,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,SelectAll,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Img,Flash,Media,Emot,Table,|,Source,Preview,Print,Fullscreen'};
toolsThemes.mfull=toolsThemes.full.replace(/\|(,Align)/i,'/$1');
var arrDbClick={'a':'Link','img':'Img','embed':'Embed'},uploadInputname='filedata';
$.xheditor=function(textarea,options)
{
var defaults={skin:'default',tools:'full',clickCancelDialog:true,linkTag:false,internalScript:false,inlineScript:false,internalStyle:true,inlineStyle:true,showBlocktag:false,forcePtag:true,upLinkExt:"zip,rar,txt",upImgExt:"jpg,jpeg,gif,png",upFlashExt:"swf",upMediaExt:"wmv,avi,wma,mp3,mid",modalWidth:350,modalHeight:220,modalTitle:true,defLinkText:'点击打开链接',layerShadow:3,emotMark:false,upBtnText:'上传',wordDeepClean:true,hoverExecDelay:100,html5Upload:true,upMultiple:99};
var _this=this,_text=textarea,_jText=$(_text),_jForm=_jText.closest('form'),_jTools,_jArea,_win,_jWin,_doc,_jDoc;
var bookmark;
var bInit=false,bSource=false,bFullscreen=false,bCleanPaste=false,outerScroll,bShowBlocktag=false,sLayoutStyle='',ev=null,timer,bDisableHoverExec=false,bQuickHoverExec=false;
var lastPoint=null,lastAngle=null;//鼠标悬停显示
var editorHeight=0;
var settings=_this.settings=$.extend({},defaults,options );
var plugins=settings.plugins,strPlugins=[];
if(plugins)
{
arrTools=$.extend({},arrTools,plugins);
$.each(plugins,function(n){strPlugins.push(n);});
strPlugins=strPlugins.join(',');
}
if(settings.tools.match(/^\s*(m?full|simple|mini)\s*$/i))
{
var toolsTheme=toolsThemes[$.trim(settings.tools)];
settings.tools=(settings.tools.match(/m?full/i)&&plugins)?toolsTheme.replace('Table','Table,'+strPlugins):toolsTheme;//插件接在full的Table后面
}
if(!settings.tools.match(/(^|,)\s*About\s*(,|$)/i))settings.tools+=',About';
settings.tools=settings.tools.split(',');
if(settings.editorRoot)editorRoot=settings.editorRoot;
editorRoot=getLocalUrl(editorRoot,'abs');
//基本控件名
var idCSS='xheCSS_'+settings.skin,idContainer='xhe'+xCount+'_container',idTools='xhe'+xCount+'_Tool',idIframeArea='xhe'+xCount+'_iframearea',idIframe='xhe'+xCount+'_iframe',idFixFFCursor='xhe'+xCount+'_fixffcursor';
var headHTML='',bodyClass='',skinPath=editorRoot+'xheditor_skin/'+settings.skin+'/',arrEmots=itemEmots,urlType=settings.urlType,urlBase=settings.urlBase,emotPath=settings.emotPath,emotPath=emotPath?emotPath:editorRoot+'xheditor_emot/',selEmotGroup='';
arrEmots=$.extend({},arrEmots,settings.emots);
emotPath=getLocalUrl(emotPath,'rel',urlBase?urlBase:null);//返回最短表情路径
bShowBlocktag=settings.showBlocktag;
if(bShowBlocktag)bodyClass+=' showBlocktag';
var arrShortCuts=[];
this.init=function()
{
//加载样式表
if($('#'+idCSS).length==0)$('head').append('<link id="'+idCSS+'" rel="stylesheet" type="text/css" href="'+skinPath+'ui.css" />');
//初始化编辑器
var cw = settings.width || _text.style.width || _jText.outerWidth();
editorHeight = settings.height || _text.style.height || _jText.outerHeight();
if(is(editorHeight,'string'))editorHeight=editorHeight.replace(/[^\d]+/g,'');
if(cw<=0||editorHeight<=0)//禁止对隐藏区域里的textarea初始化编辑器
{
alert('当前textarea处于隐藏状态,请将之显示后再初始化xhEditor,或者直接设置textarea的width和height样式');
return false;
}
if(/^[0-9\.]+$/i.test(''+cw))cw+='px';
//编辑器CSS背景
var editorBackground=settings.background || _text.style.background;
//工具栏内容初始化
var arrToolsHtml=['<span class="xheGStart"/>'],tool,cn,regSeparator=/\||\//i;
$.each(settings.tools,function(i,n)
{
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGEnd"/>');
if(n=='|')arrToolsHtml.push('<span class="xheSeparator"/>');
else if(n=='/')arrToolsHtml.push('<br />');
else
{
tool=arrTools[n];
if(!tool)return;
if(tool.c)cn=tool.c;
else cn='xheIcon xheBtn'+n;
arrToolsHtml.push('<span><a href="javascript:void(0);" title="'+tool.t+'" name="'+n+'" class="xheButton xheEnabled" tabindex="-1"><span class="'+cn+'" unselectable="on" /></a></span>');
if(tool.s)_this.addShortcuts(tool.s,n);
}
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGStart"/>');
});
arrToolsHtml.push('<span class="xheGEnd"/><br />');
_jText.after($('<input type="text" id="'+idFixFFCursor+'" style="position:absolute;display:none;" /><span id="'+idContainer+'" class="xhe_'+settings.skin+'" style="display:none"><table cellspacing="0" cellpadding="0" class="xheLayout" style="width:'+cw+';height:'+editorHeight+'px;"><tbody><tr><td id="'+idTools+'" class="xheTool" unselectable="on" style="height:1px;"></td></tr><tr><td id="'+idIframeArea+'" class="xheIframeArea"><iframe frameborder="0" id="'+idIframe+'" src="javascript:;" style="width:100%;"></iframe></td></tr></tbody></table></span>'));
_jTools=$('#'+idTools);_jArea=$('#'+idIframeArea);
headHTML='<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><link rel="stylesheet" href="'+skinPath+'iframe.css"/>';
var loadCSS=settings.loadCSS;
if(loadCSS)
{
if(is(loadCSS,'array'))for(var i in loadCSS)headHTML+='<link rel="stylesheet" href="'+loadCSS[i]+'"/>';
else
{
if(loadCSS.match(/\s*<style(\s+[^>]*?)?>[\s\S]+?<\/style>\s*/i))headHTML+=loadCSS;
else headHTML+='<link rel="stylesheet" href="'+loadCSS+'"/>';
}
}
var iframeHTML='<html><head>'+headHTML;
if(editorBackground)iframeHTML+='<style>body{background:'+editorBackground+';}</style>';
iframeHTML+='</head><body spellcheck="false" class="editMode'+bodyClass+'"></body></html>';
_this.win=_win=$('#'+idIframe)[0].contentWindow;
_jWin=$(_win);
try{
this.doc=_doc = _win.document;_jDoc=$(_doc);
_doc.open();
_doc.write(iframeHTML);
_doc.close();
if(isIE)_doc.body.contentEditable='true';
else _doc.designMode = 'On';
}catch(e){}
setTimeout(setOpts,300);
_this.setSource();
_win.setInterval=null;//针对jquery 1.3无法操作iframe window问题的hack
//添加工具栏
_jTools.append(arrToolsHtml.join('')).bind('mousedown contextmenu',returnFalse).click(function(event)
{
var jButton=$(event.target).closest('a');
if(jButton.is('.xheEnabled'))
{
ev=event;
_this.exec(jButton.attr('name'));
}
return false;
});
_jTools.find('.xheButton').hover(function(event){//鼠标悬停执行
var jButton=$(this),delay=settings.hoverExecDelay;
var tAngle=lastAngle;lastAngle=null;
if(delay==-1||bDisableHoverExec||!jButton.is('.xheEnabled'))return false;
if(tAngle&&tAngle>10)//检测误操作
{
bDisableHoverExec=true;
setTimeout(function(){bDisableHoverExec=false;},100);
return false;
}
var cmd=jButton.attr('name'),bHover=arrTools[cmd].h==1;
if(!bHover)
{
_this.hidePanel();//移到非悬停按钮上隐藏面板
return false;
}
if(bQuickHoverExec)delay=0;
if(delay>=0)timer=setTimeout(function(){
ev=event;
lastPoint={x:ev.clientX,y:ev.clientY};
_this.exec(cmd);
},delay);
},function(event){lastPoint=null;if(timer)clearTimeout(timer);}).mousemove(function(event){
if(lastPoint)
{
var diff={x:event.clientX-lastPoint.x,y:event.clientY-lastPoint.y};
if(Math.abs(diff.x)>1||Math.abs(diff.y)>1)
{
if(diff.x>0&&diff.y>0)
{
var tAngle=Math.round(Math.atan(diff.y/diff.x)/0.017453293);
if(lastAngle)lastAngle=(lastAngle+tAngle)/2
else lastAngle=tAngle;
}
else lastAngle=null;
lastPoint={x:event.clientX,y:event.clientY};
}
}
});
//初始化面板
_jPanel=$('#xhePanel');
_jShadow=$('#xheShadow');
_jCntLine=$('#xheCntLine');
if(_jPanel.length==0)
{
_jPanel=$('<div id="xhePanel"></div>').mousedown(function(ev){ev.stopPropagation()});
_jShadow=$('<div id="xheShadow"></div>');
_jCntLine=$('<div id="xheCntLine"></div>');
setTimeout(function(){
$(document.body).append(_jPanel).append(_jShadow).append(_jCntLine);
},10);
}
//切换显示区域
$('#'+idContainer).show();
_jText.hide();
_jArea.css('height',editorHeight-_jTools.outerHeight());
//绑定内核事件
_jText.focus(_this.focus);
_jForm.submit(saveResult).bind('reset', loadReset);
$(window).bind('unload beforeunload',saveResult).bind('resize',fixFullHeight);
$(document).mousedown(clickCancelPanel);
if(!bCheckEscInit){$(document).keydown(checkEsc);bCheckEscInit=true;}
_jWin.focus(function(){if(settings.focus)settings.focus();}).blur(function(){if(settings.blur)settings.blur();});
if(isSafari)_jWin.click(fixAppleSel);
_jDoc.mousedown(clickCancelPanel).keydown(checkShortcuts).keypress(forcePtag).dblclick(checkDblClick).bind('mousedown click',function(ev){_jText.trigger(ev.type);});
if(isIE)
{
//IE控件上Backspace会导致页面后退
_jDoc.keydown(function(ev){var rng=_this.getRng();if(ev.which==8&&rng.item){$(rng.item(0)).remove();return false;}});
//修正IE拖动img大小不更新width和height属性值的问题
function fixResize(ev)
{
var jImg=$(ev.target),v;
if(v=jImg.css('width'))jImg.css('width','').attr('width',v.replace(/[^0-9%]+/g, ''));
if(v=jImg.css('height'))jImg.css('height','').attr('height',v.replace(/[^0-9%]+/g, ''));
}
_jDoc.bind('controlselect',function(ev){
ev=ev.target;if(!$.nodeName(ev,'IMG'))return;
$(ev).unbind('resizeend',fixResize).bind('resizeend',fixResize);
});
}
var jBody=$(_doc.documentElement);
jBody.bind('paste',cleanPaste);
if(settings.disableContextmenu)jBody.bind('contextmenu',returnFalse);
//HTML5编辑区域直接拖放上传
if(settings.html5Upload)jBody.bind('dragenter dragover',function(ev){var types;if((types=ev.originalEvent.dataTransfer.types)&&$.inArray('Files', types)!=-1)return false;}).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0){
var i,cmd,arrCmd=['Link','Img','Flash','Media'],arrExt=[],strExt;
for(i in arrCmd){
cmd=arrCmd[i];
if(settings['up'+cmd+'Url']&&settings['up'+cmd+'Url'].match(/^[^!].*/i))arrExt.push(cmd+':,'+settings['up'+cmd+'Ext']);//允许上传
}
if(arrExt.length==0)return false;//禁止上传
else strExt=arrExt.join(',');
function getCmd(fileList){
var match,fileExt,cmd;
for(i=0;i<fileList.length;i++){
fileExt=fileList[i].fileName.replace(/.+\./,'');
if(match=strExt.match(new RegExp('(\\w+):[^:]*,'+fileExt+'(?:,|$)','i'))){
if(!cmd)cmd=match[1];
else if(cmd!=match[1])return 2;
}
else return 1;
}
return cmd;
}
cmd=getCmd(fileList);
if(cmd==1)alert('上传文件的扩展名必需为:'+strExt.replace(/\w+:,/g,''));
else if(cmd==2)alert('每次只能拖放上传同一类型文件');
else if(cmd){
_this.startUpload(fileList,settings['up'+cmd+'Url'],'*',function(arrMsg){
var arrUrl=[],msg,onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用户上传回调
for(i in arrMsg){
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!')url=url.substr(1);
arrUrl.push(url);
}
_this.exec(cmd);
$('#xhe'+cmd+'Url').val(arrUrl.join(' '));
$('#xheSave').click();
});
}
return false;
}
});
//添加用户快捷键
var shortcuts=settings.shortcuts;
if(shortcuts)$.each(shortcuts,function(key,func){_this.addShortcuts(key,func);});
xCount++;
bInit=true;
if(settings.fullscreen)_this.toggleFullscreen();
else if(settings.sourceMode)setTimeout(_this.toggleSource,20);
return true;
}
this.remove=function()
{
_this.hidePanel();
saveResult();//卸载前同步最新内容到textarea
//取消绑定事件
_jText.unbind('focus',_this.focus);
_jForm.unbind('submit',saveResult).unbind('reset', loadReset);
$(window).unbind('unload beforeunload',saveResult).unbind('resize',fixFullHeight);
$(document).unbind('mousedown',clickCancelPanel);
$('#'+idContainer+','+'#'+idFixFFCursor).remove();
_jText.show();
bInit=false;
}
this.saveBookmark=function(){
if(!bSource){
var rng=_this.getRng();
rng=rng.cloneRange?rng.cloneRange():rng;
bookmark={'top':_jWin.scrollTop(),'rng':rng};
}
}
this.loadBookmark=function()
{
if(bSource||!bookmark)return;
_this.focus();
var rng=bookmark.rng;
if(isIE)rng.select();
else
{
var sel=_this.getSel();
sel.removeAllRanges();
sel.addRange(rng);
}
_jWin.scrollTop(bookmark.top);
bookmark=null;
}
this.focus=function()
{
if(!bSource)_jWin.focus();
else $('#sourceCode',_doc).focus();
return false;
}
this.setCursorFirst=function(firstBlock)
{
_this.focus();_win.scrollTo(0,0);
var rng=_this.getRng(),_body=_doc.body,firstNode=_body,firstTag;
if(firstBlock&&firstNode.firstChild&&(firstTag=firstNode.firstChild.tagName)&&firstTag.match(/^p|div|h[1-6]$/i))firstNode=_body.firstChild;
isIE?rng.moveToElementText(firstNode):rng.setStart(firstNode,0);
rng.collapse(true);
if(isIE)rng.select();
else{var sel=_this.getSel();sel.removeAllRanges();sel.addRange(rng);}
}
this.getSel=function()
{
return _win.getSelection ? _win.getSelection() : _doc.selection;
}
this.getRng=function()
{
var sel=_this.getSel(),rng;
try{
rng = sel.rangeCount > 0 ? sel.getRangeAt(0) : (sel.createRange ? sel.createRange() : (_doc.createRange?_doc.createRange():_doc.body.createTextRange()));
}catch (ex){}
return rng;
}
this.getParent=function(tag)
{
var rng=_this.getRng(),p;
if(!isIE)
{
p = rng.commonAncestorContainer;
if(!rng.collapsed)if(rng.startContainer == rng.endContainer&&rng.startOffset - rng.endOffset < 2&&rng.startContainer.hasChildNodes())p = rng.startContainer.childNodes[rng.startOffset];
}
else p=rng.item?rng.item(0):rng.parentElement();
tag=tag?tag:'*';p=$(p);
if(!p.is(tag))p=$(p).closest(tag);
return p;
}
this.getSelect=function(format)
{
var sel=_this.getSel(),rng=_this.getRng(),isCollapsed=true;
if (!rng || rng.item)isCollapsed=false
else isCollapsed=!sel || rng.boundingWidth == 0 || rng.collapsed;
if(format=='text')return isCollapsed ? '' : (rng.text || (sel.toString ? sel.toString() : ''));
var sHtml;
if(rng.cloneContents)
{
var tmp=$('<div></div>'),c;
c = rng.cloneContents();
if(c)tmp.append(c);
sHtml=tmp.html();
}
else if(is(rng.item))sHtml=rng.item(0).outerHTML;
else if(is(rng.htmlText))sHtml=rng.htmlText;
else sHtml=rng.toString();
if(isCollapsed)sHtml='';
sHtml=_this.processHTML(sHtml,'read');
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
return sHtml;
}
this.pasteHTML=function(sHtml,bStart)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
var sel=_this.getSel(),rng=_this.getRng();
if(bStart!=undefined)//非覆盖式插入
{
if(rng.item)
{
var n=rng.item(0);
rng=_doc.body.createTextRange();
rng.moveToElementText(n);
rng.select();
}
rng.collapse(bStart);
}
sHtml+='<'+(isIE?'img':'span')+' id="_xhe_temp" style="display:none" />';
if(rng.insertNode)
{
rng.deleteContents();
rng.insertNode(rng.createContextualFragment(sHtml));
}
else
{
if(sel.type.toLowerCase()=='control'){sel.clear();rng=_this.getRng();};
rng.pasteHTML(sHtml);
}
var jTemp=$('#_xhe_temp',_doc),temp=jTemp[0];
if(isIE)
{
rng.moveToElementText(temp);
rng.select();
}
else
{
rng.selectNode(temp);
sel.removeAllRanges();
sel.addRange(rng);
}
jTemp.remove();
}
this.pasteText=function(text,bStart)
{
if(!text)text='';
text=_this.domEncode(text);
text = text.replace(/\r?\n/g, '<br />');
_this.pasteHTML(text,bStart);
}
this.appendHTML=function(sHtml)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
$(_doc.body).append(sHtml);
}
this.domEncode=function(str)
{
return str.replace(/[<>]/g,function(c){return {'<':'<','>':'>'}[c];});
}
this.setSource=function(sHtml)
{
bookmark=null;
if(typeof sHtml!='string'&&sHtml!='')sHtml=_text.value;
if(bSource)$('#sourceCode',_doc).val(sHtml);
else
{
if(settings.beforeSetSource)sHtml=settings.beforeSetSource(sHtml);
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
sHtml=_this.cleanWord(sHtml);
sHtml=_this.processHTML(sHtml,'write');
if(isIE){//修正IE会删除可视内容前的script,style,<!--
_doc.body.innerHTML='<img id="_xhe_temp" style="display:none" />'+sHtml;
$('#_xhe_temp',_doc).remove();
}
else _doc.body.innerHTML=sHtml;
}
}
this.processHTML=function(sHtml,mode)
{
var appleClass=' class="Apple-style-span"';
if(mode=='write')
{//write
//恢复emot
function restoreEmot(all,attr,q,emot)
{
emot=emot.split(',');
if(!emot[1]){emot[1]=emot[0];emot[0]=''}
if(emot[0]=='default')emot[0]='';
return all.replace(/\s+src\s*=\s*(["']?).*?\1(\s|$|\/|>)/i,'$2').replace(attr,' src="'+emotPath+(emot[0]?emot[0]:'default')+'/'+emot[1]+'.gif"'+(settings.emotMark?' emot="'+(emot[0]?emot[0]+',':'')+emot[1]+'"'+(all.match(/\s+alt\s*=\s*(["']?)\s*(.*?)\s*\1[\s\/>]/i)?'':' alt="'+emot[1]+'"'):''));
}
sHtml = sHtml.replace(/<img(?:\s+[^>]*?)?(\s+emot\s*=\s*(["']?)\s*(.*?)\s*\2)(?:\s+[^>]*?)?\/?>/ig,restoreEmot);
//保存属性值:src,href
function saveValue(all,tag,attr,n,q,v){return all.replace(attr,(urlBase?(' '+n+'="'+getLocalUrl(v,'abs',urlBase)+'"'):attr)+' _xhe_'+n+'="'+v+'"');}
sHtml = sHtml.replace(/<(\w+(?:\:\w+)?)(?:\s+[^>]*?)?(\s+(src|href)\s*=\s*(["']?)\s*(.*?)\s*\4)(?:\s+[^>]*?)?\/?>/ig,saveValue);
sHtml = sHtml.replace(/<(\/?)del(\s+[^>]*?)?>/ig,'<$1strike$2>');//编辑状态统一转为strike
if(isMozilla)
{
sHtml = sHtml.replace(/<(\/?)strong(\s+[^>]*?)?>/ig,'<$1b$2>');
sHtml = sHtml.replace(/<(\/?)em(\s+[^>]*?)?>/ig,'<$1i$2>');
}
else if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.n){s=t.wkn;break;}
}
return pre+'font-size:'+s+aft;
});
sHtml = sHtml.replace(/<strong(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-weight: bold;"$1>');
sHtml = sHtml.replace(/<em(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-style: italic;"$1>');
sHtml = sHtml.replace(/<u(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: underline;"$1>');
sHtml = sHtml.replace(/<strike(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: line-through;"$1>');
sHtml = sHtml.replace(/<\/(strong|em|u|strike)>/ig,'</span>');
sHtml = sHtml.replace(/<span((?:\s+[^>]*?)?\s+style="([^"]*;)*\s*(font-family|font-size|color|background-color)\s*:\s*[^;"]+\s*;?"[^>]*)>/ig,'<span'+appleClass+'$1>');
}
else if(isIE)
{
sHtml = sHtml.replace(/'/ig, ''');
sHtml = sHtml.replace(/\s+(disabled|checked|readonly|selected)\s*=\s*[\"\']?(false|0)[\"\']?/ig, '');
}
sHtml = sHtml.replace(/<a(\s+[^>]*?)?\/>/,'<a$1></a>');
if(!isSafari)
{
//style转font
function style2font(all,tag,style,content)
{
var attrs='',f,s1,s2,c;
f=style.match(/font-family\s*:\s*([^;"]+)/i);
if(f)attrs+=' face="'+f[1]+'"';
s1=style.match(/font-size\s*:\s*([^;"]+)/i);
if(s1)
{
s1=s1[1].toLowerCase();
for(var j=0;j<arrFontsize.length;j++)if(s1==arrFontsize[j].n||s1==arrFontsize[j].s){s2=j+1;break;}
if(s2)
{
attrs+=' size="'+s2+'"';
style=style.replace(/(^|;)(\s*font-size\s*:\s*[^;"]+;?)+/ig,'$1');
}
}
c=style.match(/(?:^|[\s;])color\s*:\s*([^;"]+)/i);
if(c)
{
var rgb;
if(rgb=c[1].match(/\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)){c[1]='#';for(var i=1;i<=3;i++)c[1]+=(rgb[i]-0).toString(16);}
c[1]=c[1].replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,'#$1$1$2$2$3$3');
attrs+=' color="'+c[1]+'"';
}
style=style.replace(/(^|;)(\s*(font-family|color)\s*:\s*[^;"]+;?)+/ig,'$1');
if(attrs!='')
{
if(style)attrs+=' style="'+style+'"';
return '<font'+attrs+'>'+content+"</font>";
}
else return all;
}
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,style2font);//最里层
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,style2font);//第2层
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,style2font);//第3层
}
}
else
{//read
//恢复属性值src,href
function restoreValue(all,n,q,v)
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
return all.replace(new RegExp('\\s+'+n+'\\s*=\\s*(["\']?).*?\\1(\\s|/?>)','ig'),' '+n+'="'+v.replace(/\$/g,'$$$$')+'"$2');
}
sHtml = sHtml.replace(/<(?:\w+(?:\:\w+)?)(?:\s+[^>]*?)?\s+_xhe_(src|href)\s*=\s*(["']?)\s*(.*?)\s*\2(?:\s+[^>]*?)?\/?>/ig,restoreValue);
if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.wkn){s=t.n;break;}
}
return pre+'font-size:'+s+aft;
});
var arrAppleSpan=[{r:/font-weight:\sbold/ig,t:'strong'},{r:/font-style:\sitalic/ig,t:'em'},{r:/text-decoration:\sunderline/ig,t:'u'},{r:/text-decoration:\sline-through/ig,t:'strike'}];
function replaceAppleSpan(all,tag,attr1,attr2,content)
{
var attr=attr1+attr2,newTag='';
if(!attr)return content;
for(var i=0;i<arrAppleSpan.length;i++)
{
if(attr.match(arrAppleSpan[i].r))
{
newTag=arrAppleSpan[i].t;
break;
}
}
if(newTag)return '<'+newTag+'>'+content+'</'+newTag+'>';
else return all;
}
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,replaceAppleSpan);//最里层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第2层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第3层
}
if(!isIE){//字符间的文本换行强制转br
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/([^<>\r\n]?)((?:\r?\n)+)([^<>\r\n]?)/ig,function(all,left,br,right){if(left||right)return left+br.replace(/\r?\n/g,'<br />')+right;else return all;});
});
}
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+(?:_xhe_|_moz_|_webkit_)[^=]+?\s*=\s*(["']?).*?\2(\s|\/?>)/ig,'$1$3');
sHtml = sHtml.replace(/(<\w+[^>]*?)\s+class\s*=\s*(["']?)\s*(?:apple|webkit)\-.+?\s*\2(\s|\/?>)/ig, "$1$3");
sHtml = sHtml.replace(/<img(\s+[^>]+?)\/?>/ig,function(all,attr){if(!attr.match(/\s+alt\s*(["']?).*?\1(\s|$)/i))attr+=' alt=""';return '<img'+attr+' />';});//img强制加alt
sHtml = sHtml.replace(/\s+jquery\d+="\d+"/ig,'');
}
return sHtml;
}
this.getSource=function(bFormat)
{
var sHtml,beforeGetSource=settings.beforeGetSource;
if(bSource)
{
sHtml=$('#sourceCode',_doc).val();
if(!beforeGetSource){
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/(\t*\r?\n\t*)+/g,'')//标准HTML模式清理缩进和换行
});
}
}
else
{
sHtml=_this.processHTML(_doc.body.innerHTML,'read');
sHtml=sHtml.replace(/^\s*(?:<(p|div)(?:\s+[^>]*?)?>)?\s*(<br(?:\s+[^>]*?)?>)*\s*(?:<\/\1>)?\s*$/i, '');//修正Firefox在空内容情况下多出来的代码
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml,bFormat);
sHtml=_this.cleanWord(sHtml);
if(beforeGetSource)sHtml=beforeGetSource(sHtml);
}
_text.value=sHtml;
return sHtml;
}
this.cleanWord=function(sHtml)
{
if(sHtml.match(/mso(-|normal)|WordDocument/i))
{
var deepClean=settings.wordDeepClean;
//格式化
sHtml = sHtml.replace(/(<link(?:\s+[^>]*?)?)\s+href\s*=\s*(["']?)\s*file:\/\/.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, '');
//区块标签清理
sHtml = sHtml.replace(/<!--[\s\S]*?-->|<!(--)?\[[\s\S]+?\](--)?>|<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
sHtml = sHtml.replace(/<\/?\w+:[^>]*>/ig, '');
if(deepClean)sHtml = sHtml.replace(/<\/?(span|a|img)(\s+[^>]*?)?>/ig,'');
//属性清理
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+class\s*=\s*(["']?)\s*mso.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//删除所有mso开头的样式
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+lang\s*=\s*(["']?)\s*.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//删除lang属性
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+align\s*=\s*(["']?)\s*left\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//取消align=left
//样式清理
sHtml = sHtml.replace(/<\w+(?:\s+[^>]*?)?(\s+style\s*=\s*(["']?)\s*([\s\S]*?)\s*\2)(?:\s+[^>]*?)?\s*\/?>/ig,function(all,attr,p,styles){
styles=$.trim(styles.replace(/\s*(mso-[^:]+:.+?|margin\s*:\s*0cm 0cm 0pt\s*|(text-align|font-variant|line-height)\s*:\s*.+?)(;|$)\s*/ig,''));
return all.replace(attr,deepClean?'':styles?' style="'+styles+'"':'');
});
}
return sHtml;
}
this.cleanHTML=function(sHtml)
{
sHtml = sHtml.replace(/<!?\/?(DOCTYPE|html|body|meta)(\s+[^>]*?)?>/ig, '');
var arrHeadSave;sHtml = sHtml.replace(/<head(?:\s+[^>]*?)?>([\s\S]*?)<\/head>/i, function(all,content){arrHeadSave=content.match(/<(script|style)(\s+[^>]*?)?>[\s\S]*?<\/\1>/ig);return '';});
if(arrHeadSave)sHtml=arrHeadSave.join('')+sHtml;
sHtml = sHtml.replace(/<\??xml(:\w+)?(\s+[^>]*?)?>([\s\S]*?<\/xml>)?/ig, '');
if(!settings.linkTag)sHtml = sHtml.replace(/<link(\s+[^>]*?)?>/ig, '');
if(!settings.internalScript)sHtml = sHtml.replace(/<script(\s+[^>]*?)?>[\s\S]*?<\/script>/ig, '');
if(!settings.inlineScript)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+on(?:click|dblclick|mousedown|mouseup|mousemove|mouseover|mouseout|mouseenter|mouseleave|keydown|keypress|keyup|change|select|submit|reset|blur|focus|load|unload)\s*=\s*(["']?)[\s\S]*?\3((?:\s+[^>]*?)?\/?>)/ig,'$1$2$4');
if(!settings.internalStyle)sHtml = sHtml.replace(/<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
if(!settings.inlineStyle)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+(style|class)\s*=\s*(["']?)[\s\S]*?\4((?:\s+[^>]*?)?\/?>)/ig,'$1$2$5');
sHtml=sHtml.replace(/<\/(strong|b|u|strike|em|i)>((?:\s|<br\/?>| )*?)<\1(\s+[^>]*?)?>/ig,'$2');//连续相同标签
return sHtml;
}
this.formatXHTML=function(sHtml,bFormat)
{
var emptyTags = makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");//HTML 4.01
var blockTags = makeMap("address,applet,blockquote,button,center,dd,dir,div,dl,dt,fieldset,form,frameset,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");//HTML 4.01
var inlineTags = makeMap("a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");//HTML 4.01
var closeSelfTags = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
var fillAttrsTags = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
var specialTags = makeMap("script,style");
var tagReplac={'b':'strong','i':'em','s':'del','strike':'del'};
var startTag = /^<\??(\w+(?:\:\w+)?)((?:\s+[\w-\:]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/(\w+(?:\:\w+)?)[^>]*>/;
var attr = /\s+([\w-]+(?:\:\w+)?)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s]+)))?/g;
var skip=0,stack=[],last=sHtml,results=Array(),lvl=-1,lastTag='body',lastTagStart;
stack.last = function(){return this[ this.length - 1 ];};
while(last.length>0)
{
if(!stack.last()||!specialTags[stack.last()])
{
skip=0;
if(last.substring(0, 4)=='<!--')
{//注释标签
skip=last.indexOf("-->");
if(skip!=-1)
{
skip+=3;
addHtmlFrag(last.substring(0,skip));
}
}
else if(last.substring(0, 2)=='</')
{//结束标签
match = last.match( endTag );
if(match)
{
parseEndTag(match[1]);
skip = match[0].length;
}
}
else if(last.charAt(0)=='<')
{//开始标签
match = last.match( startTag );
if(match)
{
parseStartTag(match[1],match[2],match[3]);
skip = match[0].length;
}
}
if(skip==0)//普通文本
{
skip=last.indexOf('<');
if(skip==0)skip=1;
else if(skip<0)skip=last.length;
addHtmlFrag(_this.domEncode(last.substring(0,skip)));
}
last=last.substring(skip);
}
else
{//处理style和script
last=last.replace(/^([\s\S]*?)<\/(style|script)>/i, function(all, script,tagName){
results.push(script);
return ''
});
parseEndTag(stack.last());
}
}
parseEndTag();
sHtml=results.join('');
results=null;
function makeMap(str)
{
var obj = {}, items = str.split(",");
for ( var i = 0; i < items.length; i++ )obj[ items[i] ] = true;
return obj;
}
function processTag(tagName)
{
if(tagName)
{
tagName=tagName.toLowerCase();
var tag=tagReplac[tagName];
if(tag)tagName=tag;
}
else tagName='';
return tagName;
}
function parseStartTag(tagName,rest,unary)
{
tagName=processTag(tagName);
if(blockTags[tagName])while(stack.last()&&inlineTags[stack.last()])parseEndTag(stack.last());
if(closeSelfTags[tagName]&&stack.last()==tagName)parseEndTag(tagName);
unary = emptyTags[ tagName ] || !!unary;
if (!unary)stack.push(tagName);
var all=Array();
all.push('<' + tagName);
rest.replace(attr, function(match, name)
{
name=name.toLowerCase();
var value = arguments[2] ? arguments[2] :
arguments[3] ? arguments[3] :
arguments[4] ? arguments[4] :
fillAttrsTags[name] ? name : "";
all.push(' '+name+'="'+value+'"');
});
all.push((unary ? " /" : "") + ">");
addHtmlFrag(all.join(''),tagName,true);
}
function parseEndTag(tagName)
{
if(!tagName)var pos=0;//清空栈
else
{
tagName=processTag(tagName);
for(var pos=stack.length-1;pos>=0;pos--)if(stack[pos]==tagName)break;//向上寻找匹配的开始标签
}
if(pos>=0)
{
for(var i=stack.length-1;i>=pos;i--)addHtmlFrag("</" + stack[i] + ">",stack[i]);
stack.length=pos;
}
}
function addHtmlFrag(html,tagName,bStart)
{
if(bFormat==true)
{
html=html.replace(/(\t*\r?\n\t*)+/g,'');//清理换行符和相邻的制表符
if(html.match(/^\s*$/))return;//不格式化空内容的标签
var bBlock=blockTags[tagName],tag=bBlock?tagName:'';
if(bBlock)
{
if(bStart)lvl++;//块开始
if(lastTag=='')lvl--;//补文本结束
}
else if(lastTag)lvl++;//文本开始
if(tag!=lastTag||bBlock)addIndent();
results.push(html);
if(tagName=='br')addIndent();//回车强制换行
if(bBlock&&(emptyTags[tagName]||!bStart))lvl--;//块结束
lastTag=bBlock?tagName:'';lastTagStart=bStart;
}
else results.push(html);
}
function addIndent(){results.push('\r\n');if(lvl>0){var tabs=lvl;while(tabs--)results.push("\t");}}
//font转style
function font2style(all,tag,attrs,content)
{
if(!attrs)return content;
var styles='',f,s,c,style;
f=attrs.match(/ face\s*=\s*"\s*([^"]+)\s*"/i);
if(f)styles+='font-family:'+f[1]+';';
s=attrs.match(/ size\s*=\s*"\s*(\d+)\s*"/i);
if(s)styles+='font-size:'+arrFontsize[(s[1]>7?7:(s[1]<1?1:s[1]))-1].n+';';
c=attrs.match(/ color\s*=\s*"\s*([^"]+)\s*"/i);
if(c)styles+='color:'+c[1]+';';
style=attrs.match(/ style\s*=\s*"\s*([^"]+)\s*"/i);
if(style)styles+=style[1];
if(styles)content='<span style="'+styles+'">'+content+'</span>';
return content;
}
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,font2style);//最里层
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,font2style);//第2层
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,font2style);//第3层
sHtml = sHtml.replace(/^(\s*\r?\n)+|(\s*\r?\n)+$/g,'');//清理首尾换行
sHtml = sHtml.replace(/(\t*\r?\n)+/g,'\r\n');//多行变一行
return sHtml;
}
this.toggleShowBlocktag=function(state)
{
if(bShowBlocktag===state)return;
bShowBlocktag=!bShowBlocktag;
var _jBody=$(_doc.body);
if(bShowBlocktag)
{
bodyClass+=' showBlocktag';
_jBody.addClass('showBlocktag');
}
else
{
bodyClass=bodyClass.replace(' showBlocktag','');
_jBody.removeClass('showBlocktag');
}
}
this.toggleSource=function(state)
{
if(bSource===state)return;
_jTools.find('[name=Source]').toggleClass('xheEnabled').toggleClass('xheActive');
var _body=_doc.body,jBody=$(_body),sHtml;
var sourceCode,cursorMark='<span id="_xhe_cursor'+new Date().getTime()+'"></span>',cursorPos=0;
if(!bSource)
{//转为源代码模式
_this.pasteHTML(cursorMark,true);//标记当前位置
sHtml=_this.getSource(true);
cursorPos=sHtml.indexOf(cursorMark);
if(!isOpera)cursorPos=sHtml.substring(0,cursorPos).replace(/\r/g,'').length;//修正非opera光标定位点
sHtml=sHtml.replace(cursorMark,'');
if(isIE)_body.contentEditable='false';
else _doc.designMode = 'Off';
jBody.attr('scroll','no').attr('class','sourceMode').html('<textarea id="sourceCode" wrap="soft" spellcheck="false" height="100%" />');
sourceCode=$('#sourceCode',jBody).blur(_this.getSource)[0];
}
else
{//转为编辑模式
sHtml=_this.getSource();
jBody.html('').removeAttr('scroll').attr('class','editMode'+bodyClass);
if(isIE)_body.contentEditable='true';
else _doc.designMode = 'On';
if(isMozilla)
{
_this._exec("inserthtml","-");//修正firefox源代码切换回来无法删除文字的问题
$('#'+idFixFFCursor).show().focus().hide();//临时修正Firefox 3.6光标丢失问题
}
}
bSource=!bSource;
_this.setSource(sHtml);
if(bSource)//光标定位源码
{
_this.focus();
if(sourceCode.setSelectionRange)sourceCode.setSelectionRange(cursorPos, cursorPos);
else
{
var rng = sourceCode.createTextRange();
rng.move("character",cursorPos);
rng.select();
}
}
else _this.setCursorFirst(true);//定位最前面
_jTools.find('[name=Source],[name=Preview]').toggleClass('xheEnabled');
_jTools.find('.xheButton').not('[name=Source],[name=Fullscreen],[name=About]').toggleClass('xheEnabled');
setTimeout(setOpts,300);
}
this.showPreview=function()
{
var beforeSetSource=settings.beforeSetSource,sContent=_this.getSource();
if(beforeSetSource)sContent=beforeSetSource(sContent);
var sHTML='<html><head>'+headHTML+'<title>预览</title>'+(urlBase?'<base href="'+urlBase+'"/>':'')+'</head><body>' + sContent + '</body></html>';
var screen=window.screen,oWindow=window.open('', 'xhePreview', 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+Math.round(screen.width*0.9)+',height='+Math.round(screen.height*0.8)+',left='+Math.round(screen.width*0.05)),oDoc=oWindow.document;
oDoc.open();
oDoc.write(sHTML);
oDoc.close();
oWindow.focus();
}
this.toggleFullscreen=function(state)
{
if(bFullscreen===state)return;
var jLayout=$('#'+idContainer).find('.xheLayout'),jContainer=$('#'+idContainer);
if(bFullscreen)
{//取消全屏
jLayout.attr('style',sLayoutStyle);
_jArea.height(editorHeight-_jTools.outerHeight());
setTimeout(function(){$(window).scrollTop(outerScroll);},10);
}
else
{//显示全屏
outerScroll=$(window).scrollTop();
sLayoutStyle=jLayout.attr('style');
jLayout.removeAttr('style');
_jArea.height('100%');
setTimeout(fixFullHeight,100);
}
if(isMozilla)//临时修正Firefox 3.6源代码光标丢失问题
{
$('#'+idFixFFCursor).show().focus().hide();
setTimeout(_this.focus,1);
}
bFullscreen=!bFullscreen;
jContainer.toggleClass('xhe_Fullscreen');
$('html').toggleClass('xhe_Fullfix');
_jTools.find('[name=Fullscreen]').toggleClass('xheActive');
setTimeout(setOpts,300);
}
this.showMenu=function(menuitems,callback)
{
var jMenu=$('<div class="xheMenu"></div>'),arrItem=[];
$.each(menuitems,function(n,v){arrItem.push('<a href="javascript:void(0);" title="'+(v.t?v.t:v.s)+'" v="'+v.v+'">'+v.s+'</a>');});
jMenu.append(arrItem.join(''));
jMenu.click(function(ev){callback($(ev.target).closest('a').attr('v'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jMenu);
}
this.showColor=function(callback)
{
var jColor=$('<div class="xheColor"></div>'),arrItem=[],count=0;
$.each(itemColors,function(n,v)
{
if(count%7==0)arrItem.push((count>0?'</div>':'')+'<div>');
arrItem.push('<a href="javascript:void(0);" xhev="'+v+'" title="'+v+'" style="background:'+v+'"></a>');
count++;
});
arrItem.push('</div>');
jColor.append(arrItem.join(''));
jColor.click(function(ev){ev=ev.target;if(!$.nodeName(ev,'A'))return;callback($(ev).attr('xhev'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jColor);
}
this.showPastetext=function()
{
var jPastetext=$(htmlPastetext),jValue=$('#xhePastetextValue',jPastetext),jSave=$('#xheSave',jPastetext);
jSave.click(function(){
_this.loadBookmark();
var sValue=jValue.val();
if(sValue)_this.pasteText(sValue);
_this.hidePanel();
return false;
});
_this.showDialog(jPastetext);
}
this.showLink=function()
{
var jLink=$(htmlLink),jParent=_this.getParent('a'),jText=$('#xheLinkText',jLink),jUrl=$('#xheLinkUrl',jLink),jTarget=$('#xheLinkTarget',jLink),jSave=$('#xheSave',jLink),selHtml=_this.getSelect();
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'href'));
jTarget.attr('value',jParent.attr('target'));
}
else if(selHtml=='')jText.val(settings.defLinkText).closest('div').show();
if(settings.upLinkUrl)_this.uploadInit(jUrl,settings.upLinkUrl,settings.upLinkExt);
jSave.click(function(){
var url=jUrl.val();
_this.loadBookmark();
if(url==''||jParent.length==0)_this._exec('unlink');
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sTarget=jTarget.val(),sText=jText.val();
if(aUrl.length>1)
{//批量插入
_this._exec('unlink');//批量前删除当前链接并重新获取选择内容
selHtml=_this.getSelect();
var sTemplate='<a href="xhe_tmpurl"',sLink,arrLink=[];
if(sTarget!='')sTemplate+=' target="'+sTarget+'"';
sTemplate+='>xhe_tmptext</a>';
sText=(selHtml!=''?selHtml:(sText?sText:url));
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sLink=sTemplate;
sLink=sLink.replace('xhe_tmpurl',url[0]);
sLink=sLink.replace('xhe_tmptext',url[1]?url[1]:sText);
arrLink.push(sLink);
}
}
_this.pasteHTML(arrLink.join(' '));
}
else
{//单url模式
url=aUrl[0].split('||');
if(!sText)sText=url[0];
sText=url[1]?url[1]:(selHtml!='')?'':sText?sText:url[0];
if(jParent.length==0)
{
if(sText)_this.pasteHTML('<a href="#xhe_tmpurl">'+sText+'</a>');
else _this._exec('createlink','#xhe_tmpurl');
jParent=$('a[href$="#xhe_tmpurl"]',_doc);
}
else if(sText&&!isSafari)jParent.text(sText);//safari改写文本会导致光标丢失
xheAttr(jParent,'href',url[0]);
if(sTarget!='')jParent.attr('target',sTarget);
else jParent.removeAttr('target');
}
}
_this.hidePanel();
return false;
});
_this.showDialog(jLink);
}
this.showImg=function()
{
var jImg=$(htmlImg),jParent=_this.getParent('img'),jUrl=$('#xheImgUrl',jImg),jAlt=$('#xheImgAlt',jImg),jAlign=$('#xheImgAlign',jImg),jWidth=$('#xheImgWidth',jImg),jHeight=$('#xheImgHeight',jImg),jBorder=$('#xheImgBorder',jImg),jVspace=$('#xheImgVspace',jImg),jHspace=$('#xheImgHspace',jImg),jSave=$('#xheSave',jImg);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jAlt.val(jParent.attr('alt'));
jAlign.val(jParent.attr('align'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
jBorder.val(jParent.attr('border'));
var vspace=jParent.attr('vspace'),hspace=jParent.attr('hspace');
jVspace.val(vspace<=0?'':vspace);
jHspace.val(hspace<=0?'':hspace);
}
if(settings.upImgUrl)_this.uploadInit(jUrl,settings.upImgUrl,settings.upImgExt);
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sAlt=jAlt.val(),sAlign=jAlign.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sBorder=jBorder.val(),sVspace=jVspace.val(),sHspace=jHspace.val();;
if(aUrl.length>1)
{//批量插入
var sTemplate='<img src="xhe_tmpurl"',sImg,arrImg=[];
if(sAlt!='')sTemplate+=' alt="'+sAlt+'"';
if(sAlign!='')sTemplate+=' align="'+sAlign+'"';
if(sWidth!='')sTemplate+=' width="'+sWidth+'"';
if(sHeight!='')sTemplate+=' height="'+sHeight+'"';
if(sBorder!='')sTemplate+=' border="'+sBorder+'"';
if(sVspace!='')sTemplate+=' vspace="'+sVspace+'"';
if(sHspace!='')sTemplate+=' hspace="'+sHspace+'"';
sTemplate+=' />';
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sImg=sTemplate;
sImg=sImg.replace('xhe_tmpurl',url[0]);
if(url[1])sImg='<a href="'+url[1]+'" target="_blank">'+sImg+'</a>'
arrImg.push(sImg);
}
}
_this.pasteHTML(arrImg.join(' '));
}
else if(aUrl.length==1)
{//单URL模式
url=aUrl[0];
if(url!='')
{
url=url.split('||');
if(jParent.length==0)
{
_this.pasteHTML('<img src="'+url[0]+'#xhe_tmpurl" />');
jParent=$('img[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0])
if(sAlt!='')jParent.attr('alt',sAlt);
if(sAlign!='')jParent.attr('align',sAlign);
else jParent.removeAttr('align');
if(sWidth!='')jParent.attr('width',sWidth);
else jParent.removeAttr('width');
if(sHeight!='')jParent.attr('height',sHeight);
else jParent.removeAttr('height');
if(sBorder!='')jParent.attr('border',sBorder);
else jParent.removeAttr('border');
if(sVspace!='')jParent.attr('vspace',sVspace);
else jParent.removeAttr('vspace');
if(sHspace!='')jParent.attr('hspace',sHspace);
else jParent.removeAttr('hspace');
if(url[1])
{
var jLink=jParent.parent('a');
if(jLink.length==0)
{
jParent.wrap('<a></a>');
jLink=jParent.parent('a');
}
xheAttr(jLink,'href',url[1]);
jLink.attr('target','_blank');
}
}
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
_this.showDialog(jImg);
}
this.showEmbed=function(sType,sHtml,sMime,sClsID,sBaseAttrs,sUploadUrl,sUploadExt)
{
var jEmbed=$(sHtml),jParent=_this.getParent('embed[type="'+sMime+'"],embed[classid="'+sClsID+'"]'),jUrl=$('#xhe'+sType+'Url',jEmbed),jWidth=$('#xhe'+sType+'Width',jEmbed),jHeight=$('#xhe'+sType+'Height',jEmbed),jSave=$('#xheSave',jEmbed);
if(sUploadUrl)_this.uploadInit(jUrl,sUploadUrl,sUploadExt);
_this.showDialog(jEmbed);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
}
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var w=jWidth.val(),h=jHeight.val(),reg=/^[0-9]+$/;
if(!reg.test(w))w=412;if(!reg.test(h))h=300;
var sBaseCode='<embed type="'+sMime+'" classid="'+sClsID+'" src="xhe_tmpurl"'+sBaseAttrs;
var aUrl=url.split(' ');
if(aUrl.length>1)
{//批量插入
var sTemplate=sBaseCode+'',sEmbed,arrEmbed=[];
sTemplate+=' width="xhe_width" height="xhe_height" />';
for(var i in aUrl)
{
url=aUrl[i].split('||');
sEmbed=sTemplate;
sEmbed=sEmbed.replace('xhe_tmpurl',url[0])
sEmbed=sEmbed.replace('xhe_width',url[1]?url[1]:w)
sEmbed=sEmbed.replace('xhe_height',url[2]?url[2]:h)
if(url!='')arrEmbed.push(sEmbed);
}
_this.pasteHTML(arrEmbed.join(' '));
}
else if(aUrl.length==1)
{//单URL模式
url=aUrl[0].split('||');
if(jParent.length==0)
{
_this.pasteHTML(sBaseCode.replace('xhe_tmpurl',url[0]+'#xhe_tmpurl')+' />');
jParent=$('embed[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0]);
jParent.attr('width',url[1]?url[1]:w);
jParent.attr('height',url[2]?url[2]:h);
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
}
this.showEmot=function(group)
{
var jEmot=$('<div class="xheEmot"></div>');
group=group?group:(selEmotGroup?selEmotGroup:'default');
var arrEmot=arrEmots[group];
var sEmotPath=emotPath+group+'/',n=0,arrList=[],jList='';
var ew=arrEmot.width,eh=arrEmot.height,line=arrEmot.line,count=arrEmot.count,list=arrEmot.list;
if(count)
{
for(var i=1;i<=count;i++)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+i+'.gif);" emot="'+group+','+i+'" xhev=""> </a>');
if(n%line==0)arrList.push('<br />');
}
}
else
{
$.each(list,function(id,title)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+id+'.gif);" emot="'+group+','+id+'" title="'+title+'" xhev="'+title+'"> </a>');
if(n%line==0)arrList.push('<br />');
});
}
var w=line*(ew+12),h=Math.ceil(n/line)*(eh+12),mh=w*0.75;
if(h<=mh)mh='';
jList=$('<style>'+(mh?'.xheEmot div{width:'+(w+20)+'px;height:'+mh+'px;}':'')+'.xheEmot div a{width:'+ew+'px;height:'+eh+'px;}</style><div>'+arrList.join('')+'</div>').click(function(ev){ev=ev.target;var jA=$(ev);if(!$.nodeName(ev,'A'))return;_this.pasteHTML('<img emot="'+jA.attr('emot')+'" alt="'+jA.attr('xhev')+'">');_this.hidePanel();return false;}).mousedown(returnFalse);
jEmot.append(jList);
var gcount=0,arrGroup=['<ul>'],jGroup;//表情分类
$.each(arrEmots,function(g,v){
gcount++;
arrGroup.push('<li'+(group==g?' class="cur"':'')+'><a href="javascript:void(0);" group="'+g+'">'+v.name+'</a></li>');
});
if(gcount>1)
{
arrGroup.push('</ul><br style="clear:both;" />');
jGroup=$(arrGroup.join('')).click(function(ev){selEmotGroup=$(ev.target).attr('group');_this.exec('Emot');return false;}).mousedown(returnFalse);
jEmot.append(jGroup);
}
_this.showPanel(jEmot);
}
this.showTable=function()
{
var jTable=$(htmlTable),jRows=$('#xheTableRows',jTable),jColumns=$('#xheTableColumns',jTable),jHeaders=$('#xheTableHeaders',jTable),jWidth=$('#xheTableWidth',jTable),jHeight=$('#xheTableHeight',jTable),jBorder=$('#xheTableBorder',jTable),jCellSpacing=$('#xheTableCellSpacing',jTable),jCellPadding=$('#xheTableCellPadding',jTable),jAlign=$('#xheTableAlign',jTable),jCaption=$('#xheTableCaption',jTable),jSave=$('#xheSave',jTable);
jSave.click(function(){
_this.loadBookmark();
var sCaption=jCaption.val(),sBorder=jBorder.val(),sRows=jRows.val(),sCols=jColumns.val(),sHeaders=jHeaders.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sCellSpacing=jCellSpacing.val(),sCellPadding=jCellPadding.val(),sAlign=jAlign.val();
var i,j,htmlTable='<table'+(sBorder!=''?' border="'+sBorder+'"':'')+(sWidth!=''?' width="'+sWidth+'"':'')+(sHeight!=''?' width="'+sHeight+'"':'')+(sCellSpacing!=''?' cellspacing="'+sCellSpacing+'"':'')+(sCellPadding!=''?' cellpadding="'+sCellPadding+'"':'')+(sAlign!=''?' align="'+sAlign+'"':'')+'>';
if(sCaption!='')htmlTable+='<caption>'+sCaption+'</caption>';
if(sHeaders=='row'||sHeaders=='both')
{
htmlTable+='<tr>';
for(i=0;i<sCols;i++)htmlTable+='<th scope="col"> </th>';
htmlTable+='</tr>';
sRows--;
}
htmlTable+='<tbody>';
for(i=0;i<sRows;i++)
{
htmlTable+='<tr>';
for(j=0;j<sCols;j++)
{
if(j==0&&(sHeaders=='col'||sHeaders=='both'))htmlTable+='<th scope="row"> </th>';
else htmlTable+='<td> </td>';
}
htmlTable+='</tr>';
}
htmlTable+='</tbody></table>';
_this.pasteHTML(htmlTable);
_this.hidePanel();
return false;
});
_this.showDialog(jTable);
}
this.showAbout=function()
{
var jAbout=$(htmlAbout);
_this.showDialog(jAbout);
}
this.addShortcuts=function(key,cmd)
{
key=key.toLowerCase();
if(arrShortCuts[key]==undefined)arrShortCuts[key]=Array();
arrShortCuts[key].push(cmd);
}
this.delShortcuts=function(key){delete arrShortCuts[key];}
this.uploadInit=function(jText,toUrl,upext)
{
var jUpload=$('<span class="xheUpload"><input type="text" style="visibility:hidden;" tabindex="-1" /><input type="button" value="'+settings.upBtnText+'" class="xheBtn" tabindex="-1" /></span>'),jUpBtn=$('.xheBtn',jUpload);
var bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
jText.after(jUpload);jUpBtn.before(jText);
toUrl=toUrl.replace(/{editorRoot}/ig,editorRoot);
if(toUrl.substr(0,1)=='!')//自定义上传管理页
{
jUpBtn.click(function(){
bShowPanel=false;//防止按钮面板被关闭
_this.showIframeModal('上传文件',toUrl.substr(1),setUploadMsg,null,null,function(){bShowPanel=true;});
});
}
else
{//系统默认ajax上传
jUpload.append('<input type="file"'+(upMultiple>1?' multiple=""':'')+' class="xheFile" size="13" name="'+uploadInputname+'" tabindex="-1" />');
var jFile=$('.xheFile',jUpload),arrMsg;
jFile.change(function(){arrMsg=[];_this.startUpload(jFile[0],toUrl,upext,setUploadMsg);});
setTimeout(function(){//拖放上传
jText.closest('.xheDialog').bind('dragenter dragover',returnFalse).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(bHtml5Upload&&dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0)_this.startUpload(fileList,toUrl,upext,setUploadMsg);
return false;
});
},10);
}
function setUploadMsg(arrMsg)
{
if(is(arrMsg,'string'))arrMsg=[arrMsg];//允许单URL传递
var bImmediate=false,i,count=arrMsg.length,msg,url,arrUrl=[],onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用户上传回调
for(i=0;i<count;i++)
{
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!'){bImmediate=true;url=url.substr(1);}
arrUrl.push(url);
}
jText.val(arrUrl.join(' '));
if(bImmediate)jText.closest('.xheDialog').find('#xheSave').click();
}
}
this.startUpload=function(fromFiles,toUrl,limitExt,onUploadComplete)
{
var arrMsg=[],bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
var upload,fileList,filename,jUploadTip=$('<div style="padding:22px 0;text-align:center;line-height:30px;">文件上传中,请稍候……<br /></div>'),sLoading='<img src="'+skinPath+'img/loading.gif">';
if(!bHtml5Upload||(fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0])))
{
if(!checkFileExt(fromFiles.value,limitExt))return;
jUploadTip.append(sLoading);
upload=new _this.html4Upload(fromFiles,toUrl,onUploadCallback);
}
else
{
if(!fileList)fileList=fromFiles;//拖放文件列表
var i,len=fileList.length;
if(len>upMultiple){alert('请不要一次上传超过'+upMultiple+'个文件');return;}
for(i=0;i<len;i++)if(!checkFileExt(fileList[i].fileName,limitExt))return;
var jProgress=$('<div class="xheProgress"><div><span>0%</span></div></div>');
jUploadTip.append(jProgress);
upload=new _this.html5Upload(uploadInputname,fileList,toUrl,onUploadCallback,function(ev){
if(ev.loaded>=0)
{
var sPercent=Math.round((ev.loaded * 100) / ev.total)+'%';
$('div',jProgress).css('width',sPercent);
$('span',jProgress).text(sPercent+' ( '+formatBytes(ev.loaded)+' / '+formatBytes(ev.total)+' )');
}
else jProgress.replaceWith(sLoading);//不支持进度
});
}
var panelState=bShowPanel;
if(panelState)bShowPanel=false;//防止面板被关闭
_this.showModal('文件上传中(Esc取消上传)',jUploadTip,320,150,function(){bShowPanel=panelState;upload.remove();});
upload.start();
function onUploadCallback(sText,bFinish)
{
var data=Object,bOK=false;
try{data=eval('('+sText+')');}catch(ex){};
if(data.err==undefined||data.msg==undefined)alert(toUrl+' 上传接口发生错误!\r\n\r\n返回的错误内容为: \r\n\r\n'+sText);
else
{
if(data.err)alert(data.err);
else
{
arrMsg.push(data.msg);
bOK=true;//继续下一个文件上传
}
}
if(!bOK||bFinish)_this.removeModal();
if(bFinish&&bOK)onUploadComplete(arrMsg);//全部上传完成
return bOK;
}
}
this.html4Upload=function(fromfile,toUrl,callback)
{
var uid = new Date().getTime(),idIO='jUploadFrame'+uid,_this=this;
var jIO=$('<iframe name="'+idIO+'" class="xheHideArea" />').appendTo('body');
var jForm=$('<form action="'+toUrl+'" target="'+idIO+'" method="post" enctype="multipart/form-data" class="xheHideArea"></form>').appendTo('body');
var jOldFile = $(fromfile),jNewFile = jOldFile.clone().attr('disabled','true');
jOldFile.before(jNewFile).appendTo(jForm);
this.remove=function()
{
if(_this!=null)
{
jNewFile.before(jOldFile).remove();
jIO.remove();jForm.remove();
_this=null;
}
}
this.onLoad=function(){callback($(jIO[0].contentWindow.document.body).text(),true);}
this.start=function(){jForm.submit();jIO.load(_this.onLoad);}
return this;
}
this.html5Upload=function(inputname,fromFiles,toUrl,callback,onProgress)
{
var xhr,i=0,count=fromFiles.length,allLoaded=0,allSize=0,_this=this;
for(var j=0;j<count;j++)allSize+=fromFiles[j].fileSize;
this.remove=function(){if(xhr){xhr.abort();xhr=null;}}
this.uploadNext=function(sText)
{
if(sText)//当前文件上传完成
{
allLoaded+=fromFiles[i-1].fileSize;
returnProgress(0);
}
if((!sText||(sText&&callback(sText,i==count)==true))&&i<count)postFile(fromFiles[i++],toUrl,_this.uploadNext,function(loaded){returnProgress(loaded);});
}
this.start=function(){_this.uploadNext();}
function postFile(fromfile,toUrl,callback,onProgress)
{
xhr = new XMLHttpRequest(),upload=xhr.upload;
xhr.onreadystatechange=function(){if(xhr.readyState==4)callback(xhr.responseText);};
if(upload)upload.onprogress=function(ev){onProgress(ev.loaded);};
else onProgress(-1);//不支持进度
xhr.open("POST", toUrl);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Content-Disposition', 'attachment; name="'+inputname+'"; filename="'+fromfile.fileName+'"');
if(xhr.sendAsBinary)xhr.sendAsBinary(fromfile.getAsBinary());
else xhr.send(fromfile);
}
function returnProgress(loaded){if(onProgress)onProgress({'loaded':allLoaded+loaded,'total':allSize});}
}
this.showIframeModal=function(title,ifmurl,callback,w,h,onRemove)
{
var jContent=$('<iframe frameborder="0" src="'+ifmurl.replace(/{editorRoot}/ig,editorRoot)+'" style="width:100%;height:100%;display:none;" /><div class="xheModalIfmWait"></div>'),jIframe=$(jContent[0]),jWait=$(jContent[1]);
_this.showModal(title,jContent,w,h,onRemove);
jIframe.load(function(){
var modalWin=jIframe[0].contentWindow,jModalDoc=$(modalWin.document);
modalWin.callback=function(v){_this.removeModal();callback(v);};
modalWin.unloadme=_this.removeModal;
jModalDoc.keydown(_this.checkEsc);
jIframe.show();jWait.remove();
});
}
this.showModal=function(title,content,w,h,onRemove)
{
if(bShowModal)return false;//只能弹出一个模式窗口
layerShadow=settings.layerShadow;
w=w?w:settings.modalWidth;h=h?h:settings.modalHeight;
jModal=$('<div class="xheModal" style="width:'+(w-1)+'px;height:'+h+'px;margin-left:-'+Math.ceil(w/2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+Math.ceil(h/2)+'px')+'">'+(settings.modalTitle?'<div class="xheModalTitle"><span class="xheModalClose" title="关闭 (Esc)"></span>'+title+'</div>':'')+'<div class="xheModalContent"></div></div>').appendTo('body');
jOverlay=$('<div class="xheModalOverlay"></div>').appendTo('body');
if(layerShadow>0)jModalShadow=$('<div class="xheModalShadow" style="width:'+jModal.outerWidth()+'px;height:'+jModal.outerHeight()+'px;margin-left:-'+(Math.ceil(w/2)-layerShadow-2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+(Math.ceil(h/2)-layerShadow-2)+'px')+'"></div>').appendTo('body');
$('.xheModalContent',jModal).css('height',h-(settings.modalTitle?$('.xheModalTitle').outerHeight():0)).html(content);
if(isIE&&browerVer==6.0)jHideSelect=$('select:visible').css('visibility','hidden');//隐藏覆盖的select
$('.xheModalClose',jModal).click(_this.removeModal);
jOverlay.show();if(layerShadow>0)jModalShadow.show();jModal.show();
bShowModal=true;
onModalRemove=onRemove;
}
this.removeModal=function(){if(jHideSelect)jHideSelect.css('visibility','visible');jModal.html('').remove();if(layerShadow>0)jModalShadow.remove();jOverlay.remove();if(onModalRemove)onModalRemove();bShowModal=false;};
this.showDialog=function(content)
{
var jDialog=$('<div class="xheDialog"></div>'),jContent=$(content),jSave=$('#xheSave',jContent);
if(jSave.length==1)
{
jContent.find('input[type=text],select').keypress(function(ev){if(ev.which==13){jSave.click();return false;}});
jContent.find('textarea').keydown(function(ev){if(ev.ctrlKey&&ev.which==13){jSave.click();return false;}});
jSave.after(' <input type="button" id="xheCancel" value="取消" />');
$('#xheCancel',jContent).click(_this.hidePanel);
if(!settings.clickCancelDialog)
{
bClickCancel=false;//关闭点击隐藏
var jFixCancel=$('<div class="xheFixCancel"></div>').appendTo('body').mousedown(returnFalse);
var xy=_jArea.offset();
jFixCancel.css({'left':xy.left,'top':xy.top,width:_jArea.outerWidth(),height:_jArea.outerHeight()})
}
jDialog.mousedown(function(){bDisableHoverExec=true;})//点击对话框禁止悬停执行
}
jDialog.append(jContent);
_this.showPanel(jDialog);
if(!isIE)setTimeout(function(){jDialog.find('input[type=text],textarea').filter(':visible').filter(function(){return $(this).css('visibility')!='hidden';}).eq(0).focus();},10);//定位首个可见输入表单项,延迟解决opera无法设置焦点
}
this.showPanel=function(content)
{
if(!ev.target)return false;
_jPanel.html('').append(content).css('left',-999).css('top',-999);
_jPanelButton=$(ev.target).closest('a').addClass('xheActive');
var xy=_jPanelButton.offset();
var x=xy.left,y=xy.top;y+=_jPanelButton.outerHeight()-1;
_jCntLine.css({'left':x+1,'top':y,'width':_jPanelButton.width()}).show();
if((x+_jPanel.outerWidth())>document.body.clientWidth)x-=(_jPanel.outerWidth()-_jPanelButton.outerWidth());//向左显示面板
var layerShadow=settings.layerShadow;
if(layerShadow>0)_jShadow.css({'left':x+layerShadow,'top':y+layerShadow,'width':_jPanel.outerWidth(),'height':_jPanel.outerHeight()}).show();
_jPanel.css({'left':x,'top':y}).show();
bQuickHoverExec=bShowPanel=true;
}
this.hidePanel=function(){if(bShowPanel){_jPanelButton.removeClass('xheActive');_jShadow.hide();_jCntLine.hide();_jPanel.hide();bShowPanel=false;if(!bClickCancel){$('.xheFixCancel').remove();bClickCancel=true;};bQuickHoverExec=bDisableHoverExec=false;lastAngle=null;}}
this.exec=function(cmd)
{
_this.hidePanel();
_this.saveBookmark();
var tool=arrTools[cmd];
if(!tool)return false;//无效命令
if(ev==null)//非鼠标点击
{
ev={};
var btn=_jTools.find('.xheButton[name='+cmd+']');
if(btn.length==1)ev.target=btn;//设置当前事件焦点
}
if(tool.e)tool.e.call(_this)//插件事件
else//内置工具
{
cmd=cmd.toLowerCase();
switch(cmd)
{
case 'cut':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的浏览器安全设置不允许使用剪切操作,请使用键盘快捷键(Ctrl + X)来完成');};
break;
case 'copy':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的浏览器安全设置不允许使用复制操作,请使用键盘快捷键(Ctrl + C)来完成');}
break;
case 'paste':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的浏览器安全设置不允许使用粘贴操作,请使用键盘快捷键(Ctrl + V)来完成');}
break;
case 'pastetext':
if(window.clipboardData)_this.pasteText(window.clipboardData.getData('Text', true));
else _this.showPastetext();
break;
case 'blocktag':
var menuBlocktag=[];
$.each(arrBlocktag,function(n,v){menuBlocktag.push({s:'<'+v.n+'>'+v.t+'</'+v.n+'>',v:'<'+v.n+'>',t:v.t});});
_this.showMenu(menuBlocktag,function(v){_this._exec('formatblock',v);});
break;
case 'fontface':
var menuFontname=[];
$.each(arrFontname,function(n,v){v.c=v.c?v.c:v.n;menuFontname.push({s:'<span style="font-family:'+v.c+'">'+v.n+'</span>',v:v.c,t:v.n});});
_this.showMenu(menuFontname,function(v){_this._exec('fontname',v);});
break;
case 'fontsize':
var menuFontsize=[];
$.each(arrFontsize,function(n,v){menuFontsize.push({s:'<span style="font-size:'+v.s+';">'+v.t+'('+v.s+')</span>',v:n+1,t:v.t});});
_this.showMenu(menuFontsize,function(v){_this._exec('fontsize',v);});
break;
case 'fontcolor':
_this.showColor(function(v){_this._exec('forecolor',v);});
break;
case 'backcolor':
_this.showColor(function(v){if(isIE)_this._exec('backcolor',v);else{setCSS(true);_this._exec('hilitecolor',v);setCSS(false);}});
break;
case 'align':
_this.showMenu(menuAlign,function(v){_this._exec(v);});
break;
case 'list':
_this.showMenu(menuList,function(v){_this._exec(v);});
break;
case 'link':
_this.showLink();
break;
case 'img':
_this.showImg();
break;
case 'flash':
_this.showEmbed('Flash',htmlFlash,'application/x-shockwave-flash','clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000',' wmode="opaque" quality="high" menu="false" play="true" loop="true" allowfullscreen="true"',settings.upFlashUrl,settings.upFlashExt);
break;
case 'media':
_this.showEmbed('Media',htmlMedia,'application/x-mplayer2','clsid:6bf52a52-394a-11d3-b153-00c04f79faa6',' enablecontextmenu="false" autostart="false"',settings.upMediaUrl,settings.upMediaExt);
break;
case 'emot':
_this.showEmot();
break;
case 'table':
_this.showTable();
break;
case 'source':
_this.toggleSource();
break;
case 'preview':
_this.showPreview();
break;
case 'print':
_win.print();
break;
case 'fullscreen':
_this.toggleFullscreen();
break;
case 'about':
_this.showAbout();
break;
default:
_this._exec(cmd);
break;
}
}
ev=null;
}
this._exec=function(cmd,param,noFocus)
{
if(!noFocus)_this.focus();
var state;
if(param!=undefined)state=_doc.execCommand(cmd,false,param);
else state=_doc.execCommand(cmd,false,null);
return state;
}
function checkDblClick(ev)
{
var target=ev.target,tool=arrDbClick[target.tagName.toLowerCase()];
if(tool)
{
if(tool=='Embed')//自动识别Flash和多媒体
{
var arrEmbed={'application/x-shockwave-flash':'Flash','application/x-mplayer2':'Media'};
tool=arrEmbed[target.type.toLowerCase()];
}
_this.exec(tool);
}
}
function checkEsc(ev)
{
if(ev.which==27)
{
if(bShowModal)_this.removeModal();
else if(bShowPanel)_this.hidePanel();
return false;
}
}
function loadReset(){setTimeout(_this.setSource,10);}
function saveResult(){_this.getSource();};
function cleanPaste(ev){
if(bSource||bCleanPaste)return true;
bCleanPaste=true;//解决IE右键粘贴重复产生paste的问题
_this.saveBookmark();
var jDiv=$('<div style="position:absolute;left:-1000px;top:'+_jWin.scrollTop()+'px;overflow:hidden;width:1px;height:1px;" />',_doc),div=jDiv[0],sel=_this.getSel(),rng=_this.getRng();
$(_doc.body).append(jDiv);
if(isIE){
rng.moveToElementText(div);
rng.execCommand('Paste');
ev.preventDefault();
}
else{
rng.selectNodeContents(div);
sel.removeAllRanges();
sel.addRange(rng);
}
setTimeout(function(){
var sPaste;
if(settings.forcePasteText===true)sPaste=jDiv.text();
else{
sPaste=div.innerHTML;
sPaste=_this.cleanHTML(sPaste);
sPaste=_this.formatXHTML(sPaste);
sPaste=_this.cleanWord(sPaste);
}
jDiv.remove();
_this.loadBookmark();
_this.pasteHTML(sPaste);
bCleanPaste=false;
},0);
}
function setCSS(css)
{
try{_this._exec('styleWithCSS',css,true);}
catch(e)
{try{_this._exec('useCSS',!css,true);}catch(e){}}
}
function setOpts()
{
if(bInit&&!bSource)
{
setCSS(false);
try{_this._exec('enableObjectResizing',true,true);}catch(e){}
//try{_this._exec('enableInlineTableEditing',false,true);}catch(e){}
if(isIE)try{_this._exec('BackgroundImageCache',true,true);}catch(e){}
}
}
function forcePtag(ev)
{
if(bSource||ev.which!=13||ev.shiftKey||ev.ctrlKey||ev.altKey)return true;
var pNode=_this.getParent('p,h1,h2,h3,h4,h5,h6,pre,address,div,li');
if(pNode.is('li'))return true;
if(settings.forcePtag){if(pNode.length==0)_this._exec('formatblock','<p>');}
else
{
_this.pasteHTML('<br />');
if(isIE&&pNode.length>0&&_this.getRng().parentElement().childNodes.length==2)_this.pasteHTML('<br />');
return false;
}
}
function fixFullHeight()
{
if(!isMozilla&&!isSafari)
{
if(bFullscreen)_jArea.height('100%').css('height',_jArea.outerHeight()-_jTools.outerHeight());
if(isIE)_jTools.hide().show();
}
}
function fixAppleSel(e)
{
e=e.target;
if(e.tagName.match(/(img|embed)/i))
{
var sel=_this.getSel(),rng=_this.getRng();
rng.selectNode(e);
sel.removeAllRanges();
sel.addRange(rng);
}
}
function xheAttr(jObj,n,v)
{
if(!n)return false;
var kn='_xhe_'+n;
if(v)//设置属性
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
jObj.attr(n,urlBase?getLocalUrl(v,'abs',urlBase):v).removeAttr(kn).attr(kn,v);
}
return jObj.attr(kn)||jObj.attr(n);
}
function clickCancelPanel(){if(bClickCancel)_this.hidePanel();}
function checkShortcuts(event)
{
if(bSource)return true;
var code=event.which,special=specialKeys[code],sChar=special?special:String.fromCharCode(code).toLowerCase();
sKey='';
sKey+=event.ctrlKey?'ctrl+':'';sKey+=event.altKey?'alt+':'';sKey+=event.shiftKey?'shift+':'';sKey+=sChar;
var cmd=arrShortCuts[sKey],c;
for(c in cmd)
{
c=cmd[c];
if($.isFunction(c)){if(c.call(_this)===false)return false;}
else{_this.exec(c);return false;}//按钮独占快捷键
}
}
function is(o,t)
{
var n = typeof(o);
if (!t)return n != 'undefined';
if (t == 'array' && (o.hasOwnProperty && o instanceof Array))return true;
return n == t;
}
function getLocalUrl(url,urlType,urlBase)//绝对地址:abs,根地址:root,相对地址:rel
{
var baseUrl=urlBase?$('<a href="'+urlBase+'" />')[0]:location,protocol=baseUrl.protocol,host=baseUrl.hostname,port=baseUrl.port,path=baseUrl.pathname.replace(/\\/g,'/').replace(/[^\/]+$/i,'');
port=(port=='')?'80':port;
url=$.trim(url);
if(urlType!='abs')url=url.replace(new RegExp(protocol+'\\/\\/'+host.replace(/\./g,'\\.')+'(?::'+port+')'+(port=='80'?'?':'')+'(\/|$)','i'),'/');
if(urlType=='rel')url=url.replace(new RegExp('^'+path.replace(/([\/\.\+\[\]\(\)])/g,'\\$1'),'i'),'');
if(urlType!='rel')
{
if(!url.match(/^((https?|file):\/\/|\/)/i))url=path+url;
if(url.charAt(0)=='/')//处理..
{
var arrPath=[],arrFolder = url.split('/'),folder,i,l=arrFolder.length;
for(i=0;i<l;i++)
{
folder=arrFolder[i];
if(folder=='..')arrPath.pop();
else if(folder!==''&&folder!='.')arrPath.push(folder);
}
if(arrFolder[l-1]=='')arrPath.push('');
url='/'+arrPath.join('/');
}
}
if(urlType=='abs')if(!url.match(/(https?|file):\/\//i))url=protocol+'//'+location.host+url;
return url;
}
function checkFileExt(filename,limitExt)
{
if(limitExt=='*'||filename.match(new RegExp('\.('+limitExt.replace(/,/g,'|')+')$','i')))return true;
else
{
alert('上传文件扩展名必需为: '+limitExt);
return false;
}
}
function formatBytes(bytes)
{
var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+s[e];
}
function returnFalse(){return false;}
}
$(function(){
$.fn.oldVal=$.fn.val;
$.fn.val=function(value)
{
var _this=this,editor;
if(value===undefined)if(this[0]&&(editor=this[0].xheditor))return editor.getSource();else return _this.oldVal(value);//读
return this.each(function(){if(editor=this.xheditor)editor.setSource(value);else _this.oldVal(value);});//写
}
$('textarea').each(function(){
var self=$(this),xhClass=self.attr('class').match(/(?:^|\s)xheditor(?:\-(m?full|simple|mini))?(?:\s|$)/i);
if(xhClass)self.xheditor(xhClass[1]?{tools:xhClass[1]}:null);
});
});
})(jQuery); | JavaScript |
/*!
* xhEditor - WYSIWYG XHTML Editor
* @requires jQuery v1.4.2
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 1.1.1 (build 101002)
*/
(function($){
if($.xheditor)return false;//防止JS重複加載
$.fn.xheditor=function(options)
{
var arrSuccess=[];
this.each(function(){
if(!$.nodeName(this,'TEXTAREA'))return;
if(options===false)//卸載
{
if(this.xheditor)
{
this.xheditor.remove();
this.xheditor=null;
}
}
else//初始化
{
if(!this.xheditor)
{
var tOptions=/({.*})/.exec($(this).attr('class'));
if(tOptions)
{
try{tOptions=eval('('+tOptions[1]+')');}catch(ex){};
options=$.extend({},tOptions,options );
}
var editor=new $.xheditor(this,options);
if(editor.init())
{
this.xheditor=editor;
arrSuccess.push(editor);
}
else editor=null;
}
else arrSuccess.push(this.xheditor);
}
});
if(arrSuccess.length==0)arrSuccess=false;
if(arrSuccess.length==1)arrSuccess=arrSuccess[0];
return arrSuccess;
}
var xCount=0,browerVer=$.browser.version,isIE=$.browser.msie,isMozilla=$.browser.mozilla,isSafari=$.browser.safari,isOpera=$.browser.opera,bShowPanel=false,bClickCancel=true,bShowModal=false,bCheckEscInit=false;
var _jPanel,_jShadow,_jCntLine,_jPanelButton;
var jModal,jModalShadow,layerShadow,jOverlay,jHideSelect,onModalRemove;
var editorRoot;
$('script[src*=xheditor]').each(function(){
var s=this.src;
if(s.match(/xheditor[^\/]*\.js/i)){editorRoot=s.replace(/[\?#].*$/, '').replace(/(^|[\/\\])[^\/]*$/, '$1');return false;}
});
var specialKeys={ 27: 'esc', 9: 'tab', 32:'space', 13: 'enter', 8:'backspace', 145: 'scroll',
20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',
35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down',
112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12' };
var itemColors=['#FFFFFF','#CCCCCC','#C0C0C0','#999999','#666666','#333333','#000000','#FFCCCC','#FF6666','#FF0000','#CC0000','#990000','#660000','#330000','#FFCC99','#FF9966','#FF9900','#FF6600','#CC6600','#993300','#663300','#FFFF99','#FFFF66','#FFCC66','#FFCC33','#CC9933','#996633','#663333','#FFFFCC','#FFFF33','#FFFF00','#FFCC00','#999900','#666600','#333300','#99FF99','#66FF99','#33FF33','#33CC00','#009900','#006600','#003300','#99FFFF','#33FFFF','#66CCCC','#00CCCC','#339999','#336666','#003333','#CCFFFF','#66FFFF','#33CCFF','#3366FF','#3333FF','#000099','#000066','#CCCCFF','#9999FF','#6666CC','#6633FF','#6600CC','#333399','#330099','#FFCCFF','#FF99FF','#CC66CC','#CC33CC','#993399','#663366','#330033'];
var arrBlocktag=[{n:'p',t:'普通段落'},{n:'h1',t:'標題1'},{n:'h2',t:'標題2'},{n:'h3',t:'標題3'},{n:'h4',t:'標題4'},{n:'h5',t:'標題5'},{n:'h6',t:'標題6'},{n:'pre',t:'已編排格式'},{n:'address',t:'地址'}];
var arrFontname=[{n:'新細明體',c:'PMingLiu'},{n:'細明體',c:'mingliu'},{n:'標楷體',c:'DFKai-SB'},{n:'微軟正黑體',c:'Microsoft JhengHei'},{n:'Arial'},{n:'Arial Narrow'},{n:'Arial Black'},{n:'Comic Sans MS'},{n:'Courier New'},{n:'System'},{n:'Times New Roman'},{n:'Tahoma'},{n:'Verdana'}];
var arrFontsize=[{n:'xx-small',wkn:'x-small',s:'8pt',t:'極小'},{n:'x-small',wkn:'small',s:'10pt',t:'特小'},{n:'small',wkn:'medium',s:'12pt',t:'小'},{n:'medium',wkn:'large',s:'14pt',t:'中'},{n:'large',wkn:'x-large',s:'18pt',t:'大'},{n:'x-large',wkn:'xx-large',s:'24pt',t:'特大'},{n:'xx-large',wkn:'-webkit-xxx-large',s:'36pt',t:'極大'}];
var menuAlign=[{s:'靠左對齊',v:'justifyleft'},{s:'置中',v:'justifycenter'},{s:'靠右對齊',v:'justifyright'},{s:'左右對齊',v:'justifyfull'}],menuList=[{s:'數字列表',v:'insertOrderedList'},{s:'符號列表',v:'insertUnorderedList'}];
var htmlPastetext='<div>使用鍵盤快捷鍵(Ctrl+V)把內容貼上到方框裡,按 確定</div><div><textarea id="xhePastetextValue" wrap="soft" spellcheck="false" style="width:300px;height:100px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlLink='<div>鏈接地址: <input type="text" id="xheLinkUrl" value="http://" class="xheText" /></div><div>打開方式: <select id="xheLinkTarget"><option selected="selected" value="">預設</option><option value="_blank">新窗口</option><option value="_self">當前窗口</option><option value="_parent">父窗口</option></select></div><div style="display:none">鏈接文字: <input type="text" id="xheLinkText" value="" class="xheText" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlImg='<div>圖片文件: <input type="text" id="xheImgUrl" value="http://" class="xheText" /></div><div>替換文本: <input type="text" id="xheImgAlt" /></div><div>對齊方式: <select id="xheImgAlign"><option selected="selected" value="">預設</option><option value="left">靠左對齊</option><option value="right">靠右對齊</option><option value="top">頂端</option><option value="middle">置中</option><option value="baseline">基線</option><option value="bottom">底邊</option></select></div><div>寬度高度: <input type="text" id="xheImgWidth" style="width:40px;" /> x <input type="text" id="xheImgHeight" style="width:40px;" /></div><div>邊框大小: <input type="text" id="xheImgBorder" style="width:40px;" /></div><div>水平間距: <input type="text" id="xheImgHspace" style="width:40px;" /> 垂直間距: <input type="text" id="xheImgVspace" style="width:40px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlFlash='<div>動畫文件: <input type="text" id="xheFlashUrl" value="http://" class="xheText" /></div><div>寬度高度: <input type="text" id="xheFlashWidth" style="width:40px;" value="480" /> x <input type="text" id="xheFlashHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlMedia='<div>媒體文件: <input type="text" id="xheMediaUrl" value="http://" class="xheText" /></div><div>寬度高度: <input type="text" id="xheMediaWidth" style="width:40px;" value="480" /> x <input type="text" id="xheMediaHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlTable='<div>行數列數: <input type="text" id="xheTableRows" style="width:40px;" value="3" /> x <input type="text" id="xheTableColumns" style="width:40px;" value="2" /></div><div>標題單元: <select id="xheTableHeaders"><option selected="selected" value="">無</option><option value="row">第一行</option><option value="col">第一列</option><option value="both">第一行和第一列</option></select></div><div>寬度高度: <input type="text" id="xheTableWidth" style="width:40px;" value="200" /> x <input type="text" id="xheTableHeight" style="width:40px;" value="" /></div><div>邊框大小: <input type="text" id="xheTableBorder" style="width:40px;" value="1" /></div><div>表格間距: <input type="text" id="xheTableCellSpacing" style="width:40px;" value="1" /> 表格填充: <input type="text" id="xheTableCellPadding" style="width:40px;" value="1" /></div><div>對齊方式: <select id="xheTableAlign"><option selected="selected" value="">預設</option><option value="left">靠左對齊</option><option value="center">置中</option><option value="right">靠右對齊</option></select></div><div>表格標題: <input type="text" id="xheTableCaption" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlAbout='<div style="font:12px Arial;width:245px;word-wrap:break-word;word-break:break-all;"><p><span style="font-size:20px;color:#1997DF;">xhEditor</span><br />v1.1.1 (build 101002)</p><p>xhEditor是基於jQuery開發的跨平台輕量XHTML編輯器,基於<a href="http://www.gnu.org/licenses/lgpl.html" target="_blank">LGPL</a>開源協議發佈。</p><p>Copyright c <a href="http://xheditor.com/" target="_blank">xhEditor.com</a>. All rights reserved.</p></div>';
var itemEmots={'default':{name:'預設',width:24,height:24,line:7,list:{'smile':'微笑','tongue':'吐舌頭','titter':'偷笑','laugh':'大笑','sad':'難過','wronged':'委屈','fastcry':'快哭了','cry':'哭','wail':'大哭','mad':'生氣','knock':'敲打','curse':'罵人','crazy':'抓狂','angry':'發火','ohmy':'驚訝','awkward':'尷尬','panic':'驚恐','shy':'害羞','cute':'可憐','envy':'羨慕','proud':'得意','struggle':'奮鬥','quiet':'安靜','shutup':'閉嘴','doubt':'疑問','despise':'鄙視','sleep':'睡覺','bye':'再見'}}};
var arrTools={Cut:{t:'剪下 (Ctrl+X)'},Copy:{t:'複製 (Ctrl+C)'},Paste:{t:'貼上 (Ctrl+V)'},Pastetext:{t:'貼上文本',h:isIE?0:1},Blocktag:{t:'段落標籤',h:1},Fontface:{t:'字型',h:1},FontSize:{t:'字型大小',h:1},Bold:{t:'粗體 (Ctrl+B)',s:'Ctrl+B'},Italic:{t:'斜體 (Ctrl+I)',s:'Ctrl+I'},Underline:{t:'底線 (Ctrl+U)',s:'Ctrl+U'},Strikethrough:{t:'刪除線 (Ctrl+S)',s:'Ctrl+S'},FontColor:{t:'字型顏色',h:1},BackColor:{t:'背景顏色',h:1},SelectAll:{t:'全選 (Ctrl+A)'},Removeformat:{t:'刪除文字格式'},Align:{t:'對齊',h:1},List:{t:'列表',h:1},Outdent:{t:'減少縮排 (Shift+Tab)',s:'Shift+Tab'},Indent:{t:'增加縮排 (Tab)',s:'Tab'},Link:{t:'超連結 (Ctrl+K)',s:'Ctrl+K',h:1},Unlink:{t:'取消超連結'},Img:{t:'圖片',h:1},Flash:{t:'Flash動畫',h:1},Media:{t:'多媒體文件',h:1},Emot:{t:'表情',s:'ctrl+e',h:1},Table:{t:'表格',h:1},Source:{t:'原始碼'},Preview:{t:'預覽'},Print:{t:'打印 (Ctrl+P)',s:'Ctrl+P'},Fullscreen:{t:'全螢幕編輯 (Esc)',s:'Esc'},About:{t:'關於 xhEditor'}};
var toolsThemes={
mini:'Bold,Italic,Underline,Strikethrough,|,Align,List,|,Link,Img',
simple:'Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,|,Align,List,Outdent,Indent,|,Link,Img,Emot',
full:'Cut,Copy,Paste,Pastetext,|,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,SelectAll,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Img,Flash,Media,Emot,Table,|,Source,Preview,Print,Fullscreen'};
toolsThemes.mfull=toolsThemes.full.replace(/\|(,Align)/i,'/$1');
var arrDbClick={'a':'Link','img':'Img','embed':'Embed'},uploadInputname='filedata';
$.xheditor=function(textarea,options)
{
var defaults={skin:'default',tools:'full',clickCancelDialog:true,linkTag:false,internalScript:false,inlineScript:false,internalStyle:true,inlineStyle:true,showBlocktag:false,forcePtag:true,upLinkExt:"zip,rar,txt",upImgExt:"jpg,jpeg,gif,png",upFlashExt:"swf",upMediaExt:"wmv,avi,wma,mp3,mid",modalWidth:350,modalHeight:220,modalTitle:true,defLinkText:'點擊打開鏈接',layerShadow:3,emotMark:false,upBtnText:'上傳',wordDeepClean:true,hoverExecDelay:100,html5Upload:true,upMultiple:99};
var _this=this,_text=textarea,_jText=$(_text),_jForm=_jText.closest('form'),_jTools,_jArea,_win,_jWin,_doc,_jDoc;
var bookmark;
var bInit=false,bSource=false,bFullscreen=false,bCleanPaste=false,outerScroll,bShowBlocktag=false,sLayoutStyle='',ev=null,timer,bDisableHoverExec=false,bQuickHoverExec=false;
var lastPoint=null,lastAngle=null;//鼠標懸停顯示
var editorHeight=0;
var settings=_this.settings=$.extend({},defaults,options );
var plugins=settings.plugins,strPlugins=[];
if(plugins)
{
arrTools=$.extend({},arrTools,plugins);
$.each(plugins,function(n){strPlugins.push(n);});
strPlugins=strPlugins.join(',');
}
if(settings.tools.match(/^\s*(m?full|simple|mini)\s*$/i))
{
var toolsTheme=toolsThemes[$.trim(settings.tools)];
settings.tools=(settings.tools.match(/m?full/i)&&plugins)?toolsTheme.replace('Table','Table,'+strPlugins):toolsTheme;//插件接在full的Table後面
}
if(!settings.tools.match(/(^|,)\s*About\s*(,|$)/i))settings.tools+=',About';
settings.tools=settings.tools.split(',');
if(settings.editorRoot)editorRoot=settings.editorRoot;
editorRoot=getLocalUrl(editorRoot,'abs');
//基本控件名
var idCSS='xheCSS_'+settings.skin,idContainer='xhe'+xCount+'_container',idTools='xhe'+xCount+'_Tool',idIframeArea='xhe'+xCount+'_iframearea',idIframe='xhe'+xCount+'_iframe',idFixFFCursor='xhe'+xCount+'_fixffcursor';
var headHTML='',bodyClass='',skinPath=editorRoot+'xheditor_skin/'+settings.skin+'/',arrEmots=itemEmots,urlType=settings.urlType,urlBase=settings.urlBase,emotPath=settings.emotPath,emotPath=emotPath?emotPath:editorRoot+'xheditor_emot/',selEmotGroup='';
arrEmots=$.extend({},arrEmots,settings.emots);
emotPath=getLocalUrl(emotPath,'rel',urlBase?urlBase:null);//返回最短表情路徑
bShowBlocktag=settings.showBlocktag;
if(bShowBlocktag)bodyClass+=' showBlocktag';
var arrShortCuts=[];
this.init=function()
{
//加載樣式表
if($('#'+idCSS).length==0)$('head').append('<link id="'+idCSS+'" rel="stylesheet" type="text/css" href="'+skinPath+'ui.css" />');
//初始化編輯器
var cw = settings.width || _text.style.width || _jText.outerWidth();
editorHeight = settings.height || _text.style.height || _jText.outerHeight();
if(is(editorHeight,'string'))editorHeight=editorHeight.replace(/[^\d]+/g,'');
if(cw<=0||editorHeight<=0)//禁止對隱藏區域裡的textarea初始化編輯器
{
alert('當前textarea處於隱藏狀態,請將之顯示後再初始化xhEditor,或者直接設置textarea的width和height樣式');
return false;
}
if(/^[0-9\.]+$/i.test(''+cw))cw+='px';
//編輯器CSS背景
var editorBackground=settings.background || _text.style.background;
//工具欄內容初始化
var arrToolsHtml=['<span class="xheGStart"/>'],tool,cn,regSeparator=/\||\//i;
$.each(settings.tools,function(i,n)
{
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGEnd"/>');
if(n=='|')arrToolsHtml.push('<span class="xheSeparator"/>');
else if(n=='/')arrToolsHtml.push('<br />');
else
{
tool=arrTools[n];
if(!tool)return;
if(tool.c)cn=tool.c;
else cn='xheIcon xheBtn'+n;
arrToolsHtml.push('<span><a href="javascript:void(0);" title="'+tool.t+'" name="'+n+'" class="xheButton xheEnabled" tabindex="-1"><span class="'+cn+'" unselectable="on" /></a></span>');
if(tool.s)_this.addShortcuts(tool.s,n);
}
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGStart"/>');
});
arrToolsHtml.push('<span class="xheGEnd"/><br />');
_jText.after($('<input type="text" id="'+idFixFFCursor+'" style="position:absolute;display:none;" /><span id="'+idContainer+'" class="xhe_'+settings.skin+'" style="display:none"><table cellspacing="0" cellpadding="0" class="xheLayout" style="width:'+cw+';height:'+editorHeight+'px;"><tbody><tr><td id="'+idTools+'" class="xheTool" unselectable="on" style="height:1px;"></td></tr><tr><td id="'+idIframeArea+'" class="xheIframeArea"><iframe frameborder="0" id="'+idIframe+'" src="javascript:;" style="width:100%;"></iframe></td></tr></tbody></table></span>'));
_jTools=$('#'+idTools);_jArea=$('#'+idIframeArea);
headHTML='<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><link rel="stylesheet" href="'+skinPath+'iframe.css"/>';
var loadCSS=settings.loadCSS;
if(loadCSS)
{
if(is(loadCSS,'array'))for(var i in loadCSS)headHTML+='<link rel="stylesheet" href="'+loadCSS[i]+'"/>';
else
{
if(loadCSS.match(/\s*<style(\s+[^>]*?)?>[\s\S]+?<\/style>\s*/i))headHTML+=loadCSS;
else headHTML+='<link rel="stylesheet" href="'+loadCSS+'"/>';
}
}
var iframeHTML='<html><head>'+headHTML;
if(editorBackground)iframeHTML+='<style>body{background:'+editorBackground+';}</style>';
iframeHTML+='</head><body spellcheck="false" class="editMode'+bodyClass+'"></body></html>';
_this.win=_win=$('#'+idIframe)[0].contentWindow;
_jWin=$(_win);
try{
this.doc=_doc = _win.document;_jDoc=$(_doc);
_doc.open();
_doc.write(iframeHTML);
_doc.close();
if(isIE)_doc.body.contentEditable='true';
else _doc.designMode = 'On';
}catch(e){}
setTimeout(setOpts,300);
_this.setSource();
_win.setInterval=null;//針對jquery 1.3無法操作iframe window問題的hack
//添加工具欄
_jTools.append(arrToolsHtml.join('')).bind('mousedown contextmenu',returnFalse).click(function(event)
{
var jButton=$(event.target).closest('a');
if(jButton.is('.xheEnabled'))
{
ev=event;
_this.exec(jButton.attr('name'));
}
return false;
});
_jTools.find('.xheButton').hover(function(event){//鼠標懸停執行
var jButton=$(this),delay=settings.hoverExecDelay;
var tAngle=lastAngle;lastAngle=null;
if(delay==-1||bDisableHoverExec||!jButton.is('.xheEnabled'))return false;
if(tAngle&&tAngle>10)//檢測誤操作
{
bDisableHoverExec=true;
setTimeout(function(){bDisableHoverExec=false;},100);
return false;
}
var cmd=jButton.attr('name'),bHover=arrTools[cmd].h==1;
if(!bHover)
{
_this.hidePanel();//移到非懸停按鈕上隱藏面板
return false;
}
if(bQuickHoverExec)delay=0;
if(delay>=0)timer=setTimeout(function(){
ev=event;
lastPoint={x:ev.clientX,y:ev.clientY};
_this.exec(cmd);
},delay);
},function(event){lastPoint=null;if(timer)clearTimeout(timer);}).mousemove(function(event){
if(lastPoint)
{
var diff={x:event.clientX-lastPoint.x,y:event.clientY-lastPoint.y};
if(Math.abs(diff.x)>1||Math.abs(diff.y)>1)
{
if(diff.x>0&&diff.y>0)
{
var tAngle=Math.round(Math.atan(diff.y/diff.x)/0.017453293);
if(lastAngle)lastAngle=(lastAngle+tAngle)/2
else lastAngle=tAngle;
}
else lastAngle=null;
lastPoint={x:event.clientX,y:event.clientY};
}
}
});
//初始化面板
_jPanel=$('#xhePanel');
_jShadow=$('#xheShadow');
_jCntLine=$('#xheCntLine');
if(_jPanel.length==0)
{
_jPanel=$('<div id="xhePanel"></div>').mousedown(function(ev){ev.stopPropagation()});
_jShadow=$('<div id="xheShadow"></div>');
_jCntLine=$('<div id="xheCntLine"></div>');
setTimeout(function(){
$(document.body).append(_jPanel).append(_jShadow).append(_jCntLine);
},10);
}
//切換顯示區域
$('#'+idContainer).show();
_jText.hide();
_jArea.css('height',editorHeight-_jTools.outerHeight());
//綁定內核事件
_jText.focus(_this.focus);
_jForm.submit(saveResult).bind('reset', loadReset);
$(window).bind('unload beforeunload',saveResult).bind('resize',fixFullHeight);
$(document).mousedown(clickCancelPanel);
if(!bCheckEscInit){$(document).keydown(checkEsc);bCheckEscInit=true;}
_jWin.focus(function(){if(settings.focus)settings.focus();}).blur(function(){if(settings.blur)settings.blur();});
if(isSafari)_jWin.click(fixAppleSel);
_jDoc.mousedown(clickCancelPanel).keydown(checkShortcuts).keypress(forcePtag).dblclick(checkDblClick).bind('mousedown click',function(ev){_jText.trigger(ev.type);});
if(isIE)
{
//IE控件上Backspace會導致頁面後退
_jDoc.keydown(function(ev){var rng=_this.getRng();if(ev.which==8&&rng.item){$(rng.item(0)).remove();return false;}});
//修正IE拖動img大小不更新width和height屬性值的問題
function fixResize(ev)
{
var jImg=$(ev.target),v;
if(v=jImg.css('width'))jImg.css('width','').attr('width',v.replace(/[^0-9%]+/g, ''));
if(v=jImg.css('height'))jImg.css('height','').attr('height',v.replace(/[^0-9%]+/g, ''));
}
_jDoc.bind('controlselect',function(ev){
ev=ev.target;if(!$.nodeName(ev,'IMG'))return;
$(ev).unbind('resizeend',fixResize).bind('resizeend',fixResize);
});
}
var jBody=$(_doc.documentElement);
jBody.bind('paste',cleanPaste);
if(settings.disableContextmenu)jBody.bind('contextmenu',returnFalse);
//HTML5編輯區域直接拖放上傳
if(settings.html5Upload)jBody.bind('dragenter dragover',function(ev){var types;if((types=ev.originalEvent.dataTransfer.types)&&$.inArray('Files', types)!=-1)return false;}).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0){
var i,cmd,arrCmd=['Link','Img','Flash','Media'],arrExt=[],strExt;
for(i in arrCmd){
cmd=arrCmd[i];
if(settings['up'+cmd+'Url']&&settings['up'+cmd+'Url'].match(/^[^!].*/i))arrExt.push(cmd+':,'+settings['up'+cmd+'Ext']);//允許上傳
}
if(arrExt.length==0)return false;//禁止上傳
else strExt=arrExt.join(',');
function getCmd(fileList){
var match,fileExt,cmd;
for(i=0;i<fileList.length;i++){
fileExt=fileList[i].fileName.replace(/.+\./,'');
if(match=strExt.match(new RegExp('(\\w+):[^:]*,'+fileExt+'(?:,|$)','i'))){
if(!cmd)cmd=match[1];
else if(cmd!=match[1])return 2;
}
else return 1;
}
return cmd;
}
cmd=getCmd(fileList);
if(cmd==1)alert('上傳文件的擴展名必需為:'+strExt.replace(/\w+:,/g,''));
else if(cmd==2)alert('每次只能拖放上傳同一類型文件');
else if(cmd){
_this.startUpload(fileList,settings['up'+cmd+'Url'],'*',function(arrMsg){
var arrUrl=[],msg,onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用戶上傳回調
for(i in arrMsg){
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!')url=url.substr(1);
arrUrl.push(url);
}
_this.exec(cmd);
$('#xhe'+cmd+'Url').val(arrUrl.join(' '));
$('#xheSave').click();
});
}
return false;
}
});
//添加用戶快捷鍵
var shortcuts=settings.shortcuts;
if(shortcuts)$.each(shortcuts,function(key,func){_this.addShortcuts(key,func);});
xCount++;
bInit=true;
if(settings.fullscreen)_this.toggleFullscreen();
else if(settings.sourceMode)setTimeout(_this.toggleSource,20);
return true;
}
this.remove=function()
{
_this.hidePanel();
saveResult();//卸載前同步最新內容到textarea
//取消綁定事件
_jText.unbind('focus',_this.focus);
_jForm.unbind('submit',saveResult).unbind('reset', loadReset);
$(window).unbind('unload beforeunload',saveResult).unbind('resize',fixFullHeight);
$(document).unbind('mousedown',clickCancelPanel);
$('#'+idContainer+','+'#'+idFixFFCursor).remove();
_jText.show();
bInit=false;
}
this.saveBookmark=function(){
if(!bSource){
var rng=_this.getRng();
rng=rng.cloneRange?rng.cloneRange():rng;
bookmark={'top':_jWin.scrollTop(),'rng':rng};
}
}
this.loadBookmark=function()
{
if(bSource||!bookmark)return;
_this.focus();
var rng=bookmark.rng;
if(isIE)rng.select();
else
{
var sel=_this.getSel();
sel.removeAllRanges();
sel.addRange(rng);
}
_jWin.scrollTop(bookmark.top);
bookmark=null;
}
this.focus=function()
{
if(!bSource)_jWin.focus();
else $('#sourceCode',_doc).focus();
return false;
}
this.setCursorFirst=function(firstBlock)
{
_this.focus();_win.scrollTo(0,0);
var rng=_this.getRng(),_body=_doc.body,firstNode=_body,firstTag;
if(firstBlock&&firstNode.firstChild&&(firstTag=firstNode.firstChild.tagName)&&firstTag.match(/^p|div|h[1-6]$/i))firstNode=_body.firstChild;
isIE?rng.moveToElementText(firstNode):rng.setStart(firstNode,0);
rng.collapse(true);
if(isIE)rng.select();
else{var sel=_this.getSel();sel.removeAllRanges();sel.addRange(rng);}
}
this.getSel=function()
{
return _win.getSelection ? _win.getSelection() : _doc.selection;
}
this.getRng=function()
{
var sel=_this.getSel(),rng;
try{
rng = sel.rangeCount > 0 ? sel.getRangeAt(0) : (sel.createRange ? sel.createRange() : (_doc.createRange?_doc.createRange():_doc.body.createTextRange()));
}catch (ex){}
return rng;
}
this.getParent=function(tag)
{
var rng=_this.getRng(),p;
if(!isIE)
{
p = rng.commonAncestorContainer;
if(!rng.collapsed)if(rng.startContainer == rng.endContainer&&rng.startOffset - rng.endOffset < 2&&rng.startContainer.hasChildNodes())p = rng.startContainer.childNodes[rng.startOffset];
}
else p=rng.item?rng.item(0):rng.parentElement();
tag=tag?tag:'*';p=$(p);
if(!p.is(tag))p=$(p).closest(tag);
return p;
}
this.getSelect=function(format)
{
var sel=_this.getSel(),rng=_this.getRng(),isCollapsed=true;
if (!rng || rng.item)isCollapsed=false
else isCollapsed=!sel || rng.boundingWidth == 0 || rng.collapsed;
if(format=='text')return isCollapsed ? '' : (rng.text || (sel.toString ? sel.toString() : ''));
var sHtml;
if(rng.cloneContents)
{
var tmp=$('<div></div>'),c;
c = rng.cloneContents();
if(c)tmp.append(c);
sHtml=tmp.html();
}
else if(is(rng.item))sHtml=rng.item(0).outerHTML;
else if(is(rng.htmlText))sHtml=rng.htmlText;
else sHtml=rng.toString();
if(isCollapsed)sHtml='';
sHtml=_this.processHTML(sHtml,'read');
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
return sHtml;
}
this.pasteHTML=function(sHtml,bStart)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
var sel=_this.getSel(),rng=_this.getRng();
if(bStart!=undefined)//非覆蓋式插入
{
if(rng.item)
{
var n=rng.item(0);
rng=_doc.body.createTextRange();
rng.moveToElementText(n);
rng.select();
}
rng.collapse(bStart);
}
sHtml+='<'+(isIE?'img':'span')+' id="_xhe_temp" style="display:none" />';
if(rng.insertNode)
{
rng.deleteContents();
rng.insertNode(rng.createContextualFragment(sHtml));
}
else
{
if(sel.type.toLowerCase()=='control'){sel.clear();rng=_this.getRng();};
rng.pasteHTML(sHtml);
}
var jTemp=$('#_xhe_temp',_doc),temp=jTemp[0];
if(isIE)
{
rng.moveToElementText(temp);
rng.select();
}
else
{
rng.selectNode(temp);
sel.removeAllRanges();
sel.addRange(rng);
}
jTemp.remove();
}
this.pasteText=function(text,bStart)
{
if(!text)text='';
text=_this.domEncode(text);
text = text.replace(/\r?\n/g, '<br />');
_this.pasteHTML(text,bStart);
}
this.appendHTML=function(sHtml)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
$(_doc.body).append(sHtml);
}
this.domEncode=function(str)
{
return str.replace(/[<>]/g,function(c){return {'<':'<','>':'>'}[c];});
}
this.setSource=function(sHtml)
{
bookmark=null;
if(typeof sHtml!='string'&&sHtml!='')sHtml=_text.value;
if(bSource)$('#sourceCode',_doc).val(sHtml);
else
{
if(settings.beforeSetSource)sHtml=settings.beforeSetSource(sHtml);
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
sHtml=_this.cleanWord(sHtml);
sHtml=_this.processHTML(sHtml,'write');
if(isIE){//修正IE會刪除可視內容前的script,style,<!--
_doc.body.innerHTML='<img id="_xhe_temp" style="display:none" />'+sHtml;
$('#_xhe_temp',_doc).remove();
}
else _doc.body.innerHTML=sHtml;
}
}
this.processHTML=function(sHtml,mode)
{
var appleClass=' class="Apple-style-span"';
if(mode=='write')
{//write
//恢復emot
function restoreEmot(all,attr,q,emot)
{
emot=emot.split(',');
if(!emot[1]){emot[1]=emot[0];emot[0]=''}
if(emot[0]=='default')emot[0]='';
return all.replace(/\s+src\s*=\s*(["']?).*?\1(\s|$|\/|>)/i,'$2').replace(attr,' src="'+emotPath+(emot[0]?emot[0]:'default')+'/'+emot[1]+'.gif"'+(settings.emotMark?' emot="'+(emot[0]?emot[0]+',':'')+emot[1]+'"'+(all.match(/\s+alt\s*=\s*(["']?)\s*(.*?)\s*\1[\s\/>]/i)?'':' alt="'+emot[1]+'"'):''));
}
sHtml = sHtml.replace(/<img(?:\s+[^>]*?)?(\s+emot\s*=\s*(["']?)\s*(.*?)\s*\2)(?:\s+[^>]*?)?\/?>/ig,restoreEmot);
//保存屬性值:src,href
function saveValue(all,tag,attr,n,q,v){return all.replace(attr,(urlBase?(' '+n+'="'+getLocalUrl(v,'abs',urlBase)+'"'):attr)+' _xhe_'+n+'="'+v+'"');}
sHtml = sHtml.replace(/<(\w+(?:\:\w+)?)(?:\s+[^>]*?)?(\s+(src|href)\s*=\s*(["']?)\s*(.*?)\s*\4)(?:\s+[^>]*?)?\/?>/ig,saveValue);
sHtml = sHtml.replace(/<(\/?)del(\s+[^>]*?)?>/ig,'<$1strike$2>');//編輯狀態統一轉為strike
if(isMozilla)
{
sHtml = sHtml.replace(/<(\/?)strong(\s+[^>]*?)?>/ig,'<$1b$2>');
sHtml = sHtml.replace(/<(\/?)em(\s+[^>]*?)?>/ig,'<$1i$2>');
}
else if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.n){s=t.wkn;break;}
}
return pre+'font-size:'+s+aft;
});
sHtml = sHtml.replace(/<strong(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-weight: bold;"$1>');
sHtml = sHtml.replace(/<em(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-style: italic;"$1>');
sHtml = sHtml.replace(/<u(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: underline;"$1>');
sHtml = sHtml.replace(/<strike(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: line-through;"$1>');
sHtml = sHtml.replace(/<\/(strong|em|u|strike)>/ig,'</span>');
sHtml = sHtml.replace(/<span((?:\s+[^>]*?)?\s+style="([^"]*;)*\s*(font-family|font-size|color|background-color)\s*:\s*[^;"]+\s*;?"[^>]*)>/ig,'<span'+appleClass+'$1>');
}
else if(isIE)
{
sHtml = sHtml.replace(/'/ig, ''');
sHtml = sHtml.replace(/\s+(disabled|checked|readonly|selected)\s*=\s*[\"\']?(false|0)[\"\']?/ig, '');
}
sHtml = sHtml.replace(/<a(\s+[^>]*?)?\/>/,'<a$1></a>');
if(!isSafari)
{
//style轉font
function style2font(all,tag,style,content)
{
var attrs='',f,s1,s2,c;
f=style.match(/font-family\s*:\s*([^;"]+)/i);
if(f)attrs+=' face="'+f[1]+'"';
s1=style.match(/font-size\s*:\s*([^;"]+)/i);
if(s1)
{
s1=s1[1].toLowerCase();
for(var j=0;j<arrFontsize.length;j++)if(s1==arrFontsize[j].n||s1==arrFontsize[j].s){s2=j+1;break;}
if(s2)
{
attrs+=' size="'+s2+'"';
style=style.replace(/(^|;)(\s*font-size\s*:\s*[^;"]+;?)+/ig,'$1');
}
}
c=style.match(/(?:^|[\s;])color\s*:\s*([^;"]+)/i);
if(c)
{
var rgb;
if(rgb=c[1].match(/\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)){c[1]='#';for(var i=1;i<=3;i++)c[1]+=(rgb[i]-0).toString(16);}
c[1]=c[1].replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,'#$1$1$2$2$3$3');
attrs+=' color="'+c[1]+'"';
}
style=style.replace(/(^|;)(\s*(font-family|color)\s*:\s*[^;"]+;?)+/ig,'$1');
if(attrs!='')
{
if(style)attrs+=' style="'+style+'"';
return '<font'+attrs+'>'+content+"</font>";
}
else return all;
}
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,style2font);//最裡層
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,style2font);//第2層
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,style2font);//第3層
}
}
else
{//read
//恢復屬性值src,href
function restoreValue(all,n,q,v)
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
return all.replace(new RegExp('\\s+'+n+'\\s*=\\s*(["\']?).*?\\1(\\s|/?>)','ig'),' '+n+'="'+v.replace(/\$/g,'$$$$')+'"$2');
}
sHtml = sHtml.replace(/<(?:\w+(?:\:\w+)?)(?:\s+[^>]*?)?\s+_xhe_(src|href)\s*=\s*(["']?)\s*(.*?)\s*\2(?:\s+[^>]*?)?\/?>/ig,restoreValue);
if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.wkn){s=t.n;break;}
}
return pre+'font-size:'+s+aft;
});
var arrAppleSpan=[{r:/font-weight:\sbold/ig,t:'strong'},{r:/font-style:\sitalic/ig,t:'em'},{r:/text-decoration:\sunderline/ig,t:'u'},{r:/text-decoration:\sline-through/ig,t:'strike'}];
function replaceAppleSpan(all,tag,attr1,attr2,content)
{
var attr=attr1+attr2,newTag='';
if(!attr)return content;
for(var i=0;i<arrAppleSpan.length;i++)
{
if(attr.match(arrAppleSpan[i].r))
{
newTag=arrAppleSpan[i].t;
break;
}
}
if(newTag)return '<'+newTag+'>'+content+'</'+newTag+'>';
else return all;
}
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,replaceAppleSpan);//最裡層
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第2層
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第3層
}
if(!isIE){//字符間的文本換行強制轉br
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/([^<>\r\n]?)((?:\r?\n)+)([^<>\r\n]?)/ig,function(all,left,br,right){if(left||right)return left+br.replace(/\r?\n/g,'<br />')+right;else return all;});
});
}
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+(?:_xhe_|_moz_|_webkit_)[^=]+?\s*=\s*(["']?).*?\2(\s|\/?>)/ig,'$1$3');
sHtml = sHtml.replace(/(<\w+[^>]*?)\s+class\s*=\s*(["']?)\s*(?:apple|webkit)\-.+?\s*\2(\s|\/?>)/ig, "$1$3");
sHtml = sHtml.replace(/<img(\s+[^>]+?)\/?>/ig,function(all,attr){if(!attr.match(/\s+alt\s*(["']?).*?\1(\s|$)/i))attr+=' alt=""';return '<img'+attr+' />';});//img強制加alt
sHtml = sHtml.replace(/\s+jquery\d+="\d+"/ig,'');
}
return sHtml;
}
this.getSource=function(bFormat)
{
var sHtml,beforeGetSource=settings.beforeGetSource;
if(bSource)
{
sHtml=$('#sourceCode',_doc).val();
if(!beforeGetSource){
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/(\t*\r?\n\t*)+/g,'')//標準HTML模式清理縮排和換行
});
}
}
else
{
sHtml=_this.processHTML(_doc.body.innerHTML,'read');
sHtml=sHtml.replace(/^\s*(?:<(p|div)(?:\s+[^>]*?)?>)?\s*(<br(?:\s+[^>]*?)?>)*\s*(?:<\/\1>)?\s*$/i, '');//修正Firefox在空內容情況下多出來的代碼
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml,bFormat);
sHtml=_this.cleanWord(sHtml);
if(beforeGetSource)sHtml=beforeGetSource(sHtml);
}
_text.value=sHtml;
return sHtml;
}
this.cleanWord=function(sHtml)
{
if(sHtml.match(/mso(-|normal)|WordDocument/i))
{
var deepClean=settings.wordDeepClean;
//格式化
sHtml = sHtml.replace(/(<link(?:\s+[^>]*?)?)\s+href\s*=\s*(["']?)\s*file:\/\/.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, '');
//區塊標籤清理
sHtml = sHtml.replace(/<!--[\s\S]*?-->|<!(--)?\[[\s\S]+?\](--)?>|<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
sHtml = sHtml.replace(/<\/?\w+:[^>]*>/ig, '');
if(deepClean)sHtml = sHtml.replace(/<\/?(span|a|img)(\s+[^>]*?)?>/ig,'');
//屬性清理
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+class\s*=\s*(["']?)\s*mso.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//刪除所有mso開頭的樣式
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+lang\s*=\s*(["']?)\s*.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//刪除lang屬性
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+align\s*=\s*(["']?)\s*left\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//取消align=left
//樣式清理
sHtml = sHtml.replace(/<\w+(?:\s+[^>]*?)?(\s+style\s*=\s*(["']?)\s*([\s\S]*?)\s*\2)(?:\s+[^>]*?)?\s*\/?>/ig,function(all,attr,p,styles){
styles=$.trim(styles.replace(/\s*(mso-[^:]+:.+?|margin\s*:\s*0cm 0cm 0pt\s*|(text-align|font-variant|line-height)\s*:\s*.+?)(;|$)\s*/ig,''));
return all.replace(attr,deepClean?'':styles?' style="'+styles+'"':'');
});
}
return sHtml;
}
this.cleanHTML=function(sHtml)
{
sHtml = sHtml.replace(/<!?\/?(DOCTYPE|html|body|meta)(\s+[^>]*?)?>/ig, '');
var arrHeadSave;sHtml = sHtml.replace(/<head(?:\s+[^>]*?)?>([\s\S]*?)<\/head>/i, function(all,content){arrHeadSave=content.match(/<(script|style)(\s+[^>]*?)?>[\s\S]*?<\/\1>/ig);return '';});
if(arrHeadSave)sHtml=arrHeadSave.join('')+sHtml;
sHtml = sHtml.replace(/<\??xml(:\w+)?(\s+[^>]*?)?>([\s\S]*?<\/xml>)?/ig, '');
if(!settings.linkTag)sHtml = sHtml.replace(/<link(\s+[^>]*?)?>/ig, '');
if(!settings.internalScript)sHtml = sHtml.replace(/<script(\s+[^>]*?)?>[\s\S]*?<\/script>/ig, '');
if(!settings.inlineScript)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+on(?:click|dblclick|mousedown|mouseup|mousemove|mouseover|mouseout|mouseenter|mouseleave|keydown|keypress|keyup|change|select|submit|reset|blur|focus|load|unload)\s*=\s*(["']?)[\s\S]*?\3((?:\s+[^>]*?)?\/?>)/ig,'$1$2$4');
if(!settings.internalStyle)sHtml = sHtml.replace(/<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
if(!settings.inlineStyle)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+(style|class)\s*=\s*(["']?)[\s\S]*?\4((?:\s+[^>]*?)?\/?>)/ig,'$1$2$5');
sHtml=sHtml.replace(/<\/(strong|b|u|strike|em|i)>((?:\s|<br\/?>| )*?)<\1(\s+[^>]*?)?>/ig,'$2');//連續相同標籤
return sHtml;
}
this.formatXHTML=function(sHtml,bFormat)
{
var emptyTags = makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");//HTML 4.01
var blockTags = makeMap("address,applet,blockquote,button,center,dd,dir,div,dl,dt,fieldset,form,frameset,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");//HTML 4.01
var inlineTags = makeMap("a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");//HTML 4.01
var closeSelfTags = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
var fillAttrsTags = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
var specialTags = makeMap("script,style");
var tagReplac={'b':'strong','i':'em','s':'del','strike':'del'};
var startTag = /^<\??(\w+(?:\:\w+)?)((?:\s+[\w-\:]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/(\w+(?:\:\w+)?)[^>]*>/;
var attr = /\s+([\w-]+(?:\:\w+)?)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s]+)))?/g;
var skip=0,stack=[],last=sHtml,results=Array(),lvl=-1,lastTag='body',lastTagStart;
stack.last = function(){return this[ this.length - 1 ];};
while(last.length>0)
{
if(!stack.last()||!specialTags[stack.last()])
{
skip=0;
if(last.substring(0, 4)=='<!--')
{//註釋標籤
skip=last.indexOf("-->");
if(skip!=-1)
{
skip+=3;
addHtmlFrag(last.substring(0,skip));
}
}
else if(last.substring(0, 2)=='</')
{//結束標籤
match = last.match( endTag );
if(match)
{
parseEndTag(match[1]);
skip = match[0].length;
}
}
else if(last.charAt(0)=='<')
{//開始標籤
match = last.match( startTag );
if(match)
{
parseStartTag(match[1],match[2],match[3]);
skip = match[0].length;
}
}
if(skip==0)//普通文本
{
skip=last.indexOf('<');
if(skip==0)skip=1;
else if(skip<0)skip=last.length;
addHtmlFrag(_this.domEncode(last.substring(0,skip)));
}
last=last.substring(skip);
}
else
{//處理style和script
last=last.replace(/^([\s\S]*?)<\/(style|script)>/i, function(all, script,tagName){
results.push(script);
return ''
});
parseEndTag(stack.last());
}
}
parseEndTag();
sHtml=results.join('');
results=null;
function makeMap(str)
{
var obj = {}, items = str.split(",");
for ( var i = 0; i < items.length; i++ )obj[ items[i] ] = true;
return obj;
}
function processTag(tagName)
{
if(tagName)
{
tagName=tagName.toLowerCase();
var tag=tagReplac[tagName];
if(tag)tagName=tag;
}
else tagName='';
return tagName;
}
function parseStartTag(tagName,rest,unary)
{
tagName=processTag(tagName);
if(blockTags[tagName])while(stack.last()&&inlineTags[stack.last()])parseEndTag(stack.last());
if(closeSelfTags[tagName]&&stack.last()==tagName)parseEndTag(tagName);
unary = emptyTags[ tagName ] || !!unary;
if (!unary)stack.push(tagName);
var all=Array();
all.push('<' + tagName);
rest.replace(attr, function(match, name)
{
name=name.toLowerCase();
var value = arguments[2] ? arguments[2] :
arguments[3] ? arguments[3] :
arguments[4] ? arguments[4] :
fillAttrsTags[name] ? name : "";
all.push(' '+name+'="'+value+'"');
});
all.push((unary ? " /" : "") + ">");
addHtmlFrag(all.join(''),tagName,true);
}
function parseEndTag(tagName)
{
if(!tagName)var pos=0;//清空棧
else
{
tagName=processTag(tagName);
for(var pos=stack.length-1;pos>=0;pos--)if(stack[pos]==tagName)break;//向上尋找匹配的開始標籤
}
if(pos>=0)
{
for(var i=stack.length-1;i>=pos;i--)addHtmlFrag("</" + stack[i] + ">",stack[i]);
stack.length=pos;
}
}
function addHtmlFrag(html,tagName,bStart)
{
if(bFormat==true)
{
html=html.replace(/(\t*\r?\n\t*)+/g,'');//清理換行符和相鄰的製表符
if(html.match(/^\s*$/))return;//不格式化空內容的標籤
var bBlock=blockTags[tagName],tag=bBlock?tagName:'';
if(bBlock)
{
if(bStart)lvl++;//塊開始
if(lastTag=='')lvl--;//補文本結束
}
else if(lastTag)lvl++;//文本開始
if(tag!=lastTag||bBlock)addIndent();
results.push(html);
if(tagName=='br')addIndent();//回車強制換行
if(bBlock&&(emptyTags[tagName]||!bStart))lvl--;//塊結束
lastTag=bBlock?tagName:'';lastTagStart=bStart;
}
else results.push(html);
}
function addIndent(){results.push('\r\n');if(lvl>0){var tabs=lvl;while(tabs--)results.push("\t");}}
//font轉style
function font2style(all,tag,attrs,content)
{
if(!attrs)return content;
var styles='',f,s,c,style;
f=attrs.match(/ face\s*=\s*"\s*([^"]+)\s*"/i);
if(f)styles+='font-family:'+f[1]+';';
s=attrs.match(/ size\s*=\s*"\s*(\d+)\s*"/i);
if(s)styles+='font-size:'+arrFontsize[(s[1]>7?7:(s[1]<1?1:s[1]))-1].n+';';
c=attrs.match(/ color\s*=\s*"\s*([^"]+)\s*"/i);
if(c)styles+='color:'+c[1]+';';
style=attrs.match(/ style\s*=\s*"\s*([^"]+)\s*"/i);
if(style)styles+=style[1];
if(styles)content='<span style="'+styles+'">'+content+'</span>';
return content;
}
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,font2style);//最裡層
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,font2style);//第2層
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,font2style);//第3層
sHtml = sHtml.replace(/^(\s*\r?\n)+|(\s*\r?\n)+$/g,'');//清理首尾換行
sHtml = sHtml.replace(/(\t*\r?\n)+/g,'\r\n');//多行變一行
return sHtml;
}
this.toggleShowBlocktag=function(state)
{
if(bShowBlocktag===state)return;
bShowBlocktag=!bShowBlocktag;
var _jBody=$(_doc.body);
if(bShowBlocktag)
{
bodyClass+=' showBlocktag';
_jBody.addClass('showBlocktag');
}
else
{
bodyClass=bodyClass.replace(' showBlocktag','');
_jBody.removeClass('showBlocktag');
}
}
this.toggleSource=function(state)
{
if(bSource===state)return;
_jTools.find('[name=Source]').toggleClass('xheEnabled').toggleClass('xheActive');
var _body=_doc.body,jBody=$(_body),sHtml;
var sourceCode,cursorMark='<span id="_xhe_cursor'+new Date().getTime()+'"></span>',cursorPos=0;
if(!bSource)
{//轉為原始碼模式
_this.pasteHTML(cursorMark,true);//標記當前位置
sHtml=_this.getSource(true);
cursorPos=sHtml.indexOf(cursorMark);
if(!isOpera)cursorPos=sHtml.substring(0,cursorPos).replace(/\r/g,'').length;//修正非opera光標定位點
sHtml=sHtml.replace(cursorMark,'');
if(isIE)_body.contentEditable='false';
else _doc.designMode = 'Off';
jBody.attr('scroll','no').attr('class','sourceMode').html('<textarea id="sourceCode" wrap="soft" spellcheck="false" height="100%" />');
sourceCode=$('#sourceCode',jBody).blur(_this.getSource)[0];
}
else
{//轉為編輯模式
sHtml=_this.getSource();
jBody.html('').removeAttr('scroll').attr('class','editMode'+bodyClass);
if(isIE)_body.contentEditable='true';
else _doc.designMode = 'On';
if(isMozilla)
{
_this._exec("inserthtml","-");//修正firefox原始碼切換回來無法刪除文字的問題
$('#'+idFixFFCursor).show().focus().hide();//臨時修正Firefox 3.6光標丟失問題
}
}
bSource=!bSource;
_this.setSource(sHtml);
if(bSource)//光標定位源碼
{
_this.focus();
if(sourceCode.setSelectionRange)sourceCode.setSelectionRange(cursorPos, cursorPos);
else
{
var rng = sourceCode.createTextRange();
rng.move("character",cursorPos);
rng.select();
}
}
else _this.setCursorFirst(true);//定位最前面
_jTools.find('[name=Source],[name=Preview]').toggleClass('xheEnabled');
_jTools.find('.xheButton').not('[name=Source],[name=Fullscreen],[name=About]').toggleClass('xheEnabled');
setTimeout(setOpts,300);
}
this.showPreview=function()
{
var beforeSetSource=settings.beforeSetSource,sContent=_this.getSource();
if(beforeSetSource)sContent=beforeSetSource(sContent);
var sHTML='<html><head>'+headHTML+'<title>預覽</title>'+(urlBase?'<base href="'+urlBase+'"/>':'')+'</head><body>' + sContent + '</body></html>';
var screen=window.screen,oWindow=window.open('', 'xhePreview', 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+Math.round(screen.width*0.9)+',height='+Math.round(screen.height*0.8)+',left='+Math.round(screen.width*0.05)),oDoc=oWindow.document;
oDoc.open();
oDoc.write(sHTML);
oDoc.close();
oWindow.focus();
}
this.toggleFullscreen=function(state)
{
if(bFullscreen===state)return;
var jLayout=$('#'+idContainer).find('.xheLayout'),jContainer=$('#'+idContainer);
if(bFullscreen)
{//取消全屏
jLayout.attr('style',sLayoutStyle);
_jArea.height(editorHeight-_jTools.outerHeight());
setTimeout(function(){$(window).scrollTop(outerScroll);},10);
}
else
{//顯示全屏
outerScroll=$(window).scrollTop();
sLayoutStyle=jLayout.attr('style');
jLayout.removeAttr('style');
_jArea.height('100%');
setTimeout(fixFullHeight,100);
}
if(isMozilla)//臨時修正Firefox 3.6原始碼光標丟失問題
{
$('#'+idFixFFCursor).show().focus().hide();
setTimeout(_this.focus,1);
}
bFullscreen=!bFullscreen;
jContainer.toggleClass('xhe_Fullscreen');
$('html').toggleClass('xhe_Fullfix');
_jTools.find('[name=Fullscreen]').toggleClass('xheActive');
setTimeout(setOpts,300);
}
this.showMenu=function(menuitems,callback)
{
var jMenu=$('<div class="xheMenu"></div>'),arrItem=[];
$.each(menuitems,function(n,v){arrItem.push('<a href="javascript:void(0);" title="'+(v.t?v.t:v.s)+'" v="'+v.v+'">'+v.s+'</a>');});
jMenu.append(arrItem.join(''));
jMenu.click(function(ev){callback($(ev.target).closest('a').attr('v'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jMenu);
}
this.showColor=function(callback)
{
var jColor=$('<div class="xheColor"></div>'),arrItem=[],count=0;
$.each(itemColors,function(n,v)
{
if(count%7==0)arrItem.push((count>0?'</div>':'')+'<div>');
arrItem.push('<a href="javascript:void(0);" xhev="'+v+'" title="'+v+'" style="background:'+v+'"></a>');
count++;
});
arrItem.push('</div>');
jColor.append(arrItem.join(''));
jColor.click(function(ev){ev=ev.target;if(!$.nodeName(ev,'A'))return;callback($(ev).attr('xhev'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jColor);
}
this.showPastetext=function()
{
var jPastetext=$(htmlPastetext),jValue=$('#xhePastetextValue',jPastetext),jSave=$('#xheSave',jPastetext);
jSave.click(function(){
_this.loadBookmark();
var sValue=jValue.val();
if(sValue)_this.pasteText(sValue);
_this.hidePanel();
return false;
});
_this.showDialog(jPastetext);
}
this.showLink=function()
{
var jLink=$(htmlLink),jParent=_this.getParent('a'),jText=$('#xheLinkText',jLink),jUrl=$('#xheLinkUrl',jLink),jTarget=$('#xheLinkTarget',jLink),jSave=$('#xheSave',jLink),selHtml=_this.getSelect();
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'href'));
jTarget.attr('value',jParent.attr('target'));
}
else if(selHtml=='')jText.val(settings.defLinkText).closest('div').show();
if(settings.upLinkUrl)_this.uploadInit(jUrl,settings.upLinkUrl,settings.upLinkExt);
jSave.click(function(){
var url=jUrl.val();
_this.loadBookmark();
if(url==''||jParent.length==0)_this._exec('unlink');
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sTarget=jTarget.val(),sText=jText.val();
if(aUrl.length>1)
{//批量插入
_this._exec('unlink');//批量前刪除當前鏈接並重新獲取選擇內容
selHtml=_this.getSelect();
var sTemplate='<a href="xhe_tmpurl"',sLink,arrLink=[];
if(sTarget!='')sTemplate+=' target="'+sTarget+'"';
sTemplate+='>xhe_tmptext</a>';
sText=(selHtml!=''?selHtml:(sText?sText:url));
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sLink=sTemplate;
sLink=sLink.replace('xhe_tmpurl',url[0]);
sLink=sLink.replace('xhe_tmptext',url[1]?url[1]:sText);
arrLink.push(sLink);
}
}
_this.pasteHTML(arrLink.join(' '));
}
else
{//單url模式
url=aUrl[0].split('||');
if(!sText)sText=url[0];
sText=url[1]?url[1]:(selHtml!='')?'':sText?sText:url[0];
if(jParent.length==0)
{
if(sText)_this.pasteHTML('<a href="#xhe_tmpurl">'+sText+'</a>');
else _this._exec('createlink','#xhe_tmpurl');
jParent=$('a[href$="#xhe_tmpurl"]',_doc);
}
else if(sText&&!isSafari)jParent.text(sText);//safari改寫文本會導致光標丟失
xheAttr(jParent,'href',url[0]);
if(sTarget!='')jParent.attr('target',sTarget);
else jParent.removeAttr('target');
}
}
_this.hidePanel();
return false;
});
_this.showDialog(jLink);
}
this.showImg=function()
{
var jImg=$(htmlImg),jParent=_this.getParent('img'),jUrl=$('#xheImgUrl',jImg),jAlt=$('#xheImgAlt',jImg),jAlign=$('#xheImgAlign',jImg),jWidth=$('#xheImgWidth',jImg),jHeight=$('#xheImgHeight',jImg),jBorder=$('#xheImgBorder',jImg),jVspace=$('#xheImgVspace',jImg),jHspace=$('#xheImgHspace',jImg),jSave=$('#xheSave',jImg);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jAlt.val(jParent.attr('alt'));
jAlign.val(jParent.attr('align'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
jBorder.val(jParent.attr('border'));
var vspace=jParent.attr('vspace'),hspace=jParent.attr('hspace');
jVspace.val(vspace<=0?'':vspace);
jHspace.val(hspace<=0?'':hspace);
}
if(settings.upImgUrl)_this.uploadInit(jUrl,settings.upImgUrl,settings.upImgExt);
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sAlt=jAlt.val(),sAlign=jAlign.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sBorder=jBorder.val(),sVspace=jVspace.val(),sHspace=jHspace.val();;
if(aUrl.length>1)
{//批量插入
var sTemplate='<img src="xhe_tmpurl"',sImg,arrImg=[];
if(sAlt!='')sTemplate+=' alt="'+sAlt+'"';
if(sAlign!='')sTemplate+=' align="'+sAlign+'"';
if(sWidth!='')sTemplate+=' width="'+sWidth+'"';
if(sHeight!='')sTemplate+=' height="'+sHeight+'"';
if(sBorder!='')sTemplate+=' border="'+sBorder+'"';
if(sVspace!='')sTemplate+=' vspace="'+sVspace+'"';
if(sHspace!='')sTemplate+=' hspace="'+sHspace+'"';
sTemplate+=' />';
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sImg=sTemplate;
sImg=sImg.replace('xhe_tmpurl',url[0]);
if(url[1])sImg='<a href="'+url[1]+'" target="_blank">'+sImg+'</a>'
arrImg.push(sImg);
}
}
_this.pasteHTML(arrImg.join(' '));
}
else if(aUrl.length==1)
{//單URL模式
url=aUrl[0];
if(url!='')
{
url=url.split('||');
if(jParent.length==0)
{
_this.pasteHTML('<img src="'+url[0]+'#xhe_tmpurl" />');
jParent=$('img[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0])
if(sAlt!='')jParent.attr('alt',sAlt);
if(sAlign!='')jParent.attr('align',sAlign);
else jParent.removeAttr('align');
if(sWidth!='')jParent.attr('width',sWidth);
else jParent.removeAttr('width');
if(sHeight!='')jParent.attr('height',sHeight);
else jParent.removeAttr('height');
if(sBorder!='')jParent.attr('border',sBorder);
else jParent.removeAttr('border');
if(sVspace!='')jParent.attr('vspace',sVspace);
else jParent.removeAttr('vspace');
if(sHspace!='')jParent.attr('hspace',sHspace);
else jParent.removeAttr('hspace');
if(url[1])
{
var jLink=jParent.parent('a');
if(jLink.length==0)
{
jParent.wrap('<a></a>');
jLink=jParent.parent('a');
}
xheAttr(jLink,'href',url[1]);
jLink.attr('target','_blank');
}
}
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
_this.showDialog(jImg);
}
this.showEmbed=function(sType,sHtml,sMime,sClsID,sBaseAttrs,sUploadUrl,sUploadExt)
{
var jEmbed=$(sHtml),jParent=_this.getParent('embed[type="'+sMime+'"],embed[classid="'+sClsID+'"]'),jUrl=$('#xhe'+sType+'Url',jEmbed),jWidth=$('#xhe'+sType+'Width',jEmbed),jHeight=$('#xhe'+sType+'Height',jEmbed),jSave=$('#xheSave',jEmbed);
if(sUploadUrl)_this.uploadInit(jUrl,sUploadUrl,sUploadExt);
_this.showDialog(jEmbed);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
}
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var w=jWidth.val(),h=jHeight.val(),reg=/^[0-9]+$/;
if(!reg.test(w))w=412;if(!reg.test(h))h=300;
var sBaseCode='<embed type="'+sMime+'" classid="'+sClsID+'" src="xhe_tmpurl"'+sBaseAttrs;
var aUrl=url.split(' ');
if(aUrl.length>1)
{//批量插入
var sTemplate=sBaseCode+'',sEmbed,arrEmbed=[];
sTemplate+=' width="xhe_width" height="xhe_height" />';
for(var i in aUrl)
{
url=aUrl[i].split('||');
sEmbed=sTemplate;
sEmbed=sEmbed.replace('xhe_tmpurl',url[0])
sEmbed=sEmbed.replace('xhe_width',url[1]?url[1]:w)
sEmbed=sEmbed.replace('xhe_height',url[2]?url[2]:h)
if(url!='')arrEmbed.push(sEmbed);
}
_this.pasteHTML(arrEmbed.join(' '));
}
else if(aUrl.length==1)
{//單URL模式
url=aUrl[0].split('||');
if(jParent.length==0)
{
_this.pasteHTML(sBaseCode.replace('xhe_tmpurl',url[0]+'#xhe_tmpurl')+' />');
jParent=$('embed[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0]);
jParent.attr('width',url[1]?url[1]:w);
jParent.attr('height',url[2]?url[2]:h);
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
}
this.showEmot=function(group)
{
var jEmot=$('<div class="xheEmot"></div>');
group=group?group:(selEmotGroup?selEmotGroup:'default');
var arrEmot=arrEmots[group];
var sEmotPath=emotPath+group+'/',n=0,arrList=[],jList='';
var ew=arrEmot.width,eh=arrEmot.height,line=arrEmot.line,count=arrEmot.count,list=arrEmot.list;
if(count)
{
for(var i=1;i<=count;i++)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+i+'.gif);" emot="'+group+','+i+'" xhev=""> </a>');
if(n%line==0)arrList.push('<br />');
}
}
else
{
$.each(list,function(id,title)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+id+'.gif);" emot="'+group+','+id+'" title="'+title+'" xhev="'+title+'"> </a>');
if(n%line==0)arrList.push('<br />');
});
}
var w=line*(ew+12),h=Math.ceil(n/line)*(eh+12),mh=w*0.75;
if(h<=mh)mh='';
jList=$('<style>'+(mh?'.xheEmot div{width:'+(w+20)+'px;height:'+mh+'px;}':'')+'.xheEmot div a{width:'+ew+'px;height:'+eh+'px;}</style><div>'+arrList.join('')+'</div>').click(function(ev){ev=ev.target;var jA=$(ev);if(!$.nodeName(ev,'A'))return;_this.pasteHTML('<img emot="'+jA.attr('emot')+'" alt="'+jA.attr('xhev')+'">');_this.hidePanel();return false;}).mousedown(returnFalse);
jEmot.append(jList);
var gcount=0,arrGroup=['<ul>'],jGroup;//表情分類
$.each(arrEmots,function(g,v){
gcount++;
arrGroup.push('<li'+(group==g?' class="cur"':'')+'><a href="javascript:void(0);" group="'+g+'">'+v.name+'</a></li>');
});
if(gcount>1)
{
arrGroup.push('</ul><br style="clear:both;" />');
jGroup=$(arrGroup.join('')).click(function(ev){selEmotGroup=$(ev.target).attr('group');_this.exec('Emot');return false;}).mousedown(returnFalse);
jEmot.append(jGroup);
}
_this.showPanel(jEmot);
}
this.showTable=function()
{
var jTable=$(htmlTable),jRows=$('#xheTableRows',jTable),jColumns=$('#xheTableColumns',jTable),jHeaders=$('#xheTableHeaders',jTable),jWidth=$('#xheTableWidth',jTable),jHeight=$('#xheTableHeight',jTable),jBorder=$('#xheTableBorder',jTable),jCellSpacing=$('#xheTableCellSpacing',jTable),jCellPadding=$('#xheTableCellPadding',jTable),jAlign=$('#xheTableAlign',jTable),jCaption=$('#xheTableCaption',jTable),jSave=$('#xheSave',jTable);
jSave.click(function(){
_this.loadBookmark();
var sCaption=jCaption.val(),sBorder=jBorder.val(),sRows=jRows.val(),sCols=jColumns.val(),sHeaders=jHeaders.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sCellSpacing=jCellSpacing.val(),sCellPadding=jCellPadding.val(),sAlign=jAlign.val();
var i,j,htmlTable='<table'+(sBorder!=''?' border="'+sBorder+'"':'')+(sWidth!=''?' width="'+sWidth+'"':'')+(sHeight!=''?' width="'+sHeight+'"':'')+(sCellSpacing!=''?' cellspacing="'+sCellSpacing+'"':'')+(sCellPadding!=''?' cellpadding="'+sCellPadding+'"':'')+(sAlign!=''?' align="'+sAlign+'"':'')+'>';
if(sCaption!='')htmlTable+='<caption>'+sCaption+'</caption>';
if(sHeaders=='row'||sHeaders=='both')
{
htmlTable+='<tr>';
for(i=0;i<sCols;i++)htmlTable+='<th scope="col"> </th>';
htmlTable+='</tr>';
sRows--;
}
htmlTable+='<tbody>';
for(i=0;i<sRows;i++)
{
htmlTable+='<tr>';
for(j=0;j<sCols;j++)
{
if(j==0&&(sHeaders=='col'||sHeaders=='both'))htmlTable+='<th scope="row"> </th>';
else htmlTable+='<td> </td>';
}
htmlTable+='</tr>';
}
htmlTable+='</tbody></table>';
_this.pasteHTML(htmlTable);
_this.hidePanel();
return false;
});
_this.showDialog(jTable);
}
this.showAbout=function()
{
var jAbout=$(htmlAbout);
_this.showDialog(jAbout);
}
this.addShortcuts=function(key,cmd)
{
key=key.toLowerCase();
if(arrShortCuts[key]==undefined)arrShortCuts[key]=Array();
arrShortCuts[key].push(cmd);
}
this.delShortcuts=function(key){delete arrShortCuts[key];}
this.uploadInit=function(jText,toUrl,upext)
{
var jUpload=$('<span class="xheUpload"><input type="text" style="visibility:hidden;" tabindex="-1" /><input type="button" value="'+settings.upBtnText+'" class="xheBtn" tabindex="-1" /></span>'),jUpBtn=$('.xheBtn',jUpload);
var bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
jText.after(jUpload);jUpBtn.before(jText);
toUrl=toUrl.replace(/{editorRoot}/ig,editorRoot);
if(toUrl.substr(0,1)=='!')//自定義上傳管理頁
{
jUpBtn.click(function(){
bShowPanel=false;//防止按鈕面板被關閉
_this.showIframeModal('上傳文件',toUrl.substr(1),setUploadMsg,null,null,function(){bShowPanel=true;});
});
}
else
{//系統預設ajax上傳
jUpload.append('<input type="file"'+(upMultiple>1?' multiple=""':'')+' class="xheFile" size="13" name="'+uploadInputname+'" tabindex="-1" />');
var jFile=$('.xheFile',jUpload),arrMsg;
jFile.change(function(){arrMsg=[];_this.startUpload(jFile[0],toUrl,upext,setUploadMsg);});
setTimeout(function(){//拖放上傳
jText.closest('.xheDialog').bind('dragenter dragover',returnFalse).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(bHtml5Upload&&dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0)_this.startUpload(fileList,toUrl,upext,setUploadMsg);
return false;
});
},10);
}
function setUploadMsg(arrMsg)
{
if(is(arrMsg,'string'))arrMsg=[arrMsg];//允許單URL傳遞
var bImmediate=false,i,count=arrMsg.length,msg,url,arrUrl=[],onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用戶上傳回調
for(i=0;i<count;i++)
{
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!'){bImmediate=true;url=url.substr(1);}
arrUrl.push(url);
}
jText.val(arrUrl.join(' '));
if(bImmediate)jText.closest('.xheDialog').find('#xheSave').click();
}
}
this.startUpload=function(fromFiles,toUrl,limitExt,onUploadComplete)
{
var arrMsg=[],bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
var upload,fileList,filename,jUploadTip=$('<div style="padding:22px 0;text-align:center;line-height:30px;">文件上傳中,請稍候……<br /></div>'),sLoading='<img src="'+skinPath+'img/loading.gif">';
if(!bHtml5Upload||(fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0])))
{
if(!checkFileExt(fromFiles.value,limitExt))return;
jUploadTip.append(sLoading);
upload=new _this.html4Upload(fromFiles,toUrl,onUploadCallback);
}
else
{
if(!fileList)fileList=fromFiles;//拖放文件列表
var i,len=fileList.length;
if(len>upMultiple){alert('請不要一次上傳超過'+upMultiple+'個文件');return;}
for(i=0;i<len;i++)if(!checkFileExt(fileList[i].fileName,limitExt))return;
var jProgress=$('<div class="xheProgress"><div><span>0%</span></div></div>');
jUploadTip.append(jProgress);
upload=new _this.html5Upload(uploadInputname,fileList,toUrl,onUploadCallback,function(ev){
if(ev.loaded>=0)
{
var sPercent=Math.round((ev.loaded * 100) / ev.total)+'%';
$('div',jProgress).css('width',sPercent);
$('span',jProgress).text(sPercent+' ( '+formatBytes(ev.loaded)+' / '+formatBytes(ev.total)+' )');
}
else jProgress.replaceWith(sLoading);//不支持進度
});
}
var panelState=bShowPanel;
if(panelState)bShowPanel=false;//防止面板被關閉
_this.showModal('文件上傳中(Esc取消上傳)',jUploadTip,320,150,function(){bShowPanel=panelState;upload.remove();});
upload.start();
function onUploadCallback(sText,bFinish)
{
var data=Object,bOK=false;
try{data=eval('('+sText+')');}catch(ex){};
if(data.err==undefined||data.msg==undefined)alert(toUrl+' 上傳接口發生錯誤!\r\n\r\n返回的錯誤內容為: \r\n\r\n'+sText);
else
{
if(data.err)alert(data.err);
else
{
arrMsg.push(data.msg);
bOK=true;//繼續下一個文件上傳
}
}
if(!bOK||bFinish)_this.removeModal();
if(bFinish&&bOK)onUploadComplete(arrMsg);//全部上傳完成
return bOK;
}
}
this.html4Upload=function(fromfile,toUrl,callback)
{
var uid = new Date().getTime(),idIO='jUploadFrame'+uid,_this=this;
var jIO=$('<iframe name="'+idIO+'" class="xheHideArea" />').appendTo('body');
var jForm=$('<form action="'+toUrl+'" target="'+idIO+'" method="post" enctype="multipart/form-data" class="xheHideArea"></form>').appendTo('body');
var jOldFile = $(fromfile),jNewFile = jOldFile.clone().attr('disabled','true');
jOldFile.before(jNewFile).appendTo(jForm);
this.remove=function()
{
if(_this!=null)
{
jNewFile.before(jOldFile).remove();
jIO.remove();jForm.remove();
_this=null;
}
}
this.onLoad=function(){callback($(jIO[0].contentWindow.document.body).text(),true);}
this.start=function(){jForm.submit();jIO.load(_this.onLoad);}
return this;
}
this.html5Upload=function(inputname,fromFiles,toUrl,callback,onProgress)
{
var xhr,i=0,count=fromFiles.length,allLoaded=0,allSize=0,_this=this;
for(var j=0;j<count;j++)allSize+=fromFiles[j].fileSize;
this.remove=function(){if(xhr){xhr.abort();xhr=null;}}
this.uploadNext=function(sText)
{
if(sText)//當前文件上傳完成
{
allLoaded+=fromFiles[i-1].fileSize;
returnProgress(0);
}
if((!sText||(sText&&callback(sText,i==count)==true))&&i<count)postFile(fromFiles[i++],toUrl,_this.uploadNext,function(loaded){returnProgress(loaded);});
}
this.start=function(){_this.uploadNext();}
function postFile(fromfile,toUrl,callback,onProgress)
{
xhr = new XMLHttpRequest(),upload=xhr.upload;
xhr.onreadystatechange=function(){if(xhr.readyState==4)callback(xhr.responseText);};
if(upload)upload.onprogress=function(ev){onProgress(ev.loaded);};
else onProgress(-1);//不支持進度
xhr.open("POST", toUrl);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Content-Disposition', 'attachment; name="'+inputname+'"; filename="'+fromfile.fileName+'"');
if(xhr.sendAsBinary)xhr.sendAsBinary(fromfile.getAsBinary());
else xhr.send(fromfile);
}
function returnProgress(loaded){if(onProgress)onProgress({'loaded':allLoaded+loaded,'total':allSize});}
}
this.showIframeModal=function(title,ifmurl,callback,w,h,onRemove)
{
var jContent=$('<iframe frameborder="0" src="'+ifmurl.replace(/{editorRoot}/ig,editorRoot)+'" style="width:100%;height:100%;display:none;" /><div class="xheModalIfmWait"></div>'),jIframe=$(jContent[0]),jWait=$(jContent[1]);
_this.showModal(title,jContent,w,h,onRemove);
jIframe.load(function(){
var modalWin=jIframe[0].contentWindow,jModalDoc=$(modalWin.document);
modalWin.callback=function(v){_this.removeModal();callback(v);};
modalWin.unloadme=_this.removeModal;
jModalDoc.keydown(_this.checkEsc);
jIframe.show();jWait.remove();
});
}
this.showModal=function(title,content,w,h,onRemove)
{
if(bShowModal)return false;//只能彈出一個模式窗口
layerShadow=settings.layerShadow;
w=w?w:settings.modalWidth;h=h?h:settings.modalHeight;
jModal=$('<div class="xheModal" style="width:'+(w-1)+'px;height:'+h+'px;margin-left:-'+Math.ceil(w/2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+Math.ceil(h/2)+'px')+'">'+(settings.modalTitle?'<div class="xheModalTitle"><span class="xheModalClose" title="關閉 (Esc)"></span>'+title+'</div>':'')+'<div class="xheModalContent"></div></div>').appendTo('body');
jOverlay=$('<div class="xheModalOverlay"></div>').appendTo('body');
if(layerShadow>0)jModalShadow=$('<div class="xheModalShadow" style="width:'+jModal.outerWidth()+'px;height:'+jModal.outerHeight()+'px;margin-left:-'+(Math.ceil(w/2)-layerShadow-2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+(Math.ceil(h/2)-layerShadow-2)+'px')+'"></div>').appendTo('body');
$('.xheModalContent',jModal).css('height',h-(settings.modalTitle?$('.xheModalTitle').outerHeight():0)).html(content);
if(isIE&&browerVer==6.0)jHideSelect=$('select:visible').css('visibility','hidden');//隱藏覆蓋的select
$('.xheModalClose',jModal).click(_this.removeModal);
jOverlay.show();if(layerShadow>0)jModalShadow.show();jModal.show();
bShowModal=true;
onModalRemove=onRemove;
}
this.removeModal=function(){if(jHideSelect)jHideSelect.css('visibility','visible');jModal.html('').remove();if(layerShadow>0)jModalShadow.remove();jOverlay.remove();if(onModalRemove)onModalRemove();bShowModal=false;};
this.showDialog=function(content)
{
var jDialog=$('<div class="xheDialog"></div>'),jContent=$(content),jSave=$('#xheSave',jContent);
if(jSave.length==1)
{
jContent.find('input[type=text],select').keypress(function(ev){if(ev.which==13){jSave.click();return false;}});
jContent.find('textarea').keydown(function(ev){if(ev.ctrlKey&&ev.which==13){jSave.click();return false;}});
jSave.after(' <input type="button" id="xheCancel" value="取消" />');
$('#xheCancel',jContent).click(_this.hidePanel);
if(!settings.clickCancelDialog)
{
bClickCancel=false;//關閉點擊隱藏
var jFixCancel=$('<div class="xheFixCancel"></div>').appendTo('body').mousedown(returnFalse);
var xy=_jArea.offset();
jFixCancel.css({'left':xy.left,'top':xy.top,width:_jArea.outerWidth(),height:_jArea.outerHeight()})
}
jDialog.mousedown(function(){bDisableHoverExec=true;})//點擊對話框禁止懸停執行
}
jDialog.append(jContent);
_this.showPanel(jDialog);
if(!isIE)setTimeout(function(){jDialog.find('input[type=text],textarea').filter(':visible').filter(function(){return $(this).css('visibility')!='hidden';}).eq(0).focus();},10);//定位首個可見輸入表單項,延遲解決opera無法設置焦點
}
this.showPanel=function(content)
{
if(!ev.target)return false;
_jPanel.html('').append(content).css('left',-999).css('top',-999);
_jPanelButton=$(ev.target).closest('a').addClass('xheActive');
var xy=_jPanelButton.offset();
var x=xy.left,y=xy.top;y+=_jPanelButton.outerHeight()-1;
_jCntLine.css({'left':x+1,'top':y,'width':_jPanelButton.width()}).show();
if((x+_jPanel.outerWidth())>document.body.clientWidth)x-=(_jPanel.outerWidth()-_jPanelButton.outerWidth());//向左顯示面板
var layerShadow=settings.layerShadow;
if(layerShadow>0)_jShadow.css({'left':x+layerShadow,'top':y+layerShadow,'width':_jPanel.outerWidth(),'height':_jPanel.outerHeight()}).show();
_jPanel.css({'left':x,'top':y}).show();
bQuickHoverExec=bShowPanel=true;
}
this.hidePanel=function(){if(bShowPanel){_jPanelButton.removeClass('xheActive');_jShadow.hide();_jCntLine.hide();_jPanel.hide();bShowPanel=false;if(!bClickCancel){$('.xheFixCancel').remove();bClickCancel=true;};bQuickHoverExec=bDisableHoverExec=false;lastAngle=null;}}
this.exec=function(cmd)
{
_this.hidePanel();
_this.saveBookmark();
var tool=arrTools[cmd];
if(!tool)return false;//無效命令
if(ev==null)//非鼠標點擊
{
ev={};
var btn=_jTools.find('.xheButton[name='+cmd+']');
if(btn.length==1)ev.target=btn;//設置當前事件焦點
}
if(tool.e)tool.e.call(_this)//插件事件
else//內置工具
{
cmd=cmd.toLowerCase();
switch(cmd)
{
case 'cut':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的瀏覽器安全設置不允許使用剪下操作,請使用鍵盤快捷鍵(Ctrl + X)來完成');};
break;
case 'copy':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的瀏覽器安全設置不允許使用複製操作,請使用鍵盤快捷鍵(Ctrl + C)來完成');}
break;
case 'paste':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的瀏覽器安全設置不允許使用貼上操作,請使用鍵盤快捷鍵(Ctrl + V)來完成');}
break;
case 'pastetext':
if(window.clipboardData)_this.pasteText(window.clipboardData.getData('Text', true));
else _this.showPastetext();
break;
case 'blocktag':
var menuBlocktag=[];
$.each(arrBlocktag,function(n,v){menuBlocktag.push({s:'<'+v.n+'>'+v.t+'</'+v.n+'>',v:'<'+v.n+'>',t:v.t});});
_this.showMenu(menuBlocktag,function(v){_this._exec('formatblock',v);});
break;
case 'fontface':
var menuFontname=[];
$.each(arrFontname,function(n,v){v.c=v.c?v.c:v.n;menuFontname.push({s:'<span style="font-family:'+v.c+'">'+v.n+'</span>',v:v.c,t:v.n});});
_this.showMenu(menuFontname,function(v){_this._exec('fontname',v);});
break;
case 'fontsize':
var menuFontsize=[];
$.each(arrFontsize,function(n,v){menuFontsize.push({s:'<span style="font-size:'+v.s+';">'+v.t+'('+v.s+')</span>',v:n+1,t:v.t});});
_this.showMenu(menuFontsize,function(v){_this._exec('fontsize',v);});
break;
case 'fontcolor':
_this.showColor(function(v){_this._exec('forecolor',v);});
break;
case 'backcolor':
_this.showColor(function(v){if(isIE)_this._exec('backcolor',v);else{setCSS(true);_this._exec('hilitecolor',v);setCSS(false);}});
break;
case 'align':
_this.showMenu(menuAlign,function(v){_this._exec(v);});
break;
case 'list':
_this.showMenu(menuList,function(v){_this._exec(v);});
break;
case 'link':
_this.showLink();
break;
case 'img':
_this.showImg();
break;
case 'flash':
_this.showEmbed('Flash',htmlFlash,'application/x-shockwave-flash','clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000',' wmode="opaque" quality="high" menu="false" play="true" loop="true" allowfullscreen="true"',settings.upFlashUrl,settings.upFlashExt);
break;
case 'media':
_this.showEmbed('Media',htmlMedia,'application/x-mplayer2','clsid:6bf52a52-394a-11d3-b153-00c04f79faa6',' enablecontextmenu="false" autostart="false"',settings.upMediaUrl,settings.upMediaExt);
break;
case 'emot':
_this.showEmot();
break;
case 'table':
_this.showTable();
break;
case 'source':
_this.toggleSource();
break;
case 'preview':
_this.showPreview();
break;
case 'print':
_win.print();
break;
case 'fullscreen':
_this.toggleFullscreen();
break;
case 'about':
_this.showAbout();
break;
default:
_this._exec(cmd);
break;
}
}
ev=null;
}
this._exec=function(cmd,param,noFocus)
{
if(!noFocus)_this.focus();
var state;
if(param!=undefined)state=_doc.execCommand(cmd,false,param);
else state=_doc.execCommand(cmd,false,null);
return state;
}
function checkDblClick(ev)
{
var target=ev.target,tool=arrDbClick[target.tagName.toLowerCase()];
if(tool)
{
if(tool=='Embed')//自動識別Flash和多媒體
{
var arrEmbed={'application/x-shockwave-flash':'Flash','application/x-mplayer2':'Media'};
tool=arrEmbed[target.type.toLowerCase()];
}
_this.exec(tool);
}
}
function checkEsc(ev)
{
if(ev.which==27)
{
if(bShowModal)_this.removeModal();
else if(bShowPanel)_this.hidePanel();
return false;
}
}
function loadReset(){setTimeout(_this.setSource,10);}
function saveResult(){_this.getSource();};
function cleanPaste(ev){
if(bSource||bCleanPaste)return true;
bCleanPaste=true;//解決IE右鍵貼上重複產生paste的問題
_this.saveBookmark();
var jDiv=$('<div style="position:absolute;left:-1000px;top:'+_jWin.scrollTop()+'px;overflow:hidden;width:1px;height:1px;" />',_doc),div=jDiv[0],sel=_this.getSel(),rng=_this.getRng();
$(_doc.body).append(jDiv);
if(isIE){
rng.moveToElementText(div);
rng.execCommand('Paste');
ev.preventDefault();
}
else{
rng.selectNodeContents(div);
sel.removeAllRanges();
sel.addRange(rng);
}
setTimeout(function(){
var sPaste;
if(settings.forcePasteText===true)sPaste=jDiv.text();
else{
sPaste=div.innerHTML;
sPaste=_this.cleanHTML(sPaste);
sPaste=_this.formatXHTML(sPaste);
sPaste=_this.cleanWord(sPaste);
}
jDiv.remove();
_this.loadBookmark();
_this.pasteHTML(sPaste);
bCleanPaste=false;
},0);
}
function setCSS(css)
{
try{_this._exec('styleWithCSS',css,true);}
catch(e)
{try{_this._exec('useCSS',!css,true);}catch(e){}}
}
function setOpts()
{
if(bInit&&!bSource)
{
setCSS(false);
try{_this._exec('enableObjectResizing',true,true);}catch(e){}
//try{_this._exec('enableInlineTableEditing',false,true);}catch(e){}
if(isIE)try{_this._exec('BackgroundImageCache',true,true);}catch(e){}
}
}
function forcePtag(ev)
{
if(bSource||ev.which!=13||ev.shiftKey||ev.ctrlKey||ev.altKey)return true;
var pNode=_this.getParent('p,h1,h2,h3,h4,h5,h6,pre,address,div,li');
if(pNode.is('li'))return true;
if(settings.forcePtag){if(pNode.length==0)_this._exec('formatblock','<p>');}
else
{
_this.pasteHTML('<br />');
if(isIE&&pNode.length>0&&_this.getRng().parentElement().childNodes.length==2)_this.pasteHTML('<br />');
return false;
}
}
function fixFullHeight()
{
if(!isMozilla&&!isSafari)
{
if(bFullscreen)_jArea.height('100%').css('height',_jArea.outerHeight()-_jTools.outerHeight());
if(isIE)_jTools.hide().show();
}
}
function fixAppleSel(e)
{
e=e.target;
if(e.tagName.match(/(img|embed)/i))
{
var sel=_this.getSel(),rng=_this.getRng();
rng.selectNode(e);
sel.removeAllRanges();
sel.addRange(rng);
}
}
function xheAttr(jObj,n,v)
{
if(!n)return false;
var kn='_xhe_'+n;
if(v)//設置屬性
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
jObj.attr(n,urlBase?getLocalUrl(v,'abs',urlBase):v).removeAttr(kn).attr(kn,v);
}
return jObj.attr(kn)||jObj.attr(n);
}
function clickCancelPanel(){if(bClickCancel)_this.hidePanel();}
function checkShortcuts(event)
{
if(bSource)return true;
var code=event.which,special=specialKeys[code],sChar=special?special:String.fromCharCode(code).toLowerCase();
sKey='';
sKey+=event.ctrlKey?'ctrl+':'';sKey+=event.altKey?'alt+':'';sKey+=event.shiftKey?'shift+':'';sKey+=sChar;
var cmd=arrShortCuts[sKey],c;
for(c in cmd)
{
c=cmd[c];
if($.isFunction(c)){if(c.call(_this)===false)return false;}
else{_this.exec(c);return false;}//按鈕獨佔快捷鍵
}
}
function is(o,t)
{
var n = typeof(o);
if (!t)return n != 'undefined';
if (t == 'array' && (o.hasOwnProperty && o instanceof Array))return true;
return n == t;
}
function getLocalUrl(url,urlType,urlBase)//絕對地址:abs,根地址:root,相對地址:rel
{
var baseUrl=urlBase?$('<a href="'+urlBase+'" />')[0]:location,protocol=baseUrl.protocol,host=baseUrl.hostname,port=baseUrl.port,path=baseUrl.pathname.replace(/\\/g,'/').replace(/[^\/]+$/i,'');
port=(port=='')?'80':port;
url=$.trim(url);
if(urlType!='abs')url=url.replace(new RegExp(protocol+'\\/\\/'+host.replace(/\./g,'\\.')+'(?::'+port+')'+(port=='80'?'?':'')+'(\/|$)','i'),'/');
if(urlType=='rel')url=url.replace(new RegExp('^'+path.replace(/([\/\.\+\[\]\(\)])/g,'\\$1'),'i'),'');
if(urlType!='rel')
{
if(!url.match(/^((https?|file):\/\/|\/)/i))url=path+url;
if(url.charAt(0)=='/')//處理..
{
var arrPath=[],arrFolder = url.split('/'),folder,i,l=arrFolder.length;
for(i=0;i<l;i++)
{
folder=arrFolder[i];
if(folder=='..')arrPath.pop();
else if(folder!==''&&folder!='.')arrPath.push(folder);
}
if(arrFolder[l-1]=='')arrPath.push('');
url='/'+arrPath.join('/');
}
}
if(urlType=='abs')if(!url.match(/(https?|file):\/\//i))url=protocol+'//'+location.host+url;
return url;
}
function checkFileExt(filename,limitExt)
{
if(limitExt=='*'||filename.match(new RegExp('\.('+limitExt.replace(/,/g,'|')+')$','i')))return true;
else
{
alert('上傳文件擴展名必需為: '+limitExt);
return false;
}
}
function formatBytes(bytes)
{
var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+s[e];
}
function returnFalse(){return false;}
}
$(function(){
$.fn.oldVal=$.fn.val;
$.fn.val=function(value)
{
var _this=this,editor;
if(value===undefined)if(this[0]&&(editor=this[0].xheditor))return editor.getSource();else return _this.oldVal(value);//讀
return this.each(function(){if(editor=this.xheditor)editor.setSource(value);else _this.oldVal(value);});//寫
}
$('textarea').each(function(){
var self=$(this),xhClass=self.attr('class').match(/(?:^|\s)xheditor(?:\-(m?full|simple|mini))?(?:\s|$)/i);
if(xhClass)self.xheditor(xhClass[1]?{tools:xhClass[1]}:null);
});
});
})(jQuery); | JavaScript |
/*!
* WYSIWYG UBB Editor support for xhEditor
* @requires xhEditor
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 0.9.6 (build 100513)
*/
function ubb2html(sUBB)
{
var i,sHtml=String(sUBB),arrcode=new Array(),cnum=0;
sHtml=sHtml.replace(/&/ig, '&');
sHtml=sHtml.replace(/[<>]/g,function(c){return {'<':'<','>':'>'}[c];});
sHtml=sHtml.replace(/\r?\n/g,"<br />");
sHtml=sHtml.replace(/\[code\s*(?:=\s*([^\]]+?))?\]([\s\S]*?)\[\/code\]/ig,function(all,t,c){//code特殊处理
cnum++;arrcode[cnum]=all;
return "[\tubbcodeplace_"+cnum+"\t]";
});
sHtml=sHtml.replace(/\[(\/?)(b|u|i|s|sup|sub)\]/ig,'<$1$2>');
sHtml=sHtml.replace(/\[color\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/ig,'<font color="$1">');
sHtml=sHtml.replace(/\[size\s*=\s*(\d+?)\s*\]/ig,'<font size="$1">');
sHtml=sHtml.replace(/\[font\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/ig,'<font face="$1">');
sHtml=sHtml.replace(/\[\/(color|size|font)\]/ig,'</font>');
sHtml=sHtml.replace(/\[back\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/ig,'<span style="background-color:$1;">');
sHtml=sHtml.replace(/\[\/back\]/ig,'</span>');
for(i=0;i<3;i++)sHtml=sHtml.replace(/\[align\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\](((?!\[align(?:\s+[^\]]+)?\])[\s\S])*?)\[\/align\]/ig,'<p align="$1">$2</p>');
sHtml=sHtml.replace(/\[img\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/img\]/ig,'<img src="$1" alt="" />');
sHtml=sHtml.replace(/\[img\s*=([^,\]]*)(?:\s*,\s*(\d*%?)\s*,\s*(\d*%?)\s*)?(?:,?\s*(\w+))?\s*\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*)?\s*\[\/img\]/ig,function(all,alt,p1,p2,p3,src){
var str='<img src="'+src+'" alt="'+alt+'"',a=p3?p3:(!isNum(p1)?p1:'');
if(isNum(p1))str+=' width="'+p1+'"';
if(isNum(p2))str+=' height="'+p2+'"'
if(a)str+=' align="'+a+'"';
str+=' />';
return str;
});
sHtml=sHtml.replace(/\[emot\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\/\]/ig,'<img emot="$1" />');
sHtml=sHtml.replace(/\[url\]\s*(((?!")[\s\S])*?)(?:"[\s\S]*?)?\s*\[\/url\]/ig,'<a href="$1">$1</a>');
sHtml=sHtml.replace(/\[url\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]*?)\s*\[\/url\]/ig,'<a href="$1">$2</a>');
sHtml=sHtml.replace(/\[email\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/email\]/ig,'<a href="mailto:$1">$1</a>');
sHtml=sHtml.replace(/\[email\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]+?)\s*\[\/email\]/ig,'<a href="mailto:$1">$2</a>');
sHtml=sHtml.replace(/\[quote\]([\s\S]*?)\[\/quote\]/ig,'<blockquote>$1</blockquote>');
sHtml=sHtml.replace(/\[flash\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/flash\]/ig,function(all,w,h,url){
if(!w)w=480;if(!h)h=400;
return '<embed type="application/x-shockwave-flash" src="'+url+'" wmode="opaque" quality="high" bgcolor="#ffffff" menu="false" play="true" loop="true" width="'+w+'" height="'+h+'"/>';
});
sHtml=sHtml.replace(/\[media\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+)\s*)?)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/media\]/ig,function(all,w,h,play,url){
if(!w)w=480;if(!h)h=400;
return '<embed type="application/x-mplayer2" src="'+url+'" enablecontextmenu="false" autostart="'+(play=='1'?'true':'false')+'" width="'+w+'" height="'+h+'"/>';
});
sHtml=sHtml.replace(/\[table\s*(?:=\s*(\d{1,4}%?)\s*(?:,\s*([^\]"]+)(?:"[^\]]*?)?)?)?\s*\]/ig,function(all,w,b){
var str='<table';
if(w)str+=' width="'+w+'"';
if(b)str+=' bgcolor="'+b+'"';
return str+'>';
});
sHtml=sHtml.replace(/\[tr\s*(?:=\s*([^\]"]+?)(?:"[^\]]*?)?)?\s*\]/ig,function(all,bg){
return '<tr'+(bg?' bgcolor="'+bg+'"':'')+'>';
});
sHtml=sHtml.replace(/\[td\s*(?:=\s*(\d{1,2})\s*,\s*(\d{1,2})\s*(?:,\s*(\d{1,4}%?))?)?\s*\]/ig,function(all,col,row,w){
return '<td'+(col>1?' colspan="'+col+'"':'')+(row>1?' rowspan="'+row+'"':'')+(w?' width="'+w+'"':'')+'>';
});
sHtml=sHtml.replace(/\[\/(table|tr|td)\]/ig,'</$1>');
sHtml=sHtml.replace(/\[\*\]((?:(?!\[\*\]|\[\/list\]|\[list\s*(?:=[^\]]+)?\])[\s\S])+)/ig,'<li>$1</li>');
sHtml=sHtml.replace(/\[list\s*(?:=\s*([^\]"]+?)(?:"[^\]]*?)?)?\s*\]/ig,function(all,type){
var str='<ul';
if(type)str+=' type="'+type+'"';
return str+'>';
});
sHtml=sHtml.replace(/\[\/list\]/ig,'</ul>');
for(i=1;i<=cnum;i++)sHtml=sHtml.replace("[\tubbcodeplace_"+i+"\t]", arrcode[i]);
sHtml=sHtml.replace(/(^|<\/?\w+(?:\s+[^>]*?)?>)([^<$]+)/ig, function(all,tag,text){
return tag+text.replace(/[\t ]/g,function(c){return {'\t':' ',' ':' '}[c];});
});
function isNum(s){if(s!=null&&s!='')return !isNaN(s);else return false;}
return sHtml;
}
function html2ubb(sHtml)
{
var mapSize={'xx-small':1,'8pt':1,'x-small':2,'10pt':2,'small':3,'12pt':3,'medium':4,'14pt':4,'large':5,'18pt':5,'x-large':6,'24pt':6,'xx-large':7,'36pt':7};
var regSrc=/\s+src\s*=\s*(["']?)\s*(.+?)\s*\1(\s|$)/i,regWidth=/\s+width\s*=\s*(["']?)\s*(\d+(?:\.\d+)?%?)\s*\1(\s|$)/i,regHeight=/\s+height\s*=\s*(["']?)\s*(\d+(?:\.\d+)?%?)\s*\1(\s|$)/i,regBg=/(?:background|background-color|bgcolor)\s*[:=]\s*(["']?)\s*((rgb\s*\(\s*\d{1,3}%?,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*\))|(#[0-9a-f]{3,6})|([a-z]{1,20}))\s*\1/i
var i,sUBB=String(sHtml),arrcode=new Array(),cnum=0;
sUBB=sUBB.replace(/\s*\r?\n\s*/g,'');
sUBB = sUBB.replace(/<(script|style)(\s+[^>]*?)?>[\s\S]*?<\/\1>/ig, '');
sUBB = sUBB.replace(/<!--[\s\S]*?-->/ig,'');
sUBB=sUBB.replace(/<br\s*?\/?>/ig,"\r\n");
sUBB=sUBB.replace(/\[code\s*(=\s*([^\]]+?))?\]([\s\S]*?)\[\/code\]/ig,function(all,t,c){//code特殊处理
cnum++;arrcode[cnum]=all;
return "[\tubbcodeplace_"+cnum+"\t]";
});
sUBB=sUBB.replace(/<(\/?)(b|u|i|s)(\s+[^>]*?)?>/ig,'[$1$2]');
sUBB=sUBB.replace(/<(\/?)strong(\s+[^>]*?)?>/ig,'[$1b]');
sUBB=sUBB.replace(/<(\/?)em(\s+[^>]*?)?>/ig,'[$1i]');
sUBB=sUBB.replace(/<(\/?)(strike|del)(\s+[^>]*?)?>/ig,'[$1s]');
sUBB=sUBB.replace(/<(\/?)(sup|sub)(\s+[^>]*?)?>/ig,'[$1$2]');
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color|background|background-color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,function(all,tag,style,content){
var face=style.match(/(?:^|;)\s*font-family\s*:\s*([^;]+)/i),size=style.match(/(?:^|;)\s*font-size\s*:\s*([^;]+)/i),color=style.match(/(?:^|;)\s*color\s*:\s*([^;]+)/i),back=style.match(/(?:^|;)\s*(?:background|background-color)\s*:\s*([^;]+)/i),str=content;
if(face)str='[font='+face[1]+']'+str+'[/font]';
if(size)
{
size=mapSize[size[1].toLowerCase()];
if(size)str='[size='+size+']'+str+'[/size]';
}
if(color)str='[color='+formatColor(color[1])+']'+str+'[/color]';
if(back)str='[back='+formatColor(back[1])+']'+str+'[/back]';
return str;
});
function formatColor(c)
{
var matchs;
if(matchs=c.match(/\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)){c=(matchs[1]*65536+matchs[2]*256+matchs[3]*1).toString(16);while(c.length<6)c='0'+c;c='#'+c;}
c=c.replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,'#$1$1$2$2$3$3');
return c;
}
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(div|p)(?:\s+[^>]*?)?[\s"';]\s*(?:text-)?align\s*[=:]\s*(["']?)\s*(left|center|right)\s*\2[^>]*>(((?!<\1(\s+[^>]*?)?>)[\s\S])+?)<\/\1>/ig,'[align=$3]$4[/align]');
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(center)(?:\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,'[align=center]$2[/align]');
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(p|div)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*text-align\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,function(all,tag,style,content){
});
sUBB=sUBB.replace(/<a(?:\s+[^>]*?)?\s+href=(["'])\s*(.+?)\s*\1[^>]*>\s*([\s\S]*?)\s*<\/a>/ig,function(all,q,url,text){
if(!(url&&text))return '';
var tag='url',str;
if(url.match(/^mailto:/i))
{
tag='email';
url=url.replace(/mailto:(.+?)/i,'$1');
}
str='['+tag;
if(url!=text)str+='='+url;
return str+']'+text+'[/'+tag+']';
});
sUBB=sUBB.replace(/<img(\s+[^>]*?)\/?>/ig,function(all,attr){
var emot=attr.match(/\s+emot\s*=\s*(["']?)\s*(.+?)\s*\1(\s|$)/i);
if(emot)return '[emot='+emot[2]+'/]';
var url=attr.match(regSrc),alt=attr.match(/\s+alt\s*=\s*(["']?)\s*(.*?)\s*\1(\s|$)/i),w=attr.match(regWidth),h=attr.match(regHeight),align=attr.match(/\s+align\s*=\s*(["']?)\s*(\w+)\s*\1(\s|$)/i),str='[img',p='';
if(!url)return '';
p+=alt[2];
if(w||h)p+=','+(w?w[2]:'')+','+(h?h[2]:'');
if(align)p+=','+align[2];
if(p)str+='='+p;
str+=']'+url[2]+'[/img]';
return str;
});
sUBB=sUBB.replace(/<blockquote(?:\s+[^>]*?)?>([\s\S]+?)<\/blockquote>/ig,'[quote]$1[/quote]');
sUBB=sUBB.replace(/<embed((?:\s+[^>]*?)?(?:\s+type\s*=\s*"\s*application\/x-shockwave-flash\s*"|\s+classid\s*=\s*"\s*clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000\s*")[^>]*?)\/>/ig,function(all,attr){
var url=attr.match(regSrc),w=attr.match(regWidth),h=attr.match(regHeight),str='[flash';
if(!url)return '';
if(w&&h)str+='='+w[2]+','+h[2];
str+=']'+url[2];
return str+'[/flash]';
});
sUBB=sUBB.replace(/<embed((?:\s+[^>]*?)?(?:\s+type\s*=\s*"\s*application\/x-mplayer2\s*"|\s+classid\s*=\s*"\s*clsid:6bf52a52-394a-11d3-b153-00c04f79faa6\s*")[^>]*?)\/>/ig,function(all,attr){
var url=attr.match(regSrc),w=attr.match(regWidth),h=attr.match(regHeight),p=attr.match(/\s+autostart\s*=\s*(["']?)\s*(.+?)\s*\1(\s|$)/i),str='[media',auto='0';
if(!url)return '';
if(p)if(p[2]=='true')auto='1';
if(w&&h)str+='='+w[2]+','+h[2]+','+auto;
str+=']'+url[2];
return str+'[/media]';
});
sUBB=sUBB.replace(/<table(\s+[^>]*?)?>/ig,function(all,attr){
var str='[table';
if(attr)
{
var w=attr.match(regWidth),b=attr.match(regBg);
if(w)
{
str+='='+w[2];
if(b)str+=','+b[2];
}
}
return str+']';
});
sUBB=sUBB.replace(/<tr(\s+[^>]*?)?>/ig,function(all,attr){
var str='[tr';
if(attr)
{
var bg=attr.match(regBg)
if(bg)str+='='+bg[2];
}
return str+']';
});
sUBB=sUBB.replace(/<(?:th|td)(\s+[^>]*?)?>/ig,function(all,attr){
var str='[td';
if(attr)
{
var col=attr.match(/\s+colspan\s*=\s*(["']?)\s*(\d+)\s*\1(\s|$)/i),row=attr.match(/\s+rowspan\s*=\s*(["']?)\s*(\d+)\s*\1(\s|$)/i),w=attr.match(regWidth);
col=col?col[2]:1;
row=row?row[2]:1;
if(col>1||row>1||w)str+='='+col+','+row;
if(w)str+=','+w[2];
}
return str+']';
});
sUBB=sUBB.replace(/<\/(table|tr)>/ig,'[/$1]');
sUBB=sUBB.replace(/<\/(th|td)>/ig,'[/td]');
sUBB=sUBB.replace(/<ul(\s+[^>]*?)?>/ig,function(all,attr){
var t;
if(attr)t=attr.match(/\s+type\s*=\s*(["']?)\s*(.+?)\s*\1(\s|$)/i);
return '[list'+(t?'='+t[2]:'')+']';
});
sUBB=sUBB.replace(/<ol(\s+[^>]*?)?>/ig,'[list=1]');
sUBB=sUBB.replace(/<li(\s+[^>]*?)?>/ig,'[*]');
sUBB=sUBB.replace(/<\/li>/ig,'');
sUBB=sUBB.replace(/<\/(ul|ol)>/ig,'[/list]');
sUBB=sUBB.replace(/<h([1-6])(\s+[^>]*?)?>/ig,function(all,n){return '\r\n\r\n[size='+(7-n)+'][b]'});
sUBB=sUBB.replace(/<\/h[1-6]>/ig,'[/b][/size]\r\n\r\n');
sUBB=sUBB.replace(/<address(\s+[^>]*?)?>/ig,'\r\n[i]');
sUBB=sUBB.replace(/<\/address>/ig,'[i]\r\n');
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(p)(?:\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,"\r\n\r\n$2\r\n\r\n");
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(div)(?:\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,"\r\n$2\r\n");
sUBB=sUBB.replace(/((\s| )*\r?\n){3,}/g,"\r\n\r\n");//限制最多2次换行
sUBB=sUBB.replace(/^((\s| )*\r?\n)+/g,'');//清除开头换行
sUBB=sUBB.replace(/((\s| )*\r?\n)+$/g,'');//清除结尾换行
for(i=1;i<=cnum;i++)sUBB=sUBB.replace("[\tubbcodeplace_"+i+"\t]", arrcode[i]);
sUBB=sUBB.replace(/<[^<>]+?>/g,'');//删除所有HTML标签
sUBB=sUBB.replace(/</ig, '<');
sUBB=sUBB.replace(/>/ig, '>');
sUBB=sUBB.replace(/ /ig, ' ');
sUBB=sUBB.replace(/&/ig, '&');
return sUBB;
} | JavaScript |
/*!
* xhEditor - WYSIWYG XHTML Editor
* @requires jQuery v1.4.2
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 1.1.1 (build 101002)
*/
(function($){
if($.xheditor)return false;//防止JS重复加载
$.fn.xheditor=function(options)
{
var arrSuccess=[];
this.each(function(){
if(!$.nodeName(this,'TEXTAREA'))return;
if(options===false)//卸载
{
if(this.xheditor)
{
this.xheditor.remove();
this.xheditor=null;
}
}
else//初始化
{
if(!this.xheditor)
{
var tOptions=/({.*})/.exec($(this).attr('class'));
if(tOptions)
{
try{tOptions=eval('('+tOptions[1]+')');}catch(ex){};
options=$.extend({},tOptions,options );
}
var editor=new $.xheditor(this,options);
if(editor.init())
{
this.xheditor=editor;
arrSuccess.push(editor);
}
else editor=null;
}
else arrSuccess.push(this.xheditor);
}
});
if(arrSuccess.length==0)arrSuccess=false;
if(arrSuccess.length==1)arrSuccess=arrSuccess[0];
return arrSuccess;
}
var xCount=0,browerVer=$.browser.version,isIE=$.browser.msie,isMozilla=$.browser.mozilla,isSafari=$.browser.safari,isOpera=$.browser.opera,bShowPanel=false,bClickCancel=true,bShowModal=false,bCheckEscInit=false;
var _jPanel,_jShadow,_jCntLine,_jPanelButton;
var jModal,jModalShadow,layerShadow,jOverlay,jHideSelect,onModalRemove;
var editorRoot;
$('script[src*=xheditor]').each(function(){
var s=this.src;
if(s.match(/xheditor[^\/]*\.js/i)){editorRoot=s.replace(/[\?#].*$/, '').replace(/(^|[\/\\])[^\/]*$/, '$1');return false;}
});
var specialKeys={ 27: 'esc', 9: 'tab', 32:'space', 13: 'enter', 8:'backspace', 145: 'scroll',
20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',
35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down',
112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12' };
var itemColors=['#FFFFFF','#CCCCCC','#C0C0C0','#999999','#666666','#333333','#000000','#FFCCCC','#FF6666','#FF0000','#CC0000','#990000','#660000','#330000','#FFCC99','#FF9966','#FF9900','#FF6600','#CC6600','#993300','#663300','#FFFF99','#FFFF66','#FFCC66','#FFCC33','#CC9933','#996633','#663333','#FFFFCC','#FFFF33','#FFFF00','#FFCC00','#999900','#666600','#333300','#99FF99','#66FF99','#33FF33','#33CC00','#009900','#006600','#003300','#99FFFF','#33FFFF','#66CCCC','#00CCCC','#339999','#336666','#003333','#CCFFFF','#66FFFF','#33CCFF','#3366FF','#3333FF','#000099','#000066','#CCCCFF','#9999FF','#6666CC','#6633FF','#6600CC','#333399','#330099','#FFCCFF','#FF99FF','#CC66CC','#CC33CC','#993399','#663366','#330033'];
var arrBlocktag=[{n:'p',t:'Paragraph'},{n:'h1',t:'Heading 1'},{n:'h2',t:'Heading 2'},{n:'h3',t:'Heading 3'},{n:'h4',t:'Heading 4'},{n:'h5',t:'Heading 5'},{n:'h6',t:'Heading 6'},{n:'pre',t:'Preformatted'},{n:'address',t:'Address'}];
var arrFontname=[{n:'Arial'},{n:'Arial Narrow'},{n:'Arial Black'},{n:'Comic Sans MS'},{n:'Courier New'},{n:'System'},{n:'Times New Roman'},{n:'Tahoma'},{n:'Verdana'}];
var arrFontsize=[{n:'xx-small',wkn:'x-small',s:'8pt',t:'xx-small'},{n:'x-small',wkn:'small',s:'10pt',t:'x-small'},{n:'small',wkn:'medium',s:'12pt',t:'small'},{n:'medium',wkn:'large',s:'14pt',t:'medium'},{n:'large',wkn:'x-large',s:'18pt',t:'large'},{n:'x-large',wkn:'xx-large',s:'24pt',t:'x-large'},{n:'xx-large',wkn:'-webkit-xxx-large',s:'36pt',t:'xx-large'}];
var menuAlign=[{s:'Align left',v:'justifyleft',t:'Align left'},{s:'Align center',v:'justifycenter',t:'Align center'},{s:'Align right',v:'justifyright',t:'Align right'},{s:'Align full',v:'justifyfull',t:'Align full'}],menuList=[{s:'Ordered list',v:'insertOrderedList',t:'Ordered list'},{s:'Unordered list',v:'insertUnorderedList',t:'Unordered list'}];
var htmlPastetext='<div>Use Ctrl+V on your keyboard to paste the text.</div><div><textarea id="xhePastetextValue" wrap="soft" spellcheck="false" style="width:300px;height:100px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlLink='<div>Link URL: <input type="text" id="xheLinkUrl" value="http://" class="xheText" /></div><div>Target: <select id="xheLinkTarget"><option selected="selected" value="">Default</option><option value="_blank">New window</option><option value="_self">Same window</option><option value="_parent">Parent window</option></select></div><div style="display:none">Link Text:<input type="text" id="xheLinkText" value="" class="xheText" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlImg='<div>Img URL: <input type="text" id="xheImgUrl" value="http://" class="xheText" /></div><div>Alt text: <input type="text" id="xheImgAlt" /></div><div>Alignment:<select id="xheImgAlign"><option selected="selected" value="">Default</option><option value="left">Left</option><option value="right">Right</option><option value="top">Top</option><option value="middle">Middle</option><option value="baseline">Baseline</option><option value="bottom">Bottom</option></select></div><div>Dimension:<input type="text" id="xheImgWidth" style="width:40px;" /> x <input type="text" id="xheImgHeight" style="width:40px;" /></div><div>Border: <input type="text" id="xheImgBorder" style="width:40px;" /></div><div>Hspace: <input type="text" id="xheImgHspace" style="width:40px;" /> Vspace:<input type="text" id="xheImgVspace" style="width:40px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlFlash='<div>Flash URL:<input type="text" id="xheFlashUrl" value="http://" class="xheText" /></div><div>Dimension:<input type="text" id="xheFlashWidth" style="width:40px;" value="480" /> x <input type="text" id="xheFlashHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlMedia='<div>Media URL:<input type="text" id="xheMediaUrl" value="http://" class="xheText" /></div><div>Dimension:<input type="text" id="xheMediaWidth" style="width:40px;" value="480" /> x <input type="text" id="xheMediaHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlTable='<div>Rows&Cols: <input type="text" id="xheTableRows" style="width:40px;" value="3" /> x <input type="text" id="xheTableColumns" style="width:40px;" value="2" /></div><div>Headers: <select id="xheTableHeaders"><option selected="selected" value="">None</option><option value="row">First row</option><option value="col">First column</option><option value="both">Both</option></select></div><div>Dimension: <input type="text" id="xheTableWidth" style="width:40px;" value="200" /> x <input type="text" id="xheTableHeight" style="width:40px;" value="" /></div><div>Border: <input type="text" id="xheTableBorder" style="width:40px;" value="1" /></div><div>CellSpacing:<input type="text" id="xheTableCellSpacing" style="width:40px;" value="1" /> CellPadding:<input type="text" id="xheTableCellPadding" style="width:40px;" value="1" /></div><div>Align: <select id="xheTableAlign"><option selected="selected" value="">Default</option><option value="left">Left</option><option value="center">Center</option><option value="right">Right</option></select></div><div>Caption: <input type="text" id="xheTableCaption" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlAbout='<div style="font:12px Arial;width:245px;word-wrap:break-word;word-break:break-all;"><p><span style="font-size:20px;color:#1997DF;">xhEditor</span><br />v1.1.1 (build 101002)</p><p>xhEditor is a platform independent WYSWYG XHTML editor based by jQuery,released as Open Source under <a href="http://www.gnu.org/licenses/lgpl.html" target="_blank">LGPL</a>.</p><p>Copyright © <a href="http://xheditor.com/" target="_blank">xhEditor.com</a>. All rights reserved.</p></div>';
var itemEmots={'default':{name:'Default',width:24,height:24,line:7,list:{'smile':'Smile','tongue':'Tongue','titter':'Titter','laugh':'Laugh','sad':'Sad','wronged':'Wronged','fastcry':'Fast cry','cry':'Cry','wail':'Wail','mad':'Mad','knock':'Knock','curse':'Curse','crazy':'Crazy','angry':'Angry','ohmy':'Oh my','awkward':'Awkward','panic':'Panic','shy':'Shy','cute':'Cute','envy':'Envy','proud':'Proud','struggle':'Struggle','quiet':'Quiet','shutup':'Shut up','doubt':'Doubt','despise':'Despise','sleep':'Sleep','bye':'Bye'}}};
var arrTools={Cut:{t:'Cut (Ctrl+X)'},Copy:{t:'Copy (Ctrl+C)'},Paste:{t:'Paste (Ctrl+V)'},Pastetext:{t:'Paste as plain text',h:isIE?0:1},Blocktag:{t:'Block tag',h:1},Fontface:{t:'Font family',h:1},FontSize:{t:'Font size',h:1},Bold:{t:'Bold (Ctrl+B)',s:'Ctrl+B'},Italic:{t:'Italic (Ctrl+I)',s:'Ctrl+I'},Underline:{t:'Underline (Ctrl+U)',s:'Ctrl+U'},Strikethrough:{t:'Strikethrough (Ctrl+S)',s:'Ctrl+S'},FontColor:{t:'Select text color',h:1},BackColor:{t:'Select background color',h:1},SelectAll:{t:'SelectAll (Ctrl+A)'},Removeformat:{t:'Remove formatting'},Align:{t:'Align',h:1},List:{t:'List',h:1},Outdent:{t:'Outdent (Shift+Tab)',s:'Shift+Tab'},Indent:{t:'Indent (Tab)',s:'Tab'},Link:{t:'Insert/edit link (Ctrl+K)',s:'Ctrl+K',h:1},Unlink:{t:'Unlink'},Img:{t:'Insert/edit image',h:1},Flash:{t:'Insert/edit flash',h:1},Media:{t:'Insert/edit media',h:1},Emot:{t:'Emotions',s:'ctrl+e',h:1},Table:{t:'Insert a new table',h:1},Source:{t:'Edit source code'},Preview:{t:'Preview'},Print:{t:'Print (Ctrl+P)',s:'Ctrl+P'},Fullscreen:{t:'Toggle fullscreen (Esc)',s:'Esc'},About:{t:'About xhEditor'}};
var toolsThemes={
mini:'Bold,Italic,Underline,Strikethrough,|,Align,List,|,Link,Img',
simple:'Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,|,Align,List,Outdent,Indent,|,Link,Img,Emot',
full:'Cut,Copy,Paste,Pastetext,|,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,SelectAll,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Img,Flash,Media,Emot,Table,|,Source,Preview,Print,Fullscreen'};
toolsThemes.mfull=toolsThemes.full.replace(/\|(,Align)/i,'/$1');
var arrDbClick={'a':'Link','img':'Img','embed':'Embed'},uploadInputname='filedata';
$.xheditor=function(textarea,options)
{
var defaults={skin:'default',tools:'full',clickCancelDialog:true,linkTag:false,internalScript:false,inlineScript:false,internalStyle:true,inlineStyle:true,showBlocktag:false,forcePtag:true,upLinkExt:"zip,rar,txt",upImgExt:"jpg,jpeg,gif,png",upFlashExt:"swf",upMediaExt:"wmv,avi,wma,mp3,mid",modalWidth:350,modalHeight:220,modalTitle:true,defLinkText:'Click to open link',layerShadow:3,emotMark:false,upBtnText:'Upload',wordDeepClean:true,hoverExecDelay:100,html5Upload:true,upMultiple:99};
var _this=this,_text=textarea,_jText=$(_text),_jForm=_jText.closest('form'),_jTools,_jArea,_win,_jWin,_doc,_jDoc;
var bookmark;
var bInit=false,bSource=false,bFullscreen=false,bCleanPaste=false,outerScroll,bShowBlocktag=false,sLayoutStyle='',ev=null,timer,bDisableHoverExec=false,bQuickHoverExec=false;
var lastPoint=null,lastAngle=null;//鼠标悬停显示
var editorHeight=0;
var settings=_this.settings=$.extend({},defaults,options );
var plugins=settings.plugins,strPlugins=[];
if(plugins)
{
arrTools=$.extend({},arrTools,plugins);
$.each(plugins,function(n){strPlugins.push(n);});
strPlugins=strPlugins.join(',');
}
if(settings.tools.match(/^\s*(m?full|simple|mini)\s*$/i))
{
var toolsTheme=toolsThemes[$.trim(settings.tools)];
settings.tools=(settings.tools.match(/m?full/i)&&plugins)?toolsTheme.replace('Table','Table,'+strPlugins):toolsTheme;//插件接在full的Table后面
}
if(!settings.tools.match(/(^|,)\s*About\s*(,|$)/i))settings.tools+=',About';
settings.tools=settings.tools.split(',');
if(settings.editorRoot)editorRoot=settings.editorRoot;
editorRoot=getLocalUrl(editorRoot,'abs');
//基本控件名
var idCSS='xheCSS_'+settings.skin,idContainer='xhe'+xCount+'_container',idTools='xhe'+xCount+'_Tool',idIframeArea='xhe'+xCount+'_iframearea',idIframe='xhe'+xCount+'_iframe',idFixFFCursor='xhe'+xCount+'_fixffcursor';
var headHTML='',bodyClass='',skinPath=editorRoot+'xheditor_skin/'+settings.skin+'/',arrEmots=itemEmots,urlType=settings.urlType,urlBase=settings.urlBase,emotPath=settings.emotPath,emotPath=emotPath?emotPath:editorRoot+'xheditor_emot/',selEmotGroup='';
arrEmots=$.extend({},arrEmots,settings.emots);
emotPath=getLocalUrl(emotPath,'rel',urlBase?urlBase:null);//返回最短表情路径
bShowBlocktag=settings.showBlocktag;
if(bShowBlocktag)bodyClass+=' showBlocktag';
var arrShortCuts=[];
this.init=function()
{
//加载样式表
if($('#'+idCSS).length==0)$('head').append('<link id="'+idCSS+'" rel="stylesheet" type="text/css" href="'+skinPath+'ui.css" />');
//初始化编辑器
var cw = settings.width || _text.style.width || _jText.outerWidth();
editorHeight = settings.height || _text.style.height || _jText.outerHeight();
if(is(editorHeight,'string'))editorHeight=editorHeight.replace(/[^\d]+/g,'');
if(cw<=0||editorHeight<=0)//禁止对隐藏区域里的textarea初始化编辑器
{
alert('Current textarea is hidden, please make it show before initialization xhEditor, or directly initialize the height.');
return false;
}
if(/^[0-9\.]+$/i.test(''+cw))cw+='px';
//编辑器CSS背景
var editorBackground=settings.background || _text.style.background;
//工具栏内容初始化
var arrToolsHtml=['<span class="xheGStart"/>'],tool,cn,regSeparator=/\||\//i;
$.each(settings.tools,function(i,n)
{
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGEnd"/>');
if(n=='|')arrToolsHtml.push('<span class="xheSeparator"/>');
else if(n=='/')arrToolsHtml.push('<br />');
else
{
tool=arrTools[n];
if(!tool)return;
if(tool.c)cn=tool.c;
else cn='xheIcon xheBtn'+n;
arrToolsHtml.push('<span><a href="javascript:void(0);" title="'+tool.t+'" name="'+n+'" class="xheButton xheEnabled" tabindex="-1"><span class="'+cn+'" unselectable="on" /></a></span>');
if(tool.s)_this.addShortcuts(tool.s,n);
}
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGStart"/>');
});
arrToolsHtml.push('<span class="xheGEnd"/><br />');
_jText.after($('<input type="text" id="'+idFixFFCursor+'" style="position:absolute;display:none;" /><span id="'+idContainer+'" class="xhe_'+settings.skin+'" style="display:none"><table cellspacing="0" cellpadding="0" class="xheLayout" style="width:'+cw+';height:'+editorHeight+'px;"><tbody><tr><td id="'+idTools+'" class="xheTool" unselectable="on" style="height:1px;"></td></tr><tr><td id="'+idIframeArea+'" class="xheIframeArea"><iframe frameborder="0" id="'+idIframe+'" src="javascript:;" style="width:100%;"></iframe></td></tr></tbody></table></span>'));
_jTools=$('#'+idTools);_jArea=$('#'+idIframeArea);
headHTML='<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><link rel="stylesheet" href="'+skinPath+'iframe.css"/>';
var loadCSS=settings.loadCSS;
if(loadCSS)
{
if(is(loadCSS,'array'))for(var i in loadCSS)headHTML+='<link rel="stylesheet" href="'+loadCSS[i]+'"/>';
else
{
if(loadCSS.match(/\s*<style(\s+[^>]*?)?>[\s\S]+?<\/style>\s*/i))headHTML+=loadCSS;
else headHTML+='<link rel="stylesheet" href="'+loadCSS+'"/>';
}
}
var iframeHTML='<html><head>'+headHTML;
if(editorBackground)iframeHTML+='<style>body{background:'+editorBackground+';}</style>';
iframeHTML+='</head><body spellcheck="false" class="editMode'+bodyClass+'"></body></html>';
_this.win=_win=$('#'+idIframe)[0].contentWindow;
_jWin=$(_win);
try{
this.doc=_doc = _win.document;_jDoc=$(_doc);
_doc.open();
_doc.write(iframeHTML);
_doc.close();
if(isIE)_doc.body.contentEditable='true';
else _doc.designMode = 'On';
}catch(e){}
setTimeout(setOpts,300);
_this.setSource();
_win.setInterval=null;//针对jquery 1.3无法操作iframe window问题的hack
//添加工具栏
_jTools.append(arrToolsHtml.join('')).bind('mousedown contextmenu',returnFalse).click(function(event)
{
var jButton=$(event.target).closest('a');
if(jButton.is('.xheEnabled'))
{
ev=event;
_this.exec(jButton.attr('name'));
}
return false;
});
_jTools.find('.xheButton').hover(function(event){//鼠标悬停执行
var jButton=$(this),delay=settings.hoverExecDelay;
var tAngle=lastAngle;lastAngle=null;
if(delay==-1||bDisableHoverExec||!jButton.is('.xheEnabled'))return false;
if(tAngle&&tAngle>10)//检测误操作
{
bDisableHoverExec=true;
setTimeout(function(){bDisableHoverExec=false;},100);
return false;
}
var cmd=jButton.attr('name'),bHover=arrTools[cmd].h==1;
if(!bHover)
{
_this.hidePanel();//移到非悬停按钮上隐藏面板
return false;
}
if(bQuickHoverExec)delay=0;
if(delay>=0)timer=setTimeout(function(){
ev=event;
lastPoint={x:ev.clientX,y:ev.clientY};
_this.exec(cmd);
},delay);
},function(event){lastPoint=null;if(timer)clearTimeout(timer);}).mousemove(function(event){
if(lastPoint)
{
var diff={x:event.clientX-lastPoint.x,y:event.clientY-lastPoint.y};
if(Math.abs(diff.x)>1||Math.abs(diff.y)>1)
{
if(diff.x>0&&diff.y>0)
{
var tAngle=Math.round(Math.atan(diff.y/diff.x)/0.017453293);
if(lastAngle)lastAngle=(lastAngle+tAngle)/2
else lastAngle=tAngle;
}
else lastAngle=null;
lastPoint={x:event.clientX,y:event.clientY};
}
}
});
//初始化面板
_jPanel=$('#xhePanel');
_jShadow=$('#xheShadow');
_jCntLine=$('#xheCntLine');
if(_jPanel.length==0)
{
_jPanel=$('<div id="xhePanel"></div>').mousedown(function(ev){ev.stopPropagation()});
_jShadow=$('<div id="xheShadow"></div>');
_jCntLine=$('<div id="xheCntLine"></div>');
setTimeout(function(){
$(document.body).append(_jPanel).append(_jShadow).append(_jCntLine);
},10);
}
//切换显示区域
$('#'+idContainer).show();
_jText.hide();
_jArea.css('height',editorHeight-_jTools.outerHeight());
//绑定内核事件
_jText.focus(_this.focus);
_jForm.submit(saveResult).bind('reset', loadReset);
$(window).bind('unload beforeunload',saveResult).bind('resize',fixFullHeight);
$(document).mousedown(clickCancelPanel);
if(!bCheckEscInit){$(document).keydown(checkEsc);bCheckEscInit=true;}
_jWin.focus(function(){if(settings.focus)settings.focus();}).blur(function(){if(settings.blur)settings.blur();});
if(isSafari)_jWin.click(fixAppleSel);
_jDoc.mousedown(clickCancelPanel).keydown(checkShortcuts).keypress(forcePtag).dblclick(checkDblClick).bind('mousedown click',function(ev){_jText.trigger(ev.type);});
if(isIE)
{
//IE控件上Backspace会导致页面后退
_jDoc.keydown(function(ev){var rng=_this.getRng();if(ev.which==8&&rng.item){$(rng.item(0)).remove();return false;}});
//修正IE拖动img大小不更新width和height属性值的问题
function fixResize(ev)
{
var jImg=$(ev.target),v;
if(v=jImg.css('width'))jImg.css('width','').attr('width',v.replace(/[^0-9%]+/g, ''));
if(v=jImg.css('height'))jImg.css('height','').attr('height',v.replace(/[^0-9%]+/g, ''));
}
_jDoc.bind('controlselect',function(ev){
ev=ev.target;if(!$.nodeName(ev,'IMG'))return;
$(ev).unbind('resizeend',fixResize).bind('resizeend',fixResize);
});
}
var jBody=$(_doc.documentElement);
jBody.bind('paste',cleanPaste);
if(settings.disableContextmenu)jBody.bind('contextmenu',returnFalse);
//HTML5编辑区域直接拖放上传
if(settings.html5Upload)jBody.bind('dragenter dragover',function(ev){var types;if((types=ev.originalEvent.dataTransfer.types)&&$.inArray('Files', types)!=-1)return false;}).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0){
var i,cmd,arrCmd=['Link','Img','Flash','Media'],arrExt=[],strExt;
for(i in arrCmd){
cmd=arrCmd[i];
if(settings['up'+cmd+'Url']&&settings['up'+cmd+'Url'].match(/^[^!].*/i))arrExt.push(cmd+':,'+settings['up'+cmd+'Ext']);//允许上传
}
if(arrExt.length==0)return false;//禁止上传
else strExt=arrExt.join(',');
function getCmd(fileList){
var match,fileExt,cmd;
for(i=0;i<fileList.length;i++){
fileExt=fileList[i].fileName.replace(/.+\./,'');
if(match=strExt.match(new RegExp('(\\w+):[^:]*,'+fileExt+'(?:,|$)','i'))){
if(!cmd)cmd=match[1];
else if(cmd!=match[1])return 2;
}
else return 1;
}
return cmd;
}
cmd=getCmd(fileList);
if(cmd==1)alert('Upload file extension required for this: '+strExt.replace(/\w+:,/g,''));
else if(cmd==2)alert('You can only drag and drop the same type of file.');
else if(cmd){
_this.startUpload(fileList,settings['up'+cmd+'Url'],'*',function(arrMsg){
var arrUrl=[],msg,onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用户上传回调
for(i in arrMsg){
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!')url=url.substr(1);
arrUrl.push(url);
}
_this.exec(cmd);
$('#xhe'+cmd+'Url').val(arrUrl.join(' '));
$('#xheSave').click();
});
}
return false;
}
});
//添加用户快捷键
var shortcuts=settings.shortcuts;
if(shortcuts)$.each(shortcuts,function(key,func){_this.addShortcuts(key,func);});
xCount++;
bInit=true;
if(settings.fullscreen)_this.toggleFullscreen();
else if(settings.sourceMode)setTimeout(_this.toggleSource,20);
return true;
}
this.remove=function()
{
_this.hidePanel();
saveResult();//卸载前同步最新内容到textarea
//取消绑定事件
_jText.unbind('focus',_this.focus);
_jForm.unbind('submit',saveResult).unbind('reset', loadReset);
$(window).unbind('unload beforeunload',saveResult).unbind('resize',fixFullHeight);
$(document).unbind('mousedown',clickCancelPanel);
$('#'+idContainer+','+'#'+idFixFFCursor).remove();
_jText.show();
bInit=false;
}
this.saveBookmark=function(){
if(!bSource){
var rng=_this.getRng();
rng=rng.cloneRange?rng.cloneRange():rng;
bookmark={'top':_jWin.scrollTop(),'rng':rng};
}
}
this.loadBookmark=function()
{
if(bSource||!bookmark)return;
_this.focus();
var rng=bookmark.rng;
if(isIE)rng.select();
else
{
var sel=_this.getSel();
sel.removeAllRanges();
sel.addRange(rng);
}
_jWin.scrollTop(bookmark.top);
bookmark=null;
}
this.focus=function()
{
if(!bSource)_jWin.focus();
else $('#sourceCode',_doc).focus();
return false;
}
this.setCursorFirst=function(firstBlock)
{
_this.focus();_win.scrollTo(0,0);
var rng=_this.getRng(),_body=_doc.body,firstNode=_body,firstTag;
if(firstBlock&&firstNode.firstChild&&(firstTag=firstNode.firstChild.tagName)&&firstTag.match(/^p|div|h[1-6]$/i))firstNode=_body.firstChild;
isIE?rng.moveToElementText(firstNode):rng.setStart(firstNode,0);
rng.collapse(true);
if(isIE)rng.select();
else{var sel=_this.getSel();sel.removeAllRanges();sel.addRange(rng);}
}
this.getSel=function()
{
return _win.getSelection ? _win.getSelection() : _doc.selection;
}
this.getRng=function()
{
var sel=_this.getSel(),rng;
try{
rng = sel.rangeCount > 0 ? sel.getRangeAt(0) : (sel.createRange ? sel.createRange() : (_doc.createRange?_doc.createRange():_doc.body.createTextRange()));
}catch (ex){}
return rng;
}
this.getParent=function(tag)
{
var rng=_this.getRng(),p;
if(!isIE)
{
p = rng.commonAncestorContainer;
if(!rng.collapsed)if(rng.startContainer == rng.endContainer&&rng.startOffset - rng.endOffset < 2&&rng.startContainer.hasChildNodes())p = rng.startContainer.childNodes[rng.startOffset];
}
else p=rng.item?rng.item(0):rng.parentElement();
tag=tag?tag:'*';p=$(p);
if(!p.is(tag))p=$(p).closest(tag);
return p;
}
this.getSelect=function(format)
{
var sel=_this.getSel(),rng=_this.getRng(),isCollapsed=true;
if (!rng || rng.item)isCollapsed=false
else isCollapsed=!sel || rng.boundingWidth == 0 || rng.collapsed;
if(format=='text')return isCollapsed ? '' : (rng.text || (sel.toString ? sel.toString() : ''));
var sHtml;
if(rng.cloneContents)
{
var tmp=$('<div></div>'),c;
c = rng.cloneContents();
if(c)tmp.append(c);
sHtml=tmp.html();
}
else if(is(rng.item))sHtml=rng.item(0).outerHTML;
else if(is(rng.htmlText))sHtml=rng.htmlText;
else sHtml=rng.toString();
if(isCollapsed)sHtml='';
sHtml=_this.processHTML(sHtml,'read');
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
return sHtml;
}
this.pasteHTML=function(sHtml,bStart)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
var sel=_this.getSel(),rng=_this.getRng();
if(bStart!=undefined)//非覆盖式插入
{
if(rng.item)
{
var n=rng.item(0);
rng=_doc.body.createTextRange();
rng.moveToElementText(n);
rng.select();
}
rng.collapse(bStart);
}
sHtml+='<'+(isIE?'img':'span')+' id="_xhe_temp" style="display:none" />';
if(rng.insertNode)
{
rng.deleteContents();
rng.insertNode(rng.createContextualFragment(sHtml));
}
else
{
if(sel.type.toLowerCase()=='control'){sel.clear();rng=_this.getRng();};
rng.pasteHTML(sHtml);
}
var jTemp=$('#_xhe_temp',_doc),temp=jTemp[0];
if(isIE)
{
rng.moveToElementText(temp);
rng.select();
}
else
{
rng.selectNode(temp);
sel.removeAllRanges();
sel.addRange(rng);
}
jTemp.remove();
}
this.pasteText=function(text,bStart)
{
if(!text)text='';
text=_this.domEncode(text);
text = text.replace(/\r?\n/g, '<br />');
_this.pasteHTML(text,bStart);
}
this.appendHTML=function(sHtml)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
$(_doc.body).append(sHtml);
}
this.domEncode=function(str)
{
return str.replace(/[<>]/g,function(c){return {'<':'<','>':'>'}[c];});
}
this.setSource=function(sHtml)
{
bookmark=null;
if(typeof sHtml!='string'&&sHtml!='')sHtml=_text.value;
if(bSource)$('#sourceCode',_doc).val(sHtml);
else
{
if(settings.beforeSetSource)sHtml=settings.beforeSetSource(sHtml);
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
sHtml=_this.cleanWord(sHtml);
sHtml=_this.processHTML(sHtml,'write');
if(isIE){//修正IE会删除可视内容前的script,style,<!--
_doc.body.innerHTML='<img id="_xhe_temp" style="display:none" />'+sHtml;
$('#_xhe_temp',_doc).remove();
}
else _doc.body.innerHTML=sHtml;
}
}
this.processHTML=function(sHtml,mode)
{
var appleClass=' class="Apple-style-span"';
if(mode=='write')
{//write
//恢复emot
function restoreEmot(all,attr,q,emot)
{
emot=emot.split(',');
if(!emot[1]){emot[1]=emot[0];emot[0]=''}
if(emot[0]=='default')emot[0]='';
return all.replace(/\s+src\s*=\s*(["']?).*?\1(\s|$|\/|>)/i,'$2').replace(attr,' src="'+emotPath+(emot[0]?emot[0]:'default')+'/'+emot[1]+'.gif"'+(settings.emotMark?' emot="'+(emot[0]?emot[0]+',':'')+emot[1]+'"'+(all.match(/\s+alt\s*=\s*(["']?)\s*(.*?)\s*\1[\s\/>]/i)?'':' alt="'+emot[1]+'"'):''));
}
sHtml = sHtml.replace(/<img(?:\s+[^>]*?)?(\s+emot\s*=\s*(["']?)\s*(.*?)\s*\2)(?:\s+[^>]*?)?\/?>/ig,restoreEmot);
//保存属性值:src,href
function saveValue(all,tag,attr,n,q,v){return all.replace(attr,(urlBase?(' '+n+'="'+getLocalUrl(v,'abs',urlBase)+'"'):attr)+' _xhe_'+n+'="'+v+'"');}
sHtml = sHtml.replace(/<(\w+(?:\:\w+)?)(?:\s+[^>]*?)?(\s+(src|href)\s*=\s*(["']?)\s*(.*?)\s*\4)(?:\s+[^>]*?)?\/?>/ig,saveValue);
sHtml = sHtml.replace(/<(\/?)del(\s+[^>]*?)?>/ig,'<$1strike$2>');//编辑状态统一转为strike
if(isMozilla)
{
sHtml = sHtml.replace(/<(\/?)strong(\s+[^>]*?)?>/ig,'<$1b$2>');
sHtml = sHtml.replace(/<(\/?)em(\s+[^>]*?)?>/ig,'<$1i$2>');
}
else if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.n){s=t.wkn;break;}
}
return pre+'font-size:'+s+aft;
});
sHtml = sHtml.replace(/<strong(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-weight: bold;"$1>');
sHtml = sHtml.replace(/<em(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-style: italic;"$1>');
sHtml = sHtml.replace(/<u(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: underline;"$1>');
sHtml = sHtml.replace(/<strike(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: line-through;"$1>');
sHtml = sHtml.replace(/<\/(strong|em|u|strike)>/ig,'</span>');
sHtml = sHtml.replace(/<span((?:\s+[^>]*?)?\s+style="([^"]*;)*\s*(font-family|font-size|color|background-color)\s*:\s*[^;"]+\s*;?"[^>]*)>/ig,'<span'+appleClass+'$1>');
}
else if(isIE)
{
sHtml = sHtml.replace(/'/ig, ''');
sHtml = sHtml.replace(/\s+(disabled|checked|readonly|selected)\s*=\s*[\"\']?(false|0)[\"\']?/ig, '');
}
sHtml = sHtml.replace(/<a(\s+[^>]*?)?\/>/,'<a$1></a>');
if(!isSafari)
{
//style转font
function style2font(all,tag,style,content)
{
var attrs='',f,s1,s2,c;
f=style.match(/font-family\s*:\s*([^;"]+)/i);
if(f)attrs+=' face="'+f[1]+'"';
s1=style.match(/font-size\s*:\s*([^;"]+)/i);
if(s1)
{
s1=s1[1].toLowerCase();
for(var j=0;j<arrFontsize.length;j++)if(s1==arrFontsize[j].n||s1==arrFontsize[j].s){s2=j+1;break;}
if(s2)
{
attrs+=' size="'+s2+'"';
style=style.replace(/(^|;)(\s*font-size\s*:\s*[^;"]+;?)+/ig,'$1');
}
}
c=style.match(/(?:^|[\s;])color\s*:\s*([^;"]+)/i);
if(c)
{
var rgb;
if(rgb=c[1].match(/\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)){c[1]='#';for(var i=1;i<=3;i++)c[1]+=(rgb[i]-0).toString(16);}
c[1]=c[1].replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,'#$1$1$2$2$3$3');
attrs+=' color="'+c[1]+'"';
}
style=style.replace(/(^|;)(\s*(font-family|color)\s*:\s*[^;"]+;?)+/ig,'$1');
if(attrs!='')
{
if(style)attrs+=' style="'+style+'"';
return '<font'+attrs+'>'+content+"</font>";
}
else return all;
}
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,style2font);//最里层
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,style2font);//第2层
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,style2font);//第3层
}
}
else
{//read
//恢复属性值src,href
function restoreValue(all,n,q,v)
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
return all.replace(new RegExp('\\s+'+n+'\\s*=\\s*(["\']?).*?\\1(\\s|/?>)','ig'),' '+n+'="'+v.replace(/\$/g,'$$$$')+'"$2');
}
sHtml = sHtml.replace(/<(?:\w+(?:\:\w+)?)(?:\s+[^>]*?)?\s+_xhe_(src|href)\s*=\s*(["']?)\s*(.*?)\s*\2(?:\s+[^>]*?)?\/?>/ig,restoreValue);
if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.wkn){s=t.n;break;}
}
return pre+'font-size:'+s+aft;
});
var arrAppleSpan=[{r:/font-weight:\sbold/ig,t:'strong'},{r:/font-style:\sitalic/ig,t:'em'},{r:/text-decoration:\sunderline/ig,t:'u'},{r:/text-decoration:\sline-through/ig,t:'strike'}];
function replaceAppleSpan(all,tag,attr1,attr2,content)
{
var attr=attr1+attr2,newTag='';
if(!attr)return content;
for(var i=0;i<arrAppleSpan.length;i++)
{
if(attr.match(arrAppleSpan[i].r))
{
newTag=arrAppleSpan[i].t;
break;
}
}
if(newTag)return '<'+newTag+'>'+content+'</'+newTag+'>';
else return all;
}
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,replaceAppleSpan);//最里层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第2层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第3层
}
if(!isIE){//字符间的文本换行强制转br
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/([^<>\r\n]?)((?:\r?\n)+)([^<>\r\n]?)/ig,function(all,left,br,right){if(left||right)return left+br.replace(/\r?\n/g,'<br />')+right;else return all;});
});
}
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+(?:_xhe_|_moz_|_webkit_)[^=]+?\s*=\s*(["']?).*?\2(\s|\/?>)/ig,'$1$3');
sHtml = sHtml.replace(/(<\w+[^>]*?)\s+class\s*=\s*(["']?)\s*(?:apple|webkit)\-.+?\s*\2(\s|\/?>)/ig, "$1$3");
sHtml = sHtml.replace(/<img(\s+[^>]+?)\/?>/ig,function(all,attr){if(!attr.match(/\s+alt\s*(["']?).*?\1(\s|$)/i))attr+=' alt=""';return '<img'+attr+' />';});//img强制加alt
sHtml = sHtml.replace(/\s+jquery\d+="\d+"/ig,'');
}
return sHtml;
}
this.getSource=function(bFormat)
{
var sHtml,beforeGetSource=settings.beforeGetSource;
if(bSource)
{
sHtml=$('#sourceCode',_doc).val();
if(!beforeGetSource){
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/(\t*\r?\n\t*)+/g,'')//标准HTML模式清理缩进和换行
});
}
}
else
{
sHtml=_this.processHTML(_doc.body.innerHTML,'read');
sHtml=sHtml.replace(/^\s*(?:<(p|div)(?:\s+[^>]*?)?>)?\s*(<br(?:\s+[^>]*?)?>)*\s*(?:<\/\1>)?\s*$/i, '');//修正Firefox在空内容情况下多出来的代码
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml,bFormat);
sHtml=_this.cleanWord(sHtml);
if(beforeGetSource)sHtml=beforeGetSource(sHtml);
}
_text.value=sHtml;
return sHtml;
}
this.cleanWord=function(sHtml)
{
if(sHtml.match(/mso(-|normal)|WordDocument/i))
{
var deepClean=settings.wordDeepClean;
//格式化
sHtml = sHtml.replace(/(<link(?:\s+[^>]*?)?)\s+href\s*=\s*(["']?)\s*file:\/\/.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, '');
//区块标签清理
sHtml = sHtml.replace(/<!--[\s\S]*?-->|<!(--)?\[[\s\S]+?\](--)?>|<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
sHtml = sHtml.replace(/<\/?\w+:[^>]*>/ig, '');
if(deepClean)sHtml = sHtml.replace(/<\/?(span|a|img)(\s+[^>]*?)?>/ig,'');
//属性清理
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+class\s*=\s*(["']?)\s*mso.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//删除所有mso开头的样式
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+lang\s*=\s*(["']?)\s*.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//删除lang属性
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+align\s*=\s*(["']?)\s*left\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//取消align=left
//样式清理
sHtml = sHtml.replace(/<\w+(?:\s+[^>]*?)?(\s+style\s*=\s*(["']?)\s*([\s\S]*?)\s*\2)(?:\s+[^>]*?)?\s*\/?>/ig,function(all,attr,p,styles){
styles=$.trim(styles.replace(/\s*(mso-[^:]+:.+?|margin\s*:\s*0cm 0cm 0pt\s*|(text-align|font-variant|line-height)\s*:\s*.+?)(;|$)\s*/ig,''));
return all.replace(attr,deepClean?'':styles?' style="'+styles+'"':'');
});
}
return sHtml;
}
this.cleanHTML=function(sHtml)
{
sHtml = sHtml.replace(/<!?\/?(DOCTYPE|html|body|meta)(\s+[^>]*?)?>/ig, '');
var arrHeadSave;sHtml = sHtml.replace(/<head(?:\s+[^>]*?)?>([\s\S]*?)<\/head>/i, function(all,content){arrHeadSave=content.match(/<(script|style)(\s+[^>]*?)?>[\s\S]*?<\/\1>/ig);return '';});
if(arrHeadSave)sHtml=arrHeadSave.join('')+sHtml;
sHtml = sHtml.replace(/<\??xml(:\w+)?(\s+[^>]*?)?>([\s\S]*?<\/xml>)?/ig, '');
if(!settings.linkTag)sHtml = sHtml.replace(/<link(\s+[^>]*?)?>/ig, '');
if(!settings.internalScript)sHtml = sHtml.replace(/<script(\s+[^>]*?)?>[\s\S]*?<\/script>/ig, '');
if(!settings.inlineScript)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+on(?:click|dblclick|mousedown|mouseup|mousemove|mouseover|mouseout|mouseenter|mouseleave|keydown|keypress|keyup|change|select|submit|reset|blur|focus|load|unload)\s*=\s*(["']?)[\s\S]*?\3((?:\s+[^>]*?)?\/?>)/ig,'$1$2$4');
if(!settings.internalStyle)sHtml = sHtml.replace(/<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
if(!settings.inlineStyle)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+(style|class)\s*=\s*(["']?)[\s\S]*?\4((?:\s+[^>]*?)?\/?>)/ig,'$1$2$5');
sHtml=sHtml.replace(/<\/(strong|b|u|strike|em|i)>((?:\s|<br\/?>| )*?)<\1(\s+[^>]*?)?>/ig,'$2');//连续相同标签
return sHtml;
}
this.formatXHTML=function(sHtml,bFormat)
{
var emptyTags = makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");//HTML 4.01
var blockTags = makeMap("address,applet,blockquote,button,center,dd,dir,div,dl,dt,fieldset,form,frameset,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");//HTML 4.01
var inlineTags = makeMap("a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");//HTML 4.01
var closeSelfTags = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
var fillAttrsTags = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
var specialTags = makeMap("script,style");
var tagReplac={'b':'strong','i':'em','s':'del','strike':'del'};
var startTag = /^<\??(\w+(?:\:\w+)?)((?:\s+[\w-\:]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/(\w+(?:\:\w+)?)[^>]*>/;
var attr = /\s+([\w-]+(?:\:\w+)?)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s]+)))?/g;
var skip=0,stack=[],last=sHtml,results=Array(),lvl=-1,lastTag='body',lastTagStart;
stack.last = function(){return this[ this.length - 1 ];};
while(last.length>0)
{
if(!stack.last()||!specialTags[stack.last()])
{
skip=0;
if(last.substring(0, 4)=='<!--')
{//注释标签
skip=last.indexOf("-->");
if(skip!=-1)
{
skip+=3;
addHtmlFrag(last.substring(0,skip));
}
}
else if(last.substring(0, 2)=='</')
{//结束标签
match = last.match( endTag );
if(match)
{
parseEndTag(match[1]);
skip = match[0].length;
}
}
else if(last.charAt(0)=='<')
{//开始标签
match = last.match( startTag );
if(match)
{
parseStartTag(match[1],match[2],match[3]);
skip = match[0].length;
}
}
if(skip==0)//普通文本
{
skip=last.indexOf('<');
if(skip==0)skip=1;
else if(skip<0)skip=last.length;
addHtmlFrag(_this.domEncode(last.substring(0,skip)));
}
last=last.substring(skip);
}
else
{//处理style和script
last=last.replace(/^([\s\S]*?)<\/(style|script)>/i, function(all, script,tagName){
results.push(script);
return ''
});
parseEndTag(stack.last());
}
}
parseEndTag();
sHtml=results.join('');
results=null;
function makeMap(str)
{
var obj = {}, items = str.split(",");
for ( var i = 0; i < items.length; i++ )obj[ items[i] ] = true;
return obj;
}
function processTag(tagName)
{
if(tagName)
{
tagName=tagName.toLowerCase();
var tag=tagReplac[tagName];
if(tag)tagName=tag;
}
else tagName='';
return tagName;
}
function parseStartTag(tagName,rest,unary)
{
tagName=processTag(tagName);
if(blockTags[tagName])while(stack.last()&&inlineTags[stack.last()])parseEndTag(stack.last());
if(closeSelfTags[tagName]&&stack.last()==tagName)parseEndTag(tagName);
unary = emptyTags[ tagName ] || !!unary;
if (!unary)stack.push(tagName);
var all=Array();
all.push('<' + tagName);
rest.replace(attr, function(match, name)
{
name=name.toLowerCase();
var value = arguments[2] ? arguments[2] :
arguments[3] ? arguments[3] :
arguments[4] ? arguments[4] :
fillAttrsTags[name] ? name : "";
all.push(' '+name+'="'+value+'"');
});
all.push((unary ? " /" : "") + ">");
addHtmlFrag(all.join(''),tagName,true);
}
function parseEndTag(tagName)
{
if(!tagName)var pos=0;//清空栈
else
{
tagName=processTag(tagName);
for(var pos=stack.length-1;pos>=0;pos--)if(stack[pos]==tagName)break;//向上寻找匹配的开始标签
}
if(pos>=0)
{
for(var i=stack.length-1;i>=pos;i--)addHtmlFrag("</" + stack[i] + ">",stack[i]);
stack.length=pos;
}
}
function addHtmlFrag(html,tagName,bStart)
{
if(bFormat==true)
{
html=html.replace(/(\t*\r?\n\t*)+/g,'');//清理换行符和相邻的制表符
if(html.match(/^\s*$/))return;//不格式化空内容的标签
var bBlock=blockTags[tagName],tag=bBlock?tagName:'';
if(bBlock)
{
if(bStart)lvl++;//块开始
if(lastTag=='')lvl--;//补文本结束
}
else if(lastTag)lvl++;//文本开始
if(tag!=lastTag||bBlock)addIndent();
results.push(html);
if(tagName=='br')addIndent();//回车强制换行
if(bBlock&&(emptyTags[tagName]||!bStart))lvl--;//块结束
lastTag=bBlock?tagName:'';lastTagStart=bStart;
}
else results.push(html);
}
function addIndent(){results.push('\r\n');if(lvl>0){var tabs=lvl;while(tabs--)results.push("\t");}}
//font转style
function font2style(all,tag,attrs,content)
{
if(!attrs)return content;
var styles='',f,s,c,style;
f=attrs.match(/ face\s*=\s*"\s*([^"]+)\s*"/i);
if(f)styles+='font-family:'+f[1]+';';
s=attrs.match(/ size\s*=\s*"\s*(\d+)\s*"/i);
if(s)styles+='font-size:'+arrFontsize[(s[1]>7?7:(s[1]<1?1:s[1]))-1].n+';';
c=attrs.match(/ color\s*=\s*"\s*([^"]+)\s*"/i);
if(c)styles+='color:'+c[1]+';';
style=attrs.match(/ style\s*=\s*"\s*([^"]+)\s*"/i);
if(style)styles+=style[1];
if(styles)content='<span style="'+styles+'">'+content+'</span>';
return content;
}
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,font2style);//最里层
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,font2style);//第2层
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,font2style);//第3层
sHtml = sHtml.replace(/^(\s*\r?\n)+|(\s*\r?\n)+$/g,'');//清理首尾换行
sHtml = sHtml.replace(/(\t*\r?\n)+/g,'\r\n');//多行变一行
return sHtml;
}
this.toggleShowBlocktag=function(state)
{
if(bShowBlocktag===state)return;
bShowBlocktag=!bShowBlocktag;
var _jBody=$(_doc.body);
if(bShowBlocktag)
{
bodyClass+=' showBlocktag';
_jBody.addClass('showBlocktag');
}
else
{
bodyClass=bodyClass.replace(' showBlocktag','');
_jBody.removeClass('showBlocktag');
}
}
this.toggleSource=function(state)
{
if(bSource===state)return;
_jTools.find('[name=Source]').toggleClass('xheEnabled').toggleClass('xheActive');
var _body=_doc.body,jBody=$(_body),sHtml;
var sourceCode,cursorMark='<span id="_xhe_cursor'+new Date().getTime()+'"></span>',cursorPos=0;
if(!bSource)
{//转为源代码模式
_this.pasteHTML(cursorMark,true);//标记当前位置
sHtml=_this.getSource(true);
cursorPos=sHtml.indexOf(cursorMark);
if(!isOpera)cursorPos=sHtml.substring(0,cursorPos).replace(/\r/g,'').length;//修正非opera光标定位点
sHtml=sHtml.replace(cursorMark,'');
if(isIE)_body.contentEditable='false';
else _doc.designMode = 'Off';
jBody.attr('scroll','no').attr('class','sourceMode').html('<textarea id="sourceCode" wrap="soft" spellcheck="false" height="100%" />');
sourceCode=$('#sourceCode',jBody).blur(_this.getSource)[0];
}
else
{//转为编辑模式
sHtml=_this.getSource();
jBody.html('').removeAttr('scroll').attr('class','editMode'+bodyClass);
if(isIE)_body.contentEditable='true';
else _doc.designMode = 'On';
if(isMozilla)
{
_this._exec("inserthtml","-");//修正firefox源代码切换回来无法删除文字的问题
$('#'+idFixFFCursor).show().focus().hide();//临时修正Firefox 3.6光标丢失问题
}
}
bSource=!bSource;
_this.setSource(sHtml);
if(bSource)//光标定位源码
{
_this.focus();
if(sourceCode.setSelectionRange)sourceCode.setSelectionRange(cursorPos, cursorPos);
else
{
var rng = sourceCode.createTextRange();
rng.move("character",cursorPos);
rng.select();
}
}
else _this.setCursorFirst(true);//定位最前面
_jTools.find('[name=Source],[name=Preview]').toggleClass('xheEnabled');
_jTools.find('.xheButton').not('[name=Source],[name=Fullscreen],[name=About]').toggleClass('xheEnabled');
setTimeout(setOpts,300);
}
this.showPreview=function()
{
var beforeSetSource=settings.beforeSetSource,sContent=_this.getSource();
if(beforeSetSource)sContent=beforeSetSource(sContent);
var sHTML='<html><head>'+headHTML+'<title>Preview</title>'+(urlBase?'<base href="'+urlBase+'"/>':'')+'</head><body>' + sContent + '</body></html>';
var screen=window.screen,oWindow=window.open('', 'xhePreview', 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+Math.round(screen.width*0.9)+',height='+Math.round(screen.height*0.8)+',left='+Math.round(screen.width*0.05)),oDoc=oWindow.document;
oDoc.open();
oDoc.write(sHTML);
oDoc.close();
oWindow.focus();
}
this.toggleFullscreen=function(state)
{
if(bFullscreen===state)return;
var jLayout=$('#'+idContainer).find('.xheLayout'),jContainer=$('#'+idContainer);
if(bFullscreen)
{//取消全屏
jLayout.attr('style',sLayoutStyle);
_jArea.height(editorHeight-_jTools.outerHeight());
setTimeout(function(){$(window).scrollTop(outerScroll);},10);
}
else
{//显示全屏
outerScroll=$(window).scrollTop();
sLayoutStyle=jLayout.attr('style');
jLayout.removeAttr('style');
_jArea.height('100%');
setTimeout(fixFullHeight,100);
}
if(isMozilla)//临时修正Firefox 3.6源代码光标丢失问题
{
$('#'+idFixFFCursor).show().focus().hide();
setTimeout(_this.focus,1);
}
bFullscreen=!bFullscreen;
jContainer.toggleClass('xhe_Fullscreen');
$('html').toggleClass('xhe_Fullfix');
_jTools.find('[name=Fullscreen]').toggleClass('xheActive');
setTimeout(setOpts,300);
}
this.showMenu=function(menuitems,callback)
{
var jMenu=$('<div class="xheMenu"></div>'),arrItem=[];
$.each(menuitems,function(n,v){arrItem.push('<a href="javascript:void(0);" title="'+(v.t?v.t:v.s)+'" v="'+v.v+'">'+v.s+'</a>');});
jMenu.append(arrItem.join(''));
jMenu.click(function(ev){callback($(ev.target).closest('a').attr('v'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jMenu);
}
this.showColor=function(callback)
{
var jColor=$('<div class="xheColor"></div>'),arrItem=[],count=0;
$.each(itemColors,function(n,v)
{
if(count%7==0)arrItem.push((count>0?'</div>':'')+'<div>');
arrItem.push('<a href="javascript:void(0);" xhev="'+v+'" title="'+v+'" style="background:'+v+'"></a>');
count++;
});
arrItem.push('</div>');
jColor.append(arrItem.join(''));
jColor.click(function(ev){ev=ev.target;if(!$.nodeName(ev,'A'))return;callback($(ev).attr('xhev'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jColor);
}
this.showPastetext=function()
{
var jPastetext=$(htmlPastetext),jValue=$('#xhePastetextValue',jPastetext),jSave=$('#xheSave',jPastetext);
jSave.click(function(){
_this.loadBookmark();
var sValue=jValue.val();
if(sValue)_this.pasteText(sValue);
_this.hidePanel();
return false;
});
_this.showDialog(jPastetext);
}
this.showLink=function()
{
var jLink=$(htmlLink),jParent=_this.getParent('a'),jText=$('#xheLinkText',jLink),jUrl=$('#xheLinkUrl',jLink),jTarget=$('#xheLinkTarget',jLink),jSave=$('#xheSave',jLink),selHtml=_this.getSelect();
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'href'));
jTarget.attr('value',jParent.attr('target'));
}
else if(selHtml=='')jText.val(settings.defLinkText).closest('div').show();
if(settings.upLinkUrl)_this.uploadInit(jUrl,settings.upLinkUrl,settings.upLinkExt);
jSave.click(function(){
var url=jUrl.val();
_this.loadBookmark();
if(url==''||jParent.length==0)_this._exec('unlink');
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sTarget=jTarget.val(),sText=jText.val();
if(aUrl.length>1)
{//批量插入
_this._exec('unlink');//批量前删除当前链接并重新获取选择内容
selHtml=_this.getSelect();
var sTemplate='<a href="xhe_tmpurl"',sLink,arrLink=[];
if(sTarget!='')sTemplate+=' target="'+sTarget+'"';
sTemplate+='>xhe_tmptext</a>';
sText=(selHtml!=''?selHtml:(sText?sText:url));
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sLink=sTemplate;
sLink=sLink.replace('xhe_tmpurl',url[0]);
sLink=sLink.replace('xhe_tmptext',url[1]?url[1]:sText);
arrLink.push(sLink);
}
}
_this.pasteHTML(arrLink.join(' '));
}
else
{//单url模式
url=aUrl[0].split('||');
if(!sText)sText=url[0];
sText=url[1]?url[1]:(selHtml!='')?'':sText?sText:url[0];
if(jParent.length==0)
{
if(sText)_this.pasteHTML('<a href="#xhe_tmpurl">'+sText+'</a>');
else _this._exec('createlink','#xhe_tmpurl');
jParent=$('a[href$="#xhe_tmpurl"]',_doc);
}
else if(sText&&!isSafari)jParent.text(sText);//safari改写文本会导致光标丢失
xheAttr(jParent,'href',url[0]);
if(sTarget!='')jParent.attr('target',sTarget);
else jParent.removeAttr('target');
}
}
_this.hidePanel();
return false;
});
_this.showDialog(jLink);
}
this.showImg=function()
{
var jImg=$(htmlImg),jParent=_this.getParent('img'),jUrl=$('#xheImgUrl',jImg),jAlt=$('#xheImgAlt',jImg),jAlign=$('#xheImgAlign',jImg),jWidth=$('#xheImgWidth',jImg),jHeight=$('#xheImgHeight',jImg),jBorder=$('#xheImgBorder',jImg),jVspace=$('#xheImgVspace',jImg),jHspace=$('#xheImgHspace',jImg),jSave=$('#xheSave',jImg);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jAlt.val(jParent.attr('alt'));
jAlign.val(jParent.attr('align'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
jBorder.val(jParent.attr('border'));
var vspace=jParent.attr('vspace'),hspace=jParent.attr('hspace');
jVspace.val(vspace<=0?'':vspace);
jHspace.val(hspace<=0?'':hspace);
}
if(settings.upImgUrl)_this.uploadInit(jUrl,settings.upImgUrl,settings.upImgExt);
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sAlt=jAlt.val(),sAlign=jAlign.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sBorder=jBorder.val(),sVspace=jVspace.val(),sHspace=jHspace.val();;
if(aUrl.length>1)
{//批量插入
var sTemplate='<img src="xhe_tmpurl"',sImg,arrImg=[];
if(sAlt!='')sTemplate+=' alt="'+sAlt+'"';
if(sAlign!='')sTemplate+=' align="'+sAlign+'"';
if(sWidth!='')sTemplate+=' width="'+sWidth+'"';
if(sHeight!='')sTemplate+=' height="'+sHeight+'"';
if(sBorder!='')sTemplate+=' border="'+sBorder+'"';
if(sVspace!='')sTemplate+=' vspace="'+sVspace+'"';
if(sHspace!='')sTemplate+=' hspace="'+sHspace+'"';
sTemplate+=' />';
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sImg=sTemplate;
sImg=sImg.replace('xhe_tmpurl',url[0]);
if(url[1])sImg='<a href="'+url[1]+'" target="_blank">'+sImg+'</a>'
arrImg.push(sImg);
}
}
_this.pasteHTML(arrImg.join(' '));
}
else if(aUrl.length==1)
{//单URL模式
url=aUrl[0];
if(url!='')
{
url=url.split('||');
if(jParent.length==0)
{
_this.pasteHTML('<img src="'+url[0]+'#xhe_tmpurl" />');
jParent=$('img[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0])
if(sAlt!='')jParent.attr('alt',sAlt);
if(sAlign!='')jParent.attr('align',sAlign);
else jParent.removeAttr('align');
if(sWidth!='')jParent.attr('width',sWidth);
else jParent.removeAttr('width');
if(sHeight!='')jParent.attr('height',sHeight);
else jParent.removeAttr('height');
if(sBorder!='')jParent.attr('border',sBorder);
else jParent.removeAttr('border');
if(sVspace!='')jParent.attr('vspace',sVspace);
else jParent.removeAttr('vspace');
if(sHspace!='')jParent.attr('hspace',sHspace);
else jParent.removeAttr('hspace');
if(url[1])
{
var jLink=jParent.parent('a');
if(jLink.length==0)
{
jParent.wrap('<a></a>');
jLink=jParent.parent('a');
}
xheAttr(jLink,'href',url[1]);
jLink.attr('target','_blank');
}
}
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
_this.showDialog(jImg);
}
this.showEmbed=function(sType,sHtml,sMime,sClsID,sBaseAttrs,sUploadUrl,sUploadExt)
{
var jEmbed=$(sHtml),jParent=_this.getParent('embed[type="'+sMime+'"],embed[classid="'+sClsID+'"]'),jUrl=$('#xhe'+sType+'Url',jEmbed),jWidth=$('#xhe'+sType+'Width',jEmbed),jHeight=$('#xhe'+sType+'Height',jEmbed),jSave=$('#xheSave',jEmbed);
if(sUploadUrl)_this.uploadInit(jUrl,sUploadUrl,sUploadExt);
_this.showDialog(jEmbed);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
}
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var w=jWidth.val(),h=jHeight.val(),reg=/^[0-9]+$/;
if(!reg.test(w))w=412;if(!reg.test(h))h=300;
var sBaseCode='<embed type="'+sMime+'" classid="'+sClsID+'" src="xhe_tmpurl"'+sBaseAttrs;
var aUrl=url.split(' ');
if(aUrl.length>1)
{//批量插入
var sTemplate=sBaseCode+'',sEmbed,arrEmbed=[];
sTemplate+=' width="xhe_width" height="xhe_height" />';
for(var i in aUrl)
{
url=aUrl[i].split('||');
sEmbed=sTemplate;
sEmbed=sEmbed.replace('xhe_tmpurl',url[0])
sEmbed=sEmbed.replace('xhe_width',url[1]?url[1]:w)
sEmbed=sEmbed.replace('xhe_height',url[2]?url[2]:h)
if(url!='')arrEmbed.push(sEmbed);
}
_this.pasteHTML(arrEmbed.join(' '));
}
else if(aUrl.length==1)
{//单URL模式
url=aUrl[0].split('||');
if(jParent.length==0)
{
_this.pasteHTML(sBaseCode.replace('xhe_tmpurl',url[0]+'#xhe_tmpurl')+' />');
jParent=$('embed[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0]);
jParent.attr('width',url[1]?url[1]:w);
jParent.attr('height',url[2]?url[2]:h);
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
}
this.showEmot=function(group)
{
var jEmot=$('<div class="xheEmot"></div>');
group=group?group:(selEmotGroup?selEmotGroup:'default');
var arrEmot=arrEmots[group];
var sEmotPath=emotPath+group+'/',n=0,arrList=[],jList='';
var ew=arrEmot.width,eh=arrEmot.height,line=arrEmot.line,count=arrEmot.count,list=arrEmot.list;
if(count)
{
for(var i=1;i<=count;i++)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+i+'.gif);" emot="'+group+','+i+'" xhev=""> </a>');
if(n%line==0)arrList.push('<br />');
}
}
else
{
$.each(list,function(id,title)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+id+'.gif);" emot="'+group+','+id+'" title="'+title+'" xhev="'+title+'"> </a>');
if(n%line==0)arrList.push('<br />');
});
}
var w=line*(ew+12),h=Math.ceil(n/line)*(eh+12),mh=w*0.75;
if(h<=mh)mh='';
jList=$('<style>'+(mh?'.xheEmot div{width:'+(w+20)+'px;height:'+mh+'px;}':'')+'.xheEmot div a{width:'+ew+'px;height:'+eh+'px;}</style><div>'+arrList.join('')+'</div>').click(function(ev){ev=ev.target;var jA=$(ev);if(!$.nodeName(ev,'A'))return;_this.pasteHTML('<img emot="'+jA.attr('emot')+'" alt="'+jA.attr('xhev')+'">');_this.hidePanel();return false;}).mousedown(returnFalse);
jEmot.append(jList);
var gcount=0,arrGroup=['<ul>'],jGroup;//表情分类
$.each(arrEmots,function(g,v){
gcount++;
arrGroup.push('<li'+(group==g?' class="cur"':'')+'><a href="javascript:void(0);" group="'+g+'">'+v.name+'</a></li>');
});
if(gcount>1)
{
arrGroup.push('</ul><br style="clear:both;" />');
jGroup=$(arrGroup.join('')).click(function(ev){selEmotGroup=$(ev.target).attr('group');_this.exec('Emot');return false;}).mousedown(returnFalse);
jEmot.append(jGroup);
}
_this.showPanel(jEmot);
}
this.showTable=function()
{
var jTable=$(htmlTable),jRows=$('#xheTableRows',jTable),jColumns=$('#xheTableColumns',jTable),jHeaders=$('#xheTableHeaders',jTable),jWidth=$('#xheTableWidth',jTable),jHeight=$('#xheTableHeight',jTable),jBorder=$('#xheTableBorder',jTable),jCellSpacing=$('#xheTableCellSpacing',jTable),jCellPadding=$('#xheTableCellPadding',jTable),jAlign=$('#xheTableAlign',jTable),jCaption=$('#xheTableCaption',jTable),jSave=$('#xheSave',jTable);
jSave.click(function(){
_this.loadBookmark();
var sCaption=jCaption.val(),sBorder=jBorder.val(),sRows=jRows.val(),sCols=jColumns.val(),sHeaders=jHeaders.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sCellSpacing=jCellSpacing.val(),sCellPadding=jCellPadding.val(),sAlign=jAlign.val();
var i,j,htmlTable='<table'+(sBorder!=''?' border="'+sBorder+'"':'')+(sWidth!=''?' width="'+sWidth+'"':'')+(sHeight!=''?' width="'+sHeight+'"':'')+(sCellSpacing!=''?' cellspacing="'+sCellSpacing+'"':'')+(sCellPadding!=''?' cellpadding="'+sCellPadding+'"':'')+(sAlign!=''?' align="'+sAlign+'"':'')+'>';
if(sCaption!='')htmlTable+='<caption>'+sCaption+'</caption>';
if(sHeaders=='row'||sHeaders=='both')
{
htmlTable+='<tr>';
for(i=0;i<sCols;i++)htmlTable+='<th scope="col"> </th>';
htmlTable+='</tr>';
sRows--;
}
htmlTable+='<tbody>';
for(i=0;i<sRows;i++)
{
htmlTable+='<tr>';
for(j=0;j<sCols;j++)
{
if(j==0&&(sHeaders=='col'||sHeaders=='both'))htmlTable+='<th scope="row"> </th>';
else htmlTable+='<td> </td>';
}
htmlTable+='</tr>';
}
htmlTable+='</tbody></table>';
_this.pasteHTML(htmlTable);
_this.hidePanel();
return false;
});
_this.showDialog(jTable);
}
this.showAbout=function()
{
var jAbout=$(htmlAbout);
_this.showDialog(jAbout);
}
this.addShortcuts=function(key,cmd)
{
key=key.toLowerCase();
if(arrShortCuts[key]==undefined)arrShortCuts[key]=Array();
arrShortCuts[key].push(cmd);
}
this.delShortcuts=function(key){delete arrShortCuts[key];}
this.uploadInit=function(jText,toUrl,upext)
{
var jUpload=$('<span class="xheUpload"><input type="text" style="visibility:hidden;" tabindex="-1" /><input type="button" value="'+settings.upBtnText+'" class="xheBtn" tabindex="-1" /></span>'),jUpBtn=$('.xheBtn',jUpload);
var bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
jText.after(jUpload);jUpBtn.before(jText);
toUrl=toUrl.replace(/{editorRoot}/ig,editorRoot);
if(toUrl.substr(0,1)=='!')//自定义上传管理页
{
jUpBtn.click(function(){
bShowPanel=false;//防止按钮面板被关闭
_this.showIframeModal('Upload file',toUrl.substr(1),setUploadMsg,null,null,function(){bShowPanel=true;});
});
}
else
{//系统默认ajax上传
jUpload.append('<input type="file"'+(upMultiple>1?' multiple=""':'')+' class="xheFile" size="13" name="'+uploadInputname+'" tabindex="-1" />');
var jFile=$('.xheFile',jUpload),arrMsg;
jFile.change(function(){arrMsg=[];_this.startUpload(jFile[0],toUrl,upext,setUploadMsg);});
setTimeout(function(){//拖放上传
jText.closest('.xheDialog').bind('dragenter dragover',returnFalse).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(bHtml5Upload&&dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0)_this.startUpload(fileList,toUrl,upext,setUploadMsg);
return false;
});
},10);
}
function setUploadMsg(arrMsg)
{
if(is(arrMsg,'string'))arrMsg=[arrMsg];//允许单URL传递
var bImmediate=false,i,count=arrMsg.length,msg,url,arrUrl=[],onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用户上传回调
for(i=0;i<count;i++)
{
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!'){bImmediate=true;url=url.substr(1);}
arrUrl.push(url);
}
jText.val(arrUrl.join(' '));
if(bImmediate)jText.closest('.xheDialog').find('#xheSave').click();
}
}
this.startUpload=function(fromFiles,toUrl,limitExt,onUploadComplete)
{
var arrMsg=[],bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
var upload,fileList,filename,jUploadTip=$('<div style="padding:22px 0;text-align:center;line-height:30px;">File uploading,please wait...<br /></div>'),sLoading='<img src="'+skinPath+'img/loading.gif">';
if(!bHtml5Upload||(fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0])))
{
if(!checkFileExt(fromFiles.value,limitExt))return;
jUploadTip.append(sLoading);
upload=new _this.html4Upload(fromFiles,toUrl,onUploadCallback);
}
else
{
if(!fileList)fileList=fromFiles;//拖放文件列表
var i,len=fileList.length;
if(len>upMultiple){alert('Please do not upload more then '+upMultiple+' files.');return;}
for(i=0;i<len;i++)if(!checkFileExt(fileList[i].fileName,limitExt))return;
var jProgress=$('<div class="xheProgress"><div><span>0%</span></div></div>');
jUploadTip.append(jProgress);
upload=new _this.html5Upload(uploadInputname,fileList,toUrl,onUploadCallback,function(ev){
if(ev.loaded>=0)
{
var sPercent=Math.round((ev.loaded * 100) / ev.total)+'%';
$('div',jProgress).css('width',sPercent);
$('span',jProgress).text(sPercent+' ( '+formatBytes(ev.loaded)+' / '+formatBytes(ev.total)+' )');
}
else jProgress.replaceWith(sLoading);//不支持进度
});
}
var panelState=bShowPanel;
if(panelState)bShowPanel=false;//防止面板被关闭
_this.showModal('File uploading(Esc cancel)',jUploadTip,320,150,function(){bShowPanel=panelState;upload.remove();});
upload.start();
function onUploadCallback(sText,bFinish)
{
var data=Object,bOK=false;
try{data=eval('('+sText+')');}catch(ex){};
if(data.err==undefined||data.msg==undefined)alert(toUrl+' upload interface error!\r\n\r\nreturn error:\r\n\r\n'+sText);
else
{
if(data.err)alert(data.err);
else
{
arrMsg.push(data.msg);
bOK=true;//继续下一个文件上传
}
}
if(!bOK||bFinish)_this.removeModal();
if(bFinish&&bOK)onUploadComplete(arrMsg);//全部上传完成
return bOK;
}
}
this.html4Upload=function(fromfile,toUrl,callback)
{
var uid = new Date().getTime(),idIO='jUploadFrame'+uid,_this=this;
var jIO=$('<iframe name="'+idIO+'" class="xheHideArea" />').appendTo('body');
var jForm=$('<form action="'+toUrl+'" target="'+idIO+'" method="post" enctype="multipart/form-data" class="xheHideArea"></form>').appendTo('body');
var jOldFile = $(fromfile),jNewFile = jOldFile.clone().attr('disabled','true');
jOldFile.before(jNewFile).appendTo(jForm);
this.remove=function()
{
if(_this!=null)
{
jNewFile.before(jOldFile).remove();
jIO.remove();jForm.remove();
_this=null;
}
}
this.onLoad=function(){callback($(jIO[0].contentWindow.document.body).text(),true);}
this.start=function(){jForm.submit();jIO.load(_this.onLoad);}
return this;
}
this.html5Upload=function(inputname,fromFiles,toUrl,callback,onProgress)
{
var xhr,i=0,count=fromFiles.length,allLoaded=0,allSize=0,_this=this;
for(var j=0;j<count;j++)allSize+=fromFiles[j].fileSize;
this.remove=function(){if(xhr){xhr.abort();xhr=null;}}
this.uploadNext=function(sText)
{
if(sText)//当前文件上传完成
{
allLoaded+=fromFiles[i-1].fileSize;
returnProgress(0);
}
if((!sText||(sText&&callback(sText,i==count)==true))&&i<count)postFile(fromFiles[i++],toUrl,_this.uploadNext,function(loaded){returnProgress(loaded);});
}
this.start=function(){_this.uploadNext();}
function postFile(fromfile,toUrl,callback,onProgress)
{
xhr = new XMLHttpRequest(),upload=xhr.upload;
xhr.onreadystatechange=function(){if(xhr.readyState==4)callback(xhr.responseText);};
if(upload)upload.onprogress=function(ev){onProgress(ev.loaded);};
else onProgress(-1);//不支持进度
xhr.open("POST", toUrl);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Content-Disposition', 'attachment; name="'+inputname+'"; filename="'+fromfile.fileName+'"');
if(xhr.sendAsBinary)xhr.sendAsBinary(fromfile.getAsBinary());
else xhr.send(fromfile);
}
function returnProgress(loaded){if(onProgress)onProgress({'loaded':allLoaded+loaded,'total':allSize});}
}
this.showIframeModal=function(title,ifmurl,callback,w,h,onRemove)
{
var jContent=$('<iframe frameborder="0" src="'+ifmurl.replace(/{editorRoot}/ig,editorRoot)+'" style="width:100%;height:100%;display:none;" /><div class="xheModalIfmWait"></div>'),jIframe=$(jContent[0]),jWait=$(jContent[1]);
_this.showModal(title,jContent,w,h,onRemove);
jIframe.load(function(){
var modalWin=jIframe[0].contentWindow,jModalDoc=$(modalWin.document);
modalWin.callback=function(v){_this.removeModal();callback(v);};
modalWin.unloadme=_this.removeModal;
jModalDoc.keydown(_this.checkEsc);
jIframe.show();jWait.remove();
});
}
this.showModal=function(title,content,w,h,onRemove)
{
if(bShowModal)return false;//只能弹出一个模式窗口
layerShadow=settings.layerShadow;
w=w?w:settings.modalWidth;h=h?h:settings.modalHeight;
jModal=$('<div class="xheModal" style="width:'+(w-1)+'px;height:'+h+'px;margin-left:-'+Math.ceil(w/2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+Math.ceil(h/2)+'px')+'">'+(settings.modalTitle?'<div class="xheModalTitle"><span class="xheModalClose" title="Close (Esc)"></span>'+title+'</div>':'')+'<div class="xheModalContent"></div></div>').appendTo('body');
jOverlay=$('<div class="xheModalOverlay"></div>').appendTo('body');
if(layerShadow>0)jModalShadow=$('<div class="xheModalShadow" style="width:'+jModal.outerWidth()+'px;height:'+jModal.outerHeight()+'px;margin-left:-'+(Math.ceil(w/2)-layerShadow-2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+(Math.ceil(h/2)-layerShadow-2)+'px')+'"></div>').appendTo('body');
$('.xheModalContent',jModal).css('height',h-(settings.modalTitle?$('.xheModalTitle').outerHeight():0)).html(content);
if(isIE&&browerVer==6.0)jHideSelect=$('select:visible').css('visibility','hidden');//隐藏覆盖的select
$('.xheModalClose',jModal).click(_this.removeModal);
jOverlay.show();if(layerShadow>0)jModalShadow.show();jModal.show();
bShowModal=true;
onModalRemove=onRemove;
}
this.removeModal=function(){if(jHideSelect)jHideSelect.css('visibility','visible');jModal.html('').remove();if(layerShadow>0)jModalShadow.remove();jOverlay.remove();if(onModalRemove)onModalRemove();bShowModal=false;};
this.showDialog=function(content)
{
var jDialog=$('<div class="xheDialog"></div>'),jContent=$(content),jSave=$('#xheSave',jContent);
if(jSave.length==1)
{
jContent.find('input[type=text],select').keypress(function(ev){if(ev.which==13){jSave.click();return false;}});
jContent.find('textarea').keydown(function(ev){if(ev.ctrlKey&&ev.which==13){jSave.click();return false;}});
jSave.after(' <input type="button" id="xheCancel" value="Cancel" />');
$('#xheCancel',jContent).click(_this.hidePanel);
if(!settings.clickCancelDialog)
{
bClickCancel=false;//关闭点击隐藏
var jFixCancel=$('<div class="xheFixCancel"></div>').appendTo('body').mousedown(returnFalse);
var xy=_jArea.offset();
jFixCancel.css({'left':xy.left,'top':xy.top,width:_jArea.outerWidth(),height:_jArea.outerHeight()})
}
jDialog.mousedown(function(){bDisableHoverExec=true;})//点击对话框禁止悬停执行
}
jDialog.append(jContent);
_this.showPanel(jDialog);
if(!isIE)setTimeout(function(){jDialog.find('input[type=text],textarea').filter(':visible').filter(function(){return $(this).css('visibility')!='hidden';}).eq(0).focus();},10);//定位首个可见输入表单项,延迟解决opera无法设置焦点
}
this.showPanel=function(content)
{
if(!ev.target)return false;
_jPanel.html('').append(content).css('left',-999).css('top',-999);
_jPanelButton=$(ev.target).closest('a').addClass('xheActive');
var xy=_jPanelButton.offset();
var x=xy.left,y=xy.top;y+=_jPanelButton.outerHeight()-1;
_jCntLine.css({'left':x+1,'top':y,'width':_jPanelButton.width()}).show();
if((x+_jPanel.outerWidth())>document.body.clientWidth)x-=(_jPanel.outerWidth()-_jPanelButton.outerWidth());//向左显示面板
var layerShadow=settings.layerShadow;
if(layerShadow>0)_jShadow.css({'left':x+layerShadow,'top':y+layerShadow,'width':_jPanel.outerWidth(),'height':_jPanel.outerHeight()}).show();
_jPanel.css({'left':x,'top':y}).show();
bQuickHoverExec=bShowPanel=true;
}
this.hidePanel=function(){if(bShowPanel){_jPanelButton.removeClass('xheActive');_jShadow.hide();_jCntLine.hide();_jPanel.hide();bShowPanel=false;if(!bClickCancel){$('.xheFixCancel').remove();bClickCancel=true;};bQuickHoverExec=bDisableHoverExec=false;lastAngle=null;}}
this.exec=function(cmd)
{
_this.hidePanel();
_this.saveBookmark();
var tool=arrTools[cmd];
if(!tool)return false;//无效命令
if(ev==null)//非鼠标点击
{
ev={};
var btn=_jTools.find('.xheButton[name='+cmd+']');
if(btn.length==1)ev.target=btn;//设置当前事件焦点
}
if(tool.e)tool.e.call(_this)//插件事件
else//内置工具
{
cmd=cmd.toLowerCase();
switch(cmd)
{
case 'cut':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('Currently not supported by your browser, use keyboard shortcuts(Ctrl+X) instead.');};
break;
case 'copy':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('Currently not supported by your browser, use keyboard shortcuts(Ctrl+C) instead.');}
break;
case 'paste':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('Currently not supported by your browser, use keyboard shortcuts(Ctrl+V) instead.');}
break;
case 'pastetext':
if(window.clipboardData)_this.pasteText(window.clipboardData.getData('Text', true));
else _this.showPastetext();
break;
case 'blocktag':
var menuBlocktag=[];
$.each(arrBlocktag,function(n,v){menuBlocktag.push({s:'<'+v.n+'>'+v.t+'</'+v.n+'>',v:'<'+v.n+'>',t:v.t});});
_this.showMenu(menuBlocktag,function(v){_this._exec('formatblock',v);});
break;
case 'fontface':
var menuFontname=[];
$.each(arrFontname,function(n,v){v.c=v.c?v.c:v.n;menuFontname.push({s:'<span style="font-family:'+v.c+'">'+v.n+'</span>',v:v.c,t:v.n});});
_this.showMenu(menuFontname,function(v){_this._exec('fontname',v);});
break;
case 'fontsize':
var menuFontsize=[];
$.each(arrFontsize,function(n,v){menuFontsize.push({s:'<span style="font-size:'+v.s+';">'+v.t+'('+v.s+')</span>',v:n+1,t:v.t});});
_this.showMenu(menuFontsize,function(v){_this._exec('fontsize',v);});
break;
case 'fontcolor':
_this.showColor(function(v){_this._exec('forecolor',v);});
break;
case 'backcolor':
_this.showColor(function(v){if(isIE)_this._exec('backcolor',v);else{setCSS(true);_this._exec('hilitecolor',v);setCSS(false);}});
break;
case 'align':
_this.showMenu(menuAlign,function(v){_this._exec(v);});
break;
case 'list':
_this.showMenu(menuList,function(v){_this._exec(v);});
break;
case 'link':
_this.showLink();
break;
case 'img':
_this.showImg();
break;
case 'flash':
_this.showEmbed('Flash',htmlFlash,'application/x-shockwave-flash','clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000',' wmode="opaque" quality="high" menu="false" play="true" loop="true" allowfullscreen="true"',settings.upFlashUrl,settings.upFlashExt);
break;
case 'media':
_this.showEmbed('Media',htmlMedia,'application/x-mplayer2','clsid:6bf52a52-394a-11d3-b153-00c04f79faa6',' enablecontextmenu="false" autostart="false"',settings.upMediaUrl,settings.upMediaExt);
break;
case 'emot':
_this.showEmot();
break;
case 'table':
_this.showTable();
break;
case 'source':
_this.toggleSource();
break;
case 'preview':
_this.showPreview();
break;
case 'print':
_win.print();
break;
case 'fullscreen':
_this.toggleFullscreen();
break;
case 'about':
_this.showAbout();
break;
default:
_this._exec(cmd);
break;
}
}
ev=null;
}
this._exec=function(cmd,param,noFocus)
{
if(!noFocus)_this.focus();
var state;
if(param!=undefined)state=_doc.execCommand(cmd,false,param);
else state=_doc.execCommand(cmd,false,null);
return state;
}
function checkDblClick(ev)
{
var target=ev.target,tool=arrDbClick[target.tagName.toLowerCase()];
if(tool)
{
if(tool=='Embed')//自动识别Flash和多媒体
{
var arrEmbed={'application/x-shockwave-flash':'Flash','application/x-mplayer2':'Media'};
tool=arrEmbed[target.type.toLowerCase()];
}
_this.exec(tool);
}
}
function checkEsc(ev)
{
if(ev.which==27)
{
if(bShowModal)_this.removeModal();
else if(bShowPanel)_this.hidePanel();
return false;
}
}
function loadReset(){setTimeout(_this.setSource,10);}
function saveResult(){_this.getSource();};
function cleanPaste(ev){
if(bSource||bCleanPaste)return true;
bCleanPaste=true;//解决IE右键粘贴重复产生paste的问题
_this.saveBookmark();
var jDiv=$('<div style="position:absolute;left:-1000px;top:'+_jWin.scrollTop()+'px;overflow:hidden;width:1px;height:1px;" />',_doc),div=jDiv[0],sel=_this.getSel(),rng=_this.getRng();
$(_doc.body).append(jDiv);
if(isIE){
rng.moveToElementText(div);
rng.execCommand('Paste');
ev.preventDefault();
}
else{
rng.selectNodeContents(div);
sel.removeAllRanges();
sel.addRange(rng);
}
setTimeout(function(){
var sPaste;
if(settings.forcePasteText===true)sPaste=jDiv.text();
else{
sPaste=div.innerHTML;
sPaste=_this.cleanHTML(sPaste);
sPaste=_this.formatXHTML(sPaste);
sPaste=_this.cleanWord(sPaste);
}
jDiv.remove();
_this.loadBookmark();
_this.pasteHTML(sPaste);
bCleanPaste=false;
},0);
}
function setCSS(css)
{
try{_this._exec('styleWithCSS',css,true);}
catch(e)
{try{_this._exec('useCSS',!css,true);}catch(e){}}
}
function setOpts()
{
if(bInit&&!bSource)
{
setCSS(false);
try{_this._exec('enableObjectResizing',true,true);}catch(e){}
//try{_this._exec('enableInlineTableEditing',false,true);}catch(e){}
if(isIE)try{_this._exec('BackgroundImageCache',true,true);}catch(e){}
}
}
function forcePtag(ev)
{
if(bSource||ev.which!=13||ev.shiftKey||ev.ctrlKey||ev.altKey)return true;
var pNode=_this.getParent('p,h1,h2,h3,h4,h5,h6,pre,address,div,li');
if(pNode.is('li'))return true;
if(settings.forcePtag){if(pNode.length==0)_this._exec('formatblock','<p>');}
else
{
_this.pasteHTML('<br />');
if(isIE&&pNode.length>0&&_this.getRng().parentElement().childNodes.length==2)_this.pasteHTML('<br />');
return false;
}
}
function fixFullHeight()
{
if(!isMozilla&&!isSafari)
{
if(bFullscreen)_jArea.height('100%').css('height',_jArea.outerHeight()-_jTools.outerHeight());
if(isIE)_jTools.hide().show();
}
}
function fixAppleSel(e)
{
e=e.target;
if(e.tagName.match(/(img|embed)/i))
{
var sel=_this.getSel(),rng=_this.getRng();
rng.selectNode(e);
sel.removeAllRanges();
sel.addRange(rng);
}
}
function xheAttr(jObj,n,v)
{
if(!n)return false;
var kn='_xhe_'+n;
if(v)//设置属性
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
jObj.attr(n,urlBase?getLocalUrl(v,'abs',urlBase):v).removeAttr(kn).attr(kn,v);
}
return jObj.attr(kn)||jObj.attr(n);
}
function clickCancelPanel(){if(bClickCancel)_this.hidePanel();}
function checkShortcuts(event)
{
if(bSource)return true;
var code=event.which,special=specialKeys[code],sChar=special?special:String.fromCharCode(code).toLowerCase();
sKey='';
sKey+=event.ctrlKey?'ctrl+':'';sKey+=event.altKey?'alt+':'';sKey+=event.shiftKey?'shift+':'';sKey+=sChar;
var cmd=arrShortCuts[sKey],c;
for(c in cmd)
{
c=cmd[c];
if($.isFunction(c)){if(c.call(_this)===false)return false;}
else{_this.exec(c);return false;}//按钮独占快捷键
}
}
function is(o,t)
{
var n = typeof(o);
if (!t)return n != 'undefined';
if (t == 'array' && (o.hasOwnProperty && o instanceof Array))return true;
return n == t;
}
function getLocalUrl(url,urlType,urlBase)//绝对地址:abs,根地址:root,相对地址:rel
{
var baseUrl=urlBase?$('<a href="'+urlBase+'" />')[0]:location,protocol=baseUrl.protocol,host=baseUrl.hostname,port=baseUrl.port,path=baseUrl.pathname.replace(/\\/g,'/').replace(/[^\/]+$/i,'');
port=(port=='')?'80':port;
url=$.trim(url);
if(urlType!='abs')url=url.replace(new RegExp(protocol+'\\/\\/'+host.replace(/\./g,'\\.')+'(?::'+port+')'+(port=='80'?'?':'')+'(\/|$)','i'),'/');
if(urlType=='rel')url=url.replace(new RegExp('^'+path.replace(/([\/\.\+\[\]\(\)])/g,'\\$1'),'i'),'');
if(urlType!='rel')
{
if(!url.match(/^((https?|file):\/\/|\/)/i))url=path+url;
if(url.charAt(0)=='/')//处理..
{
var arrPath=[],arrFolder = url.split('/'),folder,i,l=arrFolder.length;
for(i=0;i<l;i++)
{
folder=arrFolder[i];
if(folder=='..')arrPath.pop();
else if(folder!==''&&folder!='.')arrPath.push(folder);
}
if(arrFolder[l-1]=='')arrPath.push('');
url='/'+arrPath.join('/');
}
}
if(urlType=='abs')if(!url.match(/(https?|file):\/\//i))url=protocol+'//'+location.host+url;
return url;
}
function checkFileExt(filename,limitExt)
{
if(limitExt=='*'||filename.match(new RegExp('\.('+limitExt.replace(/,/g,'|')+')$','i')))return true;
else
{
alert('Upload file extension required for this: '+limitExt);
return false;
}
}
function formatBytes(bytes)
{
var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+s[e];
}
function returnFalse(){return false;}
}
$(function(){
$.fn.oldVal=$.fn.val;
$.fn.val=function(value)
{
var _this=this,editor;
if(value===undefined)if(this[0]&&(editor=this[0].xheditor))return editor.getSource();else return _this.oldVal(value);//读
return this.each(function(){if(editor=this.xheditor)editor.setSource(value);else _this.oldVal(value);});//写
}
$('textarea').each(function(){
var self=$(this),xhClass=self.attr('class').match(/(?:^|\s)xheditor(?:\-(m?full|simple|mini))?(?:\s|$)/i);
if(xhClass)self.xheditor(xhClass[1]?{tools:xhClass[1]}:null);
});
});
})(jQuery); | JavaScript |
//function movePage(absolutePage){
// window.location='?absolutePage=';
//}
function codeImg(b){
b.src="getCodeImg?"+Math.random();
} | JavaScript |
/*!
* jQuery Form Plugin
* version: 2.49 (18-OCT-2010)
* @requires jQuery v1.3.2 or later
*
* Examples and documentation at: http://malsup.com/jquery/form/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;
(function($) {
/*
* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the
* same form. These functions are intended to be exclusive. Use ajaxSubmit
* if you want to bind your own submit handler to the form. For example,
*
* $(document).ready(function() { $('#myForm').bind('submit', function(e) {
* e.preventDefault(); // <-- important $(this).ajaxSubmit({ target:
* '#output' }); }); });
*
* Use ajaxForm when you want the plugin to manage all the event binding for
* you. For example,
*
* $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output'
* }); });
*
* When using ajaxForm, the ajaxSubmit function will be invoked for you at
* the appropriate time.
*/
/**
* ajaxSubmit() provides a mechanism for immediately submitting an HTML form
* using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
if (typeof options == 'function') {
options = {
success : options
};
}
var url = $.trim(this.attr('action'));
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/) || [])[1];
}
url = url || window.location.href || '';
options = $
.extend(
true,
{
url : url,
type : this.attr('method') || 'GET',
iframeSrc : /^https/i
.test(window.location.href || '') ? 'javascript:false'
: 'about:blank'
}, options);
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [ this, options, veto ]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize
&& options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var n, v, a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (n in options.data) {
if (options.data[n] instanceof Array) {
for ( var k in options.data[n]) {
a.push( {
name : n,
value : options.data[n][k]
});
}
} else {
v = options.data[n];
v = $.isFunction(v) ? v() : v; // if value is fn, invoke it
a.push( {
name : n,
value : v
});
}
}
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit
&& options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [ a, this, options, veto ]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
} else {
options.data = q; // data is the query string for 'post'
}
var $form = this, callbacks = [];
if (options.resetForm) {
callbacks.push(function() {
$form.resetForm();
});
}
if (options.clearForm) {
callbacks.push(function() {
$form.clearForm();
});
}
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function() {
};
callbacks.push(function(data) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
} else if (options.success) {
callbacks.push(options.success);
}
options.success = function(data, status, xhr) { // jQuery 1.4+ passes
// xhr as 3rd arg
var context = options.context || options; // jQuery 1.4+ supports
// scope context
for ( var i = 0, max = callbacks.length; i < max; i++) {
callbacks[i].apply(context,
[ data, status, xhr || $form, $form ]);
}
};
// are there files to upload?
var fileInputs = $('input:file', this).length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false
&& (fileInputs || options.iframe || multipart)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see:
// http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, fileUpload);
} else {
fileUpload();
}
} else {
$.ajax(options);
}
// fire 'notify' event
this.trigger('form-submit-notify', [ this, options ]);
return this;
// private function for handling file uploads (hat tip to YAHOO!)
function fileUpload() {
var form = $form[0];
if ($(':input[name=submit],:input[id=submit]', form).length) {
// if there is an input with a name or id of 'submit' then we
// won't be
// able to invoke the submit fn on the form (at least not
// x-browser)
alert('Error: Form elements must not have name or id of "submit".');
return;
}
var s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
var id = 'jqFormIO' + (new Date().getTime()), fn = '_' + id;
window[fn] = function() {
var f = $io.data('form-plugin-onload');
if (f) {
f();
window[fn] = undefined;
try {
delete window[fn];
} catch (e) {
}
}
}
var $io = $('<iframe id="' + id + '" name="' + id + '" src="'
+ s.iframeSrc + '" onload="window[\'_\'+this.id]()" />');
var io = $io[0];
$io.css( {
position : 'absolute',
top : '-1000px',
left : '-1000px'
});
var xhr = { // mock object
aborted : 0,
responseText : null,
responseXML : null,
status : 0,
statusText : 'n/a',
getAllResponseHeaders : function() {
},
getResponseHeader : function() {
},
setRequestHeader : function() {
},
abort : function() {
this.aborted = 1;
$io.attr('src', s.iframeSrc); // abort op in progress
}
};
var g = s.global;
// trigger ajax global events so that activity/block indicators work
// like normal
if (g && !$.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [ xhr, s ]);
}
if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active--;
}
return;
}
if (xhr.aborted) {
return;
}
var cbInvoked = false;
var timedOut = 0;
// add submitting element to data if we know it
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData[n] = sub.value;
if (sub.type == "image") {
s.extraData[n + '.x'] = form.clk_x;
s.extraData[n + '.y'] = form.clk_y;
}
}
}
// take a breath so that pending repaints get some cpu time before
// the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');
// update form attrs in IE friendly way
form.setAttribute('target', id);
if (form.getAttribute('method') != 'POST') {
form.setAttribute('method', 'POST');
}
if (form.getAttribute('action') != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (!s.skipEncodingOverride) {
$form.attr( {
encoding : 'multipart/form-data',
enctype : 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
setTimeout(function() {
timedOut = true;
cb();
}, s.timeout);
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for ( var n in s.extraData) {
extraInputs.push($(
'<input type="hidden" name="' + n
+ '" value="' + s.extraData[n]
+ '" />').appendTo(form)[0]);
}
}
// add iframe to doc and submit the form
$io.appendTo('body');
$io.data('form-plugin-onload', cb);
form.submit();
} finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action', a);
if (t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
if (s.forceSync) {
doSubmit();
} else {
setTimeout(doSubmit, 10); // this lets dom updates render
}
var data, doc, domCheckCount = 50;
function cb() {
if (cbInvoked) {
return;
}
$io.removeData('form-plugin-onload');
var ok = true;
try {
if (timedOut) {
throw 'timeout';
}
// extract the server response from the iframe
doc = io.contentWindow ? io.contentWindow.document
: io.contentDocument ? io.contentDocument
: io.document;
var isXml = s.dataType == 'xml' || doc.XMLDocument
|| $.isXMLDoc(doc);
log('isXml=' + isXml);
if (!isXml && window.opera
&& (doc.body == null || doc.body.innerHTML == '')) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not
// always traversable when
// the onload callback fires, so we loop a bit to
// accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could
// be an empty document
// log('Could not access iframe DOM after mutiple
// tries.');
// throw 'DOMException: not available';
}
// log('response detected');
cbInvoked = true;
xhr.responseText = doc.documentElement ? doc.documentElement.innerHTML
: null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
xhr.getResponseHeader = function(header) {
var headers = {
'content-type' : s.dataType
};
return headers[header];
};
var scr = /(json|script)/.test(s.dataType);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
} else if (scr) {
// account for browsers injecting pre around json
// response
var pre = doc.getElementsByTagName('pre')[0];
var b = doc.getElementsByTagName('body')[0];
if (pre) {
xhr.responseText = pre.innerHTML;
} else if (b) {
xhr.responseText = b.innerHTML;
}
}
} else if (s.dataType == 'xml' && !xhr.responseXML
&& xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = $.httpData(xhr, s.dataType);
} catch (e) {
log('error caught:', e);
ok = false;
xhr.error = e;
$.handleError(s, xhr, 'error', e);
}
// ordering of these callbacks/triggers is odd, but that's how
// $.ajax does it
if (ok) {
s.success.call(s.context, data, 'success', xhr);
if (g) {
$.event.trigger("ajaxSuccess", [ xhr, s ]);
}
}
if (g) {
$.event.trigger("ajaxComplete", [ xhr, s ]);
}
if (g && !--$.active) {
$.event.trigger("ajaxStop");
}
if (s.complete) {
s.complete.call(s.context, xhr, ok ? 'success' : 'error');
}
// clean up
setTimeout(function() {
$io.removeData('form-plugin-onload');
$io.remove();
xhr.responseXML = null;
}, 100);
}
function toXml(s, doc) {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
} else {
doc = (new DOMParser()).parseFromString(s, 'text/xml');
}
return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc
: null;
}
}
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" />
* elements (if the element is used to submit the form). 2. This method will
* include the submit element's name/value data (for the element that was
* used to submit the form). 3. This method binds the submit() method to the
* form for you.
*
* The options argument for ajaxForm works exactly as it does for
* ajaxSubmit. ajaxForm merely passes the options argument along after
* properly binding events for submit elements and the form itself.
*/
$.fn.ajaxForm = function(options) {
// in jQuery 1.3+ we can fix mistakes with the ready state
if (this.length === 0) {
var o = {
s : this.selector,
c : this.context
};
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function() {
$(o.s, o.c).ajaxForm(options);
});
return this;
}
// is your DOM ready?
// http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? ''
: ' (DOM not ready)'));
return this;
}
return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
if (!e.isDefaultPrevented()) { // if event has been canceled, don't
// proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
}).bind('click.form-plugin', function(e) {
var target = e.target;
var $el = $(target);
if (!($el.is(":submit,input:image"))) {
// is this a child element of the submit el? (ex: a span within
// a button)
var t = $el.closest(':submit');
if (t.length == 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use
// dimensions
// plugin
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function() {
form.clk = form.clk_x = form.clk_y = null;
}, 100);
});
};
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An
* example of an array for a simple login form might be:
* [ { name: 'username', value: 'jresig' }, { name: 'password', value:
* 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided
* to the ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length === 0) {
return a;
}
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) {
return a;
}
var i, j, n, v, el, max, jmax;
for (i = 0, max = els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n) {
continue;
}
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if (!el.disabled && form.clk == el) {
a.push( {
name : n,
value : $(el).val()
});
a.push( {
name : n + '.x',
value : form.clk_x
}, {
name : n + '.y',
value : form.clk_y
});
}
continue;
}
v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for (j = 0, jmax = v.length; j < jmax; j++) {
a.push( {
name : n,
value : v[j]
});
}
} else if (v !== null && typeof v != 'undefined') {
a.push( {
name : n,
value : v
});
}
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it
// here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push( {
name : n,
value : $input.val()
});
a.push( {
name : n + '.x',
value : form.clk_x
}, {
name : n + '.y',
value : form.clk_y
});
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return
* a string in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function(semantic) {
// hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format:
* name1=value1&name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) {
return;
}
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for ( var i = 0, max = v.length; i < max; i++) {
a.push( {
name : n,
value : v[i]
});
}
} else if (v !== null && typeof v != 'undefined') {
a.push( {
name : this.name,
value : v
});
}
});
// hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example,
* consider the following form:
*
* <form><fieldset> <input name="A" type="text" /> <input name="A"
* type="text" /> <input name="B" type="checkbox" value="B1" /> <input
* name="B" type="checkbox" value="B2"/> <input name="C" type="radio"
* value="C1" /> <input name="C" type="radio" value="C2" /> </fieldset></form>
*
* var v = $(':text').fieldValue(); // if no values are entered into the
* text inputs v == ['',''] // if values entered into the text inputs are
* 'foo' and 'bar' v == ['foo','bar']
*
* var v = $(':checkbox').fieldValue(); // if neither checkbox is checked v
* === undefined // if both checkboxes are checked v == ['B1', 'B2']
*
* var v = $(':radio').fieldValue(); // if neither radio is checked v ===
* undefined // if first radio is checked v == ['C1']
*
* The successful argument controls whether or not the field element must be
* 'successful' (per
* http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The
* default value of the successful argument is true. If this value is false
* the value(s) for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be
* determined the array will be empty, otherwise it will contain one or more
* values.
*/
$.fn.fieldValue = function(successful) {
for ( var val = [], i = 0, max = this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined'
|| (v.constructor == Array && !v.length)) {
continue;
}
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (successful === undefined) {
successful = true;
}
if (successful
&& (!n || el.disabled || t == 'reset' || t == 'button'
|| (t == 'checkbox' || t == 'radio') && !el.checked
|| (t == 'submit' || t == 'image') && el.form
&& el.form.clk != el || tag == 'select'
&& el.selectedIndex == -1)) {
return null;
}
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) {
return null;
}
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index + 1 : ops.length);
for ( var i = (one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text
: op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};
/**
* Clears the form data. Takes the following actions on the form's input
* fields: - input text fields will have their 'value' property set to the
* empty string - select elements will have their 'selectedIndex' property
* set to -1 - checkbox and radio inputs will have their 'checked' property
* set to false - inputs of type submit, button, reset, and hidden will
* *not* be effected - button elements will *not* be effected
*/
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea') {
this.value = '';
} else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
} else if (tag == 'select') {
this.selectedIndex = -1;
}
});
};
/**
* Resets the form data. Causes all form elements to be reset to their
* original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function'
|| (typeof this.reset == 'object' && !this.reset.nodeType)) {
this.reset();
}
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) {
if (b === undefined) {
b = true;
}
return this.each(function() {
this.disabled = !b;
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function(select) {
if (select === undefined) {
select = true;
}
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio') {
this.checked = select;
} else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
}) ;
};
// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
if ($.fn.ajaxSubmit.debug) {
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,
'');
if (window.console && window.console.log) {
window.console.log(msg);
} else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
}
}
;
})(jQuery);
| JavaScript |
//**********************图片上传预览插件************************
//作者:IDDQD(2009-07-01)
//Email:iddqd5376@163.com
//http://iddqd5376.blog.163.com
//版本:1.0
//说明:图片上传预览插件
//上传的时候可以生成固定宽高范围内的等比例缩放图
//参数设置:
//width 存放图片固定大小容器的宽
//height 存放图片固定大小容器的高
//imgDiv 页面DIV的JQuery的id
//imgType 数组后缀名
//**********************图片上传预览插件*************************
(function($) {
jQuery.fn.extend({
uploadPreview: function(opts) {
opts = jQuery.extend({
width: 0,
height: 0,
imgDiv: "#imgDiv",
imgType: ["gif", "jpeg", "jpg", "bmp", "png"],
callback: function() { return false; }
}, opts || {});
var _self = this;
var _this = $(this);
var imgDiv = $(opts.imgDiv);
imgDiv.width(opts.width);
imgDiv.height(opts.height);
autoScaling = function() {
if ($.browser.version == "7.0" || $.browser.version == "8.0") imgDiv.get(0).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = "image";
var img_width = imgDiv.width();
var img_height = imgDiv.height();
if (img_width > 0 && img_height > 0) {
var rate = (opts.width / img_width < opts.height / img_height) ? opts.width / img_width : opts.height / img_height;
if (rate <= 1) {
if ($.browser.version == "7.0" || $.browser.version == "8.0") imgDiv.get(0).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = "scale";
imgDiv.width(img_width * rate);
imgDiv.height(img_height * rate);
} else {
imgDiv.width(img_width);
imgDiv.height(img_height);
}
var left = (opts.width - imgDiv.width()) * 0.5;
var top = (opts.height - imgDiv.height()) * 0.5;
imgDiv.css({ "margin-left": left, "margin-top": top });
imgDiv.show();
}
}
_this.change(function() {
if (this.value) {
if (!RegExp("\.(" + opts.imgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
alert("图片类型必须是" + opts.imgType.join(",") + "中的一种");
this.value = "";
return false;
}
imgDiv.hide();
if ($.browser.msie) {
if ($.browser.version == "6.0") {
var img = $("<img />");
imgDiv.replaceWith(img);
imgDiv = img;
var image = new Image();
image.src = 'file:///' + this.value;
imgDiv.attr('src', image.src);
autoScaling();
}
else {
imgDiv.css({ filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image)" });
imgDiv.get(0).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = "image";
try {
imgDiv.get(0).filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = this.value;
} catch (e) {
alert("无效的图片文件!");
return;
}
setTimeout("autoScaling()", 100);
}
}
else {
var img = $("<img />");
imgDiv.replaceWith(img);
imgDiv = img;
imgDiv.attr('src', this.files.item(0).getAsDataURL());
imgDiv.css({ "vertical-align": "middle" });
setTimeout("autoScaling()", 100);
}
}
});
}
});
})(jQuery); | JavaScript |
function Node(id, pid, name, url, title, target, icon, iconOpen, open) {
this.id = id;
this.pid = pid;
this.name = name;
this.url = url;
this.title = title;
this.target = target;
this.icon = icon;
this.iconOpen = iconOpen;
this._io = open || false;
this._is = false;
this._ls = false;
this._hc = false;
this._ai = 0;
this._p;
}
// Tree object
function dTree(objName) {
this.config = {target:null, folderLinks:true, useSelection:true, useCookies:true, useLines:true, useIcons:true, useStatusText:false, closeSameLevel:false, inOrder:false};
this.icon = {root:"lib/dTree/img/base.gif", folder:"lib/dTree/img/folder.gif", folderOpen:"lib/dTree/img/folderopen.gif", node:"lib/dTree/img/page.gif", empty:"lib/dTree/img/empty.gif", line:"lib/dTree/img/line.gif", join:"lib/dTree/img/join.gif", joinBottom:"lib/dTree/img/joinbottom.gif", plus:"lib/dTree/img/plus.gif", plusBottom:"lib/dTree/img/plusbottom.gif", minus:"lib/dTree/img/minus.gif", minusBottom:"lib/dTree/img/minusbottom.gif", nlPlus:"lib/dTree/img/nolines_plus.gif", nlMinus:"lib/dTree/img/nolines_minus.gif"};
this.obj = objName;
this.aNodes = [];
this.aIndent = [];
this.root = new Node(-1);
this.selectedNode = null;
this.selectedFound = false;
this.completed = false;
}
// Adds a new node to the node array
dTree.prototype.add = function (id, pid, name, url, title, target, icon, iconOpen, open) {
this.aNodes[this.aNodes.length] = new Node(id, pid, name, url, title, target, icon, iconOpen, open);
};
// Open/close all nodes
dTree.prototype.openAll = function () {
this.oAll(true);
};
dTree.prototype.closeAll = function () {
this.oAll(false);
};
// Outputs the tree to the page
dTree.prototype.toString = function () {
var str = "<div class=\"dtree\">\n";
if (document.getElementById) {
if (this.config.useCookies) {
this.selectedNode = this.getSelected();
}
str += this.addNode(this.root);
} else {
str += "Browser not supported.";
}
str += "</div>";
if (!this.selectedFound) {
this.selectedNode = null;
}
this.completed = true;
return str;
};
// Creates the tree structure
dTree.prototype.addNode = function (pNode) {
var str = "";
var n = 0;
if (this.config.inOrder) {
n = pNode._ai;
}
for (n; n < this.aNodes.length; n++) {
if (this.aNodes[n].pid == pNode.id) {
var cn = this.aNodes[n];
cn._p = pNode;
cn._ai = n;
this.setCS(cn);
if (!cn.target && this.config.target) {
cn.target = this.config.target;
}
if (cn._hc && !cn._io && this.config.useCookies) {
cn._io = this.isOpen(cn.id);
}
if (!this.config.folderLinks && cn._hc) {
cn.url = null;
}
if (this.config.useSelection && cn.id == this.selectedNode && !this.selectedFound) {
cn._is = true;
this.selectedNode = n;
this.selectedFound = true;
}
str += this.node(cn, n);
if (cn._ls) {
break;
}
}
}
return str;
};
// Creates the node icon, url and text
dTree.prototype.node = function (node, nodeId) {
var str = "<div class=\"dTreeNode\">" + this.indent(node, nodeId);
if (this.config.useIcons) {
if (!node.icon) {
node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hc) ? this.icon.folder : this.icon.node);
}
if (!node.iconOpen) {
node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node;
}
if (this.root.id == node.pid) {
node.icon = this.icon.root;
node.iconOpen = this.icon.root;
}
str += "<img id=\"i" + this.obj + nodeId + "\" src=\"" + ((node._io) ? node.iconOpen : node.icon) + "\" alt=\"\" />";
}
if (node.url) {
str += "<a id=\"s" + this.obj + nodeId + "\" class=\"" + ((this.config.useSelection) ? ((node._is ? "nodeSel" : "node")) : "node") + "\" href=\"" + node.url + "\"";
if (node.title) {
str += " title=\"" + node.title + "\"";
}
if (node.target) {
str += " target=\"" + node.target + "\"";
}
if (this.config.useStatusText) {
str += " onmouseover=\"window.status='" + node.name + "';return true;\" onmouseout=\"window.status='';return true;\" ";
}
if (this.config.useSelection && ((node._hc && this.config.folderLinks) || !node._hc)) {
str += " onclick=\"javascript: " + this.obj + ".s(" + nodeId + ");\"";
}
str += ">";
} else {
if ((!this.config.folderLinks || !node.url) && node._hc && node.pid != this.root.id) {
str += "<a href=\"javascript: " + this.obj + ".o(" + nodeId + ");\" class=\"node\">";
}
}
str += node.name;
if (node.url || ((!this.config.folderLinks || !node.url) && node._hc)) {
str += "</a>";
}
str += "</div>";
if (node._hc) {
str += "<div id=\"d" + this.obj + nodeId + "\" class=\"clip\" style=\"display:" + ((this.root.id == node.pid || node._io) ? "block" : "none") + ";\">";
str += this.addNode(node);
str += "</div>";
}
this.aIndent.pop();
return str;
};
// Adds the empty and line icons
dTree.prototype.indent = function (node, nodeId) {
var str = "";
if (this.root.id != node.pid) {
for (var n = 0; n < this.aIndent.length; n++) {
str += "<img src=\"" + ((this.aIndent[n] == 1 && this.config.useLines) ? this.icon.line : this.icon.empty) + "\" alt=\"\" />";
}
(node._ls) ? this.aIndent.push(0) : this.aIndent.push(1);
if (node._hc) {
str += "<a href=\"javascript: " + this.obj + ".o(" + nodeId + ");\"><img id=\"j" + this.obj + nodeId + "\" src=\"";
if (!this.config.useLines) {
str += (node._io) ? this.icon.nlMinus : this.icon.nlPlus;
} else {
str += ((node._io) ? ((node._ls && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._ls && this.config.useLines) ? this.icon.plusBottom : this.icon.plus));
}
str += "\" alt=\"\" /></a>";
} else {
str += "<img src=\"" + ((this.config.useLines) ? ((node._ls) ? this.icon.joinBottom : this.icon.join) : this.icon.empty) + "\" alt=\"\" />";
}
}
return str;
};
// Checks if a node has any children and if it is the last sibling
dTree.prototype.setCS = function (node) {
var lastId;
for (var n = 0; n < this.aNodes.length; n++) {
if (this.aNodes[n].pid == node.id) {
node._hc = true;
}
if (this.aNodes[n].pid == node.pid) {
lastId = this.aNodes[n].id;
}
}
if (lastId == node.id) {
node._ls = true;
}
};
// Returns the selected node
dTree.prototype.getSelected = function () {
var sn = this.getCookie("cs" + this.obj);
return (sn) ? sn : null;
};
// Highlights the selected node
dTree.prototype.s = function (id) {
if (!this.config.useSelection) {
return;
}
var cn = this.aNodes[id];
if (cn._hc && !this.config.folderLinks) {
return;
}
if (this.selectedNode != id) {
if (this.selectedNode || this.selectedNode == 0) {
eOld = document.getElementById("s" + this.obj + this.selectedNode);
eOld.className = "node";
}
eNew = document.getElementById("s" + this.obj + id);
eNew.className = "nodeSel";
this.selectedNode = id;
if (this.config.useCookies) {
this.setCookie("cs" + this.obj, cn.id);
}
}
};
// Toggle Open or close
dTree.prototype.o = function (id) {
var cn = this.aNodes[id];
this.nodeStatus(!cn._io, id, cn._ls);
cn._io = !cn._io;
if (this.config.closeSameLevel) {
this.closeLevel(cn);
}
if (this.config.useCookies) {
this.updateCookie();
}
};
// Open or close all nodes
dTree.prototype.oAll = function (status) {
for (var n = 0; n < this.aNodes.length; n++) {
if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.id) {
this.nodeStatus(status, n, this.aNodes[n]._ls);
this.aNodes[n]._io = status;
}
}
if (this.config.useCookies) {
this.updateCookie();
}
};
// Opens the tree to a specific node
dTree.prototype.openTo = function (nId, bSelect, bFirst) {
if (!bFirst) {
for (var n = 0; n < this.aNodes.length; n++) {
if (this.aNodes[n].id == nId) {
nId = n;
break;
}
}
}
var cn = this.aNodes[nId];
if (cn.pid == this.root.id || !cn._p) {
return;
}
cn._io = true;
cn._is = bSelect;
if (this.completed && cn._hc) {
this.nodeStatus(true, cn._ai, cn._ls);
}
if (this.completed && bSelect) {
this.s(cn._ai);
} else {
if (bSelect) {
this._sn = cn._ai;
}
}
this.openTo(cn._p._ai, false, true);
};
// Closes all nodes on the same level as certain node
dTree.prototype.closeLevel = function (node) {
for (var n = 0; n < this.aNodes.length; n++) {
if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hc) {
this.nodeStatus(false, n, this.aNodes[n]._ls);
this.aNodes[n]._io = false;
this.closeAllChildren(this.aNodes[n]);
}
}
};
// Closes all children of a node
dTree.prototype.closeAllChildren = function (node) {
for (var n = 0; n < this.aNodes.length; n++) {
if (this.aNodes[n].pid == node.id && this.aNodes[n]._hc) {
if (this.aNodes[n]._io) {
this.nodeStatus(false, n, this.aNodes[n]._ls);
}
this.aNodes[n]._io = false;
this.closeAllChildren(this.aNodes[n]);
}
}
};
// Change the status of a node(open or closed)
dTree.prototype.nodeStatus = function (status, id, bottom) {
eDiv = document.getElementById("d" + this.obj + id);
eJoin = document.getElementById("j" + this.obj + id);
if (this.config.useIcons) {
eIcon = document.getElementById("i" + this.obj + id);
eIcon.src = (status) ? this.aNodes[id].iconOpen : this.aNodes[id].icon;
}
eJoin.src = (this.config.useLines) ? ((status) ? ((bottom) ? this.icon.minusBottom : this.icon.minus) : ((bottom) ? this.icon.plusBottom : this.icon.plus)) : ((status) ? this.icon.nlMinus : this.icon.nlPlus);
eDiv.style.display = (status) ? "block" : "none";
};
// [Cookie] Clears a cookie
dTree.prototype.clearCookie = function () {
var now = new Date();
var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
this.setCookie("co" + this.obj, "cookieValue", yesterday);
this.setCookie("cs" + this.obj, "cookieValue", yesterday);
};
// [Cookie] Sets value in a cookie
dTree.prototype.setCookie = function (cookieName, cookieValue, expires, path, domain, secure) {
document.cookie = escape(cookieName) + "=" + escape(cookieValue) + (expires ? "; expires=" + expires.toGMTString() : "") + (path ? "; path=" + path : "") + (domain ? "; domain=" + domain : "") + (secure ? "; secure" : "");
};
// [Cookie] Gets a value from a cookie
dTree.prototype.getCookie = function (cookieName) {
var cookieValue = "";
var posName = document.cookie.indexOf(escape(cookieName) + "=");
if (posName != -1) {
var posValue = posName + (escape(cookieName) + "=").length;
var endPos = document.cookie.indexOf(";", posValue);
if (endPos != -1) {
cookieValue = unescape(document.cookie.substring(posValue, endPos));
} else {
cookieValue = unescape(document.cookie.substring(posValue));
}
}
return (cookieValue);
};
// [Cookie] Returns ids of open nodes as a string
dTree.prototype.updateCookie = function () {
var str = "";
for (var n = 0; n < this.aNodes.length; n++) {
if (this.aNodes[n]._io && this.aNodes[n].pid != this.root.id) {
if (str) {
str += ".";
}
str += this.aNodes[n].id;
}
}
this.setCookie("co" + this.obj, str);
};
// [Cookie] Checks if a node id is in a cookie
dTree.prototype.isOpen = function (id) {
var aOpen = this.getCookie("co" + this.obj).split(".");
for (var n = 0; n < aOpen.length; n++) {
if (aOpen[n] == id) {
return true;
}
}
return false;
};
// If Push and pop is not implemented by the browser
if (!Array.prototype.push) {
Array.prototype.push = function array_push() {
for (var i = 0; i < arguments.length; i++) {
this[this.length] = arguments[i];
}
return this.length;
};
}
if (!Array.prototype.pop) {
Array.prototype.pop = function array_pop() {
lastElement = this[this.length - 1];
this.length = Math.max(this.length - 1, 0);
return lastElement;
};
}
| JavaScript |
/*!
* MultiUpload for xheditor
* @requires xhEditor
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 0.9.2 (build 100505)
*/
var swfu,selQueue=[],selectID,arrMsg=[],allSize=0,uploadSize=0;
function removeFile()
{
var file;
if(!selectID)return;
for(var i in selQueue)
{
file=selQueue[i];
if(file.id==selectID)
{
selQueue.splice(i,1);
allSize-=file.size;
swfu.cancelUpload(file.id);
$('#'+file.id).remove();
selectID=null;
break;
}
}
$('#btnClear').hide();
if(selQueue.length==0)$('#controlBtns').hide();
}
function startUploadFiles()
{
if(swfu.getStats().files_queued>0)
{
$('#controlBtns').hide();
swfu.startUpload();
}
else alert('上传前请先添加文件');
}
function setFileState(fileid,txt)
{
$('#'+fileid+'_state').text(txt);
}
function fileQueued(file)//队列添加成功
{
for(var i in selQueue)if(selQueue[i].name==file.name){swfu.cancelUpload(file.id);return false;}//防止同名文件重复添加
if(selQueue.length==0)$('#controlBtns').show();
selQueue.push(file);
allSize+=file.size;
$('#listBody').append('<tr id="'+file.id+'"><td>'+file.name+'</td><td>'+formatBytes(file.size)+'</td><td id="'+file.id+'_state">就绪</td></tr>');
$('#'+file.id).hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');})
.click(function(){selectID=file.id;$('#listBody tr').removeClass('select');$(this).removeClass('hover').addClass('select');$('#btnClear').show();})
}
function fileQueueError(file, errorCode, message)//队列添加失败
{
var errorName='';
switch (errorCode)
{
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
errorName = "只能同时上传 "+this.settings.file_upload_limit+" 个文件";
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
errorName = "选择的文件超过了当前大小限制:"+this.settings.file_size_limit;
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
errorName = "零大小文件";
break;
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
errorName = "文件扩展名必需为:"+this.settings.file_types_description+" ("+this.settings.file_types+")";
break;
default:
errorName = "未知错误";
break;
}
alert(errorName);
}
function uploadStart(file)//单文件上传开始
{
setFileState(file.id,'上传中…');
}
function uploadProgress(file, bytesLoaded, bytesTotal)//单文件上传进度
{
var percent=Math.ceil((uploadSize+bytesLoaded)/allSize*100);
$('#progressBar span').text(percent+'% ('+formatBytes(uploadSize+bytesLoaded)+' / '+formatBytes(allSize)+')');
$('#progressBar div').css('width',percent+'%');
}
function uploadSuccess(file, serverData)//单文件上传成功
{
var data=Object;
try{eval("data=" + serverData);}catch(ex){};
if(data.err!=undefined&&data.msg!=undefined)
{
if(!data.err)
{
uploadSize+=file.size;
arrMsg.push(data.msg);
setFileState(file.id,'上传成功');
}
else
{
setFileState(file.id,'上传失败');
alert(data.err);
}
}
else setFileState(file.id,'上传失败!');
}
function uploadError(file, errorCode, message)//单文件上传错误
{
setFileState(file.id,'上传失败!');
}
function uploadComplete(file)//文件上传周期结束
{
if(swfu.getStats().files_queued>0)swfu.startUpload();
else uploadAllComplete();
}
function uploadAllComplete()//全部文件上传成功
{
callback(arrMsg);
}
function formatBytes(bytes) {
var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
} | JavaScript |
/*!
* xhEditor - WYSIWYG XHTML Editor
* @requires jQuery v1.4.2
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 1.1.1 (build 101002)
*/
(function($){
if($.xheditor)return false;//防止JS重复加载
$.fn.xheditor=function(options)
{
var arrSuccess=[];
this.each(function(){
if(!$.nodeName(this,'TEXTAREA'))return;
if(options===false)//卸载
{
if(this.xheditor)
{
this.xheditor.remove();
this.xheditor=null;
}
}
else//初始化
{
if(!this.xheditor)
{
var tOptions=/({.*})/.exec($(this).attr('class'));
if(tOptions)
{
try{tOptions=eval('('+tOptions[1]+')');}catch(ex){};
options=$.extend({},tOptions,options );
}
var editor=new $.xheditor(this,options);
if(editor.init())
{
this.xheditor=editor;
arrSuccess.push(editor);
}
else editor=null;
}
else arrSuccess.push(this.xheditor);
}
});
if(arrSuccess.length==0)arrSuccess=false;
if(arrSuccess.length==1)arrSuccess=arrSuccess[0];
return arrSuccess;
}
var xCount=0,browerVer=$.browser.version,isIE=$.browser.msie,isMozilla=$.browser.mozilla,isSafari=$.browser.safari,isOpera=$.browser.opera,bShowPanel=false,bClickCancel=true,bShowModal=false,bCheckEscInit=false;
var _jPanel,_jShadow,_jCntLine,_jPanelButton;
var jModal,jModalShadow,layerShadow,jOverlay,jHideSelect,onModalRemove;
var editorRoot;
$('script[src*=xheditor]').each(function(){
var s=this.src;
if(s.match(/xheditor[^\/]*\.js/i)){editorRoot=s.replace(/[\?#].*$/, '').replace(/(^|[\/\\])[^\/]*$/, '$1');return false;}
});
var specialKeys={ 27: 'esc', 9: 'tab', 32:'space', 13: 'enter', 8:'backspace', 145: 'scroll',
20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',
35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down',
112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12' };
var itemColors=['#FFFFFF','#CCCCCC','#C0C0C0','#999999','#666666','#333333','#000000','#FFCCCC','#FF6666','#FF0000','#CC0000','#990000','#660000','#330000','#FFCC99','#FF9966','#FF9900','#FF6600','#CC6600','#993300','#663300','#FFFF99','#FFFF66','#FFCC66','#FFCC33','#CC9933','#996633','#663333','#FFFFCC','#FFFF33','#FFFF00','#FFCC00','#999900','#666600','#333300','#99FF99','#66FF99','#33FF33','#33CC00','#009900','#006600','#003300','#99FFFF','#33FFFF','#66CCCC','#00CCCC','#339999','#336666','#003333','#CCFFFF','#66FFFF','#33CCFF','#3366FF','#3333FF','#000099','#000066','#CCCCFF','#9999FF','#6666CC','#6633FF','#6600CC','#333399','#330099','#FFCCFF','#FF99FF','#CC66CC','#CC33CC','#993399','#663366','#330033'];
var arrBlocktag=[{n:'p',t:'普通段落'},{n:'h1',t:'标题1'},{n:'h2',t:'标题2'},{n:'h3',t:'标题3'},{n:'h4',t:'标题4'},{n:'h5',t:'标题5'},{n:'h6',t:'标题6'},{n:'pre',t:'已编排格式'},{n:'address',t:'地址'}];
var arrFontname=[{n:'宋体',c:'SimSun'},{n:'仿宋体',c:'FangSong_GB2312'},{n:'黑体',c:'SimHei'},{n:'楷体',c:'KaiTi_GB2312'},{n:'微软雅黑',c:'Microsoft YaHei'},{n:'Arial'},{n:'Arial Narrow'},{n:'Arial Black'},{n:'Comic Sans MS'},{n:'Courier New'},{n:'System'},{n:'Times New Roman'},{n:'Tahoma'},{n:'Verdana'}];
var arrFontsize=[{n:'xx-small',wkn:'x-small',s:'8pt',t:'极小'},{n:'x-small',wkn:'small',s:'10pt',t:'特小'},{n:'small',wkn:'medium',s:'12pt',t:'小'},{n:'medium',wkn:'large',s:'14pt',t:'中'},{n:'large',wkn:'x-large',s:'18pt',t:'大'},{n:'x-large',wkn:'xx-large',s:'24pt',t:'特大'},{n:'xx-large',wkn:'-webkit-xxx-large',s:'36pt',t:'极大'}];
var menuAlign=[{s:'左对齐',v:'justifyleft'},{s:'居中',v:'justifycenter'},{s:'右对齐',v:'justifyright'},{s:'两端对齐',v:'justifyfull'}],menuList=[{s:'数字列表',v:'insertOrderedList'},{s:'符号列表',v:'insertUnorderedList'}];
var htmlPastetext='<div>使用键盘快捷键(Ctrl+V)把内容粘贴到方框里,按 确定</div><div><textarea id="xhePastetextValue" wrap="soft" spellcheck="false" style="width:300px;height:100px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlLink='<div>链接地址: <input type="text" id="xheLinkUrl" value="http://" class="xheText" /></div><div>打开方式: <select id="xheLinkTarget"><option selected="selected" value="">默认</option><option value="_blank">新窗口</option><option value="_self">当前窗口</option><option value="_parent">父窗口</option></select></div><div style="display:none">链接文字: <input type="text" id="xheLinkText" value="" class="xheText" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlImg='<div>图片文件: <input type="text" id="xheImgUrl" value="http://" class="xheText" /></div><div>替换文本: <input type="text" id="xheImgAlt" /></div><div>对齐方式: <select id="xheImgAlign"><option selected="selected" value="">默认</option><option value="left">左对齐</option><option value="right">右对齐</option><option value="top">顶端</option><option value="middle">居中</option><option value="baseline">基线</option><option value="bottom">底边</option></select></div><div>宽度高度: <input type="text" id="xheImgWidth" style="width:40px;" /> x <input type="text" id="xheImgHeight" style="width:40px;" /></div><div>边框大小: <input type="text" id="xheImgBorder" style="width:40px;" /></div><div>水平间距: <input type="text" id="xheImgHspace" style="width:40px;" /> 垂直间距: <input type="text" id="xheImgVspace" style="width:40px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlFlash='<div>动画文件: <input type="text" id="xheFlashUrl" value="http://" class="xheText" /></div><div>宽度高度: <input type="text" id="xheFlashWidth" style="width:40px;" value="480" /> x <input type="text" id="xheFlashHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlMedia='<div>媒体文件: <input type="text" id="xheMediaUrl" value="http://" class="xheText" /></div><div>宽度高度: <input type="text" id="xheMediaWidth" style="width:40px;" value="480" /> x <input type="text" id="xheMediaHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlTable='<div>行数列数: <input type="text" id="xheTableRows" style="width:40px;" value="3" /> x <input type="text" id="xheTableColumns" style="width:40px;" value="2" /></div><div>标题单元: <select id="xheTableHeaders"><option selected="selected" value="">无</option><option value="row">第一行</option><option value="col">第一列</option><option value="both">第一行和第一列</option></select></div><div>宽度高度: <input type="text" id="xheTableWidth" style="width:40px;" value="200" /> x <input type="text" id="xheTableHeight" style="width:40px;" value="" /></div><div>边框大小: <input type="text" id="xheTableBorder" style="width:40px;" value="1" /></div><div>表格间距: <input type="text" id="xheTableCellSpacing" style="width:40px;" value="1" /> 表格填充: <input type="text" id="xheTableCellPadding" style="width:40px;" value="1" /></div><div>对齐方式: <select id="xheTableAlign"><option selected="selected" value="">默认</option><option value="left">左对齐</option><option value="center">居中</option><option value="right">右对齐</option></select></div><div>表格标题: <input type="text" id="xheTableCaption" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
var htmlAbout='<div style="font:12px Arial;width:245px;word-wrap:break-word;word-break:break-all;"><p><span style="font-size:20px;color:#1997DF;">xhEditor</span><br />v1.1.1 (build 101002)</p><p>xhEditor是基于jQuery开发的跨平台轻量XHTML编辑器,基于<a href="http://www.gnu.org/licenses/lgpl.html" target="_blank">LGPL</a>开源协议发布。</p><p>Copyright © <a href="http://xheditor.com/" target="_blank">xhEditor.com</a>. All rights reserved.</p></div>';
var itemEmots={'default':{name:'默认',width:24,height:24,line:7,list:{'smile':'微笑','tongue':'吐舌头','titter':'偷笑','laugh':'大笑','sad':'难过','wronged':'委屈','fastcry':'快哭了','cry':'哭','wail':'大哭','mad':'生气','knock':'敲打','curse':'骂人','crazy':'抓狂','angry':'发火','ohmy':'惊讶','awkward':'尴尬','panic':'惊恐','shy':'害羞','cute':'可怜','envy':'羡慕','proud':'得意','struggle':'奋斗','quiet':'安静','shutup':'闭嘴','doubt':'疑问','despise':'鄙视','sleep':'睡觉','bye':'再见'}}};
var arrTools={Cut:{t:'剪切 (Ctrl+X)'},Copy:{t:'复制 (Ctrl+C)'},Paste:{t:'粘贴 (Ctrl+V)'},Pastetext:{t:'粘贴文本',h:isIE?0:1},Blocktag:{t:'段落标签',h:1},Fontface:{t:'字体',h:1},FontSize:{t:'字体大小',h:1},Bold:{t:'加粗 (Ctrl+B)',s:'Ctrl+B'},Italic:{t:'斜体 (Ctrl+I)',s:'Ctrl+I'},Underline:{t:'下划线 (Ctrl+U)',s:'Ctrl+U'},Strikethrough:{t:'删除线 (Ctrl+S)',s:'Ctrl+S'},FontColor:{t:'字体颜色',h:1},BackColor:{t:'背景颜色',h:1},SelectAll:{t:'全选 (Ctrl+A)'},Removeformat:{t:'删除文字格式'},Align:{t:'对齐',h:1},List:{t:'列表',h:1},Outdent:{t:'减少缩进 (Shift+Tab)',s:'Shift+Tab'},Indent:{t:'增加缩进 (Tab)',s:'Tab'},Link:{t:'超链接 (Ctrl+K)',s:'Ctrl+K',h:1},Unlink:{t:'取消超链接'},Img:{t:'图片',h:1},Flash:{t:'Flash动画',h:1},Media:{t:'多媒体文件',h:1},Emot:{t:'表情',s:'ctrl+e',h:1},Table:{t:'表格',h:1},Source:{t:'源代码'},Preview:{t:'预览'},Print:{t:'打印 (Ctrl+P)',s:'Ctrl+P'},Fullscreen:{t:'全屏编辑 (Esc)',s:'Esc'},About:{t:'关于 xhEditor'}};
var toolsThemes={
mini:'Bold,Italic,Underline,Strikethrough,|,Align,List,|,Link,Img',
simple:'Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,|,Align,List,Outdent,Indent,|,Link,Img,Emot',
full:'Cut,Copy,Paste,Pastetext,|,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,SelectAll,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Img,Flash,Media,Emot,Table,|,Source,Preview,Print,Fullscreen'};
toolsThemes.mfull=toolsThemes.full.replace(/\|(,Align)/i,'/$1');
var arrDbClick={'a':'Link','img':'Img','embed':'Embed'},uploadInputname='filedata';
$.xheditor=function(textarea,options)
{
var defaults={skin:'default',tools:'full',clickCancelDialog:true,linkTag:false,internalScript:false,inlineScript:false,internalStyle:true,inlineStyle:true,showBlocktag:false,forcePtag:true,upLinkExt:"zip,rar,txt",upImgExt:"jpg,jpeg,gif,png",upFlashExt:"swf",upMediaExt:"wmv,avi,wma,mp3,mid",modalWidth:350,modalHeight:220,modalTitle:true,defLinkText:'点击打开链接',layerShadow:3,emotMark:false,upBtnText:'上传',wordDeepClean:true,hoverExecDelay:100,html5Upload:true,upMultiple:99};
var _this=this,_text=textarea,_jText=$(_text),_jForm=_jText.closest('form'),_jTools,_jArea,_win,_jWin,_doc,_jDoc;
var bookmark;
var bInit=false,bSource=false,bFullscreen=false,bCleanPaste=false,outerScroll,bShowBlocktag=false,sLayoutStyle='',ev=null,timer,bDisableHoverExec=false,bQuickHoverExec=false;
var lastPoint=null,lastAngle=null;//鼠标悬停显示
var editorHeight=0;
var settings=_this.settings=$.extend({},defaults,options );
var plugins=settings.plugins,strPlugins=[];
if(plugins)
{
arrTools=$.extend({},arrTools,plugins);
$.each(plugins,function(n){strPlugins.push(n);});
strPlugins=strPlugins.join(',');
}
if(settings.tools.match(/^\s*(m?full|simple|mini)\s*$/i))
{
var toolsTheme=toolsThemes[$.trim(settings.tools)];
settings.tools=(settings.tools.match(/m?full/i)&&plugins)?toolsTheme.replace('Table','Table,'+strPlugins):toolsTheme;//插件接在full的Table后面
}
if(!settings.tools.match(/(^|,)\s*About\s*(,|$)/i))settings.tools+=',About';
settings.tools=settings.tools.split(',');
if(settings.editorRoot)editorRoot=settings.editorRoot;
editorRoot=getLocalUrl(editorRoot,'abs');
//基本控件名
var idCSS='xheCSS_'+settings.skin,idContainer='xhe'+xCount+'_container',idTools='xhe'+xCount+'_Tool',idIframeArea='xhe'+xCount+'_iframearea',idIframe='xhe'+xCount+'_iframe',idFixFFCursor='xhe'+xCount+'_fixffcursor';
var headHTML='',bodyClass='',skinPath=editorRoot+'xheditor_skin/'+settings.skin+'/',arrEmots=itemEmots,urlType=settings.urlType,urlBase=settings.urlBase,emotPath=settings.emotPath,emotPath=emotPath?emotPath:editorRoot+'xheditor_emot/',selEmotGroup='';
arrEmots=$.extend({},arrEmots,settings.emots);
emotPath=getLocalUrl(emotPath,'rel',urlBase?urlBase:null);//返回最短表情路径
bShowBlocktag=settings.showBlocktag;
if(bShowBlocktag)bodyClass+=' showBlocktag';
var arrShortCuts=[];
this.init=function()
{
//加载样式表
if($('#'+idCSS).length==0)$('head').append('<link id="'+idCSS+'" rel="stylesheet" type="text/css" href="'+skinPath+'ui.css" />');
//初始化编辑器
var cw = settings.width || _text.style.width || _jText.outerWidth();
editorHeight = settings.height || _text.style.height || _jText.outerHeight();
if(is(editorHeight,'string'))editorHeight=editorHeight.replace(/[^\d]+/g,'');
if(cw<=0||editorHeight<=0)//禁止对隐藏区域里的textarea初始化编辑器
{
alert('当前textarea处于隐藏状态,请将之显示后再初始化xhEditor,或者直接设置textarea的width和height样式');
return false;
}
if(/^[0-9\.]+$/i.test(''+cw))cw+='px';
//编辑器CSS背景
var editorBackground=settings.background || _text.style.background;
//工具栏内容初始化
var arrToolsHtml=['<span class="xheGStart"/>'],tool,cn,regSeparator=/\||\//i;
$.each(settings.tools,function(i,n)
{
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGEnd"/>');
if(n=='|')arrToolsHtml.push('<span class="xheSeparator"/>');
else if(n=='/')arrToolsHtml.push('<br />');
else
{
tool=arrTools[n];
if(!tool)return;
if(tool.c)cn=tool.c;
else cn='xheIcon xheBtn'+n;
arrToolsHtml.push('<span><a href="javascript:void(0);" title="'+tool.t+'" name="'+n+'" class="xheButton xheEnabled" tabindex="-1"><span class="'+cn+'" unselectable="on" /></a></span>');
if(tool.s)_this.addShortcuts(tool.s,n);
}
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGStart"/>');
});
arrToolsHtml.push('<span class="xheGEnd"/><br />');
_jText.after($('<input type="text" id="'+idFixFFCursor+'" style="position:absolute;display:none;" /><span id="'+idContainer+'" class="xhe_'+settings.skin+'" style="display:none"><table cellspacing="0" cellpadding="0" class="xheLayout" style="width:'+cw+';height:'+editorHeight+'px;"><tbody><tr><td id="'+idTools+'" class="xheTool" unselectable="on" style="height:1px;"></td></tr><tr><td id="'+idIframeArea+'" class="xheIframeArea"><iframe frameborder="0" id="'+idIframe+'" src="javascript:;" style="width:100%;"></iframe></td></tr></tbody></table></span>'));
_jTools=$('#'+idTools);_jArea=$('#'+idIframeArea);
headHTML='<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><link rel="stylesheet" href="'+skinPath+'iframe.css"/>';
var loadCSS=settings.loadCSS;
if(loadCSS)
{
if(is(loadCSS,'array'))for(var i in loadCSS)headHTML+='<link rel="stylesheet" href="'+loadCSS[i]+'"/>';
else
{
if(loadCSS.match(/\s*<style(\s+[^>]*?)?>[\s\S]+?<\/style>\s*/i))headHTML+=loadCSS;
else headHTML+='<link rel="stylesheet" href="'+loadCSS+'"/>';
}
}
var iframeHTML='<html><head>'+headHTML;
if(editorBackground)iframeHTML+='<style>body{background:'+editorBackground+';}</style>';
iframeHTML+='</head><body spellcheck="false" class="editMode'+bodyClass+'"></body></html>';
_this.win=_win=$('#'+idIframe)[0].contentWindow;
_jWin=$(_win);
try{
this.doc=_doc = _win.document;_jDoc=$(_doc);
_doc.open();
_doc.write(iframeHTML);
_doc.close();
if(isIE)_doc.body.contentEditable='true';
else _doc.designMode = 'On';
}catch(e){}
setTimeout(setOpts,300);
_this.setSource();
_win.setInterval=null;//针对jquery 1.3无法操作iframe window问题的hack
//添加工具栏
_jTools.append(arrToolsHtml.join('')).bind('mousedown contextmenu',returnFalse).click(function(event)
{
var jButton=$(event.target).closest('a');
if(jButton.is('.xheEnabled'))
{
ev=event;
_this.exec(jButton.attr('name'));
}
return false;
});
_jTools.find('.xheButton').hover(function(event){//鼠标悬停执行
var jButton=$(this),delay=settings.hoverExecDelay;
var tAngle=lastAngle;lastAngle=null;
if(delay==-1||bDisableHoverExec||!jButton.is('.xheEnabled'))return false;
if(tAngle&&tAngle>10)//检测误操作
{
bDisableHoverExec=true;
setTimeout(function(){bDisableHoverExec=false;},100);
return false;
}
var cmd=jButton.attr('name'),bHover=arrTools[cmd].h==1;
if(!bHover)
{
_this.hidePanel();//移到非悬停按钮上隐藏面板
return false;
}
if(bQuickHoverExec)delay=0;
if(delay>=0)timer=setTimeout(function(){
ev=event;
lastPoint={x:ev.clientX,y:ev.clientY};
_this.exec(cmd);
},delay);
},function(event){lastPoint=null;if(timer)clearTimeout(timer);}).mousemove(function(event){
if(lastPoint)
{
var diff={x:event.clientX-lastPoint.x,y:event.clientY-lastPoint.y};
if(Math.abs(diff.x)>1||Math.abs(diff.y)>1)
{
if(diff.x>0&&diff.y>0)
{
var tAngle=Math.round(Math.atan(diff.y/diff.x)/0.017453293);
if(lastAngle)lastAngle=(lastAngle+tAngle)/2
else lastAngle=tAngle;
}
else lastAngle=null;
lastPoint={x:event.clientX,y:event.clientY};
}
}
});
//初始化面板
_jPanel=$('#xhePanel');
_jShadow=$('#xheShadow');
_jCntLine=$('#xheCntLine');
if(_jPanel.length==0)
{
_jPanel=$('<div id="xhePanel"></div>').mousedown(function(ev){ev.stopPropagation()});
_jShadow=$('<div id="xheShadow"></div>');
_jCntLine=$('<div id="xheCntLine"></div>');
setTimeout(function(){
$(document.body).append(_jPanel).append(_jShadow).append(_jCntLine);
},10);
}
//切换显示区域
$('#'+idContainer).show();
_jText.hide();
_jArea.css('height',editorHeight-_jTools.outerHeight());
//绑定内核事件
_jText.focus(_this.focus);
_jForm.submit(saveResult).bind('reset', loadReset);
$(window).bind('unload beforeunload',saveResult).bind('resize',fixFullHeight);
$(document).mousedown(clickCancelPanel);
if(!bCheckEscInit){$(document).keydown(checkEsc);bCheckEscInit=true;}
_jWin.focus(function(){if(settings.focus)settings.focus();}).blur(function(){if(settings.blur)settings.blur();});
if(isSafari)_jWin.click(fixAppleSel);
_jDoc.mousedown(clickCancelPanel).keydown(checkShortcuts).keypress(forcePtag).dblclick(checkDblClick).bind('mousedown click',function(ev){_jText.trigger(ev.type);});
if(isIE)
{
//IE控件上Backspace会导致页面后退
_jDoc.keydown(function(ev){var rng=_this.getRng();if(ev.which==8&&rng.item){$(rng.item(0)).remove();return false;}});
//修正IE拖动img大小不更新width和height属性值的问题
function fixResize(ev)
{
var jImg=$(ev.target),v;
if(v=jImg.css('width'))jImg.css('width','').attr('width',v.replace(/[^0-9%]+/g, ''));
if(v=jImg.css('height'))jImg.css('height','').attr('height',v.replace(/[^0-9%]+/g, ''));
}
_jDoc.bind('controlselect',function(ev){
ev=ev.target;if(!$.nodeName(ev,'IMG'))return;
$(ev).unbind('resizeend',fixResize).bind('resizeend',fixResize);
});
}
var jBody=$(_doc.documentElement);
jBody.bind('paste',cleanPaste);
if(settings.disableContextmenu)jBody.bind('contextmenu',returnFalse);
//HTML5编辑区域直接拖放上传
if(settings.html5Upload)jBody.bind('dragenter dragover',function(ev){var types;if((types=ev.originalEvent.dataTransfer.types)&&$.inArray('Files', types)!=-1)return false;}).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0){
var i,cmd,arrCmd=['Link','Img','Flash','Media'],arrExt=[],strExt;
for(i in arrCmd){
cmd=arrCmd[i];
if(settings['up'+cmd+'Url']&&settings['up'+cmd+'Url'].match(/^[^!].*/i))arrExt.push(cmd+':,'+settings['up'+cmd+'Ext']);//允许上传
}
if(arrExt.length==0)return false;//禁止上传
else strExt=arrExt.join(',');
function getCmd(fileList){
var match,fileExt,cmd;
for(i=0;i<fileList.length;i++){
fileExt=fileList[i].fileName.replace(/.+\./,'');
if(match=strExt.match(new RegExp('(\\w+):[^:]*,'+fileExt+'(?:,|$)','i'))){
if(!cmd)cmd=match[1];
else if(cmd!=match[1])return 2;
}
else return 1;
}
return cmd;
}
cmd=getCmd(fileList);
if(cmd==1)alert('上传文件的扩展名必需为:'+strExt.replace(/\w+:,/g,''));
else if(cmd==2)alert('每次只能拖放上传同一类型文件');
else if(cmd){
_this.startUpload(fileList,settings['up'+cmd+'Url'],'*',function(arrMsg){
var arrUrl=[],msg,onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用户上传回调
for(i in arrMsg){
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!')url=url.substr(1);
arrUrl.push(url);
}
_this.exec(cmd);
$('#xhe'+cmd+'Url').val(arrUrl.join(' '));
$('#xheSave').click();
});
}
return false;
}
});
//添加用户快捷键
var shortcuts=settings.shortcuts;
if(shortcuts)$.each(shortcuts,function(key,func){_this.addShortcuts(key,func);});
xCount++;
bInit=true;
if(settings.fullscreen)_this.toggleFullscreen();
else if(settings.sourceMode)setTimeout(_this.toggleSource,20);
return true;
}
this.remove=function()
{
_this.hidePanel();
saveResult();//卸载前同步最新内容到textarea
//取消绑定事件
_jText.unbind('focus',_this.focus);
_jForm.unbind('submit',saveResult).unbind('reset', loadReset);
$(window).unbind('unload beforeunload',saveResult).unbind('resize',fixFullHeight);
$(document).unbind('mousedown',clickCancelPanel);
$('#'+idContainer+','+'#'+idFixFFCursor).remove();
_jText.show();
bInit=false;
}
this.saveBookmark=function(){
if(!bSource){
var rng=_this.getRng();
rng=rng.cloneRange?rng.cloneRange():rng;
bookmark={'top':_jWin.scrollTop(),'rng':rng};
}
}
this.loadBookmark=function()
{
if(bSource||!bookmark)return;
_this.focus();
var rng=bookmark.rng;
if(isIE)rng.select();
else
{
var sel=_this.getSel();
sel.removeAllRanges();
sel.addRange(rng);
}
_jWin.scrollTop(bookmark.top);
bookmark=null;
}
this.focus=function()
{
if(!bSource)_jWin.focus();
else $('#sourceCode',_doc).focus();
return false;
}
this.setCursorFirst=function(firstBlock)
{
_this.focus();_win.scrollTo(0,0);
var rng=_this.getRng(),_body=_doc.body,firstNode=_body,firstTag;
if(firstBlock&&firstNode.firstChild&&(firstTag=firstNode.firstChild.tagName)&&firstTag.match(/^p|div|h[1-6]$/i))firstNode=_body.firstChild;
isIE?rng.moveToElementText(firstNode):rng.setStart(firstNode,0);
rng.collapse(true);
if(isIE)rng.select();
else{var sel=_this.getSel();sel.removeAllRanges();sel.addRange(rng);}
}
this.getSel=function()
{
return _win.getSelection ? _win.getSelection() : _doc.selection;
}
this.getRng=function()
{
var sel=_this.getSel(),rng;
try{
rng = sel.rangeCount > 0 ? sel.getRangeAt(0) : (sel.createRange ? sel.createRange() : (_doc.createRange?_doc.createRange():_doc.body.createTextRange()));
}catch (ex){}
return rng;
}
this.getParent=function(tag)
{
var rng=_this.getRng(),p;
if(!isIE)
{
p = rng.commonAncestorContainer;
if(!rng.collapsed)if(rng.startContainer == rng.endContainer&&rng.startOffset - rng.endOffset < 2&&rng.startContainer.hasChildNodes())p = rng.startContainer.childNodes[rng.startOffset];
}
else p=rng.item?rng.item(0):rng.parentElement();
tag=tag?tag:'*';p=$(p);
if(!p.is(tag))p=$(p).closest(tag);
return p;
}
this.getSelect=function(format)
{
var sel=_this.getSel(),rng=_this.getRng(),isCollapsed=true;
if (!rng || rng.item)isCollapsed=false
else isCollapsed=!sel || rng.boundingWidth == 0 || rng.collapsed;
if(format=='text')return isCollapsed ? '' : (rng.text || (sel.toString ? sel.toString() : ''));
var sHtml;
if(rng.cloneContents)
{
var tmp=$('<div></div>'),c;
c = rng.cloneContents();
if(c)tmp.append(c);
sHtml=tmp.html();
}
else if(is(rng.item))sHtml=rng.item(0).outerHTML;
else if(is(rng.htmlText))sHtml=rng.htmlText;
else sHtml=rng.toString();
if(isCollapsed)sHtml='';
sHtml=_this.processHTML(sHtml,'read');
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
return sHtml;
}
this.pasteHTML=function(sHtml,bStart)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
var sel=_this.getSel(),rng=_this.getRng();
if(bStart!=undefined)//非覆盖式插入
{
if(rng.item)
{
var n=rng.item(0);
rng=_doc.body.createTextRange();
rng.moveToElementText(n);
rng.select();
}
rng.collapse(bStart);
}
sHtml+='<'+(isIE?'img':'span')+' id="_xhe_temp" style="display:none" />';
if(rng.insertNode)
{
rng.deleteContents();
rng.insertNode(rng.createContextualFragment(sHtml));
}
else
{
if(sel.type.toLowerCase()=='control'){sel.clear();rng=_this.getRng();};
rng.pasteHTML(sHtml);
}
var jTemp=$('#_xhe_temp',_doc),temp=jTemp[0];
if(isIE)
{
rng.moveToElementText(temp);
rng.select();
}
else
{
rng.selectNode(temp);
sel.removeAllRanges();
sel.addRange(rng);
}
jTemp.remove();
}
this.pasteText=function(text,bStart)
{
if(!text)text='';
text=_this.domEncode(text);
text = text.replace(/\r?\n/g, '<br />');
_this.pasteHTML(text,bStart);
}
this.appendHTML=function(sHtml)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
$(_doc.body).append(sHtml);
}
this.domEncode=function(str)
{
return str.replace(/[<>]/g,function(c){return {'<':'<','>':'>'}[c];});
}
this.setSource=function(sHtml)
{
bookmark=null;
if(typeof sHtml!='string'&&sHtml!='')sHtml=_text.value;
if(bSource)$('#sourceCode',_doc).val(sHtml);
else
{
if(settings.beforeSetSource)sHtml=settings.beforeSetSource(sHtml);
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
sHtml=_this.cleanWord(sHtml);
sHtml=_this.processHTML(sHtml,'write');
if(isIE){//修正IE会删除可视内容前的script,style,<!--
_doc.body.innerHTML='<img id="_xhe_temp" style="display:none" />'+sHtml;
$('#_xhe_temp',_doc).remove();
}
else _doc.body.innerHTML=sHtml;
}
}
this.processHTML=function(sHtml,mode)
{
var appleClass=' class="Apple-style-span"';
if(mode=='write')
{//write
//恢复emot
function restoreEmot(all,attr,q,emot)
{
emot=emot.split(',');
if(!emot[1]){emot[1]=emot[0];emot[0]=''}
if(emot[0]=='default')emot[0]='';
return all.replace(/\s+src\s*=\s*(["']?).*?\1(\s|$|\/|>)/i,'$2').replace(attr,' src="'+emotPath+(emot[0]?emot[0]:'default')+'/'+emot[1]+'.gif"'+(settings.emotMark?' emot="'+(emot[0]?emot[0]+',':'')+emot[1]+'"'+(all.match(/\s+alt\s*=\s*(["']?)\s*(.*?)\s*\1[\s\/>]/i)?'':' alt="'+emot[1]+'"'):''));
}
sHtml = sHtml.replace(/<img(?:\s+[^>]*?)?(\s+emot\s*=\s*(["']?)\s*(.*?)\s*\2)(?:\s+[^>]*?)?\/?>/ig,restoreEmot);
//保存属性值:src,href
function saveValue(all,tag,attr,n,q,v){return all.replace(attr,(urlBase?(' '+n+'="'+getLocalUrl(v,'abs',urlBase)+'"'):attr)+' _xhe_'+n+'="'+v+'"');}
sHtml = sHtml.replace(/<(\w+(?:\:\w+)?)(?:\s+[^>]*?)?(\s+(src|href)\s*=\s*(["']?)\s*(.*?)\s*\4)(?:\s+[^>]*?)?\/?>/ig,saveValue);
sHtml = sHtml.replace(/<(\/?)del(\s+[^>]*?)?>/ig,'<$1strike$2>');//编辑状态统一转为strike
if(isMozilla)
{
sHtml = sHtml.replace(/<(\/?)strong(\s+[^>]*?)?>/ig,'<$1b$2>');
sHtml = sHtml.replace(/<(\/?)em(\s+[^>]*?)?>/ig,'<$1i$2>');
}
else if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.n){s=t.wkn;break;}
}
return pre+'font-size:'+s+aft;
});
sHtml = sHtml.replace(/<strong(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-weight: bold;"$1>');
sHtml = sHtml.replace(/<em(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-style: italic;"$1>');
sHtml = sHtml.replace(/<u(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: underline;"$1>');
sHtml = sHtml.replace(/<strike(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: line-through;"$1>');
sHtml = sHtml.replace(/<\/(strong|em|u|strike)>/ig,'</span>');
sHtml = sHtml.replace(/<span((?:\s+[^>]*?)?\s+style="([^"]*;)*\s*(font-family|font-size|color|background-color)\s*:\s*[^;"]+\s*;?"[^>]*)>/ig,'<span'+appleClass+'$1>');
}
else if(isIE)
{
sHtml = sHtml.replace(/'/ig, ''');
sHtml = sHtml.replace(/\s+(disabled|checked|readonly|selected)\s*=\s*[\"\']?(false|0)[\"\']?/ig, '');
}
sHtml = sHtml.replace(/<a(\s+[^>]*?)?\/>/,'<a$1></a>');
if(!isSafari)
{
//style转font
function style2font(all,tag,style,content)
{
var attrs='',f,s1,s2,c;
f=style.match(/font-family\s*:\s*([^;"]+)/i);
if(f)attrs+=' face="'+f[1]+'"';
s1=style.match(/font-size\s*:\s*([^;"]+)/i);
if(s1)
{
s1=s1[1].toLowerCase();
for(var j=0;j<arrFontsize.length;j++)if(s1==arrFontsize[j].n||s1==arrFontsize[j].s){s2=j+1;break;}
if(s2)
{
attrs+=' size="'+s2+'"';
style=style.replace(/(^|;)(\s*font-size\s*:\s*[^;"]+;?)+/ig,'$1');
}
}
c=style.match(/(?:^|[\s;])color\s*:\s*([^;"]+)/i);
if(c)
{
var rgb;
if(rgb=c[1].match(/\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)){c[1]='#';for(var i=1;i<=3;i++)c[1]+=(rgb[i]-0).toString(16);}
c[1]=c[1].replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,'#$1$1$2$2$3$3');
attrs+=' color="'+c[1]+'"';
}
style=style.replace(/(^|;)(\s*(font-family|color)\s*:\s*[^;"]+;?)+/ig,'$1');
if(attrs!='')
{
if(style)attrs+=' style="'+style+'"';
return '<font'+attrs+'>'+content+"</font>";
}
else return all;
}
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,style2font);//最里层
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,style2font);//第2层
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,style2font);//第3层
}
}
else
{//read
//恢复属性值src,href
function restoreValue(all,n,q,v)
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
return all.replace(new RegExp('\\s+'+n+'\\s*=\\s*(["\']?).*?\\1(\\s|/?>)','ig'),' '+n+'="'+v.replace(/\$/g,'$$$$')+'"$2');
}
sHtml = sHtml.replace(/<(?:\w+(?:\:\w+)?)(?:\s+[^>]*?)?\s+_xhe_(src|href)\s*=\s*(["']?)\s*(.*?)\s*\2(?:\s+[^>]*?)?\/?>/ig,restoreValue);
if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.wkn){s=t.n;break;}
}
return pre+'font-size:'+s+aft;
});
var arrAppleSpan=[{r:/font-weight:\sbold/ig,t:'strong'},{r:/font-style:\sitalic/ig,t:'em'},{r:/text-decoration:\sunderline/ig,t:'u'},{r:/text-decoration:\sline-through/ig,t:'strike'}];
function replaceAppleSpan(all,tag,attr1,attr2,content)
{
var attr=attr1+attr2,newTag='';
if(!attr)return content;
for(var i=0;i<arrAppleSpan.length;i++)
{
if(attr.match(arrAppleSpan[i].r))
{
newTag=arrAppleSpan[i].t;
break;
}
}
if(newTag)return '<'+newTag+'>'+content+'</'+newTag+'>';
else return all;
}
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,replaceAppleSpan);//最里层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第2层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第3层
}
if(!isIE){//字符间的文本换行强制转br
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/([^<>\r\n]?)((?:\r?\n)+)([^<>\r\n]?)/ig,function(all,left,br,right){if(left||right)return left+br.replace(/\r?\n/g,'<br />')+right;else return all;});
});
}
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+(?:_xhe_|_moz_|_webkit_)[^=]+?\s*=\s*(["']?).*?\2(\s|\/?>)/ig,'$1$3');
sHtml = sHtml.replace(/(<\w+[^>]*?)\s+class\s*=\s*(["']?)\s*(?:apple|webkit)\-.+?\s*\2(\s|\/?>)/ig, "$1$3");
sHtml = sHtml.replace(/<img(\s+[^>]+?)\/?>/ig,function(all,attr){if(!attr.match(/\s+alt\s*(["']?).*?\1(\s|$)/i))attr+=' alt=""';return '<img'+attr+' />';});//img强制加alt
sHtml = sHtml.replace(/\s+jquery\d+="\d+"/ig,'');
}
return sHtml;
}
this.getSource=function(bFormat)
{
var sHtml,beforeGetSource=settings.beforeGetSource;
if(bSource)
{
sHtml=$('#sourceCode',_doc).val();
if(!beforeGetSource){
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/(\t*\r?\n\t*)+/g,'')//标准HTML模式清理缩进和换行
});
}
}
else
{
sHtml=_this.processHTML(_doc.body.innerHTML,'read');
sHtml=sHtml.replace(/^\s*(?:<(p|div)(?:\s+[^>]*?)?>)?\s*(<br(?:\s+[^>]*?)?>)*\s*(?:<\/\1>)?\s*$/i, '');//修正Firefox在空内容情况下多出来的代码
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml,bFormat);
sHtml=_this.cleanWord(sHtml);
if(beforeGetSource)sHtml=beforeGetSource(sHtml);
}
_text.value=sHtml;
return sHtml;
}
this.cleanWord=function(sHtml)
{
if(sHtml.match(/mso(-|normal)|WordDocument/i))
{
var deepClean=settings.wordDeepClean;
//格式化
sHtml = sHtml.replace(/(<link(?:\s+[^>]*?)?)\s+href\s*=\s*(["']?)\s*file:\/\/.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, '');
//区块标签清理
sHtml = sHtml.replace(/<!--[\s\S]*?-->|<!(--)?\[[\s\S]+?\](--)?>|<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
sHtml = sHtml.replace(/<\/?\w+:[^>]*>/ig, '');
if(deepClean)sHtml = sHtml.replace(/<\/?(span|a|img)(\s+[^>]*?)?>/ig,'');
//属性清理
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+class\s*=\s*(["']?)\s*mso.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//删除所有mso开头的样式
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+lang\s*=\s*(["']?)\s*.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//删除lang属性
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+align\s*=\s*(["']?)\s*left\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//取消align=left
//样式清理
sHtml = sHtml.replace(/<\w+(?:\s+[^>]*?)?(\s+style\s*=\s*(["']?)\s*([\s\S]*?)\s*\2)(?:\s+[^>]*?)?\s*\/?>/ig,function(all,attr,p,styles){
styles=$.trim(styles.replace(/\s*(mso-[^:]+:.+?|margin\s*:\s*0cm 0cm 0pt\s*|(text-align|font-variant|line-height)\s*:\s*.+?)(;|$)\s*/ig,''));
return all.replace(attr,deepClean?'':styles?' style="'+styles+'"':'');
});
}
return sHtml;
}
this.cleanHTML=function(sHtml)
{
sHtml = sHtml.replace(/<!?\/?(DOCTYPE|html|body|meta)(\s+[^>]*?)?>/ig, '');
var arrHeadSave;sHtml = sHtml.replace(/<head(?:\s+[^>]*?)?>([\s\S]*?)<\/head>/i, function(all,content){arrHeadSave=content.match(/<(script|style)(\s+[^>]*?)?>[\s\S]*?<\/\1>/ig);return '';});
if(arrHeadSave)sHtml=arrHeadSave.join('')+sHtml;
sHtml = sHtml.replace(/<\??xml(:\w+)?(\s+[^>]*?)?>([\s\S]*?<\/xml>)?/ig, '');
if(!settings.linkTag)sHtml = sHtml.replace(/<link(\s+[^>]*?)?>/ig, '');
if(!settings.internalScript)sHtml = sHtml.replace(/<script(\s+[^>]*?)?>[\s\S]*?<\/script>/ig, '');
if(!settings.inlineScript)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+on(?:click|dblclick|mousedown|mouseup|mousemove|mouseover|mouseout|mouseenter|mouseleave|keydown|keypress|keyup|change|select|submit|reset|blur|focus|load|unload)\s*=\s*(["']?)[\s\S]*?\3((?:\s+[^>]*?)?\/?>)/ig,'$1$2$4');
if(!settings.internalStyle)sHtml = sHtml.replace(/<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
if(!settings.inlineStyle)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+(style|class)\s*=\s*(["']?)[\s\S]*?\4((?:\s+[^>]*?)?\/?>)/ig,'$1$2$5');
sHtml=sHtml.replace(/<\/(strong|b|u|strike|em|i)>((?:\s|<br\/?>| )*?)<\1(\s+[^>]*?)?>/ig,'$2');//连续相同标签
return sHtml;
}
this.formatXHTML=function(sHtml,bFormat)
{
var emptyTags = makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");//HTML 4.01
var blockTags = makeMap("address,applet,blockquote,button,center,dd,dir,div,dl,dt,fieldset,form,frameset,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");//HTML 4.01
var inlineTags = makeMap("a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");//HTML 4.01
var closeSelfTags = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
var fillAttrsTags = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
var specialTags = makeMap("script,style");
var tagReplac={'b':'strong','i':'em','s':'del','strike':'del'};
var startTag = /^<\??(\w+(?:\:\w+)?)((?:\s+[\w-\:]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/(\w+(?:\:\w+)?)[^>]*>/;
var attr = /\s+([\w-]+(?:\:\w+)?)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s]+)))?/g;
var skip=0,stack=[],last=sHtml,results=Array(),lvl=-1,lastTag='body',lastTagStart;
stack.last = function(){return this[ this.length - 1 ];};
while(last.length>0)
{
if(!stack.last()||!specialTags[stack.last()])
{
skip=0;
if(last.substring(0, 4)=='<!--')
{//注释标签
skip=last.indexOf("-->");
if(skip!=-1)
{
skip+=3;
addHtmlFrag(last.substring(0,skip));
}
}
else if(last.substring(0, 2)=='</')
{//结束标签
match = last.match( endTag );
if(match)
{
parseEndTag(match[1]);
skip = match[0].length;
}
}
else if(last.charAt(0)=='<')
{//开始标签
match = last.match( startTag );
if(match)
{
parseStartTag(match[1],match[2],match[3]);
skip = match[0].length;
}
}
if(skip==0)//普通文本
{
skip=last.indexOf('<');
if(skip==0)skip=1;
else if(skip<0)skip=last.length;
addHtmlFrag(_this.domEncode(last.substring(0,skip)));
}
last=last.substring(skip);
}
else
{//处理style和script
last=last.replace(/^([\s\S]*?)<\/(style|script)>/i, function(all, script,tagName){
results.push(script);
return ''
});
parseEndTag(stack.last());
}
}
parseEndTag();
sHtml=results.join('');
results=null;
function makeMap(str)
{
var obj = {}, items = str.split(",");
for ( var i = 0; i < items.length; i++ )obj[ items[i] ] = true;
return obj;
}
function processTag(tagName)
{
if(tagName)
{
tagName=tagName.toLowerCase();
var tag=tagReplac[tagName];
if(tag)tagName=tag;
}
else tagName='';
return tagName;
}
function parseStartTag(tagName,rest,unary)
{
tagName=processTag(tagName);
if(blockTags[tagName])while(stack.last()&&inlineTags[stack.last()])parseEndTag(stack.last());
if(closeSelfTags[tagName]&&stack.last()==tagName)parseEndTag(tagName);
unary = emptyTags[ tagName ] || !!unary;
if (!unary)stack.push(tagName);
var all=Array();
all.push('<' + tagName);
rest.replace(attr, function(match, name)
{
name=name.toLowerCase();
var value = arguments[2] ? arguments[2] :
arguments[3] ? arguments[3] :
arguments[4] ? arguments[4] :
fillAttrsTags[name] ? name : "";
all.push(' '+name+'="'+value+'"');
});
all.push((unary ? " /" : "") + ">");
addHtmlFrag(all.join(''),tagName,true);
}
function parseEndTag(tagName)
{
if(!tagName)var pos=0;//清空栈
else
{
tagName=processTag(tagName);
for(var pos=stack.length-1;pos>=0;pos--)if(stack[pos]==tagName)break;//向上寻找匹配的开始标签
}
if(pos>=0)
{
for(var i=stack.length-1;i>=pos;i--)addHtmlFrag("</" + stack[i] + ">",stack[i]);
stack.length=pos;
}
}
function addHtmlFrag(html,tagName,bStart)
{
if(bFormat==true)
{
html=html.replace(/(\t*\r?\n\t*)+/g,'');//清理换行符和相邻的制表符
if(html.match(/^\s*$/))return;//不格式化空内容的标签
var bBlock=blockTags[tagName],tag=bBlock?tagName:'';
if(bBlock)
{
if(bStart)lvl++;//块开始
if(lastTag=='')lvl--;//补文本结束
}
else if(lastTag)lvl++;//文本开始
if(tag!=lastTag||bBlock)addIndent();
results.push(html);
if(tagName=='br')addIndent();//回车强制换行
if(bBlock&&(emptyTags[tagName]||!bStart))lvl--;//块结束
lastTag=bBlock?tagName:'';lastTagStart=bStart;
}
else results.push(html);
}
function addIndent(){results.push('\r\n');if(lvl>0){var tabs=lvl;while(tabs--)results.push("\t");}}
//font转style
function font2style(all,tag,attrs,content)
{
if(!attrs)return content;
var styles='',f,s,c,style;
f=attrs.match(/ face\s*=\s*"\s*([^"]+)\s*"/i);
if(f)styles+='font-family:'+f[1]+';';
s=attrs.match(/ size\s*=\s*"\s*(\d+)\s*"/i);
if(s)styles+='font-size:'+arrFontsize[(s[1]>7?7:(s[1]<1?1:s[1]))-1].n+';';
c=attrs.match(/ color\s*=\s*"\s*([^"]+)\s*"/i);
if(c)styles+='color:'+c[1]+';';
style=attrs.match(/ style\s*=\s*"\s*([^"]+)\s*"/i);
if(style)styles+=style[1];
if(styles)content='<span style="'+styles+'">'+content+'</span>';
return content;
}
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,font2style);//最里层
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,font2style);//第2层
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,font2style);//第3层
sHtml = sHtml.replace(/^(\s*\r?\n)+|(\s*\r?\n)+$/g,'');//清理首尾换行
sHtml = sHtml.replace(/(\t*\r?\n)+/g,'\r\n');//多行变一行
return sHtml;
}
this.toggleShowBlocktag=function(state)
{
if(bShowBlocktag===state)return;
bShowBlocktag=!bShowBlocktag;
var _jBody=$(_doc.body);
if(bShowBlocktag)
{
bodyClass+=' showBlocktag';
_jBody.addClass('showBlocktag');
}
else
{
bodyClass=bodyClass.replace(' showBlocktag','');
_jBody.removeClass('showBlocktag');
}
}
this.toggleSource=function(state)
{
if(bSource===state)return;
_jTools.find('[name=Source]').toggleClass('xheEnabled').toggleClass('xheActive');
var _body=_doc.body,jBody=$(_body),sHtml;
var sourceCode,cursorMark='<span id="_xhe_cursor'+new Date().getTime()+'"></span>',cursorPos=0;
if(!bSource)
{//转为源代码模式
_this.pasteHTML(cursorMark,true);//标记当前位置
sHtml=_this.getSource(true);
cursorPos=sHtml.indexOf(cursorMark);
if(!isOpera)cursorPos=sHtml.substring(0,cursorPos).replace(/\r/g,'').length;//修正非opera光标定位点
sHtml=sHtml.replace(cursorMark,'');
if(isIE)_body.contentEditable='false';
else _doc.designMode = 'Off';
jBody.attr('scroll','no').attr('class','sourceMode').html('<textarea id="sourceCode" wrap="soft" spellcheck="false" height="100%" />');
sourceCode=$('#sourceCode',jBody).blur(_this.getSource)[0];
}
else
{//转为编辑模式
sHtml=_this.getSource();
jBody.html('').removeAttr('scroll').attr('class','editMode'+bodyClass);
if(isIE)_body.contentEditable='true';
else _doc.designMode = 'On';
if(isMozilla)
{
_this._exec("inserthtml","-");//修正firefox源代码切换回来无法删除文字的问题
$('#'+idFixFFCursor).show().focus().hide();//临时修正Firefox 3.6光标丢失问题
}
}
bSource=!bSource;
_this.setSource(sHtml);
if(bSource)//光标定位源码
{
_this.focus();
if(sourceCode.setSelectionRange)sourceCode.setSelectionRange(cursorPos, cursorPos);
else
{
var rng = sourceCode.createTextRange();
rng.move("character",cursorPos);
rng.select();
}
}
else _this.setCursorFirst(true);//定位最前面
_jTools.find('[name=Source],[name=Preview]').toggleClass('xheEnabled');
_jTools.find('.xheButton').not('[name=Source],[name=Fullscreen],[name=About]').toggleClass('xheEnabled');
setTimeout(setOpts,300);
}
this.showPreview=function()
{
var beforeSetSource=settings.beforeSetSource,sContent=_this.getSource();
if(beforeSetSource)sContent=beforeSetSource(sContent);
var sHTML='<html><head>'+headHTML+'<title>预览</title>'+(urlBase?'<base href="'+urlBase+'"/>':'')+'</head><body>' + sContent + '</body></html>';
var screen=window.screen,oWindow=window.open('', 'xhePreview', 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+Math.round(screen.width*0.9)+',height='+Math.round(screen.height*0.8)+',left='+Math.round(screen.width*0.05)),oDoc=oWindow.document;
oDoc.open();
oDoc.write(sHTML);
oDoc.close();
oWindow.focus();
}
this.toggleFullscreen=function(state)
{
if(bFullscreen===state)return;
var jLayout=$('#'+idContainer).find('.xheLayout'),jContainer=$('#'+idContainer);
if(bFullscreen)
{//取消全屏
jLayout.attr('style',sLayoutStyle);
_jArea.height(editorHeight-_jTools.outerHeight());
setTimeout(function(){$(window).scrollTop(outerScroll);},10);
}
else
{//显示全屏
outerScroll=$(window).scrollTop();
sLayoutStyle=jLayout.attr('style');
jLayout.removeAttr('style');
_jArea.height('100%');
setTimeout(fixFullHeight,100);
}
if(isMozilla)//临时修正Firefox 3.6源代码光标丢失问题
{
$('#'+idFixFFCursor).show().focus().hide();
setTimeout(_this.focus,1);
}
bFullscreen=!bFullscreen;
jContainer.toggleClass('xhe_Fullscreen');
$('html').toggleClass('xhe_Fullfix');
_jTools.find('[name=Fullscreen]').toggleClass('xheActive');
setTimeout(setOpts,300);
}
this.showMenu=function(menuitems,callback)
{
var jMenu=$('<div class="xheMenu"></div>'),arrItem=[];
$.each(menuitems,function(n,v){arrItem.push('<a href="javascript:void(0);" title="'+(v.t?v.t:v.s)+'" v="'+v.v+'">'+v.s+'</a>');});
jMenu.append(arrItem.join(''));
jMenu.click(function(ev){callback($(ev.target).closest('a').attr('v'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jMenu);
}
this.showColor=function(callback)
{
var jColor=$('<div class="xheColor"></div>'),arrItem=[],count=0;
$.each(itemColors,function(n,v)
{
if(count%7==0)arrItem.push((count>0?'</div>':'')+'<div>');
arrItem.push('<a href="javascript:void(0);" xhev="'+v+'" title="'+v+'" style="background:'+v+'"></a>');
count++;
});
arrItem.push('</div>');
jColor.append(arrItem.join(''));
jColor.click(function(ev){ev=ev.target;if(!$.nodeName(ev,'A'))return;callback($(ev).attr('xhev'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jColor);
}
this.showPastetext=function()
{
var jPastetext=$(htmlPastetext),jValue=$('#xhePastetextValue',jPastetext),jSave=$('#xheSave',jPastetext);
jSave.click(function(){
_this.loadBookmark();
var sValue=jValue.val();
if(sValue)_this.pasteText(sValue);
_this.hidePanel();
return false;
});
_this.showDialog(jPastetext);
}
this.showLink=function()
{
var jLink=$(htmlLink),jParent=_this.getParent('a'),jText=$('#xheLinkText',jLink),jUrl=$('#xheLinkUrl',jLink),jTarget=$('#xheLinkTarget',jLink),jSave=$('#xheSave',jLink),selHtml=_this.getSelect();
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'href'));
jTarget.attr('value',jParent.attr('target'));
}
else if(selHtml=='')jText.val(settings.defLinkText).closest('div').show();
if(settings.upLinkUrl)_this.uploadInit(jUrl,settings.upLinkUrl,settings.upLinkExt);
jSave.click(function(){
var url=jUrl.val();
_this.loadBookmark();
if(url==''||jParent.length==0)_this._exec('unlink');
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sTarget=jTarget.val(),sText=jText.val();
if(aUrl.length>1)
{//批量插入
_this._exec('unlink');//批量前删除当前链接并重新获取选择内容
selHtml=_this.getSelect();
var sTemplate='<a href="xhe_tmpurl"',sLink,arrLink=[];
if(sTarget!='')sTemplate+=' target="'+sTarget+'"';
sTemplate+='>xhe_tmptext</a>';
sText=(selHtml!=''?selHtml:(sText?sText:url));
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sLink=sTemplate;
sLink=sLink.replace('xhe_tmpurl',url[0]);
sLink=sLink.replace('xhe_tmptext',url[1]?url[1]:sText);
arrLink.push(sLink);
}
}
_this.pasteHTML(arrLink.join(' '));
}
else
{//单url模式
url=aUrl[0].split('||');
if(!sText)sText=url[0];
sText=url[1]?url[1]:(selHtml!='')?'':sText?sText:url[0];
if(jParent.length==0)
{
if(sText)_this.pasteHTML('<a href="#xhe_tmpurl">'+sText+'</a>');
else _this._exec('createlink','#xhe_tmpurl');
jParent=$('a[href$="#xhe_tmpurl"]',_doc);
}
else if(sText&&!isSafari)jParent.text(sText);//safari改写文本会导致光标丢失
xheAttr(jParent,'href',url[0]);
if(sTarget!='')jParent.attr('target',sTarget);
else jParent.removeAttr('target');
}
}
_this.hidePanel();
return false;
});
_this.showDialog(jLink);
}
this.showImg=function()
{
var jImg=$(htmlImg),jParent=_this.getParent('img'),jUrl=$('#xheImgUrl',jImg),jAlt=$('#xheImgAlt',jImg),jAlign=$('#xheImgAlign',jImg),jWidth=$('#xheImgWidth',jImg),jHeight=$('#xheImgHeight',jImg),jBorder=$('#xheImgBorder',jImg),jVspace=$('#xheImgVspace',jImg),jHspace=$('#xheImgHspace',jImg),jSave=$('#xheSave',jImg);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jAlt.val(jParent.attr('alt'));
jAlign.val(jParent.attr('align'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
jBorder.val(jParent.attr('border'));
var vspace=jParent.attr('vspace'),hspace=jParent.attr('hspace');
jVspace.val(vspace<=0?'':vspace);
jHspace.val(hspace<=0?'':hspace);
}
if(settings.upImgUrl)_this.uploadInit(jUrl,settings.upImgUrl,settings.upImgExt);
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sAlt=jAlt.val(),sAlign=jAlign.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sBorder=jBorder.val(),sVspace=jVspace.val(),sHspace=jHspace.val();;
if(aUrl.length>1)
{//批量插入
var sTemplate='<img src="xhe_tmpurl"',sImg,arrImg=[];
if(sAlt!='')sTemplate+=' alt="'+sAlt+'"';
if(sAlign!='')sTemplate+=' align="'+sAlign+'"';
if(sWidth!='')sTemplate+=' width="'+sWidth+'"';
if(sHeight!='')sTemplate+=' height="'+sHeight+'"';
if(sBorder!='')sTemplate+=' border="'+sBorder+'"';
if(sVspace!='')sTemplate+=' vspace="'+sVspace+'"';
if(sHspace!='')sTemplate+=' hspace="'+sHspace+'"';
sTemplate+=' />';
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sImg=sTemplate;
sImg=sImg.replace('xhe_tmpurl',url[0]);
if(url[1])sImg='<a href="'+url[1]+'" target="_blank">'+sImg+'</a>'
arrImg.push(sImg);
}
}
_this.pasteHTML(arrImg.join(' '));
}
else if(aUrl.length==1)
{//单URL模式
url=aUrl[0];
if(url!='')
{
url=url.split('||');
if(jParent.length==0)
{
_this.pasteHTML('<img src="'+url[0]+'#xhe_tmpurl" />');
jParent=$('img[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0])
if(sAlt!='')jParent.attr('alt',sAlt);
if(sAlign!='')jParent.attr('align',sAlign);
else jParent.removeAttr('align');
if(sWidth!='')jParent.attr('width',sWidth);
else jParent.removeAttr('width');
if(sHeight!='')jParent.attr('height',sHeight);
else jParent.removeAttr('height');
if(sBorder!='')jParent.attr('border',sBorder);
else jParent.removeAttr('border');
if(sVspace!='')jParent.attr('vspace',sVspace);
else jParent.removeAttr('vspace');
if(sHspace!='')jParent.attr('hspace',sHspace);
else jParent.removeAttr('hspace');
if(url[1])
{
var jLink=jParent.parent('a');
if(jLink.length==0)
{
jParent.wrap('<a></a>');
jLink=jParent.parent('a');
}
xheAttr(jLink,'href',url[1]);
jLink.attr('target','_blank');
}
}
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
_this.showDialog(jImg);
}
this.showEmbed=function(sType,sHtml,sMime,sClsID,sBaseAttrs,sUploadUrl,sUploadExt)
{
var jEmbed=$(sHtml),jParent=_this.getParent('embed[type="'+sMime+'"],embed[classid="'+sClsID+'"]'),jUrl=$('#xhe'+sType+'Url',jEmbed),jWidth=$('#xhe'+sType+'Width',jEmbed),jHeight=$('#xhe'+sType+'Height',jEmbed),jSave=$('#xheSave',jEmbed);
if(sUploadUrl)_this.uploadInit(jUrl,sUploadUrl,sUploadExt);
_this.showDialog(jEmbed);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
}
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var w=jWidth.val(),h=jHeight.val(),reg=/^[0-9]+$/;
if(!reg.test(w))w=412;if(!reg.test(h))h=300;
var sBaseCode='<embed type="'+sMime+'" classid="'+sClsID+'" src="xhe_tmpurl"'+sBaseAttrs;
var aUrl=url.split(' ');
if(aUrl.length>1)
{//批量插入
var sTemplate=sBaseCode+'',sEmbed,arrEmbed=[];
sTemplate+=' width="xhe_width" height="xhe_height" />';
for(var i in aUrl)
{
url=aUrl[i].split('||');
sEmbed=sTemplate;
sEmbed=sEmbed.replace('xhe_tmpurl',url[0])
sEmbed=sEmbed.replace('xhe_width',url[1]?url[1]:w)
sEmbed=sEmbed.replace('xhe_height',url[2]?url[2]:h)
if(url!='')arrEmbed.push(sEmbed);
}
_this.pasteHTML(arrEmbed.join(' '));
}
else if(aUrl.length==1)
{//单URL模式
url=aUrl[0].split('||');
if(jParent.length==0)
{
_this.pasteHTML(sBaseCode.replace('xhe_tmpurl',url[0]+'#xhe_tmpurl')+' />');
jParent=$('embed[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0]);
jParent.attr('width',url[1]?url[1]:w);
jParent.attr('height',url[2]?url[2]:h);
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
}
this.showEmot=function(group)
{
var jEmot=$('<div class="xheEmot"></div>');
group=group?group:(selEmotGroup?selEmotGroup:'default');
var arrEmot=arrEmots[group];
var sEmotPath=emotPath+group+'/',n=0,arrList=[],jList='';
var ew=arrEmot.width,eh=arrEmot.height,line=arrEmot.line,count=arrEmot.count,list=arrEmot.list;
if(count)
{
for(var i=1;i<=count;i++)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+i+'.gif);" emot="'+group+','+i+'" xhev=""> </a>');
if(n%line==0)arrList.push('<br />');
}
}
else
{
$.each(list,function(id,title)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+id+'.gif);" emot="'+group+','+id+'" title="'+title+'" xhev="'+title+'"> </a>');
if(n%line==0)arrList.push('<br />');
});
}
var w=line*(ew+12),h=Math.ceil(n/line)*(eh+12),mh=w*0.75;
if(h<=mh)mh='';
jList=$('<style>'+(mh?'.xheEmot div{width:'+(w+20)+'px;height:'+mh+'px;}':'')+'.xheEmot div a{width:'+ew+'px;height:'+eh+'px;}</style><div>'+arrList.join('')+'</div>').click(function(ev){ev=ev.target;var jA=$(ev);if(!$.nodeName(ev,'A'))return;_this.pasteHTML('<img emot="'+jA.attr('emot')+'" alt="'+jA.attr('xhev')+'">');_this.hidePanel();return false;}).mousedown(returnFalse);
jEmot.append(jList);
var gcount=0,arrGroup=['<ul>'],jGroup;//表情分类
$.each(arrEmots,function(g,v){
gcount++;
arrGroup.push('<li'+(group==g?' class="cur"':'')+'><a href="javascript:void(0);" group="'+g+'">'+v.name+'</a></li>');
});
if(gcount>1)
{
arrGroup.push('</ul><br style="clear:both;" />');
jGroup=$(arrGroup.join('')).click(function(ev){selEmotGroup=$(ev.target).attr('group');_this.exec('Emot');return false;}).mousedown(returnFalse);
jEmot.append(jGroup);
}
_this.showPanel(jEmot);
}
this.showTable=function()
{
var jTable=$(htmlTable),jRows=$('#xheTableRows',jTable),jColumns=$('#xheTableColumns',jTable),jHeaders=$('#xheTableHeaders',jTable),jWidth=$('#xheTableWidth',jTable),jHeight=$('#xheTableHeight',jTable),jBorder=$('#xheTableBorder',jTable),jCellSpacing=$('#xheTableCellSpacing',jTable),jCellPadding=$('#xheTableCellPadding',jTable),jAlign=$('#xheTableAlign',jTable),jCaption=$('#xheTableCaption',jTable),jSave=$('#xheSave',jTable);
jSave.click(function(){
_this.loadBookmark();
var sCaption=jCaption.val(),sBorder=jBorder.val(),sRows=jRows.val(),sCols=jColumns.val(),sHeaders=jHeaders.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sCellSpacing=jCellSpacing.val(),sCellPadding=jCellPadding.val(),sAlign=jAlign.val();
var i,j,htmlTable='<table'+(sBorder!=''?' border="'+sBorder+'"':'')+(sWidth!=''?' width="'+sWidth+'"':'')+(sHeight!=''?' width="'+sHeight+'"':'')+(sCellSpacing!=''?' cellspacing="'+sCellSpacing+'"':'')+(sCellPadding!=''?' cellpadding="'+sCellPadding+'"':'')+(sAlign!=''?' align="'+sAlign+'"':'')+'>';
if(sCaption!='')htmlTable+='<caption>'+sCaption+'</caption>';
if(sHeaders=='row'||sHeaders=='both')
{
htmlTable+='<tr>';
for(i=0;i<sCols;i++)htmlTable+='<th scope="col"> </th>';
htmlTable+='</tr>';
sRows--;
}
htmlTable+='<tbody>';
for(i=0;i<sRows;i++)
{
htmlTable+='<tr>';
for(j=0;j<sCols;j++)
{
if(j==0&&(sHeaders=='col'||sHeaders=='both'))htmlTable+='<th scope="row"> </th>';
else htmlTable+='<td> </td>';
}
htmlTable+='</tr>';
}
htmlTable+='</tbody></table>';
_this.pasteHTML(htmlTable);
_this.hidePanel();
return false;
});
_this.showDialog(jTable);
}
this.showAbout=function()
{
var jAbout=$(htmlAbout);
_this.showDialog(jAbout);
}
this.addShortcuts=function(key,cmd)
{
key=key.toLowerCase();
if(arrShortCuts[key]==undefined)arrShortCuts[key]=Array();
arrShortCuts[key].push(cmd);
}
this.delShortcuts=function(key){delete arrShortCuts[key];}
this.uploadInit=function(jText,toUrl,upext)
{
var jUpload=$('<span class="xheUpload"><input type="text" style="visibility:hidden;" tabindex="-1" /><input type="button" value="'+settings.upBtnText+'" class="xheBtn" tabindex="-1" /></span>'),jUpBtn=$('.xheBtn',jUpload);
var bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
jText.after(jUpload);jUpBtn.before(jText);
toUrl=toUrl.replace(/{editorRoot}/ig,editorRoot);
if(toUrl.substr(0,1)=='!')//自定义上传管理页
{
jUpBtn.click(function(){
bShowPanel=false;//防止按钮面板被关闭
_this.showIframeModal('上传文件',toUrl.substr(1),setUploadMsg,null,null,function(){bShowPanel=true;});
});
}
else
{//系统默认ajax上传
jUpload.append('<input type="file"'+(upMultiple>1?' multiple=""':'')+' class="xheFile" size="13" name="'+uploadInputname+'" tabindex="-1" />');
var jFile=$('.xheFile',jUpload),arrMsg;
jFile.change(function(){arrMsg=[];_this.startUpload(jFile[0],toUrl,upext,setUploadMsg);});
setTimeout(function(){//拖放上传
jText.closest('.xheDialog').bind('dragenter dragover',returnFalse).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(bHtml5Upload&&dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0)_this.startUpload(fileList,toUrl,upext,setUploadMsg);
return false;
});
},10);
}
function setUploadMsg(arrMsg)
{
if(is(arrMsg,'string'))arrMsg=[arrMsg];//允许单URL传递
var bImmediate=false,i,count=arrMsg.length,msg,url,arrUrl=[],onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用户上传回调
for(i=0;i<count;i++)
{
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!'){bImmediate=true;url=url.substr(1);}
arrUrl.push(url);
}
jText.val(arrUrl.join(' '));
if(bImmediate)jText.closest('.xheDialog').find('#xheSave').click();
}
}
this.startUpload=function(fromFiles,toUrl,limitExt,onUploadComplete)
{
var arrMsg=[],bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
var upload,fileList,filename,jUploadTip=$('<div style="padding:22px 0;text-align:center;line-height:30px;">文件上传中,请稍候……<br /></div>'),sLoading='<img src="'+skinPath+'img/loading.gif">';
if(!bHtml5Upload||(fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0])))
{
if(!checkFileExt(fromFiles.value,limitExt))return;
jUploadTip.append(sLoading);
upload=new _this.html4Upload(fromFiles,toUrl,onUploadCallback);
}
else
{
if(!fileList)fileList=fromFiles;//拖放文件列表
var i,len=fileList.length;
if(len>upMultiple){alert('请不要一次上传超过'+upMultiple+'个文件');return;}
for(i=0;i<len;i++)if(!checkFileExt(fileList[i].fileName,limitExt))return;
var jProgress=$('<div class="xheProgress"><div><span>0%</span></div></div>');
jUploadTip.append(jProgress);
upload=new _this.html5Upload(uploadInputname,fileList,toUrl,onUploadCallback,function(ev){
if(ev.loaded>=0)
{
var sPercent=Math.round((ev.loaded * 100) / ev.total)+'%';
$('div',jProgress).css('width',sPercent);
$('span',jProgress).text(sPercent+' ( '+formatBytes(ev.loaded)+' / '+formatBytes(ev.total)+' )');
}
else jProgress.replaceWith(sLoading);//不支持进度
});
}
var panelState=bShowPanel;
if(panelState)bShowPanel=false;//防止面板被关闭
_this.showModal('文件上传中(Esc取消上传)',jUploadTip,320,150,function(){bShowPanel=panelState;upload.remove();});
upload.start();
function onUploadCallback(sText,bFinish)
{
var data=Object,bOK=false;
try{data=eval('('+sText+')');}catch(ex){};
if(data.err==undefined||data.msg==undefined)alert(toUrl+' 上传接口发生错误!\r\n\r\n返回的错误内容为: \r\n\r\n'+sText);
else
{
if(data.err)alert(data.err);
else
{
arrMsg.push(data.msg);
bOK=true;//继续下一个文件上传
}
}
if(!bOK||bFinish)_this.removeModal();
if(bFinish&&bOK)onUploadComplete(arrMsg);//全部上传完成
return bOK;
}
}
this.html4Upload=function(fromfile,toUrl,callback)
{
var uid = new Date().getTime(),idIO='jUploadFrame'+uid,_this=this;
var jIO=$('<iframe name="'+idIO+'" class="xheHideArea" />').appendTo('body');
var jForm=$('<form action="'+toUrl+'" target="'+idIO+'" method="post" enctype="multipart/form-data" class="xheHideArea"></form>').appendTo('body');
var jOldFile = $(fromfile),jNewFile = jOldFile.clone().attr('disabled','true');
jOldFile.before(jNewFile).appendTo(jForm);
this.remove=function()
{
if(_this!=null)
{
jNewFile.before(jOldFile).remove();
jIO.remove();jForm.remove();
_this=null;
}
}
this.onLoad=function(){callback($(jIO[0].contentWindow.document.body).text(),true);}
this.start=function(){jForm.submit();jIO.load(_this.onLoad);}
return this;
}
this.html5Upload=function(inputname,fromFiles,toUrl,callback,onProgress)
{
var xhr,i=0,count=fromFiles.length,allLoaded=0,allSize=0,_this=this;
for(var j=0;j<count;j++)allSize+=fromFiles[j].fileSize;
this.remove=function(){if(xhr){xhr.abort();xhr=null;}}
this.uploadNext=function(sText)
{
if(sText)//当前文件上传完成
{
allLoaded+=fromFiles[i-1].fileSize;
returnProgress(0);
}
if((!sText||(sText&&callback(sText,i==count)==true))&&i<count)postFile(fromFiles[i++],toUrl,_this.uploadNext,function(loaded){returnProgress(loaded);});
}
this.start=function(){_this.uploadNext();}
function postFile(fromfile,toUrl,callback,onProgress)
{
xhr = new XMLHttpRequest(),upload=xhr.upload;
xhr.onreadystatechange=function(){if(xhr.readyState==4)callback(xhr.responseText);};
if(upload)upload.onprogress=function(ev){onProgress(ev.loaded);};
else onProgress(-1);//不支持进度
xhr.open("POST", toUrl);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Content-Disposition', 'attachment; name="'+inputname+'"; filename="'+fromfile.fileName+'"');
if(xhr.sendAsBinary)xhr.sendAsBinary(fromfile.getAsBinary());
else xhr.send(fromfile);
}
function returnProgress(loaded){if(onProgress)onProgress({'loaded':allLoaded+loaded,'total':allSize});}
}
this.showIframeModal=function(title,ifmurl,callback,w,h,onRemove)
{
var jContent=$('<iframe frameborder="0" src="'+ifmurl.replace(/{editorRoot}/ig,editorRoot)+'" style="width:100%;height:100%;display:none;" /><div class="xheModalIfmWait"></div>'),jIframe=$(jContent[0]),jWait=$(jContent[1]);
_this.showModal(title,jContent,w,h,onRemove);
jIframe.load(function(){
var modalWin=jIframe[0].contentWindow,jModalDoc=$(modalWin.document);
modalWin.callback=function(v){_this.removeModal();callback(v);};
modalWin.unloadme=_this.removeModal;
jModalDoc.keydown(_this.checkEsc);
jIframe.show();jWait.remove();
});
}
this.showModal=function(title,content,w,h,onRemove)
{
if(bShowModal)return false;//只能弹出一个模式窗口
layerShadow=settings.layerShadow;
w=w?w:settings.modalWidth;h=h?h:settings.modalHeight;
jModal=$('<div class="xheModal" style="width:'+(w-1)+'px;height:'+h+'px;margin-left:-'+Math.ceil(w/2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+Math.ceil(h/2)+'px')+'">'+(settings.modalTitle?'<div class="xheModalTitle"><span class="xheModalClose" title="关闭 (Esc)"></span>'+title+'</div>':'')+'<div class="xheModalContent"></div></div>').appendTo('body');
jOverlay=$('<div class="xheModalOverlay"></div>').appendTo('body');
if(layerShadow>0)jModalShadow=$('<div class="xheModalShadow" style="width:'+jModal.outerWidth()+'px;height:'+jModal.outerHeight()+'px;margin-left:-'+(Math.ceil(w/2)-layerShadow-2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+(Math.ceil(h/2)-layerShadow-2)+'px')+'"></div>').appendTo('body');
$('.xheModalContent',jModal).css('height',h-(settings.modalTitle?$('.xheModalTitle').outerHeight():0)).html(content);
if(isIE&&browerVer==6.0)jHideSelect=$('select:visible').css('visibility','hidden');//隐藏覆盖的select
$('.xheModalClose',jModal).click(_this.removeModal);
jOverlay.show();if(layerShadow>0)jModalShadow.show();jModal.show();
bShowModal=true;
onModalRemove=onRemove;
}
this.removeModal=function(){if(jHideSelect)jHideSelect.css('visibility','visible');jModal.html('').remove();if(layerShadow>0)jModalShadow.remove();jOverlay.remove();if(onModalRemove)onModalRemove();bShowModal=false;};
this.showDialog=function(content)
{
var jDialog=$('<div class="xheDialog"></div>'),jContent=$(content),jSave=$('#xheSave',jContent);
if(jSave.length==1)
{
jContent.find('input[type=text],select').keypress(function(ev){if(ev.which==13){jSave.click();return false;}});
jContent.find('textarea').keydown(function(ev){if(ev.ctrlKey&&ev.which==13){jSave.click();return false;}});
jSave.after(' <input type="button" id="xheCancel" value="取消" />');
$('#xheCancel',jContent).click(_this.hidePanel);
if(!settings.clickCancelDialog)
{
bClickCancel=false;//关闭点击隐藏
var jFixCancel=$('<div class="xheFixCancel"></div>').appendTo('body').mousedown(returnFalse);
var xy=_jArea.offset();
jFixCancel.css({'left':xy.left,'top':xy.top,width:_jArea.outerWidth(),height:_jArea.outerHeight()})
}
jDialog.mousedown(function(){bDisableHoverExec=true;})//点击对话框禁止悬停执行
}
jDialog.append(jContent);
_this.showPanel(jDialog);
if(!isIE)setTimeout(function(){jDialog.find('input[type=text],textarea').filter(':visible').filter(function(){return $(this).css('visibility')!='hidden';}).eq(0).focus();},10);//定位首个可见输入表单项,延迟解决opera无法设置焦点
}
this.showPanel=function(content)
{
if(!ev.target)return false;
_jPanel.html('').append(content).css('left',-999).css('top',-999);
_jPanelButton=$(ev.target).closest('a').addClass('xheActive');
var xy=_jPanelButton.offset();
var x=xy.left,y=xy.top;y+=_jPanelButton.outerHeight()-1;
_jCntLine.css({'left':x+1,'top':y,'width':_jPanelButton.width()}).show();
if((x+_jPanel.outerWidth())>document.body.clientWidth)x-=(_jPanel.outerWidth()-_jPanelButton.outerWidth());//向左显示面板
var layerShadow=settings.layerShadow;
if(layerShadow>0)_jShadow.css({'left':x+layerShadow,'top':y+layerShadow,'width':_jPanel.outerWidth(),'height':_jPanel.outerHeight()}).show();
_jPanel.css({'left':x,'top':y}).show();
bQuickHoverExec=bShowPanel=true;
}
this.hidePanel=function(){if(bShowPanel){_jPanelButton.removeClass('xheActive');_jShadow.hide();_jCntLine.hide();_jPanel.hide();bShowPanel=false;if(!bClickCancel){$('.xheFixCancel').remove();bClickCancel=true;};bQuickHoverExec=bDisableHoverExec=false;lastAngle=null;}}
this.exec=function(cmd)
{
_this.hidePanel();
_this.saveBookmark();
var tool=arrTools[cmd];
if(!tool)return false;//无效命令
if(ev==null)//非鼠标点击
{
ev={};
var btn=_jTools.find('.xheButton[name='+cmd+']');
if(btn.length==1)ev.target=btn;//设置当前事件焦点
}
if(tool.e)tool.e.call(_this)//插件事件
else//内置工具
{
cmd=cmd.toLowerCase();
switch(cmd)
{
case 'cut':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的浏览器安全设置不允许使用剪切操作,请使用键盘快捷键(Ctrl + X)来完成');};
break;
case 'copy':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的浏览器安全设置不允许使用复制操作,请使用键盘快捷键(Ctrl + C)来完成');}
break;
case 'paste':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的浏览器安全设置不允许使用粘贴操作,请使用键盘快捷键(Ctrl + V)来完成');}
break;
case 'pastetext':
if(window.clipboardData)_this.pasteText(window.clipboardData.getData('Text', true));
else _this.showPastetext();
break;
case 'blocktag':
var menuBlocktag=[];
$.each(arrBlocktag,function(n,v){menuBlocktag.push({s:'<'+v.n+'>'+v.t+'</'+v.n+'>',v:'<'+v.n+'>',t:v.t});});
_this.showMenu(menuBlocktag,function(v){_this._exec('formatblock',v);});
break;
case 'fontface':
var menuFontname=[];
$.each(arrFontname,function(n,v){v.c=v.c?v.c:v.n;menuFontname.push({s:'<span style="font-family:'+v.c+'">'+v.n+'</span>',v:v.c,t:v.n});});
_this.showMenu(menuFontname,function(v){_this._exec('fontname',v);});
break;
case 'fontsize':
var menuFontsize=[];
$.each(arrFontsize,function(n,v){menuFontsize.push({s:'<span style="font-size:'+v.s+';">'+v.t+'('+v.s+')</span>',v:n+1,t:v.t});});
_this.showMenu(menuFontsize,function(v){_this._exec('fontsize',v);});
break;
case 'fontcolor':
_this.showColor(function(v){_this._exec('forecolor',v);});
break;
case 'backcolor':
_this.showColor(function(v){if(isIE)_this._exec('backcolor',v);else{setCSS(true);_this._exec('hilitecolor',v);setCSS(false);}});
break;
case 'align':
_this.showMenu(menuAlign,function(v){_this._exec(v);});
break;
case 'list':
_this.showMenu(menuList,function(v){_this._exec(v);});
break;
case 'link':
_this.showLink();
break;
case 'img':
_this.showImg();
break;
case 'flash':
_this.showEmbed('Flash',htmlFlash,'application/x-shockwave-flash','clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000',' wmode="opaque" quality="high" menu="false" play="true" loop="true" allowfullscreen="true"',settings.upFlashUrl,settings.upFlashExt);
break;
case 'media':
_this.showEmbed('Media',htmlMedia,'application/x-mplayer2','clsid:6bf52a52-394a-11d3-b153-00c04f79faa6',' enablecontextmenu="false" autostart="false"',settings.upMediaUrl,settings.upMediaExt);
break;
case 'emot':
_this.showEmot();
break;
case 'table':
_this.showTable();
break;
case 'source':
_this.toggleSource();
break;
case 'preview':
_this.showPreview();
break;
case 'print':
_win.print();
break;
case 'fullscreen':
_this.toggleFullscreen();
break;
case 'about':
_this.showAbout();
break;
default:
_this._exec(cmd);
break;
}
}
ev=null;
}
this._exec=function(cmd,param,noFocus)
{
if(!noFocus)_this.focus();
var state;
if(param!=undefined)state=_doc.execCommand(cmd,false,param);
else state=_doc.execCommand(cmd,false,null);
return state;
}
function checkDblClick(ev)
{
var target=ev.target,tool=arrDbClick[target.tagName.toLowerCase()];
if(tool)
{
if(tool=='Embed')//自动识别Flash和多媒体
{
var arrEmbed={'application/x-shockwave-flash':'Flash','application/x-mplayer2':'Media'};
tool=arrEmbed[target.type.toLowerCase()];
}
_this.exec(tool);
}
}
function checkEsc(ev)
{
if(ev.which==27)
{
if(bShowModal)_this.removeModal();
else if(bShowPanel)_this.hidePanel();
return false;
}
}
function loadReset(){setTimeout(_this.setSource,10);}
function saveResult(){_this.getSource();};
function cleanPaste(ev){
if(bSource||bCleanPaste)return true;
bCleanPaste=true;//解决IE右键粘贴重复产生paste的问题
_this.saveBookmark();
var jDiv=$('<div style="position:absolute;left:-1000px;top:'+_jWin.scrollTop()+'px;overflow:hidden;width:1px;height:1px;" />',_doc),div=jDiv[0],sel=_this.getSel(),rng=_this.getRng();
$(_doc.body).append(jDiv);
if(isIE){
rng.moveToElementText(div);
rng.execCommand('Paste');
ev.preventDefault();
}
else{
rng.selectNodeContents(div);
sel.removeAllRanges();
sel.addRange(rng);
}
setTimeout(function(){
var sPaste;
if(settings.forcePasteText===true)sPaste=jDiv.text();
else{
sPaste=div.innerHTML;
sPaste=_this.cleanHTML(sPaste);
sPaste=_this.formatXHTML(sPaste);
sPaste=_this.cleanWord(sPaste);
}
jDiv.remove();
_this.loadBookmark();
_this.pasteHTML(sPaste);
bCleanPaste=false;
},0);
}
function setCSS(css)
{
try{_this._exec('styleWithCSS',css,true);}
catch(e)
{try{_this._exec('useCSS',!css,true);}catch(e){}}
}
function setOpts()
{
if(bInit&&!bSource)
{
setCSS(false);
try{_this._exec('enableObjectResizing',true,true);}catch(e){}
//try{_this._exec('enableInlineTableEditing',false,true);}catch(e){}
if(isIE)try{_this._exec('BackgroundImageCache',true,true);}catch(e){}
}
}
function forcePtag(ev)
{
if(bSource||ev.which!=13||ev.shiftKey||ev.ctrlKey||ev.altKey)return true;
var pNode=_this.getParent('p,h1,h2,h3,h4,h5,h6,pre,address,div,li');
if(pNode.is('li'))return true;
if(settings.forcePtag){if(pNode.length==0)_this._exec('formatblock','<p>');}
else
{
_this.pasteHTML('<br />');
if(isIE&&pNode.length>0&&_this.getRng().parentElement().childNodes.length==2)_this.pasteHTML('<br />');
return false;
}
}
function fixFullHeight()
{
if(!isMozilla&&!isSafari)
{
if(bFullscreen)_jArea.height('100%').css('height',_jArea.outerHeight()-_jTools.outerHeight());
if(isIE)_jTools.hide().show();
}
}
function fixAppleSel(e)
{
e=e.target;
if(e.tagName.match(/(img|embed)/i))
{
var sel=_this.getSel(),rng=_this.getRng();
rng.selectNode(e);
sel.removeAllRanges();
sel.addRange(rng);
}
}
function xheAttr(jObj,n,v)
{
if(!n)return false;
var kn='_xhe_'+n;
if(v)//设置属性
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
jObj.attr(n,urlBase?getLocalUrl(v,'abs',urlBase):v).removeAttr(kn).attr(kn,v);
}
return jObj.attr(kn)||jObj.attr(n);
}
function clickCancelPanel(){if(bClickCancel)_this.hidePanel();}
function checkShortcuts(event)
{
if(bSource)return true;
var code=event.which,special=specialKeys[code],sChar=special?special:String.fromCharCode(code).toLowerCase();
sKey='';
sKey+=event.ctrlKey?'ctrl+':'';sKey+=event.altKey?'alt+':'';sKey+=event.shiftKey?'shift+':'';sKey+=sChar;
var cmd=arrShortCuts[sKey],c;
for(c in cmd)
{
c=cmd[c];
if($.isFunction(c)){if(c.call(_this)===false)return false;}
else{_this.exec(c);return false;}//按钮独占快捷键
}
}
function is(o,t)
{
var n = typeof(o);
if (!t)return n != 'undefined';
if (t == 'array' && (o.hasOwnProperty && o instanceof Array))return true;
return n == t;
}
function getLocalUrl(url,urlType,urlBase)//绝对地址:abs,根地址:root,相对地址:rel
{
var baseUrl=urlBase?$('<a href="'+urlBase+'" />')[0]:location,protocol=baseUrl.protocol,host=baseUrl.hostname,port=baseUrl.port,path=baseUrl.pathname.replace(/\\/g,'/').replace(/[^\/]+$/i,'');
port=(port=='')?'80':port;
url=$.trim(url);
if(urlType!='abs')url=url.replace(new RegExp(protocol+'\\/\\/'+host.replace(/\./g,'\\.')+'(?::'+port+')'+(port=='80'?'?':'')+'(\/|$)','i'),'/');
if(urlType=='rel')url=url.replace(new RegExp('^'+path.replace(/([\/\.\+\[\]\(\)])/g,'\\$1'),'i'),'');
if(urlType!='rel')
{
if(!url.match(/^((https?|file):\/\/|\/)/i))url=path+url;
if(url.charAt(0)=='/')//处理..
{
var arrPath=[],arrFolder = url.split('/'),folder,i,l=arrFolder.length;
for(i=0;i<l;i++)
{
folder=arrFolder[i];
if(folder=='..')arrPath.pop();
else if(folder!==''&&folder!='.')arrPath.push(folder);
}
if(arrFolder[l-1]=='')arrPath.push('');
url='/'+arrPath.join('/');
}
}
if(urlType=='abs')if(!url.match(/(https?|file):\/\//i))url=protocol+'//'+location.host+url;
return url;
}
function checkFileExt(filename,limitExt)
{
if(limitExt=='*'||filename.match(new RegExp('\.('+limitExt.replace(/,/g,'|')+')$','i')))return true;
else
{
alert('上传文件扩展名必需为: '+limitExt);
return false;
}
}
function formatBytes(bytes)
{
var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+s[e];
}
function returnFalse(){return false;}
}
$(function(){
$.fn.oldVal=$.fn.val;
$.fn.val=function(value)
{
var _this=this,editor;
if(value===undefined)if(this[0]&&(editor=this[0].xheditor))return editor.getSource();else return _this.oldVal(value);//读
return this.each(function(){if(editor=this.xheditor)editor.setSource(value);else _this.oldVal(value);});//写
}
$('textarea').each(function(){
var self=$(this),xhClass=self.attr('class').match(/(?:^|\s)xheditor(?:\-(m?full|simple|mini))?(?:\s|$)/i);
if(xhClass)self.xheditor(xhClass[1]?{tools:xhClass[1]}:null);
});
});
})(jQuery); | JavaScript |
/*!
* xhEditor - WYSIWYG XHTML Editor
* @requires jQuery v1.4.2
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 1.1.1 (build 101002)
*/
(function($){
if($.xheditor)return false;//防止JS重複加載
$.fn.xheditor=function(options)
{
var arrSuccess=[];
this.each(function(){
if(!$.nodeName(this,'TEXTAREA'))return;
if(options===false)//卸載
{
if(this.xheditor)
{
this.xheditor.remove();
this.xheditor=null;
}
}
else//初始化
{
if(!this.xheditor)
{
var tOptions=/({.*})/.exec($(this).attr('class'));
if(tOptions)
{
try{tOptions=eval('('+tOptions[1]+')');}catch(ex){};
options=$.extend({},tOptions,options );
}
var editor=new $.xheditor(this,options);
if(editor.init())
{
this.xheditor=editor;
arrSuccess.push(editor);
}
else editor=null;
}
else arrSuccess.push(this.xheditor);
}
});
if(arrSuccess.length==0)arrSuccess=false;
if(arrSuccess.length==1)arrSuccess=arrSuccess[0];
return arrSuccess;
}
var xCount=0,browerVer=$.browser.version,isIE=$.browser.msie,isMozilla=$.browser.mozilla,isSafari=$.browser.safari,isOpera=$.browser.opera,bShowPanel=false,bClickCancel=true,bShowModal=false,bCheckEscInit=false;
var _jPanel,_jShadow,_jCntLine,_jPanelButton;
var jModal,jModalShadow,layerShadow,jOverlay,jHideSelect,onModalRemove;
var editorRoot;
$('script[src*=xheditor]').each(function(){
var s=this.src;
if(s.match(/xheditor[^\/]*\.js/i)){editorRoot=s.replace(/[\?#].*$/, '').replace(/(^|[\/\\])[^\/]*$/, '$1');return false;}
});
var specialKeys={ 27: 'esc', 9: 'tab', 32:'space', 13: 'enter', 8:'backspace', 145: 'scroll',
20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',
35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down',
112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12' };
var itemColors=['#FFFFFF','#CCCCCC','#C0C0C0','#999999','#666666','#333333','#000000','#FFCCCC','#FF6666','#FF0000','#CC0000','#990000','#660000','#330000','#FFCC99','#FF9966','#FF9900','#FF6600','#CC6600','#993300','#663300','#FFFF99','#FFFF66','#FFCC66','#FFCC33','#CC9933','#996633','#663333','#FFFFCC','#FFFF33','#FFFF00','#FFCC00','#999900','#666600','#333300','#99FF99','#66FF99','#33FF33','#33CC00','#009900','#006600','#003300','#99FFFF','#33FFFF','#66CCCC','#00CCCC','#339999','#336666','#003333','#CCFFFF','#66FFFF','#33CCFF','#3366FF','#3333FF','#000099','#000066','#CCCCFF','#9999FF','#6666CC','#6633FF','#6600CC','#333399','#330099','#FFCCFF','#FF99FF','#CC66CC','#CC33CC','#993399','#663366','#330033'];
var arrBlocktag=[{n:'p',t:'普通段落'},{n:'h1',t:'標題1'},{n:'h2',t:'標題2'},{n:'h3',t:'標題3'},{n:'h4',t:'標題4'},{n:'h5',t:'標題5'},{n:'h6',t:'標題6'},{n:'pre',t:'已編排格式'},{n:'address',t:'地址'}];
var arrFontname=[{n:'新細明體',c:'PMingLiu'},{n:'細明體',c:'mingliu'},{n:'標楷體',c:'DFKai-SB'},{n:'微軟正黑體',c:'Microsoft JhengHei'},{n:'Arial'},{n:'Arial Narrow'},{n:'Arial Black'},{n:'Comic Sans MS'},{n:'Courier New'},{n:'System'},{n:'Times New Roman'},{n:'Tahoma'},{n:'Verdana'}];
var arrFontsize=[{n:'xx-small',wkn:'x-small',s:'8pt',t:'極小'},{n:'x-small',wkn:'small',s:'10pt',t:'特小'},{n:'small',wkn:'medium',s:'12pt',t:'小'},{n:'medium',wkn:'large',s:'14pt',t:'中'},{n:'large',wkn:'x-large',s:'18pt',t:'大'},{n:'x-large',wkn:'xx-large',s:'24pt',t:'特大'},{n:'xx-large',wkn:'-webkit-xxx-large',s:'36pt',t:'極大'}];
var menuAlign=[{s:'靠左對齊',v:'justifyleft'},{s:'置中',v:'justifycenter'},{s:'靠右對齊',v:'justifyright'},{s:'左右對齊',v:'justifyfull'}],menuList=[{s:'數字列表',v:'insertOrderedList'},{s:'符號列表',v:'insertUnorderedList'}];
var htmlPastetext='<div>使用鍵盤快捷鍵(Ctrl+V)把內容貼上到方框裡,按 確定</div><div><textarea id="xhePastetextValue" wrap="soft" spellcheck="false" style="width:300px;height:100px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlLink='<div>鏈接地址: <input type="text" id="xheLinkUrl" value="http://" class="xheText" /></div><div>打開方式: <select id="xheLinkTarget"><option selected="selected" value="">預設</option><option value="_blank">新窗口</option><option value="_self">當前窗口</option><option value="_parent">父窗口</option></select></div><div style="display:none">鏈接文字: <input type="text" id="xheLinkText" value="" class="xheText" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlImg='<div>圖片文件: <input type="text" id="xheImgUrl" value="http://" class="xheText" /></div><div>替換文本: <input type="text" id="xheImgAlt" /></div><div>對齊方式: <select id="xheImgAlign"><option selected="selected" value="">預設</option><option value="left">靠左對齊</option><option value="right">靠右對齊</option><option value="top">頂端</option><option value="middle">置中</option><option value="baseline">基線</option><option value="bottom">底邊</option></select></div><div>寬度高度: <input type="text" id="xheImgWidth" style="width:40px;" /> x <input type="text" id="xheImgHeight" style="width:40px;" /></div><div>邊框大小: <input type="text" id="xheImgBorder" style="width:40px;" /></div><div>水平間距: <input type="text" id="xheImgHspace" style="width:40px;" /> 垂直間距: <input type="text" id="xheImgVspace" style="width:40px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlFlash='<div>動畫文件: <input type="text" id="xheFlashUrl" value="http://" class="xheText" /></div><div>寬度高度: <input type="text" id="xheFlashWidth" style="width:40px;" value="480" /> x <input type="text" id="xheFlashHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlMedia='<div>媒體文件: <input type="text" id="xheMediaUrl" value="http://" class="xheText" /></div><div>寬度高度: <input type="text" id="xheMediaWidth" style="width:40px;" value="480" /> x <input type="text" id="xheMediaHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlTable='<div>行數列數: <input type="text" id="xheTableRows" style="width:40px;" value="3" /> x <input type="text" id="xheTableColumns" style="width:40px;" value="2" /></div><div>標題單元: <select id="xheTableHeaders"><option selected="selected" value="">無</option><option value="row">第一行</option><option value="col">第一列</option><option value="both">第一行和第一列</option></select></div><div>寬度高度: <input type="text" id="xheTableWidth" style="width:40px;" value="200" /> x <input type="text" id="xheTableHeight" style="width:40px;" value="" /></div><div>邊框大小: <input type="text" id="xheTableBorder" style="width:40px;" value="1" /></div><div>表格間距: <input type="text" id="xheTableCellSpacing" style="width:40px;" value="1" /> 表格填充: <input type="text" id="xheTableCellPadding" style="width:40px;" value="1" /></div><div>對齊方式: <select id="xheTableAlign"><option selected="selected" value="">預設</option><option value="left">靠左對齊</option><option value="center">置中</option><option value="right">靠右對齊</option></select></div><div>表格標題: <input type="text" id="xheTableCaption" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="確定" /></div>';
var htmlAbout='<div style="font:12px Arial;width:245px;word-wrap:break-word;word-break:break-all;"><p><span style="font-size:20px;color:#1997DF;">xhEditor</span><br />v1.1.1 (build 101002)</p><p>xhEditor是基於jQuery開發的跨平台輕量XHTML編輯器,基於<a href="http://www.gnu.org/licenses/lgpl.html" target="_blank">LGPL</a>開源協議發佈。</p><p>Copyright c <a href="http://xheditor.com/" target="_blank">xhEditor.com</a>. All rights reserved.</p></div>';
var itemEmots={'default':{name:'預設',width:24,height:24,line:7,list:{'smile':'微笑','tongue':'吐舌頭','titter':'偷笑','laugh':'大笑','sad':'難過','wronged':'委屈','fastcry':'快哭了','cry':'哭','wail':'大哭','mad':'生氣','knock':'敲打','curse':'罵人','crazy':'抓狂','angry':'發火','ohmy':'驚訝','awkward':'尷尬','panic':'驚恐','shy':'害羞','cute':'可憐','envy':'羨慕','proud':'得意','struggle':'奮鬥','quiet':'安靜','shutup':'閉嘴','doubt':'疑問','despise':'鄙視','sleep':'睡覺','bye':'再見'}}};
var arrTools={Cut:{t:'剪下 (Ctrl+X)'},Copy:{t:'複製 (Ctrl+C)'},Paste:{t:'貼上 (Ctrl+V)'},Pastetext:{t:'貼上文本',h:isIE?0:1},Blocktag:{t:'段落標籤',h:1},Fontface:{t:'字型',h:1},FontSize:{t:'字型大小',h:1},Bold:{t:'粗體 (Ctrl+B)',s:'Ctrl+B'},Italic:{t:'斜體 (Ctrl+I)',s:'Ctrl+I'},Underline:{t:'底線 (Ctrl+U)',s:'Ctrl+U'},Strikethrough:{t:'刪除線 (Ctrl+S)',s:'Ctrl+S'},FontColor:{t:'字型顏色',h:1},BackColor:{t:'背景顏色',h:1},SelectAll:{t:'全選 (Ctrl+A)'},Removeformat:{t:'刪除文字格式'},Align:{t:'對齊',h:1},List:{t:'列表',h:1},Outdent:{t:'減少縮排 (Shift+Tab)',s:'Shift+Tab'},Indent:{t:'增加縮排 (Tab)',s:'Tab'},Link:{t:'超連結 (Ctrl+K)',s:'Ctrl+K',h:1},Unlink:{t:'取消超連結'},Img:{t:'圖片',h:1},Flash:{t:'Flash動畫',h:1},Media:{t:'多媒體文件',h:1},Emot:{t:'表情',s:'ctrl+e',h:1},Table:{t:'表格',h:1},Source:{t:'原始碼'},Preview:{t:'預覽'},Print:{t:'打印 (Ctrl+P)',s:'Ctrl+P'},Fullscreen:{t:'全螢幕編輯 (Esc)',s:'Esc'},About:{t:'關於 xhEditor'}};
var toolsThemes={
mini:'Bold,Italic,Underline,Strikethrough,|,Align,List,|,Link,Img',
simple:'Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,|,Align,List,Outdent,Indent,|,Link,Img,Emot',
full:'Cut,Copy,Paste,Pastetext,|,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,SelectAll,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Img,Flash,Media,Emot,Table,|,Source,Preview,Print,Fullscreen'};
toolsThemes.mfull=toolsThemes.full.replace(/\|(,Align)/i,'/$1');
var arrDbClick={'a':'Link','img':'Img','embed':'Embed'},uploadInputname='filedata';
$.xheditor=function(textarea,options)
{
var defaults={skin:'default',tools:'full',clickCancelDialog:true,linkTag:false,internalScript:false,inlineScript:false,internalStyle:true,inlineStyle:true,showBlocktag:false,forcePtag:true,upLinkExt:"zip,rar,txt",upImgExt:"jpg,jpeg,gif,png",upFlashExt:"swf",upMediaExt:"wmv,avi,wma,mp3,mid",modalWidth:350,modalHeight:220,modalTitle:true,defLinkText:'點擊打開鏈接',layerShadow:3,emotMark:false,upBtnText:'上傳',wordDeepClean:true,hoverExecDelay:100,html5Upload:true,upMultiple:99};
var _this=this,_text=textarea,_jText=$(_text),_jForm=_jText.closest('form'),_jTools,_jArea,_win,_jWin,_doc,_jDoc;
var bookmark;
var bInit=false,bSource=false,bFullscreen=false,bCleanPaste=false,outerScroll,bShowBlocktag=false,sLayoutStyle='',ev=null,timer,bDisableHoverExec=false,bQuickHoverExec=false;
var lastPoint=null,lastAngle=null;//鼠標懸停顯示
var editorHeight=0;
var settings=_this.settings=$.extend({},defaults,options );
var plugins=settings.plugins,strPlugins=[];
if(plugins)
{
arrTools=$.extend({},arrTools,plugins);
$.each(plugins,function(n){strPlugins.push(n);});
strPlugins=strPlugins.join(',');
}
if(settings.tools.match(/^\s*(m?full|simple|mini)\s*$/i))
{
var toolsTheme=toolsThemes[$.trim(settings.tools)];
settings.tools=(settings.tools.match(/m?full/i)&&plugins)?toolsTheme.replace('Table','Table,'+strPlugins):toolsTheme;//插件接在full的Table後面
}
if(!settings.tools.match(/(^|,)\s*About\s*(,|$)/i))settings.tools+=',About';
settings.tools=settings.tools.split(',');
if(settings.editorRoot)editorRoot=settings.editorRoot;
editorRoot=getLocalUrl(editorRoot,'abs');
//基本控件名
var idCSS='xheCSS_'+settings.skin,idContainer='xhe'+xCount+'_container',idTools='xhe'+xCount+'_Tool',idIframeArea='xhe'+xCount+'_iframearea',idIframe='xhe'+xCount+'_iframe',idFixFFCursor='xhe'+xCount+'_fixffcursor';
var headHTML='',bodyClass='',skinPath=editorRoot+'xheditor_skin/'+settings.skin+'/',arrEmots=itemEmots,urlType=settings.urlType,urlBase=settings.urlBase,emotPath=settings.emotPath,emotPath=emotPath?emotPath:editorRoot+'xheditor_emot/',selEmotGroup='';
arrEmots=$.extend({},arrEmots,settings.emots);
emotPath=getLocalUrl(emotPath,'rel',urlBase?urlBase:null);//返回最短表情路徑
bShowBlocktag=settings.showBlocktag;
if(bShowBlocktag)bodyClass+=' showBlocktag';
var arrShortCuts=[];
this.init=function()
{
//加載樣式表
if($('#'+idCSS).length==0)$('head').append('<link id="'+idCSS+'" rel="stylesheet" type="text/css" href="'+skinPath+'ui.css" />');
//初始化編輯器
var cw = settings.width || _text.style.width || _jText.outerWidth();
editorHeight = settings.height || _text.style.height || _jText.outerHeight();
if(is(editorHeight,'string'))editorHeight=editorHeight.replace(/[^\d]+/g,'');
if(cw<=0||editorHeight<=0)//禁止對隱藏區域裡的textarea初始化編輯器
{
alert('當前textarea處於隱藏狀態,請將之顯示後再初始化xhEditor,或者直接設置textarea的width和height樣式');
return false;
}
if(/^[0-9\.]+$/i.test(''+cw))cw+='px';
//編輯器CSS背景
var editorBackground=settings.background || _text.style.background;
//工具欄內容初始化
var arrToolsHtml=['<span class="xheGStart"/>'],tool,cn,regSeparator=/\||\//i;
$.each(settings.tools,function(i,n)
{
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGEnd"/>');
if(n=='|')arrToolsHtml.push('<span class="xheSeparator"/>');
else if(n=='/')arrToolsHtml.push('<br />');
else
{
tool=arrTools[n];
if(!tool)return;
if(tool.c)cn=tool.c;
else cn='xheIcon xheBtn'+n;
arrToolsHtml.push('<span><a href="javascript:void(0);" title="'+tool.t+'" name="'+n+'" class="xheButton xheEnabled" tabindex="-1"><span class="'+cn+'" unselectable="on" /></a></span>');
if(tool.s)_this.addShortcuts(tool.s,n);
}
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGStart"/>');
});
arrToolsHtml.push('<span class="xheGEnd"/><br />');
_jText.after($('<input type="text" id="'+idFixFFCursor+'" style="position:absolute;display:none;" /><span id="'+idContainer+'" class="xhe_'+settings.skin+'" style="display:none"><table cellspacing="0" cellpadding="0" class="xheLayout" style="width:'+cw+';height:'+editorHeight+'px;"><tbody><tr><td id="'+idTools+'" class="xheTool" unselectable="on" style="height:1px;"></td></tr><tr><td id="'+idIframeArea+'" class="xheIframeArea"><iframe frameborder="0" id="'+idIframe+'" src="javascript:;" style="width:100%;"></iframe></td></tr></tbody></table></span>'));
_jTools=$('#'+idTools);_jArea=$('#'+idIframeArea);
headHTML='<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><link rel="stylesheet" href="'+skinPath+'iframe.css"/>';
var loadCSS=settings.loadCSS;
if(loadCSS)
{
if(is(loadCSS,'array'))for(var i in loadCSS)headHTML+='<link rel="stylesheet" href="'+loadCSS[i]+'"/>';
else
{
if(loadCSS.match(/\s*<style(\s+[^>]*?)?>[\s\S]+?<\/style>\s*/i))headHTML+=loadCSS;
else headHTML+='<link rel="stylesheet" href="'+loadCSS+'"/>';
}
}
var iframeHTML='<html><head>'+headHTML;
if(editorBackground)iframeHTML+='<style>body{background:'+editorBackground+';}</style>';
iframeHTML+='</head><body spellcheck="false" class="editMode'+bodyClass+'"></body></html>';
_this.win=_win=$('#'+idIframe)[0].contentWindow;
_jWin=$(_win);
try{
this.doc=_doc = _win.document;_jDoc=$(_doc);
_doc.open();
_doc.write(iframeHTML);
_doc.close();
if(isIE)_doc.body.contentEditable='true';
else _doc.designMode = 'On';
}catch(e){}
setTimeout(setOpts,300);
_this.setSource();
_win.setInterval=null;//針對jquery 1.3無法操作iframe window問題的hack
//添加工具欄
_jTools.append(arrToolsHtml.join('')).bind('mousedown contextmenu',returnFalse).click(function(event)
{
var jButton=$(event.target).closest('a');
if(jButton.is('.xheEnabled'))
{
ev=event;
_this.exec(jButton.attr('name'));
}
return false;
});
_jTools.find('.xheButton').hover(function(event){//鼠標懸停執行
var jButton=$(this),delay=settings.hoverExecDelay;
var tAngle=lastAngle;lastAngle=null;
if(delay==-1||bDisableHoverExec||!jButton.is('.xheEnabled'))return false;
if(tAngle&&tAngle>10)//檢測誤操作
{
bDisableHoverExec=true;
setTimeout(function(){bDisableHoverExec=false;},100);
return false;
}
var cmd=jButton.attr('name'),bHover=arrTools[cmd].h==1;
if(!bHover)
{
_this.hidePanel();//移到非懸停按鈕上隱藏面板
return false;
}
if(bQuickHoverExec)delay=0;
if(delay>=0)timer=setTimeout(function(){
ev=event;
lastPoint={x:ev.clientX,y:ev.clientY};
_this.exec(cmd);
},delay);
},function(event){lastPoint=null;if(timer)clearTimeout(timer);}).mousemove(function(event){
if(lastPoint)
{
var diff={x:event.clientX-lastPoint.x,y:event.clientY-lastPoint.y};
if(Math.abs(diff.x)>1||Math.abs(diff.y)>1)
{
if(diff.x>0&&diff.y>0)
{
var tAngle=Math.round(Math.atan(diff.y/diff.x)/0.017453293);
if(lastAngle)lastAngle=(lastAngle+tAngle)/2
else lastAngle=tAngle;
}
else lastAngle=null;
lastPoint={x:event.clientX,y:event.clientY};
}
}
});
//初始化面板
_jPanel=$('#xhePanel');
_jShadow=$('#xheShadow');
_jCntLine=$('#xheCntLine');
if(_jPanel.length==0)
{
_jPanel=$('<div id="xhePanel"></div>').mousedown(function(ev){ev.stopPropagation()});
_jShadow=$('<div id="xheShadow"></div>');
_jCntLine=$('<div id="xheCntLine"></div>');
setTimeout(function(){
$(document.body).append(_jPanel).append(_jShadow).append(_jCntLine);
},10);
}
//切換顯示區域
$('#'+idContainer).show();
_jText.hide();
_jArea.css('height',editorHeight-_jTools.outerHeight());
//綁定內核事件
_jText.focus(_this.focus);
_jForm.submit(saveResult).bind('reset', loadReset);
$(window).bind('unload beforeunload',saveResult).bind('resize',fixFullHeight);
$(document).mousedown(clickCancelPanel);
if(!bCheckEscInit){$(document).keydown(checkEsc);bCheckEscInit=true;}
_jWin.focus(function(){if(settings.focus)settings.focus();}).blur(function(){if(settings.blur)settings.blur();});
if(isSafari)_jWin.click(fixAppleSel);
_jDoc.mousedown(clickCancelPanel).keydown(checkShortcuts).keypress(forcePtag).dblclick(checkDblClick).bind('mousedown click',function(ev){_jText.trigger(ev.type);});
if(isIE)
{
//IE控件上Backspace會導致頁面後退
_jDoc.keydown(function(ev){var rng=_this.getRng();if(ev.which==8&&rng.item){$(rng.item(0)).remove();return false;}});
//修正IE拖動img大小不更新width和height屬性值的問題
function fixResize(ev)
{
var jImg=$(ev.target),v;
if(v=jImg.css('width'))jImg.css('width','').attr('width',v.replace(/[^0-9%]+/g, ''));
if(v=jImg.css('height'))jImg.css('height','').attr('height',v.replace(/[^0-9%]+/g, ''));
}
_jDoc.bind('controlselect',function(ev){
ev=ev.target;if(!$.nodeName(ev,'IMG'))return;
$(ev).unbind('resizeend',fixResize).bind('resizeend',fixResize);
});
}
var jBody=$(_doc.documentElement);
jBody.bind('paste',cleanPaste);
if(settings.disableContextmenu)jBody.bind('contextmenu',returnFalse);
//HTML5編輯區域直接拖放上傳
if(settings.html5Upload)jBody.bind('dragenter dragover',function(ev){var types;if((types=ev.originalEvent.dataTransfer.types)&&$.inArray('Files', types)!=-1)return false;}).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0){
var i,cmd,arrCmd=['Link','Img','Flash','Media'],arrExt=[],strExt;
for(i in arrCmd){
cmd=arrCmd[i];
if(settings['up'+cmd+'Url']&&settings['up'+cmd+'Url'].match(/^[^!].*/i))arrExt.push(cmd+':,'+settings['up'+cmd+'Ext']);//允許上傳
}
if(arrExt.length==0)return false;//禁止上傳
else strExt=arrExt.join(',');
function getCmd(fileList){
var match,fileExt,cmd;
for(i=0;i<fileList.length;i++){
fileExt=fileList[i].fileName.replace(/.+\./,'');
if(match=strExt.match(new RegExp('(\\w+):[^:]*,'+fileExt+'(?:,|$)','i'))){
if(!cmd)cmd=match[1];
else if(cmd!=match[1])return 2;
}
else return 1;
}
return cmd;
}
cmd=getCmd(fileList);
if(cmd==1)alert('上傳文件的擴展名必需為:'+strExt.replace(/\w+:,/g,''));
else if(cmd==2)alert('每次只能拖放上傳同一類型文件');
else if(cmd){
_this.startUpload(fileList,settings['up'+cmd+'Url'],'*',function(arrMsg){
var arrUrl=[],msg,onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用戶上傳回調
for(i in arrMsg){
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!')url=url.substr(1);
arrUrl.push(url);
}
_this.exec(cmd);
$('#xhe'+cmd+'Url').val(arrUrl.join(' '));
$('#xheSave').click();
});
}
return false;
}
});
//添加用戶快捷鍵
var shortcuts=settings.shortcuts;
if(shortcuts)$.each(shortcuts,function(key,func){_this.addShortcuts(key,func);});
xCount++;
bInit=true;
if(settings.fullscreen)_this.toggleFullscreen();
else if(settings.sourceMode)setTimeout(_this.toggleSource,20);
return true;
}
this.remove=function()
{
_this.hidePanel();
saveResult();//卸載前同步最新內容到textarea
//取消綁定事件
_jText.unbind('focus',_this.focus);
_jForm.unbind('submit',saveResult).unbind('reset', loadReset);
$(window).unbind('unload beforeunload',saveResult).unbind('resize',fixFullHeight);
$(document).unbind('mousedown',clickCancelPanel);
$('#'+idContainer+','+'#'+idFixFFCursor).remove();
_jText.show();
bInit=false;
}
this.saveBookmark=function(){
if(!bSource){
var rng=_this.getRng();
rng=rng.cloneRange?rng.cloneRange():rng;
bookmark={'top':_jWin.scrollTop(),'rng':rng};
}
}
this.loadBookmark=function()
{
if(bSource||!bookmark)return;
_this.focus();
var rng=bookmark.rng;
if(isIE)rng.select();
else
{
var sel=_this.getSel();
sel.removeAllRanges();
sel.addRange(rng);
}
_jWin.scrollTop(bookmark.top);
bookmark=null;
}
this.focus=function()
{
if(!bSource)_jWin.focus();
else $('#sourceCode',_doc).focus();
return false;
}
this.setCursorFirst=function(firstBlock)
{
_this.focus();_win.scrollTo(0,0);
var rng=_this.getRng(),_body=_doc.body,firstNode=_body,firstTag;
if(firstBlock&&firstNode.firstChild&&(firstTag=firstNode.firstChild.tagName)&&firstTag.match(/^p|div|h[1-6]$/i))firstNode=_body.firstChild;
isIE?rng.moveToElementText(firstNode):rng.setStart(firstNode,0);
rng.collapse(true);
if(isIE)rng.select();
else{var sel=_this.getSel();sel.removeAllRanges();sel.addRange(rng);}
}
this.getSel=function()
{
return _win.getSelection ? _win.getSelection() : _doc.selection;
}
this.getRng=function()
{
var sel=_this.getSel(),rng;
try{
rng = sel.rangeCount > 0 ? sel.getRangeAt(0) : (sel.createRange ? sel.createRange() : (_doc.createRange?_doc.createRange():_doc.body.createTextRange()));
}catch (ex){}
return rng;
}
this.getParent=function(tag)
{
var rng=_this.getRng(),p;
if(!isIE)
{
p = rng.commonAncestorContainer;
if(!rng.collapsed)if(rng.startContainer == rng.endContainer&&rng.startOffset - rng.endOffset < 2&&rng.startContainer.hasChildNodes())p = rng.startContainer.childNodes[rng.startOffset];
}
else p=rng.item?rng.item(0):rng.parentElement();
tag=tag?tag:'*';p=$(p);
if(!p.is(tag))p=$(p).closest(tag);
return p;
}
this.getSelect=function(format)
{
var sel=_this.getSel(),rng=_this.getRng(),isCollapsed=true;
if (!rng || rng.item)isCollapsed=false
else isCollapsed=!sel || rng.boundingWidth == 0 || rng.collapsed;
if(format=='text')return isCollapsed ? '' : (rng.text || (sel.toString ? sel.toString() : ''));
var sHtml;
if(rng.cloneContents)
{
var tmp=$('<div></div>'),c;
c = rng.cloneContents();
if(c)tmp.append(c);
sHtml=tmp.html();
}
else if(is(rng.item))sHtml=rng.item(0).outerHTML;
else if(is(rng.htmlText))sHtml=rng.htmlText;
else sHtml=rng.toString();
if(isCollapsed)sHtml='';
sHtml=_this.processHTML(sHtml,'read');
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
return sHtml;
}
this.pasteHTML=function(sHtml,bStart)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
var sel=_this.getSel(),rng=_this.getRng();
if(bStart!=undefined)//非覆蓋式插入
{
if(rng.item)
{
var n=rng.item(0);
rng=_doc.body.createTextRange();
rng.moveToElementText(n);
rng.select();
}
rng.collapse(bStart);
}
sHtml+='<'+(isIE?'img':'span')+' id="_xhe_temp" style="display:none" />';
if(rng.insertNode)
{
rng.deleteContents();
rng.insertNode(rng.createContextualFragment(sHtml));
}
else
{
if(sel.type.toLowerCase()=='control'){sel.clear();rng=_this.getRng();};
rng.pasteHTML(sHtml);
}
var jTemp=$('#_xhe_temp',_doc),temp=jTemp[0];
if(isIE)
{
rng.moveToElementText(temp);
rng.select();
}
else
{
rng.selectNode(temp);
sel.removeAllRanges();
sel.addRange(rng);
}
jTemp.remove();
}
this.pasteText=function(text,bStart)
{
if(!text)text='';
text=_this.domEncode(text);
text = text.replace(/\r?\n/g, '<br />');
_this.pasteHTML(text,bStart);
}
this.appendHTML=function(sHtml)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
$(_doc.body).append(sHtml);
}
this.domEncode=function(str)
{
return str.replace(/[<>]/g,function(c){return {'<':'<','>':'>'}[c];});
}
this.setSource=function(sHtml)
{
bookmark=null;
if(typeof sHtml!='string'&&sHtml!='')sHtml=_text.value;
if(bSource)$('#sourceCode',_doc).val(sHtml);
else
{
if(settings.beforeSetSource)sHtml=settings.beforeSetSource(sHtml);
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
sHtml=_this.cleanWord(sHtml);
sHtml=_this.processHTML(sHtml,'write');
if(isIE){//修正IE會刪除可視內容前的script,style,<!--
_doc.body.innerHTML='<img id="_xhe_temp" style="display:none" />'+sHtml;
$('#_xhe_temp',_doc).remove();
}
else _doc.body.innerHTML=sHtml;
}
}
this.processHTML=function(sHtml,mode)
{
var appleClass=' class="Apple-style-span"';
if(mode=='write')
{//write
//恢復emot
function restoreEmot(all,attr,q,emot)
{
emot=emot.split(',');
if(!emot[1]){emot[1]=emot[0];emot[0]=''}
if(emot[0]=='default')emot[0]='';
return all.replace(/\s+src\s*=\s*(["']?).*?\1(\s|$|\/|>)/i,'$2').replace(attr,' src="'+emotPath+(emot[0]?emot[0]:'default')+'/'+emot[1]+'.gif"'+(settings.emotMark?' emot="'+(emot[0]?emot[0]+',':'')+emot[1]+'"'+(all.match(/\s+alt\s*=\s*(["']?)\s*(.*?)\s*\1[\s\/>]/i)?'':' alt="'+emot[1]+'"'):''));
}
sHtml = sHtml.replace(/<img(?:\s+[^>]*?)?(\s+emot\s*=\s*(["']?)\s*(.*?)\s*\2)(?:\s+[^>]*?)?\/?>/ig,restoreEmot);
//保存屬性值:src,href
function saveValue(all,tag,attr,n,q,v){return all.replace(attr,(urlBase?(' '+n+'="'+getLocalUrl(v,'abs',urlBase)+'"'):attr)+' _xhe_'+n+'="'+v+'"');}
sHtml = sHtml.replace(/<(\w+(?:\:\w+)?)(?:\s+[^>]*?)?(\s+(src|href)\s*=\s*(["']?)\s*(.*?)\s*\4)(?:\s+[^>]*?)?\/?>/ig,saveValue);
sHtml = sHtml.replace(/<(\/?)del(\s+[^>]*?)?>/ig,'<$1strike$2>');//編輯狀態統一轉為strike
if(isMozilla)
{
sHtml = sHtml.replace(/<(\/?)strong(\s+[^>]*?)?>/ig,'<$1b$2>');
sHtml = sHtml.replace(/<(\/?)em(\s+[^>]*?)?>/ig,'<$1i$2>');
}
else if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.n){s=t.wkn;break;}
}
return pre+'font-size:'+s+aft;
});
sHtml = sHtml.replace(/<strong(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-weight: bold;"$1>');
sHtml = sHtml.replace(/<em(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-style: italic;"$1>');
sHtml = sHtml.replace(/<u(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: underline;"$1>');
sHtml = sHtml.replace(/<strike(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: line-through;"$1>');
sHtml = sHtml.replace(/<\/(strong|em|u|strike)>/ig,'</span>');
sHtml = sHtml.replace(/<span((?:\s+[^>]*?)?\s+style="([^"]*;)*\s*(font-family|font-size|color|background-color)\s*:\s*[^;"]+\s*;?"[^>]*)>/ig,'<span'+appleClass+'$1>');
}
else if(isIE)
{
sHtml = sHtml.replace(/'/ig, ''');
sHtml = sHtml.replace(/\s+(disabled|checked|readonly|selected)\s*=\s*[\"\']?(false|0)[\"\']?/ig, '');
}
sHtml = sHtml.replace(/<a(\s+[^>]*?)?\/>/,'<a$1></a>');
if(!isSafari)
{
//style轉font
function style2font(all,tag,style,content)
{
var attrs='',f,s1,s2,c;
f=style.match(/font-family\s*:\s*([^;"]+)/i);
if(f)attrs+=' face="'+f[1]+'"';
s1=style.match(/font-size\s*:\s*([^;"]+)/i);
if(s1)
{
s1=s1[1].toLowerCase();
for(var j=0;j<arrFontsize.length;j++)if(s1==arrFontsize[j].n||s1==arrFontsize[j].s){s2=j+1;break;}
if(s2)
{
attrs+=' size="'+s2+'"';
style=style.replace(/(^|;)(\s*font-size\s*:\s*[^;"]+;?)+/ig,'$1');
}
}
c=style.match(/(?:^|[\s;])color\s*:\s*([^;"]+)/i);
if(c)
{
var rgb;
if(rgb=c[1].match(/\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)){c[1]='#';for(var i=1;i<=3;i++)c[1]+=(rgb[i]-0).toString(16);}
c[1]=c[1].replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,'#$1$1$2$2$3$3');
attrs+=' color="'+c[1]+'"';
}
style=style.replace(/(^|;)(\s*(font-family|color)\s*:\s*[^;"]+;?)+/ig,'$1');
if(attrs!='')
{
if(style)attrs+=' style="'+style+'"';
return '<font'+attrs+'>'+content+"</font>";
}
else return all;
}
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,style2font);//最裡層
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,style2font);//第2層
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,style2font);//第3層
}
}
else
{//read
//恢復屬性值src,href
function restoreValue(all,n,q,v)
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
return all.replace(new RegExp('\\s+'+n+'\\s*=\\s*(["\']?).*?\\1(\\s|/?>)','ig'),' '+n+'="'+v.replace(/\$/g,'$$$$')+'"$2');
}
sHtml = sHtml.replace(/<(?:\w+(?:\:\w+)?)(?:\s+[^>]*?)?\s+_xhe_(src|href)\s*=\s*(["']?)\s*(.*?)\s*\2(?:\s+[^>]*?)?\/?>/ig,restoreValue);
if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.wkn){s=t.n;break;}
}
return pre+'font-size:'+s+aft;
});
var arrAppleSpan=[{r:/font-weight:\sbold/ig,t:'strong'},{r:/font-style:\sitalic/ig,t:'em'},{r:/text-decoration:\sunderline/ig,t:'u'},{r:/text-decoration:\sline-through/ig,t:'strike'}];
function replaceAppleSpan(all,tag,attr1,attr2,content)
{
var attr=attr1+attr2,newTag='';
if(!attr)return content;
for(var i=0;i<arrAppleSpan.length;i++)
{
if(attr.match(arrAppleSpan[i].r))
{
newTag=arrAppleSpan[i].t;
break;
}
}
if(newTag)return '<'+newTag+'>'+content+'</'+newTag+'>';
else return all;
}
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,replaceAppleSpan);//最裡層
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第2層
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第3層
}
if(!isIE){//字符間的文本換行強制轉br
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/([^<>\r\n]?)((?:\r?\n)+)([^<>\r\n]?)/ig,function(all,left,br,right){if(left||right)return left+br.replace(/\r?\n/g,'<br />')+right;else return all;});
});
}
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+(?:_xhe_|_moz_|_webkit_)[^=]+?\s*=\s*(["']?).*?\2(\s|\/?>)/ig,'$1$3');
sHtml = sHtml.replace(/(<\w+[^>]*?)\s+class\s*=\s*(["']?)\s*(?:apple|webkit)\-.+?\s*\2(\s|\/?>)/ig, "$1$3");
sHtml = sHtml.replace(/<img(\s+[^>]+?)\/?>/ig,function(all,attr){if(!attr.match(/\s+alt\s*(["']?).*?\1(\s|$)/i))attr+=' alt=""';return '<img'+attr+' />';});//img強制加alt
sHtml = sHtml.replace(/\s+jquery\d+="\d+"/ig,'');
}
return sHtml;
}
this.getSource=function(bFormat)
{
var sHtml,beforeGetSource=settings.beforeGetSource;
if(bSource)
{
sHtml=$('#sourceCode',_doc).val();
if(!beforeGetSource){
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/(\t*\r?\n\t*)+/g,'')//標準HTML模式清理縮排和換行
});
}
}
else
{
sHtml=_this.processHTML(_doc.body.innerHTML,'read');
sHtml=sHtml.replace(/^\s*(?:<(p|div)(?:\s+[^>]*?)?>)?\s*(<br(?:\s+[^>]*?)?>)*\s*(?:<\/\1>)?\s*$/i, '');//修正Firefox在空內容情況下多出來的代碼
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml,bFormat);
sHtml=_this.cleanWord(sHtml);
if(beforeGetSource)sHtml=beforeGetSource(sHtml);
}
_text.value=sHtml;
return sHtml;
}
this.cleanWord=function(sHtml)
{
if(sHtml.match(/mso(-|normal)|WordDocument/i))
{
var deepClean=settings.wordDeepClean;
//格式化
sHtml = sHtml.replace(/(<link(?:\s+[^>]*?)?)\s+href\s*=\s*(["']?)\s*file:\/\/.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, '');
//區塊標籤清理
sHtml = sHtml.replace(/<!--[\s\S]*?-->|<!(--)?\[[\s\S]+?\](--)?>|<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
sHtml = sHtml.replace(/<\/?\w+:[^>]*>/ig, '');
if(deepClean)sHtml = sHtml.replace(/<\/?(span|a|img)(\s+[^>]*?)?>/ig,'');
//屬性清理
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+class\s*=\s*(["']?)\s*mso.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//刪除所有mso開頭的樣式
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+lang\s*=\s*(["']?)\s*.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//刪除lang屬性
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+align\s*=\s*(["']?)\s*left\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//取消align=left
//樣式清理
sHtml = sHtml.replace(/<\w+(?:\s+[^>]*?)?(\s+style\s*=\s*(["']?)\s*([\s\S]*?)\s*\2)(?:\s+[^>]*?)?\s*\/?>/ig,function(all,attr,p,styles){
styles=$.trim(styles.replace(/\s*(mso-[^:]+:.+?|margin\s*:\s*0cm 0cm 0pt\s*|(text-align|font-variant|line-height)\s*:\s*.+?)(;|$)\s*/ig,''));
return all.replace(attr,deepClean?'':styles?' style="'+styles+'"':'');
});
}
return sHtml;
}
this.cleanHTML=function(sHtml)
{
sHtml = sHtml.replace(/<!?\/?(DOCTYPE|html|body|meta)(\s+[^>]*?)?>/ig, '');
var arrHeadSave;sHtml = sHtml.replace(/<head(?:\s+[^>]*?)?>([\s\S]*?)<\/head>/i, function(all,content){arrHeadSave=content.match(/<(script|style)(\s+[^>]*?)?>[\s\S]*?<\/\1>/ig);return '';});
if(arrHeadSave)sHtml=arrHeadSave.join('')+sHtml;
sHtml = sHtml.replace(/<\??xml(:\w+)?(\s+[^>]*?)?>([\s\S]*?<\/xml>)?/ig, '');
if(!settings.linkTag)sHtml = sHtml.replace(/<link(\s+[^>]*?)?>/ig, '');
if(!settings.internalScript)sHtml = sHtml.replace(/<script(\s+[^>]*?)?>[\s\S]*?<\/script>/ig, '');
if(!settings.inlineScript)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+on(?:click|dblclick|mousedown|mouseup|mousemove|mouseover|mouseout|mouseenter|mouseleave|keydown|keypress|keyup|change|select|submit|reset|blur|focus|load|unload)\s*=\s*(["']?)[\s\S]*?\3((?:\s+[^>]*?)?\/?>)/ig,'$1$2$4');
if(!settings.internalStyle)sHtml = sHtml.replace(/<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
if(!settings.inlineStyle)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+(style|class)\s*=\s*(["']?)[\s\S]*?\4((?:\s+[^>]*?)?\/?>)/ig,'$1$2$5');
sHtml=sHtml.replace(/<\/(strong|b|u|strike|em|i)>((?:\s|<br\/?>| )*?)<\1(\s+[^>]*?)?>/ig,'$2');//連續相同標籤
return sHtml;
}
this.formatXHTML=function(sHtml,bFormat)
{
var emptyTags = makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");//HTML 4.01
var blockTags = makeMap("address,applet,blockquote,button,center,dd,dir,div,dl,dt,fieldset,form,frameset,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");//HTML 4.01
var inlineTags = makeMap("a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");//HTML 4.01
var closeSelfTags = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
var fillAttrsTags = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
var specialTags = makeMap("script,style");
var tagReplac={'b':'strong','i':'em','s':'del','strike':'del'};
var startTag = /^<\??(\w+(?:\:\w+)?)((?:\s+[\w-\:]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/(\w+(?:\:\w+)?)[^>]*>/;
var attr = /\s+([\w-]+(?:\:\w+)?)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s]+)))?/g;
var skip=0,stack=[],last=sHtml,results=Array(),lvl=-1,lastTag='body',lastTagStart;
stack.last = function(){return this[ this.length - 1 ];};
while(last.length>0)
{
if(!stack.last()||!specialTags[stack.last()])
{
skip=0;
if(last.substring(0, 4)=='<!--')
{//註釋標籤
skip=last.indexOf("-->");
if(skip!=-1)
{
skip+=3;
addHtmlFrag(last.substring(0,skip));
}
}
else if(last.substring(0, 2)=='</')
{//結束標籤
match = last.match( endTag );
if(match)
{
parseEndTag(match[1]);
skip = match[0].length;
}
}
else if(last.charAt(0)=='<')
{//開始標籤
match = last.match( startTag );
if(match)
{
parseStartTag(match[1],match[2],match[3]);
skip = match[0].length;
}
}
if(skip==0)//普通文本
{
skip=last.indexOf('<');
if(skip==0)skip=1;
else if(skip<0)skip=last.length;
addHtmlFrag(_this.domEncode(last.substring(0,skip)));
}
last=last.substring(skip);
}
else
{//處理style和script
last=last.replace(/^([\s\S]*?)<\/(style|script)>/i, function(all, script,tagName){
results.push(script);
return ''
});
parseEndTag(stack.last());
}
}
parseEndTag();
sHtml=results.join('');
results=null;
function makeMap(str)
{
var obj = {}, items = str.split(",");
for ( var i = 0; i < items.length; i++ )obj[ items[i] ] = true;
return obj;
}
function processTag(tagName)
{
if(tagName)
{
tagName=tagName.toLowerCase();
var tag=tagReplac[tagName];
if(tag)tagName=tag;
}
else tagName='';
return tagName;
}
function parseStartTag(tagName,rest,unary)
{
tagName=processTag(tagName);
if(blockTags[tagName])while(stack.last()&&inlineTags[stack.last()])parseEndTag(stack.last());
if(closeSelfTags[tagName]&&stack.last()==tagName)parseEndTag(tagName);
unary = emptyTags[ tagName ] || !!unary;
if (!unary)stack.push(tagName);
var all=Array();
all.push('<' + tagName);
rest.replace(attr, function(match, name)
{
name=name.toLowerCase();
var value = arguments[2] ? arguments[2] :
arguments[3] ? arguments[3] :
arguments[4] ? arguments[4] :
fillAttrsTags[name] ? name : "";
all.push(' '+name+'="'+value+'"');
});
all.push((unary ? " /" : "") + ">");
addHtmlFrag(all.join(''),tagName,true);
}
function parseEndTag(tagName)
{
if(!tagName)var pos=0;//清空棧
else
{
tagName=processTag(tagName);
for(var pos=stack.length-1;pos>=0;pos--)if(stack[pos]==tagName)break;//向上尋找匹配的開始標籤
}
if(pos>=0)
{
for(var i=stack.length-1;i>=pos;i--)addHtmlFrag("</" + stack[i] + ">",stack[i]);
stack.length=pos;
}
}
function addHtmlFrag(html,tagName,bStart)
{
if(bFormat==true)
{
html=html.replace(/(\t*\r?\n\t*)+/g,'');//清理換行符和相鄰的製表符
if(html.match(/^\s*$/))return;//不格式化空內容的標籤
var bBlock=blockTags[tagName],tag=bBlock?tagName:'';
if(bBlock)
{
if(bStart)lvl++;//塊開始
if(lastTag=='')lvl--;//補文本結束
}
else if(lastTag)lvl++;//文本開始
if(tag!=lastTag||bBlock)addIndent();
results.push(html);
if(tagName=='br')addIndent();//回車強制換行
if(bBlock&&(emptyTags[tagName]||!bStart))lvl--;//塊結束
lastTag=bBlock?tagName:'';lastTagStart=bStart;
}
else results.push(html);
}
function addIndent(){results.push('\r\n');if(lvl>0){var tabs=lvl;while(tabs--)results.push("\t");}}
//font轉style
function font2style(all,tag,attrs,content)
{
if(!attrs)return content;
var styles='',f,s,c,style;
f=attrs.match(/ face\s*=\s*"\s*([^"]+)\s*"/i);
if(f)styles+='font-family:'+f[1]+';';
s=attrs.match(/ size\s*=\s*"\s*(\d+)\s*"/i);
if(s)styles+='font-size:'+arrFontsize[(s[1]>7?7:(s[1]<1?1:s[1]))-1].n+';';
c=attrs.match(/ color\s*=\s*"\s*([^"]+)\s*"/i);
if(c)styles+='color:'+c[1]+';';
style=attrs.match(/ style\s*=\s*"\s*([^"]+)\s*"/i);
if(style)styles+=style[1];
if(styles)content='<span style="'+styles+'">'+content+'</span>';
return content;
}
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,font2style);//最裡層
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,font2style);//第2層
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,font2style);//第3層
sHtml = sHtml.replace(/^(\s*\r?\n)+|(\s*\r?\n)+$/g,'');//清理首尾換行
sHtml = sHtml.replace(/(\t*\r?\n)+/g,'\r\n');//多行變一行
return sHtml;
}
this.toggleShowBlocktag=function(state)
{
if(bShowBlocktag===state)return;
bShowBlocktag=!bShowBlocktag;
var _jBody=$(_doc.body);
if(bShowBlocktag)
{
bodyClass+=' showBlocktag';
_jBody.addClass('showBlocktag');
}
else
{
bodyClass=bodyClass.replace(' showBlocktag','');
_jBody.removeClass('showBlocktag');
}
}
this.toggleSource=function(state)
{
if(bSource===state)return;
_jTools.find('[name=Source]').toggleClass('xheEnabled').toggleClass('xheActive');
var _body=_doc.body,jBody=$(_body),sHtml;
var sourceCode,cursorMark='<span id="_xhe_cursor'+new Date().getTime()+'"></span>',cursorPos=0;
if(!bSource)
{//轉為原始碼模式
_this.pasteHTML(cursorMark,true);//標記當前位置
sHtml=_this.getSource(true);
cursorPos=sHtml.indexOf(cursorMark);
if(!isOpera)cursorPos=sHtml.substring(0,cursorPos).replace(/\r/g,'').length;//修正非opera光標定位點
sHtml=sHtml.replace(cursorMark,'');
if(isIE)_body.contentEditable='false';
else _doc.designMode = 'Off';
jBody.attr('scroll','no').attr('class','sourceMode').html('<textarea id="sourceCode" wrap="soft" spellcheck="false" height="100%" />');
sourceCode=$('#sourceCode',jBody).blur(_this.getSource)[0];
}
else
{//轉為編輯模式
sHtml=_this.getSource();
jBody.html('').removeAttr('scroll').attr('class','editMode'+bodyClass);
if(isIE)_body.contentEditable='true';
else _doc.designMode = 'On';
if(isMozilla)
{
_this._exec("inserthtml","-");//修正firefox原始碼切換回來無法刪除文字的問題
$('#'+idFixFFCursor).show().focus().hide();//臨時修正Firefox 3.6光標丟失問題
}
}
bSource=!bSource;
_this.setSource(sHtml);
if(bSource)//光標定位源碼
{
_this.focus();
if(sourceCode.setSelectionRange)sourceCode.setSelectionRange(cursorPos, cursorPos);
else
{
var rng = sourceCode.createTextRange();
rng.move("character",cursorPos);
rng.select();
}
}
else _this.setCursorFirst(true);//定位最前面
_jTools.find('[name=Source],[name=Preview]').toggleClass('xheEnabled');
_jTools.find('.xheButton').not('[name=Source],[name=Fullscreen],[name=About]').toggleClass('xheEnabled');
setTimeout(setOpts,300);
}
this.showPreview=function()
{
var beforeSetSource=settings.beforeSetSource,sContent=_this.getSource();
if(beforeSetSource)sContent=beforeSetSource(sContent);
var sHTML='<html><head>'+headHTML+'<title>預覽</title>'+(urlBase?'<base href="'+urlBase+'"/>':'')+'</head><body>' + sContent + '</body></html>';
var screen=window.screen,oWindow=window.open('', 'xhePreview', 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+Math.round(screen.width*0.9)+',height='+Math.round(screen.height*0.8)+',left='+Math.round(screen.width*0.05)),oDoc=oWindow.document;
oDoc.open();
oDoc.write(sHTML);
oDoc.close();
oWindow.focus();
}
this.toggleFullscreen=function(state)
{
if(bFullscreen===state)return;
var jLayout=$('#'+idContainer).find('.xheLayout'),jContainer=$('#'+idContainer);
if(bFullscreen)
{//取消全屏
jLayout.attr('style',sLayoutStyle);
_jArea.height(editorHeight-_jTools.outerHeight());
setTimeout(function(){$(window).scrollTop(outerScroll);},10);
}
else
{//顯示全屏
outerScroll=$(window).scrollTop();
sLayoutStyle=jLayout.attr('style');
jLayout.removeAttr('style');
_jArea.height('100%');
setTimeout(fixFullHeight,100);
}
if(isMozilla)//臨時修正Firefox 3.6原始碼光標丟失問題
{
$('#'+idFixFFCursor).show().focus().hide();
setTimeout(_this.focus,1);
}
bFullscreen=!bFullscreen;
jContainer.toggleClass('xhe_Fullscreen');
$('html').toggleClass('xhe_Fullfix');
_jTools.find('[name=Fullscreen]').toggleClass('xheActive');
setTimeout(setOpts,300);
}
this.showMenu=function(menuitems,callback)
{
var jMenu=$('<div class="xheMenu"></div>'),arrItem=[];
$.each(menuitems,function(n,v){arrItem.push('<a href="javascript:void(0);" title="'+(v.t?v.t:v.s)+'" v="'+v.v+'">'+v.s+'</a>');});
jMenu.append(arrItem.join(''));
jMenu.click(function(ev){callback($(ev.target).closest('a').attr('v'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jMenu);
}
this.showColor=function(callback)
{
var jColor=$('<div class="xheColor"></div>'),arrItem=[],count=0;
$.each(itemColors,function(n,v)
{
if(count%7==0)arrItem.push((count>0?'</div>':'')+'<div>');
arrItem.push('<a href="javascript:void(0);" xhev="'+v+'" title="'+v+'" style="background:'+v+'"></a>');
count++;
});
arrItem.push('</div>');
jColor.append(arrItem.join(''));
jColor.click(function(ev){ev=ev.target;if(!$.nodeName(ev,'A'))return;callback($(ev).attr('xhev'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jColor);
}
this.showPastetext=function()
{
var jPastetext=$(htmlPastetext),jValue=$('#xhePastetextValue',jPastetext),jSave=$('#xheSave',jPastetext);
jSave.click(function(){
_this.loadBookmark();
var sValue=jValue.val();
if(sValue)_this.pasteText(sValue);
_this.hidePanel();
return false;
});
_this.showDialog(jPastetext);
}
this.showLink=function()
{
var jLink=$(htmlLink),jParent=_this.getParent('a'),jText=$('#xheLinkText',jLink),jUrl=$('#xheLinkUrl',jLink),jTarget=$('#xheLinkTarget',jLink),jSave=$('#xheSave',jLink),selHtml=_this.getSelect();
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'href'));
jTarget.attr('value',jParent.attr('target'));
}
else if(selHtml=='')jText.val(settings.defLinkText).closest('div').show();
if(settings.upLinkUrl)_this.uploadInit(jUrl,settings.upLinkUrl,settings.upLinkExt);
jSave.click(function(){
var url=jUrl.val();
_this.loadBookmark();
if(url==''||jParent.length==0)_this._exec('unlink');
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sTarget=jTarget.val(),sText=jText.val();
if(aUrl.length>1)
{//批量插入
_this._exec('unlink');//批量前刪除當前鏈接並重新獲取選擇內容
selHtml=_this.getSelect();
var sTemplate='<a href="xhe_tmpurl"',sLink,arrLink=[];
if(sTarget!='')sTemplate+=' target="'+sTarget+'"';
sTemplate+='>xhe_tmptext</a>';
sText=(selHtml!=''?selHtml:(sText?sText:url));
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sLink=sTemplate;
sLink=sLink.replace('xhe_tmpurl',url[0]);
sLink=sLink.replace('xhe_tmptext',url[1]?url[1]:sText);
arrLink.push(sLink);
}
}
_this.pasteHTML(arrLink.join(' '));
}
else
{//單url模式
url=aUrl[0].split('||');
if(!sText)sText=url[0];
sText=url[1]?url[1]:(selHtml!='')?'':sText?sText:url[0];
if(jParent.length==0)
{
if(sText)_this.pasteHTML('<a href="#xhe_tmpurl">'+sText+'</a>');
else _this._exec('createlink','#xhe_tmpurl');
jParent=$('a[href$="#xhe_tmpurl"]',_doc);
}
else if(sText&&!isSafari)jParent.text(sText);//safari改寫文本會導致光標丟失
xheAttr(jParent,'href',url[0]);
if(sTarget!='')jParent.attr('target',sTarget);
else jParent.removeAttr('target');
}
}
_this.hidePanel();
return false;
});
_this.showDialog(jLink);
}
this.showImg=function()
{
var jImg=$(htmlImg),jParent=_this.getParent('img'),jUrl=$('#xheImgUrl',jImg),jAlt=$('#xheImgAlt',jImg),jAlign=$('#xheImgAlign',jImg),jWidth=$('#xheImgWidth',jImg),jHeight=$('#xheImgHeight',jImg),jBorder=$('#xheImgBorder',jImg),jVspace=$('#xheImgVspace',jImg),jHspace=$('#xheImgHspace',jImg),jSave=$('#xheSave',jImg);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jAlt.val(jParent.attr('alt'));
jAlign.val(jParent.attr('align'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
jBorder.val(jParent.attr('border'));
var vspace=jParent.attr('vspace'),hspace=jParent.attr('hspace');
jVspace.val(vspace<=0?'':vspace);
jHspace.val(hspace<=0?'':hspace);
}
if(settings.upImgUrl)_this.uploadInit(jUrl,settings.upImgUrl,settings.upImgExt);
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sAlt=jAlt.val(),sAlign=jAlign.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sBorder=jBorder.val(),sVspace=jVspace.val(),sHspace=jHspace.val();;
if(aUrl.length>1)
{//批量插入
var sTemplate='<img src="xhe_tmpurl"',sImg,arrImg=[];
if(sAlt!='')sTemplate+=' alt="'+sAlt+'"';
if(sAlign!='')sTemplate+=' align="'+sAlign+'"';
if(sWidth!='')sTemplate+=' width="'+sWidth+'"';
if(sHeight!='')sTemplate+=' height="'+sHeight+'"';
if(sBorder!='')sTemplate+=' border="'+sBorder+'"';
if(sVspace!='')sTemplate+=' vspace="'+sVspace+'"';
if(sHspace!='')sTemplate+=' hspace="'+sHspace+'"';
sTemplate+=' />';
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sImg=sTemplate;
sImg=sImg.replace('xhe_tmpurl',url[0]);
if(url[1])sImg='<a href="'+url[1]+'" target="_blank">'+sImg+'</a>'
arrImg.push(sImg);
}
}
_this.pasteHTML(arrImg.join(' '));
}
else if(aUrl.length==1)
{//單URL模式
url=aUrl[0];
if(url!='')
{
url=url.split('||');
if(jParent.length==0)
{
_this.pasteHTML('<img src="'+url[0]+'#xhe_tmpurl" />');
jParent=$('img[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0])
if(sAlt!='')jParent.attr('alt',sAlt);
if(sAlign!='')jParent.attr('align',sAlign);
else jParent.removeAttr('align');
if(sWidth!='')jParent.attr('width',sWidth);
else jParent.removeAttr('width');
if(sHeight!='')jParent.attr('height',sHeight);
else jParent.removeAttr('height');
if(sBorder!='')jParent.attr('border',sBorder);
else jParent.removeAttr('border');
if(sVspace!='')jParent.attr('vspace',sVspace);
else jParent.removeAttr('vspace');
if(sHspace!='')jParent.attr('hspace',sHspace);
else jParent.removeAttr('hspace');
if(url[1])
{
var jLink=jParent.parent('a');
if(jLink.length==0)
{
jParent.wrap('<a></a>');
jLink=jParent.parent('a');
}
xheAttr(jLink,'href',url[1]);
jLink.attr('target','_blank');
}
}
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
_this.showDialog(jImg);
}
this.showEmbed=function(sType,sHtml,sMime,sClsID,sBaseAttrs,sUploadUrl,sUploadExt)
{
var jEmbed=$(sHtml),jParent=_this.getParent('embed[type="'+sMime+'"],embed[classid="'+sClsID+'"]'),jUrl=$('#xhe'+sType+'Url',jEmbed),jWidth=$('#xhe'+sType+'Width',jEmbed),jHeight=$('#xhe'+sType+'Height',jEmbed),jSave=$('#xheSave',jEmbed);
if(sUploadUrl)_this.uploadInit(jUrl,sUploadUrl,sUploadExt);
_this.showDialog(jEmbed);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
}
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var w=jWidth.val(),h=jHeight.val(),reg=/^[0-9]+$/;
if(!reg.test(w))w=412;if(!reg.test(h))h=300;
var sBaseCode='<embed type="'+sMime+'" classid="'+sClsID+'" src="xhe_tmpurl"'+sBaseAttrs;
var aUrl=url.split(' ');
if(aUrl.length>1)
{//批量插入
var sTemplate=sBaseCode+'',sEmbed,arrEmbed=[];
sTemplate+=' width="xhe_width" height="xhe_height" />';
for(var i in aUrl)
{
url=aUrl[i].split('||');
sEmbed=sTemplate;
sEmbed=sEmbed.replace('xhe_tmpurl',url[0])
sEmbed=sEmbed.replace('xhe_width',url[1]?url[1]:w)
sEmbed=sEmbed.replace('xhe_height',url[2]?url[2]:h)
if(url!='')arrEmbed.push(sEmbed);
}
_this.pasteHTML(arrEmbed.join(' '));
}
else if(aUrl.length==1)
{//單URL模式
url=aUrl[0].split('||');
if(jParent.length==0)
{
_this.pasteHTML(sBaseCode.replace('xhe_tmpurl',url[0]+'#xhe_tmpurl')+' />');
jParent=$('embed[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0]);
jParent.attr('width',url[1]?url[1]:w);
jParent.attr('height',url[2]?url[2]:h);
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
}
this.showEmot=function(group)
{
var jEmot=$('<div class="xheEmot"></div>');
group=group?group:(selEmotGroup?selEmotGroup:'default');
var arrEmot=arrEmots[group];
var sEmotPath=emotPath+group+'/',n=0,arrList=[],jList='';
var ew=arrEmot.width,eh=arrEmot.height,line=arrEmot.line,count=arrEmot.count,list=arrEmot.list;
if(count)
{
for(var i=1;i<=count;i++)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+i+'.gif);" emot="'+group+','+i+'" xhev=""> </a>');
if(n%line==0)arrList.push('<br />');
}
}
else
{
$.each(list,function(id,title)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+id+'.gif);" emot="'+group+','+id+'" title="'+title+'" xhev="'+title+'"> </a>');
if(n%line==0)arrList.push('<br />');
});
}
var w=line*(ew+12),h=Math.ceil(n/line)*(eh+12),mh=w*0.75;
if(h<=mh)mh='';
jList=$('<style>'+(mh?'.xheEmot div{width:'+(w+20)+'px;height:'+mh+'px;}':'')+'.xheEmot div a{width:'+ew+'px;height:'+eh+'px;}</style><div>'+arrList.join('')+'</div>').click(function(ev){ev=ev.target;var jA=$(ev);if(!$.nodeName(ev,'A'))return;_this.pasteHTML('<img emot="'+jA.attr('emot')+'" alt="'+jA.attr('xhev')+'">');_this.hidePanel();return false;}).mousedown(returnFalse);
jEmot.append(jList);
var gcount=0,arrGroup=['<ul>'],jGroup;//表情分類
$.each(arrEmots,function(g,v){
gcount++;
arrGroup.push('<li'+(group==g?' class="cur"':'')+'><a href="javascript:void(0);" group="'+g+'">'+v.name+'</a></li>');
});
if(gcount>1)
{
arrGroup.push('</ul><br style="clear:both;" />');
jGroup=$(arrGroup.join('')).click(function(ev){selEmotGroup=$(ev.target).attr('group');_this.exec('Emot');return false;}).mousedown(returnFalse);
jEmot.append(jGroup);
}
_this.showPanel(jEmot);
}
this.showTable=function()
{
var jTable=$(htmlTable),jRows=$('#xheTableRows',jTable),jColumns=$('#xheTableColumns',jTable),jHeaders=$('#xheTableHeaders',jTable),jWidth=$('#xheTableWidth',jTable),jHeight=$('#xheTableHeight',jTable),jBorder=$('#xheTableBorder',jTable),jCellSpacing=$('#xheTableCellSpacing',jTable),jCellPadding=$('#xheTableCellPadding',jTable),jAlign=$('#xheTableAlign',jTable),jCaption=$('#xheTableCaption',jTable),jSave=$('#xheSave',jTable);
jSave.click(function(){
_this.loadBookmark();
var sCaption=jCaption.val(),sBorder=jBorder.val(),sRows=jRows.val(),sCols=jColumns.val(),sHeaders=jHeaders.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sCellSpacing=jCellSpacing.val(),sCellPadding=jCellPadding.val(),sAlign=jAlign.val();
var i,j,htmlTable='<table'+(sBorder!=''?' border="'+sBorder+'"':'')+(sWidth!=''?' width="'+sWidth+'"':'')+(sHeight!=''?' width="'+sHeight+'"':'')+(sCellSpacing!=''?' cellspacing="'+sCellSpacing+'"':'')+(sCellPadding!=''?' cellpadding="'+sCellPadding+'"':'')+(sAlign!=''?' align="'+sAlign+'"':'')+'>';
if(sCaption!='')htmlTable+='<caption>'+sCaption+'</caption>';
if(sHeaders=='row'||sHeaders=='both')
{
htmlTable+='<tr>';
for(i=0;i<sCols;i++)htmlTable+='<th scope="col"> </th>';
htmlTable+='</tr>';
sRows--;
}
htmlTable+='<tbody>';
for(i=0;i<sRows;i++)
{
htmlTable+='<tr>';
for(j=0;j<sCols;j++)
{
if(j==0&&(sHeaders=='col'||sHeaders=='both'))htmlTable+='<th scope="row"> </th>';
else htmlTable+='<td> </td>';
}
htmlTable+='</tr>';
}
htmlTable+='</tbody></table>';
_this.pasteHTML(htmlTable);
_this.hidePanel();
return false;
});
_this.showDialog(jTable);
}
this.showAbout=function()
{
var jAbout=$(htmlAbout);
_this.showDialog(jAbout);
}
this.addShortcuts=function(key,cmd)
{
key=key.toLowerCase();
if(arrShortCuts[key]==undefined)arrShortCuts[key]=Array();
arrShortCuts[key].push(cmd);
}
this.delShortcuts=function(key){delete arrShortCuts[key];}
this.uploadInit=function(jText,toUrl,upext)
{
var jUpload=$('<span class="xheUpload"><input type="text" style="visibility:hidden;" tabindex="-1" /><input type="button" value="'+settings.upBtnText+'" class="xheBtn" tabindex="-1" /></span>'),jUpBtn=$('.xheBtn',jUpload);
var bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
jText.after(jUpload);jUpBtn.before(jText);
toUrl=toUrl.replace(/{editorRoot}/ig,editorRoot);
if(toUrl.substr(0,1)=='!')//自定義上傳管理頁
{
jUpBtn.click(function(){
bShowPanel=false;//防止按鈕面板被關閉
_this.showIframeModal('上傳文件',toUrl.substr(1),setUploadMsg,null,null,function(){bShowPanel=true;});
});
}
else
{//系統預設ajax上傳
jUpload.append('<input type="file"'+(upMultiple>1?' multiple=""':'')+' class="xheFile" size="13" name="'+uploadInputname+'" tabindex="-1" />');
var jFile=$('.xheFile',jUpload),arrMsg;
jFile.change(function(){arrMsg=[];_this.startUpload(jFile[0],toUrl,upext,setUploadMsg);});
setTimeout(function(){//拖放上傳
jText.closest('.xheDialog').bind('dragenter dragover',returnFalse).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(bHtml5Upload&&dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0)_this.startUpload(fileList,toUrl,upext,setUploadMsg);
return false;
});
},10);
}
function setUploadMsg(arrMsg)
{
if(is(arrMsg,'string'))arrMsg=[arrMsg];//允許單URL傳遞
var bImmediate=false,i,count=arrMsg.length,msg,url,arrUrl=[],onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用戶上傳回調
for(i=0;i<count;i++)
{
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!'){bImmediate=true;url=url.substr(1);}
arrUrl.push(url);
}
jText.val(arrUrl.join(' '));
if(bImmediate)jText.closest('.xheDialog').find('#xheSave').click();
}
}
this.startUpload=function(fromFiles,toUrl,limitExt,onUploadComplete)
{
var arrMsg=[],bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
var upload,fileList,filename,jUploadTip=$('<div style="padding:22px 0;text-align:center;line-height:30px;">文件上傳中,請稍候……<br /></div>'),sLoading='<img src="'+skinPath+'img/loading.gif">';
if(!bHtml5Upload||(fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0])))
{
if(!checkFileExt(fromFiles.value,limitExt))return;
jUploadTip.append(sLoading);
upload=new _this.html4Upload(fromFiles,toUrl,onUploadCallback);
}
else
{
if(!fileList)fileList=fromFiles;//拖放文件列表
var i,len=fileList.length;
if(len>upMultiple){alert('請不要一次上傳超過'+upMultiple+'個文件');return;}
for(i=0;i<len;i++)if(!checkFileExt(fileList[i].fileName,limitExt))return;
var jProgress=$('<div class="xheProgress"><div><span>0%</span></div></div>');
jUploadTip.append(jProgress);
upload=new _this.html5Upload(uploadInputname,fileList,toUrl,onUploadCallback,function(ev){
if(ev.loaded>=0)
{
var sPercent=Math.round((ev.loaded * 100) / ev.total)+'%';
$('div',jProgress).css('width',sPercent);
$('span',jProgress).text(sPercent+' ( '+formatBytes(ev.loaded)+' / '+formatBytes(ev.total)+' )');
}
else jProgress.replaceWith(sLoading);//不支持進度
});
}
var panelState=bShowPanel;
if(panelState)bShowPanel=false;//防止面板被關閉
_this.showModal('文件上傳中(Esc取消上傳)',jUploadTip,320,150,function(){bShowPanel=panelState;upload.remove();});
upload.start();
function onUploadCallback(sText,bFinish)
{
var data=Object,bOK=false;
try{data=eval('('+sText+')');}catch(ex){};
if(data.err==undefined||data.msg==undefined)alert(toUrl+' 上傳接口發生錯誤!\r\n\r\n返回的錯誤內容為: \r\n\r\n'+sText);
else
{
if(data.err)alert(data.err);
else
{
arrMsg.push(data.msg);
bOK=true;//繼續下一個文件上傳
}
}
if(!bOK||bFinish)_this.removeModal();
if(bFinish&&bOK)onUploadComplete(arrMsg);//全部上傳完成
return bOK;
}
}
this.html4Upload=function(fromfile,toUrl,callback)
{
var uid = new Date().getTime(),idIO='jUploadFrame'+uid,_this=this;
var jIO=$('<iframe name="'+idIO+'" class="xheHideArea" />').appendTo('body');
var jForm=$('<form action="'+toUrl+'" target="'+idIO+'" method="post" enctype="multipart/form-data" class="xheHideArea"></form>').appendTo('body');
var jOldFile = $(fromfile),jNewFile = jOldFile.clone().attr('disabled','true');
jOldFile.before(jNewFile).appendTo(jForm);
this.remove=function()
{
if(_this!=null)
{
jNewFile.before(jOldFile).remove();
jIO.remove();jForm.remove();
_this=null;
}
}
this.onLoad=function(){callback($(jIO[0].contentWindow.document.body).text(),true);}
this.start=function(){jForm.submit();jIO.load(_this.onLoad);}
return this;
}
this.html5Upload=function(inputname,fromFiles,toUrl,callback,onProgress)
{
var xhr,i=0,count=fromFiles.length,allLoaded=0,allSize=0,_this=this;
for(var j=0;j<count;j++)allSize+=fromFiles[j].fileSize;
this.remove=function(){if(xhr){xhr.abort();xhr=null;}}
this.uploadNext=function(sText)
{
if(sText)//當前文件上傳完成
{
allLoaded+=fromFiles[i-1].fileSize;
returnProgress(0);
}
if((!sText||(sText&&callback(sText,i==count)==true))&&i<count)postFile(fromFiles[i++],toUrl,_this.uploadNext,function(loaded){returnProgress(loaded);});
}
this.start=function(){_this.uploadNext();}
function postFile(fromfile,toUrl,callback,onProgress)
{
xhr = new XMLHttpRequest(),upload=xhr.upload;
xhr.onreadystatechange=function(){if(xhr.readyState==4)callback(xhr.responseText);};
if(upload)upload.onprogress=function(ev){onProgress(ev.loaded);};
else onProgress(-1);//不支持進度
xhr.open("POST", toUrl);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Content-Disposition', 'attachment; name="'+inputname+'"; filename="'+fromfile.fileName+'"');
if(xhr.sendAsBinary)xhr.sendAsBinary(fromfile.getAsBinary());
else xhr.send(fromfile);
}
function returnProgress(loaded){if(onProgress)onProgress({'loaded':allLoaded+loaded,'total':allSize});}
}
this.showIframeModal=function(title,ifmurl,callback,w,h,onRemove)
{
var jContent=$('<iframe frameborder="0" src="'+ifmurl.replace(/{editorRoot}/ig,editorRoot)+'" style="width:100%;height:100%;display:none;" /><div class="xheModalIfmWait"></div>'),jIframe=$(jContent[0]),jWait=$(jContent[1]);
_this.showModal(title,jContent,w,h,onRemove);
jIframe.load(function(){
var modalWin=jIframe[0].contentWindow,jModalDoc=$(modalWin.document);
modalWin.callback=function(v){_this.removeModal();callback(v);};
modalWin.unloadme=_this.removeModal;
jModalDoc.keydown(_this.checkEsc);
jIframe.show();jWait.remove();
});
}
this.showModal=function(title,content,w,h,onRemove)
{
if(bShowModal)return false;//只能彈出一個模式窗口
layerShadow=settings.layerShadow;
w=w?w:settings.modalWidth;h=h?h:settings.modalHeight;
jModal=$('<div class="xheModal" style="width:'+(w-1)+'px;height:'+h+'px;margin-left:-'+Math.ceil(w/2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+Math.ceil(h/2)+'px')+'">'+(settings.modalTitle?'<div class="xheModalTitle"><span class="xheModalClose" title="關閉 (Esc)"></span>'+title+'</div>':'')+'<div class="xheModalContent"></div></div>').appendTo('body');
jOverlay=$('<div class="xheModalOverlay"></div>').appendTo('body');
if(layerShadow>0)jModalShadow=$('<div class="xheModalShadow" style="width:'+jModal.outerWidth()+'px;height:'+jModal.outerHeight()+'px;margin-left:-'+(Math.ceil(w/2)-layerShadow-2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+(Math.ceil(h/2)-layerShadow-2)+'px')+'"></div>').appendTo('body');
$('.xheModalContent',jModal).css('height',h-(settings.modalTitle?$('.xheModalTitle').outerHeight():0)).html(content);
if(isIE&&browerVer==6.0)jHideSelect=$('select:visible').css('visibility','hidden');//隱藏覆蓋的select
$('.xheModalClose',jModal).click(_this.removeModal);
jOverlay.show();if(layerShadow>0)jModalShadow.show();jModal.show();
bShowModal=true;
onModalRemove=onRemove;
}
this.removeModal=function(){if(jHideSelect)jHideSelect.css('visibility','visible');jModal.html('').remove();if(layerShadow>0)jModalShadow.remove();jOverlay.remove();if(onModalRemove)onModalRemove();bShowModal=false;};
this.showDialog=function(content)
{
var jDialog=$('<div class="xheDialog"></div>'),jContent=$(content),jSave=$('#xheSave',jContent);
if(jSave.length==1)
{
jContent.find('input[type=text],select').keypress(function(ev){if(ev.which==13){jSave.click();return false;}});
jContent.find('textarea').keydown(function(ev){if(ev.ctrlKey&&ev.which==13){jSave.click();return false;}});
jSave.after(' <input type="button" id="xheCancel" value="取消" />');
$('#xheCancel',jContent).click(_this.hidePanel);
if(!settings.clickCancelDialog)
{
bClickCancel=false;//關閉點擊隱藏
var jFixCancel=$('<div class="xheFixCancel"></div>').appendTo('body').mousedown(returnFalse);
var xy=_jArea.offset();
jFixCancel.css({'left':xy.left,'top':xy.top,width:_jArea.outerWidth(),height:_jArea.outerHeight()})
}
jDialog.mousedown(function(){bDisableHoverExec=true;})//點擊對話框禁止懸停執行
}
jDialog.append(jContent);
_this.showPanel(jDialog);
if(!isIE)setTimeout(function(){jDialog.find('input[type=text],textarea').filter(':visible').filter(function(){return $(this).css('visibility')!='hidden';}).eq(0).focus();},10);//定位首個可見輸入表單項,延遲解決opera無法設置焦點
}
this.showPanel=function(content)
{
if(!ev.target)return false;
_jPanel.html('').append(content).css('left',-999).css('top',-999);
_jPanelButton=$(ev.target).closest('a').addClass('xheActive');
var xy=_jPanelButton.offset();
var x=xy.left,y=xy.top;y+=_jPanelButton.outerHeight()-1;
_jCntLine.css({'left':x+1,'top':y,'width':_jPanelButton.width()}).show();
if((x+_jPanel.outerWidth())>document.body.clientWidth)x-=(_jPanel.outerWidth()-_jPanelButton.outerWidth());//向左顯示面板
var layerShadow=settings.layerShadow;
if(layerShadow>0)_jShadow.css({'left':x+layerShadow,'top':y+layerShadow,'width':_jPanel.outerWidth(),'height':_jPanel.outerHeight()}).show();
_jPanel.css({'left':x,'top':y}).show();
bQuickHoverExec=bShowPanel=true;
}
this.hidePanel=function(){if(bShowPanel){_jPanelButton.removeClass('xheActive');_jShadow.hide();_jCntLine.hide();_jPanel.hide();bShowPanel=false;if(!bClickCancel){$('.xheFixCancel').remove();bClickCancel=true;};bQuickHoverExec=bDisableHoverExec=false;lastAngle=null;}}
this.exec=function(cmd)
{
_this.hidePanel();
_this.saveBookmark();
var tool=arrTools[cmd];
if(!tool)return false;//無效命令
if(ev==null)//非鼠標點擊
{
ev={};
var btn=_jTools.find('.xheButton[name='+cmd+']');
if(btn.length==1)ev.target=btn;//設置當前事件焦點
}
if(tool.e)tool.e.call(_this)//插件事件
else//內置工具
{
cmd=cmd.toLowerCase();
switch(cmd)
{
case 'cut':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的瀏覽器安全設置不允許使用剪下操作,請使用鍵盤快捷鍵(Ctrl + X)來完成');};
break;
case 'copy':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的瀏覽器安全設置不允許使用複製操作,請使用鍵盤快捷鍵(Ctrl + C)來完成');}
break;
case 'paste':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('您的瀏覽器安全設置不允許使用貼上操作,請使用鍵盤快捷鍵(Ctrl + V)來完成');}
break;
case 'pastetext':
if(window.clipboardData)_this.pasteText(window.clipboardData.getData('Text', true));
else _this.showPastetext();
break;
case 'blocktag':
var menuBlocktag=[];
$.each(arrBlocktag,function(n,v){menuBlocktag.push({s:'<'+v.n+'>'+v.t+'</'+v.n+'>',v:'<'+v.n+'>',t:v.t});});
_this.showMenu(menuBlocktag,function(v){_this._exec('formatblock',v);});
break;
case 'fontface':
var menuFontname=[];
$.each(arrFontname,function(n,v){v.c=v.c?v.c:v.n;menuFontname.push({s:'<span style="font-family:'+v.c+'">'+v.n+'</span>',v:v.c,t:v.n});});
_this.showMenu(menuFontname,function(v){_this._exec('fontname',v);});
break;
case 'fontsize':
var menuFontsize=[];
$.each(arrFontsize,function(n,v){menuFontsize.push({s:'<span style="font-size:'+v.s+';">'+v.t+'('+v.s+')</span>',v:n+1,t:v.t});});
_this.showMenu(menuFontsize,function(v){_this._exec('fontsize',v);});
break;
case 'fontcolor':
_this.showColor(function(v){_this._exec('forecolor',v);});
break;
case 'backcolor':
_this.showColor(function(v){if(isIE)_this._exec('backcolor',v);else{setCSS(true);_this._exec('hilitecolor',v);setCSS(false);}});
break;
case 'align':
_this.showMenu(menuAlign,function(v){_this._exec(v);});
break;
case 'list':
_this.showMenu(menuList,function(v){_this._exec(v);});
break;
case 'link':
_this.showLink();
break;
case 'img':
_this.showImg();
break;
case 'flash':
_this.showEmbed('Flash',htmlFlash,'application/x-shockwave-flash','clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000',' wmode="opaque" quality="high" menu="false" play="true" loop="true" allowfullscreen="true"',settings.upFlashUrl,settings.upFlashExt);
break;
case 'media':
_this.showEmbed('Media',htmlMedia,'application/x-mplayer2','clsid:6bf52a52-394a-11d3-b153-00c04f79faa6',' enablecontextmenu="false" autostart="false"',settings.upMediaUrl,settings.upMediaExt);
break;
case 'emot':
_this.showEmot();
break;
case 'table':
_this.showTable();
break;
case 'source':
_this.toggleSource();
break;
case 'preview':
_this.showPreview();
break;
case 'print':
_win.print();
break;
case 'fullscreen':
_this.toggleFullscreen();
break;
case 'about':
_this.showAbout();
break;
default:
_this._exec(cmd);
break;
}
}
ev=null;
}
this._exec=function(cmd,param,noFocus)
{
if(!noFocus)_this.focus();
var state;
if(param!=undefined)state=_doc.execCommand(cmd,false,param);
else state=_doc.execCommand(cmd,false,null);
return state;
}
function checkDblClick(ev)
{
var target=ev.target,tool=arrDbClick[target.tagName.toLowerCase()];
if(tool)
{
if(tool=='Embed')//自動識別Flash和多媒體
{
var arrEmbed={'application/x-shockwave-flash':'Flash','application/x-mplayer2':'Media'};
tool=arrEmbed[target.type.toLowerCase()];
}
_this.exec(tool);
}
}
function checkEsc(ev)
{
if(ev.which==27)
{
if(bShowModal)_this.removeModal();
else if(bShowPanel)_this.hidePanel();
return false;
}
}
function loadReset(){setTimeout(_this.setSource,10);}
function saveResult(){_this.getSource();};
function cleanPaste(ev){
if(bSource||bCleanPaste)return true;
bCleanPaste=true;//解決IE右鍵貼上重複產生paste的問題
_this.saveBookmark();
var jDiv=$('<div style="position:absolute;left:-1000px;top:'+_jWin.scrollTop()+'px;overflow:hidden;width:1px;height:1px;" />',_doc),div=jDiv[0],sel=_this.getSel(),rng=_this.getRng();
$(_doc.body).append(jDiv);
if(isIE){
rng.moveToElementText(div);
rng.execCommand('Paste');
ev.preventDefault();
}
else{
rng.selectNodeContents(div);
sel.removeAllRanges();
sel.addRange(rng);
}
setTimeout(function(){
var sPaste;
if(settings.forcePasteText===true)sPaste=jDiv.text();
else{
sPaste=div.innerHTML;
sPaste=_this.cleanHTML(sPaste);
sPaste=_this.formatXHTML(sPaste);
sPaste=_this.cleanWord(sPaste);
}
jDiv.remove();
_this.loadBookmark();
_this.pasteHTML(sPaste);
bCleanPaste=false;
},0);
}
function setCSS(css)
{
try{_this._exec('styleWithCSS',css,true);}
catch(e)
{try{_this._exec('useCSS',!css,true);}catch(e){}}
}
function setOpts()
{
if(bInit&&!bSource)
{
setCSS(false);
try{_this._exec('enableObjectResizing',true,true);}catch(e){}
//try{_this._exec('enableInlineTableEditing',false,true);}catch(e){}
if(isIE)try{_this._exec('BackgroundImageCache',true,true);}catch(e){}
}
}
function forcePtag(ev)
{
if(bSource||ev.which!=13||ev.shiftKey||ev.ctrlKey||ev.altKey)return true;
var pNode=_this.getParent('p,h1,h2,h3,h4,h5,h6,pre,address,div,li');
if(pNode.is('li'))return true;
if(settings.forcePtag){if(pNode.length==0)_this._exec('formatblock','<p>');}
else
{
_this.pasteHTML('<br />');
if(isIE&&pNode.length>0&&_this.getRng().parentElement().childNodes.length==2)_this.pasteHTML('<br />');
return false;
}
}
function fixFullHeight()
{
if(!isMozilla&&!isSafari)
{
if(bFullscreen)_jArea.height('100%').css('height',_jArea.outerHeight()-_jTools.outerHeight());
if(isIE)_jTools.hide().show();
}
}
function fixAppleSel(e)
{
e=e.target;
if(e.tagName.match(/(img|embed)/i))
{
var sel=_this.getSel(),rng=_this.getRng();
rng.selectNode(e);
sel.removeAllRanges();
sel.addRange(rng);
}
}
function xheAttr(jObj,n,v)
{
if(!n)return false;
var kn='_xhe_'+n;
if(v)//設置屬性
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
jObj.attr(n,urlBase?getLocalUrl(v,'abs',urlBase):v).removeAttr(kn).attr(kn,v);
}
return jObj.attr(kn)||jObj.attr(n);
}
function clickCancelPanel(){if(bClickCancel)_this.hidePanel();}
function checkShortcuts(event)
{
if(bSource)return true;
var code=event.which,special=specialKeys[code],sChar=special?special:String.fromCharCode(code).toLowerCase();
sKey='';
sKey+=event.ctrlKey?'ctrl+':'';sKey+=event.altKey?'alt+':'';sKey+=event.shiftKey?'shift+':'';sKey+=sChar;
var cmd=arrShortCuts[sKey],c;
for(c in cmd)
{
c=cmd[c];
if($.isFunction(c)){if(c.call(_this)===false)return false;}
else{_this.exec(c);return false;}//按鈕獨佔快捷鍵
}
}
function is(o,t)
{
var n = typeof(o);
if (!t)return n != 'undefined';
if (t == 'array' && (o.hasOwnProperty && o instanceof Array))return true;
return n == t;
}
function getLocalUrl(url,urlType,urlBase)//絕對地址:abs,根地址:root,相對地址:rel
{
var baseUrl=urlBase?$('<a href="'+urlBase+'" />')[0]:location,protocol=baseUrl.protocol,host=baseUrl.hostname,port=baseUrl.port,path=baseUrl.pathname.replace(/\\/g,'/').replace(/[^\/]+$/i,'');
port=(port=='')?'80':port;
url=$.trim(url);
if(urlType!='abs')url=url.replace(new RegExp(protocol+'\\/\\/'+host.replace(/\./g,'\\.')+'(?::'+port+')'+(port=='80'?'?':'')+'(\/|$)','i'),'/');
if(urlType=='rel')url=url.replace(new RegExp('^'+path.replace(/([\/\.\+\[\]\(\)])/g,'\\$1'),'i'),'');
if(urlType!='rel')
{
if(!url.match(/^((https?|file):\/\/|\/)/i))url=path+url;
if(url.charAt(0)=='/')//處理..
{
var arrPath=[],arrFolder = url.split('/'),folder,i,l=arrFolder.length;
for(i=0;i<l;i++)
{
folder=arrFolder[i];
if(folder=='..')arrPath.pop();
else if(folder!==''&&folder!='.')arrPath.push(folder);
}
if(arrFolder[l-1]=='')arrPath.push('');
url='/'+arrPath.join('/');
}
}
if(urlType=='abs')if(!url.match(/(https?|file):\/\//i))url=protocol+'//'+location.host+url;
return url;
}
function checkFileExt(filename,limitExt)
{
if(limitExt=='*'||filename.match(new RegExp('\.('+limitExt.replace(/,/g,'|')+')$','i')))return true;
else
{
alert('上傳文件擴展名必需為: '+limitExt);
return false;
}
}
function formatBytes(bytes)
{
var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+s[e];
}
function returnFalse(){return false;}
}
$(function(){
$.fn.oldVal=$.fn.val;
$.fn.val=function(value)
{
var _this=this,editor;
if(value===undefined)if(this[0]&&(editor=this[0].xheditor))return editor.getSource();else return _this.oldVal(value);//讀
return this.each(function(){if(editor=this.xheditor)editor.setSource(value);else _this.oldVal(value);});//寫
}
$('textarea').each(function(){
var self=$(this),xhClass=self.attr('class').match(/(?:^|\s)xheditor(?:\-(m?full|simple|mini))?(?:\s|$)/i);
if(xhClass)self.xheditor(xhClass[1]?{tools:xhClass[1]}:null);
});
});
})(jQuery); | JavaScript |
/*!
* WYSIWYG UBB Editor support for xhEditor
* @requires xhEditor
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 0.9.6 (build 100513)
*/
function ubb2html(sUBB)
{
var i,sHtml=String(sUBB),arrcode=new Array(),cnum=0;
sHtml=sHtml.replace(/&/ig, '&');
sHtml=sHtml.replace(/[<>]/g,function(c){return {'<':'<','>':'>'}[c];});
sHtml=sHtml.replace(/\r?\n/g,"<br />");
sHtml=sHtml.replace(/\[code\s*(?:=\s*([^\]]+?))?\]([\s\S]*?)\[\/code\]/ig,function(all,t,c){//code特殊处理
cnum++;arrcode[cnum]=all;
return "[\tubbcodeplace_"+cnum+"\t]";
});
sHtml=sHtml.replace(/\[(\/?)(b|u|i|s|sup|sub)\]/ig,'<$1$2>');
sHtml=sHtml.replace(/\[color\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/ig,'<font color="$1">');
sHtml=sHtml.replace(/\[size\s*=\s*(\d+?)\s*\]/ig,'<font size="$1">');
sHtml=sHtml.replace(/\[font\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/ig,'<font face="$1">');
sHtml=sHtml.replace(/\[\/(color|size|font)\]/ig,'</font>');
sHtml=sHtml.replace(/\[back\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/ig,'<span style="background-color:$1;">');
sHtml=sHtml.replace(/\[\/back\]/ig,'</span>');
for(i=0;i<3;i++)sHtml=sHtml.replace(/\[align\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\](((?!\[align(?:\s+[^\]]+)?\])[\s\S])*?)\[\/align\]/ig,'<p align="$1">$2</p>');
sHtml=sHtml.replace(/\[img\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/img\]/ig,'<img src="$1" alt="" />');
sHtml=sHtml.replace(/\[img\s*=([^,\]]*)(?:\s*,\s*(\d*%?)\s*,\s*(\d*%?)\s*)?(?:,?\s*(\w+))?\s*\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*)?\s*\[\/img\]/ig,function(all,alt,p1,p2,p3,src){
var str='<img src="'+src+'" alt="'+alt+'"',a=p3?p3:(!isNum(p1)?p1:'');
if(isNum(p1))str+=' width="'+p1+'"';
if(isNum(p2))str+=' height="'+p2+'"'
if(a)str+=' align="'+a+'"';
str+=' />';
return str;
});
sHtml=sHtml.replace(/\[emot\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\/\]/ig,'<img emot="$1" />');
sHtml=sHtml.replace(/\[url\]\s*(((?!")[\s\S])*?)(?:"[\s\S]*?)?\s*\[\/url\]/ig,'<a href="$1">$1</a>');
sHtml=sHtml.replace(/\[url\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]*?)\s*\[\/url\]/ig,'<a href="$1">$2</a>');
sHtml=sHtml.replace(/\[email\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/email\]/ig,'<a href="mailto:$1">$1</a>');
sHtml=sHtml.replace(/\[email\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]+?)\s*\[\/email\]/ig,'<a href="mailto:$1">$2</a>');
sHtml=sHtml.replace(/\[quote\]([\s\S]*?)\[\/quote\]/ig,'<blockquote>$1</blockquote>');
sHtml=sHtml.replace(/\[flash\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/flash\]/ig,function(all,w,h,url){
if(!w)w=480;if(!h)h=400;
return '<embed type="application/x-shockwave-flash" src="'+url+'" wmode="opaque" quality="high" bgcolor="#ffffff" menu="false" play="true" loop="true" width="'+w+'" height="'+h+'"/>';
});
sHtml=sHtml.replace(/\[media\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+)\s*)?)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/media\]/ig,function(all,w,h,play,url){
if(!w)w=480;if(!h)h=400;
return '<embed type="application/x-mplayer2" src="'+url+'" enablecontextmenu="false" autostart="'+(play=='1'?'true':'false')+'" width="'+w+'" height="'+h+'"/>';
});
sHtml=sHtml.replace(/\[table\s*(?:=\s*(\d{1,4}%?)\s*(?:,\s*([^\]"]+)(?:"[^\]]*?)?)?)?\s*\]/ig,function(all,w,b){
var str='<table';
if(w)str+=' width="'+w+'"';
if(b)str+=' bgcolor="'+b+'"';
return str+'>';
});
sHtml=sHtml.replace(/\[tr\s*(?:=\s*([^\]"]+?)(?:"[^\]]*?)?)?\s*\]/ig,function(all,bg){
return '<tr'+(bg?' bgcolor="'+bg+'"':'')+'>';
});
sHtml=sHtml.replace(/\[td\s*(?:=\s*(\d{1,2})\s*,\s*(\d{1,2})\s*(?:,\s*(\d{1,4}%?))?)?\s*\]/ig,function(all,col,row,w){
return '<td'+(col>1?' colspan="'+col+'"':'')+(row>1?' rowspan="'+row+'"':'')+(w?' width="'+w+'"':'')+'>';
});
sHtml=sHtml.replace(/\[\/(table|tr|td)\]/ig,'</$1>');
sHtml=sHtml.replace(/\[\*\]((?:(?!\[\*\]|\[\/list\]|\[list\s*(?:=[^\]]+)?\])[\s\S])+)/ig,'<li>$1</li>');
sHtml=sHtml.replace(/\[list\s*(?:=\s*([^\]"]+?)(?:"[^\]]*?)?)?\s*\]/ig,function(all,type){
var str='<ul';
if(type)str+=' type="'+type+'"';
return str+'>';
});
sHtml=sHtml.replace(/\[\/list\]/ig,'</ul>');
for(i=1;i<=cnum;i++)sHtml=sHtml.replace("[\tubbcodeplace_"+i+"\t]", arrcode[i]);
sHtml=sHtml.replace(/(^|<\/?\w+(?:\s+[^>]*?)?>)([^<$]+)/ig, function(all,tag,text){
return tag+text.replace(/[\t ]/g,function(c){return {'\t':' ',' ':' '}[c];});
});
function isNum(s){if(s!=null&&s!='')return !isNaN(s);else return false;}
return sHtml;
}
function html2ubb(sHtml)
{
var mapSize={'xx-small':1,'8pt':1,'x-small':2,'10pt':2,'small':3,'12pt':3,'medium':4,'14pt':4,'large':5,'18pt':5,'x-large':6,'24pt':6,'xx-large':7,'36pt':7};
var regSrc=/\s+src\s*=\s*(["']?)\s*(.+?)\s*\1(\s|$)/i,regWidth=/\s+width\s*=\s*(["']?)\s*(\d+(?:\.\d+)?%?)\s*\1(\s|$)/i,regHeight=/\s+height\s*=\s*(["']?)\s*(\d+(?:\.\d+)?%?)\s*\1(\s|$)/i,regBg=/(?:background|background-color|bgcolor)\s*[:=]\s*(["']?)\s*((rgb\s*\(\s*\d{1,3}%?,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*\))|(#[0-9a-f]{3,6})|([a-z]{1,20}))\s*\1/i
var i,sUBB=String(sHtml),arrcode=new Array(),cnum=0;
sUBB=sUBB.replace(/\s*\r?\n\s*/g,'');
sUBB = sUBB.replace(/<(script|style)(\s+[^>]*?)?>[\s\S]*?<\/\1>/ig, '');
sUBB = sUBB.replace(/<!--[\s\S]*?-->/ig,'');
sUBB=sUBB.replace(/<br\s*?\/?>/ig,"\r\n");
sUBB=sUBB.replace(/\[code\s*(=\s*([^\]]+?))?\]([\s\S]*?)\[\/code\]/ig,function(all,t,c){//code特殊处理
cnum++;arrcode[cnum]=all;
return "[\tubbcodeplace_"+cnum+"\t]";
});
sUBB=sUBB.replace(/<(\/?)(b|u|i|s)(\s+[^>]*?)?>/ig,'[$1$2]');
sUBB=sUBB.replace(/<(\/?)strong(\s+[^>]*?)?>/ig,'[$1b]');
sUBB=sUBB.replace(/<(\/?)em(\s+[^>]*?)?>/ig,'[$1i]');
sUBB=sUBB.replace(/<(\/?)(strike|del)(\s+[^>]*?)?>/ig,'[$1s]');
sUBB=sUBB.replace(/<(\/?)(sup|sub)(\s+[^>]*?)?>/ig,'[$1$2]');
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color|background|background-color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,function(all,tag,style,content){
var face=style.match(/(?:^|;)\s*font-family\s*:\s*([^;]+)/i),size=style.match(/(?:^|;)\s*font-size\s*:\s*([^;]+)/i),color=style.match(/(?:^|;)\s*color\s*:\s*([^;]+)/i),back=style.match(/(?:^|;)\s*(?:background|background-color)\s*:\s*([^;]+)/i),str=content;
if(face)str='[font='+face[1]+']'+str+'[/font]';
if(size)
{
size=mapSize[size[1].toLowerCase()];
if(size)str='[size='+size+']'+str+'[/size]';
}
if(color)str='[color='+formatColor(color[1])+']'+str+'[/color]';
if(back)str='[back='+formatColor(back[1])+']'+str+'[/back]';
return str;
});
function formatColor(c)
{
var matchs;
if(matchs=c.match(/\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)){c=(matchs[1]*65536+matchs[2]*256+matchs[3]*1).toString(16);while(c.length<6)c='0'+c;c='#'+c;}
c=c.replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,'#$1$1$2$2$3$3');
return c;
}
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(div|p)(?:\s+[^>]*?)?[\s"';]\s*(?:text-)?align\s*[=:]\s*(["']?)\s*(left|center|right)\s*\2[^>]*>(((?!<\1(\s+[^>]*?)?>)[\s\S])+?)<\/\1>/ig,'[align=$3]$4[/align]');
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(center)(?:\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,'[align=center]$2[/align]');
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(p|div)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*text-align\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,function(all,tag,style,content){
});
sUBB=sUBB.replace(/<a(?:\s+[^>]*?)?\s+href=(["'])\s*(.+?)\s*\1[^>]*>\s*([\s\S]*?)\s*<\/a>/ig,function(all,q,url,text){
if(!(url&&text))return '';
var tag='url',str;
if(url.match(/^mailto:/i))
{
tag='email';
url=url.replace(/mailto:(.+?)/i,'$1');
}
str='['+tag;
if(url!=text)str+='='+url;
return str+']'+text+'[/'+tag+']';
});
sUBB=sUBB.replace(/<img(\s+[^>]*?)\/?>/ig,function(all,attr){
var emot=attr.match(/\s+emot\s*=\s*(["']?)\s*(.+?)\s*\1(\s|$)/i);
if(emot)return '[emot='+emot[2]+'/]';
var url=attr.match(regSrc),alt=attr.match(/\s+alt\s*=\s*(["']?)\s*(.*?)\s*\1(\s|$)/i),w=attr.match(regWidth),h=attr.match(regHeight),align=attr.match(/\s+align\s*=\s*(["']?)\s*(\w+)\s*\1(\s|$)/i),str='[img',p='';
if(!url)return '';
p+=alt[2];
if(w||h)p+=','+(w?w[2]:'')+','+(h?h[2]:'');
if(align)p+=','+align[2];
if(p)str+='='+p;
str+=']'+url[2]+'[/img]';
return str;
});
sUBB=sUBB.replace(/<blockquote(?:\s+[^>]*?)?>([\s\S]+?)<\/blockquote>/ig,'[quote]$1[/quote]');
sUBB=sUBB.replace(/<embed((?:\s+[^>]*?)?(?:\s+type\s*=\s*"\s*application\/x-shockwave-flash\s*"|\s+classid\s*=\s*"\s*clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000\s*")[^>]*?)\/>/ig,function(all,attr){
var url=attr.match(regSrc),w=attr.match(regWidth),h=attr.match(regHeight),str='[flash';
if(!url)return '';
if(w&&h)str+='='+w[2]+','+h[2];
str+=']'+url[2];
return str+'[/flash]';
});
sUBB=sUBB.replace(/<embed((?:\s+[^>]*?)?(?:\s+type\s*=\s*"\s*application\/x-mplayer2\s*"|\s+classid\s*=\s*"\s*clsid:6bf52a52-394a-11d3-b153-00c04f79faa6\s*")[^>]*?)\/>/ig,function(all,attr){
var url=attr.match(regSrc),w=attr.match(regWidth),h=attr.match(regHeight),p=attr.match(/\s+autostart\s*=\s*(["']?)\s*(.+?)\s*\1(\s|$)/i),str='[media',auto='0';
if(!url)return '';
if(p)if(p[2]=='true')auto='1';
if(w&&h)str+='='+w[2]+','+h[2]+','+auto;
str+=']'+url[2];
return str+'[/media]';
});
sUBB=sUBB.replace(/<table(\s+[^>]*?)?>/ig,function(all,attr){
var str='[table';
if(attr)
{
var w=attr.match(regWidth),b=attr.match(regBg);
if(w)
{
str+='='+w[2];
if(b)str+=','+b[2];
}
}
return str+']';
});
sUBB=sUBB.replace(/<tr(\s+[^>]*?)?>/ig,function(all,attr){
var str='[tr';
if(attr)
{
var bg=attr.match(regBg)
if(bg)str+='='+bg[2];
}
return str+']';
});
sUBB=sUBB.replace(/<(?:th|td)(\s+[^>]*?)?>/ig,function(all,attr){
var str='[td';
if(attr)
{
var col=attr.match(/\s+colspan\s*=\s*(["']?)\s*(\d+)\s*\1(\s|$)/i),row=attr.match(/\s+rowspan\s*=\s*(["']?)\s*(\d+)\s*\1(\s|$)/i),w=attr.match(regWidth);
col=col?col[2]:1;
row=row?row[2]:1;
if(col>1||row>1||w)str+='='+col+','+row;
if(w)str+=','+w[2];
}
return str+']';
});
sUBB=sUBB.replace(/<\/(table|tr)>/ig,'[/$1]');
sUBB=sUBB.replace(/<\/(th|td)>/ig,'[/td]');
sUBB=sUBB.replace(/<ul(\s+[^>]*?)?>/ig,function(all,attr){
var t;
if(attr)t=attr.match(/\s+type\s*=\s*(["']?)\s*(.+?)\s*\1(\s|$)/i);
return '[list'+(t?'='+t[2]:'')+']';
});
sUBB=sUBB.replace(/<ol(\s+[^>]*?)?>/ig,'[list=1]');
sUBB=sUBB.replace(/<li(\s+[^>]*?)?>/ig,'[*]');
sUBB=sUBB.replace(/<\/li>/ig,'');
sUBB=sUBB.replace(/<\/(ul|ol)>/ig,'[/list]');
sUBB=sUBB.replace(/<h([1-6])(\s+[^>]*?)?>/ig,function(all,n){return '\r\n\r\n[size='+(7-n)+'][b]'});
sUBB=sUBB.replace(/<\/h[1-6]>/ig,'[/b][/size]\r\n\r\n');
sUBB=sUBB.replace(/<address(\s+[^>]*?)?>/ig,'\r\n[i]');
sUBB=sUBB.replace(/<\/address>/ig,'[i]\r\n');
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(p)(?:\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,"\r\n\r\n$2\r\n\r\n");
for(i=0;i<3;i++)sUBB=sUBB.replace(/<(div)(?:\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,"\r\n$2\r\n");
sUBB=sUBB.replace(/((\s| )*\r?\n){3,}/g,"\r\n\r\n");//限制最多2次换行
sUBB=sUBB.replace(/^((\s| )*\r?\n)+/g,'');//清除开头换行
sUBB=sUBB.replace(/((\s| )*\r?\n)+$/g,'');//清除结尾换行
for(i=1;i<=cnum;i++)sUBB=sUBB.replace("[\tubbcodeplace_"+i+"\t]", arrcode[i]);
sUBB=sUBB.replace(/<[^<>]+?>/g,'');//删除所有HTML标签
sUBB=sUBB.replace(/</ig, '<');
sUBB=sUBB.replace(/>/ig, '>');
sUBB=sUBB.replace(/ /ig, ' ');
sUBB=sUBB.replace(/&/ig, '&');
return sUBB;
} | JavaScript |
/*!
* xhEditor - WYSIWYG XHTML Editor
* @requires jQuery v1.4.2
*
* @author Yanis.Wang<yanis.wang@gmail.com>
* @site http://xheditor.com/
* @licence LGPL(http://www.opensource.org/licenses/lgpl-license.php)
*
* @Version: 1.1.1 (build 101002)
*/
(function($){
if($.xheditor)return false;//防止JS重复加载
$.fn.xheditor=function(options)
{
var arrSuccess=[];
this.each(function(){
if(!$.nodeName(this,'TEXTAREA'))return;
if(options===false)//卸载
{
if(this.xheditor)
{
this.xheditor.remove();
this.xheditor=null;
}
}
else//初始化
{
if(!this.xheditor)
{
var tOptions=/({.*})/.exec($(this).attr('class'));
if(tOptions)
{
try{tOptions=eval('('+tOptions[1]+')');}catch(ex){};
options=$.extend({},tOptions,options );
}
var editor=new $.xheditor(this,options);
if(editor.init())
{
this.xheditor=editor;
arrSuccess.push(editor);
}
else editor=null;
}
else arrSuccess.push(this.xheditor);
}
});
if(arrSuccess.length==0)arrSuccess=false;
if(arrSuccess.length==1)arrSuccess=arrSuccess[0];
return arrSuccess;
}
var xCount=0,browerVer=$.browser.version,isIE=$.browser.msie,isMozilla=$.browser.mozilla,isSafari=$.browser.safari,isOpera=$.browser.opera,bShowPanel=false,bClickCancel=true,bShowModal=false,bCheckEscInit=false;
var _jPanel,_jShadow,_jCntLine,_jPanelButton;
var jModal,jModalShadow,layerShadow,jOverlay,jHideSelect,onModalRemove;
var editorRoot;
$('script[src*=xheditor]').each(function(){
var s=this.src;
if(s.match(/xheditor[^\/]*\.js/i)){editorRoot=s.replace(/[\?#].*$/, '').replace(/(^|[\/\\])[^\/]*$/, '$1');return false;}
});
var specialKeys={ 27: 'esc', 9: 'tab', 32:'space', 13: 'enter', 8:'backspace', 145: 'scroll',
20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',
35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down',
112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12' };
var itemColors=['#FFFFFF','#CCCCCC','#C0C0C0','#999999','#666666','#333333','#000000','#FFCCCC','#FF6666','#FF0000','#CC0000','#990000','#660000','#330000','#FFCC99','#FF9966','#FF9900','#FF6600','#CC6600','#993300','#663300','#FFFF99','#FFFF66','#FFCC66','#FFCC33','#CC9933','#996633','#663333','#FFFFCC','#FFFF33','#FFFF00','#FFCC00','#999900','#666600','#333300','#99FF99','#66FF99','#33FF33','#33CC00','#009900','#006600','#003300','#99FFFF','#33FFFF','#66CCCC','#00CCCC','#339999','#336666','#003333','#CCFFFF','#66FFFF','#33CCFF','#3366FF','#3333FF','#000099','#000066','#CCCCFF','#9999FF','#6666CC','#6633FF','#6600CC','#333399','#330099','#FFCCFF','#FF99FF','#CC66CC','#CC33CC','#993399','#663366','#330033'];
var arrBlocktag=[{n:'p',t:'Paragraph'},{n:'h1',t:'Heading 1'},{n:'h2',t:'Heading 2'},{n:'h3',t:'Heading 3'},{n:'h4',t:'Heading 4'},{n:'h5',t:'Heading 5'},{n:'h6',t:'Heading 6'},{n:'pre',t:'Preformatted'},{n:'address',t:'Address'}];
var arrFontname=[{n:'Arial'},{n:'Arial Narrow'},{n:'Arial Black'},{n:'Comic Sans MS'},{n:'Courier New'},{n:'System'},{n:'Times New Roman'},{n:'Tahoma'},{n:'Verdana'}];
var arrFontsize=[{n:'xx-small',wkn:'x-small',s:'8pt',t:'xx-small'},{n:'x-small',wkn:'small',s:'10pt',t:'x-small'},{n:'small',wkn:'medium',s:'12pt',t:'small'},{n:'medium',wkn:'large',s:'14pt',t:'medium'},{n:'large',wkn:'x-large',s:'18pt',t:'large'},{n:'x-large',wkn:'xx-large',s:'24pt',t:'x-large'},{n:'xx-large',wkn:'-webkit-xxx-large',s:'36pt',t:'xx-large'}];
var menuAlign=[{s:'Align left',v:'justifyleft',t:'Align left'},{s:'Align center',v:'justifycenter',t:'Align center'},{s:'Align right',v:'justifyright',t:'Align right'},{s:'Align full',v:'justifyfull',t:'Align full'}],menuList=[{s:'Ordered list',v:'insertOrderedList',t:'Ordered list'},{s:'Unordered list',v:'insertUnorderedList',t:'Unordered list'}];
var htmlPastetext='<div>Use Ctrl+V on your keyboard to paste the text.</div><div><textarea id="xhePastetextValue" wrap="soft" spellcheck="false" style="width:300px;height:100px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlLink='<div>Link URL: <input type="text" id="xheLinkUrl" value="http://" class="xheText" /></div><div>Target: <select id="xheLinkTarget"><option selected="selected" value="">Default</option><option value="_blank">New window</option><option value="_self">Same window</option><option value="_parent">Parent window</option></select></div><div style="display:none">Link Text:<input type="text" id="xheLinkText" value="" class="xheText" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlImg='<div>Img URL: <input type="text" id="xheImgUrl" value="http://" class="xheText" /></div><div>Alt text: <input type="text" id="xheImgAlt" /></div><div>Alignment:<select id="xheImgAlign"><option selected="selected" value="">Default</option><option value="left">Left</option><option value="right">Right</option><option value="top">Top</option><option value="middle">Middle</option><option value="baseline">Baseline</option><option value="bottom">Bottom</option></select></div><div>Dimension:<input type="text" id="xheImgWidth" style="width:40px;" /> x <input type="text" id="xheImgHeight" style="width:40px;" /></div><div>Border: <input type="text" id="xheImgBorder" style="width:40px;" /></div><div>Hspace: <input type="text" id="xheImgHspace" style="width:40px;" /> Vspace:<input type="text" id="xheImgVspace" style="width:40px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlFlash='<div>Flash URL:<input type="text" id="xheFlashUrl" value="http://" class="xheText" /></div><div>Dimension:<input type="text" id="xheFlashWidth" style="width:40px;" value="480" /> x <input type="text" id="xheFlashHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlMedia='<div>Media URL:<input type="text" id="xheMediaUrl" value="http://" class="xheText" /></div><div>Dimension:<input type="text" id="xheMediaWidth" style="width:40px;" value="480" /> x <input type="text" id="xheMediaHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlTable='<div>Rows&Cols: <input type="text" id="xheTableRows" style="width:40px;" value="3" /> x <input type="text" id="xheTableColumns" style="width:40px;" value="2" /></div><div>Headers: <select id="xheTableHeaders"><option selected="selected" value="">None</option><option value="row">First row</option><option value="col">First column</option><option value="both">Both</option></select></div><div>Dimension: <input type="text" id="xheTableWidth" style="width:40px;" value="200" /> x <input type="text" id="xheTableHeight" style="width:40px;" value="" /></div><div>Border: <input type="text" id="xheTableBorder" style="width:40px;" value="1" /></div><div>CellSpacing:<input type="text" id="xheTableCellSpacing" style="width:40px;" value="1" /> CellPadding:<input type="text" id="xheTableCellPadding" style="width:40px;" value="1" /></div><div>Align: <select id="xheTableAlign"><option selected="selected" value="">Default</option><option value="left">Left</option><option value="center">Center</option><option value="right">Right</option></select></div><div>Caption: <input type="text" id="xheTableCaption" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="OK" /></div>';
var htmlAbout='<div style="font:12px Arial;width:245px;word-wrap:break-word;word-break:break-all;"><p><span style="font-size:20px;color:#1997DF;">xhEditor</span><br />v1.1.1 (build 101002)</p><p>xhEditor is a platform independent WYSWYG XHTML editor based by jQuery,released as Open Source under <a href="http://www.gnu.org/licenses/lgpl.html" target="_blank">LGPL</a>.</p><p>Copyright © <a href="http://xheditor.com/" target="_blank">xhEditor.com</a>. All rights reserved.</p></div>';
var itemEmots={'default':{name:'Default',width:24,height:24,line:7,list:{'smile':'Smile','tongue':'Tongue','titter':'Titter','laugh':'Laugh','sad':'Sad','wronged':'Wronged','fastcry':'Fast cry','cry':'Cry','wail':'Wail','mad':'Mad','knock':'Knock','curse':'Curse','crazy':'Crazy','angry':'Angry','ohmy':'Oh my','awkward':'Awkward','panic':'Panic','shy':'Shy','cute':'Cute','envy':'Envy','proud':'Proud','struggle':'Struggle','quiet':'Quiet','shutup':'Shut up','doubt':'Doubt','despise':'Despise','sleep':'Sleep','bye':'Bye'}}};
var arrTools={Cut:{t:'Cut (Ctrl+X)'},Copy:{t:'Copy (Ctrl+C)'},Paste:{t:'Paste (Ctrl+V)'},Pastetext:{t:'Paste as plain text',h:isIE?0:1},Blocktag:{t:'Block tag',h:1},Fontface:{t:'Font family',h:1},FontSize:{t:'Font size',h:1},Bold:{t:'Bold (Ctrl+B)',s:'Ctrl+B'},Italic:{t:'Italic (Ctrl+I)',s:'Ctrl+I'},Underline:{t:'Underline (Ctrl+U)',s:'Ctrl+U'},Strikethrough:{t:'Strikethrough (Ctrl+S)',s:'Ctrl+S'},FontColor:{t:'Select text color',h:1},BackColor:{t:'Select background color',h:1},SelectAll:{t:'SelectAll (Ctrl+A)'},Removeformat:{t:'Remove formatting'},Align:{t:'Align',h:1},List:{t:'List',h:1},Outdent:{t:'Outdent (Shift+Tab)',s:'Shift+Tab'},Indent:{t:'Indent (Tab)',s:'Tab'},Link:{t:'Insert/edit link (Ctrl+K)',s:'Ctrl+K',h:1},Unlink:{t:'Unlink'},Img:{t:'Insert/edit image',h:1},Flash:{t:'Insert/edit flash',h:1},Media:{t:'Insert/edit media',h:1},Emot:{t:'Emotions',s:'ctrl+e',h:1},Table:{t:'Insert a new table',h:1},Source:{t:'Edit source code'},Preview:{t:'Preview'},Print:{t:'Print (Ctrl+P)',s:'Ctrl+P'},Fullscreen:{t:'Toggle fullscreen (Esc)',s:'Esc'},About:{t:'About xhEditor'}};
var toolsThemes={
mini:'Bold,Italic,Underline,Strikethrough,|,Align,List,|,Link,Img',
simple:'Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,|,Align,List,Outdent,Indent,|,Link,Img,Emot',
full:'Cut,Copy,Paste,Pastetext,|,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,SelectAll,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Img,Flash,Media,Emot,Table,|,Source,Preview,Print,Fullscreen'};
toolsThemes.mfull=toolsThemes.full.replace(/\|(,Align)/i,'/$1');
var arrDbClick={'a':'Link','img':'Img','embed':'Embed'},uploadInputname='filedata';
$.xheditor=function(textarea,options)
{
var defaults={skin:'default',tools:'full',clickCancelDialog:true,linkTag:false,internalScript:false,inlineScript:false,internalStyle:true,inlineStyle:true,showBlocktag:false,forcePtag:true,upLinkExt:"zip,rar,txt",upImgExt:"jpg,jpeg,gif,png",upFlashExt:"swf",upMediaExt:"wmv,avi,wma,mp3,mid",modalWidth:350,modalHeight:220,modalTitle:true,defLinkText:'Click to open link',layerShadow:3,emotMark:false,upBtnText:'Upload',wordDeepClean:true,hoverExecDelay:100,html5Upload:true,upMultiple:99};
var _this=this,_text=textarea,_jText=$(_text),_jForm=_jText.closest('form'),_jTools,_jArea,_win,_jWin,_doc,_jDoc;
var bookmark;
var bInit=false,bSource=false,bFullscreen=false,bCleanPaste=false,outerScroll,bShowBlocktag=false,sLayoutStyle='',ev=null,timer,bDisableHoverExec=false,bQuickHoverExec=false;
var lastPoint=null,lastAngle=null;//鼠标悬停显示
var editorHeight=0;
var settings=_this.settings=$.extend({},defaults,options );
var plugins=settings.plugins,strPlugins=[];
if(plugins)
{
arrTools=$.extend({},arrTools,plugins);
$.each(plugins,function(n){strPlugins.push(n);});
strPlugins=strPlugins.join(',');
}
if(settings.tools.match(/^\s*(m?full|simple|mini)\s*$/i))
{
var toolsTheme=toolsThemes[$.trim(settings.tools)];
settings.tools=(settings.tools.match(/m?full/i)&&plugins)?toolsTheme.replace('Table','Table,'+strPlugins):toolsTheme;//插件接在full的Table后面
}
if(!settings.tools.match(/(^|,)\s*About\s*(,|$)/i))settings.tools+=',About';
settings.tools=settings.tools.split(',');
if(settings.editorRoot)editorRoot=settings.editorRoot;
editorRoot=getLocalUrl(editorRoot,'abs');
//基本控件名
var idCSS='xheCSS_'+settings.skin,idContainer='xhe'+xCount+'_container',idTools='xhe'+xCount+'_Tool',idIframeArea='xhe'+xCount+'_iframearea',idIframe='xhe'+xCount+'_iframe',idFixFFCursor='xhe'+xCount+'_fixffcursor';
var headHTML='',bodyClass='',skinPath=editorRoot+'xheditor_skin/'+settings.skin+'/',arrEmots=itemEmots,urlType=settings.urlType,urlBase=settings.urlBase,emotPath=settings.emotPath,emotPath=emotPath?emotPath:editorRoot+'xheditor_emot/',selEmotGroup='';
arrEmots=$.extend({},arrEmots,settings.emots);
emotPath=getLocalUrl(emotPath,'rel',urlBase?urlBase:null);//返回最短表情路径
bShowBlocktag=settings.showBlocktag;
if(bShowBlocktag)bodyClass+=' showBlocktag';
var arrShortCuts=[];
this.init=function()
{
//加载样式表
if($('#'+idCSS).length==0)$('head').append('<link id="'+idCSS+'" rel="stylesheet" type="text/css" href="'+skinPath+'ui.css" />');
//初始化编辑器
var cw = settings.width || _text.style.width || _jText.outerWidth();
editorHeight = settings.height || _text.style.height || _jText.outerHeight();
if(is(editorHeight,'string'))editorHeight=editorHeight.replace(/[^\d]+/g,'');
if(cw<=0||editorHeight<=0)//禁止对隐藏区域里的textarea初始化编辑器
{
alert('Current textarea is hidden, please make it show before initialization xhEditor, or directly initialize the height.');
return false;
}
if(/^[0-9\.]+$/i.test(''+cw))cw+='px';
//编辑器CSS背景
var editorBackground=settings.background || _text.style.background;
//工具栏内容初始化
var arrToolsHtml=['<span class="xheGStart"/>'],tool,cn,regSeparator=/\||\//i;
$.each(settings.tools,function(i,n)
{
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGEnd"/>');
if(n=='|')arrToolsHtml.push('<span class="xheSeparator"/>');
else if(n=='/')arrToolsHtml.push('<br />');
else
{
tool=arrTools[n];
if(!tool)return;
if(tool.c)cn=tool.c;
else cn='xheIcon xheBtn'+n;
arrToolsHtml.push('<span><a href="javascript:void(0);" title="'+tool.t+'" name="'+n+'" class="xheButton xheEnabled" tabindex="-1"><span class="'+cn+'" unselectable="on" /></a></span>');
if(tool.s)_this.addShortcuts(tool.s,n);
}
if(n.match(regSeparator))arrToolsHtml.push('<span class="xheGStart"/>');
});
arrToolsHtml.push('<span class="xheGEnd"/><br />');
_jText.after($('<input type="text" id="'+idFixFFCursor+'" style="position:absolute;display:none;" /><span id="'+idContainer+'" class="xhe_'+settings.skin+'" style="display:none"><table cellspacing="0" cellpadding="0" class="xheLayout" style="width:'+cw+';height:'+editorHeight+'px;"><tbody><tr><td id="'+idTools+'" class="xheTool" unselectable="on" style="height:1px;"></td></tr><tr><td id="'+idIframeArea+'" class="xheIframeArea"><iframe frameborder="0" id="'+idIframe+'" src="javascript:;" style="width:100%;"></iframe></td></tr></tbody></table></span>'));
_jTools=$('#'+idTools);_jArea=$('#'+idIframeArea);
headHTML='<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><link rel="stylesheet" href="'+skinPath+'iframe.css"/>';
var loadCSS=settings.loadCSS;
if(loadCSS)
{
if(is(loadCSS,'array'))for(var i in loadCSS)headHTML+='<link rel="stylesheet" href="'+loadCSS[i]+'"/>';
else
{
if(loadCSS.match(/\s*<style(\s+[^>]*?)?>[\s\S]+?<\/style>\s*/i))headHTML+=loadCSS;
else headHTML+='<link rel="stylesheet" href="'+loadCSS+'"/>';
}
}
var iframeHTML='<html><head>'+headHTML;
if(editorBackground)iframeHTML+='<style>body{background:'+editorBackground+';}</style>';
iframeHTML+='</head><body spellcheck="false" class="editMode'+bodyClass+'"></body></html>';
_this.win=_win=$('#'+idIframe)[0].contentWindow;
_jWin=$(_win);
try{
this.doc=_doc = _win.document;_jDoc=$(_doc);
_doc.open();
_doc.write(iframeHTML);
_doc.close();
if(isIE)_doc.body.contentEditable='true';
else _doc.designMode = 'On';
}catch(e){}
setTimeout(setOpts,300);
_this.setSource();
_win.setInterval=null;//针对jquery 1.3无法操作iframe window问题的hack
//添加工具栏
_jTools.append(arrToolsHtml.join('')).bind('mousedown contextmenu',returnFalse).click(function(event)
{
var jButton=$(event.target).closest('a');
if(jButton.is('.xheEnabled'))
{
ev=event;
_this.exec(jButton.attr('name'));
}
return false;
});
_jTools.find('.xheButton').hover(function(event){//鼠标悬停执行
var jButton=$(this),delay=settings.hoverExecDelay;
var tAngle=lastAngle;lastAngle=null;
if(delay==-1||bDisableHoverExec||!jButton.is('.xheEnabled'))return false;
if(tAngle&&tAngle>10)//检测误操作
{
bDisableHoverExec=true;
setTimeout(function(){bDisableHoverExec=false;},100);
return false;
}
var cmd=jButton.attr('name'),bHover=arrTools[cmd].h==1;
if(!bHover)
{
_this.hidePanel();//移到非悬停按钮上隐藏面板
return false;
}
if(bQuickHoverExec)delay=0;
if(delay>=0)timer=setTimeout(function(){
ev=event;
lastPoint={x:ev.clientX,y:ev.clientY};
_this.exec(cmd);
},delay);
},function(event){lastPoint=null;if(timer)clearTimeout(timer);}).mousemove(function(event){
if(lastPoint)
{
var diff={x:event.clientX-lastPoint.x,y:event.clientY-lastPoint.y};
if(Math.abs(diff.x)>1||Math.abs(diff.y)>1)
{
if(diff.x>0&&diff.y>0)
{
var tAngle=Math.round(Math.atan(diff.y/diff.x)/0.017453293);
if(lastAngle)lastAngle=(lastAngle+tAngle)/2
else lastAngle=tAngle;
}
else lastAngle=null;
lastPoint={x:event.clientX,y:event.clientY};
}
}
});
//初始化面板
_jPanel=$('#xhePanel');
_jShadow=$('#xheShadow');
_jCntLine=$('#xheCntLine');
if(_jPanel.length==0)
{
_jPanel=$('<div id="xhePanel"></div>').mousedown(function(ev){ev.stopPropagation()});
_jShadow=$('<div id="xheShadow"></div>');
_jCntLine=$('<div id="xheCntLine"></div>');
setTimeout(function(){
$(document.body).append(_jPanel).append(_jShadow).append(_jCntLine);
},10);
}
//切换显示区域
$('#'+idContainer).show();
_jText.hide();
_jArea.css('height',editorHeight-_jTools.outerHeight());
//绑定内核事件
_jText.focus(_this.focus);
_jForm.submit(saveResult).bind('reset', loadReset);
$(window).bind('unload beforeunload',saveResult).bind('resize',fixFullHeight);
$(document).mousedown(clickCancelPanel);
if(!bCheckEscInit){$(document).keydown(checkEsc);bCheckEscInit=true;}
_jWin.focus(function(){if(settings.focus)settings.focus();}).blur(function(){if(settings.blur)settings.blur();});
if(isSafari)_jWin.click(fixAppleSel);
_jDoc.mousedown(clickCancelPanel).keydown(checkShortcuts).keypress(forcePtag).dblclick(checkDblClick).bind('mousedown click',function(ev){_jText.trigger(ev.type);});
if(isIE)
{
//IE控件上Backspace会导致页面后退
_jDoc.keydown(function(ev){var rng=_this.getRng();if(ev.which==8&&rng.item){$(rng.item(0)).remove();return false;}});
//修正IE拖动img大小不更新width和height属性值的问题
function fixResize(ev)
{
var jImg=$(ev.target),v;
if(v=jImg.css('width'))jImg.css('width','').attr('width',v.replace(/[^0-9%]+/g, ''));
if(v=jImg.css('height'))jImg.css('height','').attr('height',v.replace(/[^0-9%]+/g, ''));
}
_jDoc.bind('controlselect',function(ev){
ev=ev.target;if(!$.nodeName(ev,'IMG'))return;
$(ev).unbind('resizeend',fixResize).bind('resizeend',fixResize);
});
}
var jBody=$(_doc.documentElement);
jBody.bind('paste',cleanPaste);
if(settings.disableContextmenu)jBody.bind('contextmenu',returnFalse);
//HTML5编辑区域直接拖放上传
if(settings.html5Upload)jBody.bind('dragenter dragover',function(ev){var types;if((types=ev.originalEvent.dataTransfer.types)&&$.inArray('Files', types)!=-1)return false;}).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0){
var i,cmd,arrCmd=['Link','Img','Flash','Media'],arrExt=[],strExt;
for(i in arrCmd){
cmd=arrCmd[i];
if(settings['up'+cmd+'Url']&&settings['up'+cmd+'Url'].match(/^[^!].*/i))arrExt.push(cmd+':,'+settings['up'+cmd+'Ext']);//允许上传
}
if(arrExt.length==0)return false;//禁止上传
else strExt=arrExt.join(',');
function getCmd(fileList){
var match,fileExt,cmd;
for(i=0;i<fileList.length;i++){
fileExt=fileList[i].fileName.replace(/.+\./,'');
if(match=strExt.match(new RegExp('(\\w+):[^:]*,'+fileExt+'(?:,|$)','i'))){
if(!cmd)cmd=match[1];
else if(cmd!=match[1])return 2;
}
else return 1;
}
return cmd;
}
cmd=getCmd(fileList);
if(cmd==1)alert('Upload file extension required for this: '+strExt.replace(/\w+:,/g,''));
else if(cmd==2)alert('You can only drag and drop the same type of file.');
else if(cmd){
_this.startUpload(fileList,settings['up'+cmd+'Url'],'*',function(arrMsg){
var arrUrl=[],msg,onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用户上传回调
for(i in arrMsg){
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!')url=url.substr(1);
arrUrl.push(url);
}
_this.exec(cmd);
$('#xhe'+cmd+'Url').val(arrUrl.join(' '));
$('#xheSave').click();
});
}
return false;
}
});
//添加用户快捷键
var shortcuts=settings.shortcuts;
if(shortcuts)$.each(shortcuts,function(key,func){_this.addShortcuts(key,func);});
xCount++;
bInit=true;
if(settings.fullscreen)_this.toggleFullscreen();
else if(settings.sourceMode)setTimeout(_this.toggleSource,20);
return true;
}
this.remove=function()
{
_this.hidePanel();
saveResult();//卸载前同步最新内容到textarea
//取消绑定事件
_jText.unbind('focus',_this.focus);
_jForm.unbind('submit',saveResult).unbind('reset', loadReset);
$(window).unbind('unload beforeunload',saveResult).unbind('resize',fixFullHeight);
$(document).unbind('mousedown',clickCancelPanel);
$('#'+idContainer+','+'#'+idFixFFCursor).remove();
_jText.show();
bInit=false;
}
this.saveBookmark=function(){
if(!bSource){
var rng=_this.getRng();
rng=rng.cloneRange?rng.cloneRange():rng;
bookmark={'top':_jWin.scrollTop(),'rng':rng};
}
}
this.loadBookmark=function()
{
if(bSource||!bookmark)return;
_this.focus();
var rng=bookmark.rng;
if(isIE)rng.select();
else
{
var sel=_this.getSel();
sel.removeAllRanges();
sel.addRange(rng);
}
_jWin.scrollTop(bookmark.top);
bookmark=null;
}
this.focus=function()
{
if(!bSource)_jWin.focus();
else $('#sourceCode',_doc).focus();
return false;
}
this.setCursorFirst=function(firstBlock)
{
_this.focus();_win.scrollTo(0,0);
var rng=_this.getRng(),_body=_doc.body,firstNode=_body,firstTag;
if(firstBlock&&firstNode.firstChild&&(firstTag=firstNode.firstChild.tagName)&&firstTag.match(/^p|div|h[1-6]$/i))firstNode=_body.firstChild;
isIE?rng.moveToElementText(firstNode):rng.setStart(firstNode,0);
rng.collapse(true);
if(isIE)rng.select();
else{var sel=_this.getSel();sel.removeAllRanges();sel.addRange(rng);}
}
this.getSel=function()
{
return _win.getSelection ? _win.getSelection() : _doc.selection;
}
this.getRng=function()
{
var sel=_this.getSel(),rng;
try{
rng = sel.rangeCount > 0 ? sel.getRangeAt(0) : (sel.createRange ? sel.createRange() : (_doc.createRange?_doc.createRange():_doc.body.createTextRange()));
}catch (ex){}
return rng;
}
this.getParent=function(tag)
{
var rng=_this.getRng(),p;
if(!isIE)
{
p = rng.commonAncestorContainer;
if(!rng.collapsed)if(rng.startContainer == rng.endContainer&&rng.startOffset - rng.endOffset < 2&&rng.startContainer.hasChildNodes())p = rng.startContainer.childNodes[rng.startOffset];
}
else p=rng.item?rng.item(0):rng.parentElement();
tag=tag?tag:'*';p=$(p);
if(!p.is(tag))p=$(p).closest(tag);
return p;
}
this.getSelect=function(format)
{
var sel=_this.getSel(),rng=_this.getRng(),isCollapsed=true;
if (!rng || rng.item)isCollapsed=false
else isCollapsed=!sel || rng.boundingWidth == 0 || rng.collapsed;
if(format=='text')return isCollapsed ? '' : (rng.text || (sel.toString ? sel.toString() : ''));
var sHtml;
if(rng.cloneContents)
{
var tmp=$('<div></div>'),c;
c = rng.cloneContents();
if(c)tmp.append(c);
sHtml=tmp.html();
}
else if(is(rng.item))sHtml=rng.item(0).outerHTML;
else if(is(rng.htmlText))sHtml=rng.htmlText;
else sHtml=rng.toString();
if(isCollapsed)sHtml='';
sHtml=_this.processHTML(sHtml,'read');
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
return sHtml;
}
this.pasteHTML=function(sHtml,bStart)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
var sel=_this.getSel(),rng=_this.getRng();
if(bStart!=undefined)//非覆盖式插入
{
if(rng.item)
{
var n=rng.item(0);
rng=_doc.body.createTextRange();
rng.moveToElementText(n);
rng.select();
}
rng.collapse(bStart);
}
sHtml+='<'+(isIE?'img':'span')+' id="_xhe_temp" style="display:none" />';
if(rng.insertNode)
{
rng.deleteContents();
rng.insertNode(rng.createContextualFragment(sHtml));
}
else
{
if(sel.type.toLowerCase()=='control'){sel.clear();rng=_this.getRng();};
rng.pasteHTML(sHtml);
}
var jTemp=$('#_xhe_temp',_doc),temp=jTemp[0];
if(isIE)
{
rng.moveToElementText(temp);
rng.select();
}
else
{
rng.selectNode(temp);
sel.removeAllRanges();
sel.addRange(rng);
}
jTemp.remove();
}
this.pasteText=function(text,bStart)
{
if(!text)text='';
text=_this.domEncode(text);
text = text.replace(/\r?\n/g, '<br />');
_this.pasteHTML(text,bStart);
}
this.appendHTML=function(sHtml)
{
if(bSource)return false;
_this.focus();
sHtml=_this.processHTML(sHtml,'write');
$(_doc.body).append(sHtml);
}
this.domEncode=function(str)
{
return str.replace(/[<>]/g,function(c){return {'<':'<','>':'>'}[c];});
}
this.setSource=function(sHtml)
{
bookmark=null;
if(typeof sHtml!='string'&&sHtml!='')sHtml=_text.value;
if(bSource)$('#sourceCode',_doc).val(sHtml);
else
{
if(settings.beforeSetSource)sHtml=settings.beforeSetSource(sHtml);
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml);
sHtml=_this.cleanWord(sHtml);
sHtml=_this.processHTML(sHtml,'write');
if(isIE){//修正IE会删除可视内容前的script,style,<!--
_doc.body.innerHTML='<img id="_xhe_temp" style="display:none" />'+sHtml;
$('#_xhe_temp',_doc).remove();
}
else _doc.body.innerHTML=sHtml;
}
}
this.processHTML=function(sHtml,mode)
{
var appleClass=' class="Apple-style-span"';
if(mode=='write')
{//write
//恢复emot
function restoreEmot(all,attr,q,emot)
{
emot=emot.split(',');
if(!emot[1]){emot[1]=emot[0];emot[0]=''}
if(emot[0]=='default')emot[0]='';
return all.replace(/\s+src\s*=\s*(["']?).*?\1(\s|$|\/|>)/i,'$2').replace(attr,' src="'+emotPath+(emot[0]?emot[0]:'default')+'/'+emot[1]+'.gif"'+(settings.emotMark?' emot="'+(emot[0]?emot[0]+',':'')+emot[1]+'"'+(all.match(/\s+alt\s*=\s*(["']?)\s*(.*?)\s*\1[\s\/>]/i)?'':' alt="'+emot[1]+'"'):''));
}
sHtml = sHtml.replace(/<img(?:\s+[^>]*?)?(\s+emot\s*=\s*(["']?)\s*(.*?)\s*\2)(?:\s+[^>]*?)?\/?>/ig,restoreEmot);
//保存属性值:src,href
function saveValue(all,tag,attr,n,q,v){return all.replace(attr,(urlBase?(' '+n+'="'+getLocalUrl(v,'abs',urlBase)+'"'):attr)+' _xhe_'+n+'="'+v+'"');}
sHtml = sHtml.replace(/<(\w+(?:\:\w+)?)(?:\s+[^>]*?)?(\s+(src|href)\s*=\s*(["']?)\s*(.*?)\s*\4)(?:\s+[^>]*?)?\/?>/ig,saveValue);
sHtml = sHtml.replace(/<(\/?)del(\s+[^>]*?)?>/ig,'<$1strike$2>');//编辑状态统一转为strike
if(isMozilla)
{
sHtml = sHtml.replace(/<(\/?)strong(\s+[^>]*?)?>/ig,'<$1b$2>');
sHtml = sHtml.replace(/<(\/?)em(\s+[^>]*?)?>/ig,'<$1i$2>');
}
else if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.n){s=t.wkn;break;}
}
return pre+'font-size:'+s+aft;
});
sHtml = sHtml.replace(/<strong(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-weight: bold;"$1>');
sHtml = sHtml.replace(/<em(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="font-style: italic;"$1>');
sHtml = sHtml.replace(/<u(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: underline;"$1>');
sHtml = sHtml.replace(/<strike(\s+[^>]*?)?>/ig,'<span'+appleClass+' style="text-decoration: line-through;"$1>');
sHtml = sHtml.replace(/<\/(strong|em|u|strike)>/ig,'</span>');
sHtml = sHtml.replace(/<span((?:\s+[^>]*?)?\s+style="([^"]*;)*\s*(font-family|font-size|color|background-color)\s*:\s*[^;"]+\s*;?"[^>]*)>/ig,'<span'+appleClass+'$1>');
}
else if(isIE)
{
sHtml = sHtml.replace(/'/ig, ''');
sHtml = sHtml.replace(/\s+(disabled|checked|readonly|selected)\s*=\s*[\"\']?(false|0)[\"\']?/ig, '');
}
sHtml = sHtml.replace(/<a(\s+[^>]*?)?\/>/,'<a$1></a>');
if(!isSafari)
{
//style转font
function style2font(all,tag,style,content)
{
var attrs='',f,s1,s2,c;
f=style.match(/font-family\s*:\s*([^;"]+)/i);
if(f)attrs+=' face="'+f[1]+'"';
s1=style.match(/font-size\s*:\s*([^;"]+)/i);
if(s1)
{
s1=s1[1].toLowerCase();
for(var j=0;j<arrFontsize.length;j++)if(s1==arrFontsize[j].n||s1==arrFontsize[j].s){s2=j+1;break;}
if(s2)
{
attrs+=' size="'+s2+'"';
style=style.replace(/(^|;)(\s*font-size\s*:\s*[^;"]+;?)+/ig,'$1');
}
}
c=style.match(/(?:^|[\s;])color\s*:\s*([^;"]+)/i);
if(c)
{
var rgb;
if(rgb=c[1].match(/\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i)){c[1]='#';for(var i=1;i<=3;i++)c[1]+=(rgb[i]-0).toString(16);}
c[1]=c[1].replace(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i,'#$1$1$2$2$3$3');
attrs+=' color="'+c[1]+'"';
}
style=style.replace(/(^|;)(\s*(font-family|color)\s*:\s*[^;"]+;?)+/ig,'$1');
if(attrs!='')
{
if(style)attrs+=' style="'+style+'"';
return '<font'+attrs+'>'+content+"</font>";
}
else return all;
}
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,style2font);//最里层
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,style2font);//第2层
sHtml = sHtml.replace(/<(span)(?:\s+[^>]*?)?\s+style\s*=\s*"((?:[^"]*?;)*\s*(?:font-family|font-size|color)\s*:[^"]*)"(?: [^>]+)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,style2font);//第3层
}
}
else
{//read
//恢复属性值src,href
function restoreValue(all,n,q,v)
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
return all.replace(new RegExp('\\s+'+n+'\\s*=\\s*(["\']?).*?\\1(\\s|/?>)','ig'),' '+n+'="'+v.replace(/\$/g,'$$$$')+'"$2');
}
sHtml = sHtml.replace(/<(?:\w+(?:\:\w+)?)(?:\s+[^>]*?)?\s+_xhe_(src|href)\s*=\s*(["']?)\s*(.*?)\s*\2(?:\s+[^>]*?)?\/?>/ig,restoreValue);
if(isSafari)
{
sHtml = sHtml.replace(/("|;)\s*font-size\s*:\s*([a-z-]+)(;?)/ig,function(all,pre,sname,aft){
var t,s;
for(var i=0;i<arrFontsize.length;i++)
{
t=arrFontsize[i];
if(sname==t.wkn){s=t.n;break;}
}
return pre+'font-size:'+s+aft;
});
var arrAppleSpan=[{r:/font-weight:\sbold/ig,t:'strong'},{r:/font-style:\sitalic/ig,t:'em'},{r:/text-decoration:\sunderline/ig,t:'u'},{r:/text-decoration:\sline-through/ig,t:'strike'}];
function replaceAppleSpan(all,tag,attr1,attr2,content)
{
var attr=attr1+attr2,newTag='';
if(!attr)return content;
for(var i=0;i<arrAppleSpan.length;i++)
{
if(attr.match(arrAppleSpan[i].r))
{
newTag=arrAppleSpan[i].t;
break;
}
}
if(newTag)return '<'+newTag+'>'+content+'</'+newTag+'>';
else return all;
}
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,replaceAppleSpan);//最里层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第2层
sHtml = sHtml.replace(/<(span)(\s+[^>]*?)?\s+class\s*=\s*"Apple-style-span"(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,replaceAppleSpan);//第3层
}
if(!isIE){//字符间的文本换行强制转br
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/([^<>\r\n]?)((?:\r?\n)+)([^<>\r\n]?)/ig,function(all,left,br,right){if(left||right)return left+br.replace(/\r?\n/g,'<br />')+right;else return all;});
});
}
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+(?:_xhe_|_moz_|_webkit_)[^=]+?\s*=\s*(["']?).*?\2(\s|\/?>)/ig,'$1$3');
sHtml = sHtml.replace(/(<\w+[^>]*?)\s+class\s*=\s*(["']?)\s*(?:apple|webkit)\-.+?\s*\2(\s|\/?>)/ig, "$1$3");
sHtml = sHtml.replace(/<img(\s+[^>]+?)\/?>/ig,function(all,attr){if(!attr.match(/\s+alt\s*(["']?).*?\1(\s|$)/i))attr+=' alt=""';return '<img'+attr+' />';});//img强制加alt
sHtml = sHtml.replace(/\s+jquery\d+="\d+"/ig,'');
}
return sHtml;
}
this.getSource=function(bFormat)
{
var sHtml,beforeGetSource=settings.beforeGetSource;
if(bSource)
{
sHtml=$('#sourceCode',_doc).val();
if(!beforeGetSource){
sHtml=sHtml.replace(/(?:(?!<(?:script|style)(?:\s+[^>]*?)?>)[\s\S])+|<(script|style)(?:\s+[^>]*?)?>[\s\S]+<\/\1>/g,function(all){
if(all.match(/^<(script|style)(?:\s+[^>]*?)?>/i))return all;
else return all.replace(/(\t*\r?\n\t*)+/g,'')//标准HTML模式清理缩进和换行
});
}
}
else
{
sHtml=_this.processHTML(_doc.body.innerHTML,'read');
sHtml=sHtml.replace(/^\s*(?:<(p|div)(?:\s+[^>]*?)?>)?\s*(<br(?:\s+[^>]*?)?>)*\s*(?:<\/\1>)?\s*$/i, '');//修正Firefox在空内容情况下多出来的代码
sHtml=_this.cleanHTML(sHtml);
sHtml=_this.formatXHTML(sHtml,bFormat);
sHtml=_this.cleanWord(sHtml);
if(beforeGetSource)sHtml=beforeGetSource(sHtml);
}
_text.value=sHtml;
return sHtml;
}
this.cleanWord=function(sHtml)
{
if(sHtml.match(/mso(-|normal)|WordDocument/i))
{
var deepClean=settings.wordDeepClean;
//格式化
sHtml = sHtml.replace(/(<link(?:\s+[^>]*?)?)\s+href\s*=\s*(["']?)\s*file:\/\/.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, '');
//区块标签清理
sHtml = sHtml.replace(/<!--[\s\S]*?-->|<!(--)?\[[\s\S]+?\](--)?>|<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
sHtml = sHtml.replace(/<\/?\w+:[^>]*>/ig, '');
if(deepClean)sHtml = sHtml.replace(/<\/?(span|a|img)(\s+[^>]*?)?>/ig,'');
//属性清理
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+class\s*=\s*(["']?)\s*mso.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//删除所有mso开头的样式
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+lang\s*=\s*(["']?)\s*.+?\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//删除lang属性
sHtml = sHtml.replace(/(<\w+(?:\s+[^>]*?)?)\s+align\s*=\s*(["']?)\s*left\s*\2((?:\s+[^>]*?)?\s*\/?>)/ig, "$1$3");//取消align=left
//样式清理
sHtml = sHtml.replace(/<\w+(?:\s+[^>]*?)?(\s+style\s*=\s*(["']?)\s*([\s\S]*?)\s*\2)(?:\s+[^>]*?)?\s*\/?>/ig,function(all,attr,p,styles){
styles=$.trim(styles.replace(/\s*(mso-[^:]+:.+?|margin\s*:\s*0cm 0cm 0pt\s*|(text-align|font-variant|line-height)\s*:\s*.+?)(;|$)\s*/ig,''));
return all.replace(attr,deepClean?'':styles?' style="'+styles+'"':'');
});
}
return sHtml;
}
this.cleanHTML=function(sHtml)
{
sHtml = sHtml.replace(/<!?\/?(DOCTYPE|html|body|meta)(\s+[^>]*?)?>/ig, '');
var arrHeadSave;sHtml = sHtml.replace(/<head(?:\s+[^>]*?)?>([\s\S]*?)<\/head>/i, function(all,content){arrHeadSave=content.match(/<(script|style)(\s+[^>]*?)?>[\s\S]*?<\/\1>/ig);return '';});
if(arrHeadSave)sHtml=arrHeadSave.join('')+sHtml;
sHtml = sHtml.replace(/<\??xml(:\w+)?(\s+[^>]*?)?>([\s\S]*?<\/xml>)?/ig, '');
if(!settings.linkTag)sHtml = sHtml.replace(/<link(\s+[^>]*?)?>/ig, '');
if(!settings.internalScript)sHtml = sHtml.replace(/<script(\s+[^>]*?)?>[\s\S]*?<\/script>/ig, '');
if(!settings.inlineScript)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+on(?:click|dblclick|mousedown|mouseup|mousemove|mouseover|mouseout|mouseenter|mouseleave|keydown|keypress|keyup|change|select|submit|reset|blur|focus|load|unload)\s*=\s*(["']?)[\s\S]*?\3((?:\s+[^>]*?)?\/?>)/ig,'$1$2$4');
if(!settings.internalStyle)sHtml = sHtml.replace(/<style(\s+[^>]*?)?>[\s\S]*?<\/style>/ig, '');
if(!settings.inlineStyle)sHtml=sHtml.replace(/(<\w+)(\s+[^>]*?)?\s+(style|class)\s*=\s*(["']?)[\s\S]*?\4((?:\s+[^>]*?)?\/?>)/ig,'$1$2$5');
sHtml=sHtml.replace(/<\/(strong|b|u|strike|em|i)>((?:\s|<br\/?>| )*?)<\1(\s+[^>]*?)?>/ig,'$2');//连续相同标签
return sHtml;
}
this.formatXHTML=function(sHtml,bFormat)
{
var emptyTags = makeMap("area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed");//HTML 4.01
var blockTags = makeMap("address,applet,blockquote,button,center,dd,dir,div,dl,dt,fieldset,form,frameset,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,p,pre,script,table,tbody,td,tfoot,th,thead,tr,ul");//HTML 4.01
var inlineTags = makeMap("a,abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");//HTML 4.01
var closeSelfTags = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
var fillAttrsTags = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
var specialTags = makeMap("script,style");
var tagReplac={'b':'strong','i':'em','s':'del','strike':'del'};
var startTag = /^<\??(\w+(?:\:\w+)?)((?:\s+[\w-\:]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/(\w+(?:\:\w+)?)[^>]*>/;
var attr = /\s+([\w-]+(?:\:\w+)?)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s]+)))?/g;
var skip=0,stack=[],last=sHtml,results=Array(),lvl=-1,lastTag='body',lastTagStart;
stack.last = function(){return this[ this.length - 1 ];};
while(last.length>0)
{
if(!stack.last()||!specialTags[stack.last()])
{
skip=0;
if(last.substring(0, 4)=='<!--')
{//注释标签
skip=last.indexOf("-->");
if(skip!=-1)
{
skip+=3;
addHtmlFrag(last.substring(0,skip));
}
}
else if(last.substring(0, 2)=='</')
{//结束标签
match = last.match( endTag );
if(match)
{
parseEndTag(match[1]);
skip = match[0].length;
}
}
else if(last.charAt(0)=='<')
{//开始标签
match = last.match( startTag );
if(match)
{
parseStartTag(match[1],match[2],match[3]);
skip = match[0].length;
}
}
if(skip==0)//普通文本
{
skip=last.indexOf('<');
if(skip==0)skip=1;
else if(skip<0)skip=last.length;
addHtmlFrag(_this.domEncode(last.substring(0,skip)));
}
last=last.substring(skip);
}
else
{//处理style和script
last=last.replace(/^([\s\S]*?)<\/(style|script)>/i, function(all, script,tagName){
results.push(script);
return ''
});
parseEndTag(stack.last());
}
}
parseEndTag();
sHtml=results.join('');
results=null;
function makeMap(str)
{
var obj = {}, items = str.split(",");
for ( var i = 0; i < items.length; i++ )obj[ items[i] ] = true;
return obj;
}
function processTag(tagName)
{
if(tagName)
{
tagName=tagName.toLowerCase();
var tag=tagReplac[tagName];
if(tag)tagName=tag;
}
else tagName='';
return tagName;
}
function parseStartTag(tagName,rest,unary)
{
tagName=processTag(tagName);
if(blockTags[tagName])while(stack.last()&&inlineTags[stack.last()])parseEndTag(stack.last());
if(closeSelfTags[tagName]&&stack.last()==tagName)parseEndTag(tagName);
unary = emptyTags[ tagName ] || !!unary;
if (!unary)stack.push(tagName);
var all=Array();
all.push('<' + tagName);
rest.replace(attr, function(match, name)
{
name=name.toLowerCase();
var value = arguments[2] ? arguments[2] :
arguments[3] ? arguments[3] :
arguments[4] ? arguments[4] :
fillAttrsTags[name] ? name : "";
all.push(' '+name+'="'+value+'"');
});
all.push((unary ? " /" : "") + ">");
addHtmlFrag(all.join(''),tagName,true);
}
function parseEndTag(tagName)
{
if(!tagName)var pos=0;//清空栈
else
{
tagName=processTag(tagName);
for(var pos=stack.length-1;pos>=0;pos--)if(stack[pos]==tagName)break;//向上寻找匹配的开始标签
}
if(pos>=0)
{
for(var i=stack.length-1;i>=pos;i--)addHtmlFrag("</" + stack[i] + ">",stack[i]);
stack.length=pos;
}
}
function addHtmlFrag(html,tagName,bStart)
{
if(bFormat==true)
{
html=html.replace(/(\t*\r?\n\t*)+/g,'');//清理换行符和相邻的制表符
if(html.match(/^\s*$/))return;//不格式化空内容的标签
var bBlock=blockTags[tagName],tag=bBlock?tagName:'';
if(bBlock)
{
if(bStart)lvl++;//块开始
if(lastTag=='')lvl--;//补文本结束
}
else if(lastTag)lvl++;//文本开始
if(tag!=lastTag||bBlock)addIndent();
results.push(html);
if(tagName=='br')addIndent();//回车强制换行
if(bBlock&&(emptyTags[tagName]||!bStart))lvl--;//块结束
lastTag=bBlock?tagName:'';lastTagStart=bStart;
}
else results.push(html);
}
function addIndent(){results.push('\r\n');if(lvl>0){var tabs=lvl;while(tabs--)results.push("\t");}}
//font转style
function font2style(all,tag,attrs,content)
{
if(!attrs)return content;
var styles='',f,s,c,style;
f=attrs.match(/ face\s*=\s*"\s*([^"]+)\s*"/i);
if(f)styles+='font-family:'+f[1]+';';
s=attrs.match(/ size\s*=\s*"\s*(\d+)\s*"/i);
if(s)styles+='font-size:'+arrFontsize[(s[1]>7?7:(s[1]<1?1:s[1]))-1].n+';';
c=attrs.match(/ color\s*=\s*"\s*([^"]+)\s*"/i);
if(c)styles+='color:'+c[1]+';';
style=attrs.match(/ style\s*=\s*"\s*([^"]+)\s*"/i);
if(style)styles+=style[1];
if(styles)content='<span style="'+styles+'">'+content+'</span>';
return content;
}
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S])*?)<\/\1>/ig,font2style);//最里层
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?)<\/\1>/ig,font2style);//第2层
sHtml = sHtml.replace(/<(font)(\s+[^>]*?)?>(((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S]|<\1(\s+[^>]*?)?>((?!<\1(\s+[^>]*?)?>)[\s\S])*?<\/\1>)*?<\/\1>)*?)<\/\1>/ig,font2style);//第3层
sHtml = sHtml.replace(/^(\s*\r?\n)+|(\s*\r?\n)+$/g,'');//清理首尾换行
sHtml = sHtml.replace(/(\t*\r?\n)+/g,'\r\n');//多行变一行
return sHtml;
}
this.toggleShowBlocktag=function(state)
{
if(bShowBlocktag===state)return;
bShowBlocktag=!bShowBlocktag;
var _jBody=$(_doc.body);
if(bShowBlocktag)
{
bodyClass+=' showBlocktag';
_jBody.addClass('showBlocktag');
}
else
{
bodyClass=bodyClass.replace(' showBlocktag','');
_jBody.removeClass('showBlocktag');
}
}
this.toggleSource=function(state)
{
if(bSource===state)return;
_jTools.find('[name=Source]').toggleClass('xheEnabled').toggleClass('xheActive');
var _body=_doc.body,jBody=$(_body),sHtml;
var sourceCode,cursorMark='<span id="_xhe_cursor'+new Date().getTime()+'"></span>',cursorPos=0;
if(!bSource)
{//转为源代码模式
_this.pasteHTML(cursorMark,true);//标记当前位置
sHtml=_this.getSource(true);
cursorPos=sHtml.indexOf(cursorMark);
if(!isOpera)cursorPos=sHtml.substring(0,cursorPos).replace(/\r/g,'').length;//修正非opera光标定位点
sHtml=sHtml.replace(cursorMark,'');
if(isIE)_body.contentEditable='false';
else _doc.designMode = 'Off';
jBody.attr('scroll','no').attr('class','sourceMode').html('<textarea id="sourceCode" wrap="soft" spellcheck="false" height="100%" />');
sourceCode=$('#sourceCode',jBody).blur(_this.getSource)[0];
}
else
{//转为编辑模式
sHtml=_this.getSource();
jBody.html('').removeAttr('scroll').attr('class','editMode'+bodyClass);
if(isIE)_body.contentEditable='true';
else _doc.designMode = 'On';
if(isMozilla)
{
_this._exec("inserthtml","-");//修正firefox源代码切换回来无法删除文字的问题
$('#'+idFixFFCursor).show().focus().hide();//临时修正Firefox 3.6光标丢失问题
}
}
bSource=!bSource;
_this.setSource(sHtml);
if(bSource)//光标定位源码
{
_this.focus();
if(sourceCode.setSelectionRange)sourceCode.setSelectionRange(cursorPos, cursorPos);
else
{
var rng = sourceCode.createTextRange();
rng.move("character",cursorPos);
rng.select();
}
}
else _this.setCursorFirst(true);//定位最前面
_jTools.find('[name=Source],[name=Preview]').toggleClass('xheEnabled');
_jTools.find('.xheButton').not('[name=Source],[name=Fullscreen],[name=About]').toggleClass('xheEnabled');
setTimeout(setOpts,300);
}
this.showPreview=function()
{
var beforeSetSource=settings.beforeSetSource,sContent=_this.getSource();
if(beforeSetSource)sContent=beforeSetSource(sContent);
var sHTML='<html><head>'+headHTML+'<title>Preview</title>'+(urlBase?'<base href="'+urlBase+'"/>':'')+'</head><body>' + sContent + '</body></html>';
var screen=window.screen,oWindow=window.open('', 'xhePreview', 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+Math.round(screen.width*0.9)+',height='+Math.round(screen.height*0.8)+',left='+Math.round(screen.width*0.05)),oDoc=oWindow.document;
oDoc.open();
oDoc.write(sHTML);
oDoc.close();
oWindow.focus();
}
this.toggleFullscreen=function(state)
{
if(bFullscreen===state)return;
var jLayout=$('#'+idContainer).find('.xheLayout'),jContainer=$('#'+idContainer);
if(bFullscreen)
{//取消全屏
jLayout.attr('style',sLayoutStyle);
_jArea.height(editorHeight-_jTools.outerHeight());
setTimeout(function(){$(window).scrollTop(outerScroll);},10);
}
else
{//显示全屏
outerScroll=$(window).scrollTop();
sLayoutStyle=jLayout.attr('style');
jLayout.removeAttr('style');
_jArea.height('100%');
setTimeout(fixFullHeight,100);
}
if(isMozilla)//临时修正Firefox 3.6源代码光标丢失问题
{
$('#'+idFixFFCursor).show().focus().hide();
setTimeout(_this.focus,1);
}
bFullscreen=!bFullscreen;
jContainer.toggleClass('xhe_Fullscreen');
$('html').toggleClass('xhe_Fullfix');
_jTools.find('[name=Fullscreen]').toggleClass('xheActive');
setTimeout(setOpts,300);
}
this.showMenu=function(menuitems,callback)
{
var jMenu=$('<div class="xheMenu"></div>'),arrItem=[];
$.each(menuitems,function(n,v){arrItem.push('<a href="javascript:void(0);" title="'+(v.t?v.t:v.s)+'" v="'+v.v+'">'+v.s+'</a>');});
jMenu.append(arrItem.join(''));
jMenu.click(function(ev){callback($(ev.target).closest('a').attr('v'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jMenu);
}
this.showColor=function(callback)
{
var jColor=$('<div class="xheColor"></div>'),arrItem=[],count=0;
$.each(itemColors,function(n,v)
{
if(count%7==0)arrItem.push((count>0?'</div>':'')+'<div>');
arrItem.push('<a href="javascript:void(0);" xhev="'+v+'" title="'+v+'" style="background:'+v+'"></a>');
count++;
});
arrItem.push('</div>');
jColor.append(arrItem.join(''));
jColor.click(function(ev){ev=ev.target;if(!$.nodeName(ev,'A'))return;callback($(ev).attr('xhev'));_this.hidePanel();return false;}).mousedown(returnFalse);
_this.showPanel(jColor);
}
this.showPastetext=function()
{
var jPastetext=$(htmlPastetext),jValue=$('#xhePastetextValue',jPastetext),jSave=$('#xheSave',jPastetext);
jSave.click(function(){
_this.loadBookmark();
var sValue=jValue.val();
if(sValue)_this.pasteText(sValue);
_this.hidePanel();
return false;
});
_this.showDialog(jPastetext);
}
this.showLink=function()
{
var jLink=$(htmlLink),jParent=_this.getParent('a'),jText=$('#xheLinkText',jLink),jUrl=$('#xheLinkUrl',jLink),jTarget=$('#xheLinkTarget',jLink),jSave=$('#xheSave',jLink),selHtml=_this.getSelect();
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'href'));
jTarget.attr('value',jParent.attr('target'));
}
else if(selHtml=='')jText.val(settings.defLinkText).closest('div').show();
if(settings.upLinkUrl)_this.uploadInit(jUrl,settings.upLinkUrl,settings.upLinkExt);
jSave.click(function(){
var url=jUrl.val();
_this.loadBookmark();
if(url==''||jParent.length==0)_this._exec('unlink');
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sTarget=jTarget.val(),sText=jText.val();
if(aUrl.length>1)
{//批量插入
_this._exec('unlink');//批量前删除当前链接并重新获取选择内容
selHtml=_this.getSelect();
var sTemplate='<a href="xhe_tmpurl"',sLink,arrLink=[];
if(sTarget!='')sTemplate+=' target="'+sTarget+'"';
sTemplate+='>xhe_tmptext</a>';
sText=(selHtml!=''?selHtml:(sText?sText:url));
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sLink=sTemplate;
sLink=sLink.replace('xhe_tmpurl',url[0]);
sLink=sLink.replace('xhe_tmptext',url[1]?url[1]:sText);
arrLink.push(sLink);
}
}
_this.pasteHTML(arrLink.join(' '));
}
else
{//单url模式
url=aUrl[0].split('||');
if(!sText)sText=url[0];
sText=url[1]?url[1]:(selHtml!='')?'':sText?sText:url[0];
if(jParent.length==0)
{
if(sText)_this.pasteHTML('<a href="#xhe_tmpurl">'+sText+'</a>');
else _this._exec('createlink','#xhe_tmpurl');
jParent=$('a[href$="#xhe_tmpurl"]',_doc);
}
else if(sText&&!isSafari)jParent.text(sText);//safari改写文本会导致光标丢失
xheAttr(jParent,'href',url[0]);
if(sTarget!='')jParent.attr('target',sTarget);
else jParent.removeAttr('target');
}
}
_this.hidePanel();
return false;
});
_this.showDialog(jLink);
}
this.showImg=function()
{
var jImg=$(htmlImg),jParent=_this.getParent('img'),jUrl=$('#xheImgUrl',jImg),jAlt=$('#xheImgAlt',jImg),jAlign=$('#xheImgAlign',jImg),jWidth=$('#xheImgWidth',jImg),jHeight=$('#xheImgHeight',jImg),jBorder=$('#xheImgBorder',jImg),jVspace=$('#xheImgVspace',jImg),jHspace=$('#xheImgHspace',jImg),jSave=$('#xheSave',jImg);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jAlt.val(jParent.attr('alt'));
jAlign.val(jParent.attr('align'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
jBorder.val(jParent.attr('border'));
var vspace=jParent.attr('vspace'),hspace=jParent.attr('hspace');
jVspace.val(vspace<=0?'':vspace);
jHspace.val(hspace<=0?'':hspace);
}
if(settings.upImgUrl)_this.uploadInit(jUrl,settings.upImgUrl,settings.upImgExt);
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var aUrl=url.split(' '),sAlt=jAlt.val(),sAlign=jAlign.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sBorder=jBorder.val(),sVspace=jVspace.val(),sHspace=jHspace.val();;
if(aUrl.length>1)
{//批量插入
var sTemplate='<img src="xhe_tmpurl"',sImg,arrImg=[];
if(sAlt!='')sTemplate+=' alt="'+sAlt+'"';
if(sAlign!='')sTemplate+=' align="'+sAlign+'"';
if(sWidth!='')sTemplate+=' width="'+sWidth+'"';
if(sHeight!='')sTemplate+=' height="'+sHeight+'"';
if(sBorder!='')sTemplate+=' border="'+sBorder+'"';
if(sVspace!='')sTemplate+=' vspace="'+sVspace+'"';
if(sHspace!='')sTemplate+=' hspace="'+sHspace+'"';
sTemplate+=' />';
for(var i in aUrl)
{
url=aUrl[i];
if(url!='')
{
url=url.split('||');
sImg=sTemplate;
sImg=sImg.replace('xhe_tmpurl',url[0]);
if(url[1])sImg='<a href="'+url[1]+'" target="_blank">'+sImg+'</a>'
arrImg.push(sImg);
}
}
_this.pasteHTML(arrImg.join(' '));
}
else if(aUrl.length==1)
{//单URL模式
url=aUrl[0];
if(url!='')
{
url=url.split('||');
if(jParent.length==0)
{
_this.pasteHTML('<img src="'+url[0]+'#xhe_tmpurl" />');
jParent=$('img[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0])
if(sAlt!='')jParent.attr('alt',sAlt);
if(sAlign!='')jParent.attr('align',sAlign);
else jParent.removeAttr('align');
if(sWidth!='')jParent.attr('width',sWidth);
else jParent.removeAttr('width');
if(sHeight!='')jParent.attr('height',sHeight);
else jParent.removeAttr('height');
if(sBorder!='')jParent.attr('border',sBorder);
else jParent.removeAttr('border');
if(sVspace!='')jParent.attr('vspace',sVspace);
else jParent.removeAttr('vspace');
if(sHspace!='')jParent.attr('hspace',sHspace);
else jParent.removeAttr('hspace');
if(url[1])
{
var jLink=jParent.parent('a');
if(jLink.length==0)
{
jParent.wrap('<a></a>');
jLink=jParent.parent('a');
}
xheAttr(jLink,'href',url[1]);
jLink.attr('target','_blank');
}
}
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
_this.showDialog(jImg);
}
this.showEmbed=function(sType,sHtml,sMime,sClsID,sBaseAttrs,sUploadUrl,sUploadExt)
{
var jEmbed=$(sHtml),jParent=_this.getParent('embed[type="'+sMime+'"],embed[classid="'+sClsID+'"]'),jUrl=$('#xhe'+sType+'Url',jEmbed),jWidth=$('#xhe'+sType+'Width',jEmbed),jHeight=$('#xhe'+sType+'Height',jEmbed),jSave=$('#xheSave',jEmbed);
if(sUploadUrl)_this.uploadInit(jUrl,sUploadUrl,sUploadExt);
_this.showDialog(jEmbed);
if(jParent.length==1)
{
jUrl.val(xheAttr(jParent,'src'));
jWidth.val(jParent.attr('width'));
jHeight.val(jParent.attr('height'));
}
jSave.click(function(){
_this.loadBookmark();
var url=jUrl.val();
if(url!=''&&url!='http://')
{
var w=jWidth.val(),h=jHeight.val(),reg=/^[0-9]+$/;
if(!reg.test(w))w=412;if(!reg.test(h))h=300;
var sBaseCode='<embed type="'+sMime+'" classid="'+sClsID+'" src="xhe_tmpurl"'+sBaseAttrs;
var aUrl=url.split(' ');
if(aUrl.length>1)
{//批量插入
var sTemplate=sBaseCode+'',sEmbed,arrEmbed=[];
sTemplate+=' width="xhe_width" height="xhe_height" />';
for(var i in aUrl)
{
url=aUrl[i].split('||');
sEmbed=sTemplate;
sEmbed=sEmbed.replace('xhe_tmpurl',url[0])
sEmbed=sEmbed.replace('xhe_width',url[1]?url[1]:w)
sEmbed=sEmbed.replace('xhe_height',url[2]?url[2]:h)
if(url!='')arrEmbed.push(sEmbed);
}
_this.pasteHTML(arrEmbed.join(' '));
}
else if(aUrl.length==1)
{//单URL模式
url=aUrl[0].split('||');
if(jParent.length==0)
{
_this.pasteHTML(sBaseCode.replace('xhe_tmpurl',url[0]+'#xhe_tmpurl')+' />');
jParent=$('embed[src$="#xhe_tmpurl"]',_doc);
}
xheAttr(jParent,'src',url[0]);
jParent.attr('width',url[1]?url[1]:w);
jParent.attr('height',url[2]?url[2]:h);
}
}
else if(jParent.length==1)jParent.remove();
_this.hidePanel();
return false;
});
}
this.showEmot=function(group)
{
var jEmot=$('<div class="xheEmot"></div>');
group=group?group:(selEmotGroup?selEmotGroup:'default');
var arrEmot=arrEmots[group];
var sEmotPath=emotPath+group+'/',n=0,arrList=[],jList='';
var ew=arrEmot.width,eh=arrEmot.height,line=arrEmot.line,count=arrEmot.count,list=arrEmot.list;
if(count)
{
for(var i=1;i<=count;i++)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+i+'.gif);" emot="'+group+','+i+'" xhev=""> </a>');
if(n%line==0)arrList.push('<br />');
}
}
else
{
$.each(list,function(id,title)
{
n++;
arrList.push('<a href="javascript:void(0);" style="background-image:url('+sEmotPath+id+'.gif);" emot="'+group+','+id+'" title="'+title+'" xhev="'+title+'"> </a>');
if(n%line==0)arrList.push('<br />');
});
}
var w=line*(ew+12),h=Math.ceil(n/line)*(eh+12),mh=w*0.75;
if(h<=mh)mh='';
jList=$('<style>'+(mh?'.xheEmot div{width:'+(w+20)+'px;height:'+mh+'px;}':'')+'.xheEmot div a{width:'+ew+'px;height:'+eh+'px;}</style><div>'+arrList.join('')+'</div>').click(function(ev){ev=ev.target;var jA=$(ev);if(!$.nodeName(ev,'A'))return;_this.pasteHTML('<img emot="'+jA.attr('emot')+'" alt="'+jA.attr('xhev')+'">');_this.hidePanel();return false;}).mousedown(returnFalse);
jEmot.append(jList);
var gcount=0,arrGroup=['<ul>'],jGroup;//表情分类
$.each(arrEmots,function(g,v){
gcount++;
arrGroup.push('<li'+(group==g?' class="cur"':'')+'><a href="javascript:void(0);" group="'+g+'">'+v.name+'</a></li>');
});
if(gcount>1)
{
arrGroup.push('</ul><br style="clear:both;" />');
jGroup=$(arrGroup.join('')).click(function(ev){selEmotGroup=$(ev.target).attr('group');_this.exec('Emot');return false;}).mousedown(returnFalse);
jEmot.append(jGroup);
}
_this.showPanel(jEmot);
}
this.showTable=function()
{
var jTable=$(htmlTable),jRows=$('#xheTableRows',jTable),jColumns=$('#xheTableColumns',jTable),jHeaders=$('#xheTableHeaders',jTable),jWidth=$('#xheTableWidth',jTable),jHeight=$('#xheTableHeight',jTable),jBorder=$('#xheTableBorder',jTable),jCellSpacing=$('#xheTableCellSpacing',jTable),jCellPadding=$('#xheTableCellPadding',jTable),jAlign=$('#xheTableAlign',jTable),jCaption=$('#xheTableCaption',jTable),jSave=$('#xheSave',jTable);
jSave.click(function(){
_this.loadBookmark();
var sCaption=jCaption.val(),sBorder=jBorder.val(),sRows=jRows.val(),sCols=jColumns.val(),sHeaders=jHeaders.val(),sWidth=jWidth.val(),sHeight=jHeight.val(),sCellSpacing=jCellSpacing.val(),sCellPadding=jCellPadding.val(),sAlign=jAlign.val();
var i,j,htmlTable='<table'+(sBorder!=''?' border="'+sBorder+'"':'')+(sWidth!=''?' width="'+sWidth+'"':'')+(sHeight!=''?' width="'+sHeight+'"':'')+(sCellSpacing!=''?' cellspacing="'+sCellSpacing+'"':'')+(sCellPadding!=''?' cellpadding="'+sCellPadding+'"':'')+(sAlign!=''?' align="'+sAlign+'"':'')+'>';
if(sCaption!='')htmlTable+='<caption>'+sCaption+'</caption>';
if(sHeaders=='row'||sHeaders=='both')
{
htmlTable+='<tr>';
for(i=0;i<sCols;i++)htmlTable+='<th scope="col"> </th>';
htmlTable+='</tr>';
sRows--;
}
htmlTable+='<tbody>';
for(i=0;i<sRows;i++)
{
htmlTable+='<tr>';
for(j=0;j<sCols;j++)
{
if(j==0&&(sHeaders=='col'||sHeaders=='both'))htmlTable+='<th scope="row"> </th>';
else htmlTable+='<td> </td>';
}
htmlTable+='</tr>';
}
htmlTable+='</tbody></table>';
_this.pasteHTML(htmlTable);
_this.hidePanel();
return false;
});
_this.showDialog(jTable);
}
this.showAbout=function()
{
var jAbout=$(htmlAbout);
_this.showDialog(jAbout);
}
this.addShortcuts=function(key,cmd)
{
key=key.toLowerCase();
if(arrShortCuts[key]==undefined)arrShortCuts[key]=Array();
arrShortCuts[key].push(cmd);
}
this.delShortcuts=function(key){delete arrShortCuts[key];}
this.uploadInit=function(jText,toUrl,upext)
{
var jUpload=$('<span class="xheUpload"><input type="text" style="visibility:hidden;" tabindex="-1" /><input type="button" value="'+settings.upBtnText+'" class="xheBtn" tabindex="-1" /></span>'),jUpBtn=$('.xheBtn',jUpload);
var bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
jText.after(jUpload);jUpBtn.before(jText);
toUrl=toUrl.replace(/{editorRoot}/ig,editorRoot);
if(toUrl.substr(0,1)=='!')//自定义上传管理页
{
jUpBtn.click(function(){
bShowPanel=false;//防止按钮面板被关闭
_this.showIframeModal('Upload file',toUrl.substr(1),setUploadMsg,null,null,function(){bShowPanel=true;});
});
}
else
{//系统默认ajax上传
jUpload.append('<input type="file"'+(upMultiple>1?' multiple=""':'')+' class="xheFile" size="13" name="'+uploadInputname+'" tabindex="-1" />');
var jFile=$('.xheFile',jUpload),arrMsg;
jFile.change(function(){arrMsg=[];_this.startUpload(jFile[0],toUrl,upext,setUploadMsg);});
setTimeout(function(){//拖放上传
jText.closest('.xheDialog').bind('dragenter dragover',returnFalse).bind('drop',function(ev){
var dataTransfer=ev.originalEvent.dataTransfer,fileList;
if(bHtml5Upload&&dataTransfer&&(fileList=dataTransfer.files)&&fileList.length>0)_this.startUpload(fileList,toUrl,upext,setUploadMsg);
return false;
});
},10);
}
function setUploadMsg(arrMsg)
{
if(is(arrMsg,'string'))arrMsg=[arrMsg];//允许单URL传递
var bImmediate=false,i,count=arrMsg.length,msg,url,arrUrl=[],onUpload=settings.onUpload;
if(onUpload)onUpload(arrMsg);//用户上传回调
for(i=0;i<count;i++)
{
msg=arrMsg[i];
url=is(msg,'string')?msg:msg.url;
if(url.substr(0,1)=='!'){bImmediate=true;url=url.substr(1);}
arrUrl.push(url);
}
jText.val(arrUrl.join(' '));
if(bImmediate)jText.closest('.xheDialog').find('#xheSave').click();
}
}
this.startUpload=function(fromFiles,toUrl,limitExt,onUploadComplete)
{
var arrMsg=[],bHtml5Upload=settings.html5Upload,upMultiple=bHtml5Upload?settings.upMultiple:1;
var upload,fileList,filename,jUploadTip=$('<div style="padding:22px 0;text-align:center;line-height:30px;">File uploading,please wait...<br /></div>'),sLoading='<img src="'+skinPath+'img/loading.gif">';
if(!bHtml5Upload||(fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0])))
{
if(!checkFileExt(fromFiles.value,limitExt))return;
jUploadTip.append(sLoading);
upload=new _this.html4Upload(fromFiles,toUrl,onUploadCallback);
}
else
{
if(!fileList)fileList=fromFiles;//拖放文件列表
var i,len=fileList.length;
if(len>upMultiple){alert('Please do not upload more then '+upMultiple+' files.');return;}
for(i=0;i<len;i++)if(!checkFileExt(fileList[i].fileName,limitExt))return;
var jProgress=$('<div class="xheProgress"><div><span>0%</span></div></div>');
jUploadTip.append(jProgress);
upload=new _this.html5Upload(uploadInputname,fileList,toUrl,onUploadCallback,function(ev){
if(ev.loaded>=0)
{
var sPercent=Math.round((ev.loaded * 100) / ev.total)+'%';
$('div',jProgress).css('width',sPercent);
$('span',jProgress).text(sPercent+' ( '+formatBytes(ev.loaded)+' / '+formatBytes(ev.total)+' )');
}
else jProgress.replaceWith(sLoading);//不支持进度
});
}
var panelState=bShowPanel;
if(panelState)bShowPanel=false;//防止面板被关闭
_this.showModal('File uploading(Esc cancel)',jUploadTip,320,150,function(){bShowPanel=panelState;upload.remove();});
upload.start();
function onUploadCallback(sText,bFinish)
{
var data=Object,bOK=false;
try{data=eval('('+sText+')');}catch(ex){};
if(data.err==undefined||data.msg==undefined)alert(toUrl+' upload interface error!\r\n\r\nreturn error:\r\n\r\n'+sText);
else
{
if(data.err)alert(data.err);
else
{
arrMsg.push(data.msg);
bOK=true;//继续下一个文件上传
}
}
if(!bOK||bFinish)_this.removeModal();
if(bFinish&&bOK)onUploadComplete(arrMsg);//全部上传完成
return bOK;
}
}
this.html4Upload=function(fromfile,toUrl,callback)
{
var uid = new Date().getTime(),idIO='jUploadFrame'+uid,_this=this;
var jIO=$('<iframe name="'+idIO+'" class="xheHideArea" />').appendTo('body');
var jForm=$('<form action="'+toUrl+'" target="'+idIO+'" method="post" enctype="multipart/form-data" class="xheHideArea"></form>').appendTo('body');
var jOldFile = $(fromfile),jNewFile = jOldFile.clone().attr('disabled','true');
jOldFile.before(jNewFile).appendTo(jForm);
this.remove=function()
{
if(_this!=null)
{
jNewFile.before(jOldFile).remove();
jIO.remove();jForm.remove();
_this=null;
}
}
this.onLoad=function(){callback($(jIO[0].contentWindow.document.body).text(),true);}
this.start=function(){jForm.submit();jIO.load(_this.onLoad);}
return this;
}
this.html5Upload=function(inputname,fromFiles,toUrl,callback,onProgress)
{
var xhr,i=0,count=fromFiles.length,allLoaded=0,allSize=0,_this=this;
for(var j=0;j<count;j++)allSize+=fromFiles[j].fileSize;
this.remove=function(){if(xhr){xhr.abort();xhr=null;}}
this.uploadNext=function(sText)
{
if(sText)//当前文件上传完成
{
allLoaded+=fromFiles[i-1].fileSize;
returnProgress(0);
}
if((!sText||(sText&&callback(sText,i==count)==true))&&i<count)postFile(fromFiles[i++],toUrl,_this.uploadNext,function(loaded){returnProgress(loaded);});
}
this.start=function(){_this.uploadNext();}
function postFile(fromfile,toUrl,callback,onProgress)
{
xhr = new XMLHttpRequest(),upload=xhr.upload;
xhr.onreadystatechange=function(){if(xhr.readyState==4)callback(xhr.responseText);};
if(upload)upload.onprogress=function(ev){onProgress(ev.loaded);};
else onProgress(-1);//不支持进度
xhr.open("POST", toUrl);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Content-Disposition', 'attachment; name="'+inputname+'"; filename="'+fromfile.fileName+'"');
if(xhr.sendAsBinary)xhr.sendAsBinary(fromfile.getAsBinary());
else xhr.send(fromfile);
}
function returnProgress(loaded){if(onProgress)onProgress({'loaded':allLoaded+loaded,'total':allSize});}
}
this.showIframeModal=function(title,ifmurl,callback,w,h,onRemove)
{
var jContent=$('<iframe frameborder="0" src="'+ifmurl.replace(/{editorRoot}/ig,editorRoot)+'" style="width:100%;height:100%;display:none;" /><div class="xheModalIfmWait"></div>'),jIframe=$(jContent[0]),jWait=$(jContent[1]);
_this.showModal(title,jContent,w,h,onRemove);
jIframe.load(function(){
var modalWin=jIframe[0].contentWindow,jModalDoc=$(modalWin.document);
modalWin.callback=function(v){_this.removeModal();callback(v);};
modalWin.unloadme=_this.removeModal;
jModalDoc.keydown(_this.checkEsc);
jIframe.show();jWait.remove();
});
}
this.showModal=function(title,content,w,h,onRemove)
{
if(bShowModal)return false;//只能弹出一个模式窗口
layerShadow=settings.layerShadow;
w=w?w:settings.modalWidth;h=h?h:settings.modalHeight;
jModal=$('<div class="xheModal" style="width:'+(w-1)+'px;height:'+h+'px;margin-left:-'+Math.ceil(w/2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+Math.ceil(h/2)+'px')+'">'+(settings.modalTitle?'<div class="xheModalTitle"><span class="xheModalClose" title="Close (Esc)"></span>'+title+'</div>':'')+'<div class="xheModalContent"></div></div>').appendTo('body');
jOverlay=$('<div class="xheModalOverlay"></div>').appendTo('body');
if(layerShadow>0)jModalShadow=$('<div class="xheModalShadow" style="width:'+jModal.outerWidth()+'px;height:'+jModal.outerHeight()+'px;margin-left:-'+(Math.ceil(w/2)-layerShadow-2)+'px;'+(isIE&&browerVer<=7.0?'':'margin-top:-'+(Math.ceil(h/2)-layerShadow-2)+'px')+'"></div>').appendTo('body');
$('.xheModalContent',jModal).css('height',h-(settings.modalTitle?$('.xheModalTitle').outerHeight():0)).html(content);
if(isIE&&browerVer==6.0)jHideSelect=$('select:visible').css('visibility','hidden');//隐藏覆盖的select
$('.xheModalClose',jModal).click(_this.removeModal);
jOverlay.show();if(layerShadow>0)jModalShadow.show();jModal.show();
bShowModal=true;
onModalRemove=onRemove;
}
this.removeModal=function(){if(jHideSelect)jHideSelect.css('visibility','visible');jModal.html('').remove();if(layerShadow>0)jModalShadow.remove();jOverlay.remove();if(onModalRemove)onModalRemove();bShowModal=false;};
this.showDialog=function(content)
{
var jDialog=$('<div class="xheDialog"></div>'),jContent=$(content),jSave=$('#xheSave',jContent);
if(jSave.length==1)
{
jContent.find('input[type=text],select').keypress(function(ev){if(ev.which==13){jSave.click();return false;}});
jContent.find('textarea').keydown(function(ev){if(ev.ctrlKey&&ev.which==13){jSave.click();return false;}});
jSave.after(' <input type="button" id="xheCancel" value="Cancel" />');
$('#xheCancel',jContent).click(_this.hidePanel);
if(!settings.clickCancelDialog)
{
bClickCancel=false;//关闭点击隐藏
var jFixCancel=$('<div class="xheFixCancel"></div>').appendTo('body').mousedown(returnFalse);
var xy=_jArea.offset();
jFixCancel.css({'left':xy.left,'top':xy.top,width:_jArea.outerWidth(),height:_jArea.outerHeight()})
}
jDialog.mousedown(function(){bDisableHoverExec=true;})//点击对话框禁止悬停执行
}
jDialog.append(jContent);
_this.showPanel(jDialog);
if(!isIE)setTimeout(function(){jDialog.find('input[type=text],textarea').filter(':visible').filter(function(){return $(this).css('visibility')!='hidden';}).eq(0).focus();},10);//定位首个可见输入表单项,延迟解决opera无法设置焦点
}
this.showPanel=function(content)
{
if(!ev.target)return false;
_jPanel.html('').append(content).css('left',-999).css('top',-999);
_jPanelButton=$(ev.target).closest('a').addClass('xheActive');
var xy=_jPanelButton.offset();
var x=xy.left,y=xy.top;y+=_jPanelButton.outerHeight()-1;
_jCntLine.css({'left':x+1,'top':y,'width':_jPanelButton.width()}).show();
if((x+_jPanel.outerWidth())>document.body.clientWidth)x-=(_jPanel.outerWidth()-_jPanelButton.outerWidth());//向左显示面板
var layerShadow=settings.layerShadow;
if(layerShadow>0)_jShadow.css({'left':x+layerShadow,'top':y+layerShadow,'width':_jPanel.outerWidth(),'height':_jPanel.outerHeight()}).show();
_jPanel.css({'left':x,'top':y}).show();
bQuickHoverExec=bShowPanel=true;
}
this.hidePanel=function(){if(bShowPanel){_jPanelButton.removeClass('xheActive');_jShadow.hide();_jCntLine.hide();_jPanel.hide();bShowPanel=false;if(!bClickCancel){$('.xheFixCancel').remove();bClickCancel=true;};bQuickHoverExec=bDisableHoverExec=false;lastAngle=null;}}
this.exec=function(cmd)
{
_this.hidePanel();
_this.saveBookmark();
var tool=arrTools[cmd];
if(!tool)return false;//无效命令
if(ev==null)//非鼠标点击
{
ev={};
var btn=_jTools.find('.xheButton[name='+cmd+']');
if(btn.length==1)ev.target=btn;//设置当前事件焦点
}
if(tool.e)tool.e.call(_this)//插件事件
else//内置工具
{
cmd=cmd.toLowerCase();
switch(cmd)
{
case 'cut':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('Currently not supported by your browser, use keyboard shortcuts(Ctrl+X) instead.');};
break;
case 'copy':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('Currently not supported by your browser, use keyboard shortcuts(Ctrl+C) instead.');}
break;
case 'paste':
try{_doc.execCommand(cmd);if(!_doc.queryCommandSupported(cmd))throw 'Error';}
catch(ex){alert('Currently not supported by your browser, use keyboard shortcuts(Ctrl+V) instead.');}
break;
case 'pastetext':
if(window.clipboardData)_this.pasteText(window.clipboardData.getData('Text', true));
else _this.showPastetext();
break;
case 'blocktag':
var menuBlocktag=[];
$.each(arrBlocktag,function(n,v){menuBlocktag.push({s:'<'+v.n+'>'+v.t+'</'+v.n+'>',v:'<'+v.n+'>',t:v.t});});
_this.showMenu(menuBlocktag,function(v){_this._exec('formatblock',v);});
break;
case 'fontface':
var menuFontname=[];
$.each(arrFontname,function(n,v){v.c=v.c?v.c:v.n;menuFontname.push({s:'<span style="font-family:'+v.c+'">'+v.n+'</span>',v:v.c,t:v.n});});
_this.showMenu(menuFontname,function(v){_this._exec('fontname',v);});
break;
case 'fontsize':
var menuFontsize=[];
$.each(arrFontsize,function(n,v){menuFontsize.push({s:'<span style="font-size:'+v.s+';">'+v.t+'('+v.s+')</span>',v:n+1,t:v.t});});
_this.showMenu(menuFontsize,function(v){_this._exec('fontsize',v);});
break;
case 'fontcolor':
_this.showColor(function(v){_this._exec('forecolor',v);});
break;
case 'backcolor':
_this.showColor(function(v){if(isIE)_this._exec('backcolor',v);else{setCSS(true);_this._exec('hilitecolor',v);setCSS(false);}});
break;
case 'align':
_this.showMenu(menuAlign,function(v){_this._exec(v);});
break;
case 'list':
_this.showMenu(menuList,function(v){_this._exec(v);});
break;
case 'link':
_this.showLink();
break;
case 'img':
_this.showImg();
break;
case 'flash':
_this.showEmbed('Flash',htmlFlash,'application/x-shockwave-flash','clsid:d27cdb6e-ae6d-11cf-96b8-4445535400000',' wmode="opaque" quality="high" menu="false" play="true" loop="true" allowfullscreen="true"',settings.upFlashUrl,settings.upFlashExt);
break;
case 'media':
_this.showEmbed('Media',htmlMedia,'application/x-mplayer2','clsid:6bf52a52-394a-11d3-b153-00c04f79faa6',' enablecontextmenu="false" autostart="false"',settings.upMediaUrl,settings.upMediaExt);
break;
case 'emot':
_this.showEmot();
break;
case 'table':
_this.showTable();
break;
case 'source':
_this.toggleSource();
break;
case 'preview':
_this.showPreview();
break;
case 'print':
_win.print();
break;
case 'fullscreen':
_this.toggleFullscreen();
break;
case 'about':
_this.showAbout();
break;
default:
_this._exec(cmd);
break;
}
}
ev=null;
}
this._exec=function(cmd,param,noFocus)
{
if(!noFocus)_this.focus();
var state;
if(param!=undefined)state=_doc.execCommand(cmd,false,param);
else state=_doc.execCommand(cmd,false,null);
return state;
}
function checkDblClick(ev)
{
var target=ev.target,tool=arrDbClick[target.tagName.toLowerCase()];
if(tool)
{
if(tool=='Embed')//自动识别Flash和多媒体
{
var arrEmbed={'application/x-shockwave-flash':'Flash','application/x-mplayer2':'Media'};
tool=arrEmbed[target.type.toLowerCase()];
}
_this.exec(tool);
}
}
function checkEsc(ev)
{
if(ev.which==27)
{
if(bShowModal)_this.removeModal();
else if(bShowPanel)_this.hidePanel();
return false;
}
}
function loadReset(){setTimeout(_this.setSource,10);}
function saveResult(){_this.getSource();};
function cleanPaste(ev){
if(bSource||bCleanPaste)return true;
bCleanPaste=true;//解决IE右键粘贴重复产生paste的问题
_this.saveBookmark();
var jDiv=$('<div style="position:absolute;left:-1000px;top:'+_jWin.scrollTop()+'px;overflow:hidden;width:1px;height:1px;" />',_doc),div=jDiv[0],sel=_this.getSel(),rng=_this.getRng();
$(_doc.body).append(jDiv);
if(isIE){
rng.moveToElementText(div);
rng.execCommand('Paste');
ev.preventDefault();
}
else{
rng.selectNodeContents(div);
sel.removeAllRanges();
sel.addRange(rng);
}
setTimeout(function(){
var sPaste;
if(settings.forcePasteText===true)sPaste=jDiv.text();
else{
sPaste=div.innerHTML;
sPaste=_this.cleanHTML(sPaste);
sPaste=_this.formatXHTML(sPaste);
sPaste=_this.cleanWord(sPaste);
}
jDiv.remove();
_this.loadBookmark();
_this.pasteHTML(sPaste);
bCleanPaste=false;
},0);
}
function setCSS(css)
{
try{_this._exec('styleWithCSS',css,true);}
catch(e)
{try{_this._exec('useCSS',!css,true);}catch(e){}}
}
function setOpts()
{
if(bInit&&!bSource)
{
setCSS(false);
try{_this._exec('enableObjectResizing',true,true);}catch(e){}
//try{_this._exec('enableInlineTableEditing',false,true);}catch(e){}
if(isIE)try{_this._exec('BackgroundImageCache',true,true);}catch(e){}
}
}
function forcePtag(ev)
{
if(bSource||ev.which!=13||ev.shiftKey||ev.ctrlKey||ev.altKey)return true;
var pNode=_this.getParent('p,h1,h2,h3,h4,h5,h6,pre,address,div,li');
if(pNode.is('li'))return true;
if(settings.forcePtag){if(pNode.length==0)_this._exec('formatblock','<p>');}
else
{
_this.pasteHTML('<br />');
if(isIE&&pNode.length>0&&_this.getRng().parentElement().childNodes.length==2)_this.pasteHTML('<br />');
return false;
}
}
function fixFullHeight()
{
if(!isMozilla&&!isSafari)
{
if(bFullscreen)_jArea.height('100%').css('height',_jArea.outerHeight()-_jTools.outerHeight());
if(isIE)_jTools.hide().show();
}
}
function fixAppleSel(e)
{
e=e.target;
if(e.tagName.match(/(img|embed)/i))
{
var sel=_this.getSel(),rng=_this.getRng();
rng.selectNode(e);
sel.removeAllRanges();
sel.addRange(rng);
}
}
function xheAttr(jObj,n,v)
{
if(!n)return false;
var kn='_xhe_'+n;
if(v)//设置属性
{
if(urlType)v=getLocalUrl(v,urlType,urlBase);
jObj.attr(n,urlBase?getLocalUrl(v,'abs',urlBase):v).removeAttr(kn).attr(kn,v);
}
return jObj.attr(kn)||jObj.attr(n);
}
function clickCancelPanel(){if(bClickCancel)_this.hidePanel();}
function checkShortcuts(event)
{
if(bSource)return true;
var code=event.which,special=specialKeys[code],sChar=special?special:String.fromCharCode(code).toLowerCase();
sKey='';
sKey+=event.ctrlKey?'ctrl+':'';sKey+=event.altKey?'alt+':'';sKey+=event.shiftKey?'shift+':'';sKey+=sChar;
var cmd=arrShortCuts[sKey],c;
for(c in cmd)
{
c=cmd[c];
if($.isFunction(c)){if(c.call(_this)===false)return false;}
else{_this.exec(c);return false;}//按钮独占快捷键
}
}
function is(o,t)
{
var n = typeof(o);
if (!t)return n != 'undefined';
if (t == 'array' && (o.hasOwnProperty && o instanceof Array))return true;
return n == t;
}
function getLocalUrl(url,urlType,urlBase)//绝对地址:abs,根地址:root,相对地址:rel
{
var baseUrl=urlBase?$('<a href="'+urlBase+'" />')[0]:location,protocol=baseUrl.protocol,host=baseUrl.hostname,port=baseUrl.port,path=baseUrl.pathname.replace(/\\/g,'/').replace(/[^\/]+$/i,'');
port=(port=='')?'80':port;
url=$.trim(url);
if(urlType!='abs')url=url.replace(new RegExp(protocol+'\\/\\/'+host.replace(/\./g,'\\.')+'(?::'+port+')'+(port=='80'?'?':'')+'(\/|$)','i'),'/');
if(urlType=='rel')url=url.replace(new RegExp('^'+path.replace(/([\/\.\+\[\]\(\)])/g,'\\$1'),'i'),'');
if(urlType!='rel')
{
if(!url.match(/^((https?|file):\/\/|\/)/i))url=path+url;
if(url.charAt(0)=='/')//处理..
{
var arrPath=[],arrFolder = url.split('/'),folder,i,l=arrFolder.length;
for(i=0;i<l;i++)
{
folder=arrFolder[i];
if(folder=='..')arrPath.pop();
else if(folder!==''&&folder!='.')arrPath.push(folder);
}
if(arrFolder[l-1]=='')arrPath.push('');
url='/'+arrPath.join('/');
}
}
if(urlType=='abs')if(!url.match(/(https?|file):\/\//i))url=protocol+'//'+location.host+url;
return url;
}
function checkFileExt(filename,limitExt)
{
if(limitExt=='*'||filename.match(new RegExp('\.('+limitExt.replace(/,/g,'|')+')$','i')))return true;
else
{
alert('Upload file extension required for this: '+limitExt);
return false;
}
}
function formatBytes(bytes)
{
var s = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes)/Math.log(1024));
return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+s[e];
}
function returnFalse(){return false;}
}
$(function(){
$.fn.oldVal=$.fn.val;
$.fn.val=function(value)
{
var _this=this,editor;
if(value===undefined)if(this[0]&&(editor=this[0].xheditor))return editor.getSource();else return _this.oldVal(value);//读
return this.each(function(){if(editor=this.xheditor)editor.setSource(value);else _this.oldVal(value);});//写
}
$('textarea').each(function(){
var self=$(this),xhClass=self.attr('class').match(/(?:^|\s)xheditor(?:\-(m?full|simple|mini))?(?:\s|$)/i);
if(xhClass)self.xheditor(xhClass[1]?{tools:xhClass[1]}:null);
});
});
})(jQuery); | JavaScript |
//function movePage(absolutePage){
// window.location='?absolutePage=';
//}
function codeImg(b){
b.src="getCodeImg?"+Math.random();
} | JavaScript |
/*!
* jQuery Form Plugin
* version: 2.49 (18-OCT-2010)
* @requires jQuery v1.3.2 or later
*
* Examples and documentation at: http://malsup.com/jquery/form/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
;
(function($) {
/*
* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the
* same form. These functions are intended to be exclusive. Use ajaxSubmit
* if you want to bind your own submit handler to the form. For example,
*
* $(document).ready(function() { $('#myForm').bind('submit', function(e) {
* e.preventDefault(); // <-- important $(this).ajaxSubmit({ target:
* '#output' }); }); });
*
* Use ajaxForm when you want the plugin to manage all the event binding for
* you. For example,
*
* $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output'
* }); });
*
* When using ajaxForm, the ajaxSubmit function will be invoked for you at
* the appropriate time.
*/
/**
* ajaxSubmit() provides a mechanism for immediately submitting an HTML form
* using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
if (typeof options == 'function') {
options = {
success : options
};
}
var url = $.trim(this.attr('action'));
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/) || [])[1];
}
url = url || window.location.href || '';
options = $
.extend(
true,
{
url : url,
type : this.attr('method') || 'GET',
iframeSrc : /^https/i
.test(window.location.href || '') ? 'javascript:false'
: 'about:blank'
}, options);
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [ this, options, veto ]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize
&& options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var n, v, a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (n in options.data) {
if (options.data[n] instanceof Array) {
for ( var k in options.data[n]) {
a.push( {
name : n,
value : options.data[n][k]
});
}
} else {
v = options.data[n];
v = $.isFunction(v) ? v() : v; // if value is fn, invoke it
a.push( {
name : n,
value : v
});
}
}
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit
&& options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [ a, this, options, veto ]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
} else {
options.data = q; // data is the query string for 'post'
}
var $form = this, callbacks = [];
if (options.resetForm) {
callbacks.push(function() {
$form.resetForm();
});
}
if (options.clearForm) {
callbacks.push(function() {
$form.clearForm();
});
}
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function() {
};
callbacks.push(function(data) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
} else if (options.success) {
callbacks.push(options.success);
}
options.success = function(data, status, xhr) { // jQuery 1.4+ passes
// xhr as 3rd arg
var context = options.context || options; // jQuery 1.4+ supports
// scope context
for ( var i = 0, max = callbacks.length; i < max; i++) {
callbacks[i].apply(context,
[ data, status, xhr || $form, $form ]);
}
};
// are there files to upload?
var fileInputs = $('input:file', this).length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false
&& (fileInputs || options.iframe || multipart)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see:
// http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, fileUpload);
} else {
fileUpload();
}
} else {
$.ajax(options);
}
// fire 'notify' event
this.trigger('form-submit-notify', [ this, options ]);
return this;
// private function for handling file uploads (hat tip to YAHOO!)
function fileUpload() {
var form = $form[0];
if ($(':input[name=submit],:input[id=submit]', form).length) {
// if there is an input with a name or id of 'submit' then we
// won't be
// able to invoke the submit fn on the form (at least not
// x-browser)
alert('Error: Form elements must not have name or id of "submit".');
return;
}
var s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
var id = 'jqFormIO' + (new Date().getTime()), fn = '_' + id;
window[fn] = function() {
var f = $io.data('form-plugin-onload');
if (f) {
f();
window[fn] = undefined;
try {
delete window[fn];
} catch (e) {
}
}
}
var $io = $('<iframe id="' + id + '" name="' + id + '" src="'
+ s.iframeSrc + '" onload="window[\'_\'+this.id]()" />');
var io = $io[0];
$io.css( {
position : 'absolute',
top : '-1000px',
left : '-1000px'
});
var xhr = { // mock object
aborted : 0,
responseText : null,
responseXML : null,
status : 0,
statusText : 'n/a',
getAllResponseHeaders : function() {
},
getResponseHeader : function() {
},
setRequestHeader : function() {
},
abort : function() {
this.aborted = 1;
$io.attr('src', s.iframeSrc); // abort op in progress
}
};
var g = s.global;
// trigger ajax global events so that activity/block indicators work
// like normal
if (g && !$.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [ xhr, s ]);
}
if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active--;
}
return;
}
if (xhr.aborted) {
return;
}
var cbInvoked = false;
var timedOut = 0;
// add submitting element to data if we know it
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData[n] = sub.value;
if (sub.type == "image") {
s.extraData[n + '.x'] = form.clk_x;
s.extraData[n + '.y'] = form.clk_y;
}
}
}
// take a breath so that pending repaints get some cpu time before
// the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');
// update form attrs in IE friendly way
form.setAttribute('target', id);
if (form.getAttribute('method') != 'POST') {
form.setAttribute('method', 'POST');
}
if (form.getAttribute('action') != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (!s.skipEncodingOverride) {
$form.attr( {
encoding : 'multipart/form-data',
enctype : 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
setTimeout(function() {
timedOut = true;
cb();
}, s.timeout);
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for ( var n in s.extraData) {
extraInputs.push($(
'<input type="hidden" name="' + n
+ '" value="' + s.extraData[n]
+ '" />').appendTo(form)[0]);
}
}
// add iframe to doc and submit the form
$io.appendTo('body');
$io.data('form-plugin-onload', cb);
form.submit();
} finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action', a);
if (t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
if (s.forceSync) {
doSubmit();
} else {
setTimeout(doSubmit, 10); // this lets dom updates render
}
var data, doc, domCheckCount = 50;
function cb() {
if (cbInvoked) {
return;
}
$io.removeData('form-plugin-onload');
var ok = true;
try {
if (timedOut) {
throw 'timeout';
}
// extract the server response from the iframe
doc = io.contentWindow ? io.contentWindow.document
: io.contentDocument ? io.contentDocument
: io.document;
var isXml = s.dataType == 'xml' || doc.XMLDocument
|| $.isXMLDoc(doc);
log('isXml=' + isXml);
if (!isXml && window.opera
&& (doc.body == null || doc.body.innerHTML == '')) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not
// always traversable when
// the onload callback fires, so we loop a bit to
// accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could
// be an empty document
// log('Could not access iframe DOM after mutiple
// tries.');
// throw 'DOMException: not available';
}
// log('response detected');
cbInvoked = true;
xhr.responseText = doc.documentElement ? doc.documentElement.innerHTML
: null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
xhr.getResponseHeader = function(header) {
var headers = {
'content-type' : s.dataType
};
return headers[header];
};
var scr = /(json|script)/.test(s.dataType);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
} else if (scr) {
// account for browsers injecting pre around json
// response
var pre = doc.getElementsByTagName('pre')[0];
var b = doc.getElementsByTagName('body')[0];
if (pre) {
xhr.responseText = pre.innerHTML;
} else if (b) {
xhr.responseText = b.innerHTML;
}
}
} else if (s.dataType == 'xml' && !xhr.responseXML
&& xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = $.httpData(xhr, s.dataType);
} catch (e) {
log('error caught:', e);
ok = false;
xhr.error = e;
$.handleError(s, xhr, 'error', e);
}
// ordering of these callbacks/triggers is odd, but that's how
// $.ajax does it
if (ok) {
s.success.call(s.context, data, 'success', xhr);
if (g) {
$.event.trigger("ajaxSuccess", [ xhr, s ]);
}
}
if (g) {
$.event.trigger("ajaxComplete", [ xhr, s ]);
}
if (g && !--$.active) {
$.event.trigger("ajaxStop");
}
if (s.complete) {
s.complete.call(s.context, xhr, ok ? 'success' : 'error');
}
// clean up
setTimeout(function() {
$io.removeData('form-plugin-onload');
$io.remove();
xhr.responseXML = null;
}, 100);
}
function toXml(s, doc) {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
} else {
doc = (new DOMParser()).parseFromString(s, 'text/xml');
}
return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc
: null;
}
}
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" />
* elements (if the element is used to submit the form). 2. This method will
* include the submit element's name/value data (for the element that was
* used to submit the form). 3. This method binds the submit() method to the
* form for you.
*
* The options argument for ajaxForm works exactly as it does for
* ajaxSubmit. ajaxForm merely passes the options argument along after
* properly binding events for submit elements and the form itself.
*/
$.fn.ajaxForm = function(options) {
// in jQuery 1.3+ we can fix mistakes with the ready state
if (this.length === 0) {
var o = {
s : this.selector,
c : this.context
};
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function() {
$(o.s, o.c).ajaxForm(options);
});
return this;
}
// is your DOM ready?
// http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? ''
: ' (DOM not ready)'));
return this;
}
return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
if (!e.isDefaultPrevented()) { // if event has been canceled, don't
// proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
}).bind('click.form-plugin', function(e) {
var target = e.target;
var $el = $(target);
if (!($el.is(":submit,input:image"))) {
// is this a child element of the submit el? (ex: a span within
// a button)
var t = $el.closest(':submit');
if (t.length == 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use
// dimensions
// plugin
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function() {
form.clk = form.clk_x = form.clk_y = null;
}, 100);
});
};
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An
* example of an array for a simple login form might be:
* [ { name: 'username', value: 'jresig' }, { name: 'password', value:
* 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided
* to the ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length === 0) {
return a;
}
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) {
return a;
}
var i, j, n, v, el, max, jmax;
for (i = 0, max = els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n) {
continue;
}
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if (!el.disabled && form.clk == el) {
a.push( {
name : n,
value : $(el).val()
});
a.push( {
name : n + '.x',
value : form.clk_x
}, {
name : n + '.y',
value : form.clk_y
});
}
continue;
}
v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for (j = 0, jmax = v.length; j < jmax; j++) {
a.push( {
name : n,
value : v[j]
});
}
} else if (v !== null && typeof v != 'undefined') {
a.push( {
name : n,
value : v
});
}
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it
// here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push( {
name : n,
value : $input.val()
});
a.push( {
name : n + '.x',
value : form.clk_x
}, {
name : n + '.y',
value : form.clk_y
});
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return
* a string in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function(semantic) {
// hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format:
* name1=value1&name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) {
return;
}
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for ( var i = 0, max = v.length; i < max; i++) {
a.push( {
name : n,
value : v[i]
});
}
} else if (v !== null && typeof v != 'undefined') {
a.push( {
name : this.name,
value : v
});
}
});
// hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example,
* consider the following form:
*
* <form><fieldset> <input name="A" type="text" /> <input name="A"
* type="text" /> <input name="B" type="checkbox" value="B1" /> <input
* name="B" type="checkbox" value="B2"/> <input name="C" type="radio"
* value="C1" /> <input name="C" type="radio" value="C2" /> </fieldset></form>
*
* var v = $(':text').fieldValue(); // if no values are entered into the
* text inputs v == ['',''] // if values entered into the text inputs are
* 'foo' and 'bar' v == ['foo','bar']
*
* var v = $(':checkbox').fieldValue(); // if neither checkbox is checked v
* === undefined // if both checkboxes are checked v == ['B1', 'B2']
*
* var v = $(':radio').fieldValue(); // if neither radio is checked v ===
* undefined // if first radio is checked v == ['C1']
*
* The successful argument controls whether or not the field element must be
* 'successful' (per
* http://www.w3.org/TR/html4/interact/forms.html#successful-controls). The
* default value of the successful argument is true. If this value is false
* the value(s) for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be
* determined the array will be empty, otherwise it will contain one or more
* values.
*/
$.fn.fieldValue = function(successful) {
for ( var val = [], i = 0, max = this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined'
|| (v.constructor == Array && !v.length)) {
continue;
}
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (successful === undefined) {
successful = true;
}
if (successful
&& (!n || el.disabled || t == 'reset' || t == 'button'
|| (t == 'checkbox' || t == 'radio') && !el.checked
|| (t == 'submit' || t == 'image') && el.form
&& el.form.clk != el || tag == 'select'
&& el.selectedIndex == -1)) {
return null;
}
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) {
return null;
}
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index + 1 : ops.length);
for ( var i = (one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text
: op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};
/**
* Clears the form data. Takes the following actions on the form's input
* fields: - input text fields will have their 'value' property set to the
* empty string - select elements will have their 'selectedIndex' property
* set to -1 - checkbox and radio inputs will have their 'checked' property
* set to false - inputs of type submit, button, reset, and hidden will
* *not* be effected - button elements will *not* be effected
*/
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea') {
this.value = '';
} else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
} else if (tag == 'select') {
this.selectedIndex = -1;
}
});
};
/**
* Resets the form data. Causes all form elements to be reset to their
* original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function'
|| (typeof this.reset == 'object' && !this.reset.nodeType)) {
this.reset();
}
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) {
if (b === undefined) {
b = true;
}
return this.each(function() {
this.disabled = !b;
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function(select) {
if (select === undefined) {
select = true;
}
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio') {
this.checked = select;
} else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
}) ;
};
// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
if ($.fn.ajaxSubmit.debug) {
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,
'');
if (window.console && window.console.log) {
window.console.log(msg);
} else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
}
}
;
})(jQuery);
| JavaScript |
//**********************图片上传预览插件************************
//作者:IDDQD(2009-07-01)
//Email:iddqd5376@163.com
//http://iddqd5376.blog.163.com
//版本:1.0
//说明:图片上传预览插件
//上传的时候可以生成固定宽高范围内的等比例缩放图
//参数设置:
//width 存放图片固定大小容器的宽
//height 存放图片固定大小容器的高
//imgDiv 页面DIV的JQuery的id
//imgType 数组后缀名
//**********************图片上传预览插件*************************
(function($) {
jQuery.fn.extend({
uploadPreview: function(opts) {
opts = jQuery.extend({
width: 0,
height: 0,
imgDiv: "#imgDiv",
imgType: ["gif", "jpeg", "jpg", "bmp", "png"],
callback: function() { return false; }
}, opts || {});
var _self = this;
var _this = $(this);
var imgDiv = $(opts.imgDiv);
imgDiv.width(opts.width);
imgDiv.height(opts.height);
autoScaling = function() {
if ($.browser.version == "7.0" || $.browser.version == "8.0") imgDiv.get(0).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = "image";
var img_width = imgDiv.width();
var img_height = imgDiv.height();
if (img_width > 0 && img_height > 0) {
var rate = (opts.width / img_width < opts.height / img_height) ? opts.width / img_width : opts.height / img_height;
if (rate <= 1) {
if ($.browser.version == "7.0" || $.browser.version == "8.0") imgDiv.get(0).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = "scale";
imgDiv.width(img_width * rate);
imgDiv.height(img_height * rate);
} else {
imgDiv.width(img_width);
imgDiv.height(img_height);
}
var left = (opts.width - imgDiv.width()) * 0.5;
var top = (opts.height - imgDiv.height()) * 0.5;
imgDiv.css({ "margin-left": left, "margin-top": top });
imgDiv.show();
}
}
_this.change(function() {
if (this.value) {
if (!RegExp("\.(" + opts.imgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
alert("图片类型必须是" + opts.imgType.join(",") + "中的一种");
this.value = "";
return false;
}
imgDiv.hide();
if ($.browser.msie) {
if ($.browser.version == "6.0") {
var img = $("<img />");
imgDiv.replaceWith(img);
imgDiv = img;
var image = new Image();
image.src = 'file:///' + this.value;
imgDiv.attr('src', image.src);
autoScaling();
}
else {
imgDiv.css({ filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image)" });
imgDiv.get(0).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = "image";
try {
imgDiv.get(0).filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = this.value;
} catch (e) {
alert("无效的图片文件!");
return;
}
setTimeout("autoScaling()", 100);
}
}
else {
var img = $("<img />");
imgDiv.replaceWith(img);
imgDiv = img;
imgDiv.attr('src', this.files.item(0).getAsDataURL());
imgDiv.css({ "vertical-align": "middle" });
setTimeout("autoScaling()", 100);
}
}
});
}
});
})(jQuery); | JavaScript |
/**
* 값이 존재 하는지 검사.
* 공백, 탭 등의 문자열들은 없는것으로 간주한다.
*/
String.prototype.isValue = function() {
if (this == null || this.replace(/ /gi, "") == "") {
return false;
}
return true;
};
/**
* 정규표현식에 부합되는지 검사
*/
String.prototype.isPattern = function(pattern) {
return pattern.test(this);
};
/**
* 숫자만 구성되었는지 검사
*/
String.prototype.isNumber = function() {
return this.isPattern(/[0-9]/);
};
/**
* 영어 알파벳만 사용되었는지 검사
*/
String.prototype.isAlphabet = function() {
return this.isPattern(/[A-Z]|[a-z]/);
};
/**
* 영어 알파벳과 숫자만 사용되었는지 검사
*/
String.prototype.isAlphabetNum = function() {
return this.isPattern(/[A-Z]|[a-z]|[0-9]/);
};
/**
* 영어 알파벳 대문자만 사용되었는지 검사
*/
String.prototype.isUpperCase = function() {
return this.isPattern(/[A-Z]/);
};
/**
* 영어 알파벳 소문자만 사용되었는지 검사
*/
String.prototype.isLowerCase = function() {
return this.isPattern(/[a-z]/);
};
/**
* 영어 알파벳 대문자와 숫자만 사용되었는지 검사
*/
String.prototype.isUpperCaseNum = function() {
return this.isPattern(/[A-Z]|[0-9]/);
};
/**
* 영어 알파벳 소문자와 숫자만 사용되었는지 검사
*/
String.prototype.isLowerCaseNum = function() {
return this.isPattern(/[a-z]|[0-9]/);
};
/**
* 한글로만 되어 있는지 검사
*/
String.prototype.isKor = function() {
return this.isPattern(/[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]/);
};
/**
* 아이피주소 형식인지 검사
*/
String.prototype.isIp = function() {
return this.isPattern(/^(1|2)?\d?\d([.](1|2)?\d?\d){3}$/);
};
/**
* 핸드폰번호 형식인지 검사
*/
String.prototype.isCellphone = function() {
return this.isPattern(/^01([0|1|6|7|8|9]?)-?([0-9]{3,4})-?([0-9]{4})$/);
};
/**
* 집전화 번호 형식인지 검사
*/
String.prototype.isTelphone = function() {
return this.isPattern(/^\d{2,3}-?\d{3,4}-?\d{4}$/);
};
/**
* URL형식인지 검사
*/
String.prototype.isUrl = function() {
return this.isPattern(/(?:(?:(https?|ftp|telnet):\/\/|[\s\t\r\n\[\]\`\<\>\"\'])((?:[\w$\-_\.+!*\'\(\),]|%[0-9a-f][0-9a-f])*\:(?:[\w$\-_\.+!*\'\(\),;\?&=]|%[0-9a-f][0-9a-f])+\@)?(?:((?:(?:[a-z0-9\-가-힣]+\.)+[a-z0-9\-]{2,})|(?:[\d]{1,3}\.){3}[\d]{1,3})|localhost)(?:\:([0-9]+))?((?:\/(?:[\w$\-_\.+!*\'\(\),;:@&=ㄱ-ㅎㅏ-ㅣ가-힣]|%[0-9a-f][0-9a-f])+)*)(?:\/([^\s\/\?\.:<>|#]*(?:\.[^\s\/\?:<>|#]+)*))?(\/?[\?;](?:[a-z0-9\-]+(?:=[^\s:&<>]*)?\&)*[a-z0-9\-]+(?:=[^\s:&<>]*)?)?(#[\w\-]+)?)/gmi);
};
/**
* 입력값이 이메일 형식인지 체크
*/
String.prototype.isEmail = function() {
return this.isPattern(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/);
};
/**
* 입력값의 바이트 길이를 리턴
*/
String.prototype.getByteLength = function() {
var byteLength = 0;
for (var inx = 0; inx < this.length; inx++) {
var oneChar = escape(this.charAt(inx));
if (oneChar.length == 1) {
byteLength++;
} else if (oneChar.indexOf("%u") != -1) {
byteLength += 2;
} else if (oneChar.indexOf("%") != -1) {
byteLength += oneChar.length / 3;
}
}
return byteLength;
};
/**
* 입력값에서 콤마를 없앤다.
*/
String.prototype.removeComma = function() {
return this.replace(/,/gi, "");
};
/**
* 주민번호 형식이 맞는지 검사한다.
*/
String.prototype.isJumin = function() {
// String은 자기 자신이 문자열 값이므로,
// 문자열 값에 접근하기 위해서는 "this"키워드를 직접 사용해야 한다.
// 값이 없는 경우
if (this == '') {
console.log("값이 저장되어 있지 않음");
return false;
}
// 13글자가 아닌 경우
if (this.length != 13) {
console.log("13글자 아님");
return false;
}
// 숫자로 변경할 수 없는 경우 > 숫자만 입력해야 함
if (isNaN(this)) {
console.log("숫자 변환 불가");
return false;
}
// 빈 배열을 만든다.
var a = new Array();
// 한 글자씩 잘라서 배열로 담는다. --> 배열의 확장
for (var i = 0; i < this.length; i++) {
a[i] = parseInt(this.charAt(i));
}
// 주민번호 계산 식 적용 (출처: 인터넷 어디어디)
var k = 11 - (((a[0] * 2) + (a[1] * 3) + (a[2] * 4) + (a[3] * 5) + (a[4] * 6) + (a[5] * 7) + (a[6] * 8) + (a[7] * 9) + (a[8] * 2) + (a[9] * 3) + (a[10] * 4) + (a[11] * 5)) % 11);
if (k > 9) {
k -= 10;
}
if (k != a[12]) {
// 주민번호 아님
console.log("주민번호 형식 검사 수식에 맞지 않음");
return false;
}
// 모든 과정을 무사 통과하면 주민번호 형식 맞음
return true;
};
| JavaScript |
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement("style");
msViewportStyle.appendChild(document.createTextNode("@-ms-viewport{width:auto!important}"));
document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
} | JavaScript |
/**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* This file was added automatically by CKEditor builder.
* You may re-use it at any time at http://ckeditor.com/builder to build CKEditor again.
*
* NOTE:
* This file is not used by CKEditor, you may remove it.
* Changing this file will not change your CKEditor configuration.
*/
var CKBUILDER_CONFIG = {
skin: 'moono',
preset: 'standard',
ignore: [
'dev',
'.gitignore',
'.gitattributes',
'README.md',
'.mailmap'
],
plugins : {
'about' : 1,
'a11yhelp' : 1,
'basicstyles' : 1,
'blockquote' : 1,
'clipboard' : 1,
'contextmenu' : 1,
'resize' : 1,
'toolbar' : 1,
'elementspath' : 1,
'enterkey' : 1,
'entities' : 1,
'filebrowser' : 1,
'floatingspace' : 1,
'format' : 1,
'htmlwriter' : 1,
'horizontalrule' : 1,
'wysiwygarea' : 1,
'image' : 1,
'indent' : 1,
'link' : 1,
'list' : 1,
'magicline' : 1,
'maximize' : 1,
'pastetext' : 1,
'pastefromword' : 1,
'removeformat' : 1,
'sourcearea' : 1,
'specialchar' : 1,
'scayt' : 1,
'stylescombo' : 1,
'tab' : 1,
'table' : 1,
'tabletools' : 1,
'undo' : 1,
'wsc' : 1,
'dialog' : 1,
'dialogui' : 1,
'menu' : 1,
'floatpanel' : 1,
'panel' : 1,
'button' : 1,
'popup' : 1,
'richcombo' : 1,
'listblock' : 1,
'fakeobjects' : 1,
'menubutton' : 1
},
languages : {
'af' : 1,
'sq' : 1,
'ar' : 1,
'eu' : 1,
'bn' : 1,
'bs' : 1,
'bg' : 1,
'ca' : 1,
'zh-cn' : 1,
'zh' : 1,
'hr' : 1,
'cs' : 1,
'da' : 1,
'nl' : 1,
'en' : 1,
'en-au' : 1,
'en-ca' : 1,
'en-gb' : 1,
'eo' : 1,
'et' : 1,
'fo' : 1,
'fi' : 1,
'fr' : 1,
'fr-ca' : 1,
'gl' : 1,
'ka' : 1,
'de' : 1,
'el' : 1,
'gu' : 1,
'he' : 1,
'hi' : 1,
'hu' : 1,
'is' : 1,
'it' : 1,
'ja' : 1,
'km' : 1,
'ko' : 1,
'ku' : 1,
'lv' : 1,
'lt' : 1,
'mk' : 1,
'ms' : 1,
'mn' : 1,
'no' : 1,
'nb' : 1,
'fa' : 1,
'pl' : 1,
'pt-br' : 1,
'pt' : 1,
'ro' : 1,
'ru' : 1,
'sr' : 1,
'sr-latn' : 1,
'sk' : 1,
'sl' : 1,
'es' : 1,
'sv' : 1,
'th' : 1,
'tr' : 1,
'ug' : 1,
'uk' : 1,
'vi' : 1,
'cy' : 1,
}
}; | JavaScript |
/**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here.
// For the complete reference:
// http://docs.ckeditor.com/#!/api/CKEDITOR.config
// The toolbar groups arrangement, optimized for two toolbar rows.
config.toolbarGroups = [
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] },
{ name: 'links' },
{ name: 'insert' },
{ name: 'forms' },
{ name: 'tools' },
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'others' },
'/',
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
{ name: 'styles' },
{ name: 'colors' },
{ name: 'about' }
];
// Remove some buttons, provided by the standard plugins, which we don't
// need to have in the Standard(s) toolbar.
config.removeButtons = 'Underline,Subscript,Superscript';
// Se the most common block elements.
config.format_tags = 'p;h1;h2;h3;pre';
// Make dialogs simpler.
config.removeDialogTabs = 'image:advanced;link:advanced';
};
| JavaScript |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
| JavaScript |
/**
* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// This file contains style definitions that can be used by CKEditor plugins.
//
// The most common use for it is the "stylescombo" plugin, which shows a combo
// in the editor toolbar, containing all styles. Other plugins instead, like
// the div plugin, use a subset of the styles on their feature.
//
// If you don't have plugins that depend on this file, you can simply ignore it.
// Otherwise it is strongly recommended to customize this file to match your
// website requirements and design properly.
CKEDITOR.stylesSet.add( 'default', [
/* Block Styles */
// These styles are already available in the "Format" combo ("format" plugin),
// so they are not needed here by default. You may enable them to avoid
// placing the "Format" combo in the toolbar, maintaining the same features.
/*
{ name: 'Paragraph', element: 'p' },
{ name: 'Heading 1', element: 'h1' },
{ name: 'Heading 2', element: 'h2' },
{ name: 'Heading 3', element: 'h3' },
{ name: 'Heading 4', element: 'h4' },
{ name: 'Heading 5', element: 'h5' },
{ name: 'Heading 6', element: 'h6' },
{ name: 'Preformatted Text',element: 'pre' },
{ name: 'Address', element: 'address' },
*/
{ name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } },
{ name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } },
{
name: 'Special Container',
element: 'div',
styles: {
padding: '5px 10px',
background: '#eee',
border: '1px solid #ccc'
}
},
/* Inline Styles */
// These are core styles available as toolbar buttons. You may opt enabling
// some of them in the Styles combo, removing them from the toolbar.
// (This requires the "stylescombo" plugin)
/*
{ name: 'Strong', element: 'strong', overrides: 'b' },
{ name: 'Emphasis', element: 'em' , overrides: 'i' },
{ name: 'Underline', element: 'u' },
{ name: 'Strikethrough', element: 'strike' },
{ name: 'Subscript', element: 'sub' },
{ name: 'Superscript', element: 'sup' },
*/
{ name: 'Marker', element: 'span', attributes: { 'class': 'marker' } },
{ name: 'Big', element: 'big' },
{ name: 'Small', element: 'small' },
{ name: 'Typewriter', element: 'tt' },
{ name: 'Computer Code', element: 'code' },
{ name: 'Keyboard Phrase', element: 'kbd' },
{ name: 'Sample Text', element: 'samp' },
{ name: 'Variable', element: 'var' },
{ name: 'Deleted Text', element: 'del' },
{ name: 'Inserted Text', element: 'ins' },
{ name: 'Cited Work', element: 'cite' },
{ name: 'Inline Quotation', element: 'q' },
{ name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } },
{ name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } },
/* Object Styles */
{
name: 'Styled image (left)',
element: 'img',
attributes: { 'class': 'left' }
},
{
name: 'Styled image (right)',
element: 'img',
attributes: { 'class': 'right' }
},
{
name: 'Compact table',
element: 'table',
attributes: {
cellpadding: '5',
cellspacing: '0',
border: '1',
bordercolor: '#ccc'
},
styles: {
'border-collapse': 'collapse'
}
},
{ name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } },
{ name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } }
]);
| JavaScript |
/**
* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.dialog.add( 'myDialog', function( editor ) {
return {
title: 'My Dialog',
minWidth: 400,
minHeight: 200,
contents: [
{
id: 'tab1',
label: 'First Tab',
title: 'First Tab',
elements: [
{
id: 'input1',
type: 'text',
label: 'Text Field'
},
{
id: 'select1',
type: 'select',
label: 'Select Field',
items: [
[ 'option1', 'value1' ],
[ 'option2', 'value2' ]
]
}
]
},
{
id: 'tab2',
label: 'Second Tab',
title: 'Second Tab',
elements: [
{
id: 'button1',
type: 'button',
label: 'Button Field'
}
]
}
]
};
});
| JavaScript |
/**
* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
// Tool scripts for the sample pages.
// This file can be ignored and is not required to make use of CKEditor.
(function() {
// Check for sample compliance.
CKEDITOR.on( 'instanceReady', function( ev ) {
var editor = ev.editor,
meta = CKEDITOR.document.$.getElementsByName( 'ckeditor-sample-required-plugins' ),
requires = meta.length ? CKEDITOR.dom.element.get( meta[ 0 ] ).getAttribute( 'content' ).split( ',' ) : [],
missing = [];
if ( requires.length ) {
for ( var i = 0; i < requires.length; i++ ) {
if ( !editor.plugins[ requires[ i ] ] )
missing.push( '<code>' + requires[ i ] + '</code>' );
}
if ( missing.length ) {
var warn = CKEDITOR.dom.element.createFromHtml(
'<div class="warning">' +
'<span>To fully experience this demo, the ' + missing.join( ', ' ) + ' plugin' + ( missing.length > 1 ? 's are' : ' is' ) + ' required.</span>' +
'</div>'
);
warn.insertBefore( editor.container );
}
}
});
})();
| JavaScript |
/*----------------------------------------\
| Cross Browser Tree Widget 1.1 |
|-----------------------------------------|
| Created by Emil A. Eklund (eae@eae.net) |
| For WebFX (http://webfx.eae.net/) |
|-----------------------------------------|
| This script is provided as is without |
| any warranty whatsoever. It may be used |
| free of charge for non commerical sites |
| For commerical use contact the author |
| of this script for further details. |
|-----------------------------------------|
| Created 2000-12-11 | Updated 2001-09-06 |
\----------------------------------------*/
var webFXTreeConfig = {
rootIcon : 'media/images/empty.png',
openRootIcon : 'media/images/empty.png',
folderIcon : 'media/images/empty.png',
openFolderIcon : 'media/images/empty.png',
fileIcon : 'media/images/empty.png',
iIcon : 'media/images/I.png',
lIcon : 'media/images/L.png',
lMinusIcon : 'media/images/Lminus.png',
lPlusIcon : 'media/images/Lplus.png',
tIcon : 'media/images/T.png',
tMinusIcon : 'media/images/Tminus.png',
tPlusIcon : 'media/images/Tplus.png',
blankIcon : 'media/images/blank.png',
defaultText : 'Tree Item',
defaultAction : 'javascript:void(0);',
defaultTarget : 'right',
defaultBehavior : 'classic'
};
var webFXTreeHandler = {
idCounter : 0,
idPrefix : "webfx-tree-object-",
all : {},
behavior : null,
selected : null,
getId : function() { return this.idPrefix + this.idCounter++; },
toggle : function (oItem) { this.all[oItem.id.replace('-plus','')].toggle(); },
select : function (oItem) { this.all[oItem.id.replace('-icon','')].select(); },
focus : function (oItem) { this.all[oItem.id.replace('-anchor','')].focus(); },
blur : function (oItem) { this.all[oItem.id.replace('-anchor','')].blur(); },
keydown : function (oItem) { return this.all[oItem.id].keydown(window.event.keyCode); },
cookies : new WebFXCookie()
};
/*
* WebFXCookie class
*/
function WebFXCookie() {
if (document.cookie.length) { this.cookies = ' ' + document.cookie; }
}
WebFXCookie.prototype.setCookie = function (key, value) {
document.cookie = key + "=" + escape(value);
}
WebFXCookie.prototype.getCookie = function (key) {
if (this.cookies) {
var start = this.cookies.indexOf(' ' + key + '=');
if (start == -1) { return null; }
var end = this.cookies.indexOf(";", start);
if (end == -1) { end = this.cookies.length; }
end -= start;
var cookie = this.cookies.substr(start,end);
return unescape(cookie.substr(cookie.indexOf('=') + 1, cookie.length - cookie.indexOf('=') + 1));
}
else { return null; }
}
/*
* WebFXTreeAbstractNode class
*/
function WebFXTreeAbstractNode(sText, sAction, sTarget) {
this.childNodes = [];
this.id = webFXTreeHandler.getId();
this.text = sText || webFXTreeConfig.defaultText;
this.action = sAction || webFXTreeConfig.defaultAction;
this.targetWindow = sTarget || webFXTreeConfig.defaultTarget;
this._last = false;
webFXTreeHandler.all[this.id] = this;
}
WebFXTreeAbstractNode.prototype.add = function (node) {
node.parentNode = this;
this.childNodes[this.childNodes.length] = node;
var root = this;
if (this.childNodes.length >=2) {
this.childNodes[this.childNodes.length -2]._last = false;
}
while (root.parentNode) { root = root.parentNode; }
if (root.rendered) {
if (this.childNodes.length >= 2) {
document.getElementById(this.childNodes[this.childNodes.length -2].id + '-plus').src = ((this.childNodes[this.childNodes.length -2].folder)?webFXTreeConfig.tMinusIcon:webFXTreeConfig.tIcon);
if (this.childNodes[this.childNodes.length -2].folder) {
this.childNodes[this.childNodes.length -2].plusIcon = webFXTreeConfig.tPlusIcon;
this.childNodes[this.childNodes.length -2].minusIcon = webFXTreeConfig.tMinusIcon;
}
this.childNodes[this.childNodes.length -2]._last = false;
}
this._last = true;
var foo = this;
while (foo.parentNode) {
for (var i = 0; i < foo.parentNode.childNodes.length; i++) {
if (foo.id == foo.parentNode.childNodes[i].id) { break; }
}
if (++i == foo.parentNode.childNodes.length) { foo.parentNode._last = true; }
else { foo.parentNode._last = false; }
foo = foo.parentNode;
}
document.getElementById(this.id + '-cont').insertAdjacentHTML("beforeEnd", node.toString());
if ((!this.folder) && (!this.openIcon)) {
this.icon = webFXTreeConfig.folderIcon;
this.openIcon = webFXTreeConfig.openFolderIcon;
}
this.folder = true;
this.indent();
this.expand();
}
return node;
}
WebFXTreeAbstractNode.prototype.toggle = function() {
if (this.folder) {
if (this.open) { this.collapse(); }
else { this.expand(); }
}
}
WebFXTreeAbstractNode.prototype.select = function() {
document.getElementById(this.id + '-anchor').focus();
}
WebFXTreeAbstractNode.prototype.focus = function() {
webFXTreeHandler.selected = this;
if ((this.openIcon) && (webFXTreeHandler.behavior != 'classic')) { document.getElementById(this.id + '-icon').src = this.openIcon; }
document.getElementById(this.id + '-anchor').style.backgroundColor = 'highlight';
document.getElementById(this.id + '-anchor').style.color = 'highlighttext';
document.getElementById(this.id + '-anchor').focus();
}
WebFXTreeAbstractNode.prototype.blur = function() {
if ((this.openIcon) && (webFXTreeHandler.behavior != 'classic')) { document.getElementById(this.id + '-icon').src = this.icon; }
document.getElementById(this.id + '-anchor').style.backgroundColor = 'transparent';
document.getElementById(this.id + '-anchor').style.color = 'menutext';
}
WebFXTreeAbstractNode.prototype.doExpand = function() {
if (webFXTreeHandler.behavior == 'classic') { document.getElementById(this.id + '-icon').src = this.openIcon; }
if (this.childNodes.length) { document.getElementById(this.id + '-cont').style.display = 'block'; }
this.open = true;
webFXTreeHandler.cookies.setCookie(this.id.substr(18,this.id.length - 18), '1');
}
WebFXTreeAbstractNode.prototype.doCollapse = function() {
if (webFXTreeHandler.behavior == 'classic') { document.getElementById(this.id + '-icon').src = this.icon; }
if (this.childNodes.length) { document.getElementById(this.id + '-cont').style.display = 'none'; }
this.open = false;
webFXTreeHandler.cookies.setCookie(this.id.substr(18,this.id.length - 18), '0');
}
WebFXTreeAbstractNode.prototype.expandAll = function() {
this.expandChildren();
if ((this.folder) && (!this.open)) { this.expand(); }
}
WebFXTreeAbstractNode.prototype.expandChildren = function() {
for (var i = 0; i < this.childNodes.length; i++) {
this.childNodes[i].expandAll();
} }
WebFXTreeAbstractNode.prototype.collapseAll = function() {
if ((this.folder) && (this.open)) { this.collapse(); }
this.collapseChildren();
}
WebFXTreeAbstractNode.prototype.collapseChildren = function() {
for (var i = 0; i < this.childNodes.length; i++) {
this.childNodes[i].collapseAll();
} }
WebFXTreeAbstractNode.prototype.indent = function(lvl, del, last, level) {
/*
* Since we only want to modify items one level below ourself,
* and since the rightmost indentation position is occupied by
* the plus icon we set this to -2
*/
if (lvl == null) { lvl = -2; }
var state = 0;
for (var i = this.childNodes.length - 1; i >= 0 ; i--) {
state = this.childNodes[i].indent(lvl + 1, del, last, level);
if (state) { return; }
}
if (del) {
if (level >= this._level) {
if (this.folder) {
document.getElementById(this.id + '-plus').src = (this.open)?webFXTreeConfig.lMinusIcon:webFXTreeConfig.lPlusIcon;
this.plusIcon = webFXTreeConfig.lPlusIcon;
this.minusIcon = webFXTreeConfig.lMinusIcon;
}
else { document.getElementById(this.id + '-plus').src = webFXTreeConfig.lIcon; }
return 1;
}
}
var foo = document.getElementById(this.id + '-indent-' + lvl);
if (foo) {
if ((del) && (last)) { foo._last = true; }
if (foo._last) { foo.src = webFXTreeConfig.blankIcon; }
else { foo.src = webFXTreeConfig.iIcon; }
}
return 0;
}
/*
* WebFXTree class
*/
function WebFXTree(sText, sAction, sBehavior, sIcon, sOpenIcon) {
this.base = WebFXTreeAbstractNode;
this.base(sText, sAction);
this.icon = sIcon || webFXTreeConfig.rootIcon;
this.openIcon = sOpenIcon || webFXTreeConfig.openRootIcon;
/* Defaults to open */
this.open = (webFXTreeHandler.cookies.getCookie(this.id.substr(18,this.id.length - 18)) == '0')?false:true;
this.folder = true;
this.rendered = false;
if (!webFXTreeHandler.behavior) { webFXTreeHandler.behavior = sBehavior || webFXTreeConfig.defaultBehavior; }
this.targetWindow = 'right';
}
WebFXTree.prototype = new WebFXTreeAbstractNode;
WebFXTree.prototype.setBehavior = function (sBehavior) {
webFXTreeHandler.behavior = sBehavior;
};
WebFXTree.prototype.getBehavior = function (sBehavior) {
return webFXTreeHandler.behavior;
};
WebFXTree.prototype.getSelected = function() {
if (webFXTreeHandler.selected) { return webFXTreeHandler.selected; }
else { return null; }
}
WebFXTree.prototype.remove = function() { }
WebFXTree.prototype.expand = function() {
this.doExpand();
}
WebFXTree.prototype.collapse = function() {
this.focus();
this.doCollapse();
}
WebFXTree.prototype.getFirst = function() {
return null;
}
WebFXTree.prototype.getLast = function() {
return null;
}
WebFXTree.prototype.getNextSibling = function() {
return null;
}
WebFXTree.prototype.getPreviousSibling = function() {
return null;
}
WebFXTree.prototype.keydown = function(key) {
if (key == 39) { this.expand(); return false; }
if (key == 37) { this.collapse(); return false; }
if ((key == 40) && (this.open)) { this.childNodes[0].select(); return false; }
return true;
}
WebFXTree.prototype.toString = function() {
var str = "<div id=\"" + this.id + "\" ondblclick=\"webFXTreeHandler.toggle(this);\" class=\"webfx-tree-item\" onkeydown=\"return webFXTreeHandler.keydown(this)\">";
str += "<img id=\"" + this.id + "-icon\" class=\"webfx-tree-icon\" src=\"" + ((webFXTreeHandler.behavior == 'classic' && this.open)?this.openIcon:this.icon) + "\" onclick=\"webFXTreeHandler.select(this);\"><a href=\"" + this.action + "\" id=\"" + this.id + "-anchor\" target=\"" + this.targetWindow + "\" onfocus=\"webFXTreeHandler.focus(this);\" onblur=\"webFXTreeHandler.blur(this);\">" + this.text + "</a></div>";
str += "<div id=\"" + this.id + "-cont\" class=\"webfx-tree-container\" style=\"display: " + ((this.open)?'block':'none') + ";\">";
for (var i = 0; i < this.childNodes.length; i++) {
str += this.childNodes[i].toString(i, this.childNodes.length);
}
str += "</div>";
this.rendered = true;
return str;
};
/*
* WebFXTreeItem class
*/
function WebFXTreeItem(sText, sAction, eParent, sIcon, sOpenIcon) {
this.base = WebFXTreeAbstractNode;
this.base(sText, sAction);
/* Defaults to close */
this.open = (webFXTreeHandler.cookies.getCookie(this.id.substr(18,this.id.length - 18)) == '1')?true:false;
if (eParent) { eParent.add(this); }
if (sIcon) { this.icon = sIcon; }
if (sOpenIcon) { this.openIcon = sOpenIcon; }
}
WebFXTreeItem.prototype = new WebFXTreeAbstractNode;
WebFXTreeItem.prototype.remove = function() {
var parentNode = this.parentNode;
var prevSibling = this.getPreviousSibling(true);
var nextSibling = this.getNextSibling(true);
var folder = this.parentNode.folder;
var last = ((nextSibling) && (nextSibling.parentNode) && (nextSibling.parentNode.id == parentNode.id))?false:true;
this.getPreviousSibling().focus();
this._remove();
if (parentNode.childNodes.length == 0) {
parentNode.folder = false;
parentNode.open = false;
}
if (last) {
if (parentNode.id == prevSibling.id) {
document.getElementById(parentNode.id + '-icon').src = webFXTreeConfig.fileIcon;
}
else { }
}
if ((!prevSibling.parentNode) || (prevSibling.parentNode != parentNode)) {
parentNode.indent(null, true, last, this._level);
}
if (document.getElementById(prevSibling.id + '-plus')) {
if (nextSibling) {
if ((parentNode == prevSibling) && (parentNode.getNextSibling)) { document.getElementById(prevSibling.id + '-plus').src = webFXTreeConfig.tIcon; }
else if (nextSibling.parentNode != prevSibling) { document.getElementById(prevSibling.id + '-plus').src = webFXTreeConfig.lIcon; }
}
else { document.getElementById(prevSibling.id + '-plus').src = webFXTreeConfig.lIcon; }
}
}
WebFXTreeItem.prototype._remove = function() {
for (var i = this.childNodes.length - 1; i >= 0; i--) {
this.childNodes[i]._remove();
}
for (var i = 0; i < this.parentNode.childNodes.length; i++) {
if (this.id == this.parentNode.childNodes[i].id) {
for (var j = i; j < this.parentNode.childNodes.length; j++) {
this.parentNode.childNodes[i] = this.parentNode.childNodes[i+1]
}
this.parentNode.childNodes.length = this.parentNode.childNodes.length - 1;
if (i + 1 == this.parentNode.childNodes.length) { this.parentNode._last = true; }
}
}
webFXTreeHandler.all[this.id] = null;
if (document.getElementById(this.id)) {
document.getElementById(this.id).innerHTML = "";
document.getElementById(this.id).removeNode();
}
}
WebFXTreeItem.prototype.expand = function() {
this.doExpand();
document.getElementById(this.id + '-plus').src = this.minusIcon;
}
WebFXTreeItem.prototype.collapse = function() {
this.focus();
this.doCollapse();
document.getElementById(this.id + '-plus').src = this.plusIcon;
}
WebFXTreeItem.prototype.getFirst = function() {
return this.childNodes[0];
}
WebFXTreeItem.prototype.getLast = function() {
if (this.childNodes[this.childNodes.length - 1].open) { return this.childNodes[this.childNodes.length - 1].getLast(); }
else { return this.childNodes[this.childNodes.length - 1]; }
}
WebFXTreeItem.prototype.getNextSibling = function() {
for (var i = 0; i < this.parentNode.childNodes.length; i++) {
if (this == this.parentNode.childNodes[i]) { break; }
}
if (++i == this.parentNode.childNodes.length) { return this.parentNode.getNextSibling(); }
else { return this.parentNode.childNodes[i]; }
}
WebFXTreeItem.prototype.getPreviousSibling = function(b) {
for (var i = 0; i < this.parentNode.childNodes.length; i++) {
if (this == this.parentNode.childNodes[i]) { break; }
}
if (i == 0) { return this.parentNode; }
else {
if ((this.parentNode.childNodes[--i].open) || (b && this.parentNode.childNodes[i].folder)) { return this.parentNode.childNodes[i].getLast(); }
else { return this.parentNode.childNodes[i]; }
} }
WebFXTreeItem.prototype.keydown = function(key) {
if ((key == 39) && (this.folder)) {
if (!this.open) { this.expand(); return false; }
else { this.getFirst().select(); return false; }
}
else if (key == 37) {
if (this.open) { this.collapse(); return false; }
else { this.parentNode.select(); return false; }
}
else if (key == 40) {
if (this.open) { this.getFirst().select(); return false; }
else {
var sib = this.getNextSibling();
if (sib) { sib.select(); return false; }
} }
else if (key == 38) { this.getPreviousSibling().select(); return false; }
return true;
}
WebFXTreeItem.prototype.toString = function (nItem, nItemCount) {
var foo = this.parentNode;
var indent = '';
if (nItem + 1 == nItemCount) { this.parentNode._last = true; }
var i = 0;
while (foo.parentNode) {
foo = foo.parentNode;
indent = "<img id=\"" + this.id + "-indent-" + i + "\" src=\"" + ((foo._last)?webFXTreeConfig.blankIcon:webFXTreeConfig.iIcon) + "\">" + indent;
i++;
}
this._level = i;
if (this.childNodes.length) { this.folder = 1; }
else { this.open = false; }
if ((this.folder) || (webFXTreeHandler.behavior != 'classic')) {
if (!this.icon) { this.icon = webFXTreeConfig.folderIcon; }
if (!this.openIcon) { this.openIcon = webFXTreeConfig.openFolderIcon; }
}
else if (!this.icon) { this.icon = webFXTreeConfig.fileIcon; }
var label = this.text;
label = label.replace('<', '<');
label = label.replace('>', '>');
var str = "<div id=\"" + this.id + "\" ondblclick=\"webFXTreeHandler.toggle(this);\" class=\"webfx-tree-item\" onkeydown=\"return webFXTreeHandler.keydown(this)\">";
str += indent;
str += "<img id=\"" + this.id + "-plus\" src=\"" + ((this.folder)?((this.open)?((this.parentNode._last)?webFXTreeConfig.lMinusIcon:webFXTreeConfig.tMinusIcon):((this.parentNode._last)?webFXTreeConfig.lPlusIcon:webFXTreeConfig.tPlusIcon)):((this.parentNode._last)?webFXTreeConfig.lIcon:webFXTreeConfig.tIcon)) + "\" onclick=\"webFXTreeHandler.toggle(this);\">"
str += "<img id=\"" + this.id + "-icon\" src=\"" + ((webFXTreeHandler.behavior == 'classic' && this.open)?this.openIcon:this.icon) + "\" onclick=\"webFXTreeHandler.select(this);\"><a href=\"" + this.action + "\" id=\"" + this.id + "-anchor\" target=\"" + this.targetWindow + "\" onfocus=\"webFXTreeHandler.focus(this);\" onblur=\"webFXTreeHandler.blur(this);\">" + label + "</a></div>";
str += "<div id=\"" + this.id + "-cont\" class=\"webfx-tree-container\" style=\"display: " + ((this.open)?'block':'none') + ";\">";
for (var i = 0; i < this.childNodes.length; i++) {
str += this.childNodes[i].toString(i,this.childNodes.length);
}
str += "</div>";
this.plusIcon = ((this.parentNode._last)?webFXTreeConfig.lPlusIcon:webFXTreeConfig.tPlusIcon);
this.minusIcon = ((this.parentNode._last)?webFXTreeConfig.lMinusIcon:webFXTreeConfig.tMinusIcon);
return str;
} | JavaScript |
/**
* BBCode editor actions
* @param Int id
*/
function DomBBCodeEditor( id ) {
this.id = id;
this.setCursorPosition = function(ctrl, pos){
if (ctrl.setSelectionRange) {
ctrl.focus();
ctrl.setSelectionRange(pos, pos);
} else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
this.addTag = function(tag1, tag2){
if (tag2 == undefined) {
tag2 = tag1;
tag1 = "";
}
textarea = document.getElementById( this.id );
// Code for IE
if( document.selection ) {
textarea.focus();
var sel = document.selection.createRange();
sel.text = tag1 + sel.text + tag2;
// Code for Mozilla Firefox
} else {
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var scrollTop = textarea.scrollTop;
var scrollLeft = textarea.scrollLeft;
var sel = textarea.value.substring(start, end);
var rep = tag1 + sel + tag2;
textarea.value = textarea.value.substring(0,start) + rep + textarea.value.substring(end,len);
textarea.scrollTop = scrollTop;
textarea.scrollLeft = scrollLeft;
}
textarea.focus();
this.setCursorPosition( textarea, end + tag1.length + tag2.length );
}
this.addImage = function() {
textarea = document.getElementById( this.id );
var url = prompt('Sisestage pildi aadress:','http://');
var scrollTop = textarea.scrollTop;
var scrollLeft = textarea.scrollLeft;
if ( document.selection ) {
textarea.focus();
var sel = document.selection.createRange();
sel.text = '[img]' + url + '[/img]';
} else {
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var sel = textarea.value.substring(start, end);
//alert(sel);
var rep = '[img]' + url + '[/img]';
textarea.value = textarea.value.substring(0,start) + rep + textarea.value.substring(end,len);
textarea.scrollTop = scrollTop;
textarea.scrollLeft = scrollLeft;
}
}
this.addUrl = function() {
textarea = document.getElementById( this.id );
var url = prompt('Sisestage veebilehe aadress:','http://');
var scrollTop = textarea.scrollTop;
var scrollLeft = textarea.scrollLeft;
if( document.selection ) {
textarea.focus();
var sel = document.selection.createRange();
if(sel.text==""){
sel.text = '[url]' + url + '[/url]';
} else {
sel.text = '[url=' + url + ']' + sel.text + '[/url]';
}
} else {
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var sel = textarea.value.substring(start, end);
if(sel==""){
var rep = '[url]' + url + '[/url]';
} else {
var rep = '[url=' + url + ']' + sel + '[/url]';
}
textarea.value = textarea.value.substring(0,start) + rep + textarea.value.substring(end,len);
textarea.scrollTop = scrollTop;
textarea.scrollLeft = scrollLeft;
}
}
}
/**
* Parses BBCode
*
* Usage:
<code>
var editor = new DomBBCode();
html = editor.parse( text );
</code>
*/
function DomBBCodeParser() {
this.opentags; // open tag stack
this.crlf2br = true; // convert CRLF to <br>?
this.noparse = false; // ignore BBCode tags?
this.urlstart = -1; // beginning of the URL if zero or greater (ignored if -1)
// aceptable BBcode tags, optionally prefixed with a slash
this.tagname_re = /^\/?(?:b|i|u|pre|samp|code|colou?r|size|this.noparse|url|s|q|blockquote)$/;
// color names or hex color
this.color_re = /^(:?black|silver|gray|white|maroon|red|purple|fuchsia|green|lime|olive|yellow|navy|blue|teal|aqua|#(?:[0-9a-f]{3})?[0-9a-f]{3})$/i;
// numbers
this.number_re = /^[\\.0-9]{1,8}$/i;
// reserved, unreserved, escaped and alpha-numeric [RFC2396]
this.uri_re = /^[-;\/\?:@&=\+\$,_\.!~\*'\(\)%0-9a-z]{1,512}$/i;
// main regular expression: CRLF, [tag=option], [tag] or [/tag]
this.postfmt_re = /([\r\n])|(?:\[([a-z]{1,16})(?:=([^\x00-\x1F"'\(\)<>\[\]]{1,256}))?\])|(?:\[\/([a-z]{1,16})\])/ig;
// stack frame object
this.taginfo_t = function(bbtag, etag) {
this.bbtag = bbtag;
this.etag = etag;
}
// check if it's a valid BBCode tag
this.isValidTag = function(str) {
if(!str || !str.length)
return false;
return this.tagname_re.test(str);
}
//
// m1 - CR or LF
// m2 - the tag of the [tag=option] expression
// m3 - the option of the [tag=option] expression
// m4 - the end tag of the [/tag] expression
//
this.textToHtmlCB = function(mstr, m1, m2, m3, m4, offset, string) {
//
// CR LF sequences
//
if(m1 && m1.length) {
if(!bbeditor.crlf2br)
return mstr;
switch (m1) {
case '\r':
return "";
case '\n':
return "<br>";
}
}
//
// handle start tags
//
if( bbeditor.isValidTag(m2) ) {
// if in the this.noparse state, just echo the tag
if(bbeditor.noparse)
return "[" + m2 + "]";
// ignore any tags if there's an open option-less [url] tag
if(bbeditor.opentags.length && bbeditor.opentags[bbeditor.opentags.length-1].bbtag == "url" && bbeditor.urlstart >= 0)
return "[" + m2 + "]";
switch (m2) {
case "code":
bbeditor.opentags.push(new bbeditor.taginfo_t(m2, "</code></pre>"));
bbeditor.crlf2br = false;
return "<pre><code>";
case "pre":
bbeditor.opentags.push(new bbeditor.taginfo_t(m2, "</pre>"));
bbeditor.crlf2br = false;
return "<pre>";
case "color":
case "colour":
if(!m3 || !bbeditor.color_re.test(m3))
m3 = "inherit";
bbeditor.opentags.push(new bbeditor.taginfo_t(m2, "</span>"));
return "<span style=\"color: " + m3 + "\">";
case "size":
if(!m3 || !bbeditor.number_re.test(m3))
m3 = "1";
bbeditor.opentags.push(new bbeditor.taginfo_t(m2, "</span>"));
return "<span style=\"font-size: " + Math.min(Math.max(m3, 0.7), 3) + "em\">";
case "s":
bbeditor.opentags.push(new bbeditor.taginfo_t(m2, "</span>"));
return "<span style=\"text-decoration: line-through\">";
case "this.noparse":
bbeditor.noparse = true;
return "";
case "url":
bbeditor.opentags.push(new bbeditor.taginfo_t(m2, "</a>"));
// check if there's a valid option
if(m3 && bbeditor.uri_re.test(m3)) {
// if there is, output a complete start anchor tag
bbeditor.urlstart = -1;
return "<a href=\"" + m3 + "\" target=\"_blank\">";
}
// otherwise, remember the URL offset
bbeditor.urlstart = mstr.length + offset;
// and treat the text following [url] as a URL
return "<a target=\"_blank\" href=\"";
case "q":
case "blockquote":
bbeditor.opentags.push(new bbeditor.taginfo_t(m2, "</" + m2 + ">"));
return m3 && m3.length && bbeditor.uri_re.test(m3) ? "<" + m2 + " cite=\"" + m3 + "\">" : "<" + m2 + ">";
default:
// [samp], [b], [i] and [u] don't need special processing
bbeditor.opentags.push(new bbeditor.taginfo_t(m2, "</" + m2 + ">"));
return "<" + m2 + ">";
}
}
//
// process end tags
//
if( bbeditor.isValidTag(m4) ) {
if(bbeditor.noparse) {
// if it's the closing this.noparse tag, flip the this.noparse state
if(m4 == "this.noparse") {
bbeditor.noparse = false;
return "";
}
// otherwise just output the original text
return "[/" + m4 + "]";
}
// highlight mismatched end tags
if(!bbeditor.opentags.length || bbeditor.opentags[bbeditor.opentags.length-1].bbtag != m4)
return "<span style=\"color: red\">[/" + m4 + "]</span>";
if(m4 == "url") {
// if there was no option, use the content of the [url] tag
if(bbeditor.urlstart > 0)
return "\">" + string.substr(bbeditor.urlstart, offset-bbeditor.urlstart) + bbeditor.opentags.pop().etag;
// otherwise just close the tag
return bbeditor.opentags.pop().etag;
}
else if(m4 == "code" || m4 == "pre")
bbeditor.crlf2br = true;
// other tags require no special processing, just output the end tag
return bbeditor.opentags.pop().etag;
}
return mstr;
}
//
// post must be HTML-encoded
//
this.parse = function(post) {
bbeditor = this;
var result, endtags, tag;
// convert CRLF to <br> by default
this.crlf2br = true;
// create a new array for open tags
if(this.opentags == null || this.opentags.length)
this.opentags = new Array(0);
// run the text through main regular expression matcher
result = post.replace(this.postfmt_re, this.textToHtmlCB);
// reset this.noparse, if it was unbalanced
if(this.noparse)
this.noparse = false;
// if there are any unbalanced tags, make sure to close them
if(this.opentags.length) {
endtags = new String();
// if there's an open [url] at the top, close it
if(this.opentags[this.opentags.length-1].bbtag == "url") {
this.opentags.pop();
endtags += "\">" + post.substr(this.urlstart, post.length-this.urlstart) + "</a>";
}
// close remaining open tags
while(this.opentags.length)
endtags += this.opentags.pop().etag;
}
bbeditor = null;
return endtags ? result + endtags : result;
}
}
| JavaScript |
/*
* Treeview pre-1.4.1 - jQuery plugin to hide and show branches of a tree
*
* http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
* http://docs.jquery.com/Plugins/Treeview
*
* Copyright (c) 2007 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.treeview.js 4684 2008-02-07 19:08:06Z joern.zaefferer $
*
*/
;(function($) {
$.extend($.fn, {
swapClass: function(c1, c2) {
var c1Elements = this.filter('.' + c1);
this.filter('.' + c2).removeClass(c2).addClass(c1);
c1Elements.removeClass(c1).addClass(c2);
return this;
},
replaceClass: function(c1, c2) {
return this.filter('.' + c1).removeClass(c1).addClass(c2).end();
},
hoverClass: function(className) {
className = className || "hover";
return this.hover(function() {
$(this).addClass(className);
}, function() {
$(this).removeClass(className);
});
},
heightToggle: function(animated, callback) {
animated ?
this.animate({ height: "toggle" }, animated, callback) :
this.each(function(){
jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
if(callback)
callback.apply(this, arguments);
});
},
heightHide: function(animated, callback) {
if (animated) {
this.animate({ height: "hide" }, animated, callback);
} else {
this.hide();
if (callback)
this.each(callback);
}
},
prepareBranches: function(settings) {
if (!settings.prerendered) {
// mark last tree items
this.filter(":last-child:not(ul)").addClass(CLASSES.last);
// collapse whole tree, or only those marked as closed, anyway except those marked as open
this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide();
}
// return all items with sublists
return this.filter(":has(>ul)");
},
applyClasses: function(settings, toggler) {
this.filter(":has(>ul):not(:has(>a))").find(">span").click(function(event) {
// don't handle click events on children, eg. checkboxes
if ( this == event.target )
toggler.apply($(this).next());
}).add( $("a", this) ).hoverClass();
if (!settings.prerendered) {
// handle closed ones first
this.filter(":has(>ul:hidden)")
.addClass(CLASSES.expandable)
.replaceClass(CLASSES.last, CLASSES.lastExpandable);
// handle open ones
this.not(":has(>ul:hidden)")
.addClass(CLASSES.collapsable)
.replaceClass(CLASSES.last, CLASSES.lastCollapsable);
// create hitarea
this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea).each(function() {
var classes = "";
$.each($(this).parent().attr("class").split(" "), function() {
classes += this + "-hitarea ";
});
$(this).addClass( classes );
});
}
// apply event to hitarea
this.find("div." + CLASSES.hitarea).click( toggler );
},
treeview: function(settings) {
settings = $.extend({
cookieId: "treeview"
}, settings);
if (settings.add) {
return this.trigger("add", [settings.add]);
}
if ( settings.toggle ) {
var callback = settings.toggle;
settings.toggle = function() {
return callback.apply($(this).parent()[0], arguments);
};
}
// factory for treecontroller
function treeController(tree, control) {
// factory for click handlers
function handler(filter) {
return function() {
// reuse toggle event handler, applying the elements to toggle
// start searching for all hitareas
toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() {
// for plain toggle, no filter is provided, otherwise we need to check the parent element
return filter ? $(this).parent("." + filter).length : true;
}) );
return false;
};
}
// click on first element to collapse tree
$("a:eq(0)", control).click( handler(CLASSES.collapsable) );
// click on second to expand tree
$("a:eq(1)", control).click( handler(CLASSES.expandable) );
// click on third to toggle tree
$("a:eq(2)", control).click( handler() );
}
// handle toggle event
function toggler() {
$(this)
.parent()
// swap classes for hitarea
.find(">.hitarea")
.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
// swap classes for parent li
.swapClass( CLASSES.collapsable, CLASSES.expandable )
.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
// find child lists
.find( ">ul" )
// toggle them
.heightToggle( settings.animated, settings.toggle );
if ( settings.unique ) {
$(this).parent()
.siblings()
// swap classes for hitarea
.find(">.hitarea")
.replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
.replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
.end()
.replaceClass( CLASSES.collapsable, CLASSES.expandable )
.replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
.find( ">ul" )
.heightHide( settings.animated, settings.toggle );
}
}
function serialize() {
function binary(arg) {
return arg ? 1 : 0;
}
var data = [];
branches.each(function(i, e) {
data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0;
});
$.cookie(settings.cookieId, data.join("") );
}
function deserialize() {
var stored = $.cookie(settings.cookieId);
if ( stored ) {
var data = stored.split("");
branches.each(function(i, e) {
$(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ]();
});
}
}
// add treeview class to activate styles
this.addClass("treeview");
// prepare branches and find all tree items with child lists
var branches = this.find("li").prepareBranches(settings);
switch(settings.persist) {
case "cookie":
var toggleCallback = settings.toggle;
settings.toggle = function() {
serialize();
if (toggleCallback) {
toggleCallback.apply(this, arguments);
}
};
deserialize();
break;
case "location":
var current = this.find("a").filter(function() { return this.href.toLowerCase() == location.href.toLowerCase(); });
if ( current.length ) {
current.addClass("selected").parents("ul, li").add( current.next() ).show();
}
break;
}
branches.applyClasses(settings, toggler);
// if control option is set, create the treecontroller and show it
if ( settings.control ) {
treeController(this, settings.control);
$(settings.control).show();
}
return this.bind("add", function(event, branches) {
$(branches).prev()
.removeClass(CLASSES.last)
.removeClass(CLASSES.lastCollapsable)
.removeClass(CLASSES.lastExpandable)
.find(">.hitarea")
.removeClass(CLASSES.lastCollapsableHitarea)
.removeClass(CLASSES.lastExpandableHitarea);
$(branches).find("li").andSelf().prepareBranches(settings).applyClasses(settings, toggler);
});
}
});
// classes used by the plugin
// need to be styled via external stylesheet, see first example
var CLASSES = $.fn.treeview.classes = {
open: "open",
closed: "closed",
expandable: "expandable",
expandableHitarea: "expandable-hitarea",
lastExpandableHitarea: "lastExpandable-hitarea",
collapsable: "collapsable",
collapsableHitarea: "collapsable-hitarea",
lastCollapsableHitarea: "lastCollapsable-hitarea",
lastCollapsable: "lastCollapsable",
lastExpandable: "lastExpandable",
last: "last",
hitarea: "hitarea"
};
// provide backwards compability
$.fn.Treeview = $.fn.treeview;
})(jQuery); | JavaScript |
/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
var path = options.path ? '; path=' + options.path : '';
var domain = options.domain ? '; domain=' + options.domain : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
}; | JavaScript |
/**
* Misc functions
*/
function fg_findPos( p ) {
var left = 0;
var top = 0;
var left = p.offsetLeft
var top = p.offsetTop+10;
for (; p; p = p.offsetParent){
top+= p.offsetTop;
left += p.offsetLeft;
}
return [left,top];
}
function fg_getElementWidth(Elem) {
if ( ns4 ) {
var elem = getObjNN4(document, Elem);
return elem.clip.width;
} else {
if(document.getElementById) {
var elem = document.getElementById(Elem);
} else if (document.all){
var elem = document.all[Elem];
}
if (op5) {
xPos = elem.style.pixelWidth;
} else {
xPos = elem.offsetWidth;
}
return xPos;
}
}
function fg_getElementHeight(Elem) {
if ( ns4 ) {
var elem = getObjNN4(document, Elem);
return elem.clip.height;
} else {
if(document.getElementById) {
var elem = document.getElementById(Elem);
} else if (document.all){
var elem = document.all[Elem];
}
if (op5) {
xPos = elem.style.pixelHeight;
} else {
xPos = elem.offsetHeight;
}
return xPos;
}
}
// Temporary variables to hold mouse x-y pos.s
var fg_mouseX = 0
var fg_mouseY = 0
document.onmousemove = captureMouseXY;
if ( !document.all )
document.captureEvents(Event.MOUSEMOVE)
function captureMouseXY(e) {
if ( document.all ) { // grab the x-y pos.s if browser is IE
fg_mouseX = event.clientX + document.body.scrollLeft
fg_mouseY = event.clientY + document.body.scrollTop
} else { // grab the x-y pos.s if browser is NS
fg_mouseX = e.pageX
fg_mouseY = e.pageY
}
// catch possible negative values in NS4
if (fg_mouseX < 0) fg_mouseX = 0;
if (fg_mouseY < 0) fg_mouseY = 0;
return true;
}
function getMouseXY() {
return [fg_mouseX,fg_mouseY];
}
/**
* Function that toggles tab menu
*/
function fg_showTab( group, tabId, tabNr ) {
eval("var tabs="+group+";");
//document.getElementsByName( group+"_name" );
for( i=0; i<tabs.length; i++) {
tab = document.getElementById( tabs[i] );
if( tab.id == tabId ) {
tab.className = 'selected';
document.getElementById(tab.id+"_frame").style.display = "";
} else {
tab.className = '';
document.getElementById(tab.id+"_frame").style.display = "none";
}
}
document.getElementById(group + "_selectedTab").value = tabNr;
}
/**
* Handles submit button clicks.
*/
function fg_submit( element, name, value, action, target ) {
$(element).append('<input type="hidden" id="'+name+'-id" name="'+name+'" value="'+value+'" />');
var button = document.getElementById( name + "-id" );
button.value = value;
if( action != null)
button.form.action = action;
button.form.submit();
}
function fg_confirm( message, to, target ) {
if( confirm(message) ) {
document.location = to;
}
}
function fg_open( to, target ) {
if( confirm(message) ) {
document.location = to;
}
}
function fg_button_click( element, name, value, link, submitLink, target, confirmMessage ) {
if( confirmMessage != '' && confirmMessage != null ) {
if( confirm(confirmMessage) == false ) {
return;
}
}
if (link != '') {
if (target == '_blank') {
var newWindow = window.open(link, '_blank');
newWindow.focus();
}
else {
document.location = link;
}
} else {
$(element).append('<input type="hidden" id="' + name + '-id" name="' + name + '" value="' + value + '" />');
var button = document.getElementById(name + "-id");
button.value = value;
if( submitLink != "" && submitLink != null) {
button.form.action = submitLink;
}
button.form.submit();
}
}
/**
* Html editor image manager handling function
* @author Oliver Leisalu
* @package DomFg
* @created 11.11.2009
*/
function updateHtmlEditorImage( id, url ) {
window.opener.document.updateContent(id, url);
}
/**
* Panel
* @author Oliver Leisalu
* @package DomFg
* @created 11.11.2009
*/
$.fn.fg_panel = function(options){
var defaults = {
'id' : '',
'closed': false
};
var options = $.extend( defaults, options );
var panelHeader = $("#panelHeader_"+options.id);
var panelContent = $("#panelContent_"+options.id);
if( options.closed ) {
panelContent.slideToggle(0);
}
panelHeader.click( function() {
panelContent.slideToggle(500);
});
}
/**
Drop down menu maker
@author Oliver Leisalu
@package DomFg
@created 16.06.2008
*/
DomFgMenu = function( uid ) {
this.uid = uid;
this.reactionTime = 250;
this.timeout = -1;
this.oTd = null;
this.doMenu = function(td){
clearTimeout(this.timeout);
var i;
var sT="";
var tda=new Array();
var tda = td.id.split("_");
if(this.oTd!=null){
var tdo=new Array();
tdo=this.oTd.id.split("_");
for(i=1;i<tdo.length;i++){
sT+="_"+tdo[i];
if(tdo[i]!=tda[i]){
if(document.getElementById(this.uid+"tbl"+sT)!=null) {
document.getElementById(this.uid+"tbl"+sT).style.visibility="hidden";
document.getElementById(this.uid+"td"+sT).className = "";
}
}
}
}
this.oTd=td;
sT="";
for(i=1;i<tda.length;i++)
sT+="_"+tda[i];
if(document.getElementById(this.uid+"tbl"+sT)!=null) {
document.getElementById(this.uid+"tbl"+sT).style.visibility="visible";
document.getElementById(this.uid+"td"+sT).className = "selected";
//this.setPos( this.uid+"tbl"+sT );
}
}
this.clearMenu = function(){
if(this.oTd!=null){
var tdo=new Array();
tdo=this.oTd.id.split("_");
var sT="";
for(var i=1;i<tdo.length;i++){
sT+="_"+tdo[i];
if(document.getElementById(this.uid+"tbl"+sT)!=null) {
document.getElementById(this.uid+"tbl"+sT).style.visibility="hidden";
document.getElementById(this.uid+"td"+sT).className = "";
}
}
this.oTd=null;
}
}
//this.tt="";
//this.sT="";
//this.pT=new Array();
//this.tA=new Array();
this.setPos = function( st ) {
var pos = this.findPos( st );
var element = document.getElementById( st );
// alert(st+": top:"+pos.top+"px;left:"+pos.left+"px")
//alert(element.id)
element.style.left = pos.left+"px";
element.style.top = pos.top+"px";
if( element.id == 'menu2tbl_0_1') {
//alert('hei')
}
}
this.findPos = function ( st ) {
var tA = st.split("_");
if( tA.length > 2 ){
tA = tA.slice(0,-1);
var tt = tA.join("_");
var main = document.getElementById(this.uid+"tbl"+tt);
var tile = document.getElementById(this.uid+"td"+st);
var curleft = main.offsetWidth;
var curtop = -1;
} else {
var main = document.getElementById(this.uid+"mainmenu");
var tile = document.getElementById(this.uid+"td"+st);
var curleft = 5;
var curtop = tile.offsetHeight;
}
do {
curleft += tile.offsetLeft;
curtop += tile.offsetTop;
} while ( tile = tile.offsetParent )
//alert(st+": top:"+curtop+"px;left:"+curleft+"px")
return {top:curtop,left:curleft}
//return "top:"+curtop+"px;left:"+curleft+"px";
}
this.menuMouseOut = function() {
this.timeout = setTimeout(this.uid+".clearMenu()", this.reactionTime )
}
this.drawMenu = function( menu, parentId ) {
var drawMain = parentId == 0;
if( drawMain == true ) {
var id = this.uid+"mainmenu";
var className = "fg_menu";
var parentId = "";
var style = "";
} else {
var id = this.uid+"tbl"+parentId;
var className = "fg_submenu";
var pos = this.findPos( parentId );
var style = "top:"+pos.top+"px;left:"+pos.left+"px";
}
var html = "<div id=\""+id+"\" class=\""+className+"\" style=\""+style+"\">";
for( var i=0; i<menu.length; i++) {
if( menu[i] ) {
if( menu[i][0] == "separator" ) {
html += "<div class=\"fg_menuSeparator\"></div>";
} else {
html += "<a id=\""+this.uid+"td"+parentId+"_"+i+"\" onmouseover=\""+this.uid+".doMenu(this)\" onmouseout=\""+this.uid+".menuMouseOut()\" href=\""+menu[i][1]+"\">";
html += "<span class=\"fg_border\">";
html += "<span class=\"fg_icon\">";
if( drawMain == false && menu[i][2] != "" )
html += "<img src=\""+menu[i][2]+"\" />";
html += "</span>";
html += "<span class=\""+(menu[i][3].length > 0 ? "fg_hasSubs" : "")+"\">"+menu[i][0]+"</span>";
html += "</span>";
html += "</a>";
}
}
}
document.write( html + "</div>" );
for( var i=0; i<menu.length; i++) {
if( menu[i] && menu[i][3].length > 0 )
this.drawMenu( menu[i][3], parentId+"_"+i );
}
//document.getElementById(uid+"mainmenu").style.visibility="visible";
}
}
/**
DomFgSearchSelect handler
@author Oliver Leisalu
@package DomFg
@created 16.06.2008
*/
function fg_searchSelect( name, url, maxElements, allowAddingNew ) {
this.name = name;
this.url = url;
this.searchElement = document.getElementById( name+"_search");
this.keysElement = document.getElementById( name+"_keys");
this.valuesElement = document.getElementById( name+"_values");
this.resultElement = document.getElementById( name+"_result");
this.resultContentsElement = document.getElementById( name+"_resultContents");
// Table where items are held
this.tableElement = document.getElementById( name+"_table");
// Message that says there are no elements
this.noneElement = document.getElementById( name+"_none");
this.maxElements = maxElements;
this.allowAddingNew = allowAddingNew == 1 ? true : false;
this.newCount = 0;
this.search = function() {
var url = this.url;
var varPos = url.indexOf("[$search]");
if( varPos > 0)
url = url.substr(0,varPos) + this.searchElement.value + url.substr(varPos+9, url.length);
else
url += this.searchElement.value;
eval("function onSuccess( data ) {"+this.name+"_searchObject.finishSearch( data ); }");
jQuery.get( url, {}, onSuccess, 'text');
pos = fg_findPos( this.searchElement );
this.resultElement.style.left = pos[0]-5+"px";
this.resultElement.style.top = pos[1]+8+"px";
this.resultContentsElement.innerHTML = "Laen...";
this.resultElement.style.display = "";
}
this.enterSearch = function ( e ) {
var key = (navigator.appName == "Netscape") ? e.which : e.keyCode;
if( key == 13 || key == 0) {
this.search();
}
}
this.makeValueSafe = function( str ) {
var newStr = str;
newStr = newStr.replace(/\"/g,""");
newStr = newStr.replace(/\'/g,"\\'");
return newStr;
}
this.finishSearch = function( responseText ) {
var rows = eval( responseText )
var contents = "";
if( this.allowAddingNew == true && this.searchElement.value != "")
contents += "<a href=\"javascript:"+this.name+"_searchObject.add('new','"+this.makeValueSafe(this.searchElement.value)+"')\"> Lisa uus: <b>"+this.searchElement.value+"</b></a><br /><br />";
if( rows.length > 0) {
contents += "<b>Leitud vasted</b><br /><ul class=\"fg_searchSelectList\">";
for( i=0; i<rows.length-(document.all ? 1 : 0); i++) {
contents += "<li><a href=\"javascript:"+this.name+"_searchObject.add('"+rows[i].key+"','"+this.makeValueSafe(rows[i].value)+"')\">"+(rows[i].showValue ? rows[i].showValue : rows[i].value)+"</a></li>";
}
contents += "</ul>";
} else {
contents += "<b>Ei leitud tulemusi!</b><br />";
}
this.resultContentsElement.innerHTML = contents;
}
this.hideResult = function() {
this.resultElement.style.display = "none";
}
this.testIfAdded = function( id, name ) {
el = this.keysElement.value.split("|");
values = this.valuesElement.value.split("|");
for( i=0; i<el.length; i++) {
if( el[i] == id || values[i] == name ) {
return true;
}
}
return false;
}
this.add = function( id, value ) {
this.resultElement.style.display = "none";
// checking if max limit has been reached
if( this.maxElements <= this.tableElement.rows.length-1 ) {
alert("Rohkem ei ole lubatud lisada!");
} else {
// if new suggested changing key
if( id == "new" ) {
id = "new"+this.newCount;
this.newCount++;
}
// checking, if item not already added
if( this.testIfAdded( id, value ) == true) {
alert("Juba lisatud!");
} else {
this.valuesElement.value += (this.valuesElement.value != "" ? "|" : "")+value;
this.keysElement.value += (this.keysElement.value != "" ? "|" : "")+id;
this.searchElement.value = "";
var pos = this.tableElement.rows.length;
this.tableElement.insertRow( pos );
var row = this.tableElement.rows[pos];
row.insertCell(0);
row.insertCell(1);
row.style.backgroundColor = "#FFFFFF";
row.cells[0].innerHTML = value;
row.cells[0].width = 190;
row.cells[1].innerHTML = "<a href=\"javascript:"+this.name+"_searchObject.removeValue('"+id+"')\" style=\"color:#990000\">Eemalda</a>";
row.cells[1].width = 20;
this.noneElement.style.display="none";
}
}
}
this.removeValue = function( id ) {
el = this.keysElement.value.split("|");
values = this.valuesElement.value.split("|");
newValues = "";
newKeys = "";
added = false;
for( i=0; i<el.length; i++) {
if( el[i] == id ) {
this.tableElement.deleteRow(i+1)
} else {
newValues += (added == true ? "|" : "") + values[i];
newKeys += (added == true ? "|" : "") + el[i];
added = true;
}
}
this.keysElement.value = newKeys;
this.valuesElement.value = newValues;
if( this.keysElement.value == "") {
this.noneElement.style.display="";
}
}
}
/**
* Mp3Player
*/
function fg_replaceMp3Player( locationId, song, playerLocation ) {
swfobject.embedSWF( playerLocation, locationId, "80", "18", "9.0.0", false, {song: song, playerLocation:playerLocation, playerName:locationId, allowscriptaccess: "always"} );
}
function fg_makeMp3PlayerLocation( id, song, playerLocation ){
try {
e = document.createElement("<div id="+id+" class=\"fg_mp3PlayerSub\" onclick=\"fg_replaceMp3Player(\'"+id+"\',\'"+song+"\',\'"+playerLocation+"\')\" />");
} catch (er) {
e = document.createElement("div");
e.setAttribute("id", id);
e.setAttribute("class", "fg_mp3PlayerSub");
e.setAttribute("onclick","fg_replaceMp3Player(\'"+id+"\',\'"+song+"\',\'"+playerLocation+"\')");
}
t = document.getElementById( id+"Border" ).appendChild( e );
}
function fg_removeMp3Player( id, song, playerLocation ) {
document.getElementById( id+"Border" ).innerHTML = "";
fg_makeMp3PlayerLocation( id, song, playerLocation );
}
/**
DomFgTip handler
Using: onmouseover="tip.show('parent element id','title','contents')"
@author Oliver Leisalu
@package DomFg
@created 27.07.2009
*/
var tip = new fg_toolTip();
function fg_toolTip(){
var currentElement = null;
this.show = function( elementId, title, contents ){
if( this.currentElement != null ) {
this.currentElement.onmousemove = null;
this.currentElement.onmouseout = null;
}
this.currentElement = document.getElementById(elementId);
document.getElementById("fg_toolTipTitle").innerHTML = title;
document.getElementById("fg_toolTipContents").innerHTML = contents;
this.updateLocation();
document.getElementById("fg_toolTip").style.display = "";
document.getElementById("fg_toolTipTitle").style.width = (document.getElementById("fg_toolTipContents").offsetWidth-8)+"px";
this.currentElement.onmousemove = function(){
tip.updateLocation();
};
this.currentElement.onmouseout = function() {
tip.hide();
};
}
this.hide = function(){
document.getElementById("fg_toolTip").style.display = "none";
this.currentElement.onmousemove = null;
this.currentElement.onmouseout = null;
}
this.updateLocation = function() {
var pos = getMouseXY();
document.getElementById("fg_toolTip").style.top = (pos[1]+25)+"px";
document.getElementById("fg_toolTip").style.left = (pos[0]-10)+"px";
}
}
/**
Grid functions
@author Oliver Leisalu
@package DomFg
@created 22.09.2010
*/
function gridOrderBy( gridName, orderByField, orderByDirection ) {
v = document.getElementById( gridName+'_orderBy');
v.value = 1;
v = document.getElementById( gridName+'_orderByField');
v.value = orderByField;
v = document.getElementById( gridName+'_orderByDirection');
v.value = orderByDirection;
v.form.submit();
}
/**
Image grid drag drop interface
@author Oliver Leisalu
@package DomFg
@created 27.07.2009
*/
var activeDroppable = null;
$.fn.fg_galleryItem = function(options){
var defaults = {
'id' : 'default',
'name' : 'default',
'separatorQuery' : '#'+options.id+'_separator',
'orderFunction' : function() {
$("#"+options.id+"_order").get(0).value = "";
$(".fg_imageGrid > div").not(':last').each( function() {
if( this.id != options.id+"_separator") {
$("#"+options.id+"_order").get(0).value += this.id.split('_')[1]+";";
}
});
}
};
var options = $.extend( defaults, options );
options.orderFunction();
return this.each(function( ){
$(this).draggable({
'helper': 'clone',
'opacity':0.4,
'distance':10,
'start': function( event, ui ) {
},
'stop': function( event, ui ) {
$(options.separatorQuery).hide().next().removeClass("fg_imageGridImageOver");
},
'drag': function( event, ui ) {
/*$('#order').html(
(activeDroppable == null ? "element undefined<br>" : "element: "+activeDroppable.text()+" ("+activeDroppable.offset().left+" : "+activeDroppable.offset().top+") <br> ")+
"separator: "+$("#separator").prev().offset().left+":"+$("#separator").prev().offset().top+"<br> "+
"helper: "+ui.position.left+":"+ui.position.top+"<br> "+
"mouse :"+event.pageX+":"+event.pageY );
*/
if( activeDroppable == null)
return;
var separator = $(options.separatorQuery);
separator.next().removeClass("fg_imageGridImageOver");
separator.css("clear",'none');
separator.css("height",separator.next().height()+"px");
// positions element to right
if( activeDroppable.offset().left + activeDroppable.width()/2 < event.pageX ) {
activeDroppable.after( separator );
// determine if next item is not on next line
if( separator.next().offset().top <= event.pageY ) {
separator.next().addClass("fg_imageGridImageOver");
}
// positions element to left
} else {
activeDroppable.before( separator );
separator.next().addClass("fg_imageGridImageOver");
// determine if previous item is on previous line
var marginBetweenItems = separator.next().offset().top - separator.prev().offset().top - separator.prev().height();
if( marginBetweenItems < 0 )
marginBetweenItems = 0;
//$('#order').html(separator.prev().offset().top+" + "+separator.prev().height()+" + "+marginBetweenItems+" < "+separator.next().offset().top );
if( separator.prev().offset().top + separator.prev().height() + marginBetweenItems <= separator.next().offset().top ) {
separator.css('clear','left');
}
}
}
});
$(this).droppable({
'tolerance': 'pointer',
'drop': function( event , ui ) {
$(options.separatorQuery).hide().next().removeClass("fg_imageGridImageOver");
activeDroppable = null;
if( $(this).offset().left + $(this).width()/2 < event.pageX ) {
$(this).after( ui.draggable );
} else {
$(this).before( ui.draggable );
}
options.orderFunction();
},
'over': function( event, ui ) {
activeDroppable = $(this);
$(options.separatorQuery).show().next().addClass("fg_imageGridImageOver");;
},
'out' : function( event, ui ) {
activeDroppable = null;
$(options.separatorQuery).hide().next().removeClass("fg_imageGridImageOver");
}
});
});
};
/**
Init html editor
@author Oliver Leisalu
@package DomFg
@created 22.09.2010
*/
function initHtmlEditor( name, imageManagerUrl, templateUrl ) {
tinyMCE.init({
mode : "exact",
elements : name+"-id",
theme : "advanced",
width: '100%',
media_strict: false,
plugins : "imageManager,flash,safari,advlink,inlinepopups,fullscreen",
theme_advanced_buttons1 : "undo,redo,|,bold,italic,underline,strikethrough,image,imageManager,link,unlink,forecolor,backcolor,formatselect,|,bullist,numlist,|,cleanup,code,fullscreen",
theme_advanced_buttons2 : "",
theme_advanced_buttons3 : "",
theme_advanced_buttons4 : "",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : false,
remove_script_host : 0,
convert_urls : 0,
imageManagerUrl: imageManagerUrl,
setup : function(ed) {
ed.onBeforeSetContent.add(function(ed, o) {
o.content = o.content.replace(/<\?/gi, "<?");
o.content = o.content.replace(/\?>/gi, "?>");
});
},
content_css : templateUrl+"Input/htmlEditor.css"
});
} | JavaScript |
/************************************************************************************************************
JS Calendar
Copyright (C) September 2006 DTHMLGoodies.com, Alf Magne Kalleland
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Dhtmlgoodies.com., hereby disclaims all copyright interest in this script
written by Alf Magne Kalleland.
Alf Magne Kalleland, 2006
Owner of DHTMLgoodies.com
************************************************************************************************************/
/* Update log:
(C) www.dhtmlgoodies.com, September 2005
Version 1.2, November 8th - 2005 - Added <iframe> background in IE
Version 1.3, November 12th - 2005 - Fixed top bar position in Opera 7
Version 1.4, December 28th - 2005 - Support for Spanish and Portuguese
Version 1.5, January 18th - 2006 - Fixed problem with next-previous buttons after a month has been selected from dropdown
Version 1.6, February 22nd - 2006 - Added variable which holds the path to images.
Format todays date at the bottom by use of the todayStringFormat variable
Pick todays date by clicking on todays date at the bottom of the calendar
Version 2.0 May, 25th - 2006 - Added support for time(hour and minutes) and changing year and hour when holding mouse over + and - options. (i.e. instead of click)
Version 2.1 July, 2nd - 2006 - Added support for more date formats(example: d.m.yyyy, i.e. one letter day and month).
// Modifications by Gregg Buntin
Version 2.1.1 8/9/2007 gfb - Add switch to turn off Year Span Selection
This allows me to only have this year & next year in the drop down
Version 2.1.2 8/30/2007 gfb - Add switch to start week on Sunday
Add switch to turn off week number display
Fix bug when using on an HTTPS page
*/
var turnOffYearSpan = false; // true = Only show This Year and Next, false = show +/- 5 years
var weekStartsOnSunday = false; // true = Start the week on Sunday, false = start the week on Monday
var showWeekNumber = true; // true = show week number, false = do not show week number
var languageCode = 'ee'; // Possible values: en,ge,no,nl,es,pt-br,fr
// en = english, ge = german, no = norwegian,nl = dutch, es = spanish, pt-br = portuguese, fr = french, da = danish, hu = hungarian(Use UTF-8 doctype for hungarian)
var calendar_display_time = true;
// Format of current day at the bottom of the calendar
// [todayString] = the value of todayString
// [dayString] = day of week (examle: mon, tue, wed...)
// [UCFdayString] = day of week (examle: Mon, Tue, Wed...) ( First letter in uppercase)
// [day] = Day of month, 1..31
// [monthString] = Name of current month
// [year] = Current year
var todayStringFormat = '[todayString] [UCFdayString]. [day]. [monthString] [year]';
var pathToImages = templateUrl+'Input/Calendar/images/'; // Relative to your HTML file
var speedOfSelectBoxSliding = 200; // Milliseconds between changing year and hour when holding mouse over "-" and "+" - lower value = faster
var intervalSelectBox_minutes = 5; // Minute select box - interval between each option (5 = default)
var calendar_offsetTop = 0; // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
var calendar_offsetLeft = 0; // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
var calendarDiv = false;
var MSIE = false;
var Opera = false;
if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)MSIE=true;
if(navigator.userAgent.indexOf('Opera')>=0)Opera=true;
switch(languageCode){
case "en": /* English */
var monthArray = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var dayArray = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
var weekString = 'Week';
var todayString = '';
break;
case "ge": /* German */
var monthArray = ['Januar','Februar','M�rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'];
var dayArray = ['Mon','Die','Mit','Don','Fre','Sam','Son'];
var weekString = 'Woche';
var todayString = 'Heute';
break;
case "no": /* Norwegian */
var monthArray = ['Januar','Februar','Mars','April','Mai','Juni','Juli','August','September','Oktober','November','Desember'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Des'];
var dayArray = ['Man','Tir','Ons','Tor','Fre','Lør','Søn'];
var weekString = 'Uke';
var todayString = 'Dagen i dag er';
break;
case "nl": /* Dutch */
var monthArray = ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Aug','Sep','Okt','Nov','Dec'];
var dayArray = ['Ma','Di','Wo','Do','Vr','Za','Zo'];
var weekString = 'Week';
var todayString = 'Vandaag';
break;
case "es": /* Spanish */
var monthArray = ['Enero','Febrero','Marzo','April','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
var monthArrayShort =['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
var dayArray = ['Lun','Mar','Mie','Jue','Vie','Sab','Dom'];
var weekString = 'Semana';
var todayString = 'Hoy es';
break;
case "pt-br": /* Brazilian portuguese (pt-br) */
var monthArray = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
var monthArrayShort = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];
var dayArray = ['Seg','Ter','Qua','Qui','Sex','Sáb','Dom'];
var weekString = 'Sem.';
var todayString = 'Hoje é';
break;
case "fr": /* French */
var monthArray = ['Janvier','F�vrier','Mars','Avril','Mai','Juin','Juillet','Ao�t','Septembre','Octobre','Novembre','D�cembre'];
var monthArrayShort = ['Jan','Fev','Mar','Avr','Mai','Jun','Jul','Aou','Sep','Oct','Nov','Dec'];
var dayArray = ['Lun','Mar','Mer','Jeu','Ven','Sam','Dim'];
var weekString = 'Sem';
var todayString = "Aujourd'hui";
break;
case "da": /*Danish*/
var monthArray = ['januar','februar','marts','april','maj','juni','juli','august','september','oktober','november','december'];
var monthArrayShort = ['jan','feb','mar','apr','maj','jun','jul','aug','sep','okt','nov','dec'];
var dayArray = ['man','tirs','ons','tors','fre','lør','søn'];
var weekString = 'Uge';
var todayString = 'I dag er den';
break;
case "hu": /* Hungarian - Remember to use UTF-8 encoding, i.e. the <meta> tag */
var monthArray = ['Január','Február','Március','�?prilis','Május','Június','Július','Augusztus','Szeptember','Október','November','December'];
var monthArrayShort = ['Jan','Feb','Márc','�?pr','Máj','Jún','Júl','Aug','Szep','Okt','Nov','Dec'];
var dayArray = ['Hé','Ke','Sze','Cs','Pé','Szo','Vas'];
var weekString = 'Hét';
var todayString = 'Mai nap';
break;
case "it": /* Italian*/
var monthArray = ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'];
var monthArrayShort = ['Gen','Feb','Mar','Apr','Mag','Giu','Lugl','Ago','Set','Ott','Nov','Dic'];
var dayArray = ['Lun',';Mar','Mer','Gio','Ven','Sab','Dom'];
var weekString = 'Settimana';
var todayString = 'Oggi è il';
break;
case "sv": /* Swedish */
var monthArray = ['Januari','Februari','Mars','April','Maj','Juni','Juli','Augusti','September','Oktober','November','December'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','Maj','Jun','Jul','Aug','Sep','Okt','Nov','Dec'];
var dayArray = ['Mån','Tis','Ons','Tor','Fre','Lör','Sön'];
var weekString = 'Vecka';
var todayString = 'Idag är det den';
break;
case "cz": /* Czech */
var monthArray = ['leden','únor','březen','duben','květen','červen','červenec','srpen','září','říjen','listopad','prosinec'];
var monthArrayShort = ['led','ún','bř','dub','kvě','čer','čer-ec','srp','zář','říj','list','pros'];
var dayArray = ['Pon','Út','St','Čt','Pá','So','Ne'];
var weekString = 'týden';
var todayString = '';
break;
case "ee": /* English */
var monthArray = ['Jaanuar','Veebruar','Märts','Aprill','Mai','Juuni','Juuli','August','September','Oktoober','November','Detsember'];
var monthArrayShort = ['Jan','Veb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Det'];
var dayArray = ['Esm','Tei','Kol','Nel','Ree','lau','Püh'];
var weekString = 'Nädal';
var todayString = '';
break;
}
if (weekStartsOnSunday) {
var tempDayName = dayArray[6];
for(var theIx = 6; theIx > 0; theIx--) {
dayArray[theIx] = dayArray[theIx-1];
}
dayArray[0] = tempDayName;
}
var daysInMonthArray = [31,28,31,30,31,30,31,31,30,31,30,31];
var currentMonth;
var currentYear;
var currentHour;
var currentMinute;
var calendarContentDiv;
var returnDateTo;
var returnFormat;
var activeSelectBoxMonth;
var activeSelectBoxYear;
var activeSelectBoxHour;
var activeSelectBoxMinute;
var iframeObj = false;
//// fix for EI frame problem on time dropdowns 09/30/2006
var iframeObj2 =false;
function EIS_FIX_EI1(where2fixit)
{
if(!iframeObj2)return;
iframeObj2.style.display = 'block';
iframeObj2.style.height =document.getElementById(where2fixit).offsetHeight+1;
iframeObj2.style.width=document.getElementById(where2fixit).offsetWidth;
iframeObj2.style.left=getleftPos(document.getElementById(where2fixit))+1-calendar_offsetLeft;
iframeObj2.style.top=getTopPos(document.getElementById(where2fixit))-document.getElementById(where2fixit).offsetHeight-calendar_offsetTop;
}
function EIS_Hide_Frame()
{ if(iframeObj2)iframeObj2.style.display = 'none';}
//// fix for EI frame problem on time dropdowns 09/30/2006
var returnDateToYear;
var returnDateToMonth;
var returnDateToDay;
var returnDateToHour;
var returnDateToMinute;
var inputYear;
var inputMonth;
var inputDay;
var inputHour;
var inputMinute;
var calendarDisplayTime = false;
var selectBoxHighlightColor = '#D60808'; // Highlight color of select boxes
var selectBoxRolloverBgColor = '#E2EBED'; // Background color on drop down lists(rollover)
var selectBoxMovementInProgress = false;
var activeSelectBox = false;
function cancelCalendarEvent()
{
return false;
}
function isLeapYear(inputYear)
{
if(inputYear%400==0||(inputYear%4==0&&inputYear%100!=0)) return true;
return false;
}
var activeSelectBoxMonth = false;
var activeSelectBoxDirection = false;
function highlightMonthYear()
{
if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
activeSelectBox = this;
if(this.className=='monthYearActive'){
this.className='';
}else{
this.className = 'monthYearActive';
activeSelectBoxMonth = this;
}
if(this.innerHTML.indexOf('-')>=0 || this.innerHTML.indexOf('+')>=0){
if(this.className=='monthYearActive')
selectBoxMovementInProgress = true;
else
selectBoxMovementInProgress = false;
if(this.innerHTML.indexOf('-')>=0)activeSelectBoxDirection = -1; else activeSelectBoxDirection = 1;
}else selectBoxMovementInProgress = false;
}
function showMonthDropDown()
{
if(document.getElementById('monthDropDown').style.display=='block'){
document.getElementById('monthDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
}else{
document.getElementById('monthDropDown').style.display='block';
document.getElementById('yearDropDown').style.display='none';
document.getElementById('hourDropDown').style.display='none';
document.getElementById('minuteDropDown').style.display='none';
if (MSIE)
{ EIS_FIX_EI1('monthDropDown')}
//// fix for EI frame problem on time dropdowns 09/30/2006
}
}
function showYearDropDown()
{
if(document.getElementById('yearDropDown').style.display=='block'){
document.getElementById('yearDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
}else{
document.getElementById('yearDropDown').style.display='block';
document.getElementById('monthDropDown').style.display='none';
document.getElementById('hourDropDown').style.display='none';
document.getElementById('minuteDropDown').style.display='none';
if (MSIE)
{ EIS_FIX_EI1('yearDropDown')}
//// fix for EI frame problem on time dropdowns 09/30/2006
}
}
function showHourDropDown()
{
if(document.getElementById('hourDropDown').style.display=='block'){
document.getElementById('hourDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
}else{
document.getElementById('hourDropDown').style.display='block';
document.getElementById('monthDropDown').style.display='none';
document.getElementById('yearDropDown').style.display='none';
document.getElementById('minuteDropDown').style.display='none';
if (MSIE)
{ EIS_FIX_EI1('hourDropDown')}
//// fix for EI frame problem on time dropdowns 09/30/2006
}
}
function showMinuteDropDown()
{
if(document.getElementById('minuteDropDown').style.display=='block'){
document.getElementById('minuteDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
}else{
document.getElementById('minuteDropDown').style.display='block';
document.getElementById('monthDropDown').style.display='none';
document.getElementById('yearDropDown').style.display='none';
document.getElementById('hourDropDown').style.display='none';
if (MSIE)
{ EIS_FIX_EI1('minuteDropDown')}
//// fix for EI frame problem on time dropdowns 09/30/2006
}
}
function selectMonth()
{
document.getElementById('calendar_month_txt').innerHTML = this.innerHTML
currentMonth = this.id.replace(/[^\d]/g,'');
document.getElementById('monthDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
for(var no=0;no<monthArray.length;no++){
document.getElementById('monthDiv_'+no).style.color='';
}
this.style.color = selectBoxHighlightColor;
activeSelectBoxMonth = this;
writeCalendarContent();
}
function selectHour()
{
document.getElementById('calendar_hour_txt').innerHTML = this.innerHTML
currentHour = this.innerHTML.replace(/[^\d]/g,'');
document.getElementById('hourDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
if(activeSelectBoxHour){
activeSelectBoxHour.style.color='';
}
activeSelectBoxHour=this;
this.style.color = selectBoxHighlightColor;
}
function selectMinute()
{
document.getElementById('calendar_minute_txt').innerHTML = this.innerHTML
currentMinute = this.innerHTML.replace(/[^\d]/g,'');
document.getElementById('minuteDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
if(activeSelectBoxMinute){
activeSelectBoxMinute.style.color='';
}
activeSelectBoxMinute=this;
this.style.color = selectBoxHighlightColor;
}
function selectYear()
{
document.getElementById('calendar_year_txt').innerHTML = this.innerHTML
currentYear = this.innerHTML.replace(/[^\d]/g,'');
document.getElementById('yearDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
if(activeSelectBoxYear){
activeSelectBoxYear.style.color='';
}
activeSelectBoxYear=this;
this.style.color = selectBoxHighlightColor;
writeCalendarContent();
}
function switchMonth()
{
if(this.src.indexOf('left')>=0){
currentMonth=currentMonth-1;;
if(currentMonth<0){
currentMonth=11;
currentYear=currentYear-1;
}
}else{
currentMonth=currentMonth+1;;
if(currentMonth>11){
currentMonth=0;
currentYear=currentYear/1+1;
}
}
writeCalendarContent();
}
function createMonthDiv(){
var div = document.createElement('DIV');
div.className='monthYearPicker';
div.id = 'monthPicker';
for(var no=0;no<monthArray.length;no++){
var subDiv = document.createElement('DIV');
subDiv.innerHTML = monthArray[no];
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = highlightMonthYear;
subDiv.onclick = selectMonth;
subDiv.id = 'monthDiv_' + no;
subDiv.style.width = '56px';
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
if(currentMonth && currentMonth==no){
subDiv.style.color = selectBoxHighlightColor;
activeSelectBoxMonth = subDiv;
}
}
return div;
}
function changeSelectBoxYear(e,inputObj)
{
if(!inputObj)inputObj =this;
var yearItems = inputObj.parentNode.getElementsByTagName('DIV');
if(inputObj.innerHTML.indexOf('-')>=0){
var startYear = yearItems[1].innerHTML/1 -1;
if(activeSelectBoxYear){
activeSelectBoxYear.style.color='';
}
}else{
var startYear = yearItems[1].innerHTML/1 +1;
if(activeSelectBoxYear){
activeSelectBoxYear.style.color='';
}
}
for(var no=1;no<yearItems.length-1;no++){
yearItems[no].innerHTML = startYear+no-1;
yearItems[no].id = 'yearDiv' + (startYear/1+no/1-1);
}
if(activeSelectBoxYear){
activeSelectBoxYear.style.color='';
if(document.getElementById('yearDiv'+currentYear)){
activeSelectBoxYear = document.getElementById('yearDiv'+currentYear);
activeSelectBoxYear.style.color=selectBoxHighlightColor;;
}
}
}
function changeSelectBoxHour(e,inputObj)
{
if(!inputObj)inputObj = this;
var hourItems = inputObj.parentNode.getElementsByTagName('DIV');
if(inputObj.innerHTML.indexOf('-')>=0){
var startHour = hourItems[1].innerHTML/1 -1;
if(startHour<0)startHour=0;
if(activeSelectBoxHour){
activeSelectBoxHour.style.color='';
}
}else{
var startHour = hourItems[1].innerHTML/1 +1;
if(startHour>14)startHour = 14;
if(activeSelectBoxHour){
activeSelectBoxHour.style.color='';
}
}
var prefix = '';
for(var no=1;no<hourItems.length-1;no++){
if((startHour/1 + no/1) < 11)prefix = '0'; else prefix = '';
hourItems[no].innerHTML = prefix + (startHour+no-1);
hourItems[no].id = 'hourDiv' + (startHour/1+no/1-1);
}
if(activeSelectBoxHour){
activeSelectBoxHour.style.color='';
if(document.getElementById('hourDiv'+currentHour)){
activeSelectBoxHour = document.getElementById('hourDiv'+currentHour);
activeSelectBoxHour.style.color=selectBoxHighlightColor;;
}
}
}
function updateYearDiv()
{
var yearSpan = 5;
if (turnOffYearSpan) {
yearSpan = 0;
}
var div = document.getElementById('yearDropDown');
var yearItems = div.getElementsByTagName('DIV');
for(var no=1;no<yearItems.length-1;no++){
yearItems[no].innerHTML = currentYear/1 -yearSpan + no;
if(currentYear==(currentYear/1 -yearSpan + no)){
yearItems[no].style.color = selectBoxHighlightColor;
activeSelectBoxYear = yearItems[no];
}else{
yearItems[no].style.color = '';
}
}
}
function updateMonthDiv()
{
for(no=0;no<12;no++){
document.getElementById('monthDiv_' + no).style.color = '';
}
document.getElementById('monthDiv_' + currentMonth).style.color = selectBoxHighlightColor;
activeSelectBoxMonth = document.getElementById('monthDiv_' + currentMonth);
}
function updateHourDiv()
{
var div = document.getElementById('hourDropDown');
var hourItems = div.getElementsByTagName('DIV');
var addHours = 0;
if((currentHour/1 -6 + 1)<0){
addHours = (currentHour/1 -6 + 1)*-1;
}
for(var no=1;no<hourItems.length-1;no++){
var prefix='';
if((currentHour/1 -6 + no + addHours) < 10)prefix='0';
hourItems[no].innerHTML = prefix + (currentHour/1 -6 + no + addHours);
if(currentHour==(currentHour/1 -6 + no)){
hourItems[no].style.color = selectBoxHighlightColor;
activeSelectBoxHour = hourItems[no];
}else{
hourItems[no].style.color = '';
}
}
}
function updateMinuteDiv()
{
for(no=0;no<60;no+=intervalSelectBox_minutes){
var prefix = '';
if(no<10)prefix = '0';
document.getElementById('minuteDiv_' + prefix + no).style.color = '';
}
if(document.getElementById('minuteDiv_' + currentMinute)){
document.getElementById('minuteDiv_' + currentMinute).style.color = selectBoxHighlightColor;
activeSelectBoxMinute = document.getElementById('minuteDiv_' + currentMinute);
}
}
function createYearDiv()
{
if(!document.getElementById('yearDropDown')){
var div = document.createElement('DIV');
div.className='monthYearPicker';
}else{
var div = document.getElementById('yearDropDown');
var subDivs = div.getElementsByTagName('DIV');
for(var no=0;no<subDivs.length;no++){
subDivs[no].parentNode.removeChild(subDivs[no]);
}
}
var d = new Date();
if(currentYear){
d.setFullYear(currentYear);
}
var startYear = d.getFullYear()/1 - 5;
var yearSpan = 10;
if (! turnOffYearSpan) {
var subDiv = document.createElement('DIV');
subDiv.innerHTML = ' - ';
subDiv.onclick = changeSelectBoxYear;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
} else {
startYear = d.getFullYear()/1 - 0;
yearSpan = 2;
}
for(var no=startYear;no<(startYear+yearSpan);no++){
var subDiv = document.createElement('DIV');
subDiv.innerHTML = no;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = highlightMonthYear;
subDiv.onclick = selectYear;
subDiv.id = 'yearDiv' + no;
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
if(currentYear && currentYear==no){
subDiv.style.color = selectBoxHighlightColor;
activeSelectBoxYear = subDiv;
}
}
if (! turnOffYearSpan) {
var subDiv = document.createElement('DIV');
subDiv.innerHTML = ' + ';
subDiv.onclick = changeSelectBoxYear;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
}
return div;
}
/* This function creates the hour div at the bottom bar */
function slideCalendarSelectBox()
{
if(selectBoxMovementInProgress){
if(activeSelectBox.parentNode.id=='hourDropDown'){
changeSelectBoxHour(false,activeSelectBox);
}
if(activeSelectBox.parentNode.id=='yearDropDown'){
changeSelectBoxYear(false,activeSelectBox);
}
}
setTimeout('slideCalendarSelectBox()',speedOfSelectBoxSliding);
}
function createHourDiv()
{
if(!document.getElementById('hourDropDown')){
var div = document.createElement('DIV');
div.className='monthYearPicker';
}else{
var div = document.getElementById('hourDropDown');
var subDivs = div.getElementsByTagName('DIV');
for(var no=0;no<subDivs.length;no++){
subDivs[no].parentNode.removeChild(subDivs[no]);
}
}
if(!currentHour)currentHour=0;
var startHour = currentHour/1;
if(startHour>14)startHour=14;
var subDiv = document.createElement('DIV');
subDiv.innerHTML = ' - ';
subDiv.onclick = changeSelectBoxHour;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
for(var no=startHour;no<startHour+10;no++){
var prefix = '';
if(no/1<10)prefix='0';
var subDiv = document.createElement('DIV');
subDiv.innerHTML = prefix + no;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = highlightMonthYear;
subDiv.onclick = selectHour;
subDiv.id = 'hourDiv' + no;
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
if(currentYear && currentYear==no){
subDiv.style.color = selectBoxHighlightColor;
activeSelectBoxYear = subDiv;
}
}
var subDiv = document.createElement('DIV');
subDiv.innerHTML = ' + ';
subDiv.onclick = changeSelectBoxHour;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
return div;
}
/* This function creates the minute div at the bottom bar */
function createMinuteDiv()
{
if(!document.getElementById('minuteDropDown')){
var div = document.createElement('DIV');
div.className='monthYearPicker';
}else{
var div = document.getElementById('minuteDropDown');
var subDivs = div.getElementsByTagName('DIV');
for(var no=0;no<subDivs.length;no++){
subDivs[no].parentNode.removeChild(subDivs[no]);
}
}
var startMinute = 0;
var prefix = '';
for(var no=startMinute;no<60;no+=intervalSelectBox_minutes){
if(no<10)prefix='0'; else prefix = '';
var subDiv = document.createElement('DIV');
subDiv.innerHTML = prefix + no;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = highlightMonthYear;
subDiv.onclick = selectMinute;
subDiv.id = 'minuteDiv_' + prefix + no;
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
if(currentYear && currentYear==no){
subDiv.style.color = selectBoxHighlightColor;
activeSelectBoxYear = subDiv;
}
}
return div;
}
function highlightSelect()
{
if(this.className=='selectBoxTime'){
this.className = 'selectBoxTimeOver';
this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_time_over.gif';
}else if(this.className=='selectBoxTimeOver'){
this.className = 'selectBoxTime';
this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_time.gif';
}
if(this.className=='selectBox'){
this.className = 'selectBoxOver';
this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_over.gif';
}else if(this.className=='selectBoxOver'){
this.className = 'selectBox';
this.getElementsByTagName('IMG')[0].src = pathToImages + 'down.gif';
}
}
function highlightArrow()
{
if(this.src.indexOf('over')>=0){
if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left.gif';
if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right.gif';
}else{
if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left_over.gif';
if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right_over.gif';
}
}
function highlightClose()
{
if(this.src.indexOf('over')>=0){
this.src = pathToImages + 'close.gif';
}else{
this.src = pathToImages + 'close_over.gif';
}
}
function closeCalendar(){
document.getElementById('yearDropDown').style.display='none';
document.getElementById('monthDropDown').style.display='none';
document.getElementById('hourDropDown').style.display='none';
document.getElementById('minuteDropDown').style.display='none';
calendarDiv.style.display='none';
if(iframeObj){
iframeObj.style.display='none';
//// //// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();}
if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
if(activeSelectBoxYear)activeSelectBoxYear.className='';
}
function writeTopBar()
{
var topBar = document.createElement('DIV');
topBar.className = 'topBar';
topBar.id = 'topBar';
calendarDiv.appendChild(topBar);
// Left arrow
var leftDiv = document.createElement('DIV');
leftDiv.style.marginRight = '1px';
var img = document.createElement('IMG');
img.src = pathToImages + 'left.gif';
img.onmouseover = highlightArrow;
img.onclick = switchMonth;
img.onmouseout = highlightArrow;
leftDiv.appendChild(img);
topBar.appendChild(leftDiv);
if(Opera)leftDiv.style.width = '16px';
// Right arrow
var rightDiv = document.createElement('DIV');
rightDiv.style.marginRight = '1px';
var img = document.createElement('IMG');
img.src = pathToImages + 'right.gif';
img.onclick = switchMonth;
img.onmouseover = highlightArrow;
img.onmouseout = highlightArrow;
rightDiv.appendChild(img);
if(Opera)rightDiv.style.width = '16px';
topBar.appendChild(rightDiv);
// Month selector
var monthDiv = document.createElement('DIV');
monthDiv.id = 'monthSelect';
monthDiv.onmouseover = highlightSelect;
monthDiv.onmouseout = highlightSelect;
monthDiv.onclick = showMonthDropDown;
var span = document.createElement('SPAN');
span.innerHTML = monthArray[currentMonth];
span.id = 'calendar_month_txt';
monthDiv.appendChild(span);
var img = document.createElement('IMG');
img.src = pathToImages + 'down.gif';
img.style.position = 'absolute';
img.style.right = '0px';
monthDiv.appendChild(img);
monthDiv.className = 'selectBox';
if(Opera){
img.style.cssText = 'float:right;position:relative';
img.style.position = 'relative';
img.style.styleFloat = 'right';
}
topBar.appendChild(monthDiv);
var monthPicker = createMonthDiv();
monthPicker.style.left = '37px';
monthPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
monthPicker.style.width ='60px';
monthPicker.id = 'monthDropDown';
calendarDiv.appendChild(monthPicker);
// Year selector
var yearDiv = document.createElement('DIV');
yearDiv.onmouseover = highlightSelect;
yearDiv.onmouseout = highlightSelect;
yearDiv.onclick = showYearDropDown;
var span = document.createElement('SPAN');
span.innerHTML = currentYear;
span.id = 'calendar_year_txt';
yearDiv.appendChild(span);
topBar.appendChild(yearDiv);
var img = document.createElement('IMG');
img.src = pathToImages + 'down.gif';
yearDiv.appendChild(img);
yearDiv.className = 'selectBox';
if(Opera){
yearDiv.style.width = '50px';
img.style.cssText = 'float:right';
img.style.position = 'relative';
img.style.styleFloat = 'right';
}
var yearPicker = createYearDiv();
yearPicker.style.left = '113px';
yearPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
yearPicker.style.width = '35px';
yearPicker.id = 'yearDropDown';
calendarDiv.appendChild(yearPicker);
var img = document.createElement('IMG');
img.src = pathToImages + 'close.gif';
img.style.styleFloat = 'right';
img.onmouseover = highlightClose;
img.onmouseout = highlightClose;
img.onclick = closeCalendar;
topBar.appendChild(img);
if(!document.all){
img.style.position = 'absolute';
img.style.right = '2px';
}
}
function writeCalendarContent()
{
var calendarContentDivExists = true;
if(!calendarContentDiv){
calendarContentDiv = document.createElement('DIV');
calendarDiv.appendChild(calendarContentDiv);
calendarContentDivExists = false;
}
currentMonth = currentMonth/1;
var d = new Date();
d.setFullYear(currentYear);
d.setDate(1);
d.setMonth(currentMonth);
var dayStartOfMonth = d.getDay();
if (! weekStartsOnSunday) {
if(dayStartOfMonth==0)dayStartOfMonth=7;
dayStartOfMonth--;
}
document.getElementById('calendar_year_txt').innerHTML = currentYear;
document.getElementById('calendar_month_txt').innerHTML = monthArray[currentMonth];
document.getElementById('calendar_hour_txt').innerHTML = currentHour;
document.getElementById('calendar_minute_txt').innerHTML = currentMinute;
var existingTable = calendarContentDiv.getElementsByTagName('TABLE');
if(existingTable.length>0){
calendarContentDiv.removeChild(existingTable[0]);
}
var calTable = document.createElement('TABLE');
calTable.width = '100%';
calTable.cellSpacing = '0';
calendarContentDiv.appendChild(calTable);
var calTBody = document.createElement('TBODY');
calTable.appendChild(calTBody);
var row = calTBody.insertRow(-1);
row.className = 'calendar_week_row';
if (showWeekNumber) {
var cell = row.insertCell(-1);
cell.innerHTML = weekString;
cell.className = 'calendar_week_column';
cell.style.backgroundColor = selectBoxRolloverBgColor;
}
for(var no=0;no<dayArray.length;no++){
var cell = row.insertCell(-1);
cell.innerHTML = dayArray[no];
}
var row = calTBody.insertRow(-1);
if (showWeekNumber) {
var cell = row.insertCell(-1);
cell.className = 'calendar_week_column';
cell.style.backgroundColor = selectBoxRolloverBgColor;
var week = getWeek(currentYear,currentMonth,1);
cell.innerHTML = week; // Week
}
for(var no=0;no<dayStartOfMonth;no++){
var cell = row.insertCell(-1);
cell.innerHTML = ' ';
}
var colCounter = dayStartOfMonth;
var daysInMonth = daysInMonthArray[currentMonth];
if(daysInMonth==28){
if(isLeapYear(currentYear))daysInMonth=29;
}
for(var no=1;no<=daysInMonth;no++){
d.setDate(no-1);
if(colCounter>0 && colCounter%7==0){
var row = calTBody.insertRow(-1);
if (showWeekNumber) {
var cell = row.insertCell(-1);
cell.className = 'calendar_week_column';
var week = getWeek(currentYear,currentMonth,no);
cell.innerHTML = week; // Week
cell.style.backgroundColor = selectBoxRolloverBgColor;
}
}
var cell = row.insertCell(-1);
if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){
cell.className='activeDay';
}
cell.innerHTML = no;
cell.onclick = pickDate;
colCounter++;
}
if(!document.all){
if(calendarContentDiv.offsetHeight)
document.getElementById('topBar').style.top = calendarContentDiv.offsetHeight + document.getElementById('timeBar').offsetHeight + document.getElementById('topBar').offsetHeight -1 + 'px';
else{
document.getElementById('topBar').style.top = '';
document.getElementById('topBar').style.bottom = '0px';
}
}
if(iframeObj){
if(!calendarContentDivExists)setTimeout('resizeIframe()',350);else setTimeout('resizeIframe()',10);
}
}
function resizeIframe()
{
iframeObj.style.width = calendarDiv.offsetWidth + 'px';
iframeObj.style.height = calendarDiv.offsetHeight + 'px' ;
}
function pickTodaysDate()
{
var d = new Date();
currentMonth = d.getMonth();
currentYear = d.getFullYear();
pickDate(false,d.getDate());
}
function pickDate(e,inputDay)
{
var month = currentMonth/1 +1;
if(month<10)month = '0' + month;
var day;
if(!inputDay && this)day = this.innerHTML; else day = inputDay;
if(day/1<10)day = '0' + day;
if(returnFormat){
returnFormat = returnFormat.replace('dd',day);
returnFormat = returnFormat.replace('mm',month);
returnFormat = returnFormat.replace('yyyy',currentYear);
returnFormat = returnFormat.replace('hh',currentHour);
returnFormat = returnFormat.replace('ii',currentMinute);
returnFormat = returnFormat.replace('d',day/1);
returnFormat = returnFormat.replace('m',month/1);
returnDateTo.value = returnFormat;
try{
returnDateTo.onchange();
}catch(e){
}
}else{
for(var no=0;no<returnDateToYear.options.length;no++){
if(returnDateToYear.options[no].value==currentYear){
returnDateToYear.selectedIndex=no;
break;
}
}
for(var no=0;no<returnDateToMonth.options.length;no++){
if(returnDateToMonth.options[no].value==parseInt(month)){
returnDateToMonth.selectedIndex=no;
break;
}
}
for(var no=0;no<returnDateToDay.options.length;no++){
if(returnDateToDay.options[no].value==parseInt(day)){
returnDateToDay.selectedIndex=no;
break;
}
}
if(calendarDisplayTime){
for(var no=0;no<returnDateToHour.options.length;no++){
if(returnDateToHour.options[no].value==parseInt(currentHour)){
returnDateToHour.selectedIndex=no;
break;
}
}
for(var no=0;no<returnDateToMinute.options.length;no++){
if(returnDateToMinute.options[no].value==parseInt(currentMinute)){
returnDateToMinute.selectedIndex=no;
break;
}
}
}
}
closeCalendar();
}
// This function is from http://www.codeproject.com/csharp/gregorianwknum.asp
// Only changed the month add
function getWeek(year,month,day){
if (! weekStartsOnSunday) {
day = (day/1);
} else {
day = (day/1)+1;
}
year = year /1;
month = month/1 + 1; //use 1-12
var a = Math.floor((14-(month))/12);
var y = year+4800-a;
var m = (month)+(12*a)-3;
var jd = day + Math.floor(((153*m)+2)/5) +
(365*y) + Math.floor(y/4) - Math.floor(y/100) +
Math.floor(y/400) - 32045; // (gregorian calendar)
var d4 = (jd+31741-(jd%7))%146097%36524%1461;
var L = Math.floor(d4/1460);
var d1 = ((d4-L)%365)+L;
NumberOfWeek = Math.floor(d1/7) + 1;
return NumberOfWeek;
}
function writeTimeBar()
{
var timeBar = document.createElement('DIV');
timeBar.id = 'timeBar';
timeBar.className = 'timeBar';
var subDiv = document.createElement('DIV');
subDiv.innerHTML = 'Time:';
//timeBar.appendChild(subDiv);
// Year selector
var hourDiv = document.createElement('DIV');
hourDiv.onmouseover = highlightSelect;
hourDiv.onmouseout = highlightSelect;
hourDiv.onclick = showHourDropDown;
hourDiv.style.width = '30px';
var span = document.createElement('SPAN');
span.innerHTML = currentHour;
span.id = 'calendar_hour_txt';
hourDiv.appendChild(span);
timeBar.appendChild(hourDiv);
var img = document.createElement('IMG');
img.src = pathToImages + 'down_time.gif';
hourDiv.appendChild(img);
hourDiv.className = 'selectBoxTime';
if(Opera){
hourDiv.style.width = '30px';
img.style.cssText = 'float:right';
img.style.position = 'relative';
img.style.styleFloat = 'right';
}
var hourPicker = createHourDiv();
hourPicker.style.left = '130px';
//hourPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
hourPicker.style.width = '35px';
hourPicker.id = 'hourDropDown';
calendarDiv.appendChild(hourPicker);
// Add Minute picker
// Year selector
var minuteDiv = document.createElement('DIV');
minuteDiv.onmouseover = highlightSelect;
minuteDiv.onmouseout = highlightSelect;
minuteDiv.onclick = showMinuteDropDown;
minuteDiv.style.width = '30px';
var span = document.createElement('SPAN');
span.innerHTML = currentMinute;
span.id = 'calendar_minute_txt';
minuteDiv.appendChild(span);
timeBar.appendChild(minuteDiv);
var img = document.createElement('IMG');
img.src = pathToImages + 'down_time.gif';
minuteDiv.appendChild(img);
minuteDiv.className = 'selectBoxTime';
if(Opera){
minuteDiv.style.width = '30px';
img.style.cssText = 'float:right';
img.style.position = 'relative';
img.style.styleFloat = 'right';
}
var minutePicker = createMinuteDiv();
minutePicker.style.left = '167px';
//minutePicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
minutePicker.style.width = '35px';
minutePicker.id = 'minuteDropDown';
calendarDiv.appendChild(minutePicker);
return timeBar;
}
function writeBottomBar()
{
var d = new Date();
var bottomBar = document.createElement('DIV');
bottomBar.id = 'bottomBar';
bottomBar.style.cursor = 'pointer';
bottomBar.className = 'todaysDate';
// var todayStringFormat = '[todayString] [dayString] [day] [monthString] [year]'; ;;
var subDiv = document.createElement('DIV');
subDiv.onclick = pickTodaysDate;
subDiv.id = 'todaysDateString';
subDiv.style.width = (calendarDiv.offsetWidth - 95) + 'px';
var day = d.getDay();
if (! weekStartsOnSunday) {
if(day==0)day = 7;
day--;
}
var bottomString = todayStringFormat;
bottomString = bottomString.replace('[monthString]',monthArrayShort[d.getMonth()]);
bottomString = bottomString.replace('[day]',d.getDate());
bottomString = bottomString.replace('[year]',d.getFullYear());
bottomString = bottomString.replace('[dayString]',dayArray[day].toLowerCase());
bottomString = bottomString.replace('[UCFdayString]',dayArray[day]);
bottomString = bottomString.replace('[todayString]',todayString);
subDiv.innerHTML = todayString + ': ' + d.getDate() + '. ' + monthArrayShort[d.getMonth()] + ', ' + d.getFullYear() ;
subDiv.innerHTML = bottomString ;
bottomBar.appendChild(subDiv);
var timeDiv = writeTimeBar();
bottomBar.appendChild(timeDiv);
calendarDiv.appendChild(bottomBar);
}
function getTopPos(inputObj)
{
var returnValue = inputObj.offsetTop + inputObj.offsetHeight;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop;
return returnValue + calendar_offsetTop;
}
function getleftPos(inputObj)
{
var returnValue = inputObj.offsetLeft;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
return returnValue + calendar_offsetLeft;
}
function positionCalendar(inputObj)
{
calendarDiv.style.left = getleftPos(inputObj) + 'px';
calendarDiv.style.top = getTopPos(inputObj) + 'px';
if(iframeObj){
iframeObj.style.left = calendarDiv.style.left;
iframeObj.style.top = calendarDiv.style.top;
//// fix for EI frame problem on time dropdowns 09/30/2006
iframeObj2.style.left = calendarDiv.style.left;
iframeObj2.style.top = calendarDiv.style.top;
}
}
function initCalendar()
{
if(MSIE){
iframeObj = document.createElement('IFRAME');
iframeObj.style.filter = 'alpha(opacity=0)';
iframeObj.style.position = 'absolute';
iframeObj.border='0px';
iframeObj.style.border = '0px';
iframeObj.style.backgroundColor = '#FF0000';
//// fix for EI frame problem on time dropdowns 09/30/2006
iframeObj2 = document.createElement('IFRAME');
iframeObj2.style.position = 'absolute';
iframeObj2.border='0px';
iframeObj2.style.border = '0px';
iframeObj2.style.height = '1px';
iframeObj2.style.width = '1px';
//// fix for EI frame problem on time dropdowns 09/30/2006
// Added fixed for HTTPS
iframeObj2.src = 'blank.html';
iframeObj.src = 'blank.html';
document.body.appendChild(iframeObj2); // gfb move this down AFTER the .src is set
document.body.appendChild(iframeObj);
}
calendarDiv = document.createElement('DIV');
calendarDiv.id = 'calendarDiv';
calendarDiv.style.zIndex = 1000;
slideCalendarSelectBox();
document.body.appendChild(calendarDiv);
writeBottomBar();
writeTopBar();
if(!currentYear){
var d = new Date();
currentMonth = d.getMonth();
currentYear = d.getFullYear();
}
writeCalendarContent();
}
function setTimeProperties()
{
if(!calendarDisplayTime){
document.getElementById('timeBar').style.display='none';
document.getElementById('timeBar').style.visibility='hidden';
document.getElementById('todaysDateString').style.width = '100%';
}else{
document.getElementById('timeBar').style.display='block';
document.getElementById('timeBar').style.visibility='visible';
document.getElementById('hourDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px';
document.getElementById('minuteDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px';
document.getElementById('minuteDropDown').style.right = '50px';
document.getElementById('hourDropDown').style.right = '50px';
document.getElementById('todaysDateString').style.width = '115px';
}
}
function calendarSortItems(a,b)
{
return a/1 - b/1;
}
function displayCalendar(inputField,format,buttonObj,displayTime,timeInput)
{
if(displayTime)calendarDisplayTime=true; else calendarDisplayTime = false;
if(inputField.value.length>6){ //dates must have at least 6 digits...
if(!inputField.value.match(/^[0-9]*?$/gi)){
var items = inputField.value.split(/[^0-9]/gi);
var positionArray = new Array();
positionArray['m'] = format.indexOf('mm');
if(positionArray['m']==-1)positionArray['m'] = format.indexOf('m');
positionArray['d'] = format.indexOf('dd');
if(positionArray['d']==-1)positionArray['d'] = format.indexOf('d');
positionArray['y'] = format.indexOf('yyyy');
positionArray['h'] = format.indexOf('hh');
positionArray['i'] = format.indexOf('ii');
var positionArrayNumeric = Array();
positionArrayNumeric[0] = positionArray['m'];
positionArrayNumeric[1] = positionArray['d'];
positionArrayNumeric[2] = positionArray['y'];
positionArrayNumeric[3] = positionArray['h'];
positionArrayNumeric[4] = positionArray['i'];
positionArrayNumeric = positionArrayNumeric.sort(calendarSortItems);
var itemIndex = -1;
currentHour = '00';
currentMinute = '00';
for(var no=0;no<positionArrayNumeric.length;no++){
if(positionArrayNumeric[no]==-1)continue;
itemIndex++;
if(positionArrayNumeric[no]==positionArray['m']){
currentMonth = items[itemIndex]-1;
continue;
}
if(positionArrayNumeric[no]==positionArray['y']){
currentYear = items[itemIndex];
continue;
}
if(positionArrayNumeric[no]==positionArray['d']){
tmpDay = items[itemIndex];
continue;
}
if(positionArrayNumeric[no]==positionArray['h']){
currentHour = items[itemIndex];
continue;
}
if(positionArrayNumeric[no]==positionArray['i']){
currentMinute = items[itemIndex];
continue;
}
}
currentMonth = currentMonth / 1;
tmpDay = tmpDay / 1;
}else{
var monthPos = format.indexOf('mm');
currentMonth = inputField.value.substr(monthPos,2)/1 -1;
var yearPos = format.indexOf('yyyy');
currentYear = inputField.value.substr(yearPos,4);
var dayPos = format.indexOf('dd');
tmpDay = inputField.value.substr(dayPos,2);
var hourPos = format.indexOf('hh');
if(hourPos>=0){
tmpHour = inputField.value.substr(hourPos,2);
currentHour = tmpHour;
}else{
currentHour = '00';
}
var minutePos = format.indexOf('ii');
if(minutePos>=0){
tmpMinute = inputField.value.substr(minutePos,2);
currentMinute = tmpMinute;
}else{
currentMinute = '00';
}
}
}else{
var d = new Date();
currentMonth = d.getMonth();
currentYear = d.getFullYear();
currentHour = '08';
currentMinute = '00';
tmpDay = d.getDate();
}
inputYear = currentYear;
inputMonth = currentMonth;
inputDay = tmpDay/1;
if(!calendarDiv){
initCalendar();
}else{
if(calendarDiv.style.display=='block'){
closeCalendar();
return false;
}
writeCalendarContent();
}
returnFormat = format;
returnDateTo = inputField;
positionCalendar(buttonObj);
calendarDiv.style.visibility = 'visible';
calendarDiv.style.display = 'block';
if(iframeObj){
iframeObj.style.display = '';
iframeObj.style.height = '140px';
iframeObj.style.width = '195px';
iframeObj2.style.display = '';
iframeObj2.style.height = '140px';
iframeObj2.style.width = '195px';
}
setTimeProperties();
updateYearDiv();
updateMonthDiv();
updateMinuteDiv();
updateHourDiv();
}
function displayCalendarSelectBox(yearInput,monthInput,dayInput,hourInput,minuteInput,buttonObj)
{
if(!hourInput)calendarDisplayTime=false; else calendarDisplayTime = true;
currentMonth = monthInput.options[monthInput.selectedIndex].value/1-1;
currentYear = yearInput.options[yearInput.selectedIndex].value;
if(hourInput){
currentHour = hourInput.options[hourInput.selectedIndex].value;
inputHour = currentHour/1;
}
if(minuteInput){
currentMinute = minuteInput.options[minuteInput.selectedIndex].value;
inputMinute = currentMinute/1;
}
inputYear = yearInput.options[yearInput.selectedIndex].value;
inputMonth = monthInput.options[monthInput.selectedIndex].value/1 - 1;
inputDay = dayInput.options[dayInput.selectedIndex].value/1;
if(!calendarDiv){
initCalendar();
}else{
writeCalendarContent();
}
returnDateToYear = yearInput;
returnDateToMonth = monthInput;
returnDateToDay = dayInput;
returnDateToHour = hourInput;
returnDateToMinute = minuteInput;
returnFormat = false;
returnDateTo = false;
positionCalendar(buttonObj);
calendarDiv.style.visibility = 'visible';
calendarDiv.style.display = 'block';
if(iframeObj){
iframeObj.style.display = '';
iframeObj.style.height = calendarDiv.offsetHeight + 'px';
iframeObj.style.width = calendarDiv.offsetWidth + 'px';
//// fix for EI frame problem on time dropdowns 09/30/2006
iframeObj2.style.display = '';
iframeObj2.style.height = calendarDiv.offsetHeight + 'px';
iframeObj2.style.width = calendarDiv.offsetWidth + 'px'
}
setTimeProperties();
updateYearDiv();
updateMonthDiv();
updateHourDiv();
updateMinuteDiv();
}
| JavaScript |
/*
A simple class for displaying file information and progress
Note: This is a demonstration only and not part of SWFUpload.
Note: Some have had problems adapting this class in IE7. It may not be suitable for your application.
*/
// Constructor
// file is a SWFUpload file object
// targetID is the HTML element id attribute that the FileProgress HTML structure will be added to.
// Instantiating a new FileProgress object with an existing file will reuse/update the existing DOM elements
function FileProgress(file, targetID) {
this.fileProgressID = file.id;
this.opacity = 100;
this.height = 0;
this.fileProgressWrapper = document.getElementById(this.fileProgressID);
if (!this.fileProgressWrapper) {
this.fileProgressWrapper = document.createElement("div");
this.fileProgressWrapper.className = "fg_uploadProgressWrapper";
this.fileProgressWrapper.id = this.fileProgressID;
this.fileProgressElement = document.createElement("div");
this.fileProgressElement.className = "fg_uploadProgressContainer";
var progressCancel = document.createElement("a");
progressCancel.className = "fg_uploadProgressCancel";
progressCancel.href = "#";
progressCancel.style.visibility = "hidden";
progressCancel.appendChild(document.createTextNode(" "));
var progressText = document.createElement("div");
progressText.className = "fg_uploadProgressName";
progressText.appendChild(document.createTextNode(file.name));
var progressBar = document.createElement("div");
progressBar.className = "fg_uploadProgressBarInProgress";
var progressStatus = document.createElement("div");
progressStatus.className = "fg_uploadProgressBarStatus";
progressStatus.innerHTML = " ";
this.fileProgressElement.appendChild(progressCancel);
this.fileProgressElement.appendChild(progressText);
this.fileProgressElement.appendChild(progressStatus);
this.fileProgressElement.appendChild(progressBar);
this.fileProgressWrapper.appendChild(this.fileProgressElement);
document.getElementById(targetID).appendChild(this.fileProgressWrapper);
} else {
this.fileProgressElement = this.fileProgressWrapper.firstChild;
this.reset();
}
this.height = this.fileProgressWrapper.offsetHeight;
this.setTimer(null);
}
FileProgress.prototype.setTimer = function (timer) {
this.fileProgressElement["FP_TIMER"] = timer;
};
FileProgress.prototype.getTimer = function (timer) {
return this.fileProgressElement["FP_TIMER"] || null;
};
FileProgress.prototype.reset = function () {
this.fileProgressElement.className = "fg_uploadProgressContainer";
this.fileProgressElement.childNodes[2].innerHTML = " ";
this.fileProgressElement.childNodes[2].className = "fg_uploadProgressBarStatus";
this.fileProgressElement.childNodes[3].className = "fg_uploadProgressBarInProgress";
this.fileProgressElement.childNodes[3].style.width = "0%";
this.appear();
};
FileProgress.prototype.setProgress = function (percentage) {
this.fileProgressElement.className = "fg_uploadProgressContainer fg_uploadGreen";
this.fileProgressElement.childNodes[3].className = "fg_uploadProgressBarInProgress";
this.fileProgressElement.childNodes[3].style.width = percentage + "%";
this.appear();
};
FileProgress.prototype.setComplete = function () {
this.fileProgressElement.className = "fg_uploadProgressContainer fg_uploadBlue";
this.fileProgressElement.childNodes[3].className = "fg_uploadProgressBarComplete";
this.fileProgressElement.childNodes[3].style.width = "";
var oSelf = this;
this.setTimer(setTimeout(function () {
oSelf.disappear();
}, 10000));
};
FileProgress.prototype.setError = function () {
this.fileProgressElement.className = "fg_uploadProgressContainer fg_uploadRed";
this.fileProgressElement.childNodes[3].className = "fg_uploadProgressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
var oSelf = this;
this.setTimer(setTimeout(function () {
oSelf.disappear();
}, 5000));
};
FileProgress.prototype.setCancelled = function () {
this.fileProgressElement.className = "fg_uploadProgressContainer";
this.fileProgressElement.childNodes[3].className = "fg_uploadProgressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
var oSelf = this;
this.setTimer(setTimeout(function () {
oSelf.disappear();
}, 2000));
};
FileProgress.prototype.setStatus = function (status) {
this.fileProgressElement.childNodes[2].innerHTML = status;
};
// Show/Hide the cancel button
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
if (swfUploadInstance) {
var fileID = this.fileProgressID;
this.fileProgressElement.childNodes[0].onclick = function () {
swfUploadInstance.cancelUpload(fileID);
return false;
};
}
};
FileProgress.prototype.appear = function () {
if (this.getTimer() !== null) {
clearTimeout(this.getTimer());
this.setTimer(null);
}
if (this.fileProgressWrapper.filters) {
try {
this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=100)";
}
} else {
this.fileProgressWrapper.style.opacity = 1;
}
this.fileProgressWrapper.style.height = "";
this.height = this.fileProgressWrapper.offsetHeight;
this.opacity = 100;
this.fileProgressWrapper.style.display = "";
};
// Fades out and clips away the FileProgress box.
FileProgress.prototype.disappear = function () {
var reduceOpacityBy = 15;
var reduceHeightBy = 4;
var rate = 30; // 15 fps
if (this.opacity > 0) {
this.opacity -= reduceOpacityBy;
if (this.opacity < 0) {
this.opacity = 0;
}
if (this.fileProgressWrapper.filters) {
try {
this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")";
}
} else {
this.fileProgressWrapper.style.opacity = this.opacity / 100;
}
}
if (this.height > 0) {
this.height -= reduceHeightBy;
if (this.height < 0) {
this.height = 0;
}
this.fileProgressWrapper.style.height = this.height + "px";
}
if (this.height > 0 || this.opacity > 0) {
var oSelf = this;
this.setTimer(setTimeout(function () {
oSelf.disappear();
}, rate));
} else {
this.fileProgressWrapper.style.display = "none";
this.setTimer(null);
}
}; | JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.