var SEMI_COLON=";";
var MACRO_NAME_ID=0;
var MACRO_DISPLAY_NAME_ID=1;
var m_blnSaving = false;
var m_blnDataChanged = false;
var m_blnEditorLoadedAPI = false;
var MCR_FLD="MqField:";
var MCR_FLD_ENCODED_TAG_START = "&lt;MqField";
var MCR_FLD_ENCODED_TAG_END = "&gt;";
var MCR_FLD_TAG_START = "<MqField";
var MCR_FLD_TAG_END = ">";
var QS_TYPE="Type";

var BODY_MODE_HTML=1;
var BODY_MODE_PLAIN_TEXT=0;

var m_intSetHTMLEditorMethodRetries = 0;

function GetCurrentCtrlObject(strCtrlID){
	var objCtrl;
	if(strCtrlID == "" || strCtrlID == null){
		if(m_blnEditorLoadedAPI){
			objCtrl = m_objEmailEditor.GetBody();
		}
	}else{
		objCtrl = document.getElementById(strCtrlID);
	}
	return objCtrl;
}

function LoadAvailableMacros(strCtrlID)
{
	m_strCurrentCtrlID = strCtrlID;
	var objFrameContainer;
	var objFrameMain;
	
	if(window.frames){
		objFrameContainer=window.frames["fraEmailTabs"];
		if(objFrameContainer){
			objFrameMain=objFrameContainer.window.frames["Main"];
		}
	}else{
		if(window.frames){
			objFrameContainer=window.frames["fraEmailTabs"];
			if(objFrameContainer){
				objFrameMain=objFrameContainer.window.frames["Main"];
			}
		}
	}

	if(objFrameMain){
		var objAvailableMacros=objFrameMain.document.getElementById("AvailableMacros");
				
		if(objAvailableMacros){
			objAvailableMacros.innerHTML=GetMacrosForField(strCtrlID);
		}
	}
}

function WindowClosing()
{
	if(m_blnDataChanged && !m_blnSaving){
		return MSG_NAVIGATE_AWAY;
	}
}
 
function DataChanged()
{
	m_blnDataChanged = true;
}

function GetMacrosForField(strCtrlID)
{
	var strReturn=NO_MACROS;
	var objCtrl = GetCurrentCtrlObject(strCtrlID);
	if(objCtrl){
		var lngFieldID=objCtrl.getAttribute("MqFieldID");
		var arrMacros;
		var arrMacro;
		var lngCount;
		var strButton;
		var strMacroName;
		var strMacroDisplayName;
		var lngMacroType=g_MqRef.MqStr.GetQueryStringValue(location.search,QS_MACRO_TYPE)
		
		if(m_arrAvailableMacros[lngFieldID]){
			arrMacros=m_arrAvailableMacros[lngFieldID];
			strReturn="<table>";
			
			if((lngFieldID==parseInt(FLD_SUBJECT_ID) || lngFieldID==parseInt(FLD_BODY_ID))&&(lngMacroType & MACRO_TYPE_ISSUE)==MACRO_TYPE_ISSUE){
				strButton = m_objMqButton.GetButtonHTML("MacroBullet", "m_objRef.InsertFieldMacro();", "MacroBullet", false, m_objMqButton.STATE_1,"");
				strReturn+="<tr><td width='24'>" + strButton + "<\/td>";
				strReturn+="<td><a href='#' onclick='m_objRef.InsertFieldMacro();' class='LinkList'>" + g_MqRef.MqStr.MqHtmlEncode("Field Value") + "</a><\/td><\/tr>";
			}
			
			if(lngFieldID==parseInt(FLD_BODY_ID)){
				strButton = m_objMqButton.GetButtonHTML("MacroBullet", "m_objRef.InsertLinkToIssueMacro();", "MacroBullet", false, m_objMqButton.STATE_1,"");
				strReturn+="<tr><td width='24'>" + strButton + "<\/td>";
				strReturn+="<td><a href='#' onclick='m_objRef.InsertLinkToIssueMacro();' class='LinkList'>" + g_MqRef.MqStr.MqHtmlEncode("Link To Issue") + "</a><\/td><\/tr>";
			}
			
			for(lngCount=0; lngCount<arrMacros.length; lngCount++){
				arrMacro=arrMacros[lngCount].split(SEMI_COLON);
				strMacroName=arrMacro[MACRO_NAME_ID];
				strMacroDisplayName=arrMacro[MACRO_DISPLAY_NAME_ID];
				
				if(strMacroDisplayName.length==0){
					strMacroDisplayName=strMacroName;
				}
				strButton = m_objMqButton.GetButtonHTML("MacroBullet", "m_objRef.InsertMacro('" + strMacroName + "');", "MacroBullet", false, m_objMqButton.STATE_1,"");
				strReturn+="<tr><td width='24'>" + strButton + "<\/td>";
				strReturn+="<td><a href='#' onclick='m_objRef.InsertMacro(\"" + strMacroName + "\");' class='LinkList'>" + g_MqRef.MqStr.MqHtmlEncode(strMacroDisplayName) + "</a><\/td><\/tr>";
			}
			strReturn+="<\/table>";
		}		
	}
	return strReturn;
}
		
function InsertMacro(strMacro)
{
	var bFldMacro=true;
	var blnAbort = false;
	
	var objCurrentCtrl = GetCurrentCtrlObject(m_strCurrentCtrlID);
		
	if(objCurrentCtrl){
		var lngFieldID=objCurrentCtrl.getAttribute("MqFieldID");
		if(lngFieldID == parseInt(FLD_BODY_ID)){
				if(!HTMLEditorIsEligibleForInsert(MSG_HTML_EDITOR_MODE_CONFLICT_MACRO)){
					blnAbort = true;
				}
		}
		
		var lngFieldID=objCurrentCtrl.getAttribute("MqFieldID");
		
		if(!blnAbort){
			if (strMacro.indexOf(MCR_FLD)==-1){
				bFldMacro=false;
			}

			if ((m_lngMode & MODE_HIDE_SEND_EMAIL_BUTTON)!=MODE_HIDE_SEND_EMAIL_BUTTON){
				strMacro=ResolveMacros(strMacro, lngFieldID);
			}else{
				//template mode
				var lngHTMLBody = GetHTMLBodyMode();
				if(objCurrentCtrl.getAttribute("MqFieldID") == FLD_BODY_ID && lngHTMLBody == BODY_MODE_HTML){
					strMacro=g_MqRef.MqStr.MqHtmlEncode(strMacro, false);
				}
			}
			var strFunc=objCurrentCtrl.getAttribute("MqInsertFunc");
	
			if (!strMacro && bFldMacro){
				alert(MSG_EMPTY_VAL);
			}
			if(!strFunc){
				strFunc="InsertAtCursor";
			}
		
			eval(strFunc + "(objCurrentCtrl, strMacro);");
		}
	}
}

