﻿var Editor = {
	value : '',
	textarea : '',
	width : '730',
	height : '370',
	iframe : '',
	imgPath : 'http://cache.soso.com/baike/i/',//
	formateLayerUrl: 'http://baike.soso.com/cache/FormatLayer.html',
	uploadPicUrl : 'UploadPicBySelect.htm',//UploadPicBySelect.htm
	editorInCss:'http://cache.soso.com/baike/css/editorIn_4.css',//http://cache.soso.com/baike/css/editorIn_2.css
	charHtmlUrl:'http://baike.soso.com/cache/char_1.html',//http://baike.soso.com/cache/char_1.html
	parseUrl:'/api/util/filter',
	loadingImg:'http://cache.soso.com/baike/i/imgLoading.gif',
	captureUploadUrl:'z/CaptureUploadPic',
	captureActiveX:null,

	
	message : '最多输入<b>30000</b>字',
	nodeTimer : null,
	formatTipsId:'formatTips',
	titleTipsId:'titleTips',
	pictureTipsId:'pictureTips',
	invalidNode:['A','SCRIPT','FORM','INPUT','FONT','IFRAME','STYLE','OBJECT','EMBED'],
	specialChar:'&nbsp;|&lt;|&gt;|&amp;',//( |<|>|&)
	ieSelection : null,
	onBeforeClose : null,
	stopNodeChange:false,
	ie : Zhishi.Browser.isIE,
	fireFox:Zhishi.Browser.isFireFox,
	startTime:null,
	toolBar : {'baike' : [
			{type : 'normal',label : '撤销',value : 'Undo'},
			{type : 'normal',label : '重做',value : 'Redo'},
			{type : 'separator'},
			{type : 'extend',label : '加粗',value : 'Bold'},
			{type : 'extend',label : '斜体',value : 'Italic'},
			{type : 'separator'}, 
			{type : 'normal',label : '段落标题',value : 'Title',hasText:true},  
			{type : 'normal',label : '特殊字符',value : 'Char',hasText:true}, 
			{type : 'normal',label : '插入/修改图片',value : 'Image',hasText:true},
			{type : 'normal',label : '截屏',value : 'Capture',hasText:true,isIE:true},
			{type : 'separator'},
			{type : 'normal',label : '帮你自动检查格式问题',value : 'Formate',hasText2:true},
			{type : 'normal',label : '內部词条链接',value : 'InnerLink',hasText:true}
	]},
	
	count:{
		'b_undo':0,			'b_redo':0,		'b_bold':0,			'b_italic':0,		'b_title':0,		'b_char':0,
		'b_char_suc':0,		'b_img':0,		'b_img_suc':0,		'b_format':0,		'b_add':0,			'b_plus':0,
		'b_link':0,			'b_capture':0,	'b_capture_suc':0,
		'k_z':0,			'k_y':0,		'k_b':0,			'k_i':0,			'k_v':0,			'k_c':0,		
		'k_x':0,			'right_click':0
	},
	
	keyMaps : {
		CTRL_B : 1000 + 66,		CTRL_I : 1000 + 73,		CTRL_U : 1000 + 85,		CTRL_L : 1000 + 76,		CTRL_K : 1000 + 75,
		CTRL_Z : 1000 + 90,		CTRL_Y : 1000 + 89,		CTRL_V : 1000 + 86,		CTRL_X : 1000 + 88,		CTRL_C : 1000 + 67
	},
    
	init : function(id, config) {
		this.textarea = get(id);
		for (var i in config) Editor[i] = config[i];
		this.createUI();
		Zhishi.Event.attachEventListener(Editor.getWindow(),'load',Editor.initEvent.bind(this));
		this.setToolTip(Editor.message);		
		try{
			this.getDoc().execCommand('BackgroundImageCache', false, true);
			this.getDoc().execCommand('styleWithCSS', false, false);
			this.getDoc().execCommand('useCSS',false);
		}catch(e){};
		Editor.changeButtonState(['Redo','Undo'],'disable');
		Editor.Image.addEvent();
	},
	
	initEvent : function(doc) {
		Zhishi.Event.attachEventListener(doc, 'click', Editor.nodeChange_);
		Zhishi.Event.attachEventListener(doc, 'mouseup', Editor.nodeChange);
		Zhishi.Event.attachEventListener(doc, 'keyup', this.handleKeyUp);
		Zhishi.Event.attachEventListener(doc, 'keydown',this.handleKeyDown);
		Zhishi.Event.attachEventListener(doc,'contextmenu',this.handleRightClick);
		var str = Editor.textarea.value;
		if(Editor.fireFox) str = str || '<br/>';
	},
	
	setToolTip : function(msg){
		if(msg!=Editor.message) msg='<span style="color:red;">'+msg+'</span>';
		if(!get('toolTip')){
			var tempNode = document.createElement('span');
			tempNode.innerHTML = msg;
			tempNode.id = 'toolTip';
			tempNode.className = 'ed_toolTip';
			get('ed_stateBar').appendChild(tempNode);
		}
		else{
			get('ed_stateBar').removeChild(get('toolTip'));
			var tempNode = document.createElement('span');
			tempNode.innerHTML = msg;
			tempNode.id = 'toolTip';
			tempNode.className = 'ed_toolTip';
			get('ed_stateBar').appendChild(tempNode);
		}
	},

	changeHeight : function(type){
		if(type=='+'){
			this.height = parseInt(this.height) + 80;
			Editor.count.b_add++;
		}
		else if(this.height > 280 && type=='-'){
			this.height = parseInt(this.height) - 80;
			Editor.count.b_plus++;
		}
		else
			return;
		$('ed_iframeContainer').style.height = (this.height-62)+'px';
		$('ed_container').style.height = this.height +'px';
		this.iframe.style.height = (this.height-62)+'px';
	},
	
	createUI : function(iframe){
		var d = this.toolBar.baike.length;
		var result = '<table cellspacing="0" height="30"  class="ed_toolBar_table" cellpadding="0" border="0"><tbody><tr>';
		for (var i = 0; i < d; i++) {
			var o = this.toolBar.baike[i];
			if (o.type == 'separator'){
				if(o.isIE && !Editor.ie) continue;
				result += '<td class="divider"><img src="' + this.imgPath + 'blank.gif" class="img" alt=""/></td>';
			}
			else {
				if(o.isIE && !Editor.ie) continue;
				var temp_class = '';
				if(o.hasText) temp_class='width:54px;';
				if(o.hasText2) temp_class='width:74px;';
				var cmd = 'Editor.' + o.value;
				var button_class = o.value;
				//处理截屏按钮的样式
				//if(button_class == 'Capture' && !Editor.Capture.checkHasCaptureX()) button_class = o.value+'_disable';
				result += '<td unselectable="on"><div unselectable="on" onmouseover="' + cmd
						+ '.handleMouseOver(this)" onmouseout="' + cmd
						+ '.handleMouseOut(this)" onmousedown="' + cmd
						+ '.handleMouseDown(this)" onmouseup="' + cmd
						+ '.handleMouseUp(this)" onclick="' + cmd
						+ '.handleClick(this)" id="Tool_' + o.value
						+ '" title="' + o.label
						+ '" class="ToolbarItem"><img src="' + this.imgPath
						+ 'blank.gif" alt="' + o.label + '" class="img '
						+ button_class + '" style="'+temp_class+'"/></div></td>';
			}
		}
		result += '</tr></tbody></table>';
		
		var editorToolBar = document.createElement('div');
		editorToolBar.className = 'ed_toolBar';
		editorToolBar.id='ed_toolBarId';
		editorToolBar.style.height = '30px';
		editorToolBar.style.width = this.width+'px';
		editorToolBar.innerHTML = result;
		
		var stateBar = document.createElement('div');
		stateBar.id = 'ed_stateBar';
		stateBar.style.height = '30px';
		stateBar.style.width = this.width+'px';
		var tempStr = '<span style="float:left;">';
		if(navigator.appVersion.indexOf("MSIE 6.")>=0) tempStr = '<span style="float:left;padding-top:7px;">';
		stateBar.innerHTML = tempStr+'<span style="cursor:pointer;" onclick="Editor.changeHeight(\'+\');" title="扩展编辑框"><img src="' + this.imgPath + 'add.gif"/>&nbsp;加大</span>&nbsp;&nbsp;<span style="cursor:pointer;" onclick="Editor.changeHeight(\'-\');" title="收缩编辑框"><img src="' + this.imgPath + 'plus.gif">&nbsp;减小</span></span>';
		
		var ifrm = document.createElement('iframe');
		ifrm.id = 'ed_ifrm_id';
		ifrm.className = 'ed_Iframe';
		ifrm.setAttribute('frameBorder', '0');
		ifrm.setAttribute('border', 0);
		ifrm.setAttribute('width',(this.width-2)+'px');
		ifrm.setAttribute('marginWidth', '0');
		ifrm.setAttribute('marginHeight', '0');
		ifrm.setAttribute('height', (this.height - 62)+'px');
		
		
		var iframeContainer = document.createElement('div');
		iframeContainer.id ='ed_iframeContainer';
		iframeContainer.height = (this.height - 62)+'px';
		iframeContainer.width = this.width+'px';
		iframeContainer.appendChild(ifrm);
						
		var editorContainer = document.createElement('div');
		editorContainer.id = 'ed_container';
		editorContainer.style.height = this.height + 'px';
		editorContainer.style.width = this.width+'px';
		
		editorContainer.appendChild(editorToolBar);
		editorContainer.appendChild(iframeContainer);
		editorContainer.appendChild(stateBar);
		
		var tempValue = this.textarea.value;
		if(Editor.fireFox) tempValue = this.textarea.value || '<br/>';
		this.textarea.parentNode.insertBefore(editorContainer, this.textarea.nextSibling);
		this.textarea.hide();
		ifrm.contentWindow.document.open();
		Editor.initEvent(ifrm.contentWindow.document);
		var editable = '';
		if(Editor.ie){
			editable = 'contentEditable="true" onpaste="parent.Editor.handlePasteForIE()"';
		}
		ifrm.contentWindow.document.write('<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="X-UA-Compatible" content="IE=7" /><link rel="stylesheet" href="'+Editor.editorInCss+'" type="text/css"/></head><body '+ editable +' id="ed_body">'+tempValue+'</body></html>');
		ifrm.contentWindow.document.close();
		if(!Editor.ie){
			ifrm.contentWindow.document.designMode = 'on';
		}
		this.iframe = ifrm;
	},
	
	handleKeyUp : function(ev) {
		ev = window.event || ev;
		var code = ev.which || ev.keyCode || ev.charCode;
		switch(code){
			case 33://pageup
			case 34://pagedown
			case 35://end
			case 36://home
			case 37://left
			case 38://top
			case 39://right
			case 40://down
			case 8://back space
			case 46://del
				Editor.nodeChange();
				break;
			default:
				break;
		}
	},
	
	handleKeyDown : function(ev){
		if(Editor.startTime==null) Editor.startTime = new Date();
		ev = window.event || ev;
		var code = ev.which || ev.keyCode || ev.charCode;
		var key = Editor.keyMaps;
		var codeValue = 0;
		if(ev.ctrlKey || ev.metaKey)
			codeValue += 1000;
		else if(ev.shiftKey)
			codeValue +=2000;
		codeValue += code;
		switch(codeValue){
			case key.CTRL_B:
				Editor.count.k_b++;
				Editor.prevent(ev);
				Editor.Bold.execute(false);
				break;
			case key.CTRL_I:
				Editor.count.k_i++;
				Editor.prevent(ev);
				Editor.Italic.execute();
				break;
			case key.CTRL_V:
				Editor.count.k_v++;
				if(Zhishi.Browser.isFirefox) setTimeout(Editor.Util.pasteTips,500);
				if(Editor.ie) Editor.checkClipBorderHasImg(true);
				break;
			case key.CTRL_C:
				Editor.count.k_c++;
				break;
			case key.CTRL_X:
				Editor.count.k_x++;
				break;
			case key.CTRL_Z:
				Editor.count.k_z++;
				break;
			case key.CTRL_Y:
				Editor.count.k_y++;
				break;
			default:
				break;
		}
		Editor.nodeChange();
	},
	
	handlePasteForIE : function(){
		Editor.checkClipBorderHasImg(false);
		setTimeout(Editor.Util.pasteTips,500);
		return true;
	},
	//检测剪贴板中是否有图片
	checkClipBorderHasImg:function(isCtrlVUploadPicForActiveX){
		if(!Editor.Capture.isOnDoingPaste){
			Editor.Capture.isOnDoingPaste = true;
			if(Editor.captureActiveX==null) Editor.Capture.initCapture(false);
			if(Editor.captureActiveX!=null && Editor.captureActiveX.IsClipBoardImage){
				Editor.getIeRange();
				if(Editor.Capture.compareVersion(Editor.Capture.captureVersionForCtrlV,Editor.captureActiveX.Version))
					Editor.captureActiveX.UploadClipBoardImg2(isCtrlVUploadPicForActiveX);
				else
					Editor.captureActiveX.UploadClipBoardImg();
				Editor.Capture.showProcess();
			}
			//处理ie下ctrl+v和系统paste事件重复两次的bug
			setTimeout(function(){Editor.Capture.isOnDoingPaste = false;},100)
		}
	},
	
	handleRightClick : function(){
		if(Editor.captureActiveX==null) Editor.Capture.initCapture(false);
		if(Editor.captureActiveX!=null){
			if(Editor.Capture.compareVersion(Editor.Capture.captureVersionForCtrlV,Editor.captureActiveX.Version)) {
				Editor.captureActiveX.ContextMenuProcess();
			}
		}
		Editor.count.right_click++;
	},
	
	prevent : function(ev){
		ev.returnValue = false;
		if(ev.preventDefault)
			ev.preventDefault();
		return true;
	},
	
	getCmdList : function(){
		var list = [] , toolList = Editor.toolBar.baike;
		for(var i=0;i<toolList.length;i++)
			if(toolList[i].type=='extend' && toolList[i].value!=null)
				list.push(toolList[i].value);
		return list;
	},
	
	nodeChange : function(){
		if(!Editor.stopNodeChange){
			if(Editor.nodeTimer!=null) clearTimeout(Editor.nodeTimer);
			Editor.nodeTimer = setTimeout(Editor.nodeChange_,100);
		}
		else{
			setTimeout(function(){Editor.stopNodeChange = false;},100);
		}
	},
	isInnerLink : function(node){
		if(node.nodeName != "A") return false;
		var className = node.className;
		var href = node.href;
		if(className == null || href == null) return false;
		return className == "ed_inner_link";
	},
	nodeChange_ : function(){
		var list = Editor.getCmdList();
		var activateList = new Array();
		var node = Editor.getSelectedElement();
		for(var i=0;i<list.length;i++) if(Editor.getDoc().queryCommandState(list[i])) activateList.push(list[i]);
		if(node){
			while(node.nodeName!='BODY'){
				if(node.nodeName=='H2'){
					activateList.push('Title');
					if(Editor.ie) activateList.shift();
					break;
				}else if(Editor.isInnerLink(node)){
					activateList.push('InnerLink');
					break;
				}else{
					node = node.parentNode;
				}
			};
		}
		list.push('Title');
		list.push('InnerLink');
		var unReDo = ['Undo','Redo'];
		for(var i=0;i<unReDo.length;i++){
			if(Editor.getDoc().queryCommandEnabled(unReDo[i]))
				Editor[unReDo[i]]['enable']();
			else
				Editor[unReDo[i]]['disable']();
		}
		Editor.changeButtonState(list,'deactivate');
		Editor.changeButtonState(activateList, 'activate');
	},
	
	changeButtonState : function(list, state) {
		for (var i = 0; i < list.length; i++)
			Editor[list[i]][state]();
	},
	
	pasteHTML : function(data){
		if(!Editor.ie)
			Editor.getDoc().execCommand('insertHtml',false,data);
		else
			Editor.getDoc().selection.createRange().pasteHTML(data);
	},

	getValue : function() {
			return this.getDoc().body.innerHTML;
	},
	
	getContent : function(){
		return Editor.getDoc().body.innerHTML;
	},
	
	setValue : function(html){
		this.getDoc().body.innerHTML = html;
	},
	
	unFocus : function(){
		window.focus();
	},
	
	focus : function(){
		Editor.getWindow().focus();
	},

	getDoc : function() {
		return this.iframe.contentWindow.document;
	},
	
	getWindow : function() {
		return this.iframe.contentWindow;
	},

	getMySelection : function() {
		if (this.getWindow().getSelection)
			return this.getWindow().getSelection();
		else
			return this.getDoc().selection;
	},

	getRange : function() {
		var sel = this.getMySelection();
		var range = null;
		if (sel.getRangeAt) {
			range = sel.getRangeAt(0);
		} else if (sel.baseNode) {
			range = this.getDoc().createRange();
			range.setStart(sel.baseNode, sel.baseOffset);
			range.setEnd(sel.extentNode, sel.extentOffset);

			if (range.collapsed) {
				range.setStart(sel.extentNode, sel.extentOffset);

				range.setEnd(sel.baseNode, sel.baseOffset);
			}
		} else {
			range = sel.createRange();
		}
		return range;
	},
	
	getText : function() {
		var text = this.getRange();
		return text ? (Editor.ie ? text.text : text.toString()) : null;
	},
	
	getSelectedElement : function() {
		var doc = this.getDoc(), sel = null, range = null, check = true, elm = null;
		if (Editor.ie) {
			range = this.getRange();
			if (range) {
				elm = range.item ? range.item(0) : range.parentElement();
			}
		} else {
			sel = this.getMySelection();
			range = this.getRange();

			if (!sel || !range) {
				return null;
			}
			if (Zhishi.Browser.isWebKit) {
				if (range.startContainer) {
					check = false;
					if (range.startContainer.nodeType == 3) {
						elm = range.startContainer.parentNode;
					} else if (range.startContainer.nodeType == 1) {
						elm = range.startContainer;
					} else {
						check = true;
					}
				}
			}
			if (check) {
				if (sel.anchorNode && (sel.anchorNode.nodeType == 3)) {
					if (sel.anchorNode.parentNode) { // next check parentNode
						elm = sel.anchorNode.parentNode;
					}
					if (sel.anchorNode.nextSibling != sel.focusNode.nextSibling) {
						elm = sel.anchorNode.nextSibling;
					}
				}
				if (!elm) {
					elm = range.commonAncestorContainer;
					if (!range.collapsed)
						if (range.startContainer == range.endContainer)
							if (range.startOffset - range.endOffset < 2)
								if (range.startContainer.hasChildNodes())
									elm = range.startContainer.childNodes[range.startOffset];
				}
			}
		}
		return elm || this.getDoc().body;
	},
	
	getIeRange : function(){
		if(Editor.ie) Editor.ieSelection = Editor.getDoc().selection.createRange();
	}, 
	
	selectIeRange : function(){
		if(Editor.ie && Editor.ieSelection){
			Editor.ieSelection.select();
			Editor.ieSelection = null;
		}
	},
	
	closeFormatTips:function(){
		Editor.getIeRange();
		get(Editor.formatTipsId).style.display='none';
		Editor.selectIeRange();
		Editor.focus();
	},
	
	closeTitleTips:function(){
		Editor.getIeRange();
		get(Editor.titleTipsId).style.display='none';
		Editor.selectIeRange();
		Editor.focus();
	},
	
	closePictureTips:function(){
		Editor.getIeRange();
		get(Editor.pictureTipsId).style.display='none';
		Editor.selectIeRange();
		Editor.focus();
	},
	
	hasParagraphTitle : function() {
		var titles = Editor.getDoc().getElementsByTagName('h2');
		if(titles.length==0)
			return false;
		return true;
	},
	
	hasAbstractPicture : function() {
		var pics = Editor.getDoc().getElementById('topPic');
		if(!pics)
			return false;
		return true;
	},
	
	isEditingParagraph : function() {
		var contentBefore = document.getElementById("contentBefore");
		var contentAfter = document.getElementById("contentAfter");
		if(contentBefore) {
			if(contentBefore.innerHTML.length!=0)
				return true;
			return false;
		} else 
			return false;
		
		if(contentAfter) {
			if(contentAfter.innerHTML.length!=0)
				return true;
			return false;
		} else 
			return false;
	}
};

