﻿function gid(id){return document.getElementById?document.getElementById(id):null;}

var dpe_lang_Default_Folder = "/Comm/DP_Editor/";
var dpe_lang_Default_Font = "arial";
var dpe_lang_Default_FontSize = "14.8px";

var dpe_lang_Bold = true;
function GenerateButtonBold(){return "<a href=\"#\" onclick=\"this.blur();DPEEditorFormat(" + dp_EditorActive + ", 'bold');return false;\" class=\"DP_Editor_Button\" title=\"粗体\"><img src=\"" + dpe_lang_Default_Folder + "dp_editor_bold.gif\" border=\"0\" /></a>";}

var dpe_lang_FontSize = true;
var dpe_lang_FontSizeArray = [1, 2, 3, 4, 5];
function GenerateFontSizePicker()
{
	var html = "";
	html = "&nbsp;<select onchange=\"var Value = this.options[this.selectedIndex].value;DPEEditorFormat(" + dp_EditorActive + ", 'fontsize', Value);this.options[0].selected = true;\">";
	html += "<option value=\"2\">文字大小</option>";
	for (var i=0;i<dpe_lang_FontSizeArray.length;i++) html += "<option value=\"" + dpe_lang_FontSizeArray[i] + "\">" + dpe_lang_FontSizeArray[i] + "号</option>";
	html += "</select>&nbsp;"
	return html;
}

var dpe_lang_TextColor = true;
var dpe_lang_ColorArray = [ '434343', 'a2a2a2', '7f7f00', 'bfbf00', '525330', '898a49', 'aea945', '407f00', '60bf00', '80ff00', '3b5738', '668f5a', '7f9757', '8a9b55', '007f40', '00bf60', '00ff80', '033d21', '438059', '7fa37c', '007f7f', '00bfbf','033d3d', '347d7e', '609a9f','00407f', '0060bf', '0080ff', '1b2c48', '385376', '57708f','00007f', '0000bf', '0000ff', '212143', '373e68', '444f75', '40007f', '6000bf', '8000ff','302449', '54466f', '655a7f',  '7f007f', 'bf00bf', 'ff00ff', '4a234a', '794a72', '936386',  '7f003f', 'bf005f', 'ff007f', '451528', '823857', 'a94a76', '441415', '82393c', 'aa4d4e', '7f3f00', 'bf5f00', 'ff7f00', '482c1b', '855a40', 'b27c51',  '800000', 'c00000', 'ff0000','000000'];

function GenerateTextColorPicker()
{
	var html = "";
	html += "&nbsp;<select onchange=\"var Value = this.options[this.selectedIndex].value;DPEEditorFormat(" + dp_EditorActive + ", 'forecolor', Value);this.options[0].selected = true;\">";
	html += "<option value='000000'>文字颜色</option>";
	for (var i=dpe_lang_ColorArray.length-1;i>=0; i--) html += "<option value=\"" + dpe_lang_ColorArray[i] + "\" style=\"color:#" + dpe_lang_ColorArray[i] + ";background:#" + dpe_lang_ColorArray[i] + ";\">#" + dpe_lang_ColorArray[i].toUpperCase() + "</option>";
	html += "</select>&nbsp;"
	return html;
}

var dpe_lang_CreateHyperlink = true;
function GenerateButtonLink(){return "<a href=\"#\" onclick=\"this.blur();DPEEditorOnCreateHyperlink(" + dp_EditorActive + ");return false;\" class=\"DP_Editor_Button\" title=\"插入链接\"><img src=\"" + dpe_lang_Default_Folder + "dp_editor_link.gif\" border=\"0\" /></a>";}

function DPEEditorOnCreateHyperlink(id)
{
	if ( ! DPEEditorValidateMode(id) ) return;
	var editor = dp_EditorMap[id];
	var theSelection = editor.GetSelection();
	var theAnchor = null;
	if ( theSelection != null )
	{
		if ( theSelection.parentElement )
		{
			var theParent = theSelection.parentElement();
			theAnchor = DPEEditorGetElement( "A", theParent );
		}
		else
		{
			theParent = theSelection.commonAncestorContainer;
			if ( theParent != null && theParent.nodeType != 3 )
			{
				var tagList = theParent.getElementsByTagName( "A" );
				if ( tagList && tagList.length > 0 )
				{
					theAnchor = tagList[0];
				}
			}
		}
	}
	var link = prompt("输入链接地址\n（如：http://www.dianping.com）:", theAnchor ? theAnchor.href : "http://");
	if (link && link != "http://") DPEEditorFormat( id, "CreateLink", link );
}

