///// <reference path="XrmPage-vsdoc.js" />
///// <reference path="XrmPageTemplate.js" />

// ColorizeForm
// vcri_setUserFacilityDefault
// request_ShowHideTabByUserRoleName
// request_ReasonsCascadingFormOnLoad
// dynamicAssignment - ftp_/RequestAssignment.js
// fileterRFP - ftp_/RequestAssignment.js

//global form variables
var currentUserDetails = {
    SystemUserId: "",
    Name: "",
    ConfigurationName: "",
    roles: [],
    teams: []
};

var owningUserDetails = {
    SystemUserId: "",
    Name: "",
    ConfigurationName: "",
    roles: [],
    teams: []
};

var multipleReasonsForRequestGUID = "156db634-ee0d-e511-8108-00155d14711e";
var otherReasonForRequestGUID = "136db634-ee0d-e511-8108-00155d14711e";
var narcoticRFRName = "Medication - Renewal Narcotic";
var nonNarcoticRFRName = "Medication - Renewal Non-Narcotic";
var _retrievedSettings = null,
	_ICN = null,
	_nationalId = null,
	_notProd = true;

function form_onLoad() {
    //fire USD event to fire form_onLoadWithParameters with parameters from USD $Context
    window.open("http://event?eventname=RequestFormReady");
}

function form_onLoadWithParameters(pICN) {
    //Parameters to this function are passed via a USD action call on the Shared Hidden Veteran's 'PageLoadComplete' event.
    var thisOrgUrl = Xrm.Page.context.getClientUrl();
    _notProd = thisOrgUrl.indexOf("ftp.dev") > 1 || thisOrgUrl.indexOf("INTFTP") > 1 || thisOrgUrl.indexOf("QAFTP") > 1 || thisOrgUrl.indexOf("PREFTP") > 1;

    _ICN = !!pICN ? pICN : null;
    _nationalId = !!_ICN ? _ICN.substring(0, 10) : null;
    retrieveActiveSettings();

    //always save ftp_hungupinqueue value
    var hungUpInQueueAttr = Xrm.Page.getAttribute("ftp_ishungupinqueue_bool");
    if (!!hungUpInQueueAttr) hungUpInQueueAttr.setSubmitMode("always");

    //populate currentUser & Owner role/team arrays, then run ProcessRequest()
    retrieveCurrentUserAndOwnerTeamsAndRoles(ProcessRequest);
}

function retrieveCurrentUserAndOwnerTeamsAndRoles(pCallbackFunction) {
    //populates the global currentUserDetails and owningUserDetails objects and then performs pCallbackFunction();
    if (typeof pCallbackFunction == "function") {
        //clear out original objects first
        currentUserDetails = {
            SystemUserId: "",
            Name: "",
            ConfigurationName: "",
            roles: [],
            teams: []
        };

        owningUserDetails = {
            SystemUserId: "",
            Name: "",
            ConfigurationName: "",
            roles: [],
            teams: []
        };

        var retrievedUsers = [];
        var queryOptions = "$expand=teammembership_association,systemuserroles_association";
        queryOptions += "&$select=SystemUserId,FullName,msdyusd_USDConfigurationId,teammembership_association/Name,teammembership_association/TeamId,systemuserroles_association/RoleId,systemuserroles_association/Name";
        queryOptions += "&$filter=SystemUserId eq guid'" + Xrm.Page.context.getUserId() + "'";
        var ownerValue = Xrm.Page.getAttribute("ownerid").getValue();
        if (!!ownerValue && ownerValue[0].entityType == "systemuser") {
            queryOptions += " or SystemUserId eq guid'" + ownerValue[0].id + "'";
        }
        SDK.REST.retrieveMultipleRecords(
			"SystemUser",
			queryOptions,
			function (retrievedRecords) {
			    if (!!retrievedRecords && retrievedRecords.length > 0) retrievedUsers = retrievedUsers.concat(retrievedRecords);
			},
			errorHandler,
			function () {
			    for (var i = 0, l = retrievedUsers.length; i < l; i++) {
			        var thisUser = retrievedUsers[i];

			        //populate currentUserDetails object
			        if (cleanGUID(thisUser.SystemUserId) == cleanGUID(Xrm.Page.context.getUserId())) {
			            currentUserDetails.SystemUserId = thisUser.SystemUserId;
			            currentUserDetails.Name = thisUser.FullName;
			            currentUserDetails.ConfigurationName = (!!thisUser.msdyusd_USDConfigurationId) ? thisUser.msdyusd_USDConfigurationId.Name : "";
			            //roles
			            for (var j = 0, m = thisUser.systemuserroles_association.results.length; j < m; j++) {
			                var thisRole = thisUser.systemuserroles_association.results[j];
			                currentUserDetails.roles.push({ RoleId: thisRole.RoleId, Name: thisRole.Name });
			            }
			            //teams
			            for (var j = 0, m = thisUser.teammembership_association.results.length; j < m; j++) {
			                var thisTeam = thisUser.teammembership_association.results[j];
			                currentUserDetails.teams.push({ TeamId: thisTeam.TeamId, Name: thisTeam.Name });
			            }
			        }

			        //populate owningUserDetails object
			        if (!!ownerValue && ownerValue[0].entityType == "systemuser" && cleanGUID(thisUser.SystemUserId) == cleanGUID(ownerValue[0].id)) {
			            owningUserDetails.SystemUserId = thisUser.SystemUserId;
			            owningUserDetails.Name = thisUser.FullName;
			            owningUserDetails.ConfigurationName = (!!thisUser.msdyusd_USDConfigurationId) ? thisUser.msdyusd_USDConfigurationId.Name : "";
			            //roles
			            for (var j = 0, m = thisUser.systemuserroles_association.results.length; j < m; j++) {
			                var thisRole = thisUser.systemuserroles_association.results[j];
			                owningUserDetails.roles.push({ RoleId: thisRole.RoleId, Name: thisRole.Name });
			            }
			            //teams
			            for (var j = 0, m = thisUser.teammembership_association.results.length; j < m; j++) {
			                var thisTeam = thisUser.teammembership_association.results[j];
			                owningUserDetails.teams.push({ TeamId: thisTeam.TeamId, Name: thisTeam.Name });
			            }
			        }
			    }

			    //perform whatever callback we wanted
			    pCallbackFunction();
			}//end retrieveMultipleRecords(users) OnComplete function
		);
    }
    else {
        alert("Your callback parameter must be a function");
    }
}

function errorHandler(error) {
    alert(error.message);
}

function ProcessRequest() {
    try {
        ShowHideTabByUserRoleName();
        ExecuteBusinessRules();
        ShowHideResolveCheckbox();

        populateStartDate();
        Xrm.Page.getAttribute("ftp_callbacknumber").fireOnChange();
        parentChild();
        setOriginalPriority();
        saveID();
    }
    catch (e) { alert(e.message); }
}

