Skip to content

Instantly share code, notes, and snippets.

@captbunzo
Last active December 6, 2017 08:02
Show Gist options
  • Save captbunzo/6e2e550637b6d88c17087a9c6cb7e10d to your computer and use it in GitHub Desktop.
Save captbunzo/6e2e550637b6d88c17087a9c6cb7e10d to your computer and use it in GitHub Desktop.
custom.js for poke.farm
const BROWSER_ID_MSIE = 'MSIE';
const BROWSER_ID_EDGE = 'Edge';
const BROWSER_ID_CHROME = 'Chrome';
const BROWSER_ID_FIREFOX = 'Firefox';
const BROWSER_ID_SAFARI = 'Safari';
const BROWSER_ID_OPERA = 'Opera';
const BROWSER_ID_UNKNOWN = 'Unknown';
function getBrowserId() {
// Check if browser is IE
if (navigator.userAgent.search("MSIE") >= 0) {
return BROWSER_ID_MSIE;
// Check if browser is Edge
} else if (navigator.userAgent.search("Edge") >= 0) {
return BROWSER_ID_EDGE;
// Check if browser is Chrome
} else if (navigator.userAgent.search("Chrome") >= 0) {
return BROWSER_ID_CHROME;
// Check if browser is Firefox
} else if (navigator.userAgent.search("Firefox") >= 0) {
return BROWSER_ID_FIREFOX;
// Check if browser is Safari
} else if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
return BROWSER_ID_SAFARI;
// Check if browser is Opera
} else if (navigator.userAgent.search("Opera") >= 0) {
return BROWSER_ID_OPERA;
// I guess we just do not know
} else {
return BROWSER_ID_UNKNOWN
}
}
/*
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
*/
function getProtocol() {
return window.location.protocol;
}
function getCurrentDomain() {
return window.location.host.replace(/^[^.]+\./g, '');
}
function getDomain() {
switch (getBrowserId()) {
case BROWSER_ID_CHROME : return 'xn--pok-dma.farm';
case BROWSER_ID_MSIE :
case BROWSER_ID_EDGE :
case BROWSER_ID_UNKNOWN : return 'poke.farm';
default : return window.location.host.replace(/^[^.]+\./g, '');
}
}
function getSubdomain() {
return window.location.host.split('.')[0];
}
function getLocationHashValue() {
var hash = location.hash.replace(/^#/, '');
return ( hash != '' ? hash : null );
}
function getRegion() {
var region = getSubdomain();
if ( (region != null) && (region != '') && (region != 'map') && (region != 'maps') ) {
return region;
} else {
return 'greatswamp';
}
}
function getTown() {
var hash = getLocationHashValue();
if ( (hash == null) || (hash.match(/^[a-zA-Z0-9\-]+$/) == null) ) {
return null;
}
return ( hash != null ? hash.replace('-', '') : null );
}
function getCoords() {
var hash = getLocationHashValue();
if ( (hash == null) || (hash.match(/^-?[0-9]+[.[0-9]*]?,-?[0-9]+[.[0-9]*]?,[0-9]+z$/) == null) ) {
return null;
}
var parts = hash.split(',');
return { lat: Number(parts[0]), lng: Number(parts[1]), zoom: Number(parts[2].replace(/z$/, '')) };
}
function createLink(label, url) {
return { label: label, url: url };
}
function createTown(name, lat, lng, zoom) {
var id = name.toLowerCase().replace(' ', '');
var hash = name.toLowerCase().replace(' ', '-');
return { id: id, name: name, hash: hash, lat: lat, lng: lng, zoom: zoom };
}
function createRegion(region) {
var links = new Array();
var towns = new Array();
switch (region) {
case 'boonton' :
links['discord'] = createLink('Boonton Chat', 'http://discord.gg/H4gTva2');
links['patreon'] = createLink('Donate Now!', 'http://patreon.com/TeamUnityBoonton');
towns['boonton'] = createTown('Boonton', 40.9026076, -74.4110998, 14);
towns['denville'] = createTown('Denville', 40.8889371, -74.4803950, 14);
towns['dover'] = createTown('Dover', 40.8831280, -74.5646857, 14);
towns['easthanover'] = createTown('East Hanover', 40.8189249, -74.3667140, 14);
towns['lakehiawatha'] = createTown('Lake Hiawatha', 40.8796864, -74.3820104, 14);
towns['madison'] = createTown('Madison', 40.7587738, -74.4175343, 14);
towns['montville'] = createTown('Montville', 40.9128873, -74.3832916, 14);
towns['morristown'] = createTown('Morristown', 40.7945707, -74.4823439, 14);
towns['mountarlington'] = createTown('Mount Arlington', 40.9224819, -74.6364432, 14);
towns['parsippany'] = createTown('Parsippany', 40.8645465, -74.4199720, 14);
towns['randolph'] = createTown('Randolph', 40.8450322, -74.5740550, 14);
return { id: region
, name: 'Boonton'
, lat: 40.8839380
, lng: -74.4081290
, zoom: 12
, links: links
, towns: towns };
break;
case 'greatswamp' :
links['discord'] = createLink('Team Unity Chat', 'http://discord.gg/9SXuuWE');
links['patreon'] = createLink('Donate Now!', 'http://patreon.com/TeamUnityPogo');
towns['berkeleyheights'] = createTown('Berkeley Heights', 40.6765566, -74.4309294, 14);
towns['chatham'] = createTown('Chatham', 40.7389077, -74.3832849, 14);
towns['chathamtownship'] = createTown('Chatham Township', 40.7247466, -74.4202902, 14);
towns['florhampark'] = createTown('Florham Park', 40.7868362, -74.3891407, 14);
towns['longhill'] = createTown('Long Hill', 40.6783343, -74.4941848, 14);
towns['madison'] = createTown('Madison', 40.7587738, -74.4175343, 14);
towns['newprovidence'] = createTown('New Providence', 40.6974946, -74.4009004, 14);
towns['shorthills'] = createTown('Short Hills', 40.7313797, -74.3218263, 14);
towns['somerset'] = createTown('Somerset', 40.4446071, -74.5278626, 13);
towns['summit'] = createTown('Summit', 40.7136834, -74.3654981, 14);
return { id: region
, name: 'Great Swamp'
, lat: 40.730072
, lng: -74.4137590
, zoom: 12
, links: links
, towns: towns };
break;
case 'memphis' :
links['discord'] = createLink('MemphisPOGO Chat', 'http://discord.gg/Jt3QjQ3');
links['patreon'] = createLink('Donate Now!', 'http://patreon.com/TeamUnityMemphis');
towns['airport'] = createTown('Airport', 35.0436519, -89.9826890, 16);
towns['carriagecrossing'] = createTown('Carriage Crossing', 35.0234947, -89.7190719, 16);
towns['collierville'] = createTown('Collierville', 35.0464954, -89.6938846, 14);
towns['cordova'] = createTown('Cordova', 35.1598000, -89.7615000, 13);
towns['downtown'] = createTown('Downtown', 35.1406355, -90.0348828, 14);
towns['eastmemphis'] = createTown('East Memphis', 35.1142147, -89.9230447, 13);
towns['germantown'] = createTown('Germantown', 35.0836244, -89.8073619, 13);
towns['graceland'] = createTown('Graceland', 35.0485312, -90.0251922, 15);
towns['oakland'] = createTown('Oakland', 35.2213218, -89.5136372, 13);
towns['oakville'] = createTown('Oakville', 35.0606038, -89.9455369, 13);
towns['olivebranch'] = createTown('Olive Branch', 34.9602579, -89.8285940, 13);
towns['shelbyfarms'] = createTown('Shelby Farms', 35.1311519, -89.8310645, 14);
towns['southaven'] = createTown('Southaven', 34.9939740, -90.0008736, 13);
towns['whitehaven'] = createTown('Whitehaven', 35.0251792, -90.0469772, 13);
return { id: region
, name: 'Memphis'
, lat: 35.099443
, lng: -89.8638777
, zoom: 12
, links: links
, towns: towns };
break;
case 'ramapo' :
links['discord'] = createLink('Team Unity Chat', 'http://discord.gg/GwKB3SG');
links['patreon'] = createLink('Donate Now!', 'http://patreon.com/TeamUnityPogo');
// No individual towns yet for this region
return { id: region
, name: 'Ramapo'
, lat: 41.0818795
, lng: -74.1729253
, zoom: 13
, links: links
, towns: towns };
break;
case 'route22' :
links['discord'] = createLink('Team Unity Chat', 'http://discord.gg/jSr3WK6');
links['patreon'] = createLink('Donate Now!', 'http://patreon.com/TeamUnityPogo');
// No individual towns yet for this region
return { id: region
, name: 'Route 22'
, lat: 40.6594151
, lng: -74.3883392
, zoom: 12
, links: links
, towns: towns };
break;
}
}
function createOptGroup(label, id) {
var optgroup = document.createElement('optgroup');
optgroup.label = label;
optgroup.id = id;
return optgroup;
}
function createOption(text, value, style = null) {
var option = document.createElement('option');
option.innerText = text;
option.value = ( value != null ? value : '' );
if (style != null) {
option.style.cssText = style;
}
return option;
}
function createPokeFarmUrl(regionId = null, hash = null) {
var id = (regionId != null ? regionId : getRegion() );
return getProtocol() + '//'
+ id + '.' + getDomain()
+ ( hash != null ? '/#' + hash : '' );
}
function openInNewTab(url) {
var win = window.open(url, '_blank');
win.focus();
}
function buildRegionMenu(r, t) {
var after = document.getElementById('statsToggle');
var h1 = document.createElement('h1');
var select = document.createElement('select');
var optgroup;
// Make the h1 and select identifiable and give the select an onChange event
h1.id = 'pokeFarmMenu';
select.id = 'pokeFarmMenuSelect';
select.setAttribute('onchange', 'selectUsefulStuff(this.value)');
// Add the top level title
select.appendChild( createOption('Useful Stuff...', null, 'font-style: italic; color: #777;') );
// Creeate the links section
if (Object.keys(r.links).length > 0) {
optgroup = createOptGroup('-- Links --', 'pokeFarmMenuLinks');
for (let x in r.links) {
optgroup.appendChild( createOption(r.links[x].label, r.links[x].url) );
}
select.appendChild(optgroup);
}
// Create the regions section
optgroup = createOptGroup('-- Regions --', 'pokeFarmMenuRegions');
for (let x in regions) {
var option = createOption(regions[x].name, 'region:' + regions[x].id);
if ( (r.id == regions[x].id) && (t == null) ) {
option.selected = true;
}
optgroup.appendChild(option);
}
select.appendChild(optgroup);
// Create the towns section
if (Object.keys(r.towns).length > 0) {
optgroup = createOptGroup('-- Towns --', 'pokeFarmMenuTowns');
for (let x in r.towns) {
var option = createOption(r.towns[x].name, 'town:' + r.towns[x].id);
if ( (t != null) && (t.id == r.towns[x].id) ) {
option.selected = true;
}
optgroup.appendChild(option);
}
select.appendChild(optgroup);
}
// Delete the old one (if it exists)
var oldH1 = document.getElementById('pokeFarmMenu');
if (oldH1 != null) oldH1.remove();
// Finally, add the select to the h1 and the h1 to the document
h1.appendChild(select);
after.parentNode.insertBefore(h1, after);
}
function preparePokeFarm() {
// Get the region and town from the url
var region = getRegion();
var town = getTown();
var coords = getCoords();
/*
console.log('region = ' + region);
console.log('town = ' + town);
console.log('coords = ');
console.log(coords);
*/
// Get the corresponding region and town objects
var r = regions[region];
var t = r.towns[town];
// Update the document title
document.title = r.name + ' Poké Farm' + ( t != null ? ' - ' + t.name : '' );
// Pan and Zoom
if (coords != null) {
map.panTo({lat: coords.lat, lng: coords.lng});
map.setZoom(coords.zoom);
} else if (t == null) {
map.panTo({lat: r.lat, lng: r.lng})
map.setZoom(r.zoom)
} else {
map.panTo({lat: t.lat, lng: t.lng});
map.setZoom(t.zoom);
}
// And build the menu
buildRegionMenu(r, t);
}
function selectRegion(region) {
var r = regions[region];
// If nothing has changed or we could not find the region object, do nothing
if ( (region == null) || (r == null) || (r.id == getRegion()) ) {
return;
}
// Update the window location
window.location.href = createPokeFarmUrl(r.id);
}
function selectTown(town) {
var region = getRegion();
var r = regions[region];
var t = r.towns[town];
// If nothing has changed or we could not find the town object, do nothing
if ( (town == null) || (t == null) || (t.hash == location.hash) ) {
return;
}
// Pan and zoom
map.panTo({lat: t.lat, lng: t.lng});
map.setZoom(t.zoom);
// Update the document title
document.title = r.name + ' Poké Farm - ' + t.name;
// Update the hash
location.hash = t.hash;
}
function selectUsefulStuff(stuff) {
// We cannot select no stuff
if (stuff == '') {
return;
}
// See what stuff we are selecting
var parts = stuff.split(':');
// And select the right stuff
switch (parts[0]) {
case 'region' : selectRegion(parts[1]); break;
case 'town' : selectTown(parts[1]); break;
default : openInNewTab(stuff); break;
}
}
function checkAutoRedirect() {
// Check for redirection of raw map(s) urls
var subdomain = getSubdomain();
if ( (subdomain == 'map') || (subdomain == 'maps') ) {
window.location.href = createPokeFarmUrl('greatswamp', getLocationHashValue());
}
// Check for redirection to the preferred domain (poke.farm vs poké.farm)
var preferredDomain = getDomain();
var currentDomain = getCurrentDomain();
if ( currentDomain != preferredDomain ) {
window.location.href = createPokeFarmUrl(getRegion(), getLocationHashValue());
}
}
function getPokeFarmCoordsHash(lat, lng, zoom) {
var d = 6;
var latRounded = Number(Math.round(lat + 'e' + d) + 'e-' + d);
var lngRounded = Number(Math.round(lng + 'e' + d) + 'e-' + d);
var zoomRounded = Number(Math.round(zoom + 'e0' ) + 'e-0' );
return latRounded + ',' + lngRounded + ',' + zoomRounded + 'z';
}
function handleMapBoundsChanged() {
var region = getRegion();
var town = getTown();
var r = regions[region];
var t = r.towns[town];
var coordsHash = getPokeFarmCoordsHash(map.getCenter().lat(), map.getCenter().lng(), map.getZoom());
var regionCoordsHash;
var townCoordsHash;
if ( (region != null) && (r != null) ) {
regionCoordsHash = getPokeFarmCoordsHash(r.lat, r.lng, r.zoom);
}
if ( (town != null) && (t != null) ) {
townCoordsHash = getPokeFarmCoordsHash(t.lat, t.lng, t.zoom);
}
/*
console.log('region = ' + region);
console.log('town = ' + town);
console.log(r);
console.log(t);
console.log( (coordsHash == regionCoordsHash) + ' :: ' + coordsHash + ' == ' + regionCoordsHash );
console.log( (coordsHash == townCoordsHash) + ' :: ' + coordsHash + ' == ' + townCoordsHash );
*/
if ( (coordsHash != regionCoordsHash) && (coordsHash != townCoordsHash) ) {
location.hash = coordsHash;
}
}
function addMapListeners() {
map.addListener('bounds_changed', handleMapBoundsChanged);
}
var regions = new Array();
regions['boonton'] = createRegion('boonton');
regions['greatswamp'] = createRegion('greatswamp');
regions['memphis'] = createRegion('memphis');
regions['ramapo'] = createRegion('ramapo');
regions['route22'] = createRegion('route22');
$(function () {
'use strict'
/* Settings. */
//const scaleByRarity = true // Disable scaling by rarity and notification. Default: true.
//const upscaledPokemon = [] // Add Pokémon IDs separated by commas (e.g. [1, 2, 3]) to upscale icons.
// Google Analytics property ID. Leave empty to disable.
// Looks like 'UA-XXXXX-Y'.
//const analyticsKey = 'UA-105594492-1'
// MOTD.
//const motdEnabled = false
//const motdTitle = 'MOTD'
//const motd = 'Hi there! This is an easily customizable MOTD with optional title!'
// Only show every unique MOTD message once. If disabled, the MOTD will be
// shown on every visit. Requires support for localStorage.
// Updating only the MOTD title (and not the text) will not make the MOTD
// appear again.
//const motdShowOnlyOnce = true
// What pages should the MOTD be shown on? By default, homepage and mobile
// pages.
//const motdShowOnPages = [
// '/',
// '/mobile'
//]
// Clustering! Different zoom levels for desktop vs mobile.
const disableClusters = false // Default: false
const maxClusterZoomLevel = 13 // Default: 14
const maxClusterZoomLevelMobile = 13 // Default: same as desktop
const clusterZoomOnClick = false // Default: false
const clusterZoomOnClickMobile = false // Default: same as desktop
const clusterGridSize = 60 // Default: 60
const clusterGridSizeMobile = 60 // Default: same as desktop
// Process Pokémon in chunks to improve responsiveness.
//const processPokemonChunkSize = 100 // Default: 100
//const processPokemonIntervalMs = 100 // Default: 100ms
/* Feature detection. */
//const hasStorage = (function () {
// var mod = 'RocketMap'
// try {
// localStorage.setItem(mod, mod)
// localStorage.removeItem(mod)
// return true
// } catch (exception) {
// return false
// }
//}())
/* Do stuff. */
const currentHost = window.location.host
const currentPage = window.location.pathname
// Set custom Store values.
Store.set('maxClusterZoomLevel', maxClusterZoomLevel)
Store.set('clusterZoomOnClick', clusterZoomOnClick)
Store.set('clusterGridSize', clusterGridSize)
//Store.set('processPokemonChunkSize', processPokemonChunkSize)
//Store.set('processPokemonIntervalMs', processPokemonIntervalMs)
//Store.set('scaleByRarity', scaleByRarity)
//Store.set('upscaledPokemon', upscaledPokemon)
if (typeof window.orientation !== "undefined" || isMobileDevice()) {
Store.set('maxClusterZoomLevel', maxClusterZoomLevelMobile)
Store.set('clusterZoomOnClick', clusterZoomOnClickMobile)
Store.set('clusterGridSize', clusterGridSizeMobile)
}
if (disableClusters) {
Store.set('maxClusterZoomLevel', -1)
}
// Google Analytics.
//if (analyticsKey.length > 0) {
// window.ga = window.ga || function () {
// (ga.q = ga.q || []).push(arguments)
// }
// ga.l = Date.now
// ga('create', analyticsKey, 'auto')
// ga('send', 'pageview')
//}
// Show MOTD.
//if (motdEnabled && motdShowOnPages.indexOf(currentPage) !== -1) {
// let motdIsUpdated = true
//
// if (hasStorage) {
// const lastMOTD = window.localStorage.getItem('lastMOTD') || ''
//
// if (lastMOTD === motd) {
// motdIsUpdated = false
// }
// }
//
// if (motdIsUpdated || !motdShowOnlyOnce) {
// window.localStorage.setItem('lastMOTD', motd)
//
// swal({
// title: motdTitle,
// text: motd
// })
// }
//}
checkAutoRedirect(),
preparePokeFarm();
addMapListeners();
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment