var _intervalVar = null;
var userid = Xrm.Page.context.getUserId();
var positionid = GetPositionIDFortheUser(userid);

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);
	}
	else {
	    var vetValue = Xrm.Page.getAttribute("bah_veteranid").getValue();
 		if (vetValue) {
			if (Xrm.Page.getAttribute("vhacrm_interactionno_text").getValue() && vetValue[0].name != "No Veteran") {
				if (positionid.toUpperCase() != "FC110E98-32D8-E611-8126-127B25DCBDE7"){
					Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_correspondencebutton").setVisible(true);
				}
				Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_contact_method").setVisible(true);
			}
			else {
				Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_correspondencebutton").setVisible(false);
				Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_contact_method").setVisible(false);
			}
		}
	}
	Xrm.Page.ui.controls.get("IFRAME_addresses").setSrc("/WebResources/vhacrm_/ESRParts/Blank.htm");

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

    //check for subareas and templates asynchronously
	checkAreas(false);
	checkSubareas();
	//checkTemplates();

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

}


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);
    Xrm.Page.data.save().then(type_Callback(), function (err) { alert(err); });
	checkVeteran();
}




function checkVeteran() {
    //show and hide sections according to veteran
    var vetValue = Xrm.Page.getAttribute("bah_veteranid").getValue();
    if (vetValue) {
        switch (vetValue[0].name) {
            case "No Veteran, No Veteran":
				Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo_input").setVisible(false);
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo").setVisible(true);
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veterancontact").setVisible(false);
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("tab_verificationmethods").setVisible(false);
                Xrm.Page.ui.tabs.get("tab_verificationmethodslist").setDisplayState("collapsed")
                Xrm.Page.ui.tabs.get("tab_History").setDisplayState("collapsed");
                Xrm.Page.ui.tabs.get("tab_veteransearch").setDisplayState("collapsed");
			default:
				Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo_input").setVisible(false);
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veteraninfo").setVisible(true);
                Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_veterancontact").setVisible(true);
                Xrm.Page.ui.tabs.get("tab_History").setDisplayState("collapsed");
                Xrm.Page.ui.tabs.get("tab_veteransearch").setDisplayState("collapsed");
				if (Xrm.Page.getAttribute("vhacrm_interactionno_text").getValue()) {
					Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_contact_method").setVisible(true);
					Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("tab_verificationmethods").setVisible(true);
					Xrm.Page.ui.tabs.get("tab_verificationmethodslist").setDisplayState("expanded");
					if (positionid.toUpperCase() != "FC110E98-32D8-E611-8126-127B25DCBDE7"){
						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);
					Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_contact_method").setVisible(false);
					Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("tab_verificationmethods").setVisible(false);
					Xrm.Page.ui.tabs.get("tab_verificationmethodslist").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_interactioninformation").sections.get("section_veterancontact").setVisible(false);
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("tab_verificationmethods").setVisible(false);
		Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_correspondencebutton").setVisible(false);
		Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_contact_method").setVisible(false);
        Xrm.Page.ui.tabs.get("tab_verificationmethodslist").setDisplayState("collapsed")
        Xrm.Page.ui.tabs.get("tab_veteransearch").setDisplayState("expanded");
        Xrm.Page.ui.tabs.get("tab_History").setDisplayState("collapsed");
    }
}

function area_OnChange(context) {
    Xrm.Page.data.save().then(area_Callback(), function (err) { alert(err); });
	checkVeteran();
}
function ForRoutingOnly_OnChange(context) {
	checkAreas(false);
	checkSubareas();
	checkTemplates();
	checkVeteran();
}
function type_Callback() {
    checkVeteran();
	checkAreas(false);
    Xrm.Page.getAttribute("vhacrm_areaintersectionid").setValue(null);
    
}

function area_Callback() {
    checkSubareas();
    checkTemplates();
    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();
}

function checkResolution() {
    if (Xrm.Page.getAttribute("vhacrm_resolutionintersectionid").getValue()) {
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_complete").setVisible(true);
    }
    else {
        Xrm.Page.ui.tabs.get("tab_interactioninformation").sections.get("section_complete").setVisible(false);
    }
}

function caseNoteTemplate_OnChange(context) {
    appendTemplateText();
}

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

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

function loadAddresses(icn) {
    displayWebPart(icn, 'IFRAME_addresses', 'esr_addresses_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 checkAreas (sync) {
	var forroutingonly = Xrm.Page.getAttribute("vhacrm_forroutingonly_bool").getValue();
    var typeintersectionid = Xrm.Page.getAttribute("vhacrm_typeintersectionid").getValue();
    if (typeintersectionid) {
        var oDataSetName = "vhacrm_areaintersection";
        var filter = "vhacrm_typeintersectionid/Id eq (guid'" + typeintersectionid[0].id.toString() + "') and statecode/Value eq 0";
        var columns = "*";

        if (sync) {
            var data = retrieveMultipleSync(oDataSetName, columns, filter);
            if (data != null) {
                if (data.length > 0 && forroutingonly == false) {
                    Xrm.Page.getAttribute('vhacrm_areaintersectionid').setRequiredLevel('required');
                }
                else {
                    Xrm.Page.getAttribute('vhacrm_areaintersectionid').setRequiredLevel('none');
                }
            }
        }
        else {
            var querystring = "$select=" + columns + "&$filter=" + filter;
            SDK.REST.retrieveMultipleRecords(
				oDataSetName,
				querystring,
				function (data) {
				    if (data.length > 0 && forroutingonly == false) {
				        Xrm.Page.getAttribute('vhacrm_areaintersectionid').setRequiredLevel('required');
				    }
				    else {
				        Xrm.Page.getAttribute('vhacrm_areaintersectionid').setRequiredLevel('none');
				    }
				},
				function (error) {
				    alert(error);
				    //do nothing
				},
				function () {
				    //do nothing on completion
				}
			);
        }
    }
}
function checkSubareas() {
    var forroutingonly = Xrm.Page.getAttribute("vhacrm_forroutingonly_bool").getValue();
    if (forroutingonly) {
        Xrm.Page.getAttribute('vhacrm_subareaintersectionid').setRequiredLevel('none');
    }
    else {
        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 checkTemplates(sync) {
    var forroutingonly = Xrm.Page.getAttribute("vhacrm_forroutingonly_bool").getValue();
    if (forroutingonly) {
        Xrm.Page.getAttribute('vhacrm_casenotetemplateid').setRequiredLevel('none');
        Xrm.Page.getAttribute('vhacrm_casenotes_memo').setRequiredLevel('none');
    }
    else {
        var areaintersectionid = Xrm.Page.getAttribute("vhacrm_areaintersectionid").getValue();
		var existingcasenotetext = Xrm.Page.getAttribute("vhacrm_casenotes_memo").getValue();
		if (areaintersectionid && existingcasenotetext == null) {
            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');
                        if (data.length == 1) {
                            var lookupReference = [];
                            lookupReference[0] = {};
                            lookupReference[0].id = data[0].vhacrm_casenotetemplateId;
                            lookupReference[0].entityType = 'vhacrm_casenotetemplate';
                            lookupReference[0].name = data[0].vhacrm_name;

                            Xrm.Page.getAttribute("vhacrm_casenotetemplateid").setValue(lookupReference);

                            var casenotetext = data[0].vhacrm_template_memo;
                            var existingcasenotetext = Xrm.Page.getAttribute("vhacrm_casenotes_memo").getValue();
                            if (casenotetext) {
                                if (existingcasenotetext) {
                                    casenotetext = existingcasenotetext + "\r\n------------\r\n" + casenotetext;
                                    Xrm.Page.getAttribute("vhacrm_casenotes_memo").setValue(casenotetext);
                                }
                                else {
                                    Xrm.Page.getAttribute("vhacrm_casenotes_memo").setValue(casenotetext);
                                }
                            }
                        }
                        Xrm.Page.getAttribute("vhacrm_temp_text").setValue(null);
                    }
                    else {
                        Xrm.Page.getAttribute('vhacrm_casenotetemplateid').setRequiredLevel('none');
                        Xrm.Page.getAttribute('vhacrm_casenotes_memo').setRequiredLevel('none');
                    }
                },
                function (error) {
                    //do nothing
                    alert(error);
                },
                function () {
                    //do nothing on completion
                }
            );
        }
    }
}

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

function GetPositionIDFortheUser(userid) {
 
 try {
	var serverUrl = "";
    if (Xrm.Page.context.getClientUrl) {
        //Post UR 12
        serverUrl = Xrm.Page.context.getClientUrl();
    }
    else {
        //Pre UR 12
        serverUrl = Xrm.Page.context.getServerUrl();
    }
        var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
        oDataEndpointUrl += "SystemUserSet?$select=PositionId&$filter=SystemUserId eq guid'" + userid + "'";
        var service = getRequestObject();
        if (service != null) {
            service.open("GET", oDataEndpointUrl, false);
            service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
            service.setRequestHeader("Accept", "application/json,text/javascript, */*");
            service.send(null);

            var requestResults = eval('(' + service.responseText + ')').d;
            if (requestResults != null && requestResults.results.length == 1) {
                var userRecord = requestResults.results[0];
                if (userRecord.PositionId && userRecord.PositionId.Id) {
                    return userRecord.PositionId.Id;
                }
            }
        }

        return "";
   }
    catch (err) {
        return "";
    }
}
//helper function for making xmlhttp requests
function getRequestObject() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex) {
            return null;
        }
    }
}