<html><head><meta charset="utf-8"></head><body style="overflow-wrap: break-word;">﻿<style type="text/css">
:root #header + #content > #left > #rlblock_left
{ display: none !important; }</style>﻿



    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link href="css/esrpartstyle.css" rel="stylesheet" type="text/css"><br>
    <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="jquery.js" type="text/javascript"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    
    <style>
            .button{
                                margin-left:10%;
                                margin-right:10%;
                                margin-top:6%;
                                width:80%;
                                height:25px;
                                font-family: 'Segoe UI';
                }
            .sidebar {
                                background-color:#002050;
                                width:15%;
                                height:100%;
                                position:fixed;
                                left: 0;
                                top:0;
                }
/*            .frame{
                                display: none;
                                width: 100%;
                                height: 100%;
                }*/
                
                .framecontainer{                                
                                position:fixed;
                                top:0px;
                                left: 15%;
                                width:97%;
                                height: 100%;
                                border: 1px solid #777777;
                                background:#f0f0f0;
                               box-shadow:0px 0px 10px #777777;
                }
                #frameWrap {
                                position:relative;
                                height: 360px;
                                width: 640px;
                                border: 1px solid #777777;
                                background:#f0f0f0;
                               box-shadow:0px 0px 10px #777777;
                } 


                .iframe{
                                scroll-behavior: auto;
                                width:87%;
                                height:100%;
                                margin-right:1%;
                                //position: relative;
                                top: 50%;
                                //transform: translateY(-50%);
                }

               .loader {
                                position:absolute;
                                left:40%;
                                top:35%;
                                border-radius:20px;
                                padding:25px;
                                border:1px solid #777777;
                                background: #ffffff;
                                box-shadow:0px 0px 10px #777777;
                } 


    </style>

    <div class="sidebar" id="sidebar">
        <button class="button" id="consultsbtn">Consults</button><br>
        <button class="button" id="notesbtn">Notes</button><br>
        <button class="button" id="ordersbtn">Orders</button><br>
        <button class="button" id="postingsbtn">Postings</button><br>
        <button class="button" id="appointmentsbtn">Appointments</button><br>
    </div>
    
    <div class="framecontainer" id="framecontainer">
            <span class="loader" id="UserInstruction">Please select a button on the left to display information.</span>
            <div class="loader" id="loader1" style="background: lemonchiffon;">Please wait while Clinical Information is retrieved...</div>
            <iframe title="IFrame placeholder" class="iframe" id="displayframe"></iframe>
    </div>
   

    <script>
(function($) {
    $.QueryString = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i)
        {
            var p=a[i].split('=', 2);
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'))
})(jQuery);
	
	
$(document).ready(function(){

$('#loader1').hide(); 
var _kvpname; 
// 7/11 does this need to be updated for interactions?
// When Entity = "Request", run this w/o user interaction: 
	var entity = window.parent.Xrm.Page.data.entity.getEntityName();
	if (entity == "incident") {
		var action = "";
		var actionintersection = window.parent.Xrm.Page.getAttribute("vhacrm_actionintersectionid").getValue();
		if (actionintersection) {
			action = actionintersection[0].name;
		}
		// if Action = "Appointment Modification" or "Appointment Cancellation" then open Appointments by default
		if (action == "Modify Appointment" || action == "Cancel Appointment") {
			// Appointments should be selected
			getWebPartURL("hdr_appointments");
			}
		// If Action = "Authorization/Referral Investigation" + routing reason = "Approved Consult Without Referral"
		else if (action == "Authorization/Referral Investigation" && window.parent.Xrm.Page.getAttribute("vhacrm_routingreason_code").getValue()=="713770001") {
			getWebPartURL("hdr_consults");
		}	
		// If neither of the above conditions, then collapse the Clinical Information Tab
		else {
			window.parent.Xrm.Page.ui.tabs.get("tab_11").setDisplayState("collapsed");
			}
		}

function getWebPartURL(kvpname) {
debugger;
        var url = "not set";
        var icn = $.QueryString["data"];
        var vetUIds = "";
        $('#loader1').show();
        $('#UserInstruction').hide(); 

        var entityInfo =  getEntityData(kvpname);
        kvpname = entityInfo.kvpname;
        vetUIds = entityInfo.vetUIds;

        _kvpname = kvpname;

        if (icn.length>0) {

               SDK.REST.retrieveMultipleRecords("bah_keyvaluepair",
               "$select=*&$filter=bah_name_text eq '"+kvpname+"'",
               function(data){
                  if(data.length>0) {
                    url = data[0].bah_stringvalue_text;
                   }
                 //  check if the kvp is _addremove, build URL to accept the vetUIds string
                 if (kvpname.indexOf("_addremove") >= 0) {
                     var newUrl = url.replace('{0}', icn);
                     newUrl = newUrl.replace('{1}', vetUIds);
                     }
                     else {
						var newUrl = url.replace('{0}', icn);
						}

                   // avoid entry to the history stack by dropping & recreating iFrame (vs resetting the Src)
                   $('#displayframe').remove();

                   $('<iframe />').attr({
                   name: 'displayframe',
                   id: 'displayframe',
                   src: newUrl,
                   class: 'iframe'
                   }).appendTo("#framecontainer");
                  
                   $('#UserInstruction').hide(); 
                    $('#displayframe').on('load', function () {
                        $('#loader1').hide();
                        }); 

              },

               function(error){
                 //do nothing
               },

               function(){
                 //do nothing on completion
               }
               );

         }
          else
             { alert("ERROR: No National ID available.");}

      } // end getWebPartUrl


//window event handlers...
window.addEventListener(
"message",
function (pMessageContent) {
    if (!!pMessageContent && !!pMessageContent.data && (typeof pMessageContent.data == "object") && !!pMessageContent.data.buttonClicked && !!pMessageContent.data.data) {
        AddRemoveRequestIDs(_kvpname, pMessageContent.data.data, pMessageContent.data.buttonClicked);
    }
});



$('#consultsbtn').click(function(){
    getWebPartURL("hdr_consults");
});
$('#notesbtn').click(function(){
    getWebPartURL("hdr_notes");
});
$('#ordersbtn').click(function(){
    getWebPartURL("hdr_orders");
});
$('#postingsbtn').click(function(){
    getWebPartURL("hdr_postings");
});
$('#appointmentsbtn').click(function(){
    getWebPartURL("hdr_appointments");
});


}); // close jquery
    
