{% extends 'profile/_base_profile.html' %}{% load humanize lookup staticfiles %}

{% block head_title %}{{ geography.this.short_name }} - {{ block.super }}{% endblock %}

{% block head_meta_description %}Population data and election figures from {{ geography.this.short_name}}, broken down by category: Demographics, Service delivery, Economics and Education.{% endblock %}

{% block head_facebook_tags %}
    <meta property="og:title" content="Wazimap profile: {% firstof geography.this.full_name geography.this.short_name %}" />
    <meta property="og:site_name" content="Wazimap" />
    <meta property="og:url" content="http://wazimap.co.za/profiles/{{ geography.this.full_geoid }}/" />
    <meta property="og:description" content="Population data and election figures from {{ geography.this.short_name}}, broken down by category: Demographics, Service delivery, Economics and Education." />
    <meta property="og:type" content="article" />
    {#}<meta property="og:image" content="" />{#}
{% endblock %}

{% block head_css_extra %}
<link rel="stylesheet" href="{% static 'css/vendor/leaflet-0.6.4.css' %}" />
<!--[if lte IE 8]>
    <link rel="stylesheet" href="{% static 'css/vendor/leaflet-0.6.4.ie.css' %}" />
<![endif]-->
<link href="{% static 'css/vendor/leaflet.label.css' %}" rel="stylesheet" />
{% endblock %}
{% block body_id %}profile{% endblock %}

{% block header_content %}
<div id="cover-map" class="clearfix">
    <div id="slippy-map"></div>
    <div id="cover-profile" class="wrapper">
        <article class="clearfix column-half">
            <header id="header-box" class="column-full">
                <h1 class="title">{{ geography.this.short_name }}</h1>
                <p class="caption">
                  {{ geography.this.geo_level|capfirst }}
                  {% if geography.this.geo_level != 'country' %}
                      in
                      {% for level in geography.parents_ordering %}
                        {% with g=geography.parents|get:level %}
                          <a href="/profiles/{{ g.full_geoid }}/">{{ g.short_name }}</a>{% if not forloop.last %},{%endif%}
                        {% endwith %}
                      {% endfor %}
                  {% endif %}
                </p>
            </header>
            <div class="column-half">
                <div class="stat">
                    <span class="primary">
                        <span class="value">{{ demographics.total_population.values.this|floatformat:"0" }}</span>
                        <span class="name">Population</span>
                    </span>
                </div>
            </div>
            {% if geography.this.square_kms %}
            <div class="column-half">
                <div class="stat">
                    <span class="secondary">
                        <span class="value">{% if geography.this.square_kms < 1.0 %}{{ geography.this.square_kms|floatformat:"3" }}{% else %}{{ geography.this.square_kms|floatformat:"1" }}{% endif %}</span>
                        <span class="name"> square kilometres</span>
                    </span>
                    {% if demographics.population_density.values.this %}
                    <span class="secondary">
                        <span class="value">{{ demographics.population_density.values.this|floatformat:"1" }}</span>
                        <span class="name"> people per square kilometre</span>
                    </span>
                    {% endif %}
                </div>
            </div>
            {% endif %}

            {% if geography.this.show_extra_links %}
                {% include "profile/_blocks/_header_extra_links.html" %}
            {% endif %}

            <div class="column-full">
                <p class="caption">
                    <strong>Census data:</strong> 2011
                    {% if crime %}
                    <br>
                    <strong>Crime data:</strong> {{ crime.dataset }}</p>
                    {% endif %}
                </p>
            </div>
        </article>
    </div>
</div>
{% endblock %}

{% block content %}
{% comment %}
<section class="clearfix" id="query-topic-picker">
    <h2>Find data for this place</h2>
    <div class="typeahead-container">
        <input name="topic_select" id="topic-select" type="text" placeholder="Search by table or column name..." autocomplete="off">
    </div>
</section>
{% endcomment %}

<section class="clearfix" id="compare-place-picker">
    <h2>Compare this place with another</h2>
    <div class="typeahead-container">
        <input name="place_select" id="compare-place-select" type="text" placeholder="Start typing a place name or address to compare with..." autocomplete="off">
    </div>
</section>

<div id="share-this-page" style="text-align: right;">
    <!-- AddThis Button BEGIN -->
    <div class="addthis_toolbox addthis_default_style " style="margin:2px 0 10px 5px;float:right;width:175px;">
        <a class="addthis_button_facebook"></a>
        <a class="addthis_button_twitter"></a>
        <a class="addthis_button_gmail"></a>
        <a class="addthis_counter addthis_bubble_style" style="margin-left: 5px;"></a>
    </div>
    <!-- AddThis Button END -->
    Share this page:
</div>

<p class="explain">Interact with charts and statistics for additional information.</p>

<article id="elections" class="clearfix">
    <header class="section-contents">
        <h1>Elections</h1>
    </header>
    <div class="section-container">

        {% for key in elections %}
        {% with elections|get:key as election_data %}
        <section class="clearfix stat-row">
            <h2 class="header-for-columns"><a class="permalink" href="#{{ election_data.name }}" id="{{ election_data.name }}">{{ election_data.name.capitalize }} <i class="fa fa-link"></i></a></h2>
            <div class="column-quarter">
                {% include 'profile/_blocks/_stat_list.html' with stat=election_data.registered_voters|get:"Number of registered voters" stat_type='number' %}
            </div>
            <div class="column-quarter">
                {% include 'profile/_blocks/_stat_list.html' with stat=election_data.total_votes|get:"Of registered voters cast their vote" stat_type='percentage' %}
            </div>
            <div class="column-half" id="chart-histogram-elections-{{ key }}-party_distribution" data-stat-type="scaled-percentage" data-chart-title="Voters by party"></div>
        </section>
        {% endwith %}
        {% endfor %}

        {% if geography.this.geo_level == 'country' %}
            <section class="clearfix stat-row">
                <h2 class="header-for-columns"><a class="permalink" href="#elections_2014_media" id="elections_2014_media">Elections 2014 Media Coverage<i class="fa fa-link"></i></a></h2>
                <div class="column-half" id="chart-pie-elections-national_2014-media_coverage-genders" data-stat-type="scaled-percentage" data-chart-title="Gender of politicians quoted by the media"></div>
                <div class="column-half" id="chart-histogram-elections-national_2014-media_coverage-parties" data-stat-type="scaled-percentage" data-chart-title="Media coverage by political party"></div>
            </section>
        {% endif %}

    </div>
</article>

<article id="demographics" class="clearfix">
    <header class="section-contents">
        <h1>Demographics</h1>
    </header>
    <div class="section-container">

        <section class="clearfix stat-row">
            <h2 class="header-for-columns"><a class="permalink" href="#age" id="age">Age <i class="fa fa-link"></i></a></h2>
            <div class="column-quarter">
                {% include 'profile/_blocks/_stat_list.html' with stat=demographics.median_age stat_type='number' %}
            </div>
            <div class="column-half" id="chart-histogram-demographics-age_group_distribution" data-stat-type="scaled-percentage" data-chart-title="Population by age range"></div>
            <div class="column-quarter" id="chart-pie-demographics-age_category_distribution" data-stat-type="percentage" data-initial-sort="-value" data-chart-title="Population by age category"></div>
        </section>
        <section class="clearfix stat-row">
            <h2 class="header-for-columns"><a class="permalink" href="#pop_count" id="pop_count">Population <i class="fa fa-link"></i></a></h2>
            <div class="column-quarter">
                {% include 'profile/_blocks/_stat_list.html' with stat=demographics.total_population stat_type='number' %}
            </div>
            <div class="column-half">
                <div id="chart-column-demographics-population_group_distribution" data-stat-type="scaled-percentage" data-chart-title="Population group"></div>
            </div>
            <div class="column-quarter">
                <div id="chart-pie-demographics-sex_ratio" data-stat-type="percentage" data-initial-sort="-value" data-chart-title="Sex"></div>
            </div>
        </section>
        <section class="clearfix stat-row">
            <h2 class="header-for-columns"><a class="permalink" href="#language" id="language">Language <i class="fa fa-link"></i></a></h2>
            <div class="column-quarter">
                {% include 'profile/_blocks/_stat_list.html' with stat=demographics.language_most_spoken stat_type='name' stat_name='Language most spoken at home' %}
            </div>
            <div class="column-three-quarters">
                <div id="chart-histogram-demographics-language_distribution" data-stat-type="scaled-percentage" data-chart-title="Population by language most spoken at home"></div>
            </div>
        </section>
        <section class="clearfix stat-row">
            <h2 class="header-for-columns"><a class="permalink" href="#migration" id="migration">Migration <i class="fa fa-link"></i></a></h2>
            <div class="column-quarter">
                {% include 'profile/_blocks/_stat_list.html' with stat=demographics.born_in_south_africa stat_type='percentage' stat_name='Born in South Africa' %}
            </div>
            <div class="column-half" id="chart-column-demographics-province_of_birth_distribution" data-stat-type="scaled-percentage" data-chart-title="Province of birth"></div>
            <div class="column-quarter" id="chart-pie-demographics-region_of_birth_distribution" data-stat-type="scaled-percentage" data-chart-title="Region of birth"></div>
        </section>
        <section class="clearfix stat-row">
            <h2 class="header-for-columns"><a class="permalink" href="#citizenship" id="citizenship">Citizenship <i class="fa fa-link"></i></a></h2>
            <div class="column-quarter">
                {% include 'profile/_blocks/_stat_list.html' with stat=demographics.citizenship_south_african stat_type='percentage' stat_name='South African citizens' %}
            </div>
            <div class="column-quarter" id="chart-pie-demographics-citizenship_distribution" data-stat-type="percentage" data-chart-title="South African citizenship"></div>
        </section>

    </div>
</article>

<article id="service_delivery" class="clearfix">
    <header class="section-contents">
        <h1>Households</h1>
    </header>
    <div class="section-container">

        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#households" id="households">Households <i class="fa fa-link"></i></a></h2>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=households.total_households stat_type='number' %}
            </div>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=households.informal stat_type='percentage' %}
            </div>
            <div class="column-third" id="chart-pie-households-type_of_dwelling_distribution" data-stat-type="percentage" data-chart-title="Households by type of dwelling"></div>
        </section>
        <section class="clearfix stat-row grouped-row">
            <h2><a class="permalink" href="#tenure" id="tenure">Household ownership <i class="fa fa-link"></i></a></h2>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=households.owned stat_type='percentage' %}
            </div>
            <div class="column-third" id="chart-pie-households-tenure_distribution" data-stat-type="percentage" data-initial-sort="-value" data-chart-title="Households by ownership"></div>
        </section>
        <section class="clearfix stat-row grouped-row">
            <h2><a class="permalink" href="#household-head" id="household-head">Head of household <i class="fa fa-link"></i></a></h2>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=households.head_of_household.female stat_type='percentage' %}
            </div>
            <div class="column-third" id="chart-pie-households-head_of_household-gender_distribution" data-stat-type="percentage" data-initial-sort="-value" data-chart-title="Head of household by gender"></div>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=households.head_of_household.under_18 stat_type='number' %}
            </div>
        </section>
        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#household-income" id="household-income">Annual household income<i class="fa fa-link"></i></a></h2>
            <aside>
                Average annual household income is a median estimate, be careful with this value.
            </aside>
            <div class="column-quarter">
                {% include 'profile/_blocks/_stat_list.html' with stat=households.median_annual_income stat_type='dollar' %}
            </div>
            <div class="column-three-quarters" id="chart-column-households-annual_income_distribution" data-stat-type="scaled-percentage" data-chart-title="Annual household income"></div>
        </section>
        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#household_goods" id="household_goods">Household goods <i class="fa fa-link"></i></a></h2>
            <div class="column-full" id="chart-column-households-household_goods" data-stat-type="scaled-percentage" data-chart-title="Goods available by household"></div>
        </section>
    </div>