Editor.Util = {
	
	getCountInfo:function(){
		var result='';
		var endTime = new Date();
		var wasteTime = (Date.parse(endTime) - Date.parse(Editor.startTime))/1000 || 0;
		for(var i in Editor.count){
			result +=i+':'+Editor.count[i]+',';
		}
		return result+'time:'+wasteTime;
	},
	
	resetCountInfo:function(){
		for(var i in Editor.count)Editor.count[i] = 0;
	},
	
	pasteTips : function(){
		var flag = false;
		for(var i=0;i<Editor.invalidNode.length;i++){
			var find = Editor.getDoc().getElementsByTagName(Editor.invalidNode[i]);
			if(find.length > 0){
				flag = true;
				break;
			}
		}
		var imgs = Editor.getDoc().getElementsByTagName('IMG');
		for(var i=0;i<imgs.length;i++){
			if(imgs[i].src.indexOf('.soso.com')==-1 && imgs[i].src.indexOf('p/')!=0){
				flag = true;
				break;
			}
		}
		if(flag){
			var button = get('Tool_Formate');
			var tips = get(Editor.formatTipsId);
			tips.style.left = button.getXY()[0] - 20 +'px';
			tips.style.top = button.getXY()[1] - 75 +'px';
			tips.style.position = 'absolute';
			tips.style.display = 'block';
		}
	},
	
	showTitleTips : function(){
		var button = get('Tool_Title');
		var tips = get(Editor.titleTipsId);
		tips.style.left = button.getXY()[0] - 20 +'px';
		tips.style.top = button.getXY()[1] - 75 +'px';
		tips.style.position = 'absolute';
		tips.style.display = 'block';
	},
	
	showPictureTips : function(){
		var button = get('Tool_Image');
		var tips = get(Editor.pictureTipsId);
		tips.style.left = button.getXY()[0] - 20 +'px';
		tips.style.top = button.getXY()[1] - 75 +'px';
		tips.style.position = 'absolute';
		tips.style.display = 'block';
	},
	
	filterHtml : function(html){
		var result = '';
		result = html.replace(/<br>/gi,'');
		result = result.replace(/&/gi,'&amp;');
		result = result.replace(/</gi,'&lt;');
		result = result.replace(/>/gi,'&gt;');
		return result;
	}

};

