function addRowAttribute(row, attributename, attributevalue, addcolumn) {
	if(addcolumn) {
		var column = document.createElement('td');
		column.appendChild(document.createTextNode(attributevalue));
		row.appendChild(column);
	}
	row.setAttribute(attributename, attributevalue);
}

function addHeaderColumn(row, colname){
	var th = document.createElement('th');

	th.appendChild(document.createTextNode(colname));
	row.appendChild(th);
}

function formatDatePart(datepart) {
	return datepart.length == 1 ? "0" + datepart : datepart;
}

function buildQueryFilter(field, value, and) {
	// remove unwanted characters 
	var arr1 = ["'", "\""];
	for (a = 0; a < arr1.length ; a++) {
		if (value.indexOf(arr1[a]))
			value = value.replace(arr1[a], " ");
	}

	if (and) {
		return " and " + field + " eq '" + value + "'";
	} else {
		return field + " eq '" + value + "'";
	}
}

function validateDateOfBirth(dobyear, dobmonth, dobday) {
	if ((dobyear == "" || dobyear == "YYYY") && (dobmonth == "" || dobmonth == "MM") && (dobday == "" || dobday == "DD")) {
		return true;
	}
	if (dobyear != "YYYY" || dobmonth != "MM" || dobday != "DD") {
		if ((dobyear != "" && isNumeric(dobyear) == false) || (dobmonth != "" && isNumeric(dobmonth) == false) || (dobday != "" && isNumeric(dobday) == false)) {
			return false;
		}
	}
	if (dobyear.length != 4) {
		return false;
	}
	if (dobyear >= (new Date).getFullYear() + 1) {
		return false;
	}
	if (dobyear < (new Date).getFullYear() - 200) {
		return false;
	}
	if (dobmonth < 1 || dobmonth > 12) {
		return false;
	}
	if (dobday < 1 || dobday > 31) {
		return false;
	}
	return true;
}

function isNumeric(value) {
	return !isNaN(parseFloat(value) && isFinite(value));
}

function formatName(data) {
	var firstName = data.crme_FirstName != null ? data.crme_FirstName : "";
	var middleName = data.crme_MiddleName != null ? data.crme_MiddleName : "";
	var lastName = data.crme_LastName != null ? data.crme_LastName : "";

	var fullName = lastName != "" ? lastName : "";
	fullName += firstName != "" && lastName != "" ? ", " + firstName : "";
	fullName += middleName != "" && firstName != "" && lastName != "" ? " " + middleName : "";

	return fullName;
}

function formatAddress(data) {
	if (data.crme_FullAddress != null) {
		return data.crme_FullAddress;
	}
	if (data.crme_StateProvinceId != null && data.crme_ZIPPostalCodeId != null) {
		var street = data.crme_Address1 != null ? data.crme_Address1 : "";
		var city = data.crme_City != null ? data.crme_City : "";
		var state = data.crme_StateProvinceId.Name != null ? data.crme_StateProvinceId.Name : "";
		var zip = data.crme_ZIPPostalCodeId.Name != null ? data.crme_ZIPPostalCodeId.Name : "";

		return street + " " + city + " " + state + " " + zip;
	}
	return "";
}

function clearField(obj) {
	if (obj.defaultValue == obj.value) obj.value = '';
}

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 + "?";
	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 getRequestObject() {
	if (window.XMLHttpRequest) {
		return new window.XMLHttpRequest;
	}
	else {
		try {
			return new ActiveXObject("MSXML2.XMLHTTP.3.0");
		}
		catch (ex) {
			return null;
		}
	}
}

function formatExecutingSearch() {
	$('div#tmpDialog').show();
	$("#validationFailedDiv").hide();
	$("#resultsFieldSetDiv").hide();
	$("#notFoundDiv").hide();
	$("#possibleResultsDiv").hide();
	$("#createDiv").hide();
	$("#searchResultsMessageDiv").hide();
	$("#SearchByNameButton").attr('disabled', true);
	$("#SearchByAddButton").attr('disabled', true);
	$("#SearchByIdentifierButton").attr('disabled', true);
	$("#mviDownCreateRow").hide();
	$("#last4CreateRow").hide();
	$("#createAttributesTable").hide();
	$("#createLastNameTextBox").val("");
	$("#createFirstNameTextBox").val("");

}

function formatValidationFailed() {
	$("#validationFailedDiv").show();
	$("#notFoundDiv").hide();
	$("#possibleResultsDiv").hide();
	$("#createDiv").hide();
	$("#resultsFieldSetDiv").hide();
	$("#searchResultsMessageDiv").hide();
	$("#personSearchResultsTable").find("thead, tr, th").remove();
	$("#personSearchResultsTable").find("tr:gt(0)").remove();
	$("#mviDownCreateRow").hide();
	$("#last4CreateRow").hide();
	$("#createAttributesTable").hide();
	$("#createLastNameTextBox").val("");
	$("#createFirstNameTextBox").val("");

}

function personSearchComplete() {
	$('div#tmpDialog').hide();
	$("#SearchByNameButton").attr('disabled', false);
	$("#SearchByAddButton").attr('disabled', false);
	$("#SearchByIdentifierButton").attr('disabled', false);
	//$("#personSearchResultsTable").find("tr:gt(0)").focus();               
	$("#personSearchResultsTable").focus();
}

function edipiSearchCallBack(data) {
	searchCallBack(data);     
	//   searchCallBackWithStations(data, true);
}

function traitsSearchCallBack(data) {
	searchCallBack(data);     
	//   searchCallBackWithStations(data, false);
}

function showResultsMessageDiv(resultsMessage){
	$("#searchResultsMessageDiv").show();
	$("#searchResultsMessageDiv").text(resultsMessage);
}

function showNotFoundDiv(notFoundLabel){
	$("#noResultsLabel").text(notFoundLabel);
	$("#notFoundDiv").show();
}

