var wd_wyschanged_mark=false;
var wd_visedit_b_HtmlMode=0;

function wd_EditorSelected(sFldName) {
	var sFraName=sFldName+'_editor';
	var theFrame=document.frames[sFraName]; // to work with iframe 'document' object
	var theFraDoc=theFrame.document;
}

function wd_ShowDialog(sDlgType, sFldName, sButtName, iUpDir, iLtDir) {
	eval("tmr_"+sDlgType+"=window.setTimeout('document.getElementById(\\\""+sDlgType+"\\\").style.visibility=\\\"hidden\\\";document.getElementById(\\\""+sFldName+"_editor\\\").style.visibility=\\\"visible\\\";', 1000);");
	if (!(document.createAttribute)) {
		var theField=document.getElementById(sFldName+"_editor");
		if (theField) theField.style.visibility="hidden";
	}
	var theDialog=document.getElementById(sDlgType);
	var theButt=document.images[sFldName+"_"+sButtName];
	var arrButtPos=wd_AbsPos(theButt);
	var theEditorF=document.getElementById(sDlgType+'_editor');
	if (theEditorF) theEditorF.value=sFldName;
	var theActorF=document.getElementById(sDlgType+'_actor');
	if (theActorF) theActorF.value=sButtName;
	var theValueF=document.getElementById(sDlgType+'_value');
	if (theValueF) theValueF.value="";
	var theCurrF=document.getElementById(sDlgType+'_current');
	if (theCurrF) theCurrF.innerText="";
	//
	var lDlgLt=0;
	if (iLtDir) {
		lDlgLt=arrButtPos[0]+theButt.offsetWidth-theDialog.offsetWidth;
	} else {
		lDlgLt=arrButtPos[0];
	}
	if (lDlgLt<2) lDlgLt=2;
	theDialog.style.left=lDlgLt+"px";
	//
	var lDlgTp=0;
	if (iUpDir) {
		lDlgTp=arrButtPos[1]-theDialog.offsetHeight;
	} else {
		lDlgTp=arrButtPos[1]+theButt.offsetHeight;
	}
	if (lDlgTp<2) lDlgTp=2;
	theDialog.style.top=lDlgTp+"px";
	//
	theDialog.style.visibility="visible";
}

var wd_ArrTxtRngContnrs = new Array();
wd_ArrTxtRngContnrs['TD']=1; wd_ArrTxtRngContnrs['LI']=1;
wd_ArrTxtRngContnrs['OL']=1; wd_ArrTxtRngContnrs['UL']=1;
wd_ArrTxtRngContnrs['DIV']=1; wd_ArrTxtRngContnrs['A']=1;
wd_ArrTxtRngContnrs['BODY']=1; wd_ArrTxtRngContnrs['TH']=1;
wd_ArrTxtRngContnrs['FORM']=1; wd_ArrTxtRngContnrs['INPUT']=1;
wd_ArrTxtRngContnrs['P']=1; wd_ArrTxtRngContnrs['PRE']=1;
wd_ArrTxtRngContnrs['SPAN']=1;