function ShowHideTabByUserRoleName() {
    writeToConsole("begin ShowHideTabByUserRoleName()");
    //debugger;
    var showPharmacyValidationAndActionTakenTabs =
		userHasRole("FtP Pharmacy", currentUserDetails.roles) ||
		userHasRole("FtP Manager", currentUserDetails.roles) ||
		userHasRole("FtP Supervisor", currentUserDetails.roles) ||
		userHasRole("FTP Facility Admin", currentUserDetails.roles) ||
		userHasRole("FtP PACT", currentUserDetails.roles);

    //NOTE: other code in ftp_reasonforrequest_onChange may hide this tab
    Xrm.Page.ui.tabs.get("Tab_PharmacyValidation").setVisible(showPharmacyValidationAndActionTakenTabs);
    writeToConsole("Pharmacy Validation Tab visible? " + Xrm.Page.ui.tabs.get("Tab_PharmacyValidation").getVisible());

    //Xrm.Page.ui.tabs.get("Tab_ActionTaken").setVisible(showPharmacyValidationAndActionTakenTabs);

    var disableFieldDueToPactRole = userHasRole("FtP PACT", currentUserDetails.roles);
    var fieldsToDisableForPactUsers = [
		"ftp_opiodagreementonfile",
		"ftp_udsonfile",
		"ftp_statedrugmonitoringreport",
		"ftp_spdmpstateonfile",
		"ftp_spdmpstate2",
		"ftp_subreasonid",
		"ftp_minorreasonid",
		"ftp_lastfilled",
		"ftp_quantitytaking",
		"ftp_pickupmethod",
		"ftp_rxnumber",
		"ftp_rxrefillquantity",
		"ftp_earlyrefillcomment",
		"ftp_trackingnumber",
		"ftp_ishungupinqueue_bool",
		"ftp_reassignmentreason_text",
		"ftp_downgradeexplanation_memo"
    ];
    for (var i = 0, l = fieldsToDisableForPactUsers.length; i < l; i++) {
        var control = Xrm.Page.getControl(fieldsToDisableForPactUsers[i]);
        if (!!control) {
            control.setDisabled(disableFieldDueToPactRole);
        }
    }
}

function ExecuteBusinessRules() {
    var formType = Xrm.Page.ui.getFormType();

    //Initialize
    var fieldList = [
		"ftp_minorreasonid",
		"ftp_lastfilled",
		"ftp_quantitytaking",
		"ftp_pickupmethod",
		"ftp_rxnumber",
		"ftp_rxrefillquantity",
		"ftp_earlyrefillcomment",
		"ftp_vacationstart",
		"ftp_vacationend",
		"ftp_trackingnumber"
    ];
    for (var i = 0, l = fieldList.length; i < l; i++) {
        var control = Xrm.Page.getControl(fieldList[i]);
        var value = control.getAttribute().getValue();
        control.getAttribute().setRequiredLevel("none");
        control.setVisible(!!value);
    }

    ftp_priority_onChange(); //see note in function

    //now address business rules, via onchange functions
    var ownerValue = Xrm.Page.getAttribute("ownerid").getValue();
    if (!!ownerValue) {
        var pharmacyBoolean = userIsOnTeam("Pharmacy", currentUserDetails.teams);
        var pactBoolean = userHasRole("FtP PACT", currentUserDetails.roles); //add check for PACT User team??

        ftp_reasonforrequest_onChange(pharmacyBoolean, pactBoolean, true);

        //Warm Transfer is visible to anyone if the owner is the Pharmacy team or a user on the Pharmacy team
        var showWarmTransfer = userIsOnTeam("Pharmacy", owningUserDetails.teams) || ownerIsTeam("Pharmacy", ownerValue);
        Xrm.Page.getControl("ftp_iswarmtransfer").setVisible(showWarmTransfer);
    }
}

function ShowHideResolveCheckbox() {
    //deprecated
    return false;
}

function populateStartDate() {
    if (!(Xrm.Page.getAttribute("ftp_start").getValue()) || !(Xrm.Page.getAttribute("ftp_target").getValue())) {
        var today = new Date();
        var target = new Date();
        target = new Date(target.setDate(target.getDate() + 3));
        Xrm.Page.getAttribute("ftp_start").setValue(today);
        Xrm.Page.getAttribute("ftp_target").setValue(target);
    }
}

function formatTelephoneNumber(pContext) {
    if (!!pContext) {
        var changedAttribute = pContext.getEventSource();
        if (!!changedAttribute) {
            var value = changedAttribute.getValue();
            if (!!value) {
                var tempValue = value.toString().replace(/[^0-9A-Za-z]/g, "").toUpperCase();
                if (tempValue.substr(0, 1) == "1") tempValue = tempValue.substr(1, 99);
                var formattedValue = (tempValue.length >= 10) ? "(" + tempValue.substr(0, 3) + ") " + tempValue.substr(3, 3) + "-" + tempValue.substr(6, 4) : tempValue.substr(0, 3) + "-" + tempValue.substr(3, 4);
                changedAttribute.setValue(formattedValue);
            }
        }
    }
}

function parentChild() {
    var parentCaseControl = Xrm.Page.getControl("parentcaseid");
    if (!!parentCaseControl) {
        var parentCaseHasValue = !!parentCaseControl.getAttribute().getValue();
        parentCaseControl.setVisible(parentCaseHasValue);
        var parentNoteControl = Xrm.Page.getControl("tri_parentnote");
        if (!!parentNoteControl) parentNoteControl.setVisible(parentCaseHasValue);
    }
}

function setOriginalPriority() {
    try {
        var ftype = Xrm.Page.ui.getFormType();
        if (ftype > 1) {
            var initialPriority = Xrm.Page.getAttribute("ftp_priority").getInitialValue().toString();
            if (!!initialPriority) Xrm.Page.getAttribute("ftp_originalpriority").setValue(initialPriority);
        }
    }
    catch (e) {
        alert("There was an issue setting Original Priority. Error:" + e);
    }
}

function saveID() {
    //partially deprecated	
    var ftype = Xrm.Page.ui.getFormType();
    if (ftype !== 1) {
        //deprecated.  this Logic is already covered in ExecuteBusinessRules
        return;
        retrieveTeamsForUser(
			function (retrievedRecords) {
			    for (var i = 0, l = retrievedRecords.length; i < l; i++) {
			        if (retrievedRecords[i].Name == "Pharmacy") {
			            Xrm.Page.getControl("ftp_iswarmtransfer").setVisible(false);
			            break;
			        }
			    }
			}
		);

        /* if (location.href.indexOf("Outlook15White") != -1) {
            //USD Session
            window.open("http://event/?EventName=Saved Request&id=" + Xrm.Page.data.entity.getId() + "");
        } */
    }
    else {
        Xrm.Page.data.entity.save();
    }
}