var dpe_lang_InsertImage = true;
function GenerateButtonInsertImage(){return "<a href=\"#\" onclick=\"this.blur();DPEEditorOnInsertImage(" + dp_EditorActive + ");return false;\" class=\"DP_Editor_Button\" title=\"插入图片\"><img src=\"" + dpe_lang_Default_Folder + "dp_editor_image.gif\"border=\"0\" /></a>";}
function DPEEditorOnInsertImage(id)
{
	if ( ! DPEEditorValidateMode(id)) return;
	var theImage = prompt("输入图片地址\n（如：http://www.dianping.com/Comm/Images/Logo.gif）:", "http://");
	if (!theImage || theImage == "http://") return;
	DPEEditorFormat( id, "InsertImage", theImage );
}

// insert video item
var dpe_lang_InsertVideo = false; // this have to be false @zack
function GenerateButtonInsertVideo(){return "<a href=\"#\" onclick=\"this.blur();DPEEditorOnInsertVideo(" + dp_EditorActive + ");return false;\" class=\"DP_Editor_Button\" title=\"插入视频\"><img src=\"" + dpe_lang_Default_Folder + "dp_editor_video.gif\"  alt=\"InsertVideo\"  border=\"0\" /></a>";}
function DPEEditorOnInsertVideo(id)
{
    if ( ! DPEEditorValidateMode(id)) return;
	var theVideo = prompt("部落目前支持优酷、土豆、六间房、56、Ku6、Youtube多家视频网站。\n请输入上述视频网站提供的分享html代码或flash地址\n", "");
	if (!theVideo) 
	{
	    return;
	}
	if ( ! DPEEditorValidateMode( id ))
	{
		return;
	}
	
	var src = checkDPEditorVideoCode(theVideo);
	if(src)
	{
	    var editor = dp_EditorMap[ id ];
	    editor.Focus();
	    try
	    {
		    var videop = editor.GetComposition().document.createElement("p");
		    videop.innerHTML = "[video]" + src + "[/video]";
		    editor.GetComposition().document.body.appendChild(videop);
	    }
	    catch (e)
	    {
		    alert( e.message );
	    }
	}
	else
	{
	    alert("部落目前仅支持优酷、土豆、六间房、56、Ku6、Youtube这几家视频网站\n请输入正确的分享html代码或flash地址");
	}
}

function checkDPEditorVideoCode(code)
{
    var re = new RegExp("<object[^>]*>(.*?)</object>","gi");
    var ree = new RegExp("<embed[^>]*>(.*?)</embed>","gi");
    var m = re.exec(code);
   
    if(m == null)
    {
       m = ree.exec(code);
       if(m == null)
       {
          var rehttp = new RegExp("http://(www.|player.)?(6.cn|youku.com|youtube.com|tudou.com|56.com|ku6.com)/[^.!,?;\"']+(?:[.!,?]+[^.!,?;\"']+)*","gi");
          var mrec = rehttp.exec(code);
          if(mrec == null)
          {
            return null;
          }
          else
          {
            return mrec[0];
          }  
       }
    }
    
    
    if(m.index == 0)
    {
       // check company
       var rec = new RegExp("<embed [^>]*src=\"(http://(www.|player.)?(6.cn|youku.com|youtube.com|tudou.com|56.com|ku6.com)/[^\"]*)\"[^>]*>", "gi");
       var mrec = rec.exec(code);
       if(mrec == null)
       {
          return null
       }
       return mrec[1];
    }
    return null;
}

