/**
*
*  Copyright 2007 Hexun.com Inc. All rights reserved.
*  和讯公司
*  @author chenzhaohui@staff.hexun.com
*  date: 2008-06-05
**/

window.isIE = (navigator.appName == "Microsoft Internet Explorer");
if(window.isIE) 
{
	if(navigator.userAgent.indexOf("Opera")>-1) window.isIE = null;
}
else
{
	if(navigator.userAgent.indexOf("Gecko")==-1) window.isIE = null;
}



Function.prototype.bindAsEventListener2 = function(object,info) {
  var __method = this;
  return function(event) {
    return __method.call(object, event || window.event,info);
  }
};

function Dom(){}

Dom.create = function(tag,class2,parent)
{
	var element = document.createElement(tag);
	if(class2) element.className = class2;
	if(!parent) parent = document.body;
	parent.appendChild(element);
	return element;
};

Dom.show = function(element)
{
	element.style.visibility = "visible";
};
Dom.hide = function(element)
{
	element.style.visibility = "hidden";
};

Dom.showD = function(element,value)
{
	element.style.display = value?value:"";
};
Dom.hideD = function(element)
{
	element.style.display = "none";
};

Dom.getClientRect = function(element)
{
	var rect = 
	{
		left:0,
		top:0,
		width:0,
		height:0,
		bottom:0,
		right:0
	};
	if(element == document) element = document.documentElement;
	rect.left = 0;
	rect.top = 0;
	if(element == document.body && !window.isIE)
	{
		element = document.documentElement;
		rect.width = element.scrollWidth;
		rect.height = element.scrollHeight;
	}
	else
	{
		rect.width = element.clientWidth;
		rect.height = element.clientHeight;
	}
	rect.bottom = rect.top + rect.height;
	rect.right = rect.left + rect.width;
	return rect;
};

Dom.getOffsetRect = function(element)
{
	var rect = 
	{
		left:0,
		top:0,
		width:0,
		height:0,
		bottom:0,
		right:0
	};
	if(element == document)
	{
		element = document.documentElement;
		rect.left = element.scrollLeft;
		rect.top = element.scrollTop;
		if(window.isIE)
		{
			rect.width = element.offsetWidth;
			rect.height = element.offsetHeight;
		}
		else
		{
			rect.width = window.innerWidth;
			rect.height = window.innerHeight;
		}
	}
	else
	{
		rect.left = element.offsetLeft;
		rect.top = element.offsetTop;
		if(element == document.body && !window.isIE)
		{
			element = document.documentElement;
			rect.width = element.scrollWidth;
			rect.height = element.scrollHeight;
		}
		else
		{
			rect.width = element.offsetWidth;
			rect.height = element.offsetHeight;
		}
	}
	rect.bottom = rect.top + rect.height;
	rect.right = rect.left + rect.width;
	return rect;
};

Dom.getRect = function(element)
{
	var rect = Dom.getOffsetRect(element);
	var parent = element.offsetParent;
	while(parent)
	{
		var tempRect = Dom.getOffsetRect(parent);
		rect.left += tempRect.left;
		rect.top += tempRect.top;
		parent = parent.offsetParent;
	}
	rect.bottom = rect.top + rect.height;
	rect.right = rect.left + rect.width;
	return rect;
};

Dom.setPosition = function(element,position)
{
	element.style.left = position.left + "px";
	element.style.top = position.top + "px";
};
Dom.setRect = function(element,rect)
{
	Dom.setPosition(element,rect);
	element.style.width = rect.width + "px";
	element.style.height = rect.height + "px";
};

Dom.isInRect = function(position,rect)
{
	return (position.left >= rect.left && position.top >= rect.top && position.left <= rect.right && rect.top <= rect.bottom);
};

Dom.maxRect = function(rect1,rect2)
{
	var rect = 
	{
		left:0,
		top:0,
		width:0,
		height:0,
		bottom:0,
		right:0
	};
	rect.left = Math.min(rect1.left,rect2.left);
	rect.top = Math.min(rect1.top,rect2.top);
	rect.bottom = Math.max(rect1.bottom,rect2.bottom);
	rect.right = Math.max(rect1.right,rect2.right);
	rect.width = rect.right - rect.left;
	rect.height = rect.bottom - rect.top;
	return rect;
};
Dom.showModalDialog = function(url,args,feas)
{
	var win = false;
	if(!args) args = null;
	var feasStr = "";
	if(window.isIE)
	{
		if(feas)
		{
			var i;
			for(i=0;i<feas.length;i++)
			{
				var name = feas[i][0];
				var value = feas[i][1];
				switch(name)
				{
					case "width":
					{
						name = "dialogWidth";
						value = value + "px";
						break;
					}
					case "height":
					{
						name = "dialogHeight";
						value = value + "px";
						break;
					}
				}
				feasStr += name + ":" + value + ";";
			}
		}
		win = window.showModalDialog(url,args,feasStr);
	}
	else
	{
		if(feas)
		{
			var i;
			for(i=0;i<feas.length;i++)
			{
				var name = feas[i][0];
				var value = feas[i][1];
				feasStr += name + "=" + value + ",";
			}
		}
		win = window.open(url,null,feasStr + "modal=yes");
		win.dialogArguments = args;
	}
	return win;
};
Dom.open = function(url,args,feas,isClear)
{
	var win = false;
	if(!args) args = null;
	var feasStr = "";
	if(!feas) feas = [["modal","yes"]];
	
	if(isClear) {
		feas.push(["location","no"]);
		feas.push(["menubar","no"]);
		feas.push(["toolbar","no"]);
		feas.push(["scrollbars","yes"]);
		feas.push(["resizable","yes"]);
	}
	
	var i;
	for(i=0;i<feas.length;i++) 
	{
		feasStr += feas[i][0] + "=" + feas[i][1];
		if(i != feas.length-1) feasStr += ",";
	}
	
	window.openDialogArguments = args;
	win = window.open(url,null,feasStr);
	return win;
}



var Editor = new Object();

Editor.editorWin = false;
Editor.editorObj = false;
Editor.cache = false;
Editor.coder = false;
Editor.selection = false;
Editor.rangeCache = false;
Editor.viewState = "edit";

Editor.init = function (menuName,editorName,coderName)
{
	Editor.menu = menuName;
	Editor.coder = coderName;
	if(window.isIE == null)
	{
		alert("您现在所使用的浏览器不支持此编辑器很多高级功能，建议您采用IE或Firefox！");
		Dom.show(Editor.coder);
		Editor.menu.style.height = "0px";
	}
	else
	{
		Editor.container = editorName;
		Editor.initElements();
	}
};