function ResolveMacros(strStringWithMacros, lngFieldID)
{
	var strReturn=strStringWithMacros;
	
	if(m_objHTTPRequest){
		var strIssueID = g_MqRef.MqStr.GetQueryStringValue(location.search, "IssueID");
	
		var lngHTMLBody = GetHTMLBodyMode();

		var co=m_objHTTPRequest.Get(m_strCurrentLocation + "WCMqEmailEditor.ASP?WCI=wciResolveMacros&str=" + g_MqRef.MqStr.MqEncodeURIComponent(strStringWithMacros) + "&Fld=" + lngFieldID + "&CIssueID=" + strIssueID + "&HTMLBody=" + lngHTMLBody);

		if (co!=m_objHTTPRequest.CANCEL_PROCESS){
															
			var objResponse=m_objHTTPRequest.Response(co);
			if (objResponse){
				if (objResponse.HasErrors()){
					objResponse.ProcessErrors("",true);
				}else{
					strReturn=co;
				}
			}
		}
	}
	return strReturn;
}

function InsertFieldMacro()
{
	var blnAbort = false;
	
	if(!HTMLEditorIsEligibleForInsert(MSG_HTML_EDITOR_MODE_CONFLICT_MACRO)){
		blnAbort = true;
	}

	if(!blnAbort){
		OpenChildWindow("WCMqEmailEditor.ASP?WCI=wciFieldValueMacroTmpl", "InsertFieldVal", "toolbar=no,directories=no,resizable=yes,scrollbars=auto,width=300,height=150", true, 300, 150);
	}
}

function InsertLinkToIssueMacro()
{
	var blnAbort = false;

	if(!HTMLEditorIsEligibleForInsert(MSG_HTML_EDITOR_MODE_CONFLICT_MACRO)){
		blnAbort = true;
	}
	
	if(!blnAbort){
		var strIssueID = g_MqRef.MqStr.GetQueryStringValue(location.search, "IssueID");
	
		OpenChildWindow("TmplCreateLinkToIssue.htm?IssueID=" + strIssueID, "LinkToIssue", "toolbar=no,directories=no,resizable=yes,scrollbars=auto,width=500,height=325", true, 500, 325);
	}
}

function LoadAvailableTemplates()
{
	if(m_objHTTPRequest){
		var objFrameContainer=window.frames["fraEmailTabs"];
		if(objFrameContainer){
			var objFrameMain=objFrameContainer.window.frames["Main"];
			if(objFrameMain){
				var objTemplateLst=objFrameMain.document.getElementById("lstTemplates");
						
				if(objTemplateLst){
					var co=m_objHTTPRequest.Get(m_strCurrentLocation + "WCMqEmailEditor.ASP?WCI=wciGetTmplList");

					if (co!=m_objHTTPRequest.CANCEL_PROCESS){
														
						var objResponse=m_objHTTPRequest.Response(co);
						if (objResponse){
							if (objResponse.HasErrors()){
								objResponse.ProcessErrors("",true);
							}else{
								var strAvailableTemplates=co;
								var arrAvailableTemplates=new Array();
								if(strAvailableTemplates.length>0){
									var arrTemp=g_MqRef.MqStr.MqDecodeURIComponent(strAvailableTemplates).split(";");
									for(var lngCount=0; lngCount<arrTemp.length; lngCount++){
										arrAvailableTemplates[lngCount]=g_MqRef.MqStr.MqDecodeURIComponent(arrTemp[lngCount]).split(",");								
									}
								}
								m_objFormElement.SetPossibleValues(arrAvailableTemplates, false,objTemplateLst);
							}
						}
					}					
				}
			}
		}
	}else{
		window.setTimeout("LoadAvailableTemplates()", 100);
	}
}

function Form_OnLoad()
{
	SetModeDisplay();

	if(m_objRef){
		m_objHTTPRequest=m_objRef.objRequest;
	
		if(!m_objHTTPRequest){
			m_objHTTPRequest=m_objRef.m_objHTTPRequest;
		}
		if(!m_objHTTPRequest){
			m_objHTTPRequest=m_objRef.m_objRequest;
		}
		if(!m_objHTTPRequest){
			if(m_objRef.m_objRef){
				if(m_objRef.m_objRef.m_objRef){
					m_objHTTPRequest=m_objRef.m_objRef.m_objRef.mobjHTTPrequest;
				}
			}	
		}
		if(!m_objHTTPRequest){
			if(m_objRef.parent){
				m_objHTTPRequest=m_objRef.parent.objRequest;
			}	
		}
		if(!m_objHTTPRequest){
			if(m_objRef.m_objRef){
				m_objHTTPRequest=m_objRef.m_objRef.m_objHTTPrequest;
			}
		}
		if(!m_blnHasFeatureFromEnabled){
			var lngType=g_MqRef.MqStr.GetQueryStringValue(location.search, QS_TYPE);
			var MAIL_EDITOR_TYPE_VIEWS=3;
			if(lngType==MAIL_EDITOR_TYPE_VIEWS){
				var objElement=document.getElementById("trMailFrom");
				if (objElement){
					objElement.style.display="none";
				}
			}
		}
	}
	
	m_objHiddenUploadPath=document.getElementById("txtUploadPath");
	
	var strTitle=g_MqRef.MqStr.GetQueryStringValue(location.search,"Title");
	if(strTitle!=""){
		document.title=strTitle;
	}
	
	StartEditor();
	
	FillCurrentContent_OnLoad(m_strXMLMailContentFields);
	
	SetHiddenAttachFields("txtUploadDir", m_strMailAttachID);
	
	HandleSendIndiv();

	SetFocusInCtrl();

	g_MqRef.ResMgr.ProcessAll(document);
}

function SetEmailBody()
{
		if(m_arrMailContentValues){
			SetEditorContents(m_arrMailContentValues[FLD_BODY_ID]);
		}else{
			SetEditorContents("");
		}
}


function SetFocusInCtrl()
{
	var objCtrl;
	var objSelectedCtrl;
	var objRow;
	
	objSelectedCtrl=document.getElementById("txtMailTo");
	if(objSelectedCtrl){
		objRow=document.getElementById("trMailTo");
		if (objRow){
			if(objRow.style.display!="none"){
				objCtrl=objSelectedCtrl;
			}
		}
	}
	
	if(!objCtrl){
		objSelectedCtrl=document.getElementById("txtMailTemplateName");
		if(objSelectedCtrl){
			objRow=document.getElementById("trMailTmplName");
			if (objRow){
				if(objRow.style.display!="none"){
					objCtrl=objSelectedCtrl;
				}
			}
		}
	}
	
	if(objCtrl){
		objCtrl.focus();
		StoreCursor(objCtrl);
	}
}

