//global variable.
var _notProd = true;
var _ICN = "", _EDIPI = "";
var _retrievedSettings = null;
var _summary = null;

function form_onLoad() {
	//fire USD event to fire form_onLoadWithParameters with parameters from USD $Context
	window.open("http://event?eventname=VeteranFormReady");
}

function form_onLoadWithParameters(pICN, pEDIPI){
	/*
	Parameters to this function are passed via a USD action call on the Shared Hidden Veteran's 'PageLoadComplete' event.
	*/
	var thisOrgUrl = Xrm.Page.context.getClientUrl();
    _notProd = thisOrgUrl.indexOf("ftp.dev") > 1 || thisOrgUrl.indexOf("INTFTP") > 1 || thisOrgUrl.indexOf("QAFTP") > 1 || thisOrgUrl.indexOf("PREFTP") > 1;
	
	_ICN = !!pICN ? pICN : "";
	_EDIPI = !!pEDIPI ? pEDIPI : "";
	
	//always do these functions
	unemployableVisibility();
	setSubmitModeOnSomeAttributes();
	resetViersCheckboxesOnLoad();
	
    if (_ICN == "MISSING") {
		/*we've reached this branch by creating a new Contact from the MVI search page,
		so don't perform any more web service calls...
		and unlock some fields... Fields to be left unlocked:  first, last, dob, ssn, current address, phone numbers.
		*/
		var fieldsToUnlock = [
			"firstname",
			"middlename",
			"lastname",
			"governmentid",
			"ftp_dateofbirth",
			"ftp_mobilephone",
			"ftp_homephone",
			"ftp_workphone",
			"address1_composite_compositionLinkControl_address1_line1",
			"address1_composite_compositionLinkControl_address1_line2",
			"address1_composite_compositionLinkControl_address1_line3",
			"address1_composite_compositionLinkControl_address1_city",
			"address1_composite_compositionLinkControl_address1_stateorprovince",
			"address1_composite_compositionLinkControl_address1_postalcode",
			"address1_composite_compositionLinkControl_address1_country"
		];
		
		for(var i = 0; i < fieldsToUnlock.length; i++){
			var con = Xrm.Page.getControl(fieldsToUnlock[i]);
			if(!!con) {
				con.setDisabled(false);
				if(fieldsToUnlock[i].indexOf("address1") == -1){
					con.setVisible(true); //control
					con.getParent().setVisible(true); //section
					con.getParent().getParent().setVisible(true); //tab
				}
			}
		}
		return;
    }
	else{
		//SetVisn();
		maskPhones();
		unattendedMVISearchFromVeteran(_ICN);
	}
}

function hideBusinessProcessFlow() {
    var flow = Xrm.Page.ui.process;
    if (!!flow && flow.getVisible())
        flow.setVisible(false);
}

function maskPhones() {
    var phoneFields = [
		"ftp_mobilephone",
		"ftp_mobilephone",
		"ftp_workphone"
    ];

    for (var i = 0, l = phoneFields.length; i < l; i++) {
        var attr = Xrm.Page.getAttribute(phoneFields[i]);
        if (!!attr) attr.fireOnChange();
    }
}

function formatTelephoneNumber(pContext) {
    if (!!pContext) {
        var changedAttribute = pContext.getEventSource();
        if (!!changedAttribute) {
            var value = changedAttribute.getValue();
            if (!!value) {
                var tempValue = value.toString().replace(/[^0-9A-Za-z]/g, "").toUpperCase();
                if (tempValue.substr(0, 1) == "1") tempValue = tempValue.substr(1, 99);
                var formattedValue = (tempValue.length >= 10) ? "(" + tempValue.substr(0, 3) + ") " + tempValue.substr(3, 3) + "-" + tempValue.substr(6, 4) : tempValue.substr(0, 3) + "-" + tempValue.substr(3, 4);
                changedAttribute.setValue(formattedValue);
            }
        }
    }
}

function unemployableVisibility() {
    Xrm.Page.getControl("ftp_unemployable").setVisible(Xrm.Page.getAttribute("ftp_scpercent").getValue() !== null);
}

