//global array to hold functions to execute in unattendedSearchFromRelatedRecordCallback
var _successFunctions = [];

///starts everything off
function unattendedSearchFromRelatedRecord(veteranField) {
    _successFunctions = [];


    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            _successFunctions[i - 1] = arguments[i];
        }
    }
    if (Xrm.Page.getAttribute(veteranField) != null) {
        var veteranId = Xrm.Page.getAttribute(veteranField).getValue();
        if (veteranId != null) {
            if (veteranId[0].id != null) {
                retrieveVeteran(veteranId[0].id);
            }
        }
    }
}

///retrieves the veteran's details from crm
function retrieveVeteran(id) {
    var selectFields = "bah_dob_date";
    selectFields += ",bah_edipi_text";
    selectFields += ",bah_ssn_text";
    selectFields += ",FirstName";
    selectFields += ",LastName";

    var expandFields = "";

    //retrieve veteran
    SDK.REST.retrieveRecord(id.toString(), "Contact", selectFields, expandFields, retrieveVeteranSuccessCallback, retrieveVeteranErrorCallback);
}

function retrieveVeteranErrorCallback() {
    //do nothing
}

///executes mvi search to get icn
function retrieveVeteranSuccessCallback(result) {
    var filter = "";
    var filterPrefix = "$select=*&$filter=";

    var edipi = result.bah_edipi_text;
    if (edipi != null) {
        if (edipi.length > 11) {
            edipi = "";
        }
    }
    else {
        edipi = "";
    }
    var firstname = result.FirstName;
    var lastname = result.LastName;

    var dobdate = result.bah_dob_date;
    var dobstring = "";
    if (dobdate != null) {
        dobstring = (dobdate.getMonth() + 1) + "/" + dobdate.getDate() + "/" + dobdate.getFullYear();
    }


    var ssn = result.bah_ssn_text;
    if (ssn != "" && ssn != null) {
        ssn = ssn.replace(/-/g, "");
    }

    //if we have edipi, search using just it
    if (edipi != "") {
        filter = buildQueryFilter("crme_EDIPI", edipi, false);
        filter += buildQueryFilter("crme_ClassCode", 'MIL', true);
        filter += buildQueryFilter("crme_SearchType", 'SearchByIdentifier', true);

        //set search type as unattended
        filter += " and crme_IsAttended eq false";
    }
    else {
        //otherwise search using lastname, firstname, ssn, dob
        filter = buildQueryFilter("crme_LastName", lastname, false); //assuming lastname will never be blank

        if (firstname != "" && firstname != null) {
            filter += buildQueryFilter("crme_FirstName", firstname, true);
        }

        if (ssn != "" && ssn != null) {
            filter += buildQueryFilter("crme_SSN", ssn, true);
        }

        if (dobstring != "") {
            filter += " and crme_DOBString eq '" + dobstring + "'";
        }
        filter += buildQueryFilter("crme_SearchType", 'SearchByFilter', true);

        //set search type as attended (for now)
        filter += " and crme_IsAttended eq true";
    }

    filter = encodeURIComponent(filter);
    filter = filterPrefix + filter;
    //debugger;
    SDK.REST.retrieveMultipleRecords("crme_person", filter, unattendedSearchFromRelatedRecordCallback, function (error) { alert(error.message); }, unattendedSearchComplete);
}

///callback for mvi search. if we get an icn, the _successFuntions will be executed here
function unattendedSearchFromRelatedRecordCallback(returnData) {
    if (returnData != null && returnData.length == 1) {
        // check for exceptions 1st
        if (returnData[0].crme_ExceptionOccured || (returnData[0].crme_ReturnMessage != null && returnData[0].crme_ReturnMessage == "An unexpected error occured during the MVI search. Please try again or contact your system administrator if the problem persists.")) {
            //do nothing
        }
        else {
            var patientMviIdentifier = returnData[0].crme_PatientMviIdentifier == null ? "" : returnData[0].crme_PatientMviIdentifier;
            if (patientMviIdentifier != "") {
                var idparts = patientMviIdentifier.split("^");

                if (idparts.length > 0) {
                    var nationalId = idparts[0];

                    for (var i = 0; i < _successFunctions.length; i++) {
                        _successFunctions[i](nationalId);
                    }
                }
            }
        }
    }
}

///looks up a kvp url for a web part, replaces the placeholder {0} with the icn and sets an iframe's source url to the full path
function displayWebPart(icn, iframename, kvpname) {
    SDK.REST.retrieveMultipleRecords("bah_keyvaluepair",
		"$select=*&$filter=bah_name_text eq '" + kvpname + "'",
		function (data) {
		    if (data.length > 0) {
		        url = data[0].bah_stringvalue_text;
		        var webresource = Xrm.Page.ui.controls.get(iframename);
		        var webresourceUrl = url.replace('{0}', icn);
		        webresource.setSrc(webresourceUrl);
		    }
		},
		function (error) {
		    //do nothing
		},
		function () {
		    //do nothing on completion
		}
	);
}