function DoApplyTemplate(lngID)
{			
	var strDelim="|";
	var lngHTMLBody = GetHTMLBodyMode();
	var strIssueID = g_MqRef.MqStr.GetQueryStringValue(location.search, "IssueID");
	var blnAbort = false;
	
	if(lngID!=INVALID_TMPL_ID){
		if(m_objHTTPRequest){
			if(lngHTMLBody == BODY_MODE_HTML){
				if(!HTMLEditorIsEligibleForInsert(MSG_HTML_EDITOR_MODE_CONFLICT_TEMPLATE)){
					blnAbort = true;
				}
			}
			
			if(!blnAbort){
				var strAttachPath="";
				var strAttachFolder=GetHiddenAttachFields("txtUploadDir");
				if(strAttachFolder){
					strAttachPath=g_MqRef.MqStr.MqEncodeURIComponent(GetAttachPath());
				}
				var co=m_objHTTPRequest.Get(m_strCurrentLocation + "WCMqEmailEditor.ASP?WCI=wciApplyTemplate" 
								+ "&TmplID=" + lngID + "&Delim=" + strDelim + "&HTMLBody=" + lngHTMLBody + "&AP=" + strAttachPath
								+ "&CIssueID=" + strIssueID);
				if (co!=m_objHTTPRequest.CANCEL_PROCESS){
															
					var objResponse=m_objHTTPRequest.Response(co);
					if (objResponse){
						if (objResponse.HasErrors()){
							objResponse.ProcessErrors("",true);
						}else{

							var arrResult=co.split(strDelim);
							
							var strSrc=arrResult[0];
							var strValue;
							var strTemplateValue;
							var objCtrl;
							
							objCtrl=document.getElementById("txtMailSubject");
							if(objCtrl){
								strValue=objCtrl.value;
								strTemplateValue=g_MqRef.MqStr.PropStringDecode(g_MqRef.MqStr.GetQueryStringValue(strSrc,FLD_SUBJECT_ID,true));
								if(strValue.length>0 && strTemplateValue.length>0){
									strValue+=" ";
								}
								objCtrl.value=strValue+strTemplateValue;	
							}
									
							objCtrl=document.getElementById(FLD_BODY_CONTROL_NAME);
							if(objCtrl){
								strValue=objCtrl.value;
								strTemplateValue= g_MqRef.MqStr.PropStringDecode(g_MqRef.MqStr.GetQueryStringValue(strSrc,FLD_BODY_ID,true));
								lngTemplateBodyType = g_MqRef.MqStr.PropStringDecode(g_MqRef.MqStr.GetQueryStringValue(strSrc,FLD_HTML_BODY_ID,true));
								if(lngHTMLBody == BODY_MODE_HTML &&  lngTemplateBodyType == BODY_FORMAT_TYPE_TEXT){// if checkbox is set to HTML, and we are expecting a plain text body.
									strTemplateValue = PrepareBodyTextForHTMLEditor(strTemplateValue, true);
								}
								if(strValue.length>=0 && strTemplateValue.length>0){
									if(lngHTMLBody == BODY_MODE_HTML){
										strTemplateValue+="<br /><br />";
										m_objEmailEditor.InsertHTML(strTemplateValue);
										
									}else{
										strTemplateValue+="\r\n\r\n";
										
										var objCurrentCtrl=GetCurrentCtrlObject(m_strCurrentCtrlID);
										var blnSwitchFocus=false;
										var objCurPos;
										if(objCurrentCtrl){
											if(objCurrentCtrl.id!=objCtrl.id){
												if(objCurrentCtrl.CursorPos){
													objCurPos=objCurrentCtrl.CursorPos;
												}
												objCtrl.focus();
												StoreCursor(objCtrl);
												blnSwitchFocus=true;
											}
										}
										InsertAtCursor(objCtrl, strTemplateValue);
										
										if(blnSwitchFocus){
											objCurPos.select();
										}
									}
								}
							}
									
							objCtrl=document.getElementById("txtMailAttach");
							if(objCtrl){
								strValue=objCtrl.value;
								strTemplateValue=g_MqRef.MqStr.MqDecodeURIComponent(g_MqRef.MqStr.GetQueryStringValue(strSrc,FLD_ATTACH_ID,false));
								if(strValue.length>0 && strTemplateValue.length>0){
									strValue+=";";
								}
								objCtrl.value=strValue+strTemplateValue;	
							}
							if(arrResult.length>0){
								var objUploadDirFld = document.getElementById("txtUploadDir");
								if(objUploadDirFld){
									if(objUploadDirFld.value == ""){
										SetHiddenAttachFields("txtUploadDir", arrResult[1]);
									}
								}
							}
						}
					}
				}
			}
		}
	}
}

function SetModeDisplay()
{
	var objElement;

	objElement=document.getElementById("divLoading");

	if (objElement){
		objElement.style.display="none";
	}

	objElement=document.getElementById("tdBtnCancel");
	if (objElement){
		objElement.style.display="";
	}
	
	if ((m_lngMode & MODE_HIDE_TEMPLATES_TAB)!= MODE_HIDE_TEMPLATES_TAB ||
		(m_lngMode & MODE_HIDE_MACROS_TAB)!= MODE_HIDE_MACROS_TAB){
		objElement=document.getElementById("tdSidebar");
		if (objElement){
			objElement.style.display="";
		}
	}else{
		//Make use of the sidebar space.
		var objMainTable = document.getElementById("tdMainContents");
		var objMailWrapper = document.getElementById("mailWrapper");
		if (objMainTable){
			objMainTable.style.width="95%";
			objMainTable.style.height="82%";
		}
		if (objMailWrapper) {
			objMailWrapper.style.marginRight="20px";
		}
		var objSidebar = document.getElementById("tdSidebar");
		if (objSidebar){
			objSidebar.style.display="none";
		}
	}
	
	if ((m_lngMode & MODE_HIDE_TMPL_NAME_FIELD)!=MODE_HIDE_TMPL_NAME_FIELD){
		objElement=document.getElementById("trMailTmplName");
		if (objElement){
			objElement.style.display="";
		}
	}

	if ((m_lngMode & MODE_HIDE_TO_FIELD)!=MODE_HIDE_TO_FIELD){
		objElement=document.getElementById("trMailTo");
		if (objElement){
			objElement.style.display="";
		}
	}

	if ((m_lngMode & MODE_HIDE_CC_FIELD)!=MODE_HIDE_CC_FIELD){
		objElement=document.getElementById("trMailCc");
		if (objElement){
			objElement.style.display="";
		}
		objElement=document.getElementById("trMailBCc");
		if (objElement){
			objElement.style.display="";
		}
	}
	
	if ((m_lngMode & MODE_HIDE_FROM_FIELD)!=MODE_HIDE_FROM_FIELD){
		objElement=document.getElementById("trMailFrom");
		if (objElement){
			objElement.style.display="";
		}
	}
	
	if ((m_lngMode & MODE_HIDE_SUBJECT_FIELD)!=MODE_HIDE_SUBJECT_FIELD){
		objElement=document.getElementById("trMailSubject");
		if (objElement){
			objElement.style.display="";
		}
	}

	if ((m_lngMode & MODE_HIDE_ATTACH_FIELD)!=MODE_HIDE_ATTACH_FIELD){
		objElement=document.getElementById("trMailAttach");
		if (objElement){
			objElement.style.display="";
		}
	}
	
	if ((m_lngMode & MODE_HIDE_BODY_FIELD)!=MODE_HIDE_BODY_FIELD){
		objElement=document.getElementById("trMailBody");
		if (objElement){
			objElement.style.display="";
		}
	}
	
	if ((m_lngMode & MODE_HIDE_INDIV_RECIP_CHK)!=MODE_HIDE_INDIV_RECIP_CHK){
		objElement=document.getElementById("tdMailIndivRecip");
		var objCheckbox = document.getElementById("chkSendIndiv");
		var objLbl = document.getElementById("spnSendIndvLbl");
		
		if(objElement){
			objElement.style.display="";
		}
		
		if(objLbl){
			objLbl.style.display="";
		}
		
		if(objCheckbox){
			objCheckbox.style.display="";
		}
	}

	if ((m_lngMode & MODE_HIDE_HTML_BODY_CHK)!=MODE_HIDE_HTML_BODY_CHK){
		objElement=document.getElementById("tdMailHTMLBody");
		if (objElement){
			objElement.style.display="";
		}
	}
	
	if ((m_lngMode & MODE_HIDE_SAVE_CONVQUEUE_ROW)!=MODE_HIDE_SAVE_CONVQUEUE_ROW){
		objElement=document.getElementById("trSaveConvQueue");
		var objConvQueueCheckbox = document.getElementById("chkSaveConvQueue");
		if (objElement){
			objElement.style.display="";
		}
		if(objConvQueueCheckbox){
			objConvQueueCheckbox.style.display="";
		}
	}
	
	if ((m_lngMode & MODE_HIDE_SAVE_CONV_CHK)!=MODE_HIDE_SAVE_CONV_CHK){
		objElement=document.getElementById("spnSaveConv");
		if (objElement){
			objElement.style.display="";
		}
	}
	
		if ((m_lngMode & MODE_HIDE_SAVE_CONVQUEUE_CHK)!=MODE_HIDE_SAVE_CONVQUEUE_CHK){
		objElement=document.getElementById("spnSaveConvQueueCombo");
		if (objElement){
			objElement.style.display="";
		}
	}

	if ((m_lngMode & MODE_HIDE_SAVE_QUEUE_CHK)!=MODE_HIDE_SAVE_QUEUE_CHK){
		objElement=document.getElementById("spnSaveQueue");
		if (objElement){
			objElement.style.display=""
		}
	}
	
	if ((m_lngMode & MODE_HIDE_SEND_EMAIL_BUTTON)!=MODE_HIDE_SEND_EMAIL_BUTTON){
		objElement=document.getElementById("tdBtnSendEmail");
		if (objElement){
			objElement.style.display="";
		}
	}
	
	if ((m_lngMode & MODE_HIDE_SAVE_TMPL_BUTTON)!=MODE_HIDE_SAVE_TMPL_BUTTON){
		objElement=document.getElementById("tdBtnSaveTmpl");
		if (objElement){
			objElement.style.display="";
		}
	}

	if ((m_lngMode & MODE_HIDE_SAVE_EMAIL_BUTTON)!=MODE_HIDE_SAVE_EMAIL_BUTTON){
		objElement=document.getElementById("tdBtnSaveEmail");
		if (objElement){
			objElement.style.display="";
		}
	}
	
	if ((m_lngMode & MODE_HIDE_LINK_ATTACHMENT)==MODE_HIDE_LINK_ATTACHMENT){
		objElement=document.getElementById("txtMailAttach");
		if (objElement){
			objElement.setAttribute("AttachMode", 2);
		}
	}
}