Editor.initTools = function()
{
	Editor.controls = new Object();
	
	var toolsData = Config.tool.data;
	var css = Config.tool.css;
	if(!Config.isAdmin)
	{
	    var node = Config.tool.data.pop();
	    Config.tool.data.pop();
	    Config.tool.data.push(node);
	}
	
	var jump = false;
	
	for(var i=0;i<toolsData.length;i++)
	{
		
		var part = Dom.create("div",css.part,Editor.menu);
		var partData = toolsData[i];
		
		for(var j=0;j<partData.length;j++)
		{
			Dom.create("div",css.newLine,part);
			var row = Dom.create("div",css.row,part);
			var rowData = partData[j];
		
			for(var k=0;k<rowData.length;k++)
			{
				var toolData = rowData[k];
				var type = toolData[0];
				var controlId = toolData[1];
				if(type == "line")
				{
					var src = Config.basePath + "images/" + controlId + ".gif";
					var tool = Dom.create("div",css.tool,row);
					var img = Dom.create("img",false,tool);
					img.src = src;
				}
				else
				{
					var name = toolData[2];
					var downCall = toolData[3];
					var upCall = toolData[4];
					var selectCall = toolData[5];
					var cancelCall = toolData[6];
					var popCall = toolData[7];
					
					var tool = Dom.create("div",css.tool,row);
					Editor.controls[controlId] = tool;
					
					tool.hexun = {};
					tool.hexun.id = controlId;
					tool.hexun.type = type;
					tool.hexun.state = 0;
					
					if(type == "img")
					{
						var src = Config.basePath + "images/" + controlId + ".gif";
						var img = Dom.create("img",false,tool);
						img.src = src;
						img.alt = name;
						img.title = name;
						
						tool.hexun.tool = img;
					}
					else
					{
						var toolCss = controlId + "Select";
						var tool2 = Dom.create("div",controlId,tool);
						
						if(window.isIE)
						{
							tool.hexun.tool = new Array();
							tool.hexun.tool.selectedIndex = 0;
							tool.hexun.tool[0] = Dom.create("div",toolCss,tool2);
							tool.hexun.tool[0].hexunValue = null;
							var texts,values;
							if(controlId == "fontname")
							{
								texts = Config.lister.fontNameData.text;
								values = Config.lister.fontNameData.value;
								tool.hexun.tool[0].innerHTML = "字体";
							}
							else
							{
								texts = Config.lister.fontSizeData.text;
								values = Config.lister.fontSizeData.value;
								tool.hexun.tool[0].innerHTML = "字号";
							}
							var i = 0;
							for(i=0;i<texts.length;i++)
							{
								var newElement = Dom.create("div",toolCss,tool2);
								newElement.style.display = "none";
								newElement.innerHTML = texts[i];
								newElement.hexunValue = values[i].toString();
								tool.hexun.tool[i+1] = newElement;
							}
						}
						else
						{
							jump = true;
							tool.hexun.tool = Dom.create("div",toolCss,tool2);
						}
					}
					
					tool.hexun.downCall = downCall;
					if(upCall)
					{
						tool.hexun.upCall = upCall;
						if(selectCall) tool.hexun.selectCall = selectCall;
						if(cancelCall) tool.hexun.cancelCall = cancelCall;
						
					}
					else tool.hexun.upCall = downCall;
					if(popCall) 
					{
					    tool.hexun.popCall = popCall;
					}
					Event.observe(tool,"mouseover",Editor.toolMouseOver.bind(Editor,tool));
					Event.observe(tool,"mouseout",Editor.toolMouseOut.bind(Editor,tool));
					Event.observe(tool,"mousedown",Editor.toolMouseDown.bind(Editor,tool));
					Event.observe(tool,"mouseup",Editor.toolMouseUp.bindAsEventListener2(Editor,tool));
				}
			}
		}
		if(jump)
		{
			jump = false;
			i += 4;
		}
	}
};
Editor.ConvertToHtml = function(content)
{
    var html = "";
	html += "<html>";
	html += "<head>";
	html += '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
	html += "<style> *{line-height:130%;}body{font-size:14px;line-height:130%;font-family:'宋体',Verdana,Arial,Helvetica,sans-serif;}img{border:0;} p{margin:0 0 10px 0;padding:0px;}";
	if(window.isIE)
	{
	    html += " table.FCK__ShowTableBorders, table.FCK__ShowTableBorders td, table.FCK__ShowTableBorders th{border: #d3d3d3 1px solid;} "
	    html += " TABLE { behavior: url(http://post.blog.hexun.com/htmleditor/css/showtableborders.htc) ; }"
	}
	else
	{
	    html += " table[border='0'],table[border='0'] > tr > td, table[border='0'] > tr > th,table[border='0'] > tbody > tr > td, table[border='0'] > tbody > tr > th,table[border='0'] > thead > tr > td, table[border='0'] > thead > tr > th,table[border='0'] > tfoot > tr > td, table[border='0'] > tfoot > tr > th{border: #d3d3d3 1px dotted ;}";
        html += " table:not([border]),table:not([border]) > tr > td, table:not([border]) > tr > th,table:not([border]) > tbody > tr > td, table:not([border]) > tbody > tr > th,table:not([border]) > thead > tr > td, table:not([border]) > thead > tr > th,table:not([border]) > tfoot > tr > td, table:not([border]) > tfoot > tr > th{border: #d3d3d3 1px dotted ;}";
    }
	html += "</style></head>";
	html += "<body>";
	html += content;
	html += "</body>";
	html += "</html>";
	return html;
}
Editor.initElements = function()
{
	var css = Config.tool.css;
	Dom.show(Editor.coder);
	Dom.hideD(Editor.coder);
	
	Editor.initTools();
	Editor.menu.onselectstart = function(){return false;};
	
	window.hexun = {};
	
	var iframeTag = window.isIE?"<iframe frameborder='0'></iframe>":"iframe";
	Editor.editorObj = Dom.create(iframeTag,css.editor,Editor.container);
	Editor.editorObj.style.height = Config.frameHeight + "px";
	Editor.coder.style.height = Config.frameHeight + "px";
	Editor.coder.style.width = "99.5%";
	Editor.editorWin = Editor.editorObj.contentWindow;
		
	var doc = Editor.editorWin.document;
	doc.open();
	var html = Editor.ConvertToHtml(Editor.coder.value);
	doc.write(html);
	doc.close();
		
	if(window.isIE)
	{
		Editor.iCache = Dom.create("iframe",css.cache,Editor.container);
		Editor.iCacheDoc = Editor.iCache.contentWindow.document;
		Editor.iCacheDoc.open();
		Editor.iCacheDoc.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" ><html><head><style>body{font-family:'宋体';}</style></head><body></body></html>");
		Editor.iCacheDoc.close();
		
		doc.body.contentEditable = true;
		
		Event.observe(Editor.editorWin.document.body,"beforedeactivate",Editor.cacheRange);
		Event.observe(Editor.getDocument().body,"paste",Editor.shortcutPaste);
		Event.observe(Editor.editorWin.document,"selectionchange",Editor.checkAllState);
		if(Editor.coder.onfocus != null)
		{
		    Editor.editorWin.onfocus = Editor.coder.onfocus;
		}
		
//		window.onunload = function()
//		{
//			var range = Editor.editorWin.document.body.createTextRange();
//			range.execCommand("Copy");
//		};
		
//		Editor.editorWin.document.body.innerHTML = Editor.coder.value;

	}
	else
	{
	    Editor.editorWin.addEventListener("focus", Editor.coder.focus, true);
		Editor.disableSpecialTool();
		Editor.bindLoadFF();
	}
	//Editor.editorWin.focus();
	
	Editor.cache = Dom.create("div",css.cache,document.body);
	
	if(!Config.showFooter)return;
	var footer = Dom.create("div",Config.tool.css.footer,Editor.container);
	footer.innerHTML = '<table style="width:100%" border="0" cellpadding="0" cellspacing="0"><tr><td><div style="float:left"><img class="EditorButtonActive" title="普通" id="editorButton" src="' + Config.basePath + 'images/design.gif" IsCommandActive="true" /><img class="EditorButton" title="代码" id="codeButton" src="' + Config.basePath + 'images/htmlview.gif" IsCommandActive="false" /><img class="EditorButton" id="previewButton" title="预览状态" src="' + Config.basePath + 'images/preview.gif" IsCommandActive="false" isout="true" /></div><div style="float:right;display:none"><img class="EditorButton" title="扩大编辑窗口" src="' + Config.basePath + 'images/plus.gif" Command="SizePlus" id="sizePlus" IsCommandDisabled="false" isout="true" /><img class="EditorButton" title="缩小编辑窗口" src="' + Config.basePath + 'images/minus.gif" Command="SizeMinus" id="sizeMinus" IsCommandDisabled="false" isout="true" /></div></td><tr></table>';
	
	Editor.editorButton = $("editorButton");
	Editor.codeButton = $("codeButton");
	Editor.previewButton = $("previewButton");
	Editor.sizePlus = $("sizePlus");
	Editor.sizeMinus = $("sizeMinus");
	
	Editor.editorButton.Command = "edit";
	Editor.codeButton.Command = "code";
	Editor.previewButton.Command = "view";
	Editor.sizePlus.Command = "plus";
	Editor.sizeMinus.Command = "minus";
	
	var editorButtonMouseOver = function()
    {
        var e = arguments[0] || window.event;
        var src = e.srcElement || e.target;
        src.oldclassName = src.className;
        src.className = Config.tool.css.editorbuttonOver;
    };
    var editorButtonMouseOut = function()
    {
        var e = arguments[0] || window.event;
        var src = e.srcElement || e.target;
        src.className = src.oldclassName;
    };
    var sizePlusMinus = function()
    {
        var e = arguments[0] || window.event;
        var btn = e.srcElement || e.target;
        var height = parseInt(Editor.editorObj.style.height);
        if(btn.Command == "plus")
        {
            Editor.editorObj.style.height = (height + 100) + "px";
            Editor.coder.style.height = (height + 100) + "px";
        }
        else
        {
            if(height >= 200)
            {
                Editor.editorObj.style.height = (height - 100) + "px";
                Editor.coder.style.height = (height - 100) + "px";
            }
        }
    };
	Event.observe(Editor.editorButton, "mouseover", editorButtonMouseOver);
	Event.observe(Editor.codeButton, "mouseover", editorButtonMouseOver);
	Event.observe(Editor.previewButton, "mouseover", editorButtonMouseOver);
	Event.observe(Editor.sizePlus, "mouseover", editorButtonMouseOver);
	Event.observe(Editor.sizeMinus, "mouseover", editorButtonMouseOver);
	
	Event.observe(Editor.editorButton, "mouseout", editorButtonMouseOut);
	Event.observe(Editor.codeButton, "mouseout", editorButtonMouseOut);
	Event.observe(Editor.previewButton, "mouseout", editorButtonMouseOut);
	Event.observe(Editor.sizePlus, "mouseout", editorButtonMouseOut);
	Event.observe(Editor.sizeMinus, "mouseout", editorButtonMouseOut);
	
	Event.observe(Editor.editorButton, "click", Editor.setView);
	Event.observe(Editor.codeButton, "click", Editor.setView);
	Event.observe(Editor.previewButton, "click", Editor.setView);
    Event.observe(Editor.sizePlus, "click", sizePlusMinus);
    Event.observe(Editor.sizeMinus, "click", sizePlusMinus);
	
};