function displayWebPartVCL(icn, iframename, kvpname) {
    SDK.REST.retrieveMultipleRecords("bah_keyvaluepair",
		"$select=*&$filter=bah_name_text eq '" + kvpname + "'",
		function (data) {
		    if (data.length > 0) {
		        url = data[0].bah_stringvalue_text;
		        var webresource = Xrm.Page.ui.controls.get(iframename);
		        var webresourceUrl = webresource.getSrc() + "?data=" + encodeURIComponent("webpart=" + encodeURIComponent(url.replace('{0}', icn)));
		        webresource.setSrc(webresourceUrl);
		    }
		},
		function (error) {
		    //do nothing
		},
		function () {
		    //do nothing on completion
		}
	);
}

function displayWebPart(icn, iframename, kvpname) {
    SDK.REST.retrieveMultipleRecords("bah_keyvaluepair",
		"$select=*&$filter=bah_name_text eq '" + kvpname + "'",
		function (data) {
		    if (data.length > 0) {
		        url = data[0].bah_stringvalue_text;
		        var webresource = Xrm.Page.ui.controls.get(iframename);
		        var webresourceUrl = url.replace('{0}', icn);
		        webresource.setSrc(webresourceUrl);
		    }
		},
		function (error) {
		    //do nothing
		},
		function () {
		    //do nothing on completion
		}
	);
}

function buildQueryFilter(field, value, and) {
    if (value == '') {
        if (and) {
            return " and " + field + " eq null";
        } else {
            return field + " eq null";
        }
    }
    else {
        if (and) {
            return " and " + field + " eq '" + value + "'";
        } else {
            return field + " eq '" + value + "'";
        }
    }
}

function unattendedSearchFromVeteran() {
    _successFunctions = [];
    if (arguments.length > 0) {
        for (var i = 0; i < arguments.length; i++) {
            _successFunctions[i] = arguments[i];
        }
    }
    var filter = "";
    var filterPrefix = "$select=*&$filter=";

    var edipi = Xrm.Page.getAttribute("bah_edipi_text").getValue();
    if (edipi != null) {
        if (edipi.length > 11) {
            edipi = "";
        }
    }
    else {
        edipi = "";
    }
    var firstname = Xrm.Page.getAttribute("firstname").getValue();
    var lastname = Xrm.Page.getAttribute("lastname").getValue();

    var dobdate = Xrm.Page.getAttribute("bah_dob_date").getValue();
    var dobstring = "";
    if (dobdate != null) {
        dobstring = (dobdate.getMonth() + 1) + "/" + dobdate.getDate() + "/" + dobdate.getFullYear();
    }


    var ssn = Xrm.Page.getAttribute("bah_ssn_text").getValue();
    if (ssn != "" && ssn != null) {
        ssn = ssn.replace(/-/g, "");
    }

    //if we have edipi, search using just it
    if (edipi != "") {
        filter = buildQueryFilter("crme_EDIPI", edipi, false);
        filter += buildQueryFilter("crme_ClassCode", 'MIL', true);
        filter += buildQueryFilter("crme_SearchType", 'SearchByIdentifier', true);

        //set search type as unattended
        filter += " and crme_IsAttended eq false";
    }
    else {
        //otherwise search using lastname, firstname, ssn, dob
        filter = buildQueryFilter("crme_LastName", lastname, false); //assuming lastname will never be blank

        if (firstname != "" && firstname != null) {
            filter += buildQueryFilter("crme_FirstName", firstname, true);
        }

        if (ssn != "" && ssn != null) {
            filter += buildQueryFilter("crme_SSN", ssn, true);
        }

        if (dobstring != "") {
            filter += " and crme_DOBString eq '" + dobstring + "'";
        }
        filter += buildQueryFilter("crme_SearchType", 'SearchByFilter', true);

        //set search type as attended (for now)
        filter += " and crme_IsAttended eq true";
    }


    filter = encodeURIComponent(filter);
    filter = filterPrefix + filter;
    //debugger;
    SDK.REST.retrieveMultipleRecords("crme_person", filter, unattendedSearchCallback, function (error) { alert(error.message); }, unattendedSearchComplete);
}

function unattendedSearchCallback(returnData) {
    if (returnData != null && returnData.length == 1) {
        // check for exceptions 1st
        if (returnData[0].crme_ExceptionOccured || (returnData[0].crme_ReturnMessage != null && returnData[0].crme_ReturnMessage == "An unexpected error occured during the MVI search. Please try again or contact your system administrator if the problem persists.")) {
            //do nothing
        }
        else {
            var patientMviIdentifier = returnData[0].crme_PatientMviIdentifier == null ? "" : returnData[0].crme_PatientMviIdentifier;
            if (patientMviIdentifier != "") {
                var idparts = patientMviIdentifier.split("^");

                if (idparts.length > 0) {
                    var nationalId = idparts[0];
                    for (var i = 0; i < _successFunctions.length; i++) {
                        _successFunctions[i](nationalId);
                    }
                }
            }
        }
    }
}

function unattendedSearchComplete() {
    //do nothing
}