</article>

<article id="service_delivery" class="clearfix">
    <header class="section-contents">
        <h1>Service delivery</h1>
    </header>
    <div class="section-container">

        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#water" id="water">Water <i class="fa fa-link"></i></a></h2>
            <aside>
            </aside>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=service_delivery.percentage_water_from_service_provider stat_type='percentage' %}
            </div>
            <div class="column-third" id="chart-pie-service_delivery-water_source_distribution" data-stat-type="percentage" data-chart-title="Population by water source"></div>
        </section>

        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#electricity" id="electricity">Electricity <i class="fa fa-link"></i></a></h2>
            <aside>
            </aside>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=service_delivery.percentage_electricity_access stat_type='percentage' %}
            </div>
            <div class="column-third" id="chart-pie-service_delivery-electricity_access_distribution" data-stat-type="percentage" data-chart-title="Population by electricity usage"></div>
        </section>

        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#toilets" id="toilets">Toilet facilities <i class="fa fa-link"></i></a></h2>
            <aside>
            </aside>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=service_delivery.percentage_flush_toilet_access stat_type='percentage' %}
            </div>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=service_delivery.percentage_no_toilet_access stat_type='percentage' %}
            </div>
            <div class="column-third" id="chart-pie-service_delivery-toilet_facilities_distribution" data-stat-type="percentage" data-chart-title="Population by toilet facilities"></div>
        </section>

        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#refuse" id="refuse">Refuse disposal <i class="fa fa-link"></i></a></h2>
            <aside>
            </aside>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=service_delivery.percentage_ref_disp_from_service_provider stat_type='percentage' %}
            </div>
            <div class="column-third" id="chart-pie-service_delivery-refuse_disposal_distribution" data-chart-title="Population by refuse disposal" data-stat-type="percentage"></div>
        </section>

    </div>