function ftp_reasonforrequest_onChange(pPharmacyBoolean, pPactBoolean, pFiredOnLoadOrOnSave) {
    writeToConsole("begin ftp_reasonforrequest_onChange()");
    var formType = Xrm.Page.ui.getFormType();
    var ownerValue = Xrm.Page.getAttribute("ownerid").getValue();
    var pharmacyBoolean = (pPharmacyBoolean != null) ? pPharmacyBoolean : userIsOnTeam("Pharmacy", currentUserDetails.teams);
    var pactBoolean = (pPactBoolean != null) ? pPactBoolean : userHasRole("FtP PACT", currentUserDetails.roles);
    var firedOnLoadOrOnSave = (pFiredOnLoadOrOnSave != null) ? pFiredOnLoadOrOnSave : false;
    var reasonForRequestValue = Xrm.Page.getAttribute("ftp_reasonforrequest").getValue();
    var requestTitle = setTitleField();
    var reasonForRequestName = !!reasonForRequestValue ? reasonForRequestValue[0].name : "";
    var isNarcoticRefill = (reasonForRequestName == narcoticRFRName) || (!!requestTitle && requestTitle.indexOf(narcoticRFRName) > -1);
    var isNonNarcoticRefill = (reasonForRequestName == nonNarcoticRFRName) || (!!requestTitle && requestTitle.indexOf(nonNarcoticRFRName) > -1);

    /*adjust visibility of Pharmacy Validation tab and sections within it*/
    var pharmacyValidationTab = Xrm.Page.ui.tabs.get("Tab_PharmacyValidation");
    if (!!pharmacyValidationTab) {
        var showPharmacyValidationTab = (isNarcoticRefill || isNonNarcoticRefill) && (pharmacyBoolean || pactBoolean);
        pharmacyValidationTab.setVisible(showPharmacyValidationTab);

        //sections
        /*
		"Section_NarcoticRenewalValidations"
		hide this section manually for non-narcotic renewals
		*/
        var narcoticRenewalValidationsSection = pharmacyValidationTab.sections.get("Section_NarcoticRenewalValidations");
        if (!!narcoticRenewalValidationsSection) {
            var visible = isNarcoticRefill && (pharmacyBoolean || pactBoolean);
            narcoticRenewalValidationsSection.setVisible(visible);
        }

        /*
		"Section_MedicationRenewalDetails", "Section_PharmacyRefillNarcoticEarly", "Section_PharmacyRefillNarcoticLost"
		These three sections' visiblity is handled automatically when we hide/show fields within them
		*/

    }

    var subReasonControl = Xrm.Page.getControl("ftp_subreasonid");
    if (!!subReasonControl) {
        var visible = (isNarcoticRefill || isNonNarcoticRefill) && (pharmacyBoolean || pactBoolean);
        var require = (isNarcoticRefill || isNonNarcoticRefill) && (pharmacyBoolean);
        subReasonControl.setVisible(visible);
        subReasonControl.getAttribute().setRequiredLevel(require && formType > 1 ? "required" : "none");
        if (!firedOnLoadOrOnSave) subReasonControl.getAttribute().setValue(); //clear minor reason value if we reach this code from actually changing ftp_reasonforrequest
        ftp_subreasonid_onChange(pharmacyBoolean, pactBoolean, firedOnLoadOrOnSave);
    }

    //require fields in the "Required Validation for Narcotic Renewal" section if this is a narcotic renewal
    var narcoticRenewalFieldSet = [
		"ftp_opiodagreementonfile",
		"ftp_udsonfile",
		"ftp_statedrugmonitoringreport"
    ];
    for (var i = 0, l = narcoticRenewalFieldSet.length; i < l; i++) {
        var require = pharmacyBoolean && isNarcoticRefill;
        Xrm.Page.getAttribute(narcoticRenewalFieldSet[i]).setRequiredLevel(require && formType > 1 ? "required" : "none");
    }
    Xrm.Page.getAttribute("ftp_statedrugmonitoringreport").fireOnChange();

    //require ftp_otherreason field if select reason for request is "Other"
    var otherReasonControl = Xrm.Page.getControl("ftp_otherreason");
    if (!!otherReasonControl) {
        var require = !!reasonForRequestValue && cleanGUID(reasonForRequestValue[0].id) == cleanGUID(otherReasonForRequestGUID);
        otherReasonControl.setVisible(require);
        otherReasonControl.getAttribute().setRequiredLevel(require && formType > 1 ? "required" : "none");
    }

    //update this request's priority based on the priority value of the selected reason for request (if it's not "Multiple Reasons for Request")
    //only do this onChange of ftp_reasonforrequest, not onLoad or onSave
    if (!firedOnLoadOrOnSave && !!reasonForRequestValue && cleanGUID(reasonForRequestValue[0].id) != cleanGUID(multipleReasonsForRequestGUID)) {
        var columnSet = "ftp_reasonforrequestId,ftp_reason,ftp_Priority,ftp_AutoResolve";
        SDK.REST.retrieveRecord(
			reasonForRequestValue[0].id,
			"ftp_reasonforrequest",
			columnSet,
			null,
			function (retrievedRecord) {
			    if (!!retrievedRecord) {
			        if (!!retrievedRecord.ftp_Priority && !!retrievedRecord.ftp_Priority.Value) {
			            var priorityAttr = Xrm.Page.getAttribute("ftp_priority");
			            priorityAttr.setValue(retrievedRecord.ftp_Priority.Value);
			            priorityAttr.fireOnChange();
			        }

			        var canAutoResolve = retrievedRecord.ftp_AutoResolve == true;
			        /*fire a USD event under the Shared New Request hosted control to indicate if this Request record can be auto-resolved when the USD session closes.*/
			        var eventUrl = "http://event/?eventname=SetCanAutoResolveRequest&value=" + canAutoResolve.toString();
			        window.open(eventUrl);
			    }
			},
			errorHandler
		);
    }

    /*begin non-narcotic fields logic*/
    Xrm.Page.ui.clearFormNotification("EGFR");
    var nonNarcoticDetailsTab = Xrm.Page.ui.tabs.get("Tab_NonNarcoticDetails");
    if (!!nonNarcoticDetailsTab) {
        var showNonNarcoticDetailsTab = (isNarcoticRefill || isNonNarcoticRefill) && pharmacyBoolean;
        nonNarcoticDetailsTab.setVisible(showNonNarcoticDetailsTab);
    }

    var nonNarcoticRenewalDetailsFieldSet = [
		"ftp_rxtype",
		"ftp_methodofrequest",
		"ftp_age",
		"ftp_pcp",
		"ftp_calccrcl",
		"ftp_latestegfrresult"
    ];
    for (var i = 0; i < nonNarcoticRenewalDetailsFieldSet.length; i++) {
        var thisControl = Xrm.Page.getControl(nonNarcoticRenewalDetailsFieldSet[i]);
        if (!!thisControl) {
            var require = pharmacyBoolean && isNonNarcoticRefill;
            var visible = require;
            thisControl.getAttribute().setRequiredLevel(require ? "required" : "none");
            thisControl.setVisible(visible);

            if (nonNarcoticRenewalDetailsFieldSet[i] == "ftp_latestegfrresult" && isNonNarcoticRefill && pharmacyBoolean) {
                queryLabsAPI();
            }
        }
    }
    /*temporary: don't require ftp_calccrcl yet, until a new web service is ready. kknab 5/2/17*/
    Xrm.Page.getControl("ftp_calccrcl").getAttribute().setRequiredLevel("none");

    Xrm.Page.getControl("ftp_latestegfrresult").getAttribute().setRequiredLevel("none"); //don't ever require ftp_latestegfrresult since its value is set via API.

    /*retrieve data from veteran and put into some fields on Request*/
    var customerValue = Xrm.Page.getAttribute("customerid").getValue();
    if (!!customerValue && customerValue[0].entityType == "contact") {
        var columnSet = "ftp_PrimaryCareProvider,ftp_DateofBirth";
        SDK.REST.retrieveRecord(
			customerValue[0].id,
			"Contact",
			columnSet,
			null,
			function (retrievedRecord) {
			    if (!!retrievedRecord) {
			        /* 
					//removed on 5/5/17 per SME request
					if(!!retrievedRecord.ftp_PrimaryCareProvider){
						var pcpAttr = Xrm.Page.getAttribute("ftp_pcp");
						if(!!pcpAttr){
							pcpAttr.setValue(retrievedRecord.ftp_PrimaryCareProvider);
						}
					}
					*/
			        if (!!retrievedRecord.ftp_DateofBirth) {
			            var ageAttr = Xrm.Page.getAttribute("ftp_age");
			            if (!!ageAttr) {
			                ageAttr.setValue(getAge(retrievedRecord.ftp_DateofBirth).toString());
			            }
			        }
			    }
			},
			errorHandler
		);
    }
    /*end non-narcotic fields logic*/

    var medicationPickerTab = Xrm.Page.ui.tabs.get("Tab_MedicationSelection");
    if (!!medicationPickerTab) {
        var visible = pharmacyBoolean && (isNarcoticRefill || isNonNarcoticRefill);
        var tabState = visible ? "expanded" : "collapsed";
        medicationPickerTab.setDisplayState(tabState);
        medicationPickerTab.setVisible(visible);
        if (visible) {
            var medPickerWR = Xrm.Page.getControl("WebResource_MedicationPicker");
            if (!!medPickerWR) {
                medPickerWR.setSrc(medPickerWR.getSrc());
            }
        }
    }
}