function BodyFormat_OnChange()
{
	m_objEmailEditor.FormatChange();
	if(document.getElementById(FLD_FORMAT_CONTROL_NAME).checked)
	{
		if(m_arrMailContentValues){
			m_arrMailContentValues[FLD_HTML_BODY_ID] = BODY_FORMAT_TYPE_HTML;
		}
		SwitchBodyToHTML();
	}else{
		SwitchBodyToText();
	}
}

function SwitchBodyToText()
{	
		SetHTMLContentsToMemo();
}

function SetHTMLContentsToMemo(blnSkipHTMLDecode)
{
	var objMemBody=document.getElementById(FLD_BODY_CONTROL_NAME);
	
	if(objMemBody){
		objMemBody.value=m_objEmailEditor.GetData();
		if(!blnSkipHTMLDecode){
			objMemBody.value = ExtractHtmlBodyAsText(objMemBody.value);
		}
	}
}

function SwitchBodyToHTML()
{	
	var objMemBody=document.getElementById(FLD_BODY_CONTROL_NAME);
	var strBody;

	if(objMemBody){
		strBody=objMemBody.value;
	}
	strBody = PrepareBodyTextForHTMLEditor(strBody, true);
	
	if(m_arrMailContentValues){
		m_arrMailContentValues[FLD_BODY_ID] = strBody;
	}
	
	LoadAndPopulateHTMLEditor();
}

function ExtractHtmlBodyAsText(strHTML)
{
	if(m_objHTTPRequest){
		
		var co=m_objHTTPRequest.Post(m_strCurrentLocation + "WCMqEmailEditor.ASP?WCI=wciExtractHtmlBodyAsText",
																		"Data=" + g_MqRef.MqStr.MqEncodeURIComponent(strHTML));
		if (co!=m_objHTTPRequest.CANCEL_PROCESS){
			var objResponse=m_objHTTPRequest.Response(co);
			
			if (objResponse){
				if (objResponse.HasErrors()){
					objResponse.ProcessErrors("",true,window);
				}else{
					co = g_MqRef.MqStr.MqDecodeURIComponent(co);
					
					//The output of wciExtractHTMLBodyAsText is not immediately suitable for Firefox.
					//Firefox uses '\n' for line breaks, rather than '\r', or '\r\n', so we must make corrections.
					var regExp;
					regExp=new RegExp("\n\r","g");
					co=co.replace(regExp,"\n");
					regExp=new RegExp("\r\n","g");
					co=co.replace(regExp,"\n");
					regExp=new RegExp("\r","g");
					co=co.replace(regExp,"");
					
					regExp=new RegExp(/^\n/);
					if (regExp.test(co)) {
						regExp=new RegExp("\n");
						co=co.replace(regExp,"");
					}
					
					return co;
				}
			}
		}
	}
}
	
function HTMLEditorIsEligibleForInsert(strErrorMsgToDisplay){
	var blnReturn = true;
	var blnHTMLEditorNormalMode = false;
	var objChk=document.getElementById(FLD_FORMAT_CONTROL_NAME);
	
	if(objChk){
		if(objChk.checked){
			var objCurrentCtrl = GetCurrentCtrlObject(m_strCurrentCtrlID);
			if(objCurrentCtrl){
				
				var lngFieldID = objCurrentCtrl.getAttribute("MqFieldID");
				
				if(lngFieldID == parseInt(FLD_BODY_ID)){

					if(m_objEmailEditor.GetMode() == "wysiwyg"){
						blnHTMLEditorNormalMode = true;
					}

					if(!blnHTMLEditorNormalMode){
						if(strErrorMsgToDisplay){
							alert(strErrorMsgToDisplay);
						}
						blnReturn = false;
					}
				}
			}
		}
	}

	return blnReturn;
}

function Form_Clear()
{
	if(window.confirm(MSG_CONFIRM_CLEAR)){
		document.frmEmailContentEditor.reset();
	}
}

function CallWhileWait(strFunctionEval) {
     window.setTimeout (strFunctionEval, 100);
}

