﻿<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 - Close Interaction and Set Resolution Field Resolved';
    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 () {
        $('#actionButton').click(function () {

            var isdirty = parent.Xrm.Page.data.entity.getIsDirty();

            //Set Non-Core Parameters
            var isNonCore = false;
            var hasNonCore = parent.Xrm.Page.getAttribute("vhacrm_interactionpurposeid").getValue();

            try {
                if (hasNonCore[0].name.toUpperCase() == 'Non-Core'.toUpperCase()) {
                    isNonCore = true;
                }
            }
            catch (err) { isNonCore = false }


            if (isNonCore == false) {
                if (!validateForm()) {
                    return;
                }
            }

            _parentId = parent.Xrm.Page.data.entity.getId();
            _workflowId = getWorkflowId(_workflowname);

            debugger;
            if (_workflowId) {
                // Check if Value is Non-Core and set values as non-required.
                if (isNonCore == true) {
                    parent.Xrm.Page.getAttribute("bah_firstname_text").setRequiredLevel("none");
                    parent.Xrm.Page.getAttribute("bah_lastname_text").setRequiredLevel("none");
                    parent.Xrm.Page.getAttribute("bah_interactedwithother_text").setRequiredLevel("none");
                    parent.Xrm.Page.getAttribute("bah_phonenumber_text").setRequiredLevel("none");
                    parent.Xrm.Page.getAttribute("hrc_emailaddress_text").setRequiredLevel("none");
                    parent.Xrm.Page.getAttribute("ccwf_faxnumber_text").setRequiredLevel("none");
                    parent.Xrm.Page.getAttribute("bah_vsooffice_text").setRequiredLevel("none");
                    parent.Xrm.Page.getAttribute("bah_relationshiptoveteran_code").setRequiredLevel("none");
                    parent.Xrm.Page.getAttribute("bah_otherrelationship_text").setRequiredLevel("none");
                    parent.Xrm.Page.getAttribute("vhacrm_addressline1_text").setRequiredLevel("none");
                    parent.Xrm.Page.getAttribute("vhacrm_city_text").setRequiredLevel("none");
                    parent.Xrm.Page.getAttribute("vhacrm_stateid").setRequiredLevel("none");
                    parent.Xrm.Page.getAttribute("vhacrm_zip_text").setRequiredLevel("none");
                }



                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);
        }
        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>
</head>
<body style="-ms-word-wrap: break-word;">
    <button name="actionButton" id="actionButton" type="button">Submit</button>

</body>
</html>