// called by the web service return message when content == object and button == clicked
// accepts the kvpname, content data (oData), buttonClicked(add/remove request)
function AddRemoveRequestIDs(kvpname, oData, btnClicked) {
    var vetUIds = "";
	var crmAppointmentDateTime = "";
    var entityInfo = getEntityData(kvpname);
    var vetUItempfield = entityInfo.vetUItempfield;
	var appointmentDateTimeField = entityInfo.appointmentDateTime;
    vetUIds = parent.Xrm.Page.getAttribute(vetUItempfield).getValue();
	if (vetUIds == null) vetUIds = ""; // need to pass in a blank and not null
    if (btnClicked == 'btnAddRequest') {
        try {
            if (vetUIds != "") {
                vetUIds += "|" + (kvpname.indexOf("consults") >= 0 ? oData.consultUId : kvpname.indexOf("appointments") >= 0 ? oData.appUId : oData.consultUId);
            }
            else if (vetUIds == "") {
                vetUIds += (kvpname.indexOf("consults") >= 0 ? oData.consultUId : kvpname.indexOf("appointments") >= 0 ? oData.appUId : oData.consultUId);
			}
            // set the temporary field
            parent.Xrm.Page.getAttribute(vetUItempfield).setValue(vetUIds);
            console.log("Added consult: " + (kvpname.indexOf("consults") >= 0 ? oData.consultUId : kvpname.indexOf("appointments") >= 0 ? oData.appUId: oData.consultUId) + " to temporary field");
			
			if (kvpname.indexOf("appointments") >= 0) {
				// compare the selected app's date with the current date in CRM, if it's earlier then override the value
				crmAppointmentDateTime = window.parent.Xrm.Page.getAttribute(appointmentDateTimeField).getValue();
				// the date from the web service is the vetUId in the format YYYYMMDDTTTT, which needs to be parsed in order to convert to UTC datetime
				var selectedAppointmentDateTime = stringToDate(oData.appUId);
				if (crmAppointmentDateTime) {
					if (selectedAppointmentDateTime < crmAppointmentDateTime) {
						// if the selected appointment is less than the current crm appointment field, override it, otherwise keep the existing value
						window.parent.Xrm.Page.getAttribute(appointmentDateTimeField).setValue(selectedAppointmentDateTime);
					}
				}
				else window.parent.Xrm.Page.getAttribute(appointmentDateTimeField).setValue(selectedAppointmentDateTime);
			}
        }
        catch (err) {
            alert("There was an error adding the requested item! Please contact your Administrator");
        }
    }
    else if (btnClicked == 'btnRemRequest') {
        try {
            vetUIds = vetUIds.split("|");
            if (vetUIds != "") {
                // get the index of the matching consultUId or appUId
                var index = FindIndex(vetUIds, (kvpname.indexOf("consults") >= 0 ? oData.consultUId : kvpname.indexOf("appointments") >= 0 ? oData.appUId : oData.consultUId));
                vetUIds.splice(index, 1);
                vetUIds.join('|');
				vetUIds = String(vetUIds);
            }
            else if (vetUIds == "") {
                alert("ERROR: There isn't an association to this " + entityInfo.entity + " for item: " + (kvpname.indexOf("consults") >= 0 ? oData.consultUId : kvpname.indexOf("appointments") >= 0 ? oData.appUId : oData.consultUId));
            }

            parent.Xrm.Page.getAttribute(vetUItempfield).setValue(vetUIds);
        }
        catch (err) {
            alert("There was an error removing the requested item! Please contact your Administrator");
        }
    }
}