function WaitUntilEditorIsLoadedAndInsertBody(){
		if(!m_blnEditorLoadedAPI){
			CallWhileWait("WaitUntilEditorIsLoadedAndInsertBody()");
		}else{
			SetEmailBody();
		}
}

function FormatMacrosInBodyForHTML(strBodyContent, lngFieldID)
{
	if(m_arrAvailableMacros[lngFieldID]){
		var arrMacros=m_arrAvailableMacros[lngFieldID];
		var lngCount;
		var arrMacro;
		var regExp;
		var strMacroName;
		if (strBodyContent) {
			for(lngCount=0; lngCount<arrMacros.length; lngCount++){
				arrMacro=arrMacros[lngCount].split(SEMI_COLON);
				strMacroName=arrMacro[MACRO_NAME_ID];
				//replace the macro with the HTML encoded one
				regExp=new RegExp(strMacroName,"g");
				strBodyContent=strBodyContent.replace(regExp, g_MqRef.MqStr.MqHtmlEncode(strMacroName,false));

			}
			
			//replace the field name macro with the HTML encoded one
			var lngIndexStart;
			var lngIndexEnd;
			var strBeforeMatch;
			var strToChange;
			
			while(strBodyContent.indexOf(MCR_FLD_TAG_START) != -1){
				lngIndexStart = strBodyContent.indexOf(MCR_FLD_TAG_START);
				strBeforeMatch = strBodyContent.substring(0,lngIndexStart);
				lngIndexEnd = strBodyContent.indexOf(MCR_FLD_TAG_END, lngIndexStart);
				lngIndexEnd = lngIndexEnd + 1;// Len of ">" (MCR_FLD_TAG_END)
				strToChange = strBodyContent.substring(lngIndexStart, lngIndexEnd);
				strAfterMatch = strBodyContent.substring(lngIndexEnd);
				strToChange = g_MqRef.MqStr.MqHtmlEncode(strToChange,false);
				strBodyContent = strBeforeMatch + strToChange + strAfterMatch;	
			}
		}
	}
	return strBodyContent;
}

function FillCurrentContent_OnLoad(strXMLMailContentFields)
{
	var CURRENT_DOC="document";
	var FLD_MAIL_CONTENT_ID="nID";
	var strMailContentValues="";
	var objFields=new CMqFieldCol();
		
	if(m_objHiddenSrcFld){
		strMailContentValues=m_objHiddenSrcFld.value;
	}

	var objMailContentFieldsRS;
	
	if(strXMLMailContentFields){									
		objMailContentFieldsRS=new CMqRecordset(strXMLMailContentFields,FLD_MAIL_CONTENT_ID);
	}
	
	objFields.Load(objMailContentFieldsRS);
	m_objLoadDataMgr=new CMqLoadDataMgr(objFields, CURRENT_DOC);
	m_objLoadDataMgr.SetUnescapeData(false);	

	m_arrMailContentValues = FormatFieldArray(strMailContentValues);

	EmailFormSet(m_objLoadDataMgr,m_arrMailContentValues);
	
	if(m_strMailContentValues.length==0){
		var objFromTxt=document.getElementById("txtMailFrom");
		
		if(objFromTxt){
			objFromTxt.value=g_MqRef.MqStr.MqHtmlDecode(m_strDefaultFromAddress,false);
		}
	}
						
}
 function IsMailContentBodyHTML(strHTMLChkFld)
{
	if(strHTMLChkFld == BODY_FORMAT_TYPE_HTML || strHTMLChkFld == "-1" || strHTMLChkFld == "true"){
		blnReturn = true;
	}else{
		blnReturn = false;
	}
	
	return blnReturn;
}

function EmailFormSet(objLoadDataMgr, arrMailContentValues)
{
	var strBody;
	var objMemBody=document.getElementById(FLD_BODY_CONTROL_NAME);
	if(m_arrMailContentValues){

		if(IsMailContentBodyHTML(m_arrMailContentValues[FLD_HTML_BODY_ID])){
			strBody = arrMailContentValues[FLD_BODY_ID];

			objLoadDataMgr.Load(arrMailContentValues,false);

			strBody = PrepareBodyTextForHTMLEditor(strBody, false, true);
			m_arrMailContentValues[FLD_BODY_ID] = strBody;
			
			LoadAndPopulateHTMLEditor();
		}else{ //plain text
				objLoadDataMgr.Load(arrMailContentValues,false);
				SetEmailBody();
		}
	}
}

function StartEditor()
{
	var CKEDITOR_BASEPATH = "../HTMLEditor/";
	
	CKEDITOR.replace( FLD_BODY_CONTROL_NAME , 
							{
								removePlugins: 'resize,scayt,spellchecker,elementspath,tabletools,contextmenu,liststyle,magicline',
								extraPlugins: 'onchange',
								toolbar: 'MQ',
								disableNativeSpellChecker:false,
								enterMode: CKEDITOR.ENTER_DIV,
								tabSpaces: 4,
								entities: false,
								width: '100%',
								on:
								{
									instanceReady:function(ev)
									{
										//Need to use this so that extra lines are not added when loading text.
										this.dataProcessor.writer.lineBreakChars='';
										
										m_objEmailEditor = new CMqRichTextEditor(CKEDITOR.instances[FLD_BODY_CONTROL_NAME], FLD_FORMAT_CONTROL_NAME, FLD_BODY_CONTROL_NAME);
										m_objEmailEditor.Init();
																			
										m_objEmailEditor.GetBody().setAttribute("MqFieldID", FLD_BODY_ID);
										m_objEmailEditor.GetBody().setAttribute("MqInsertFunc", "InsertAtCursor");
										
										HandleBodyUI();
										m_blnEditorLoadedAPI = true;
										
										
									},
									change:function(ev)
									{
										//Equivalent onChange event.  Uses a custom plugin.
										if(CKEDITOR.currentInstance)
										{
											if(CKEDITOR.currentInstance.checkDirty())
											{
												DataChanged();
											}
										}
									},
									dialogDefinition:function(ev)
									{
										//Fix for dialogs that are larger than the Issue Details panel.
										var dialogName = ev.data.name;
										var dialogDefinition = ev.data.definition;
										dialogDefinition.dialog.parts.dialog.setStyles(
											{
												position : 'absolute'
											});
									},
									focus:function(ev)
									{
										//On focus, load all available macros for the mail body field.
										LoadAvailableMacros(FLD_BODY_CONTROL_NAME);
									},
									click:function(ev)
									{
										StoreCursor();
									},
									key:function(ev)
									{
										if(m_objEmailEditor.GetMode() == "wysiwyg")
										{
											StoreCursor(m_objEmailEditor.GetBody());
										}
										DataChanged();
									}
								}
							});
}

function LoadAndPopulateHTMLEditor()
{
		WaitUntilEditorIsLoadedAndInsertBody();
}

function PrepareBodyTextForHTMLEditor(strBody, blnManualSwitch, blnSkipCRToHTMLConversion)
{
		if(blnManualSwitch){
			strBody = g_MqRef.MqStr.MqHtmlEncode(strBody,false);
		}else{
			strBody = FormatMacrosInBodyForHTML(strBody, Number(FLD_BODY_ID));
		}
		
		if(!blnSkipCRToHTMLConversion){
			strBody = ConvertCarriageReturnsToHTML(strBody);
		}
		return strBody;
}