function queryLabsAPI() {
    /*for non-narcotic refill/renewal scenarios, query the HDR Labs API for the latest eGFR lab result*/
    if (!!_ICN) {
        if (!!_retrievedSettings) {
            if (!!_retrievedSettings.ftp_DACURL && !!_retrievedSettings.ftp_LabAPIURL) {
                Xrm.Page.ui.clearFormNotification("EGFR");
                Xrm.Page.ui.setFormNotification("Checking for latest eGFR lab result...", "INFO", "EGFR");

                var apiUsingJson = _retrievedSettings.ftp_LabAPIURL.replace("xml", "json");
                var fullUrl = _retrievedSettings.ftp_DACURL + apiUsingJson + _ICN + _retrievedSettings.ftp_Filter;
                writeToConsole("querying Labs API: " + fullUrl);
                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    datatype: "json",
                    url: fullUrl,
                    beforeSend: function (XMLHttpRequest) {
                        XMLHttpRequest.setRequestHeader("Accept", "application/json");
                    },
                    success: function (response, textStatus, XmlHttpRequest) {
                        writeToConsole("inside Labs API ajax success callback");
                        if (!!response && !!response.Data && Array.isArray(response.Data) && response.Data.length > 0) {
                            //strip out labs except eGFR types
                            for (var i = response.Data.length - 1; i > -1; i--) {
                                var thisLab = response.Data[i];
                                if (thisLab.typeName.toLowerCase() != "egfr" && thisLab.typeName.toLowerCase() != "zzegfr" && thisLab.typeName.toLowerCase() != "egfr and creatinine" && thisLab.typeName.toLowerCase() != "creatinine and egfr") {
                                    response.Data.splice(i, 1);
                                }
                            }

                            if (response.Data.length > 0) {
                                //the results from the API are supposedly sorted by date already..., but sort by date again just in case.
                                response.Data.sort(SortObjectArray("-observed"));
                                var latestResultString = response.Data[0].result;
                                var attr = Xrm.Page.getAttribute("ftp_latestegfrresult");
                                if (!!attr) {
                                    attr.setValue(latestResultString);
                                    attr.setSubmitMode("always");
                                    Xrm.Page.ui.clearFormNotification("EGFR");
                                }
                            }
                            else {
                                Xrm.Page.ui.setFormNotification("Did not find any eGFR lab results.", "INFO", "EGFR");
                                setTimeout(function () { Xrm.Page.ui.clearFormNotification("EGFR"); }, 5000);
                            }
                        }
                        else {
                            Xrm.Page.ui.setFormNotification("Did not find any eGFR lab results.", "INFO", "EGFR");
                            setTimeout(function () { Xrm.Page.ui.clearFormNotification("EGFR"); }, 5000);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        Xrm.Page.ui.setFormNotification("Error retrieving eGFR lab results.", "ERROR", "EGFR");
                        setTimeout(function () { Xrm.Page.ui.clearFormNotification("EGFR"); }, 5000);
                    },
                    async: true,
                    cache: false
                });
            }
        }
        else {
            retrieveActiveSettings(queryLabsAPI);
        }
    }
    else {
        //cannot query HDR APIs without the ICN
    }
}

