$(function () {
    var $body = $('body');

    svg4everybody();

    var CaptchaCallback = function () {
        var recaptchas = document.querySelectorAll('div[class=g-recaptcha]');

        for (i = 0; i < recaptchas.length; i++) {
            grecaptcha.render(recaptchas[i].id, {
                'sitekey': '{{ google_recaptcha_public_key }}',
            });
        }
    }


    // Custom checkbox and radio buttons behavior
    $body.on('click', 'input[type="checkbox"] ~ .icon, input[type="radio"] ~ .icon', function () {
        var jInput = $(this).parent().children('input[type="checkbox"], input[type="radio"]'); // Previous element in the DOM must be the input widget

        if (!jInput.prop('disabled')) {
            jInput.prop('checked', !jInput.prop('checked')).trigger('change');
        }
    });

    $body.on('click', '.fakefile--button', function (e) {
        e.preventDefault();

        $(this).parent().children('.fakefile--file').trigger('click');
    });

    // Update fake file input with the value of the real hidden one
    $body.on('change', '.fakefile--file', function () {
        $(this).parent().children('.fakefile--value').val($(this).val());
    });

    // Datepicker 
    if ($.datepicker) {
        $.datepicker.regional.fr = {
            closeText: 'Fermer',
            prevText: 'Précédent',
            nextText: 'Suivant',
            currentText: 'Aujourd\'hui',
            monthNames: [
                'janvier', 'février', 'mars', 'avril',
                'mai', 'juin', 'juillet', 'août',
                'septembre', 'octobre', 'novembre', 'décembre'
            ],
            monthNamesShort: [
                'janv.', 'févr.', 'mars', 'avril',
                'mai', 'juin', 'juil.', 'août',
                'sept.', 'oct.', 'nov.', 'déc.'
            ],
            dayNames: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
            dayNamesShort: ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
            dayNamesMin: ['D', 'L', 'M', 'M', 'J', 'V', 'S'],
            weekHeader: 'Sem.',
            dateFormat: 'dd/mm/yy',
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: false,
            yearSuffix: ''
        };

        $.datepicker.setDefaults($.datepicker.regional.fr);

        $('input.date').each(function () {
            var input_date_options = { dateFormat: 'dd/mm/yy' };

            var date_format = $(this).data('datepicker-date-format');
            var date_min = $(this).data('datepicker-date-min');
            var date_max = $(this).data('datepicker-date-max');

            if (date_format) {
                input_date_options.dateFormat = date_format;
            }

            if (date_min) {
                input_date_options.minDate = date_min;
            }

            if (date_max) {
                input_date_options.maxDate = date_max;
            }

            $(this).datepicker(input_date_options);
        });
    }

    if ($.fancybox) {
        $('[data-fancybox]').fancybox({
            afterShow: function () {
                if ($.datepicker) {
                    $('input.date').datepicker({ dateFormat: 'dd/mm/yy' });
                }
            },
            beforeClose: function () {
                if ($.datepicker) {
                    $('input.date').datepicker("hide");
                }
            },
            touch: {
                vertical: true, // Allow to drag content vertically
                momentum: true // Continue movement after releasing mouse/touch when panning
            },
            mobile: {
                preventCaptionOverlap: false,
                idleTime: false,
                modal: false,
                hideScrollbar: true,
                css: {
                    position: 'absolute',
                    top: '0',
                    left: '0',
                    width: '100%',
                    height: '100%'
                },
                clickContent: function (current, event) {
                    return current.type === "image" ? "toggleControls" : false;
                },
                clickSlide: function (current, event) {
                    return current.type === "image" ? "toggleControls" : "close";
                },
                dblclickContent: function (current, event) {
                    return current.type === "image" ? "zoom" : false;
                },
                dblclickSlide: function (current, event) {
                    return current.type === "image" ? "zoom" : false;
                }
            },
            arrows: false,
            buttons: [
                'slideShow',
                'fullScreen',
                'thumbs',
                'close'
            ],
            i18n: {
                fr: {
                    CLOSE: 'Fermer',
                    NEXT: 'Suivant',
                    PREV: 'Précédent',
                    ERROR: 'Le contenu ne peut être chargé. <br/> Veuillez réessayer plus tard.',
                    PLAY_START: 'Démarrer le diaporama',
                    PLAY_STOP: 'Mettre enpause le diaporama',
                    FULL_SCREEN: 'Plein écran',
                    THUMBS: 'Miniatures'
                },
            },
            infobar: true,
            lang: document.getElementsByTagName('html')[0].getAttribute('lang').split('-')[0],
        });

        $("[data-fancybox-manual]").click(function () {
            var gallery = eval($(this).attr('rel'));

            $.fancybox.open(gallery, {
                arrows: true,
                buttons: [
                    'slideShow',
                    'fullScreen',
                    'thumbs',
                    'close'
                ],
                i18n: {
                    fr: {
                        CLOSE: 'Fermer',
                        NEXT: 'Suivant',
                        PREV: 'Précédent',
                        ERROR: 'Le contenu ne peut être chargé. <br/> Veuillez réessayer plus tard.',
                        PLAY_START: 'Démarrer le diaporama',
                        PLAY_STOP: 'Mettre enpause le diaporama',
                        FULL_SCREEN: 'Plein écran',
                        THUMBS: 'Miniatures'
                    },
                },
                infobar: true,
                lang: document.getElementsByTagName('html')[0].getAttribute('lang').split('-')[0],
            });

            return false;
        });

        if (typeof first_login_content !== "undefined") {
            $.fancybox.open({
                src: first_login_content,
                type: 'html'
            });
        }
    }

    $body.on('click', '[data-toggle]', function () {
        var target = $($(this).data('target'));

        if (target.hasClass('d-none')) {
            target.removeClass('d-none');
        }
        else {
            target.addClass('d-none');
        }
    });

    /*
    $('.slider-home').bxSlider({
        mode: 'fade',
        captions: true,
        controls: false,
        auto: true
    }); */

    $("#accordion").accordion({
        animate: {
            easing: 'swing',
            duration: 400
        },
        collapsible: true,
        active: false,
        heightStyle: 'content'
    });

    $('.galleries-tabs a').on('click', function (e) {
        e.preventDefault();

        var href = e.target.getAttribute('href');

        $('.galleries-tabs a.current').removeClass('current');
        $(this).addClass('current');

        $('.gallery.on').removeClass('on');
        $(href).addClass('on');
    });


    $body.on('paste', '.disable-paste, #registration_form_email_second', function (e) {
        e.preventDefault();
        return false;
    });

    /**
     * Geocoding
     */

    function isInt(x) {
        return /^(\d+)$/.test(x);
    }

    function isZipcodeFR(x) {
        return /^([0-9]{5})$/.test(x);
    }

    function getCountryByZipcode(x) {

        var country;

        switch (x.substr(0, 3)) {
            case "971":
                country = "Guadeloupe"; break;
            case "973":
                country = "Guyane"; break;
            case "975":
                country = "St-Pierre-et-Miquelon"; break;
            case "972":
                country = "Martinique"; break;
            case "974":
                country = "La Réunion"; break;
            case "976":
                country = "Mayotte"; break;
            case "984":
                country = "Terres-Australes et Antarctiques"; break;
            case "987":
                country = "Polynésie Française"; break;
            case "986":
                country = "Wallis-et-Futuna"; break;
            case "988":
                country = "Nouvelle-Calédonie"; break;
            default:
                country = "France"; break;
        }

        return country;
    }

    function isDate(x) {
        return /^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/.test(x);
    }

    if (typeof geocoder !== "undefined" && typeof fieldPrefix !== "undefined") {

        /**
         * Build an addresse from form fields.
         * Field's name are deduced from the given properties.
         */
        function buildAddress(properties) {
            var address = [];
            var country = '';

            for (var i = 0; i < properties.length; i++) {
                address.push($(fieldPrefix + properties[i]).val());

                if (isZipcodeFR($(fieldPrefix + properties[i]).val())) {
                    country = getCountryByZipcode($(fieldPrefix + properties[i]).val());
                }
            }

            if (country !== '') {
                address.push(country);
            }

            return address;
        }

        /**
         * Geocode an address, and update the form fields if the geocoding was successful
         */
        function geocode(address, latPropertyName, lngPropertyName) {
            var lat, lng;

            geocoder.geocode({ 'address': address.join(' ') }, function (results, status) {
                // console.log(status);
                // console.log(results);
                if (status == google.maps.GeocoderStatus.OK) {
                    lat = results[0].geometry.location.lat();
                    lng = results[0].geometry.location.lng();

                    // Update hidden fields with coordinates found
                    $(fieldPrefix + latPropertyName).val(lat);
                    $(fieldPrefix + lngPropertyName).val(lng);
                }
            });
        }

        /**
         * Initialize the address geocoding:
         * 1. React on the 'blur' form event of the fields
         * 2. Validate the adress
         * 3. Geocode the address
         * 4. Fill the appropriate fields with the coordinates
         */
        function initAddressGeocoding(properties, latPropertyName, lngPropertyName) {
            // Build form field names from the property names
            var fields = properties.map(function (property) {
                return fieldPrefix + property;
            });

            // console.log(fields);

            // 1. React on the 'change' (legacy of blur : cause limit API quota) form event of the fields
            $(fields.join(',')).on('change', function () {
                var address = buildAddress(properties);
                // console.log(address);
                // 2. Validate the adress: every part of the address must be at least 1 character long
                var triggerGeocoding = address.every(function (adr) { return adr.length > 0 });
                // console.log(triggerGeocoding);
                if (triggerGeocoding) {
                    // 3. Geocode the address
                    // 4. Fill the appropriate fields with the coordinates
                    geocode(address, latPropertyName, lngPropertyName);
                };
            });
        }

        initAddressGeocoding(
            ['establishmentAddress', 'establishmentZipcode', 'establishmentCity'],
            'latitude',
            'longitude'
        );

        initAddressGeocoding(
            ['personalAddress', 'personalZipcode', 'personalCity'],
            'personalLatitude',
            'personalLongitude'
        );

    }



    /**
     * Ajout d'une icone automatique sur les titres de module sur la home
     */
    $('.home .maincontent .body .module .module-title, .home .maincontent .after_body .module .module-title, .has-color-bubbles').prepend('<i class="icon-cgenial icon-triple-color"><span class="path1"></span><span class="path2"></span><span class="path3"></span></i>');

    /**
     * Smooth scrolling (necessary for hash module)
     */
    var hash = window.location.hash;

    if ($(hash).length > 0) {
        $('html, body').animate({
            scrollTop: $(hash).offset().top - 80
        }, 100);
    }

    /**
     * Formulaire de contact - Sujet du message dynamique
     */

    var contact_form = $('#contact_form'),
        contact_form_subjects = contact_form.find('#contact_form_subject').find('option');

    function updateContactFormSubject() {
        var form = contact_form,
            subject = form.find('#contact_form_subject');

        var category = form.find('#contact_form_category').val();

        subject.html('');

        $.each(contact_form_subjects, function () {
            var value = $(this).val();
            if (value.indexOf(category) === 0) {
                subject.append($(this));
            }
        })
    }

    // $body.on('change', '#contact_form_category', function() {
    //     updateContactFormSubject();
    // });

    // updateContactFormSubject();

    /**
     * Switch toggle
     */
    $body.on('change', '.toggle-availability input[type=checkbox]', function () {
        var is_available = $(this).is(':checked'),
            label = $(this).parents('.toggle-availability').find('.label'),
            url = $(this).parents('.toggle-availability').data('ajax'),
            data = {};

        data['is_available'] = is_available ? 1 : 0;

        $.post(url, data, function (data) {
            if (typeof data.new_label !== 'undefined') {
                label.text(data.new_label);
            }
        }, 'json');

    });


    /**
     * Dynamic relationship between 2 fields
     */

    var cache_options = [];

    function initDynamicFilteringChild() {
        $('select.filtering-other-field').each(function () {
            var nChild = $(this).data('field');
            var child = $(nChild);

            cache_options[nChild] = child.find('option');
        });

        dynamicFilteringChild();
    }


    function dynamicFilteringChild() {
        var form = $('form'),
            selectInput = form.find('select.filtering-other-field');

        if (selectInput.length > 0) {
            $.each(selectInput, function () {
                var vParent = $(this).val();
                var nChild = $(this).data('field');
                var child = $(nChild);

                if (child.length > 0 && cache_options[nChild].length > 0) {
                    //child.html('');
                    child.find('option').attr('data-visible', "0").hide();

                    $.each(cache_options[nChild], function () {
                        var vChild = $(this).val();
                        if (!vChild || vChild.indexOf('other') === 0 || vChild.indexOf(vParent) === 0) {
                            // child.append($(this));
                            child.find('[value="' + vChild + '"]').attr('data-visible', "1").show();
                        }
                    })

                    if (child.find(':selected').attr('data-visible') == 0) {
                        child.prop('selectedIndex', child.find('option[data-visible="1"]').filter(function () { return $(this).val() != ""; }).eq(0).index());
                    }
                    child.trigger('change');
                }
            })
        }
    }

    $body.on('change', 'select.filtering-other-field', function () {
        dynamicFilteringChild();
    });

    initDynamicFilteringChild();

    /**
     * Display / Hide Other field
     */
    function dynamicInputOther() {
        var form = $('form'),
            selectInput = form.find('select.relationship-with-other-field');

        if (selectInput.length > 0) {

            $.each(selectInput, function () {
                var selectInputId = $(this).attr('id'),
                    otherInput = form.find('#' + selectInputId + 'Other, #' + selectInputId + 'other, #' + selectInputId + 'NameOther');

                var value = $(this).val();

                if (($(this).hasClass('display-other-field-if-no-value') && !value) || value.indexOf('other') === 0) {
                    otherInput.closest('.form-group').show();
                    otherInput.closest('.form-group').find('label').addClass('required');
                    otherInput.attr('required', true);
                    otherInput.attr('aria-required', true);
                }
                else {
                    otherInput.closest('.form-group').hide();
                    otherInput.closest('.form-group').find('label').removeClass('required');
                    otherInput.val('');
                    otherInput.attr('required', false);
                    otherInput.attr('aria-required', false);
                }
            });
        }
    }

    $body.on('change', 'select.relationship-with-other-field', function () {
        dynamicInputOther();
    });

    dynamicInputOther();

    /**
     * Dynamic collection
     */
    function refreshAvailableOptions() {
        var list = $('.form-collection:not(#collection-merITDLC)');

        //Reset disabled options if is select element
        list.find('select').find('option').prop('disabled', false);

        // Disabled already used options if is select element
        list.find('select').each(function () {
            var value = $(this).val();
            list.find('select').not($(this)).find('option').filter('[value="' + value + '"]').prop('disabled', true);
        });

        // Change dynamic value if selected is disabled (after add action)
        list.find('select').each(function () {
            var value = $(this).val();

            if (value === null) {
                $(this).val($(this).find('option').filter(':not([disabled])').eq(0).val());
            }
        });
    }

    refreshAvailableOptions();

    $body.on('change', '.form-collection:not(#collection-merITDLC) select', function () {
        refreshAvailableOptions();
    })

    $('.form-collection--add').on('click', function (e) {
        e.preventDefault();

        var list = $($(this).attr('data-list'));
        // Try to find the counter of the list
        var counter = list.data('widget-counter') | list.children().length;
        // If the counter does not exist, use the length of the list

        // grab the prototype template
        var newWidget = list.attr('data-prototype');
        // replace the "__name__" used in the id and name of the prototype
        // with a number that's unique to your emails
        // end name attribute looks like name="contact[emails][2]"
        newWidget = newWidget.replace(/__name__/g, counter);

        // create a new list element and add it to the list
        var newElem = $(list.attr('data-widget-tags')).html(newWidget);
        // add delete button
        if (counter > 1 && list.attr('data-remove-tags')) { newElem.append(list.attr('data-remove-tags')); }
        newElem.appendTo(list);

        // Increase the counter
        counter++;


        // And store it, the length cannot be used if deleting widgets is allowed
        list.data(' widget-counter', counter);

        refreshAvailableOptions();

        // Disabled add if all options are selected
        var nbSelect = list.find('select').length;
        var nbOptions = list.find('select').eq(0).find('option').length;

        if (nbSelect >= nbOptions) {
            $(this).hide();
        }

        return false;
    });

    $('.form-collection--add').each(function () {
        var list = $($(this).attr('data-list'));
        // Try to find the counter of the list
        var counter = list.children().length;

        // If the counter does not exist, use the length of the list
        if (counter == 1) { $(this).trigger('click'); }
    });

    // handle the removal, just for this example
    $body.on('click', '.form-collection--delete', function (e) {
        e.preventDefault();

        var list = $(this).parents('.form-collection:not(#collection-merITDLC)');

        $(this).closest('li').remove();

        refreshAvailableOptions();

        // Enable add if all options are not selected
        var nbSelect = list.find('select').length;
        var nbOptions = list.find('select').eq(0).find('option').length;

        if (nbSelect < nbOptions) {
            list.closest('.form-collection--wrapper').find('.form-collection--add').show();
        }

        return false;
    });


    /**
     * Module Map PEE
     */
    $body.on('click', '.operations-list-navigation .operations-list-next-page', function (e) {
        e.preventDefault();

        var target = $(this).attr('href');

        if ($(target).length > 0) {
            $(target).addClass('show').addClass('in');
        }

        $(this).parents('.operations-list-navigation').hide();
    });

    $body.on('click', 'button.select-ope', function (e) {
        e.preventDefault();

        var checkbox = $(this).prev('input[name="operation[]"]');
        var checked = !checkbox.attr("checked");

        if (checked && !mapPEESelectionValidator(checkbox)) {
            return false;
        }

        checkbox.attr("checked", !checkbox.attr("checked"));
        checkbox.trigger("change");
    });

    $body.on('change', '.module-mappee .operations-list input[name="operation[]"]', function (e) {
        e.preventDefault();

        var ope = $(this).parents('.item');
        var btn = ope.find('button.select-ope');
        var checked = $(this).attr('checked');

        var index = ope.data('index');

        // Change Btn content
        if (checked) {
            btn.html(mappee_txt_checked);
            map_markers[index].setIcon(mappee_marker_link_active + '&id=' + parseInt(markers[index].indexMarker));
            map_markers[index].setZIndex(100 + parseInt(index));
        }
        else if (parseInt(ope.data('remaining')) <= 0) {
            btn.html(mappee_txt_waiting_list);
            map_markers[index].setIcon(mappee_marker_link + '?id=' + parseInt(markers[index].indexMarker));
            map_markers[index].setZIndex(parseInt(index));
        }
        else {
            btn.html(mappee_txt_registration);
            map_markers[index].setIcon(mappee_marker_link + '?id=' + parseInt(markers[index].indexMarker));
            map_markers[index].setZIndex(parseInt(index));
        }

        // Update others operations 
        var dateVisite = ope.data('datevisite');
        var operations = $(this).parents('.operations-list').find('.item').not(ope).not('.registered').filter('[data-datevisite="' + dateVisite + '"]');
        if (checked) {
            operations.find('button').removeClass('select-ope').addClass('disabled').attr('disabled', true).html(mappee_txt_date_identical);
        }
        else {
            $.each(operations, function () {
                if (parseInt($(this).data('fenced')) == 1) {
                    $(this).find('button').addClass('select-ope').addClass('disabled').attr('disabled', true).html(mappee_txt_fenced);
                }
                else if (parseInt($(this).data('remaining')) <= 0) {
                    $(this).find('button').addClass('select-ope').removeClass('disabled').attr('disabled', false).html(mappee_txt_waiting_list);
                }
                else {
                    $(this).find('button').addClass('select-ope').removeClass('disabled').attr('disabled', false).html(mappee_txt_registration);
                }
            })
        }

        // Update Text remaining
        var nb_ope = $('.module-mappee .operations-list input[name="operation[]"]:checked').length;
        var limit_remaining = mappee_max_pee_limit_remaining - nb_ope;
        $('.mappee_ope_remaining').text(limit_remaining);
    });

    function mapPEESelectionValidator(checkbox) {
        var ope = checkbox.parents('.item');
        var registered = $('.module-mappee .operations-list .item.registered').not(ope);
        var operations = $('.module-mappee .operations-list input[name="operation[]"]:checked').parents('.item').not(ope);
        var nb_ope = operations.length;
        var limit_remaining = mappee_max_pee_limit_remaining - nb_ope;

        if (limit_remaining <= 0) {
            alert(mappee_txt_error_limit_reached);
            return false;
        }

        if (parseInt(ope.data('fenced')) == 1) {
            alert(mappee_txt_error_fenced);
            return false;
        }

        var dateVisite = ope.data('datevisite');
        if (operations.filter('[data-datevisite="' + dateVisite + '"]').length > 0) {
            alert(mappee_txt_error_date_identical);
            return false;
        }

        // Check date availables 
        // Valid with preselected operations (already selected in profil)
        if (registered.filter('[data-datevisite="' + dateVisite + '"]').length > 0) {
            alert(mappee_txt_error_date_identical);
            return false;
        }

        return true;
    }

    if (typeof mappee_ajax_get_content !== "undefined") {

        $body.on('keyup', '.module-mappee form.search_form input[name="zipCode"]', function (e) {
            e.preventDefault();

            var mappee_search_form = $(this).parents('form.search_form'),
                mappee_search_zipcode = mappee_search_form.find('input[name="zipCode"]'),
                mappee_search_latitude = mappee_search_form.find('input[name="search_latitude"]'),
                mappee_search_longitude = mappee_search_form.find('input[name="search_longitude"]');

            if ($(this).val() && isZipcodeFR($(this).val())) {
                $('#' + mappee_ajax_content_wrapper + ' + .cgenial-loader').fadeIn('fast');

                // Get Geoloc by Google
                var geocoder = new google.maps.Geocoder();
                var country = getCountryByZipcode($(this).val());

                geocoder.geocode({ 'address': $(this).val() + ', ' + country }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        // Update hidden fields with coordinates found
                        mappee_search_latitude.val(results[0].geometry.location.lat());
                        mappee_search_longitude.val(results[0].geometry.location.lng());

                        mappee_search_zipcode.removeClass('is-invalid');
                    }
                    else {
                        mappee_search_zipcode.addClass('is-invalid');
                    }
                    $('#' + mappee_ajax_content_wrapper + ' + .cgenial-loader').fadeOut('fast');
                });


            }
            else {
                mappee_search_latitude.val('');
                mappee_search_longitude.val('');
            }
        });

        function reloadMapPeeContent() {
            $('#' + mappee_ajax_content_wrapper + ' + .cgenial-loader').fadeIn('fast');

            var mappee_error = false,
                mappee_wrapper = $('#' + mappee_ajax_content_wrapper).parent(),
                mappee_search_form = mappee_wrapper.find('form.search_form'),
                mappee_search_zipcode = mappee_search_form.find('input[name="zipCode"]'),
                mappee_search_latitude = mappee_search_form.find('input[name="search_latitude"]'),
                mappee_search_longitude = mappee_search_form.find('input[name="search_longitude"]'),
                mappee_search_category = mappee_search_form.find('select[name="category"]'),
                mappee_search_datevisite = mappee_search_form.find('input[name="dateVisite"]'),
                filters = {};

            if (mappee_search_latitude.val() && mappee_search_longitude.val()) {
                filters.search_latitude = mappee_search_latitude.val();
                filters.search_longitude = mappee_search_longitude.val();
            }

            if (mappee_search_zipcode.val()) {
                if (isZipcodeFR(mappee_search_zipcode.val())) {
                    filters.zipCode = mappee_search_zipcode.val();

                    // Hide error
                    mappee_search_zipcode.removeClass('is-invalid');

                }
                else {
                    // Display Error
                    mappee_search_zipcode.addClass('is-invalid');

                    mappee_error = true;
                }
            }
            else {
                // Hide error
                mappee_search_zipcode.removeClass('is-invalid');
            }

            if (mappee_search_category.val()) {
                if (isInt(mappee_search_category.val())) {
                    filters.category = mappee_search_category.val();

                    // Hide error
                    mappee_search_category.removeClass('is-invalid');

                }
                else {
                    // Display Error
                    mappee_search_category.addClass('is-invalid');

                    mappee_error = true;
                }
            }
            else {
                // Hide error
                mappee_search_category.removeClass('is-invalid');
            }

            if (mappee_search_datevisite.val()) {
                if (isDate(mappee_search_datevisite.val())) {
                    filters.dateVisite = mappee_search_datevisite.val();

                    // Hide error
                    mappee_search_datevisite.removeClass('is-invalid');

                }
                else {
                    // Display Error
                    mappee_search_datevisite.addClass('is-invalid');

                    mappee_error = true;
                }
            }
            else {
                // Hide error
                mappee_search_datevisite.removeClass('is-invalid');
            }

            if (!mappee_error) {
                $.post(mappee_ajax_get_content, filters, function (html) {
                    $('#' + mappee_ajax_content_wrapper).html(html);

                    $('#' + mappee_ajax_content_wrapper + ' + .cgenial-loader').fadeOut('fast');
                }, 'html');
            }
            else {
                $('#' + mappee_ajax_content_wrapper + ' + .cgenial-loader').fadeOut('fast');
            }
        }

        $body.on('click', '.module-mappee .submit-search', function (e) {
            e.preventDefault();
            e.stopPropagation();

            reloadMapPeeContent();
        });

        mappee_initialize();
    }


    /***
     * Slider video
     */

    if ($('.video-slider').length > 0) {

        $('.video-slider').slick({
            dots: false,
            infinite: true,
            draggable: false,
            speed: 400,
            slidesToShow: 1,
            adaptiveHeight: false,
        });

        $('.video-slider').on('beforeChange', function (event, slick, currentSlide, nextSlide) {
            var player = eval($(this).find('.slick-slide').eq(currentSlide).data('player'));

            if (typeof player === "object" && typeof player.pauseVideo === "function") {
                player.pauseVideo();
            }
        });
    }



    /***
     * Filter
     */
    $body.on('change', '.filter_form select.filter_by', function (e) {
        e.preventDefault();

        var option = $(this).find(":selected");
        var target = option.data('redirect');

        window.location.href = target;

        return false;
    });


    /**
     * Modal Call to action
     */
    $body.on('click', '.modal-cta-ajax', function () {
        if (typeof modal_cta_ajax_url === "string") {

            if (typeof modal_cta_ajax_data == "undefined") {
                modal_cta_ajax_data = {};
            }

            $.post(modal_cta_ajax_url, modal_cta_ajax_data, function (data) {
                window.location.reload(false);
            }, 'json');
        }

    });


    /**
     * Preferences
     */
    $body.on('click', '.module-inview-user-preferences button.select-preference-user', function (e) {
        e.preventDefault();

        var checkbox = $(this).prev('input[name="preference[]"]');

        checkbox.attr("checked", !checkbox.attr("checked"));
        checkbox.trigger("change");
    });

    $body.on('click', '.cgenial-modal button.select-preference-user', function (e) {
        e.preventDefault();

        var user = $(this).data('user');
        var checkbox = $('.module-inview-user-preferences input[value=' + user + ']');

        checkbox.attr("checked", !checkbox.attr("checked"));
        checkbox.trigger("change");

        if ($.fancybox) {
            $.fancybox.close();
        }
    });

    $body.on('change', '.preference input[name="preference[]"]', function (e) {
        e.preventDefault();

        var ope = $(this).parents('.item');
        var btn = ope.find('button.select-preference-user');

        if (typeof preferences_ajax_url === "string") {
            var checked = $(this).attr('checked');
            var data = {
                id: $(this).val(),
                actif: checked ? 'true' : 'false',
            };

            $.post(preferences_ajax_url, data, function (data) {
                // Change Btn content
                if (checked) {
                    btn.addClass('has-select-icon').html(preferences_txt_checked);
                }
                else {
                    btn.removeClass('has-select-icon').html(preferences_txt_unchecked);
                }
            }, 'json');
        }
    });


    /**
    * Interest
    */
    $body.on('click', '.block-demandes .blockItdlc button.select-interest-itdlc', function (e) {
        e.preventDefault();

        var checkbox = $(this).prev('input[name="interest[]"]');

        checkbox.attr("checked", !checkbox.attr("checked"));
        checkbox.trigger("change");
    });

    $body.on('click', '.cgenial-modal button.select-interest-itdlc', function (e) {
        e.preventDefault();

        var demande = $(this).data('demande');
        var checkbox = $('.block-demandes .blockItdlc input[value=' + demande + ']');

        checkbox.attr("checked", !checkbox.attr("checked"));
        checkbox.trigger("change");

        if ($.fancybox) {
            $.fancybox.close();
        }
    });

    $body.on('change', '.block-demandes .blockItdlc input[name="interest[]"]', function (e) {
        e.preventDefault();

        var ope = $(this).parents('.item');
        var btn = ope.find('button.select-interest-itdlc');
        var interest_ajax_url = btn.data('ajax-url');

        if (typeof interest_ajax_url === "string") {
            var checked = $(this).attr('checked');
            var data = {
                interested: checked ? 1 : 0,
            };

            $.post(interest_ajax_url, data, function (data) {
                // Change Btn content
                if (checked) {
                    btn.addClass('has-select-icon').html(interest_txt_checked);
                }
                else {
                    btn.removeClass('has-select-icon').html(interest_txt_unchecked);
                }
            }, 'json');
        }
    });
});