Editor.setView = function()
{
	if(Editor.viewState != "changing")
	{
	    var e = arguments[0] || window.event;
        var editorBtn = e.srcElement || e.target;
        
		var oldViewState = Editor.viewState;
		Editor.viewState = "changing";
		var newViewState = editorBtn.Command;
		
		if(oldViewState == newViewState)return;
		
		if(newViewState == "code")
		{
		    if(window.isIE)
			{
                Editor.editorWin.document.body.contentEditable = false;
			}
			else
			{
			    Editor.editorWin.document.designMode = "off";
			}
			    
			Editor.coder.value = Editor.getHTML();
			
			Dom.showD(Editor.menu);
			Dom.hideD(Editor.editorObj);
			Dom.showD(Editor.coder);
			
			Editor.editorWin.document.body.innerHTML = "";
			
			Editor.menu.style.filter = "Alpha(Opacity=30)";
			Editor.menu.style.MozOpacity = "0.3";
			
			Editor.editorButton.oldclassName=Editor.editorButton.className = Config.tool.css.editorbutton;
	        Editor.codeButton.oldclassName=Editor.codeButton.className = Config.tool.css.editorbuttonActive;
	        Editor.previewButton.oldclassName=Editor.previewButton.className = Config.tool.css.editorbutton;
			
			Editor.coder.focus();
		}
		else if(newViewState == "edit")
		{
		    Editor.editorWin = Editor.editorObj.contentWindow;
            Editor.editorWin.document.open();
			var html = Editor.ConvertToHtml(Editor.coder.value);
			Editor.editorWin.document.write(html);
			Editor.editorWin.document.close();		
	       
			
			Dom.hideD(Editor.coder);
			Dom.showD(Editor.menu);
			Dom.showD(Editor.editorObj);
			Editor.menu.style.filter = "Alpha(Opacity=100)";
			Editor.menu.style.MozOpacity = "1";
			
			Editor.editorButton.oldclassName=Editor.editorButton.className = Config.tool.css.editorbuttonActive;
	        Editor.codeButton.oldclassName=Editor.codeButton.className = Config.tool.css.editorbutton;
	        Editor.previewButton.oldclassName=Editor.previewButton.className = Config.tool.css.editorbutton;
			
			if(window.isIE)
			{
				var range = Editor.editorWin.document.body.createTextRange();
				range.setEndPoint("EndToStart",range);
				range.select();
				Editor.editorWin.document.body.contentEditable = true;
				Event.observe(Editor.editorWin.document.body,"beforedeactivate",Editor.cacheRange);
		        Event.observe(Editor.getDocument().body,"paste",Editor.shortcutPaste);
		        Event.observe(Editor.editorWin.document,"selectionchange",Editor.checkAllState);
			}
			/* 11.1
			Editor.editorObj.focus();
			*/
			else
			Editor.editorWin.document.designMode = "on";
			if(Editor.editorObj.focus) Editor.editorObj.focus();
		}
		else if(newViewState == "view")
		{		
			if(oldViewState == "code")
			{
			    Editor.editorWin.document.open();
			    var html = Editor.ConvertToHtml(Editor.coder.value);
			    Editor.editorWin.document.write(html);
			    Editor.editorWin.document.close();
			}
			else if(oldViewState == "edit")
			{
			    Editor.coder.value = Editor.editorWin.document.body.innerHTML;
			}
			
			Dom.hideD(Editor.coder);
			Dom.hideD(Editor.menu);
			Dom.showD(Editor.editorObj);
			Editor.menu.style.filter = "Alpha(Opacity=30)";
			Editor.menu.style.MozOpacity = "0.3";
			
			Editor.editorButton.oldclassName=Editor.editorButton.className = Config.tool.css.editorbutton;
	        Editor.codeButton.oldclassName=Editor.codeButton.className = Config.tool.css.editorbutton;
	        Editor.previewButton.oldclassName=Editor.previewButton.className = Config.tool.css.editorbuttonActive;
			
			if(window.isIE)
			{
                Editor.editorWin.document.body.contentEditable = false;
			}
			else
			    Editor.editorWin.document.designMode = "off";
			//if(Editor.editorObj.focus) Editor.editorObj.focus();
		}
		Editor.viewState = newViewState;
	}
};

Editor.disableSpecialTool = function()
{
	Editor.setState(Editor.controls["cut"],-3);
	Editor.setState(Editor.controls["copy"],-3);
	Editor.setState(Editor.controls["paste"],-3);
	Editor.controls["cut"].hexun.tool.title = "提示：您现在所使用的浏览器不支持此操作，请使用快捷键 [Ctrl + C]！";
	Editor.controls["copy"].hexun.tool.title = "提示：您现在所使用的浏览器不支持此操作，请使用快捷键 [Ctrl + X]！";
	Editor.controls["paste"].hexun.tool.title = "提示：您现在所使用的浏览器不支持此操作，请使用快捷键 [Ctrl + V]！";
};
Editor.bindLoadFF = function()
{
	Editor.setDesignMode(true);
	Event.observe(Editor.editorWin.document.body,"mouseup",Editor.checkAllState);
	Event.observe(Editor.editorWin.document,"keypress",Editor.checkAllState);
};
Editor.setContent = function()
{
	if(Editor.coder.style.display == "none")
	{
		Editor.coder.value = Editor.getHTML();
	}
};

