function form_OnLoad() {
    if (Xrm.Page.ui.getFormType() != 1) { loadLOBForm(); }
    Xrm.Page.getAttribute("vhacrm_previousfacilityid").setValue(Xrm.Page.getAttribute("vhacrm_facilityid").getValue());


    if (Xrm.Page.ui.getFormType() == 4) {
        Xrm.Page.getControl("WebResource_CreateCorrespondence").setVisible(false);
        Xrm.Page.getControl("WebResource_completenotes").setVisible(false);
    }

    loadWebParts();
}


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

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");
}

function area_OnChange(context) {
    Xrm.Page.data.entity.save();
    Xrm.Page.getAttribute("vhacrm_subareaintersectionid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_casenotetemplateid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_subareaintersectionid").setRequiredLevel("none");
    N52.Clientside.ExecuteFormulas(context, 'Q5i');
}

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

function caseNoteTemplate_OnChange(context) {
    N52.Clientside.ExecuteFormulas(context, 'lSq');
    Xrm.Page.data.entity.save();
}

function facility_OnChange() {
    Xrm.Utility.confirmDialog("Are you sure you want to change the facility?",
        function () { //YES
            // Set Previous Facility Lookup to new Facility
            Xrm.Page.getAttribute("vhacrm_previousfacilityid").setValue(Xrm.Page.getAttribute("vhacrm_facilityid").getValue());
            // Clear Note Type and Vista Location 
            Xrm.Page.getAttribute("vhacrm_notetype_code").setValue(null);
            Xrm.Page.getAttribute("vhacrm_vistalocationid_text").setValue(null);
            Xrm.Page.getAttribute("vhacrm_vistalocationname_text").setValue(null);

            // Trigger email notification to new Facility
            Xrm.Page.data.entity.save();
        },

        function () { //NO
            // Set Facility back to previous facility
            Xrm.Page.getAttribute("vhacrm_facilityid").setValue(Xrm.Page.getAttribute("vhacrm_previousfacilityid").getValue());
            return false;
        }
    );

}

function noteType_OnChange() {
    // Check for Historical Note
    var notetype = Xrm.Page.getAttribute("vhacrm_notetype_code").getValue();
    if (notetype == "713770001" || notetype =="713770002") {  // Historical or Workload
        // Hide CRM Case Note button
        Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_crmnote").setVisible(false);

        // Check login & show additional fields required for writing note to Vista
        if (via_checkUserLogIn()) {
            // Get Vista Facility Locations
            via_getLocations(getLocations_Result);
            // Get Vista Veteran Id
            var veteranId = Xrm.Page.getAttribute("customerid").getValue();
            if (veteranId) {
                via_getVeteran(veteranId, getVeteran_Result);
            }
        }
        else {
            showVistaLogin();
        }
    }
    else {
        // Hide login & additional case note information
        hideVistaLogin();
        Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_vistanote").setVisible(false);

        // Show CRM Case Note button
        Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_crmnote").setVisible(true);
    }
}

function loadWebParts() {
    unattendedSearchFromRelatedRecord("customerid", loadCaseNotes, loadAssociations, loadESRWebParts);
}

function loadCaseNotes(icn) {
    displayWebPart(icn, 'IFRAME_cprscasenotes', 'hdr_notes_endpoint');
}

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_esrenrollment|enrollment.htm,WebResource_esreligibility|eligibility.htm,WebResource_esrdemographics|demographics.htm');
}

function hideVistaLogin() {
    //Hide the login section
    Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_vistalogin").setVisible(false);
}

function showVistaLogin() {
    //Show the login section
    Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_vistalogin").setVisible(true);
    //Set focus to the login control
    Xrm.Page.getControl("WebResource_VistaLoginControl").setFocus();
    return false;
}

function getLocations_Result(serviceResult) {
    try {
        if (serviceResult.length > 0) {
            var ddLocations = Xrm.Page.getcontrol('WebResource_VistaWriteNoteControl').getObject().contentWindow.document.getElementById('ddLocation');

            $.each(serviceResult, function (index, item) {
                if (item.error !== "" && item.error !== null) {
                    //Handle Errors
                    alert(item.error + "\n" + item.fault);
                } else {
                    //Success
                    //$('#ddLocation').append($("<option />").val(item.id).text(item.name));
                    ddLocations.add(new Option(item.name,item.id));
                }
            });
        }
    } catch (err) {
        alert("getLocations_Result: " + err.message);
    }
}

function getVeteran_Result(serviceResult) {
    arrayPatientTO = serviceResult;
    patientTO = arrayPatientTO[0];
    // Set Vista Veteran fields
    Xrm.Page.getAttribute("vhacrm_vistaveteranid_text").setValue(patientTO.localpid);
    Xrm.Page.getAttribute("vhacrm_vistaveteranname_text").setValue(patientTO.patientname);
}