
var userlcid;
var selectedChannel;
var arrayUserRoles;
//var inxmailProfUserRoleId = "3C97E0E8-BBCC-E011-AAA4-00155D021550";
var inxmailProfUserRoleName = "Inxmail Professional User";
var inxmailProfChannelTypeCode = 121550000;

function CampaignActivityOnLoad() {

	/*if (arguments.length > 0) {
		inxmailProfUserRoleId = String(arguments[0]);
	}*/

	userlcid = Xrm.Page.context.getUserLcid();
	selectedChannel = Xrm.Page.getAttribute("channeltypecode").getValue();
	arrayUserRoles = Xrm.Page.context.getUserRoles();


	if (!CheckUserRole()) {
		SetFieldsDisabled();
	}

	CheckMailing();

	if (Xrm.Page.getAttribute("channeltypecode").getValue() == inxmailProfChannelTypeCode) {
		Xrm.Page.getControl("channeltypecode").setDisabled(true);

		Xrm.Page.getAttribute("inx_listname").setRequiredLevel("required");
		Xrm.Page.getAttribute("inx_sender").setRequiredLevel("required");
		Xrm.Page.getAttribute("inx_answerto").setRequiredLevel("required");
	}
	else {
		SetFieldsDisabled();
	}
}
function MailingSentOnChange() {
	CheckMailing();
}


function CheckUserRole() {

	// 2011-09-11 FB: mit UR 4 hat sich die Reihenfolge geändert --> erst wird die Ribbon initialisiert, dann feuert onload
	// Ergebnis: die Benutzerrollen sind unter Umständen noch nicht initialisiert
	if (arrayUserRoles == null) { arrayUserRoles = Xrm.Page.context.getUserRoles(); }
	if (arrayUserRoles == null) return false;

	for (var i = 0; i < arrayUserRoles.length; i++) {
		
		if (GetSecurityRoleName(arrayUserRoles[i]) == true){
			return true;
		}
				
		/*var currentuserRole = arrayUserRoles[i];
		if (currentuserRole.toUpperCase() == userRole.toUpperCase()) {
			return true;
		}*/
	}

	return false;
}



function GetSecurityRoleName(secRoleID){
	
	// Prepare variables for a customer to retrieve.
	var authenticationHeader = GenerateAuthenticationHeader();

	// Prepare the SOAP message.
	var xml = "<?xml version='1.0' encoding='utf-8'?>" +
		"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
		authenticationHeader +
			"<soap:Body>" +
				"<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
					"<entityName>role</entityName>" +
					"<id>" + secRoleID + "</id>" +
					"<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>" +
						"<q1:Attributes>" +
							"<q1:Attribute>name</q1:Attribute>" +							
						"</q1:Attributes>" +
					"</columnSet>" +
				"</Retrieve>" +
			"</soap:Body>" +
		"</soap:Envelope>";
	// Prepare the xmlHttpObject and send the request.
	var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
	xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
	xHReq.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
	xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
	xHReq.setRequestHeader("Content-Length", xml.length);
	xHReq.send(xml);
	
	// Capture the result.
	var resultXml = xHReq.responseXML;

	// Check for errors.
	var errorCount = resultXml.selectNodes('//error').length;
	if (errorCount != 0) {
		var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
		alert(msg);
	}
	// Display the retrieved value.
	else {
		try {					
			
			if (resultXml.selectSingleNode('//q1:name').text.toUpperCase() == inxmailProfUserRoleName.toUpperCase()) {
			    return true;
			}
			else{
				return false;
			}			
			
		}
	catch (e) { }
	}
		
	return false;
}





function ChannelTypeCodeOnChange() {

	if (Xrm.Page.getAttribute("channeltypecode").getValue() == inxmailProfChannelTypeCode) {
		if (CheckUserRole()) {
			if (confirm(SetConfirmMessage())) {
				Xrm.Page.getAttribute("inx_listname").setValue(Xrm.Page.getAttribute("subject").getValue());

				SetFieldsEnabled();
				Xrm.Page.getAttribute("inx_listname").setRequiredLevel("required");
				Xrm.Page.getAttribute("inx_sender").setRequiredLevel("required");
				Xrm.Page.getAttribute("inx_answerto").setRequiredLevel("required");
			}
			else {
				Xrm.Page.getAttribute("channeltypecode").setValue(selectedChannel);

				SetFieldsDisabled();
				Xrm.Page.getAttribute("inx_listname").setRequiredLevel("none");
				Xrm.Page.getAttribute("inx_sender").setRequiredLevel("none");
				Xrm.Page.getAttribute("inx_answerto").setRequiredLevel("none");
			}
		}
		else {
			alert(SetAlertMessage());
			Xrm.Page.getAttribute("channeltypecode").setValue(selectedChannel);

			SetFieldsDisabled();
			Xrm.Page.getAttribute("inx_listname").setRequiredLevel("none");
			Xrm.Page.getAttribute("inx_sender").setRequiredLevel("none");
			Xrm.Page.getAttribute("inx_answerto").setRequiredLevel("none");
		}
	}
	else {
		SetFieldsDisabled();
		Xrm.Page.getAttribute("inx_listname").setRequiredLevel("none");
		Xrm.Page.getAttribute("inx_sender").setRequiredLevel("none");
		Xrm.Page.getAttribute("inx_answerto").setRequiredLevel("none");
	}
}
function SetConfirmMessage() {

	switch (userlcid) {
		case 1031: //Deutsch
			return "Wählen Sie diesen Kanal aus, wenn Sie ein Mailing direkt in der E-Mail-Marketing-" +
            "Software Inxmail Professional erstellen möchten. Die Auswahl des Kanals kann " +
            "anschließend nicht mehr verändert werden.\n\nMöchten Sie fortfahren?";
      case 1036: // Französisch
         return "Sélectionnez ce canal si vous souhaitez créer un mailing directement dans la solution " +
              "d'email marketing Inxmail Professional. Votre sélection ne pourra pas être " +
              "modifiée par la suite.\n\nSouhaitez-vous continuer?";
		default: //Englisch
			return "Choose this channel if you want to create a mailing directly within the email-" +
            "marketing software Inxmail Professional. The selection of this channel cannot " +
            "be undone.\n\nDo you want to continue?";
	}
}
function SetAlertMessage() {

	switch (userlcid) {
		case 1031: //Deutsch
		   return "Sie haben nicht die Berechtigung diesen Kanal zu wählen!";
		case 1036: // Französisch
         return "Vous n'êtes pas autorisé(e) à sélectionner ce canal!";
		default: //Englisch
			return "You do not have permission to select this channel!";
	}
}