var dpe_lang_InsertEmoticon = true;
var dpe_lang_InsertEmoticonCount = 70;
var dpe_lang_InsertEmoticonPage = [2, 2];
var dpe_lang_InsertEmoticonPageSize = [25, 10];
function GenerateEmoticonBar()
{
	var html = "";
	html += "<div class=\"DP_Editor_Emoticon_Div\" id=\"DP_Editor_Emoticon_List\">";
	html += DPEEditorEmotionsPage(1);
	html += "</div>";
	return html;
}
function DPEEditorNextEmotions(EmotionIndex)
{
	var objEmotionList = gid("DP_Editor_Emoticon_List");
	if(objEmotionList!=null)
	{
		objEmotionList.innerHTML = DPEEditorEmotionsPage(EmotionIndex);
	}
	var objIcon = gid("DP_Editor_Emoticon_Div_Right");
	if (objIcon!=null)
	{
		if (EmotionIndex==1)
		{
			objEmotionList.style.height="30px";
			objIcon.innerHTML = "<a href=\"#\" onclick=\"this.blur();DPEEditorNextEmotions(2);return false;\"><img src=\"http://static.dianping.com/comm/dp_editor/dp_editor_face_down.gif\" border=\"0\" alt=\"下一页\" /></a>";
		}
		else
		{
			objEmotionList.style.height="160px";
			objIcon.innerHTML = "<a href=\"#\" onclick=\"this.blur();DPEEditorNextEmotions(1);return false;\"><img src=\"http://static.dianping.com/comm/dp_editor/dp_editor_face_up.gif\" border=\"0\" alt=\"下一页\" /></a>";
		}
	}
}
function DPEEditorEmotionsPage(EmotionIndex)
{
	var nowPage = parseInt(EmotionIndex);
	var nextPage;
	var html = "";
	html += "<span class=\"DP_Editor_Emoticon_Div_Left\">";
	if (nowPage == 2)
	{
		nextPage = 1;
		for (var i=1; i<3; i++)
		{
			for (var j =1+(i-1)*dpe_lang_InsertEmoticonPageSize[0];j<dpe_lang_InsertEmoticonPageSize[0]+1+(i-1)*dpe_lang_InsertEmoticonPageSize[0];j++)
			{
				html +="<img src=\"" + dpe_lang_Default_Folder + "Emoticon" + j + ".gif\" class=\"DP_Editor_Emoticon\" onclick=\"DPEEditorOnInsertEmoticon(" + dp_EditorActive + ", " + j + ");\" />&nbsp;";
			}
			html += "<br />"
		}
		for (var i=1; i<3; i++)
		{
			for (var j =1+2*dpe_lang_InsertEmoticonPageSize[0]+(i-1)*dpe_lang_InsertEmoticonPageSize[1];j<dpe_lang_InsertEmoticonPageSize[1]+1+2*dpe_lang_InsertEmoticonPageSize[0]+(i-1)*dpe_lang_InsertEmoticonPageSize[1];j++)
			{
				html +="<img src=\"" + dpe_lang_Default_Folder + "Emoticon" + j + ".gif\" class=\"DP_Editor_Emoticon\" onclick=\"DPEEditorOnInsertEmoticon(" + dp_EditorActive + ", " + j + ");\" />&nbsp;";
			}
			html += "<br />"
		}
	}
	else
	{
		nextPage = 2;
		for (var j =1;j<dpe_lang_InsertEmoticonPageSize[0]+1;j++)
		{
			html +="<img src=\"" + dpe_lang_Default_Folder + "Emoticon" + j + ".gif\" class=\"DP_Editor_Emoticon\" onclick=\"DPEEditorOnInsertEmoticon(" + dp_EditorActive + ", " + j + ");\" />&nbsp;";
		}
	}
	html += "</span><span class=\"DP_Editor_Emoticon_Div_Right\" id=\"DP_Editor_Emoticon_Div_Right\"><a href=\"#\" onclick=\"this.blur();DPEEditorNextEmotions(" + nextPage + ");return false;\"><img src=\"http://static.dianping.com/comm/dp_editor/dp_editor_face_down.gif\" border=\"0\" alt=\"下一页\" /></a></span>";
	return html;
}

function DPEEditorOnInsertEmoticon(id, em)
{
	if (!DPEEditorValidateMode(id) || !em) return;
	var theImage = dpe_lang_Default_Folder + "Emoticon" + em + ".gif";
	var imgTag = '<img src="' + theImage + '" border="0" />';
	var editor = dp_EditorMap[id];
	editor.selectionRange = editor.GetSelection();
	var bodyRange = editor.selectionRange;
	if ( bodyRange.pasteHTML )
	{
		var docRange = document.selection.createRange();
		if ( docRange.boundingTop != bodyRange.boundingTop )
		{
			bodyRange.pasteHTML( imgTag );
		}
		else
		{
			editor.GetDocument().body.innerHTML += imgTag;
			editor.selectionRange.collapse( false );
			editor.selectionRange.select();
		}
	}
	else
	{
		imgTag = document.createElement( "img" );
		imgTag.src = theImage;
		bodyRange.deleteContents()
		bodyRange.collapse( true );
		bodyRange.insertNode( imgTag );
	}
	editor.Focus();
}

