PageSourceSearch

https://www.stych.fr/js/stych/prix-local.js?v=1745302574

js stych.fr collected 2026-10-09 22:42:02 UTC 9,642 bytes, 296 lines download raw bytes

1
2function selectFirstPredictionOnEnter(input) {
3   var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent;
4 
5   function addEventListenerWrapper(type, listener) {
6       if(type == 'keydown') {
7           var orig_listener = listener;
8 
9           listener = function(event) {
10               var suggestion_selected = $(".pac-item-selected").length > 0;
11 
12               if (event.which == 13 && !suggestion_selected) {
13                   var simulated_downarrow = $.Event("keydown", {
14                       keyCode: 40,
15                       which: 40
16                   });
17 
18                   orig_listener.apply(input, [simulated_downarrow]);
19               }
20 
21               orig_listener.apply(input, [event]);
22           };
23       }
24 
25       _addEventListener.apply(input, [type, listener]);
26   }
27 
28   if (input.addEventListener)
29       input.addEventListener = addEventListenerWrapper;
30   else if (input.attachEvent)
31       input.attachEvent = addEventListenerWrapper;
32 }
33
34(function() {
35   if (window.prixLocalInitialized) {
36      return;
37   }
38   window.prixLocalInitialized = true;
39
40   // gestion de la géolocalisation.
41   function handleGeolocation() {
42      if (!navigator.geolocation) {
43         alert("La géolocalisation n'est pas supportée par ce navigateur.");
44         return;
45      }
46
47      navigator.geolocation.getCurrentPosition(
48         position => {
49            updateZipCodeFromCoordinates({
50               lat: position.coords.latitude,
51               lng: position.coords.longitude
52            }, window.location_container);
53         },
54         () => alert("La géolocalisation a échoué.")
55      );
56   }
57
58   // gestion de l'enregistrement du code postal.
59   function handleSubmitZipCode(context) {
60      let zip_code = $(context).find('.zip-code-prix-local').val();
61      let city = $(context).find('.city-prix-local').val();
62
63      var data = {
64         zip_code: zip_code,
65         city: city,
66         update_info_eleve: window.PRIX_LOCAL_CONFIG.update_info_eleve
67      };
68
69      $.pjson(window.PRIX_LOCAL_CONFIG.handleTarifLocalUrl, data)
70      .done(function (data) {
71         if (data.statut == 'OK') {
72            window.location.reload();
73         }
74      });
75   }
76
77   // gestion de l'autocomplete.
78   function initializeAutocomplete()
79   {
80      if (window.googleMapAutoCompleteInitialized)
81         return;
82      window.googleMapAutoCompleteInitialized = true;
83
84      const options = {
85         componentRestrictions: { country: ["fr"] },
86         types: ['(regions)'],
87         fields: ["place_id", "name", "geometry", "formatted_address"]
88      };
89
90      $('.input-search-display').each(function() {
91         const input = this;
92         const autocomplete = new google.maps.places.Autocomplete(input, options);
93         selectFirstPredictionOnEnter(input)
94
95         google.maps.event.addListener(autocomplete, 'place_changed', () => {
96            handlePlaceSelection(autocomplete.getPlace(), this);
97         });
98      });
99   }
100
101   function initializeGoogleMap(callback)
102   {
103      if (window.googleMapsScriptIsInjected)
104         return;
105      window.googleMapsScriptIsInjected = true;
106
107      window.onGoogleMapsLoaded = function() {
108         window.googleMapsLoaded = true;
109         if (typeof callback === "function") {
110            callback();
111         }
112      };
113
114      var options = {
115         key: window.GOOGLEMAP_API_KEY,
116         loading: 'async',
117         language: 'fr',
118         libraries: 'places',
119         v: window.GOOGLE_MAPS_API_VERSION,
120         callback: 'onGoogleMapsLoaded'
121      }
122
123      var optionsQuery = Object.keys(options)
124         .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(options[k]))
125         .join('&');
126
127      var apiURL = 'https://maps.googleapis.com/maps/api/js?' + optionsQuery;
128      var mapScript = document.createElement('script');
129      mapScript.setAttribute('src', apiURL);
130      mapScript.setAttribute('async', '');
131      mapScript.setAttribute('defer', '');
132
133      document.head.appendChild(mapScript);
134   }
135
136   // quand on clique sur une option du select.
137   function handlePlaceSelection(place, inputElement) {
138      const context = $(inputElement).closest('.location-container');
139      const zip_code = extractZipCode(place.address_components);
140      const city = extractCity(place.address_components);
141
142      if (zip_code) {
143         updateZipCodeInput(context, zip_code, city);
144      }
145      else if (place.geometry) {
146         updateZipCodeFromCoordinates(place.geometry.location, context);
147      } else {
148         handleInvalidZipCode(context);
149      }
150   }
151
152   // on détermine le zipcode via le retour de l'api.
153   function extractZipCode(addressComponents) {
154      if (!addressComponents)
155         return '';
156
157      const postalComponent = addressComponents.find(component =>
158         component.types.includes("postal_code")
159      );
160
161      if (!postalComponent || !postalComponent.long_name)
162         return '';
163
164      return postalComponent.long_name;
165   }
166
167   // on détermine la ville via le retour de l'api.
168   function extractCity(addressComponents) {
169      if (!addressComponents) return '';
170
171      const cityComponent = addressComponents.find(component =>
172         component.types.includes("locality")
173      );
174
175      return cityComponent ? cityComponent.long_name : '';
176   }
177
178   // on détermine le zipcode via lat/lng quand l'utilisateur clique sur une ville et non un code postal.
179   function updateZipCodeFromCoordinates(location, context) {
180      const geocoder = new google.maps.Geocoder();
181
182      geocoder.geocode({
183         location: {
184            lat: typeof location.lat === 'function' ? location.lat() : location.lat,
185            lng: typeof location.lng === 'function' ? location.lng() : location.lng
186         }
187      }, (results, status) => handleGeocodeResponse(results, status, context));
188   }
189
190   // gestion du retour de geocode.
191   function handleGeocodeResponse(results, status, context) {
192      if (status !== 'OK' || !results[0]) {
193         handleInvalidZipCode("Géolocalisation échouée.", context);
194         return;
195      }
196
197      var authLocationType = [
198         'neighborhood',
199         'establishment',
200         'political',
201         'locality',
202         'colloquial_area',
203         'sublocality',
204         'postal_code',
205         'country',
206         'administrative_area_level_1',
207         'administrative_area_level_2'
208      ];
209
210      var info_result = [];
211
212      for (j = 0; j < results.length; j++) {
213         var result = results[j];
214
215         var type = result.types[0];
216         if (!authLocationType.includes(type) || !extractZipCode(result.address_components))
217            continue;
218
219         info_result = result;
220         break;
221      }
222
223      const zip_code = extractZipCode(info_result.address_components);
224      const city = extractCity(info_result.address_components);
225
226      if (zip_code) {
227         updateZipCodeInput(context, zip_code, city);
228      } else {
229         handleInvalidZipCode("Impossible de détecter un code postal à partir de cette position.", context);
230      }
231   }
232
233   function updateZipCodeInput(context, zip_code, city = '') {
234      $(context).find('.zip-code-prix-local').val(zip_code);
235      $(context).find('.city-prix-local').val(city);
236
237      const displayValue = city ? `${zip_code} - ${city}` : zip_code;
238      $(context).find('.input-search-display').val(displayValue);
239
240      $(context).trigger('locationUpdated');
241   }
242
243   // gestion des cas de zipcode invalides
244   function handleInvalidZipCode(message = "Veuillez sélectionner une ville ou un code postal valide.", 
244context) {
245      if (typeof message !== 'string') {
246         message = "Veuillez sélectionner une ville ou un code postal valide.";
247      }
248      alert(message);
249      updateZipCodeInput(context, '');
250   }
251
252   window.googleMapsScriptIsInjected = false;
253   window.googleMapAutoCompleteInitialized = false
254   window.googleMapsLoaded = false;
255   window.location_container = null;
256   $(document).ready(() => {
257      $('.location-container').off('locationUpdated').one('locationUpdated', function() {
258         if ($(this).data('auto-submit') === 1) {
259            handleSubmitZipCode($(this));
260         }
261      });
262
263      $('.input-search').on('input', function() {
264         if (window.googleMapsLoaded) {
265            initializeAutocomplete();
266         } else {
267            initializeGoogleMap(initializeAutocomplete);
268         }
269      });
270
271      $(document).on('click', '.btn-geolocation', function() {
272         window.location_container = $(this).closest('.location-container');
273         if (window.googleMapsLoaded) {
274            handleGeolocation();
275         } else {
276            initializeGoogleMap(handleGeolocation);
277         }
278      });
279
280      $(document).on('click', '.btn-submit-zipcode', function() {
281         let zip_code = $(this).closest('.location-container').find('.zip-code-prix-local').val();
282         let city = $(this).closest('.location-container').find('.city-prix-local').val();
283
284         if (!zip_code || !city)
285            alert("Merci d'indiquer ton code postal");
286         else
287            handleSubmitZipCode($(this).closest('.location-container'));
288      });
289
290      $('.zip-code-trigger, .btn-action, .trigger-zip-modal').on('click', function() {
291         $('#modalZipCode').modal('show');
292      });
293
294   });
295
296})();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.