﻿<html>
<head>
    <title>Button</title>
    <script src="ClientGlobalContext.js.aspx"></script>
    <script src="bah_SDK.REST.js" type="text/javascript"></script>
    <script src="bah_jquery1.4.1.min.js" type="text/javascript"></script>
    <link href="north52_purecss.css" rel="stylesheet" type="text/css">
    <style type="text/css">
        html, body {
            height: 100%;
            overflow: auto;
            border-width: 0px;
        }

        body {
            padding: 0;
            margin: 0;
        }
    </style>

    <script type="text/javascript">

function callWorkflowSync(workflowId, recordId) {
	var errormessage = null;
	var url = Xrm.Page.context.getClientUrl();
    var request = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>" +
          "<s:Body>" +
            "<Execute xmlns='http://schemas.microsoft.com/xrm/2011/Contracts/Services' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
              "<request i:type='b:ExecuteWorkflowRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts' xmlns:b='http://schemas.microsoft.com/crm/2011/Contracts'>" +
                "<a:Parameters xmlns:c='http://schemas.datacontract.org/2004/07/System.Collections.Generic'>" +
                  "<a:KeyValuePairOfstringanyType>" +
                    "<c:key>EntityId</c:key>" +
                    "<c:value i:type='d:guid' xmlns:d='http://schemas.microsoft.com/2003/10/Serialization/'>" + recordId + "</c:value>" +
                  "</a:KeyValuePairOfstringanyType>" +
                  "<a:KeyValuePairOfstringanyType>" +
                    "<c:key>WorkflowId</c:key>" +
                    "<c:value i:type='d:guid' xmlns:d='http://schemas.microsoft.com/2003/10/Serialization/'>" + workflowId + "</c:value>" +
                  "</a:KeyValuePairOfstringanyType>" +
                "</a:Parameters>" +
                "<a:RequestId i:nil='true' />" +
                "<a:RequestName>ExecuteWorkflow</a:RequestName>" +
              "</request>" +
            "</Execute>" +
          "</s:Body>" +
        "</s:Envelope>";

    var req = new XMLHttpRequest();
    req.open("POST", url + "/XRMServices/2011/Organization.svc/web", false);

    req.setRequestHeader("Accept", "application/xml, text/xml, */*");
    req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
    req.send(request);
	if (req.status != 200){
		errormessage = processError(req.responseXML).message;
	}

	return errormessage;
}

function processError(errorXml){
	var errorMessage = 'could not parse faultstring';
	if (typeof errorXml == 'object') {
		try {
			var bodyNode = errorXml.firstChild.firstChild;
			//Retrieve the fault node
			for (var i = 0; i < bodyNode.childNodes.length; i++) {
				var node = bodyNode.childNodes[i];
				if ("s:Fault" == node.nodeName) {
					for (var j = 0; j < node.childNodes.length; j++) {
						var faultStringNode = node.childNodes[j];
						if ('faultstring' == faultStringNode.nodeName) {
							errorMessage = faultStringNode.textContent;
							break;
						}
					}
					break;
				}
			}
		}
		catch (e) {}
	}
	return new Error(errorMessage);
}

function retrieveMultipleSync(odataSetName, select, filter) {
	// Get Server URL
	var url = Xrm.Page.context.getClientUrl();
	var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
	var odataUri = url + ODATA_ENDPOINT + "/" + odataSetName + "?";
	if (select) {
		odataUri += "$select=" + select;
	}
	if (filter) {
		odataUri += "&" + "$filter=" + filter;
	}
	var service = new XMLHttpRequest();
	if (service != null) {
		service.open("GET", odataUri, false);
		service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
		service.setRequestHeader("Accept", "application/json,text/javascript, */*");
		service.send(null);
		var requestResults = JSON.parse(service.responseText).d;
		return requestResults;
	}
}

//Interaction - Set Resolution to Non-Core on Button Click
function getWorkflowId(workflowname) {
	var workflowId = null;

	var oDataSetName = "WorkflowSet";
	var filter = "(Category/Value eq 0) and (Type/Value eq 1) and (StateCode/Value eq 1) and Name eq '"+workflowname+"'";
	var columns = "WorkflowId,Name";
	var requestResults = retrieveMultipleSync(oDataSetName, columns, filter);
	var workflow = null;

	if (requestResults != null) {
		workflow = requestResults.results[0];
		if (workflow != null)
		{
			workflowId = workflow.WorkflowId;
		}
	}

	return workflowId;
}

//get the id of the record for which we are running
var _parentId = null;

//get the id of the workflow we want to run
var _workflowname = 'Interaction - Set Resolution to Non-Core on Button Click';
var _workflowId = null;
var _intervalVar = null;