function SetEditorContents(strBody){
		var strHTMLInBody = "";
		if(m_arrMailContentValues){
			strHTMLInBody = m_arrMailContentValues[FLD_HTML_BODY_ID];
		}
		
		if(IsMailContentBodyHTML(strHTMLInBody)){
			m_objEmailEditor.SetData(strBody)
		}else{
			var objBodyCtrl=document.frmEmailContentEditor.txtMailBody;
			
			if(strBody){
				objBodyCtrl.value = strBody;
			}
		}
}

function EmailFormGet(objLoadDataMgr, strEditorInstanceName)
{
	var strDataForSave;
	var strBodyTmp;
	var arrDataForSave;
	
	strDataForSave=objLoadDataMgr.GetDataForSave(false, true);
	arrDataForSave = FormatFieldArray(strDataForSave);

	if (IsMailContentBodyHTML(arrDataForSave[FLD_HTML_BODY_ID])){
		strBodyTmp = m_objEmailEditor.GetData();

		strBodyTmp = g_MqRef.MqStr.PropStringEncode(strBodyTmp);
		strDataForSave = g_MqRef.MqStr.ReplacePropertyValue(strDataForSave,FLD_BODY_ID, strBodyTmp, "&", "=");
	}

	return strDataForSave;
}

function ConvertCarriageReturnsToHTML(strToConvert){

	var regExp;
	
	regExp=new RegExp("\r\n","g");
	strToConvert=strToConvert.replace(regExp,"<br />");
	
	regExp=new RegExp("\n","g");
	strToConvert=strToConvert.replace(regExp,"<br />");
	
	return strToConvert;
}

function FormatFieldArray(strFieldVals)
{
	if(strFieldVals){
		var arrFieldsTemp=strFieldVals.split("&");
		var arrTempField;
		var arrFieldsFinal=new Array();
		var lngCount;
	
		for(lngCount=0; lngCount<arrFieldsTemp.length; lngCount++){
			arrTempField=arrFieldsTemp[lngCount].split("=");
			if(arrTempField.length>=1){
				arrFieldsFinal[arrTempField[0]]= g_MqRef.MqStr.PropStringDecode(arrTempField[1]);
			}
		}
	
		return arrFieldsFinal;
	}
}
		
function ShowNameList(lngMqFieldID)
{
	var blnOpenWindow=true;
	InitLookupItemVals(lngMqFieldID);
	if(m_objLookupItemInfoColl){
		var objLookupItemInfo=m_objLookupItemInfoColl[lngMqFieldID];
		
		if(objLookupItemInfo){
			if(objLookupItemInfo.SourceControl){
				if(objLookupItemInfo.SourceControl.disabled==true){
					blnOpenWindow=false;
				}
			}
			if(blnOpenWindow){
				if(lngMqFieldID == 2 || lngMqFieldID == 12){
					var objSendIndivChk=document.getElementById("chkSendIndiv");
					objSendIndivChk.disabled=true;
				}
				
				if(objLookupItemInfo.MultiSelect){
					OpenChildWindow("HTML/TmplLookupItemMultiSelect.htm?Path=" + g_MqRef.MqStr.MqEncodeURIComponent("../../../") + "&FID=" + lngMqFieldID, "LookupUsers", "toolbar=no,directories=no,resizable=yes,scrollbars=no,width=800,height=570", true, 800, 570);	
				}else{
					OpenChildWindow("HTML/TmplLookupItem.htm?Path=" + g_MqRef.MqStr.MqEncodeURIComponent("../../../") + "&FID=" + lngMqFieldID, "LookupUsers", "toolbar=no,directories=no,resizable=yes,scrollbars=no,width=650,height=500", true, 650, 500);	
				}
			}
		}
	}
}
		
function ShowAttachmentsDlg(ctrl)
{
	var strCtrlVal="-1";
	var strCtrlName="";
	var strValue;
	var strFieldName="";
			
	if(ctrl){
		strCtrlName=ctrl.id;
		strValue=ctrl.value;
		strFieldName=ctrl.getAttribute("MqFieldID");
	}
			
	if (strValue !== "") {
		strCtrlVal=g_MqRef.MqStr.MqEncodeURIComponent(strValue, ";");
	}
				
	var strArgs="AttachID=" + g_MqRef.MqStr.MqEncodeURIComponent(GetHiddenAttachFields("txtUploadDir")) + 
					"&UP=" + g_MqRef.MqStr.MqEncodeURIComponent(m_strUploadPath) + 
					"&FldName=" + g_MqRef.MqStr.MqEncodeURIComponent("Mail_" + strFieldName) +
					"&CtrlName=" + g_MqRef.MqStr.MqEncodeURIComponent(strCtrlName) +
					"&ctrlValue=" + strCtrlVal;
	OpenChildWindow("Attachment.asp?WCI=wciAttachment&" + strArgs, "UploadFiles" + strCtrlName,"scrollbars=yes,resizable=yes", true, 500, 550);
			
}

//this function will get the hidden fields if there are 
//attachments in a new email
function GetHiddenAttachFields(ctrlName)
{
	return document.getElementById(ctrlName).value;
}

//this function will set the hidden fields if there are 
//attachments in a new email
function SetHiddenAttachFields(ctrlName,strNewValue)
{
	var ctrl = document.getElementById(ctrlName);
	var ctrlvalue = ctrl.value;

	if (ctrlvalue !=  strNewValue){
		ctrl.value = strNewValue;
	}
}


function VerifyValue(ctrlName,strNewValue)
{
	//This function is here for the calendar so we can 
	//share the code. Same as function in CensusMain.js
											
	var ctrl=document.getElementById(ctrlName);
							
	if(ctrl){
		ctrlvalue = ctrl.value;
		if (ctrlvalue !=  strNewValue){
			ctrl.value = strNewValue;
		}
	}
}

function GetAttachPathQS()
{
	return "&AP=" + g_MqRef.MqStr.MqEncodeURIComponent(GetAttachPath());	
}

function GetAttachPath()
{
	return g_MqRef.MqFS.ConcatenatePath(m_strUploadPath, GetHiddenAttachFields("txtUploadDir"));	
}

function Save()
{
	if(ValidateForm()){
		SaveEmailContent();
	}
}

