﻿//ViaServiceLibrary.js
//Contains functions that interact with the VIA Services

var vialib_soapHeaderStartText = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' " +
							  "xmlns:ser='http://DNS        .URL       /'><soapenv:Header/><soapenv:Body>";
var vialib_soapHeaderEndText = "</soapenv:Body></soapenv:Envelope>";

function vialib_loginVIA(vialib_requestingApp, vialib_consumingAppToken, vialib_consumingAppPassword, vialib_baseServiceEndpointUrl, vialib_accessCode, vialib_verifyCode, vialib_siteCode, vialib_responseCallback) {
    //This function is used to perform a login to VIA and returns an object containing the DUZ/Token and Full Name plus other data
    //vialib_requestingApp: This is the VIA Application Code
    //vialib_consumingAppToken: This is the VIA Application Token
    //vialib_consumingAppPassword: This is the VIA Application Password
    //vialib_baseServiceEndpointUrl: Thist is the VIA Service URL
    //vialib_accessCode: This is the VIA/VistA UserId
    //vialib_verifyCode: This is the VIA/VistA Password
    //vialib_siteCode: This is the Facility Number/Id e.g. 516 representing the facility the VIA/VistA user belongs to
    //vialib_responseCallback: This is the name of the function to return the query result to

    //Return Values:
    //1. error text (null when no error)
    //2. the VIA Service data object returned (null when error occured)

    try {
        //Construct Login Soap message
        var vialib_soapMessage = vialib_soapHeaderStartText + "<ser:loginVIA>" + "<queryBean>" +
            "<requestingApp>" + vialib_encodeString(vialib_requestingApp) + "</requestingApp>" +
			"<consumingAppToken>" + vialib_encodeString(vialib_consumingAppToken) + "</consumingAppToken>" +
			"<consumingAppPassword>" + vialib_encodeString(vialib_consumingAppPassword) + "</consumingAppPassword>" + "</queryBean>" +
            "<accessCode>" + vialib_encodeString(vialib_accessCode) + "</accessCode>" +
			"<verifyCode>" + vialib_encodeString(vialib_verifyCode) + "</verifyCode>" +
            "<siteCode>" + vialib_siteCode + "</siteCode>" +
            "</ser:loginVIA>" + vialib_soapHeaderEndText;

        //Call VIA Services
        var vialib_loginResponse = null;
        $.ajax({
            url: vialib_baseServiceEndpointUrl + "/EmrService",
            type: "POST",
            datatype: "xml",
            data: vialib_soapMessage,
            contentType: "text/xml; charset=\'utf-8'",
            dataType: "xml",
            success: function (data) {
                vialib_loginResponse = data;
                vialib_responseCallback(null, vialib_loginResponse);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //System Error
                vialib_responseCallback(textStatus, errorThrown.message);
            },
            async: false,
            cache: false
        });
    }
    catch (err) {
        //Return function error to callback function
        vialib_responseCallback("ViaServiceLibrary.js Function Error(vialib_loginVIA): " + err.message, null);
    }
}