Editor.checkAllState = function()
{
	if(!Editor.isChecking)
	{
		Editor.isChecking = true;
		if(!Editor.stateArray)
		{
			Editor.stateChecking = true;
			if(window.isIE)
			{
				Editor.stateArray = [
					"Paste","Cut","Copy","FontName","FontSize","Bold","Italic","Underline","JustifyLeft","InsertOrderedList","InsertUnorderedList","Undo","Redo"];
			}
			else
			{
				Editor.stateArray = ["fontname","fontsize","bold","italic","underline","justifyleft","insertorderedlist","insertunorderedlist"];
			}
		}
		try
		{
			var range = Editor.editorWin.document;
			if(range)
			{
				var i = 0;
				for(i=0;i<Editor.stateArray.length;i++)
				{
					Editor.checkCommandState(Editor.stateArray[i],range);
				}
			}
		}
		catch(e){}
		finally
		{
			Editor.isChecking = false;
		}
	}
};
Editor.checkCommandState = function(command,range)
{
	var returnValue = false;
	var commandLower = command.toLowerCase();
	var element = Editor.controls[commandLower];
	if(commandLower == "insertorderedlist") element = Editor.controls["orderlist"];
	else if(commandLower == "insertunorderedlist") element = Editor.controls["unorderlist"];
	
	switch(commandLower)
	{
		case "cut":
		case "copy":
		case "paste":
		{
			returnValue = range.queryCommandEnabled(command);
			if(returnValue) Editor.setState(element,0);
			else Editor.setState(element,-3);
			break;
		}
		case "fontname":
		case "fontsize":
		{
			returnValue = range.queryCommandValue(command);
			if(window.isIE)
			{
				var childs = element.hexun.tool;
				var oldSelectedIndex = childs.selectedIndex;
				if(childs[oldSelectedIndex].hexunValue != returnValue)
				{
					var i = 0, hasValue = false;
					if(returnValue != null)
					{
						for(i=1;i<childs.length;i++)
						{
							if(childs[i].hexunValue == returnValue)
							{
								hasValue = true;
								childs.selectedIndex = i;
							}
						}
					}
					if(!hasValue) childs.selectedIndex = 0;
					if(childs.selectedIndex != oldSelectedIndex)
					{
						childs[oldSelectedIndex].style.display = "none";
						childs[childs.selectedIndex].style.display = "";
					}
				}
			}
			else
			{
				if(commandLower == "fontname")
				{
					if(returnValue == "") returnValue = "字体";
					else
					{
						returnValue = returnValue.replace(/'/g,"");
						var dotIndex = returnValue.indexOf(",");
						if(dotIndex > 0) returnValue = returnValue.substr(0,dotIndex);
						dotIndex = returnValue.indexOf("_");
						if(dotIndex > 0) returnValue = returnValue.substr(0,dotIndex);
					}
				}
				else
				{
					if(returnValue == "") returnValue = "字号";
					else
					{
						var i = 0,hasValue = false;
						var values = Config.lister.fontSizeData.value;
						for(i=0;i<values.length;i++)
						{
							if(values[i] == returnValue)
							{
								returnValue = Config.lister.fontSizeData.text[i];
								hasValue = true;
								break;
							}
						}
						if(!hasValue) returnValue = "字号";
					}
				}
				element.hexun.tool.innerHTML = returnValue;
			}
			break;
		}
		case "justifyleft":
		case "justifycenter":
		case "justifyright":
		{
			var left=0,center=0,right=0;
			if(window.isIE)
			{
				left = range.queryCommandState("JustifyLeft")?-2:0;
				center = range.queryCommandState("JustifyCenter")?-2:0;
				right = range.queryCommandState("JustifyRight")?-2:0;
			}
			else
			{
				returnValue = range.queryCommandValue(command);
				if(returnValue == "left") left = -2;
				if(returnValue == "center") center = -2;
				if(returnValue == "right") right = -2;
			}
			Editor.setState(Editor.controls["justifyleft"],left);
			Editor.setState(Editor.controls["justifycenter"],center);
			Editor.setState(Editor.controls["justifyright"],right);
			break;
		}
		case "undo":
		case "redo":
		{
			returnValue = Editor.editorWin.document.queryCommandEnabled(command);
			if(returnValue) Editor.setState(element,0);
			else Editor.setState(element,-3);
			break;
		}
		default:
		{
			returnValue = range.queryCommandState(command);
			if(returnValue) Editor.setState(element,-2);
			else Editor.setState(element,0);
			break;
		}
	}
	return returnValue;
};
Editor.command = function(commandText,option)
{
	var returnValue = false;
	if(Editor.isEdit())
	{
		Editor.checkRange();
		if(option && option=="#" && window.isIE)
		{
			Editor.removeColor(commandText);
		}
		else
		{
			try
			{
				if(!window.isIE) commandText = commandText.toLowerCase();
				Editor.editorWin.document.execCommand(commandText,false,option);
				if(!window.isIE) Editor.editorWin.focus();
			}catch(e){}
		}
	}
	return returnValue;
};
Editor.getText = function()
{
	var range = Editor.getRange();
	if(range)
	{
		if(Editor.selection.type.toLowerCase() == "control")
		{
			html = range.item(0).innerHTML;
		}
		else
		{
			html = range.text;
		}
		if(!html) html = "";
	}	
	return html;
};
Editor.removeColor = function(command)
{
	var html = Editor.getText();
	if(html.length > 0)
	{
		var element = Editor.getSpecialElement("font",true);
		if(element && element.innerHTML == html)
		{
			if(command == "ForeColor")
			{
				element.color = "";
			}
			else
			{
				element.style.backgroundColor = "";
			}
		}
	}
	else
	{
		Editor.editorWin.document.execCommand(command,false,"#");
	}
};
Editor.undo = function()
{
	Editor.command("Undo",1);
	return -1;
};

Editor.redo = function()
{
	Editor.command("Redo",1);
	return -1;
};

Editor.checkFocus = function()
{
	if(window.hexun && window.hexun.win && window.hexun.win.win) 
	{
		window.hexun.win.win.focus();
	}
};
Editor.setState = function(element,stateValue,controlId)
{
	if(!element) element = Editor.controls[controlId];
	if(element)
	{
		element.hexun.state = stateValue;
		if(element.hexun.type != "select")
		{
			switch(stateValue)
			{
				case 1:
					element.className = Config.tool.css.toolOver;
					break;
				case 0:
					element.className = Config.tool.css.tool;
					break;
				case -1:
				case -2:
					element.className = Config.tool.css.toolDown;
					break;
				case -3:
					element.className = Config.tool.css.toolDisable;
					break;
			}
		}
	}
};
Editor.toolMouseOver = function(element)
{
	if(Editor.isEdit() && element.hexun.state == 0)
	{
		Editor.setState(element,1);
	}
};
Editor.toolMouseOut = function(element)
{
	if(Editor.isEdit() && (element.hexun.state == 1 || element.hexun.state == -1))
	{
		Editor.setState(element,0);
	}
};
Editor.toolMouseDown = function(element)
{
	if(Editor.isEdit() && element.hexun.state != -3)
	{
		if(Lister.now) 
		{
			if(!(element.hexun.lister && element.hexun.lister == Lister.now))
			{
				Lister.now.cancel(false);
			}
		}
		
		if(element.hexun.state != -1 && element.hexun.state != -2) Editor.setState(element,-1);
	}
};
Editor.toolMouseUp = function(e,element)
{
	if(Editor.isEdit() && element.hexun.state != -3)
	{
		var newState = 1;
		if(element.hexun.state == -1) newState = element.hexun.downCall.call(Editor);
		if(element.hexun.state == -2) newState = element.hexun.upCall.call(Editor);
		Editor.setState(element,newState);
		Event.stop(e);
		
		Editor.checkAllState();
	}
};
Editor.blankUpCall = function(){return 0;};
Editor.blankCall = function(returnValue)
{
	if(typeof(returnValue) != "undefined") return returnValue;
};
Editor.normalCancelCall = function(controlId,state)
{
	var newState = 0;
	if(state) newState = state;
	Editor.setState(null,newState,controlId);
};
Editor.showFontNameList = function()
{
	var element = Editor.controls["fontname"];
	if(!element.hexun.lister) element.hexun.lister = new Lister(element,Config.lister.fontNameData,1,Config.lister.option);
	element.hexun.lister.show();
	return -2;
};
Editor.hideFontNameList = function()
{
	var element = Editor.controls["fontname"];
	if(element.hexun.lister) element.hexun.lister.cancel(false);
	return 1;
};
Editor.setFontName = function(fontName)
{
	if(fontName) Editor.command("FontName",fontName);
	Editor.setState(null,0,"fontname");
};
Editor.cancelFontName = function()
{
	Editor.setState(null,0,"fontname");
};
Editor.showFontName = function(fontName,fontValue)
{
	var element = Editor.controls["fontname"].hexun.tool;
	var str = "字体";
	if(fontName) str = fontName;
	else if(fontValue)
	{
		var i = 0;
		var fontNameData = Config.lister.fontNameData
		for(i=0;i<fontNameData.value.length;i++)
		{
			if(fontNameData.value[i] == fontValue)
			{
				str = fontNameData.text[i];
			}
		}
	}
	element.innerHTML = str;
};
Editor.showFontSizeList = function()
{
	var element = Editor.controls["fontsize"];
	if(!element.hexun.lister) element.hexun.lister = new Lister(element,Config.lister.fontSizeData,1,Config.lister.option);
	element.hexun.lister.show();
	return -2;
};
Editor.hideFontSizeList = function()
{
	var element = Editor.controls["fontsize"];
	if(element.hexun.lister) element.hexun.lister.cancel(false);
	return 1;
};
Editor.setFontSize = function(fontSize)
{
	if(fontSize) Editor.command("FontSize",fontSize);
	Editor.setState(null,0,"fontname");
};
Editor.cancelFontSize = function()
{
	Editor.setState(null,0,"fontsize");
};
Editor.showFontSize = function(fontName,fontValue)
{
	var element = Editor.controls["fontsize"].hexun.tool;
	var str = "字号";
	if(fontName) str = fontName;
	else if(fontValue)
	{
		var i = 0;
		var fontNameData = Config.lister.fontSizeData
		for(i=0;i<fontNameData.value.length;i++)
		{
			if(fontNameData.value[i] == fontValue)
			{
				str = fontNameData.text[i];
			}
		}
	}
	element.innerHTML = str;
};
Editor.showForeColorList = function()
{
	var element = Editor.controls["forecolor"];
	if(!element.hexun.lister) element.hexun.lister = new Lister(element,Config.lister.colorData,8,Config.lister.option);
	element.hexun.lister.show();
	return -2;
};
Editor.hideForeColorList = function()
{
	var element = Editor.controls["forecolor"];
	if(element.hexun.lister) element.hexun.lister.cancel(false);
	return 1;
};
Editor.setForeColor = function(foreColor)
{
	if(foreColor) Editor.command("ForeColor",foreColor);
	Editor.setState(null,0,"forecolor");
};
Editor.cancelForeColor = function()
{
	Editor.setState(null,0,"forecolor");
};
Editor.showBackColorList = function()
{
	var element = Editor.controls["backcolor"];
	if(!element.hexun.lister) element.hexun.lister = new Lister(element,Config.lister.colorData,6,Config.lister.option);
	element.hexun.lister.show();
	return -2;
};
Editor.hideBackColorList = function()
{
	var element = Editor.controls["backcolor"];
	if(element.hexun.lister) element.hexun.lister.cancel(false);
	return 1;
};
Editor.setBackColor = function(backColor,element)
{
	if(backColor)
	{
		if(window.isIE) Editor.command("BackColor",backColor);
		else Editor.command("hilitecolor",backColor);
	}
	Editor.setState(null,0,"backcolor");
};
Editor.cancelBackColor = function()
{
	Editor.setState(null,0,"backcolor");
};

Editor.getDocument = function()
{
	return Editor.editorWin.document;
};

Editor.setDesignMode = function (canEdit)
{
	Editor.getDocument().designMode = canEdit?"On":"Off";
};

Editor.canEdit = function()
{
	return (Editor.viewState != "changing");
};
Editor.isEdit = function()
{
	return (Editor.viewState == "edit");
};
Editor.showBrow = function()
{
	var element = Editor.controls["emot"];
	if(!element.hexun.lister) {
		var browConfig = {
			init: function(container, callback) {
				Emote.init({parent: container, output: 'url', callback: function(url, title) {
					callback('<img src="' + url + '" title="' + title + '" alt="' + title + '" />');
				},
				matrix: {
					"20": [11, 6],
					"42": [6, 4]
				}});
			},
			type: 'function'
		}
		element.hexun.lister = new Lister(element,browConfig,8,Config.lister.option);
	}
	element.hexun.lister.show();
	return -2;
};
Editor.hideBrow = function()
{
	var element = Editor.controls["emot"];
	if(element.hexun.lister) element.hexun.lister.cancel(false);
	return 1;
};
Editor.addBrow = function(browName)
{
	if(browName)
	{
		var html = "&nbsp;" + browName + "&nbsp;";
		Editor.pasteHTML(html);
	}
	Editor.setState(null,0,"emot");
};
Editor.cancelBrowCall = function()
{
	Editor.setState(null,0,"emot");
};
Editor.fastPasteHTML = function(html)
{
	if(window.isIE)
	{
		var range = Editor.editorWin.document.selection.createRange();
		if(range) range.pasteHTML(html);
	}
	else
	{
		var range = Editor.editorWin.document;
		range.execCommand("inserthtml",null,html);
	}
};
Editor.pasteHTML = function(html)
{
	var returnValue = false;
	if(Editor.isEdit())
	{
		var range = Editor.getRange();
		if(range)
		{
			if(window.isIE) 
			{
				if(Editor.selection.type.toLowerCase() == "control")
				{
					var tempRange = Editor.editorWin.document.body.createTextRange();
					tempRange.moveToElementText(range.item(0));
					range = tempRange;
				}
				range.pasteHTML(html);
				range.select();
			}
			else 
			{
				Editor.command("inserthtml",html);
			}
			returnValue = true;
		}
		else
		{
			alert("发生错误，请重新操作！");
		}
	}
	return returnValue;
};

/*
Editor.getClipboardData = function()
{
	Editor.cache.innerHTML = "";
	var range = document.body.createTextRange();
	range.moveToElementText(Editor.cache);
	
	range.execCommand("Paste");
	
	var htmlData = "";
	if(Editor.cache.childNodes.length == 1 && Editor.cache.childNodes[0].tagName && Editor.cache.childNodes[0].tagName.toLowerCase() == "font" && Editor.cache.childNodes[0].color == "#000000")
	{
		htmlData = Editor.cache.childNodes[0].innerHTML;
	}
	else htmlData = Editor.cache.innerHTML;
	
	Editor.cache.innerHTML = "";
	return htmlData;
};
*/

Editor.getClipboardData = function()
{
	Editor.iCacheDoc.body.innerHTML = "";
	Editor.iCacheDoc.body.createTextRange().execCommand("Paste");
	var htmlData = Editor.iCacheDoc.body.innerHTML;
	Editor.iCacheDoc.body.innerHTML = "";
	return htmlData;
};

Editor.clearHTMLTag = function(html)
{
  return   html.replace(/\<.*?>/ig,"");  
}
Editor.clearFromWord = function(html)
{
	html = html.replace(/<\/?SPAN[^>]*>/gi, "" );
	html = html.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3");
	html = html.replace(/<(\w[^>]*) style="([^"]*)"([^>]*)/gi, "<$1$3");
	html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3");
	html = html.replace(/<\\?\?xml[^>]*>/gi, "");
	html = html.replace(/<\/?\w+:[^>]*>/gi, "");
	html = html.replace(/<\/?\w+:[^>]*>/gi, "");
	html = html.replace(/<\/?\w+:[^>]*>/gi, "");
	return html;
};



