//Copyright (c) 2000 Microsoft Corporation.  All rights reserved.
//<script>
var g_szImagePath;
var g_bInitialize = 0;
var g_fOpenAttach=false;
var g_fCloseAfterSave=false;
var g_fHasBeenSaved=false;
var g_winDocAll = null;
var m_szUrl = "";
var g_szXML = '<a:propertyupdate xmlns:a="DAV:" xmlns:b="urn:schemas:contacts:" xmlns:c="urn:schemas:calendar:" xmlns:d="urn:schemas:httpmail:" ' +
			  'xmlns:e="urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/" xmlns:f="http://schemas.microsoft.com/exchange/" >' +
				'<a:set>' +
					'<a:prop>' +
						'<b:businesshomepage/><b:callbackphone/><b:co/><b:department/><b:email1/>' +
						'<b:email2/><b:email3/><b:facsimiletelephonenumber/><b:fileasid/><b:givenName/>' +
						'<b:homeCity/><b:homeCountry/><b:homefax/><b:homePhone/><b:homephone2/><b:homePostalCode/>' +
						'<b:homeState/><b:homeStreet/><b:internationalisdnnumber/><b:l/><b:mailingaddressid/>' +
						'<b:manager/><b:middlename/><b:mobile/><b:nickname/><b:o/><b:organizationmainphone/>' +
						'<b:othercity/><b:othercountry/><b:otherfax/><b:othermobile/><b:otherpostalcode/><b:otherstate/>' +
						'<b:otherstreet/><b:otherTelephone/><b:pager/><b:postalcode/><b:profession/><b:roomnumber/>' +
						'<b:secretarycn/><b:secretaryphone/><b:sn/><b:spousecn/><b:st/><b:street/><b:telephoneNumber/>' +
						'<b:telephonenumber2/><b:title/><c:fburl/><d:htmldescription/><f:outlookmessageclass/>' +
					'</a:prop>' +
				'</a:set>' +
			'</a:propertyupdate>';
var g_objXMLData = null;
var g_fNew = false;

function UpdateTitle()
{
	var szTitle =  g_winDocAll("idFirstName").value + " " + g_winDocAll("idMiddleName").value + " " + g_winDocAll("idLastName").value;
	if(szTitle != "" && szTitle != "  ")
	{
		window.document.title = szTitle;
	}
}

function UpdateMailingAddress(fSet)
{
	var mailingID   =   g_winDocAll("idDefaultMail");
	var hidmailingID=   g_winDocAll("urn:schemas:contacts:mailingaddressid");
	var selElement  =   g_winDocAll("selAddressSelector");
	if(fSet == true)
	{
		mailingID.checked = ((selElement.selectedIndex+1) == hidmailingID.value)?true:false;
	}
	else
	{
		hidmailingID.value  =  (false == mailingID.checked)?0:selElement.selectedIndex+1;
	}   
}

function BindSelectData(selPhone, inputField, fChange)
{
	var szName      =   selPhone.value;
	var formElement =   window.document.all(szName);
	if(fChange == true)
	{
		inputField.value = formElement.value;
	}
	else
	{
		formElement.value   =   inputField.value;
	}
}