function vialib_getNoteTitles(vialib_requestingApp, vialib_consumingAppToken, vialib_consumingAppPassword, vialib_baseServiceEndpointUrl, vialib_providerName, vialib_Duz, vialib_loginSiteCode, vialib_Target, vialib_Direction, vialib_responseCallback, vialib_externalObject) {
    //This function is used to retrieve VIA Note Titles, used in the Notes Write process
    //vialib_requestingApp: This is the VIA Application Code
    //vialib_consumingAppToken: This is the VIA Application Token
    //vialib_consumingAppPassword: This is the VIA Application Password
    //vialib_baseServiceEndpointUrl: Thist is the VIA Service URL
    //vialib_providerName: This is the full VIA/VistA username as returned by the loginVIA service
    //vialib_Duz: This is the VIA session/token as returned by the loginVIA service
    //vialib_loginSiteCode: This is the facility id e.g. 516 as a text string
    //vialib_Target: This is the search parameter leave as blank for all or a single letter for note titles starting with that letter
    //vialib_Direction: This is the sort order 1=ASC -1=DESC
    //vialib_responseCallback: This is the name of the function to return the query result to
    //vialib_externalObject: This is an external object not used by this function. This object can be returned to the response function if needed

    //Return Values:
    //1. error text (null when no error)
    //2. the VIA Service data object returned (null when error occured)
    //3. the externalObject

    try {
        //Construct getNoteTitles Soap message
        var vialib_soapMessage = vialib_soapHeaderStartText + "<ser:getNoteTitles>" + "<queryBean>" +
            "<requestingApp>" + vialib_encodeString(vialib_requestingApp) + "</requestingApp>" +
			"<consumingAppToken>" + vialib_encodeString(vialib_consumingAppToken) + "</consumingAppToken>" +
			"<consumingAppPassword>" + vialib_encodeString(vialib_consumingAppPassword) + "</consumingAppPassword>" + 
            "<provider>" + "<name>" + vialib_encodeString(vialib_providerName) + "</name>" + "<loginSiteCode>" + vialib_loginSiteCode + "</loginSiteCode>" +
            "<userId>" + vialib_encodeString(vialib_Duz) + "</userId>" + "</provider>" +
            "<target>" + encodeURIComponent(vialib_Target) + "</target>" + "<direction>" + vialib_Direction + "</direction>" + "</queryBean>" +
            "</ser:getNoteTitles>" + vialib_soapHeaderEndText;

        //Call VIA Services
        var vialib_notetitlesResponse = null;
        $.ajax({
            url: vialib_baseServiceEndpointUrl + "/EmrService",
            type: "POST",
            datatype: "xml",
            data: vialib_soapMessage,
            contentType: "text/xml; charset=\'utf-8'",
            dataType: "xml",
            success: function (data) {
                vialib_notetitlesResponse = data;
                vialib_responseCallback(null, vialib_notetitlesResponse, vialib_externalObject);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //System Error
                vialib_responseCallback(textStatus, errorThrown.message, vialib_externalObject);
            },
            async: true,
            cache: false
        });
    }
    catch (err) {
        //Return function error to callback function
        vialib_responseCallback("ViaServiceLibrary.js Function Error(vialib_getNoteTitles): " + err.message, null, vialib_externalObject);
    }
}

function vialib_getLocations(vialib_requestingApp, vialib_consumingAppToken, vialib_consumingAppPassword, vialib_baseServiceEndpointUrl, vialib_providerName, vialib_Duz, vialib_loginSiteCode, vialib_Target, vialib_Direction, vialib_responseCallback, vialib_externalObject) {
    //This function is used to retrieve VIA Locations, used in the Notes Write process
    //vialib_requestingApp: This is the VIA Application Code
    //vialib_consumingAppToken: This is the VIA Application Token
    //vialib_consumingAppPassword: This is the VIA Application Password
    //vialib_baseServiceEndpointUrl: Thist is the VIA Service URL
    //vialib_providerName: This is the full VIA/VistA username as returned by the loginVIA service
    //vialib_Duz: This is the VIA session/token as returned by the loginVIA service
    //vialib_loginSiteCode: This is the facility id e.g. 516 as a text string
    //vialib_Target: This is the search parameter leave as blank for all or a single letter for note titles starting with that letter
    //vialib_Direction: This is the sort order 1=ASC -1=DESC
    //vialib_responseCallback: This is the name of the function to return the query result to
    //vialib_externalObject: This is an external object not used by this function. This object can be returned to the response function if needed

    //Return Values:
    //1. error text (null when no error)
    //2. the VIA Service data object returned (null when error occured)
    //3. the externalObject

    try {
        //Construct getLocations Soap message
        var vialib_soapMessage = vialib_soapHeaderStartText + "<ser:getLocations>" + "<queryBean>" +
            "<requestingApp>" + vialib_encodeString(vialib_requestingApp) + "</requestingApp>" +
			"<consumingAppToken>" + vialib_encodeString(vialib_consumingAppToken) + "</consumingAppToken>" +
			"<consumingAppPassword>" + vialib_encodeString(vialib_consumingAppPassword) + "</consumingAppPassword>" +
            "<provider>" + "<name>" + vialib_encodeString(vialib_providerName) + "</name>" + "<loginSiteCode>" + vialib_loginSiteCode + "</loginSiteCode>" +
            "<userId>" + vialib_encodeString(vialib_Duz) + "</userId>" + "</provider>" +
            "<target>" + encodeURIComponent(vialib_Target) + "</target>" + "<direction>" + vialib_Direction + "</direction>" + "</queryBean>" +
            "</ser:getLocations>" + vialib_soapHeaderEndText;

        //Call VIA Services
        var vialib_locationsResponse = null;
        $.ajax({
            url: vialib_baseServiceEndpointUrl + "/EmrService",
            type: "POST",
            datatype: "xml",
            data: vialib_soapMessage,
            contentType: "text/xml; charset=\'utf-8'",
            dataType: "xml",
            success: function (data) {
                vialib_locationsResponse = data;
                vialib_responseCallback(null, vialib_locationsResponse, vialib_externalObject);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //System Error
                vialib_responseCallback(textStatus, errorThrown.message, vialib_externalObject);
            },
            async: true,
            cache: false
        });
    }
    catch (err) {
        //Return function error to callback function
        vialib_responseCallback("ViaServiceLibrary.js Function Error(vialib_getLocations): " + err.message, null, vialib_externalObject);
    }
}

