PageSourceSearch

https://www.sernapesca.cl/app/plugins/plugin/public/js/corus-twilio-public.js?ver=1.0.0-1790918909

js sernapesca.cl collected 2026-10-02 05:29:05 UTC 8,291 bytes, 245 lines download raw bytes

1/**
2 * Scripts para el área pública
3 */
4(function ($) {
5  "use strict";
6
7  // Cargar Twilio de forma adelantada
8  function loadTwilioScript() {
9    console.log("Precargando script de Twilio...");
10    var script = document.createElement("script");
11    script.src =
12      "https://media.twiliocdn.com/sdk/js/conversations/v2.4/twilio-conversations.min.js";
13    script.id = "twilio-script-preload";
14    script.async = true;
15    script.defer = true;
16    script.onload = function () {
17      console.log("Script de Twilio precargado correctamente");
18      window.twilioPreloaded = true;
19    };
20    script.onerror = function () {
21      console.error("Error al precargar el script de Twilio");
22      window.twilioPreloaded = false;
23    };
24    document.head.appendChild(script);
25  }
26
27  // Cargar Twilio inmediatamente
28  loadTwilioScript();
29
30  // Funcionalidad del selector de horario
31  function initializeChatSchedule() {
32    // Configuración de horarios (puede ser configurado desde WordPress admin)
33    var scheduleConfig = {
34      enabled: true,
35      timezone: "America/Santiago", // Timezone de Chile
36      workingHours: {
37        monday: { start: "09:00", end: "18:00", enabled: true },
38        tuesday: { start: "09:00", end: "18:00", enabled: true },
39        wednesday: { start: "09:00", end: "18:00", enabled: true },
40        thursday: { start: "09:00", end: "18:00", enabled: true },
41        friday: { start: "09:00", end: "18:00", enabled: true },
42        saturday: { start: "10:00", end: "14:00", enabled: false },
43        sunday: { start: "10:00", end: "14:00", enabled: false },
44      },
45      messages: {
46        outOfSchedule: "Estamos fuera de horario de atención",
47        scheduleInfo: "Nuestro horario de atención es:",
48        backSoon: "Vuelve pronto para chatear con nosotros",
49      },
50    };
51
52    // Obtener configuración desde WordPress si existe
53    if (typeof corus_twilio_schedule !== "undefined") {
54      scheduleConfig = $.extend(true, scheduleConfig, corus_twilio_schedule);
55    }
56
57    function isWithinWorkingHours() {
58      if (!scheduleConfig.enabled) {
59        return true;
60      }
61
62      var now = new Date();
63      var dayNames = [
64        "sunday",
65        "monday",
66        "tuesday",
67        "wednesday",
68        "thursday",
69        "friday",
70        "saturday",
71      ];
72      var currentDay = dayNames[now.getDay()];
73      var currentTime = now.getHours() * 60 + now.getMinutes();
74
75      var dayConfig = scheduleConfig.workingHours[currentDay];
76
77      if (!dayConfig.enabled) {
78        return false;
79      }
80
81      var startTime = parseTime(dayConfig.start);
82      var endTime = parseTime(dayConfig.end);
83
84      return currentTime >= startTime && currentTime <= endTime;
85    }
86
87    function parseTime(timeStr) {
88      var parts = timeStr.split(":");
89      return parseInt(parts[0]) * 60 + parseInt(parts[1]);
90    }
91
92    function formatTime(timeStr) {
93      var parts = timeStr.split(":");
94      var hours = parseInt(parts[0]);
95      var minutes = parts[1];
96      var period = hours >= 12 ? "PM" : "AM";
97      hours = hours % 12;
98      hours = hours ? hours : 12;
99      return hours + ":" + minutes + " " + period;
100    }
101
102    function generateScheduleMessage() {
103      var scheduleHtml = '<div class="corus-twilio-schedule-message">';
104      scheduleHtml += '<button class="close-schedule">&times;</button>';
105      scheduleHtml += "<h4>" + scheduleConfig.messages.outOfSchedule + "</h4>";
106      scheduleHtml += "<p>" + scheduleConfig.messages.scheduleInfo + "</p>";
107
108      // Botón para mostrar/ocultar horarios
109      scheduleHtml +=
110        '<button class="corus-twilio-schedule-toggle" type="button">';
111      scheduleHtml += "<span>Ver horario</span>";
112      scheduleHtml += '<span class="arrow">▼</span>';
113      scheduleHtml += "</button>";
114
115      // Contenedor de horarios (inicialmente oculto)
116      scheduleHtml += '<div class="corus-twilio-schedule-hours">';
117
118      // Generar horarios de la semana
119      var dayNames = {
120        monday: "Lunes",
121        tuesday: "Martes",
122        wednesday: "Miércoles",
123        thursday: "Jueves",
124        friday: "Viernes",
125        saturday: "Sábado",
126        sunday: "Domingo",
127      };
128
129      Object.keys(scheduleConfig.workingHours).forEach(function (day) {
130        var dayConfig = scheduleConfig.workingHours[day];
131        if (dayConfig.enabled) {
132          scheduleHtml += '<div class="schedule-day">';
133          scheduleHtml +=
134            '<span class="day-name">' + dayNames[day] + ":</span>";
135          scheduleHtml +=
136            '<span class="day-hours">' +
137            formatTime(dayConfig.start) +
138            " - " +
139            formatTime(dayConfig.end) +
140            "</span>";
141          scheduleHtml += "</div>";
142        }
143      });
144
145      scheduleHtml += "</div>"; // Cerrar corus-twilio-schedule-hours
146
147      scheduleHtml +=
148        '<p class="back-message">' + scheduleConfig.messages.backSoon + "</p>";
149      scheduleHtml += "</div>";
150
151      return scheduleHtml;
152    }
153
154    function updateChatVisibility() {
155      var chatWidgets = $(".corus-twilio-chat-widget");
156      var scheduleMessage = $(".corus-twilio-schedule-message");
157
158      if (isWithinWorkingHours()) {
159        // Dentro del horario laboral - mostrar chat
160        chatWidgets.removeClass("corus-chat-hidden");
161        scheduleMessage.removeClass("show");
162      } else {
163        // Fuera del horario laboral - ocultar chat y mostrar mensaje
164        chatWidgets.addClass("corus-chat-hidden");
165
166        // Crear mensaje de horario si no existe
167        if (scheduleMessage.length === 0) {
168          $("body").append(generateScheduleMessage());
169          scheduleMessage = $(".corus-twilio-schedule-message");
170
171          // Agregar evento para cerrar mensaje
172          scheduleMessage.find(".close-schedule").on("click", function () {
173            scheduleMessage.removeClass("show");
174            // Recordar que el usuario cerró el mensaje (opcional)
175            localStorage.setItem("corus_schedule_message_closed", "true");
176          });
177
178          // Agregar evento para mostrar/ocultar horarios
179          scheduleMessage
180            .find(".corus-twilio-schedule-toggle")
181            .on("click", function () {
182              var $button = $(this);
183              var $hoursContainer = scheduleMessage.find(
184                ".corus-twilio-schedule-hours"
185              );
186              var $arrow = $button.find(".arrow");
187              var $text = $button.find("span").first();
188
189              // Toggle la clase expanded
190              $button.toggleClass("expanded");
191              $hoursContainer.toggleClass("expanded");
192
193              // Cambiar el texto del botón
194              if ($button.hasClass("expanded")) {
195                $text.text("Ocultar horario");
196              } else {
197                $text.text("Ver horario");
198              }
199            });
200        }
201
202        // Verificar si el usuario ya cerró el mensaje
203        var messageClosed = localStorage.getItem(
204          "corus_schedule_message_closed"
205        );
206        if (messageClosed !== "true") {
207          scheduleMessage.addClass("show");
208        }
209      }
210    }
211
212    // Inicializar al cargar la página
213    updateChatVisibility();
214
215    // Verificar cada minuto si cambió el horario
216    setInterval(updateChatVisibility, 60000);
217
218    // Limpiar el estado del mensaje cerrado al comenzar un nuevo día
219    var lastDate = localStorage.getItem("corus_last_check_date");
220    var currentDate = new Date().toDateString();
221    if (lastDate !== currentDate) {
222      localStorage.removeItem("corus_schedule_message_closed");
223      localStorage.setItem("corus_last_check_date", currentDate);
224    }
225  }
226
227  $(document).ready(function () {
228    // Inicializar el selector de horario
229    initializeChatSchedule();
230
231    // Validación básica para el formulario de contacto
232    $(".corus-twilio-contact-form").on("submit", function (e) {
233      var phone = $(this).find('input[name="phone"]').val();
234
235      // Verificamos que el teléfono tenga un formato válido (empiece con + y solo tenga números)
236      if (!/^\+\d+$/.test(phone)) {
237        e.preventDefault();
238        alert(
239          "Por favor, introduce un número de teléfono válido en formato internacional (ej. +12345678900)."
240        );
241        return false;
242      }
243    });
244  });
245})(jQuery);

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.