Editor.BaseButton = {

	disabled : false,

	command : '',

	execute : function(count) {
		if(count==null){
			switch(this.command){
				case 'Undo':
					Editor.count.b_undo++;
					break;
				case 'Redo':
					Editor.count.b_redo++;
					break;
				case 'Bold':
					Editor.count.b_bold++;
					break;
				case 'Italic':
					Editor.count.b_italic++;
					break;
				default:
					break;
			}
		}
		Editor.getDoc().execCommand(this.command, false, null);
	},
	
	afterExecute : function(){
		Editor.nodeChange_();
		Editor.focus();
		Editor.stopNodeChange = true;
	},
	
	beforeExecute : function(){
		Editor.focus();
	},

	getButton : function() {
		return get('Tool_' + this.command);
	},

	addClass : function(cName) {
		this.getButton().addClassName(cName);
	},

	removeClass : function(cName) {
		this.getButton().removeClassName(cName);
	},
	
	hasClass : function(cName){
		return this.getButton().hasClassName(cName);
	},
	
	enable : function() {
		this.disabled = false;
		this.removeClass("ed_button_disabled");
	},

	disable : function() {
		this.disabled = true;
		this.removeClass("ed_button_mousedown");
		this.removeClass("ed_button_mouseover");
		this.addClass("ed_button_disabled");
	},

	activate : function() {
		this.addClass("ed_button_mousedown");
	},

	deactivate : function() {
		this.removeClass("ed_button_mousedown");
	},

	handleClick : function() {
		if (this.disabled) {return;}
		this.beforeExecute();
		this.execute();
		this.afterExecute();
	},

	handleMouseUp : function() {
		this.removeClass("ed_button_mousedown");
	},

	handleMouseDown : function() {
		if (this.disabled) {return;}
		this.addClass("ed_button_mousedown");
	},

	handleMouseOut : function() {
		this.removeClass("ed_button_mouseover");
	},

	handleMouseOver : function() {
		if (this.disabled) {return;}
		if(!this.hasClass("ed_button_mousedown")) this.addClass("ed_button_mouseover")
	}

};

