{% extends "qommon/forms/widget.html" %}
{% block widget-content %}
<div id="imio-hours-block">
    <div id="imio-hours-debut" class="imio-hours">
        
    </div>
    <div id="imio-hours-fin" class="imio-hours">
        
    </div>
</div>
<h5>Légende</h5>
<div id="legend_div">
    <div id="available" class="legend">
        <p>Disponible</p>
    </div>
    <div id="high_availability" class="legend">
        <p>Haute disponibilité</p>
        <p class="detail_legend">entre 1 et 4h déjà réservées</p>
    </div>
    <div id="low_availability" class="legend">
        <p>Peu de disponibilité</p>
        <p class="detail_legend">entre 5 et 12h déjà réservées</p>
    </div>
    <div id="verylow_availability" class="legend">
        <p>Très peu de disponibilité</p>
        <p class="detail_legend">entre 13 et 22h déjà réservées</p>
    </div>
    <div id="unavailable" class="legend">
        <p>Indisponible</p>
    </div>
    <div id="selected" class="legend">
        <p>Dates sélectionnées</p>
    </div>
</div>
{% with delai_min=form_option_delai_min|default:7 %}
{% with delai_max=form_option_delai_max|default:737 %}
{% with today|add_days:delai_min as debut %}
{% with today|add_days:delai_max as fin %}
{% with debut.year|multiply:"-1"|add:fin.year|add:1 as number_year %}

<h2>Disponibilités</h2>
<div class="imio-error" id="not_yet_error_message" style="color:red"></div>
<div id="imio-disponibilites-calendrier">

<div id="imio-wrapper-arrow-year">
    <a id="imio-previous-year" class="imio-arrow left-arrow" onclick="plusSlideYear(-1)">&#10094;</a>
    <a id="imio-next-year" class="imio-arrow right-arrow" onclick="plusSlideYear(1)">&#10095;</a>
</div>

