<?php
require "../../../src/config.php";

page::set([
    "title" => "Mail Progress",
    "nav-parent" => "mail_progress",
    "layout" => "admin",
    "size" => "box-full"
]);

page::header();
?>

<div id="list"></div>

<?php
require "template.php";
require "template_all.php";
?>

<script>
    var data = [];
    var template = $("#template").html();
    var template_all = $("#template_all").html();

    function show() {

        $("#list").html(UI_loading);

        var i = active_institution();
        var year = active_year();

        if (data[i] && data[i][year]) {

            $("#list").html(Mustache.render(template, data[i][year]));
            animate_progress();

        } else {

            if (i == "all") {
                $.getJSON(API + "mail/progress/overall.php", {
                    year: year
                }, function(response) {
                    update_data(i, year, response);
                });
            } else {
                $.getJSON(API + "mail/progress/division.php", {
                    institution: i,
                    year: year
                }, function(response) {
                    update_data(i, year, response);

                });
            }


        }


    }

    function update_data(i, y, d) {

        if (!data[i]) {
            data[i] = [];
        }

        data[i][y] = d;

        $("#list").html(Mustache.render(template, data[i][y]));
        animate_progress();

    }

    show();

    $("#year_select").on("change", show);

    function animate_progress() {
        $('.progress-bar').each(function(index) {
            var element = $(this);
            setTimeout(function() {
                element.css({
                    'width': element.data("value") + "%",
                    "transition": "width 1s",
                    "transition-timing-function": "ease"
                });
            });
        });
    }

    function changecategory(category) {

        $(".pill").removeClass("active");
        $("#pill_" + category).addClass("active");
        show();
    }

    function active_institution() {
        return $(".pill.active").data("institution");
    }

    function changeyear(year) {

        $(".year-pill").removeClass("active");
        $("#pill_" + year).addClass("active");
        show();
    }

    function active_year() {
        return $("#year_select").find(":selected").data("year");
    }
</script>


<?php page::footer(); ?>