{% extends "base.html" %}
{% load static %}
{% load removeSpace_filter %}

{% block title %} REIndicator {% endblock %}

{% block head_block %}
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <link rel="shortcut icon" href="/media/icons/favicon.ico" />
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" />
    <!-- <script src="/static/js/jquery.dd.min.js" type="text/javascript"></script> -->
    <script src="{% static 'js/jquery.dd.min.js' %}" type="text/javascript"></script>
    <script src="https://unpkg.com/interact.js@1.2.8/dist/interact.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key={{ googleMapApiKey }}&libraries=&v=weekly&callback=main" defer></script>
    <link href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" rel="stylesheet">
    <link href="/static/plugins/select2-4.0.13/css/select2.min.css" rel="stylesheet" />
    <script src="/static/plugins/select2-4.0.13/js/select2.full.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/static/css/dd.css" />
    <link rel="stylesheet" type="text/css" href="/static/css/styles.css?v=3.6.4" />

    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <link rel="stylesheet" href="/static/css/jquery.toast.css">
    <script src="/static/js/jquery.toast.js"></script>
    <script src="/static/js/js.cookie.min.js"></script>

    <!-- Include Leaflet -->
    <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
    
    <!-- Include CARTO.js -->
    <script src="https://libs.cartocdn.com/carto.js/v4.2.0/carto.min.js"></script>

    <script src="https://unpkg.com/leaflet.gridlayer.googlemutant@0.10.0/Leaflet.GoogleMutant.js"></script>
    <link rel="stylesheet" href="/static/css/leaflet-pegman/leaflet-pegman.css" />
    <script src="/static/js/leaflet-pegman/leaflet-pegman.js"></script>

    <link rel="stylesheet" type="text/css" href="/static/css/w3_custom.css" />
    <link rel="stylesheet" type="text/css" href="/static/css/webmap.css?v=3.6.1" />
    <link rel="stylesheet" type="text/css" href="/static/css/header.css?v=3.6.1" />
    <link rel="stylesheet" type="text/css" href="/static/css/toogle-button.css?v=3.4" />
    <script type='text/javascript' src="/static/js/custom.js?v=3.6.4" ></script>

    <link rel="stylesheet" type="text/css" href="/static/css/audioplayer.css" />
    <script type='text/javascript' src="/static/js/audioplayer.js" ></script>
    <style>
        #map {
            z-index:0;
        }

        .leaflet-bottom .leaflet-control-scale {
            margin-bottom: 12px;
            margin-left: 15px;
        }
    </style>
    {% if deleted %}
    <script class="del_Dialog_script">
        $(function () {
            $( "#dialog" ).dialog();
            $("#Closer").click(function() {
                $("#dialog").dialog('close');
            });
        });
    </script>
    {% endif %}
{% endblock %}