</article>

<article id="economics" class="clearfix">
    <header class="section-contents">
        <h1>Economics</h1>
    </header>
    <div class="section-container">
        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#employment" id="employment">Employment <i class="fa fa-link"></i></a></h2>
            <aside>
            </aside>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=economics.employment_status.Employed stat_type='percentage' %}
            </div>
            <div class="column-third" id="chart-pie-economics-employment_status" data-chart-title="Population by employment status" data-stat-type="percentage" data-initial-sort="-value" data-qualifier="Universe: {{ economics.employment_status.metadata.universe }}"></div>
            <div class="column-third" id="chart-pie-economics-sector_type_distribution" data-chart-title="Sector of employment" data-stat-type="percentage" data-initial-sort="-value" data-qualifier="Universe: {{ economics.sector_type_distribution.metadata.universe }}"></div>
        </section>
        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#income" id="income">Monthly income <i class="fa fa-link"></i></a></h2>
            <aside>
                Average monthly income is a median estimate, be careful with this value.
            </aside>
            <div class="column-quarter">
                {% include 'profile/_blocks/_stat_list.html' with stat=economics.median_individual_income stat_type='dollar' %}
            </div>
            <div class="column-three-quarters" id="chart-histogram-economics-individual_income_distribution" data-chart-title="Employees by monthly income" data-stat-type="scaled-percentage" data-qualifier="Universe: {{ economics.individual_income_distribution.metadata.universe }}"></div>
        </section>
        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#internet" id="internet">Internet access <i class="fa fa-link"></i></a></h2>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=economics.internet_access stat_type='percentage' %}
            </div>
            <div class="column-third" id="chart-pie-economics-internet_access_distribution" data-chart-title="Primary means of internet access" data-stat-type="scaled-percentage" data-initial-sort="-value"></div>
        </section>
    </div>