function SaveTemplate()
{
	if(ValidateTemplateForm()){
		m_blnSaving = true;
	
		var strDataForSave = EmailFormGet(m_objLoadDataMgr, FLD_BODY_CONTROL_NAME);
		if(m_objHTTPRequest){
			
			var lngID=g_MqRef.MqStr.GetQueryStringValue(location.search, "TmplID");
			var strUserTemplate=g_MqRef.MqStr.GetQueryStringValue(location.search, "UserTmpl");
			
			var co=m_objHTTPRequest.Post(m_strCurrentLocation + "WCMqEmailEditor.ASP?WCI=wciSaveMailTmpl", 
					"TmplID=" + lngID + "&UserTmpl=" + strUserTemplate + "&TmplSrc=" + g_MqRef.MqStr.MqEncodeURIComponent(strDataForSave) + GetAttachPathQS());

			if (co!=m_objHTTPRequest.CANCEL_PROCESS){
														
				var objResponse=m_objHTTPRequest.Response(co);
				if (objResponse){
					if (objResponse.HasErrors()){
						objResponse.ProcessErrors("",true);
					}else{
						if(opener){
							try{
								if(opener.ReloadTemplates){
									opener.ReloadTemplates();
								}
								
								if(opener.SetTemplateID){
									var objMsg=objResponse.GetContent();
									if (objMsg){
										opener.SetTemplateID(objMsg.GetText());
									}
								}
								
								if(opener.RefreshEmailSignatureFrame){
									opener.RefreshEmailSignatureFrame();
								}
								
							}catch(e){}
						}
                        window.close();
					}
				}
			}
		}
	}
}
		
function SendEmail()
{
    if(ValidateForm()){
		m_blnSaving = true;
    
		var strDataForSave = EmailFormGet(m_objLoadDataMgr, FLD_BODY_CONTROL_NAME);
		var lngTag = g_MqRef.MqStr.GetQueryStringValue(location.search, "Tag");
		var strInQueue = g_MqRef.MqStr.GetQueryStringValue(location.search, "InQ")
		var strIssueID = g_MqRef.MqStr.GetQueryStringValue(location.search, "IssueID");

        if(m_objHTTPRequest){

			var co=m_objHTTPRequest.Post(m_strCurrentLocation + "WCMqEmailEditor.ASP?WCI=wciSendEmail",
																"Data=" + g_MqRef.MqStr.MqEncodeURIComponent(strDataForSave) + "&Tag=" + lngTag + 
																GetAttachPathQS() + "&InQ=" + strInQueue + "&IssueID=" + strIssueID);
													
			if (co!=m_objHTTPRequest.CANCEL_PROCESS){								
			var objResponse=m_objHTTPRequest.Response(co);
				if (objResponse){
					if (objResponse.HasErrors()){
						objResponse.ProcessErrors("",true);
					}else{
						window.close();
						if(opener){
							try{
								if(opener.Initialize){
									opener.Initialize();
									opener.Refresh();
								}
							}catch(e){}
						}
					}
				}
			}
        }
    }
}

function ValidateForm()
{	
	var objContentEditor=document.frmEmailContentEditor;
	var blnReturn=true;
	if(objContentEditor.txtMailTo.value==""){
		alert(MSG_ENTER_TO_ADDRESS);
		objContentEditor.txtMailTo.focus();
		blnReturn=false;
	}else{
		if(objContentEditor.txtMailFrom.value==""){
			alert(MSG_ENTER_FROM_ADDRESS);
			objContentEditor.txtMailFrom.focus();
			blnReturn=false;
		}
	}
			
	return blnReturn;
}

function ValidateTemplateForm()
{	
	var objContentEditor=document.frmEmailContentEditor;
	var blnReturn=true;
	if(objContentEditor.txtMailTemplateName.value==""){
		alert(MSG_ENTER_TEMPLATE_NAME);
		objContentEditor.txtMailTemplateName.focus();
		blnReturn=false;
	}
			
	return blnReturn;
}

function SaveEmailContent()
{	
	m_blnSaving = true;
	
	if(m_objHiddenUploadPath){
		m_objHiddenUploadPath.value=GetAttachPath();
	}
	
	if(m_objRef){
		if(m_objRef.GetCurrentRowCheckboxState){
			if(m_objRef.GetCurrentRowCheckboxState()){
				if(m_blnDataChanged){
					if(m_objRef.DataChanged){
						m_objRef.DataChanged();
					}
				}
			}else{
				if(m_objRef.EnsureCurrentRowIsEnabled){
					m_objRef.EnsureCurrentRowIsEnabled();
				}
				if(m_objRef.DataChanged){
					m_objRef.DataChanged();
				}
			}
		}
	}

	var strDataForSave = EmailFormGet(m_objLoadDataMgr, FLD_BODY_CONTROL_NAME);
	
	if(m_objHiddenSrcFld){
		m_objHiddenSrcFld.value=strDataForSave;
		
		if(m_objVisibleSrcFld){
			var objToCtrl=document.getElementById("txtMailTo");
			if(objToCtrl){
				m_objVisibleSrcFld.innerHTML=g_MqRef.MqStr.MqHtmlEncode(objToCtrl.value);
			}
		}

		if(m_objHiddenUploadID){
			m_objHiddenUploadID.value=GetHiddenAttachFields("txtUploadDir");
		}

		window.close();
	}
}
		
function PreviewBodyHTML()
{
	var objBodyCtrl=document.frmEmailContentEditor.txtMailBody;
	
	if(objBodyCtrl){
		var strHTML=objBodyCtrl.value;
	
		var lngFieldID=objBodyCtrl.getAttribute("MqFieldID");
		var arrMacros;
		var arrMacro;
		var lngCount;
		var strMacro;
		var regExp;
	
		if(m_arrAvailableMacros[lngFieldID]){
			arrMacros=m_arrAvailableMacros[lngFieldID];
			
			for(lngCount=0; lngCount<arrMacros.length; lngCount++){
				arrMacro=arrMacros[lngCount].split(SEMI_COLON);
				strMacro=arrMacro[MACRO_NAME_ID];
				//replace all macros with a HTML encoded one
				regExp=new RegExp(strMacro,"g");
				strHTML=strHTML.replace(regExp,g_MqRef.MqStr.MqHtmlEncode(strMacro));
			}		
		}
	
		var objWin=window.open("tmplPreviewEmail.htm", "PreviewEmail", "width=500,height=500,resizable=yes,scrollbars=yes");
		if(strHTML.length>0){
			objWin.document.write(strHTML);
		}
	}
}
		
function StoreCursor(objCtrl)
{	
	if(objCtrl){
		if (objCtrl.createTextRange){
			if(!(objCtrl.selectionStart || objCtrl.selectionStart==0)){
				objCtrl.CursorPos = document.selection.createRange().duplicate();
			}
		}
		
		// Store last control in focus (used by context-aware menus).
		window.m_sCurCtrlID=objCtrl.id;
	}
}

function InsertAtCursor(objCtrl, strString)
{
	var lngHTMLBody = GetHTMLBodyMode();
	if(objCtrl.getAttribute("MqFieldID") == FLD_BODY_ID && lngHTMLBody == BODY_MODE_HTML){
		m_objEmailEditor.InsertHTML(strString);
	}else{
		if (objCtrl.createTextRange && objCtrl.CursorPos){
			var objCursorPos=objCtrl.CursorPos;
			if(objCursorPos.text.charAt(objCursorPos.text.length - 1) == ' '){
				objCursorPos.text=strString + ' ';
			}else{
				objCursorPos.text=strString;
			}
			//show the cursor
			objCursorPos.select();
		}else{
			if(objCtrl.selectionStart || objCtrl.selectionStart==0){
				var lngStart = objCtrl.selectionStart;
				var lngEnd = objCtrl.selectionEnd;
				var strCtrlVal=objCtrl.value;
				
				if(strCtrlVal.charAt(lngEnd - 1) == ' '){
					strString+=' ';
				}
				
				objCtrl.value = strCtrlVal.substring(0, lngStart)
					+ strString
					+ strCtrlVal.substring(lngEnd, strCtrlVal.length);
				
				SetCursor(objCtrl, lngStart+strString.length);
			}else{
				if(objCtrl.type){
					objCtrl.value=objCtrl.value+strString;
				}else{
					objCtrl.innerHTML=objCtrl.innerHTML+g_MqRef.MqStr.MqHtmlEncode(strString);
				}
			}
		}
	}
}  

