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 () {
            Xrm.Page.getAttribute("vhacrm_previousfacilityid").setValue(Xrm.Page.getAttribute("vhacrm_facilityid").getValue());
            Xrm.Page.data.entity.save();
            // Load Locations
            getLocations()
        },

        function () {
            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();
    switch (notetype) {
        case 713770001:  // Historical
            // 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
            Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_vistanote").setVisible(true);
            break;

        case 713770002:  // 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
            Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_vistanote").setVisible(true);
            break;

        default:
            // Hide login & additional case note information
            Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_vistalogin").setVisible(false);
            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);
            break;
    }
}

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 writeNoteResult(serviceResult) {
    //alert(serviceResult);
    $.each(serviceResult, function (index, item) {
        //$('#ipResult').val($('#ipResult').val() +
        //"error= " + item.error.toString() +
        //" id= " + item.id.toString() +
        //" totalpages= " + item.totalpages.toString() + ' \n');

        if (item.error !== "" && item.error !== null) {
            //Handle Errors
            alert(item.error + "\n" + item.fault);
        } else {
            //Success
            Xrm.Page.getAttribute("vhacrm_vistacasenoteid_text").setValue(item.id.toString());
            alert("Case Note added successfully: " + item.id.toString());
        }

    });
}

function getLocations() {
    //Check if VIA Login cookie exist (not expired)
    var userTO = vlc_getCookie("viasessionlink");
    if (userTO == null) {
        //Show Vista Login section and exit if cookie exist
        Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_vistalogin").setVisible(true);
        var loggedin = false;
        alert("You must login to VISTA. Please enter your Access Code and Verify Code.");
        return false;

    } else {
        var apiName = "getLocations";
        var target = "*"; //document.getElementById("ipLocation").value;

        try {
            if (target !== null && userTO !== null) {
                VIAServices.getLocations(userTO, target, getLocations_Result);
            } else {
                alert("All fields must be filled out, please try again.");
            }
        } catch (err) {
            alert(apiName.value + ': ' + err.value);
        }
    }
}