var dpe_lang_ViewHTML = "要使用工具条，请不要选中\“显示 HTML 代码\”。";

var DPE_EDITOR_COMPOSITION_PREFIX = "dp_EditorComposition";
var DPE_EDITOR_TOOLBAR_PREFIX = "dp_EditorToolbar";
var DPE_EDITOR_MAX_HEIGHT = 800;
var dp_EditorMap = new Object();
var dp_EditorIDGenerator = null;
var dp_EditorActive = 0;

function FunctionCall(p_oFunction, p_aArguments)
{
	this.Function = p_oFunction;
	this.Arguments = p_aArguments;
}

function DPEEditor(idGenerator)
{
	var m_oThis = this;
	this.idGenerator = idGenerator;
	this.textMode = false;
	this.backgroundColor = "";
	this.backgroundImage = "";
	this.foregroundColor = "";
	this.fontFamily = "";
	this.fontSize = "";
	this.expandPT = false;
	this.showPT = false;
	this.imageSize = 120;
	this.instantiated = false;
	this.Instantiate = DPEEditorInstantiate;
	this.SetText = DPEEditorSetText;
	this.AddText = DPEEditorAddText;
	this.GetHTML = DPEEditorGetHTML;
	this.Focus = DPEEditorFocus;
	this.GetComposition = DPEEditorGetComposition;
	this.GetDocument = DPEEditorGetDocument;
	this.GetSelection = DPEEditorGetSelection;
	this.Exec = DPEEditorExec;
	this.SetHeight = DPEEditorSetHeight;
	this.UploadImage = DPEEditorUploadImage;
	this.UploadInfoImage = DPEEditorUploadInfoImage;
	if ( document.all )
	{
		this.GetEditorFrame = DPEEditorGetFrameIE;
	}
	else
	{
		this.GetEditorFrame = DPEEditorGetFrameMoz;
	}
}

function addStyleSheet ( doc, id )
{
	if ( doc == null )
	{
		return;
	}
	if ( id != null )
	{
		removeStyleSheet ( doc, id );
	}
	var styleElt = doc.createElement( "STYLE" );
	if ( id != null )
	{
		styleElt.id = id;
	}
	doc.getElementsByTagName( "HEAD" ).item( 0 ).appendChild( styleElt );
	return doc.styleSheets[ doc.styleSheets.length-1 ];
}

function removeStyleSheet ( doc, id )
{
	var sheets = doc.getElementsByTagName("STYLE");
	var n;
	for ( var i=0, n=sheets.length; i<n; ++i )
	{
		if ( sheets[i].id == id )
		{
			sheets[i].parentNode.removeChild ( sheets[i] );
			return sheets[i];
		}
	}
	return null;
}

function addStylesheetRule ( styleSheet, name, styles )
{
	if ( styleSheet == null ) return;
	if ( typeof styleSheet.addRule != "undefined" ) styleSheet.addRule( name, styles );
	else if ( typeof styleSheet.insertRule != "undefined" ) styleSheet.insertRule( name + " { " + styles + " }", styleSheet.cssRules.length );
}

function DPEEditorGetFrameIE( id )
{
	return eval( DPE_EDITOR_COMPOSITION_PREFIX + id );
}

function DPEEditorGetFrameMoz( id )
{
	return document.getElementById( DPE_EDITOR_COMPOSITION_PREFIX + id );
}