function wd_EditCommand(sFldName, sCommand, sParam1, sParam2) {
	//alert(sFldName+"\n"+sCommand+"\n"+sParam1+"\n"+sParam2);
	var bReturnAnswer=true;
	//
	var sButtName=sCommand;
	sCommand=sCommand.toUpperCase();
	//
	var sFraName=sFldName+'_editor';
	var theTAName='pgfields['+sFldName+']';
	var theFrame=document.frames[sFraName]; // to work with iframe 'document' object
	var theTA=document.getElementById(theTAName); // textarea for nonvisual editing
	if (theFrame) {
		theFrame.focus();
		var theFraDoc=theFrame.document;
		var theSel=theFraDoc.selection;
		var sSelType=theSel.type.toUpperCase();
		var theRange=theSel.createRange();
		//
		if (sSelType=="CONTROL") {
			var theObj=theRange.item(0);
		} else {
			if (sSelType==="TEXT") {
				while ((theRange.htmlText.length>=4 && (theRange.htmlText.substr(theRange.htmlText.length-4).toUpperCase()==="<BR>")) || (theRange.htmlText.length>=5 && (theRange.htmlText.substr(theRange.htmlText.length-5).toUpperCase()==="<BR/>"))) {
					theRange.moveEnd('character', -1);
				}
				while ((theRange.htmlText.length>=4 && (theRange.htmlText.substr(0, 4).toUpperCase()==="<BR>")) || (theRange.htmlText.length>=5 && (theRange.htmlText.substr(0, 5).toUpperCase()==="<BR>"))) {
					theRange.moveStart('character', 1);
				}
				theRange.select();
			}
			var theObj=theRange.parentElement();
			var sOTag=theObj.tagName.toUpperCase();
			while (theObj.parentElement && (!wd_ArrTxtRngContnrs[sOTag])) {
				theObj=theObj.parentElement;
				sOTag=theObj.tagName.toUpperCase();
			}
			// ==== to detect multiple cells selection:

			var theStartCell=null; var theFinCell=null;
			try {
				var theStartTRange=theRange.duplicate();
				theStartTRange.collapse(true);
				var theStartObj=theStartTRange.parentElement();
				theStartObj=wd_ClimbToTag(theStartObj, "TD");
				if (theStartObj && theStartObj.tagName && theStartObj.tagName.toUpperCase()==="TD") {
					theStartCell=theStartObj;
				}
				var theFinTRange=theRange.duplicate();
				theFinTRange.collapse(false);
				var theFinObj=theFinTRange.parentElement();
				theFinObj=wd_ClimbToTag(theFinObj, "TD");
				if (theFinObj && theFinObj.tagName && theFinObj.tagName.toUpperCase()==="TD") {
					theFinCell=theFinObj;
				}
				//alert(theStartObj.outerHTML+"\n\n"+theFinObj.outerHTML);
			} catch (theError) {
				//alert(theError.description);
			}
		}
		var sTag=theObj.tagName.toUpperCase();
		var sClass=theObj.className;
		//
		var sTabTag=sTag;
		var theTabObj=theObj;
		if (!(sTabTag=="TABLE"||sTabTag=="TBODY"||sTabTag=="TR"||sTabTag=="TD"||sTabTag=="TH")) {
			while (!(sTabTag=="TABLE"||sTabTag=="TBODY"||sTabTag=="TR"||sTabTag=="TD"||sTabTag=="TH")&&theTabObj.offsetParent) {
				theTabObj=theTabObj.offsetParent;
				sTabTag=theTabObj.tagName.toUpperCase();
			}
		}
		var sTabClass=theTabObj.className;
		//
		var sDivTag=sTag;
		var theDivObj=theObj;
		if (sDivTag!="DIV") {
			while (sDivTag!="DIV" && theDivObj.parentElement) {
				theDivObj=theDivObj.parentElement;
				sDivTag=theDivObj.tagName.toUpperCase();
			}
		}
		var sDivClass=theDivObj.className;
		//
		var sAnchorTag=sTag;
		var theAnchorObj=theObj;
		if (sAnchorTag!="A") {
			while (sAnchorTag!="A" && theAnchorObj.parentElement) {
				theAnchorObj=theAnchorObj.parentElement;
				sAnchorTag=theAnchorObj.tagName.toUpperCase();
			}
		}
		var sAnchorClass=theAnchorObj.className;
		//
		var bInGlyph=(sDivTag=="DIV" && sDivClass.substr(0, 5)=="glyph");
		if (bInGlyph && !(sCommand=="ONKEYCODE" && sParam1==13)) {
			wd_wyschanged_mark=true;
			return true;
		}
		//
		var theVisButt=document.getElementById(sFldName+"_visbutt");
		var bCodeMode=true; if (theVisButt.disabled) bCodeMode=false;
		//
		//alert("sSelType="+sSelType+"\nsOTag="+sOTag+"\nsTabTag="+sTabTag+"\nsAnchorTag="+sAnchorTag);
	} else if (theTA) {
		var bCodeMode=true;
		var theRange=document.selection.createRange();
		var theParEl=theRange.parentElement();
		if (theRange && theParEl && theParEl.type=="textarea" && theParEl.id==theTAName) {
			var theSel=document.selection;
			var sSelType=theSel.type.toUpperCase();
		} else {
			theTA.focus();
			var theRange=theTA.createTextRange();
			var theSel=document.selection;
			var sSelType=theSel.type.toUpperCase();
		}
	}
	//
	switch (sCommand) {
		case "TEST":
			alert(sSelType+"\n"+theObj.tagName);
			break;
		case "ONPASTE":
			try {
				var theIFra=window.parent.document.frames['wd_visedit_paster'];
			} catch (theError) {
				alert("onpaste err1: "+theError.description);
			}
			if (theIFra) {
				try {
					var theDoc=theIFra.document;
				} catch (theError) {
					alert("onpaste err2: "+theError.description);
				}
				if (theDoc) {
					try {
						var theBody=theDoc.body;
					} catch (theError) {
						alert("onpaste err3: "+theError.description);
					}
					if (theBody) {
						try {
							theBody.innerHTML="";
							theBody.focus();
						} catch (theError) {
							alert("onpaste err4: "+theError.description);
						}
						try {
							theDoc.execCommand("PASTE");
						} catch (theError) {
							alert("onpaste err5: "+theError.description);
						}
						if (wd_visedit_b_HtmlMode) {
							try {
								var sCleaned=theBody.innerText;
								theRange.text=sCleaned;
							} catch (theError) {
								alert("onpaste err6: "+theError.description);
							}
						} else {
							try {
								var sWasted=theBody.innerHTML;
								theBody.innerHTML="";
								var theDiv=document.createElement("DIV");
								theDiv.innerHTML=sWasted;
								cleanTree(theDiv, false);
								var sCleaned=theDiv.innerHTML;
								theRange.pasteHTML(sCleaned);
								theDiv.removeNode(true);
							} catch (theError) {
								alert("onpaste err7: "+theError.description);
							}
						}
					}
				}
				// для баги с прорисовкой после вставки: //
				try {
					window.parent.opener.focus();
					window.setTimeout("document.frames['"+sFraName+"'].focus();", 200);
				} catch (theError) {
					alert("onpaste err8: "+theError.description);
				}
			}
			//
			wd_wyschanged_mark=true;
			bReturnAnswer=false;
			break;
		case "ONKEYCODE":
			/*
			для обработки нажатия клавиш (см. wd_MkViseditorsPrepareing())
			sParam1 - keyCode, sParam2 - frame event Object
			*/
			switch (sParam1) { // sParam2=event
				case 13: // ENTER
					if (sParam2.ctrlKey) {
						if (sDivTag=="DIV") {
							theRange.moveToElementText(theDivObj);
							theRange.collapse(false);
							theRange.pasteHTML("<BR>");
							theRange.collapse(false);
							theRange.select();
						}
						bReturnAnswer=false;
					} else if (sTag!="LI") {
						if (sSelType != "CONTROL") {
							theRange.collapse(true);
							if (sOTag=="PRE") {
								theRange.text="\n ";
							} else {
								theRange.pasteHTML("<BR>");
							}
							theRange.select();
						}
						bReturnAnswer=false;
					}
					break;
				case 16: // Shift
				case 17: // Ctrl
				case 18: // Alt
					bReturnAnswer=true;
					break;
				case 49: // 1 = STYLE1
				case 50: // 2 = STYLE2
				case 51: // 3 = STYLE3
					if (sParam2.ctrlKey) {
						wd_EditCommand(sFldName, "STYLE"+(sParam1-48), "", "");
						bReturnAnswer=false;
					}
					break;
				case 66: // B = Bold
				case 73: // I = Italic
				case 84: // T = Table
					if (sParam2.ctrlKey) {
						wd_EditCommand(sFldName, String.fromCharCode(sParam1), "", "");
						bReturnAnswer=false;
					}
					break;
				default:
					break;
			}
			wd_wyschanged_mark=true;
			break;
		case "BOLD":
		case "B":
			if (!bCodeMode) {
				if (sSelType=="NONE"||sSelType=="CONTROL") {
					if (theObj.style.fontWeight=="normal"||(!theObj.style.fontWeight)) {
						theObj.style.fontWeight="bold";
					} else {
						theObj.style.fontWeight="";
					}
				} else if (sSelType=="TEXT") {
					theRange.execCommand("bold");
				}
			} else {
				if (sSelType=="NONE") {
					theRange.text="<B></B>";
				} else if (sSelType=="TEXT") {
					theRange.text="<B>"+theRange.text+"</B>";
				}
			}
			break;
		case "ITALIC":
		case "I":
			if (!bCodeMode) {
				if (sSelType=="NONE"||sSelType=="CONTROL") {
					if (theObj.style.fontStyle=="normal"||(!theObj.style.fontStyle)) {
						theObj.style.fontStyle="italic";
					} else {
						theObj.style.fontStyle="";
					}
				} else if (sSelType=="TEXT") {
					theRange.execCommand("italic");
				}
			} else {
				if (sSelType=="NONE") {
					theRange.text="<I></I>";
				} else if (sSelType=="TEXT") {
					theRange.text="<I>"+theRange.text+"</I>";
				}
			}
			break;
		case "STYLE1":
		case "STYLE2":
		case "STYLE3":
			if (bCodeMode || JS_VER_MS<5.5) {
				if (sSelType=="NONE") {
					theRange.text="["+sCommand+"]"+"paragraph text"+"[/"+sCommand+"]";
				} else if (sSelType=="TEXT") {
					theRange.text="["+sCommand+"]"+theRange.text+"[/"+sCommand+"]";
				}
			} else {
				if (sDivTag=="DIV" && sDivClass.substr(0, 9)=="tpl_style") {
					var sCurrStyle=sDivClass.substr(4, 6).toUpperCase();
					//theRange.moveToElementText(theDivObj);
					if (sCurrStyle==sCommand) {
						theDivObj.outerHTML=theDivObj.innerHTML;
					} else {
						theDivObj.className="tpl_"+sCommand.toLowerCase();
					}
					//theRange.collapse(false);
					//theRange.select();
				} else {
					if (sSelType=="NONE") {
						/*
						var iMoved=1; var sCurrText="";
						while (iMoved && sCurrText!="<BR><BR>") {
							iMoved=theRange.moveEnd("character", 1);
							sCurrText=theRange.htmlText;
							if (sCurrText.length) {
								sCurrText=sCurrText.substr(sCurrText.length-8);
							}
						}
						var iMoved=1; var sCurrText="";
						while (iMoved && sCurrText!="<BR><BR>") {
							iMoved=theRange.moveStart("character", -1);
							sCurrText=theRange.htmlText;
							if (sCurrText.length) sCurrText=sCurrText.substr(0, 8);
						}
						var sCurrText=theRange.htmlText;
						if (theRange.text.length && sCurrText.substr(0, 8)=="<BR><BR>" && sCurrText.substr(sCurrText.length-8)=="<BR><BR>") {
							sCurrText=sCurrText.substr(8);
							sCurrText=sCurrText.substr(0, sCurrText.length-8);
							alert(sCurrText);
							theRange.pasteHTML("<DIV CLASS=\"tpl_"+sCommand.toLowerCase()+"\">"+sCurrText+"</DIV>");
						}
						*/
						theRange.pasteHTML("<DIV CLASS=\"tpl_"+sCommand.toLowerCase()+"\">"+"paragraph text"+"</DIV>");
					} else if (sSelType=="TEXT") {
						var theDuplRange=theRange.duplicate();
						theDuplRange.moveEnd("character", 1);
						var theRgHtml=theDuplRange.htmlText;
						if (theRgHtml.substr(theRgHtml.length-4)=="<BR>") theRange=theDuplRange;
						theRange.pasteHTML("<DIV CLASS=\"tpl_"+sCommand.toLowerCase()+"\" ID=\"wd_tmpid\">"+theRange.htmlText+"</DIV>");
						var theDiv=theFraDoc.getElementById("wd_tmpid");
						if (theDiv) {
							if (theDiv.childNodes.length && wd_IsEl(theDiv.childNodes[theDiv.childNodes.length-1], "BR")) theDiv.childNodes[theDiv.childNodes.length-1].removeNode(true);
							theDiv.removeAttribute('id', true);
						}
					}
				}
			}
			break;
		case "FCOLOR":
			if (sParam1=="-") {
				wd_ShowDialog('wd_dlg_palette', sFldName, sButtName);
			} else {
				var sColor=sParam1;
				if (bCodeMode) {
					if (JS_VER_MS<5.5&&arrPaletteCodes[sColor]) sColor=arrPaletteCodes[sColor];
					if (sSelType!="CONTROL") theRange.text="color:"+sColor+";";
				} else {
					if (arrPaletteCodes[sColor]) sColor=arrPaletteCodes[sColor];
					if (sSelType=="TEXT") {
						theRange.execCommand("ForeColor", false, sColor);
					} else {
						theObj.style.color=sColor;
					}
				}
			}
			break;
		case "BCOLOR":
			if (sParam1=="-") {
				wd_ShowDialog('wd_dlg_palette', sFldName, sButtName);
			} else {
				var sColor=sParam1;
				if (bCodeMode) {
					if (JS_VER_MS<5.5 && arrPaletteCodes[sColor]) sColor=arrPaletteCodes[sColor];
					if (sSelType!="CONTROL") theRange.text="background-color:"+sColor+";";
				} else {
					if (arrPaletteCodes[sColor]) sColor=arrPaletteCodes[sColor];
					if (sSelType=="TEXT") {
						theRange.execCommand("BackColor", false, sColor);
					} else {
						theObj.style.backgroundColor=sColor;
					}
				}
			}
			break;
		case "FFAM":
			if (sParam1=="-") {
				wd_ShowDialog('wd_dlg_ffamily', sFldName, sButtName);
			} else {
				var sFFam=sParam1;
				if (bCodeMode) {
					if (sSelType!="CONTROL") theRange.text="font-family:"+sFFam+";";
				} else {
					if (sSelType=="TEXT") {
						theRange.execCommand("FontName", false, sFFam);
					} else {
						theObj.style.fontFamily=sFFam;
					}
				}
			}
			break;
		case "FSIZE":
			if (sParam1=="-") {
				wd_ShowDialog('wd_dlg_fsize', sFldName, sButtName);
			} else {
				var sFSize=sParam1;
				if (bCodeMode) {
					if (sSelType!="CONTROL") theRange.text="font-size:"+sFSize+";";
				} else {
					if (sSelType=="TEXT") {
						if (theObj.innerText==theRange.text) {
							theObj.style.fontSize=sFSize;
						} else {
							theRange.pasteHTML("<SPAN STYLE=\"font-size:"+sFSize+";\">"+theRange.htmlText+"</SPAN>");
						}
					} else {
						theObj.style.fontSize=sFSize;
					}
				}
			}
			break;
		case "OL":
			if ((!bCodeMode)&&sSelType!="CONTROL") {
				var theCurrText=theRange.htmlText;
				theCurrText=theCurrText.replace(/<BR>/gi, "</LI><LI>");
				theCurrText="<OL><LI>"+theCurrText+"</LI></OL>";
				theRange.pasteHTML(theCurrText);
			} else if (sSelType!="CONTROL") {
				if (sSelType=="NONE") {
					theRange.text="\r\n<OL>\r\n<LI>\r\n</OL>\r\n";
				} else if (sSelType=="TEXT") {
					theRange.text="\r\n<OL>\r\n<LI>"+theRange.text+"\r\n</OL>\r\n";
				}
			}
			break;
		case "UL":
			if ((!bCodeMode)&&sSelType!="CONTROL") {
				var theCurrText=theRange.htmlText;
				theCurrText=theCurrText.replace(/<BR>/gi, "</LI><LI>");
				theCurrText="<UL><LI>"+theCurrText+"</LI></UL>";
				theRange.pasteHTML(theCurrText);
			} else if (sSelType!="CONTROL") {
				if (sSelType=="NONE") {
					theRange.text="\r\n<UL>\r\n<LI>\r\n</UL>\r\n";
				} else if (sSelType=="TEXT") {
					theRange.text="\r\n<UL>\r\n<LI>"+theRange.text+"\r\n</UL>\r\n";
				}
			}
			break;
		case "ALLEFT":
			if (!bCodeMode) {
				if (sSelType=="CONTROL") {
					switch (sTag) {
						case "IMG":
							theObj.align="left";
							break;
						case "TABLE":
							theObj.align="";
							theObj.style.styleFloat="none";
							break;
						default:
							theRange.execCommand("JustifyLeft");
							break;
					}
				} else {
					switch (sTag) {
						case "P":
						case "DIV":
							theObj.align="left";
							break;
						case "TD":
						case "TH":
							theObj.style.textAlign="left";
							break;
						default:
							theRange.execCommand("JustifyLeft");
							break;
					}
				}
			} else if (sSelType!="CONTROL") {
				theRange.text="text-align:left;";
			}
			break;
		case "ALCENT":
			if (!bCodeMode) {
				if (sSelType=="CONTROL") {
					switch (sTag) {
						case "IMG":
							theObj.align="middle";
							break;
						case "TABLE":
							theObj.align="center";
							theObj.style.styleFloat="none";
							break;
						default:
							theRange.execCommand("JustifyCenter");
							break;
					}
				} else {
					switch (sTag) {
						case "P":
						case "DIV":
							theObj.align="center";
							break;
						case "TD":
						case "TH":
							theObj.style.textAlign="center";
							break;
						default:
							theRange.execCommand("JustifyLeft");
							break;
					}
				}
			} else if (sSelType!="CONTROL") {
				theRange.text="text-align:center;";
			}
			break;
		case "ALRIGHT":
			if (!bCodeMode) {
				if (sSelType=="CONTROL") {
					switch (sTag) {
						case "IMG":
							theObj.align="right";
							break;
						case "TABLE":
							theObj.align="right";
							theObj.style.styleFloat="none";
							break;
						default:
							theRange.execCommand("JustifyRight");
							break;
					}
				} else {
					switch (sTag) {
						case "P":
						case "DIV":
							theObj.align="right";
							break;
						case "TD":
						case "TH":
							theObj.style.textAlign="right";
							break;
						default:
							theRange.execCommand("JustifyRight");
							break;
					}
				}
			} else if (sSelType!="CONTROL") {
				theRange.text="text-align:right;";
			}
			break;
		//
		case "TABLE":
		case "T":
			if ((!bCodeMode)&&sSelType!="CONTROL") {
				theRange.collapse(false);
				theRange.pasteHTML("<TABLE WIDTH=\"100%\" CELLSPACING=\""+(typeof(iWDTblCellspacing)=="undefined"?"0":iWDTblCellspacing)+"\" BORDER=\""+(typeof(iWDTblOpts3D)=="undefined"?"0":iWDTblOpts3D)+"\" CLASS=\"WDTBL\"><THEAD><TR><TH CLASS=\"WDTH\">A</TH><TH CLASS=\"WDTH\">B</TH><TH CLASS=\"WDTH\">C</TH><TH CLASS=\"WDTH\">D</TH></TR></THEAD><TBODY><TR><TD CLASS=\"WDTD\">A1</TD><TD CLASS=\"WDTD\">B1</TD><TD CLASS=\"WDTD\">C1</TD><TD CLASS=\"WDTD\">D1</TD></TR><TR><TD CLASS=\"WDTD\">A2</TD><TD CLASS=\"WDTD\">B2</TD><TD CLASS=\"WDTD\">C2</TD><TD CLASS=\"WDTD\">D2</TD></TR><TR><TD CLASS=\"WDTD\">A3</TD><TD CLASS=\"WDTD\">B3</TD><TD CLASS=\"WDTD\">C3</TD><TD CLASS=\"WDTD\">D3</TD></TR></TBODY></TABLE>");
			} else if (bCodeMode && sSelType!="CONTROL") {
				theRange.text="[TABLE\r\n|| a || b || c || d ||\r\n| a1 | b1 | c1 | d1 |\r\n| a2 | b2 | c2 | d2 |\r\n]\r\n"+theRange.text;
				/*if (sSelType=="NONE") {
					theRange.text="\r\n<TABLE CLASS=\"WDTBL\">\r\n<TR>\r\n<TD CLASS=\"WDTD\"></TD>\r\n</TR>\r\n</TABLE>\r\n";
				} else if (sSelType=="TEXT") {
					theRange.text="\r\n<TABLE CLASS=\"WDTBL\">\r\n<TR>\r\n<TD CLASS=\"WDTD\">"+theRange.text+"</TD>\r\n</TR>\r\n</TABLE>\r\n";
				}*/
			}
			break;
		case "COL":
			if ((!bCodeMode)&&(sTabTag=="TABLE"||sTabTag=="TBODY"||sTabTag=="TR"||sTabTag=="TD"||sTabTag=="TH")) {
				var iIndex=-1;
				var theTable=theTabObj;
				var iI=0;
				var theTable=theTabObj;
				if (sTabTag=="TD"||sTabTag=="TH") {
					iIndex=theTabObj.cellIndex;
					var theTR=theTabObj.parentElement;
					var theTmp=theTR.parentElement;
					while (theTmp&&theTmp.tagName&&theTmp.tagName.toUpperCase()!="TABLE") {
						theTmp=theTmp.parentElement;
					}
					theTable=theTmp;
				} else if (sTabTag=="TR") {
					var theTmp=theTR.parentElement;
					while (theTmp&&theTmp.tagName&&theTmp.tagName.toUpperCase()!="TABLE") {
						theTmp=theTmp.parentElement;
					}
					theTable=theTmp;
				}
				for (iI=0; iI<theTable.rows.length; iI++) {
					var theNextTD=theTable.rows[iI].insertCell(iIndex);
					var iSampleIndex=0; if (iIndex==0) iSampleIndex=1;
					theNextTD.className=theTable.rows[iI].cells[iSampleIndex].className;
				}
			} else if (bCodeMode && sSelType!="CONTROL") {
				if (sSelType=="NONE") {
					theRange.text="<TD CLASS=\"WDTD\"></TD>";
				} else if (sSelType=="TEXT") {
					theRange.text="<TD CLASS=\"WDTD\">"+theRange.text+"</TD>";
				}
			}
			break;
		case "DELCOL":
			if ((!bCodeMode)&&(sTabTag=="TABLE"||sTabTag=="TBODY"||sTabTag=="TR"||sTabTag=="TD"||sTabTag=="TH")) {
				var iIndex=-1;
				var theTable=theTabObj;
				var iI=0;
				var theTable=theTabObj;
				if (sTabTag=="TD"||sTabTag=="TH") {
					iIndex=theTabObj.cellIndex;
					var theTR=theTabObj.parentElement;
					var theTmp=theTR.parentElement;
					while (theTmp&&theTmp.tagName&&theTmp.tagName.toUpperCase()!="TABLE") {
						theTmp=theTmp.parentElement;
					}
					theTable=theTmp;
				}
				for (iI=0; iI<theTable.rows.length; iI++) theTable.rows[iI].deleteCell(iIndex);
			}
			break;
		case "ROW":
			if ((!bCodeMode)&&(sTabTag=="TABLE"||sTabTag=="TBODY"||sTabTag=="TR"||sTabTag=="TD"||sTabTag=="TH")) {
				var iIndex=-1;
				var theTable=theTabObj;
				var iI=0;
				if (sTabTag=="TD"||sTabTag=="TH"||sTabTag=="TR") {
					if (sTabTag=="TD"||sTabTag=="TH") {
						var theTR=theTabObj.parentElement;
					} else {
						var theTR=theTabObj;
					}
					iIndex=theTR.rowIndex;
					var theTmp=theTR.parentElement;
					while (theTmp&&theTmp.tagName&&theTmp.tagName.toUpperCase()!="TABLE") {
						theTmp=theTmp.parentElement;
					}
					theTable=theTmp;
				} else {
					var theTR=theTable.rows[theTable.rows.length-1];
				}
				var iCells=theTable.rows[0].cells.length;
				var theNewTR=theTable.insertRow(iIndex);
				var iSampleIndex=0; if (iIndex==0) iSampleIndex=1;
				var sClass=theTR.cells[0].className;
				for (iI=0; iI<iCells; iI++) {
					var theNextTD=theNewTR.insertCell();
					theNextTD.className=sClass;
				}
			} else if (bCodeMode && sSelType!="CONTROL") {
				if (sSelType=="NONE") {
					theRange.text="\r\n<TR>\r\n<TD CLASS=\"WDTD\"></TD>\r\n</TR>\r\n";
				} else if (sSelType=="TEXT") {
					theRange.text="\r\n<TR>\r\n<TD CLASS=\"WDTD\">"+theRange.text+"</TD>\r\n</TR>\r\n";
				}
			}
			break;
		case "DELROW":
			if ((!bCodeMode)&&(sTabTag=="TABLE"||sTabTag=="TBODY"||sTabTag=="TR"||sTabTag=="TD"||sTabTag=="TH")) {
				var iIndex=-1;
				var theTable=theTabObj;
				if (sTabTag=="TD"||sTabTag=="TH"||sTabTag=="TR") {
					if (sTabTag=="TD"||sTabTag=="TH") {
						var theTR=theTabObj.parentElement;
					} else {
						var theTR=theTabObj;
					}
					iIndex=theTR.rowIndex;
					var theTmp=theTR.parentElement;
					while (theTmp&&theTmp.tagName&&theTmp.tagName.toUpperCase()!="TABLE") {
						theTmp=theTmp.parentElement;
					}
					theTable=theTmp;
				}
				theTable.deleteRow(iIndex);
			}
			break;
		//
		case "LINK":
			try {
			if (sSelType!="CONTROL" || sTag=="IMG") {
				if (sParam1=="-") {
					var bFirstParam=true; if (sParam2.indexOf("?")!=-1) bFirstParam=false;
					var sStartMark="?"; if (!bFirstParam) sStartMark="&";
					var sLText=""; if (sSelType=="TEXT") sLText=theRange.text;
					var arrPreParams=new Array();
					arrPreParams[0]=''; // text
					arrPreParams[1]=''; // href
					arrPreParams[2]=''; // target
					arrPreParams[3]=''; // onclick
					if (sAnchorTag=="A") {
						sLText=theAnchorObj.innerText;
						var sOnclick=theAnchorObj.onclick;
						var sPreHref=theAnchorObj.href;
						if (sPreHref.indexOf("#")!=-1) {
							sPreHref="";
							if (sOnclick.length) {
								var iLocStart1=sOnclick.indexOf(".open(");
								var iLocStart2=sOnclick.indexOf(".href=");
								if (iLocStart1!=-1) {
									sPreHref=sOnclick.substr(iLocStart1+".open(".length);
								} else if (iLocStart2!=-1) {
									sPreHref=sOnclick.substr(iLocStart2+".href=".length);
								}
								if (sPreHref.substr(0,1)=="\"" || sPreHref.substr(0,1)=="'") {
									sPreHref=sPreHref.substr(1);
								}
								sPreHref=sPreHref.replace(/\'|\"/ig, "'");
								var arrPreHref=sPreHref.split("'");
								sPreHref=arrPreHref[0];
							}
						}
						arrPreParams[1]=sPreHref;
						arrPreParams[2]=theAnchorObj.target;
						arrPreParams[3]=sOnclick;
					}
					arrPreParams[0]=sLText;
					var sUserInput=amg_ModalDialog(sParam2+sStartMark+"field="+sFldName+"&actor="+sButtName, 360, 580, arrPreParams, 0);
					//
					if (sUserInput) {
						var arrParams=sUserInput;//.split("+++");
						sParam1=arrParams[0];
						sParam2=arrParams[1];
						sParam3=arrParams[2];
						//
						if (sParam1.length) {
							var sLinkURL=sParam1;
							var sLinkText=sParam3;
							if (!sLinkText.length) sLinkText=sLinkURL;
							//if (sSelType=="TEXT") sLinkText=theRange.text;
							sLinkText=sLinkText.replace(/[\(\)\[\]]/gi, "/");
							var iParam2=parseInt(sParam2);
							var bJSLink=(iParam2&1);
							var bNewWin=(iParam2&2);
							if (bCodeMode) {
								var sToPaste=sLinkURL;
								if (sLinkURL!=sLinkText) sToPaste+=(" "+sLinkText);
								var bExtLink=(sLinkURL.substr(0,7).toUpperCase()=="HTTP://"||sLinkURL.substr(0,4).toUpperCase()=="WWW.");
								if ((bNewWin&&(!bExtLink))||(bExtLink&&(!bNewWin))) sToPaste+=" 1";
								if (bJSLink) {
									sToPaste="["+sToPaste+"]";
								} else {
									sToPaste="("+sToPaste+")";
								}
								if (bCodeMode) {
									theRange.text=sToPaste;
								} else {
									theRange.pasteHTML(sToPaste);
								}
							} else {
								var sHref=""; var sTarget=""; var sOnClick=""; var sText="";
								//
								sText=sLinkText;
								if (bJSLink) {
									sHref="#"+sText.replace(/\"/ig, "&quot;");
									if (bNewWin) {
										sOnClick="window.open('"+sLinkURL+"'); return false;";
										sTarget="";
									} else {
										sOnClick="document.location.href='"+sLinkURL+"'; return false;";
										sTarget="";
									}
								} else {
									sHref=sLinkURL;
									if (bNewWin) {
										sOnClick="";
										sTarget="_blank";
									} else {
										sOnClick="";
										sTarget="";
									}
								}
								if (sAnchorTag=="A") {
									theAnchorObj.href=sHref
									theAnchorObj.target=sTarget
									theAnchorObj.onclick=sOnClick
									theAnchorObj.title=sText.replace(/\"/ig, "&quot;");
									if (sTag!="IMG") theAnchorObj.innerText=sText;
								} else {
									var sToPaste="<A HREF=\""+sHref+"\" TARGET=\""+sTarget+"\" ONCLICK=\""+sOnClick+"\" TITLE=\""+sText.replace(/\"/ig, "&quot;")+"\">"+sText+"</A>";
									if (bCodeMode) {
										theRange.text=sToPaste;
									} else {
										if (sTag=="IMG") {
											var theAnchor=theFraDoc.createElement("A");
											theAnchor.href=sHref;
											theAnchor.target=sTarget;
											theAnchor.onclick=sOnClick;
											theAnchor.title=sText.replace(/\"/ig, "&quot;");
											theAnchor.innerHTML=theObj.outerHTML;
											theFraDoc.body.replaceChild(theAnchor, theObj);
										} else {
											theRange.pasteHTML(sToPaste);
										}
									}
								}
							}
						}
					}
				} else {
					if (sParam1.length) {
						var sLinkURL=sParam1;
						var sLinkText=sLinkURL;
						if (sSelType=="TEXT") sLinkText=theRange.text;
						var iParam2=parseInt(sParam2);
						var bJSLink=(iParam2&1);
						var bNewWin=(iParam2&2);
						var sToPaste=sLinkURL;
						if (sLinkURL!=sLinkText) sToPaste+=(" "+sLinkText);
						var bExtLink=(sLinkURL.substr(0,7).toUpperCase()=="HTTP://"||sLinkURL.substr(0,4).toUpperCase()=="WWW.");
						if ((bNewWin&&(!bExtLink))||(bExtLink&&(!bNewWin))) sToPaste+=" 1";
						if (bJSLink) {
							sToPaste="["+sToPaste+"]";
						} else {
							sToPaste="("+sToPaste+")";
						}
						if (bCodeMode) {
							theRange.text=sToPaste;
						} else {
							theRange.pasteHTML(sToPaste);
						}
					}
				}
			}
			} catch (theError) {
				//alert("theError: "+theError.description);
			}
			break;
		case "MDLMACROS":
			//alert(sParam2);
			var sToPaste='['+sParam2.toUpperCase()+']';
			if (bCodeMode) {
				theRange.text=sToPaste;
			} else {
				sToPaste="<DIV CLASS=\"glyph_mcrs\">"+sToPaste+"</DIV><BR>&nbsp;";
				theRange.pasteHTML(sToPaste);
			}
			break;
		case "MDLSELITEM":
		case "MDLSELFOLDER":
			if (sParam1=="-") {
				var iTreeType=0;
				if (sCommand==="MDLSELFOLDER") iTreeType=1;
				var arrParam2=sParam2.split("::");
				if (arrParam2.length>1) {
					var arrPreParams=new Array();
					arrPreParams[0]=arrParam2[1];
					var sUserInput=amg_ModalDialog("/webdirector/shell/setmainitem.php"+"?treetype="+iTreeType+"&mdl="+arrParam2[0]+"&field="+sFldName+"&actor="+sButtName, 360, 520, arrPreParams, 0);
					if (sUserInput) {
						if (sSelType=="TEXT") theRange.collapse(true);
						var sToPaste="["+arrParam2[1].toUpperCase()+" "+sUserInput+"]";
						if (!bCodeMode) sToPaste="<DIV CLASS=\"glyph_mcrs\" STYLE=\"background-image:url(/webdirector/"+arrParam2[0]+"/images/mcrs_"+arrParam2[1]+".gif);\">"+sToPaste+"</DIV><BR>&nbsp;";
						if (bCodeMode) {
							theRange.text=sToPaste;
						} else {
							theRange.pasteHTML(sToPaste);
						}
					}
				}
			} else {
				void(0);
			}
			break;
		case "CHILDREN":
			if (sSelType!="CONTROL") {
				if (sParam1=="-") {
					var bFirstParam=true; if (sParam2.indexOf("?")!=-1) bFirstParam=false;
					var sStartMark="?"; if (!bFirstParam) sStartMark="&";
					var sUserInput=amg_ModalDialog(sParam2+sStartMark+"field="+sFldName+"&actor="+sButtName, 360, 560, "wd_cataloger", -96);
					//
					if (sUserInput) {
						var arrParams=sUserInput.split("+++");
						sParam1=arrParams[0];
						sParam2=arrParams[1];
						//
						if (sParam1.length) {
							var arrParam1=sParam1.split("%%%");
							var arrParam2=sParam2.split("/");
							var sColumnSID=arrParam1[0];
							var sTplSID=arrParam1[1];
							var sCurrSID=arrParam1[2];
							var iNeedReverse=parseInt(arrParam2[0]);
							var iNeedLimit=parseInt(arrParam2[1]);
							var iQuantLimit=parseInt(arrParam2[2]);
							if (!iQuantLimit) iQuantLimit=0;
							var sToPaste="[CATALOG";
							if (sColumnSID.length) {
								if (sColumnSID!=sCurrSID||sTplSID.length||(iNeedLimit&&iQuantLimit)||iNeedReverse) {
									sToPaste+=(" "+sColumnSID);
									if (sTplSID.length&&(sTplSID!=sCurrSID||(iNeedLimit&&iQuantLimit)||iNeedReverse)) {
										sToPaste+=(" "+sTplSID);
										if ((iNeedLimit&&iQuantLimit)||iNeedReverse) sToPaste+=(" "+iQuantLimit);
										if (iNeedReverse) sToPaste+=" reverse";
									}
								}
							}
							sToPaste+="]";
							if (sToPaste=="[CATALOG "+sCurrSID+"]") sToPaste="[CATALOG]";
							//
							if (sSelType=="TEXT") theRange.collapse(true);
							if (bCodeMode) {
								theRange.text=sToPaste;
							} else {
								sToPaste="<DIV CLASS=\"glyph_ctlg\">"+sToPaste+"</DIV><BR>&nbsp;";
								theRange.pasteHTML(sToPaste);
							}
						}
					}
				} else {
					if (sParam1.length) {
						var arrParam1=sParam1.split("%%%");
						var arrParam2=sParam2.split("/");
						var sColumnSID=arrParam1[0];
						var sTplSID=arrParam1[1];
						var sCurrSID=arrParam1[2];
						var iNeedReverse=parseInt(arrParam2[0]);
						var iNeedLimit=parseInt(arrParam2[1]);
						var iQuantLimit=parseInt(arrParam2[2]);
						if (!iQuantLimit) iQuantLimit=0;
						var sToPaste="[CATALOG";
						if (sColumnSID.length) {
							if (sColumnSID!=sCurrSID||sTplSID.length||iNeedLimit||iNeedReverse) {
								sToPaste+=(" "+sColumnSID);
								if (sTplSID.length&&(sTplSID!=sCurrSID||iNeedLimit||iNeedReverse)) {
									sToPaste+=(" "+sTplSID);
									if (iNeedLimit||iNeedReverse) sToPaste+=(" "+iQuantLimit);
									if (iNeedReverse) sToPaste+=" reverse";
								}
							}
						}
						sToPaste+="]";
						//
						if (sSelType=="TEXT") theRange.collapse(true);
						if (!bCodeMode) sToPaste="<DIV CLASS=\"glyph_ctlg\">"+sToPaste+"</DIV><BR>&nbsp;";
						if (bCodeMode) {
							theRange.text=sToPaste;
						} else {
							theRange.pasteHTML(sToPaste);
						}
					}
				}
			}
			break;
		case "FORMA":
			if (sSelType=="NONE"||sSelType=="TEXT") {
				var sCaption="Form Caption";
				if (sSelType=="TEXT") sCaption=theRange.text;
				var sText="[FORM\n";
				sText+="email=email@example.com\n";
				sText+="subject="+sCaption+"\n";
				sText+="caption="+sCaption+"\n";
				sText+="submit=Submit form\n";
				sText+="====\n";
				sText+="separator=Section 1\n";
				sText+="string=String Field\n";
				sText+="text=Text Field\n";
				sText+="separator=Section 2\n";
				sText+="select=Select One=a+b+c+d\n";
				sText+="]\n";
				if (bCodeMode) {
					theRange.text=sText;
				} else {
					//sText=sText.replace(/\n/ig, "<BR>");
					sText="<DIV CLASS=\"glyph_form\"><PRE>"+sText+"</PRE></DIV><BR>&nbsp;";
					theRange.pasteHTML(sText);
				}
				
			}
			break;
		case "CODE":
			if (sSelType=="NONE"||sSelType=="TEXT") {
				if (bCodeMode) {
					theRange.text="<?\n"+theRange.text+"\n?>";
				} else {
					theRange.pasteHTML("<BR>&nbsp;<DIV CLASS=\"glyph_code\"><PRE>&lt;?\n"+theRange.htmlText+"\n?&gt;</PRE></DIV><BR>&nbsp;");
				}
			}
			break;
		case "REDIRECT":
			if (sSelType!="CONTROL") {
				if (sParam1=="-") {
					var bFirstParam=true; if (sParam2.indexOf("?")!=-1) bFirstParam=false;
					var sStartMark="?"; if (!bFirstParam) sStartMark="&";
					var sUserInput=amg_ModalDialog(sParam2+sStartMark+"field="+sFldName+"&actor="+sButtName, 320, 530, "wd_redirector");
					//
					if (sUserInput) {
						sParam1=sUserInput;
						if (sParam1.length) {
							if (sSelType=="TEXT") theRange.collapse(true);
							var sToPaste="[REDIRECT "+sParam1+"]";
							if (!bCodeMode) sToPaste="<DIV CLASS=\"glyph_rdrt\">"+sToPaste+"</DIV><BR>&nbsp;";
							if (bCodeMode) {
								theRange.text=sToPaste;
							} else {
								theRange.pasteHTML(sToPaste);
							}
						}
					}
				} else {
					if (sParam1.length) {
						if (sSelType=="TEXT") theRange.collapse(true);
						var sToPaste="[REDIRECT "+sParam1+"]";
						if (!bCodeMode) sToPaste="<DIV CLASS=\"glyph_rdrt\">"+sToPaste+"</DIV><BR>&nbsp;";
						if (bCodeMode) {
							theRange.text=sToPaste;
						} else {
							theRange.pasteHTML(sToPaste);
						}
					}
				}
			}
			break;
		case "IMG":
			if (sSelType!="CONTROL" || sTag=="IMG") {
				if (sParam1=="-") {
					var bFirstParam=true; if (sParam2.indexOf("?")!=-1) bFirstParam=false;
					var sStartMark="?"; if (!bFirstParam) sStartMark="&";
					amg_ModalWin(sParam2+sStartMark+"field="+sFldName+"&actor="+sButtName+"&bmode="+bCodeMode, 480, 600, "wd_imgsettor", 0, 1);
				} else {
					if (sParam1.length) {
						var arrParam1=sParam1.split("%%%");
						var arrParam2=sParam2.split("/");
						var sImgName=arrParam1[0];
						var sImgAlt=arrParam1[1];
						var sImgAlign=arrParam2[0];
						var sImgHSpace=arrParam2[1];
						var sImgVSpace=arrParam2[2];
						if (sSelType=="TEXT") theRange.collapse(true);
						if (sImgName.length) {
							if (bCodeMode) {
								arrImgName=sImgName.split("/");
								if (arrImgName.length>0) sImgName=arrImgName[arrImgName.length-1];
								var sToPaste="("+sImgName;
								if (sImgAlt.length) {
									//sImgAlt=sImgAlt.replace(/,|\(|\)\[\]/ig, "_");
									sToPaste+=(", "+sImgAlt);
								} else if (sImgAlign!="0"||sImgHSpace!="-1"||sImgVSpace!="-1") {
									sToPaste+=(", ");
								}
								if (sImgAlign!="0") {
									switch (sImgAlign) {
										case "1":
											sToPaste+=(", left");
											break;
										case "2": 
											sToPaste+=(", right");
											break;
										default:
											break;
									}
								} else if (sImgHSpace!="-1"||sImgVSpace!="-1") {
									sToPaste+=(", ");
								}
								if (sImgHSpace!="-1") {
									sToPaste+=(", "+sImgHSpace);
								} else if (sImgVSpace!="-1") {
									sToPaste+=(", ");
								}
								if (sImgVSpace!="-1") sToPaste+=(", "+sImgVSpace);
								//
								sToPaste+=")";
							} else {
								var sToPaste="";
								//if (sImgAlt.length) sImgAlt=sImgAlt.replace(/,|\(|\)\[\]/ig, "_");
								switch (sImgAlign) {
									case "1":
										var sAlignment=" ALIGN=\"left\"";
										break;
									case "2":
										var sAlignment=" ALIGN=\"right\"";
										break;
									default:
										var sAlignment="";
										break;
								}
								var sHSpacer="";
								if (sImgHSpace!="-1") sHSpacer=" HSPACE=\""+sImgHSpace+"\"";
								var sVSpacer="";
								if (sImgVSpace!="-1") sVSpacer=" VSPACE=\""+sImgVSpace+"\"";
								//
								sToPaste="<IMG SRC=\""+sImgName+"\" ALT=\""+sImgAlt+"\" BORDER=\"0\""+sAlignment+""+sHSpacer+""+sVSpacer+">";
							}
							//
							if (bCodeMode) {
								theRange.text=sToPaste;
							} else {
								if (sTag=="IMG") {
									theObj.src=sImgName;
									theObj.alt=sImgAlt;
									switch (sImgAlign) {
										case "1":
											theObj.align="left";
											break;
										case "2":
											theObj.align="right";
											break;
										default:
											theObj.align="";
											break;
									}
									if (sImgHSpace!="-1") {
										theObj.hspace=sImgHSpace;
									} else {
										theObj.hspace=0;
									}
									if (sImgVSpace!="-1") {
										theObj.vspace=sImgVSpace;
									} else {
										theObj.vspace=0;
									}
								} else {
									var boo=theRange.pasteHTML(sToPaste);
								}
							}
						}
					}
				}
			}
			break;
		case "BGIMG":
			if (true || sSelType=="NONE" || sTag=="TABLE") {
				if (sParam1=="-") {
					var bFirstParam=true; if (sParam2.indexOf("?")!=-1) bFirstParam=false;
					var sStartMark="?"; if (!bFirstParam) sStartMark="&";
					amg_ModalWin(sParam2+sStartMark+"field="+sFldName+"&actor="+sButtName+"&bmode="+bCodeMode, 480, 600, "wd_imgsettor", 0, 1);
				} else {
					if (sParam1.length) {
						var arrParam1=sParam1.split("%%%");
						var arrParam2=sParam2.split("/");
						var sImgName=arrParam1[0];
						var sImgAlt=arrParam1[1];
						var sBgPositionX=arrParam2[0];
						switch (sBgPositionX) {
							case '2':
								sBgPositionX="right";
								break;
							case '1':
								sBgPositionX="center";
								break;
							case '0':
							default:
								sBgPositionX="left";
								break;
						}
						var sBgPositionY=arrParam2[1];
						switch (sBgPositionY) {
							case '2':
								sBgPositionY="bottom";
								break;
							case '1':
								sBgPositionY="center";
								break;
							case '0':
							default:
								sBgPositionY="top";
								break;
						}
						var sBgRepeat=arrParam2[2];
						switch (sBgRepeat) {
							case '3':
								sBgRepeat="repeat-y";
								break;
							case '2':
								sBgRepeat="repeat-x";
								break;
							case '1':
								sBgRepeat="no-repeat";
								break;
							case '0':
							default:
								sBgRepeat="repeat";
								break;
						}
						if (sSelType=="TEXT") theRange.collapse(true);
						if (sImgName.length) {
							if (bCodeMode) {
								//theRange.text=sToPaste;
							} else {
								theObj.style.backgroundImage="url("+sImgName+")";
								theObj.style.backgroundRepeat=sBgRepeat;
								theObj.style.backgroundPositionY=sBgPositionY;
								theObj.style.backgroundPositionX=sBgPositionX;
							}
						} else {
							theObj.style.backgroundImage="none";
						}
					}
				}
			}
			break;
		case "DOC":
			if (sSelType!="CONTROL") {
				if (sParam1=="-") {
					var sText=""; if (sSelType=="TEXT") sText=theRange.text;
					sText=sText.replace(/,|\(|\)\[\]/ig, "_");
					sText=sText.replace(/\r\n/ig, "");
					sText=sText.replace(/\"/ig, "&quot;");
					var arrText=sText.split("<");
					sText=arrText[0];
					//sText=escape(sText);
					//sText="";
					var bFirstParam=true; if (sParam2.indexOf("?")!=-1) bFirstParam=false;
					var sStartMark="?"; if (!bFirstParam) sStartMark="&";
					amg_ModalWin(sParam2+sStartMark+"field="+sFldName+"&actor="+sButtName+"&lnktext="+sText, 480, 600, "wd_docsettor", 0, 1);
				} else {
					if (sParam1.length) {
						var arrParam1=sParam1.split("%%%");
						var sImgName=arrParam1[0];
						var sImgAlt=arrParam1[1];
						if (sSelType=="TEXT") theRange.collapse(true);
						if (sImgName.length) {
							if (bCodeMode) {
								var sToPaste="("+sImgName;
								if (sImgAlt.length) {
									//sImgAlt=sImgAlt.replace(/,|\(|\)\[\]/ig, "_");
									sImgAlt=sImgAlt.replace(/\r\n/ig, "");
									sImgAlt=sImgAlt.replace(/\"/ig, "&quot;");
									sToPaste+=(", "+sImgAlt);
								}
								sToPaste+=")";
							} else {
								//sImgAlt=sImgAlt.replace(/,|\(|\)\[\]/ig, "_");
								sImgAlt=sImgAlt.replace(/\r\n/ig, "");
								sImgAlt=sImgAlt.replace(/\"/ig, "&quot;");
								sToPaste="<A HREF=\""+sImgName+"\" ALT=\""+sImgAlt+"\">"+sImgAlt+"</A>";
							}
							//
							if (bCodeMode) {
								theRange.text=sToPaste;
							} else {
								theRange.pasteHTML(sToPaste);
							}
						}
					}
				}
			}
			break;
		case "COLOR":
			if (sSelType!="CONTROL") {
				if (sParam1=="-") {
					wd_ShowDialog('wd_dlg_palette', sFldName, sButtName, 1, 1);
				} else {
					var sColor=sParam1;
					if ((!bCodeMode)||JS_VER_MS<5.5) {
						if (arrPaletteCodes[sColor]) sColor=arrPaletteCodes[sColor];
					}
					theRange.pasteHTML(sColor);
				}
			}
			break;
		//
		default:
			break;
	}
	// == <P>&nbsp;</P> :
	//if (theFrame && theFrame.document && theFrame.document.body && !theFrame.document.body.innerText.length) {
	//	theFrame.document.body.innerHTML="";
	//}
	//if (sCommand==="ONKEYCODE" && (sParam1===8 || sParam1===46) && theFrame && theFrame.document && theFrame.document.body && theFrame.document.body.innerText.length===1) {
	//	theFrame.document.body.innerHTML="";
	//}
	if (theFrame && theFrame.document && theFrame.document.body && theFrame.document.body.innerHTML==="<P>&nbsp;</P>") {
		theFrame.document.body.innerHTML="";
	}
	// ==
	if (typeof(wd_wyschanged_mark)!="undefined" && !wd_wyschanged_mark) {
		wd_wyschanged_mark=bReturnAnswer;
	}
	return bReturnAnswer;
}
		//
		/*function wd_ValEditors(sFormName) {
			var theForm=document.forms[sFormName];
			var iI=0;
			for (iI=0; iI<document.frames.length; iI++) {
				var theFrame=document.frames[iI]; // to work with iframe 'document' object
				var sID=theFrame.name;
				if (sID.length) {
					var theFra=eval("document.all."+sID); // to work with 'iframe' object
					var sIDTail=sID.substr(sID.length-7, 7);
					if (sIDTail=="_editor") {
						var sIDBase=sID.substr(0, sID.length-7);
						if (theForm.elements['pgfields['+sIDBase+']']) {
							var theVisButt=document.getElementById(sIDBase+"_visbutt");
							var bCodeMode=true; if (theVisButt.disabled) bCodeMode=false;
							if (bCodeMode) {
								theForm.elements['pgfields['+sIDBase+']'].value=theFrame.document.body.innerText;
							} else {
								theForm.elements['pgfields['+sIDBase+']'].value=wd_VisToWik(theFrame.document.body.innerHTML);
							}
						}
					}
				}
			}
			//
			return true;
		}*/
//==============================================================================
clean_a=true;
clean_img=true;
clean_colors=false;
clean_aligns=false;

function cleanTree(theDomObj, bNeedClean) {
	var theChildren=theDomObj.children;
	var i=0;
	if (theChildren) {
		for(i=theChildren.length-1; i>=0; i--) cleanTree(theChildren[i], true);
	}
	if(bNeedClean) cleanObject(theDomObj);
}
function cleanObject(o) {
	var s="";
	var myAttributes=[];
	var i;
	
	if (o.outerHTML.substr(0,2)=="<?") {
		o.removeNode(false);
		//o.parentNode.replaceChild(o.firstChild, o)
		return;
	}
	var tag=o.tagName.toLowerCase();

	// удаляем плохие, заказные и пустые теги //
	if(!goodTags[tag] || (clean_a && tag=="a") || (clean_img && tag=="img") || (o.canHaveHTML && o.innerHTML=="" && !canEmptyTags[tag])){
		try{
			o.removeNode(false);
		//	o.parentNode.replaceChild(o.firstChild, o)
		}catch(e){}

		return;
	}

	var a=o.attributes;
	if(!a) return;

	for(i in a){ // хм...
		if(""+a[i]!="null"){ // странно, но просто if(a[i]) не прокатывает //
			myAttributes[i]=a[i];
		}
	}
	// киляем плохие атрибуты и плохие классы //
	for(i in myAttributes){
		//i=i.toLowerCase()
		if( 
			(
				!goodAttributes[""][i] &&
				(
					!goodAttributes[tag] || !goodAttributes[tag][i] || i=="class" || i=="className"
				)
			)
			||
			(
				clean_colors &&
				(
					i=="bgColor" || i=="color"
				)
			)
			||
			(
				clean_aligns &&
				(
					i=="align" || i=="vAlign"
				)
			)
		){
			
			if(i=="class"){
				i="className";
			}
			if(i!="className" || !goodClasses[o.className]){
				o.removeAttribute(i);
			}
		}	
	}
	// в 6-ом MSIE не киляем непонятных атрибутов у таблиц. см. выше. //
	if(o.tagName.toLowerCase()!="table"){
		for(i in mustDieAttributes){
			o.removeAttribute(mustDieAttributes[i]);
		}
	}
	o.style.cssText="";
	try {
		var sOTag=o.tagName.toUpperCase();
		switch (sOTag) {
			case "TABLE":
				o.width="100%";
				o.cellSpacing=(typeof(iWDTblCellspacing)=="undefined"?"0":iWDTblCellspacing);
				o.border=(typeof(iWDTblOpts3D)=="undefined"?"0":iWDTblOpts3D);
				o.className="WDTBL";
				break;
			case "TH":
				o.className="WDTH";
				break;
			case "TD":
				o.className="WDTD";
				break;
			default:
				break;
		}
	} catch (theError) {
		//alert("err1:\n"+sOTag+"\n"+theError.description);
	}
	try {
//
		if ((sOTag=="A" || sOTag=="ACRONYM" || sOTag=="ADDRESS" || sOTag=="B" || sOTag=="BDO" || sOTag=="BIG" || sOTag=="BLOCKQUOTE" || sOTag=="BODY" || sOTag=="BUTTON" || sOTag=="CAPTION" || sOTag=="CENTER" || sOTag=="CITE" || sOTag=="CODE" || sOTag=="COL" || sOTag=="COLGROUP" || sOTag=="CUSTOM" || sOTag=="DD" || sOTag=="DEL" || sOTag=="DFN" || sOTag=="DIR" || sOTag=="DIV" || sOTag=="DL" || sOTag=="DT" || sOTag=="EM" || sOTag=="FIELDSET" || sOTag=="FONT" || sOTag=="FORM" || sOTag=="FRAMESET" || sOTag=="HN" || sOTag=="HTML" || sOTag=="I" || sOTag=="INS" || sOTag=="KBD" || sOTag=="LABEL" || sOTag=="LEGEND" || sOTag=="LI" || sOTag=="LISTING" || sOTag=="MAP" || sOTag=="MARQUEE" || sOTag=="MENU" || sOTag=="NOBR" || sOTag=="OL" || sOTag=="OPTION" || sOTag=="P" || sOTag=="PRE" || sOTag=="Q" || sOTag=="RT" || sOTag=="RUBY" || sOTag=="S" || sOTag=="SAMP" || sOTag=="SCRIPT" || sOTag=="SELECT" || sOTag=="SMALL" || sOTag=="SPAN" || sOTag=="STRIKE" || sOTag=="STRONG" || sOTag=="STYLE" || sOTag=="SUB" || sOTag=="SUP" || sOTag=="TABLE" || sOTag=="TBODY" || sOTag=="TD" || sOTag=="TFOOT" || sOTag=="TH" || sOTag=="THEAD" || sOTag=="TITLE" || sOTag=="TR" || sOTag=="TT" || sOTag=="U" || sOTag=="UL" || sOTag=="VAR")&&(sOTag!="COL" && sOTag!="COLGROUP" && sOTag!="FRAMESET" && sOTag!="HTML" && sOTag!="STYLE" && sOTag!="TABLE" && sOTag!="TBODY" && sOTag!="TFOOT" && sOTag!="THEAD" && sOTag!="TITLE" && sOTag!="TR")) {
			var sHtml=o.innerHTML;
			sHtml=sHtml.replace(/<P\/?>/ig, "<BR><BR>");
			sHtml=sHtml.replace(/<\/P>/ig, "");
			o.innerHTML=sHtml;
		}
	} catch (theError) {
		//alert("err2:\n"+sOTag+"\n"+theError.description);
	}
}

// хорошие теги
goodTags0=["a","p","br","strong","b","em","i","tt","code","pre","ul","ol","li","img","table","tbody","thead","tfoot","caption","tr","td","th","col","colgroup","h1","h2","h3","h4","h5","h6","small","big","sub","sup","div"]

// теги, которые canHaveHTML() и могут быть пустыми. //
canEmptyTags0=["td","th"]

goodAttributes0=[]
// хорошие атрибуты (допустимы у всех тегов) //
goodAttributes0[""] = ["href", "target", "name", "title", "alt", "src", "id", "bgColor", "color"]

// дополнительные допустимые атрибуты для отдельных тегов //
goodAttributes0["img"] = ["width", "height", "border", "align"]
goodAttributes0["table"] = ["cellSpacing", "cellPadding", "border", "width %"] // width % - на будущее - сделаю, чтоб только процентные меры принимать, остальные посылать... //
goodAttributes0["td"] = ["colSpan", "rowSpan"]
goodAttributes0["tr td col colgroup"] = ["noWrap", "align", "vAlign", "width %"]
goodAttributes0["a area"] = ["href", "name"]
goodAttributes0["br"] = ["clear"]

// однозначно убиваемые псевдо-атрибуты (отсутствуют в коллекции attributes)
mustDieAttributes=["x:str","x:num","x:fmla"] // внимание - в 6-ом MSIE убийство несуществующих атрибутов у тега TABLE ведет к краху браузера //

// хорошие классы (не убиваем)
goodClasses0=["important","noindent","note","h1","h2","h3","h4","h5","h6"]

goodTags=[]
for(i in goodTags0){
	goodTags[goodTags0[i]]=true
}
canEmptyTags=[]
for(i in canEmptyTags0){
	canEmptyTags[canEmptyTags0[i]]=true
}

goodAttributes=[]
for(i in goodAttributes0){
	var splitted=i.split(" ")
	for(ii in splitted){
		if(!goodAttributes[splitted[ii]]) goodAttributes[splitted[ii]]=[]		
		for(j in goodAttributes0[i]){
			goodAttributes[splitted[ii]][goodAttributes0[i][j]]=true
		}		
	}
}

goodClasses=[]
for(i in goodClasses0){
	goodClasses[goodClasses0[i]]=true
}