<html><head><title>Button</title>
<script src="../../ClientGlobalContext.js.aspx" type="text/javascript"></script>
<script src="../../bah_jquery1.4.1.min.js" type="text/javascript"></script>
<script src="../../bah_SDK.REST.js" type="text/javascript"></script> 
<script src="../../vhacrm_/via/vhacrm_via_library.js" type="text/javascript"></script> 
<style type="text/css">
html, body{ height: 100%; overflow: auto;  border-width: 0px; }
body {  padding: 0;  margin: 0;  }
table.stdTable { width: 100%; height: 100%; border: 0px; background-color: White; font-family: Segoe UI,Tahoma,Arial; font-size:12px; }
</style>

<script type="text/javascript">

    if (typeof (VIACompleteNoteButton) === "undefined") {
        VIACompleteNoteButton = { __namespace: true };
    }
    //Static Variables
    var vlc_UserSiteId = '';
    var vlc_UserSiteNo = '';

    var userTO;
    var arrayPatientTO = [];
    var patientTO;
    var arrayVisitTO = [];
   
    $(document).ready(function () {
        if (typeof (VIAServices) === "undefined") {
            VIAServices = { __namespace: true };
        }

        VIACompleteNoteButton.Initialize();
       
        consumingApp = new AppInfo();
        consumingApp.name = via_getCookie("viasessionappname");
        consumingApp.token = via_getCookie("viasessionapptoken");
        consumingApp.password = via_getCookie("viasessionapppass");
        consumingApp.notetitleid = via_getCookie("viasessionnotetitleid");
        consumingApp.url = via_getCookie("viasessionappurl");
    });

    VIACompleteNoteButton.Click = function () {

        document.getElementById("notebutton").disabled = true;
        document.getElementById("notebutton").textContent = "In-Progress...";

        // check for required fields, if not, alert (and reset button)        
        if (VIACompleteNoteButton.CheckRequiredFields()) {
            VIACompleteNoteButton.CompleteNote();
        }
        else {
            document.getElementById("notebutton").disabled = false;
            document.getElementById("notebutton").textContent = VIACompleteNoteButton.GetButtonDescription();
        }
    }

    VIACompleteNoteButton.CheckRequiredFields = function () {

        //Check if user is logged into Vista
        userTO = getLoggedInUser()
        if (userTO == null) {
            //Show Vista Login section and exit if cookie exist
            parent.Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_vistalogin").setVisible(true);
            alert("You must login to VISTA. Please enter your Access Code and Verify Code.");
            return false;
        }

        //Check for case notes
        var casenote = parent.Xrm.Page.getAttribute("vhacrm_casenotes_memo").getValue();
        if (casenote == "") {
            parent.Xrm.Page.ui.setFormNotification("Case Note is required.", "ERROR", "CaseNoteReq");
            return false;
        }

        //Check for Location
        var facilitylocation = parent.Xrm.Page.getAttribute("vhacrm_vistalocationid_text").getValue();
        if (facilitylocation != null) {
            parent.Xrm.Page.ui.clearFormNotification("LocationReq");
            return true;
        }
        else {
            // Check to see if Location dropdown is empty
            if ($("#ddLocation :selected").length == 0) {
                // Populate Location dropdown
                via_getLocations(getLocations_Result);
            }

            parent.Xrm.Page.ui.setFormNotification("Location is required.", "ERROR", "LocationReq");
            return false;
        }

        // Check for Veteran
        var veteranId = parent.Xrm.Page.getAttribute("customerid").getValue();
        if (veteranId == "") {
            parent.Xrm.Page.ui.setFormNotification("Veteran is required.", "ERROR", "VeteranReq");
            return false;
        }
        else {
            via_getVeteran(veteranId);
            return true;
        }

    }

    VIACompleteNoteButton.CompleteNote = function () {
        try {

            //Check if user is logged into Vista
            userTO = getLoggedInUser()
            if (userTO == null) {
                //Show Vista Login section and exit if cookie exist
                parent.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;
            }

            // Check for Historical or Workload Note
            var notetype = parent.Xrm.Page.getAttribute("vhacrm_notetype_code").getValue();
            if (notetype == "713770001") {  // Historical
                var apiName = "writeNote";
                var content = parent.Xrm.Page.getAttribute("vhacrm_casenotes_memo").getValue();
                var titleId = consumingApp.notetitleid;
                var locationId = parent.Xrm.Page.getAttribute("vhacrm_vistalocationid_text").getValue();

                //Build encounter string
                var encounterString = BuildEncounterString("Y", locationId);

                //Get Veteran info
                var localPid = parent.Xrm.Page.getAttribute("vhacrm_vistaveteranid_text").getValue();
                if (localPid == null) {
                    alert("You must associate a Veteran to the Request prior to writing a note to VISTA.");
                    return false;
                }

                // Write Note
                VIAServices.writeNote(userTO, localPid, titleId, encounterString, content, writeNote_Result);
            }

        } catch (err) {
            alert('Error occurred WriteNote: ' + err.message);
        }

        document.getElementById("notebutton").disabled = false;
        VIACompleteNoteButton.Initialize();
    }

    VIACompleteNoteButton.GetQuerystring = function (e) {
        var t = e.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var n = new RegExp("[\\?&]" + t + "=([^&#]*)");

        var r = n.exec(window.location.href);

        if (r == null)
            return null;

        return r[1]
    }

    VIACompleteNoteButton.GetButtonDescription = function () {
        var e = VIACompleteNoteButton.GetQuerystring("data");
        var t = decodeURIComponent(e);
        var n = t.split("|");

        return n[1];
    }

    VIACompleteNoteButton.GetButtonStyle = function () {
        var e = VIACompleteNoteButton.GetQuerystring("data");
        var t = decodeURIComponent(e);
        var n = t.split("|");

        return n[2];
    }

    VIACompleteNoteButton.Initialize = function () {
        var buttonDescription = VIACompleteNoteButton.GetButtonDescription();
        var buttonStyle = VIACompleteNoteButton.GetButtonStyle();

        document.title = buttonDescription;
        document.getElementById("notebutton").textContent = buttonDescription;
        document.getElementById("notebutton").className = buttonStyle;

    }

    function getLoggedInUser() {
        var cookieUser = via_getCookie("viasessionlink");
        //Check to see if User is logged in
        if (cookieUser == null) {
            //Show Vista Login section and exit if cookie exist
            parent.Xrm.Page.ui.tabs.get("tab_general").sections.get("tab_general_section_vistalogin").setVisible(true);
            alert("You must login to VISTA. Please enter your Access Code and Verify Code.");
            return cookieUser;
        }
        else {
            return cookieUser;
        }
    }

    function getLocations_Result(serviceResult) {
        try {
            if (serviceResult.length > 0) {

                $.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));
                    }
                });
            }
        } catch (err) {
            alert("getLocations_Result: " + err.message);
        }
    }

    function writeNote_Result(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
                parent.Xrm.Page.getAttribute("vhacrm_vistacasenoteid_text").setValue(item.id.toString());
                alert("Case Note added successfully to VISTA"); //: " + item.id.toString());
            }
        });
    }

</script>
<meta charset="utf-8"><meta><meta><meta></head>
<body style="-ms-word-wrap: break-word;">
    <table class="stdTable">
        <tbody><tr>
            <td style="width: 120px;">Location:</td>
            <td><select id="ddLocation" style="width: 300px;" onchange="selectLocation(this.options[this.selectedIndex])"></select></td>
        </tr>
        <tr>
            <td colspan="2"><button id="notebutton" onclick="VIACompleteNoteButton.Click();" type="button">Send Note to VISTA</button></td>
        </tr>
    </tbody></table>

</body></html>