var OffersFinder = (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://graddegree.com/majors/" +
major_slug +
"/rankings/best-schools/"
);
dpOffersFetch(major_slug);
return false;
}
function dpOffersFetch(majorSlug) {
var url = "/majors/" + majorSlug + "/offers.json";
// var url = '/' + majorSlug + '/offers.json';
clearResults();
var loadingStateElement = document.getElementById("loadingState");
loadingStateElement.style.display = "block";
fetch(url)
.then((response) => response.json())
.then((data) => {
buildResultsOrRedirect(data, majorSlug);
})
.catch((error) => {
loadingStateElement.style.cssText = "display: none !important;";
console.log("ERROR FETCHING major offers");
console.log("json fetch for URL: " + url + "Error: ", error);
});
}
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://graddegree.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 = "graddegree.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", "graddegree-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://graddegree.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) {
// Get the current base URL including protocol and host
const baseUrl = window.location.origin;
// Construct the path with selected slugs
let path = "majors" + "/" + majorSlug;
path += "/offers.html";
// Append query parameter for the level of education
if (formData.level) {
path += "?level=" + encodeURIComponent(formData.level);
}
const fullUrl = baseUrl + "/" + path;
// Redirect the browser to the constructed URL
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: "graddegree.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"); // Assume button has this ID
// Initially disable the button
findRankingsBtn.disabled = true;
cip0Select.addEventListener("change", function () {
updateCip2Dropdown(this.value);
populateDropdown("cip6", [], null); // Reset cip6 when cip2 changes
findRankingsBtn.disabled = !this.value || this.value === "";
findRankingsBtn.disabled = true; // Keep button disabled until cip2 is selected
});
cip2Select.addEventListener("change", function () {
const cip2Entry = grad_degree_majors_list[cip0Select.value].cip4s.find(
(cip4) => cip4.cip4_slug === this.value
);
if (cip2Entry && cip2Entry.cip6s) {
var cip6Options = cip2Entry.cip6s.map((cip6) => {
return { name: cip6.cip6_name, slug: cip6.cip6_slug };
});
populateDropdown("cip6", cip6Options, null);
// focusDiv.style.display = "block";
} else {
populateDropdown("cip6", [], null); // Reset cip6 if no cip4 is found
}
findRankingsBtn.disabled = !this.value || this.value === "";
});
cip6Select.addEventListener("change", function () {
// findRankingsBtn.disabled = !this.value || this.value === "";
});
}
// Function to update cip2 based on cip0 selection
function updateCip2Dropdown(selectedCip0) {
if (selectedCip0) {
const cip2Options = grad_degree_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);
} else {
populateDropdown("cip2", [], null); // Reset cip2 if no cip0 is found
}
}
// 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://graddegree.com/"
);
backBtn.addEventListener("click", nextPage);
document.getElementById("referring_url").value = return_url;
} else {
document.getElementById("referring_url").value = document.referrer;
}
}
function initializeDropdowns() {
var currentCip2 = null;
var cip2Options = Object.keys(grad_degree_majors_list)
.map((key) => {
return { name: grad_degree_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,
};
/* Common Shared Functions */
function GetParameterValues(param) {
var url = window.location.href
.slice(window.location.href.indexOf("?") + 1)
.split("&");
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split("=");
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
function ConvertFormToJSON(form) {
var json = {};
const formData = new FormData(form);
for (const [key, value] of formData.entries()) {
json[key] = value || "";
}
return json;
}
})();
window.onload = OffersFinder.initialize;