var _intervalVar = null;

function form_OnLoad() {
    if (Xrm.Page.ui.getFormType() != 1) { loadLOBForm(); }

    if (Xrm.Page.getAttribute("vhacrm_isassist_bool") != null) {
        Xrm.Page.getAttribute("vhacrm_isassist_bool").setSubmitMode("never");
    }

    if (Xrm.Page.getAttribute("vhacrm_dayssincelastcontact_text") != null) {
        Xrm.Page.getAttribute("vhacrm_dayssincelastcontact_text").setSubmitMode("always");
    }

    if (Xrm.Page.ui.getFormType() == 4) {
        Xrm.Page.getControl("WebResource_CompleteInteraction").setVisible(false);
        Xrm.Page.getControl("WebResource_completecasenote").setVisible(false);
        Xrm.Page.getControl("WebResource_mvisearch").setVisible(false);
    }

    //show Call Source
    showCallSource();

    //show and hide sections according to type
    checkType();
    checkResolution();

    //check for subareas and templates asynchronously
    checkSubareas();
    //checkTemplates();


    //load ESR, VISTA web parts
    loadWebParts();
}

function form_OnSave(context) {
    preventAutoSave(context);
}

function firstname_OnChange() { refresh.firstname_OnChange(); }

function lastname_OnChange() { refresh.lastname_OnChange(); }

function dob_OnChange() { refresh.dob_OnChange(); }

function ssn_OnChange() { refresh.ssn_OnChange(); }

function edipi_OnChange() { refresh.edipi_OnChange(); }

function gender_OnChange() { refresh.gender_OnChange(); }

function daytimePhone_OnChange() { refresh.daytimePhone_OnChange(); }

function interactionno_OnChange(context) {
    if (Xrm.Page.getAttribute("vhacrm_interactionno_text").getValue()) {
        Xrm.Page.ui.tabs.get("tab_veteransearch").setDisplayState("expanded");
        //refresh.standard_call();
    }
    //else {
    // Xrm.Page.ui.tabs.get("tab_veteransearch").setDisplayState("collapsed");
    // }
}

function type_OnChange(context) {
    Xrm.Page.getAttribute("vhacrm_areaintersectionid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_subareaintersectionid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_resolutionintersectionid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_casenotetemplateid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_subareaintersectionid").setRequiredLevel("none");
    Xrm.Page.getAttribute("vhacrm_casenotetemplateid").setRequiredLevel("none");
    Xrm.Page.getAttribute("vhacrm_callsourceid").setRequiredLevel("none");
    Xrm.Page.getAttribute("vhacrm_assist_casenotetemplateid").setValue(null);
    N52.Clientside.ExecuteFormulas(context, 'yR9');
}

function callSource_OnChange(context) {
    Xrm.Page.data.entity.save();
}

function interactionType_OnChange(context) {
    showCallSource();
    checkType();
}

function showCallSource() {
    var callSource = Xrm.Page.getAttribute("vhacrm_callsourceid").controls;
    callSource.forEach(function (control) {
        control.setVisible(true);
    });
}

function checkType() {
    //show and hide sections according to type
    typeValue = Xrm.Page.getAttribute("vhacrm_typeintersectionid").getValue();
    if (typeValue) {
        if (typeValue[0].name == "EVH") {
            Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_general").setVisible(true);
            Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_assessment").setVisible(false);
            Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_generalhomeless").setVisible(false);
            Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_consulttype").setVisible(false);
        }
        else {
            Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_general").setVisible(false);
            Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_assessment").setVisible(true);
            Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_generalhomeless").setVisible(true);
            Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_consulttype").setVisible(true);
        }
    }
    else {
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_general").setVisible(false);
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_assessment").setVisible(true);
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_generalhomeless").setVisible(true);
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_consulttype").setVisible(true);
    }
}

function checkVeteran() {
    //show and hide sections according to veteran
    var vetValue = Xrm.Page.getAttribute("bah_veteranid").getValue();
    if (vetValue) {
        switch (vetValue[0].name) {
            case "No Veteran":
                Xrm.Page.getAttribute("bah_veteranid").setValue(null);
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo").setVisible(false);
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veterancontact").setVisible(false);
                Xrm.Page.ui.tabs.get("tab_History").setDisplayState("collapsed");
            case "Anonymous":
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo_input").setVisible(false);
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo").setVisible(false);
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veterancontact").setVisible(false);
                Xrm.Page.ui.tabs.get("tab_History").setDisplayState("collapsed");
            case "":
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo_input").setVisible(true);
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo").setVisible(false);
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veterancontact").setVisible(false);
                Xrm.Page.ui.tabs.get("tab_veteransearch").setDisplayState("expanded");
                Xrm.Page.ui.tabs.get("tab_History").setDisplayState("collapsed");
            default:
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo_input").setVisible(false);
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo").setVisible(true);
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veterancontact").setVisible(true);
                Xrm.Page.ui.tabs.get("tab_History").setDisplayState("expanded");
                Xrm.Page.ui.tabs.get("tab_veteransearch").setDisplayState("expanded");
        }
    }
    else {
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo_input").setVisible(true);
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo").setVisible(false);
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veterancontact").setVisible(false);
        if (Xrm.Page.getAttribute("vhacrm_interactionno_text").getValue()) {
            Xrm.Page.ui.tabs.get("tab_veteransearch").setDisplayState("expanded");
        }
        //else {
        // Xrm.Page.ui.tabs.get("tab_veteransearch").setDisplayState("collapsed")
        //}
        Xrm.Page.ui.tabs.get("tab_History").setDisplayState("collapsed");
    }
}

