if (typeof (VIAServices) === "undefined") {
    VIAServices = { __namespace: true };
}

//Static Variables
var consumingApp;
//Get VIA URL and other items needed 
consumingApp = new AppInfo();
consumingApp.name = "HRC_CRM";
consumingApp.token = "HRC_CRM_ID_5496";
consumingApp.password = "Bf5d2w!rQj";
consumingApp.url = "https://URL     ";
consumingApp.notetitleid = 1949;

var callBackFunction;

var xml_encode_map = {
    '&': '&amp;',
    '"': '&quot;',
    '<': '&lt;',
    '>': '&gt;',
    '/': '&#92;'
};

var xml_decode_map = {
    '&amp;': '&',
    '&quot;': '"',
    '&lt;': '<',
    '&gt;': '>',
    '&#92;': '/'
};

function encodeXml(string) {
    return string.replace(/([\&"<>])/g, function (str, item) {
        return xml_encode_map[item];
    });
};

function decodeXml(string) {
    return string.replace(/(&quot;|&lt;|&gt;|&amp;)/g,
		function (str, item) {
		    return xml_decode_map[item];
		});
}

function viaLineBreaks(string) {
    return string.replace(/[\n\r]/g, '|');
}

function createNode(tag, value) {
    return "<" + tag + ">" + value + "</" + tag + ">"
}

function via_getCookie(cname) {
    try {
        var name = cname + "=";
        var result = document.cookie.match(new RegExp(cname + '=([^;]+)'));
        result && (result = JSON.parse(result[1]));
        return result;
    }
    catch (err) {
        alert('via_getCookie: ' + err.message);
    }
}

function via_setCookie(cname, cvalue, exminutes) {
    var via_context = GetGlobalContext();
    var via_orgName = via_context.getOrgUniqueName();

    try {
        var d = new Date();
        d.setMinutes(d.getMinutes() + (exminutes));
        var expires = "expires=" + d.toUTCString();
        document.cookie = [cname, "=", JSON.stringify(cvalue), "; ", expires, "; path=/", via_orgName, "/;"].join("");
    }
    catch (err) {
        alert('via_setCookie: ' + err.message);
    }
}

function via_checkUserLogIn() {
    //Check if VIA Login cookie exist (not expired)
    var loginCookie = via_getCookie("viasessionlink");

    //Hide Vista Login section and exit if cookie exist
    if (loginCookie != null) {
        return true;
    }
    else {
        return false;
    }
}

function via_getLocations(callback) {
    var apiName = "getLocations";
    var target = "*";  // Get all locations
    var userTO = via_getCookie("viasessionlink");
    try {
        if (target !== null && userTO !== null) {
            VIAServices.getLocations(userTO, target, callback);
        } else {
            alert("All fields must be filled out, please try again.");
        }
    } catch (err) {
        alert(apiName.value + ': ' + err.message);
    }
}

function via_getVeteran(veteranId, callback) {
    // Get selected Veteran's SSN
    SDK.REST.retrieveMultipleRecords("Contact",
        "$select=bah_ssn_text&$filter=ContactId eq guid'" + veteranId[0].id.toString() + "'",
        function (data) {
            if (data.length > 0) {
                var target = data[0].bah_ssn_text;
                var userTO = via_getCookie("viasessionlink");
                if (target && userTO) {
                    VIAServices.match(userTO, target, callback);
                }
            }
        },
        function (error) {
            alert("Error loading Veteran identifiers" + ":\n" + error);
        },
        function () {
            //do nothing on completion
        }
    );
}

//Key Value Pairs
function getKeyValuePair(kvpname, callback) {
    SDK.REST.retrieveMultipleRecords("bah_keyvaluepair",
        "$select=*&$filter=bah_name_text eq '" + kvpname + "'",
        function (data) {
            if (data.length > 0) {
                switch (data[0].bah_valuetype_code.Value) {
                    case 810050003:
                        callback(data[0].bah_datevalue_date);
                        break;
                    case 810050001:
                        callback(data[0].bah_decimalvalue_num);
                        break;
                    case 810050002:
                        callback(data[0].bah_integervalue_num);
                        break;
                    case 810050000:
                        callback(data[0].bah_stringvalue_text);
                        break;
                }
            } else {
                alert("Could not find value for " + kvpname);
            }
        },
        function (error) {
            alert("Error loading value for " + kvpname + ":\n" + error);
        },
        function () {
            //do nothing on completion
        }
    );
}

function get2Digits(startValue) {
    var endValue = "0";

    if (startValue < 10) {
        endValue += startValue;
    } else {
        endValue = startValue;
    }

    return endValue;
}

function getVistaDate(myDate) {

    var day = get2Digits(myDate.getDate());
    var month = get2Digits(myDate.getMonth() + 1); //January is 0!
    var year = myDate.getFullYear() - 1700;
    var hour = get2Digits(myDate.getHours());
    var minute = get2Digits(myDate.getMinutes());
    var second = get2Digits(myDate.getSeconds());

    return (year + month + day + "." + hour + minute + second);
}

Date.prototype.vista_date = function () {
    var day = get2Digits(this.getDate());
    var month = get2Digits(this.getMonth() + 1); //January is 0!
    var year = this.getFullYear() - 1700;
    var hour = get2Digits(this.getHours());
    var minute = get2Digits(this.getMinutes());
    var second = get2Digits(this.getSeconds());

    return (year + month + day + "." + hour + minute + second);
};

Date.prototype.yyyymmdd = function () {
    var day = get2Digits(this.getDate());
    var month = get2Digits(this.getMonth() + 1); // getMonth() is zero-based
    var year = this.getFullYear();

    return (year + month + day);
};



//AppInfo
function AppInfo() {
    this.name = "";
    this.token = "";
    this.password = "";
    this.notetitleid = "";
    this.url = "";
}

AppInfo.prototype.getXMLNodes = function () {
    return "<requestingApp>" + this.name + "</requestingApp>" +
			"<consumingAppToken>" + this.token + "</consumingAppToken>" +
			"<consumingAppPassword>" + this.password + "</consumingAppPassword>";
};

//Soap Wrapper
function SoapWrapper(servicename) {
    this.servicename = servicename;
}

SoapWrapper.prototype.getSoapHeader = function () {
    return "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' " +
            "xmlns:ser='http://DNS        .URL       /'>" +
			"<soapenv:Header/>" +
			"<soapenv:Body>" +
			"<ser:" + this.servicename + ">";
};

SoapWrapper.prototype.getSoapFooter = function () {
    return "</ser:" + this.servicename + ">" +
			"</soapenv:Body>" +
			"</soapenv:Envelope>";
};

//UserTO
function UserTO() {
    this.name = "";
    this.ssn = "";
    this.duz = "";
    this.vistaduz = "";
    this.siteid = "";
    this.greeting = "";
    this.fault = "";
    this.error = "";
    this.value = "";
}

UserTO.prototype.getXMLNodes = function () {
    return "<name>" + this.name + "</name>" +
			"<loginSiteCode>" + this.getSubDivision() + "</loginSiteCode>" +
			"<userId>" + this.duz + "</userId>";
};
UserTO.prototype.getSiteId = function () {
    return this.siteid.substr(0, 3);
};
UserTO.prototype.getSubDivision = function () {
    return ((this.siteid.length > 3) ? this.siteid.substr(3) : this.siteid.substr(0, 3));
};

//Patient
function PatientTO() {
    this.name = "";
    this.ssn = "";
    this.dob = "";
    this.patientname = "";
    this.localpid = "";
    this.patientflags = "";
    this.fault = "";
    this.error = "";
    this.value = "";

    //additional fields from select
    this.gender = "";
    this.mpipid = "";
    this.mpichecksum = "";
    this.location = "";
    this.restricted = "";
    this.confidentiality = "";

}

PatientTO.prototype.getXMLNodes = function () {
    return "<name>" + this.patientname + "</name>" +
			"<localPid>" + this.localpid + "</localPid>";

};

//Note Titles
function NoteTitle() {
    this.id = "";
    this.name = "";
    this.fault = "";
    this.error = "";
    this.value = "";
}

//Location
function Location() {
    this.id = "";
    this.name = "";
    this.fault = "";
    this.error = "";
    this.value = "";
}

//isConsult isSurgery
function VisitTO() {
    this.type = "";
    this.location = new Location();
    this.timestamp = "";
    this.status = "";
    this.fault = "";
    this.error = "";
    this.value = "";
}


//Write Note 
function NoteResultTO() {
    this.id = "";
    this.totalpages = "";
    this.lastpagerecd = "";
    this.fault = "";
    this.error = "";
    this.value = "";
}

//isConsult isSurgery Confidentiality
function TextTo() {
    this.text = "";
    this.fault = "";
    this.error = "";
    this.value = "";
}

function BuildEncounterString(isHistorical, locationId) {
    //LOCATIONIEN;YYYYMMDD;ENCOUNTERTYPE
    // -------------------------------------------------
    //	historical
    //	-location   locationid; currentdate; E  
    // -------------------------------------------------
    //	non-historic
    //	-location   locationid; currentdate; A
    //	-visit	    visitlocationid; visitdate; visittype
    // -------------------------------------------------
    // Encounter Type – Can be one of three possible values: 
    //	 	A (AMBULATORY), 
    //		H (HOSPITALIZATION)
    // 		E (EVENT- HISTORICAL)

    //var visitTime = window.parent.Xrm.Page.getAttribute("vcl_via_visit_time_text").getValue();
    //var visitType = window.parent.Xrm.Page.getAttribute("vcl_via_visit_type_text").getValue();

    var encounterType = (isHistorical = 'Y' ? 'E' : 'A');

    var encounterDate = getVistaDate(new Date());

    return (locationId + ";" + encounterDate + ";" + encounterType)
}

//Start of Namespace

VIAServices = {

    callService: function (soapMessage, on_success, on_error) {
        var resultData = null;
        $.ajax({
            url: consumingApp.url,
            type: "POST",
            datatype: "xml",
            data: soapMessage,
            contentType: "text/xml; charset=\'utf-8'",
            success: on_success,
            error: on_error
        });
    },

    //VIA SERVICE: loginVIA	
    loginVIA: function (siteId, accessCode, verifyCode, callback) {
        var viaLoginWrapper = new SoapWrapper("loginVIA");

        var soapMessage = viaLoginWrapper.getSoapHeader() +
						"<queryBean>" +
                            createNode("requestingApp", consumingApp.name) +
                            createNode("consumingAppToken", consumingApp.token) +
                            createNode("consumingAppPassword", consumingApp.password) +
						"</queryBean>" +
						createNode("siteCode", siteId) +
						createNode("accessCode", encodeXml(accessCode)) +
						createNode("verifyCode", encodeXml(verifyCode)) +
                        viaLoginWrapper.getSoapFooter();

        if (typeof callback === "function") { callBackFunction = callback; }
        else { callBackFunction = ""; }
        VIAServices.callService(soapMessage, VIAServices.loginVIA_OnSuccess, VIAServices.loginVIA_OnError);
    },

    loginVIA_OnSuccess: function (data, status) {
        //FIND TAG NAME:  valueNodes.childNodes[0].childNodes[2].tagName		

        //Check for return node
        if (data.getElementsByTagName('ns2:UserTO').length > 0) {
            var valueNodes = data.getElementsByTagName('ns2:UserTO')[0];

            //Parse return node (including fault)
            var returnUserTO = new UserTO();
            returnUserTO.name = $(valueNodes.getElementsByTagName('name')).text();
            returnUserTO.ssn = $(valueNodes.getElementsByTagName('SSN')).text();
            returnUserTO.duz = $(valueNodes.getElementsByTagName('DUZ')).text();
            returnUserTO.siteid = $(valueNodes.getElementsByTagName('siteId')).text();
            returnUserTO.greeting = $(valueNodes.getElementsByTagName('greeting')).text();
            returnUserTO.vistaduz = $(valueNodes.getElementsByTagName('vistaDUZ')).text();
            returnUserTO.fault = $(valueNodes.getElementsByTagName('fault')).text();
            returnUserTO.value = $(valueNodes).text();

            //check if error
            if (returnUserTO.fault !== "" && returnUserTO.fault !== null) {
                returnUserTO.error = "Login failed";
            }
        }

        if (callBackFunction !== "") { callBackFunction(returnUserTO); }
    },

    loginVIA_OnError: function (request, status, error) {
        //Parse Fault
        var returnUserTO = new UserTO();
        returnUserTO.error = error;
        returnUserTO.fault = $(request.responseXML.getElementsByTagName('faultstring')).text();
        returnUserTO.value = $(request.responseText).text();

        if (callBackFunction !== "") { callBackFunction(returnUserTO); }
    },

    //VIA SERVICE: match	
    match: function (userTO, target, callback) {
        // target and direction are optional per documentation
        var getMatchWrapper = new SoapWrapper("match");

        var soapMessage = getMatchWrapper.getSoapHeader() +
                            "<queryBean>" +
							createNode("target", encodeXml(target)) +
							createNode("direction", 1) +
                            "<provider>" +
                            createNode("name", userTO.name) +
                            createNode("loginSiteCode", ((userTO.siteid.length > 3) ? userTO.siteid.substr(3) : userTO.siteid.substr(0, 3))) +
                            createNode("userId", userTO.duz) +
                            "</provider>" +
                            createNode("requestingApp", consumingApp.name) +
                            createNode("consumingAppToken", consumingApp.token) +
                            createNode("consumingAppPassword", consumingApp.password) +
							"</queryBean>" +
						getMatchWrapper.getSoapFooter();

        if (typeof callback === "function") { callBackFunction = callback; }
        else { callBackFunction = ""; }
        VIAServices.callService(soapMessage, VIAServices.match_OnSuccess, VIAServices.match_OnError);
    },

    match_OnSuccess: function (data, status) {
        var returnResult = [];

        //Check for return node
        if (data.getElementsByTagName("ns2:TaggedPatientArray").length > 0) {
            var valueNodes = data.getElementsByTagName("ns2:TaggedPatientArray")[0].getElementsByTagName("patients")[0];

            $(valueNodes).children().each(function (index) {
                //Parse return node (including fault)
                var tempPatientTO = new PatientTO();
                tempPatientTO.name = $(valueNodes.childNodes[index].getElementsByTagName('name')).text();
                tempPatientTO.ssn = $(valueNodes.childNodes[index].getElementsByTagName('ssn')).text()
                tempPatientTO.dob = $(valueNodes.childNodes[index].getElementsByTagName('dob')).text();
                tempPatientTO.patientname = $(valueNodes.childNodes[index].getElementsByTagName('patientName')).text();
                tempPatientTO.localpid = $(valueNodes.childNodes[index].getElementsByTagName('localPid')).text();
                tempPatientTO.patientflags = $(valueNodes.childNodes[index].getElementsByTagName('patientFlags')).text();
                tempPatientTO.fault = $(valueNodes.childNodes[index].getElementsByTagName('fault')).text();
                tempPatientTO.value = $(valueNodes.childNodes[index].getElementsByTagName('patientTO')).text();

                //check if error
                if (tempPatientTO.fault !== "" && tempPatientTO.fault !== null) {
                    tempPatientTO.error = "Get Patient Failed";
                }

                returnResult.push(tempPatientTO);
            });

        } else {
            //Could not find main node
            //Parse Fault
            var tempPatientTO = new PatientTO();
            tempPatientTO.error = "Could not find return data in expected structure";
            tempPatientTO.fault = $(data.getElementsByTagName('fault')).text();
            tempPatientTO.value = $(data.documentElement).text();

            returnResult.push(tempPatientTO);
        }

        if (callBackFunction !== "") { callBackFunction(returnResult); }
    },

    match_OnError: function (request, status, error) {
        var returnResult = [];

        var tempPatientTO = new PatientTO();
        tempPatientTO.value = request;
        tempPatientTO.error = error;

        if (callBackFunction !== "") { callBackFunction(returnResult.push(tempPatientTO)); }
    },

    //VIA SERVICE: select
    select: function (userTO, localPid, target, callback) {
        // target and direction are optional per documentation
        var selectWrapper = new SoapWrapper("select");

        var soapMessage = selectWrapper.getSoapHeader() +
							"<queryBean>" +
								"<patient>" +
									createNode("localPid", localPid) +
									createNode("localSiteId", userTO.getSiteId()) +
								"</patient>" +
                            "<provider>" +
                            createNode("name", userTO.name) +
                            createNode("loginSiteCode", ((userTO.siteid.length > 3) ? userTO.siteid.substr(3) : userTO.siteid.substr(0, 3))) +
                            createNode("userId", userTO.duz) +
                            "</provider>" +
                            createNode("requestingApp", consumingApp.name) +
                            createNode("consumingAppToken", consumingApp.token) +
                            createNode("consumingAppPassword", consumingApp.password) +
                            "</queryBean>" +
						selectWrapper.getSoapFooter();

        if (typeof callback === "function") { callBackFunction = callback; }
        else { callBackFunction = ""; }
        VIAServices.callService(soapMessage, VIAServices.select_OnSuccess, VIAServices.select_OnError);

    },

    select_OnSuccess: function (data, status) {
        var returnResult = [];

        if (data.getElementsByTagName("ns2:selectResponse").length > 0) {
            var valueNodes = data.getElementsByTagName("ns2:selectResponse")[0];

            $(valueNodes).children().each(function (index) {
                var tempPatientTo = new PatientTO();

                tempPatientTo.name = $(valueNodes.childNodes[index].getElementsByTagName('name')).text();
                tempPatientTo.ssn = $(valueNodes.childNodes[index].getElementsByTagName('ssn')).text();
                tempPatientTo.dob = $(valueNodes.childNodes[index].getElementsByTagName('dob')).text();
                tempPatientTo.patientname = $(valueNodes.childNodes[index].getElementsByTagName('patientName')).text();
                tempPatientTo.localpid = $(valueNodes.childNodes[index].getElementsByTagName('localPid')).text();
                tempPatientTo.patientflags = $(valueNodes.childNodes[index].getElementsByTagName('patientFlags')).text();

                tempPatientTo.gender = $(valueNodes.childNodes[index].getElementsByTagName('gender')).text();
                tempPatientTo.mpipid = $(valueNodes.childNodes[index].getElementsByTagName('mpiPid')).text();
                tempPatientTo.mpichecksum = $(valueNodes.childNodes[index].getElementsByTagName('mpiChecksum')).text();
                tempPatientTo.location = $(valueNodes.childNodes[index].getElementsByTagName('location')).text();
                tempPatientTo.restricted = $(valueNodes.childNodes[index].getElementsByTagName('restricted')).text();
                tempPatientTo.confidentiality = $(valueNodes.childNodes[index].getElementsByTagName('confidentiality')).text();

                tempPatientTo.fault = $(valueNodes.childNodes[index].getElementsByTagName('fault')).text();
                tempPatientTo.value = $(valueNodes.childNodes[index]).text();

                //check if error
                if (tempPatientTo.fault !== "" && tempPatientTo.fault !== null) {
                    tempPatientTo.error = "Select Patient Failed";
                }

                returnResult.push(tempPatientTo);
            });

        } else {
            //Could not find main node
            //Parse Fault
            var tempPatientTo = new PatientTO();
            tempPatientTo.error = "Could not find return data in expected structure";
            tempPatientTo.fault = $(data.getElementsByTagName('fault')).text();
            tempPatientTo.value = $(data.documentElement).text();

            returnResult.push(tempPatientTo);
        }

        if (callBackFunction !== "") { callBackFunction(returnResult); }

    },

    select_OnError: function (request, status, error) {
        var returnResult = [];

        var tempPatientTo = new PatientTO();
        tempPatientTo.error = error;
        tempPatientTo.fault = $(request.responseXML.getElementsByTagName('faultstring')).text();
        tempPatientTo.value = $(request.responseText).text();

        returnResult.push(tempPatientTo);

        if (callBackFunction !== "") { callBackFunction(returnResult); }
    },


    //VIA SERVICE: getLocations	
    getLocations: function (userTO, target, callback) {
        // target and direction are optional per documentation
        var getLocationsWrapper = new SoapWrapper("getLocations");

        var soapMessage = getLocationsWrapper.getSoapHeader() +
                            "<queryBean>" +
							createNode("target", encodeXml(target)) +
							createNode("direction", 1) +
                            "<provider>" +
                            createNode("name", userTO.name) +
                            createNode("loginSiteCode", ((userTO.siteid.length > 3) ? userTO.siteid.substr(3) : userTO.siteid.substr(0, 3))) +
                            createNode("userId", userTO.duz) +
                            "</provider>" +
                            createNode("requestingApp", consumingApp.name) +
                            createNode("consumingAppToken", consumingApp.token) +
                            createNode("consumingAppPassword", consumingApp.password) +
							"</queryBean>" +
						getLocationsWrapper.getSoapFooter();

        if (typeof callback === "function") { callBackFunction = callback; }
        else { callBackFunction = ""; }
        VIAServices.callService(soapMessage, VIAServices.getLocations_OnSuccess, VIAServices.getLocations_OnError);
    },

    getLocations_OnSuccess: function (data, status) {
        var returnResult = [];

        if (data.getElementsByTagName("ns2:TaggedHospitalLocationArray").length > 0) {
            var valueNodes = data.getElementsByTagName("locations")[0];

            $(valueNodes).children().each(function (index) {
                var tempLocation = new Location();
                tempLocation.id = $(valueNodes.childNodes[index].getElementsByTagName('id')).text();
                tempLocation.name = $(valueNodes.childNodes[index].getElementsByTagName('name')).text();
                tempLocation.fault = $(valueNodes.childNodes[index].getElementsByTagName('fault')).text();
                tempLocation.value = $(valueNodes.childNodes[index]).text();

                //check if error
                if (tempLocation.fault !== "" && tempLocation.fault !== null) {
                    tempLocation.error = "Get Location Failed";
                }

                returnResult.push(tempLocation);
            });
        } else {
            //Could not find main node
            //Parse Fault
            var tempLocation = new Location();
            tempLocation.error = "Could not find return data in expected structure";
            tempLocation.fault = $(data.getElementsByTagName('fault')).text();
            tempLocation.value = $(data.documentElement).text();

            returnResult.push(tempLocation);
        }

        if (callBackFunction !== "") { callBackFunction(returnResult); }
    },

    getLocations_OnError: function (request, status, error) {
        var returnResult = [];

        var tempLocation = new Location();
        tempLocation.error = error;
        tempLocation.fault = $(request.responseXML.getElementsByTagName('faultstring')).text();
        tempLocation.value = $(request.responseText).text();

        returnResult.push(tempLocation);

        if (callBackFunction !== "") { callBackFunction(returnResult); }
    },


    
    //VIA SERVICE: writeNotes	
    writeNote: function (userTO, localPid, titleId, encounterString, content, callback) {
        //encounter date
        var myDate = new Date();
        var encounterDate = getVistaDate(new Date());
        //Change linebreaks
        content = viaLineBreaks(content);

        // target and direction are optional per documentation
        var writeNoteWrapper = new SoapWrapper("writeNote");

        var soapMessage = writeNoteWrapper.getSoapHeader() +
							createNode("titleIEN", titleId);

        soapMessage += createNode("encounterString", encounterString);	//LOCATIONIEN;YYYYMMDD;ENCOUNTERTYPE

        soapMessage += createNode("text", content) +
                        "<queryBean>" +
                            "<patient>" +
                                createNode("localPid", localPid) +
                            "</patient>" +
                            "<provider>" +
                            createNode("name", userTO.name) +
                            createNode("loginSiteCode", ((userTO.siteid.length > 3) ? userTO.siteid.substr(3) : userTO.siteid.substr(0, 3))) +
                            createNode("userId", userTO.duz) +
                            "</provider>" +
                            createNode("recordSiteCode", ((userTO.siteid.length > 3) ? userTO.siteid.substr(3) : userTO.siteid.substr(0, 3))) +
                            createNode("requestingApp", consumingApp.name) +
                            createNode("consumingAppToken", consumingApp.token) +
                            createNode("consumingAppPassword", consumingApp.password) +
                        "</queryBean>" +
                    writeNoteWrapper.getSoapFooter();

        //<encounterString>887;3140121.163242;E</encounterString>
        // Location ID – Might need to use the VIA service “getHospitalLocations” to retrieve the valid location IDs by name
        // VistA Date/Time - Generate the second piece of information by sending a date and time in Vista format. 
        //			i.e. 3130715.163242 represents July 15, 2013 4:32:42. 
        //			The VistA date format is VistaYear + mmdd.hhmmss. 
        //			The only weird thing is the VistA year. It is calculated using the current year minus 1700.
        //So February 7, 2017 08:00 would be 3170207.080000. Where 317 is 2017 – 1700.

        if (typeof callback === "function") { callBackFunction = callback; }
        else { callBackFunction = ""; }
        VIAServices.callService(soapMessage, VIAServices.writeNote_OnSuccess, VIAServices.writeNote_OnError);
    },

    writeNote_OnSuccess: function (data, status) {
        var returnResult = [];

        //Check for return node
        if (data.getElementsByTagName('soap:Envelope').length > 0) {
            var valueNodes = data.getElementsByTagName('soap:Envelope')[0].childNodes[0].childNodes[0];

            $(valueNodes).children().each(function (index) {
                //Parse return node (including fault)
                var noteResultTo = new NoteResultTO();
                noteResultTo.id = $(valueNodes.childNodes[index].getElementsByTagName('id')).text();
                noteResultTo.totalpages = $(valueNodes.childNodes[index].getElementsByTagName('totalPages')).text()
                noteResultTo.lastpagerecd = $(valueNodes.childNodes[index].getElementsByTagName('lastPageRecd')).text();
                noteResultTo.fault = $(valueNodes.childNodes[index].getElementsByTagName('fault')).text();
                noteResultTo.value = $(valueNodes.childNodes[index]).text();

                //check if error
                if (noteResultTo.fault !== "" && noteResultTo.fault !== null) {
                    noteResultTo.error = "Note Write Failed";
                }

                returnResult.push(noteResultTo);
            });

        } else {
            //Could not find main node
            //Parse Fault
            var noteResultTo = new NoteResultTO();
            noteResultTo.error = "Could not find return data in expected structure";
            noteResultTo.fault = $(data.getElementsByTagName('fault')).text();
            noteResultTo.value = $(data.documentElement).text();

            returnResult.push(noteResultTo);
        }

        if (callBackFunction !== "") { callBackFunction(returnResult); }

    },

    writeNote_OnError: function (request, status, error) {
        var returnResult = [];

        var noteResultTo = new NoteResultTO();
        noteResultTo.error = error;
        noteResultTo.fault = $(request.responseXML.getElementsByTagName('faultstring')).text();
        noteResultTo.value = $(request.responseText).text();

        returnResult.push(noteResultTo);

        if (callBackFunction !== "") { callBackFunction(returnResult); }

    },

}