function BindAddressData(selAddress, fChange)
{
	var szName      =   selAddress.value;
	var iIndex      =   selAddress.selectedIndex + 1;
	var mailingID   =   g_winDocAll("idDefaultMail");
	var hidmailingID=   g_winDocAll("urn:schemas:contacts:mailingaddressid");
	var objhidStreet=   ""; 
	var objhidCity  =   "";
	var objhidState =   "";
	var objhidZip   =   "";
	var objhidCountry=  "";

	if (hidmailingID.value == "")
		hidmailingID.value = iIndex;

	mailingID.checked = (iIndex == hidmailingID.value)?true:false;
	switch(iIndex)
	{
		case 1:
			objhidStreet    =   g_winDocAll("urn:schemas:contacts:homeStreet");
			objhidCity      =   g_winDocAll("urn:schemas:contacts:homeCity");
			objhidState     =   g_winDocAll("urn:schemas:contacts:homeState");
			objhidZip       =   g_winDocAll("urn:schemas:contacts:homePostalCode");
			objhidCountry   =   g_winDocAll("urn:schemas:contacts:homeCountry");      
		break;
		case 2:
			objhidStreet    =   g_winDocAll("urn:schemas:contacts:street");
			objhidCity      =   g_winDocAll("urn:schemas:contacts:l");
			objhidState     =   g_winDocAll("urn:schemas:contacts:st");
			objhidZip       =   g_winDocAll("urn:schemas:contacts:postalcode");
			objhidCountry   =   g_winDocAll("urn:schemas:contacts:co");
		break;
		case 3:
			objhidStreet    =   g_winDocAll("urn:schemas:contacts:otherstreet");
			objhidCity      =   g_winDocAll("urn:schemas:contacts:othercity");
			objhidState     =   g_winDocAll("urn:schemas:contacts:otherstate");
			objhidZip       =   g_winDocAll("urn:schemas:contacts:otherpostalcode");
			objhidCountry   =   g_winDocAll("urn:schemas:contacts:othercountry");     
		break;
	}
	if(fChange == true)
	{
		g_winDocAll("idStreet").value     =   objhidStreet.value;
		g_winDocAll("idCity").value       =   objhidCity.value;
		g_winDocAll("idState").value      =   objhidState.value;
		g_winDocAll("idZipCode").value    =   objhidZip.value;
		g_winDocAll("idCountry").value    =   objhidCountry.value;
	}
	else
	{
		objhidStreet.value  =   g_winDocAll("idStreet").value;
		objhidCity.value    =   g_winDocAll("idCity").value;
		objhidState.value   =   g_winDocAll("idState").value;
		objhidZip.value     =   g_winDocAll("idZipCode").value;
		objhidCountry.value =   g_winDocAll("idCountry").value;
	}   
}

function Field_OnKeyDown(selElement, iIndex)
{
	var iIncrement  =   0;
	switch(event.keyCode)
	{
		case 40:
			iIncrement = 1;
		break;
		case 38:
			iIncrement = -1;
		break;
	}
	if(iIncrement==0)
	{
		return(false);
	}
	event.cancelBubble  = true;
	event.returnValue   = false;
	switch(iIndex)
	{
		case 0:
			BindSelectData(selElement, event.srcElement, false);
		break;
		case 1:
			BindAddressData(selElement, false);
		break;
	}   
	var index = (selElement.selectedIndex + iIncrement)%selElement.options.length;
	if(index < 0)
	{
		index += selElement.options.length;
	}
	selElement.selectedIndex = index;
	switch(iIndex)
	{
		case 0:
			BindSelectData(selElement, event.srcElement, true);
		break;
		case 1:
			BindAddressData(selElement, true);
		break;      
	}
}

function window.onload()
{
	g_winDocAll = window.document.all;
	UpdateTitle();
	UpdateMailingAddress(true);
	g_szImagePath = g_szVirtualRoot + "/img/";
	var szURLParams = document.location.search;
	szURLParams = szURLParams.toLowerCase();

	fixIE_width();
	g_fNew = (-1 != szURLParams.indexOf("cmd=new"));
	g_bInitialize |= (g_fNew) ? 3 : 5;

	if( !g_fNew )
	{	
		m_szUrl = window.document.location.protocol+ "//" + window.document.location.hostname  + window.document.location.pathname;
	}

	if(window.location.search.indexOf("Cmd=open") != -1)
	{
		g_fHasBeenSaved = true;
	}

	if( 8 == (8 & g_bInitialize) )
	{
		var obj = document.all.tbContentElement;
		tbContentElement_DocumentComplete( obj );
	}

	idTabControl.initialize();
}

function window.onbeforeprint()
{
	var obj = AccessFld(g_winDocAll.prnContactNote);
	if( null != obj )
	{
		obj.style.display="";
		var objText = AccessFld( g_winDocAll.tbContentElement );
		obj.innerHTML = objText.DocumentHTML;
		objText.style.display="none";
	}
}

function window.onafterprint()
{
	var obj = AccessFld(g_winDocAll.prnContactNote);
	if( null != obj )
	{
		obj.style.display="none";
		obj.innerHTML = "";
		var objText = AccessFld( g_winDocAll.tbContentElement );
		objText.style.display="";
	}
}

function tbContentElement_DocumentComplete( obj )
{
	g_bInitialize |= 8;
	if( 1 == (1 & g_bInitialize) )
	{
		if( 2 == (2 & g_bInitialize ) )
		{
			g_bInitialize -= 2;
			InitializeHTMLEditor(obj, null);
		}
		else if( 4 == (4 & g_bInitialize) )
		{
			g_bInitialize -= 4;
			var szURL  = window.document.location.protocol + "//" + window.document.location.hostname  + window.document.location.pathname;
			try
			{
				obj.LoadURL(szURL+"/"+g_szHtmlViewUrl) 
			}
			catch(e)
			{
				//Guard against any html errors here
			}    
		}
		obj.heightReserve = 5;
	}
}