</article>

<article id="education" class="clearfix">
    <header class="section-contents">
        <h1>Education</h1>
    </header>
    <div class="section-container">

        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#highest-educational-level" id="highest-educational-level">Educational level <i class="fa fa-link"></i></a></h2>
            <aside>
            </aside>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=education.educational_attainment.percent_get_or_higher stat_type='percentage' %}
            </div>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=education.educational_attainment.percent_fet_or_higher stat_type='percentage' %}
            </div>
        </section>
        <section class="clearfix stat-row">
            <div class="column-full" id="chart-histogram-education-educational_attainment_distribution" data-stat-type="scaled-percentage" data-chart-title="Population by highest educational level" data-qualifier="Universe: {{ education.educational_attainment_distribution.metadata.universe }}"></div>
        </section>

    </div>
</article>

<article id="children" class="clearfix">
    <header class="section-contents">
        <h1>Children</h1>
    </header>
    <div class="section-container">

        <section class="clearfix stat-row">
            <h2 class="header-for-columns"><a class="permalink" href="#child_pop_count" id="child_pop_count">Child population <i class="fa fa-link"></i></a></h2>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=children.demographics.total_children stat_type='number' %}
            </div>
            <div class="column-third">
                <div id="chart-pie-children-demographics-gender_distribution" data-stat-type="percentage" data-chart-title="Children under 18 by gender" data-qualifier="Universe: {{ children.demographics.gender_distribution.metadata.universe }}"></div>
            </div>
            <div class="column-third">
                <div id="chart-pie-children-demographics-child_adult_distribution" data-stat-type="percentage" data-chart-title="Population by age category"></div>
            </div>
        </section>
        <section class="clearfix stat-row">
            <h2 class="header-for-columns"><a class="permalink" href="#parents" id="parents">Parents <i class="fa fa-link"></i></a></h2>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=children.demographics.percent_no_parent stat_type='percentage' %}
            </div>
            <div class="column-third">
                <div id="chart-pie-children-demographics-parental_survival_distribution" data-stat-type="percentage" data-initial-sort="-value" data-chart-title="Children 14 and under by biological parental survival" data-qualifier="Universe: {{ children.demographics.parental_survival_distribution.metadata.universe }}"></div>
            </div>
        </section>
        {% if crime %}
        <section class="clearfix stat-row">
            <aside>
                Crime information is only currently available at national and provincial levels.
            </aside>
            <h2 class="header-for-columns"><a class="permalink" href="#crimes_children" id="crimes_children">Crimes against children <i class="fa fa-link"></i></a></h2>
            <div class="column-full">
                {% include 'profile/_blocks/_stat_list.html' with stat=crime.crime_against_children stat_type='number' %}
            </div>
        </section>
        {% endif %}
        <section class="clearfix stat-row">
            <h2 class="header-for-columns"><a class="permalink" href="#child_school" id="child_school">School attendance <i class="fa fa-link"></i></a></h2>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=children.school.percent_school_attendance stat_type='percentage' %}
            </div>
            <div class="column-third">
                <div id="chart-pie-children-school-school_attendance_distribution" data-stat-type="percentage" data-chart-title="Children 5 to 17 by school attendance" data-initial-sort="-value" data-qualifier="Universe: {{ children.school.school_attendance_distribution.metadata.universe }}"></div>
            </div>
        </section>
        <section class="clearfix stat-row">
            <div class="column-full">
                <div id="chart-column-children-school-education17_distribution" data-stat-type="scaled-percentage" data-chart-title="17-year-olds by highest educational level" data-qualifier="Universe: {{ children.school.education17_distribution.metadata.universe }}"></div>
            </div>
        </section>
        <section class="clearfix stat-row">
            <h2 class="header-for-columns"><a class="permalink" href="#child_employment" id="child_employment">Employment of 15- to 17-year-olds <i class="fa fa-link"></i></a></h2>
            <aside>
                Average monthly income is a median estimate, be careful with this value.
            </aside>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=children.employment.median_income stat_type='dollar' %}
            </div>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=children.employment.percent_in_labour_force stat_type='percentage' %}
            </div>
            <div class="column-third">
                <div id="chart-pie-children-employment-employment_distribution" data-stat-type="percentage" data-chart-title="15- to 17-year olds by employment status" data-initial-sort="-value" data-qualifier="Universe: {{ children.employment.employment_distribution.metadata.universe }}"></div>
            </div>
        </section>

    </div>