function searchCallBack(returnData) {
	$('div#tmpDialog').show();
	// get the table
	var table = $("#personSearchResultsTable");

	// reset the table by removing all data rows
	$("#personSearchResultsTable").find("thead, tr, th").remove();
	$("#personSearchResultsTable").find("tr:gt(0)").remove();
	$("#resultsFieldSetDiv").hide();

	if (returnData != null && returnData.length > 0) {

		// check for exceptions 1st
		if (returnData[0].crme_ExceptionOccured) {
			showResultsMessageDiv(returnData[0].crme_ExceptionMessage);
			showNotFoundDiv("Error searching in MVI");
			return;
		}

		var thead = document.createElement('thead');
		var theadRow = document.createElement('tr');

		for (var i = 0; i < returnData.length; i++) {

			var fullName = formatName(returnData[i]);

			//CRMe can return result, even if just ReturnMessage that there were no results...
			//If blank\no name, we should break
			if (fullName.trim() == "") {
				showResultsMessageDiv((returnData != null && returnData.length > 0 && returnData[0].crme_ReturnMessage != null) ? returnData[0].crme_ReturnMessage : "Your search in MVI did not find any records matching the search criteria.");
				showNotFoundDiv("No Records Found");
				return;
			}

			var recordSource = returnData[i].crme_RecordSource == null ? "" : returnData[i].crme_RecordSource;
			var patientMviIdentifier = returnData[i].crme_PatientMviIdentifier == null ? "" : returnData[i].crme_PatientMviIdentifier;
			var icn = returnData[i].crme_ICN == null ? "" : returnData[i].crme_ICN;
			
			var edipi = returnData[i].crme_EDIPI == null ? "" : returnData[i].crme_EDIPI;						
			
			var ssn = returnData[i].crme_SSN == null ? "" : returnData[i].crme_SSN;
			var gender = returnData[i].crme_Gender == null ? "" : returnData[i].crme_Gender;
			var deceasedDate = returnData[i].crme_DeceasedDate == null ? "" : returnData[i].crme_DeceasedDate;
			var branchOfService = returnData[i].crme_BranchOfService == null ? "" : returnData[i].crme_BranchOfService;
			var dateOfBirth = returnData[i].crme_DOBString == null ? "" : returnData[i].crme_DOBString;
			var pobc = returnData[i].crme_POBC == null ? "" : returnData[i].crme_POBC;
			var pobs = returnData[i].crme_POBS == null ? "" : returnData[i].crme_POBS;
			var mmn = returnData[i].crme_MMN == null ? "" : returnData[i].crme_MMN;

			var firstName = returnData[i].crme_FirstName == null ? "" : returnData[i].crme_FirstName;
			var middleName = returnData[i].crme_MiddleName == null ? "" : returnData[i].crme_MiddleName;						
			var lastName = returnData[i].crme_LastName == null ? "" : returnData[i].crme_LastName;
			var alias = returnData[i].crme_Alias == null ? "" : returnData[i].crme_Alias;

			var fulladdress = formatAddress(returnData[i]);
			var address1 = returnData[i].crme_Address1 == null ? "" : returnData[i].crme_Address1;
			var address2 = returnData[i].crme_Address2 == null ? "" : returnData[i].crme_Address2;
			var city = returnData[i].crme_City == null ? "" : returnData[i].crme_City;						
			var state = returnData[i].crme_StateProvinceId == null ? "" : returnData[i].crme_StateProvinceId.Name;						
			var zip = returnData[i].crme_ZIPPostalCodeId == null ? "" : returnData[i].crme_ZIPPostalCodeId.Name;						
			var phoneNumber = returnData[i].crme_PrimaryPhone == null ? "" : returnData[i].crme_PrimaryPhone;
			var email = returnData[i].crme_Email == null ? "" : returnData[i].crme_Email;
			
			var classcode = returnData[i].crme_ClassCode == null ? "" : returnData[i].crme_ClassCode;
			var identityTheft = returnData[i].crme_IdentityTheft == null ? "" : returnData[i].crme_IdentityTheft;
			var vetSensLevel = returnData[i].crme_VeteranSensitivityLevel == null ? "" : returnData[i].crme_VeteranSensitivityLevel;
			var participantId = returnData[i].crme_PatientMviIdentifier == null ? "" : returnData[i].crme_PatientMviIdentifier;


			if (i == 0) {
				addHeaderColumn(theadRow, 'Name');
				addHeaderColumn(theadRow, 'SSN');
				addHeaderColumn(theadRow, 'EDIPI');
				addHeaderColumn(theadRow, 'Date of Birth');
				addHeaderColumn(theadRow, 'Deceased Date');
				addHeaderColumn(theadRow, 'Br. of Svc');
				addHeaderColumn(theadRow, 'Phone No');
				addHeaderColumn(theadRow, 'Address');
				addHeaderColumn(theadRow, 'Source');      
				thead.appendChild(theadRow);
			}

			// Table rows
			var row = document.createElement('tr');
			addRowAttribute(row, 'fullName', fullName, true);
			addRowAttribute(row, 'ssn', ssn, true);
			addRowAttribute(row, 'edipi', edipi, true);
			addRowAttribute(row, 'dateofbirth', dateOfBirth, true);
			addRowAttribute(row, 'deceasedDate', deceasedDate, true);
			addRowAttribute(row, 'branchOfService', branchOfService, true);
			addRowAttribute(row, 'phoneNumber', phoneNumber, true);
			addRowAttribute(row, 'fulladdress', fulladdress, true);
			addRowAttribute(row, 'recordSource', recordSource, true);

			addRowAttribute(row, 'firstName', firstName, false);
			addRowAttribute(row, 'lastName', lastName, false);
			addRowAttribute(row, 'patientMviIdentifier', patientMviIdentifier, false);
			addRowAttribute(row, 'gender', gender, false);
			addRowAttribute(row, 'pobc', pobc, false);
			addRowAttribute(row, 'pobs', pobs, false);
			addRowAttribute(row, 'mmn', mmn, false);
			addRowAttribute(row, 'middleName', middleName, false);
			addRowAttribute(row, 'alias', alias, false);
			addRowAttribute(row, 'address1', address1, false);
			addRowAttribute(row, 'address2', address2, false);
			addRowAttribute(row, 'city', city, false);
			addRowAttribute(row, 'state', state, false);
			addRowAttribute(row, 'zip', zip, false);
			addRowAttribute(row, 'email', email, false);
			addRowAttribute(row, 'classcode', classcode, false);
			addRowAttribute(row, 'icn', icn, false);
			addRowAttribute(row, 'vetSensLevel', vetSensLevel, false);
			addRowAttribute(row, 'participantId', participantId, false); 
			
			row.className = (i % 2 == 0) ? "even" : "odd";

			row.ondblclick = function () { openSelectedPerson(this); };
			row.onkeydown = function (e) {
				if (e.keyCode === 13 || e.keyCode === 32) {
					openSelectedPerson(this);
				}
			};
			row.tabIndex = 100 + i;
			table.append(thead);
			table.append(row);

			$("#resultsFieldSetDiv").show();
			if (i == 1)
				row.focus = true;
		}
		$("#createDiv").show();
		$("#mviDownCreateRow").show();
		if(_lastSearchType=="EDIPI") {
			$("#createAttributesTable").show();
		}
	}
	else {
		showNotFoundDiv("No Records Found");
	}
	showResultsMessageDiv((returnData != null && returnData.length > 0 && returnData[0].crme_ReturnMessage != null) ? returnData[0].crme_ReturnMessage : "Your search in MVI did not find any records matching the search criteria.");
}


