function bulkResolveRequestsHEC(selectedItems) {

    // loop through selected item
    for (i = 0; i < selectedItems.length; i++) {
        var selectedItem = selectedItems[i];
        var remainingItems = selectedItems.length;

        // Call action (action will stop if LOB is not correct)
        callAction("vhacrm_InteractionHECDeactivate",
            [{
                key: "Target",
                type: "a:EntityReference",
                value: selectedItem
            }],
            function () { //SUCCESS CALLBACK
                remainingItems--;
                debugger;
                if (remainingItems == 0) {
                 //   if (crmGrid) {
                 //       crmGrid.Refresh();
                 //   }
                    window.location = window.location;
                }
            },
            function (e, t) { //ERROR CALLBACK
                // Error
                alert(e);
            }
        );
    }
}

function DeactivateInteractions() {

    // loop through selected item
    for (i = 0; i < selectedItems.length; i++) {
        var selectedItem = selectedItems[i];
        var remainingItems = selectedItems.length;

        // Call action (action will stop if LOB is not correct)
        callAction("vhacrm_InteractionDeactivateButton",
            [{
                key: "Target",
                type: "a:EntityReference",
                value: selectedItem
            }],
            function () { //SUCCESS CALLBACK
                remainingItems--;
                debugger;
                if (remainingItems == 0) {
                 //   if (crmGrid) {
                 //       crmGrid.Refresh();
                 //   }
                    window.location = window.location;
                }
            },
            function (e, t) { //ERROR CALLBACK
                // Error
                alert(e);
            }
        );
    }
}

function enableDeactivateButton() {
 
    var enableButton = true;

    var userid = Xrm.Page.context.getUserId();
	var businessUnitId = GetBusinessUnitIDFortheUser(userid);
    //disable the button if Business Unit = HEC
	if (businessUnitId.toUpperCase() == "C60A6BA1-BA38-E611-8120-127B25DCBDE7") 
	{
        enableButton = false;
    }

    return enableButton;
}

function enableBulkResolveButtonHEC() {

    var enableButton = false;
    var teamidSupv = "C8CCF913-8F90-E611-8124-127B25DCBDE7";
    var teamidAdmin = "FCBD5B58-B99B-E611-8124-127B25DCBDE7";

    // Check if EED Supervisor or EED Admin
    var userid = Xrm.Page.context.getUserId();
    if (isUserOnTeam(userid, teamidSupv) || (isUserOnTeam (userid, teamidAdmin)))
    {
        enableButton=true;
    }
   
    return enableButton;
}

