function form_OnLoad() {
    if (Xrm.Page.ui.getFormType() == 1) {
        Xrm.Page.getControl("bah_firstname_text").setFocus(true);
        InitialSave();
    }
	
	// sync temporary vet fields if request exists
	var request = Xrm.Page.getAttribute("vhacrm_requestid").getValue();
	if (request) {
		var id = request[0].id;
		SyncSideBarFields(id);
	}
    if (Xrm.Page.data.entity.attributes.get("bah_veteranid").getValue() != null) {
        loadWebParts();
    }
	else showSensitiveVetMode(true);
}

function form_OnSave(context) {
    //   preventAutoSave(context);
    // check for validation
    // deprecated
    // checkConsultForReferrals(context);
	
	// sync veteran sidebar fields with the related request
	SaveSideBarFieldsToRequest();
}

function area_OnChange() {
 //   Xrm.Page.data.entity.save();
    Xrm.Page.getAttribute("vhacrm_subareaintersectionid").setValue(null);
 //   Xrm.Page.getAttribute("vhacrm_topicresolutionintersectionid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_actionintersectionid").setValue(null);
}

function veteran_OnChange() {
    DisplayPleaseWaitNotification();
    DisplayNotification();
    Xrm.Page.data.entity.save();
    loadWebParts();

    /*    //test - 
        Xrm.Page.data.save().then(
            function(){
                //Xrm.Page.data.refresh();
                loadWebParts();
            },
            function(){
                alert('could not save record');
            }
        ); */
}

function request_OnChange() {
	loadWebParts();
}
function dob_OnChange() { refreshMVI(); }

function firstName_OnChange() { refreshMVI(); }

function lastName_OnChange() { refreshMVI(); }

function ssn_OnChange() { refreshMVI(); }

function topicResolution_OnChange() { Xrm.Page.data.entity.save(); }

function topicAction_OnChange() { Xrm.Page.data.entity.save(); }

function InitialSave() {
    var chkInteractionNbr = Xrm.Page.getAttribute("hrc_interactionno_text").getValue();

    //validate recordid
    if (chkInteractionNbr == null) {
        Xrm.Page.data.entity.save();
        Xrm.Page.getControl("bah_firstname_text").setFocus(true);
    }
}

function preventAutoSave(econtext) {
    var eventArgs = econtext.getEventArgs();

    if (eventArgs.getSaveMode() == 70) {
        eventArgs.preventDefault();
    }
}

function getRequestObject() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex) {
            return null;
        }
    }
}

function makeRequest(query) {
    var serverUrl = Xrm.Page.context.getClientUrl();
    var oDataEndpointUrl = serverUrl += "/XRMServices/2011/OrganizationData.svc/";
    oDataEndpointUrl += query;

    var service = getRequestObject();

    if (service != null) {
        service.open("GET", oDataEndpointUrl, false);
        service.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        service.setRequestHeader("Accept", "application/json, text/javascript, */*");
        service.send(null);

        var retrieved = JSON.parse(service.responseText).d;

        var results = new Array();
        for (var i = 0; i < retrieved.results.length; i++) {
            results.push(retrieved.results[i]);
        }
        return results;
    }
    return '0';
}