function setSubmitModeOnSomeAttributes() {
    var fieldsToSave = [
        "firstname",
        "middlename",
        "lastname",
        "ftp_edipi",
        "governmentid",
        "ftp_dateofbirth",
        "ftp_nextofkin",
        "ftp_remarks",
        "ftp_primaryeligibilitycode",
        "ftp_patienttype",
        "ftp_serviceconnected",
        "ftp_scpercent",
        "ftp_unemployable",
        "ftp_dentalinj",
        "ftp_medicationcopaymentexemptionstatus",
        "ftp_copaymentexemptionstatus",
        "ftp_isinsurance",
        "ftp_mobilephone",
        "ftp_homephone",
        "ftp_workphone"
    ];
    for (var i = 0, l = fieldsToSave.length; i < l; i++) {
        var field = Xrm.Page.getAttribute(fieldsToSave[i]);
        if (!!field) field.setSubmitMode("always");
    }
}

function resetViersCheckboxesOnLoad(){
	var viersFields = [
		"ftp_ischangemobile",
		"ftp_ischangehome",
		"ftp_ischangework",
		"ftp_ischangepermanentaddress",
		"ftp_ischangetemporaryaddress"
	];
	for (var i = 0, l = viersFields.length; i < l; i++) {
        var attr = Xrm.Page.getAttribute(viersFields[i]);
        if (!!attr) attr.fireOnChange();
    }
}

function SetVisn() {
	//deprecated in favor of ftp_facilityid_onChange()
	return;
    ////debugger;
    var facilityLookupValue = Xrm.Page.getAttribute("ftp_facilityid").getValue();
    if (!!facilityLookupValue) {
        var columnset = "ftp_visnid";
        SDK.REST.retrieveRecord(
            facilityLookupValue[0].id,
            "ftp_facility",
            columnset,
            null,
            function (retrievedRecord) {
                if (!!retrievedRecord && !!retrievedRecord.ftp_visnid) {
                    Xrm.Page.getAttribute("ftp_visn").setValue(retrievedRecord.ftp_visnid.Name);
                    Xrm.Page.getAttribute("ftp_visn").setSubmitMode("always");
                }
            },
            errorHandler
        );
    }
}

function unattendedMVISearchFromVeteran(pICN) {
    if (!!pICN) {
        setupExternalWebServiceCalls(pICN);        
    } 
	else {
        //perform MVI search (SearchByFilter) to get ICN before proceeding to setupExternalWebServiceCalls().
        var queryString = "$select=*&$filter=";
        var firstname = Xrm.Page.getAttribute("firstname").getValue();
        var lastname = Xrm.Page.getAttribute("lastname").getValue();

        var dobdate = Xrm.Page.getAttribute("ftp_dateofbirth").getValue();
        var dobstring = !!dobdate ? dobdate : "";

        var ssn = Xrm.Page.getAttribute("governmentid").getValue();
        if (!!ssn) ssn = ssn.replace(/-/g, "");

        queryString += buildQueryFilter("crme_LastName", lastname, false); //assuming lastname will never be blank
        if (!!firstname) queryString += buildQueryFilter("crme_FirstName", firstname, true);
        if (!!ssn) queryString += buildQueryFilter("crme_SSN", ssn, true);
        if (!!dobstring) queryString += " and crme_DOBString eq '" + dobstring + "'";
        queryString += buildQueryFilter("crme_SearchType", 'SearchByFilter', true);
        //set search type as attended (for now)
        queryString += " and crme_IsAttended eq true";
		
		//queryString = encodeURIComponent(queryString);
        var retrievedPerson = null;
        var MVIBadResultsText = "Invalid results from MVI";
        SDK.REST.retrieveMultipleRecords(
			"crme_person",
			queryString,
			function (retrievedRecords) {
			    //debugger;
			    if (typeof retrievedRecords != "undefined" && !!retrievedRecords && retrievedRecords.length == 1) {
			        retrievedPerson = retrievedRecords[0];
			    }
			    else {
			        MVIBadResultsText = "Could not determine veteran ICN from " + retrievedRecords.length + " MVI search results.";
			    }
			},
			errorHandler,
			function () {
			    //debugger;
			    if (!!retrievedPerson) {
			        // check for exceptions 1st
			        if ((retrievedPerson.crme_ExceptionOccured || !!retrievedPerson.crme_ExceptionMessage)
						|| (!!retrievedPerson.crme_ReturnMessage && retrievedPerson.crme_ReturnMessage == "An unexpected error occured during the MVI search. Please try again or contact your system administrator if the problem persists.")
						|| (!!retrievedPerson.crme_ReturnMessage && retrievedPerson.crme_ReturnMessage == "Unknown Key Identifier| Unknown Key Identifier")
						|| (!!retrievedPerson.crme_ReturnMessage && retrievedPerson.crme_ReturnMessage == "Your search in MVI did not find any records matching the search criteria.")) {
			            var MVIBadResultsText =
							!!retrievedPerson.crme_ExceptionMessage ? retrievedPerson.crme_ExceptionMessage :
							!!retrievedPerson.crme_ReturnMessage ? retrievedPerson.crme_ReturnMessage :
							"Unknown error";
			            Xrm.Utility.alertDialog(
							"Error performing MVI search for veteran ICN: \n\n" + MVIBadResultsText,
							function () {
								Xrm.Page.ui.setFormNotification(MVIBadResultsText, "INFO", "MVIBadResultsMessage");
							    finishedGettingPrimaryCareProviders = true;
							    finishedGettingMHTC = true;
							    //window.open("http://event/?eventname=EndSessionOnBadESRCall");
							}
						);
			        }
			        else {
			            var patientMviIdentifier = retrievedPerson.crme_PatientMviIdentifier == null ? "" : retrievedPerson.crme_PatientMviIdentifier;
			            if (patientMviIdentifier != "") {
			                var idparts = patientMviIdentifier.split("^");

			                if (idparts.length > 0) {
			                    var ICN = idparts[0];
			                    _ICN = ICN;
								setupExternalWebServiceCalls(ICN);
			                }
			            }
			        }
			    }
			    else {
					MVIBadResultsText = "Could not determine veteran ICN from MVI.";
			        Xrm.Utility.alertDialog(
						MVIBadResultsText,
						function () {
						    Xrm.Page.ui.setFormNotification(MVIBadResultsText, "INFO", "MVIBadResultsMessage");
						    finishedGettingPrimaryCareProviders = true;
						    finishedGettingMHTC = true;
						    //window.open("http://event/?eventname=EndSessionOnBadESRCall");
						}
					);
			    }
			}
		);
    }
}