function handleMviError() {
	showNotFoundDiv("Error Contacting MVI");
	showResultsMessageDiv("There was a problem searching MVI.");
}

// called from searchCallBack methods above
function openSelectedPerson(obj) {

	$('div#tmpDialog').show();
	
	//set global selected person object for use later just in case
	_selectedPersonObj = obj;

	var firstName = obj.getAttribute('firstName');
	var lastName = obj.getAttribute('lastName');
	var patientMviIdentifier = obj.getAttribute('patientMviIdentifier');
	var ssn = obj.getAttribute('ssn');
	var edipi = obj.getAttribute('edipi');
	var dob = obj.getAttribute('dateofbirth');
	var recordSource = obj.getAttribute('recordSource');
	var gender = obj.getAttribute('gender');
	var deceasedDate = obj.getAttribute('deceasedDate'); 
	var bos = obj.getAttribute('branchOfService'); 
	var pobc = obj.getAttribute('pobc'); 
	var pobs = obj.getAttribute('pobs'); 
	var mmn = obj.getAttribute('mmn'); 
	var middleName = obj.getAttribute('middleName'); 
	var alias = obj.getAttribute('alias');
	var address1 = obj.getAttribute('address1'); 
	var address2 = obj.getAttribute('address2');
	var city = obj.getAttribute('city');
	var state = obj.getAttribute('state');
	var zip = obj.getAttribute('zip');
	var fullAddress = obj.getAttribute('fulladdress');
	var phoneNumber = obj.getAttribute('phoneNumber');
	var email = obj.getAttribute('email');
	var classcode = obj.getAttribute('classcode');	
	var participantId = obj.getAttribute('participantId');
	var icn = obj.getAttribute('icn');				
	var vetSensLevel = obj.getAttribute('vetSensLevel');
	
	__MVI_FullName = lastName + ", " + firstName + " " + middleName;
	
	var filter = "&select=*&$filter=crme_PatientMviIdentifier eq '" + patientMviIdentifier + "' and crme_SearchType eq 'SelectedPersonSearch'";
	
	if (firstName != null && firstName != "") filter += buildQueryFilter("crme_FirstName", firstName, true);
	if (middleName != null && middleName != "") filter += buildQueryFilter("crme_MiddleName", middleName, true);
	if (lastName != null && lastName != "") filter += buildQueryFilter("crme_LastName", lastName, true);
	if (ssn != null && ssn != "") filter += buildQueryFilter("crme_SSN", ssn, true);
	if (recordSource != null && recordSource != "") filter += buildQueryFilter("crme_RecordSource", recordSource, true);
	//if (icn != null && icn != "") filter += buildQueryFilter("crme_ICN", icn, true);
	//if ((icn == null || icn == "") && participantId != null && participantId != "") filter += buildQueryFilter("crme_ICN", participantId, true);
	if (participantId != "" ) filter += buildQueryFilter("crme_ParticipantID", participantId, true);
	if (edipi != null && edipi != "") filter += buildQueryFilter("crme_EDIPI", edipi, true);
	if (vetSensLevel != null && vetSensLevel != "") filter += buildQueryFilter("crme_VeteranSensitivityLevel", vetSensLevel, true);
	if (dob != null && dob != "") filter += buildQueryFilter("crme_MVIDOBString", dob, true);
	if (fullAddress != null && fullAddress != "") filter += buildQueryFilter("crme_MVIFullAddress", fullAddress, true);

	SDK.REST.retrieveMultipleRecords("crme_person", filter, personRetrieveCallback, function (error) { alert(error.message); }, function () { });				

	return false;
}