function SetCursor(objElement, lngCursorPos) 
{
	if(objElement){
		if(objElement.createTextRange){
			var range = objElement.createTextRange();
			range.move('character', lngCursorPos);
			range.select();
		}else{
			elem.focus();
		}
	}
}

function Insert1ToMValue(objCtrl, strValue)
{
	var DISPLAY_DELIM = "; ";
	
	if(objCtrl){
		if (objCtrl.createTextRange && objCtrl.CursorPos){
			var objCursorPos=objCtrl.CursorPos;

			if(!ItemExistsInList(strValue, objCtrl.value, SEMI_COLON)){				
				var objTempRange=objCtrl.createTextRange();
				objTempRange.setEndPoint("EndToEnd", objCursorPos);
				var strTextBeforeCursor=objTempRange.text;
				
				var objTempRange=objCtrl.createTextRange();
				objTempRange.setEndPoint("StartToEnd", objCursorPos);
				var strTextAfterCursor=objTempRange.text;
				
				strValue=Get1ToMFormattedValue(objCtrl, strValue, strTextBeforeCursor, strTextAfterCursor);
				InsertAtCursor(objCtrl, strValue);
			}else{
				//show the cursor
				objCursorPos.select();
			}
		}else{
			if(!ItemExistsInList(strValue, objCtrl.value, SEMI_COLON)){
				objCtrl.value=objCtrl.value + Get1ToMFormattedValue(objCtrl, strValue, objCtrl.value, "");
				objCtrl.focus();
			}else{
				objCtrl.focus();
			}
		}
	}
}

function Get1ToMFormattedValue(objCtrl, strValue, strTextBeforeCursor, strTextAfterCursor)
{
	var DISPLAY_DELIM = "; ";
	
	if(objCtrl){
		if(!(objCtrl.value=="")){
			if(strTextBeforeCursor==""){
				//beginning
				strValue+=DISPLAY_DELIM;
			}else{
				if(g_MqRef.MqStr.Right(strTextBeforeCursor, SEMI_COLON.length)==SEMI_COLON){
					//cursor after ; (so add a space)
					strValue=" " + strValue + SEMI_COLON;
				}else{
					if(g_MqRef.MqStr.Right(strTextBeforeCursor, DISPLAY_DELIM.length)==DISPLAY_DELIM){
						//cursor after ;<space>
						strValue+=DISPLAY_DELIM;
					}else{
						if(strTextAfterCursor==""){
							//end
							strValue=DISPLAY_DELIM+strValue;
						}
					}
				}
			}
		}
	}
	return strValue;
}

function Insert1To1Value(objCtrl, strValue)
{
	if(objCtrl){
		objCtrl.value=strValue;
		objCtrl.focus();
	}
}

function ItemExistsInList(strItem, strList, strListDelim)
{
	var arrList=strList.split(strListDelim);
	var lngCount;
	var blnReturn=false;
			
	for(lngCount=0; lngCount<arrList.length; lngCount++){
				
		if(g_MqRef.MqStr.TrimString(arrList[lngCount])==strItem){
			blnReturn=true;
			lngCount=arrList.length;
		}
	}
	return blnReturn;
}

function CancelEmail()
{
	var lngTmplID=g_MqRef.MqStr.GetQueryStringValue(location.search, "TmplID");
	var lngMailID=g_MqRef.MqStr.GetQueryStringValue(location.search, "MID");
	var strAttachments=document.frmEmailContentEditor.txtMailAttach.value;
	
	if(m_objHTTPRequest){

		var strUploadDir=GetHiddenAttachFields("txtUploadDir");

		if(strUploadDir!="" && strUploadDir!="undefined"){
			var co=m_objHTTPRequest.Get(m_strCurrentLocation + "WCMqEmailEditor.ASP?WCI=wciDeleteTempAttach" 
							+ GetAttachPathQS() + 
							"&TmplID=" + g_MqRef.MqStr.MqEncodeURIComponent(lngTmplID) + 
							"&MID=" + g_MqRef.MqStr.MqEncodeURIComponent(lngMailID) + 
							"&Atmts=" + g_MqRef.MqStr.MqEncodeURIComponent(strAttachments) + 
							"&Type=" + g_MqRef.MqStr.GetQueryStringValue(location.search, QS_TYPE));

			if (co!=m_objHTTPRequest.CANCEL_PROCESS){
															
				var objResponse=m_objHTTPRequest.Response(co);
				if (objResponse){
					if (objResponse.HasErrors()){
						objResponse.ProcessErrors("",true);
					}
				}
			}
		}
	}
	window.close();
}

function HandleBodyUI()
{
	var objMailBodyWrapper=document.getElementById("MailBodyWrapper");
	
	if(objMailBodyWrapper){
		objMailBodyWrapper.style.display="";
	}
}

function HandleSendIndiv()
{
	var objCCTxt=document.getElementById("txtMailCC");
	var objBCCTxt=document.getElementById("txtMailBCC");
	var objSendIndivChk=document.getElementById("chkSendIndiv");
	
	HandleSendIndivUI(objCCTxt, objSendIndivChk);
	HandleSendIndivUI(objBCCTxt, objSendIndivChk);
}

function HandleSendIndivUI(objTxt, objSendIndivChk)
{
	if(objTxt){
		if(objSendIndivChk){
			if(objTxt.value.length>0){
				objSendIndivChk.disabled=true;
			}else{
				objSendIndivChk.disabled=false;
				
				if(objSendIndivChk.checked){
					objTxt.disabled=true;
					objTxt.style.backgroundColor="#dfe3ea";
				}else{
					objTxt.disabled=false;
					objTxt.style.backgroundColor="";
				}			
			}
		}
	}
}

function OnAfterSetValue(objLookupItemInfo)
{
	if(objLookupItemInfo){
		if(objLookupItemInfo.TargetControl){
			if(objLookupItemInfo.TargetControl.id=="txtMailCC" || objLookupItemInfo.TargetControl.id=="txtMailBCC"){
				
				var objSendIndivChk=document.getElementById("chkSendIndiv");
				
				if(objSendIndivChk){
					if(objLookupItemInfo.TargetControl.value==""){
						objSendIndivChk.disabled = false;
					}else{
						objSendIndivChk.disabled = true;
					}
				}
			}
		}
	}
}

function GetHTMLBodyMode()
{
	var lngHTMLBody = BODY_MODE_PLAIN_TEXT;
	var objChk=document.getElementById(FLD_FORMAT_CONTROL_NAME);
	if(objChk.checked){
		lngHTMLBody = BODY_MODE_HTML;
	}
	
	return lngHTMLBody;
}