function DPEEditorInstantiate()
{
	if (this.instantiated) return;
	this.id = this.idGenerator.GenerateID();
	dp_EditorMap[this.id] = this;
	dp_EditorIDGenerator = this.idGenerator;
	var html = "";
	html += "<table id=\"DP_Editor_Table\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"DP_Editor_Table\" nowrap>";
	html += "<tbody>";
	html += "<tr>";
	html += "<td>";
	
	html += "<table id=\"DP_Editor_TooBar_Table" + this.id + "\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"DP_Editor_TooBar_Table\">"
	html += "<tbody>";
	html += "<tr>";
	html += "<td id=\"" + DPE_EDITOR_TOOLBAR_PREFIX + this.id + "\">";
	
	html += "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">";
	html += "<tbody>";
	html += "<tr>";
	if (dpe_lang_Bold)
	{
		html += "<td>";
		html += GenerateButtonBold();
		html += "</td>";
	}	

	if (dpe_lang_CreateHyperlink)
	{
		html += "<td>";
		html += GenerateButtonLink();
		html += "</td>";
	}
	if (dpe_lang_InsertImage)
	{
		html += "<td>";
		html += GenerateButtonInsertImage();
		html += "</td>";
	}
	
	if(dpe_lang_InsertVideo)
	{
	    html += "<td>";
		html += GenerateButtonInsertVideo();
		html += "</td>";
	}
	
	if (dpe_lang_TextColor)
	{
		html += "<td>";
		html += GenerateTextColorPicker();
		html += "</td>";
	}
	if (dpe_lang_FontSize)
	{
		html += "<td>";
		html += GenerateFontSizePicker();
		html += "</td>";
	}
	html += "</tr>";
	html += "</tbody>";
	html += "</table>";
	
	html += "</td>";
	html += "</tr>";
	html += "</tbody>";
	html += "</table>"
	html += '</td>';
	html += "</tr>";
	html += "<tr>";
	html += "<td>";
	html += '<iframe id="' + DPE_EDITOR_COMPOSITION_PREFIX + this.id + '" class=\"DP_Editor_Body\" frameborder="0" src="about:blank">';
	html += '</iframe>';
	html += "</td>";
	html += "</tr>";
	html += "</tbody>";
	html += "</table>";

	if (dpe_lang_InsertEmoticon)
	{
		//html += "<tr><td>";
		html += GenerateEmoticonBar();
		//html += "</td></tr>";
	}
	document.write(html);


	html = "";
	html += '<style>.quote{	 margin-left: 40px;	 margin-right:40px;	 padding:5px;	 background-color: #F7F7F7; border:1px #AAA solid;font-size:12px;}.innerquote{	 margin-left: 5px;	 margin-right:5;	 padding:5px;	 background-color: #F7F7F7; border:1px #AAA solid;font-size:12px;}</style><body style=\"line-height:22px;font-family:' + dpe_lang_Default_Font + ';font-size:' + dpe_lang_Default_FontSize + '\" ></body>';
	if (document.all)
	{
		var theFrame = eval( DPE_EDITOR_COMPOSITION_PREFIX + this.id );
		theFrame.document.designMode = "on";
		theFrame.document.open();
		theFrame.document.write(html);
		theFrame.document.close();
		theFrame.document.body.id = this.id;
	}
	else
	{
		var theFrame = this.GetEditorFrame( this.id );
		var theDoc = theFrame.contentWindow.document;
		theDoc.body.contentEditable = 'true';
		theDoc.open();
		theDoc.write(html);
		theDoc.close();
		theDoc.body.id = this.id;
		if ( ! document.all )
		{
			theDoc.designMode = "on";
			theDoc.body.__defineGetter__( "innerText", DPEEditorGetInnerText );
			theDoc.body.__defineSetter__( "innerText", DPEEditorSetInnerText );
		}
	}
	var sheet = addStyleSheet( theFrame.document );
	addStylesheetRule ( sheet, "P", "margin:0px;" );
	dp_EditorIDGenerator = null;
	this.instantiated = true;
}

function convertTextToHTML(s)
{
    s = s.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<BR>");
    while (/\s\s/.test(s))
    {
	    s = s.replace(/\s\s/, "&nbsp;");
    }
    return s.replace(/\s/g, " ");
}

function DPEEditorSetHeight(p_sId)
{
	var sId = p_sId ? p_sId : (DPE_EDITOR_COMPOSITION_PREFIX + this.id);
	var nClientHeight = document.body.clientHeight;
	var nHeight = nClientHeight < DPE_EDITOR_MAX_HEIGHT ? nClientHeight : DPE_EDITOR_MAX_HEIGHT;
	nHeight -= 50;
	document.getElementById(sId).height = nHeight;
}

function DPEEditorGetInnerText()
{
	var r = this.ownerDocument.createRange();
	r.selectNodeContents( this );
	return r.toString();
}

function DPEEditorSetInnerText( sText )
{
	this.innerHTML = convertTextToHTML( sText );
	return sText;
}

function DPEEditorSetText(text)
{
	text = text.replace(/\n/g, "<br />");
	text = text.replace(/<div><\/div>/gi, "<br />");
	text = "<div>" + text + "</div>";
	this.GetDocument().body.innerHTML = text;
}

function DPEEditorAddText(text)
{
	text = text.replace(/\n/g, "<br />");
	text = text.replace(/<div><\/div>/gi, "<br />");
	text = "<div>" + text + "</div>";
	this.GetDocument().body.innerHTML += text;
}