function personRetrieveCallback(data) {
	var participantId = _selectedPersonObj.getAttribute('participantId');
	var idparts = participantId.split("^");
	if(idparts.length>0) {
		_icn = idparts[0];
		SDK.REST.retrieveMultipleRecords("bah_keyvaluepair", 
			"$select=*&$filter=bah_name_text eq 'esr_endpoint'",
			function(data){
				if(data.length>0) {
					_esrEndpoint = data[0].bah_stringvalue_text;
					if(_esrEndpoint != "" && _icn.length>0) {
						var nationalId = _icn;
						var actualEndpoint = _esrEndpoint.replace('{0}','000000'+nationalId+'000000'); //pad ICN with six zeroes on beginning and end
					
						$.ajax({
							url: actualEndpoint,
							timeout: 4000, 
							error: function(){
								_esrObj = null;
								esrCallback();
							}, 
							success: function(result){
								_esrObj = result;
								esrCallback();
							}
						});
					}
					else {
						//we didn't get endpoint from CRM, but we should execute the next function anyway
						_esrObj = null;
						esrCallback();
					}
				}
			},
			function(error){
				//do nothing
			},
			function(){
				//do nothing on completion
			}
		);
	}
}

function esrCallback() {
	obj = _selectedPersonObj;
	var firstName = obj.getAttribute('firstName');
	var lastName = obj.getAttribute('lastName');
	var patientMviIdentifier = obj.getAttribute('patientMviIdentifier');
	var ssn = obj.getAttribute('ssn');
	var edipi = obj.getAttribute('edipi');
	var dob = obj.getAttribute('dateofbirth');
	var recordSource = obj.getAttribute('recordSource');
	var gender = obj.getAttribute('gender');
	var deceasedDate = obj.getAttribute('deceasedDate'); 
	var bos = obj.getAttribute('branchOfService'); 
	var pobc = obj.getAttribute('pobc'); 
	var pobs = obj.getAttribute('pobs'); 
	var mmn = obj.getAttribute('mmn'); 
	var middleName = obj.getAttribute('middleName'); 
	var alias = obj.getAttribute('alias');
	var address1 = obj.getAttribute('address1'); 
	var address2 = obj.getAttribute('address2');
	var city = obj.getAttribute('city');
	var state = obj.getAttribute('state');
	var zip = obj.getAttribute('zip');
	var country = "";
	var fullAddress = obj.getAttribute('fulladdress');
	var phoneNumber = obj.getAttribute('phoneNumber');
	var email = obj.getAttribute('email');
	var classcode = obj.getAttribute('classcode');	
	var participantId = obj.getAttribute('participantId');
	var icn = obj.getAttribute('icn');				
	var vetSensLevel = obj.getAttribute('vetSensLevel');
	var preferredFacility = "";
	
	__MVI_FullName = lastName + ", " + firstName + " " + middleName;
	
	if (_esrObj != null) {
		try {
			if(!_esrObj.ErrorOccurred) {
				var permanentAddress = null;
				//alert(_esrObj.getEESummaryResponse.summary.demographics.contactInfo.addresses.address[0].line1);
				if (Array.isArray(_esrObj.Data.Demographics.ContactInfo.Addresses.Address)) {
					var addressArray = _esrObj.Data.Demographics.ContactInfo.Addresses.Address;
					var permanentAddresses = addressArray.filter(function (data) { return data.AddressTypeCode.toUpperCase() == "PERMANENT"; });
					if (permanentAddresses.length > 0) {
						permanentAddress = permanentAddresses[0];
					}
				}
				else {
					if (_esrObj.Data.Demographics.ContactInfo.Addresses.Address.AddressTypeCode.toUpperCase() == "PERMANENT") {
						permanentAddress = _esrObj.Data.Demographics.ContactInfo.Addresses.Address;
					}
				}
				if (permanentAddress != null) {
					address1 = permanentAddress.Line1;
					address2 = permanentAddress.Line2 == null ? "" : permanentAddress.Line2;
					city = permanentAddress.City;
					//check for state
					if(permanentAddress.State!=null) {
						state = permanentAddress.State;
					}
					//check for province
					if(permanentAddress.ProvinceCode!=null) {
						state = permanentAddress.ProvinceCode;
					}
					
					//check for zipcode
					if(permanentAddress.ZipCode!=null) {
						zip = permanentAddress.ZipCode;
					}
					//check for postalcode
					if(permanentAddress.PostalCode!=null) {
						zip = permanentAddress.PostalCode;
					}
					
					country = permanentAddress.Country == null ? "" : permanentAddress.Country;

					//fullAddress = address1 + "\n" + city + ", " + state + " " + zip;
					//alert(fullAddress);
				}
				
				if(_esrObj.Data.Demographics.PreferredFacility != null){
					preferredFacility = _esrObj.Data.Demographics.PreferredFacility;
				}
			}
			else {
				//alert("no esr");
				//should we clear any values out?
			}
		}
		catch(err) {
			//do nothing
		}
	}
	var filterPrefix = "$select=*&$filter=";
	
	var filter2= buildQueryFilter("bah_searchtype_text", "CREATEUPDATEMVI", false);
	//filter2+= buildQueryFilter("bah_mvipatientidentifier_text", patientMviIdentifier, true); 

	if (edipi != "") filter2+= buildQueryFilter("bah_edipi_text", edipi, true);
	if (ssn != "") filter2 += buildQueryFilter("bah_ssn_text", ssn, true);
	if (firstName != "") filter2 += buildQueryFilter("FirstName", firstName, true);
	if (lastName != "") filter2 += buildQueryFilter("LastName", lastName, true);
	if (middleName != "") filter2 += buildQueryFilter("MiddleName", middleName, true);				
	if (alias != "") filter2 += buildQueryFilter("NickName", alias, true); 	
	if (recordSource != "") filter2 += buildQueryFilter("bah_source_text", recordSource, true); 
	if (bos != "") filter2 += buildQueryFilter("bah_branch_text", bos, true);
	if (pobc != "") filter2 += buildQueryFilter("bah_placeofbirth_city_text", pobc, true);
	if (mmn != "") filter2 += buildQueryFilter("bah_mmn_text", mmn, true); 
	if (phoneNumber != "") filter2 += buildQueryFilter("Telephone1", phoneNumber, true);
	if (email != "") filter2 += buildQueryFilter("EMailAddress1", email, true);
	if (preferredFacility != "") filter2 += buildQueryFilter("bah_preferredfacility_text", preferredFacility, true);
	if (gender == "M")
	{
		filter2 += " and GenderCode/Value eq 1";
	}
	else if (gender == "F")
	{
		filter2 += " and GenderCode/Value eq 2";
	}
	
	if (address1 != "") filter2 += buildQueryFilter("Address1_Line1", address1, true);
	if (address2 != "") filter2 += buildQueryFilter("Address1_Line2", address2, true);				
	if (city != "") filter2 += buildQueryFilter("Address1_City", city, true);
	
	if (state != "") {
		var stateObj = getState(state);
		if (stateObj != null) {
			filter2 += " and DNS_address1_stateid/Id eq (guid'" + stateObj.DNS_stateId.toString() + "')";
			filter2 += buildQueryFilter("Address1_StateOrProvince", stateObj.DNS_name, true);
		}
		else{
			filter2 += buildQueryFilter("Address1_StateOrProvince", state, true);
		}
	}
	
	if (country != "") {
		var countryId = getCountryId(country);
		if (countryId != "") {
			filter2 += " and DNS_address1_countryid/Id eq (guid'" + countryId.toString() + "')";
		}
		filter2 += buildQueryFilter("Address1_Country", country, true);
	}
	
	if (zip != "") filter2 += buildQueryFilter("Address1_PostalCode", zip, true);				
	
	if (dob != "")
	{
		var dobdate = new Date(dob);
		var dobsearchstring = dobdate.getFullYear() + "-" + ("0" + (dobdate.getMonth() + 1)).slice(-2) + "-" + ("0" + dobdate.getDate()).slice(-2);
		dobsearchstring += "T12:00:00Z";
		filter2 += " and bah_dob_date eq datetime'" + dobsearchstring + "'"; 
	}
	
	if (deceasedDate != "")
	{				
		var dDate = new Date(deceasedDate);
		var dsearchstring = dDate.getFullYear() + "-" + ("0" + (dDate.getMonth() + 1)).slice(-2) + "-" + ("0" + dDate.getDate()).slice(-2);					
		dsearchstring += "T12:00:00Z";
		filter2 += " and bah_dateofdeath_date eq datetime'" + dsearchstring + "'"; 
	}
	
	filter2 = encodeURIComponent(filter2);
	filter2 = filterPrefix + filter2;
	
	SDK.REST.retrieveMultipleRecords("Contact", filter2, selectedPersonCallBack, function (error) { alert(error.message); }, personSearchComplete);

	return false;
}