Editor.Undo = {};
Object.extend(Editor.Undo, Editor.BaseButton);
Object.extend(Editor.Undo, {
	command : 'Undo',
	afterExecute : function(){
		Editor.nodeChange_();
		Editor.focus();
	}	
});

Editor.Redo = {};
Object.extend(Editor.Redo, Editor.BaseButton);
Object.extend(Editor.Redo, {
	command : 'Redo',
	afterExecute : function(){
		Editor.nodeChange_();
		Editor.focus();
	}
});

Editor.Bold = {};
Object.extend(Editor.Bold, Editor.BaseButton);
Object.extend(Editor.Bold, {
	command : 'Bold',
	handleMouseUp : function() {}
});

Editor.Italic = {};
Object.extend(Editor.Italic, Editor.BaseButton);
Object.extend(Editor.Italic, {
	command : 'Italic',
	handleMouseUp : function() {}
});

Editor.Title = {};
Object.extend(Editor.Title, Editor.BaseButton);
Object.extend(Editor.Title, {
	command : 'Title',
	execute : function() {
		// 关闭段落标题Tips提示
		var tip = get(Editor.titleTipsId);
		if(tip)
			tip.style.display='none'
	
		Editor.count.b_title++;
		var nodeName = Editor.getSelectedElement().nodeName;
		if(nodeName && nodeName=='H2'){
			Editor.getDoc().execCommand('formatblock', false, '<p>');
		}
		else if(nodeName!='IMG'){
			Editor.getDoc().execCommand("RemoveFormat", false, null);
			var text = Editor.getText();
			var sElm = Editor.getSelectedElement();	
			if(Editor.fireFox && sElm.innerHTML=='') sElm.parentNode.removeChild(sElm);
			if(text==''){
				return;
			}
			else{
				var str = '<H2>'+Editor.Util.filterHtml(text)+'</H2>';
				if(Editor.ie){
					var rng=Editor.getDoc().selection.createRange();
					Editor.getIeRange();
					//如果选中了br，先把br移动出去
					if(rng.htmlText.endsWith('<BR>')) rng.moveEnd("character",-1);
					//尝试向后移到，看能不能找到某个标签的>，如果找到了就往回移一位
					if(rng.moveEnd("character",1)>0){
						if(!rng.htmlText.endsWith('>')) rng.moveEnd("character",-1);
					}
					//尝试向前移到，看能不能找到某个标签的<，如果找到了就往回移一位
					if(rng.moveStart("character",-1)<0){
						if(!rng.htmlText.indexOf('<')>=0) rng.moveStart("character",1);
					}
					//最后再看有没有br
					if(!rng.htmlText.contains('<BR>')){
						Editor.selectIeRange();
						Editor.pasteHTML(str);
					}
					else{
						rng.pasteHTML(str);
		            	rng.collapse(false);
		            	rng.select();
					}
				}
				else{
					var selElm = Editor.getSelectedElement();
					if(selElm.tagName=='BR') Editor.getDoc().execCommand('formatblock', false, '<h2>');
					else Editor.pasteHTML(str);
				}
			}
		}
	}
});

