PageSourceSearch

https://uptoyoueducacion.com/wp-content/plugins/correosoficial/js/ajax_wc_checkout.js?ver=2.3.0

js uptoyoueducacion.com collected 2026-10-05 05:42:55 UTC 32,996 bytes, 775 lines download raw bytes

1/**
2 * This program is free software: you can redistribute it and/or modify it under the
3 * terms of the GNU General Public License as published by the Free Software Foundation,
4 * either version 3 of the License, or (at your option) any later version.
5 *
6 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
7 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8 * See the GNU General Public License for more details.
9 *
10 * You should have received a copy of the GNU General Public License along with this program.
11 * If not, see https://www.gnu.org/licenses/.
12 */
13// Página cargada
14jQuery(document).ready(function (e) {
15    const actionCityPaq = 'SearchCityPaqByPostalCode';
16    const actionOffice = 'SearchOfficeByPostalCode';
17    const actionPudoCEX = 'SearchPudoCEXByPostalCode';
18    
19    let googleMap = new Array();
20    let carriersData = new Array();
21
22    // ACCIONES SEGÚN CONTEXTO
23    switch (varsAjax.whereAmI) {
24        case 'cart':
25            // Cargamos directamente
26            initLoad();
27            // Cargamos al cambiar de método
28            jQuery(document.body).on('updated_shipping_method', function () {
29                initLoad();
30            });
31            break;
32        case 'checkout':
33            // Esperamos carga ajax del checkout por parte de WC
34            jQuery(document.body).on('updated_checkout', function () {
35                initLoad();
36
37                // Para algunos temas que no llegan a tiempo a cargar el código postal
38                if (jQuery('.search-citypaq-by-cp-input').val() == '' || jQuery('.search-office-by-cp-input').val() == '') {
39                    setTimeout(function () {
40                        initLoad();
41                    }, 3000);
42                }
43            });
44            break;
45    }
46
47    jQuery(document.body).on('updated_wc_div', function () {
48        initLoad();
49    });
50
51    // CARGA INICIAL DE SELECTORES
52    function initLoad() {
53        // EVENTO CAMBIO DE TRANSPORTISTA
54        let carrierSelected = jQuery('input[type="radio"][name^="shipping_method["][name$="]"]:checked');
55        let radioButtonsCarriers = jQuery('input[type="radio"][name^="shipping_method["][name$="]"]');
56        radioButtonsCarriers.on('change', function () {
57            cleanCheckoutMetadata();
58            carrierSelected = jQuery(this).val();
59            let carrierData = carriersData[parseInt(carrierSelected)];
60            
61            if (carrierData != undefined) {
62                if (carrierData.action == actionCityPaq) {
63                    insertCityPaq(carrierData.selected_location, carrierSelected);
64                }
65                if (carrierData.action == actionOffice) {
66                    insertOffice(carrierData.selected_location, carrierSelected);
67                }
68                if (carrierData.action == actionPudoCEX) {
69                    insertPudoCEX(carrierData.selected_location, carrierId);
70                }
71            }
72        });
73
74        // OBTENEMOS SELECTORES CARGADOS
75        let citypaqCarriers = jQuery('[id^="citypaq_selector_"]');
76        let officeCarriers = jQuery('[id^="office_selector_"]');
77
78        // CITYPAQS
79        citypaqCarriers.each(function (index, element) {
80            // Obtenemos el value del elemento
81            let carrierId = jQuery(element).val();
82
83            // Elementos del DOM
84            let currentReference = jQuery('#citypaq_reference_' + carrierId);
85            let currentPostcode = jQuery('#citypaq_postcode_' + carrierId);
86            let inputSearch = jQuery('#SearchCityPaqByCPInput_' + carrierId);
87            let buttonSearch = jQuery('#SearchCityPaqByCpButton_' + carrierId);
88            let selectCityPaqs = jQuery('#CityPaqSelect_' + carrierId);
89            let scheduleAndMap = jQuery('#scheduleAndMap_' + carrierId);
90
91            // Obtenemos metadata
92            let checkoutMetadata = getCheckoutMetadata();
93
94            // Si tenemos metadata, la cargamos
95            if (checkoutMetadata.CarrierID == carrierId) {
96                currentReference.val(checkoutMetadata.SelectedReference);
97
98                // Si no tenemos currentReference, la buscamos en carriersData
99            } else if (!currentReference.val()) {
100                let carrierData = carriersData[carrierId];
101                if (carrierData != undefined) {
102                    currentReference.val(carrierData.selected_location.reference);
103                }
104            }
105
106            // Ocultamos horario y mapa
107            scheduleAndMap.hide();
108
109            // Añadimos postcode al input de búsqueda
110            inputSearch.val(currentPostcode.val());
111            inputSearch.keydown(function (event) {
112                if (event.key === 'Enter') {
113                    event.preventDefault();
114                    buttonSearch.click();
115                }
116            });
117
118            // Si el valor del inputsearch es igual o mayor a 5, buscamos oficinas
119            if (inputSearch.val().length >= 5) {
120                setLocations(actionCityPaq, currentPostcode.val(), carrierId, selectCityPaqs, currentReference.val());
121            }
122
123            // Añadimos evento click al botón de buscar citipaq
124            buttonSearch.on('click', async function () {
125                // Obtenemos el valor del input
126                let searchPostcode = inputSearch.val();
127
128                let searchPostalCodeSub;
129                let shippingAddressPostalCodeSub;
130                if (searchPostcode) {
131                    searchPostalCodeSub = searchPostcode.substring(0, 2);
132                }
133
134                if (currentPostcode.val()) {
135                    let shippingAddressPostalCode = currentPostcode.val();
136                    shippingAddressPostalCodeSub = shippingAddressPostalCode.substring(0, 2);
137                }
138
139                if (searchPostalCodeSub && shippingAddressPostalCodeSub) {
140                    if (searchPostalCodeSub != shippingAddressPostalCodeSub) {
141                        alert(pickupPointSameProvince);
142                        return false;
143                    }
144                }
145
146                // set de locations
147                try {
148                    let locations = await setLocations(actionCityPaq, searchPostcode, carrierId, selectCityPaqs, null);
149                    let selected_location = locations[0];
150                    insertCityPaq(selected_location, carrierId);
151                    currentReference.val(selected_location.reference); // set current reference
152                    currentPostcode.val(searchPostcode); // set current postcode
153                } catch (error) {
154                    alert(cityPaqPostCodeNotFound);
155                    inputSearch.val(currentPostcode.val()); // reset search input
156                }
157            });
158
159            // Map
160            if (defined_google_api_key == 1) {
161                // verificar si google está cargado
162                if (typeof google !== 'undefined') {
163                    let newGoogleMaps = new google.maps.Map(document.getElementById('GoogleMapCorreos_' + carrierId), {
164                        center: { lat: 40.234013044698884, lng: -3.768710630003362 },
165                        zoom: 13,
166                    });
167
168                    googleMap[carrierId] = {
169                        map: newGoogleMaps,
170                        markers: [],
171                    };
172                }
173            }
174        });
175
176        // OFICINAS
177        officeCarriers.each(function (index, element) {
178            // Obtenemos el value del elemento
179            let carrierId = jQuery(element).val();
180
181            // Elementos del DOM
182            let currentReference = jQuery('#office_reference_' + carrierId);
183            let currentPostcode = jQuery('#office_postcode_' + carrierId);
184            let inputSearch = jQuery('#SearchOfficeByCPInput_' + carrierId);
185            let buttonSearch = jQuery('#SearchOfficeByCpButton_' + carrierId);
186            let selectOffices = jQuery('#OfficeSelect_' + carrierId);
187            let scheduleAndMap = jQuery('#scheduleAndMap_' + carrierId);
188
189            // Obtenemos metadata
190            let checkoutMetadata = getCheckoutMetadata();
191
192            // Si tenemos metadata, la cargamos
193            if (checkoutMetadata.CarrierID == carrierId) {
194                currentReference.val(checkoutMetadata.SelectedReference);
195
196                // Si no tenemos currentReference, la buscamos en carriersData
197            } else if (!currentReference.val()) {
198                let carrierData = carriersData[carrierId];
199                if (carrierData != undefined) {
200                    currentReference.val(carrierData.selected_location.reference);
201                }
202            }
203
204            // Ocultamos horario y mapa
205            scheduleAndMap.hide();
206
207            // Añadimos postcode al input de búsqueda
208            inputSearch.val(currentPostcode.val());
209            inputSearch.keydown(function (event) {
210                if (event.key === 'Enter') {
211                    event.preventDefault();
212                    buttonSearch.click();
213                }
214            });
215
216            // Si el valor del inputsearch es igual o mayor a 5, buscamos oficinas
217            if (inputSearch.val().length >= 5) {
218                setLocations(actionOffice, currentPostcode.val(), carrierId, selectOffices, currentReference.val());
219            }
220
221            // Añadimos evento click al botón de buscar oficinas
222            buttonSearch.on('click', async function () {
223                // Obtenemos el valor del input
224                let searchPostcode = inputSearch.val();
225
226                let searchPostalCodeSub;
227                let shippingAddressPostalCodeSub;
228                if (searchPostcode) {
229                    searchPostalCodeSub = searchPostcode.substring(0, 2);
230                }
231
232                if (currentPostcode.val()) {
233                    let shippingAddressPostalCode = currentPostcode.val();
234                    shippingAddressPostalCodeSub = shippingAddressPostalCode.substring(0, 2);
235                }
236
237                if (searchPostalCodeSub && shippingAddressPostalCodeSub) {
238                    if (searchPostalCodeSub != shippingAddressPostalCodeSub) {
239                        alert(pickupPointSameProvince);
240                        return false;
241                    }
242                }
243
244                // set de locations
245                try {
246                    let locations = await setLocations(actionOffice, searchPostcode, carrierId, selectOffices, null);
247                    let selected_location = locations[0];
248                    insertOffice(selected_location, carrierId);
249                    currentReference.val(selected_location.reference); // set current reference
250                    currentPostcode.val(searchPostcode); // set current postcode
251                } catch (error) {
252                    alert(officePostCodeNotFound);
253                    inputSearch.val(currentPostcode.val()); // reset search input
254                }
255            });
256
257            // Map
258            if (defined_google_api_key == 1) {
259                // verificar si google está cargado
260                if (typeof google !== 'undefined') {
261                    let newGoogleMaps = new google.maps.Map(document.getElementById('GoogleMapCorreos_' + carrierId), {
262                        center: { lat: 40.234013044698884, lng: -3.768710630003362 },
263                        zoom: 13,
264                    });
265
266                    googleMap[carrierId] = {
267                        map: newGoogleMaps,
268                        markers: [],
269                    };
270                }
271            }
272        });
273
274        // PUDO CEX
275        let pudocexCarriers = jQuery('[id^="pudocex_selector_"]');
276
277        pudocexCarriers.each(function (index, element) {
278            // Obtenemos el value del elemento
279            let carrierId = jQuery(element).val();
280
281            // Elementos del DOM
282            let currentReference = jQuery('#pudocex_reference_' + carrierId);
283            let currentPostcode = jQuery('#pudocex_postcode_' + carrierId);
284            let inputSearch = jQuery('#SearchPudoCEXByCPInput_' + carrierId);
285            let buttonSearch = jQuery('#SearchPudoCEXByCpButton_' + carrierId);
286            let selectPudoCEX = jQuery('#PudoCEXSelect_' + carrierId);
287            let scheduleAndMap = jQuery('#scheduleAndMap_' + carrierId);
288
289            // Obtenemos metadata
290            let checkoutMetadata = getCheckoutMetadata();
291
292            // Si tenemos metadata, la cargamos
293            if (checkoutMetadata.CarrierID == carrierId) {
294                currentReference.val(checkoutMetadata.SelectedReference);
295            } else if (!currentReference.val()) {
296                let carrierData = carriersData[carrierId];
297                if (carrierData != undefined) {
298                    currentReference.val(carrierData.selected_location.reference);
299                }
300            }
301
302            // Ocultamos horario y mapa
303            scheduleAndMap.hide();
304
305            // Añadimos postcode al input de búsqueda
306            inputSearch.val(currentPostcode.val());
307            inputSearch.keydown(function (event) {
308                if (event.key === 'Enter') {
309                    event.preventDefault();
310                    buttonSearch.click();
311                }
312            });
313
314            // Si el valor del inputsearch es igual o mayor a 5, buscamos puntos pudocex
315            if (inputSearch.val().length >= 5) {
316                setLocations(actionPudoCEX, currentPostcode.val(), carrierId, selectPudoCEX, currentReference.val());
317            }
318
319            // Añadimos evento click al botón de buscar pudocex
320            buttonSearch.on('click', async function () {
321                // Obtenemos el valor del input
322                let searchPostcode = inputSearch.val();
323
324                let searchPostalCodeSub;
325                let shippingAddressPostalCodeSub;
326                if (searchPostcode) {
327                    searchPostalCodeSub = searchPostcode.substring(0, 2);
328                }
329
330                if (currentPostcode.val()) {
331                    let shippingAddressPostalCode = currentPostcode.val();
332                    shippingAddressPostalCodeSub = shippingAddressPostalCode.substring(0, 2);
333                }
334
335                if (searchPostalCodeSub && shippingAddressPostalCodeSub) {
336                    if (searchPostalCodeSub != shippingAddressPostalCodeSub) {
337                        alert(pickupPointSameProvince);
338                        return false;
339                    }
340                }
341
342                // set de locations
343                try {
344                    let locations = await setLocations(actionPudoCEX, searchPostcode, carrierId, selectPudoCEX, null);
345                    let selected_location = locations[0];
346                    insertPudoCEX(selected_location, carrierId);
347                    currentReference.val(selected_location.reference); // set current reference
348                    currentPostcode.val(searchPostcode); // set current postcode
349                } catch (error) {
350                    alert(pudoCEXPostCodeNotFound);
351                    inputSearch.val(currentPostcode.val()); // reset search input
352                }
353            });
354
355            // Map
356            if (defined_google_api_key == 1) {
357                // verificar si google está cargado
358                if (typeof google !== 'undefined') {
359                    let newGoogleMaps = new google.maps.Map(document.getElementById('GoogleMapCorreos_' + carrierId), {
360                        center: { lat: 40.234013044698884, lng: -3.768710630003362 },
361                        zoom: 13,
362                    });
363
364                    googleMap[carrierId] = {
365                        map: newGoogleMaps,
366                        markers: [],
367                    };
368                }
369            }
370        });
371    }
372
373    // OBTIENE Y CARGA LOCATIONS
374    function setLocations(action, postcode, id_carrier, select, currentReference) {
375        return new Promise(function (resolve, reject) {
376            let results = new Array();
377            let selectedOutput = null;
378            
379            jQuery.ajax({
380                url: varsAjax.ajaxUrl,
381                type: 'POST',
382                data: {
383                    action: 'correosOficialDispacher',
384                    _nonce: varsAjax.nonce,
385                    dispatcher: {
386                        controller: 'CorreosOficialCheckoutModuleFrontController',
387                        action: action,
388                        id_carrier: id_carrier,
389                        postcode: postcode,
390                        shortcode: true,
391                    },
392                },
393                cache: false,
394                processData: true,
395                success: function (parsed_data) {
396
397                    // Parseamos para CityPaq
398                    if (action == actionCityPaq) {
399                        selectedOutput = jQuery('#citypaq_reference_' + id_carrier);
400
401                        parsed_data.forEach(function (location) {
402                            let data = {
403                                reference: location.reference,
404                                address: location.address,
405                                city: location.city,
406                                cp: location.zipcode,
407                                terminal: location.data.alias,
408                                schedule: location.schedule,
409                                lat: parseFloat(location.lat),
410                                lng: parseFloat(location.long),
411                                raw: location.data,
412                                full: location
413                            };
414                            results.push(data);
415                        });
416
417                        // Si tenemos resultados
418                        if (results.length > 0) {
419                            fillSelect(id_carrier, action, select, results, currentReference, selectedOutput);
420                            resolve(results);
421                        } else {
422                            cleanCheckoutMetadata();
423                            alert(cityPaqPostCodeNotFound);
424                        }
425                    }
426
427                    // Parseamos para Oficinas
428                    if (action == actionOffice) {
429                        selectedOutput = jQuery('#office_reference_' + id_carrier);
430
431                        parsed_data.forEach(function (location) {
432                            let data = {
433                                reference: location.reference,
434                                address: location.address,
435                                city: location.city,
436                                cp: location.zipcode,
437                                terminal: location.name,
438                                schedule: {
439                                    horarioLV: location.scheduleLV,
440                                    horarioS: location.scheduleS,
441                                    horarioF: location.scheduleF,
442                                },
443                                lat: parseFloat(location.lat),
444                                lng: parseFloat(location.long),
445                                raw: location.data,
446                                full: location
447                            };
448                            results.push(data);
449                        });
450
451                        // Si tenemos resultados
452                        if (results.length > 0) {
453                            fillSelect(id_carrier, action, select, results, currentReference, selectedOutput);
454                            resolve(results);
455                        } else {
456                            cleanCheckoutMetadata();
457                            alert(officePostCodeNotFound);
458                        }
459                    }
460
461                    // Parseamos para PudoCEX
462                    if (action == actionPudoCEX) {
463                        selectedOutput = jQuery('#pudocex_reference_' + id_carrier);
464
465                        parsed_data.forEach(function (location) {
466                            let data = {
467                                reference: location.reference,
468                                address: location.address,
469                                city: location.city,
470                                cp: location.zipcode,
471                                terminal: location.name,
472                                phone: location.phone,
473                                schedule: {
474                                    horarioLV: location.scheduleLV,
475                                    horarioS: location.scheduleS,
476                                    horarioF: location.scheduleF,
477                                },
478                                lat: parseFloat(location.lat),
479                                lng: parseFloat(location.long),
480                                raw: location.data,
481                                full: location
482                            };
483                            results.push(data);
484                        });
485
486                        // Si tenemos resultados
487                        if (results.length > 0) {
488                            fillSelect(id_carrier, action, select, results, currentReference, selectedOutput);
489                            resolve(results);
490                        } else {
491                            cleanCheckoutMetadata();
492                            alert(pudoCEXPostCodeNotFound);
493                        }
494                    }
495                },
496                error: function (e) {
497                    reject(false);
498                },
499            });
500        });
501    }
502
503    // CARGA EL SELECT DEL CARRIER PASADO
504    function fillSelect(id_carrier, action, select, locations, currentReference, selectedOutput = null) {
505        let currentLocation;
506
507        // Desactivamos evento change en el select
508        select.off('change');
509
510        // Eliminamos todos los options
511        select.find('option').remove();
512
513        // Si tenemos currentReference, buscamos el location
514        if (currentReference) {
515            currentLocation = locations.find((location) => location.reference == currentReference);
516        }
517
518        // Si no tenemos currentReference, seleccionamos el primero
519        if (!currentReference || currentLocation == undefined) {
520            currentReference = locations[0].reference;
521            currentLocation = locations.find((location) => location.reference == currentReference);
522            if (selectedOutput != null) {
523                selectedOutput.val(currentReference);
524            }
525        }
526
527        // Opción seleccionada para este select
528        option_selected = locations.find((location) => location.reference == currentReference);
529        if (option_selected == undefined && locations.length > 0) {
530            option_selected = locations[0];
531        }
532
533        // Carrier data
534        updateCarrierData(id_carrier, action, option_selected);
535
536        locations.forEach(function (location) {
537
538            // Si tenemos guardado el punto de entrega para el carrito, lo seleccionamos
539            if(location.cart){
540                currentReference = location.reference;
541            }
542
543            if (currentReference == location.reference) {
544                select.append('<option value=' + location.reference + ' selected>' + location.terminal + '</option>');
545
546                let carrierData = carriersData[parseInt(id_carrier)];
547
548                if (carrierData != undefined) {
549                    if (action == actionCityPaq) {
550                        insertCityPaq(location, id_carrier);
551                    }
552                    if (action == actionOffice) {
553                        insertOffice(location, id_carrier);
554                    }
555                    if (action == actionPudoCEX) {
556                        insertPudoCEX(location, id_carrier);
557                    }
558                }
559
560            } else {
561                select.append('<option value=' + location.reference + '>' + location.terminal + '</option>');
562            }
563        });
564
565        // Mostramos horario, direccion y mapa
566        setScheduleAndMap(id_carrier, locations, currentReference, action);
567
568        // Tras Cargar los options, activamos el evento change
569        select.on('change', function () {
570
571            // obtenemos el valor de la option seleccionada y asignamos al hidden del carrier
572            //if (selectedOutput != null) {
573                // selectedOutput.val(jQuery(this).val());
574
575                // Configuramos horarios
576                setScheduleAndMap(id_carrier, locations, jQuery(this).val(), action);
577
578                let selected_location = locations.find((location) => location.reference == jQuery(this).val());
579
580                // Guardamos en BD
581                if (action == actionCityPaq) {
582                    insertCityPaq(selected_location, id_carrier);
583                }
584
585                if (action == actionOffice) {
586                    insertOffice(selected_location, id_carrier);
587                }
588
589                if (action == actionPudoCEX) {
590                    insertPudoCEX(selected_location, id_carrier);
591                }
592            //}
593        });
594    }
595
596    // CONTROL MARCADORES EN MAPA
597    function setGoogleMapsMarkers(carrierId, myLatLng, title) {
598        if (defined_google_api_key == 1) {
599            let carrierMap = googleMap[carrierId];
600            if (carrierMap != undefined) {
601                let map = googleMap[carrierId].map;
602                let markers = googleMap[carrierId].markers;
603
604                // Verificar si hay marcadores existentes para este transportista y eliminamos
605                if (markers.length > 0) {
606                    markers.forEach(function (marker) {
607                        marker.setMap(null);
608                    });
609                }
610                let marker = new google.maps.Marker({
611                    position: myLatLng,
612                    title: title,
613                });
614
615                marker.setMap(map);
616                markers.push(marker);
617
618                map.setCenter(myLatLng);
619                map.setZoom(14);
620            }
621        }
622    }
623
624    // ACIONES HORARIOS Y MAPA
625    function setScheduleAndMap(id_carrier, locations, reference, action) {
626        let scheduleAndMap = jQuery('#scheduleAndMap_' + id_carrier);
627
628        // buscamos en el array de locations el que tenga el reference seleccionado
629        let locationSelected = locations.find((location) => location.reference == reference);
630        if (locationSelected == undefined && locations.length > 0) {
631            locationSelected = locations[0];
632        }
633
634        // Mostramos horario, direccion y mapa
635        scheduleAndMap.show();
636
637        // Actualizamos horario, dirección y mapa del carrier para CityPaq
638        if (action == actionCityPaq && locationSelected != undefined) {
639            scheduleAndMap.find('.citypaq-address-info p.address').text(locationSelected.address);
640            scheduleAndMap.find('.citypaq-address-info p.city').text(locationSelected.city);
641            scheduleAndMap.find('.citypaq-address-info p.cp').text(locationSelected.cp);
642            scheduleAndMap.find('.citypaq-terminal-info p').text(locationSelected.terminal);
643            scheduleAndMap.find('.scheduleInfo p').text(locationSelected.schedule === '1' ? openingInfo : opening24hInfo);
644        }
645
646        // Actualizamos horario, dirección y mapa del carrier para Oficinas o Pudos de Cex
647        if ((action == actionOffice || action == actionPudoCEX) && locationSelected != undefined) {
648            scheduleAndMap.find('.office-address-info p.address').text(locationSelected.address);
649            scheduleAndMap.find('.office-address-info p.city').text(locationSelected.city);
650            scheduleAndMap.find('.office-address-info p.cp').text(locationSelected.cp);
651            scheduleAndMap.find('.office-address-info p.phone').text(locationSelected.phone);
652            scheduleAndMap.find('.office-terminal-info p').text(locationSelected.terminal);
653            scheduleAndMap.find('.scheduleInfo p.timeScheduleLV').text(locationSelected.schedule.horarioLV);
654            scheduleAndMap.find('.scheduleInfo p.timeScheduleS').text(locationSelected.schedule.horarioS);
655            scheduleAndMap.find('.scheduleInfo p.timeScheduleF').text(locationSelected.schedule.horarioF);
656        }
657
658        // map
659        setGoogleMapsMarkers(id_carrier, { lat: locationSelected.lat, lng: locationSelected.lng }, locationSelected.terminal);
660    }
661
662    function updateCarrierData(id_carrier, action, selected_location) {
663        carriersData[id_carrier] = {
664            action: action,
665            selected_location: selected_location,
666        };
667    }
668
669    function insertCityPaq(selected_location, id_carrier) {
670        // Carrier data
671        updateCarrierData(id_carrier, actionCityPaq, selected_location);
672
673        // Metadata
674        setMetadataCheckout(parseInt(id_carrier), 'CityPaq', selected_location.reference, JSON.stringify(selected_location.raw));
675    }
676
677    function insertOffice(selected_location, id_carrier) {
678        // Carrier data
679        updateCarrierData(id_carrier, actionOffice, selected_location);
680
681        // Metadata
682        setMetadataCheckout(parseInt(id_carrier), 'Oficina', selected_location.reference, JSON.stringify(selected_location.raw));
683    }
684
685    function insertPudoCEX(selected_location, id_carrier) {
686        // Carrier data
687        updateCarrierData(id_carrier, actionPudoCEX, selected_location);
688
689        setMetadataCheckout(parseInt(id_carrier), 'pudocex', selected_location.reference, JSON.stringify(selected_location.raw));
690    }
691
692    function setMetadataCheckout(CarrierID, ReferenceType, SelectedReference, SelectedReferenceData) {
693        let metadataArray = [
694            { name: 'CarrierID', value: parseInt(CarrierID) },
695            { name: 'ReferenceType', value: 'Oficina' },
696            { name: 'SelectedReference', value: SelectedReference },
697            { name: 'SelectedReferenceData', value: SelectedReferenceData },
698        ];
699
700        // Actualizamos cookie
701        let checkoutMetadata = getCheckoutMetadata();
702        metadataArray.forEach(function (metadata) {
703            let inputName = metadata.name;
704            let newValue = metadata.value;
705            checkoutMetadata[inputName] = newValue;
706        });
707        checkoutMetadata = JSON.stringify(checkoutMetadata);
708        checkoutMetadata = btoa(checkoutMetadata);
709        document.cookie = 'correosoficial_checkout=' + checkoutMetadata + '; path=/';
710
711        // Actualizamos formulario
712        let checkoutForm = jQuery('form[name="checkout"]');
713
714        metadataArray.forEach(function (metadata) {
715            let inputName = metadata.name;
716            let newValue = metadata.value;
717            let inputExist = jQuery('[name="' + inputName + '"]');
718
719            if (inputExist.length > 0) {
720                inputExist.val(newValue);
721            } else {
722                // El input no existe, crear uno nuevo y agregarlo al formulario
723                let newInput = jQuery('<input>').attr('type', 'hidden').attr('name', inputName).val(newValue);
724                checkoutForm.append(newInput);
725            }
726        });
727    }
728
729    function cleanCheckoutMetadata() {
730        let metadataArray = ['CarrierID', 'ReferenceType', 'SelectedReference', 'SelectedReferenceData'];
731
732        // Limpiamos inputs formulario
733        metadataArray.forEach(function (metadata) {
734            let inputExist = jQuery('[name="' + metadata + '"]');
735            if (inputExist.length > 0) {
736                inputExist.remove();
737            }
738        });
739
740        // Limpiamos cookie
741        let checkoutMetadata = getCheckoutMetadata();
742        metadataArray.forEach(function (metadata) {
743            checkoutMetadata[metadata] = '';
744        });
745
746        checkoutMetadata = JSON.stringify(checkoutMetadata);
747        checkoutMetadata = btoa(checkoutMetadata);
748        document.cookie = 'correosoficial_checkout=' + checkoutMetadata + '; path=/';
749    }
750
751    // Obtenemos metadata del checkout
752    function getCheckoutMetadata() {
753        return false;
754        let checkoutMetadata = getCookie('correosoficial_checkout');
755        checkoutMetadata = atob(checkoutMetadata);
756        checkoutMetadata = JSON.parse(checkoutMetadata);
757        return checkoutMetadata;
758    }
759
760    // Función para obtener el valor de una cookie específica
761    function getCookie(name) {
762        const nameEQ = name + '=';
763        const cookies = document.cookie.split(';');
764        for (let i = 0; i < cookies.length; i++) {
765            let cookie = cookies[i];
766            while (cookie.charAt(0) === ' ') {
767                cookie = cookie.substring(1);
768            }
769            if (cookie.indexOf(nameEQ) === 0) {
770                return decodeURIComponent(cookie.substring(nameEQ.length));
771            }
772        }
773        return null;
774    }
775});

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.