function selectedPersonCallBack(data) {
   // currently called after RetrieveMultiple Contact
	$("#SearchByIdentifierButton").enable = true;
	$('div#tmpDialog').hide(100);
	if (data != null && data.length > 0) {

		//var url = Xrm.Page.context.getClientUrl();
		//url += "/main.aspx?etc=2&pagetype=entityrecord&id=%7b" + data[0].ContactId + "%7d";
	 
		//INSTEAD OF OPENING THE URL HERE, YOU CAN SET THE INTERACTION CONTACTID TO THE CONTACTID RETURNED ABOVE!
		//window.open(url);
		
		window.parent.Xrm.Page.data.entity.save();					
		window.parent.mvi.personSelected(data[0].ContactId, __MVI_FullName);					
	}
	else {
		var lastName = _selectedPersonObj.getAttribute('lastName');
		var ssn = _selectedPersonObj.getAttribute('ssn');
		var dob = _selectedPersonObj.getAttribute('dateofbirth');
		//only run search if we have all three criteria
		if (ssn != "") {
			var filterPrefix = "$select=*&$filter=";
			var filter = "";
			filter += buildQueryFilter("bah_ssn_text", ssn.slice(-4), false);
		
			if (dob != "") {
				var dobdate = new Date(dob);
				var dobsearchstring = dobdate.getFullYear() + "-" + ("0" + (dobdate.getMonth() + 1)).slice(-2) + "-" + ("0" + dobdate.getDate()).slice(-2);
				dobsearchstring += "T12:00:00Z";
				filter += " and bah_dob_date eq datetime'" + dobsearchstring + "'";
			
				if (lastName != "") {
					filter += buildQueryFilter("LastName", lastName, true);
					
					filter = encodeURIComponent(filter);
					filter = filterPrefix + filter;
					
					SDK.REST.retrieveMultipleRecords("Contact", filter, crmVeteranSearchCallBackFromLast4SsnSearch, function (error) { alert(error.message); }, function() {/*do nothing*/});
				}
			}
		}
		//alert("no data returned by contact search in crm");
	}
}

function crmVeteranSearchCallBackFromLast4SsnSearch(veteranData) {
	crmVeteranSearchCallBack(veteranData, true);
}

function crmVeteranSearchCallBackFromMviDownSearch(veteranData) {
	crmVeteranSearchCallBack(veteranData, false);
}