function window.document.onkeydown()
{    
	var fClearKey=false;
	if( event.ctrlKey ) 
	{
		if(event.keyCode==83) //ctrl-S = Save
		{
			onCbClick("SAVEANDCLOSE");
			fClearkey=true;
		}
	}
	if (fClearKey)
	{
		event.cancelBubble=true;
		event.returnValue=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 "SAVEANDCLOSE":
		DisableButtons();    
		g_fCloseAfterSave = true;
		SaveContact()
		break;  
	case "ATTACH":  
		if(g_fHasBeenSaved == false)
		{
			DisableButtons();       
			g_fCloseAfterSave = false;
			g_fOpenAttach = true;
			SaveContact();   
		}
		else
		{
			OpenAttachments();
		}
		break; 
	case "PRINT":
		window.print();
	break;            
	case "DELETE": 
		if( m_szUrl.length )
		{
			DisableButtons();
			DeleteMessage(m_szUrl, g_szUserBase)
		}
		else
		{
			CloseForm();
		}
		break;
	case "SENDTOCONTACT":
		sendToContact();
	break;
	case "MAP":
		mapAddress();   
	break; 
	case "ADDRESSBOOK":
		openGal();
	break;             
	case "HELP":
		LaunchHelp();
		break;             
	}
	return(false);
}

