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

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

	Xrm.Page.ui.controls.get("IFRAME_addresses").setSrc("/WebResources/vhacrm_/ESRParts/Blank.htm");
    loadWebParts();
    checkAreas(false);
	checkVeteran();
  
}


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

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

function area_OnChange(context)
{
	Xrm.Page.data.entity.save();
	Xrm.Page.getAttribute("vhacrm_subareaintersectionid").setValue(null);
	Xrm.Page.getAttribute("vhacrm_casenotetemplateid").setValue(null);
	Xrm.Page.getAttribute("vhacrm_subareaintersectionid").setRequiredLevel("none");
	N52.Clientside.ExecuteFormulas(context, 'Q5i'); 
}

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

function caseNoteTemplate_OnChange(context)
{
    N52.Clientside.ExecuteFormulas(context, 'lSq');
	Xrm.Page.data.entity.save();
}

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

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_esrenrollment|enrollment.htm,WebResource_esreligibility|eligibility.htm,WebResource_esrdemographics|demographics.htm');
}

function loadAddresses(icn) {
    displayWebPart(icn, 'IFRAME_addresses', 'esr_addresses_endpoint');
}

function type_Callback() {
    checkAreas(false);
    Xrm.Page.getAttribute("vhacrm_areaintersectionid").setValue(null);

}

function checkVeteran() {
    //show and hide sections according to veteran
    var vetValue = Xrm.Page.getAttribute("customerid").getValue();
	if (vetValue[0].id == "{1B8680E1-8D87-E611-9422-0050568DADE6}") {
		Xrm.Page.ui.tabs.get("tab_general").sections.get("section_verificationmethods").setVisible(false);
		Xrm.Page.ui.tabs.get("tab_general").sections.get("section_contact_method").setVisible(false);
		Xrm.Page.ui.tabs.get("tab_general").sections.get("section_correspondencebutton").setVisible(false);
		Xrm.Page.ui.tabs.get("tab_verificationmethodslist").setVisible(false);
    }
    else {
		Xrm.Page.ui.tabs.get("tab_general").sections.get("section_verificationmethods").setVisible(true);
		Xrm.Page.ui.tabs.get("tab_general").sections.get("section_contact_method").setVisible(true);
		Xrm.Page.ui.tabs.get("tab_verificationmethodslist").setVisible(true);
		if (positionid.toUpperCase() != "FC110E98-32D8-E611-8126-127B25DCBDE7"){
			Xrm.Page.ui.tabs.get("tab_general").sections.get("section_correspondencebutton").setVisible(true);
		}
		else{
			Xrm.Page.ui.tabs.get("tab_general").sections.get("section_correspondencebutton").setVisible(false);
		}
    }
}

function checkAreas(sync) {

    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) {
                    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) {
				        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 retrieveMultipleSync(odataSetName, select, filter) {
    // Get Server URL
    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 ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    var odataUri = serverUrl + ODATA_ENDPOINT + "/" + odataSetName + 'Set' + "?";
    if (select) {
        odataUri += "$select=" + select;
    }
    if (filter) {
        odataUri += "&" + "$filter=" + filter;
    }
    var service = getRequestObject();
    if (service != null) {
        service.open("GET", odataUri, false);
        service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
        service.setRequestHeader("Accept", "application/json,text/javascript, */*");
        service.send(null);
        var requestResults = eval('(' + service.responseText + ')').d;
        return requestResults;
    }
}

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