function area_OnChange(context) {
    Xrm.Page.getAttribute("vhacrm_casenotetemplateid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_casenotetemplateid").setRequiredLevel("none");

    checkSubareas();
    checkTemplates();
}

function resolution_OnChange(context) {
    Xrm.Page.data.save().then(checkResolution(), function (err) { alert(err); });
}

function checkResolution() {
    if (Xrm.Page.getAttribute("vhacrm_resolutionintersectionid").getValue()) {
        //when Resolution is changed to 'Disconnected Call, set the fields to not required 
        if (Xrm.Page.getAttribute("vhacrm_resolutionintersectionid").getValue()[0].name == "Disconnected Call") {
            Xrm.Page.getAttribute("vhacrm_casenotetemplateid").setRequiredLevel("none");
            Xrm.Page.getAttribute("vhacrm_callsourceid").setRequiredLevel("none");
            Xrm.Page.getAttribute("vhacrm_areaintersectionid").setRequiredLevel("none");
            //clear required notifications
            Xrm.Page.getControl("vhacrm_callsourceid").clearNotification();
            Xrm.Page.getControl("vhacrm_areaintersectionid").clearNotification();
            Xrm.Page.getControl("vhacrm_casenotetemplateid").clearNotification();
        }
        else {
            Xrm.Page.getAttribute("vhacrm_callsourceid").setRequiredLevel("required");
            Xrm.Page.getAttribute("vhacrm_areaintersectionid").setRequiredLevel("required");
        }
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_complete").setVisible(true);
    }
    else {
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_complete").setVisible(false);
    }
}

function caseNoteTemplate_OnChange(context) {
    appendTemplateText();
}

function loadWebParts() {
    unattendedSearchFromRelatedRecord("bah_veteranid", loadAssociations, loadESRWebParts);
    checkVeteran();
}

function loadAssociations(icn) {
    displayWebPart(icn, 'IFRAME_associations', 'esr_associations_endpoint');
}

function loadESRWebParts(icn) {
    //pass icn, folder path and list of control names/resource names to the loadEsrResources function
    loadEsrResources(icn, '/webresources/vhacrm_/ESRParts', 'WebResource_enrollment|enrollment.htm,WebResource_esreligibility|eligibility.htm,WebResource_demographics|demographics.htm');
}
// If there is only one Sub Area, make it the default
function checkSubareas() {
    var areaintersectionid = Xrm.Page.getAttribute("vhacrm_areaintersectionid").getValue();
    if (areaintersectionid) {
        var oDataSetName = "vhacrm_subareaintersection";
        var filter = "vhacrm_areaintersectionid/Id eq (guid'" + areaintersectionid[0].id.toString() + "') and statecode/Value eq 0";
        var columns = "*";
        var querystring = "$select=" + columns + "&$filter=" + filter;
        SDK.REST.retrieveMultipleRecords(
			oDataSetName,
			querystring,
			function (data) {
			    if (data.length > 0) {
			        Xrm.Page.getAttribute('vhacrm_subareaintersectionid').setRequiredLevel('required');
			    }
			    else {
			        Xrm.Page.getAttribute('vhacrm_subareaintersectionid').setRequiredLevel('none');
			    }
			},
			function (error) {
			    alert(error);
			    //do nothing
			},
			function () {
			    //do nothing on completion
			}
		);
    }
}