function ftp_subreasonid_onChange(pPharmacyBoolean, pPactBoolean, pFiredOnLoadOrOnSave) {
    writeToConsole("begin ftp_subreasonid_onChange()");
    var formType = Xrm.Page.ui.getFormType();
    var ownerValue = Xrm.Page.getAttribute("ownerid").getValue();
    var pharmacyBoolean = (pPharmacyBoolean != null) ? pPharmacyBoolean : userIsOnTeam("Pharmacy", currentUserDetails.teams);
    var pactBoolean = (pPactBoolean != null) ? pPactBoolean : userHasRole("FtP PACT", currentUserDetails.roles);
    var firedOnLoadOrOnSave = (pFiredOnLoadOrOnSave != null) ? pFiredOnLoadOrOnSave : false;

    var reasonForRequestValue = Xrm.Page.getAttribute("ftp_reasonforrequest").getValue();
    var reasonForRequestName = !!reasonForRequestValue ? reasonForRequestValue[0].name : "";
    var requestTitle = Xrm.Page.getAttribute("title").getValue();
    var isNarcoticRefill = (reasonForRequestName == narcoticRFRName) || (!!requestTitle && requestTitle.indexOf(narcoticRFRName) > -1);
    var isNonNarcoticRefill = (reasonForRequestName == nonNarcoticRFRName) || (!!requestTitle && requestTitle.indexOf(nonNarcoticRFRName) > -1);
    var subReasonValue = Xrm.Page.getAttribute("ftp_subreasonid").getValue();
    var subReasonName = !!subReasonValue ? subReasonValue[0].name : "";
    var minorReasonValue = Xrm.Page.getAttribute("ftp_minorreasonid").getValue();
    var minorReasonName = !!minorReasonValue ? minorReasonValue[0].name : "";

    //check against pharmacyBoolean and subReasonName to decide whether to show each controls (and require if formType > 1)
    var minorReasonControl = Xrm.Page.getControl("ftp_minorreasonid");
    if (!!minorReasonControl) {
        if (!!subReasonValue) {
            var oDataPath = Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/";
            var query = "ftp_subreasonSet(guid'" + subReasonValue[0].id + "')/ftp_ftp_subreason_ftp_minorreason?$select=ftp_name";

            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/" + query,
                beforeSend: function (XMLHttpRequest) {
                    //Specifying this header ensures that the results will be returned as JSON.
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                },
                success: function (data, textStatus, XmlHttpRequest) {
                    if (!!data) {
                        var visible = (pharmacyBoolean || pactBoolean) && (isNarcoticRefill || isNonNarcoticRefill) && (data.d.results.length > 0);
                        var require = (pharmacyBoolean) && (isNarcoticRefill || isNonNarcoticRefill) && (data.d.results.length > 0);
                        minorReasonControl.setVisible(visible);
                        minorReasonControl.getAttribute().setRequiredLevel(require/* && formType > 1 */ ? "required" : "none");
                        if (!firedOnLoadOrOnSave) minorReasonControl.getAttribute().setValue(); //clear minor reason value if we reach this code from actually changing ftp_subreasonid
                        ftp_minorreasonid_onChange(pharmacyBoolean);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error retrieving minor reasons for selected sub reason: " + errorThrown);
                },
                async: true,
                cache: false
            });
        }
        else {
            minorReasonControl.setVisible(false);
            minorReasonControl.getAttribute().setRequiredLevel("none");
        }
    }

    var pickupMethodControl = Xrm.Page.getControl("ftp_pickupmethod");
    if (!!pickupMethodControl) {
        var visible = (pharmacyBoolean || pactBoolean) && ((isNarcoticRefill && (subReasonName == "Lost" || subReasonName == "Early" || subReasonName == "Stolen" || subReasonName == "Regular")) || isNonNarcoticRefill);
        var require = pharmacyBoolean && ((isNarcoticRefill && (subReasonName == "Lost" || subReasonName == "Early" || subReasonName == "Stolen" || subReasonName == "Regular")) || isNonNarcoticRefill);
        pickupMethodControl.setVisible(visible);
        pickupMethodControl.getAttribute().setRequiredLevel(require/* && formType > 1 //removed, kknab 5/2/17*/ ? "required" : "none");
    }

    var rxNumberControl = Xrm.Page.getControl("ftp_rxnumber");
    if (!!rxNumberControl) {
        var visible = (pharmacyBoolean || pactBoolean) && isNarcoticRefill && (subReasonName == "Lost");
        var require = pharmacyBoolean && isNarcoticRefill && (subReasonName == "Lost");
        rxNumberControl.setVisible(visible);
        rxNumberControl.getAttribute().setRequiredLevel(require ? "required" : "none");
    }

    var narcoticRefillQuantityControlArray = Xrm.Page.getAttribute("ftp_rxrefillquantity").controls.get(function (con) { return con.getParent().getName() == "Section_PharmacyRefillNarcoticLost"; });
    if (narcoticRefillQuantityControlArray.length == 1) {
        var narcoticRefillQuantityControl = narcoticRefillQuantityControlArray[0];
        var visible = (pharmacyBoolean || pactBoolean) && isNarcoticRefill && (subReasonName == "Lost");
        var require = pharmacyBoolean && isNarcoticRefill && (subReasonName == "Lost");
        narcoticRefillQuantityControl.setVisible(visible);
        narcoticRefillQuantityControl.getAttribute().setRequiredLevel(require ? "required" : "none");
    }

    var lastFilledControl = Xrm.Page.getControl("ftp_lastfilled");
    if (!!lastFilledControl) {
        var visible = (pharmacyBoolean || pactBoolean) && ((isNarcoticRefill && (subReasonName == "Lost" || subReasonName == "Early" || subReasonName == "Stolen" || subReasonName == "Regular")) || isNonNarcoticRefill);
        var require = pharmacyBoolean && ((isNarcoticRefill && (subReasonName == "Lost" || subReasonName == "Early" || subReasonName == "Stolen" || subReasonName == "Regular")) || isNonNarcoticRefill);
        lastFilledControl.setVisible(visible);
        lastFilledControl.getAttribute().setRequiredLevel(require ? "required" : "none");
    }

    var earlyNarcoticRefillCommentControl = Xrm.Page.getControl("ftp_earlyrefillcomment");
    if (!!earlyNarcoticRefillCommentControl) {
        var visible = (pharmacyBoolean || pactBoolean) && isNarcoticRefill && subReasonName == "Early";
        earlyNarcoticRefillCommentControl.setVisible(visible);
    }

    var nonNarcoticRenewalFieldSet1 = [
		"ftp_lastdirectionsonfile",
		"ftp_patientstatesdirections",
		"ftp_veteranchangeddose",
        "ftp_discusswithprovider_bool"
    ];
    for (var i = 0; i < nonNarcoticRenewalFieldSet1.length; i++) {
        var thisControl = Xrm.Page.getControl(nonNarcoticRenewalFieldSet1[i]);
        if (!!thisControl) {
            var require = pharmacyBoolean && isNonNarcoticRefill && (subReasonName == "Requesting Renewal, Not on Profile" && minorReasonName == "Dose Change, Taking Regularly" || subReasonName == "Dose Changed / Taking Differently than Prescribed" || minorReasonName == "Directions changed from what is on file");
            var visible = require;
            thisControl.getAttribute().setRequiredLevel(require ? "required" : "none");
            thisControl.setVisible(visible);
        }
    }

    var discussWithProviderControl = Xrm.Page.getControl("ftp_discusswithprovider_bool");
    if (discussWithProviderControl && pharmacyBoolean && isNonNarcoticRefill && (subReasonName == "Requesting Renewal, Not on Profile" && minorReasonName == "Dose Change, Taking Regularly" || subReasonName == "Dose Changed / Taking Differently than Prescribed" || minorReasonName == "Directions changed from what is on file")) { 
        Xrm.Page.getAttribute("ftp_discusswithprovider_bool").fireOnChange();
    }

    var otherTextControl = Xrm.Page.getControl("ftp_othertext");
    if (!!otherTextControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill && (subReasonName == "Other" || subReasonName == "Requesting Hold / Unhold");
        var visible = require;
        otherTextControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        otherTextControl.setVisible(visible);
    }

    var nonNarcoticLostOrStolenControl = Xrm.Page.getControl("ftp_lostorstolen");
    if (!!nonNarcoticLostOrStolenControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill && subReasonName == "Requesting Replacement" && minorReasonName == "Medication Lost or Stolen";
        var visible = require;
        nonNarcoticLostOrStolenControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        nonNarcoticLostOrStolenControl.setVisible(visible);
    }

    var nonNarcoticTrackingNumberControl = Xrm.Page.getControl("ftp_trackingnumber");
    if (!!nonNarcoticTrackingNumberControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill && subReasonName == "Requesting Replacement" && minorReasonName == "Medication never arrived";
        var visible = require;
        nonNarcoticTrackingNumberControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        nonNarcoticTrackingNumberControl.setVisible(visible);
    }

    var nonNarcoticDaysSupplyControl = Xrm.Page.getControl("ftp_dayssupply_text");
    if (nonNarcoticDaysSupplyControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill && subReasonName == "Requesting Change in Refill Quantity";
        var visible = require;
        nonNarcoticDaysSupplyControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        nonNarcoticDaysSupplyControl.setVisible(visible);
    }

    var nonNarcoticCopayReversalControl = Xrm.Page.getControl("ftp_othercopayreversal");
    if (!!nonNarcoticCopayReversalControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill && subReasonName == "Requesting Medication Copay Reversal" && minorReasonName == "Other Reason for Reversal";
        var visible = require;
        nonNarcoticCopayReversalControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        nonNarcoticCopayReversalControl.setVisible(visible);
    }

    var nonNarcoticReasonForStoppingControl = Xrm.Page.getControl("ftp_reasonforstopping");
    if (!!nonNarcoticReasonForStoppingControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill && subReasonName == "Has Stopped Taking Medication";
        var visible = require;
        nonNarcoticReasonForStoppingControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        nonNarcoticReasonForStoppingControl.setVisible(visible);
    }

    var nonNarcoticQuantityReportsTakingControl = Xrm.Page.getControl("ftp_quantityreportstaking");
    if (!!nonNarcoticQuantityReportsTakingControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill &&
			((subReasonName == "Veteran Requesting Early Refill" && minorReasonName == "Requires Extra Medication") ||
			(subReasonName == "Requesting Partial Refill" && minorReasonName == "Requiring extra medication"));
        var visible = require;
        nonNarcoticQuantityReportsTakingControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        nonNarcoticQuantityReportsTakingControl.setVisible(visible);
    }

    var methodOfRequestControl = Xrm.Page.getControl("ftp_methodofrequest");
    if (!!methodOfRequestControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill;
        var visible = require;
        require = subReasonName == "Requesting Hold / Unhold" ? false : true;
        methodOfRequestControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        methodOfRequestControl.setVisible(visible);
    }

    var ageControl = Xrm.Page.getControl("ftp_age");
    if (!!ageControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill;
        var visible = require;
        require = subReasonName == "Requesting Hold / Unhold" ? false : true;
        ageControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        ageControl.setVisible(visible);
    }

    var pcpControl = Xrm.Page.getControl("ftp_pcp");
    if (!!pcpControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill;
        var visible = require;
        require = subReasonName == "Requesting Hold / Unhold" ? false : true;
        pcpControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        pcpControl.setVisible(visible);
    }
}