function setupExternalWebServiceCalls(pICN) {
    try {
        var fType = Xrm.Page.ui.getFormType();
		Xrm.Page.ui.clearFormNotification("WebServiceError");
        if (!!pICN && pICN != "MISSING" && !!fType && fType > 1) {
            //retrieve Active Settings record to get URLs, THEN perform external web service calls
            var queryString = "$select=*&$filter=mcs_name eq 'Active Settings'";
            var retrievedSettings = null;
            SDK.REST.retrieveMultipleRecords(
                "mcs_setting",
                queryString,
                function (retrievedRecords) {
                    if (typeof retrievedRecords != "undefined" && !!retrievedRecords && retrievedRecords.length == 1) retrievedSettings = retrievedRecords[0];
                },
                errorHandler,
                function () {
                    if (!!retrievedSettings) {
						_retrievedSettings = retrievedSettings;
                        if (!(retrievedSettings.hasOwnProperty("ftp_DACURL")) || !retrievedSettings.ftp_DACURL) {
							var msg = "Configuration error: Active Settings record is missing some URLs; contact your system administrator.";
                            Xrm.Utility.alertDialog(
								msg,
								function () {
									Xrm.Page.ui.setFormNotification(msg, "ERROR", "WebServiceError");
								}
							);
                            return;
                        }
                        writeToConsole("got Active Settings record.");

                        //perform ESR web service call for demographics and sensitivity flag
                        //this function call is deprecated 10/10/17
						//performESRWebServiceCall(pICN);
						
						if(typeof getBranchAndRankFromVIERS == "function"){
							writeToConsole("firing getBranchAndRankFromVIERS");
							getBranchAndRankFromVIERS();
						}
                    } //end if !!retrievedSettings
                    else {
                        Xrm.Utility.alertDialog(
							"Could not find Active Settings for this org; contact your system administrator.",
							function () {
								Xrm.Page.ui.setFormNotification("Could not find Active Settings for this org; contact your system administrator", "ERROR", "WebServiceError");
							}
						);
                    }
                }
            );
        }
        else if (!pICN && !!fType && fType > 1) {
            return;
        }
        else {
            return;
        }
    }
    catch (e) {
        alert(e);
    }
}

