var _intervalVar = null;
var _userTimeZone = "";

function form_OnLoad() {
    if (Xrm.Page.ui.getFormType() != 1) { loadLOBForm(); }

    if (Xrm.Page.getAttribute("vhacrm_isassist_bool") != null) {
        Xrm.Page.getAttribute("vhacrm_isassist_bool").setSubmitMode("never");
    }

    if (Xrm.Page.getAttribute("vhacrm_dayssincelastcontact_text") != null) {
        Xrm.Page.getAttribute("vhacrm_dayssincelastcontact_text").setSubmitMode("always");
    }
    if (Xrm.Page.ui.getFormType() == 4) {
		Xrm.Page.getControl("WebResource_CompleteInteraction").setVisible(false);
		Xrm.Page.getControl("WebResource_completecasenote").setVisible(false);
		Xrm.Page.getControl("WebResource_mvisearch").setVisible(false);
		Xrm.Page.getControl("WebResource_CreateCorrespondence").setVisible(false);
		Xrm.Page.getControl("WebResource_sendformrequests").setVisible(false);
    }
    else {
        if (Xrm.Page.getAttribute("vhacrm_interactionno_text").getValue() && Xrm.Page.getAttribute("bah_veteranid").getValue()) {
            Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_correspondencebutton").setVisible(true);
        }
        else {
            Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_correspondencebutton").setVisible(false);
        }
    }

    //Default the case notes for new interactions
    if (Xrm.Page.ui.getFormType() == 1) { setCaseNoteDefault(); } 

    //show/hide sections and tabs
    checkResolution();

    //check for default subareas
    checkSubareas();

    //load ESR, VISTA web parts
    loadWebParts();

    //Get User Timezone
    getUserTimeZone();
}

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

function firstname_OnChange() { refresh.firstname_OnChange(); }

function lastname_OnChange() { refresh.lastname_OnChange(); }

function dob_OnChange() { refresh.dob_OnChange(); }

function ssn_OnChange() { refresh.ssn_OnChange(); }

function edipi_OnChange() { refresh.edipi_OnChange(); }

function gender_OnChange() { refresh.gender_OnChange(); }

function daytimePhone_OnChange() { refresh.daytimePhone_OnChange(); }

function type_OnChange(context) {
    Xrm.Page.getAttribute("vhacrm_areaintersectionid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_subareaintersectionid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_resolutionintersectionid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_casenotetemplateid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_subareaintersectionid").setRequiredLevel("none");
    Xrm.Page.getAttribute("vhacrm_casenotetemplateid").setRequiredLevel("none");
    Xrm.Page.getAttribute("vhacrm_assist_casenotetemplateid").setValue(null);
    N52.Clientside.ExecuteFormulas(context, 'yDn');
}

function checkVeteran() {
    if (Xrm.Page.getAttribute("bah_veteranid").getValue()) {
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo").setVisible(true);
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo_input").setVisible(false);
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_correspondencebutton").setVisible(true);
        Xrm.Page.ui.tabs.get("tab_History").setDisplayState("expanded");
        Xrm.Page.ui.tabs.get("tab_veteransearch").setDisplayState("collapsed");
    }
    else {
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo_input").setVisible(true);
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo").setVisible(false);
        Xrm.Page.ui.tabs.get("tab_History").setDisplayState("collapsed");
        if (Xrm.Page.getAttribute("vhacrm_interactionno_text").getValue()) {
            Xrm.Page.ui.tabs.get("tab_veteransearch").setDisplayState("expanded");
        }
    }
}

function area_OnChange(context) {
    Xrm.Page.data.save().then(area_Callback(), function (err) { alert(err); });
}
function area_Callback() {
    checkSubareas();
    Xrm.Page.getAttribute("vhacrm_subareaintersectionid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_casenotetemplateid").setValue(null);
    Xrm.Page.getAttribute("vhacrm_assist_casenotetemplateid").setValue(null);
}

function resolution_OnChange(context) {
    checkResolution();
    setDescription();
}

function checkResolution() {
    var resolutionintersectionid = Xrm.Page.getAttribute("vhacrm_resolutionintersectionid").getValue();
    var areaintersectionid = Xrm.Page.getAttribute("vhacrm_areaintersectionid").getValue();

    if (resolutionintersectionid) {
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_complete").setVisible(true);

        //if resolution = "Escalated", then require the template if there are templates for the area.

        if (resolutionintersectionid[0].name == "Escalated") {
            var oDataSetName = "vhacrm_casenotetemplate";
            var filter = "vhacrm_areaintersectionid/Id eq (guid'" + areaintersectionid[0].id.toString() + "') and statecode/Value eq 0";
            var columns = "*";
            var querystring = "$select=" + columns + "&$filter=" + filter;
            SDK.REST.retrieveMultipleRecords(
			    oDataSetName,
			    querystring,
			    function (data) {
			        if (data.length > 0) {
			            Xrm.Page.getAttribute('vhacrm_casenotetemplateid').setRequiredLevel('required');
			        }
			        else {
			            Xrm.Page.getAttribute('vhacrm_casenotetemplateid').setRequiredLevel('none');
			        }
			    },
			    function (error) {
			        //do nothing
			        alert(error);
			    },
			    function () {
			        //do nothing on completion
			    }
		    );
        }
        else {
            Xrm.Page.getAttribute('vhacrm_casenotetemplateid').setRequiredLevel('none');
        }
    }
    else {
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_complete").setVisible(false);
    }
}

