<html>
<head>
</head>
<body style="-ms-word-wrap: break-word;">
    ﻿
    <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">
    $(document).ready(function () {
        $('#sendEmailButton').click(function () {
            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 - Send Correspondence Email
            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 - Send Correspondence Email';
            var _workflowId = null;
            var _intervalVar = null;

            function validateForm() {
                var valid = true;
                var valuestring = '';
                parent.Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
                    if (attribute.getRequiredLevel() == "required") {
                        if (attribute.getValue() == null) {
                            var control = attribute.controls.get(0);
                            valuestring += control.getLabel() + '\n';
                            valid = false;
                        }
                    }
                });

                if (!valid) {
                    alert('You must complete the following fields:\n' + valuestring);
                }
                return valid;
            }

            $(document).ready(function () {
                $('#sendEmailButton').click(function () {
                    //Add code to call workflow once complete
                    parent.Xrm.Page.data.entity.save();
                    _parentId = parent.Xrm.Page.data.entity.getId();
                    _workflowId = getWorkflowId(_workflowname);

                    if (_workflowId) {
                        //parent.Xrm.Page.data.entity.save();
                        _intervalVar = setInterval(function () { if (!parent.Xrm.Page.data.entity.getIsDirty()) { refreshCallback(); } }, 100);
                    }
                    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);

                if (workflowstatus) {
                    alert('There was an error executing the workflow.\n' + workflowstatus);
                }
            }
        });
    });
    </script>
    <button name="sendEmailButton" id="sendEmailButton" type="button">Send Email</button>

</body>
</html>