let tooltipThreshold = 16;
let toolIconThreshold = 12;
let tooltipSmall;
let tooltipBig;
let singletooltipopen = false;
let addressReferrer = '';
let home_id = '';
const is_home_in_mbm = () => {
if (home_id === '') {
return false;
}
else {
return true;
}
};
let id = 0;
const corner1 = [37.866964, -88.606680];
const corner2 = [35.735020, -86.061297];
const interestBox = new bootstrap.Modal(document.getElementById('interestBox'));
const thankYouBox = new bootstrap.Modal(document.getElementById('thankyouBox'));
const colors = ["#8f8389","#e0a100","#00AFF5","#f25cd7","#5ce8f2"]
const transcolors = ["rgba(143, 131, 137,.25)", "rgba(224, 161, 0,0.25)", "rgba(0, 175, 245,0.25)"]
const apiKey = "AAPKf3b50bc234014cb6a6a75347af8db0d2LIJ5XSQAYjsxBuxdmWT74QSa-BJBv0YtkdbUHv_MAqpXUIuTSH5VW5fD1wWgEsKi";
const basemapEnum = "ArcGIS:LightGray";
const polygons = [];
const layers = [];
let markers = [];
const polygon_areas_load_status = {"0":false,"1":false,"2":false, "business": false};
const are_all_polygon_areas_loaded = obj => {return Object.keys(obj).every(key => obj[key] === true)};
let all_polygon_areas_loaded = {"result": false}; // must be an object so it's passed by reference to the waitForEquality function
let specialBusinessZonePolygon = null;
let inside_hopkinsville_special_business_zone = null;
let can_get_service = false;
const map = L.map('map',{
maxBounds: [corner1,corner2],
}).setView([36.8656, -87.4886],11);
function init_map(map) {
map.createPane('pane0');
map.getPane('pane0').style.zIndex = 1100;
map.getPane('pane0').style.pointerEvents = 'none';
map.createPane('pane1');
map.getPane('pane1').style.zIndex = 1101;
map.getPane('pane1').style.pointerEvents = 'none';
map.createPane('pane2');
map.getPane('pane2').style.zIndex = 1102;
map.getPane('pane2').style.pointerEvents = 'none';
map.createPane('mkPane');
map.getPane('mkPane').style.zIndex = 1103;
map.getPane('mkPane').style.pointerEvents = 'none';
map.createPane('ttPane');
map.getPane('ttPane').style.zIndex = 1104;
map.getPane('ttPane').style.pointerEvents = 'none';
map.options.minZoom = 11;
map.options.maxZoom = 16;
L.esri.Vector.vectorBasemapLayer(basemapEnum, {
apiKey: apiKey,
}).addTo(map);
fetch("https://goenergynet.com" + "/home/getSpecialBusinessZonePolygon")
.then(function(response) {
return response.json();
}).then(function(data) {
specialBusinessZonePolygon = data.features[0].geometry.coordinates;
polygon_areas_load_status["business"] = true;
all_polygon_areas_loaded["result"] = are_all_polygon_areas_loaded(polygon_areas_load_status);
}).catch(error => { console.log(error)});
fetch("https://goenergynet.com" + "/home/mapAreas/0")
.then(function(response) {
return response.json();
}).then(function(data0) {
if (data0["features"] != null) {
renderGeoJson(data0, "pane0");
}
polygon_areas_load_status["0"] = true;
all_polygon_areas_loaded["result"] = are_all_polygon_areas_loaded(polygon_areas_load_status);
}).catch(error => { console.log(error)});
fetch("https://goenergynet.com" + "/home/mapAreas/1")
.then(function(response) {
return response.json();
}).then(function(data1) {
if (data1["features"] != null) {
renderGeoJson(data1, "pane1");
}
polygon_areas_load_status["1"] = true;
all_polygon_areas_loaded["result"] = are_all_polygon_areas_loaded(polygon_areas_load_status);
}).catch(error => {console.log(error)});
fetch("https://goenergynet.com" + "/home/mapAreas/2")
.then(function(response) {
return response.json();
}).then(function(data2) {
if (data2["features"] != null) {
renderGeoJson(data2, "pane2");
}
polygon_areas_load_status["2"] = true;
all_polygon_areas_loaded["result"] = are_all_polygon_areas_loaded(polygon_areas_load_status);
}).catch(error => {console.log(error)});
var legend = L.control({position: 'topright'});
legend.onAdd = function (map) {
let middlehtml = '';
var div = L.DomUtil.create('div', 'info legend bg-white bg-gradient border border-info shadow rounded p-4'),
grades = ["Planning", "Under Construction", "Available"],
labels = ["https://goenergynet.com/images/planningMarker.png","https://goenergynet.com/images/constructionMarker.png", "https://goenergynet.com/images/completeMarker.png"];
if(!L.Browser.mobile){
for (var i = 0; i < grades.length; i++) {
middlehtml +=
"
" + grades[i] + " |
";
}
div.innerHTML += "Legend
Click an area on the map
for additional information.
";
return div;
} else {
for (var i = 0; i < grades.length; i++) {
middlehtml +=
"" + grades[i] + "";
}
div.innerHTML += "Legend
" + middlehtml + "Click an area on the map for additional information.
";
return div;
}
};
legend.addTo(map);
handleReferrerAndSearch();
}
(function() {
init_map(map);
})();
function renderGeoJson(data, pane) {
let geo = new L.GeoJSON(data, {
style: function(feature) {
return {
color: colors[feature.properties.ready],
weight: 2,
opacity: 1,
clickable: false
};
},
onEachFeature: function (feature, layer) {
let readydate = luxon.DateTime.fromISO(feature.properties.ready_date).toLocaleString({ month: 'long', year: 'numeric'})
let icon;
let marker;
let text = 'Construction';
polygons.push(feature);
layer.id = id;
let thislayer = { id: id, layer: layer};
layers.push(thislayer)
switch(feature.properties.ready){
case 0:
icon='planningIcon.png'
marker='planningMarker.png'
text='Planning Phase' +
'Construction expected to begin:
' + readydate + '';
break;
case 1:
icon='constructionIcon.png'
marker='constructionMarker.png'
text='Construction Phase' +
'Early Signup Available.
Enter your address above!
Est. ' + readydate + '';
break;
case 2:
icon='completeIcon.png'
marker='completeMarker.png'
text='Available Today!' +
'Enter your address to
Sign up now!';
break;
case 999:
marker=''
text=''
break;
}
let html = ''
layer.bindTooltip(html, {interactive: false,opacity: .9, direction: 'center', pane: 'ttPane', className: 'project-area-callout tt-big-' + feature.properties.id + '',offset:[0, -45] })
layer.on('click', function(event) {
if(L.Browser.mobile) {
layers.forEach(function(thelayer){
thelayer.layer.setStyle({
fillOpacity: 0.2
});
});
layer.setStyle({
fillOpacity: 0.7
});
}
map.closeTooltip();
layer.openTooltip(event.latlng);
});
if(!L.Browser.mobile) {
layer.on('mouseover', function(event){
map.closeTooltip();
layer.setStyle({
fillOpacity: 0.7
});
layer.openTooltip(event.latlng);
});
layer.on('mousemove', function(event) {
layer.openTooltip(event.latlng);
});
layer.on('mouseout', function(){
map.closeTooltip();
layer.setStyle({
fillOpacity: 0.2
});
});
}
id++;
},
pane: pane
}).addTo(map);
}
function handleReferrerAndSearch() {
if(addressReferrer !== "") {
L.esri.Geocoding.geocode({apikey: apiKey}).text(addressReferrer).run(function (err, results, response) {
if (err) {
console.log(err);
return;
}
const theData = {}
theData.results = response.results;
searchHandler(results, response);
});
}
}
function waitForEquality(n, a, key, b) {
// every n miliseconds, check a[key] == b. once true, resolve
// a must be an object so it's passed to this function by reference not by value
return new Promise((resolve, reject) => {
const intervalId = setInterval(() => {
if (a[key] === b) {
clearInterval(intervalId);
resolve();
}
}, n);
});
}
function attach_callback_to_radio_group(groupName, callback) {
const radio_buttons = document.getElementsByName(groupName);
for (const radio_button of [...radio_buttons.values()]) {
radio_button.addEventListener('change', callback);
}
}
function res_or_bus_press_callback(event) {
if (getSelectedRadioValue("res_or_bus") === "residential") {
document.getElementById("businessName").style.display = "none";
setTitleAndSubmitButtonText();
}
if (getSelectedRadioValue("res_or_bus") === "business") {
document.getElementById("businessName").style.display = "block";
setTitleAndSubmitButtonText();
}
}
const getSelectedRadioValue = (radioGroupName) => {
const radios = document.getElementsByName(radioGroupName);
for (const radio of radios) {
if (radio.checked) {
return radio.value;
}
}
return "";
}
const signupFormTitleText = () => {
if (is_home_in_mbm()) {
return "Ready to sign up?"
}
else {
return "More information needed"
}
}
const signupFormSubText = (can_get_service) => {
if (can_get_service) {
if (is_home_in_mbm()) {
return "Fill out this quick form and we'll send you to the signup portal!"
}
else {
return "Our Fiber Optic internet service appears to be available at your address but it is not yet registered in our system. Please enter your contact information below and we will contact you to register the address and guide you through the rest of the signup process."
}
}
else {
return ""
}
}
async function searchHandler(data, results){
const theLatLng = data.results[0].latlng;
const address = data.results[0].text;
const marker = L.marker(theLatLng).addTo(map);
let point = turf.helpers.point([+theLatLng.lng, +theLatLng.lat]);
let available = false;
let signup = false;
let noform = false;
let clickedArea = "unavailable";
let logSearch = await postDataAsJson({url:'https://goenergynet.com/addressForm', data: {address: address}});
inside_hopkinsville_special_business_zone = turf.booleanPointInPolygon.default(point, turf.helpers.polygon(specialBusinessZonePolygon));
await waitForEquality(100, all_polygon_areas_loaded, "result", true); // async waits for polygons to be loaded
for(let j = 0; j < polygons.length; j++){
let poly = turf.helpers.polygon(polygons[j].geometry.coordinates)
if(turf.booleanPointInPolygon.default(point, poly)) {
switch(polygons[j].properties.ready) {
case 0:
clickedArea = polygons[j].properties.name;
available = true;
break;
case 1:
clickedArea = polygons[j].properties.name;
available = true;
signup = true;
can_get_service = true;
break;
case 2:
clickedArea = polygons[j].properties.name;
available = true;
signup = true;
can_get_service = true;
break;
}
}
}
fetch('https://goenergynet.com' + '/home/signupForm')
.then(function(response) {
return response.text();
}).then(function(data) {
if(!noform) {
const modalContentForm = document.querySelector("#formContainerDiv");
modalContentForm.innerHTML = data;
document.querySelector('#address').value = address;
document.querySelector('#address').readOnly = true;
document.querySelector('#clickedArea').value = clickedArea;
document.querySelector('#signup').value = signup;
attach_callback_to_radio_group('res_or_bus', res_or_bus_press_callback);
const interestForm = document.getElementById("interestForm");
setTitleAndSubmitButtonText();
interestForm.addEventListener("submit", (event) => handleSignUpFormSubmit(event, can_get_service, clickedArea, inside_hopkinsville_special_business_zone));
}
document.querySelector("#formBox").style.display = "block";
}).then(function() {
interestBox.toggle();
});
}
const setTitleAndSubmitButtonText = () => {
let title = document.getElementById("formTitle");
let button = document.getElementById("signup");
let texts = signupFormTitleTextAndButtonText();
title.textContent = texts[0];
button.textContent = texts[1];
};
async function postDataAsJson({ url, data }) {
const formDataJsonString = JSON.stringify(data);
const fetchOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: formDataJsonString,
};
const response = await fetch(url, fetchOptions);
if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}
return response.json();
}
const are_form_fields_filled = () => {
if (getSelectedRadioValue("res_or_bus") == "") {
alert("Please specify Residential or Business");
return false;
}
if (getSelectedRadioValue("res_or_bus") == "business" && document.getElementById("businessName").value == "") {
alert("Please specify Business Name");
return false;
}
if (document.getElementById("firstName").value == "") {
alert("Please fill in first name");
return false;
}
if (document.getElementById("lastName").value == "") {
alert("Please fill in last name");
return false;
}
if (document.getElementById("primaryPhoneNumber").value == "") {
alert("Please fill in phone number");
return false;
}
if (document.getElementById("email").value == "") {
alert("Please fill in email");
return false;
}
return true;
}
async function saveInterestForm(form_data) {
const formDataJsonString = JSON.stringify(form_data);
const fetchOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: formDataJsonString,
};
const response = await fetch("/interestForm", fetchOptions);
if (!response.ok) {
const errorMessage = await response.text();
console.log(errorMessage);
const msg = JSON.parse(errorMessage).msg;
document.getElementById('signupErrors').innerHTML = Object.values(msg)[0];
return;
}
interestBox.toggle();
thankYouBox.show();
return response.json();
}
const signupFormTitleTextAndButtonText = () => {
const t1 = ["Available Now!", "Let's Connect!"];
const t2 = ["We're not planning fiber in this area just yet.", "Contact Me Once Fiber is Available!"];
// available to no one
if (!can_get_service && !inside_hopkinsville_special_business_zone) {
return t2;
}
// available to special business zone AND not in a standard polygon
if (inside_hopkinsville_special_business_zone && !can_get_service) {
if (getSelectedRadioValue("res_or_bus") === "residential") {
return t2;
}
else if (getSelectedRadioValue("res_or_bus") === "business") {
return t1;
}
else if (getSelectedRadioValue("res_or_bus") === "") {
return t1;
}
}
// available to either
if (can_get_service) {
return t1;
}
else {
"Error: Invalid title generation state"
}
}
async function handleSignUpFormSubmit(event, can_get_service, clickedArea, isInSpecialBusinessZone) {
event.preventDefault();
if (!are_form_fields_filled()) {
return;
}
document.querySelector('.interestAlert').style.display = "none";
const address = document.getElementById('address').value;
const form = event.currentTarget;
const formData = new FormData(form);
const plainFormData = Object.fromEntries(formData.entries());
plainFormData["inquiryType"] = getSelectedRadioValue("res_or_bus");
///////////////////////////// Form Data ///////////////////////////
// note: there are similarly named fields for convenience, the apis require slight deviations
const form_data = {
"homeId": home_id,
"inquiryType": getSelectedRadioValue("res_or_bus"),
"businessName": document.getElementById("businessName").value,
"firstName": document.getElementById("firstName").value,
"lastName": document.getElementById("lastName").value,
"phoneNumber": document.getElementById("primaryPhoneNumber").value,
"primaryPhoneNumber": document.getElementById("primaryPhoneNumber").value,
"email": document.getElementById("email").value,
"emailAddress": document.getElementById("email").value,
"smsAllowed": document.getElementById("smsAllowed_0").checked,
"clickedArea": clickedArea,
"address": address
}
// ///////////////////////////// Conditionals ////////////////////////////
// 1) Residential / Business
let res_or_bus = form_data["inquiryType"];
// 2) Exist or not exist in broadhub (TODO: review the truth table in sql with micah)
// 3) In broadhub, marked or not as available?
let exists_and_available_in_broadhub = is_home_in_mbm();
// 4) Can get service (Blue yellow polygon overlap) / can't get service (grey, no polygon overlap)
can_get_service = can_get_service;
// 5) Inside Hopkinsville special Business zone or not
let inside_hopkinsville_special_business_zone = isInSpecialBusinessZone;
///////////////////////////// Effects ////////////////////////////
if (res_or_bus === "residential") {
if (exists_and_available_in_broadhub === true) {
if (can_get_service === true) {
package_selection_page(form_data);
console.log("1");
}
if (can_get_service === false) {
console.log("2");
debug_email(form_data);
}
}
if (exists_and_available_in_broadhub === false) {
if (can_get_service === true) {
console.log("3");
email_sales(form_data);
}
if (can_get_service === false) {
console.log("4");
saveInterestForm(form_data);
}
}
}
else if (res_or_bus === "business") {
if (can_get_service === true) {
console.log("5");
email_sales(form_data);
}
if (can_get_service === false) {
if (inside_hopkinsville_special_business_zone === true) {
console.log("6");
email_sales(form_data);
}
if (inside_hopkinsville_special_business_zone === false) {
console.log("7");
saveInterestForm(form_data);
}
}
}
else {
console.log("error: not residential or business");
}
}
async function email_sales (form_data) {
return fetch("https://goenergynet.com" + "/home/notifySalesOfSignup", {
method: "POST",
body: JSON.stringify(form_data),
headers: {
'Content-Type': 'application/json'
},
}).then( async (response) => {
if (!response.ok) {
const errorMessage = await response.text();
console.log(errorMessage);
const msg = JSON.parse(errorMessage).msg;
document.getElementById('signupErrors').innerHTML = Object.values(msg)[0];
return;
}
else {
interestBox.toggle();
thankYouBox.show();
}
});
}
const debug_email = (form_data) => {
return fetch("https://goenergynet.com" + "/home/debugEmail", {
method: "POST",
body: JSON.stringify(form_data),
headers: {
'Content-Type': 'application/json'
},
}).then( (response) => {
return response.json();
}).then( (response) => {
interestBox.toggle();
thankYouBox.show();
});
}
const package_selection_page = (form_data) => {
const mbmUrl = 'https://mybroadbandaccount.com/energynet/gateway/v1/entrance'
const handoffData = {
"homeId": form_data.homeId,
"customer": {
"firstName": form_data.firstName,
"lastName": form_data.lastName,
"email": form_data.email,
"primaryPhoneNumber": form_data.primaryPhoneNumber,
}
}
// use fetch to post the json data to home/mbmRedirect
fetch("https://goenergynet.com" + "/home/mbmRedirect", {
method: "POST",
body: JSON.stringify(handoffData),
headers: {
'Content-Type': 'application/json'
},
}).then(function(response) {
return response.json();
}).then(function(data) {
if(typeof(data.error) !== 'undefined') {
document.getElementById('signupErrors').innerHTML = data.error;
} else {
const mbmForm = document.createElement('form');
mbmForm.setAttribute('id', 'mbmForm');
mbmForm.setAttribute('method', 'post');
mbmForm.setAttribute('action', mbmUrl);
mbmForm.setAttribute('target', '_blank');
//iterate over the data object and create input elements
for (var key in data) {
if (data.hasOwnProperty(key)) {
const mbmFormInput = document.createElement('input');
mbmFormInput.setAttribute('type', 'hidden');
mbmFormInput.setAttribute('name', key);
mbmFormInput.setAttribute('value', data[key]);
mbmForm.appendChild(mbmFormInput);
}
}
document.body.appendChild(mbmForm);
// if it is mobile, do other things
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// set the form target to the current window
mbmForm.setAttribute('target', '_self');
}
mbmForm.submit();
interestBox.toggle();
thankYouBox.show();
document.getElementById("thankYouBoxSubtextContents").textContent = "We're opening the signup page in another tab."
}
}).catch(error => { console.log(error)});
}