Editor.getSelectedHTML = function()
{
	var html = "";
	var range = Editor.getRange();
	if(range) 
	{
		if(window.isIE)
		{
			if(Editor.selection.type.toLowerCase() == "control")
			{
				html = range.item(0).outerHTML;
			}
			else
			{
				html = range.htmlText;
			}
			if(!html) html = "";
		}
		else
		{
			if(Editor.selection.rangeCount > 0)
			{
				var tRange = Editor.selection.getRangeAt(0);
				var dFragment = tRange.cloneContents();
				Editor.cache.innerHTML = "";
				Editor.cache.appendChild(dFragment);
				html = Editor.cache.innerHTML;
				Editor.cache.innerHTML = "";
			}
		}
		
	}
	return html;
};

Editor.setBold = function()
{
	var newState = Editor.command("Bold")?-2:0;
	return newState;
};
Editor.setItalic = function()
{
	var newState = Editor.command("Italic")?-2:0;
	return newState;
};
Editor.setUnderline = function()
{
	var newState = Editor.command("Underline")?-2:0;
	return newState;
};
Editor.copy = function()
{
	if(window.isIE) 
	{
		Editor.command("Copy");
		return -1;
	}
	else
	{
		alert("提示：您现在所使用的浏览器不支持此操作，请使用快捷键 [Ctrl + C]！");
		return 0;
	}
};
Editor.cut = function()
{
	if(window.isIE)
	{
		Editor.command("Cut");
		return -1;
	}
	else
	{
		alert("提示：您现在所使用的浏览器不支持此操作，请使用快捷键 [Ctrl + X]！");
		return 0;
	}
};
Editor.shortcutPaste = function()
{
	Editor.paste();
	return false;
};
Editor.paste = function()
{
	if(window.isIE) 
	{
		if(Editor.isEdit())
		{
			var pasteData = Editor.getClipboardData();
			if(pasteData && pasteData.length > 0)
			{
				var wordPattern = /<\w[^>]* class="?MsoNormal"?/gi;
				if(wordPattern.test(pasteData))
				{
					if(confirm("您现在是从word中复制，是否清除其中的格式？\r\n\r\n小提示：清除格式可以使编辑更为方便！"))
					{
						pasteData = Editor.clearFromWord(pasteData);
					}
				}
				Editor.pasteHTML(pasteData);
			}
		}
		return -1;
	}
	else
	{
		alert("提示：您现在所使用的浏览器不支持此操作，请使用快捷键 [Ctrl + V]！");
		return 0;
	}
};

Editor.setElementJustify = function(element,value)
{
	switch(value)
	{
		case "left":
			align = "FLOAT: left; MARGIN: 0px 10px 10px 0px";
			break;
		case "center":
			align = "DISPLAY: block; MARGIN: 0px auto 10px; TEXT-ALIGN: center";
			break;
		case "right":
			align = "FLOAT: right; MARGIN: 0px 0px 10px 10px";
			break;
		default:
			align = "DISPLAY: block";
			break;
	}
	element.style.cssText = align;
};