function mviDownSearch() {
	$('#notFoundDiv').hide();
	var lastName = $("#LastNameTextBox").val();
	var firstName = $("#FirstNameTextBox").val();
	var middleName = $("#AddMiddleNameTextBox").val();             
	var ssn = $("#SocialSecurityTextBox").val();
	var dobyear = $("#BirthYearTextBox").val();
	var dobmonth = $("#BirthMonthTextBox").val();
	var dobday = $("#BirthDayTextBox").val();
	var dob = "";
	if(isNumeric(dobyear) && isNumeric(dobmonth) && isNumeric(dobday)) {
		if(!isNaN(Date.parse(dobyear + "-" + dobmonth + "-" + dobday))) {
			dob = dobyear + "-" + dobmonth + "-" + dobday;
		}
	}
	var filterPrefix = "$select=*&$filter=";
	var filter = "";

	//try to search by edipi
	if(_lastSearchType=="EDIPI") {
		var edipi = $("#EdipiTextBox").val();
		filter += buildQueryFilter("bah_edipi_text", edipi, false);
	}
	else {
		if (lastName != "") { //we should always have lastname if we got to this point
			filter += buildQueryFilter("LastName", lastName, false);
		}
		if (ssn != "") {
			filter += buildQueryFilter("bah_ssn_text", ssn, true);
		}
		if (dob != "") {
			var dobdate = new Date(dob);
			var dobsearchstring = dobdate.getFullYear() + "-" + ("0" + (dobdate.getMonth() + 1)).slice(-2) + "-" + ("0" + dobdate.getDate()).slice(-2);
			dobsearchstring += "T12:00:00Z";
			filter += " and bah_dob_date eq datetime'" + dobsearchstring + "'";
		}
		if (firstName != "") {
			filter += buildQueryFilter("FirstName", firstName, true);
			
		}
	}
	filter = encodeURIComponent(filter);
	filter = filterPrefix + filter;
	SDK.REST.retrieveMultipleRecords("Contact", filter, crmVeteranSearchCallBackFromMviDownSearch, function (error) { alert(error.message); }, function() {/*do nothing*/});
}
	
function crmVeteranSearchCallBack(veteranData, last4CallBack) {
	if (veteranData != null && veteranData.length > 0) {
		$("#possibleResultsTable").find("thead, tr, th").remove();
		$("#possibleResultsTable").find("tr:gt(0)").remove();
		$("#possibleResultsDiv").hide();
		$("#createDiv").hide();
		
		var table = $("#possibleResultsTable");
		var thead = document.createElement('thead');
		var theadRow = document.createElement('tr');
		for (var i = 0; i < veteranData.length; i++) {
			var contactId = veteranData[i].ContactId == null ? "" : veteranData[i].ContactId;
			var edipi = veteranData[i].bah_edipi_text == null ? "" : veteranData[i].bah_edipi_text;
			var dateOfBirth = veteranData[i].bah_dob_date == null ? "" : veteranData[i].bah_dob_date;
			var ssn = veteranData[i].bah_ssn_text == null ? "" : veteranData[i].bah_ssn_text;
			var firstName = veteranData[i].FirstName == null ? "" : veteranData[i].FirstName;
			var middleName = veteranData[i].MiddleName == null ? "" : veteranData[i].MiddleName;
			var lastName = veteranData[i].LastName == null ? "" : veteranData[i].LastName;
			var branch = veteranData[i].bah_branch_text == null ? "" : veteranData[i].bah_branch_text;
			var telephone1 = veteranData[i].Telephone1 == null ? "" : veteranData[i].Telephone1;
			//Address1_Line1
			var street1 = veteranData[i].Address1_Line1 == null ? "" : veteranData[i].Address1_Line1;
			var city = veteranData[i].Address1_City == null ? "" : veteranData[i].Address1_City;
			var zip = veteranData[i].Address1_PostalCode  == null ? "" : veteranData[i].Address1_PostalCode;
			var state = veteranData[i].bah_address1_state_code  == null ? "" : veteranData[i].bah_address1_state_code.Value;
			var source = veteranData[i].bah_source_text  == null ? "" : veteranData[i].bah_source_text;
			
			var fulladdress = "";
			if(city!="" && street1!="" && zip!="" && state!="") {
				fulladdress = street1 + " " + city + ", " + state + " " + zip;
			}
			
			var dobstring = "";
			if (dateOfBirth != "") {
				var dobdate = new Date(dateOfBirth);
				dobstring = ("0" + (dobdate.getMonth() + 1)).slice(-2) + "/" + ("0" + dobdate.getDate()).slice(-2) + "/" + dobdate.getFullYear();
			}

			if (i === 0) {
				addHeaderColumn(theadRow, "Full Name"); 
				if(last4CallBack){
					addHeaderColumn(theadRow, "Partial SSN");
				}
				else{
					addHeaderColumn(theadRow, "SSN");
				}
				addHeaderColumn(theadRow, "EDIPI");
				addHeaderColumn(theadRow, "Date of Birth");
				addHeaderColumn(theadRow, "Phone No"); 
				addHeaderColumn(theadRow, "Address");
				addHeaderColumn(theadRow, "Source");
				thead.appendChild(theadRow);
			}
				
			// Table rows
			var row = document.createElement('tr');
			addRowAttribute(row, 'fullName', lastName + ", " + firstName + " " + middleName, true);
			if(last4CallBack){
				addRowAttribute(row, 'ssn', "*****"+ssn, true);
			}
			else{
				addRowAttribute(row, 'ssn', ssn, true);
			}
			addRowAttribute(row, 'edipi', edipi, true);
			addRowAttribute(row, 'dobstring', dobstring, true);
			addRowAttribute(row, 'telephone1', telephone1, true);
			addRowAttribute(row, 'fulladdress', fulladdress, true);
			addRowAttribute(row, 'source', source, true);

				
			row.className = (i % 2 === 0) ? "even" : "odd";
			row.id = "resultstable-row-" + i;
			row.setAttribute('contactId', contactId);
			if(last4CallBack){
				row.ondblclick = function () { updateSelectedPersonFromLast4Search(this); };
				row.onkeydown = function (e) {
					if (e.keyCode === 13 || e.keyCode === 32) {
						updateSelectedPersonFromLast4Search(this);
					}
				};
			}
			else
			{
				row.ondblclick = function () { updateSelectedVeteranFromMviDownSearch(this); };
				row.onkeydown = function (e) {
					if (e.keyCode === 13 || e.keyCode === 32) {
						updateSelectedVeteranFromMviDownSearch(this);
					}
				};
			}
			table.append(row);
			table.append(thead);
		}
		$("#possibleResultsDiv").show();
	}
	else {
		alert("Could not find matching contact in CRM using provided search criteria");
	}
	
	$("#createDiv").show();
	if(last4CallBack) {
		$("#last4CreateRow").show();
		$("#mviDownCreateRow").hide();
	}
	else {
		$("#last4CreateRow").hide();
		$("#mviDownCreateRow").show();
		if(_lastSearchType=="EDIPI") {
			$("#createAttributesTable").show();
		}
		else
		{
			$("#createAttributesTable").hide();
		}
	}
}