function caseNoteTemplate_OnChange(context) {
    appendTemplateText();
}

function correspondenceHistory_TabStateChange() {
    // Refresh quick view form
    if (Xrm.Page.ui.tabs.get("tab_correspondencehistory").getDisplayState() == 'expanded') {
        var currentvalue = Xrm.Page.getAttribute("bah_veteranid").getValue()
        Xrm.Page.getAttribute("bah_veteranid").setValue(null);
        Xrm.Page.getAttribute("bah_veteranid").setValue(currentvalue);
    }
}

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

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

function loadAssociations(icn) {
    displayWebPart(icn, 'IFRAME_associations', 'esr_associations_endpoint');
}

function loadESRWebParts(icn) {
    //pass icn, folder path and list of control names/resource names to the loadEsrResources function
    loadEsrResources(icn, '/webresources/vhacrm_/ESRParts', 'WebResource_enrollment|enrollment.htm,WebResource_esreligibility|eligibility.htm,WebResource_demographics|demographics.htm');
}


function checkDescription() {
    var desc = Xrm.Page.getAttribute("vhacrm_description_memo").getValue();
    if (desc) { setDescription() };
}

function setDescription() {
    var desc = "";
    var now = LocalDateTimeNow();
    var description = Xrm.Page.getAttribute("vhacrm_description_memo");
    var dob = Xrm.Page.getAttribute("bah_dob_date");
    var casenote = Xrm.Page.getAttribute("vhacrm_casenotes_memo");

    
    if (now) {
        desc = desc.concat(now.format("MM/dd/yyyy hh:mm tt")," ", _userTimeZone, "\n");
    }

    if (description) {
        description.setValue(desc);
    }
}

function getUserTimeZone() {
    var timeZone = "";
    var timeZoneCode = 0;
    var oDataSetName = "UserSettings";
    var filter = "SystemUserId eq (guid'" + Xrm.Page.context.getUserId() + "')";
    var columns = "*";
    var querystring = "$select=" + columns + "&$filter=" + filter;
    SDK.REST.retrieveMultipleRecords(
        oDataSetName,
		querystring,
		function (data) {
		    if (data.length > 0) {
		        timeZoneCode = data[0].TimeZoneCode;
		        if (timeZoneCode > 0) {
		            var oDataSetName = "TimeZoneDefinition";
		            var filter = "TimeZoneCode eq (" + timeZoneCode + ")";
		            var columns = "*";
		            var querystring = "$select=" + columns + "&$filter=" + filter;
		            SDK.REST.retrieveMultipleRecords(
                        oDataSetName,
                        querystring,
                        function (data) {
                            if (data.length > 0) {
                                timeZone = data[0].StandardName;
                                timeZone = timeZone.substring(0, 1) + "T";
                                _userTimeZone = timeZone;
                            }
                        },
                        function (error) {
                            alert(error);
                            //do nothing
                        },
                        function () {
                            //do nothing on completion
                        }
                    );
		        }
		    }
		},
		function (error) {
			alert(error);
			//do nothing
		},
		function () {
			//do nothing on completion
		}
    );
}

// If there is only one Sub Area, make it the default
function checkSubareas() {
    var areaintersectionid = Xrm.Page.getAttribute("vhacrm_areaintersectionid").getValue();
    if (areaintersectionid) {
        var oDataSetName = "vhacrm_subareaintersection";
        var filter = "vhacrm_areaintersectionid/Id eq (guid'" + areaintersectionid[0].id.toString() + "') and statecode/Value eq 0";
        var columns = "*";
        var querystring = "$select=" + columns + "&$filter=" + filter;
        SDK.REST.retrieveMultipleRecords(
			oDataSetName,
			querystring,
			function (data) {
				if (data.length > 0) {
				    Xrm.Page.getAttribute('vhacrm_subareaintersectionid').setRequiredLevel('required');
				}
				else {
				    Xrm.Page.getAttribute('vhacrm_subareaintersectionid').setRequiredLevel('none');
				}
			},
			function (error) {
				alert(error);
				//do nothing
			},
			function () {
				//do nothing on completion
			}
		);
    }
}

function setCaseNoteDefault() {
	var casenotetext = Xrm.Page.getAttribute("vhacrm_casenotes_memo");
	if (casenotetext.getValue() == null) { casenotetext.setValue("Caller:\r\nIssue:\r\nResolution:\r\n"); }
}

function appendTemplateText() {
	var templateid = Xrm.Page.getAttribute("vhacrm_casenotetemplateid").getValue();
	var existingcasenotetext = Xrm.Page.getAttribute("vhacrm_casenotes_memo").getValue();

    if (templateid) {
        SDK.REST.retrieveRecord(
			templateid[0].id.toString(),
			"vhacrm_casenotetemplate",
			"vhacrm_template_memo",
			null,
			function (data) {
				var casenotetext = data.vhacrm_template_memo;
				if (casenotetext) {
					if (existingcasenotetext) {
						casenotetext = existingcasenotetext + "\r\n------------\r\n" + casenotetext;
					}
					Xrm.Page.getAttribute("vhacrm_casenotes_memo").setValue(casenotetext);
				}
				Xrm.Page.getAttribute("vhacrm_temp_text").setValue(null);
			},
			function (error) {
			    //do nothing
			    alert(error);
			}
		);
    }
}