</article>

<article id="child_headed_households" class="clearfix">
    <header class="section-contents">
        <h1>Child-headed households</h1>
    </header>
    <div class="section-container">

        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#child-households" id="child-households">Households headed by children under 18 years old<i class="fa fa-link"></i></a></h2>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=child_households.total_households stat_type='number' %}
            </div>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=child_households.informal stat_type='percentage' %}
            </div>
            <div class="column-third" id="chart-pie-child_households-type_of_dwelling_distribution" data-stat-type="percentage" data-chart-title="Child-headed households by type of dwelling" data-initial-sort="-value" data-qualifier="Universe: {{ child_households.type_of_dwelling_distribution.metadata.universe }}"></div>
        </section>
        <section class="clearfix stat-row grouped-row">
            <h2><a class="permalink" href="#child-household-head" id="child-household-head">Head of household <i class="fa fa-link"></i></a></h2>
            <div class="column-third">
                {% include 'profile/_blocks/_stat_list.html' with stat=child_households.head_of_household.female stat_type='percentage' %}
            </div>
            <div class="column-third" id="chart-pie-child_households-head_of_household-gender_distribution" data-stat-type="percentage" data-initial-sort="-value" data-chart-title="Head of child-headed household by gender" data-initial-sort="-value" data-qualifier="Universe: {{ child_households.head_of_household.gender_distribution.metadata.universe }}"></div>
        </section>
        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#child-household-income" id="child-household-income">Annual household income <i class="fa fa-link"></i></a></h2>
            <aside>
                Average annual household income is a median estimate, be careful with this value.
            </aside>
            <div class="column-quarter">
                {% include 'profile/_blocks/_stat_list.html' with stat=child_households.median_annual_income stat_type='dollar' %}
            </div>
            <div class="column-three-quarters" id="chart-column-child_households-annual_income_distribution" data-stat-type="scaled-percentage" data-chart-title="Annual child-headed household income" data-qualifier="Universe: {{ child_households.annual_income_distribution.metadata.universe }}"></div>
        </section>
        <section class="clearfix stat-row">
            <h2><a class="permalink" href="#child-household-size" id="child-household-size">Household size <i class="fa fa-link"></i></a></h2>
            <div class="column-full" id="chart-grouped_column-child_households-household_size_distribution" data-stat-type="scaled-percentage" data-chart-title="Size of household by age of household head"></div>
        </section>
    </div>