function CheckMailing() {

	if (Xrm.Page.getAttribute("inx_mailingsent").getValue() == true) {
		SetFieldsDisabled();
	}
}
function SetFieldsDisabled() {
	Xrm.Page.getControl("inx_sender").setDisabled(true);
	Xrm.Page.getControl("inx_answerto").setDisabled(true);
	Xrm.Page.getControl("inx_createmailactivities").setDisabled(true);
	Xrm.Page.getControl("inx_webcampaign").setDisabled(true);
	Xrm.Page.getControl("inx_listname").setDisabled(true);
	Xrm.Page.getControl("inx_createcampaignresponses").setDisabled(true);

	Xrm.Page.getAttribute("inx_sender").setSubmitMode("always");
	Xrm.Page.getAttribute("inx_answerto").setSubmitMode("always");
	Xrm.Page.getAttribute("inx_createmailactivities").setSubmitMode("always");
	Xrm.Page.getAttribute("inx_webcampaign").setSubmitMode("always");
	Xrm.Page.getAttribute("inx_listname").setSubmitMode("always");
	Xrm.Page.getAttribute("inx_createcampaignresponses").setSubmitMode("always");
}
function SetFieldsEnabled() {
	Xrm.Page.getControl("inx_sender").setDisabled(false);
	Xrm.Page.getControl("inx_answerto").setDisabled(false);
	Xrm.Page.getControl("inx_createmailactivities").setDisabled(false);
	Xrm.Page.getControl("inx_webcampaign").setDisabled(false);
	Xrm.Page.getControl("inx_listname").setDisabled(false);
	Xrm.Page.getControl("inx_createcampaignresponses").setDisabled(false);
}

function EnableSendReceiver() {

	return (CheckUserRole()) &&
	(Xrm.Page.getAttribute("channeltypecode").getValue() == inxmailProfChannelTypeCode) &&
	!(Xrm.Page.getAttribute("inx_mailingsent").getValue());
}
function EnableGetReport() {

	return (CheckUserRole()) &&
	(Xrm.Page.getAttribute("channeltypecode").getValue() == inxmailProfChannelTypeCode) &&
	(Xrm.Page.getAttribute("inx_mailingsent").getValue());
}

function CampaignActivitySubjectOnChange() {

	if (!Xrm.Page.getControl("inx_listname").getDisabled() && !Xrm.Page.getAttribute("inx_mailingsent").getValue()) {
		Xrm.Page.getAttribute("inx_listname").setValue(Xrm.Page.getAttribute("subject").getValue());
	}
}











function is_email_valid(email) {
	return email.search(/^.+@[^@]+\.[^@]+$/) != -1;
}

function CheckEmailAddress(fieldName) {
	var email = null;
	try {
		email = Xrm.Page.getAttribute(fieldName).getValue();
	}
	catch (e) { }
	if (email == null) return true;

	email = String(email).replace(/\s+/g, "");
	if (email.length == 0) return true;

	if (is_email_valid(email)) return true;

	return false;
}

function GetInvalidEmailMessage() {
	switch (userlcid) {
		case 1031: //Deutsch
			return "Bitte geben Sie eine gültige Email-Adresse an.";
		default: //Englisch
			return "Please enter valid email address.";
	}
}

function EmailAddress_OnChange(fieldName) {
	var valid = CheckEmailAddress(fieldName);
	if (!valid) {
		alert(GetInvalidEmailMessage());
	}
	return valid;
}


function CampaignActivity_OnSave() {
	if (!EmailAddress_OnSave("inx_sender")) return;
	if (!EmailAddress_OnSave("inx_answerto")) return;
}

function EmailAddress_OnSave(fieldName) {
	var save = true;
	var ctrl = Xrm.Page.getControl(fieldName);
	if (!ctrl.getDisabled() && !EmailAddress_OnChange(fieldName)) {
		ctrl.setFocus();
		event.returnValue = false;
		save = false;
	}
	return save;
}