function validateSearchByIdentifier() {
	var edipi = $("#EdipiTextBox").val();

	if (edipi != "") {
		if ((edipi.length != 10 || isNumeric(edipi) == false)) {
			$("#validationFailedDiv").text("VALIDATION FAILED: EDIPI is invalid.");
			return false;
		}
		return true;
	}
	else {
		$("#validationFailedDiv").text("VALIDATION FAILED: The search requires an EDIPI.");
		return false;
	}
}

function updateSelectedPersonFromLast4Search(obj) {
	//alert("here we would set the SSN for " + obj.getAttribute('contactId')+ " to " + _selectedPersonObj.getAttribute('ssn'));
	
	var contact = {};
	var contactid = obj.getAttribute('contactId');
	var fname = _selectedPersonObj.getAttribute('firstName');
	var lname = _selectedPersonObj.getAttribute('lastName');
	var patientMviIdentifier = _selectedPersonObj.getAttribute('patientMviIdentifier');
	var ssn = _selectedPersonObj.getAttribute('ssn');
	var edipi = _selectedPersonObj.getAttribute('edipi');
	var phone = _selectedPersonObj.getAttribute('phoneNumber');
	var mname = _selectedPersonObj.getAttribute('middleName'); 
	var street = _selectedPersonObj.getAttribute('address1'); 
	var city = _selectedPersonObj.getAttribute('city');
	var state = _selectedPersonObj.getAttribute('state');
	var zip = _selectedPersonObj.getAttribute('zip');
	var mmn = _selectedPersonObj.getAttribute('mmn'); 
	var gender = _selectedPersonObj.getAttribute('gender');
	var source = _selectedPersonObj.getAttribute('recordSource');
	var dobstring = _selectedPersonObj.getAttribute('dateofbirth');
	
	var dob;
	
	if (lname == "" || dob == "" || (ssn == "" && edipi == "")) {
		alert("Last Name, Date of Birth, and SSN or EDIPI are required to update the Veteran Record");
		return;
	}
	else {
		if(!isNaN(Date.parse(dobstring))) {
			var dobdate = new Date(dobstring);
			var dobmonth = dobdate.getMonth() + 1;
			var dobday = dobdate.getDate();
			var dobyear = dobdate.getFullYear() ;
			dob = dobyear + "-" + dobmonth + "-" + dobday + "T12:00:00Z";
			contact.bah_dob_date = dob;
		}
			
		contact.LastName = lname;
		contact.bah_dob_date = dob;
		contact.bah_source_text = source;
		
		if (ssn != "") { contact.bah_ssn_text = ssn; }
		if (edipi != "") { contact.bah_edipi_text = edipi; }
		if (fname != "") { contact.FirstName = fname; }
		if (mname != "") { contact.MiddleName = mname; }
		if (mmn != "") { contact.bah_mmn_text = mmn; }
		if (phone != "") { contact.Telephone1 = phone; }
		if (street != "") { contact.Address1_Line1 = street; }
		if (city != "") { contact.Address1_City = city; }
		if (zip != "") { contact.Address1_PostalCode = zip; }
		if (patientMviIdentifier != "") {contact.bah_mvipatientidentifier_text = patientMviIdentifier; }

		if (gender == "M")  { 
			contact.GenderCode = { Value: 1 };
		}
		else if (gender == "F") {
			contact.GenderCode = { Value: 2 };
		}
	
		if (state != "") {
			var stateObj = getState(state);
		}
		if (stateObj != null) {
			contact.DNS_address1_stateid = { Id: stateObj.DNS_stateId, LogicalName: "DNS_state", Name: stateObj.DNS_name };
			contact.Address1_StateOrProvince = stateObj.DNS_name;
		}
		else{
			contact.Address1_StateOrProvince = state;
		}
	}
	
	var fullname = lname + ", " + fname + " " + mname;
	SDK.REST.updateRecord(contactid, contact, "Contact", function() { updateSelectedVeteranOnForm(contactid, fullname); } , function (error) { alert(error.message); });
}

function updateSelectedVeteranFromMviDownSearch(obj) {
	var contactid = obj.getAttribute('contactId');
	var fullName = obj.getAttribute('fullName');
	updateSelectedVeteranOnForm(contactid, fullName);
}