{% for y in ''|center:number_year %}
    
    {% with debut.year|add:forloop.counter0|stringformat:"i" as year %}
    <div id="imio-year-{{year}}" class="imio-year{% if forloop.first %} imio-year-start{% endif %}{% if forloop.last %} imio-year-end{% endif %}">
        <h3 style="text-align: center;">{{year}}</h3>
        <div id="imio-wrapper-arrow-month">
            <a id="imio-previous-month" class="imio-arrow left-arrow" onclick="plusSlideMonth(-1)">&#10094;</a>
            <a id="imio-next-month" class="imio-arrow right-arrow" onclick="plusSlideMonth(1)">&#10095;</a>
        </div>
        {% if forloop.first and forloop.last %}
            {% with debut.month|multiply:-1|add:fin.month|add:1 as number_month %}
                {% for i in ''|center:number_month %}
                    {% with debut.month|add:forloop.counter0|stringformat:"i" as month %}
                    <div class="imio-month {{ "01/"|add:month|add:"/"|add:year|date:"F" }}{% if forloop.first %} imio-month-start{% endif %}{% if forloop.last %} imio-month-end{% endif %}" id="{{year}}-{{month}}">

                        <h4>{{ "01/"|add:month|add:"/"|add:year|date:"F"|title }}</h4>
                        <div class="imio-month-grid">
                            {% if forloop.first and forloop.last %}

                                {% with debut.day|multiply:-1|add:fin.day|add:1 as number_day %}
                                    {% for i in ''|center:number_day %}
                                        {% with debut.day|add:forloop.counter0|stringformat:"i"|add:"/"|add:month|add:"/"|add:year|date as complete_date %}
                                            {% if complete_date %}
                                                {% if forloop.first %}
                                                    {% with complete_date|date|add_days:-1|date:"w" as no_days %}
                                                        {% for no_day in ''|center:no_days %}
                                                            <div class="imio-day no-day">
                                                                
                                                            </div>
                                                        {% endfor %}
                                                    {% endwith %}
                                                {% endif %}
                                            <div class="imio-day {{complete_date|date:"l"}}" id="imio-day-{{complete_date}}">
                                                <p>{{complete_date|date:"l"}}</br>{{complete_date}}</p>
                                            </div>
                                            {% endif %}
                                        {% endwith %}
                                    {% endfor %}
                                {% endwith %}

                            {% elif forloop.first %}
                                
                                {% with debut.day|multiply:-1|add:32 as number_day %}
                                    {% for d in ''|center:number_day %}
                                        {% with debut.day|add:forloop.counter0|stringformat:"i"|add:"/"|add:month|add:"/"|add:year|date as complete_date %}
                                            {% if complete_date %}
                                                {% if forloop.first %}
                                                    {% with complete_date|date|add_days:-1|date:"w" as no_days %}
                                                        {% for no_day in ''|center:no_days %}
                                                            <div class="imio-day no-day">
                                                                
                                                            </div>
                                                        {% endfor %}
                                                    {% endwith %}
                                                {% endif %}
                                            <div class="imio-day {{complete_date|date:"l"}}" id="imio-day-{{complete_date}}">
                                                <p>{{complete_date|date:"l"}}</br>{{complete_date}}</p>
                                            </div>
                                            {% endif %}
                                        {% endwith %}
                                    {% endfor %}
                                {% endwith %}

                            {% elif forloop.last %}

                                {% for d in ''|center:fin.day %}
                                    {% with forloop.counter|stringformat:"i"|add:"/"|add:month|add:"/"|add:year|date as complete_date %}
                                        {% if complete_date %}
                                            {% if forloop.first %}
                                                {% with complete_date|date|add_days:-1|date:"w" as no_days %}
                                                    {% for no_day in ''|center:no_days %}
                                                        <div class="imio-day no-day">
                                                            
                                                        </div>
                                                    {% endfor %}
                                                {% endwith %}
                                            {% endif %}
                                            <div class="imio-day {{complete_date|date:"l"}}" id="imio-day-{{complete_date}}">
                                                <p>{{complete_date|date:"l"}}</br>{{complete_date}}</p>
                                            </div>
                                        {% endif %}
                                    {% endwith %}
                                {% endfor %}

                            {% else %}

                                {% for d in ''|center:31 %}
                                    {% with forloop.counter|stringformat:"i"|add:"/"|add:month|add:"/"|add:year|date as complete_date %}
                                        {% if complete_date %}
                                            {% if forloop.first %}
                                                {% with complete_date|date|add_days:-1|date:"w" as no_days %}
                                                    {% for no_day in ''|center:no_days %}
                                                        <div class="imio-day no-day">
                                                            
                                                        </div>
                                                    {% endfor %}
                                                {% endwith %}
                                            {% endif %}
                                            <div class="imio-day {{complete_date|date:"l"}}" id="imio-day-{{complete_date}}">
                                                <p>{{complete_date|date:"l"}}</br>{{complete_date}}</p>
                                            </div>
                                        {% endif %}
                                    {% endwith %}
                                {% endfor %}

                            {% endif %}
                        </div>
                    </div>
                    {% endwith %}
                {% endfor %}
            {% endwith %}

        {% elif forloop.first %}
            {% with debut.month|multiply:"-1"|add:13 as number_loop %}
                {% for i in ''|center:number_loop %}
                    {% with debut.month|add:forloop.counter0|stringformat:"i" as month %}
                    <div class="imio-month {{ "01/"|add:month|add:"/"|add:year|date:"F" }}{% if forloop.first %} imio-month-start{% endif %}" id="{{year}}-{{month}}">

                        <h4>{{ "01/"|add:month|add:"/"|add:year|date:"F"|title }}</h4>
                        <div class="imio-month-grid">
                            {% if forloop.first %}
                                
                                {% with debut.day|multiply:-1|add:32 as number_day %}
                                    {% for d in ''|center:number_day %}
                                        {% with debut.day|add:forloop.counter0|stringformat:"i"|add:"/"|add:month|add:"/"|add:year|date as complete_date %}
                                            {% if complete_date %}
                                                {% if forloop.first %}
                                                    {% with complete_date|date|add_days:-1|date:"w" as no_days %}
                                                        {% for no_day in ''|center:no_days %}
                                                            <div class="imio-day no-day">
                                                                
                                                            </div>
                                                        {% endfor %}
                                                    {% endwith %}
                                                {% endif %}
                                                <div class="imio-day {{complete_date|date:"l"}}" id="imio-day-{{complete_date}}">
                                                    <p>{{complete_date|date:"l"}}</br>{{complete_date}}</p>
                                                </div>
                                            {% endif %}
                                        {% endwith %}
                                    {% endfor %}
                                {% endwith %}

                            {% else %}

                                {% for d in ''|center:31 %}
                                    {% with forloop.counter|stringformat:"i"|add:"/"|add:month|add:"/"|add:year|date as complete_date %}
                                        {% if complete_date %}
                                            {% if forloop.first %}
                                                {% with complete_date|date|add_days:-1|date:"w" as no_days %}
                                                    {% for no_day in ''|center:no_days %}
                                                        <div class="imio-day no-day">
                                                            
                                                        </div>
                                                    {% endfor %}
                                                {% endwith %}
                                            {% endif %}
                                            <div class="imio-day {{complete_date|date:"l"}}" id="imio-day-{{complete_date}}">
                                                <p>{{complete_date|date:"l"}}</br>{{complete_date}}</p>
                                            </div>
                                        {% endif %}
                                    {% endwith %}
                                {% endfor %}
                                
                            {% endif %}
                        </div>
                    </div>
                    {% endwith %}
                {% endfor %}
            {% endwith %}

        {% elif forloop.last %}
            {% for i in ''|center:fin.month %}
                {% with forloop.counter|stringformat:"i" as month %}
                <div class="imio-month {{ "01/"|add:month|add:"/"|add:year|date:"F" }}{% if forloop.last %} imio-month-end{% endif %}" id="{{year}}-{{month}}">
                    <h4>{{ "01/"|add:month|add:"/"|add:year|date:"F"|title }}</h4>
                    <div class="imio-month-grid">
                        {% if forloop.last %}

                            {% for d in ''|center:fin.day %}
                                {% with forloop.counter|stringformat:"i"|add:"/"|add:month|add:"/"|add:year|date as complete_date %}
                                    {% if complete_date %}
                                        {% if forloop.first %}
                                            {% with complete_date|date|add_days:-1|date:"w" as no_days %}
                                                {% for no_day in ''|center:no_days %}
                                                    <div class="imio-day no-day">
                                                        
                                                    </div>
                                                {% endfor %}
                                            {% endwith %}
                                        {% endif %}
                                        <div class="imio-day {{complete_date|date:"l"}}" id="imio-day-{{complete_date}}">
                                            <p>{{complete_date|date:"l"}}</br>{{complete_date}}</p>
                                        </div>
                                    {% endif %}
                                {% endwith %}
                            {% endfor %}

                        {% else %}

                            {% for d in ''|center:31 %}
                                {% with forloop.counter|stringformat:"i"|add:"/"|add:month|add:"/"|add:year|date as complete_date %}
                                    {% if complete_date %}
                                        {% if forloop.first %}
                                            {% with complete_date|date|add_days:-1|date:"w" as no_days %}
                                                {% for no_day in ''|center:no_days %}
                                                    <div class="imio-day no-day">
                                                        
                                                    </div>
                                                {% endfor %}
                                            {% endwith %}
                                        {% endif %}
                                        <div class="imio-day {{complete_date|date:"l"}}" id="imio-day-{{complete_date}}">
                                            <p>{{complete_date|date:"l"}}</br>{{complete_date}}</p>
                                        </div>
                                    {% endif %}
                                {% endwith %}
                            {% endfor %}

                        {% endif %}
                    </div>
                </div>    
                {% endwith %}
            {% endfor %}

        {% else %}
            {% for i in ''|center:12 %}
                {% with forloop.counter|stringformat:"i" as month %}
                <div class="imio-month {{ "01/"|add:month|add:"/"|add:year|date:"F" }}" id="{{year}}-{{month}}">
                    <h4>{{ "01/"|add:month|add:"/"|add:year|date:"F"|title }}</h4>
                    <div class="imio-month-grid">
                        {% for d in ''|center:31 %}
                            {% with forloop.counter|stringformat:"i"|add:"/"|add:month|add:"/"|add:year|date as complete_date %}
                                {% if complete_date %}
                                    {% if forloop.first %}
                                        {% with complete_date|date|add_days:-1|date:"w" as no_days %}
                                            {% for no_day in ''|center:no_days %}
                                                <div class="imio-day no-day">
                                                    
                                                </div>
                                            {% endfor %}
                                        {% endwith %}
                                    {% endif %}
                                    <div class="imio-day {{complete_date|date:"l"}}" id="imio-day-{{complete_date}}">
                                        <p>{{complete_date|date:"l"}}</br>{{complete_date}}</p>
                                    </div>
                                {% endif %}
                            {% endwith %}
                        {% endfor %}
                    </div>
                </div>
                {% endwith %}
            {%endfor%}

        {% endif %}
    </div>
    {% endwith %}
{% endfor %}
</div>
{% endwith %}
{% endwith %}
{% endwith %}
{% endwith %}
{% endwith %}