function ftp_minorreasonid_onChange(pPharmacyBoolean, pPactBoolean) {
    writeToConsole("begin ftp_minorreasonid_onChange()");
    var formType = Xrm.Page.ui.getFormType();
    var ownerValue = Xrm.Page.getAttribute("ownerid").getValue();
    var pharmacyBoolean = (pPharmacyBoolean != null) ? pPharmacyBoolean : userIsOnTeam("Pharmacy", currentUserDetails.teams);
    var pactBoolean = (pPactBoolean != null) ? pPactBoolean : userHasRole("FtP PACT", currentUserDetails.roles);
    var takingExtra = "Veteran has been requiring extra medication and is taking more than prescribed (Qty reported below)";
    var vacation = "Veteran leaving out of town for vacation, has no secure address to mail to";
    var notDelivered = "Not delivered by postal service. Lost in delivery stream (tracking # below)";
    var notLasting = "Veteran is taking within directions prescribed, but does not get quantity to last 28 or 30 days.";

    var reasonForRequestValue = Xrm.Page.getAttribute("ftp_reasonforrequest").getValue();
    var reasonForRequestName = !!reasonForRequestValue ? reasonForRequestValue[0].name : "";
    var requestTitle = Xrm.Page.getAttribute("title").getValue();
    var isNarcoticRefill = (reasonForRequestName == narcoticRFRName) || (!!requestTitle && requestTitle.indexOf(narcoticRFRName) > -1);
    var isNonNarcoticRefill = (reasonForRequestName == nonNarcoticRFRName) || (!!requestTitle && requestTitle.indexOf(nonNarcoticRFRName) > -1);
    var subReasonValue = Xrm.Page.getAttribute("ftp_subreasonid").getValue();
    var subReasonName = !!subReasonValue ? subReasonValue[0].name : "";
    var minorReasonValue = Xrm.Page.getAttribute("ftp_minorreasonid").getValue();
    var minorReasonName = !!minorReasonValue ? minorReasonValue[0].name : "";

    //check against pharmacyBoolean minorReasonName to decide whether to show each controls (and require if formType > 1)
    var quantityTakingControl = Xrm.Page.getControl("ftp_quantitytaking");
    if (!!quantityTakingControl) {
        var visible = (pharmacyBoolean || pactBoolean) && isNarcoticRefill && (minorReasonName == takingExtra || minorReasonName == vacation || minorReasonName == notLasting);
        var require = pharmacyBoolean && isNarcoticRefill && (minorReasonName == takingExtra || minorReasonName == vacation || minorReasonName == notLasting);
        quantityTakingControl.setVisible(visible);
        quantityTakingControl.getAttribute().setRequiredLevel(require && formType > 1 ? "required" : "none");
    }

    var vacationStartControl = Xrm.Page.getControl("ftp_vacationstart");
    if (!!vacationStartControl) {
        var visible = (pharmacyBoolean || pactBoolean) && isNarcoticRefill && minorReasonName == vacation;
        var require = pharmacyBoolean && isNarcoticRefill && minorReasonName == vacation;
        vacationStartControl.setVisible(visible);
        vacationStartControl.getAttribute().setRequiredLevel(require && formType > 1 ? "required" : "none");
    }

    var vacationEndControl = Xrm.Page.getControl("ftp_vacationend");
    if (!!vacationEndControl) {
        var visible = (pharmacyBoolean || pactBoolean) && isNarcoticRefill && minorReasonName == vacation;
        var require = pharmacyBoolean && isNarcoticRefill && minorReasonName == vacation;
        vacationEndControl.setVisible(visible);
        vacationEndControl.getAttribute().setRequiredLevel(require && formType > 1 ? "required" : "none");
    }

    var narcoticTrackingNumberControlArray = Xrm.Page.getAttribute("ftp_trackingnumber").controls.get(function (con) { return con.getParent().getName() == "Section_PharmacyRefillNarcoticLost"; });
    if (narcoticTrackingNumberControlArray.length == 1) {
        var narcoticTrackingNumberControl = narcoticTrackingNumberControlArray[0];
        var visible = (pharmacyBoolean || pactBoolean) && isNarcoticRefill && minorReasonName == notDelivered;
        var require = pharmacyBoolean && isNarcoticRefill && minorReasonName == notDelivered;
        narcoticTrackingNumberControl.setVisible(visible);
        narcoticTrackingNumberControl.getAttribute().setRequiredLevel(require && formType > 1 ? "required" : "none");
    }

    /*begin non-narcotic fields logic*/
    var nonNarcoticRenewalFieldSet1 = [
		"ftp_lastdirectionsonfile",
		"ftp_patientstatesdirections",
		"ftp_veteranchangeddose",
        "ftp_discusswithprovider_bool"
    ];
    for (var i = 0; i < nonNarcoticRenewalFieldSet1.length; i++) {
        var thisControl = Xrm.Page.getControl(nonNarcoticRenewalFieldSet1[i]);
        if (!!thisControl) {
            var require = pharmacyBoolean && isNonNarcoticRefill && (subReasonName == "Requesting Renewal, Not on Profile" && minorReasonName == "Dose Change, Taking Regularly" || subReasonName == "Dose Changed / Taking Differently than Prescribed" || minorReasonName == "Directions changed from what is on file");
            var visible = require;
            thisControl.getAttribute().setRequiredLevel(require ? "required" : "none");
            thisControl.setVisible(visible);
        }
    }

    var discussWithProviderControl = Xrm.Page.getControl("ftp_discusswithprovider_bool");
    if (discussWithProviderControl && pharmacyBoolean && isNonNarcoticRefill && (subReasonName == "Requesting Renewal, Not on Profile" && minorReasonName == "Dose Change, Taking Regularly" || subReasonName == "Dose Changed / Taking Differently than Prescribed" || minorReasonName == "Directions changed from what is on file")) {
        Xrm.Page.getAttribute("ftp_discusswithprovider_bool").fireOnChange();
    }

    var otherTextControl = Xrm.Page.getControl("ftp_othertext");
    if (!!otherTextControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill && (subReasonName == "Other" || subReasonName == "Requesting Hold / Unhold");
        var visible = require;
        otherTextControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        otherTextControl.setVisible(visible);
    }
    var nonNarcoticLostOrStolenControl = Xrm.Page.getControl("ftp_lostorstolen");
    if (!!nonNarcoticLostOrStolenControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill && subReasonName == "Requesting Replacement" && minorReasonName == "Medication Lost or Stolen";
        var visible = require;
        nonNarcoticLostOrStolenControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        nonNarcoticLostOrStolenControl.setVisible(visible);
    }

    var nonNarcoticTrackingNumberControlArray = Xrm.Page.getAttribute("ftp_trackingnumber").controls.get(function (con) { return con.getParent().getName() == "Section_NonNarcoticReplacement"; });
    if (nonNarcoticTrackingNumberControlArray.length == 1) {
        var nonNarcoticTrackingNumberControl = nonNarcoticTrackingNumberControlArray[0];
        var require = pharmacyBoolean && isNonNarcoticRefill && subReasonName == "Requesting Replacement" && minorReasonName == "Medication never arrived";
        var visible = require;
        nonNarcoticTrackingNumberControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        nonNarcoticTrackingNumberControl.setVisible(visible);
    }

    var nonNarcoticCopayReversalControl = Xrm.Page.getControl("ftp_othercopayreversal");
    if (!!nonNarcoticCopayReversalControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill && subReasonName == "Requesting Medication Copay Reversal" && minorReasonName == "Other Reason for Reversal";
        var visible = require;
        nonNarcoticCopayReversalControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        nonNarcoticCopayReversalControl.setVisible(visible);
    }

    var nonNarcoticQuantityReportsTakingControl = Xrm.Page.getControl("ftp_quantityreportstaking");
    if (!!nonNarcoticQuantityReportsTakingControl) {
        var require = pharmacyBoolean && isNonNarcoticRefill &&
			((subReasonName == "Veteran Requesting Early Refill" && minorReasonName == "Requires Extra Medication") ||
			(subReasonName == "Requesting Partial Refill" && minorReasonName == "Requiring extra medication"));
        var visible = require;
        nonNarcoticQuantityReportsTakingControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        nonNarcoticQuantityReportsTakingControl.setVisible(visible);
    }
    /*end non-narcotic fields logic*/
}