function DPEEditorGetHTML()
{
	if ( this.textMode ) return this.GetText();

	if (document.all)
	{
		var source_obj = this.GetDocument().body; //html fragment ie
	}
	else
	{
		var source_obj = this.GetDocument().documentElement; //html fragment mozilla
	}

    
	var lang = "zh";
	var encoding = "utf-8";

	var xhtml_content = get_xhtml(source_obj, lang, encoding);
    
	var sMessage = xhtml_content.replace('<a','<a target="_blank"');
	if ( sMessage.toLowerCase() == "<div></div>" ) return "";
	sMessage = sMessage.replace( /<p(\s+[^>]*)>/gi, "<div$1>" );
	sMessage = sMessage.replace( /<p\s*>/gi, "<div>" );
	sMessage = sMessage.replace( /<\/p>/gi, "</div>" );
	sMessage = sMessage.replace( /\s/g, " " );
	//sMessage = sMessage.replace(/<script[\s\S]+<\/script *>/g, '', sMessage);
	//sMessage = sMessage.replace(/ href*=*[\s\S]*script/g, '', sMessage);
	//sMessage = sMessage.replace(/  on[\s\S]*=/g, '', sMessage);
	//sMessage = sMessage.replace(/<iframe[\s\S]+<\/iframe *>/g, '', sMessage);
	//sMessage = sMessage.replace(/<IFRAME[\s\S]+<\/IFRAME *>/g, '', sMessage);
	//sMessage = sMessage.replace(/<frameset[\s\S]+<\/frameset *>/g, '', sMessage);
	//sMessage = sMessage.replace(/id=/g, '', sMessage);
	//sMessage = sMessage.replace(/onclick=/g, '', sMessage);
	return sMessage;
}

function DPEEditorUploadImage(imgURL,imgThumbURL)
{
	if(imgThumbURL == undefined) imgThumbURL = imgURL;
	editor.SetText(editor.GetHTML() + "<a href=\"" + imgURL + "\" target=\"_blank\"><img src=\"" + imgThumbURL + "\" border=\"0\" /></a><br /><br />");
	editor.Focus();
}
function DPEEditorUploadInfoImage(imgURL,imgThumbURL)
{
	if(imgThumbURL == undefined) imgThumbURL = imgURL;
	editor.SetText(editor.GetHTML() + "<a href=\"" + imgURL + "\" target=\"_blank\"><img src=\"" + imgThumbURL + "\" border=\"0\" /></a><br /><a href=\"" + imgURL + "\" class=\"BL\">打印图片</a><br /><br />");
	editor.Focus();
}

function DPEEditorFocus()
{
	this.GetComposition().focus();
}

function DPEEditorValidateMode(id)
{
	var editor = dp_EditorMap[id];
	if ( ! editor.textMode )
	{
		return true;
	}
	alert( dpe_lang_ViewHTML );
	editor.Focus();
	return false;
}

function DPEEditorFormat(id, what, opt)
{
	if ( ! DPEEditorValidateMode( id ))
	{
		return;
	}
	if ( opt == "removeFormat" )
	{
		what = opt;
		opt = null;
	}
	var editor = dp_EditorMap[ id ];
	editor.Focus();
	editor.Exec( what, opt );
}

function DPEEditorGetElement(tagName, start)
{
	while (start && start.tagName != tagName)
	{
		start = start.parentNode;
	}
	return start;
}

function DPEEditorGetComposition()
{
	var theFrame = this.GetEditorFrame( this.id );
	return theFrame.contentWindow? theFrame.contentWindow : theFrame;
}

function DPEEditorGetDocument()
{
	return this.GetComposition().document;
}

function DPEEditorGetSelection()
{
	if ( window.getSelection )
	{
		var theWin = this.GetComposition();
		var theSel = theWin.getSelection();
		if ( theSel )
		{
			return theSel.getRangeAt(0);
		}
	}
	else if (document.getSelection)
	{
		var theDoc = this.GetDocument();
		return theDoc.getSelection().createRange();
	}
	else if ( document.selection && document.selection.createRange )
	{
		var theDoc = this.GetDocument();
		return theDoc.selection.createRange();
	}
	else
	{
		alert( "Selection unsupported" );
	}
	return null;
}

function DPEEditorExec(what, opt)
{
	try
	{
		this.GetComposition().document.execCommand( what, false, opt );
	}
	catch (e)
	{
		alert( e.message );
	}
}