{% block dropdown %}
    <div id='selector_menu'>
        {% if user.is_authenticated and userLevel != 'Hiatus' %}
        <div class = "overlayselector_div_class">
            <div id="overlayer_spinner" style="position: absolute;
                z-index: 1;
                width: 100%;
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: center;">
                <img src='/media/images/spinner.svg' style='height: 40px;'>
            </div>
            {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' %}
            <select id="overlayselector">
                <optgroup label="▲ MicroNeighborhoods™">
                    {% if user.is_superuser or userLevel == 'Both_Anticipator' %}
                    <option value="MicroNeighborhoods">• MicroNeighborhoods Multi Family</option>
                    <option value="MicroNeighborhoodsSingleFamily">• MicroNeighborhoods Single Family</option>
                    <option value="DCTestNew">• DC Test New</option>
                    {% elif userLevel == 'Multi_Anticipator' %}
                    <option value="MicroNeighborhoods">• MicroNeighborhoods Multi Family</option>
                    {% elif userLevel == 'Single_Anticipator' %}
                    <option value="MicroNeighborhoodsSingleFamily">• MicroNeighborhoods Single Family</option>
                    {% endif %}
                </optgroup>
                <optgroup label="▲ Emerging Markets">
                    <option value="EmergingMarkets2023Q2">• Emerging Markets 2023 Q2</option>
                    <option value="EmergingMarkets2023Q1">• Emerging Markets 2023 Q1</option>
                    <option value="EmergingMarkets2022Q4">• Emerging Markets 2022 Q4</option>
                    <option value="EmergingMarkets2022Q3">• Emerging Markets 2022 Q3</option>
                    <option value="EmergingMarkets2022Q2">• Emerging Markets 2022 Q2</option>
                    <option value="EmergingMarkets2022Q1">• Emerging Markets 2022 Q1</option>
                    <option value="EmergingMarkets2022">• Emerging Markets 2022</option>
                    <option value="EmergingMarkets2021">• Emerging Markets 2021</option>
                    <option value="EmergingMarkets2020">• Emerging Markets 2020</option>
                    <option value="EmergingMarkets2019">• Emerging Markets 2019</option>
                    <option value="EmergingMarkets2018">• Emerging Markets 2018</option>
                    <option value="EmergingMarkets2017">• Emerging Markets 2017</option>
                    <option value="EmergingMarkets2016">• Emerging Markets 2016</option>
                    <option value="EmergingMarkets2015">• Emerging Markets 2015</option>
                    <option value="EmergingMarkets2014">• Emerging Markets 2014</option>
                    <option value="EmergingMarkets2013">• Emerging Markets 2013</option>
                    <option value="EmergingMarkets2012">• Emerging Markets 2012</option>
                    <option value="EmergingMarkets2011">• Emerging Markets 2011</option>
                    <option value="EmergingMarkets2010">• Emerging Markets 2010</option>
                    <option value="EmergingMarkets2009">• Emerging Markets 2009</option>
                    <option value="EmergingMarkets2008">• Emerging Markets 2008</option>
                    <option value="EmergingMarkets2007">• Emerging Markets 2007</option>
                    <option value="EmergingMarkets2006">• Emerging Markets 2006</option>
                    <option value="EmergingMarkets2005">• Emerging Markets 2005</option>
                    <option value="EmergingMarkets2004">• Emerging Markets 2004</option>
                    <option value="EmergingMarkets2003">• Emerging Markets 2003</option>
                    <option value="EmergingMarkets2002">• Emerging Markets 2002</option>
                    <option value="EmergingMarkets2001">• Emerging Markets 2001</option>
                    <option value="EmergingMarkets2000">• Emerging Markets 2000</option>
                    <option value="EmergingMarkets1999">• Emerging Markets 1999</option>
                    <option value="EmergingMarkets1998">• Emerging Markets 1998</option>
                    <option value="EmergingMarkets1997">• Emerging Markets 1997</option>
                    <option value="EmergingMarkets1996">• Emerging Markets 1996</option>
                    <option value="EmergingMarkets1995">• Emerging Markets 1995</option>
                    <option value="EmergingMarkets1994">• Emerging Markets 1994</option>
                    <option value="EmergingMarkets1993">• Emerging Markets 1993</option>
                </optgroup>
                <option value="MarketGrowthGroups20122022">Market Growth Groups 2012-2022</option>
                <option value="StrongRecessionRecoveryMarkets">Strong Recession Recovery Markets</option>
                <option value="FedBeigeBookDistricts">Fed Beige Book Districts</option>
                <option value="Exit" disabled>Market Trend Groups (Coming Soon)</option>
            </select>
            {% elif userLevel == 'MDM1' %}
            <select id="overlayselector">
                <optgroup label="▲ MicroNeighborhoods™">
                    <option value="MicroNeighborhoods">• MicroNeighborhoods Multi Family</option>
                </optgroup>
                <optgroup label="▲ Emerging Markets">
                    <option value="EmergingMarkets2014">• Emerging Markets 2014</option>
                    <option value="EmergingMarkets2013">• Emerging Markets 2013</option>
                    <option value="EmergingMarkets2012">• Emerging Markets 2012</option>
                    <option value="EmergingMarkets2011">• Emerging Markets 2011</option>
                    <option value="EmergingMarkets2010">• Emerging Markets 2010</option>
                    <option value="EmergingMarkets2009">• Emerging Markets 2009</option>
                    <option value="EmergingMarkets2008">• Emerging Markets 2008</option>
                    <option value="EmergingMarkets2007">• Emerging Markets 2007</option>
                    <option value="EmergingMarkets2006">• Emerging Markets 2006</option>
                    <option value="EmergingMarkets2005">• Emerging Markets 2005</option>
                    <option value="EmergingMarkets2004">• Emerging Markets 2004</option>
                    <option value="EmergingMarkets2003">• Emerging Markets 2003</option>
                    <option value="EmergingMarkets2002">• Emerging Markets 2002</option>
                    <option value="EmergingMarkets2001">• Emerging Markets 2001</option>
                    <option value="EmergingMarkets2000">• Emerging Markets 2000</option>
                    <option value="EmergingMarkets1999">• Emerging Markets 1999</option>
                    <option value="EmergingMarkets1998">• Emerging Markets 1998</option>
                    <option value="EmergingMarkets1997">• Emerging Markets 1997</option>
                    <option value="EmergingMarkets1996">• Emerging Markets 1996</option>
                    <option value="EmergingMarkets1995">• Emerging Markets 1995</option>
                    <option value="EmergingMarkets1994">• Emerging Markets 1994</option>
                    <option value="EmergingMarkets1993">• Emerging Markets 1993</option>
                </optgroup>
                <option value="MarketGrowthGroups20122022">Market Growth Groups 2012-2022</option>
                <option value="StrongRecessionRecoveryMarkets">Strong Recession Recovery Markets</option>
                <option value="FedBeigeBookDistricts">Fed Beige Book Districts</option>
                <option value="Exit" disabled>Market Trend Groups (Coming Soon)</option>
            </select>
            {% else %}
            <select id='overlayselector'>
                {% if userLevel == 'Both_Analyzer' or userLevel == 'Both_Snapshots' %}
                <option value="MicroNeighborhoods"> MicroNeighborhoods Multi Family</option>
                <option value="MicroNeighborhoodsSingleFamily"> MicroNeighborhoods Single Family</option>
                {% elif userLevel == 'Multi_Analyzer' or userLevel == 'Multi_Snapshots' %}
                <option value='MicroNeighborhoods'> MicroNeighborhoods Multi Family</option>
                {% elif userLevel == 'Single_Analyzer' or userLevel == 'Single_Snapshots' %}
                <option value="MicroNeighborhoodsSingleFamily"> MicroNeighborhoods Single Family</option>
                {% endif %}
                <option value='{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}'> Emerging Markets 2023 Q2</option>
                {% if userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer' %}
                <option value="MarketGrowthGroups20122022">Market Growth Groups 2012-2022</option>
                <option value="StrongRecessionRecoveryMarkets">Strong Recession Recovery Markets</option>
                {% endif %}
                <option value="FedBeigeBookDistricts">Fed Beige Book Districts</option>
            </select>
            {% endif %}
        </div>
        {% endif %}
        <div class = "selector_div_class">
            <input type="checkbox" class="toggle-switch switch-gender" id="base_selector" checked='true'/>
            {% if user.is_authenticated and userLevel != 'Hiatus' %}
            <input type="checkbox" class="toggle-switch switch-data-show" id="data_show_selector" checked='true'/>
            {% endif %}
        </div>
        {% if user.is_authenticated and userLevel != 'Hiatus' %}
        <div class = "msa_selector_div_class">
            <select id='msaTypeSelector' style='display:none;'>
                <option value="entire">Entire MSAs</option>
                <option value="division">MSAs with Divisions</option>
                <option value="submarket">Only Submarkets</option>
            </select>
        </div>
        {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' or userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer' or userLevel == 'MDM1' %}
        <div class = "msa_selector_div_class">
            <select id='fedBeigeBookDateSelector' style='display:none;'>
                <option value="20240117">January 17, 2024</option>
                <option value="20231129">November 29, 2023</option>
                <option value="20231018">October 18, 2023</option>
                <option value="20230906">September 6, 2023</option>
                <option value="20230712">July 12, 2023</option>
                <option value="20230531">May 31, 2023</option>
                <option value="20230419">April 19, 2023</option>
                <option value="20230308">March 8, 2023</option>
                <option value="20230118">January 18, 2023</option>
                <option value="20221130">November 30, 2022</option>
                <option value="20221019">October 19, 2022</option>
                <option value="20220907">September 7, 2022</option>
                <option value="20220713">July 13, 2022</option>
                <option value="20220601">June 1, 2022</option>
                <option value="20220420">April 20, 2022</option>
                <option value="20220302">March 2, 2022</option>
                <option value="20220112">January 12, 2022</option>
                <option value="20211201">December 1, 2021</option>
                <option value="20211020">October 20, 2021</option>
                <option value="20210908">September 8, 2021</option>
                <option value="20210714">July 14, 2021</option>
                <option value="20210602">June 2, 2021</option>
            </select>
        </div>
        {% endif %}
        {% endif %}
    </div>
    <a id='us_button' title='Reset Zoom'><img src="/media/images/US_Outline_Btn.png" class="us_button_image" /></a>
    {% if user.is_authenticated and userLevel == 'Hiatus' %}
    <div id="HiatusModal" class="w3-modal w3-animate-opacity" style="padding-top:0px!important;">
        <div class="w3-modal-content w3-card-4" style="margin: auto;">
            <header class="w3-container w3-deep-orange">
                <span onclick="document.getElementById('HiatusModal').style.display='none'" class="w3-button w3-display-topright">&times;</span>
                <h2 class="print_model_title">Your account is inactive.</h2>
            </header>
            <div class="w3-container" style="overflow: auto;max-height: calc( 100vh - 220px );">
                <p>Your account appears to be inactive.</p><p>Please call Tech Support (617) 963-0918, or email <a href="mailto:support@reindicator.com">support@reindicator.com</a>.</p>
            </div>
            <footer class="w3-container w3-deep-orange">
                <p>
                    <a class="w3-button w3-black" onclick="document.getElementById('HiatusModal').style.display='none'">Close</a>
                </p>
            </footer>
        </div>
    </div>
    {% endif %}
    {% if user.is_authenticated and userLevel != 'Hiatus' %}
    <a id='market_print_button' title='Print market data' onclick="document.getElementById('emergingMarketPrintModal').style.display='flex';$('.printingNotify').html('Select Categories to Print...')" style='display:none;'><img src="/media/images/print_market.png" class="market_print_button_image" /></a>
    <div id="emergingMarketPrintModal" class="w3-modal w3-animate-opacity" style="padding-top:0px!important;">
        <div class="w3-modal-content w3-card-4" style="margin: auto; max-width: 800px; width: 100%;">
            <header class="w3-container w3-teal"> 
                <span onclick="document.getElementById('emergingMarketPrintModal').style.display='none'" class="w3-button w3-large w3-display-topright">&times;</span>
                <span class='printingNotify'>Select Categories to Print</span>
                <h2 class="print_model_title">Print market data</h2>
            </header>
            <div class="w3-container">
                {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' or userLevel == 'MDM1' %}
                <p>
                    <span>Select year to Print - </span>
                    <select class='print_year' style='border: 1px solid #ccc; padding: 7px 3px;'>
                        <option value="2022_q4">2022 Q4</option>
                        <option value="2022_q3">2022 Q3</option>
                        <option value="2022_q2">2022 Q2</option>
                        <option value="2022_q1">2022 Q1</option>
                        <option value="2022">2022</option>
                        <option value="2021">2021</option>
                        <option value="2020">2020</option>
                        <option value="2019">2019</option>
                        <option value="2018">2018</option>
                        <option value="2017">2017</option>
                        <option value="2016">2016</option>
                        <option value="2015">2015</option>
                        <option value="2014">2014</option>
                        <option value="2013">2013</option>
                        <option value="2012">2012</option>
                        <option value="2011">2011</option>
                        <option value="2010">2010</option>
                        <option value="2009">2009</option>
                        <option value="2008">2008</option>
                        <option value="2007">2007</option>
                        <option value="2006">2006</option>
                        <option value="2005">2005</option>
                        <option value="2004">2004</option>
                        <option value="2003">2003</option>
                        <option value="2002">2002</option>
                        <option value="2001">2001</option>
                        <option value="2000">2000</option>
                        <option value="1999">1999</option>
                        <option value="1998">1998</option>
                        <option value="1997">1997</option>
                        <option value="1996">1996</option>
                        <option value="1995">1995</option>
                        <option value="1994">1994</option>
                        <option value="1993">1993</option>
                    </select>
                </p>
                <div class='printCheckbox'><input type="checkbox" class='w3-check market1' checked/><p>New Emerging Markets (Only 2 Years)</p></div>
                {% else %}
                <div class='printCheckbox'><input type="checkbox" class='w3-check market1' checked/><p>New Emerging Markets in 2022 (Only 2 Years)</p></div>
                {% endif %}
                <div class='printCheckbox'><input type="checkbox" class='w3-check market2' checked/><p>Continuing Emerging Markets (3+ Years)</p></div>
                <div class='printCheckbox'><input type="checkbox" class='w3-check market3' checked/><p>Not Emerging</p></div>
                <div class='printCheckbox'><input type="checkbox" class='w3-check market4' checked/><p>Insufficient Data</p></div>
            </div>
            <footer class="w3-container w3-teal">
                <p>
                    Order By: 
                    <select class='orderby-select'>
                        <option value="name_asc">Name A -> Z</option>
                        <option value="name_desc">Name Z -> A</option>
                        <option value="population_asc">Population ASC</option>
                        <option value="population_desc">Population DESC</option>
                        <option value="sizecategory_asc">Size category A -> Z</option>
                        <option value="sizecategory_desc">Size category Z -> A</option>
                    </select>
                    <a type="submit" class="w3-button w3-black" onclick="printMarketData();">Print Market Data</a>
                </p>
            </footer>
        </div>
    </div>
    <a id='marketGrowthGroups_print_button' title='Print market growth group data' onclick="document.getElementById('marketGrowthGroupsPrintModal').style.display='flex';$('.printingNotify').html('Select Categories to Print...')" style='display:none;'><img src="/media/images/print_market.png" class="market_print_button_image" /></a>
    <div id="marketGrowthGroupsPrintModal" class="w3-modal w3-animate-opacity" style="padding-top:0px!important;">
        <div class="w3-modal-content w3-card-4" style="margin: auto; max-width: 800px; width: 100%;">
            <header class="w3-container w3-teal"> 
                <span onclick="document.getElementById('marketGrowthGroupsPrintModal').style.display='none'" class="w3-button w3-large w3-display-topright">&times;</span>
                <span class='printingNotify'>Select Categories to Print</span>
                <h2 class="print_model_title">Print market data</h2>
            </header>
            <div class="w3-container" style="margin: 10px 0;">
                <div class='printCheckbox'><input type="checkbox" class='w3-check marketGrowthGroup1' checked/><p>Superstars</p></div>
                <div class='printCheckbox'><input type="checkbox" class='w3-check marketGrowthGroup2' checked/><p>Stars</p></div>
                <div class='printCheckbox'><input type="checkbox" class='w3-check marketGrowthGroup3' checked/><p>Moderates</p></div>
                <div class='printCheckbox'><input type="checkbox" class='w3-check marketGrowthGroup4' checked/><p>Laggards</p></div>
                <div class='printCheckbox'><input type="checkbox" class='w3-check marketGrowthGroup5' checked/><p>Decliners</p></div>
            </div>
            <footer class="w3-container w3-teal">
                <p>
                    Order By: 
                    <select class='orderby-select'>
                        <option value="name_asc">Name A -> Z</option>
                        <option value="name_desc">Name Z -> A</option>
                    </select>
                    <a type="submit" class="w3-button w3-black" onclick="printMarketGrowthGroupData();">Print Market Growth Group Data</a>
                </p>
            </footer>
        </div>
    </div>
    
    <div id="exitMarketModal" class="w3-modal w3-animate-opacity" style="padding-top:0px!important;">
        <div class="w3-modal-content w3-card-4" style="margin: auto; max-width: 1000px; width: 100%;">
            <header class="w3-container w3-teal"> 
                <span onclick="document.getElementById('exitMarketModal').style.display='none'" 
                class="w3-button w3-large w3-display-topright">&times;</span>
                <h2 class="print_model_title">Exit Markets</h2>
            </header>
            <div class="w3-container" style="overflow: auto;max-height: calc( 100vh - 220px );">
                <p>An “Exit” market is a market that is showing signs of a significant slowdown in growth.</p>
                <p>Due to the COVID-19 pandemic, the US economy is currently in a recovery phase.  Every market recorded substantial jobs losses in April of 2020. Markets are recovering at different rates.</p>
                <p>Thus far, markets have not yet demonstrated a pattern of a slow-down that indicates that an “Exit” may be more favorable.</p>
                <p>Most Metropolitan Statistical Areas (MSAs) and New England City and Town Areas (NECTAs)—the geographies REIndicator™ uses as ‘markets’—have not yet reached their pre-pandemic employment levels.  Only a few are above pre-pandemic levels, and they continue to show signs of growth.</p>
                <p>We are taking this time to refresh our Exit Market model and algorithms. Current trends suggest that we may have sufficient data to provide Exit Market data sometime in 2022.  We reevaluate every month—so check back often.</p>
                <p>Our goal is to keep you ahead of the curve as much as we can.</p>
                <p>Join us for our Members-only FREE Webinars during which we discuss the latest in economic developments that affect multifamily acquisitions.  Click the red button in the upper left portion of your REIndicator menu bar to register and join us for the next Webinar.</p>
                <p>If you have any questions, please call us at 617-963-0918.</p>
            </div>
            <footer class="w3-container w3-teal">
                <p>
                    <a class="w3-button w3-black" onclick="document.getElementById('exitMarketModal').style.display='none'">Close</a>
                </p>
            </footer>
        </div>
    </div>
    <div id="legalDisclaimerModal" class="w3-modal w3-animate-opacity" style="padding-top:0px!important;">
        <div class="w3-modal-content w3-card-4" style="margin: auto; max-width: 1000px; width: 100%;">
            <header class="w3-container w3-deep-orange">
                <h2 class="print_model_title">Legal Disclaimer</h2>
            </header>
            <div class="w3-container" style="overflow: auto;max-height: calc( 100vh - 220px );">

                <p>By using this website, you acknowledge and accept the following:</p>

                <p>The data, content, and projections in this program are informational in nature and do not take into account suitability of any particular investment for any individual. This information is not a substitute for the advice of a financial advisor, real estate professional, appraiser, lawyer, accountant, or any other professional.</p>
                
                <p>REIndicator.com does not recommend or promote any particular purchase or investment. The user assumes full responsibility to independently conduct due diligence and make independent investment decisions.</p>
                
                <p>We use a proprietary process to gather, analyze and classify each market. Among the many factors considered are population, job, wage growth, unemployment, and multi-family occupancy and rent changes. We rely on third-party data, including government data, to provide this service. We endeavor to update the data once per year but make no warranty or representation that the data on which we rely is accurate or that our data is current at any given time.</p>
                
                <p>All investments have risk and the level of risk depends on multiple factors that REIndicator.com cannot control. The user assumes all risks of his or her investments.</p>
                
                <p>The user releases REIndicator.com and its agents from liability for any claims arising out of the purchasing and investment decisions made by user even if user bases those decisions on the data provided in this program.</p>

            </div>
            <footer class="w3-container w3-deep-orange">
                <p>
                    <span><input type="checkbox" class="w3-check" id="disclaimer_agree_check" name="disclaimer_agree_check" value="disclaimer_agree_check">
                    <label for="disclaimer_agree_check" style='font-size: 1em;'> I have read and agree to the terms of this Agreement.  A copy of this Agreement is in my User Settings.</label></span>
                    <a class="isDisabledLink w3-button w3-black disclaimerAgreeButton" title="Agree">Agree</a>
                    <a class="w3-button w3-black" href="{% url 'admin:logout' %}" title="Log Out">Log Out</a>
                </p>
            </footer>
        </div>
    </div>
    <div id='zipcode_show_div'><input class="w3-check" type="checkbox" id='zipcode_show_checkbox'><label class='checkbox_label'>ZIP Codes</label></div>
    <div id='recovered_markets_show_div'><input class="w3-check" type="checkbox" id='recovered_markets_show_checkbox'><label class='checkbox_label'>Recovered Markets</label></div>
    <div id='county_show_div'><input class="w3-check" type="checkbox" id='county_show_checkbox'><label class='checkbox_label'>Counties</label></div>
    <div id='city_show_div'><input class="w3-check" type="checkbox" id='city_show_checkbox'><label class='checkbox_label'>City Boundaries</label></div>
    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' or userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer' or userLevel == 'MDM1' %}
    <div id='opportunity_zone_show_div'><input class="w3-check" type="checkbox" id='opportunity_zone_show_checkbox'><label class='checkbox_label'>IRS Opportunity Zones</label></div>
    {% endif %}
    <div id='national_summary_div'><a title='National Summary' id='national_summary_button' href='/media/FedBeigeBook/20231129/National.pdf' target='_blank'><img src="/media/images/open-book.png"/></a></div>
    <div id='beigies_award_div'><a title='Beigies Award' onclick="clickBeigeAudioButton()"><img src="/media/images/music.png"/></a></div>
    <div id="beigiesAwardModal" class="w3-modal w3-animate-opacity" style="padding-top:0px!important;">
        <div class="w3-modal-content w3-card-4" style="margin: auto; max-width: 800px; width: 100%;">
            <header class="w3-container w3-teal"> 
                <span onclick="closeBeigeModel();" 
                class="w3-button w3-large w3-display-topright">&times;</span>
                <h2 class="print_model_title">Beigies Award</h2>
            </header>
            <div class="w3-container">
                <p class="beigesAudioDescription">Source: The Indicator from Planet Money, NPR, October 18, 2023</p>
                <p>
                    <audio preload="none" controls id="beigesAwardPlayer">
                        <source src="/media/audio/20231129/Beigies_20231129.mp3">
                    </audio>
                </p>
            </div>
            <footer class="w3-container w3-teal">
                <p>
                    <a class="w3-button w3-black" onclick="closeBeigeModel();">Close</a>
                </p>
            </footer>
        </div>
    </div>
    <div id="beigiesAwardNotAvailableModal" class="w3-modal w3-animate-opacity" style="padding-top:0px!important;">
        <div class="w3-modal-content w3-card-4" style="margin: auto; max-width: 800px; width: 100%;">
            <header class="w3-container w3-teal"> 
                <span onclick="document.getElementById('beigiesAwardNotAvailableModal').style.display='none'" 
                class="w3-button w3-large w3-display-topright">&times;</span>
                <h2 class="print_model_title">Beigies Award</h2>
            </header>
            <div class="w3-container">
                <p style="margin: 2em 0;">The Beigies were not Awarded for this month.</p>
            </div>
            <footer class="w3-container w3-teal">
                <p>
                    <a class="w3-button w3-black" onclick="document.getElementById('beigiesAwardNotAvailableModal').style.display='none'">Close</a>
                </p>
            </footer>
        </div>
    </div>
    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' %}
    <div id='timeline_slider_wrap_div' style='display:none;'>
        <input class="w3-check" type="checkbox" id='timeline_slider_show_checkbox'><label class='checkbox_label'>Market Animation</label>
        <div id='timeline_slider_div' style='display:none;'>
            <div style="display:flex;margin: 7px 0 0 4px;">
                <button id="animationBtn" onclick="play()"><i class="fa fa-play" aria-hidden="true"></i></button>
                <input type="range" min="0" max="35" class="slider" id="timeline_slider" value = 0 step=1>
            </div>
        </div>
    </div>
    {% endif %}
    {% if userLevel == 'MDM1' %}
    <div id='timeline_slider_wrap_div' style='display:none;'>
        <input class="w3-check" type="checkbox" id='timeline_slider_show_checkbox'><label class='checkbox_label'>Market Animation</label>
        <div id='timeline_slider_div' style='display:none;'>
            <div style="display:flex;margin: 7px 0 0 4px;">
                <button id="animationBtn" onclick="play()"><i class="fa fa-play" aria-hidden="true"></i></button>
                <input type="range" min="0" max="21" class="slider" id="timeline_slider" value = 0 step=1>
            </div>
        </div>
    </div>
    {% endif %}
    {% endif %}
{% endblock %}

{% block buttonoverlay %}{% endblock %}

{% block content %}
    {% if deleted %}
    <div id="dialog" title="Point Deleted">
        <p>The point {{ deleted }} has been deleted.</p>
        <button id="Closer">Close</button>
    </div>
    {% endif %}
{% endblock %}

{% block map_scripts %}
    <script type='text/javascript' src="/static/js/paneltoggle.js" ></script>
    <!-- load the map -->
    <script class = "map_script">
        var layers = {};
        var styles = {};
        var sources = {};
        {% if user.is_authenticated and userLevel != 'Hiatus' %}
        var cartoApiKey = '{{ cartoApiKey }}';
        const client = new carto.Client({
            apiKey: cartoApiKey,
            username: 'reindicator'
        });
        {% endif %}
        var basemaps;
        basemaps = {};
        var map;
        const legendBox = $(".legend");
        const legend = $(".legend-content");
        var legenddata = {}
        var markers;
        markers = {};
        var markerCircles;
        markerCircles = {};
        var circle_label_group
        circle_label_group = {};
        var markerLabels;
        markerLabels = {};
        var allPoints = {};
        var emailChangeToast;
        var marketPopupData;
        var isColorBlind = "{{ isColorBlind }}" == "True" ? true : false
        var isMarkerLabelShowing = false;
        var isENSymbolShowing = false;
        var isSFENSymbolShowing = false;
        var isEDNSymbolShowing = false;
        var isShowMyCurrentLocation = false;
        var fedDate = '20240117'
        var LayerPopupAction = {};
        var layerList = [];
        {% if userLevel != 'Hiatus' %}
        var layer_css = {
            {% for overlay in overlays %}
            {% if overlay.name == 'MicroNeighborhoods'%}
                {% if userLevel != 'MDM1' %}
                {{ overlay.name |remove_whitespace }}:{
                    normal:`#layer {
                                polygon-fill: ramp([new_score], (#229a00, #ffcc00, #ff660c, #d3d3d3, #3e7bb6, #a9a9a9, #ffffff), ("C", "B", "A", "N", "D", "I"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #ffffff;
                                line-opacity: 1;
                            }`,
                    colorBlindFriendly:`#layer {
                                polygon-fill: ramp([new_score], (#78c679, #ffffb2, #fecc5c, #bdbdbd, #67a9cf, #636363, #ffffff), ("C", "B", "A", "N", "D", "I"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #FFFFFF;
                                line-opacity: 1;
                            }`,
                    EN_symbol:`#layer::labels {
                                text-name: [new_en_marker];
                                text-face-name: 'DejaVu Sans Book';
                                text-size: 22;
                                text-fill: #9a00ff;
                                text-label-position-tolerance: 0;
                                text-halo-radius: 1;
                                text-halo-fill: #6F808D;
                                text-dy: 0;
                                text-allow-overlap: false;
                                text-placement: point;
                                text-placement-type: dummy;
                            }`
                },
                {% else %} // For MDM1
                {{ overlay.name |remove_whitespace }}:{
                    normal:`#layer {
                                polygon-fill: ramp([score], (#229a00, #dcdcdc, #ffffff, #ffcc00, #ff660c, #3e7bb6), ("C", "F", "N", "B", "A", "D"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #ffffff;
                                line-opacity: 1;
                            }`,
                    colorBlindFriendly:`#layer {
                                polygon-fill: ramp([score], (#78c679, #dcdcdc, #ffffff, #ffffb2, #fecc5c, #67a9cf), ("C", "F", "N", "B", "A", "D"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #ffffff;
                                line-opacity: 1;
                            }`,
                    EN_symbol:`#layer::labels {
                                text-name: [new_en_marker];
                                text-face-name: 'DejaVu Sans Book';
                                text-size: 22;
                                text-fill: #9a00ff;
                                text-label-position-tolerance: 0;
                                text-halo-radius: 1;
                                text-halo-fill: #6F808D;
                                text-dy: 0;
                                text-allow-overlap: false;
                                text-placement: point;
                                text-placement-type: dummy;
                            }`
                },
                {% endif %}
            {% elif overlay.name == 'MicroNeighborhoodsSingleFamily'%}
                {{ overlay.name |remove_whitespace }}:{
                    normal:`#layer {
                                polygon-fill: ramp([single_f_score], (#229a00, #3e7bb6, #ff660c, #ffcc00, #d3d3d3, #a9a9a9, #ffffff), ("C", "D", "A", "B", "F", "N", ), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #ffffff;
                                line-opacity: 1;
                            }`,
                    colorBlindFriendly:`#layer {
                                polygon-fill: ramp([single_f_score], (#78c679, #67a9cf, #fecc5c, #ffffb2, #bdbdbd, #636363, #ffffff), ("C", "D", "A", "B", "F", "N", ), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #FFFFFF;
                                line-opacity: 1;
                            }`,
                    EN_symbol:`#layer::labels {
                                text-name: [single_f_en_marker];
                                text-face-name: 'DejaVu Sans Book';
                                text-size: 22;
                                text-fill: #9a00ff;
                                text-label-position-tolerance: 0;
                                text-halo-radius: 1;
                                text-halo-fill: #6F808D;
                                text-dy: 0;
                                text-allow-overlap: false;
                                text-placement: point;
                                text-placement-type: dummy;
                            }`
                },
            {% elif overlay.name == 'DCTestNew'%}
                {{ overlay.name |remove_whitespace }}:{
                    normal:`#layer {
                                polygon-fill: ramp([test_score], (#ff660c, #ff9556, #fed6be, #ffcc00, #fedc51, #ffeca0, #229a00, #62d940, #8ef970, #3e7bb6, #80b0de, #a0cbf3, #d3d3d3, #a9a9a9, #ffffff), ("A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F", "N"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 1;
                                line-color: #FFFFFF;
                                line-opacity: 0.5;
                            }
                            #layer::labels {
                                text-name: [tract];
                                text-face-name: 'DejaVu Sans Book';
                                text-size: 14;
                                text-label-position-tolerance: 0;
                                text-halo-radius: 1;
                                text-halo-fill: #6F808D;
                                text-dy: 0;
                                text-allow-overlap: false;
                                text-placement: point;
                                text-placement-type: dummy;
                                text-fill: #FFFFFF;
                                [emerging_declining = '+'] { text-fill: #9a00ff; }
                                [emerging_declining = '−'] { text-fill: #ff0000; }
                            }`,
                    colorBlindFriendly:`#layer {
                                polygon-fill: ramp([test_score], (#ff660c, #ff9556, #fed6be, #ffcc00, #fedc51, #ffeca0, #229a00, #62d940, #8ef970, #3e7bb6, #80b0de, #a0cbf3, #d3d3d3, #a9a9a9, #ffffff), ("A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F", "N"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 1;
                                line-color: #FFFFFF;
                                line-opacity: 0.5;
                            }
                            #layer::labels {
                                text-name: [tract];
                                text-face-name: 'DejaVu Sans Book';
                                text-size: 14;
                                text-label-position-tolerance: 0;
                                text-halo-radius: 1;
                                text-halo-fill: #6F808D;
                                text-dy: 0;
                                text-allow-overlap: false;
                                text-placement: point;
                                text-placement-type: dummy;
                                text-fill: #FFFFFF;
                                [emerging_declining = '+'] { text-fill: #9a00ff; }
                                [emerging_declining = '−'] { text-fill: #ff0000; }
                            }`,
                    EDN_symbol:`#layer::labels {
                                text-name: [emerging_declining];
                                text-face-name: 'DejaVu Sans Book';
                                text-size: 22;
                                text-label-position-tolerance: 0;
                                text-halo-radius: 1;
                                text-halo-fill: #6F808D;
                                text-dy: 0;
                                text-allow-overlap: false;
                                text-placement: point;
                                text-placement-type: dummy;
                                text-fill: #FFFFFF;
                                [emerging_declining = '+'] { text-fill: #9a00ff; }
                                [emerging_declining = '−'] { text-fill: #ff0000; }
                            }`
                },
            {% elif overlay.name == 'Emerging Markets 2022' %}  // only snapshot and analyzer
                {{ overlay.name |remove_whitespace }}:{
                    normal:`#layer {
                                polygon-fill: ramp([_{{ overlay.name|slice:"-4:" }}_em_code], (#a9a8ac, #397944, #d5ff0c, #ffffff), ("0", "3", "2", "9"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #ffffff;
                                line-opacity: 1;
                            }`,
                    colorBlindFriendly:`#layer {
                                polygon-fill: ramp([_{{ overlay.name|slice:"-4:" }}_em_code], (#dcdcdc, #238B45, #B8E186, #ffffff), ("0", "3", "2", "9"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #ffffff;
                                line-opacity: 1;
                            }`,
                    RM_Symbol:`#layer::labels {
                                text-name: [employment_recovered];
                                text-face-name: 'DejaVu Sans Book';
                                text-size: 30;
                                text-fill: #9a00ff;
                                text-label-position-tolerance: 0;
                                text-halo-radius: 1;
                                text-halo-fill: #6F808D;
                                text-dy: 0;
                                text-allow-overlap: false;
                                text-placement: point;
                                text-placement-type: dummy;
                            }`
                },
            {% elif 'EmergingMarkets2023Q' in overlay.name %}
                {{ overlay.name |remove_whitespace }}:{
                    normal:`#layer {
                                polygon-fill: ramp([_2023_q{{ overlay.name|slice:"-1:" }}_em_code], (#a9a8ac, #397944, #d5ff0c, #ffffff), ("0", "3", "2", "9"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #ffffff;
                                line-opacity: 1;
                            }`,
                    colorBlindFriendly:`#layer {
                                polygon-fill: ramp([_2023_q{{ overlay.name|slice:"-1:" }}_em_code], (#dcdcdc, #238B45, #B8E186, #ffffff), ("0", "3", "2", "9"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #ffffff;
                                line-opacity: 1;
                            }`,
                    RM_Symbol:`#layer::labels {
                                text-name: [employment_recovered];
                                text-face-name: 'DejaVu Sans Book';
                                text-size: 30;
                                text-fill: #9a00ff;
                                text-label-position-tolerance: 0;
                                text-halo-radius: 1;
                                text-halo-fill: #6F808D;
                                text-dy: 0;
                                text-allow-overlap: false;
                                text-placement: point;
                                text-placement-type: dummy;
                            }`
                },
            {% elif 'EmergingMarkets2022Q' in overlay.name %}
                {{ overlay.name |remove_whitespace }}:{
                    normal:`#layer {
                                polygon-fill: ramp([_2022_q{{ overlay.name|slice:"-1:" }}_em_code], (#a9a8ac, #397944, #d5ff0c, #ffffff), ("0", "3", "2", "9"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #ffffff;
                                line-opacity: 1;
                            }`,
                    colorBlindFriendly:`#layer {
                                polygon-fill: ramp([_2022_q{{ overlay.name|slice:"-1:" }}_em_code], (#dcdcdc, #238B45, #B8E186, #ffffff), ("0", "3", "2", "9"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #ffffff;
                                line-opacity: 1;
                            }`,
                    RM_Symbol:`#layer::labels {
                                text-name: [employment_recovered];
                                text-face-name: 'DejaVu Sans Book';
                                text-size: 30;
                                text-fill: #9a00ff;
                                text-label-position-tolerance: 0;
                                text-halo-radius: 1;
                                text-halo-fill: #6F808D;
                                text-dy: 0;
                                text-allow-overlap: false;
                                text-placement: point;
                                text-placement-type: dummy;
                            }`
                },
            {% elif 'Emerging' in overlay.name %}
                {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' or userLevel == 'MDM1' %}
                {{ overlay.name |remove_whitespace }}:{
                    normal:`#layer {
                                polygon-fill: ramp([_{{ overlay.name|slice:"-4:" }}_em_code], (#a9a8ac, #397944, #d5ff0c, #ffffff), ("0", "3", "2", "9"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #ffffff;
                                line-opacity: 1;
                            }`,
                    colorBlindFriendly:`#layer {
                                polygon-fill: ramp([_{{ overlay.name|slice:"-4:" }}_em_code], (#dcdcdc, #238B45, #B8E186, #ffffff), ("0", "3", "2", "9"), "=");
                                polygon-opacity: 0.7;
                            }
                            #layer::outline {
                                line-width: 0.5;
                                line-color: #ffffff;
                                line-opacity: 1;
                            }`
                },
                {% endif %}
            {% endif %}
            {% endfor %}
            {% if userLevel != 'Single_Anticipator' and userLevel != 'Single_Analyzer' and userLevel != 'Single_Snapshots' %}
            MFPPoints30: {
                normal:`#layer {
                            marker-width: 2;
                            marker-fill: #800080;
                            marker-fill-opacity: 0.9;
                            marker-file: url('https://s3.amazonaws.com/com.cartodb.users-assets.production/maki-icons/warehouse-18.svg');
                            marker-allow-overlap: true;
                            marker-line-width: 3.5;
                            marker-line-color: #ffffff;
                            marker-line-opacity: 1;
                            [zoom>5]{
                                marker-width: 5;
                            }
                            [zoom>10]{
                                marker-width: 10;
                            }
                            [zoom>12]{
                                marker-width: 15;
                            }
                            [zoom>14]{
                                marker-width: 20;
                            }
                            [zoom>15]{
                                marker-width: 25;
                            }
                            [zoom>16]{
                                marker-width: 30;
                            }
                            [zoom>17]{
                                marker-width: 35;
                            }
                            [zoom>18]{
                                marker-width: 40;
                            }
                        }`
            },
            {% endif %}
            US_county_boundaries: {
                normal:`#layer {
                            polygon-fill: #ffffff;
                            polygon-opacity: 0;
                        }
                        #layer::outline {
                            line-width: 2;
                            line-color: #0031ff;
                            line-opacity: 0.5;
                        }
                        #layer::labels {
                            text-name: [name];
                            text-face-name: 'DejaVu Sans Book';
                            text-size: 14;
                            text-fill: #0010ff;
                            text-label-position-tolerance: 0;
                            text-halo-radius: 1;
                            text-halo-fill: #6F808D;
                            text-dy: 0;
                            text-allow-overlap: false;
                            text-placement: point;
                            text-placement-type: dummy;
                        }`
            },
            US_zip_boundaries: {
                normal:`#layer {
                            polygon-fill: transparent;
                            polygon-opacity: 0;
                        }
                        #layer::outline {
                            line-width: 1;
                            line-color: #000000;
                            line-opacity: 0.8;
                        }
                        #layer::labels {
                            text-name: [zip];
                            text-face-name: 'DejaVu Sans Book';
                            text-size: 13;
                            text-fill: #FFFFFF;
                            text-label-position-tolerance: 0;
                            text-halo-radius: 1;
                            text-halo-fill: #6F808D;
                            text-dy: 0;
                            text-allow-overlap: false;
                            text-placement: point;
                            text-placement-type: dummy;
                        }`
            },
            US_cities: {
                normal:`#layer {
                            polygon-fill: #00ffdd;
                            polygon-opacity: 0.3;
                        }
                        #layer::outline {
                            line-width: 2;
                            line-color: #8000ff;
                            line-opacity: 0.5;
                        }
                        #layer::labels {
                            text-name: [name];
                            text-face-name: 'DejaVu Sans Book';
                            text-size: 14;
                            text-fill: #000000;
                            text-label-position-tolerance: 0;
                            text-halo-radius: 1;
                            text-halo-fill: #6F808D;
                            text-dy: 0;
                            text-allow-overlap: false;
                            text-placement: point;
                            text-placement-type: dummy;
                        }`
            },
            FedBeigeBookDistricts: {
                normal:`#layer {
                            polygon-fill: ramp([number], (#d75800, #a4930f, #b36666, #ac3939, #28535d, #555639, #aa844c, #465d6b, #005196, #3a2442, #4f6019, #636363), ("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11"), "=");
                            polygon-opacity: 0.7;
                        }
                        #layer::outline {
                            line-width: 0.5;
                            line-color: #FFFFFF;
                            line-opacity: 1;
                        }`
            },
            {% if userLevel != 'Both_Snapshots' and userLevel != 'Multi_Snapshots' and userLevel != 'Single_Snapshots' %}
            StrongRecessionRecoveryMarkets: {
                normal:`#layer {
                            polygon-fill: ramp([strong_recession_recovery_markets], (#bb22e1, #ffffff), ("1", ), "=");
                            polygon-opacity: 0.7;
                        }
                        #layer::outline {
                            line-width: 1;
                            line-color: #FFFFFF;
                            line-opacity: 0.5;
                        }`
            },
            MarketGrowthGroups20122022: {
                normal:`#layer {
                            polygon-fill: ramp([market_growth_group], (#0000ff, #ffa500, #ffff00, #006400, #90ee90), (5, 4, 3, 2, 1), "=");
                            polygon-opacity: 0.7;
                        }
                        #layer::outline {
                            line-width: 1;
                            line-color: #FFFFFF;
                            line-opacity: 0.5;
                        }`
            },
            OpportunityZone: {
                normal:`#layer {
                            polygon-fill: transparent;
                            polygon-opacity: 0;  
                            polygon-pattern-opacity: 0.3;
                            polygon-pattern-file:url('https://t4.ftcdn.net/jpg/01/84/61/35/360_F_184613577_88lnmUrjdQyYMb5LcewZiYKWG61LjFlh.jpg');
                        }
                        #layer::outline {
                            line-width: 5;
                            line-color: #d9138a;
                            line-opacity: 0.5;
                            [zoom<9]{
                            line-width: 3;
                            }
                        }`
            },
            {% endif %}
        }
        {% endif %}
        {% if lat and lon %}
        var center = [{{ lat }}, {{ lon }}];
        var zoom = 13;
        {% else %}
        var center = [38.51, -97.376];
        var zoom = 4;
        {% endif %}
        function main() {
            {% if not is_disclaimer_agreed and not user.is_superuser %}
            $('#legalDisclaimerModal').css('display', 'flex');
            {% endif %}
            map = new L.Map('map', {
                zoomControl: true,
                center: center,
                zoom: zoom,
                legends:true,
                maxZoom: 18
            });
            L.control.scale({ position: 'bottomleft' }).addTo(map);
            // add default basemap
            {% for basemap in basemaps %}
            basemaps["{{ basemap.name }}"] = L.tileLayer('{{ basemap.tileURL }}', {attribution: '{{ basemap.name }}'}
            {% if forloop.counter0 %}
            );
            {% else %}
            ).addTo(map);
            {% endif %}
            {% endfor %}
            {% if user.is_authenticated and userLevel != 'Hiatus' %}
            /*emailChangeToast= $.toast({
                text: `Your current email is <span style='color: #57ff8b;'>{{ user.email }}</span><br>Once you confirm the email, this popup will never appear.<br> 
                        <a class='emailConfirm'>Confirm</a> <a class='changeEmailShow'>Change Email</a><br>
                        <div class='emailChangeInput' style='display: none;'>
                            <input type = 'email' class='emailInputInPopup' value='{{ user.email }}' onkeyup = 'validateEmail(this.value);' />
                            <div class='emailErrorMessage'></div>
                            <a class='emailChangeInPopup'>Change</a>
                        </div>`, // Text that is to be shown in the toast
                heading: '<span style="text-align: center;">Please Confirm Your Email</span>', // Optional heading to be shown on the toast
                icon: 'info', // Type of toast icon
                showHideTransition: 'slide', // fade, slide or plain            
                hideAfter: false, // false to make it sticky or number representing the miliseconds as time after which toast needs to be hidden
                stack: 5, // false if there should be only one toast at a time or a number representing the maximum number of toasts to be shown at a time
                position: 'bottom-center',
                textAlign: 'center',  // Text alignment i.e. left, right or center
                bgColor: '#3c763d',
                textColor: '#dff0d8'
            })*/
            
            var colorBlindNumber = 0;
            var popup;

            {% if userLevel != 'Single_Anticipator' and userLevel != 'Single_Analyzer' and userLevel != 'Single_Snapshots' %}
                // MFPPoints30
                sources['MFPPoints30'] = new carto.source.Dataset('mfp_top_30_markets');
                styles['MFPPoints30'] = new carto.style.CartoCSS(layer_css['MFPPoints30'].normal);
                layers['MFPPoints30'] = new carto.layer.Layer(sources['MFPPoints30'], styles['MFPPoints30'], {
                    featureClickColumns: ['cartodb_id', 'buildingname', 'address', 'city', 'state']
                }).on('featureClicked', featureEvent => {
                    var popup_content = '<div class="widget"><div style="text-align: center;"><strong><span style="font-size: 0.9em;">Name:</span></strong><br>' + featureEvent.data.buildingname + '<br><br><strong><span style="font-size: 0.9em;">Address:</span></strong><br>' + featureEvent.data.address + ', ' + featureEvent.data.city + ', ' + featureEvent.data.state +'</div></div>'

                    popup = L.popup({ closeButton: true });
                    popup.setContent(popup_content);
                    popup.setLatLng(featureEvent.latLng);
                    if (!popup.isOpen()) {
                        popup.openOn(map);
                    }
                });
            {% endif %}

            {% if userLevel != 'Both_Snapshots' and userLevel != 'Multi_Snapshots' and userLevel != 'Single_Snapshots' %}
                // OpportunityZone
                sources['OpportunityZone'] = new carto.source.Dataset('table_8764oz');
                styles['OpportunityZone'] = new carto.style.CartoCSS(layer_css['OpportunityZone'].normal);
                layers['OpportunityZone'] = new carto.layer.Layer(sources['OpportunityZone'], styles['OpportunityZone']);
            {% endif %}

            // US_county_boundaries
            sources['US_county_boundaries'] = new carto.source.Dataset('cb_2020_us_county_500k');
            styles['US_county_boundaries'] = new carto.style.CartoCSS(layer_css['US_county_boundaries'].normal);
            layers['US_county_boundaries'] = new carto.layer.Layer(sources['US_county_boundaries'], styles['US_county_boundaries']);

            // US_zip_boundaries
            sources['US_zip_boundaries'] = new carto.source.Dataset('zip_boundaries_us');
            styles['US_zip_boundaries'] = new carto.style.CartoCSS(layer_css['US_zip_boundaries'].normal);
            layers['US_zip_boundaries'] = new carto.layer.Layer(sources['US_zip_boundaries'], styles['US_zip_boundaries']);

            // US_cities
            sources['US_cities'] = new carto.source.Dataset('cityboundaries');
            styles['US_cities'] = new carto.style.CartoCSS(layer_css['US_cities'].normal);
            layers['US_cities'] = new carto.layer.Layer(sources['US_cities'], styles['US_cities']);

            {% if userLevel != 'MDM1' %}
                {% if userLevel != 'Multi_Anticipator' and userLevel != 'Multi_Analyzer' and userLevel != 'Multi_Snapshots' %}
                // MicroNeighborhoodsSingleFamily
                sources['MicroNeighborhoodsSingleFamily'] = new carto.source.Dataset('microneighborhoods_data_newest');
                    {% if isColorBlind %}
                    styles['MicroNeighborhoodsSingleFamily'] = new carto.style.CartoCSS(layer_css['MicroNeighborhoodsSingleFamily'].colorBlindFriendly);
                    {% else %}
                    styles['MicroNeighborhoodsSingleFamily'] = new carto.style.CartoCSS(layer_css['MicroNeighborhoodsSingleFamily'].normal);
                    {% endif %}
                layers['MicroNeighborhoodsSingleFamily'] = new carto.layer.Layer(sources['MicroNeighborhoodsSingleFamily'], styles['MicroNeighborhoodsSingleFamily']);
                layerList.push(layers['MicroNeighborhoodsSingleFamily']);
                {% endif %}
                {% if userLevel != 'Single_Anticipator' and userLevel != 'Single_Analyzer' and userLevel != 'Single_Snapshots' %}
                // MicroNeighborhoods
                sources['MicroNeighborhoods'] = new carto.source.Dataset('microneighborhoods_data_newest');
                    {% if isColorBlind %}
                    styles['MicroNeighborhoods'] = new carto.style.CartoCSS(layer_css['MicroNeighborhoods'].colorBlindFriendly);
                    {% else %}
                    styles['MicroNeighborhoods'] = new carto.style.CartoCSS(layer_css['MicroNeighborhoods'].normal);
                    {% endif %}
                layers['MicroNeighborhoods'] = new carto.layer.Layer(sources['MicroNeighborhoods'], styles['MicroNeighborhoods']);
                layerList.push(layers['MicroNeighborhoods']);
                {% endif %}
                {% if user.is_superuser or userLevel == 'Both_Anticipator' %}
                // DCTestNew
                sources['DCTestNew'] = new carto.source.Dataset('new_microneighborhoods_data');
                    {% if isColorBlind %}
                    styles['DCTestNew'] = new carto.style.CartoCSS(layer_css['DCTestNew'].colorBlindFriendly);
                    {% else %}
                    styles['DCTestNew'] = new carto.style.CartoCSS(layer_css['DCTestNew'].normal);
                    {% endif %}
                layers['DCTestNew'] = new carto.layer.Layer(sources['DCTestNew'], styles['DCTestNew']);
                layerList.push(layers['DCTestNew']);
                {% endif %}
            {% else %}
                // MicroNeighborhoods(2014)
                sources['MicroNeighborhoods'] = new carto.source.Dataset('microneighborhoods_data_2014');
                    {% if isColorBlind %}
                    styles['MicroNeighborhoods'] = new carto.style.CartoCSS(layer_css['MicroNeighborhoods'].colorBlindFriendly);
                    {% else %}
                    styles['MicroNeighborhoods'] = new carto.style.CartoCSS(layer_css['MicroNeighborhoods'].normal);
                    {% endif %}
                layers['MicroNeighborhoods'] = new carto.layer.Layer(sources['MicroNeighborhoods'], styles['MicroNeighborhoods']);
                layerList.push(layers['MicroNeighborhoods']);
            {% endif %}
            // Emerging Markets
            {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' %}
                {% for overlay in overlays %}
                    {% if 'Emerging' in overlay.name %}
                        sources["{{ overlay.name |remove_whitespace }}"] = new carto.source.SQL('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                            {% if isColorBlind %}
                            styles["{{ overlay.name |remove_whitespace }}"] = new carto.style.CartoCSS(layer_css["{{ overlay.name |remove_whitespace }}"].colorBlindFriendly);
                            {% else %}
                            styles["{{ overlay.name |remove_whitespace }}"] = new carto.style.CartoCSS(layer_css["{{ overlay.name |remove_whitespace }}"].normal);
                            {% endif %}
                        {% if overlay.name == 'Emerging Markets 2022' %}
                        layers["{{ overlay.name |remove_whitespace }}"] = new carto.layer.Layer(
                            sources["{{ overlay.name |remove_whitespace }}"],
                            styles["{{ overlay.name |remove_whitespace }}"],
                            {
                                featureClickColumns: ['cartodb_id', 'msaname', 'msacode', '_2020_population', '_2020_population_rank', '_2019_2020_growth', '_2020_growth_rank', 'market_size_category', '_2022_em_code', 'recession_recovery_june_2021', 'recession_recovery_rank_june_2021', 'volatility_rank']
                            })
                            .on('featureClicked', featureEvent => (LayerPopupAction["{{ overlay.name |remove_whitespace }}"](featureEvent)));
                        {% else %}
                        layers["{{ overlay.name |remove_whitespace }}"] = new carto.layer.Layer(
                            sources["{{ overlay.name |remove_whitespace }}"],
                            styles["{{ overlay.name |remove_whitespace }}"],
                            {
                                featureClickColumns: ['cartodb_id', 'msaname']
                            })
                            .on('featureClicked', featureEvent => (LayerPopupAction["{{ overlay.name |remove_whitespace }}"](featureEvent)));
                        {% endif %}
                        layerList.push(layers["{{ overlay.name |remove_whitespace }}"]);
                    {% endif %}
                    {% if overlay.name == 'Strong Recession Recovery Markets' %}
                        sources["{{ overlay.name |remove_whitespace }}"] = new carto.source.SQL('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                        styles["{{ overlay.name |remove_whitespace }}"] = new carto.style.CartoCSS(layer_css["{{ overlay.name |remove_whitespace }}"].normal);
                        layers["{{ overlay.name |remove_whitespace }}"] = new carto.layer.Layer(
                            sources["{{ overlay.name |remove_whitespace }}"],
                            styles["{{ overlay.name |remove_whitespace }}"],
                            {
                                featureClickColumns: ['cartodb_id', 'msaname', 'msacode', '_2020_population', '_2020_population_rank', '_2019_2020_growth', '_2020_growth_rank', 'market_size_category', '_2022_em_code', 'recession_recovery_june_2021', 'recession_recovery_rank_june_2021', 'volatility_rank']
                            })
                            .on('featureClicked', featureEvent => (LayerPopupAction["{{ overlay.name |remove_whitespace }}"](featureEvent)));
                        layerList.push(layers["{{ overlay.name |remove_whitespace }}"]);
                    {% endif %}
                    {% if overlay.name == 'MarketGrowthGroups20122022' %}
                        sources["{{ overlay.name |remove_whitespace }}"] = new carto.source.SQL('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                        styles["{{ overlay.name |remove_whitespace }}"] = new carto.style.CartoCSS(layer_css["{{ overlay.name |remove_whitespace }}"].normal);
                        layers["{{ overlay.name |remove_whitespace }}"] = new carto.layer.Layer(
                            sources["{{ overlay.name |remove_whitespace }}"],
                            styles["{{ overlay.name |remove_whitespace }}"],
                            {
                                featureClickColumns: ['cartodb_id', 'msaname']
                            })
                            .on('featureClicked', featureEvent => (LayerPopupAction["{{ overlay.name |remove_whitespace }}"](featureEvent)));
                        layerList.push(layers["{{ overlay.name |remove_whitespace }}"]);
                    {% endif %}
                    {% if overlay.name == 'Fed Beige Book Districts' %}
                        sources["{{ overlay.name |remove_whitespace }}"] = new carto.source.Dataset('fed_beige_book_districts');
                        styles["{{ overlay.name |remove_whitespace }}"] = new carto.style.CartoCSS(layer_css["{{ overlay.name |remove_whitespace }}"].normal);
                        layers["{{ overlay.name |remove_whitespace }}"] = new carto.layer.Layer(
                            sources["{{ overlay.name |remove_whitespace }}"],
                            styles["{{ overlay.name |remove_whitespace }}"],
                            {
                                featureClickColumns: ['district_name', 'summary_20211020', 'summary_20210908', 'summary_20210714', 'summary_20210602', 'summary_20211201', 'summary_20220112', 'summary_20220302', 'summary_20220420', 'summary_20220601', 'summary_20220713', 'summary_20220907', 'summary_20221019', 'summary_20221130', 'summary_20230118', 'summary_20230308', 'summary_20230419', 'summary_20230531', 'summary_20230712', 'summary_20230906', 'summary_20231018', 'summary_20231129', 'summary_20240117', 'book_name']
                            })
                            .on('featureClicked', featureEvent => (LayerPopupAction["{{ overlay.name |remove_whitespace }}"](featureEvent)));
                        layerList.push(layers["{{ overlay.name |remove_whitespace }}"]);
                    {% endif %}
                {% endfor %}
            {% elif userLevel == 'MDM1' %}
                {% for overlay in overlays %}
                    {% if overlay.name != 'EmergingMarkets2023Q2' and overlay.name != 'EmergingMarkets2023Q1' and overlay.name != 'EmergingMarkets2022Q4' and overlay.name != 'EmergingMarkets2022Q3' and overlay.name != 'EmergingMarkets2022Q2' and overlay.name != 'EmergingMarkets2022Q1' and overlay.name != 'Emerging Markets 2022' and overlay.name != 'Emerging Markets 2021' and overlay.name != 'Emerging Markets 2020' and overlay.name != 'Emerging Markets 2019' and overlay.name != 'Emerging Markets 2018' and overlay.name != 'Emerging Markets 2017' and overlay.name != 'Emerging Markets 2016' and overlay.name != 'Emerging Markets 2015' and overlay.name != 'MicroNeighborhoodsSingleFamily'%}
                        {% if 'Emerging' in overlay.name %}
                            sources["{{ overlay.name |remove_whitespace }}"] = new carto.source.SQL('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                                {% if isColorBlind %}
                                styles["{{ overlay.name |remove_whitespace }}"] = new carto.style.CartoCSS(layer_css["{{ overlay.name |remove_whitespace }}"].colorBlindFriendly);
                                {% else %}
                                styles["{{ overlay.name |remove_whitespace }}"] = new carto.style.CartoCSS(layer_css["{{ overlay.name |remove_whitespace }}"].normal);
                                {% endif %}
                            {% if overlay.name == 'Emerging Markets 2014' %}
                            layers["{{ overlay.name |remove_whitespace }}"] = new carto.layer.Layer(
                                sources["{{ overlay.name |remove_whitespace }}"],
                                styles["{{ overlay.name |remove_whitespace }}"],
                                {
                                    featureClickColumns: ['cartodb_id', 'msaname', 'msacode', '_2020_population', '_2020_population_rank', '_2019_2020_growth', '_2020_growth_rank', 'market_size_category', '_2014_em_code', 'recession_recovery_june_2021', 'recession_recovery_rank_june_2021', 'volatility_rank']
                                })
                                .on('featureClicked', featureEvent => (LayerPopupAction["{{ overlay.name |remove_whitespace }}"](featureEvent)));
                            {% else %}
                            layers["{{ overlay.name |remove_whitespace }}"] = new carto.layer.Layer(
                                sources["{{ overlay.name |remove_whitespace }}"],
                                styles["{{ overlay.name |remove_whitespace }}"],
                                {
                                    featureClickColumns: ['cartodb_id', 'msaname']
                                })
                                .on('featureClicked', featureEvent => (LayerPopupAction["{{ overlay.name |remove_whitespace }}"](featureEvent)));
                            {% endif %}
                            layerList.push(layers["{{ overlay.name |remove_whitespace }}"]);
                        {% endif %}
                        {% if overlay.name == 'Strong Recession Recovery Markets' %}
                            sources["{{ overlay.name |remove_whitespace }}"] = new carto.source.SQL('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                            styles["{{ overlay.name |remove_whitespace }}"] = new carto.style.CartoCSS(layer_css["{{ overlay.name |remove_whitespace }}"].normal);
                            layers["{{ overlay.name |remove_whitespace }}"] = new carto.layer.Layer(
                                sources["{{ overlay.name |remove_whitespace }}"],
                                styles["{{ overlay.name |remove_whitespace }}"],
                                {
                                    featureClickColumns: ['cartodb_id', 'msaname', 'msacode', '_2020_population', '_2020_population_rank', '_2019_2020_growth', '_2020_growth_rank', 'market_size_category', '_2014_em_code', 'recession_recovery_june_2021', 'recession_recovery_rank_june_2021', 'volatility_rank']
                                })
                                .on('featureClicked', featureEvent => (LayerPopupAction["{{ overlay.name |remove_whitespace }}"](featureEvent)));
                            layerList.push(layers["{{ overlay.name |remove_whitespace }}"]);
                        {% endif %}
                        {% if overlay.name == 'MarketGrowthGroups20122022' %}
                            sources["{{ overlay.name |remove_whitespace }}"] = new carto.source.SQL('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                            styles["{{ overlay.name |remove_whitespace }}"] = new carto.style.CartoCSS(layer_css["{{ overlay.name |remove_whitespace }}"].normal);
                            layers["{{ overlay.name |remove_whitespace }}"] = new carto.layer.Layer(
                                sources["{{ overlay.name |remove_whitespace }}"],
                                styles["{{ overlay.name |remove_whitespace }}"],
                                {
                                    featureClickColumns: ['cartodb_id', 'msaname']
                                })
                                .on('featureClicked', featureEvent => (LayerPopupAction["{{ overlay.name |remove_whitespace }}"](featureEvent)));
                            layerList.push(layers["{{ overlay.name |remove_whitespace }}"]);
                        {% endif %}
                        {% if overlay.name == 'Fed Beige Book Districts' %}
                            sources["{{ overlay.name |remove_whitespace }}"] = new carto.source.Dataset('fed_beige_book_districts');
                            styles["{{ overlay.name |remove_whitespace }}"] = new carto.style.CartoCSS(layer_css["{{ overlay.name |remove_whitespace }}"].normal);
                            layers["{{ overlay.name |remove_whitespace }}"] = new carto.layer.Layer(
                                sources["{{ overlay.name |remove_whitespace }}"],
                                styles["{{ overlay.name |remove_whitespace }}"],
                                {
                                    featureClickColumns: ['district_name', 'summary_20211020', 'summary_20210908', 'summary_20210714', 'summary_20210602', 'summary_20211201', 'summary_20220112', 'summary_20220302', 'summary_20220420', 'summary_20220601', 'summary_20220713', 'summary_20220907', 'summary_20221019', 'summary_20221130', 'summary_20230118', 'summary_20230308', 'summary_20230419', 'summary_20230531', 'summary_20230712', 'summary_20230906', 'summary_20231018', 'summary_20231129', 'summary_20240117', 'book_name']
                                })
                                .on('featureClicked', featureEvent => (LayerPopupAction["{{ overlay.name |remove_whitespace }}"](featureEvent)));
                            layerList.push(layers["{{ overlay.name |remove_whitespace }}"]);
                        {% endif %}
                    {% endif %}
                {% endfor %}
            {% else %} // Analyzer and Snapshots
                sources['{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}'] = new carto.source.SQL('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                    {% if isColorBlind %}
                    styles['{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}'] = new carto.style.CartoCSS(layer_css['{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}'].colorBlindFriendly);
                    {% else %}
                    styles['{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}'] = new carto.style.CartoCSS(layer_css['{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}'].normal);
                    {% endif %}
                layers['{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}'] = new carto.layer.Layer(
                    sources['{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}'],
                    styles['{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}'],
                    {
                        featureClickColumns: ['cartodb_id', 'msaname', 'msacode', '_2020_population', '_2020_population_rank', '_2019_2020_growth', '_2020_growth_rank', 'market_size_category', '_2022_em_code', 'recession_recovery_june_2021', 'recession_recovery_rank_june_2021']
                    })
                    .on('featureClicked', featureEvent => (LayerPopupAction['{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}'](featureEvent)));
                layerList.push(layers['{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}']);
                {% if userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer' %} // Analyzer
                    sources["StrongRecessionRecoveryMarkets"] = new carto.source.SQL('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                    styles["StrongRecessionRecoveryMarkets"] = new carto.style.CartoCSS(layer_css["StrongRecessionRecoveryMarkets"].normal);
                    layers["StrongRecessionRecoveryMarkets"] = new carto.layer.Layer(
                        sources["StrongRecessionRecoveryMarkets"],
                        styles["StrongRecessionRecoveryMarkets"],
                        {
                            featureClickColumns: ['cartodb_id', 'msaname', 'msacode', '_2020_population', '_2020_population_rank', '_2019_2020_growth', '_2020_growth_rank', 'market_size_category', '_2022_em_code', 'recession_recovery_june_2021', 'recession_recovery_rank_june_2021']
                        })
                        .on('featureClicked', featureEvent => (LayerPopupAction["StrongRecessionRecoveryMarkets"](featureEvent)));
                    layerList.push(layers["StrongRecessionRecoveryMarkets"]);
                    sources["MarketGrowthGroups20122022"] = new carto.source.SQL('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                    styles["MarketGrowthGroups20122022"] = new carto.style.CartoCSS(layer_css["MarketGrowthGroups20122022"].normal);
                    layers["MarketGrowthGroups20122022"] = new carto.layer.Layer(
                        sources["MarketGrowthGroups20122022"],
                        styles["MarketGrowthGroups20122022"],
                        {
                            featureClickColumns: ['cartodb_id', 'msaname']
                        })
                        .on('featureClicked', featureEvent => (LayerPopupAction["MarketGrowthGroups20122022"](featureEvent)));
                    layerList.push(layers["MarketGrowthGroups20122022"]);
                    sources["FedBeigeBookDistricts"] = new carto.source.Dataset('fed_beige_book_districts');
                    styles["FedBeigeBookDistricts"] = new carto.style.CartoCSS(layer_css["FedBeigeBookDistricts"].normal);
                    layers["FedBeigeBookDistricts"] = new carto.layer.Layer(
                        sources["FedBeigeBookDistricts"],
                        styles["FedBeigeBookDistricts"],
                        {
                            featureClickColumns: ['district_name', 'summary_20211020', 'summary_20210908', 'summary_20210714', 'summary_20210602', 'summary_20211201', 'summary_20220112', 'summary_20220302', 'summary_20220420', 'summary_20220601', 'summary_20220713', 'summary_20220907', 'summary_20221019', 'summary_20221130', 'summary_20230118', 'summary_20230308', 'summary_20230419', 'summary_20230531', 'summary_20230712', 'summary_20230906', 'summary_20231018', 'summary_20231129', 'summary_20240117', 'book_name']
                        })
                        .on('featureClicked', featureEvent => (LayerPopupAction["FedBeigeBookDistricts"](featureEvent)));
                    layerList.push(layers["FedBeigeBookDistricts"])
                {% else %} // Snapshots
                    sources["FedBeigeBookDistricts"] = new carto.source.Dataset('fed_beige_book_districts');
                    styles["FedBeigeBookDistricts"] = new carto.style.CartoCSS(layer_css["FedBeigeBookDistricts"].normal);
                    layers["FedBeigeBookDistricts"] = new carto.layer.Layer(
                        sources["FedBeigeBookDistricts"],
                        styles["FedBeigeBookDistricts"],
                        {
                            featureClickColumns: ['cartodb_id', 'district_name', 'summary_20240117', 'book_name']
                        })
                        .on('featureClicked', featureEvent => (LayerPopupAction["FedBeigeBookDistricts"](featureEvent)));
                    layerList.push(layers["FedBeigeBookDistricts"])
                {% endif %}
            {% endif %}
            layerList.push(layers['US_cities']);
            layerList.push(layers['US_zip_boundaries']);
            layerList.push(layers['US_county_boundaries']);
            {% if userLevel != 'Both_Snapshots' and userLevel != 'Multi_Snapshots' and userLevel != 'Single_Snapshots' %}
            layerList.push(layers['OpportunityZone']);
            {% endif %}
            {% if userLevel != 'Single_Anticipator' and userLevel != 'Single_Analyzer' and userLevel != 'Single_Snapshots' %}
            layerList.push(layers['MFPPoints30']);
            {% endif %}

            client.addLayers(layerList)
                .then(() => {
                    $("#overlayer_spinner").hide()
                    for(let layer of layerList) {
                        layer.hide()
                    }
                    {% if userLevel == 'Single_Anticipator' or userLevel == 'Single_Analyzer' or userLevel == 'Single_Snapshots' %}
                    layers['MicroNeighborhoodsSingleFamily'].show()
                    showLegend('MicroNeighborhoodsSingleFamily')
                    $('#showSingleEN').show();
                    $('#showEN').hide();
                    $('#showEDN').hide();
                    {% else %}
                    layers['MicroNeighborhoods'].show()
                    showLegend('MicroNeighborhoods')
                    $('#showEN').show();
                    $('#showSingleEN').hide();
                    $('#showEDN').hide();
                    {% endif %}
                    // Hide opportunity zone and en legend by default 
                    opportunityZoneLegendVisible(false)
                    enLegendVisible(false)
                    legendBox.show()
                })
                .catch(cartoError => {
                    console.error(cartoError.message);
                });
            client.getLeafletLayer().addTo(map);

            var totalSecond = 60;
            var myToast
            client.on(carto.events.ERROR, cartoError => {
                console.error(cartoError.message);
                if(!myToast) {
                    myToast = $.toast({
                        heading: 'Need to reload the page',
                        text: 'Ooops! It appears that you have been away from the system for a while.<br>Don’t worry. Just click <a style="color:#e4ef8d;" href="javascript:refreshPage()">HERE</a> to reload the page right now. Or it will be reloaded in <span style="color:#e4ef8d;">'+totalSecond+'</span> seconds automatically.',
                        icon: 'error', // Type of toast icon
                        showHideTransition: 'fade', // fade, slide or plain
                        allowToastClose: false, // Boolean value true or false
                        hideAfter: totalSecond * 1000, // false to make it sticky or number representing the miliseconds as time after which toast needs to be hidden
                        stack: 5, // false if there should be only one toast at a time or a number representing the maximum number of toasts to be shown at a time
                        position: 'bottom-center', // bottom-left or bottom-right or bottom-center or top-left or top-right or top-center or mid-center or an object representing the left, right, top, bottom values
                        textAlign: 'left', 
                        loaderBg: '#9EC600',
                        bgColor: '#a94442',
                        afterHidden: function () {refreshPage()}
                    });
                    setInterval(function(){
                        totalSecond--;
                        myToast.update({
                            heading: 'Need to reload the page',
                            text: 'Ooops! It appears that you have been away from the system for a while.<br>Don’t worry. Just click <a style="color:#e4ef8d;" href="javascript:refreshPage()">HERE</a> to reload the page right now. Or it will be reloaded in <span style="color:#e4ef8d;">'+totalSecond+'</span> seconds automatically.',
                            icon: 'error', // Type of toast icon
                            showHideTransition: 'fade', // fade, slide or plain
                            allowToastClose: false, // Boolean value true or false
                            hideAfter: totalSecond * 1000, // false to make it sticky or number representing the miliseconds as time after which toast needs to be hidden
                            stack: 5, // false if there should be only one toast at a time or a number representing the maximum number of toasts to be shown at a time
                            position: 'bottom-center', // bottom-left or bottom-right or bottom-center or top-left or top-right or top-center or mid-center or an object representing the left, right, top, bottom values
                            textAlign: 'left', 
                            loaderBg: '#9EC600',
                            bgColor: '#a94442',
                            afterHidden: function () {refreshPage()}
                        });
                    }, 1000);
                }
            })

            var pegmanControl = new L.Control.Pegman({
                position: 'bottomright', // position of control inside the map
                //theme: "leaflet-pegman-v3-small", // or "leaflet-pegman-v3-default"
                theme: "leaflet-pegman-v3-default",
            });
            pegmanControl.addTo(map);
            
            // Legend
            {% if userLevel != 'MDM1' %}
            {% for overlay in overlays %}
            {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' or overlay.name == 'MicroNeighborhoods' or overlay.name == emergingMarketLayerNameForAnalyzerAndSnapshots or overlay.name == 'MicroNeighborhoodsSingleFamily' or overlay.name == 'Fed Beige Book Districts' or overlay.name == 'Strong Recession Recovery Markets' or overlay.name == 'MarketGrowthGroups20122022' %}
            legenddata["{{ overlay.name |remove_whitespace }}"] = {}
            legenddata["{{ overlay.name |remove_whitespace }}"]['legendTitle'] = '{{ overlay.legendTitle }}'
            legenddata["{{ overlay.name |remove_whitespace }}"]['legendData'] = {{ overlay.legendData|safe }}
            {% endif %}
            {% endfor %}
            {% else %} // for MDM1
            {% for overlay in overlays %}
            {% if overlay.name != 'EmergingMarkets2023Q2' and overlay.name != 'EmergingMarkets2023Q1' and overlay.name != 'EmergingMarkets2022Q4' and overlay.name != 'EmergingMarkets2022Q3' and overlay.name != 'EmergingMarkets2022Q2' and overlay.name != 'EmergingMarkets2022Q1' and overlay.name != 'Emerging Markets 2022' and overlay.name != 'Emerging Markets 2021' and overlay.name != 'Emerging Markets 2020' and overlay.name != 'Emerging Markets 2019' and overlay.name != 'Emerging Markets 2018' and overlay.name != 'Emerging Markets 2017' and overlay.name != 'Emerging Markets 2016' and overlay.name != 'Emerging Markets 2015' and overlay.name != 'MicroNeighborhoodsSingleFamily'%}
            legenddata["{{ overlay.name |remove_whitespace }}"] = {}
            legenddata["{{ overlay.name |remove_whitespace }}"]['legendTitle'] = '{{ overlay.legendTitle }}'
            legenddata["{{ overlay.name |remove_whitespace }}"]['legendData'] = {{ overlay.legendData|safe }}
            {% endif %}
            {% endfor %}
            {% endif %}

            function showLegend(layername){
                legend.empty();
                legend.append(`<div class="legend-title">${legenddata[layername]['legendTitle']}</div>`)
                {% if isColorBlind %}
                const data = legenddata[layername]['legendData'][1];
                {% else %}
                const data = legenddata[layername]['legendData'][0];
                {% endif %}
                for (category of data){
                    if(category.type == 'color_array') {
                        legend.append(`<li><div class="gradient_legend_container">
                            <div class="square" style="background:${category.value[0]}">${category.name}+</div>
                            <div class="square" style="background:${category.value[1]}">${category.name}</div>
                            <div class="square" style="background:${category.value[2]}">${category.name}-</div>
                          </div></li>`)
                    }
                    else if(category.value[0] == '#')
                        legend.append(`<li><div class="bullet" style="background:${category.value}"></div> ${category.name}</li>`)
                    else
                        legend.append(`<li><div class="bullet ${category.value}"></div> ${category.name}</li>`)
                }
            }
            {% if userLevel == 'Single_Anticipator' or userLevel == 'Single_Analyzer' or userLevel == 'Single_Snapshots' %}
            layers['MicroNeighborhoodsSingleFamily'].show()
            showLegend('MicroNeighborhoodsSingleFamily')
            {% else %}
            layers['MicroNeighborhoods'].show()
            showLegend('MicroNeighborhoods')
            {% endif %}

            var markerPopupContent;
            {% for point in points %}
                // check if point has no any category, show the default icon on the map
                var iUrl = "";
                {% if  point.category.pin_icon.icon.url == None %}
                    iUrl = "https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/images/marker-icon.png"
                {% else %}
                    iUrl = "{{ point.category.pin_icon.icon.url}}";
                {% endif %}
                var myIcon = L.icon({
                    iconUrl: iUrl,
                    iconSize: [25,41],
                    iconAnchor: [13,41],
                    popupAnchor:  [0, -30]
                });
                allPoints["{{ forloop.counter }}"] = {
                    'lat':'{{ point.latitude }}',
                    'lon':'{{ point.longitude }}',
                    'name':'{{ point.location|cut:", United States" }}',
                    'folderID':'{{point.folder.id}}'
                }
                var myLatLng = L.latLng({{ point.latitude }},{{ point.longitude }});
                markers["{{ forloop.counter }}"] = L.marker(myLatLng, {icon: myIcon});
                markerLabels["{{ forloop.counter }}"] = {};
                // Rings and labels
                markerCircles["{{ forloop.counter }}"] = {};
                circle_label_group["{{ forloop.counter }}"] = {};
                markerCircles["{{ forloop.counter }}"][0] = L.circle(L.latLng({{ point.latitude }}, {{ point.longitude }}), 1609, {fill:false,color:'#000000',weight:3,opacity:0.5})
                    .bindTooltip('1 mile', {sticky : true})
                markerCircles["{{ forloop.counter }}"]["_0"] = false
                circle_label_group["{{ forloop.counter }}"][0] = new L.tooltip({ // 1: default : right
                            permanent: true,
                            direction: direction_string[1],
                    })
                    .setContent("1 mile")
                    .setLatLng([
                        {{ point.latitude }},
                        {{ point.longitude }}
                    ])
                markerCircles["{{ forloop.counter }}"][1] = L.circle(L.latLng({{ point.latitude }}, {{ point.longitude }}), 1609 * 3, {fill:false,color:'#000000',weight:3,opacity:0.5})
                    .bindTooltip('3 mile', {sticky : true})
                markerCircles["{{ forloop.counter }}"]["_1"] = false
                circle_label_group["{{ forloop.counter }}"][1] = new L.tooltip({ // 1: default : right
                            permanent: true,
                            direction: direction_string[1],
                    })
                    .setContent("3 mile")
                    .setLatLng([
                        {{ point.latitude }},
                        {{ point.longitude }}
                    ])
                markerCircles["{{ forloop.counter }}"][2] = L.circle(L.latLng({{ point.latitude }}, {{ point.longitude }}), 1609 * 5, {fill:false,color:'#000000',weight:3,opacity:0.5})
                    .bindTooltip('5 mile', {sticky : true})
                markerCircles["{{ forloop.counter }}"]["_2"] =  false
                circle_label_group["{{ forloop.counter }}"][2] = new L.tooltip({ // 1: default : right
                            permanent: true,
                            direction: direction_string[1],
                    })
                    .setContent("5 mile")
                    .setLatLng([
                        {{ point.latitude }},
                        {{ point.longitude }}
                    ])
                {% if  point.visible %}
                    markers["{{ forloop.counter }}"].addTo(map);
                    {% if point.circleVisible %}
                        markerCircles["{{ forloop.counter }}"][0].addTo(map);
                        circle_label_group["{{ forloop.counter }}"][0].setLatLng([
                                {{ point.latitude }},
                                markerCircles["{{ forloop.counter }}"][0].getBounds().getEast()
                            ])
                        if(Cookies.get('showAllCircleLabels') == 'show'){
                            map.addLayer(circle_label_group["{{ forloop.counter }}"][0]);
                        }
                    {% endif %}
                    {% if point.circleVisible1 %}
                        markerCircles["{{ forloop.counter }}"][1].addTo(map);
                        circle_label_group["{{ forloop.counter }}"][1].setLatLng([
                                {{ point.latitude }},
                                markerCircles["{{ forloop.counter }}"][1].getBounds().getEast()
                            ])
                        if(Cookies.get('showAllCircleLabels') == 'show'){
                            map.addLayer(circle_label_group["{{ forloop.counter }}"][1]);
                        }
                    {% endif %}
                    {% if point.circleVisible2 %}
                        markerCircles["{{ forloop.counter }}"][2].addTo(map);
                        circle_label_group["{{ forloop.counter }}"][2].setLatLng([
                                {{ point.latitude }},
                                markerCircles["{{ forloop.counter }}"][2].getBounds().getEast()
                            ])
                        if(Cookies.get('showAllCircleLabels') == 'show'){
                            map.addLayer(circle_label_group["{{ forloop.counter }}"][2]);
                        }
                    {% endif %}
                {% endif %}
                {% if point.circleVisible %}
                    markerCircles["{{ forloop.counter }}"]["_0"] =  true
                {% endif %}
                {% if point.circleVisible1 %}
                    markerCircles["{{ forloop.counter }}"]["_1"] =  true
                {% endif %}
                {% if point.circleVisible2 %}
                    markerCircles["{{ forloop.counter }}"]["_2"] =  true
                {% endif %}
                markerPopupContent = {% if point.address %}'<strong>{{ point.location|cut:", United States" }}</strong><br/><br/><span style="font-style:italic; font-size:0.9em;">ADDRESS : {{ point.address|cut:", United States" }}'{% else %}'<strong>{{ point.location|cut:", United States" }}</strong>'{% endif %}
                markers["{{ forloop.counter }}"].bindPopup(markerPopupContent);
            {% endfor %}
            // define overlay actions
            {% if userLevel != 'MDM1' %}
            var LayerActions = {
                {% for overlay in overlays %}
                {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' or overlay.name == 'MicroNeighborhoods' or overlay.name == emergingMarketLayerNameForAnalyzerAndSnapshots or overlay.name == 'MicroNeighborhoodsSingleFamily' or overlay.name == 'Fed Beige Book Districts'%}
                {{ overlay.name |remove_whitespace }}: function(){
                    removeAllOverlays()
                    layers["{{ overlay.name |remove_whitespace }}"].show();
                    showLegend("{{ overlay.name |remove_whitespace }}");
                    return true;
                },
                {% elif userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer' %}
                    {% if overlay.name == 'Strong Recession Recovery Markets' or overlay.name == 'MarketGrowthGroups20122022' %}
                    {{ overlay.name |remove_whitespace }}: function(){
                        removeAllOverlays()
                        layers["{{ overlay.name |remove_whitespace }}"].show();
                        showLegend("{{ overlay.name |remove_whitespace }}");
                        return true;
                    },
                    {% endif %}
                {% endif %}
                {% endfor %}
            }
            function removeAllOverlays() {
                {% for otheroverlay in overlays %}
                {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' or otheroverlay.name == 'MicroNeighborhoods' or otheroverlay.name == emergingMarketLayerNameForAnalyzerAndSnapshots or otheroverlay.name == 'MicroNeighborhoodsSingleFamily' or otheroverlay.name == 'Fed Beige Book Districts'%}
                if(layers["{{ otheroverlay.name |remove_whitespace }}"] && layers["{{ otheroverlay.name |remove_whitespace }}"].isVisible()){
                    layers["{{ otheroverlay.name |remove_whitespace }}"].hide();
                }
                {% elif userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer' %}
                    {% if otheroverlay.name == 'Strong Recession Recovery Markets' or otheroverlay.name == 'MarketGrowthGroups20122022' %}
                        if(layers["{{ otheroverlay.name |remove_whitespace }}"].isVisible()){
                            layers["{{ otheroverlay.name |remove_whitespace }}"].hide();
                        }
                    {% endif %}
                {% endif %}
                {% endfor %}
            }
            {% else %} // MDM1
            var LayerActions = {
                {% for overlay in overlays %}
                {% if overlay.name != 'EmergingMarkets2023Q2' and overlay.name != 'EmergingMarkets2023Q1' and overlay.name != 'EmergingMarkets2022Q4' and overlay.name != 'EmergingMarkets2022Q3' and overlay.name != 'EmergingMarkets2022Q2' and overlay.name != 'EmergingMarkets2022Q1' and overlay.name != 'Emerging Markets 2022' and overlay.name != 'Emerging Markets 2021' and overlay.name != 'Emerging Markets 2020' and overlay.name != 'Emerging Markets 2019' and overlay.name != 'Emerging Markets 2018' and overlay.name != 'Emerging Markets 2017' and overlay.name != 'Emerging Markets 2016' and overlay.name != 'Emerging Markets 2015' and overlay.name != 'MicroNeighborhoodsSingleFamily'%}
                {{ overlay.name |remove_whitespace }}: function(){
                    removeAllOverlays()
                    layers["{{ overlay.name |remove_whitespace }}"].show();
                    showLegend("{{ overlay.name |remove_whitespace }}");
                    return true;
                },
                {% endif %}
                {% endfor %}
            }
            function removeAllOverlays() {
                {% for otheroverlay in overlays %}
                {% if otheroverlay.name != 'EmergingMarkets2023Q2' and otheroverlay.name != 'EmergingMarkets2023Q1' and otheroverlay.name != 'EmergingMarkets2022Q4' and otheroverlay.name != 'EmergingMarkets2022Q3' and otheroverlay.name != 'EmergingMarkets2022Q2' and otheroverlay.name != 'EmergingMarkets2022Q1' and otheroverlay.name != 'Emerging Markets 2022' and otheroverlay.name != 'Emerging Markets 2021' and otheroverlay.name != 'Emerging Markets 2020' and otheroverlay.name != 'Emerging Markets 2019' and otheroverlay.name != 'Emerging Markets 2018' and otheroverlay.name != 'Emerging Markets 2017' and otheroverlay.name != 'Emerging Markets 2016' and otheroverlay.name != 'Emerging Markets 2015' and otheroverlay.name != 'MicroNeighborhoodsSingleFamily'%}
                if(layers["{{ otheroverlay.name |remove_whitespace }}"].isVisible()){
                    layers["{{ otheroverlay.name |remove_whitespace }}"].hide();
                }
                {% endif %}
                {% endfor %}
            }
            {% endif %}
            LayerPopupAction = {
                {% for overlay in overlays %}
                    {%  if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' %}
                        {% if overlay.name == 'Emerging Markets 2022' or overlay.name == 'Strong Recession Recovery Markets' %}
                            {{ overlay.name |remove_whitespace }}: function(featureEvent){
                                marketPopupData = {
                                    "Market Name":featureEvent.data.msaname,
                                    "Market Population 2020":featureEvent.data._2020_population != null ? featureEvent.data._2020_population.toLocaleString('en') : 'NA',
                                    "Market Population 2020 Rank":(featureEvent.data._2020_population_rank != null ? '#'+featureEvent.data._2020_population_rank.toLocaleString('en') : 'NA'),
                                    "Market Size Category":featureEvent.data.market_size_category,
                                    "Market Population 2020 Growth Rate":(featureEvent.data._2019_2020_growth != '#VALUE!' && featureEvent.data._2019_2020_growth != null ? (featureEvent.data._2019_2020_growth * 100).toFixed(2)+'%' : 'NA'),
                                    "Market Population 2020 Growth Rank":(featureEvent.data._2020_growth_rank != 'NA' && featureEvent.data._2020_growth_rank != null ? '#'+featureEvent.data._2020_growth_rank.toLocaleString('en') : 'NA'),
                                    "Emerging Market Category":getEMCategoryFromEMCode(featureEvent.data._2022_em_code),
                                    "Volatility Rank of 444 Markets":(featureEvent.data.volatility_rank == 'NA' || featureEvent.data.volatility_rank == null ? 'NA' : '#'+featureEvent.data.volatility_rank ),
                                    "Recession Recovery June 2021":(featureEvent.data.recession_recovery_june_2021 != '#VALUE!' && featureEvent.data.recession_recovery_june_2021 != null ? (featureEvent.data.recession_recovery_june_2021 * 100).toFixed(2)+'%' : 'NA'),
                                    "Recession Recovery Rank June 2021":(featureEvent.data.recession_recovery_rank_june_2021 != 'NA' && featureEvent.data.recession_recovery_rank_june_2021 != null ? '#'+featureEvent.data.recession_recovery_rank_june_2021.toLocaleString('en') : 'NA'),
                                    "Chart msacode": featureEvent.data.msacode
                                }
                                var popup_content = `<em><span style="font-size: 0.9em; color: #df4c4c;">Data Scheduled for Update in April 2023</span></em>`
                                    +`<br><br>`
                                    +`<strong><span style="font-size: 0.9em;">Market Name: </span></strong>`
                                    + featureEvent.data.msaname
                                    +`<br><br>`
                                    +'<strong><span style="font-size: 0.9em;">Market Population 2020: </span></strong>'
                                    + (featureEvent.data._2020_population != null ? featureEvent.data._2020_population.toLocaleString('en') : 'NA')
                                    + '<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Market Population 2020 Rank: </span></strong>'
                                    + (featureEvent.data._2020_population_rank != null ? '#'+featureEvent.data._2020_population_rank.toLocaleString('en') : 'NA')
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Market Size Category: </span></strong>'
                                    + featureEvent.data.market_size_category
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Market Population 2020 Growth Rate: </span></strong>'
                                    + (featureEvent.data._2019_2020_growth != '#VALUE!' && featureEvent.data._2019_2020_growth != null ? (featureEvent.data._2019_2020_growth * 100).toFixed(2)+'%' : 'NA')
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Market Population 2020 Growth Rank: </span></strong>'
                                    + (featureEvent.data._2020_growth_rank != 'NA' && featureEvent.data._2020_growth_rank != null ? '#'+featureEvent.data._2020_growth_rank.toLocaleString('en') : 'NA')
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Emerging Market Category: </span></strong>'
                                    +getEMCategoryFromEMCode(featureEvent.data._2022_em_code)
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Volatility Rank of 444 Markets: </span></strong>'
                                    + (featureEvent.data.volatility_rank == 'NA' || featureEvent.data.volatility_rank == null ? 'NA' : '#'+featureEvent.data.volatility_rank )
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Recession Recovery June 2021: </span></strong>'
                                    + (featureEvent.data.recession_recovery_june_2021 != '#VALUE!' && featureEvent.data.recession_recovery_june_2021 != null ? (featureEvent.data.recession_recovery_june_2021 * 100).toFixed(2)+'%' : 'NA')
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Recession Recovery Rank June 2021: </span></strong>'
                                    + (featureEvent.data.recession_recovery_rank_june_2021 != 'NA' && featureEvent.data.recession_recovery_rank_june_2021 != null ? '#'+featureEvent.data.recession_recovery_rank_june_2021.toLocaleString('en') : 'NA')
                                    +'<br><br>'
                                    +`<a class="image-popup-no-margins" href="/media/images/Market_Popup_Charts/` + featureEvent.data.msacode + `.png">
                                        <img src="/media/images/Market_Popup_Charts/` + featureEvent.data.msacode + `.png" alt="Unknown" style="width: 270px; height: auto;">
                                    </a>`
                                    +'<br><br>'
                                    +'<a title="Print" onclick="printEMPopupPDF(marketPopupData)">Print the popup information</a>'
                                
                                if(featureEvent.data.cartodb_id >= 460 && featureEvent.data.cartodb_id <= 464) { // Revised MSAs (temporarily cuz of no data)
                                    popup_content = `<em><span style="font-size: 0.9em; color: #df4c4c;">Revised Market--Additional Data Available in April 2023</span></em>`
                                    +`<br><br>`
                                    +`<strong><span style="font-size: 0.9em;">Market Name: </span></strong>`
                                    + featureEvent.data.msaname
                                }
                                popup = L.popup({ closeButton: true });
                                popup.setContent(popup_content);
                                popup.setLatLng(featureEvent.latLng);
                                if (!popup.isOpen()) {
                                    popup.openOn(map);
                                }
                                $('.image-popup-no-margins').magnificPopup({
                                    type: 'image',
                                    closeOnContentClick: true,
                                    closeBtnInside: false,
                                    fixedContentPos: true,
                                    mainClass: 'mfp-no-margins mfp-with-zoom', // class to remove default margin from left and right side
                                    image: {
                                        verticalFit: true
                                    },
                                    zoom: {
                                        enabled: true,
                                        duration: 300 // don't foget to change the duration also in CSS
                                    }
                                });
                                return true;
                            },
                        {% elif 'Emerging' in overlay.name %}
                            {{ overlay.name |remove_whitespace }}: function(featureEvent){
                                var popup_content = '<strong><span style="font-size: 0.9em;">Market Name:  </span></strong><br><br>'
                                + featureEvent.data.msaname
                                popup = L.popup({ closeButton: true });
                                popup.setContent(popup_content);
                                popup.setLatLng(featureEvent.latLng);
                                if (!popup.isOpen()) {
                                    popup.openOn(map);
                                }
                                return true;
                            },
                        {% elif overlay.name == 'MarketGrowthGroups20122022' %}
                            {{ overlay.name |remove_whitespace }}: function(featureEvent){
                                var popup_content = '<strong><span style="font-size: 0.9em;">Market Name:  </span></strong><br><br>'
                                + featureEvent.data.msaname
                                popup = L.popup({ closeButton: true });
                                popup.setContent(popup_content);
                                popup.setLatLng(featureEvent.latLng);
                                if (!popup.isOpen()) {
                                    popup.openOn(map);
                                }
                                return true;
                            },
                        {% elif overlay.name == 'Fed Beige Book Districts' %}
                            {{ overlay.name |remove_whitespace }}: function(featureEvent){
                                var popup_content = `<strong><span style="font-size: 1.5em;">`
                                    + featureEvent.data.district_name
                                    +`</span></strong><br>` + getDateStringFromOptionValue(fedDate) + `<br><br>`
                                    + featureEvent.data['summary_' + fedDate]
                                    + '<br><br>'
                                    +`<a href="/media/FedBeigeBook/` + fedDate + `/` + featureEvent.data.book_name + `.pdf" target='_blank'>Click here for the full report PDF</a>`
                                popup = L.popup({ closeButton: true });
                                popup.setContent(popup_content);
                                popup.setLatLng(featureEvent.latLng);
                                if (!popup.isOpen()) {
                                    popup.openOn(map);
                                }
                                return true;
                            },
                        {% endif %}
                    {% elif userLevel == 'MDM1' %}
                        {% if overlay.name != 'EmergingMarkets2023Q2' and overlay.name != 'EmergingMarkets2023Q1' and overlay.name != 'EmergingMarkets2022Q4' and overlay.name != 'EmergingMarkets2022Q3' and overlay.name != 'EmergingMarkets2022Q2' and overlay.name != 'EmergingMarkets2022Q1' and overlay.name != 'Emerging Markets 2022' and overlay.name != 'Emerging Markets 2021' and overlay.name != 'Emerging Markets 2020' and overlay.name != 'Emerging Markets 2019' and overlay.name != 'Emerging Markets 2018' and overlay.name != 'Emerging Markets 2017' and overlay.name != 'Emerging Markets 2016' and overlay.name != 'Emerging Markets 2015' and overlay.name != 'MicroNeighborhoodsSingleFamily'%}
                            {% if overlay.name == 'Emerging Markets 2014' or overlay.name == 'Strong Recession Recovery Markets' %}
                                {{ overlay.name |remove_whitespace }}: function(featureEvent){
                                    marketPopupData = {
                                        "Market Name":featureEvent.data.msaname,
                                        "Market Population 2020":featureEvent.data._2020_population != null ? featureEvent.data._2020_population.toLocaleString('en') : 'NA',
                                        "Market Population 2020 Rank":(featureEvent.data._2020_population_rank != null ? '#'+featureEvent.data._2020_population_rank.toLocaleString('en') : 'NA'),
                                        "Market Size Category":featureEvent.data.market_size_category,
                                        "Market Population 2020 Growth Rate":(featureEvent.data._2019_2020_growth != '#VALUE!' && featureEvent.data._2019_2020_growth != null ? (featureEvent.data._2019_2020_growth * 100).toFixed(2)+'%' : 'NA'),
                                        "Market Population 2020 Growth Rank":(featureEvent.data._2020_growth_rank != 'NA' && featureEvent.data._2020_growth_rank != null ? '#'+featureEvent.data._2020_growth_rank.toLocaleString('en') : 'NA'),
                                        "Emerging Market Category":getEMCategoryFromEMCode(featureEvent.data._2014_em_code),
                                        "Volatility Rank of 444 Markets":(featureEvent.data.volatility_rank == 'NA' || featureEvent.data.volatility_rank == null ? 'NA' : '#'+featureEvent.data.volatility_rank ),
                                        "Recession Recovery June 2021":(featureEvent.data.recession_recovery_june_2021 != '#VALUE!' && featureEvent.data.recession_recovery_june_2021 != null ? (featureEvent.data.recession_recovery_june_2021 * 100).toFixed(2)+'%' : 'NA'),
                                        "Recession Recovery Rank June 2021":(featureEvent.data.recession_recovery_rank_june_2021 != 'NA' && featureEvent.data.recession_recovery_rank_june_2021 != null ? '#'+featureEvent.data.recession_recovery_rank_june_2021.toLocaleString('en') : 'NA'),
                                        "Chart msacode": featureEvent.data.msacode
                                    }
                                    var popup_content = `<em><span style="font-size: 0.9em; color: #df4c4c;">Data Scheduled for Update in April 2023</span></em>`
                                        +`<br><br>`
                                        +`<strong><span style="font-size: 0.9em;">Market Name: </span></strong>`
                                        + featureEvent.data.msaname
                                        +`<br><br>`
                                        +'<strong><span style="font-size: 0.9em;">Market Population 2020: </span></strong>'
                                        + (featureEvent.data._2020_population != null ? featureEvent.data._2020_population.toLocaleString('en') : 'NA')
                                        + '<br><br>'
                                        +'<strong><span style="font-size: 0.9em;">Market Population 2020 Rank: </span></strong>'
                                        + (featureEvent.data._2020_population_rank != null ? '#'+featureEvent.data._2020_population_rank.toLocaleString('en') : 'NA')
                                        +'<br><br>'
                                        +'<strong><span style="font-size: 0.9em;">Market Size Category: </span></strong>'
                                        + featureEvent.data.market_size_category
                                        +'<br><br>'
                                        +'<strong><span style="font-size: 0.9em;">Market Population 2020 Growth Rate: </span></strong>'
                                        + (featureEvent.data._2019_2020_growth != '#VALUE!' && featureEvent.data._2019_2020_growth != null ? (featureEvent.data._2019_2020_growth * 100).toFixed(2)+'%' : 'NA')
                                        +'<br><br>'
                                        +'<strong><span style="font-size: 0.9em;">Market Population 2020 Growth Rank: </span></strong>'
                                        + (featureEvent.data._2020_growth_rank != 'NA' && featureEvent.data._2020_growth_rank != null ? '#'+featureEvent.data._2020_growth_rank.toLocaleString('en') : 'NA')
                                        +'<br><br>'
                                        +'<strong><span style="font-size: 0.9em;">Emerging Market Category: </span></strong>'
                                        +getEMCategoryFromEMCode(featureEvent.data._2014_em_code)
                                        +'<br><br>'
                                        +'<strong><span style="font-size: 0.9em;">Volatility Rank of 444 Markets: </span></strong>'
                                        + (featureEvent.data.volatility_rank == 'NA' || featureEvent.data.volatility_rank == null ? 'NA' : '#'+featureEvent.data.volatility_rank )
                                        +'<br><br>'
                                        +'<strong><span style="font-size: 0.9em;">Recession Recovery June 2021: </span></strong>'
                                        + (featureEvent.data.recession_recovery_june_2021 != '#VALUE!' && featureEvent.data.recession_recovery_june_2021 != null ? (featureEvent.data.recession_recovery_june_2021 * 100).toFixed(2)+'%' : 'NA')
                                        +'<br><br>'
                                        +'<strong><span style="font-size: 0.9em;">Recession Recovery Rank June 2021: </span></strong>'
                                        + (featureEvent.data.recession_recovery_rank_june_2021 != 'NA' && featureEvent.data.recession_recovery_rank_june_2021 != null ? '#'+featureEvent.data.recession_recovery_rank_june_2021.toLocaleString('en') : 'NA')
                                        +'<br><br>'
                                        +`<a class="image-popup-no-margins" href="/media/images/Market_Popup_Charts/` + featureEvent.data.msacode + `.png">
                                            <img src="/media/images/Market_Popup_Charts/` + featureEvent.data.msacode + `.png" alt="Unknown" style="width: 270px; height: auto;">
                                        </a>`
                                        +'<br><br>'
                                        +'<a title="Print" onclick="printEMPopupPDF(marketPopupData)">Print the popup information</a>'
                                    
                                    if(featureEvent.data.cartodb_id >= 460 && featureEvent.data.cartodb_id <= 464) { // Revised MSAs (temporarily cuz of no data)
                                        popup_content = `<em><span style="font-size: 0.9em; color: #df4c4c;">Revised Market--Additional Data Available in April 2023</span></em>`
                                        +`<br><br>`
                                        +`<strong><span style="font-size: 0.9em;">Market Name: </span></strong>`
                                        + featureEvent.data.msaname
                                    }
                                    popup = L.popup({ closeButton: true });
                                    popup.setContent(popup_content);
                                    popup.setLatLng(featureEvent.latLng);
                                    if (!popup.isOpen()) {
                                        popup.openOn(map);
                                    }
                                    $('.image-popup-no-margins').magnificPopup({
                                        type: 'image',
                                        closeOnContentClick: true,
                                        closeBtnInside: false,
                                        fixedContentPos: true,
                                        mainClass: 'mfp-no-margins mfp-with-zoom', // class to remove default margin from left and right side
                                        image: {
                                            verticalFit: true
                                        },
                                        zoom: {
                                            enabled: true,
                                            duration: 300 // don't foget to change the duration also in CSS
                                        }
                                    });
                                    return true;
                                },
                            {% elif 'Emerging' in overlay.name %}
                                {{ overlay.name |remove_whitespace }}: function(featureEvent){
                                    var popup_content = '<strong><span style="font-size: 0.9em;">Market Name:  </span></strong><br><br>'
                                    + featureEvent.data.msaname
                                    popup = L.popup({ closeButton: true });
                                    popup.setContent(popup_content);
                                    popup.setLatLng(featureEvent.latLng);
                                    if (!popup.isOpen()) {
                                        popup.openOn(map);
                                    }
                                    return true;
                                },
                            {% elif overlay.name == 'MarketGrowthGroups20122022' %}
                                {{ overlay.name |remove_whitespace }}: function(featureEvent){
                                    var popup_content = '<strong><span style="font-size: 0.9em;">Market Name:  </span></strong><br><br>'
                                    + featureEvent.data.msaname
                                    popup = L.popup({ closeButton: true });
                                    popup.setContent(popup_content);
                                    popup.setLatLng(featureEvent.latLng);
                                    if (!popup.isOpen()) {
                                        popup.openOn(map);
                                    }
                                    return true;
                                },
                            {% elif overlay.name == 'Fed Beige Book Districts' %}
                                {{ overlay.name |remove_whitespace }}: function(featureEvent){
                                    var popup_content = `<strong><span style="font-size: 1.5em;">`
                                        + featureEvent.data.district_name
                                        +`</span></strong><br>` + getDateStringFromOptionValue(fedDate) + `<br><br>`
                                        + featureEvent.data['summary_' + fedDate]
                                        + '<br><br>'
                                        +`<a href="/media/FedBeigeBook/` + fedDate + `/` + featureEvent.data.book_name + `.pdf" target='_blank'>Click here for the full report PDF</a>`
                                    popup = L.popup({ closeButton: true });
                                    popup.setContent(popup_content);
                                    popup.setLatLng(featureEvent.latLng);
                                    if (!popup.isOpen()) {
                                        popup.openOn(map);
                                    }
                                    return true;
                                },
                            {% endif %}
                        {% endif %}
                    {% elif userLevel == 'Both_Analyzer' or userLevel == 'Both_Snapshots' or userLevel == 'Multi_Analyzer' or userLevel == 'Multi_Snapshots' or userLevel == 'Single_Analyzer' or userLevel == 'Single_Snapshots' %}
                        {% if overlay.name == emergingMarketLayerNameForAnalyzerAndSnapshots %}
                            {{ overlay.name |remove_whitespace }}: function(featureEvent){
                                marketPopupData = {
                                    "Market Name":featureEvent.data.msaname,
                                    "Market Population 2020":featureEvent.data._2020_population != null ? featureEvent.data._2020_population.toLocaleString('en') : 'NA',
                                    "Market Population 2020 Rank":(featureEvent.data._2020_population_rank != null ? '#'+featureEvent.data._2020_population_rank.toLocaleString('en') : 'NA'),
                                    "Market Size Category":featureEvent.data.market_size_category,
                                    {% if userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer' %}
                                    "Market Population 2020 Growth Rate":(featureEvent.data._2019_2020_growth != '#VALUE!' && featureEvent.data._2019_2020_growth != null ? (featureEvent.data._2019_2020_growth * 100).toFixed(2)+'%' : 'NA'),
                                    "Market Population 2020 Growth Rank":(featureEvent.data._2020_growth_rank != 'NA' && featureEvent.data._2020_growth_rank != null ? '#'+featureEvent.data._2020_growth_rank.toLocaleString('en') : 'NA'),
                                    {% endif %}
                                    "Emerging Market Category":getEMCategoryFromEMCode(featureEvent.data._2022_em_code),
                                    {% if userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer' %}
                                    "Recession Recovery June 2021":(featureEvent.data.recession_recovery_june_2021 != '#VALUE!' && featureEvent.data.recession_recovery_june_2021 != null ? (featureEvent.data.recession_recovery_june_2021 * 100).toFixed(2)+'%' : 'NA'),
                                    "Recession Recovery Rank June 2021":(featureEvent.data.recession_recovery_rank_june_2021 != 'NA' && featureEvent.data.recession_recovery_rank_june_2021 != null ? '#'+featureEvent.data.recession_recovery_rank_june_2021.toLocaleString('en') : 'NA')
                                    {% endif %}
                                }
                                var popup_content = `<em><span style="font-size: 0.9em; color: #df4c4c;">Data Scheduled for Update in April 2023</span></em>`
                                    +`<br><br>`
                                    +`<strong><span style="font-size: 0.9em;">Market Name: </span></strong>`
                                    + featureEvent.data.msaname
                                    +`<br><br>`
                                    +'<strong><span style="font-size: 0.9em;">Market Population 2020: </span></strong>'
                                    + (featureEvent.data._2020_population != null ? featureEvent.data._2020_population.toLocaleString('en') : 'NA')
                                    + '<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Market Population 2020 Rank: </span></strong>'
                                    + (featureEvent.data._2020_population_rank != null ? '#'+featureEvent.data._2020_population_rank.toLocaleString('en') : 'NA')
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Market Size Category: </span></strong>'
                                    + featureEvent.data.market_size_category
                                    {% if userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer' %}
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Market Population 2020 Growth Rate: </span></strong>'
                                    + (featureEvent.data._2019_2020_growth != '#VALUE!' && featureEvent.data._2019_2020_growth != null ? (featureEvent.data._2019_2020_growth * 100).toFixed(2)+'%' : 'NA')
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Market Population 2020 Growth Rank: </span></strong>'
                                    + (featureEvent.data._2020_growth_rank != 'NA' && featureEvent.data._2020_growth_rank != null ? '#'+featureEvent.data._2020_growth_rank.toLocaleString('en') : 'NA')
                                    {% endif %}
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Emerging Market Category: </span></strong>'
                                    +getEMCategoryFromEMCode(featureEvent.data._2022_em_code)
                                    {% if userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer' %}
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Recession Recovery June 2021: </span></strong>'
                                    + (featureEvent.data.recession_recovery_june_2021 != '#VALUE!' && featureEvent.data.recession_recovery_june_2021 != null ? (featureEvent.data.recession_recovery_june_2021 * 100).toFixed(2)+'%' : 'NA')
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Recession Recovery Rank June 2021: </span></strong>'
                                    + (featureEvent.data.recession_recovery_rank_june_2021 != 'NA' && featureEvent.data.recession_recovery_rank_june_2021 != null ? '#'+featureEvent.data.recession_recovery_rank_june_2021.toLocaleString('en') : 'NA')
                                    {% endif %}
                                    +'<br><br>'
                                    +'<a title="Print" onclick="printEMPopupPDF(marketPopupData)">Print the popup information</a>'
    
                                if(featureEvent.data.cartodb_id >= 460 && featureEvent.data.cartodb_id <= 464) { // Revised MSAs (temporarily cuz of no data)
                                    popup_content = `<em><span style="font-size: 0.9em; color: #df4c4c;">Revised Market--Additional Data Available in April 2023</span></em>`
                                    +`<br><br>`
                                    +`<strong><span style="font-size: 0.9em;">Market Name: </span></strong>`
                                    + featureEvent.data.msaname
                                }
    
                                popup = L.popup({ closeButton: true });
                                popup.setContent(popup_content);
                                popup.setLatLng(featureEvent.latLng);
                                if (!popup.isOpen()) {
                                    popup.openOn(map);
                                }
                                return true;
                            },
                        {% elif overlay.name == 'MarketGrowthGroups20122022' %}
                            {{ overlay.name |remove_whitespace }}: function(featureEvent){
                                var popup_content = '<strong><span style="font-size: 0.9em;">Market Name:  </span></strong><br><br>'
                                + featureEvent.data.msaname
                                popup = L.popup({ closeButton: true });
                                popup.setContent(popup_content);
                                popup.setLatLng(featureEvent.latLng);
                                if (!popup.isOpen()) {
                                    popup.openOn(map);
                                }
                                return true;
                            },
                        {% elif overlay.name == 'Fed Beige Book Districts' %}
                            {{ overlay.name |remove_whitespace }}: function(featureEvent){
                                {% if userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer'%}
                                var popup_content = `<strong><span style="font-size: 1.5em;">`
                                    + featureEvent.data.district_name
                                    +`</span></strong><br>` + getDateStringFromOptionValue(fedDate) + `<br><br>`
                                    + featureEvent.data['summary_' + fedDate]
                                    + '<br><br>'
                                    +`<a href="/media/FedBeigeBook/` + fedDate + `/` + featureEvent.data.book_name + `.pdf" target='_blank'>Click here for the full report PDF</a>`
                                {% else %}
                                var popup_content = `<strong><span style="font-size: 1.5em;">`
                                    + featureEvent.data.district_name
                                    +`</span></strong><br>January 17, 2024<br><br>`
                                    + featureEvent.data.summary_20240117
                                    + '<br><br>'
                                    +`<a href="/media/FedBeigeBook/20240117/` + featureEvent.data.book_name + `.pdf" target='_blank'>Click here for the full report PDF</a>`
                                {% endif %}
                                popup = L.popup({ closeButton: true });
                                popup.setContent(popup_content);
                                popup.setLatLng(featureEvent.latLng);
                                if (!popup.isOpen()) {
                                    popup.openOn(map);
                                }
                                return true;
                            },
                        {% elif overlay.name == 'Strong Recession Recovery Markets' %}
                            {{ overlay.name |remove_whitespace }}: function(featureEvent){
                                marketPopupData = {
                                    "Market Name":featureEvent.data.msaname,
                                    "Market Population 2020":featureEvent.data._2020_population != null ? featureEvent.data._2020_population.toLocaleString('en') : 'NA',
                                    "Market Population 2020 Rank":(featureEvent.data._2020_population_rank != null ? '#'+featureEvent.data._2020_population_rank.toLocaleString('en') : 'NA'),
                                    "Market Size Category":featureEvent.data.market_size_category,
                                    "Market Population 2020 Growth Rate":(featureEvent.data._2019_2020_growth != '#VALUE!' && featureEvent.data._2019_2020_growth != null ? (featureEvent.data._2019_2020_growth * 100).toFixed(2)+'%' : 'NA'),
                                    "Market Population 2020 Growth Rank":(featureEvent.data._2020_growth_rank != 'NA' && featureEvent.data._2020_growth_rank != null ? '#'+featureEvent.data._2020_growth_rank.toLocaleString('en') : 'NA'),
                                    "Emerging Market Category":getEMCategoryFromEMCode(featureEvent.data._2022_em_code),
                                    "Recession Recovery June 2021":(featureEvent.data.recession_recovery_june_2021 != '#VALUE!' && featureEvent.data.recession_recovery_june_2021 != null ? (featureEvent.data.recession_recovery_june_2021 * 100).toFixed(2)+'%' : 'NA'),
                                    "Recession Recovery Rank June 2021":(featureEvent.data.recession_recovery_rank_june_2021 != 'NA' && featureEvent.data.recession_recovery_rank_june_2021 != null ? '#'+featureEvent.data.recession_recovery_rank_june_2021.toLocaleString('en') : 'NA')
                                }
                                var popup_content = `<em><span style="font-size: 0.9em; color: #df4c4c;">Data Scheduled for Update in April 2023</span></em>`
                                    +`<br><br>`
                                    +`<strong><span style="font-size: 0.9em;">Market Name: </span></strong>`
                                    + featureEvent.data.msaname
                                    +`<br><br>`
                                    +'<strong><span style="font-size: 0.9em;">Market Population 2020: </span></strong>'
                                    + (featureEvent.data._2020_population != null ? featureEvent.data._2020_population.toLocaleString('en') : 'NA')
                                    + '<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Market Population 2020 Rank: </span></strong>'
                                    + (featureEvent.data._2020_population_rank != null ? '#'+featureEvent.data._2020_population_rank.toLocaleString('en') : 'NA')
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Market Size Category: </span></strong>'
                                    +featureEvent.data.market_size_category
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Market Population 2020 Growth Rate: </span></strong>'
                                    + (featureEvent.data._2019_2020_growth != '#VALUE!' && featureEvent.data._2019_2020_growth != null ? (featureEvent.data._2019_2020_growth * 100).toFixed(2)+'%' : 'NA')
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Market Population 2020 Growth Rank: </span></strong>'
                                    + (featureEvent.data._2020_growth_rank != 'NA' && featureEvent.data._2020_growth_rank != null ? '#'+featureEvent.data._2020_growth_rank.toLocaleString('en') : 'NA')
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Emerging Market Category: </span></strong>'
                                    +getEMCategoryFromEMCode(featureEvent.data._2022_em_code)
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Recession Recovery June 2021: </span></strong>'
                                    + (featureEvent.data.recession_recovery_june_2021 != '#VALUE!' && featureEvent.data.recession_recovery_june_2021 != null ? (featureEvent.data.recession_recovery_june_2021 * 100).toFixed(2)+'%' : 'NA')
                                    +'<br><br>'
                                    +'<strong><span style="font-size: 0.9em;">Recession Recovery Rank June 2021: </span></strong>'
                                    + (featureEvent.data.recession_recovery_rank_june_2021 != 'NA' && featureEvent.data.recession_recovery_rank_june_2021 != null ? '#'+featureEvent.data.recession_recovery_rank_june_2021.toLocaleString('en') : 'NA')
                                    +'<br><br>'
                                    +'<a title="Print" onclick="printEMPopupPDF(marketPopupData)">Print the popup information</a>'
    
                                if(featureEvent.data.cartodb_id >= 460 && featureEvent.data.cartodb_id <= 464) { // Revised MSAs (temporarily cuz of no data)
                                    popup_content = `<em><span style="font-size: 0.9em; color: #df4c4c;">Revised Market--Additional Data Available in April 2023</span></em>`
                                    +`<br><br>`
                                    +`<strong><span style="font-size: 0.9em;">Market Name: </span></strong>`
                                    + featureEvent.data.msaname
                                }
                                popup = L.popup({ closeButton: true });
                                popup.setContent(popup_content);
                                popup.setLatLng(featureEvent.latLng);
                                if (!popup.isOpen()) {
                                    popup.openOn(map);
                                }
                                return true;
                            },
                        {% endif %}
                    {% endif %}
                {% endfor %}
            }
            $('#overlayselector').change(function() {
                LayerActions[$(this).val()]();

                // UI buttons for Emerging Market
                if($(this).val().indexOf('EmergingMarkets') > -1 || $(this).val() == 'StrongRecessionRecoveryMarkets' || $(this).val() == 'MarketGrowthGroups20122022'){
                    if($(this).val() == 'StrongRecessionRecoveryMarkets') {
                        $('#market_print_button').hide()
                        $('#marketGrowthGroups_print_button').hide()
                        $('#timeline_slider_wrap_div').hide()
                    } else if($(this).val() == 'MarketGrowthGroups20122022') {
                        $('#market_print_button').hide()
                        $('#marketGrowthGroups_print_button').show()
                        $('#timeline_slider_wrap_div').hide()
                    } else {
                        $('#market_print_button').show()
                        $('#marketGrowthGroups_print_button').hide()
                        $('#timeline_slider_wrap_div').show()                        
                    }
                    $('#msaTypeSelector').show()
                    $('#msaTypeSelector').next(".select2-container").show();
                } else {
                    $('#market_print_button').hide()
                    $('#marketGrowthGroups_print_button').hide()
                    $('#timeline_slider_wrap_div').hide()
                    stop()
                    $('#msaTypeSelector').hide()
                    $('#msaTypeSelector').next(".select2-container").hide();
                }
                if($(this).val() == 'MicroNeighborhoods'){
                    $('#zipcode_show_div').show()
                    $('#county_show_div').show()
                    $('#city_show_div').show()
                    {% if userLevel != 'Both_Snapshots' and userLevel != 'Multi_Snapshots' and userLevel != 'Single_Snapshots' %}
                    $('#opportunity_zone_show_div').show()
                    if(!$( "#opportunity_zone_show_checkbox" ).prop("checked")) {
                        opportunityZoneLegendVisible(false)
                    } else opportunityZoneLegendVisible(true)
                    {% else %}
                    opportunityZoneLegendVisible(false)
                    {% endif %}
                    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Both_Analyzer' or userLevel == 'Multi_Anticipator' or userLevel == 'Multi_Analyzer' or userLevel == 'MDM1' %}
                    $('#showMFPPoints30').show()
                    $('#warningPopupIconForMFPPoints30').show()
                    {% endif %}
                    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'MDM1' %}
                    $('#showEN').show()
                    $('#showSingleEN').hide()
                    $('#showEDN').hide()
                    if(isENSymbolShowing) enLegendVisible(true);
                    else enLegendVisible(false);
                    {% endif %}
                } else if($(this).val() == 'MicroNeighborhoodsSingleFamily'){
                    $('#zipcode_show_div').show()
                    $('#county_show_div').show()
                    $('#city_show_div').show()
                    {% if userLevel != 'Both_Snapshots' and userLevel != 'Multi_Snapshots' and userLevel != 'Single_Snapshots' %}
                    $('#opportunity_zone_show_div').show()
                    if(!$( "#opportunity_zone_show_checkbox" ).prop("checked")) {
                        opportunityZoneLegendVisible(false)
                    } else opportunityZoneLegendVisible(true)
                    {% else %}
                    opportunityZoneLegendVisible(false)
                    {% endif %}
                    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Single_Anticipator' %}
                    $('#showSingleEN').show()
                    $('#showEN').hide()
                    $('#showEDN').hide()
                    if(isSFENSymbolShowing) enLegendVisible(true);
                    else enLegendVisible(false);
                    {% endif %}
                    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Both_Analyzer' %}
                    $('#showMFPPoints30').hide()
                    $('#warningPopupIconForMFPPoints30').hide()
                    layers['MFPPoints30'].hide()
                    $('#showMFPPoints30').attr('src', '/media/icons/MFP.png');
                    {% endif %}
                } else if($(this).val() == 'DCTestNew'){
                    $('#zipcode_show_div').show()
                    $('#county_show_div').show()
                    $('#city_show_div').show()
                    {% if userLevel != 'Both_Snapshots' and userLevel != 'Multi_Snapshots' and userLevel != 'Single_Snapshots' %}
                    $('#opportunity_zone_show_div').show()
                    if(!$( "#opportunity_zone_show_checkbox" ).prop("checked")) {
                        opportunityZoneLegendVisible(false)
                    } else opportunityZoneLegendVisible(true)
                    {% else %}
                    opportunityZoneLegendVisible(false)
                    {% endif %}
                    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Both_Analyzer' or userLevel == 'Multi_Anticipator' or userLevel == 'Multi_Analyzer' or userLevel == 'MDM1' %}
                    $('#showMFPPoints30').show()
                    $('#warningPopupIconForMFPPoints30').show()
                    {% endif %}
                    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'MDM1' %}
                    $('#showEN').hide()
                    $('#showSingleEN').hide()
                    $('#showEDN').show()
                    if(isEDNSymbolShowing) enLegendVisible(true);
                    else enLegendVisible(false);
                    {% endif %}
                } else {
                    if($( "#zipcode_show_checkbox" ).prop("checked"))
                        $( "#zipcode_show_checkbox" ).prop( "checked", false ).change();
                    if($( "#county_show_checkbox" ).prop("checked"))
                        $( "#county_show_checkbox" ).prop( "checked", false ).change();
                    if($( "#city_show_checkbox" ).prop("checked"))
                        $( "#city_show_checkbox" ).prop( "checked", false ).change();
                    $('#zipcode_show_div').hide()
                    $('#county_show_div').hide()
                    $('#city_show_div').hide()
                    {% if userLevel != 'Both_Snapshots' and userLevel != 'Multi_Snapshots' and userLevel != 'Single_Snapshots' %}
                    if($( "#opportunity_zone_show_checkbox" ).prop("checked"))
                        $( "#opportunity_zone_show_checkbox" ).prop( "checked", false ).change();
                    $('#opportunity_zone_show_div').hide()
                    {% endif %}
                    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Both_Analyzer' or userLevel == 'Multi_Anticipator' or userLevel == 'Multi_Analyzer' or userLevel == 'MDM1' %}
                    $('#showMFPPoints30').hide()
                    $('#warningPopupIconForMFPPoints30').hide()
                    layers['MFPPoints30'].hide()
                    $('#showMFPPoints30').attr('src', '/media/icons/MFP.png');
                    {% endif %}
                    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'MDM1' %}
                    $('#showEN').hide()
                    $('#showEDN').hide()
                    {% endif %}
                    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Single_Anticipator' %}
                    $('#showSingleEN').hide()
                    {% endif %}
                }
                if($(this).val() == 'FedBeigeBookDistricts') {
                    $('#beigies_award_div').show()
                    $('#national_summary_div').show()
                    $('#fedBeigeBookDateSelector').next(".select2-container").show();
                } else {
                    $('#beigies_award_div').hide()
                    $('#national_summary_div').hide()
                    $('#fedBeigeBookDateSelector').next(".select2-container").hide();
                }
                if($(this).val().includes('EmergingMarkets2022')) {
                    $('#recovered_markets_show_div').show()
                } else {
                    $('#recovered_markets_show_div').hide()
                    if($( "#recovered_markets_show_checkbox" ).prop("checked"))
                        $( "#recovered_markets_show_checkbox" ).prop( "checked", false ).change();
                }
            });
            $('#fedBeigeBookDateSelector').change(function() {
                fedDate = $(this).val();
                $('#national_summary_button').attr('href', '/media/FedBeigeBook/' + fedDate + '/National.pdf');
                document.getElementById("beigesAwardPlayer").src = '/media/audio/' + fedDate + '/Beigies_' + fedDate + '.mp3';
                $('.beigesAudioDescription').html('Source: The Indicator from Planet Money, NPR, ' + getDateStringFromOptionValue(fedDate));
            });
            $("#zipcode_show_checkbox").change(function(e){
                if (e.target.checked == false) {
                    layers['US_zip_boundaries'].hide()
                } else {
                    layers['US_zip_boundaries'].show()
                }
            })
            $("#recovered_markets_show_checkbox").change(function(e){
                if (e.target.checked == false) {
                    showRecoveredMarkets(false)
                } else {
                    showRecoveredMarkets(true)
                }
            })
            $("#county_show_checkbox").change(function(e){
                if (e.target.checked == false) {
                    layers['US_county_boundaries'].hide()
                } else {
                    layers['US_county_boundaries'].show()
                }
            })
            $("#city_show_checkbox").change(function(e){
                if (e.target.checked == false) {
                    layers['US_cities'].hide()
                } else {
                    layers['US_cities'].show()
                }
            })
            $("#opportunity_zone_show_checkbox").change(function(e){
                if (e.target.checked == false) {
                    layers['OpportunityZone'].hide()
                    opportunityZoneLegendVisible(false)
                } else {
                    layers['OpportunityZone'].show()
                    opportunityZoneLegendVisible(true)
                }
            })
            $("#timeline_slider_show_checkbox").change(function(e){
                if (e.target.checked == false) {
                    $('#timeline_slider_div').hide()
                    stop()
                } else {
                    $('#timeline_slider_div').show()
                }
            })

            $("#disclaimer_agree_check").change(function(e){
                if (e.target.checked == false) {
                    $(".disclaimerAgreeButton").addClass("isDisabledLink")
                } else {
                    $(".disclaimerAgreeButton").removeClass("isDisabledLink")
                }
            })
            $(".disclaimerAgreeButton").click(function () {
                if(!$(this).hasClass("isDisabledLink")){
                    disclaimerConfirm()
                }
            })
            /*{% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' or userLevel == 'MDM1' %}
            $("body").on('click', '#select2-overlayselector-results li:last-child', function (e) {
                $('#exitMarketModal').css('display', 'flex');
            });
            {% endif %}*/
            $('#videoPopupLink').magnificPopup({
                type:'inline',
                midClick: true // Allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source in href.
            });

            $('#videoPopupLink').click(function () {
                Cookies.set('v3_3_{{ user.id }}','watched',{ expires: 150 })
                videoToast.close()
            });

            $('.skipVideo').click(function () {
                Cookies.set('v3_3_{{ user.id }}','watched',{ expires: 150 })
                videoToast.close()
            });

            $('.watchLaterVideo').click(function () {
                videoToast.close()
            });

            $('.emailConfirm').click(function () {
                // remove cookie?
                emailChangeToast.close()
            });

            $('.emailChangeInPopup').click(function () {
                if(validateEmail($('.emailInputInPopup').val())){
                    console.log("Email changed!")
                    changeEmail($('.emailInputInPopup').val())
                } else {
                    $('.emailInputInPopup').focus()
                }
            });

            $('.changeEmailShow').click(function () {
                $(".emailChangeInput").css("display","block");
            });

            function disclaimerConfirm() {
                var csrftoken = Cookies.get('csrftoken');
                $.ajax({
                    method: "POST",
                    headers: { "X-CSRFToken": csrftoken },
                    url: "webmap/disclaimerConfirm/",
                    success: function( msg ) {
                        if(msg == 'success'){
                            $('#legalDisclaimerModal').hide()
                        } else if(msg == 'unAuthenticated'){
                            alert("Please login first.")
                        } else if(msg == 'noPostMethod') {
                            alert("Invalid request type!")
                        } else {
                            alert("Error occured while processing!")
                        }
                    }
                });
            }

            function getEMCategoryFromEMCode(EMCode) {
                switch (EMCode) {
                    case '0':
                        return 'Not Emerging';
                        break;
                    case '3':
                        return 'Continuing Emerging';
                        break;
                    case '2':
                        return 'New Emerging';
                        break;
                    case '9':
                        return 'Insufficient Data';
                        break;
                    default:
                        return 'Unknown';
                }
            }

            function getDateStringFromOptionValue(optionValue) {
                switch (optionValue) {
                    case '20240117':
                        return 'January 17, 2024';
                        break;
                    case '20231129':
                        return 'November 29, 2023';
                        break;
                    case '20231018':
                        return 'October 18, 2023';
                        break;
                    case '20230906':
                        return 'September 6, 2023';
                        break;
                    case '20230712':
                        return 'July 12, 2023';
                        break;
                    case '20230531':
                        return 'May 31, 2023';
                        break;
                    case '20230419':
                        return 'April 19, 2023';
                        break;
                    case '20230308':
                        return 'March 8, 2023';
                        break;
                    case '20230118':
                        return 'January 18, 2023';
                        break;
                    case '20221130':
                        return 'November 30, 2022';
                        break;
                    case '20221019':
                        return 'October 19, 2022';
                        break;
                    case '20220907':
                        return 'September 7, 2022';
                        break;
                    case '20220713':
                        return 'July 13, 2022';
                        break;
                    case '20220601':
                        return 'June 1, 2022';
                        break;
                    case '20220420':
                        return 'April 20, 2022';
                        break;
                    case '20220302':
                        return 'March 2, 2022';
                        break;
                    case '20220112':
                        return 'January 12, 2022';
                        break;
                    case '20211201':
                        return 'December 1, 2021';
                        break;
                    case '20211020':
                        return 'October 20, 2021';
                        break;
                    case '20210908':
                        return 'September 8, 2021';
                        break;
                    case '20210714':
                        return 'July 14, 2021';
                        break;
                    case '20210602':
                        return 'June 2, 2021';
                        break;
                    default:
                        return 'Unknown';
                }
            }

            {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' or userLevel == 'MDM1' %}
            slider.oninput = function() {
                if(timeline_timeInterval_id){
                    stop()
                }
                $("#overlayselector").val(scrollValue_to_selectValue(this.value)).trigger("change");
            }
            {% endif %}
            
            {% else %}
            removeSavedLocationCookies()
            {% endif %}
            $('#base_selector').change(function(e) {
                if (e.target.checked == true) {
                    BaseLayerActions["Streets"]();
                } else {
                    BaseLayerActions["Satellite"]();
                }
            });
            var BaseLayerActions = {
                {% for basemap in basemaps %}
                    {{ basemap.name }}: function(){
                        // remove old basemaps and add this one
                        {% for othermap in basemaps %}
                        map.removeLayer(basemaps["{{ othermap.name }}"]);
                        {% endfor %}
                        map.addLayer(basemaps["{{ basemap.name }}"]);
                        $('#data_show_selector').change()
                        return true;
                    },
                {% endfor %}
            }
            
            {% if user.is_authenticated and userLevel != 'Hiatus' %}
            $('#data_show_selector').change(function(e) {
                if (e.target.checked == true) {
                    DataShowLayerAction["DataShow"]();
                } else {
                    DataShowLayerAction["DataHide"]();
                }
            });
            var DataShowLayerAction = {
                DataShow: function(){
                    {% for basemap in basemaps %}
                    if(map.hasLayer(basemaps["{{ basemap.name }}"]))
                        basemaps["{{ basemap.name }}"].bringToBack();
                    {% endfor %}
                    return true;
                },
                DataHide: function(){
                    {% for basemap in basemaps %}
                    if(map.hasLayer(basemaps["{{ basemap.name }}"]))
                        basemaps["{{ basemap.name }}"].bringToFront();
                    {% endfor %}
                    return true;
                },
            }
            $('#msaTypeSelector').change(function(e) {
                if (e.target.value == 'entire') {
                    MSALayerActions["Only_MSAs"]();
                } else if (e.target.value == 'division') {
                    MSALayerActions["MSA_Division"]();
                } else {
                    MSALayerActions["MSA_Submarket"]();
                }
            });
            var MSALayerActions = {
                Only_MSAs: function(){
                    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' or userLevel == 'MDM1' %}
                    {% for overlay in overlays %}
                    {% if 'Emerging' in overlay.name %}
                    {% if userLevel != 'MDM1' %}
                    sources["{{ overlay.name |remove_whitespace }}"].setQuery('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                    {% elif overlay.name != 'EmergingMarkets2023Q2' and overlay.name != 'EmergingMarkets2023Q1' and overlay.name != 'EmergingMarkets2022Q4' and overlay.name != 'EmergingMarkets2022Q3' and overlay.name != 'EmergingMarkets2022Q2' and overlay.name != 'EmergingMarkets2022Q1' and overlay.name != 'Emerging Markets 2022' and overlay.name != 'Emerging Markets 2021' and overlay.name != 'Emerging Markets 2020' and overlay.name != 'Emerging Markets 2019' and overlay.name != 'Emerging Markets 2018' and overlay.name != 'Emerging Markets 2017' and overlay.name != 'Emerging Markets 2016' and overlay.name != 'Emerging Markets 2015' %}
                    sources["{{ overlay.name |remove_whitespace }}"].setQuery('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                    {% endif %}
                    {% endif %}
                    {% if overlay.name == 'Strong Recession Recovery Markets' or overlay.name == 'MarketGrowthGroups20122022' %}
                    sources["{{ overlay.name |remove_whitespace }}"].setQuery('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                    {% endif %}
                    {% endfor %}
                    {% else %}
                    sources['{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}'].setQuery('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                    {% if userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer' %}
                    sources["StrongRecessionRecoveryMarkets"].setQuery('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                    sources["MarketGrowthGroups20122022"].setQuery('SELECT * FROM final_msa_data where type IN (0,1,2,3,4)');
                    {% endif %}
                    {% endif %}
                },
                MSA_Division: function(){
                    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' or userLevel == 'MDM1' %}
                    {% for overlay in overlays %}
                    {% if 'Emerging' in overlay.name %}
                    {% if userLevel != 'MDM1' %}
                    sources["{{ overlay.name |remove_whitespace }}"].setQuery('SELECT * FROM final_msa_data where type IN (0,1,2,5)');
                    {% elif overlay.name != 'EmergingMarkets2023Q2' and overlay.name != 'EmergingMarkets2023Q1' and overlay.name != 'EmergingMarkets2022Q4' and overlay.name != 'EmergingMarkets2022Q3' and overlay.name != 'EmergingMarkets2022Q2' and overlay.name != 'EmergingMarkets2022Q1' and overlay.name != 'Emerging Markets 2022' and overlay.name != 'Emerging Markets 2021' and overlay.name != 'Emerging Markets 2020' and overlay.name != 'Emerging Markets 2019' and overlay.name != 'Emerging Markets 2018' and overlay.name != 'Emerging Markets 2017' and overlay.name != 'Emerging Markets 2016' and overlay.name != 'Emerging Markets 2015' %}
                    sources["{{ overlay.name |remove_whitespace }}"].setQuery('SELECT * FROM final_msa_data where type IN (0,1,2,5)');
                    {% endif %}
                    {% endif %}
                    {% if overlay.name == 'Strong Recession Recovery Markets' or overlay.name == 'MarketGrowthGroups20122022' %}
                    sources["{{ overlay.name |remove_whitespace }}"].setQuery('SELECT * FROM final_msa_data where type IN (0,1,2,5)');
                    {% endif %}
                    {% endfor %}
                    {% else %}
                    sources['{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}'].setQuery('SELECT * FROM final_msa_data where type IN (0,1,2,5)');
                    {% if userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer' %}
                    sources["StrongRecessionRecoveryMarkets"].setQuery('SELECT * FROM final_msa_data where type IN (0,1,2,5)');
                    sources["MarketGrowthGroups20122022"].setQuery('SELECT * FROM final_msa_data where type IN (0,1,2,5)');
                    {% endif %}
                    {% endif %}
                },
                MSA_Submarket: function(){
                    {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' or userLevel == 'MDM1' %}
                    {% for overlay in overlays %}
                    {% if 'Emerging' in overlay.name %}
                    {% if userLevel != 'MDM1' %}
                    sources["{{ overlay.name |remove_whitespace }}"].setQuery('SELECT * FROM final_msa_data where type = 6');
                    {% elif overlay.name != 'EmergingMarkets2023Q2' and overlay.name != 'EmergingMarkets2023Q1' and overlay.name != 'EmergingMarkets2022Q4' and overlay.name != 'EmergingMarkets2022Q3' and overlay.name != 'EmergingMarkets2022Q2' and overlay.name != 'EmergingMarkets2022Q1' and overlay.name != 'Emerging Markets 2022' and overlay.name != 'Emerging Markets 2021' and overlay.name != 'Emerging Markets 2020' and overlay.name != 'Emerging Markets 2019' and overlay.name != 'Emerging Markets 2018' and overlay.name != 'Emerging Markets 2017' and overlay.name != 'Emerging Markets 2016' and overlay.name != 'Emerging Markets 2015' %}
                    sources["{{ overlay.name |remove_whitespace }}"].setQuery('SELECT * FROM final_msa_data where type = 6');
                    {% endif %}
                    {% endif %}
                    {% if overlay.name == 'Strong Recession Recovery Markets' or overlay.name == 'MarketGrowthGroups20122022' %}
                    sources["{{ overlay.name |remove_whitespace }}"].setQuery('SELECT * FROM final_msa_data where type = 6');
                    {% endif %}
                    {% endfor %}
                    {% else %}
                    sources['{{ emergingMarketLayerNameForAnalyzerAndSnapshots }}'].setQuery('SELECT * FROM final_msa_data where type = 6');
                    {% if userLevel == 'Both_Analyzer' or userLevel == 'Multi_Analyzer' or userLevel == 'Single_Analyzer' %}
                    sources["StrongRecessionRecoveryMarkets"].setQuery('SELECT * FROM final_msa_data where type = 6');
                    sources["MarketGrowthGroups20122022"].setQuery('SELECT * FROM final_msa_data where type = 6');
                    {% endif %}
                    {% endif %}
                },
            }

            function opportunityZoneLegendVisible(isShow){
                if(isShow){
                    $('.legend-content .opportunityLegend').parent().css('margin', '7px 0 0 0')
                    $('.legend-content .opportunityLegend').parent().show()
                }else{
                    $('.legend-content .opportunityLegend').parent().prev().css('margin', '0')
                    $('.legend-content .opportunityLegend').parent().hide()
                }
            }

            if(Cookies.get('location') != undefined  && Cookies.get('latlon') != undefined){
                panto(JSON.parse(Cookies.get('latlon')))
                addMarker(JSON.parse(Cookies.get('latlon')))
                if(Cookies.get("icon_url") != undefined && Cookies.get("catvalue") != undefined) {
                    changeMarkerIcon(Cookies.get("icon_url"),Cookies.get("catvalue"))            
                }
            }

            // set initial marker label show/hide
            if(!isMarkerLabelShowing) {
                $("#toggleAllMarkerLabels").attr('src', '/media/icons/name.png');
            } else {
                $("#toggleAllMarkerLabels").attr('src', '/media/icons/name_hover.png');
                var markerCount = Object.keys(markers).length
                for (var i = 1; i <= markerCount; i++){
                    if(map.hasLayer(markers[i])){
                        clearLabelOfOnePoint(i);
                        markerLabels[i][2] = new L.tooltip({ // 2: default : bottom
                                            permanent: true,
                                            direction: direction_string[2],
                                            className: 'location_name_label',
                                    })
                                    .setContent(allPoints[i].name.replace(/\s*,\s*|\s+,/g, '<br>'))
                                    .setLatLng([
                                        allPoints[i].lat,
                                        allPoints[i].lon
                                    ])
                                    .addTo(map);
                    } else {
                        clearLabelOfOnePoint(i);
                    }
                }
            }

            // set initial folder show/hide icon
            for(var folderID of getAllFolderIDs()) {
                if(Cookies.get('sAMIF'+folderID) == undefined || Cookies.get('sAMIF'+folderID) == 'show'){
                    $(".folderShow_"+folderID).attr('src', '/media/icons/show2.png');
                } else {
                    $(".folderShow_"+folderID).attr('src', '/media/icons/show1.png');
                }
            }
            if(Cookies.get('showAllMarkersNotInFolder') == undefined || Cookies.get('showAllMarkersNotInFolder') == 'show'){
                $(".folderShow_undefined").attr('src', '/media/icons/show2.png');
            } else {
                $(".folderShow_undefined").attr('src', '/media/icons/show1.png');
            }

            // Beigies Award audio initialize
            $('audio').audioPlayer();
            {% endif %}
        }
        {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator' or userLevel == 'MDM1' %}
        var slider = document.getElementById("timeline_slider");
        var value_number = 0
        var timeline_timeInterval_id = null
        var animationBtn = document.getElementById("animationBtn");
        function play(){
            if(!timeline_timeInterval_id){
                animationBtn.innerHTML = '<i class="fa fa-pause" aria-hidden="true"></i>';
                value_number = parseInt(slider.value)
                timeline_timeInterval_id = setInterval(frame, 3000);
                function frame() {
                    {% if userLevel != 'MDM1' %}
                    if (value_number >= 35) {
                    {% else %}
                    if (value_number >= 21) {
                    {% endif %}
                        value_number = 0
                        slider.value = value_number;
                        $("#overlayselector").val(scrollValue_to_selectValue(value_number)).trigger("change");
                    } else {
                        value_number = parseInt(slider.value) + 1;
                        slider.value = value_number;
                        $("#overlayselector").val(scrollValue_to_selectValue(value_number)).trigger("change");
                    }
                }
            }else{
                stop()
            }
        }
        function scrollValue_to_selectValue(scorllValue) {
            if(scorllValue == 0){
                return 'EmergingMarkets1993'
            } else if(scorllValue == 1){
                return 'EmergingMarkets1994'
            } else if(scorllValue == 2){
                return 'EmergingMarkets1995'
            } else if(scorllValue == 3){
                return 'EmergingMarkets1996'
            } else if(scorllValue == 4){
                return 'EmergingMarkets1997'
            } else if(scorllValue == 5){
                return 'EmergingMarkets1998'
            } else if(scorllValue == 6){
                return 'EmergingMarkets1999'
            } else if(scorllValue == 7){
                return 'EmergingMarkets2000'
            } else if(scorllValue == 8){
                return 'EmergingMarkets2001'
            } else if(scorllValue == 9){
                return 'EmergingMarkets2002'
            } else if(scorllValue == 10){
                return 'EmergingMarkets2003'
            } else if(scorllValue == 11){
                return 'EmergingMarkets2004'
            } else if(scorllValue == 12){
                return 'EmergingMarkets2005'
            } else if(scorllValue == 13){
                return 'EmergingMarkets2006'
            } else if(scorllValue == 14){
                return 'EmergingMarkets2007'
            } else if(scorllValue == 15){
                return 'EmergingMarkets2008'
            } else if(scorllValue == 16){
                return 'EmergingMarkets2009'
            } else if(scorllValue == 17){
                return 'EmergingMarkets2010'
            } else if(scorllValue == 18){
                return 'EmergingMarkets2011'
            } else if(scorllValue == 19){
                return 'EmergingMarkets2012'
            } else if(scorllValue == 20){
                return 'EmergingMarkets2013'
            } else if(scorllValue == 21){
                return 'EmergingMarkets2014'
            }
            {% if userLevel != 'MDM1' %}
            else if(scorllValue == 22){
                return 'EmergingMarkets2015'
            } else if(scorllValue == 23){
                return 'EmergingMarkets2016'
            } else if(scorllValue == 24){
                return 'EmergingMarkets2017'
            } else if(scorllValue == 25){
                return 'EmergingMarkets2018'
            } else if(scorllValue == 26){
                return 'EmergingMarkets2019'
            } else if(scorllValue == 27){
                return 'EmergingMarkets2020'
            } else if(scorllValue == 28){
                return 'EmergingMarkets2021'
            } else if(scorllValue == 29){
                return 'EmergingMarkets2022'
            } else if(scorllValue == 30){
                return 'EmergingMarkets2022Q1'
            } else if(scorllValue == 31){
                return 'EmergingMarkets2022Q2'
            } else if(scorllValue == 32){
                return 'EmergingMarkets2022Q3'
            } else if(scorllValue == 33){
                return 'EmergingMarkets2022Q4'
            } else if(scorllValue == 34){
                return 'EmergingMarkets2023Q1'
            } else if(scorllValue == 35){
                return 'EmergingMarkets2023Q2'
            }
            {% endif %}
        }
        function stop(){
            clearInterval(timeline_timeInterval_id)
            timeline_timeInterval_id = null
            animationBtn.innerHTML = '<i class="fa fa-play" aria-hidden="true"></i>';
        }
        {% endif %}

        function enLegendVisible(isShow){
            if(isShow){
                $('.legend-content .enLegend').parent().css('margin', '7px 0 0 0')
                $('.legend-content .enLegend').parent().show()
                $('.legend-content .dnLegend').parent().css('margin', '7px 0 0 0')
                $('.legend-content .dnLegend').parent().show()
            }else{
                $('.legend-content .enLegend').parent().hide()
                $('.legend-content .dnLegend').parent().hide()
            }
        }

        function clickBeigeAudioButton(){
            if(fedDate == '20220302' || fedDate == '20220420' || fedDate == '20231129'){
                document.getElementById('beigiesAwardNotAvailableModal').style.display='flex';
            } else {
                document.getElementById('beigiesAwardModal').style.display='flex';
            }
        }
        function closeBeigeModel(){
            document.getElementById('beigiesAwardModal').style.display='none';
            document.getElementById('beigesAwardPlayer').pause();
            if ($(".audioplayer").hasClass('audioplayer-playing')) {
                $(".audioplayer").removeClass('audioplayer-playing');
            }
        }
        function showRecoveredMarkets(isShow) {
            {% if user.is_superuser or userLevel == 'Both_Anticipator' or userLevel == 'Multi_Anticipator' or userLevel == 'Single_Anticipator'%}
            if(isShow == true) {
                if (isColorBlind == false) {
                    styles['EmergingMarkets2022'].setContent(layer_css.EmergingMarkets2022.normal + layer_css.EmergingMarkets2022.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q1'].setContent(layer_css.EmergingMarkets2022Q1.normal + layer_css.EmergingMarkets2022Q1.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q2'].setContent(layer_css.EmergingMarkets2022Q2.normal + layer_css.EmergingMarkets2022Q2.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q3'].setContent(layer_css.EmergingMarkets2022Q3.normal + layer_css.EmergingMarkets2022Q3.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q4'].setContent(layer_css.EmergingMarkets2022Q4.normal + layer_css.EmergingMarkets2022Q4.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                } else {
                    styles['EmergingMarkets2022'].setContent(layer_css.EmergingMarkets2022.colorBlindFriendly + layer_css.EmergingMarkets2022.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q1'].setContent(layer_css.EmergingMarkets2022Q1.colorBlindFriendly + layer_css.EmergingMarkets2022Q1.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q2'].setContent(layer_css.EmergingMarkets2022Q2.colorBlindFriendly + layer_css.EmergingMarkets2022Q2.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q3'].setContent(layer_css.EmergingMarkets2022Q3.colorBlindFriendly + layer_css.EmergingMarkets2022Q3.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q4'].setContent(layer_css.EmergingMarkets2022Q4.colorBlindFriendly + layer_css.EmergingMarkets2022Q4.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                }
            } else {
                if (isColorBlind == false) {
                    styles['EmergingMarkets2022'].setContent(layer_css.EmergingMarkets2022.normal)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q1'].setContent(layer_css.EmergingMarkets2022Q1.normal)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q2'].setContent(layer_css.EmergingMarkets2022Q2.normal)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q3'].setContent(layer_css.EmergingMarkets2022Q3.normal)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q4'].setContent(layer_css.EmergingMarkets2022Q4.normal)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                } else {
                    styles['EmergingMarkets2022'].setContent(layer_css.EmergingMarkets2022.colorBlindFriendly)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q1'].setContent(layer_css.EmergingMarkets2022Q1.colorBlindFriendly)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q2'].setContent(layer_css.EmergingMarkets2022Q2.colorBlindFriendly)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q3'].setContent(layer_css.EmergingMarkets2022Q3.colorBlindFriendly)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                    styles['EmergingMarkets2022Q4'].setContent(layer_css.EmergingMarkets2022Q4.colorBlindFriendly)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                }
            }
            {% elif userLevel == 'MDM1' %}
            if(isShow == true) {
                if (isColorBlind == false) {
                    styles['EmergingMarkets2014'].setContent(layer_css.EmergingMarkets2014.normal + layer_css.EmergingMarkets2022.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                } else {
                    styles['EmergingMarkets2014'].setContent(layer_css.EmergingMarkets2014.colorBlindFriendly + layer_css.EmergingMarkets2022.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                }
            } else {
                if (isColorBlind == false) {
                    styles['EmergingMarkets2014'].setContent(layer_css.EmergingMarkets2014.normal)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                } else {
                    styles['EmergingMarkets2014'].setContent(layer_css.EmergingMarkets2014.colorBlindFriendly)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                }
            }
            {% else %}
            if(isShow == true) {
                if (isColorBlind == false) {
                    styles['EmergingMarkets2022'].setContent(layer_css.EmergingMarkets2022.normal + layer_css.EmergingMarkets2022.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                } else {
                    styles['EmergingMarkets2022'].setContent(layer_css.EmergingMarkets2022.colorBlindFriendly + layer_css.EmergingMarkets2022.RM_Symbol)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                }
            } else {
                if (isColorBlind == false) {
                    styles['EmergingMarkets2022'].setContent(layer_css.EmergingMarkets2022.normal)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                } else {
                    styles['EmergingMarkets2022'].setContent(layer_css.EmergingMarkets2022.colorBlindFriendly)
                        .catch(() => {
                            console.error('Error updating the cartoCSS for the layer');
                        });
                }
            }
            {% endif %}
        }
        function validateEmail(emailFieldValue){
            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

            if (reg.test(emailFieldValue) == false) 
            {
                $(".emailErrorMessage").html("<span style='color:#7b0006;'>Invalid Email</span>")
                $(".emailChangeInPopup").addClass('isDisabledLink')
                return false;
            }
            $(".emailChangeInPopup").removeClass('isDisabledLink')
            $(".emailErrorMessage").html("")
            return true;
        }

        function changeEmail(email) {
            var csrftoken = Cookies.get('csrftoken');
            $.ajax({
                method: "POST",
                headers: { "X-CSRFToken": csrftoken },
                url: "webmap/changeEmail/",
                data: { email },
                success: function( msg ) {
                    if(msg == 'success'){
                        console.log("Email changed!")
                        emailChnagedSuccessfullyAfter(email)
                    } else if(msg == 'unAuthenticated') {
                        console.log("Non authenticated user request!")
                        $(".emailErrorMessage").html("<span style='color:#7b0006;'>Non authenticated user request!</span>")
                        $(".emailChangeInPopup").addClass('isDisabledLink')
                    } else if(msg == 'noPostMethod') {
                        console.log("Invalid request type!")
                        $(".emailErrorMessage").html("<span style='color:#7b0006;'>Invalid request type!</span>")
                        $(".emailChangeInPopup").addClass('isDisabledLink')
                    } else {
                        console.log(msg)
                        $(".emailErrorMessage").html("<span style='color:#7b0006;'>" + msg + "</span>")
                        $(".emailChangeInPopup").addClass('isDisabledLink')
                    }
                }
            });
        }

        function emailChnagedSuccessfullyAfter(email) {
            emailChangeToast.close()
            $.toast({            
                text: `Your email has changed successfully!<br>
                Your current email is <span style='color: #57ff8b;'>`+ email +`</span>`, // Text that is to be shown in the toast
                heading: '<span style="text-align: center;">Email changed</span>', // Optional heading to be shown on the toast
                icon: 'info', // Type of toast icon
                showHideTransition: 'slide', // fade, slide or plain            
                hideAfter: false, // false to make it sticky or number representing the miliseconds as time after which toast needs to be hidden
                stack: 5, // false if there should be only one toast at a time or a number representing the maximum number of toasts to be shown at a time
                position: 'bottom-center',
                textAlign: 'center',  // Text alignment i.e. left, right or center
                bgColor: '#3c763d',
                textColor: '#dff0d8'
            })
        }

        function refreshPage() {
            location.reload()
        }

        function mfpWarningPopup() {
            $.toast({
                heading: "Beta version: Multifamily Properties",
                text: 'Beta, currently available in 30 Largest MSAs, does not include ALL multifamily properties.  Properties with a just a street address as the "Name" should NOT be used as they are very likely to be smaller than 5 units.',
                icon: 'error', // Type of toast icon
                showHideTransition: 'fade', // fade, slide or plain
                allowToastClose: true, // Boolean value true or false
                hideAfter: 20000, // false to make it sticky or number representing the miliseconds as time after which toast needs to be hidden
                stack: 5, // false if there should be only one toast at a time or a number representing the maximum number of toasts to be shown at a time
                position: 'top-right', // bottom-left or bottom-right or bottom-center or top-left or top-right or top-center or mid-center or an object representing the left, right, top, bottom values
                textAlign: 'left', 
                loaderBg: '#9EC600',
                bgColor: '#a94442'
            });
        }

        {% if user.is_authenticated and userLevel == 'Hiatus' %}
        document.getElementById('HiatusModal').style.display='flex'
        {% endif %}
        // you could use $(window).load(main);
        //window.onload = main;
        //$(window).load(main);
    </script>
{% endblock %}

{% block drawer %}
{% include "webmap/drawer.html" %}
{% endblock %}

{% block map %}
    <div id="map" class="map"></div>
    <div class="legend" style='display: none;'>
        <div class="legend-content"></div>
    </div>
{% endblock %}

{% block very_bottom %}
{% if lat and lon %}

{% endif %}
{% endblock %}