// useable function to loop through an array and find the index for the matching string
function FindIndex(array, string) {
    if (array != null && string != null) {
        for (var i = 0; i < array.length; i++) {
            if (array[i] == string) {
                return i;
                break;
            }
            else continue;
        }
    }
}

function getEntityData(kvpname) {
    // If we're on the Requests (incident)/Interaction (bah_interactions) entity, we need to get the AddRemove version of the Consults and Appointments, & Notes
    // temp field and UId field
    var entity = window.parent.Xrm.Page.data.entity.getEntityName();
    console.log("entity = " + entity);
    if ((entity == 'incident' || entity == 'bah_interactions') && (kvpname == 'hdr_appointments' || kvpname == 'hdr_notes' || kvpname == 'hdr_consults' || kvpname == 'hdr_appointments_addremove' || kvpname == 'hdr_consults_addremove' || kvpname == 'hdr_notes_addremove' )) { 
        if (kvpname.indexOf("_addremove") <= 0) {
            kvpname = kvpname + '_addremove';
            console.log("kvpname = " + kvpname);
        }
        var vetUItempfield = "";
        var vetUIdsfield = "";
        var vetUIds = "";
        // get field names for the corresponding entities
        switch (entity) {
            case "incident": // Requests
                if (kvpname.indexOf("hdr_consults") >= 0) { // consults
                    vetUIdsfield = "vhacrm_consult_id_list";
                    vetUItempfield = "vhacrm_vetconsultuidstempfield_text";
                }
                else if (kvpname.indexOf("hdr_appointments") >= 0) { // else if, appointments
                    vetUIdsfield = "vhacrm_appt_id_list";
                    vetUItempfield = "vhacrm_vetappidtempfield_text";
                    var appointmentDateTime = "vhacrm_appointmentdatetime_date";
                }
                else if (kvpname.indexOf("hdr_notes") >= 0) { // else, notes
                    vetUIdsfield = "vhacrm_notes_id_list";
                    vetUItempfield = "vhacrm_vetnotesidtempfield_text";
                }
            break;
			// interactions not hooked up yet
            case "bah_interactions": // Interactions
                if (kvpname.indexOf("hdr_consults") >= 0) { // consults
					vetUIdsfield = "vhacrm_vetconsultidstempfield_text";
					vetUItempfield = "vhacrm_vetconsultidstempfield_text";
				}
				else if (kvpname.indexOf("hdr_appointments") >= 0) { // else, appointments
					vetUIdsfield = "vhacrm_vetappidtempfield_text";
					vetUItempfield = "vhacrm_vetappidtempfield_text";
					var appointmentDateTime = "vhacrm_appointmentdatetime_date";
				}
				else if (kvpname.indexOf("hdr_notes") >= 0) { // else, notes
				    vetUIdsfield = "vhacrm_vetnotesidtempfield_text";
				    vetUItempfield = "vhacrm_vetnotesidtempfield_text";
				}
                break;
            default:
                break;
        }
		
        vetUIds = window.parent.Xrm.Page.getAttribute(vetUIdsfield).getValue();
		if (vetUIds == null) vetUIds = ""; // need to pass in a blank and not null
		return {
			kvpname: kvpname,
			vetUIds: vetUIds,
			vetUItempfield: vetUItempfield,
			appointmentDateTime: appointmentDateTime,
			entity: entity
		}
    }
	else {
		return {
			kvpname: kvpname,
			vetUIds: ""
		}
	}
}

function stringToDate(date) {
	// YYYYMMDDTTTT
	var min = '00';
	var year = date.slice(0, 4);
	var month = parseInt(date.slice(4, 6));
	var day = date.slice(6, 8);
	var hour = date.slice(8, 10);
	if (date.length = 12) min = date.slice(10, 12);
	var secs = '00';
	var formattedDate = new Date(year + '-' + month + '-' + day + "T" + hour + ":" + min + ":" + secs + "Z");
	return formattedDate;
}

	
	</script>


</body></html>