function DPEIDGenerator(nextID)
{
	this.nextID = nextID;
	this.GenerateID = DPEIDGeneratorGenerateID;
}

function DPEIDGeneratorGenerateID()
{
	return this.nextID++;
}


//add \n before opening tag
var need_nl_before = '|div|p|table|tbody|tr|td|th|title|head|body|script|comment|li|meta|h1|h2|h3|h4|h5|h6|hr|ul|ol|option|link|';
//add \n after opening tag
var need_nl_after = '|html|head|body|p|th|style|';

var re_comment = new RegExp();
re_comment.compile("^<!--(([a]|[^a])*)-->$");

var re_hyphen = new RegExp();
re_hyphen.compile("-$");


function get_xhtml(node, lang, encoding, need_nl, inside_pre) {
var i;
var text = '';
var children = node.childNodes;
var child_length = children.length;
var tag_name;
var do_nl = need_nl?true:false;
var page_mode = true;
	for (i=0;i<child_length;i++) {
		var child = children[i];
		if (child.parentNode && String(node.tagName).toLowerCase() != String(child.parentNode.tagName).toLowerCase()) continue;
        
		switch (child.nodeType) {

			case 1: { //ELEMENT_NODE
				var tag_name = String(child.tagName).toLowerCase();
				if (tag_name == '') break;

				if (tag_name == 'meta') {
					var meta_name = String(child.name).toLowerCase();
					if (meta_name == 'generator') break;
				}
				           
                // quote fix for ie @zack 2008-5-6
                if(tag_name == 'embed' && navigator.appName == "Microsoft Internet Explorer")
                {
                    text+=fix_object_code(child.outerHTML);
                    break;
                }
               
				if (document.all && tag_name == 'object'){
					text += fix_object_code(child.outerHTML);
					continue;
				}

				if (!need_nl && tag_name == 'body') { //html fragment mode
					page_mode = false;
				}

				if (tag_name == '!') { //COMMENT_NODE in IE 5.0/5.5
					//get comment inner text
					var parts = re_comment.exec(child.text);
                    
					if (parts) {
						//the last char of the comment text must not be a hyphen
						var inner_text = parts[1];
						text += fix_comment(inner_text);
					}
				} else {
					if (tag_name == 'html'){
						text = '<?xml version="1.0" encoding="'+encoding+'"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n';
					}

					//inset \n to make code more neat
					if (need_nl_before.indexOf('|'+tag_name+'|') != -1) {
						if ((do_nl || text != '') && !inside_pre) text += '\n';
							else do_nl = true;
					}

					text += '<'+tag_name;
                    
					//add attributes
					var attr = child.attributes;
					var attr_length = attr.length;
					var attr_value;
                    
                     
                    
					var attr_lang = false;
					var attr_xml_lang = false;
					var attr_xmlns = false;

					var is_alt_attr = false;

					for (j=0;j<attr_length;j++) {
						var attr_name = attr[j].nodeName.toLowerCase();
						if (!attr[j].specified &&
							attr_name != 'selected' &&
							attr_name != 'style' &&
							attr_name != 'value') continue; //IE 5.0

						if (attr_name == 'selected' &&
							!child.selected ||
							attr_name == 'style' && //IE 5.0
							child.style.cssText == '') continue;

						if (attr_name == '_moz_dirty' ||
							attr_name == '_moz_resizing' ||
							tag_name == 'br' && attr_name == 'type' &&
							child.getAttribute('type') == '_moz') continue;

						var valid_attr = true;
                        
                       
						switch (attr_name) {
							case "style" :
								attr_value = child.style.cssText;
								break;
							case "class" :
								attr_value = child.className;
								break;
							case "http-equiv":
								attr_value = child.httpEquiv;
								break;
							case "noshade": //this set of choices will extend
							case "checked":
							case "selected":
							case "multiple":
							case "nowrap":
							case "disabled":
								attr_value = attr_name;
								break;
							default:
								try {
									attr_value = child.getAttribute(attr_name, 2);
								} catch (e) {
									valid_attr = false;
								}
						}

                       
                        
						//html tag attribs
						if (attr_name == 'lang' && tag_name == 'html') {
							attr_lang = true;
							attr_value = lang;
						}
						if (attr_name == 'xml:lang') {
							attr_xml_lang = true;
							attr_value = lang;
						}
						if (attr_name == 'xmlns') attr_xmlns = true;

						if (valid_attr) {
							//value attribute set to "0" is not handled correctly in Mozilla
							if (!(tag_name == 'li' && attr_name == 'value')) {
								text += ' '+attr_name+'="'+fix_attribute(attr_value)+'"';
							}
						}

						if (attr_name == 'alt') is_alt_attr = true;
					}

					if (tag_name == 'img' && !is_alt_attr) {
						text += ' alt=""';
					}

					if (tag_name == 'html') {
						if (!attr_lang) text += ' lang="'+lang+'"';
						if (!attr_xml_lang) text += ' xml:lang="'+lang+'"';
						if (!attr_xmlns) text += ' xmlns="http://www.w3.org/1999/xhtml"';
					}

					if (child.canHaveChildren || child.hasChildNodes()){
						text += '>';
						if (need_nl_after.indexOf('|'+tag_name+'|') != -1) {
//							text += '\n';
						}
						text += get_xhtml(child, lang, encoding, true,
					inside_pre||tag_name=='pre'?true:false);
						text += '</'+tag_name+'>';
					} else {

						if (tag_name == 'style' || tag_name == 'title' ||
							tag_name == 'script' || tag_name == 'textarea' ||
							tag_name == 'a') {

							text += '>';
							var inner_text;
							if (tag_name == 'script') {
								inner_text = child.text;
							}else inner_text = child.innerHTML;

							if (tag_name == 'style') {
								inner_text = String(inner_text).replace(/[\n]+/g,'\n');
							}

							text += inner_text+'</'+tag_name+'>';

						} else {
							text += ' />';
						}
					}

				}
				break;
			}
			case 3: { //TEXT_NODE
				if (!inside_pre) { //do not change text inside <pre> tag
					if (child.nodeValue != '\n') {
						text += fix_entities(fix_text(child.nodeValue));
					}
				} else text += child.nodeValue;
				break;
			}
			case 8: { //COMMENT_NOTE
				text += fix_comment(child.nodeValue);
				break;
			}
			default:
				break;
		}
	}

	if (!need_nl && !page_mode) { 
			text = text.replace(/<\/?head>[\n]*/gi, "");
			text = text.replace(/<head \/>[\n]*/gi, "");
			text = text.replace(/<\/?body>[\n]*/gi, "");
	}

	return text;
}