Editor.setLeft = function()
{
	var element = Editor.getSpecialElement(["img","embed"]);
	if(element) Editor.setElementJustify(element,"left");
	else Editor.command("JustifyLeft");
	//	Editor.command("JustifyLeft");
	return -1;
};
Editor.setCenter = function()
{
	var element = Editor.getSpecialElement(["img","embed"]);
	if(element) Editor.setElementJustify(element,"center");
	else Editor.command("JustifyCenter");
	//	Editor.command("JustifyCenter");
	return -1;
};
Editor.setRight = function()
{
	var element = Editor.getSpecialElement(["img","embed"]);
	if(element) Editor.setElementJustify(element,"right");
	else Editor.command("JustifyRight");
	//	Editor.command("JustifyRight");
	return -1;
};
Editor.setOrder = function()
{
	Editor.command("InsertOrderedList");
	return -1;
};
Editor.setUnorder = function()
{
	Editor.command("InsertUnorderedList");
	return -1;
};
Editor.setIndent = function()
{
	Editor.command("Indent");
	return -1;
};
Editor.setOutdent = function()
{
	Editor.command("Outdent");
	return -1;
};
Editor.cleanup = function()
{
    Editor.editorWin.document.body.innerHTML = Editor.clearHTMLTag(Editor.editorWin.document.body.innerHTML);
    return 0;
}
Editor.showLink = function()
{
	var controler = Editor.controls["url"];
	var linkElement = Editor.getSpecialElement("a",true);
	var str = "";	
	if(!linkElement)
	{
		str = Editor.getSelectedHTML();
//		if(str.length < 1)
//		{
//			alert("请选择要添加链接的内容！");
//			return 0;
//		}
	}
	
	var feas = 
	[
		["height","260"],
		["width","440"],
		["center","yes"]
	];
	
	var args = 
	{
		win:window,
		controler:controler,
		obj:linkElement,
		str:str
	};
	var win = Dom.showModalDialog(Config.basePath + "dialog/insert_link.htm",args,feas);
	
	return 0;
};
Editor.clearLink = function()
{
	if(window.isIE)
	{
		Editor.command("Unlink");
	}
	else
	{
		var html = "";
		var linkElement;
		if(window.isIE) linkElement = Editor.getSpecialElement("a",true);
		else linkElement = Editor.getSpecialElement("a",false);
		
		if(linkElement)
		{
			html = linkElement.innerHTML;
			if(!window.isIE)
			{
				var tempRange = Editor.editorWin.document.createRange();
				tempRange.selectNode(linkElement);
				var sel = Editor.editorWin.getSelection();
				if(sel) 
				{
					sel.removeAllRanges();
					sel.addRange(tempRange);
				}
			}
			Editor.pasteHTML(html);
		}
	}
};
Editor.cancelLinkCall = function()
{
	Editor.setState(null,0,"url");
};
Editor.addLink = function(obj)
{
	if(obj)
	{
		var html = "";
		
		var linkElement = Editor.getSpecialElement("a");
		
		if(obj.innerhtml.trim() == "")
		{
		    obj.innerhtml = obj.link;
		}
		if(linkElement)
		{
		    linkElement.innerHTML = obj.innerhtml;
			linkElement.href = obj.link;
			linkElement.target = obj.target;
		}
		else
		{
			html = '<a href="' + obj.link + '" target="' + obj.target + '">' + obj.innerhtml + '</a>';	
			Editor.pasteHTML(html);
		}
	}
};
Editor.showImg = function()
{
    Editor.editorWin.focus();
	var controler = Editor.controls["simg"];
	var imgElement = Editor.getSpecialElement("img",true);
	var feas = 
	[
		["height","400"],
		["width","600"],
		["center","yes"]
	];
	
	var args = 
	{
		win:window,
		controler:controler,
		obj:imgElement
	};
	var win = Dom.open(Config.imagePageUrl,args,feas,true);
	
	return 0;
};
Editor.cancelImgCall = function()
{
	Editor.setState(null,0,"simg");
};
Editor.addImg = function(info)
{
	if(info)
	{
		//	首先判断是添加新图片还是修改图片信息
		var imgElement = Editor.getSpecialElement("img",true);
		
		var align = "";
		if(info.align)
		{
			switch(info.align)
			{
				case "none":
					align = " ";
					break;
				case "left":
					align = "FLOAT: left; MARGIN: 0px 10px 10px 0px";
					break;
				case "center":
					align = "DISPLAY: block; MARGIN: 0px auto 10px; TEXT-ALIGN: center";
					break;
				case "right":
					align = "FLOAT: right; MARGIN: 0px 0px 10px 10px";
					break;
			}
		}		
		Editor.pasteHTML(info.data);
	}
}

Editor.popForeColor = function()
{
    Editor.hideForeColorList();
	var controler = Editor.controls["forecolor"];
	var feas = 
	[
		["height","300"],
		["width","300"],
		["center","yes"]
	];
	
	var args = 
	{
		win:window,
		controler:controler,
		obj:null
	};
	var win = Dom.showModalDialog(Config.basePath + "dialog/select_color.htm",args,feas,true);
	
	return 0;
};

Editor.popBackColor = function()
{
    Editor.hideBackColorList();
	var controler = Editor.controls["backcolor"];
	var feas = 
	[
		["height","300"],
		["width","300"],
		["center","yes"]
	];
	
	var args = 
	{
		win:window,
		controler:controler,
		obj:null
	};
	var win = Dom.showModalDialog(Config.basePath + "dialog/select_color.htm",args,feas,true);
	
	return 0;
};


Editor.showChar = function()
{
	var controler = Editor.controls["char"];
	var feas = 
	[
		["height","350"],
		["width","500"],
		["center","yes"]
	];
	
	var args = 
	{
		win:window,
		controler:controler,
		obj:null
	};
	var win = Dom.showModalDialog(Config.basePath + "dialog/insert_char.htm",args,feas);
	return 0;
};
Editor.cancelCharCall = function()
{
	Editor.setState(null,0,"char");
};
Editor.addChar = function(info)
{
	if(info)
	{
		Editor.pasteHTML(info.data);
	}
}

//增加附件
Editor.showFile = function()
{
    Editor.editorWin.focus();
	var controler = Editor.controls["sfile"];
	var feas = 
	[
		["height","400"],
		["width","500"],
		["center","yes"]
	];
	
	var args = 
	{
		win:window,
		controler:controler,
		obj:null
	};
	var win = Dom.open(Config.filePageUrl,args,feas,true);
	
	return 0;
};
Editor.cancelFileCall = function()
{
	Editor.setState(null,0,"sfile");
};
Editor.addFile = function(info)
{
	if(info)
	{
		Editor.pasteHTML(info.data);
	}
}

//增加投票
Editor.showVote = function()
{
    Editor.editorWin.focus();
	var controler = Editor.controls["vote"];
	var feas = 
	[
		["height","500"],
		["width","800"],
		["center","yes"]
	];
	
	var args = 
	{
		win:window,
		controler:controler,
		obj:null
	};
	var win = Dom.open(Config.votePageUrl,args,feas,true);
	
	return 0;
};
Editor.cancelVoteCall = function()
{
	Editor.setState(null,0,"vote");
};
Editor.addVote = function(info)
{
	if(info)
	{
		Editor.pasteHTML(info.data);
	}
}


//增加附件
Editor.showMedia = function()
{
    Editor.editorWin.focus();
	var controler = Editor.controls["media"];
	var feas = 
	[
		["height","520"],
		["width","700"],
		["center","yes"]
	];
	
	var args = 
	{
		win:window,
		controler:controler,
		obj:null
	};
	var win = Dom.open(Config.mediaPageUrl,args,feas,true);
	
	return 0;
};
Editor.cancelMediaCall = function()
{
	Editor.setState(null,0,"media");
};
Editor.addMedia = function(info)
{
	if(info)
	{
		Editor.pasteHTML(info.data);
	}
}

Editor.redraw = function()
{
	Editor.editorWin.document.body.style.visibility = "hidden";
	Editor.editorWin.document.body.style.visibility = "visible";
};
Editor.showFlash = function()
{
	var controler = Editor.controls["flash"];
	var mvElement = Editor.getSpecialElement("embed",true);
	var feas = 
	[
		["height","250"],
		["width","400"],
		["center","yes"]
	];
	
	var args = 
	{
		win:window,
		controler:controler,
		obj:mvElement
	};
	var win = Dom.showModalDialog(Config.basePath + "dialog/insert_flash.htm",args,feas);
	
	return 0;
};
Editor.cancelFlashCall = function()
{
	Editor.setState(null,0,"flash");
};
Editor.addFlash = function(mvObj)
{
	if(mvObj)
	{
		var mvElement = Editor.getSpecialElement("embed");
		if(mvElement)
		{
			var range = Editor.getRange();
			mvElement.src = mvObj.f_url;
			mvElement.width = mvObj.f_width;
			mvElement.height = mvObj.f_height;
			mvElement.play = (mvObj.f_autostart=="true")?true:false;
			mvElement.loop = (mvObj.f_loop=="true")?true:false;
		}
		else
		{
			var html = '<embed src="' + mvObj.f_url + '" width="' + mvObj.f_width + '" height="' + mvObj.f_height + '" type="application/x-shockwave-flash" loop="' + mvObj.f_loop + '" play="' + mvObj.f_autostart + '" menu="true"/>';
			Editor.pasteHTML(html);
		}
	}
};


Editor.getHTML = function() {
	var html = "";
	var filter = new Editor.Filter();
	filter.removeForbidTag(Editor.editorWin.document);
	return Editor.editorWin.document.body.innerHTML;
};

