{% extends "qommon/forms/widget.html" %}
{% block widget-content %}
{% with webservice.aes_get_plaines.themes as themes %}
<div id="themes">
    {% for theme in themes %}
    {% if theme.label != False %}
    <div class="theme" id="_S{{ theme.week }}">
        {{ theme.label }}
    </div>
    {% endif %}
    {% endfor %}
</div>
{% endwith %}
<div id="content" class="divTable">
    <div class="plaine divTablerow" index="-1">
        <span class="week_title"></span>
        <div class="divTableCell"><span class="day_label">Lundi</span>
            <div n_day="1" class="day"></div>
        </div>
        <div class="divTableCell"><span class="day_label">Mardi</span>
            <div n_day="2" class="day"></div>
        </div>
        <div class="divTableCell"><span class="day_label">Mercredi</span>
            <div n_day="3" class="day"></div>
        </div>
        <div class="divTableCell"><span class="day_label">Jeudi</span>
            <div n_day="4" class="day"></div>
        </div>
        <div class="divTableCell"><span class="day_label">Vendredi</span>
            <div n_day="5" class="day"></div>
        </div>
        <div class="divTableCell"><span class="day_label">Samedi</span>
            <div n_day="6" class="day"></div>
        </div>
        <div class="divTableCell"><span class="day_label">Dimanche</span>
            <div n_day="0" class="day"></div>
        </div>
    </div>
