﻿


window.addEvent('domready', function()
{
	previewReq = new Request.HTML({
		url: '/Email/EmailPreview.asp',
		method: 'post',
		onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript)
		{
			PreviewRequestSuccess(responseHTML);
		},

		//Our request will most likely succeed, but just in case, we'll add an
		//onFailure method which will let the user know what happened.
		onFailure: function()
		{
			PreviewRequestFailure();
		}
	});

	// sendReq = new Request.HTML(....
	// (see below)


	var btn;

	// Screens that implement a single DDL an a Preview Button can use this method
	btn = $('makePreviewRequest');
	if (btn != null)
	{
		btn.addEvent('click', function()
		{
			ET_ShowPreview();
			return false;
		});
	}

	$$('#previewCloseButton', '#previewFade').addEvent('click', function()
	{
		HidePreview();
		return false;
	});


	if ($('sendContent') != null)
	{
		sendReq = new Request.HTML({
		url: '/Email/EmailSend.asp',
			method: 'post',
			onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript)
			{
				SendRequestSuccess(responseHTML);
			},

			//Our request will most likely succeed, but just in case, we'll add an
			//onFailure method which will let the user know what happened.
			onFailure: function()
			{
				SendRequestFailure();
			}
		});

		$('sendCloseLog').addEvent('click', function()
		{
			// Hide Send Log
			$('sendFrame').style.display = 'none';
			$('sendCloseLog').style.display = 'none';
			$('sendViewLog').style.display = 'inline-block';

			return false;
		});
		$('sendViewLog').addEvent('click', function()
		{
			// Show Send Log
			$('sendFrame').style.display = 'block';
			$('sendCloseLog').style.display = 'inline-block';
			$('sendViewLog').style.display = 'none';
			return false;
		});
	}


});

function HidePreview()
{
	// Hide overlay
	$('previewContent').style.display = 'none';
	$('previewFade').style.display = 'none';
}

function IsIE6()
{
	return (document.all && !window.opera && !window.XMLHttpRequest);
}
function CreateIE6Popup()
{
	return window.open("about:blank", "emailpopup", "status=0,toolbar=0,location=0,menubar=0,resizable=1,width=800,height=600", true);
}
// Shows the preview with an option form to post
function ET_ShowPreview()
{
	if (IsIE6())
	{
		// Need to post the previewForm to a popup window
		var oPopup = CreateIE6Popup();
		var oForm  = $('previewForm');
		oForm.target = "emailpopup";
		oForm.action = "Email/EmailPreview.asp";
		$('previewForm').submit();
		return;
	}
	// Write "Preview Loading" message to preview frame
	PreviewWriteMessage("<center>Preview Loading...</center>");

	// Display overlays
	$('previewContent').style.display = 'block';
	$('previewFade').style.display = 'block';
	$('previewCloseButton').focus();

	// Action buttons?
	if($defined(fnPreviewActionCallback) && $defined(sPreviewActions))
	{
		var s = "";
		for (var i = 0; i < sPreviewActions.length; i++)
			if(sPreviewActions[i] != '')
				s = s + '<a href="#">'+sPreviewActions[i]+'</a> ';

		$('previewActionButtons').innerHTML = s;
		$$('#previewActionButtons a').addEvent('click', function(e)
		{
			fnPreviewActionCallback(e.target.text);
		});
	}
	// Send request
	previewReq.post($('previewForm'));
}


function PreviewRequestSuccess(html)
{
	// Write preview content
	WriteToPreviewIFrame(html);
}


function PreviewRequestFailure()
{
	PreviewWriteMessage("Error retrieving preview");
}


function PreviewWriteMessage(sText)
{
	var val =
		"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
		"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n"+
		"\t<title>Information</title>\n"+
		"\t<style type=\"text/css\">BODY { background-color:#EEE; color:#999; font-size:10pt; font-family:Verdana; } CENTER { text-align: center; font-size:2em; margin-top: 3em; }</style>\n" +
		"</head>\n"+
		"<body>\n"+
		"\t"+sText+"\n"+
		"</body></html>\n";
		
	WriteToPreviewIFrame(val);
}

function SendWriteMessage(sText)
{
	// Display Frame and write to log.
	// Ref: ~\Projects\Samples\SampleHTML\pre_multiline_test.htm for why we replace \n wtih <br />
	$('sendContent').style.display = 'block';
	$('sendFrame').set('html', sText.replace(/\r\n/g, "<br />").replace(/\n/g, "<br />"));
}

function WriteToPreviewIFrame(sText)
{
	var previewFrame = $('previewFrame');

	// now write out the new contents
	var doc = previewFrame.contentDocument;
	if (doc == undefined || doc == null)
		doc = previewFrame.contentWindow.document;

	doc.open();
	doc.write(sText);
	doc.close();
}







// FUNCTIONS TO CALL FROM PAGE

// Resets all preview form fields
function ET_Reset()
{
	if ($('pfTemplateID') == null)
	{
		var s = "Page is missing OutputPreviewArea() include from DataAccess\EmailTemplates.asp";
		alert(s);
		throw s;
	}
	$('pfTemplateID').value = '';
	$('pfUserID').value = '';
	$('pfSubject').value = '';
	$('pfBody').value = '';
	$('pfFrom').value = '';
	$('pfTo').value = 'userid';
	$('pfReplacementFields').value = '';
	
	fnPreviewActionCallback = null;
	sPreviewActions = null;
}

// Sets the required TemplateID to preview.
function ET_SetTemplateID(n)
{
	$('pfTemplateID').value = n;
}

// Sets the optional UserID which is used to retrieve most replacement fields
// via the GetEmailData() call.
function ET_SetUserID(n)
{
	$('pfUserID').value = n;
}