function vialib_writeNote(vialib_requestingApp, vialib_consumingAppToken, vialib_consumingAppPassword, vialib_baseServiceEndpointUrl, vialib_providerName, vialib_Duz, vialib_loginSiteCode, vialib_noteTitleIen, vialib_locationIen, vialib_encounterDate, vialib_encounterType, vialib_patientId, vialib_noteText, vialib_responseCallback) {
    //This function is used to create a new note in VistA/CPRS
    //vialib_requestingApp: This is the VIA Application Code
    //vialib_consumingAppToken: This is the VIA Application Token
    //vialib_consumingAppPassword: This is the VIA Application Password
    //vialib_baseServiceEndpointUrl: Thist is the VIA Service URL
    //vialib_providerName: This is the full VIA/VistA username as returned by the loginVIA service
    //vialib_Duz: This is the VIA session/token as returned by the loginVIA service
    //vialib_loginSiteCode: This is the facility id e.g. 516 as a text string
    //vialib_noteTitleIen: This is the IEN for the Note Title
    //vialib_locationIen: This is the IEN for the Location
    //vialib_encounterDate: This is the encounter date, a datetime string formatted in a VistA/VIA datetime format
    //vialib_encounterType: This is the encounter type A-Historical, E-Non-Historical
    //vialib_patientId: This is the patient identifier
    //vialib_noteText: This is the text for the note
    //vialib_responseCallback: This is the name of the function to return the query result to

    //Return Values:
    //1. error text (null when no error)
    //2. the VIA Service data object returned (null when error occured)

    try {
        //Construct writeNote Soap message
        var vialib_soapMessage = vialib_soapHeaderStartText + "<ser:writeNote>" + 
            "<titleIEN>" + vialib_noteTitleIen + "</titleIEN>" +
            "<encounterString>" + vialib_locationIen + ";" + vialib_encounterDate + ";" + vialib_encounterType + "</encounterString>" +
            "<text>" + vialib_encodeString(vialib_noteText) + "</text>" +
            "<queryBean>" +
            "<patient>" + "<localPid>" + vialib_patientId + "</localPid>" + "</patient>" +
            "<provider>" + "<name>" + vialib_encodeString(vialib_providerName) + "</name>" + "<loginSiteCode>" + vialib_loginSiteCode + "</loginSiteCode>" +
            "<userId>" + vialib_encodeString(vialib_Duz) + "</userId>" + "</provider>" +
            "<recordSiteCode>" + vialib_loginSiteCode + "</recordSiteCode>" +
            "<requestingApp>" + vialib_encodeString(vialib_requestingApp) + "</requestingApp>" +
			"<consumingAppToken>" + vialib_encodeString(vialib_consumingAppToken) + "</consumingAppToken>" +
			"<consumingAppPassword>" + vialib_encodeString(vialib_consumingAppPassword) + "</consumingAppPassword>" +
            "</queryBean>" +
            "</ser:writeNote>" + vialib_soapHeaderEndText;

        //Call VIA Services
        var vialib_writeNoteResponse = null;
        $.ajax({
            url: vialib_baseServiceEndpointUrl + "/EmrService",
            type: "POST",
            datatype: "xml",
            data: vialib_soapMessage,
            contentType: "text/xml; charset=\'utf-8'",
            dataType: "xml",
            success: function (data) {
                vialib_writeNoteResponse = data;
                vialib_responseCallback(null, vialib_writeNoteResponse);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //System Error
                vialib_responseCallback(textStatus, errorThrown.message);
            },
            async: true,
            cache: false
        });
    }
    catch (err) {
        //Return function error to callback function
        vialib_responseCallback("ViaServiceLibrary.js Function Error(vialib_writeNote): " + err.message, null);
    }
}