//copied from here - https://processjs.codeplex.com/
function callAction(actionName, inputParams, successCallback, errorCallback) {
    var url = Xrm.Page.context.getClientUrl();

    var requestXml = "<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 xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts'>" +
				"<a:Parameters xmlns:b='http://schemas.datacontract.org/2004/07/System.Collections.Generic'>";

    if (inputParams) {
        // Add each input param
        for (var i = 0; i < inputParams.length; i++) {
            var param = inputParams[i];

            var value = "";
            var displayXmlns = false;

            // Check the param type to determine how the value is formed
            switch (param.type) {
                case "c:boolean":
                case "c:int":
                    value = param.value;
                    displayXmlns = true;
                    break;
                case "c:dateTime":
                    value = param.value.toISOString();
                    displayXmlns = true;
                    break;
                    /* case "a:EntityReference":
                         value = "<a:Id>" + param.value.id + "</a:Id>" +
                           "<a:LogicalName>" + param.value.entityType + "</a:LogicalName>" +
                           "<a:Name i:nil='true' />";
                         break; */
                case "a:EntityReference":
                    value = "<a:Id>" + param.value.Id + "</a:Id>" +
                      "<a:LogicalName>" + param.value.TypeName + "</a:LogicalName>" +
                      "<a:Name i:nil='true' />";
                    break;
                case "a:Entity":
                    value = "<a:Id>" + param.value.Id + "</a:Id>" +
                      "<a:LogicalName>" + param.value.TypeName + "</a:LogicalName>" +
                      "<a:Name i:nil='true' />";
                    break;
                case "a:OptionSetValue":
                case "a:Money":
                    value = "<a:Value>" + param.value + "</a:Value>";
                    break;
                default:
                    if (errorCallback) {
                        errorCallback("Type of input parameter " + (i + 1) + " '" + param.type + "' is invalid or unsupported");
                    }
                    return;
                    break;
            }

            requestXml += "<a:KeyValuePairOfstringanyType>" +
					"<b:key>" + param.key + "</b:key>" +
					"<b:value i:type='" + param.type + "' " + (displayXmlns ? "xmlns:c='http://www.w3.org/2001/XMLSchema'" : "") + ">" + value + "</b:value>" +
				  "</a:KeyValuePairOfstringanyType>";
        }
    }

    requestXml += "</a:Parameters>" +
				"<a:RequestId i:nil='true' />" +
				"<a:RequestName>" + actionName + "</a:RequestName>" +
			  "</request>" +
			"</Execute>" +
		  "</s:Body>" +
		"</s:Envelope>";

    var req = new XMLHttpRequest();
    req.open("POST", url + "/XRMServices/2011/Organization.svc/web", true);
    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.onreadystatechange = function () {
        if (req.readyState == 4) {
            if (req.status == 200) {
                // Action completed successfully - get output params
                var responseParams = req.responseXML.getElementsByTagName("a:KeyValuePairOfstringanyType"); // IE
                if (responseParams.length == 0) {
                    responseParams = req.responseXML.getElementsByTagName("KeyValuePairOfstringanyType"); // FireFox and Chrome
                }

                var outputParams = [];
                for (i = 0; i < responseParams.length; i++) {

                    var attrNameNode = responseParams[i].childNodes[0].firstChild;
                    var attributeName = attrNameNode.textContent || attrNameNode.nodeValue || attrNameNode.data || attrNameNode.text;

                    var attributeValue = "";
                    if (responseParams[i].childNodes[1].firstChild != null) {
                        var attrValueNode = responseParams[i].childNodes[1].firstChild;
                        attributeValue = attrValueNode.textContent || attrValueNode.nodeValue || attrValueNode.data || attrValueNode.text;
                    }

                    // Values will be string, figure out the types yourself
                    outputParams.push({ key: attributeName, value: attributeValue });

                    /*
					DateTime = "2015-06-23T21:00:00Z" (AS UTC STRING)
					bool = "true" (AS STRING)
					OptionSet, int, etc = "1" (AS STRING)
					*/
                }

                if (successCallback) {
                    // Make sure the callback accepts exactly 1 argument - use dynamic function if you want more
                    successCallback(outputParams);
                }
            }
            else {
                // Error has occured, action failed
                if (errorCallback) {
                    var error = null;
                    try { error = req.responseXML.getElementsByTagName("Message")[0].firstChild.nodeValue; } catch (e) { }
                    errorCallback(error);
                }
            }
        }
    };

    req.send(requestXml);
}

//check if the user is on the team using a synchronous odata call
function isUserOnTeam(userid, teamid) {
    var returnvalue = false;
    var oDataSetName = "TeamMembershipSet";
    var filter = "SystemUserId eq guid' " + userid + " ' and TeamId eq guid' " + teamid + "'";
    var columns = "*";
    var requestResults = retrieveMultipleSync(oDataSetName, columns, filter);

    if (requestResults != null) {
        if (requestResults.results.length > 0) {
            returnvalue = true;
        }
    }
    return returnvalue;
}

//helper function for making sync odata calls
function retrieveMultipleSync(odataSetName, select, filter) {
    // Get Server URL
    var serverUrl = "";
    if (Xrm.Page.context.getClientUrl) {
        //Post UR 12
        serverUrl = Xrm.Page.context.getClientUrl();
    }
    else {
        //Pre UR 12
        serverUrl = Xrm.Page.context.getServerUrl();
    }
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    var odataUri = serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "?";
    if (select) {
        odataUri += "$select=" + select;
    }
    if (filter) {
        odataUri += "&" + "$filter=" + filter;
    }
    var service = getRequestObject();
    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 = eval('(' + service.responseText + ')').d;
        return requestResults;
    }
}

function GetBusinessUnitIDFortheUser(userid) {
 
 try {
	var serverUrl = "";
    if (Xrm.Page.context.getClientUrl) {
        //Post UR 12
        serverUrl = Xrm.Page.context.getClientUrl();
    }
    else {
        //Pre UR 12
        serverUrl = Xrm.Page.context.getServerUrl();
    }
        var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
        oDataEndpointUrl += "SystemUserSet?$select=BusinessUnitId&$filter=SystemUserId eq guid'" + userid + "'";
        var service = getRequestObject();
        if (service != null) {
            service.open("GET", oDataEndpointUrl, false);
            service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
            service.setRequestHeader("Accept", "application/json,text/javascript, */*");
            service.send(null);

            var requestResults = eval('(' + service.responseText + ')').d;
            if (requestResults != null && requestResults.results.length == 1) {
                var userRecord = requestResults.results[0];
                if (userRecord.BusinessUnitId && userRecord.BusinessUnitId.Id) {
                    return userRecord.BusinessUnitId.Id;
                }
            }
        }

        return "";
   }
    catch (err) {
        return "";
    }
}
//helper function for making xmlhttp requests
function getRequestObject() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex) {
            return null;
        }
    }
}