</div>
<script>
    var DEBUG = false;
    var DISPLAY_CHECKBOX = false;
    var $CHECKED_SPAN = "<span style='float:right;color:green' class='checked_span'>V</span>";
    var SOURCE_DATE_FORMAT = ""; // ex: dd-mm-yyyy
    var ITEM_ALWAYS_AVAILABLE = true;
    var ITEM_SELECTED_COLOR = "white";
    var CHECK_FULL_WEEK = false; // if true you can select full week in one click.

    $(function() {
        var $num_week = -1;
        var $current_date = null;
        var $available = null;
        var $previous_date = null;
        var $current_plaine = null;
        var $plaine = $("div#content > div.plaine");
        var $navigation = create_navigation(); // navigation.
        // select_items est une liste triee par id.
        // l'id a le format suivant : [num_semaine]_[yyyy-mm-dd_Act]_[cpt_activite]
        var $select_items = $("div.CheckboxesWidget.pp_plaines > div.content > ul > li");
        $select_items.css("list-style-type", "none"); // clear dot in li list.
        $select_items.find("label").css("display", "block");
        $("div#themes").hide();
        if (DEBUG == false) {
            // On cache la selectbox. Attention, ne pas la supprimer, on en a besoin.
            $("div.CheckboxesWidget.pp_plaines").hide();
        }

        if (DISPLAY_CHECKBOX == false) {
            $select_items.find("input").css("display", "none");
        }
        // comme la liste est triee par id, on peut gerer les items sequentiellement.
        $select_items.each(function(index) {
            $clone = $(this).clone(true, true);
            $clone.find("input").attr("name", $(this).find("input").attr("name") + "table");
            // console.log($clone.find("input").attr("name"));
            // Je ne peux cliquer sur les activites que si je ne peux pas cliquer sur la semaine entiere.
            if (CHECK_FULL_WEEK == false) {
                $clone.find("input").bind('click', {
                    obj: $clone.find("input")
                }, click_input);
            }
            var arr_item_attributes = $(this).find("input").attr("name").split("_");
            $current_date = arr_item_attributes[2];
            if (SOURCE_DATE_FORMAT == "dd-mm-yyyy"
                || $current_date.split("-")[2].length > 2) {
                $current_date = $current_date.split("-")[2] + "-" + $current_date.split("-")[1] + "-" + $current_date.split("-")[0];
            }
            // console.log($current_date);
            if (ITEM_ALWAYS_AVAILABLE == false) {
                $available = arr_item_attributes[arr_item_attributes.length - 1];
            } else {
                $available = "available";
            }
            var $pretty_date = $current_date.split("-")[2] + "/" + $current_date.split("-")[1] + "/" + $current_date.split("-")[0];
            $current_day = new Date($current_date + "T00:00:00").getDay();
            // S20, S21, S22, ...
            var $current_num_week = $(this).find("input").attr("name").split("_")[1];
            // nouvelle semaine => on va cloner le "template" de plaine.
            if ($num_week != $current_num_week) {
                $num_week = $current_num_week;
                $previous_date = $current_date;
                // console.log("je clone" + $current_date);
                $current_plaine = $plaine.clone(true, true).attr("index", $current_num_week);
                // $current_plaine.attr("index", $current_num_week);
                // affichage du nom de la semaine
                var theme_label = $("div#themes > div[id$='" + $num_week + "']").text();
                var $label_week = "";
                if (theme_label != "") {
                    $label_week = $("div#themes > div[id$='" + $num_week + "']").text();
                } else {
                    $label_week = "Semaine calendrier : " + $num_week;
                }
                if (CHECK_FULL_WEEK == true) {
                    var $CBx_full_week = $('<input type="checkbox" id="CBx_full_week' + $num_week + '" name="CBx_full_week' + $num_week + '" value="' + $num_week + '" >' + $label_week + '</input>');
                    $CBx_full_week.prop("checked", $("div.CheckboxesWidget.pp_plaines > div.content > ul > li input[name*='" + $num_week + "']").first().prop("checked"));
                    $CBx_full_week.bind('click', {
                        obj: $("div.CheckboxesWidget.pp_plaines > div.content > ul > li")
                    }, click_full_week);
                    $current_plaine.find(".week_title").append($CBx_full_week);
                } else {
                    $current_plaine.find(".week_title").html($label_week);
                }
                $current_plaine.find("div[n_day=" + $current_day + "]").html("<div class='current_date'>" + $pretty_date + "</div><div attr='A' available='" + $available + "' class='input'></div>");
                if ($clone.find("span").text().startsWith("_S") == false) {
                    $current_plaine.find("div[n_day='" + $current_day + "'] .input").append($clone);
                }
                $current_plaine.insertAfter($("div.CommentWidget.template-pp_plaines div#content .plaine:last"));
            }
            // On est toujours dans la même semaine de plaine.
            else {
                // une activité dans le même jour que la précédente.
                if ($previous_date == $current_date) {
                    if ($clone.find("span").text().startsWith("_S") == false) {
                        $current_plaine.find("div[n_day='" + $current_day + "'] .input").append($clone);
                    }
                } else {
                    // une activité dans un nouveau jour de la même plaine
                    $current_plaine.find("div[n_day='" + $current_day + "']").html("<div class='current_date'>" + $pretty_date + "</div><div attr='D' available='" + $available + "' class='input'></div>");
                    if ($clone.find("span").text().startsWith("_S") == false) {
                        $current_plaine.find("div[n_day='" + $current_day + "'] .input").append($clone);
                    }
                    $previous_date = $current_date;
                }
            }
        });
        // Fixe l'affichage de la semaine au chargement
        // Gestion des cases a cocher
        // Gestion des jours sans activites
        // Gestion des semaines indisponibles
        var $days = $("div.CommentWidget.template-pp_plaines div#content .plaine .divTableCell");
        $days.each(function(idx) {
            change_selection($(this).find("li input"));
            if ($(this).find(".day").text().trim() == "") {
                $(this).addClass("no_activity");
            }

            if ($(this).find("div.input").attr("available") == "unaivalable") {
                var week_value = $(this).parent().attr("index");
                var week = $(".week_title input[value='" + week_value + "']");
                week.prop("disabled", true);
                if (!week.parent().find("div.nomoreplace").length) {
                    week.parent().append("<div class='nomoreplace'>Plus de place disponible</div>");
                }
                $(this).addClass("no_activity");
            }
        });
        $("div.divTablerow").each(function(idx) {
            var $input_week = $(this).find("span.week_title input");
            var _value = $input_week.val();
            var week_is_checked = $input_week.is(":checked");
            change_divTableCell(_value, week_is_checked);
        });
        // initialisation de la visualisation des plaines (1 par 1 via la navigation)
        $("div.CommentWidget.template-pp_plaines div#content .plaine").hide();
        $("div.CommentWidget.template-pp_plaines div#content .plaine:first").remove();
        $("div.CommentWidget.template-pp_plaines div#content .plaine:first").show();
        // Une seule semaine => pas de navigation.
        if ($("div.CommentWidget.template-pp_plaines div#content .plaine").length <= 1) {
            $navigation.remove();
        } else {
            $("#cal_previous").bind('click', {
                plaines: $("div.CommentWidget.template-pp_plaines div#content .plaine")
            }, nav_previous);
            $("#cal_next").bind('click', {
                plaines: $("div.CommentWidget.template-pp_plaines div#content .plaine")
            }, nav_next);
        }
        // 1ere fonction pour le mouseEnter, 2e fonction pour le mouseLeave.
        // Cet effet sur les différentes activités n'est chargé que si on peut faire de la sélection
        // activité par activité.
        if (CHECK_FULL_WEEK == false) {
            $(".day li").hover(function() {
                    $(this).css({
                        "background-color": ITEM_SELECTED_COLOR
                    });
                },
                function() {
                    if ($(this).find("input").prop("checked") == true) {
                        $(this).css("background-color", ITEM_SELECTED_COLOR);
                    } else {
                        $(this).css("background-color", "#d4e2e3");
                    }
                }
            );
        } else {
            $("div.day div.input li label").css("cursor", "default");
        }
    });

    // General method to get elements thanks to regex !
    // sample : $('div:regex(class,jqTable[0-9]_.*)'); */
    $.expr[':'].regex = function(elem, index, match) {
        var matchParams = match[3].split(','),
            validLabels = /^(data|css):/,
            attr = {
                method: matchParams[0].match(validLabels) ?
                    matchParams[0].split(':')[0] : 'attr',
                property: matchParams.shift().replace(validLabels, '')
            },
            regexFlags = 'ig',
            regex = new RegExp(matchParams.join('').replace(/^s+|s+$/g, ''), regexFlags);
        return regex.test(jQuery(elem)[attr.method](attr.property));
    }
    // End of General method to get elements thanks to regex !

    function create_navigation() {
        $("div.template-pp_plaines").prepend('<div id="nav_plaines"><p><input type="button" id="cal_previous" value="Semaine précédente" date="" />&nbsp;<input type="button" id="cal_next" value="Semaine suivante" date="" /></p>');
        return $("div#nav_plaines");
    }

    function change_selection(obj) {
        var $input = obj;
        if ($input.prop("checked") == false) {
            $input.closest("label").css("font-weight", "normal");
            $input.closest("li").css("background-color", "transparent");
            $input.closest("li").css({
                "box-shadow": "2px 2px 5px #aaa"
            });
        } else {
            $input.closest("label").css("font-weight", "bold");
            $input.closest("li").css("background-color", ITEM_SELECTED_COLOR);
            $input.closest("li").css("box-shadow", "none");
        }
    }

    function change_divTableCell(week_number, is_checked) {
        var $divTableCell = $("div.divTablerow[index='" + week_number + "']").find("div.divTableCell");
        $divTableCell.each(function() {
            if (!$(this).hasClass("no_activity")) {
                if (is_checked == true) {
                    $(this).find("span.day_label").after($CHECKED_SPAN);
                } else {
                    $(this).find("span.checked_span").remove();
                }
            }
        });
    }

    var click_full_week = function(event) {
        // _value contient le numero de la semaine dans l'annee. (ex: S27)
        var _value = $(this).val();
        var week_is_checked = $(this).is(":checked");
        // C'est la liste de checkbox
        $("div.CheckboxesWidget.pp_plaines > div.content > ul > li input:regex(name," + _value + ")").prop("checked", week_is_checked);
        $("div.plaine[index='" + _value + "'] li input").prop("checked", week_is_checked);
        change_selection($("div.plaine[index='" + _value + "'] li input"));
        change_divTableCell(_value, week_is_checked);
    };

    var click_input = function(event) {
        change_selection(event.data.obj);
    };

    var nav_previous = function(event) {
        $plaines = event.data.plaines;
        // $plaines = $($plaines.get().reverse());
        var $visible_elem = $plaines.filter(":visible");
        if ($visible_elem.attr("index") != $plaines.first().attr("index")) {
            $visible_elem.hide();
            $visible_elem.prev(".plaine").show();
            /*var id = $visible_elem.attr("index").substr(1);
            var prevID = "S" + (parseInt(id, 10) - 1);
            $(".plaine[index=" + prevID + "]").show();
            //var $label_week = $("div#themes > div[id$='_" + $prevID + "']").text();
            //$current_plaine.find(".week_title").html($label_week);*/
        } else {
            // console.log("same");
        }
    };

    var nav_next = function(event) {
        $plaines = event.data.plaines;
        var $visible_elem = $plaines.filter(":visible");
        if ($visible_elem.attr("index") != $plaines.last().attr("index")) {
            $visible_elem.hide();
            var id = $visible_elem.attr("index").substr(1);
            /* var nextID = "S" + (parseInt(id, 10) + 1);
            $(".plaine[index=" + nextID + "]").show();*/
            $visible_elem.next(".plaine").show();
        } else {
            // console.log("same");
        }
    };
