//Copyright (c) 2000 Microsoft Corporation.  All rights reserved.
//<script>
var g_szImagePath;
var g_fLoadComplete = false;
var g_rgDINode = new Array();
var g_URLRetBody = "";
var g_winDocAll;
var g_objDivTo;
var g_objDivCc;
var g_objDivBcc;
var g_bReply = 0;
CONST_SAVE_NO         = 0;
CONST_SAVE_EXPLICIT   = 1;
CONST_SAVE_IMPLICIT   = 2;
var g_nMsgSavedOld = CONST_SAVE_NO;
var g_nMsgSaved = CONST_SAVE_NO;
var g_fReqRecord = false;
var g_ctrlMedia = null;
var g_bMedia = 0;

function doc_oncopy()
{
	if( "Text" != document.selection.type )
	{
		event.returnValue = false;
		event.cancelBubble = true;
	}
}

function window.onload()
{
	var objBody = document.body;
	var obj = AccessFld(objBody.all.idFormatbar);
	obj.addBehavior( g_szVirtualRoot + "/CONTROLS/formatbar.htc");

	fixIE_width();

	//g_winDocAll is also used in recipients.js
	g_winDocAll = document.all;
	document.body.oncopy = doc_oncopy;

	var tblHdr = AccessFld(g_winDocAll.subject);
	g_nFontHeight = tblHdr.offsetHeight;

	g_szImagePath = g_szVirtualRoot + "/img/";    
	
	//Initialize the global object for use in recipients.js
	g_objDivTo = AccessFld(g_winDocAll.divTo);
	g_objDivCc = AccessFld(g_winDocAll.divCc);
	g_objDivBcc = AccessFld(g_winDocAll.divBcc);

	var szURLParams = "";
	var szURL  = document.location.protocol + "//" + document.location.hostname  + document.location.pathname; 
	var szURLParams = document.location.search;
	szURLParams = szURLParams.toLowerCase();
	g_nMsgSavedOld = g_nMsgSaved = CONST_SAVE_NO;

	var fNewMessage = false;
	var fLoadData = true;

	var re = new RegExp("cmd=([^&]+)", "i" );
	var rgVals = szURLParams.match( re );
	if( null != rgVals )
	{
		rgVals[1] = rgVals[1].toLowerCase();
		switch( rgVals[1] )
		{
			case 'new':
				fNewMessage = true;
				fLoadData = false;
				InitializeHTMLEditor(tbContentElement, unescape(g_URLRetBody));
				break;
			case 'reply':
			case 'replyall':
				g_nMsgSavedOld = g_nMsgSaved = CONST_SAVE_IMPLICIT;
				g_bReply = 1;
				break;
			case 'forward':
				g_nMsgSavedOld = g_nMsgSaved = CONST_SAVE_IMPLICIT;
				g_bReply = 2;
				break;
			case 'open':
			default:
				g_nMsgSavedOld = g_nMsgSaved = CONST_SAVE_EXPLICIT;
				break;
		}
	}
	InitializeRecipientFields(fNewMessage);
	ParseURLForMailTo();

	var fEnableMM = true;
	//parse the content-class
	var szClass = objMessage.contentclass;
	if( szClass.length )
	{
		if( szClass.indexOf("urn:content-classes:calendarmessage")==0 )
		{
			fEnableMM = false;
			setupApptReply(szClass);
		}
	}

	if( fEnableMM )
	{
		var obj = AccessFld(g_winDocAll.multimedia);
		if( obj )
		{
			var fInstalled = oClientCaps.isComponentInstalled("{6E767503-024A-11D3-9D47-00C04F68AC7D}", "ComponentID", g_szEMVer);
			if( fInstalled )
			{
				g_bMedia = 1;
			}
		}
	}

	if (fLoadData == true)
	{
		loadBodyContents(szURL);
	} 
	setTimeout("forceImagePaint()",100);
	objMessage.onchecknames = objMessage_OnCheckNames;
	
	//Initialize toolbar
	try
	{
		//TODO: This is a bad design because the onclick event will trigger binding
		//to the xmldata island which is unnecessary.
		var iImportance = 1;
		iImportance = objMessage.importance
		//TODO: The message object needs to return an integer instead of a string
		if (iImportance != "")
		{
			if (iImportance == "0")
			{
				IMPLOW.click();
			}
			else if(iImportance == "2")
			{
				IMPHIGH.click();
			}
		}
	}
	catch(e)
	{   
	}

	if( 1 != g_bReply )
	{
		g_winDocAll['MsgTo'].focus();
	}
}

