var NursingCollegeFinder = (function () {
const dpForms = document.querySelectorAll("#leadFormConnecOfferstInline");
if (dpForms[0].attachEvent) {
dpForms[0].attachEvent("submit", dpSubmit);
} else {
dpForms[0].addEventListener("submit", dpSubmit);
}
const dpCip2Divs = document.querySelectorAll("#cip2div");
const dpCip6Divs = document.querySelectorAll("#cip6div");
function validateProgramInfo() {
var data = ConvertFormToJSON(
document.getElementById("leadFormConnecOfferstInline")
);
console.log("validate basic info form data = " + JSON.stringify(data));
// Form Validation
//if (data.cip0 == "" || data.cip2 == "") {
if (data.cip0 == "") {
//alert("Please select a study area and major.");
alert("Please select at least a study area.");
return;
}
return true;
}
function submitProgramInfo(e) {
e.preventDefault();
is_valid = validateProgramInfo();
if (is_valid) {
dpSubmit(e);
}
}
function dpSubmit(e) {
if (e.preventDefault) e.preventDefault();
var data = ConvertFormToJSON(
document.getElementById("leadFormConnecOfferstInline")
);
console.log("dpSubmit form data = " + JSON.stringify(data));
var major_slug = data.cip0;
if (data.cip2 != "" && typeof data.cip2 !== "undefined") {
major_slug += "/" + data.cip2;
}
if (data.cip6 != "" && typeof data.cip6 !== "undefined") {
major_slug += "/" + data.cip6;
}
console.log("offers_lookup major_slug = " + major_slug);
var backBtn = document.getElementById("nothanks");
backBtn.setAttribute(
"href",
"https://nursingdegreesearch.com/majors/" +
major_slug +
"/rankings/best-schools/"
);
dpOffersFetch(major_slug);
return false;
}
function dpOffersFetch(majorSlug) {
var url = "/majors/" + majorSlug + "/offers.json";
var url = "https://nursingdegreesearch.com" + "/majors/" + majorSlug + "/offers.json";
clearResults();
var loadingStateElement = document.getElementById("loadingState");
loadingStateElement.style.display = "block";
fetch(url, { mode: 'cors' })
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
buildResultsOrRedirect(data, majorSlug);
})
.catch((error) => {
console.log("Error fetching major offers:", error);
// Fallback: redirect to rankings page
radirectToRankings(majorSlug);
})
.finally(() => {
loadingStateElement.style.cssText = "display: none !important;";
});
}
function clearResults() {
// Clear existing results
var resultsContainer = document.getElementById("searchResults");
var esResults = document.getElementsByClassName("esy_widget_container")[0];
esResults.innerHTML = "";
resultsContainer.innerHTML = "";
}
function buildResultsOrRedirect(offers, majorSlug) {
var template = "";
var formData = ConvertFormToJSON(
document.getElementById("leadFormConnecOfferstInline")
);
console.log("json_data for: " + majorSlug);
console.log(offers);
if (!offers || offers.length === 0) {
// No offers found, redirect to rankings page
template = "rankings/best-schools/";
location.href =
"https://nursingdegreesearch.com/majors/" + majorSlug + "/" + template;
} else {
// Offers found, build results page
buildResults(offers, formData, majorSlug);
}
}
function buildResults(offers, formData, majorSlug) {
var esyohOffers = getRelevantEsyohOffers(offers, formData);
if (esyohOffers.length > 0) {
var esyohListingCategoryIds = esyohOffers.map((offer) => {
var credentialSourceMeta = JSON.parse(
htmlUnescape(offer.credential_source_meta)
);
return credentialSourceMeta.esyoh_id;
});
// buildEsyohWidget(esyohListingCategoryIds);
buildAndRedirectUrl(formData, majorSlug);
} else {
// No ESYOH offers found, build generic results
tryBuildSnhuOffers(offers, formData, majorSlug);
}
}
function tryBuildSnhuOffers(offersData, formData, majorSlug) {
// else use direct offers (ie. SNHU)
var directOffers = offersData.offers.filter(
(offer) => offer.credential_source !== "esyoh"
);
var title = "Featured Programs";
var intro = "Schools that offer programs in your area of interest";
var widgetId = "featured_programs";
var maxDisplay = 5;
var resultsContainer = document.getElementById("searchResults");
var container = document.createElement("div");
if (directOffers.length > 0) {
container.setAttribute("name", widgetId);
container.classList.add("featured-schools");
container.innerHTML = `
ADVERTISEMENTS
`;
if (title.length > 0 || intro.length > 0) {
if (title.length > 0) {
container.innerHTML += `${title}
`;
}
if (intro.length > 0) {
container.innerHTML += `${intro}
`;
}
container.innerHTML += ``;
} else {
container.innerHTML += `
`;
}
directOffers.slice(0, maxDisplay).forEach((offer) => {
var pageUrlNoPrefix = "nursingdegreesearch.com/" + majorSlug;
var pageUrlNoDomain = majorSlug;
var leadUrl = offer.lead_url
.replace(
"[page_url_no_prefix]",
encodeURIComponent(pageUrlNoPrefix).replace("/", "%2f")
)
.replace(
"[page_url_no_domain]",
encodeURIComponent(pageUrlNoDomain).replace("/", "%2f")
)
.replace("collegefactual-linkout", "nursingdegreesearch-linkout");
console.log("leadUrl = " + leadUrl);
container.innerHTML += `
`;
});
hideLoadingState();
container.innerHTML += `
`;
resultsContainer.appendChild(container);
} else {
setTimeout(() => {
hideLoadingState();
container.innerHTML += `
Found Best Schools rankings in your area of interest
`;
container.innerHTML += `
Taking you there automatically
`;
container.innerHTML += `
`;
resultsContainer.appendChild(container);
}, 1500);
setTimeout(() => {
radirectToRankings(majorSlug);
}, 3500);
}
}
function hideLoadingState() {
var loadingStateElement = document.getElementById("loadingState");
loadingStateElement.style.cssText = "display: none !important;";
}
function radirectToRankings(majorSlug) {
document.location.href =
"https://nursingdegreesearch.com/majors/" +
majorSlug +
"/rankings/best-schools/";
}
function getRelevantEsyohOffers(offersData, formData) {
// Narrow List to Current Degree Level If Available
console.log("formData = " + JSON.stringify(formData));
var mostRelevantOnly = formData.mostRelevantOnly;
var minRelevance = 0.8;
var maxRelevance = 1.0;
var returnOffers = [];
var relevantOffers = [];
var featuredOffers = offersData.offers.filter(
(offer) => offer.credential_source === "esyoh"
);
if (featuredOffers.length === 0) {
return relevantOffers;
}
if (formData.level) {
featuredOffers = featuredOffers.filter(
(offer) => offer.education_level_type_slug === formData.level
);
}
// Get Sorted List of Featured Offers that Meet Relevance Requirements
featuredOffers = featuredOffers
.sort((a, b) => b.lead_cpl - a.lead_cpl)
.sort((a, b) => b.relevance - a.relevance)
.slice(0);
featuredOffers.forEach((offer) => {
if (offer.relevance >= minRelevance && offer.relevance <= maxRelevance) {
console.log("offer relevance = ", offer.relevance);
relevantOffers.push(offer);
}
});
// TODO: Consider doing deeper display if only a single program
// If relevant ESYOH offers use those
if (relevantOffers.length > 0) {
if (mostRelevantOnly) {
// return only 1 top offer, whatever is most relevant
returnOffers = featuredOffers
.filter((offer) => offer.relevance >= 0.5)
.sort((a, b) => b.relevance - a.relevance)
.slice(0, 1);
} else {
// If opted to NOT just show most relevant, show all relevant
// For now only filtering to those with exact 1.0 match
returnOffers = relevantOffers.filter((offer) => offer.relevance >= 0.9);
}
}
return returnOffers;
}
function buildAndRedirectUrl(formData, majorSlug) {
const baseUrl = window.location.origin;
// Construct the path with selected slugs
let path = "majors" + "/" + majorSlug;
path += "/offers.html";
if (formData.level) {
path += "?level=" + encodeURIComponent(formData.level);
}
const fullUrl = baseUrl + "/" + path;
window.location.href = fullUrl;
}
function buildEsyohWidget(categoryIds) {
console.log("categoryIds = " + categoryIds);
setTimeout(() => {
var loadingStateElement = document.getElementById("loadingState");
loadingStateElement.style.cssText = "display: none !important;";
ESY.Widget({
category_id: `'${categoryIds.join(",")}'`,
new_window: "",
results: "3",
title: "",
domain_id: "nursingdegreesearch.com",
type: "listings",
widget_layout: "vertical",
intro: "",
placement: "",
});
}, 1000);
}
function populateDropdown(selector, options, currentValue) {
const select = document.getElementById(selector);
const existingOptions = select.children;
if (existingOptions.length > 1) {
for (var i = existingOptions.length - 1; i > 0; i--) {
select.removeChild(existingOptions[i]);
}
}
select.disabled = options.length === 0;
options.forEach((option) => {
if (option.slug !== "None") {
// Exclude options with 'None' as slug
const opt = document.createElement("option");
opt.value = option.slug;
opt.text = option.name;
if (option.slug === currentValue) {
opt.selected = true;
}
select.appendChild(opt);
}
});
}
// Function to handle changes in cip0 and cip2 dropdowns
function handleDropdownChange() {
const cip0Select = document.getElementById("cip0");
const cip2Select = document.getElementById("cip2");
const cip6Select = document.getElementById("cip6");
const focusDiv = document.getElementById("focus");
const findRankingsBtn = document.getElementById("findRankingsBtn");
// Initially disable the button
findRankingsBtn.disabled = true;
cip0Select.addEventListener("change", function () {
updateCip2Dropdown(this.value);
populateDropdown("cip6", [], null); // Reset cip6 when cip0 changes
findRankingsBtn.disabled = true; // Keep button disabled until cip2 is selected
});
cip2Select.addEventListener("change", function () {
const selectedCip0 = cip0Select.value;
const selectedCip2 = this.value;
const cip2Entry = healthcare_majors_list[selectedCip0].cip4s.find(
(cip4) => cip4.cip4_slug === selectedCip2
);
if (cip2Entry && cip2Entry.cip6s) {
var cip6Options = cip2Entry.cip6s.map((cip6) => {
return { name: cip6.cip6_name, slug: cip6.cip6_slug };
})
.sort((a, b) => a.name.localeCompare(b.name)); // Sort alphabetically
populateDropdown("cip6", cip6Options, null);
} else {
populateDropdown("cip6", [], null); // Reset cip6 if no cip4 is found
}
findRankingsBtn.disabled = !this.value || this.value === "";
});
cip6Select.addEventListener("change", function () {
// Enable the button when a cip6 item is selected
findRankingsBtn.disabled = !this.value || this.value === "";
});
}
// Function to update cip2 based on cip0 selection
function updateCip2Dropdown(selectedCip0) {
if (selectedCip0) {
const cip2Options = healthcare_majors_list[selectedCip0].cip4s
.map((cip4) => {
return { name: cip4.cip4_name, slug: cip4.cip4_slug };
})
.sort((a, b) => a.name.localeCompare(b.name));
populateDropdown("cip2", cip2Options, null);
const cip2Select = document.getElementById("cip2");
if (cip2Select.options.length > 1) {
cip2Select.selectedIndex = 1; // Select the first non-placeholder option
// Get the selected cip2 value
const selectedCip2 = cip2Select.value;
// Find the corresponding cip2 entry
const cip2Entry = healthcare_majors_list[selectedCip0].cip4s.find(
(cip4) => cip4.cip4_slug === selectedCip2
);
// Populate cip6 dropdown if cip6s exist
if (cip2Entry && cip2Entry.cip6s) {
const cip6Options = cip2Entry.cip6s.map((cip6) => {
return { name: cip6.cip6_name, slug: cip6.cip6_slug };
})
.sort((a, b) => a.name.localeCompare(b.name)); // Sort alphabetically
populateDropdown("cip6", cip6Options, null);
} else {
populateDropdown("cip6", [], null); // Reset cip6 if no cip6s are found
}
cip2Select.dispatchEvent(new Event('change')); // Trigger change event
}
} else {
populateDropdown("cip2", [], null); // Reset cip2 if no cip0 is found
populateDropdown("cip6", [], null); // Also reset cip6
}
// Update button state based on cip2 selection
const findRankingsBtn = document.getElementById("findRankingsBtn");
findRankingsBtn.disabled = !selectedCip0 || cip2Select.selectedIndex === 0;
}
// Utility function to unescape HTML entities
function htmlUnescape(str) {
var temp = document.createElement("div");
temp.innerHTML = str;
var result = temp.childNodes[0] ? temp.childNodes[0].nodeValue : "";
temp.remove();
return result;
}
function populateInitialValues() {
// Code to handle URL parameters and prefill values
document.getElementById("landing_url").value = window.location.href;
var return_url = GetParameterValues("return_url");
if (return_url != "" && return_url != undefined && return_url != null) {
var backBtn = document.getElementById("nothanks");
backBtn.setAttribute(
"href",
decodeURIComponent(GetParameterValues("return_url")) ||
"https://nursingdegreesearch.com/"
);
backBtn.addEventListener("click", nextPage);
document.getElementById("referring_url").value = return_url;
} else {
document.getElementById("referring_url").value = document.referrer;
}
}
function initializeDropdowns() {
var currentCip2 = "health-professions";
var cip2Options = Object.keys(healthcare_majors_list)
.map((key) => {
return { name: healthcare_majors_list[key].cip2_name, slug: key };
})
.sort((a, b) => a.name.localeCompare(b.name));
populateDropdown("cip0", cip2Options, currentCip2);
if (currentCip2) updateCip2Dropdown(currentCip2);
}
function nextPage(e) {
e.preventDefault();
window.location.href = document.getElementById("nothanks").href;
return true;
}
// Publicly exposed functions
return {
initialize: function () {
populateInitialValues();
initializeDropdowns();
handleDropdownChange();
},
submitProgramInfo: submitProgramInfo,
};
})();
window.onload = NursingCollegeFinder.initialize;