</script>
<style>
    .divTablerow {
        display: flex;
        flex-wrap: wrap;
    }

    .divTableCell {
        display: block;
        min-width: 100px;
        margin-bottom: 20px;
        margin-left: 10px;
        background: #f2f2f2;
        padding: 5px;
        border-radius: 3px;
    }

    div.divTableCell>span {
        font-weight: bold !important;
        font-size: 16px !important;
    }

    div.day .current_date {
        margin-bottom: 07px;
        font-size: 15px;
        color: #626262;
        letter-spacing: 0.02em;
    }

    div.day div.input li {
        border: none;
        padding: 0px 1px 6px 0.2em;
        border-radius: 2px;
        box-shadow: 2px 2px 5px #aaa;
        background: #d4e2e3;
        font: bold 13px;
        color: #555;
        display: block;
        margin-bottom: 5px;
        height: 20px;
    }

    div.day div.input li label {
        cursor: pointer;
        display: block;
        padding-top: 6px;
        height: 100%
    }

    .week_title {
        width: 100%;
        margin-bottom: 18px;
        font-weight: bold;
        font-size: 16px;
    }

    .no_activity {
        display: block !important;
        color: #b5b5b5 !important;
        /* juste pour écraser color white (temporaire) */
        background: repeating-linear-gradient(45deg,
                #d4e2e3,
                #d4e2e3 10px,
                #f9f9f9 10px,
                #f9f9f9 20px);
    }
</style>
{% endblock %}
</div>