Editor.stripBaseURL = function(string) {
	var baseurl = Config.baseURL;

	// strip to last directory in case baseurl points to a file
	baseurl = baseurl.replace(/[^\/]+$/, '');
	var basere = new RegExp(baseurl);
	string = string.replace(basere, "");

	// strip host-part of URL which is added by MSIE to links relative to server root
	baseurl = baseurl.replace(/^(https?:\/\/[^\/]+)(.*)$/, '$1');
	basere = new RegExp(baseurl);
	return string.replace(basere, "");
};
Editor.needsClosingTag = function(el) {
	var closingTags = " head script style div span tr td tbody table em strong font a title iframe ";
	return (closingTags.indexOf(" " + el.tagName.toLowerCase() + " ") != -1);
};

Editor.Filter = function () {
	this.version = "1.0";
	
	this.htmlAllow = [
		[ "a", 			["href", "name", "rel", "style", "title", "target"] ],
		[ "abbr", 		["title", "style"] ],
		[ "acronym", 	["title", "style"] ],
		[ "b", 			["title", "style"] ],
		[ "big", 		["title", "style"] ],
		[ "blockquote", ["cite" , "title", "style"] ],
		[ "br", 		[] ],
		[ "center", 	["title", "style"] ],
		[ "cite", 		["title", "style"] ],
		[ "code", 		["title", "style"] ],
		[ "dd", 		["align", "style"] ],
		[ "div", 		["align", "style"] ],
		[ "dl", 		["align", "style"] ],
		[ "dt", 		["align", "style"] ],
		[ "em", 		["title", "style"] ],
		[ "embed",		["src", "width", "height", "type", "autostart", 'play', "loop", "style"] ],
		[ "font", 		["color", "face", "size", "style"] ],
		[ "h1", 		["title", "style"] ],
		[ "h2", 		["title", "style"] ],
		[ "h3", 		["title", "style"] ],
		[ "h4", 		["title", "style"] ],
		[ "h5", 		["title", "style"] ],
		[ "h6", 		["title", "style"] ],
		[ "hr", 		["title", "style"] ],
		[ "i", 			["title", "style"] ],
		[ "img", 		["src", "width", "height", "alt", "border", "style"] ],
		[ "li", 		["title", "style"] ],
		[ "ol", 		["title", "style"] ],
		[ "p", 			["align"] ],
		[ "pre", 		["title", "style"] ],
		[ "s", 			["title", "style"] ],
		[ "small", 		["title", "style"] ],
		[ "span", 		["title", "style"] ],
		[ "strike", 	["title", "style"] ],
		[ "strong", 	["title", "style"] ],
		[ "sub", 		["title", "style"] ],
		[ "sup", 		["title", "style"] ],
		[ "table", 		["align", "bgcolor", "border", "cellpadding", "cellspacing", "frame", "rules", "summary", "title", "style"] ],
		[ "tbody", 		["align", "char", "charoff", "valign", "title", "style"] ],
		[ "td", 		["abbr", "align", "axis", "bgcolor", "char", "charoff", "colspan", "headers", "height", "rowspan", "scope", "valign", "title", "style"] ],
		[ "tfoot", 		["align", "char", "charoff", "valign", "title", "style"] ],
		[ "thead", 		["align", "char", "charoff", "valign", "title", "style"] ],
		[ "tr", 		["align", "bgcolor", "char", "charoff", "valign", "title", "style"] ],
		[ "tt", 		["title", "style"] ],
		[ "u", 			["title", "style"] ],
		[ "ul", 		["title", "style"] ],
		[ "xmp", 		["title", "style"] ],
		["iframe",      ["src", "style","marginwidth","marginheight","allowtransparency","frameborder","height","width","scrolling"]]
	];

	this.htmlForbid = [ "script", "frameset", "frame", "meta"];
	
	this.isHtmlAllowTag = function(_tagName) {
		for (var i=0; i<this.htmlAllow.length; i++) {
			if (_tagName == this.htmlAllow[i][0])
				return true;
		}
		return false;
	};

	this.isHtmlAllowAttrOfTag = function(_attr, _tagName) {
		for (var i=0; i<this.htmlAllow.length; i++) {
			if (_tagName == this.htmlAllow[i][0]) {
				for (var j=0; j<this.htmlAllow[i][1].length; j++) {
					if (_attr == this.htmlAllow[i][1][j])
						return true;
				}
			}
		}
		return false;
	};

	this.isHtmlForbidTag = function(_tagName) {
		for (var i=0; i<this.htmlForbid.length; i++) {
			if (_tagName == this.htmlForbid[i])
				return true;
		}
		return false;
	};
	
	this.removeForbidTag = function(document){
	    for(var i=0; i < this.htmlForbid.length; i++)
	    {
	        var objlist = document.getElementsByTagName(this.htmlForbid[i]);
	     
	        if(!objlist)continue;
	        
	        for(var j =0;j < objlist.length; j++)
	        {
	            if(this.htmlForbid[i] == "iframe" && objlist[j].src.indexOf("hexun.com/") >= 0)
	                continue;
	            else
	            {
	                objlist[j].parentNode.removeChild(objlist[j]);
	               //objlist[j].removeNode(true); 
	            }
	        }
	        
	    }
	}
};

Editor.htmlEncode = function(str) {
	str = str.replace(/&/ig, "&amp;");
	str = str.replace(/</ig, "&lt;");
	str = str.replace(/>/ig, "&gt;");
	str = str.replace(/\x22/ig, "&quot;");
	return str;
};

Editor.showTable = function()
{
	var controler = Editor.controls["table"];
	var tableElement = Editor.getSpecialElement("table",true);
	var feas = 
	[
		["height","250"],
		["width","400"],
		["center","yes"]
	];
	
	var args = 
	{
		win:window,
		controler:controler,
		obj:tableElement
	};
	var win = Dom.showModalDialog(Config.basePath + "dialog/insert_table.htm",args,feas);
	return 0;
};

Editor.cancelTableCall = function()
{
	Editor.setState(null,0,"table");
};
Editor.addTable = function(info)
{
	if(info)
	{
		//	首先判断是添加新图片还是修改图片信息
		var tableElement = Editor.getSpecialElement("table",true);
		
		var align = "";
		if(info.align && info.align != "none")
		{
		    align = " align='" + info.align + "'";
		}
		var style= "BORDER-COLLAPSE: collapse;";
		if(info.tbwidth != "")
		{
		    style += "width:" + info.tbwidth + "px";
		}
		var border = "";
		if(info.tbwidth != "")
		{
		    border = " border='" + info.tbborder + "'";
		}
		var cellpadding = "";
		if(info.tbwidth != "")
		{
		    cellpadding = " cellpadding='" + info.cellpadding + "' ";
		}
		style = " style=\"" + style + "\" ";
		var html = "<table cellspacing='1' "+ align + style + border + cellpadding + ">\r\n";
		html += "<tbody>\r\n" ;
		for(var i = 0; i < info.selrow; i++)
		{
		    html += "      <tr>\r\n";
		    for(var j = 0; j < info.selcol; j++)
		    {
		        html += "        <td>&nbsp;</td>\r\n";
		    }
		    html += "      </tr>\r\n"
		}
		html += "</tbody>\r\n";
		html += "</table>\r\n";
		Editor.pasteHTML(html);
	}
}
Editor.getDateStr = function(timestamp) {
	var date = new Date(parseInt(timestamp));
	var month = date.getMonth() + 1;
	month = (month>9?"":"0") + month;
	var day= (date.getDate()>9?"":"0") + date.getDate();
	var str = date.getFullYear() + "-" + month + "-" + day;
	return str;
};
Editor.focusContent = function() {
	Editor.editorWin.focus();
};