function performESRWebServiceCall(pICN) {
    /*
    This entire function has been deprecated 10/10/17
    We now query ESR before reaching the Veteran form, and store ESR data in USD replacement parameters
    onLoad of this form, USD action call(s) populate demographic fields using data from USD replacement parameters
    */
    return;
	Xrm.Page.ui.clearFormNotification("WebServiceError");
	if(!!getDeepProperty("_retrievedSettings.ftp_DACURL") && !!getDeepProperty("_retrievedSettings.ftp_ESRAPIURL") && !!pICN){
		var esrJsonUrl = _retrievedSettings.ftp_ESRAPIURL.replace("xml", "json");
		var esrUrl = _retrievedSettings.ftp_DACURL + esrJsonUrl + "000000" + pICN + "000000";
		$.ajax({
			type: "GET",
			contentType: "application/json; charset=utf-8",
			datatype: "json",
			url: esrUrl,
			beforeSend: function (XMLHttpRequest) {
				//Specifying this header ensures that the results will be returned as JSON.
				//XMLHttpRequest.setRequestHeader("Accept", "application/json");
			},
			success: function (response, textStatus, XmlHttpRequest) {
				_summary = getDeepProperty("SOAP-ENV:Envelope.SOAP-ENV:Body.getEESummaryResponse.summary", response);
				if(!!_summary){
					var preferredFacility = getDeepProperty("_summary.demographics.preferredFacility");
					findOrCreateFacilityInCRM(preferredFacility);
					
					return;
                    //everything below here has been moved to VeteranAlerts.js where the data is now copied to [[ESR]] replacement parameters
					/*phone(s)*/
					var phoneList = getDeepProperty("_summary.demographics.contactInfo.phones.phone");
					if(!!phoneList){
						phoneList = Array.isArray(phoneList) ? phoneList : [phoneList]; /*if phones.phone is only an object, make it an array of 1*/
						for(var i = 0; i < phoneList.length; i++){
							var thisPhone = phoneList[i];
							if(!!thisPhone.phoneNumber && !!thisPhone.type){
								switch(thisPhone.type){
									case "Home":
										setAndSubmitValue("ftp_homephone",thisPhone.phoneNumber);
										break;
									case "Business":
										setAndSubmitValue("ftp_workphone",thisPhone.phoneNumber);
										break;
									case "Mobile":
										setAndSubmitValue("ftp_mobilephone",thisPhone.phoneNumber);
										break;
									default:
										break;
								}
							}
						}
					}
					
					/*address(es)*/
					var addressList = getDeepProperty("_summary.demographics.contactInfo.addresses.address");
					if(!!addressList){
						addressList = Array.isArray(addressList) ? addressList : [addressList]; /*if addresses.address is only an object, make it an array of 1*/
						for(var i = 0; i < addressList.length; i++){
							var thisAddress = addressList[i];
							if(!!thisAddress.addressTypeCode){
								switch(thisAddress.addressTypeCode){
									case "Permanent":
										if (!!thisAddress.line1) { setAndSubmitValue("address1_line1",thisAddress.line1); }
										if (!!thisAddress.line2) { setAndSubmitValue("address1_line2",thisAddress.line2); }
										if (!!thisAddress.line3) { setAndSubmitValue("address1_line3",thisAddress.line3); }
										if (!!thisAddress.zipCode) { setAndSubmitValue("address1_postalcode",thisAddress.zipCode); }
										if (!!thisAddress.state) { setAndSubmitValue("address1_stateorprovince",thisAddress.state); }
										if (!!thisAddress.city) { setAndSubmitValue("address1_city",thisAddress.city); }
										if (!!thisAddress.country) { setAndSubmitValue("address1_country",thisAddress.country); }
										break;
									case "Temporary":
										if (!!thisAddress.line1) { setAndSubmitValue("address2_line1",thisAddress.line1); }
										if (!!thisAddress.line2) { setAndSubmitValue("address2_line2",thisAddress.line2); }
										if (!!thisAddress.line3) { setAndSubmitValue("address2_line3",thisAddress.line3); }
										if (!!thisAddress.zipCode) { setAndSubmitValue("address2_postalcode",thisAddress.zipCode); }
										if (!!thisAddress.state) { setAndSubmitValue("address2_stateorprovince",thisAddress.state); }
										if (!!thisAddress.city) { setAndSubmitValue("address2_city",thisAddress.city); }
										if (!!thisAddress.country) { setAndSubmitValue("address2_country",thisAddress.country); }
										break;
									default:
										break;
								}
							}
						}
					}
					
					/*miscellaneous*/
					//If they are a veteran- pull that return
					var isAVeteran = getDeepProperty("_summary.enrollmentDeterminationInfo.veteran") == "true";
					setAndSubmitValue("ftp_patienttype", isAVeteran ? "veteran" : "Non-Veteran");

					var eligibilityType = getDeepProperty("_summary.enrollmentDeterminationInfo.primaryEligibility.type");
					setAndSubmitValue("ftp_primaryeligibilitycode", eligibilityType);
					
					var unemployable = getDeepProperty("_summary.enrollmentDeterminationInfo.serviceConnectionAward.unemployable");
					setAndSubmitValue("ftp_unemployable", unemployable == "true" ? "Yes" : "No");
					
					var svcConnIndicator = getDeepProperty("_summary.enrollmentDeterminationInfo.serviceConnectionAward.serviceConnectedIndicator");
					setAndSubmitValue("ftp_serviceconnected", svcConnIndicator == "true");

					if(svcConnIndicator == "true"){
						var percentage = getDeepProperty("_summary.enrollmentDeterminationInfo.serviceConnectionAward.serviceConnectedPercentage");
						if(!!percentage){ setAndSubmitValue("ftp_scpercent", percentage); }
					}
					
					var sensitivityFlag = getDeepProperty("_summary.sensitivityInfo.sensityFlag");
					setAndSubmitValue("ftp_sensitiveveteran", sensitivityFlag == "true");

					var hasInsurance = !!getDeepProperty("_summary.insuranceList.insurance");
					setAndSubmitValue("ftp_isinsurance", hasInsurance);

					//next of kin
					var associationList = getDeepProperty("_summary.associations.association");
					if(!!associationList){
						associationList = Array.isArray(associationList) ? associationList : [associationList];
						for(var i = 0; i < associationList.length; i++){
							var thisAssociation = associationList[i];
							if(thisAssociation.contactType == "Primary Next of Kin"){
								var nokString = !!thisAssociation.givenName ? thisAssociation.givenName.trim() : "";
								nokString += (!!thisAssociation.middleName ? " " + thisAssociation.middleName.trim() : "");
								nokString += (!!thisAssociation.familyName ? " " + thisAssociation.familyName.trim() : "");
								nokString += (!!thisAssociation.relationship ? ", " + thisAssociation.relationship.trim() : "");
								if(!!nokString) { setAndSubmitValue("ftp_nextofkin", nokString); }
							}
						}
					}
				}
				else{
					Xrm.Page.ui.setFormNotification("ESR did not return summary data.", "WARNING", "WebServiceError");
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				//(500) Internal Server Error is probably due to a bad ICN.
				Xrm.Page.ui.setFormNotification("Error querying ESR: " + errorThrown, "ERROR", "WebServiceError");
			},
			async: true,
			cache: false
		});
	}
	else{
		Xrm.Page.ui.setFormNotification("Configuration error: missing URLs or ICN.", "ERROR", "WebServiceError");
	}
}

function findOrCreateFacilityInCRM(pPreferredFacilityFromESR) {
    /*this function is called from a USD action call under the Shared Hidden Veteran's 'VeteranFormReady' event*/
	Xrm.Page.ui.clearFormNotification("WebServiceError");
	if(!!pPreferredFacilityFromESR){
		var pfAsArray = pPreferredFacilityFromESR.split("-");
		if(pfAsArray.length == 2){
			var facilityCodeFromESR = pfAsArray[0].trim();
			var facilityNameFromESR = pfAsArray[1].trim();
			var fullName = facilityCodeFromESR + " - " + facilityNameFromESR; //build it from its parts, just in case it was missing any spaces to begin with

		    /*
            this secondary function call (performPCMMWebServiceCall) has been moved to a USD action call under the Shared Hidden Veteran's 'VeteranFormReady' event
            10/10/17
            */
			//performPCMMWebServiceCall(facilityCodeFromESR, _ICN);
			
			if (!!facilityCodeFromESR) {
                /*10/12/17 ftp_facilitycode (whole number) has been replaced by the ftp_FacilityCode_text field so we can lookup on alphanumeric facility codes*/
			    var facilityQueryString = "$select=ftp_name,ftp_FacilityCode_text,ftp_facilityId,ftp_visnid&$filter=ftp_FacilityCode_text eq '" + facilityCodeFromESR + "' and statecode/Value eq 0&$top=1"
				var retrievedFacility = null;
				SDK.REST.retrieveMultipleRecords(
					"ftp_facility",
					facilityQueryString,
					function(retrievedRecords){
						if(!!retrievedRecords && retrievedRecords.length == 1){
							retrievedFacility = retrievedRecords[0];
						}
					},
					errorHandler,
					function(){
						if(!!retrievedFacility){
							updateFacilityOnForm(retrievedFacility);
						}
						else{
							//create the facility record in CRM, then set the lookup field on this form
							var newFacility = {
								ftp_name: fullName,
								ftp_FacilityCode_text: facilityCodeFromESR,
								ftp_SiteName: facilityNameFromESR
							};
							SDK.REST.createRecord(
								newFacility,
								"ftp_facility",
								function(createdRecord){
									updateFacilityOnForm(createdRecord);
								},
								errorHandler
							);
						}
					}
				);
			}
		}
	}
}
function updateFacilityOnForm(pFacilityObject){
    if (!!pFacilityObject) {
        setAndSubmitValue(
            "ftp_facilityid",
            [{
                id: pFacilityObject.ftp_facilityId,
                name: pFacilityObject.ftp_name,
                entityType: "ftp_facility"
            }]
        );
		
		Xrm.Page.getAttribute("ftp_facilityid").fireOnChange();
	}
}
function ftp_facilityid_onChange(){
	Xrm.Page.ui.clearFormNotification("missingVISN");
	writeToConsole("inside ftp_facilityid_onChange");
	var facilityLookupValue = Xrm.Page.getAttribute("ftp_facilityid").getValue();
    if (!!facilityLookupValue) {
        var columnset = "ftp_visnid";
        SDK.REST.retrieveRecord(
            facilityLookupValue[0].id,
            "ftp_facility",
            columnset,
            null,
            function (retrievedRecord) {
                if (!!getDeepProperty("ftp_visnid.Name", retrievedRecord)) {
					writeToConsole("found VISN from facility: " + retrievedRecord.ftp_visnid.Name);
					setAndSubmitValue("ftp_visn", retrievedRecord.ftp_visnid.Name);
                }
				else{
					Xrm.Page.ui.setFormNotification("Identified home facility does not have a VISN.", "INFO", "missingVISN");
				}
            },
            errorHandler
        );
    }
}

function buildQueryFilter(field, value, and) {
    return !!field ? ((and ? " and " : "") + field + " eq " + (value == '' ? "null" : "'" + value + "'")) : "";
}

function errorHandler(error) {
	writeToConsole(error.message);
    alert(error.message);
}
function writeToConsole(message) {
    if (typeof console != 'undefined') console.log(message);
}
function getDeepProperty(pPath, pObject){
	if(!!pPath){
		var pathAsArray = pPath.split(".");
		var returnObj = !!pObject ? pObject : window[pathAsArray.shift()];
		if(typeof returnObj != "undefined"){
			while(!!returnObj && pathAsArray.length > 0){
				returnObj = returnObj[pathAsArray.shift()];
			}
			return returnObj;
		}
		else{
			return undefined;
		}
	}
	else{
		return undefined;
	}
}
function setAndSubmitValue(pAttribute, pValue){
	var attr = Xrm.Page.getAttribute(pAttribute);
	if(!!attr){
		attr.setValue(pValue);
		attr.setSubmitMode("always");
	}
}
function SortObjectArray(pSortProperty){
	var sortOrder = 1;
	if(pSortProperty[0] === "-"){
		sortOrder = -1;
		pSortProperty = pSortProperty.substr(1);
	}
	return function (a,b){
		var result = (a[pSortProperty] < b[pSortProperty]) ? -1 : (a[pSortProperty] > b[pSortProperty]) ? 1 : 0;
		return result * sortOrder;
	};
}