pitchfinder.org.uk Open in urlscan Pro
2620:1ec:46::45  Public Scan

URL: https://pitchfinder.org.uk/static-backend/mapping/js/site_selector.js
Submission: On April 25 via manual from GB — Scanned from GB

Form analysis 0 forms found in the DOM

Text Content

/* eslint-disable indent */

;(function(){

var allOptions = [];
var scripts = document.getElementsByTagName('script');
var origin = (document.currentScript || scripts[scripts.length - 1]).src.split('/').slice(0, 3).join('/');

function iframeOnLoad(e){
    e.target.style.display = 'block';
}

function makeKey() {
    var text = '';
    var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    for (var i = 0; i < 10; i++){
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }

    return text;
}

var keysToOptions = {};

function checkPostMessageOrigin(event){
    return event.origin.replace('3000', '8000') != origin.replace('3000', '8000');
}

var meta = document.createElement('meta');
meta.setAttribute('name', 'viewport');
meta.setAttribute('content', 'width=device-width, initial-scale=1, maximum-scale=1,user-scalable=0');

var defaultSuggestSite = 'Select an icon below. Site missing? <a target="_blank" href="https://footballfoundation-self.achieveservice.com/service/PitchFinder">Tell&nbsp;us</a>';

window.siteSelector = function(options){
    options.getQuery = options.getQuery || function(){};
    options.getSiteId = options.getSiteId || function(){};
    options.getLocation = options.getLocation || function(){};

    var lightbox = document.getElementById('pf-site-selector');
    var lightboxContent = document.getElementById('pf-site-selector-content');
    var topBar = document.getElementById('pf-site-selector-top-bar');
    var searchForm = document.getElementById('pf-site-selector-search-form');
    var searchField = document.getElementById('pf-site-selector-search');
    var closeButton = document.getElementById('pf-site-selector-close');
    var iframeWrapper = document.getElementById('pf-site-selector-iframe-wrapper');
    var iframe = document.getElementById('pf-site-selector-iframe');

    // TODO: remove next line and amend code on FT
    options.element.setAttribute('type', 'submit');

    function getIframeUrl(){
        // the key allows us to tell which instance should receive site/location selected events from the iframe
        var key = options.element.getAttribute('site-selector-key');
        if(!key){
            key = makeKey();
            options.element.setAttribute('site-selector-key', key);
        }
        keysToOptions[key] = options;

        var iframeUrl = origin.replace(':8000', ':3000').replace(/\/$/, '') + '/map/?site_selector=true&key=' + key + '&';
        var siteId = options.getSiteId(options.element);
        var query = options.getQuery(options.element) || '';
        var location = options.getLocation(options.element);

        if(siteId){
            iframeUrl = iframeUrl.replace('map/?', siteId +'/?');
        } else if(location && location.latitude && location.longitude){
            iframeUrl += 'lat=' + encodeURIComponent(location.latitude);
            iframeUrl += '&lng=' + encodeURIComponent(location.longitude);
            iframeUrl += '&zoom=16';
        } else if(query){
            iframeUrl += 'query=' + encodeURIComponent(query);
            iframeUrl += '&zoom=14';
        }

        if(options.showAllSites){
            iframeUrl += '&show_all=on';
        }

        if (!options.onLocationSelected) {
            iframeUrl += '&disable_location_select=on';
        }

        // max-device-width can't be used within an iframe, so we set it this way instead
        if (window.matchMedia('(max-device-width: 600px)').matches) {
            iframeUrl += '&zoomed=on';
        }

        return iframeUrl;
    }

    function getHTMLFromIframe(event){
        if (checkPostMessageOrigin(event)){
            return;
        }
        if(event.data.type != 'ui'){
            return;
        }
        if(!document.getElementById('pf-site-selector')){
            var div = document.createElement('div');
            div.style.display = 'none';
            div.innerHTML = event.data.html;
            div.childNodes[0].style.display = 'none';
            document.body.appendChild(div.childNodes[0]);
            var iframeWrapper = document.getElementById('pf-site-selector-iframe-wrapper');
            var iframe = document.getElementById('pf-site-selector-iframe');
            iframeWrapper.appendChild(iframe);
            // Now that we've got the lighbox UI we initialise all site selectors
            // that were called before it was fully loaded.
            for (var i = 0; i < allOptions.length; i++) {
                window.siteSelector(allOptions[i]);
            }
        }
        window.removeEventListener('message', getHTMLFromIframe);
    }

    if(!lightbox){
        // If we don't have the UI loaded yet then we get it via postmessage from the iframe.
        // Then we move the same iframe into the lightbox UI.
        // This is a bit convoluted but since we're relying on postMessage anyway
        // it's less error prone to get the html for the UI via postMessage too,
        // instead of making cross origin ajax/jsonp/accessing the iframe contents directly.
        // Because we have a lightbox we need some UI outside the iframe to start with
        // but we rather add the whole search bar outside the iframe too,
        // so that everything (apart from the map) can be styled by the parent page.
        window.addEventListener('message', getHTMLFromIframe, false);

        if(!document.getElementById('pf-site-selector-iframe')){
            iframe = document.createElement('iframe');
            iframe.setAttribute('id', 'pf-site-selector-iframe');
            iframe.setAttribute('width', '100%');
            iframe.setAttribute('scrolling', 'no');
            iframe.style.display = 'none';
            document.body.appendChild(iframe);
            var iframeUrl = getIframeUrl();
            iframe.src = 'about:blank';
            iframe.src = iframeUrl;
        }

        // capture clicking on a button to open lightbox, and trigger once UI is loaded
        options.element.addEventListener('click', function(e){
            options.element.setAttribute('clicked', 'clicked');
            e.preventDefault();
            e.stopPropagation();
        });

        // collect all the options from each invocation to be called later
        allOptions.push(options);

        // siteSelector(options) will be triggered once again after the iframe is loaded
        return;
    }else{
        // open lightbox if the button was clicked before everything had been loaded
        if(options.element.getAttribute('clicked')){
            options.element.removeAttribute('clicked');
            options.element.click();
        }

        // we're reusing the same iframe for all instances,
        // so this way we avoid having multiple listeners
        iframe.removeEventListener('load', iframeOnLoad);
        iframe.addEventListener('load', iframeOnLoad);
    }

    // handle lightbox open/close
    var origHeight = lightboxContent.style.height;
    var origOverflow = document.body.style.overflow;
    function openLightbox(){
        // disable zoom by adding a meta tag
        document.head.appendChild(meta);
        // disable scrolling
        document.body.style.overflow = 'hidden';
        // set search field value
        var query = options.getQuery(options.element) || '';
        searchField.value = query;
        // set iframe url
        var iframeUrl = getIframeUrl();
        iframe.style.display = 'none';
        iframe.src = iframeUrl;
        // show/resize lightbox
        lightbox.style.display = 'block';
        var topbarheight = (getComputedStyle(topBar).zoom || 1) * topBar.getBoundingClientRect().height;
        var paddingTop = parseFloat(getComputedStyle(lightboxContent).marginTop);
        var iframeHeight = window.innerHeight - topbarheight - 3 * paddingTop;
        iframeWrapper.style.height = iframeHeight + 10 + 'px';
        iframe.style.height = (iframeHeight - 1) + 'px';
        // change the height again to ensure map tiles load
        setTimeout(function(){
            iframe.style.height = iframeHeight + 'px';
        }, 500);

        // set suggest site html:
        document.getElementById('pf-site-selector-suggest-site').innerHTML = options.suggestSite || defaultSuggestSite;
    }
    function closeLightbox(){
        try{
            document.head.removeChild(meta);
        }catch(_){}
        lightbox.style.display = 'none';
        iframe.style.display = 'none';
        iframe.src = 'about:blank';
        lightboxContent.style.height = origHeight;
        document.body.style.overflow = origOverflow;
    }

    // bind open lightbox listener
    options.element.addEventListener('click', function(e){
        openLightbox();
        e.preventDefault();
        e.stopPropagation();
    });

    if (!lightbox.getAttribute('initialised')) {
        // handle close lightbox (need to add these listeners only once, unlike for options.element)
        closeButton.addEventListener('click', closeLightbox);
        lightbox.addEventListener('click', function(e){
            if(e.target == lightbox){
                closeLightbox();
            }
        });

        // add handler to trigger search within the iframe
        searchForm.addEventListener('submit', function(e){
            e.preventDefault();
            e.stopPropagation();
            iframe.contentWindow.postMessage({
                'type': 'search',
                'value': searchField.value
            }, origin);
        });

        // mark lightbox as initialised to prevent binding event handlers again
        lightbox.setAttribute('initialised', 'initialised');
    }

    // handle site selection events from the iframe
    window.addEventListener('message', function (event){
        if (checkPostMessageOrigin(event)){
            return;
        }
        if (event.data.type == 'site_selected'){
            closeLightbox();
        }
        if (event.data.type == 'location_selected'){
            closeLightbox();
        }
    }, false);
};


// handle site/location selection events from the iframe
window.addEventListener('message', function (event){
    if (checkPostMessageOrigin(event)){
        return;
    }
    var options = keysToOptions[event.data.key];
    if (event.data.type == 'site_selected'){
        options.onSiteSelected(options.element, event.data.data);
    }
    if (event.data.type == 'location_selected'){
        options.onLocationSelected(options.element, event.data.data);
    }
}, false);

})();