Editor.InnerLink = {};
Object.extend(Editor.InnerLink, Editor.BaseButton);
Object.extend(Editor.InnerLink, {
	command : 'InnerLink',
	execute : function() {
		Editor.count.b_link++;
		var node = Editor.getSelectedElement();
		var nodeName = Editor.getSelectedElement().nodeName;
		if(nodeName && nodeName=='A' && node.className=="ed_inner_link"){
			Editor.getDoc().execCommand('Unlink', false, null);
			if(Editor.fireFox){
				var oNewNode= Editor.getDoc().createTextNode(node.textContent);
				node.parentNode.replaceChild(oNewNode, node);
			}
			return;
		}
		if(node && (node.nodeName=="B" || node.nodeName=="STRONG" || node.nodeName=="EM" || node.nodeName=="I")){
			if(node.parentNode && node.parentNode.nodeName == "A" && node.parentNode.className=="ed_inner_link"){
				Editor.getDoc().execCommand('Unlink', false, null);
				return;
			}
		}
		if(nodeName!='IMG' && nodeName != "H2"){
			//Editor.getDoc().execCommand("RemoveFormat", false, null);
			var text = Editor.getText();
			var sElm = Editor.getSelectedElement();
			if(Editor.fireFox && sElm.innerHTML=='') sElm.parentNode.removeChild(sElm);
			if(text=='' || text.length > 20){ return;}
			else{
				var str = '<A target="_blank" class="ed_inner_link" href="#">'+Editor.Util.filterHtml(text)+'</A>';
				if(Editor.ie){
					var rng=Editor.getDoc().selection.createRange();
					Editor.getIeRange();
					//如果选中了br，先把br移动出去
					if(rng.htmlText.endsWith('<BR>')) rng.moveEnd("character",-1);
					//尝试向后移到，看能不能找到某个标签的>，如果找到了就往回移一位
					if(rng.moveEnd("character",1)>0){
						if(!rng.htmlText.endsWith('>')) rng.moveEnd("character",-1);
					}
					//尝试向前移到，看能不能找到某个标签的<，如果找到了就往回移一位
					if(rng.moveStart("character",-1)<0){
						if(!rng.htmlText.indexOf('<')>=0) rng.moveStart("character",1);
					}
					//最后再看有没有br
					if(!rng.htmlText.contains('<BR>')){
						Editor.selectIeRange();
						Editor.pasteHTML(str);
					}
					else{
						rng.pasteHTML(str);
		            	rng.collapse(false);
		            	rng.select();
					}
				}
				else{
					Editor.pasteHTML(str);
				}
			}
		}
	}
});

Editor.Char = {};
Object.extend(Editor.Char, Editor.BaseButton);
Object.extend(Editor.Char, {
	command : 'Char',
	charValue : '',
	clickCharWindow : false,
	charDialog : null,
	tdClick : function(){
		Editor.count.b_char_suc++;
		Editor.Char.clickCharWindow = true;
		Editor.selectIeRange();
		Editor.pasteHTML(Editor.Char.charValue.trim());
		Editor.Char.charDialog.close();
		Editor.focus();
	},
	
	execute : function() {
		Editor.count.b_char++;
		if(Editor.getSelectedElement().tagName=='IMG'){
			alert('图片不支持此操作！');
			return;
		}
		Editor.Char.clickCharWindow = false;
		Editor.Char.charDialog = new Zhishi.Dialog('插入特殊符号',390,400,true,Editor.charHtmlUrl);
		Editor.Char.charDialog.show();
		Editor.getIeRange();
		Editor.Char.charDialog.afterClose = function(){
			if(!Editor.Char.clickCharWindow) Editor.selectIeRange();
		};
	}
});

Editor.Image = {};
Object.extend(Editor.Image, Editor.BaseButton);
Object.extend(Editor.Image, {
	command : 'Image',
	align : 'top',
	title : '',
	uploadDialog : null,
	hasClick : false,
	currentImage : null,
	
	scaleImage : function(realWidth, realHeight, maxWidth, maxHeight){
		var xScale = 1.0;
		var yScale = 1.0;
		if(realWidth > maxWidth || realHeight > maxHeight){
			if(realWidth > maxWidth){
				xScale = maxWidth / realWidth;
			}
			if(realHeight > maxHeight){
				yScale = maxHeight / realHeight;
			}
			xScale = yScale = Math.min(xScale, yScale);
		}
		return xScale;
	},
	scaleForWidth : function(realWidth, realHeight, maxWidth, maxHeight){
		return realWidth * Editor.Image.scaleImage(realWidth, realHeight, maxWidth, maxHeight);
	},
	scaleForHeight : function(realWidth, realHeight, maxWidth, maxHeight){
		return realHeight * Editor.Image.scaleImage(realWidth, realHeight, maxWidth, maxHeight);
	},
	
	showPreview : function(src, url, width, height){
		Editor.count.b_img_suc++;
		Editor.Image.hasClick = true;
		Editor.selectIeRange();
		if(Editor.ie){
			if(Editor.getSelectedElement().tagName=='IMG'){
				Editor.getDoc().execCommand('delete');
			}
		}
		if(url == null || url == '' || url=='null') url = src;
		var string = "";
		var maxWidth = 300;
		var maxHeight = 300;
		var showWidth = maxWidth;
		var showHeight = maxHeight;
		
		var showTitle = this.title;
		//if(showTitle == '')
		showTitle="点击查看大图";
		if(this.align=="right" || this.align=="left"){
			if(width && height){
				showWidth = Editor.Image.scaleForWidth(width, height, maxWidth, maxHeight);
				showHeight = Editor.Image.scaleForHeight(width, height, maxWidth, maxHeight);
			}
			string = '<a target="_blank" title="' + showTitle + '" href="' + url + '" class="ed_image_link">' + '<img alt="图片" class="ed_imgfloat_' + this.align+'"  title="' + this.title + '" src="'+ src + '" width="' + showWidth +  '" height="' + showHeight + '">' + '</a>';
			var selElm = Editor.getSelectedElement();
			if(Editor.Image.currentImage != null && selElm.nodeName == "IMG" && selElm.parentNode.nodeName == "A"){
				selElm.parentNode.href = url;
				selElm.parentNode.className = "ed_image_link";
				selElm.parentNode.removeAttribute("id");
				selElm.className = 'ed_imgfloat_' + Editor.Image.align;
				selElm.removeAttribute("id");
				selElm.title = Editor.Image.title;
				selElm.src = src;
				selElm.width = showWidth;
				selElm.height = showHeight;
				selElm.focus();
			}else{
				Editor.pasteHTML(string);
			}
			Editor.Image.addEvent();
		}else{
			maxWidth = 230;
			maxHeight = 230;
			if(width && height){
				showWidth = Editor.Image.scaleForWidth(width, height, maxWidth, maxHeight);
				showHeight = Editor.Image.scaleForHeight(width, height, maxWidth, maxHeight);
			}
			var doc = Editor.getDoc();
			var topPic = doc.getElementById("topPic");
			var topPicLink = null;
			if(topPic){
				topPicLink = topPic.parentNode;
			}
			if(topPicLink && topPicLink.id=="topPicLink" && topPicLink.nodeName== "A" && topPic){
				var selElm = Editor.getSelectedElement();
				if(selElm.nodeName == "IMG" && (selElm.id == null || selElm.id != "topPic")) 
					Editor.getDoc().execCommand("delete", false, null);
				topPicLink.href=url;
				topPic.src=src;
				if(topPic.getAttribute("style")) topPic.removeAttribute("style");
				if(topPic.getAttribute("height")) topPic.removeAttribute("height");
				if(topPic.getAttribute("width")) topPic.removeAttribute("width");
				topPic.title=this.title;
				topPic.width = showWidth;
				topPic.height = showHeight;
				topPic.focus();
			}else{
				if(topPic) topPic.parentNode.removeChild(topPic);
				if(topPicLink) topPicLink.parentNode.removeChild(topPicLink);
				string = '<a target="_blank" id="topPicLink" title="' + showTitle + '" href="' + url + '" class="ed_image_link">' + '<img alt="图片" class="ed_imgfloat_' + this.align+'"  id="topPic" title="' + this.title + '" src="'+ src + '" width="' + showWidth +  '" height="' + showHeight + '">' + '</a>';
				var selElm = Editor.getSelectedElement();
				if(selElm.nodeName == "IMG") Editor.getDoc().execCommand("delete", false, null);
				Editor.setValue(string + Editor.getContent().replace(/hasdbevent="1"/gi,"").replace(/hasdbevent=1/gi, ""));
				Editor.Image.addEvent();
				setTimeout(function(){Editor.getWindow().scrollTo(0,0);}, 50);
			}
		}
		this.title='';
		Editor.Image.uploadDialog.close();
		Editor.focus();
		var sel = Editor.getDoc().selection;
		if (Editor.ie && sel && sel.type == "Control" ) {
			var range = Editor.getDoc().body.createTextRange();
			range.moveToElementText( Editor.getDoc().selection.createRange().item(0));
			range.collapse( false );
			range.select();
		}
		Editor.nodeChange_();
	},
	
	execute : function() {
		// 关闭摘要图片Tips
		var tip = get(Editor.pictureTipsId);
		if(tip)
			tip.style.display='none';
			
		Editor.count.b_img++;
		Editor.Image.align = 'right';
		Editor.Image.title = '';
		var selElm = Editor.getSelectedElement();
		if(selElm.nodeName == "IMG") Editor.Image.currentImage = selElm;
		else Editor.Image.currentImage = null;
		Editor.Image.uploadDialog = new Zhishi.Dialog('<DIV class="upload_img"></DIV><SPAN class="layer_title">上传图片</SPAN>',550,375,true,Editor.uploadPicUrl,{'hasBottomHr':false,'top':30});
		Editor.Image.uploadDialog.show();
		Zhishi.Cookie.setCookie("uploadpicpath", "", 2);
		Editor.getIeRange();

		Editor.Image.uploadDialog.afterClose = function(){
			Zhishi.Cookie.setCookie("uploadpicpath", "");
			if(Editor.Image.hasClick){
				if(Editor.ieSelection != null)
					Editor.selectIeRange();
			}
			else{
				Editor.selectIeRange();
				Editor.focus();
			}
		};
	},
	addEvent : function() {
	
		var images = Editor.getDoc().getElementsByTagName("IMG");
		if(images == null) return;
		for(var i = 0; i < images.length; i++){
			var image = images[i];
			if(image.getAttribute("hasdbevent") == null){
				Zhishi.Event.attachEventListener(image,'dblclick',Editor.Image.execute);
				image.setAttribute("hasdbevent", "1");
			}
		}
	}
});

Editor.Formate = {};
Object.extend(Editor.Formate, Editor.BaseButton);
Object.extend(Editor.Formate, {
	layerDialog : null,
	command : 'Formate',
	execute : function(){
		Editor.count.b_format++;
		var str = Editor.getContent();
		Zhishi.Ajax.sendRequest('POST',Editor.parseUrl,{
			postdata:str,
			encode:false,
			onSuccess:function(data){
				Editor.setValue(data);
				Editor.Image.addEvent();
			}
		});
		get(Editor.formatTipsId).style.display='none';
		
		// 判断是否有摘要图片和段落标题
		if((!Editor.hasParagraphTitle() || !Editor.hasAbstractPicture()) && !Editor.isEditingParagraph())
		{
			// 弹出提示的浮动层
			Editor.Formate.layerDialog = new Zhishi.Dialog("<SPAN class=layer_title>格式助手</SPAN>",373,255, true, Editor.formateLayerUrl, {});
			Editor.Formate.layerDialog.show();
			Editor.Formate.layerDialog.afterClose = function() {
				Editor.Formate.afterLayerClosed();
				Editor.focus();
			};
			
		}
	},
	
	afterLayerClosed : function() {
		// 触发段落标题和摘要图片的Tip
		var hasTitle = Editor.hasParagraphTitle();
		var hasPic = Editor.hasAbstractPicture();
		if(!hasTitle && !hasPic)
			Editor.Util.showTitleTips();
		else if(!hasTitle)
			Editor.Util.showTitleTips();
		else if(!hasPic)
			Editor.Util.showPictureTips();
	},
	
	handleLayerClose:function(){
		Editor.Formate.layerDialog.close();
	}
});

