{% extends 'Front/layout.html.twig' %}

{% set userTypeProf = constant('AppBundle\\Enum\\UserType::TEACHER') %}

{% block javascripts %}
    <!-- Google Maps JavaScript API v3 key -->
    <script src="https://maps.googleapis.com/maps/api/js?key={{ google_maps_id }}"></script>

    <script>
        //<![CDATA[
        $(function () {
            var fieldPrefix = '#registration_step2_' + (0 === $('#registration_step2_prof_form_establishmentAddress').length ? 'inge' : 'prof') + '_form_';
            var geocoder = new google.maps.Geocoder();

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

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

                address.push('FRANCE');

                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) {
                    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;
                });

                // 1. React on the 'blur' form event of the fields
                $(fields.join(',')).on('blur', function() {
                    var address = buildAddress(properties);

                    // 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});

                    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(
                ['personalZipcode', 'personalCity'],
                'personalLatitude',
                'personalLongitude'
            );

            if ('#registration_step2_prof_form_' === fieldPrefix) { // Prof
                $(fieldPrefix + 'job').closest('.form-row').addClass('form-row-half');
                $(fieldPrefix + 'jobOther').closest('.form-row').addClass('form-row-half');
            } else { // Inge
                $(fieldPrefix + 'establishment').closest('.form-row').addClass('form-row-half');
                $(fieldPrefix + 'establishmentNameOther').closest('.form-row').addClass('form-row-half');
            }

            /**
             * Fait varier la condition requise (required) entre 1 menu déroulant (<select>) et 1 champ texte (<input type="text">),
             * d'après son contenu. Si l'un de ces deux champs se rempli, il devient requis
             * et l'autre champ est réinitialisé et devient optionnel.
             * Les deux champs fonctionnant de cette façon doivent être tous les deux inclus dans un parent comporant la classe .form-row-half.
             */
            $('.form-row-half select, .form-row-half input[type="text"]').on('change', function () {
                var is_select = $(this).is('select'),
                    row = $(this).closest('.form-row'),
                    row_other = (is_select ? row.next('.form-row-half') : row.prev('.form-row-half'));

                // Le champ n'est pas vide
                if (0 < $(this).val().length) {
                    // On indique le champ et son label comme requis
                    $(this).attr('required', 'required');
                    $(this).attr('aria-required', 'aria-required');
                    row.find('.form-row-label label').attr('class', 'required');

                    // On indique l'autre champ comme optionnel (suppression de l'attribut required="required"),
                    // et on réinitialise sa valeur.
                    row_other.find('.form-row-label label').removeClass('required');
                    row_other.find('.form-row-field  ' + (is_select ? 'input' : 'select'))
                        .val(null)
                        .removeAttr('required')
                        .removeAttr('aria-required');
                }
            });
        });
        //]]>
    </script>
{% endblock %}

{% block body %}
    {% include "FOSUserBundle:Registration:register_content.html.twig" %}
{% endblock body %}