function vialib_match(vialib_requestingApp, vialib_consumingAppToken, vialib_consumingAppPassword, vialib_baseServiceEndpointUrl, vialib_providerName, vialib_Duz, vialib_loginSiteCode, vialib_Target, vialib_responseCallback) {
    //This function is used to get a list of patients matching target entered
    //vialib_requestingApp: This is the VIA Application Code
    //vialib_consumingAppToken: This is the VIA Application Token
    //vialib_consumingAppPassword: This is the VIA Application Password
    //vialib_baseServiceEndpointUrl: Thist is the VIA Service URL
    //vialib_providerName: This is the full VIA/VistA username as returned by the loginVIA service
    //vialib_Duz: This is the VIA session/token as returned by the loginVIA service
    //vialib_loginSiteCode: This is the facility id e.g. 516 as a text string
    //vialib_Target: This is the search parameter which should be:  SSN or LAST, FIRST or LXXXX (first letter of last name followed by last four digits of SSN)
    //vialib_responseCallback: This is the name of the function to return the query result to

    //Return Values:
    //1. error text (null when no error)
    //2. the VIA Service data object returned (null when error occured)

    try {
        //Construct match Soap message
        var vialib_soapMessage = vialib_soapHeaderStartText + "<ser:match>" + "<queryBean>" +
            "<requestingApp>" + vialib_encodeString(vialib_requestingApp) + "</requestingApp>" +
			"<consumingAppToken>" + vialib_encodeString(vialib_consumingAppToken) + "</consumingAppToken>" +
			"<consumingAppPassword>" + vialib_encodeString(vialib_consumingAppPassword) + "</consumingAppPassword>" +
            "<provider>" + "<name>" + vialib_encodeString(vialib_providerName) + "</name>" + "<loginSiteCode>" + vialib_loginSiteCode + "</loginSiteCode>" +
            "<userId>" + vialib_encodeString(vialib_Duz) + "</userId>" + "</provider>" +
            "<target>" + encodeURIComponent(vialib_Target) + "</target>" + "</queryBean>" +
            "</ser:match>" + vialib_soapHeaderEndText;

        //Call VIA Services
        var vialib_matchResponse = null;
        $.ajax({
            url: vialib_baseServiceEndpointUrl + "/EmrService",
            type: "POST",
            datatype: "xml",
            data: vialib_soapMessage,
            contentType: "text/xml; charset=\'utf-8'",
            dataType: "xml",
            success: function (data) {
                vialib_matchResponse = data;
                vialib_responseCallback(null, vialib_matchResponse);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //System Error
                vialib_responseCallback(textStatus, errorThrown.message);
            },
            async: true,
            cache: false
        });
    }
    catch (err) {
        //Return function error to callback function
        vialib_responseCallback("ViaServiceLibrary.js Function Error(vialib_match): " + err.message, null);
    }
}