Editor.cacheRange = function()
{
	Editor.selection = Editor.editorWin.document.selection;
	Editor.rangeCache = Editor.selection.createRange();
};
Editor.checkRange = function()
{
	if(Editor.rangeCache)
	{
		Editor.editorWin.focus();
		Editor.rangeCache.select();
		Editor.rangeCache = false;
	}
};
Editor.getRange = function()
{
	var range = false;
	if(window.isIE)
	{
		Editor.editorWin.focus();
		Editor.selection = Editor.editorWin.document.selection;
		range = Editor.selection.createRange();
	}
	else 
	{
		Editor.selection = Editor.editorWin.getSelection();
		range = Editor.editorWin.document;
	}
	
	return range;
};
Editor.getElement = function()
{
	var element = null;
	var sel;
	var range;
	
	if(window.isIE)
	{
		sel = Editor.editorWin.document.selection;
		switch(sel.type.toLowerCase())
		{
			case "none":
			case "text":
			{
				range = sel.createRange();
				element = range.parentElement();
				break;
			}
			case "control":
			{
				var ranges = sel.createRange();
				element = ranges.item(0);
				break;
			}
		}
	}
	else
	{
		sel = Editor.editorWin.getSelection();
		if(sel.rangeCount > 0)
		{
			range = sel.getRangeAt(0);
			if(range.startContainer == range.endContainer)
			{
				if(range.startContainer.nodeType != 3)
				{
					element = range.startContainer.childNodes[range.startOffset];
				}
				else element = range.startContainer;
			}
			else element = range.commonAncestorContainer;
		}
		if(element && element.nodeType == 3) element = element.parentNode;
	}
	
	return element;
};
Editor.getSpecialElement = function(tagName,isFoucs)
{
	var element = null;
	
	var tempElement = Editor.getElement();
	
	if(tempElement)
	{
		if(typeof(tagName) == "string") tagName = [tagName];
		while(tempElement && tempElement.tagName)
		{
			for(var i=tagName.length-1;i>=0;i--)
			{
				if(tagName[i] == tempElement.tagName.toLowerCase())
				{
					element = tempElement;
					break;
				}
			}
			if(element) break;
			else tempElement = tempElement.parentNode;
		}
	}
	
	if(isFoucs && element)
	{
		if(window.isIE)
		{
			Editor.rangeCache = false;
			var range = Editor.editorWin.document.body.createTextRange();
			range.moveToElementText(element);
			range.select();
		}
		else
		{
			var sel = Editor.editorWin.getSelection();
			if(sel) 
			{
				var range = sel.getRangeAt(0);
				range.selectNode(element);
				sel.removeAllRanges();
				sel.addRange(range);
			}
		}
	}
	
	return element;
};

//var Class={create:function(){return function(){this.initialize.apply(this,arguments);};}};

var Lister = Class.create();

Lister.now = false;

Lister.prototype = 
{
	initialize: function(controler,listData,colCount,option)
	{
		this.controler = controler;
		this.listData = listData;
		this.colCount = colCount;
		this.containerClass = option.containerClass;
		this.itemClass = listData.itemClass?listData.itemClass:option.itemClass;
		this.itemOverClass = listData.itemOverClass?listData.itemOverClass:option.itemOverClass;
		
		if(!this.listData.text) this.listData.text = this.listData.value;
		
		this.clickEventObj = false;
		this.visibility = false;
		
		this.initContainer(this.containerClass);
	},
	
	initContainer: function(class2)
	{
		var element = document.createElement("div");
		element.className = class2;
		element.style.visibility = "hidden";
		this.container = element;
		this.initContent();
		document.body.appendChild(this.container);
	},
	
	initContent: function()
	{
		switch(this.listData.type)
		{
			case "auto":
			{
				for(var i=0;i<this.listData.value.length;i++)
				{
					if(i%this.colCount == 0 && i > 0) Dom.create("div","newLine",this.container);
					
					this.initListItem(i,this.container);
				}
				break;
			}
			case "manual":
			{
				for(var i=0;i<this.listData.value.length;i++)
				{
					this.initListItem2(i,this.container);
				}
				break;
			}
			case "manual2":
			{
				this.container.innerHTML = this.listData.content;
				break;
			}
			case "table":
			{
			    var table = Dom.create("table","",this.container);
			    for(var i=0;i<this.listData.value.length;i++)
				{
				    var newtr = table.insertRow(i);
					this.initListItem3(i,newtr);
				}
				break;
			}
			case "function":
				this.listData.init(this.container, this.selectedCall.bind(this)); 
				break;
		}
	},
	
	initListItem: function(index,parent)
	{
		var text = this.listData.text[index];
		var value = this.listData.value[index];
		var pattern = this.listData.pattern;
		
		text = pattern.replace(/\$=text\$/ig,text).replace(/\$=value\$/ig,value);
		
		var element = Dom.create("div",this.itemClass,parent);
		
		element.innerHTML = text;
		
		var itemClickFunc = this.selectedCall.bind(this,value);
		var itemOverFunc = this.itemMouseOver.bind(this,element);
		var itemOutFunc = this.itemMouseOut.bind(this,element);
		Event.observe(element,"click",itemClickFunc);
		Event.observe(element,"mouseover",itemOverFunc);
		Event.observe(element,"mouseout",itemOutFunc);
	},
	
	initListItem2: function(index,parent)
	{
		var text = this.listData.value[index][0];
		var value = this.listData.value[index][1];
		
		if(text)
		{
			var element = Dom.create("div",this.itemClass,parent);
			
			element.innerHTML = text;
			
			var itemClickFunc = this.selectedCall.bind(this,value);
			var itemOverFunc = this.itemMouseOver.bind(this,element);
			var itemOutFunc = this.itemMouseOut.bind(this,element);
			Event.observe(element,"click",itemClickFunc);
			Event.observe(element,"mouseover",itemOverFunc);
			Event.observe(element,"mouseout",itemOutFunc);
		}
		else
		{
		    if(index < this.listData.value.length-1)
			Dom.create("div","newLine",this.container);
		}
	
	},
	initListItem3: function(index,parent)
	{
	
	    if(this.listData.value[index].length == 2)
	    {
	        var element = parent.insertCell(0);
	        element.className =  this.itemClass;
	        element.colSpan = 8;
	        element.align = "center";
	        var value = this.listData.value[index][1];
	        element.innerHTML = value;
	        var itemOverFunc = this.itemMouseOver.bind(this,element);
			var itemOutFunc = this.itemMouseOut.bind(this,element);
			
			Event.observe(element,"mouseover",itemOverFunc);
			Event.observe(element,"mouseout",itemOutFunc);
			
	        if(this.listData.value[index][0] == "header")
	        {
	            var itemClickFunc = this.selectedCall.bind(this,"#");
	            Event.observe(element,"click",itemClickFunc);
			    
			}
			else
			{
			    var itemClickFunc = this.popCall.bind(this,"");
	            Event.observe(element,"click",itemClickFunc);
			}
	    }
        else
		{
		    for(var i = 0; i < this.listData.value[index].length; i++)
		    {
			    var element = parent.insertCell(i);
			    element.className =  this.itemClass;
			    element.width = 14 + "px";
			    element.height = 14 + "px";
			    element.align = "center";
			    element.vAlign = "middle";
			    var value = this.listData.value[index][i];
			    element.innerHTML = '<div style="border:1px solid #0a246a;width:10px;height:10px;background-color: '+value+'"></div>';
			    var itemClickFunc = this.selectedCall.bind(this,value);
			    var itemOverFunc = this.itemMouseOver.bind(this,element);
			    var itemOutFunc = this.itemMouseOut.bind(this,element);
			    Event.observe(element,"click",itemClickFunc);
			    Event.observe(element,"mouseover",itemOverFunc);
			    Event.observe(element,"mouseout",itemOutFunc);
			    
			}
		}
	},
	itemMouseOver: function(element)
	{
		element.className = this.itemOverClass;
	},
	
	itemMouseOut: function(element)
	{
		element.className = this.itemClass;
	},
	
	selectedCall: function(value)
	{
		this.hide();
		this.controler.hexun.selectCall.call(Editor,value,this.controler);
	},
	popCall: function(value)
	{
		this.hide();
		this.controler.hexun.popCall.call(Editor,value,this.controler);
	},
	
	cancel: function(e)
	{
		if(this.visibility)
		{
			var canCancel = true;
			if(typeof(e) != "boolean")
			{
				e = window.event || e;
				if(e)
				{
					eventEle = Event.element(e);
					while(eventEle)
					{
						if(this.container == eventEle)
						{
							canCancel = false;
							break;
						}
						eventEle = eventEle.parentElement;
					}
				}
			}
			if(canCancel)
			{
				this.hide();
				this.controler.hexun.cancelCall.call(this.controler);
			}
		}
	},
	
	show: function()
	{
		if(!this.visibility)
		{
			this.visibility = true;
			var rect = Dom.getRect(this.controler);
			var position = {left:rect.left,top:rect.bottom};
			Dom.setPosition(this.container,position);
			this.clickEventObj = this.cancel.bind(this);
			Event.observe(document,"mouseup",this.clickEventObj);
			Event.observe(Editor.editorWin.document,"mouseup",this.clickEventObj);
			Dom.show(this.container);
			Lister.now = this;
			
			if(this.listData.init) eval(this.listData.init);
		}
	},
	
	hide: function()
	{
		Lister.now = false;
		if(this.clickEventObj)
		{
			Event.stopObserving(document,"mouseup",this.clickEventObj);
			Event.stopObserving(Editor.editorWin.document,"mouseup",this.clickEventObj);
			this.clickEventObj = false;
		}
		this.visibility = false;
		Dom.hide(this.container);
	}
};