</article>

{% endblock %}

{% block body_javascript_extra %}{{ block.super }}
<script src="{% static 'js/vendor/leaflet-0.6.4.js' %}"></script>
<script src="{% static 'js/vendor/leaflet.label.js' %}"></script>
<script src="{% static 'js/charts.js' %}"></script>
<script src="{% static 'js/head2head.js' %}"></script>
<script type="text/javascript">

var drawMaps = function() {
    var geo = profileData.geography;
    var geo_level = geo.this.geo_level;
    var geo_code = geo.this.geo_code;
    var mapit_type = MAPIT_LEVEL_TYPES[geo_level];
    var mapit_simplify = MAPIT_LEVEL_SIMPLIFY[mapit_type];

    // draw a map
    var allowMapDrag = (browserWidth > 480) ? true : false;
    var map = L.map('slippy-map', {
        scrollWheelZoom: false,
        zoomControl: false,
        doubleClickZoom: false,
        boxZoom: false,
        keyboard: false,
        dragging: allowMapDrag,
        touchZoom: allowMapDrag
    });

    if (allowMapDrag) {
        map.addControl(new L.Control.Zoom({
            position: 'topright'
        }));
    }

    // add imagery
    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
      subdomains: 'abc',
      maxZoom: 17
    }).addTo(map);

    // add demarcation boundaries
    if (geo_level == 'country') {
        map.setView({lat: -28.4796, lng: 10.698445}, 5);
    } else {
        d3.json("http://mapit.code4sa.org/area/MDB:" + geo_code +
                ".geojson?generation=1&simplify_tolerance=" + mapit_simplify +
                "&type=" + mapit_type, function(error, geojson) {
          if (error) return console.warn(error);

          var featureLayer = L.geoJson(geojson, {
              style: {
                  "fillColor": "#66c2a5",
                  "color": "#777",
                  "weight": 2,
                  "opacity": 0.3,
                  "fillOpacity": 0.5,
                  "clickable": false
              }
          });
          map.addLayer(featureLayer);
          var objBounds = featureLayer.getBounds();

          if (browserWidth > 768) {
              var z;
              for(z = 16; z > 2; z--) {
                  var swPix = map.project(objBounds.getSouthWest(), z),
                      nePix = map.project(objBounds.getNorthEast(), z),
                      pixWidth = Math.abs(nePix.x - swPix.x),
                      pixHeight = Math.abs(nePix.y - swPix.y);
                  if (pixWidth <  500 && pixHeight < 400) {
                      break;
                  }
              }

              map.setView(featureLayer.getBounds().getCenter(), z);
              map.panBy([-270, 0], {animate: false});
          } else {
              map.fitBounds(featureLayer.getBounds());
          }
        });
    }

    // load surrounding map shapes

    // [level, code] pairs
    var levels = _.map(geo.parents_ordering, function(level) {
        return [level, geo.parents[level].geo_code];
    });
    levels.unshift([geo_level, geo_code]);
    if (geo.this.child_level) {
        levels.unshift([geo.this.child_level, '']);
    }

    for (var i = 0; i < levels.length; i++) {
        var level = levels[i][0],
            code  = levels[i][1];
        var mapit_level = MAPIT_LEVEL_TYPES[level];

        // For each level, add map shapes for that level, limited to within the
        // parent level (eg. wards within a municipality).

        (function(level, code) {
            if (level == 'country') {
                return;
            }

            var parent = levels[i+1];
            parent = MAPIT_LEVEL_TYPES[parent[0]] + '-' + parent[1];

            var url = '/areas/MDB-levels:' + parent + '|' + mapit_level +
                      '.geojson?generation=1&simplify_tolerance=' + MAPIT_LEVEL_SIMPLIFY[mapit_level];

            d3.json("http://mapit.code4sa.org" + url, function(error, geojson) {
                if (error) return console.warn(error);

                var featureLayer = L.geoJson(geojson, {
                    style: {
                        "clickable": true,
                        "color": "#00d",
                        "fillColor": "#ccc",
                        "weight": 1.0,
                        "opacity": 0.3,
                        "fillOpacity": 0.3,
                    },
                    filter: function(feature, layer) {
                        // don't include this smaller geo, we already have a shape for that
                        return feature.properties.codes.MDB != code;
                    },
                    onEachFeature: function(feature, layer) {
                        var name = feature.properties.name;
                        if (level == 'ward') { name = 'Ward ' + name; }

                        layer.bindLabel(name, {direction: 'auto'});

                        layer.on('mouseover', function() {
                            layer.setStyle({
                                "fillColor": "#66c2a5",
                                "fillOpacity": 0.7,
                            });
                        });
                        layer.on('mouseout', function() {
                            layer.setStyle({
                                "fillColor": "#ccc",
                                "fillOpacity": 0.3,
                            });
                        });
                        layer.on('click', function() {
                            window.location = '/profiles/' + level + '-' + feature.properties.codes.MDB + '/';
                        });
                    },
                });
                map.addLayer(featureLayer);
            });
        })(level, code);
    }
};