function vialib_saveNoteAndEncounter(vialib_requestingApp, vialib_consumingAppToken, vialib_consumingAppPassword, vialib_baseServiceEndpointUrl, vialib_providerName, vialib_Duz, vialib_loginSiteCode, vialib_noteTitleIen, vialib_locationIen, vialib_patientId, vialib_noteText, vialib_startDate, vialib_patientLocalSiteNo, vialib_Inpatient, vialib_CptArrayText, vialib_DiagnosisArrayText, vialib_eSignCode, vialib_signingProviders, vialib_serviceCategory, vialib_responseCallback) {
    //This function is used to create a new note and encounter in VistA/CPRS
    //vialib_requestingApp: This is the VIA Application Code
    //vialib_consumingAppToken: This is the VIA Application Token
    //vialib_consumingAppPassword: This is the VIA Application Password
    //vialib_baseServiceEndpointUrl: Thist is the VIA Service URL
    //vialib_providerName: This is the full VIA/VistA username as returned by the loginVIA service
    //vialib_Duz: This is the VIA session/token as returned by the loginVIA service
    //vialib_loginSiteCode: This is the facility id e.g. 516 as a text string
    //vialib_noteTitleIen: This is the IEN for the Note Title
    //vialib_locationIen: This is the IEN for the Location
    //vialib_patientId: This is the patient identifier
    //vialib_noteText: This is the text for the note
    //vialib_startDate: This is the note date
    //vialib_patientLocalSiteNo: This is the patient's local Site/Facility No e.g. 613 as a text string
    //vialib_Inpatient: Inpatient = 1, Not Inpatient = 0
    //vialib_CptArrayText: This is the string passed as <procedures>, is made up of CPT Codes and Description formatted per specs
    //vialib_DiagnosisArrayText: This is the string passed as <diagnoses>, is made up of Diagnosis Codes and Description formatted per specs
    //vialib_eSignCode: The eSignature Code (A unique signature code assigned in Vista to the VIA logged in user.  (Not the IEN or DUZ values))
    //vialib_signingProviders: The IENs for additional signers/providers.  A comma delimited string of IENs
    //vialib_serviceCategory:  A, H or E
    //vialib_responseCallback: This is the name of the function to return the query result to

    //Return Values:
    //1. error text (null when no error)
    //2. the VIA Service data object returned (null when error occured)

    try {
        //Construct saveNoteAndEncounter Soap message
        //NOTE: Added default of '<visitRelatedTos>SC</visitRelatedTos>' below, to correct service issue per Jessica Romeroll 02/16/2017
        var vialib_soapMessage = vialib_soapHeaderStartText + "<ser:saveNoteAndEncounter>" +
            "<noteAndEncounter>" +
            "<locationIen>" + vialib_locationIen + "</locationIen>" +
            "<noteTitleIen>" + vialib_noteTitleIen + "</noteTitleIen>" +
            "<serviceCategory>" + vialib_encodeString(vialib_serviceCategory) + "</serviceCategory>" +
            "<procedures>" + vialib_encodeString(vialib_CptArrayText) + "</procedures>" +
            "<diagnoses>" + vialib_encodeString(vialib_DiagnosisArrayText) + "</diagnoses>" +
            "<noteBody>" + vialib_encodeString(vialib_noteText) + "</noteBody>" +
            "<eSig>" + vialib_encodeString(vialib_eSignCode) + "</eSig>" +
            "<providers>" + vialib_signingProviders + "</providers>" +
            "<visitRelatedTos>SC</visitRelatedTos>" +
            "</noteAndEncounter>" +
            "<queryBean>" +
            "<patient>" + "<localPid>" + vialib_patientId + "</localPid>" + "<localSiteId>" + vialib_patientLocalSiteNo + "</localSiteId>" +
            "<inPatient>" + vialib_Inpatient + "</inPatient>" + "</patient>" +
            "<provider>" + "<name>" + vialib_encodeString(vialib_providerName) + "</name>" + "<loginSiteCode>" + vialib_loginSiteCode + "</loginSiteCode>" +
            "<userId>" + vialib_encodeString(vialib_Duz) + "</userId>" + "</provider>" +
            "<recordSiteCode>" + vialib_loginSiteCode + "</recordSiteCode>" +
            "<requestingApp>" + vialib_encodeString(vialib_requestingApp) + "</requestingApp>" +
			"<consumingAppToken>" + vialib_encodeString(vialib_consumingAppToken) + "</consumingAppToken>" +
			"<consumingAppPassword>" + vialib_encodeString(vialib_consumingAppPassword) + "</consumingAppPassword>" +
            "<startDate>" + vialib_startDate + "</startDate>" +
            "</queryBean>" +
            "</ser:saveNoteAndEncounter>" + vialib_soapHeaderEndText;

        //Call VIA Services
        var vialib_saveNoteAndEncounterResponse = null;
        $.ajax({
            url: vialib_baseServiceEndpointUrl + "/TiuNotesService",
            type: "POST",
            datatype: "xml",
            data: vialib_soapMessage,
            contentType: "text/xml; charset=\'utf-8'",
            dataType: "xml",
            success: function (data) {
                vialib_saveNoteAndEncounterResponse = data;
                vialib_responseCallback(null, vialib_saveNoteAndEncounterResponse, vialib_noteText);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //System Error
                vialib_responseCallback(textStatus, errorThrown.message, vialib_noteText);
            },
            async: true,
            cache: false
        });
    }
    catch (err) {
        //Return function error to callback function
        vialib_responseCallback("ViaServiceLibrary.js Function Error(vialib_saveNoteAndEncounter): " + err.message, null);
    }
}