{{webservice.indisponibiltes_d_une_salle|json_script:'imio-indisponibilite'}}
<script type="text/javascript">
    // Array of colors for availability of day
    const colors = {
        default: "lightgreen",
        high_availability: "yellow",
        low_availability: "orange",
        verylow_availability: "fuchsia",
        unavailable: "red"
    }

    // all div year
    let dom_years = document.querySelectorAll('.imio-year');
    // all div month (month name's and grid)
    let dom_months = document.querySelectorAll('.imio-month');
    // all grid month (grid of day)
    let dom_months_grid = document.querySelectorAll('.imio-month-grid');
    // all div day
    let dom_days = document.querySelectorAll('.imio-day');
    // imio-hours-block
    let block_hours = document.getElementById('imio-hours-block')
    // imio-hours-debut
    let hours_debut = document.getElementById('imio-hours-debut')
    // imio-hours-fin
    let hours_fin = document.getElementById('imio-hours-fin')

    // init index of slider year and month
    var slide_index_year = 1;
    var slide_index_month = 1;

    // list of index in year and month (0, 1, 2, ...)
    var list_index_year = [...Array(dom_years.length).keys()];
    var list_index_month = [...Array(dom_months.length).keys()];

    // all right and left arrows (multiple year = multiple arrow for month)
    var right_arrows = document.querySelectorAll('.right-arrow');
    var left_arrows = document.querySelectorAll('.left-arrow');

    left_arrow_year = document.getElementById("imio-previous-year");
    right_arrow_year = document.getElementById("imio-next-year");

    // error message if pisk up a date out of index
    const error_message = document.querySelector('#not_yet_error_message');

    // date with occupation
    var indisponibilites = JSON.parse(document.getElementById('imio-indisponibilite').textContent)['data'];
    
    // Dictionary of imio-days-id (string): number of hours unavailabe (int)
    var occupation_day = {};

    // array of string that if in hours_debut or hours_fin days are not enfolds
    var no_enfolds = ["La date choisie n'est pas du tout disponible. Merci d'en sélectionner une autre.", 
    "La réservation est impossible : une des dates choisies est déjà réservée."];

    // Init slider year and sliders month
    showSlidesYear(slide_index_year);
    showSlidesMonth(slide_index_month);

    // color availabilities of days
    colorDays(indisponibilites);
    switchColor(occupation_day);

    // Color legend
    legend();

    function legend() {
        available_style = document.getElementById("available").style;
        available_style.backgroundColor = colors["default"];

        high_availability_style = document.getElementById("high_availability").style;
        high_availability_style.backgroundColor = colors["high_availability"];

        low_availability_style = document.getElementById("low_availability").style;
        low_availability_style.backgroundColor = colors["low_availability"];

        verylow_availability_style = document.getElementById("verylow_availability").style;
        verylow_availability_style.backgroundColor = colors["verylow_availability"];

        unavailable_style = document.getElementById("unavailable").style;
        unavailable_style.backgroundColor = colors["unavailable"];

        selected_style = document.getElementById("selected").style;
        selected_style.border = "solid"
    }

    // All the div widget date picker (title + date picker)
    let input_elements = document.querySelectorAll('.DateWidget');
    // For all widget, install event listener. If value change the month slide change
    for (var i = 0; i < input_elements.length; i++) {
        input_elements[i].getElementsByClassName('date-pick')[0].addEventListener('change', (event) => {
            error_message.textContent = "";
            var value = event.target.value.split("-");
            var id_day = "imio-day-" + value[2] + "/" + value[1] + "/" + value[0];
            unenfold_select_days();
            try {
                var index_year = Array.prototype.indexOf.call(dom_years, document.getElementById(id_day).parentElement.parentElement.parentElement);
                var index_month = Array.prototype.indexOf.call(dom_months, document.getElementById(id_day).parentElement.parentElement);

                slide_index_year = index_year + 1;
                slide_index_month = index_month + 1;

                hideSlidesYear();
                hideSlidesMonth();
                                    
                showSlidesYearDTP(index_year);
                showSlidesMonthDTP(index_month);

                message = "<h4>" + value[2] + "/" + value[1] + "/" + value[0] + "</h4>";

                date_end = document.getElementById('var_date_fin').getElementsByClassName("date-pick")[0].value;
                date_start = document.getElementById('var_date_debut').getElementsByClassName("date-pick")[0].value;

                date_end_for_user = date_end.split("-");
                date_start_for_user = date_start.split("-");

                message_hours_fin = "<h4>Fin : " + date_end_for_user[2] + "/" + date_end_for_user[1] + "/" + date_end_for_user[0] + "</h4>";

                message_hours_debut = "<h4>Début : " + date_start_for_user[2] + "/" + date_start_for_user[1] + "/" + date_start_for_user[0] + "</h4>";

                if (date_start != "") {
                    date_start = new Date(Date.parse(date_start));
                    date_start.setHours(0, 0, 0, 0);
                }

                if (date_end != "") {
                    date_end = new Date(Date.parse(date_end));
                    date_end.setHours(0, 0, 0, 0);
                }

                if (typeof(date_end) == "string" || date_start.getTime() <= date_end.getTime()) {

                    try {
                        message_hours_debut += list_hours_start(indisponibilites, date_start, date_end);
                    } catch (error) {
                        error_message.textContent = "list_hours_start error"
                    }
                } else {
                    message_hours_debut += "<p class=\"avertissement\">La date de début de la location est postérieure à la date de fin</p>"
                }

                hours_debut.innerHTML = message_hours_debut

                if (date_start != "" && date_start.getTime() <= date_end.getTime()) {

                    try {
                        message_hours_fin += list_hours_end(indisponibilites, date_start, date_end);

                    } catch (error) {
                        error_message.textContent = "list_hours_end error"
                    }

                    try {
                        enfold = true;

                        for (var i = 0; i < no_enfolds.length; i++) {
                            if (message_hours_debut.includes(no_enfolds[i])) {
                                enfold = false
                            }
                            if (message_hours_fin.includes(no_enfolds[i])) {
                                enfold = false
                            }
                        }

                        if (enfold) {
                            enfold_selected_days(date_start, date_end);
                        }

                    } catch(err) {
                        console.log(err)
                    }

                } else {
                    message_hours_fin += "<p class=\"avertissement\">La date de fin de location est antérieure à la date de début.</p>"
                }
                
                hours_fin.innerHTML = message_hours_fin


                block_hours.style.display = "flex"

            } catch (error) {
                mois_min_message_error = document.getElementsByClassName('imio-month-start')[0];
                jour_min_message_error = mois_min_message_error.getElementsByClassName('imio-day')[0];
                string_min_message_error = jour_min_message_error.innerText.replace('lundi', '').replace('mardi', '').replace('mercredi', '').replace('jeudi', '').replace('vendredi', '').replace('samedi', '').replace('dimanche', '').replace('\n', ' ').trim();

                mois_max_message_error = document.getElementsByClassName('imio-month-end')[0];
                jours_max_message_error = mois_max_message_error.getElementsByClassName('imio-day');
                jour_max_message_error = jours_max_message_error[jours_max_message_error.length - 1];
                string_max_message_error = jour_max_message_error.innerText.replace('lundi', '').replace('mardi', '').replace('mercredi', '').replace('jeudi', '').replace('vendredi', '').replace('samedi', '').replace('dimanche', '').replace('\n', ' ').trim();


                error_message.textContent = "Merci d'indiquer une date dans un délai supérieur au " + string_min_message_error + " ou inférieur au " + string_max_message_error + ".";
            }
        });
    }


    /**
     * change year when you click on years arrow's
     * @param { int } n number to add to the year index
     */
    function plusSlideYear(n) {
        if ((slide_index_year + n -1) in list_index_year) {
            // Incrémente l'année
            showSlidesYear(slide_index_year += n);

            // Incrémente les mois
            slide_index_month = 12 * n + slide_index_month;
            while (slide_index_month > dom_months.length) {
                slide_index_month -= 1;
            }
            while (slide_index_month < 1) {
                slide_index_month += 1
            }

            // Montre les mois de l'année sélectionnée
            showSlidesMonth(slide_index_month);
        }
    }

    /**
     * change month when you click on month arrow's
     * @param { int } n number to add to the month index
     */
    function plusSlideMonth(n) {

        future_index = slide_index_month + n - 1

        if (future_index in list_index_month) {
            // Incrémente les mois
            showSlidesMonth(slide_index_month += n);

            if (n == -1 && dom_months[future_index].classList.contains('décembre')) {
                showSlidesYear(slide_index_year += n);
            }

            if (n == 1 && dom_months[future_index].classList.contains('janvier')) {
                showSlidesYear(slide_index_year += n);
            }
        }


    }

    /**
     * Show year
     * @param { int } n index+1 of year
     */
    function showSlidesYear(n) {
        var slides = dom_years;

        for (var i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";
        }
        slides[slide_index_year-1].style.display = "block";
        hideShowArrows()
    }

    /**
     * Show month
     * @param { int } n index+1 of month
     */
    function showSlidesMonth(n){
        var slides = dom_months;
        var grid = dom_months_grid;
        for (i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";
        }
        for (var i = 0; i < grid.length; i++) {
            grid[i].style.display = "none";
        }
        slides[slide_index_month-1].style.display = "block";
        grid[slide_index_month-1].style.display = "inline-grid";
        grid[slide_index_month-1].style.gridTemplateColumns = "repeat(7, 1fr)";
        hideShowArrows();
    }

    /**
     * Hide year
     */
    function hideSlidesYear() {
        var slides = dom_years;

        for (var i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";
        }
    }

    /**
     * Hide month
     */
    function hideSlidesMonth() {
        var slides = dom_months;
        var grid = dom_months_grid;

        for (var i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";
        }
        for (var i = 0; i < grid.length; i++) {
            grid[i].style.display = "none";
        }
    }

    /**
     * Show the year of the date picker 
     */
    function showSlidesYearDTP(index) {
        var slides = dom_years;
        slides[index].style.display = "block";
    }

    /**
     * Show the month of the date picker 
     * Need to rework showSlidesMonthDTP showSlidesMonth showSlidesYear showSlidesYearDTP
     */
    function showSlidesMonthDTP(index) {
        var slides = dom_months;
        var grid = dom_months_grid;
        slides[index].style.display = "block";
        grid[index].style.display = "inline-grid";
        grid[index].style.gridTemplateColumns = "repeat(7, 1fr)";
        hideShowArrows();
    }

    /**
     * Hide and show arrows of year and month
     * bug with hide arrows of year
     */
    function hideShowArrows() {
        if (dom_months[slide_index_month - 1].classList.contains("imio-month-end")) {
            for (i = 0; i < right_arrows.length; i++) {
                right_arrows[i].style.display = "none";
            }
        } else {
            for (i = 0; i < right_arrows.length; i++) {
                right_arrows[i].style.display = "block";
            }
        }

        if (dom_months[slide_index_month - 1].classList.contains("imio-month-start")) {
            for (i = 0; i < left_arrows.length; i++) {
                left_arrows[i].style.display = "none";
            }
        } else {
            for (i = 0; i < left_arrows.length; i++) {
                left_arrows[i].style.display = "block";
            }
        }

        if (dom_years[slide_index_year - 1].classList.contains('imio-year-start')) {
            left_arrow_year.style.display = "none";
        } else {
            left_arrow_year.style.display = "block";
        }

        if (dom_years[slide_index_year - 1].classList.contains('imio-year-end')) {
            right_arrow_year.style.display = "none";
        } else {
            right_arrow_year.style.display = "block";
        }
    }


    /**
     * Change color of the days
     * @param { Array of Object } days
     */
    function colorDays(days) {
        for (var i = 0; i < days.length; i++) {
            var start_date = new Date(Date.parse(days[i]['StartDate']));
            start_date.setMinutes(0)

            var end_date = new Date(Date.parse(days[i]['EndDate']));
            if (end_date.getMinutes() != 0) {end_date.setHours(end_date.getHours() + 1)}
            end_date.setMinutes(0)

            var diff_date = end_date.getDate() - start_date.getDate();

            // start day == end day case
            if (diff_date == 0) {
                comput_availabilities(start_date, end_date)
            } else {
                for (var ii = 0; ii < (diff_date + 1); ii++) {
                    // first day case
                    if (ii == 0) {
                        var temp_date = new Date(start_date);
                        temp_date.setHours(24);

                        comput_availabilities(start_date, temp_date);
                    }

                    // last day case 
                    if (ii != 0 && ii == diff_date) {
                        var temp_date = new Date(end_date);
                        temp_date.setHours(0);

                        comput_availabilities(temp_date, end_date);
                    }

                    // case betwenn start day and end day
                    if (ii > 0 && ii < diff_date) {
                        var temp_start_date = new Date(start_date);
                        temp_start_date.setDate(temp_start_date.getDate() + ii);
                        temp_start_date.setHours(0);
                        var temp_end_date = new Date(temp_start_date);
                        temp_end_date.setHours(24);

                        comput_availabilities(temp_start_date, temp_end_date);
                    }
                }
            }
        }
    }

    /**
     * Calcul how many hours are unavailable in days
     * @param { Date } fstart_date 
     * @param { Date } fend_date
     */
    function comput_availabilities(fstart_date, fend_date) {
        var diff_time = (fend_date.getTime() - fstart_date.getTime()) / 3600000;
        id_day = "imio-day-" + fstart_date.toLocaleDateString('fr');
        
        occupation_day[id_day] = occupation_day[id_day] ? occupation_day[id_day] + diff_time : diff_time;
    }

    function switchColor(dict_days) {
        for (cle in dict_days) {
            var div_day = document.getElementById(cle);

            var occuped_hours = dict_days[cle]

            switch (true) {
                    case (occuped_hours >= 1 && occuped_hours <= 4):
                        div_day.style.backgroundColor = colors["high_availability"];
                        break;
                    case (occuped_hours >= 5 && occuped_hours <= 12):
                        div_day.style.backgroundColor = colors["low_availability"];
                        break;
                    case (occuped_hours >= 13 && occuped_hours <= 22):
                        div_day.style.backgroundColor = colors["verylow_availability"];
                        break;
                    case (occuped_hours >= 23):
                        div_day.style.backgroundColor = colors["unavailable"];
                        break;
                    default:
                        div_day.style.backgroundColor = colors["default"];
            }

        }
    }

    function list_hours_start(findisponibilites, fstart_date, fend_date="") {
        liste_indisponibilites_string = ""
        for (var i = 0; i < findisponibilites.length; i++) {
            debut_indisponibilite = new Date(Date.parse(findisponibilites[i]["StartDate"]));
            fin_indisponibilite = new Date(Date.parse(findisponibilites[i]["EndDate"]));

            debut_indisponibilite_jour = new Date(debut_indisponibilite);
            debut_indisponibilite_jour.setHours(0, 0, 0, 0);
            fin_indisponibilite_jour = new Date(fin_indisponibilite);
            fin_indisponibilite_jour.setHours(0, 0, 0, 0);

            if (fend_date != "" && fstart_date.getTime() < debut_indisponibilite_jour.getTime() && debut_indisponibilite_jour.getTime() < fend_date.getTime()) {
                return "<p class=\"avertissement\">La réservation est impossible : une des dates choisies est déjà réservée.</p>";
            }

            if (debut_indisponibilite <= fstart_date && fstart_date < fin_indisponibilite) {
                return "<p>La date choisie n'est pas du tout disponible. Merci d'en sélectionner une autre.</p>";
            }


            if (debut_indisponibilite_jour.getTime() === fstart_date.getTime()) {
                debut_indisponibilite_hour = ("0" + debut_indisponibilite.getHours()).slice(-2);
                debut_indisponibilite_minute = ("0" + debut_indisponibilite.getMinutes()).slice(-2);

                hour_start_string = debut_indisponibilite_hour + ":" + debut_indisponibilite_minute;
                
                if (debut_indisponibilite_jour.getTime() === fin_indisponibilite_jour.getTime()) {
                    fin_indisponibilite_hour = ("0" + fin_indisponibilite.getHours()).slice(-2);
                    fin_indisponibilite_minute = ("0" + fin_indisponibilite.getMinutes()).slice(-2);

                    hour_end_string = fin_indisponibilite_hour + ":" + fin_indisponibilite_minute;

                    liste_indisponibilites_string += ("<p>Indisponible de " + hour_start_string + " à " + hour_end_string + "</p>");
                }

                if (debut_indisponibilite_jour.getTime() < fin_indisponibilite_jour.getTime()) {
                    liste_indisponibilites_string += ("<p>Vous ne pouvez pas réserver la salle après " + hour_start_string + "</p>");
                }
            }

            if (fin_indisponibilite_jour.getTime() === fstart_date.getTime()) {
                if (debut_indisponibilite_jour.getTime() < fin_indisponibilite_jour.getTime()) {
                    fin_indisponibilite_hour = ("0" + fin_indisponibilite.getHours()).slice(-2);
                    fin_indisponibilite_minute = ("0" + fin_indisponibilite.getMinutes()).slice(-2);

                    hour_end_string = fin_indisponibilite_hour + ":" + fin_indisponibilite_minute;

                    liste_indisponibilites_string += ("<p>Vous pouvez réserver la salle après " + fhour +  "</p>");
                }
            }
        }

        if (liste_indisponibilites_string == "") {
            return "<p>Disponible</p>";
        }

        return liste_indisponibilites_string;
    }

    function list_hours_end(findisponibilites, fstart_date, fend_date) {
        liste_indisponibilites_string = "";
        for (var i = 0; i < findisponibilites.length; i++) {
            debut_indisponibilite = new Date(Date.parse(findisponibilites[i]["StartDate"]));
            fin_indisponibilite = new Date(Date.parse(findisponibilites[i]["EndDate"]));

            debut_indisponibilite_jour = new Date(debut_indisponibilite);
            debut_indisponibilite_jour.setHours(0, 0, 0, 0);
            fin_indisponibilite_jour = new Date(fin_indisponibilite);
            fin_indisponibilite_jour.setHours(0, 0, 0, 0);

            if (debut_indisponibilite_jour.getTime() < fend_date.getTime() && fend_date.getTime() < fin_indisponibilite_jour.getTime()) {
                return "<p class=\"avertissement\">La date choisie n'est pas du tout disponible. Merci d'en sélectionner une autre.</p>";
            }

            if (fstart_date.getTime() < debut_indisponibilite_jour.getTime() && debut_indisponibilite_jour.getTime() < fend_date.getTime()) {
                return "<p class=\"avertissement\">La réservation est impossible : une des dates choisies est déjà réservée.</p>";
            }

            if (fend_date.getTime() === debut_indisponibilite_jour.getTime()) {
                debut_indisponibilite_hour = ("0" + debut_indisponibilite.getHours()).slice(-2);
                debut_indisponibilite_minute = ("0" + debut_indisponibilite.getMinutes()).slice(-2);
                hour_start_string = debut_indisponibilite_hour + ":" + debut_indisponibilite_minute;

                if (debut_indisponibilite_jour.getTime() === fin_indisponibilite_jour.getTime()) {
                    fin_indisponibilite_hour = ("0" + fin_indisponibilite.getHours()).slice(-2);
                    fin_indisponibilite_minute = ("0" + fin_indisponibilite.getMinutes()).slice(-2);

                    hour_end_string = fin_indisponibilite_hour + ":" + fin_indisponibilite_minute;

                    liste_indisponibilites_string += ("<p>Indisponible de " + hour_start_string + " à " + hour_end_string + "</p>");
                }
                if (debut_indisponibilite_jour.getTime() < fin_indisponibilite_jour.getTime()) {
                    liste_indisponibilites_string += ("<p>Vous ne pouvez pas réserver la salle après " + hour_start_string + "</p>");
                }
            }

            if (fin_indisponibilite_jour.getTime() === fend_date.getTime()) {
                if (debut_indisponibilite_jour.getTime() < fin_indisponibilite_jour.getTime()) {
                    fin_indisponibilite_hour = ("0" + fin_indisponibilite.getHours()).slice(-2);
                    fin_indisponibilite_minute = ("0" + fin_indisponibilite.getMinutes()).slice(-2);

                    hour_end_string = fin_indisponibilite_hour + ":" + fin_indisponibilite_minute;

                    liste_indisponibilites_string += ("<p>Vous pouvez réserver la salle après " + fhour +  "</p>");
                }
            }
        }
        if (liste_indisponibilites_string == "") {
            return "<p>Disponible</p>";
        }
        return liste_indisponibilites_string
    }

    function enfold_selected_days(fstart_date, fend_date="") {
        if (fend_date == "") {
            fend_date = new Date(fstart_date.getTime())
        }

        number_days = fend_date.getTime() - fstart_date.getTime();
        number_days = parseInt(number_days / (1000 * 3600 * 24))
        for (var i = 0; i <= number_days; i++) {
            id_day = "imio-day-" + fstart_date.toLocaleDateString('fr');
            document.getElementById(id_day).style.border = "solid";

            fstart_date.setDate((fstart_date.getDate() + 1))
        }
        
    }

    function unenfold_select_days() {
        for (var i = 0; i < dom_days.length; i++) {
            dom_days[i].style.border = "none";
        }
    }

</script>
<style type="text/css">
    

    #imio-disponibilites-calendrier {
        display: flex;
    }

    .imio-year {
        display: none;
    }

    .imio-month {
        display: none;
    }   

    .imio-arrow {
        cursor: pointer;
        position: absolute;
        margin: 15px;
        font-weight: bold;
        font-size: 15px;
        transform: 0.6s ease;
        user-select: none;
    }

    .imio-arrow:hover {
        background-color: rgba(0, 0, 0, 0.8);
    }

    .right-arrow {
        right: 0;
    }

    .imio-day {
        margin: 20px;
        text-align: center;
        background-color: lightgreen;
        padding: 10px;
        margin: 10px;
    }

    .no-day {
        background-color: white;
    }

    h4{
        text-align: center;
    }

    #imio-hours-block {
        display: none;
        text-align: center;
        flex-direction: row;
        flex-wrap: nowrap;
        justify-content: space-around;
    }

    #legend_div {
        display: inline-grid;
        grid-template-columns: repeat(7, 1fr);
    }

    .legend {
        margin: 5px;
        text-align: center;
    }

    .avertissement {
        font-weight: bold;
        color: red;
    }

    .detail_legend {
        font-size: small;
    }

</style>
{% endblock %}
