{#
/**
 * Copyright © 2003-2024 The Galette Team
 *
 * This file is part of Galette (https://galette.eu).
 *
 * Galette is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Galette is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Galette. If not, see <http://www.gnu.org/licenses/>.
 */
#}
        <script type="text/javascript" src="{{ base_path() }}/{{ constant('GALETTE_THEME') }}ui/semantic.min.js"></script>
        <script type="text/javascript" src="{{ base_path() }}/assets/js/galette-main.bundle.min.js"></script>
    {% if login.isDarkModeEnabled() %}
        <script type="text/javascript" src="{{ base_path() }}/assets/js/darkreader.min.js"></script>
    {% endif %}

        <script type="text/javascript">
            function csrfSafeMethod(method) {
                // these HTTP methods do not require CSRF protection
                return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
            }

            $(function(){
                function _darkMode() {
                    var _dark_enabled = Cookies.get('galette_dark_mode');
                    var _cookie_value = 1;
                    if (_dark_enabled && _dark_enabled == 1) {
                        var _cookie_value = 0;
    {% set darkcssfile = constant('GALETTE_CACHE_DIR') ~ "dark.css" %}
    {% if not file_exists(darkcssfile) %}
                        function writeDarkTheme() {
                            DarkReader.enable({
                                brightness: 100,
                                contrast: 90,
                                sepia: 10
                            });
                            return DarkReader.exportGeneratedCSS();
                        }
                        writeDarkTheme().then(function(cssdata) {
                            $.ajax({
                                url: '{{ url_for("writeDarkCSS") }}',
                                method: 'post',
                                data: cssdata.replaceAll('themes/galette/assets', 'themes/default/ui/themes/galette/assets'),
                                success: function(res) {
                                    console.log('Dark theme CSS stored');
                                },
                                error: function() {
                                    console.log('Error storing dark theme CSS');
                                }
                            });
                        });
    {% endif %}
                    }
                    $('.darkmode').on('click', function(e) {
                        e.preventDefault();
                        Cookies.set(
                            'galette_dark_mode',
                            _cookie_value,
                            {
                                expires: 365,
                                path: '/'
                            }
                        );
                        window.location.reload();
                    });
                    if (window.matchMedia) {
                        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
                            if (event.matches) {
                                _cookie_value = 1;
                            }
                            Cookies.set(
                                'galette_dark_mode',
                                _cookie_value,
                                {
                                    expires: 365,
                                    path: '/'
                                }
                            );
                            window.location.reload();
                        });
                    }
                }
                _darkMode();

                $.ajaxPrefilter(function(options, originalOptions, jqXHR){
                    if (options.type.toLowerCase() === "post") {
                        // initialize `data` to empty string if it does not exist
                        options.data = options.data || "";

                        // add leading ampersand if `data` is non-empty
                        options.data += options.data?"&":"";

                        // add csrf
                        options.data += encodeURIComponent("{{ csrf_name_key }}") + "=" + encodeURIComponent("{{ csrf_name }}") + "&" + encodeURIComponent("{{ csrf_value_key }}") + "=" + encodeURIComponent("{{ csrf_value }}")
                    }
                });

    {% if login.isLogged() %}
                // Display user menu in compact mode
                var _compactMenu = function() {
                    var _hidden = Cookies.get('galette_compact_menu');
                    var _menu = document.getElementById('sidemenu');
                    var _content = _menu.nextElementSibling;
                    var _trigger = document.getElementById('compactmenu');
                    if (_hidden & _hidden == 1) {
                        _trigger.checked = true;
                        _menu.classList.add('compact_menu');
                        _content.classList.add('extended');
                    }
                    _trigger.addEventListener('change', function() {
                        var _checked = $(this).is(':checked');
                        Cookies.set(
                            'galette_compact_menu',
                            (_checked ? 1 : 0),
                                {
                                    expires: 365,
                                    path: '/'
                                }
                        );
                        window.location.reload();
                    });
                }

                _compactMenu();
    {% endif %}

    {% if autocomplete %}
                $('#ville_adh_field, #lieu_naissance_field').search({
                    apiSettings: {
                        url: '{{ url_for('suggestTown', {'term': '{query}'}) }}',
                        method: 'post',
                        onFailure: function(response, element, xhr) {
                            console.log(response);
                        },
                        onError: function(errorMessage, element, xhr) {
                            {% include "elements/js/modal.js.twig" with {
                                modal_title_twig: _T("An error occurred :(")|e("js"),
                                modal_content: "errorMessage",
                                modal_class: "tiny",
                                modal_content_class: "scrolling",
                                modal_deny_only: true,
                                modal_cancel_text: _T("Close")|e("js"),
                                modal_classname: "redalert",
                            } %}
                            console.log(xhr);
                        }
                    },
                    minCharacters : 2
                });
                $('#pays_adh_field').search({
                    apiSettings: {
                        url: '{{ url_for('suggestCountry', {'term': '{query}'}) }}',
                        method: 'post',
                        onFailure: function(response, element, xhr) {
                            console.log(response);
                        },
                        onError: function(errorMessage, element, xhr) {
                            {% include "elements/js/modal.js.twig" with {
                                modal_title_twig: _T("An error occurred :(")|e("js"),
                                modal_content: "errorMessage",
                                modal_class: "tiny",
                                modal_content_class: "scrolling",
                                modal_deny_only: true,
                                modal_cancel_text: _T("Close")|e("js"),
                                modal_classname: "redalert",
                            } %}
                            console.log(xhr);
                        }
                    },
                    minCharacters : 2
                });
                $('#region_adh_field').search({
                    apiSettings: {
                        url: '{{ url_for('suggestRegion', {'term': '{query}'}) }}',
                        method: 'post',
                        onFailure: function(response, element, xhr) {
                            console.log(response);
                        },
                        onError: function(errorMessage, element, xhr) {
                            {% include "elements/js/modal.js.twig" with {
                                modal_title_twig: _T("An error occurred :(")|e("js"),
                                modal_content: "errorMessage",
                                modal_class: "tiny",
                                modal_content_class: "scrolling",
                                modal_deny_only: true,
                                modal_cancel_text: _T("Close")|e("js"),
                                modal_classname: "redalert",
                            } %}
                            console.log(xhr);
                        }
                    },
                    minCharacters : 2
                });
    {% endif %}

            {% include "elements/js/calendar.js.twig" %}

    {% if renew_telemetry is defined %}
            {% include "modals/telemetry.html.twig" with {part: "jsdialog"} %}
    {% endif %}

            {% include "elements/js/messages.js.twig" %}

            });
        </script>
    {% if login.isLogged() %}
        <script type="module" src="{{ base_path() }}/assets/js/sortable.min.js"></script>
    {% endif %}
    {% if require_charts %}
        <script type="module" src="{{ base_path() }}/assets/js/chartjs.min.js"></script>
    {% endif %}
    {% if require_mass %}
        <script type="text/javascript" src="{{ base_path() }}/assets/js/masschanges.min.js"></script>
    {% endif %}
    {% if html_editor %}
        <script type="text/javascript" src="{{ base_path() }}/assets/js/codemirror.js"></script>
        <script type="text/javascript" src="{{ base_path() }}/assets/js/xml.js"></script>
        <script type="text/javascript" src="{{ base_path() }}/assets/js/formatting.js"></script>
        <script type="text/javascript" src="{{ base_path() }}/assets/js/summernote.min.js"></script>
        <script type="text/javascript" src="{{ base_path() }}/assets/js/lang/summernote-{{ i18n.getID()|replace({'_': '-'}) }}.min.js"></script>
        <script type="text/javascript">
            function activateHtmlEditor(elt, basic) {
                if (basic === true) {
                    var _toolbar = [
                        ['font', ['bold', 'italic', 'strikethrough', 'clear']],
                        ['para', ['ul', 'ol']],
                        ['insert', ['link']],
                        ['view', ['codeview']]
                    ];
                } else {
                    var _toolbar = [
                        ['style', ['style']],
                        ['font', ['bold', 'italic', 'strikethrough', 'clear']],
                        ['para', ['ul', 'ol', 'paragraph']],
                        ['insert', ['link', 'picture']],
                        ['view', ['codeview']]
                    ];
                }
                elt.summernote({
                    lang: '{{ i18n.getID()|replace({'_': '-'}) }}',
                    disableDragAndDrop: true,
                    height: 240,
                    toolbar: _toolbar,
                    styleTags: [
                        'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
                    ],
                    callbacks: {
                        onImageUpload: function (data) {
                            //prevent image copypaste
                            data.pop();
                        }
                    }
                });
                elt.summernote('focus');
            }

            function deactivateHtmlEditor(elt) {
                elt.summernote('destroy');
            }

            function activateMailingEditor() {
                if(!$('#mailing_html').attr('checked')){
                    $('#mailing_html').attr('checked', true);
                }

                $('input#html_editor_active').attr('value', '1');
                $('#activate_editor').remove();
                $('#summernote_toggler').html('<a class="ui blue tertiary button" href="javascript:deactivateMailingEditor();" id="deactivate_editor">{{ _T("Deactivate HTML editor") }}</a>');

                activateHtmlEditor($('#mailing_corps'));
            }
            function deactivateMailingEditor() {
                deactivateHtmlEditor($('#mailing_corps'));
                $('#deactivate_editor').remove();
                $('#summernote_toggler').html('<a class="ui blue tertiary button" href="javascript:activateMailingEditor();" id="activate_editor">{{ _T("Activate HTML editor") }}</a>');
            }
        {% if html_editor_active is defined and html_editor_active == 1 %}
            $(function(){
                activateMailingEditor();
            });
        {% endif %}
        </script>
    {% endif %}
    {% set localjstracking = constant('_CURRENT_THEME_PATH') ~ "tracking.js" %}
    {% if file_exists(localjstracking) %}
        <script type="text/javascript" src="{{ base_path() }}/{{ constant('GALETTE_THEME') }}tracking.js"></script>
    {% endif %}