// deprecated
function checkConsultForReferrals(context) {
    var request = Xrm.Page.getAttribute("vhacrm_requestid").getValue();
    if (request) {
        // check for the conditions request action = authorization / referral investigation & routing reason = approved consult w/o referral
        var actionId = "";
        var actionRecord = Xrm.Page.getAttribute("vhacrm_actionintersectionid").getValue();
        if (actionRecord) {
            actionId = actionRecord[0].id;
            actionId.toString();
        }
        if (actionId && Xrm.Page.getAttribute("vhacrm_routingreason_code").getValue() == '713770001') {
            // place holder variables
            var actionOptions = ['{48B21CBE-E61E-E711-812A-1289A8FDD3DA}', '{1389B2F3-C11F-E711-812A-1289A8FDD3DA}', '{E8B874FD-852F-E711-812A-1289A8FDD3DA}'];
            var match = false;
            var requestInfo = "";
            var noteQuery = "AnnotationSet?$select=*&$filter=substringof('Consult Title', NoteText) eq true and ObjectId/Id eq guid'" + request[0].id + "'";
            var requestQuery = "IncidentSet?$select=*&$filter=IncidentId/Id eq guid'" + request[0].id + "'";
            for (var i = 0; i < actionOptions.length; i++) {
                if (actionId.toUpperCase() == actionOptions[i]) {
                    match = true;
                    break;
                }
            }
            if (match == true) {
                // check to see if a consult or note exists
                if (Xrm.Page.getAttribute("vhacrm_vetconsultidstempfield_text").getValue() != null && Xrm.Page.getAttribute("vhacrm_vetconsultidstempfield_text").getValue() != "") {
                    // passes, do nothing
                }
                else if (Xrm.Page.getAttribute("vhacrm_interaction_request_notes").getValue() != null && Xrm.Page.getAttribute("vhacrm_interaction_request_notes").getValue() != "") {
                    // passes, do nothing
                }
                else if (makeRequest(noteQuery).length > 0) {
                    // passes, do nothing
                }
                // check request fields
                else if (requestInfo = makeRequest(requestQuery).length > 0) {
                    for (var p = 0; requestInfo.length > 0; p++) {
                        if (requestInfo[p].vhacrm_consult_Id_List != null && requestInfo[p].vhacrm_consult_Id_List != "") {
                            // passes, do nothing
                        }
                        else if (requestInfo[p].vhacrm_requestnotes_memo != null && requestInfo[p].vhacrm_requestnotes_memo != "") {
                            // passes, do nothing
                        }
                        else {
                            // display error message and prevent autosave
                            var eventArgs = context.getEventArgs();
                            if (eventArgs) eventArgs.preventDefault();
                            prompt("A consult is needed for this process. Please attach a consult, or complete the following fields in the Notes box:",
                                 "Date*"
                                + "\nConsult Title*"
                                + "\nRequesting Provider"
                                + "\nConsult Status"
                                + "\nConsult Number*"
                                + "\nConsult Urgency");
                        }
                    }
                }
                else {
                    // display error message and prevent autosave
                    var eventArgs = context.getEventArgs();
                    if (eventArgs) eventArgs.preventDefault();
                    prompt("A consult is needed for this process. Please attach a consult, or complete the following fields in the Notes box:",
                         "Date*"
                        + "\nConsult Title*"
                        + "\nRequesting Provider"
                        + "\nConsult Status"
                        + "\nConsult Number*"
                        + "\nConsult Urgency");
                }
            }
        }
    }
}

function DisplayPleaseWaitNotification() {
    var message = "Please wait while Request is being created ";
    var type = "INFO"; //INFO, WARNING, ERROR
    var id = "Info1"; //Notification Id
    var time = 5000; //Display time in milliseconds

    //Display the notification
    Xrm.Page.ui.setFormNotification(message, type, id);

    //Wait the designated time and then remove
    setTimeout(
        function () {
            Xrm.Page.ui.clearFormNotification(id);
        },
        time
    );
}

function DisplayNotification() {
    var message = "Required Fields Must be Filled In to Create the Request for the Veteran";
    var type = "ERROR"; //INFO, WARNING, ERROR
    var id = "Info1"; //Notification Id
    var time = 3000; //Display time in milliseconds
    var firstname = Xrm.Page.data.entity.attributes.get("bah_firstname_text").getValue();
    var phonenumber = Xrm.Page.data.entity.attributes.get("bah_phonenumber_text").getValue();
    var tin = Xrm.Page.data.entity.attributes.get("ccwf_tin_text").getValue();
    var providerfacility = Xrm.Page.data.entity.attributes.get("ccwf_providerfacility_text").getValue();
    var isProvider = Xrm.Page.getAttribute("bah_interactedwith_code").getText();

    if (isProvider != "Provider") {
        return;
    }
    //Display the notification
    if (firstname == null) {
        Xrm.Page.ui.setFormNotification(message, type, id);
    }
    if (phonenumber == null) {
        Xrm.Page.ui.setFormNotification(message, type, id);
    }
//    if (tin == null) {
//       Xrm.Page.ui.setFormNotification(message, type, id);
//    }
}

function N52Callback(callbackname) {
    switch (callbackname) {
 /*
        case "addclaim":
            Xrm.Page.ui.controls.get("Claims").refresh();
            break;

        case "newtopicnewvet":
            //wait before clearing fields, to let the form finish saving after clicking the button.
            setTimeout(clearFieldsForNewTopicNewVetClick, 250);
            break;

        case "newtopicsamevet":
            setTimeout(setFieldsForNewTopicSameVetClick, 250);
            break;
*/
        case "emailalert":
            alert("Email has been sent");
        default:
            break;
    }
}

function setFieldsForNewTopicSameVetClick() {

    Xrm.Page.getAttribute("ccwf_createadditionalrequest_bool").setValue(true);
    Xrm.Page.data.entity.save();
}