function vialib_getNote(vialib_requestingApp, vialib_consumingAppToken, vialib_consumingAppPassword, vialib_baseServiceEndpointUrl, vialib_providerName, vialib_Duz, vialib_loginSiteCode, vialib_searchNoteId, vialib_searchSiteId, vialib_searchPatientId, vialib_searchPatientSiteId, vialib_responseCallback) {
    //This function is used to retrieve an existing VIA Note
    //vialib_requestingApp: This is the VIA Application Code
    //vialib_consumingAppToken: This is the VIA Application Token
    //vialib_consumingAppPassword: This is the VIA Application Password
    //vialib_baseServiceEndpointUrl: Thist is the VIA Service URL
    //vialib_providerName: This is the full VIA/VistA username as returned by the loginVIA service
    //vialib_Duz: This is the VIA session/token as returned by the loginVIA service
    //vialib_loginSiteCode: This is the facility id e.g. 516 as a text string
    //vialib_searchNoteId: This is the Note Id/Item Id for an existing note
    //vialib_searchSiteId: This is the Site Id/recordSiteCode that the note is associated with
    //vialib_searchPatientId: This is the Patient Id
    //vialib_searchPatientSiteId: This is the Patient's local Site Id e.g. 613 as a text string
    //vialib_responseCallback: This is the name of the function to return the query result to

    //Return Values:
    //1. error text (null when no error)
    //2. the VIA Service data object returned (null when error occured)

    try {
        //Construct getNote Soap message
        var vialib_soapMessage = vialib_soapHeaderStartText + "<ser:getNote>" + "<queryBean>" +
            "<requestingApp>" + vialib_encodeString(vialib_requestingApp) + "</requestingApp>" +
			"<consumingAppToken>" + vialib_encodeString(vialib_consumingAppToken) + "</consumingAppToken>" +
			"<consumingAppPassword>" + vialib_encodeString(vialib_consumingAppPassword) + "</consumingAppPassword>" +
            "<provider>" + "<name>" + vialib_encodeString(vialib_providerName) + "</name>" + "<loginSiteCode>" + vialib_loginSiteCode + "</loginSiteCode>" +
            "<userId>" + vialib_encodeString(vialib_Duz) + "</userId>" + "</provider>" +
            "<itemId>" + vialib_searchNoteId + "</itemId>" +
            "<recordSiteCode>" + vialib_encodeString(vialib_searchSiteId) + "</recordSiteCode>" +
            "<patient>" + "<localPid>" + vialib_searchPatientId + "</localPid>" + "<localSiteId>" + vialib_searchPatientSiteId + "</localSiteId>" + "</patient>" +
            "</queryBean>" +
            "</ser:getNote>" + vialib_soapHeaderEndText;

        //Call VIA Services
        var vialib_noteResponse = null;
        $.ajax({
            url: vialib_baseServiceEndpointUrl + "/EmrService",
            type: "POST",
            datatype: "xml",
            data: vialib_soapMessage,
            contentType: "text/xml; charset=\'utf-8'",
            dataType: "xml",
            success: function (data) {
                vialib_noteResponse = data;
                vialib_responseCallback(null, vialib_noteResponse);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //System Error
                vialib_responseCallback(textStatus, errorThrown.message);
            },
            async: true,
            cache: false
        });
    }
    catch (err) {
        //Return function error to callback function
        vialib_responseCallback("ViaServiceLibrary.js Function Error(vialib_getNote): " + err.message, null);
    }
}