Editor.Capture = {};
Object.extend(Editor.Capture, Editor.BaseButton);
Object.extend(Editor.Capture, {
	command : 'Capture',
	processDialog:null,
	helpTipsDialog:null,
	systemClose:false,
	isOnDoingPaste:false, //ie下ctrl+v 和 onpaste事件是否有一个在运行
	isCtrlVUploadPicForActiveX:false,//是ctrl+v上传还是右键上传
	isDoing:false, //截屏动作是不是正在进行
	isUserStopUpload:false,
	xType:0,
	ieBarX:null,
	
	captureVersionForCtrlV :'3.1.14.11', //支持了右键粘贴
	captureVersion:'3.1.15.10', //第一个包含了自动升级逻辑的截屏控件版本
	includeXToolbarVersion:'3.1.27.10',//包含了截屏控件的toolbar的最低版本号
	captureActiveSteupExe : 'http://toolbar.soso.com/download/TencentSosoActiveXSetup3.EXE',//控件安装包
	captureActiveUpdateExe : 'http://toolbar.soso.com/download/TencentSosoActiveXInstall3.EXE',//控件升级包
	captureToolbar:'http://toolbar.soso.com/download/QQToolbarInstallerForWenWenBaike3.exe',//包含工具栏的控件包
	
	execute : function(){
		if(!Editor.Capture.isDoing){
			//重新初始化下载类型选择
			Editor.Capture.xType = 0;
			if(Editor.Capture.initCapture(true)){
				Editor.getIeRange();
				Editor.Capture.systemClose = false;
				Editor.captureActiveX.DoCapture();
				Editor.Capture.isDoing = true;
				Editor.count.b_capture++;
			}
		}
	},
	//初始化截屏控件
	initCapture:function(isCheckX){
		if(Editor.Capture.checkHasCaptureX(false)){
			if(Editor.Capture.isNeedUpdate(isCheckX)){
				Editor.Capture.showHelpTips(8);
				return false;
			}
			else{
				Editor.captureActiveX = Editor.Capture.getCaptureX();
				Editor.captureActiveX.URL = Editor.captureUploadUrl;
				Editor.captureActiveX.OnCaptureFinished = function(){
					Editor.focus();
					Editor.captureActiveX.StartUpload();
					Editor.Capture.showProcess();
				};
				Editor.captureActiveX.OnCaptureCanceled = function(){
					Editor.selectIeRange();
					Editor.focus();
					Editor.Capture.isDoing = false;
				};
				Editor.captureActiveX.OnUploadFinished = function(picUrl){
					Editor.Capture.hideProcess();
					Editor.selectIeRange();
					if(Editor.getSelectedElement().tagName=='IMG'){
						Editor.getDoc().execCommand('delete');
						Editor.focus();
					}
					if(picUrl && picUrl.length>8){
						var srcDir = picUrl.substr(0,8)+'/';
						picUrl ='http://baike.soso.com/p/'+ srcDir + picUrl;
					}
					var string = '<a target="_blank" title="点击查看大图" href="' + picUrl + '" class="ed_image_link"><img class="ed_imgfloat_right" title="" src="'+ picUrl + '"></a>';
					Editor.pasteHTML(string);
					Editor.focus();
					Editor.Capture.isDoing = false;
					Editor.Image.addEvent();
				};
				Editor.captureActiveX.OnError = function(errType,errDesc){
					if(Editor.Capture.processDialog) {
						Editor.Capture.processDialog.onClose = function(){return true;};
						Editor.Capture.processDialog.close();
					}
					if(!Editor.Capture.isUserStopUpload){
						alert(errType);
					}
					else{
						Editor.Capture.isUserStopUpload = false;
					}
					Editor.selectIeRange();
					Editor.focus();
					Editor.Capture.isDoing = false;
				};
				return true;
			}
		}
		else if(Editor.Capture.canRegFromToolbar(isCheckX)){
			return false;			
		}
		else if(isCheckX){
			Editor.Capture.showHelpTips(1);
			return false;
		}
	},
	
	getCaptureX : function(){
		if(Editor.captureActiveX){
			return Editor.captureActiveX;
		}
		else{
			return new ActiveXObject('SosoBaike.ScreenCapture');
		}
	},
	
	getIEBarX : function(){
		if(Editor.Capture.ieBarX)
			return Editor.Capture.ieBarX;
		else
			return new ActiveXObject('SosoIEBar.IEBarObj');
	},
	
	showProcess:function(){
		Editor.Capture.processDialog = new Zhishi.Dialog('搜搜百科',370,200,false,$('tips6').innerHTML);
		Editor.Capture.processDialog.onClose = function(){
			if(!Editor.Capture.systemClose){
				var result = confirm('图片正在上传中，您确定要关闭此窗口?');
				if(result && Editor.captureActiveX){
					Editor.Capture.isUserStopUpload = true;
					Editor.captureActiveX.StopUpload();
				}
				return result;
			}
			else{
				return true;
			}
		};
		Editor.Capture.processDialog.show();
		Editor.Capture.processDialog.afterClose = function(){
			Editor.selectIeRange();
			Editor.focus();
			Editor.Capture.isDoing = false;
		};
	},
	
	hideProcess:function(){
		if(Editor.Capture.processDialog!=null){
			Editor.Capture.systemClose = true;
			Editor.Capture.processDialog.close();
		}
	},
	
	//检测截屏控件是否需要升级
	isNeedUpdate:function(isShowTips){
		var result = false;
		if(isShowTips){
			var cookie = Zhishi.Cookie.getCookie('isUpdateActiveX');
			if(cookie && cookie=='0') return false;
			Editor.captureActiveX = Editor.Capture.getCaptureX();
			var oldVersion = Editor.captureActiveX.Version;
			var newVersion = Editor.Capture.captureVersion;
			if(oldVersion != newVersion) result = Editor.Capture.compareVersion(oldVersion,newVersion);		
		}
		return result;
	},
	
	//<=
	compareVersion : function(oldV,newV){
		var oldVersion = null;
		var result = false;
		if(oldV!='' && newV!='') {
			if(oldV == newV) return true;
			else{
				oldVersion = oldV.split('.');
				var newVersion = newV.split('.');
				for(var i=0;i<newVersion.length;i++){
					if(parseInt(newVersion[i]) > parseInt(oldVersion[i])){
						result = true;
						break;
					}else if(parseInt(newVersion[i]) < parseInt(oldVersion[i])){
						result = false;
						break;
					}
				}
			}
		}
		return result;
	},
	
	//检测截屏控件
	checkHasCaptureX:function(isCheckVersion){
		var result = false;	
		try {
			Editor.captureActiveX = Editor.Capture.getCaptureX();
			if(isCheckVersion)
				result = (Editor.Capture.compareVersion(Editor.Capture.captureVersion,Editor.captureActiveX.Version)) ? true : false;
			else
				result = Editor.captureActiveX ? true : false;
		}catch(e){}
		return result;
	},
	
	//检测工具栏
	checkHasToolbarX:function(){
		var result = false;	
		try {
			Editor.Capture.ieBarX = Editor.Capture.getIEBarX();
			result = Editor.Capture.ieBarX ? true : false;
		}catch(e){}
		return result;
	},
	
	showHelpTips:function(tipsType){
		Editor.getIeRange();
		if(tipsType==1){
			if(Editor.Capture.checkHasToolbarX()){
				tipsType = 7;
			}else{
				$('tips1').getElementsByTagName('input')[0].checked = 'checked';
			}
		}
		else if(tipsType==2){
			var a = $('tips2').getElementsByTagName('a')[0];
			if(Editor.Capture.xType == '0'){
				a.href = Editor.Capture.captureToolbar;
			}
			else if(Editor.Capture.xType == '1'){
				a.href = Editor.Capture.captureActiveSteupExe;
			}
			else if(Editor.Capture.xType == '2'){
				a.href = Editor.Capture.captureActiveUpdateExe;
				if(document.location.href.indexOf('.sd')==-1) {
					Zhishi.Cookie.setCookie('VisitedUrl',document.location,12);
				}
			}
		}
		var result = $('tips'+tipsType).innerHTML;
		Editor.Capture.helpTipsDialog = null;
		Editor.Capture.helpTipsDialog = new Zhishi.Dialog('安装提示',370,220,false,result);
		Editor.Capture.helpTipsDialog.show();
		setTimeout(Zhishi.removeWindowCloseEvent,100);
	},
	
	selectType:function(value){
		Editor.Capture.xType = value;
	},
	
	download:function(type){
		if(type) Editor.Capture.xType = type;
		this.hideTips();
		this.showHelpTips(2);
		
		var a = document.createElement('a');
		if(Editor.Capture.xType == '0'){
			a.href = Editor.Capture.captureToolbar;
		}
		else if(Editor.Capture.xType == '1'){
			a.href = Editor.Capture.captureActiveSteupExe;
		}
		else if(Editor.Capture.xType =='2'){
			a.href = Editor.Capture.captureActiveUpdateExe;
		}
		document.body.appendChild(a);
		a.click();
	},
	
	hideTips:function(){
		Editor.Capture.helpTipsDialog.close();
		Editor.selectIeRange();
		Editor.focus();
	},
	
	startCheck:function(){
		Editor.Capture.hideTips();
		Editor.Capture.showHelpTips(3);
		setTimeout(function(){
			Editor.Capture.hideTips();
			if(Editor.Capture.checkHasCaptureX(true)){
				Editor.count.b_capture_suc++;
				Editor.Capture.showHelpTips(4);
			}
			else
				Editor.Capture.showHelpTips(5);
		},1000);
	},
	
	canRegFromToolbar:function(isCheckX){
		if(isCheckX && Editor.Capture.checkHasToolbarX()){
			Editor.Capture.ieBarX = Editor.Capture.getIEBarX();
			var version = null;
			version = Editor.Capture.ieBarX.info("version","SosoIEBar.IEBarObj");
			if(Editor.Capture.compareVersion(Editor.Capture.includeXToolbarVersion,version)){
				if(confirm("您还没有安装截屏控件，是否现在安装？")){
					Editor.Capture.ieBarX.RegisterPrscrnAcitveX();
				}
				return true;
			}
		}
		return false;
	},
	
	cancelUpdate:function(){
		Zhishi.Cookie.setCookie('isUpdateActiveX',0,7*24);
		Editor.Capture.hideTips();
	}
});