function OpenAttachments()
{
	var objDoc = window.document;
	var msgURL = objDoc.ComposeContactForm.action;
	var rgParams = new Array();
	rgParams["MessageURL"] = msgURL;
	rgParams["WindowOpener"] = window;
	rgParams["InsertAttachWellAfterElement"] = objDoc.all("tbContentElement");
	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 sendToContact()
{
	var rgNodes             = new Array();
	rgNodes[rgNodes.length] = g_winDocAll(g_winDocAll("selEmailSelector").options[0].value)
	rgNodes[rgNodes.length] = g_winDocAll(g_winDocAll("selEmailSelector").options[1].value)
	rgNodes[rgNodes.length] = g_winDocAll(g_winDocAll("selEmailSelector").options[2].value)
	var i;
	var sz = "";
	var szsemiColon = "";
	for(i = 0;i < rgNodes.length; i++)
	{
		if(i > 0)szsemiColon = ";"
		if(rgNodes[i].value != "")
		{
			sz += szsemiColon + rgNodes[i].value;
		}
	}
	sz = "mailto:" + sz;
	openNewWindow(g_szUserBase + '/' + g_szDrafts + "/?Cmd=new&"+sz,"",640, 500)
}

function mapAddress()
{
	var szAddress       = g_winDocAll("idStreet").value;
	var szCity          = g_winDocAll("idCity").value;
	var szState         = g_winDocAll("idState").value;
	var szZip           = g_winDocAll("idZipCode").value;
	var szlblAddress    = "Street="
	var szlblCity       = "&City=";
	var szlblState      = "&State=";
	var szlblZip        = "&Zip=";
	var szExpURL        = "http://www.expediamaps.com/results.asp?";
	var szURL           = "";
	szURL = szExpURL + szlblAddress + szAddress + szlblCity + szCity + szlblState + szState + szlblZip + szZip;
	window.open(szURL)
}

//$$NOTE: newmessage.htc should be simplified to work in this manner so that it works very similar to the standard
//form, but still handles all of the url updating, etc.
var m_xmlHTTP =   new ActiveXObject("Microsoft.xmlHTTP");

function event_noop()
{
	return(false);
}

function event_onreadystate_savecontact()
{
	if(m_xmlHTTP.readyState == 4)
	{
		m_xmlHTTP.onreadystatechange  = event_noop;
		EnableButtons();
		var iStatus = m_xmlHTTP.status;
		if(iStatus == 207)
		{
			g_fHasBeenSaved = true;
			g_fNew = false;
			var szHREF = null;
			var objXML = m_xmlHTTP.responseXML;
			if(objXML != null)
			{
				var objNode = objXML.selectSingleNode("a:multistatus/a:response/a:href");
				m_szUrl = objNode.text;
				window.document.ComposeContactForm.action = m_szUrl
				var obj = window.document.all.tags('BASE');
				if( obj && obj.length )
				{
					obj[0].href = m_szUrl + "/";

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

			if(g_fCloseAfterSave == true)
			{
				CloseForm();
			}
			if(g_fOpenAttach == true)
			{
				OpenAttachments();
				g_fOpenAttach = false;
			}
		}
		
		else if (iStatus == 412)
		{
			//This error is caused by an item having the same name
			var objDate = new Date()
			//Add suffix on to the file name to make it unique.
			event_onreadystate_savecontact.fileName += "-" + objDate.getTime().toString(36)
			g_saveData	(null, 
						event_onreadystate_savecontact.fileName, 
						event_onreadystate_savecontact.objXML,
						event_onreadystate_savecontact.createNew);
			
			
		}
		else
		{
			
			//Handle errors
			switch(iStatus)
			{
				case 401:
				case 403:
					alert(errPermissionDeniedError);
					break;
				case 404:
				case 409:
					alert(errItemNotFound);
					break;
				case 500:
					alert(errInternalServerError);
					break;
				case 503:
					alert(errServiceNotAvailable);
					break;
				default:
					alert(iStatus + " " + m_xmlHTTP.statusText)
					break;						
			}
			event_onreadystate_savecontact.url = null;
			event_onreadystate_savecontact.fileName = null;
			event_onreadystate_savecontact.objXML = null;
			event_onreadystate_savecontact.createNew = null;
		}
	}
}
//Context properties
event_onreadystate_savecontact.url = null;
event_onreadystate_savecontact.fileName = null;
event_onreadystate_savecontact.objXML = null;
event_onreadystate_savecontact.createNew = null;

function SaveContact()
{
	var objForm = g_winDocAll("ComposeContactForm");
	var elements = objForm.elements;
	var i;
	var szPostString = "";
	
	//Build XML data to proppatch contact
	if(g_objXMLData == null)
	{
		g_objXMLData = new ActiveXObject("Microsoft.xmldom");
		g_objXMLData.loadXML(g_szXML);
		g_objXMLData.preserveWhiteSpace = true;
	}
	
	//Iterate through prop nodes and bind form data to xml
	var objPropNodes = g_objXMLData.documentElement.selectNodes("a:set/a:prop/*")
	
	for(i=0; i < objPropNodes.length; i++)
	{
		//If htmldescription then get data from dhtmledit control
		var objNode = objPropNodes.item(i)
		if(objNode.baseName == "htmldescription")
		{
			objNode.text = g_winDocAll("tbContentElement").DocumentHTML
		}
		else
		{
			objNode.text = ComposeContactForm.all(objNode.namespaceURI + objNode.baseName).value
		}	
	}
	if(g_fNew)
	{
		//Create a file name
		var szFileName = ComposeContactForm.all("urn:schemas:contacts:sn").value + ComposeContactForm.all("urn:schemas:contacts:givenName").value
		//Check for illegal chars and remove them
		var re       = /[\/\\&~\?\*\|\<\>\"\#\;:\^\%\+]/g;
	    szFileName = szFileName.replace(re, "");
		
		if(szFileName == "")
		{
			szFileName = "NoSubject";
		}
		else
		{
			//UTF8 Encode File Name
			szFileName = toUTF8(szFileName);
			szFileName = szFileName.substr(0,2000);
		}
		
		//Call save data with null url.  The function will generate it's own url when fCreateNew = true
		g_saveData(null,szFileName, g_objXMLData, true);
	}
	else
	{
		//If the item exists then call g_saveData with a null filename and fCreateNew = false
		g_saveData(m_szUrl, null, g_objXMLData, false)
	}
	
	
	
}

function g_saveData(szURL,szFileName, objXML, fCreateNew)
{
	if(szURL == null)
	{
			szURL  = document.location.protocol + "//" + document.location.hostname  + document.location.pathname+ szFileName + ".eml"; 
	}	
	
	m_xmlHTTP.open("PROPPATCH",szURL,true); 
	
	if(g_szAcceptLang != "" )
	{
		m_xmlHTTP.setRequestHeader("Accept-Language:",g_szAcceptLang);		
	}
	
	if(fCreateNew)
	{
	
		m_xmlHTTP.setRequestHeader("If-none-match:","*");
	}	
	event_onreadystate_savecontact.url = szURL;
	event_onreadystate_savecontact.fileName = szFileName;
	event_onreadystate_savecontact.objXML = objXML;
	event_onreadystate_savecontact.createNew = fCreateNew;
	m_xmlHTTP.onreadystatechange  =   event_onreadystate_savecontact;
	m_xmlHTTP.setRequestHeader( "Content-type:", "text/xml");    
	m_xmlHTTP.send(objXML.xml);  
}

function CloseForm()
{
	self.close();
}

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";
		}
	}
}