// If there is only one Case Note Template, make it the default
function checkTemplates() {
    var areaintersectionid = Xrm.Page.getAttribute("vhacrm_areaintersectionid").getValue();
    var existingcasenotetext = Xrm.Page.getAttribute("vhacrm_casenotes_memo").getValue();
    var casenotetemplateid = Xrm.Page.getAttribute('vhacrm_casenotetemplateid').getValue();
    if (areaintersectionid) {
        if (areaintersectionid[0].id.toString() == "{D165CC8A-6E06-E611-811E-127B25DCBDE7}") {
            // Urgent Area, so apply Urgent template
            var oDataSetName = "vhacrm_casenotetemplate";
            var filter = "vhacrm_casenotetemplateId eq (guid'2631CA03-2E1D-E611-811F-127B25DCBDE7')";
            var columns = "*";
            var querystring = "$select=" + columns + "&$filter=" + filter;
            SDK.REST.retrieveMultipleRecords(
                oDataSetName,
                querystring,
                function (data) {
                    if (data.length > 0) {
                        var lookupReference = [];
                        lookupReference[0] = {};
                        lookupReference[0].id = data[0].vhacrm_casenotetemplateId;
                        lookupReference[0].entityType = 'vhacrm_casenotetemplate';
                        lookupReference[0].name = data[0].vhacrm_name;

                        Xrm.Page.getAttribute("vhacrm_casenotetemplateid").setValue(lookupReference);
                        Xrm.Page.getAttribute("vhacrm_casenotes_memo").setValue(data[0].vhacrm_template_memo);
                        Xrm.Page.getAttribute('vhacrm_casenotetemplateid').setRequiredLevel('required');
                        Xrm.Page.getAttribute("vhacrm_temp_text").setValue(null);
                    }
                    else {
                        Xrm.Page.getAttribute('vhacrm_casenotetemplateid').setRequiredLevel('none');
                        Xrm.Page.getAttribute('vhacrm_casenotes_memo').setRequiredLevel('none');
                    }
                },
                function (error) {
                    //do nothing
                    alert(error);
                },
                function () {
                    //do nothing on completion
                }
            );
        }
        else {
            var currenttemplate = Xrm.Page.getAttribute("vhacrm_casenotetemplateid").getValue();
            var oDataSetName = "vhacrm_casenotetemplate";
            var filter = "vhacrm_areaintersectionid/Id eq (guid'" + areaintersectionid[0].id.toString() + "') and statecode/Value eq 0";
            var columns = "*";

            var querystring = "$select=" + columns + "&$filter=" + filter;
            SDK.REST.retrieveMultipleRecords(
                oDataSetName,
                querystring,
                function (data) {
                    if (data.length > 0) {
                        Xrm.Page.getAttribute('vhacrm_casenotetemplateid').setRequiredLevel('required');
                        if (data.length == 1) {
                            var lookupReference = [];
                            lookupReference[0] = {};
                            lookupReference[0].id = data[0].vhacrm_casenotetemplateId;
                            lookupReference[0].entityType = 'vhacrm_casenotetemplate';
                            lookupReference[0].name = data[0].vhacrm_name;

                            if (lookupReference != currenttemplate) {
                                Xrm.Page.getAttribute("vhacrm_casenotetemplateid").setValue(lookupReference);

                                var casenotetext = data[0].vhacrm_template_memo;
                                var existingcasenotetext = Xrm.Page.getAttribute("vhacrm_casenotes_memo").getValue();
                                if (casenotetext) {
                                    if (existingcasenotetext) {
                                        casenotetext = existingcasenotetext + "\r\n------------\r\n" + casenotetext;
                                        Xrm.Page.getAttribute("vhacrm_casenotes_memo").setValue(casenotetext);
                                    }
                                    else {
                                        Xrm.Page.getAttribute("vhacrm_casenotes_memo").setValue(casenotetext);
                                    }
                                }
                            }
                        }
                        Xrm.Page.getAttribute("vhacrm_temp_text").setValue(null);
                    }
                    else {
                        Xrm.Page.getAttribute('vhacrm_casenotetemplateid').setRequiredLevel('none');
                        Xrm.Page.getAttribute('vhacrm_casenotes_memo').setRequiredLevel('none');
                    }
                },
                function (error) {
                    //do nothing
                    alert(error);
                },
                function () {
                    //do nothing on completion
                }
            );
        }
    }
}

function appendTemplateText() {
    var templateid = Xrm.Page.getAttribute("vhacrm_casenotetemplateid").getValue();
    var existingcasenotetext = Xrm.Page.getAttribute("vhacrm_casenotes_memo").getValue();

    if (templateid) {
        SDK.REST.retrieveRecord(
			templateid[0].id.toString(),
			"vhacrm_casenotetemplate",
			"vhacrm_template_memo",
			null,
			function (data) {
			    var casenotetext = data.vhacrm_template_memo;
			    if (casenotetext) {
			        if (existingcasenotetext) {
			            casenotetext = existingcasenotetext + "\r\n------------\r\n" + casenotetext;
			        }
			        Xrm.Page.getAttribute("vhacrm_casenotes_memo").setValue(casenotetext);
			    }
			    Xrm.Page.getAttribute("vhacrm_temp_text").setValue(null);
			},
			function (error) {
			    //do nothing
			    alert(error);
			}
		);
    }
}