function clearFieldsForNewTopicNewVetClick() {

    var fieldsToClear = [

         "vhacrm_request_beginningdate_date"
       , "vhacrm_actionintersectionid"
       , "vhacrm_topicresolutionintersectionid"
       , "vhacrm_request_methodofdelivery_code"
       , "vhacrm_request_endingdate_date"
       , "vhacrm_request_address1_attentionline_text"
       , "vhacrm_request_address1_line1_text"
       , "vhacrm_request_address1_city_text"
       , "vhacrm_request_address1_stateid"
       , "vhacrm_request_address1_postalcode_text"
       , "vhacrm_request_email_text"
       , "vhacrm_request_fax_text"
       , "vhacrm_claimnumber_text"
       , "vhacrm_billedamount_currency"
       , "vhacrm_startdateofservice_date"
       , "vhacrm_enddateofservice_date"
       , "vhacrm_claimid"
       , "vhacrm_stationwithactivityid"
       , "vhacrm_stationtobeloadedtoid"
	   , "vhacrm_vetconsultuidstempfield_text"
       , "vhacrm_vetappidtempfield_text"
	   , "vhacrm_appointmentdatetime_date"
    ];

    for (var i = 0, l = fieldsToClear.length; i < l; i++) {
        Xrm.Page.getAttribute(fieldsToClear[i]).setValue();
    }
}


function loadWebParts() {
    unattendedSearchFromRelatedRecord("bah_veteranid", loadESRWebParts);
}

function loadESRWebParts(icn) {
    //pass icn, folder path and list of control names/resource names to the loadEsrResources function
    loadEsrResources(icn, '/webresources/vhacrm_/ESRParts', 'WebResource_Eligibility_Mini|Eligibility_Mini.htm,WebResource_Insurance_Mini|Insurance_Mini.htm');
	getICN('IFRAME_veteransidebar', icn);
}

///takes icn, path to web resources (starting from root CRM url) and list of form control names and web resource names as arguments
///example - loadEsrResources(icn, '/webresources/vhacrm_/ESRParts', 'WebResource_enrollment|enrollment.htm,WebResource_esreligibility|eligibility.htm,WebResource_demographics|demographics.htm');
function loadEsrResources(icn, resourcepath, resourceparam) {
    SDK.REST.retrieveMultipleRecords("bah_keyvaluepair",
		"$select=*&$filter=bah_name_text eq 'esr_endpoint'",
		function (data) {
		    if (data.length > 0) {
		        //figure out the full url to the BAH esr proxy
		        var esrEndpoint = data[0].bah_stringvalue_text;
		        var actualEndpoint = esrEndpoint.replace('{0}', '000000' + icn + '000000'); //pad ICN with six zeroes on beginning and end

		        //build the querystring to call the page that will query esr and display the data - note CRM requires everything be encoded and passed in a 'data' parameter
		        var qs = 'data=' + encodeURIComponent('esr=' + encodeURIComponent(actualEndpoint));

		        var resourcearr = resourceparam.split(',');

		        if (resourcearr.length > 0) {
		            for (var i = 0; i < resourcearr.length; i++) {
		                try {
		                    //start with assumption that resource name and control name are the same
		                    var controlname = "";
		                    var webresourcename = "";

		                    //check to see if we have pipe-separated value -> control name should be first, resource name should be second
		                    if (resourcearr[i].indexOf('|') > 0) {
		                        controlname = resourcearr[i].split('|')[0];
		                        webresourcename = resourcearr[i].split('|')[1];
		                    }
		                    else {
		                        throw ("ESR resource target control and resource name not supplied in correct format.")
		                    }

		                    //get a reference to the iframe
		                    var webresource = Xrm.Page.ui.controls.get(controlname);
		                    if (webresource == null) {
		                        throw ("Could not find ESR resource target control with name - '" + controlname + "'");
		                    }

		                    //set the iframe's url
		                    var webresourceUrl = Xrm.Page.context.getClientUrl() + resourcepath + '/' + webresourcename + '?' + qs;
		                    webresource.setSrc(webresourceUrl);
		                }
		                catch (err) { alert(err); }
		            }
		        }
		    }
		},
		function (error) {
		    //do nothing
		},
		function () {
		    //do nothing on completion
		}
	);
}



function interactionpurposeid_OnChange(){

     var arrpurposeid = new Array;
    arrpurposeid[0] = new Object();
    arrpurposeid = Xrm.Page.getAttribute("vhacrm_interactionpurposeid").getValue();
    var arrsubpurposeid = new Array;
    arrsubpurposeid = Xrm.Page.getAttribute("vhacrm_interactionsubpurposeid").getValue();

    // if subpurposeID is not empty, check to see if it relates to the new interactionPurposeID (Sub Area Intersection Lookup View)
    if (arrsubpurposeid != null && arrpurposeid != null)
        {
        var strSelect = "$select=*&$filter=vhacrm_subareaintersectionId eq(guid'" +  arrpurposeid[0].id.substring(1,37) +"')"; // and vhacrm_subareaid eq '" + arrsubpurposeid[0].id.substring(1,37) + "'";
//alert(strSelect);

        SDK.REST.retrieveMultipleRecords("vhacrm_subareaintersection",
        strSelect,
        function (data) {
            if (data.length > 0) {
                // do nothing - this is ok
            }
            else {
                // if it does not relate to the new purpose, then clear it out...
                Xrm.Page.getAttribute("vhacrm_interactionsubpurposeid").setValue(null);
            }
        },
 function (error) {
            //do nothing
            //alert(error.message);
        },
        function () {
            //do nothing on completion
        });
        }

}