// Create all the charts
var Charts = {},
    chartContainers = $('[id^=chart-]'),
    defaultDataRelease = '{{ geography.census_release }}',
    profileData = {{ profile_data_json }};

var gracefulType = function(chartType) {
    // convert certain chart types to more readable versions at narrow widths
    if (browserWidth <= 640) {
        if (chartType == 'column' || chartType == 'histogram') {
            return 'bar'
        } else if (chartType == 'grouped_column') {
            return 'grouped_bar'
        }
    }
    return chartType
}

var makeCharts = function() {
    $.each(chartContainers, function(i, obj) {
        $(obj).empty();
        var chartID = $(this).prop('id'),
            chartDataKey = chartID.replace('chart-','').replace('alt-',''),
            chartDataID = chartDataKey.split('-'),
            chartType = gracefulType(chartDataID[0]),
            chartData = profileData[chartDataID[1]],
            chartChartTitle = $(this).data('chart-title'),
            chartChartShowYAxis = $(this).data('chart-show-y-axis'),
            chartInitialSort = $(this).data('initial-sort'),
            chartStatType = $(this).data('stat-type'),
            chartQualifier = $(this).data('qualifier') || null,
            geographyData = profileData['geography'];

        // allow arbitrary nesting in API data structure
        var drilldown = chartDataID.length - 1;
        if (drilldown >= 2) {
            for (var n = 2; n <= drilldown; n++) {
                chartData = chartData[chartDataID[n]]
            }
        }

        // determine whether data point is from anything other
        // than the primary ACS release for this page
        for (var key in chartData) if (chartData.hasOwnProperty(key)) break;
        var thisRelease = chartData[key]['acs_release'],
            noteRelease = (thisRelease != defaultDataRelease) ? thisRelease + ' data' : null;

        /*chartQualifier = (chartQualifier && noteRelease) ? Array(chartQualifier, noteRelease)
            .filter(function(n) { return n }).join('; ') : null;*/

        var chartstuff = {
            chartContainer: chartID,
            chartDataKey: chartDataKey,
            chartType: chartType,
            chartHeight: 160,
            chartData: chartData,
            chartQualifier: chartQualifier,
            chartChartTitle: chartChartTitle,
            chartInitialSort: chartInitialSort,
            chartStatType: chartStatType,
            geographyData: geographyData
        }
        try {
            Charts[i] = Chart(chartstuff);
        } catch(e) {
            console.log("Error making chart " + chartID)
            console.log(chartstuff);
        }
    });
}
drawMaps();
makeCharts();

// listen for resize, redraw charts to new dimensions
var lazyRedrawCharts = _.debounce(function() {
    window.browserWidth = document.documentElement.clientWidth;
    window.browserHeight = document.documentElement.clientHeight;
    makeCharts();
}, 50);
$(window).resize(lazyRedrawCharts);

// for touch devices, still allow context toggle
$('.stat-row').on('click', '.stat', function() {
    $(this).find('.context').toggle();
});

</script>
{% endblock %}