$(document).ready(function(){
	$('#actionButton').click(function(){
		var isdirty = parent.Xrm.Page.data.entity.getIsDirty();
		_parentId = parent.Xrm.Page.data.entity.getId();
		_workflowId = getWorkflowId(_workflowname);

		debugger;
		if(_workflowId){
			//parent.Xrm.Page.data.entity.removeOnSave(parent.N52.Clientside.ExecuteFormulas);
			//parent.Xrm.Page.data.entity.removeOnSave(parent.form_OnSave);
			//set a bunch of fields to not required so we can save the form
			parent.Xrm.Page.getAttribute("bah_phonenumber_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("bah_firstname_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("bah_lastname_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("bah_ssn_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("bah_dob_date").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("ccwf_providerfacility_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("ccwf_tin_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("bah_vsooffice_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_address1_line1_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_address1_city_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_address1_stateid").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_address1_zip_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("bah_relationshiptoveteran_code").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("bah_interactedwithother_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("bah_otherrelationship_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_areaintersectionid").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("bah_otherrelationship_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("hrc_emailaddress_text").setRequiredLevel("none");
                        parent.Xrm.Page.getAttribute("bah_facilityid").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("ccwf_faxnumber_text").setRequiredLevel("none");
			//parent.Xrm.Page.getAttribute("vhacrm_topicresolutionintersectionid").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_actionintersectionid").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_request_methodofdelivery_code").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_request_beginningdate_date").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_request_endingdate_date").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_request_address1_attentionline_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_request_address1_line1_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_request_address1_city_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_request_address1_stateid").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_request_address1_postalcode_text").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_request_email_text").setRequiredLevel("none");
                        parent.Xrm.Page.getAttribute("vhacrm_faxattentionline_text").setRequiredLevel("none");
                        parent.Xrm.Page.getAttribute("vhacrm_claimnumber_text").setRequiredLevel("none");
                        parent.Xrm.Page.getAttribute("vhacrm_startdateofservice_date").setRequiredLevel("none");
                        parent.Xrm.Page.getAttribute("vhacrm_enddateofservice_date").setRequiredLevel("none");
                        parent.Xrm.Page.getAttribute("vhacrm_billedamount_currency").setRequiredLevel("none");
                        parent.Xrm.Page.getAttribute("vhacrm_stationwithactivityid").setRequiredLevel("none");
                        parent.Xrm.Page.getAttribute("vhacrm_stationtobeloadedtoid").setRequiredLevel("none");
                        parent.Xrm.Page.getAttribute("bah_visnid").setRequiredLevel("none");
			parent.Xrm.Page.getAttribute("vhacrm_request_fax_text").setRequiredLevel("none");

			debugger;
			isdirty = parent.Xrm.Page.data.entity.getIsDirty();
			//save the record
			//parent.Xrm.Page.data.save().then(refreshCallback, refreshError);
			parent.Xrm.Page.data.entity.save();
			_intervalVar = setInterval(function(){ if(!parent.Xrm.Page.data.entity.getIsDirty()){refreshCallback();} }, 100);
			//refreshCallback();
		}
		else{
			alert('Could not find activated workflow named ' + _workflowname);
		}
	});
});

function refreshError(){
	alert('there was an error');
}

function refreshCallback(){
	clearInterval(_intervalVar);

	//call the workflow
	var workflowstatus = callWorkflowSync(_workflowId.toString(),_parentId);
	isdirty = parent.Xrm.Page.data.entity.getIsDirty();

	if(workflowstatus) {
		alert('There was an error executing the workflow.\n' + workflowstatus);

		//re-require the fields from above
		parent.Xrm.Page.getAttribute("bah_phonenumber_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("bah_firstname_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("bah_lastname_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("bah_ssn_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("bah_dob_date").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("ccwf_providerfacility_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("ccwf_tin_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("bah_vsooffice_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_address1_line1_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_address1_city_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_address1_stateid").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_address1_zip_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("bah_relationshiptoveteran_code").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("bah_interactedwithother_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("bah_otherrelationship_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_areaintersectionid").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("bah_otherrelationship_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("hrc_emailaddress_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("ccwf_faxnumber_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_topicresolutionintersectionid").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_actionintersectionid").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_request_methodofdelivery_code").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_request_beginningdate_date").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_request_endingdate_date").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_request_address1_attentionline_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_request_address1_line1_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_request_address1_city_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_request_address1_stateid").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_request_address1_postalcode_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_request_email_text").setRequiredLevel("required");
		parent.Xrm.Page.getAttribute("vhacrm_request_fax_text").setRequiredLevel("required");
	}
	else{
		isdirty = parent.Xrm.Page.data.entity.getIsDirty();
		fixDirtyAttributes();

		Xrm.Utility.openEntityForm("bah_interactions");
	}

}

function fixDirtyAttributes(){
    var names = "";
    parent.Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
        if (attribute.getIsDirty()) {
            names += attribute.getName() + ";";
			parent.Xrm.Page.getAttribute(attribute.getName()).setSubmitMode("never");
        }
    });
    //alert(names);
}
    </script>
    <meta charset="utf-8">
</head>
<body style="-ms-word-wrap: break-word;">
    <button name="actionButton" id="actionButton" type="button">Non-Core</button>

</body>
</html>