function SyncSideBarFields(id) {
	// retrieve request record and check if vet ids contains data, if it does then update interaction
	SDK.REST.retrieveRecord(id.toString(), "Incident", "vhacrm_consult_Id_List,vhacrm_appt_Id_List,vhacrm_notes_id_list", null, retrieveRequestSuccessCallBack, retrieveRequestErrorCallBack);
}

function retrieveRequestSuccessCallBack(result) {
	var consultIds = result.vhacrm_consult_Id_List;
	var appIds = result.vhacrm_appt_Id_List;
	var notesIds = result.vhacrm_notes_id_list;
	if (Xrm.Page.getAttribute("vhacrm_vetconsultidstempfield_text").getValue() != consultIds) {
		Xrm.Page.getAttribute("vhacrm_vetconsultidstempfield_text").setValue(consultIds);
	}
	if (Xrm.Page.getAttribute("vhacrm_vetappidtempfield_text").getValue() != appIds) {
		Xrm.Page.getAttribute("vhacrm_vetappidtempfield_text").setValue(appIds);
	}
	if (Xrm.Page.getAttribute("vhacrm_vetnotesidtempfield_text").getValue() != notesIds) {
	    Xrm.Page.getAttribute("vhacrm_vetnotesidtempfield_text").setValue(notesIds);
	}
}

function retrieveRequestErrorCallBack() {
	// do nothing
}

// syncs the interaction temporary sidebar fields to the active request
function SaveSideBarFieldsToRequest() {
	var requestId = "";
	var type = [];
	var vetUIds = "";
	var appUIds = "";
	var notesUIds = "";
	var crmAppointmentDateTime = "";
	var request = Xrm.Page.getAttribute("vhacrm_requestid").getValue();
	if (request) {
		requestId = request[0].id;
	}
	
	// if consults changed	
	if (Xrm.Page.getAttribute("vhacrm_vetconsultidstempfield_text").getIsDirty()) {
		type.push("consults");
		vetUIds = Xrm.Page.getAttribute("vhacrm_vetconsultidstempfield_text").getValue();
	}
	
	// if appointments changed
	if (Xrm.Page.getAttribute("vhacrm_vetappidtempfield_text").getIsDirty()) {
		type.push("app");
		appUIds = Xrm.Page.getAttribute("vhacrm_vetappidtempfield_text").getValue();
		crmAppointmentDateTime = Xrm.Page.getAttribute("vhacrm_appointmentdatetime_date").getValue();
	}

    // if notes changed
	if (Xrm.Page.getAttribute("vhacrm_vetnotesidtempfield_text").getIsDirty()) {
	    type.push("notes");
	    notesUIds = Xrm.Page.getAttribute("vhacrm_vetnotesidtempfield_text").getValue();
	}
	
	if (requestId) {
		UpdateRequest(requestId, vetUIds, appUIds, notesUIds, crmAppointmentDateTime, type);
	}
}

function UpdateRequest(requestId, vetUIds, appUIds, notesUIds, crmAppointmentDateTime, type) {
	var request = {};
	for (var i = 0; i < type.length; i++) {
		switch (type[i]) {
			case "consults":
				request.vhacrm_consult_Id_List = vetUIds;
			    request.vhacrm_vetConsultUIdstempfield_text = vetUIds;
				break;
		    case "app":
		        request.vhacrm_appt_Id_List = appUIds;
		        request.vhacrm_vetappidtempfield_text = appUIds;
		        request.vhacrm_appointmentdatetime_date = crmAppointmentDateTime;
		        break;
		    case "notes":
		        request.vhacrm_notes_id_list = notesUIds;
		        request.vhacrm_vetnotesidtempfield_text = notesUIds;
		        break;
			default:
				break;
		}
	}
	console.log("Updating request: " + requestId.toString());
	SDK.REST.updateRecord(requestId.toString(), request, "Incident", UpdateRequestCallBack, UpdateRequestErrorCallBack);
}

function UpdateRequestCallBack(data) {
	console.log("Fields updated on Request");
}

function UpdateRequestErrorCallBack(error) {
	alert(error.message);
}