function fix_comment(text){
	text = text.replace(/--/g, "__");

	if(re_hyphen.exec(text)){
		text += " ";
	}

	return "<!--"+text+"-->";
}

function fix_text(text) {
    
	var temp_text = String(text).replace(/\&lt;/g, "#h2x_lt").replace(/\&gt;/g, "#h2x_gt");
	temp_text = temp_text.replace(/\n{2,}/g, "\n").replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\u00A0/g, "&nbsp;");
	return temp_text.replace(/#h2x_lt/g, "&lt;").replace(/#h2x_gt/g, "&gt;");
}

function fix_attribute(text) {
	var temp_text = String(text).replace(/\&lt;/g, "#h2x_lt").replace(/\&gt;/g, "#h2x_gt");
	temp_text = temp_text.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;");
	return temp_text.replace(/#h2x_lt/g, "&lt;").replace(/#h2x_gt/g, "&gt;");
}

function fix_object_code(text) {
var temp = String(text);
	temp = temp.replace(/ style=/gi, ' style=');
	temp = temp.replace(/ codeBase=/gi, ' codebase=');
	temp = temp.replace(/ height=/gi, ' height=');
	temp = temp.replace(/ width=/gi, ' width=');
	temp = temp.replace(/ align=/gi, ' align=');
	temp = temp.replace(/ classid=/gi, ' classid=');
	temp = temp.replace(/ src=/gi, ' src=');
	temp = temp.replace(/ NAME=/gi, ' name=');
	temp = temp.replace(/ VALUE=/gi, ' value=');
	temp = temp.replace(/ quality=/gi, ' quality=');
	temp = temp.replace(/ TYPE=/gi, ' type=');
	temp = temp.replace(/ PLUGINSPAGE=/gi, ' pluginspage=');
	temp = temp.replace(/<OBJECT /gi, '<object ');
	temp = temp.replace(/<\/OBJECT>/gi, '</object>');
	temp = temp.replace(/<PARAM /gi, '<param ');
	temp = temp.replace(/<\/PARAM>/gi, '</param>');
	temp = temp.replace(/<EMBED /gi, '<embed ');
	temp = temp.replace(/<\/EMBED>/gi, '</embed>');
	return temp;
}

function fix_entities(text) {
	return text;
}
 