function ownerid_onChange(pContext) {
    var attr = Xrm.Page.getAttribute("ownerid");
    if (!!attr) {
        attr.setSubmitMode("always");
        var ownerValue = attr.getValue();
        if (!!ownerValue && cleanGUID(ownerValue[0].id) == cleanGUID(Xrm.Page.context.getUserId())) {
            Xrm.Page.ui.setFormNotification("You own this request. Should you assign the request to someone else?", "WARNING", "assignedToSelf");
        }
        else {
            Xrm.Page.ui.clearFormNotification("assignedToSelf");
        }

        retrieveCurrentUserAndOwnerTeamsAndRoles(ExecuteBusinessRules);
    }
}

function ftp_statedrugmonitoringreport_onChange() {
    //100000000 positive
    //100000001 negative

    var reportValue = Xrm.Page.getAttribute("ftp_statedrugmonitoringreport").getValue();
    var requireState = userIsOnTeam("Pharmacy", currentUserDetails.teams) && !!reportValue && (reportValue == 100000000 || reportValue == 100000001);
    Xrm.Page.getAttribute("ftp_spdmpstateonfile").setRequiredLevel(requireState && Xrm.Page.ui.getFormType() > 1 ? "required" : "none");
}

function userHasRole(pRoleName, pRoleArray) {
    var result = false;
    for (var i = 0, l = pRoleArray.length; i < l; i++) {
        if (pRoleArray[i].Name.toLowerCase() == pRoleName.toLowerCase()) {
            result = true;
            break;
        }
    }
    return result;
}

function userIsOnTeam(pTeamName, pTeamArray) {
    var result = false;
    for (var i = 0, l = pTeamArray.length; i < l; i++) {
        if (pTeamArray[i].Name.toLowerCase() == pTeamName.toLowerCase()) {
            result = true;
            break;
        }
    }
    return result;
}

function ownerIsTeam(pTeamName, pOwnerValue) {
    var result = false;
    if (!!pTeamName && !!pOwnerValue) {
        result = pOwnerValue[0].entityType == "team" && pOwnerValue[0].name == pTeamName;
    }
    return result;
}

function form_onSave(pContext) {
    var saveMode = pContext.getEventArgs().getSaveMode();
    if (saveMode == 1 || saveMode == 70) {
        var recordId = Xrm.Page.data.entity.getId();
        if (!!recordId) {
            //check user/team assignment selection and then evaluate business rules AGAIN.
            retrieveCurrentUserAndOwnerTeamsAndRoles(ExecuteBusinessRules);
        }
    }

    //set title to match reason for request
    var newTitle = setTitleField();
}

function setTitleField(pReasonForRequestValue) {
    var reasonForRequestValue = pReasonForRequestValue != undefined ? pReasonForRequestValue : Xrm.Page.getAttribute("ftp_reasonforrequest").getValue();
    if (!!reasonForRequestValue) {
        var cleanRFRId = cleanGUID(reasonForRequestValue[0].id);
        if (cleanRFRId == otherReasonForRequestGUID || cleanRFRId == multipleReasonsForRequestGUID) {
            Xrm.Page.getAttribute("title").setValue(Xrm.Page.getAttribute("ftp_otherreason").getValue());
            return Xrm.Page.getAttribute("ftp_otherreason").getValue();
        }
        else {
            if (!(Xrm.Page.getAttribute("ftp_grouped").getValue())) { //not sure what ftp_grouped is, but left it in there anyway
                Xrm.Page.getAttribute("title").setValue(reasonForRequestValue[0].name);
                return reasonForRequestValue[0].name;
            }
        }
    }
    else {
        return "";
    }
}

function updateTitleOnSaveWithOtherText() {
    //deprecated
    return;
    var reasonForRequest = Xrm.Page.getAttribute("ftp_reasonforrequest").getValue();
    var grouped = Xrm.Page.getAttribute("ftp_grouped").getValue();
    var reasonForRequestGuid;
    if (reasonForRequest != null) {
        reasonForRequestGuid = cleanGUID(reasonForRequest[0].id);
    }
    if (reasonForRequestGuid != null) {
        if (reasonForRequestGuid == "136db634-ee0d-e511-8108-00155d14711e" || reasonForRequest[0].name == "Multiple Reasons for Request") {
            Xrm.Page.getAttribute("title").setValue(Xrm.Page.getAttribute("ftp_otherreason").getValue());
        } else if (!grouped) {
            Xrm.Page.getAttribute("title").setValue(reasonForRequest[0].name);
        }
    }
}

function cleanGUID(guid) {
    return guid.replace(/[{}]/g, "").toLowerCase();
}

function collapseBusinessProcessBanner() {
    if (Xrm.Page.ui.process != null) {
        //Xrm.Page.ui.process.setDisplayState("collapsed");
        Xrm.Page.ui.process.setVisible(false);
    } else {
        setTimeout(collapseBusinessProcessBanner, 500);
    }
}

function hideRules() {
    //deprecated
    return false;
    try {
        var fType = Xrm.Page.ui.getFormType();
        var currentUser = Xrm.Page.context.getUserId();
        var SetName = "TeamMembershipSet";
        var filter = "SystemUserId";
        var cca = null;
        var pact = null;
        var tArray = [];
        var data = {};
        var d = {};

        var actionsTakenAtt = Xrm.Page.getAttribute("ftp_countofactionstaken_number");
        var aTaken = !!actionsTakenAtt ? Xrm.Page.getAttribute("ftp_countofactionstaken_number").getValue() : 0;

        var owner = Xrm.Page.getAttribute("ownerid").getValue();

        retrieveTeamsForUser(
			function (retrievedRecords) {
			    for (var i = 0, l = retrievedRecords.length; i < l; i++) {
			        var thisTeam = retrievedRecords[i];
			        if (thisTeam.Name == "PACT User" && !!aTaken && aTaken > 0 && (owner[0].name == "PACT User" || owner[0].id == currentUser)) Xrm.Page.getControl("ftp_resolved").setDisabled(false);
			        if (thisTeam.Name == "Pharmacy") {
			            Xrm.Page.getControl("ftp_iswarmtransfer").setVisible(true);
			            if (!!aTaken && aTaken > 2 && owner[0].id == currentUser) Xrm.Page.getControl("ftp_isresolved").setDisabled(false);
			        }
			    }
			}
		);
    }
    catch (e) {
        alert("Error in hideRules(): " + e);
    }
}

function hideActionTaken() {
    try {
        retrieveTeamsForUser(
			function (retrievedRecords) {
			    for (var i = 0, l = retrievedRecords.length; i < l; i++) {
			        var thisTeam = retrievedRecords[i];
			        if (thisTeam.Name == "CCA Team" || thisTeam.Name == "Pharmacy" || thisTeam.Name == "TAN") {
			            Xrm.Page.ui.tabs.get("tab_8").setVisible(false);
			        }
			        else if (thisTeam.Name == "PACT Team") {
			            Xrm.Page.ui.tabs.get("tab_8").setVisible(true);
			        }
			    }
			}
		);
    }
    catch (e) {
        alert("Error in hideActionTaken(): " + e);
    }
}