/*!
 * jQuery Cookie Plugin v1.4.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2006, 2014 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD (Register as an anonymous module)
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var pluses = /\+/g;

    function encode(s) {
        return config.raw ? s : encodeURIComponent(s);
    }

    function decode(s) {
        return config.raw ? s : decodeURIComponent(s);
    }

    function stringifyCookieValue(value) {
        return encode(config.json ? JSON.stringify(value) : String(value));
    }

    function parseCookieValue(s) {
        if (s.indexOf('"') === 0) {
            // This is a quoted cookie as according to RFC2068, unescape...
            s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }

        try {
            // Replace server-side written pluses with spaces.
            // If we can't decode the cookie, ignore it, it's unusable.
            // If we can't parse the cookie, ignore it, it's unusable.
            s = decodeURIComponent(s.replace(pluses, ' '));
            return config.json ? JSON.parse(s) : s;
        } catch (e) { }
    }

    function read(s, converter) {
        var value = config.raw ? s : parseCookieValue(s);
        return $.isFunction(converter) ? converter(value) : value;
    }

    var config = $.cookie = function (key, value, options) {

        // Write

        if (arguments.length > 1 && !$.isFunction(value)) {
            options = $.extend({}, config.defaults, options);

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
            }

            return (document.cookie = [
                encode(key), '=', stringifyCookieValue(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path ? '; path=' + options.path : '',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''));
        }

        // Read

        var result = key ? undefined : {},
            // To prevent the for loop in the first place assign an empty array
            // in case there are no cookies at all. Also prevents odd result when
            // calling $.cookie().
            cookies = document.cookie ? document.cookie.split('; ') : [],
            i = 0,
            l = cookies.length;

        for (; i < l; i++) {
            var parts = cookies[i].split('='),
                name = decode(parts.shift()),
                cookie = parts.join('=');

            if (key === name) {
                // If second argument (value) is a function it's a converter...
                result = read(cookie, value);
                break;
            }

            // Prevent storing a cookie that we couldn't decode.
            if (!key && (cookie = read(cookie)) !== undefined) {
                result[name] = cookie;
            }
        }

        return result;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        // Must not alter options, thus extending a fresh object...
        $.cookie(key, '', $.extend({}, options, { expires: -1 }));
        return !$.cookie(key);
    };

}));