function vialib_cprsUserLookup(vialib_requestingApp, vialib_consumingAppToken, vialib_consumingAppPassword, vialib_baseServiceEndpointUrl, vialib_providerName, vialib_Duz, vialib_loginSiteCode, vialib_Target, vialib_responseCallback, vialib_externalObject) {
    //This function is used to retrieve VIA Users
    //vialib_requestingApp: This is the VIA Application Code
    //vialib_consumingAppToken: This is the VIA Application Token
    //vialib_consumingAppPassword: This is the VIA Application Password
    //vialib_baseServiceEndpointUrl: Thist is the VIA Service URL
    //vialib_providerName: This is the full VIA/VistA username as returned by the loginVIA service
    //vialib_Duz: This is the VIA session/token as returned by the loginVIA service
    //vialib_loginSiteCode: This is the facility id e.g. 516 as a text string
    //vialib_Target: This is the search parameter usually consist of lastname, firstname (does partial lastname search)
    //vialib_responseCallback: This is the name of the function to return the query result to
    //vialib_externalObject: This is an external object not used by this function. This object can be returned to the response function if needed

    //Return Values:
    //1. error text (null when no error)
    //2. the VIA Service data object returned (null when error occured)
    //3. the externalObject

    try {
        //Construct cprsUserLookup Soap message
        var vialib_soapMessage = vialib_soapHeaderStartText + "<ser:cprsUserLookup>" + "<queryBean>" +
            "<requestingApp>" + vialib_encodeString(vialib_requestingApp) + "</requestingApp>" +
			"<consumingAppToken>" + vialib_encodeString(vialib_consumingAppToken) + "</consumingAppToken>" +
			"<consumingAppPassword>" + vialib_encodeString(vialib_consumingAppPassword) + "</consumingAppPassword>" +
            "<provider>" + "<name>" + vialib_encodeString(vialib_providerName) + "</name>" + "<loginSiteCode>" + vialib_loginSiteCode + "</loginSiteCode>" +
            "<userId>" + vialib_encodeString(vialib_Duz) + "</userId>" + "</provider>" +
            "<target>" + encodeURIComponent(vialib_Target) + "</target>" + "</queryBean>" +
            "</ser:cprsUserLookup>" + vialib_soapHeaderEndText;

        //Call VIA Services
        var vialib_userlookupResponse = null;
        $.ajax({
            url: vialib_baseServiceEndpointUrl + "/EmrService",
            type: "POST",
            datatype: "xml",
            data: vialib_soapMessage,
            contentType: "text/xml; charset=\'utf-8'",
            dataType: "xml",
            success: function (data) {
                vialib_userlookupResponse = data;
                vialib_responseCallback(null, vialib_userlookupResponse, vialib_externalObject);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //System Error
                vialib_responseCallback(textStatus, errorThrown.message, vialib_externalObject);
            },
            async: true,
            cache: false
        });
    }
    catch (err) {
        //Return function error to callback function
        vialib_responseCallback("ViaServiceLibrary.js Function Error(vialib_cprsUserLookup): " + err.message, null, vialib_externalObject);
    }
}

function vialib_signNote(vialib_requestingApp, vialib_consumingAppToken, vialib_consumingAppPassword, vialib_baseServiceEndpointUrl, vialib_providerName, vialib_Duz, vialib_loginSiteCode, vialib_noteIEN, vialib_eSig, vialib_responseCallback) {
    //This function is used to sign an existing note in VistA/CPRS
    //vialib_requestingApp: This is the VIA Application Code
    //vialib_consumingAppToken: This is the VIA Application Token
    //vialib_consumingAppPassword: This is the VIA Application Password
    //vialib_baseServiceEndpointUrl: Thist is the VIA Service URL
    //vialib_providerName: This is the full VIA/VistA username as returned by the loginVIA service
    //vialib_Duz: This is the VIA session/token as returned by the loginVIA service
    //vialib_loginSiteCode: This is the facility id e.g. 516 as a text string
    //vialib_noteIEN: This is the existing note id as string
    //vialib_eSig: This is the esignature code for the current logged in user as string
    //vialib_responseCallback: This is the name of the function to return the query result to

    //Return Values:
    //1. error text (null when no error)
    //2. the VIA Service data object returned (null when error occured)

    try {
        //Construct writeNote Soap message
        var vialib_soapMessage = vialib_soapHeaderStartText + "<ser:signNote>" +
            "<noteIEN>" + vialib_encodeString(vialib_noteIEN) + "</noteIEN>" +
            "<userDUZ>" + vialib_encodeString(vialib_Duz) + "</userDUZ>" +
            "<esig>" + vialib_encodeString(vialib_eSig) + "</esig>" +
            "<queryBean>" +
            "<provider>" + "<name>" + vialib_encodeString(vialib_providerName) + "</name>" + "<loginSiteCode>" + vialib_loginSiteCode + "</loginSiteCode>" +
            "<userId>" + vialib_encodeString(vialib_Duz) + "</userId>" + "</provider>" +
            "<recordSiteCode>" + vialib_loginSiteCode + "</recordSiteCode>" +
            "<requestingApp>" + vialib_encodeString(vialib_requestingApp) + "</requestingApp>" +
			"<consumingAppToken>" + vialib_encodeString(vialib_consumingAppToken) + "</consumingAppToken>" +
			"<consumingAppPassword>" + vialib_encodeString(vialib_consumingAppPassword) + "</consumingAppPassword>" +
            "</queryBean>" +
            "</ser:signNote>" + vialib_soapHeaderEndText;

        //Call VIA Services
        var vialib_signNoteResponse = null;
        $.ajax({
            url: vialib_baseServiceEndpointUrl + "/EmrService",
            type: "POST",
            datatype: "xml",
            data: vialib_soapMessage,
            contentType: "text/xml; charset=\'utf-8'",
            dataType: "xml",
            success: function (data) {
                vialib_signNoteResponse = data;
                vialib_responseCallback(null, vialib_signNoteResponse);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //System Error
                vialib_responseCallback(textStatus, errorThrown.message);
            },
            async: true,
            cache: false
        });
    }
    catch (err) {
        //Return function error to callback function
        vialib_responseCallback("ViaServiceLibrary.js Function Error(vialib_signNote): " + err.message, null);
    }
}