function window.onunload()
{
	if( CONST_SAVE_IMPLICIT == g_nMsgSaved )
	{
		DeleteMessage(objMessage.url, null, DeleteMessage.iACT_NO_CONFIRM_SYNC);
	}
}

function window.onbeforeprint()
{
	var obj = AccessFld(g_winDocAll.prnMsgBody);
	if( null != obj )
	{
		obj._szTitle = document.title;
		document.title = "";

		obj.style.display="";
		obj.innerHTML = tbContentElement.DocumentHTML;
		tbContentElement.style.display="none";
	}
}

function window.onafterprint()
{
	var obj = AccessFld(g_winDocAll.prnMsgBody);
	if( null != obj )
	{
		document.title = obj._szTitle;

		obj.style.display="none";
		obj.innerHTML = "";
		tbContentElement.style.display="";
	}

	if( null != g_ctrlMedia )
	{
		ctrlMedia_positionUpdate();
	}
}

function SaveMessage()
{
	DisableButtons();
	UpdateMessageData();
	objMessage.save();
}

function ParseURLForMailTo()
{	
	var szSearch =  window.location.search;
	if( 0 == szSearch.length )
	{
		return(false);
	}

	var re = new RegExp("&mailto:([^&]+)", "i" );
	var rgVals = szSearch.match( re );
	if( null == rgVals )
	{
		return(false);
	}

	var fld = AccessFld(g_winDocAll.MsgTo);
	fld.value = rgVals[1];

	rgVals = parseURLfor("cc");
	if( null != rgVals )
	{
		fld = AccessFld(g_winDocAll.MsgCc);
		fld.value = rgVals;
	}

	rgVals = parseURLfor("bcc");
	if( null != rgVals )
	{
		fld = AccessFld(g_winDocAll.MsgBcc);
		fld.value = rgVals;
	}

	rgVals = parseURLfor("body");
	if( null != rgVals )
	{
		g_URLRetBody = rgVals;
	}

	rgVals = parseURLfor("subject");
	if( null != rgVals )
	{
		fld = AccessFld(g_winDocAll.subject);
		fld.value = unescape(rgVals);
	}
	g_bReply = 8;
}

function tbContentElement_DocumentComplete()
{
	if( !tbContentElement.busy )
	{
		if( g_bReply )
		{
			var objDOM = tbContentElement.DOM;

			var oInlines = inlineAttachments(objDOM);
			if( null != oInlines )
			{
				objMessage.msgClass = "IPM.Note.Multimedia";
			}

			// One shot adding the reply header.
			if( 4 != (4 & g_bReply) && (3 & g_bReply) )
			{
				g_bReply |= 4;
				var szTextHeader    =   "";
				if(idReplyFwdMsgTextHeader)
				{
					szTextHeader = idReplyFwdMsgTextHeader.innerHTML;
				}

				var szBodyHTML = objDOM.body.innerHTML;
				objDOM.body.innerHTML = '<DIV>&nbsp;</DIV><BLOCKQUOTE dir=ltr style="MARGIN-RIGHT: 0px">' + szTextHeader + szBodyHTML + '</BLOCKQUOTE>';
			}

			var rng = objDOM.body.createTextRange();
			rng.move( "word", 0 );
			rng.select();
			if( 5 == g_bReply || 8 == g_bReply )
			{
				tbContentElement.focus();
			}
		}
		if( 1 == g_bMedia ) 
		{
			g_bMedia |= 2;
			insertMediaCtrl();
		}
	}
}