function createNewVeteranFromLast4Search() {
	if (Xrm != null && Xrm.Page != null && Xrm.Page.context != null) {
		var fname = _selectedPersonObj.getAttribute('firstName');
		var lname = _selectedPersonObj.getAttribute('lastName');
		var patientMviIdentifier = _selectedPersonObj.getAttribute('patientMviIdentifier');
		var ssn = _selectedPersonObj.getAttribute('ssn');
		var edipi = _selectedPersonObj.getAttribute('edipi');
		var phone = _selectedPersonObj.getAttribute('phoneNumber');
		var mname = _selectedPersonObj.getAttribute('middleName'); 
		var street = _selectedPersonObj.getAttribute('address1'); 
		var city = _selectedPersonObj.getAttribute('city');
		var state = _selectedPersonObj.getAttribute('state');
		var zip = _selectedPersonObj.getAttribute('zip');
		var mmn = _selectedPersonObj.getAttribute('mmn'); 
		var gender = _selectedPersonObj.getAttribute('gender');
		var source = _selectedPersonObj.getAttribute('recordSource');
		var dobstring = _selectedPersonObj.getAttribute('dateofbirth');
		
		var dob;
		
		if (lname == "" || dob == "" || (ssn == "" && edipi == "")) {
			alert("Last Name, Date of Birth, and SSN or EDIPI are required to create a new Veteran Record");
			return;
		}
		else {
			var dobdate = new Date(dobstring);
			var dobmonth = dobdate.getMonth() + 1;
					var dobday = dobdate.getDate();
						var dobyear = dobdate.getFullYear() ;
			dob = dobyear + "-" + dobmonth + "-" + dobday + "T12:00:00Z";
		}
			
		// TODO: Add additional fields

		var contact = {};
		contact.LastName = lname;
		contact.bah_dob_date = dob;
		contact.bah_source_text = source;
		
		if (ssn != "") { contact.bah_ssn_text = ssn; }
		if (edipi != "") { contact.bah_edipi_text = edipi; }
		if (fname != "") { contact.FirstName = fname; }
		if (mname != "") { contact.MiddleName = mname; }
		if (mmn != "") { contact.bah_mmn_text = mmn; }
		if (phone != "") { contact.Telephone1 = phone; }
		if (street != "") { contact.Address1_Line1 = street; }
		if (city != "") { contact.Address1_City = city; }
		if (zip != "") { contact.Address1_PostalCode = zip; }
		if (patientMviIdentifier != "") {contact.bah_mvipatientidentifier_text = patientMviIdentifier; }
		
		if (gender == "M")  { 
			contact.GenderCode = { Value: 1 };
		}
		else if (gender == "F") {
			contact.GenderCode = { Value: 2 };
		}
		
		if (state != "") {
			var stateObj = getState(state);
			if (stateObj != null) {
				contact.DNS_address1_stateid = { Id: stateObj.DNS_stateId, LogicalName: "DNS_state", Name: stateObj.DNS_name };
				contact.Address1_StateOrProvince = stateObj.DNS_name;
			}
			else{
				contact.Address1_StateOrProvince = state;
			}
		}
		
		SDK.REST.createRecord(contact, "Contact", contactCreateCallBack, function (error) { alert(error.message); });
	}
}


function contactCreateCallBack(returnData) {
	if (returnData != null && returnData.length > 0) {
		alert("Contact was not created.");
		return;
	}
	
	try {
		window.parent.Xrm.Page.data.entity.save();
		window.parent.mvi.personSelected(returnData.ContactId, returnData.FullName);					
	}
	catch(err) {
		alert("Error encountered trying to update bah_veteranid field value to " + returnData.ContactId + " : " + err);
	}
}

function updateSelectedVeteranOnForm(contactid, fullname) {
	try {
		window.parent.Xrm.Page.data.entity.save();
		window.parent.mvi.personSelected(contactid, fullname);					
	}
	catch(err) {
		alert("Error encountered trying to update bah_veteranid field value to " + contactid + " : " + err);
	}
}

function showHideTable(tblObj, imgObj, msgObj) {
	if (tblObj.style.display != "") {  // show table & display -
		tblObj.style.display = "";
		imgObj.alt = "Hide Additional Search Criteria";
		imgObj.src = "bah_collapse"; //"expand_collapse_minus.gif"; 
		msgObj.value = "Hide Additional Search Criteria";
	}
	else {  // hide table & display +
		tblObj.style.display = "none";
		imgObj.alt = "Show Additional Search Criteria";
		imgObj.src = "bah_expand"; //"expand_collapse_plus.gif";
		msgObj.value = "Show Additional Search Criteria";
	}
}

function showHideTableFromKeydown(tblObj, imgObj, msgObj, event) {
	if (event.keyCode === 13 || event.keyCode === 32) {
		if (tblObj.style.display != "") {  // show table & show -
			tblObj.style.display = "";
			imgObj.alt = "Hide Additional Search Criteria";
			imgObj.src = "bah_collapse"; //"expand_collapse_minus.gif";
			msgObj.value = "Hide Additional Search Criteria";
		}
		else {  // hide table & show +
			tblObj.style.display = "none";
			imgObj.alt = "Show Additional Search Criteria";
			imgObj.src = "bah_expand"; // "expand_collapse_plus.gif";
			msgObj.value = "Show Additional Search Criteria";
		}

		// need to set focus back on the image (**NOT WORKING IN CRM)
		imgObj.focus();
	}
}

function getCountryId(countryname) {
	var countryId = "";

	var oDataSetName = "DNS_countrySet";
	var filter = "DNS_name eq '" + countryname + "'";
	var columns = "DNS_name, DNS_countryId";
	var requestResults = retrieveMultipleSync(oDataSetName, columns, filter);
	var country = null;

	if (requestResults != null) {
		country = requestResults.results[0];
		if (country != null)
		{
			countryId = country.DNS_countryId;
		}
	}
	
	return countryId;
}

function getState(statename){			
	var oDataSetName = "DNS_stateSet";
	var filter = "DNS_abbreviation_text eq '" + statename + "' or DNS_name eq '" + statename + "'";
	var columns = "DNS_name, DNS_stateId, DNS_abbreviation_text";
	var requestResults = retrieveMultipleSync(oDataSetName, columns, filter);			
	var result = null;

	if (requestResults != null) {
		result = requestResults.results[0];
	}
	
	if (result == null)
	{
		var oDataSetName = "DNS_stateSet";
		var filter = "DNS_name eq '" + statename + "'";
		var columns = "DNS_name, DNS_stateId";
		var requestResults = retrieveMultipleSync(oDataSetName, columns, filter);			
		var result = null;

		if (requestResults != null) {
			result = requestResults.results[0];
		}
	}
	return result;
}