//Related utility functions
function vialib_formatTwoDigits(vialib_numberToFormat) {
    //This function takes an integer and reformats it with a '0' prefix if the value is less than 10
    //vialib_numberToFormat is the integer value
    try {
        var vialib_prefixValue = "0";
        if (vialib_numberToFormat < 10) { return (vialib_prefixValue + vialib_numberToFormat.toString()); }
        else { return vialib_numberToFormat.toString(); }
    }
    catch (err) {
        //Display error
        alert("ViaServiceLibrary.js Function Error(vialib_formatTwoDigits): " + err.message);
        return null;
    }
}

function vialib_convertToVistaDateTime(vialib_datetimeToConvert) {
    //This function takes a JavaScript DateTime Object and reformats it for use as a Vista/VIA datetime value
    //vialib_datetimeToConvert: This is a JavaScript datetime object e.g. (new Date())
    try {
        var vialib_day = vialib_formatTwoDigits(vialib_datetimeToConvert.getDate());
        var vialib_month = vialib_formatTwoDigits(vialib_datetimeToConvert.getMonth() + 1);
        var vialib_year = (vialib_datetimeToConvert.getFullYear() - 1700).toString();
        var vialib_hour = vialib_formatTwoDigits(vialib_datetimeToConvert.getHours());
        var vialib_minute = vialib_formatTwoDigits(vialib_datetimeToConvert.getMinutes());
        var vialib_second = vialib_formatTwoDigits(vialib_datetimeToConvert.getSeconds());
        var vialib_vistaDateTime = (vialib_year + vialib_month + vialib_day + "." + vialib_hour + vialib_minute + vialib_second);                             
        return vialib_vistaDateTime;         
    }
    catch (err) {
        //Display error
        alert("ViaServiceLibrary.js Function Error(vialib_convertToVistaDateTime): " + err.message);
        return null;
    }
}

function vialib_convertToStringDateTime(vialib_datetimeToConvert) {
    //This function takes a JavaScript DateTime Object and reformats it as a string date in the format yyyymmdd.hhmmss
    //vialib_datetimeToConvert: This is a JavaScript datetime object e.g. (new Date())
    try {
        var vialib_day = vialib_formatTwoDigits(vialib_datetimeToConvert.getDate());
        var vialib_month = vialib_formatTwoDigits(vialib_datetimeToConvert.getMonth() + 1);
        var vialib_year = (vialib_datetimeToConvert.getFullYear()).toString();
        var vialib_hour = vialib_formatTwoDigits(vialib_datetimeToConvert.getHours());
        var vialib_minute = vialib_formatTwoDigits(vialib_datetimeToConvert.getMinutes());
        var vialib_second = vialib_formatTwoDigits(vialib_datetimeToConvert.getSeconds());
        var vialib_stringDateTime = (vialib_year + vialib_month + vialib_day + "." + vialib_hour + vialib_minute + vialib_second);
        return vialib_stringDateTime;
    }
    catch (err) {
        //Display error
        alert("ViaServiceLibrary.js Function Error(vialib_convertToStringDateTime): " + err.message);
        return null;
    }
}

function vialib_encodeString(vialib_unencodedString) {
    if (vialib_unencodedString == undefined || vialib_unencodedString == null || vialib_unencodedString == '') { return ''; }
    //This function takes a string and encodes for use in XML
    try {
        return vialib_unencodedString.replace(/&/g, '&amp;')
               .replace(/</g, '&lt;')
               .replace(/>/g, '&gt;')
               .replace(/"/g, '&quot;')
               .replace(/'/g, '&apos;');
    }
    catch (err) {
        //Display Error
        alert("ViaServiceLibrary.js Function Error(vialib_encodeString): " + err.message);
        return null;
    }
}