//sets the header fields for a meeting request response
function setupApptReply(szContentClass)
{
	g_winDocAll['trGroove'].style.display="";
	g_winDocAll['trLocation'].style.display="";
	try  //g_iInstanceType may not even exist (in which case we can ignore this)
	{
		if (g_iInstanceType != null && g_iInstanceType.length > 0) //this is a meeting reply from a response
		{
			if (Number(g_iInstanceType) > 0) //recurring
			{
				//put the recurrence pattern in the When field
				if (g_PrintRecurrencePattern.length)
				{
					g_winDocAll['spanWhenText'].innerText = g_PrintRecurrencePattern;
				}    
			}
		}
	} 
	catch(e)
	{
	}
	g_winDocAll['trWhen'].style.display="";
}

function loadBodyContents(szURL)
{
	try
	{
		tbContentElement.LoadURL(szURL+"/"+g_szHtmlViewUrl);
	}
	catch(e)
	{
		//Guard against any html errors here
	}    
	g_fLoadComplete = true;
	return (true);
}

function forceImagePaint()
{
	document.body.insertAdjacentHTML("beforeEnd","<img style='display:none' src='"+ g_szVirtualRoot + "/img/send.gif'>");
}

function window.document.onkeydown()
{
	//$TODO: need a dirty flag here
	if(event.keyCode==27) //ESC = close
	{
		if( confirm(L_AreYouSureCloseMessage_Text) )
		{
			if( CONST_SAVE_IMPLICIT == g_nMsgSaved )
			{
				DeleteMessage(objMessage.url, null, DeleteMessage.iACT_NO_CONFIRM);
				g_nMsgSavedOld = g_nMsgSaved = CONST_SAVE_NO;
			}
			else
			{
				window.close();
			}
		}
	}

	if (!event.ctrlKey)
	{
		return(true);
	}

	switch( event.keyCode )
	{
		case 13:	//ctrl-Enter = Send
			onCbClick("SEND");
			break;
	 	case 75:	//ctrl-K = Resolve
			onCbClick("CHKNAMES");
			break;
		case 83:	//ctrl-S = Save
			onCbClick("SAVE");
			break;
	}
}

var g_fCloseAfterSave   =   false;
var g_fOpenAttach       =   false;
var g_fButtonsDisabled  =   false;
function onCbClick(szCommand, varValue )
{
	if(event && event.button == 2)
	{
		return(false);
	}
	if(g_fButtonsDisabled==true)
	{
		return(false);
	}
	switch(szCommand.toUpperCase())
	{
		case "PRINT":
			window.print();
			break;
		case "SEND":
			DisableButtons();
			UpdateMessageData();
			g_nMsgSavedOld = g_nMsgSaved;
			g_nMsgSaved = CONST_SAVE_EXPLICIT;
			objMessage.send();
			break;
		case "SAVEANDCLOSE":
			g_fCloseAfterSave = true;
			// Do the same thing as SAVE now. Fall through
		case "SAVE":
			g_nMsgSavedOld = g_nMsgSaved;
			g_nMsgSaved = CONST_SAVE_EXPLICIT;
			SaveMessage();
			break;
		case "NORESPONSE":
			DeleteMessage(objMessage.url, null, DeleteMessage.iACT_NO_CONFIRM);
			g_nMsgSavedOld = g_nMsgSaved = CONST_SAVE_NO;
			break;
		case "ATTACH":
			if( CONST_SAVE_NO == g_nMsgSaved )
			{
				g_nMsgSaved = CONST_SAVE_IMPLICIT;
				g_fOpenAttach=true;
				SaveMessage();
			}
			else
			{
				openAttach();
			}
			break;
		case "CHKNAMES":
			DisableButtons();
			setRecipients();
			//change the update recipient handler to dislay anr dialog
			objMessage.onupdaterecipients = resolveAllRecipients;
			if( CONST_SAVE_NO == g_nMsgSaved )
			{
				g_nMsgSaved = CONST_SAVE_IMPLICIT;
			}
			objMessage.checkNames();
			break;
		case "OPTIONS":
			openOptions();
			break;
		case "IMPHIGH":
			objMessage.importance = (varValue) ? 2 : 1;
			break;
		case "IMPLOW":
			objMessage.importance = (varValue) ? 0 : 1;
			break;
		case "MEDIATOOL":
			insertMediaCtrl();
			break;
		case "HELP":
			LaunchHelp();
			break;
	}
}

