function form_OnLoad() {
    if (Xrm.Page.ui.getFormType() == 1) {
        Xrm.Page.getControl("bah_firstname_text").setFocus(true);
        InitialSave();
    }
    if (Xrm.Page.data.entity.attributes.get("bah_veteranid").getValue() != null) {
        loadWebParts();
    }
}

function form_OnSave(context) {
    //   preventAutoSave(context);
}

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 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 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;

        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"
    ];

    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');
}

///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
		}
	);
}