function ftp_priority_onChange() {
    //the ftp_downgradeexplanation_memo control is visible by default, and then hidden when not needed.
    //so fire this script onLoad and onChange of the ftp_priority attribute value
    //Do it this way because this multi-line text field acts weird if we hide it by default and then use script to show it
    var priorityAttr = Xrm.Page.getAttribute("ftp_priority");
    var downgradeMemoControl = Xrm.Page.getControl("ftp_downgradeexplanation_memo");
    if (!!downgradeMemoControl && !!priorityAttr) {
        var downgraded = priorityAttr.getValue() < priorityAttr.getInitialValue();
        var memoValue = downgradeMemoControl.getAttribute().getValue();

        //show the downgradeMemoControl to everyone if priority has been downgraded or if the memo already has a value
        downgradeMemoControl.setVisible(downgraded || !!memoValue);

        //require it if the user doing the downgrading is on the Pharmacy team
        downgradeMemoControl.getAttribute().setRequiredLevel(downgraded && userIsOnTeam("Pharmacy", currentUserDetails.teams) ? "required" : "none");
    }
}

function ftp_discusswithprovider_onChange() {
    var directionsByControl = Xrm.Page.getControl("ftp_directionsby");
    if (!!directionsByControl) {
        var require = Xrm.Page.getAttribute("ftp_discusswithprovider_bool").getValue() == true;
        var visible = require;
        directionsByControl.getAttribute().setRequiredLevel(require ? "required" : "none");
        directionsByControl.setVisible(visible);
    }
}

function saveHungUpInQueue() {
    //deprecated. merged into onLoad function
    return;
    try {
        Xrm.Page.getAttribute("ftp_ishungupinqueue_bool").setSubmitMode("always");
    }
    catch (e) {
        alert("There was an error saving the Hung Up In Queue status. Error:" + e);
    }
}

RetrieveMultipleEntitySync = function (EntitySetName, filter, Guid) {

    //This function will return a json object with every attribute from an entity for a single record synchronously 
    try {
        //Perform REST call
        var context = Xrm.Page.context;
        var serverUrl = context.getClientUrl();
        var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
        //Format Entity Guid
        var EntityIdnobracket = Guid.replace(/({|})/g, '');
        //Construct the JSON Query
        var selectString = "";
        if (filter !== "") { selectString = "?$filter=" + filter + " eq guid'" + EntityIdnobracket + "'"; }
        else { selectString = "(guid'" + EntityIdnobracket + "')?$select=*"; }

        var jsonQuery = serverUrl + ODATA_ENDPOINT + "/" + EntitySetName + selectString;

        //Initialize the return value
        var EntityData = null;
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: jsonQuery,
            beforeSend: function (XMLHttpRequest) {
                //Specifying this header ensures that the results will be returned as JSON.
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
            },
            success: function (data, textStatus, XmlHttpRequest) {
                //Get the data values
                EntityData = data;
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('Fail: Ajax Error in RetrieveMultipleEntitySync: ' + errorThrown);
            },
            async: false,
            cache: false
        });
        //Return the data result
        return EntityData;
    }
    catch (err) {
        //Display Error
        alert("An error occured in the RetrieveMultipleEntitySyncEntitySync function.  Error Detail Message: " + err);
    }
};

function retrieveActiveSettings(pCallbackFunction) {
    Xrm.Page.ui.clearFormNotification("WebServiceError");
    var retrievedRecords = [];
    var queryString = "$select=*&$filter=mcs_name eq 'Active Settings'";
    var retrievedSettings = null;
    SDK.REST.retrieveMultipleRecords(
		"mcs_setting",
		queryString,
		function (retrievedRecords) {
		    if (typeof retrievedRecords != "undefined" && !!retrievedRecords && retrievedRecords.length == 1) retrievedSettings = retrievedRecords[0];
		},
		errorHandler,
		function () {
		    if (!!retrievedSettings) {
		        _retrievedSettings = retrievedSettings;
		        if (typeof pCallbackFunction == "function") {
		            pCallbackFunction();
		        }
		        if (!(retrievedSettings.hasOwnProperty("ftp_DACURL")) || !retrievedSettings.ftp_DACURL) {
		            var msg = "Configuration error: Active Settings record is missing some URLs; contact your system administrator.";
		            Xrm.Utility.alertDialog(
						msg,
						function () {
						    Xrm.Page.ui.setFormNotification(msg, "ERROR", "WebServiceError");
						}
					);
		            return;
		        }
		    }
		    else {
		        Xrm.Utility.alertDialog(
					"Could not find Active Settings for this org; contact your system administrator.",
					function () {
					    Xrm.Page.ui.setFormNotification("Could not find Active Settings for this org; contact your system administrator", "ERROR", "WebServiceError");
					}
				);
		    }
		}
	);
}

function enableTriageButton() {
    var TANTeam = false;
    try {
        var user = Xrm.Page.context.getUserId();
        var SetName = "TeamMembershipSet";
        var filter = "SystemUserId";
        var tArray = [];
        var data = {};
        var d = {};
        data = RetrieveMultipleEntitySync(SetName, filter, user);
        for (i = 0; i < data.d.results.length; i++) {
            tArray.push(data.d.results[i].TeamId);
        }
        for (i = 0; i < tArray.length; i++) {
            d = RetrieveMultipleEntitySync("TeamSet", "", tArray[i]);
            // d = RetrieveAllAttributesByEntitySync("TeamSet", tArray[i]);
            if (d.d.Name === "TAN") {
                TANTeam = true;
            }
        }
    }
    catch (e) {
    }
    return TANTeam;
}

function retrieveTeamsForUser(CallBackParameter) {
    if (typeof CallBackParameter == "function") {
        var currentUserId = Xrm.Page.context.getUserId();
        var oDataPath = Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/";
        var query = "SystemUserSet(guid'" + currentUserId + "')/teammembership_association?$select=Name,TeamId";

        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: oDataPath + query,
            beforeSend: function (XMLHttpRequest) {
                //Specifying this header ensures that the results will be returned as JSON.
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
            },
            success: function (data, textStatus, XmlHttpRequest) {
                if (!!data) CallBackParameter(data.d.results);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Error retrieving teams for current user: " + errorThrown);
            },
            async: true,
            cache: false
        });
    }
    else {
        alert("Did not retrieve teams for current user.  CallBackParameter must be a function.");
        //CallBackParameter must be a function
    }
}

function writeToConsole(message) {
    if (typeof console != 'undefined') console.log(message);
}

function checkDirtyFields() {
    var msg = "Dirty fields since last save:";
    if (Xrm.Page.ui.getFormType() == 1) {
        msg += "\nIt's a new record...they're all dirty!";
    }
    else {
        var attributes = Xrm.Page.data.entity.attributes.get();
        for (var i in attributes) {
            if (attributes[i].getIsDirty()) msg += ("\n" + attributes[i].getName());
        }
    }
    alert(msg);
}
function getAge(pString) {
    var today = new Date();
    var birthDate = new Date(pString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}
function getDeepProperty(pPath, pObject) {
    if (!!pPath) {
        var pathAsArray = pPath.split(".");
        var returnObj = !!pObject ? pObject : window[pathAsArray.shift()];
        if (typeof returnObj != "undefined") {
            while (!!returnObj && pathAsArray.length > 0) {
                returnObj = returnObj[pathAsArray.shift()];
            }
            return returnObj;
        }
        else {
            return undefined;
        }
    }
    else {
        return undefined;
    }
}
function SortObjectArray(pSortProperty) {
    var sortOrder = 1;
    if (pSortProperty[0] === "-") {
        sortOrder = -1;
        pSortProperty = pSortProperty.substr(1);
    }
    return function (a, b) {
        var result = (a[pSortProperty] < b[pSortProperty]) ? -1 : (a[pSortProperty] > b[pSortProperty]) ? 1 : 0;
        return result * sortOrder;
    };
}