function DisableButtons()
{
	g_fButtonsDisabled = true;

	with( g_winDocAll.idToolbar )
	{
		with( runtimeStyle )
		{
			filter = "alpha(opacity=35)";
			cursor = "wait";
		}
	}
}

function EnableButtons()
{
	g_fButtonsDisabled = false;

	with( g_winDocAll.idToolbar )
	{
		with( runtimeStyle )
		{
			filter = "alpha(opacity=100)";
			cursor = "hand";
		}
	}
}

function openAttach()
{
	var oInlines = inlineAttachments( tbContentElement.DOM );

	var rgParams = { "MessageURL" : objMessage.url,
					 "WindowOpener" : window,
					 "InsertAttachWellAfterElement" : tbContentElement,
					 "SuppressList" : oInlines };

	var szPath  =   g_szUserBase+"?Cmd=dialog&template=dlg_attach";
	var hWin = window.showModelessDialog(szPath, rgParams,"dialogHeight:400px;status:no;resizable:yes;help:no;center:yes;")
}

function openOptions()
{
	var rgDialogArgs = { "objMsg" : objMessage,
						 "ccField": cc_RecipientRow,
						 "bccField" : bcc_RecipientRow,
						 "toolbar" : idToolbar,
						 "highImport" : IMPHIGH,
						 "lowImport" : IMPLOW };
	var hWin = window.showModalDialog(g_szUserBase +"?Cmd=dialog&template=dlg_msgoptions", rgDialogArgs,"dialogHeight:13em;dialogWidth:24em;status:no;resizable:no;help:no;scroll:no")
	return(true);
}

function UpdateMessageData()
{
	setRecipients();

	if (g_winDocAll("subject").dirty == "1")
	{
		objMessage.subject = g_winDocAll["subject"].value;
		g_winDocAll("subject").dirty="0";
	}
	if( g_bMedia )
	{
		RemoveMMObjectTags(tbContentElement);
		objMessage.msgClass = (g_nMMobjs) ? "IPM.Note.Multimedia" : "IPM.Note";
	}

	var re = /<OBJECT classid=CLSID:D2646502-2424-11D3-9D50-00C04F68AC7D[^>]+><\/OBJECT>/i; 
	objMessage.htmlBody = tbContentElement.DocumentHTML.replace( re, "" );
}

function setRecipients()
{
	if(g_winDocAll["MsgTo"].value != "")
	{
		objMessage.addRecipients(1,g_winDocAll["MsgTo"].value)
	}
	if(g_winDocAll["MsgCc"].value != "")
	{
		objMessage.addRecipients(2,g_winDocAll["MsgCc"].value)
	}
	if(g_winDocAll["MsgBcc"].value != "")
	{
		objMessage.addRecipients(3,g_winDocAll["MsgBcc"].value)
	}
}

function onSaveEx()
{
	objMessage_OnSave();

	var status = event.status;
	if(status == 200)
	{
		var obj = window.document.all.tags('BASE');
		if( obj && obj.length )
		{
			obj[0].href = objMessage.url + "/";

			obj = document.all("idAttachmentWell");
			var rePath = /(<A href=\")[^"]*\//ig;
			obj.innerHTML=obj.innerHTML.replace( rePath, '$1');
		}

		var bstrSubject = AccessFld(g_winDocAll.subject).value;
		if( 0 == bstrSubject.length )
		{
			bstrSubject = g_szNewMessage;
		}
		document.title = bstrSubject;

		if( false == g_fCloseAfterSave )
		{
			if (g_fReqRecord == true)
			{
				g_fReqRecord = false;
				Record();
			}
		}
	}
	else
	{
		g_nMsgSaved = g_nMsgSavedOld;
	}
}