// Sets an option Body html content which overrides the Template Body from the given Template ID
// This is used when previewing something that the user is currently editing or customising.
function ET_SetBody(s)
{
	$('pfBody').value = s;
}

// Sets an option Subject html content which overrides the Template Subject from the given Template ID
// This is used when previewing something that the user is currently editing or customising.
function ET_SetSubject(s)
{
	$('pfSubject').value = s;
}


// Sets a comma separated list of actions and a callback function if the user selects on
var fnPreviewActionCallback;
var sPreviewActions;

function ET_SetPreviewActions(fnCallback, sList)
{
	if (sList != "")
	{
		fnPreviewActionCallback = fnCallback;
		sPreviewActions = sList.split(',');
	}
}

// Sets an optional to name/address of who to send email to.
// If not set then the name and email from the user's ID is used.  If no userID set then a value (other than 'userid') must be set here.
// Values are as follows:
// sToType : Must be one of the following strings: { userid (default), system, p42admin, pricontact, orgadmin, current_user, custom }
// sToName : If "custom", then the To Name
// sToEmail: If "custom", then the To Email Address
function ET_SetTo(sToType, sToName, sToEmail)
{
	switch (sToType)
	{
		case 'userid':
		case 'system':
		case 'p42admin':
		case 'pricontact':
		case 'orgadmin':
		case 'current_user':

			$('pfTo').value = sToName;
			break;

		case 'custom':

			if (!sToName || !sToEmail)
				throw "Setting ET_SetTo.  Custom type requires a name and email address";

			$('pfTo').value = sToType + '|' + sToName + '|' + sToEmail;
			break;

		default:
			throw "ERROR: Setting ET_SetTo.  Invalid sToType (" + sToType + ")";
	}
}

// Sets a from name/address of who is sending the email.
// Values are as follows:
// sFromType : Must be one of the following strings: { system, p42admin, pricontact, orgadmin, current_user, custom }
// sFromName : If "custom", then the From Name
// sFromEmail: If "custom", then the From Email Address
function ET_SetFrom(sFromType, sFromName, sFromEmail)
{
	switch(sFromType)
	{
	case 'system' :
	case 'p42admin' :
	case 'pricontact' :
	case 'orgadmin' :
	case 'current_user':

		$('pfFrom').value = sFromType;
		break;

	case 'custom' :

		if (!sFromName || !sFromEmail)
			throw "Setting ET_SetFrom.  Custom type requires a name and email address";

		$('pfFrom').value = sFromType + '|' + sFromName + '|' + sFromEmail;
		break;

	default :
		throw "ERROR: Setting ET_SetFrom.  Invalid sFromType ("+sFromType+")";
	}
}


function ET_AddReplacementField(n, v)
{
	var s = $('pfReplacementFields').value;
	if (s.length > 0)
		s += '|';
	s += n.toString() + '|' + v.toString();
	$('pfReplacementFields').value = s;
}

var _fnSendSuccsessCallback, _fnSendFailureCallback;

function ET_SendEmails(fnSendSuccsessCallback, fnSendFailureCallback)
{
	// Save callback functions (three parameters are returned in the callback:
	// Parameter 1: Return Status: { "Success", "Warning", "Error", "CommsFailure" }
	//              ("Success" and "Warning" are returned to fnSendSuccsessCallback; 
	//               "Error" and "CommsFailure" are returned to fnSendFailureCallback)
	// Parameter 2: Warning Count (applicable onnly for "Warning" status code)
	// Parameter 3: Copy of the HTML returned (it will already be posted into the Feedback Log)
	//
	_fnSendSuccsessCallback = fnSendSuccsessCallback;
	_fnSendFailureCallback  = fnSendFailureCallback;

	// Write "Preview Loading" message to preview frame
//	SendWriteMessage("Sending Email(s)... please wait");

	// Send request
	sendReq.post($('previewForm'));
}


// Calls
//
//
function SendRequestSuccess(html)
{
	// Write preview content
	SendWriteMessage(html);

	// Identify the result (ERROR, WARNINGS [nnnn], SUCCESS)
	var sReturnStatus, nWarningCount = 0;
	if (html.substr(0, 14) == '<!-- ERROR -->')
		sReturnStatus = "Error";
	else if (html.substr(0, 16) == '<!-- SUCCESS -->')
		sReturnStatus = "Success";
	else if (html.substr(0, 15) == '<!-- WARNINGS [')
	{
		sReturnStatus = "Warning";
		nWarningCount = parseInt(html.substr(13, html.indexOf(']')-13), 10);
	}

	//alert("Error Level = " + sReturnStatus + "; Error Count = " + nWarningCount);

	if (sReturnStatus == "Success" || sReturnStatus == "Warning")
	{
		// Call success callback	
		if ($type(_fnSendSuccsessCallback) == "function")
			_fnSendSuccsessCallback(sReturnStatus, nWarningCount, html);
	}
	else
	{
		// Call failure callback
		if ($type(_fnSendFailureCallback) == "function")
			_fnSendFailureCallback(sReturnStatus, nWarningCount, html);
	}
}


function SendRequestFailure()
{
	// Write "Preview Loading" message to preview frame
	SendWriteMessage("Send Email Request failed.");

	// Call failure callback
	if ($type(_fnSendFailureCallback) == "function")
		_fnSendFailureCallback("CommsFailure", 0, "");
}




function HideEdit()
{
	// Hide overlay
	$('editContent').style.display = 'none';
}


// Shows the preview with an option form to post
function ShowEdit()
{
	// Display Edit Area
	$('editContent').style.display = 'block';

	// Send request
	previewReq.post($('previewForm'));
}


