{extends file="$layouts_admin"}
{block name="head"}



<link
  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"
  rel="stylesheet"
/>


{/block}

{block name="content"}

<style type="text/css">

    .list-group{
        max-height: 150px;
        margin-bottom: 10px;
        overflow:scroll;
        -webkit-overflow-scrolling: touch;
    }    

    .swal2-container {
         z-index: 9999;
      }

.wrapper {
  overflow: hidden;  
}

ul.breadcrumbs {
  margin: 0;
  padding: 0;
  display: flex; /* Cambiar a flex para un mejor ajuste en pantallas pequeñas */
  flex-wrap: wrap; /* Permitir que los elementos se ajusten en múltiples líneas si es necesario */
  justify-content:center;
}

ul.breadcrumbs li {
  position: relative;
  margin: 0;
  padding: 0;
  list-style: none;
  display: inline-block;
  border-left: 1px solid #ccc;
  transition: 0.3s ease;
}

ul.breadcrumbs li:hover:before {
  /* border-left: 10px solid #5e6e82; */
}

ul.breadcrumbs li:hover a {
  /* color: white;
  background: #5e6e82; */
 
}

ul.breadcrumbs li:before {
  content: "";
  position: absolute;
  right: -9px;
  top: 50%; /* Centrar el triángulo verticalmente */
  transform: translateY(-50%); /* Ajustar la posición */
  z-index: 20;
  border-left: 10px solid #fff;
  border-top: 22px solid transparent;
  border-bottom: 22px solid transparent;
  transition: 0.3s ease;
}

ul.breadcrumbs li:after {
  content: "";
  position: absolute;
  right: -10px;
  top: 50%; /* Centrar el triángulo verticalmente */
  transform: translateY(-50%); /* Ajustar la posición */
  z-index: 10;
  border-left: 10px solid #ccc;
  border-top: 22px solid transparent;
  border-bottom: 22px solid transparent;
}

ul.breadcrumbs li.active {
  background: #5e6e82; /* Fondo para el activo */
}

ul.breadcrumbs li.active a {
  color: white !important; /* Color del texto activo */
  padding: 0 15px 0 25px; /* Ajustar el padding */
  background: #5e6e82;
}

ul.breadcrumbs li.first {
  border-left: none;
}

ul.breadcrumbs li.first a {
  font-size: 18px;
  padding-left: 20px;
  border-radius: 5px 0px 0px 5px;
}

ul.breadcrumbs li.last:before {
  display: none;
}

ul.breadcrumbs li.last:after {
  display: none;
}

ul.breadcrumbs li.last a {
  padding-right: 20px;
  border-radius: 0px 40px 40px 0px;
}

ul.breadcrumbs li a {
  display: block;
  font-size: 12px;
  line-height: 40px;
  color: #757575;
  padding: 0px 15px 0px 25px;
  text-decoration: none;
  background: #fff;
  border: 1px solid #ddd;
  white-space: nowrap; /* Evitar que el texto se envuelva */
  overflow: hidden;
  transition: 0.3s ease;
}

ul.breadcrumbs li.active:before {
  display: block; /* Mostrar el triángulo en el activo */
}

ul.breadcrumbs li.active:after {
  display: block; /* Mostrar el triángulo secundario en el activo */
}

@media (max-width: 768px) {
  ul.breadcrumbs {
    flex-direction: column; /* Cambiar a una columna en pantallas más pequeñas */
  }

  ul.breadcrumbs li {
    border-left: none; /* Eliminar el borde izquierdo en pantallas pequeñas */
    margin-bottom: 5px; /* Espaciado entre elementos */
    margin-right: 10px;
  }
}
ul.breadcrumbs li.active:before {
  border-left: 10px solid #5e6e82; /* Cambia el color del triángulo al hacer hover sobre el activo */
}

.cursor_manito {
  cursor: pointer;
}



</style>

    <input
         type="text"
         value="{$url_base}"
         disabled
         hidden
         id="URL_BASE"
    />

    <input
         type="text"
         value="{$id_user}"
         disabled
         hidden
         id="ID_USER"
    />

   <input
         type="text"
         value="{$UUID_ENC}"
         disabled
         hidden
         id="UUID_ENC"
    />

    <input
         type="text"
         value="{$UUID}"
         disabled
         hidden
         id="UUID"
    />

    <input
         type="text"
         value="{$id_ifp}"
         disabled
         hidden
         id="id_ifp"
    />

   <input type="text" id="url_modulo_api_direccion_smarty" name="url_modulo_api_direccion_smarty" class="form-control url_modulo_api_direccion_smarty" value="{$url_modulo_api_direccion_smarty}" disabled hidden >
   <input type="text" id="key_modulo_api_direccion_smarty" name="key_modulo_api_direccion_smarty" class="form-control key_modulo_api_direccion_smarty" value="{$key_modulo_api_direccion_smarty}" disabled hidden  >
   <input type="text" id="host_modulo_api_direccion_smarty" name="host_modulo_api_direccion_smarty" class="form-control host_modulo_api_direccion_smarty" value="{$host_modulo_api_direccion_smarty}" disabled hidden  >
   <input type="text" id="referer_modulo_api_direccion_smarty" name="referer_modulo_api_direccion_smarty" class="form-control referer_modulo_api_direccion_smarty" value="{$referer_modulo_api_direccion_smarty}" disabled hidden  >

 
<div class="row pantalla_cargada"  style="display: none;">
   <div class="col-12 col-lg-12 col-sm-12 col-md-12">
      <div class="panel">
         <div class="panel-hdr">
            <h2><span></span>Prospecting Stages</h2>
         </div>

         <div class="panel-container show" id="ibox_form">
            <div class="panel-content">
               <div class="wrapper">
                  <ul class="breadcrumbs">
                     <li class="cursor_manito" data-id="datos_prestamos">
                        <a>Loan details</a>
                     </li>

                     <li
                        class="cursor_manito active"
                        data-id="historial_crediticio"
                     >
                        <a>Credit history</a>
                     </li>

                     <li class="cursor_manito" data-id="general_information">
                        <a>General information</a>
                     </li>

                     <li class="cursor_manito" data-id="referencia">
                        <a>References</a>
                     </li>

                     <li class="cursor_manito" data-id="documento_respaldo">
                        <a>Supporting documents</a>
                     </li>

                     <li class="cursor_manito" data-id="preaprobacion">
                        <a>Pre-approval</a>
                     </li>

                     <li class="cursor_manito" data-id="plan_pago">
                        <a>Payment plan</a>
                     </li>

                     <li class="cursor_manito" data-id="desembolzo">
                        <a>Disbursement</a>
                     </li>

                     <!--  -->
                  </ul>
               </div>
            </div>
         </div>
      </div>
   </div>

   {**}
   <div class="col-md-12">
      <div class="panel">
         <div class="panel-hdr">
            <h2>Credit history</h2>
         </div>

         <div class="panel-container show" id="ibox_form">
            <div class="panel-content" style="padding: 0px">
               <div class="table-responsive">
                  <table
                     class="table table-striped table-hover estilosTabla"
                     id="clx_datatable"
                     style="margin: 0px"
                  >
                     <thead>
                        <tr>
                           <th class="centrar">No. Credit</th>
                           <th class="centrar">Start date</th>
                           <th class="centrar">Expiration Date</th>
                           <th class="centrar">Term</th>
                           <th class="centrar">Amount</th>
                           <th class="centrar">Interest rate</th>
                           <th class="centrar">State</th>
                            
                        </tr>
                     </thead>

                     <tbody class="tbody_envios">
                        
                     </tbody>
                  </table>
               </div>

               {*botones*}
               <div class="row">
                  <div class="col-md-12">
                     <div
                        class="mb-3"
                        style="display: flex; justify-content: space-between"
                     >
                        <button
                           class="mt-3 ms-3 btn btn-default waves-effect waves-themed back"
                           type="button"
                           id="submit"
                        >
                           Back
                        </button>

                        <div>
                           <button
                              class="btn btn-primary mt-3 me-3 waves-effect waves-themed guardar_siguiente"
                              type="button"
                              id="submit"
                           >
                              Next
                           </button>

                           <button
                              class="btn btn-primary mt-3 me-3 waves-effect waves-themed loading_guardar_siguiente"
                              style="display: none"
                              disabled
                           >
                              <div style="display: flex; align-items: center">
                                 <span
                                    class="spinner-border spinner-border-sm"
                                    style="
                                       height: 20px;
                                       width: 20px;
                                       margin-right: 5px;
                                    "
                                    role="status"
                                    aria-hidden="true"
                                 ></span>
                                 Next
                              </div>
                           </button>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>


{***}
<div
   class="modal fade"
   id="modalMensaje"
   data-bs-backdrop="static"
   data-bs-keyboard="false"
   tabindex="-1"
   aria-labelledby="staticBackdropLabel"
   aria-hidden="true"
>
   <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
         <div class="modal-header">
            <h5
               class="modal-title modal_titulo_mensaje"
               id="staticBackdropLabel"
            >
               Group Message
            </h5>
            <button
               type="button"
               class="btn-close btn_cerrar_confirmacion_modal"
            ></button>
         </div>
         <div class="modal-body text-center">
            <p class="modal_contenido_mensaje">
               The group advertising campaign has been sent. For more
            </p>
         </div>
      </div>
   </div>
</div>

 {**}

{**}
<div
   class="modal fade"
   id="modal_asignar_clientes_contactos"
   data-bs-backdrop="static"
   data-bs-keyboard="false"
   tabindex="-1"
   aria-labelledby="staticBackdropLabel4"
   aria-hidden="true"
>
   <div
      class="modal-dialog modal-dialog-centered modal-xl"
      style="max-width: 80%"
   >
      <div class="modal-content">
         <div class="modal-header">
            <h5 class="modal-title" id="staticBackdropLabel4">
               Search Customer
            </h5>

            <button
               type="button"
               class="btn-close"
               data-bs-dismiss="modal"
               aria-label="Close"
            ></button>
         </div>
         <div class="modal-body pantalla_modal" style="background: white">
            <div style="display: flex">
               <input
                  type="text"
                  placeholder="search"
                  class="form-control form-control-sm buscador_asignar_clientes"
                  style="margin-right: 10px"
               />
               <button
                  class="btn"
                  id="btn_filtro_buscador_clientes"
                  type="button"
                  style="
                     border-color: #d3cac0;
                     border: 1px solid #d3cac0;
                     background-color: white;
                  "
               >
                  Search
               </button>
            </div>
            <br />
            <div class="row">
               <div
                  class="col-sm-12"
                  style="background: white; border-radius: 4px"
               >
                  <div class="table-responsive" style="height: 401px">
                     <!-- Agregado -->
                     <table class="table">
                        <thead>
                           <tr>
                              <th class="centrar">Account</th>
                              <th class="centrar">Phone</th>
                              <th class="centrar">Email</th>
                              <th class="centrar">Address</th>
                              <th class="centrar">Company</th>
                              <th class="centrar"></th>
                           </tr>
                        </thead>
                        <tbody class="tbody_asignar_clientes">
                           {*

                           <tr>
                              <td class="centrar">Juan</td>
                              <td class="centrar">Juan@live.com</td>
                              <td class="centrar">Satelite</td>
                              <td class="centrar">
                                 <button class="btn btn-primary" type="button">
                                    Add
                                 </button>
                              </td>
                           </tr>
                           *}
                        </tbody>
                     </table>
                  </div>
                  <!-- Cierre del div table-responsive -->
               </div>
            </div>
            <!-- <select
               class="tener_select_contact"
               name="select_contact"
               id="select_contact"
               style="width: 100%"
            ></select> -->
         </div>
      </div>
   </div>
</div>

{**}
<div
   class="modal fade"
   id="ventana_confirmacion"
   tabindex="-1"
   aria-labelledby="exampleModalLabel__ventanaconfirmacion"
   aria-hidden="true"
   data-bs-backdrop="static"
   data-bs-keyboard="false"
>
   <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content" style="background-color: white">
         <div class="modal-header">
            <h3 class="titulo_modal_confirmar">Estas seguro de eliminar</h3>
            <button
               type="button"
               class="btn-close"
               id="btn_close_ventana_confirmacion"
            ></button>
         </div>
         <div
            class="modal-body"
            style="background-color: white; border-radius: 10px"
         >
            <div class="row">
               <div class="col-md-12">
                  <div class="panel-container show" id="ibox_form">
                     <div class="panel-content">
                        <div class="px-2">
                           <div
                              class="alert alert-danger"
                              id="emsg"
                              style="display: none"
                           >
                              <span id="emsgbody"></span>
                           </div>
                           <input
                              class="tipo_modal_confirmar"
                              hidden
                              disabled
                           />
                           <input class="data_id" hidden disabled />
                           <div class="row">
                              <div class="col-md-12 col-sm-12">
                                 <h4
                                    class="mensaje_modal_confirmar"
                                    style="text-align: center; color: black"
                                 >
                                    Estas seguro de eliminar
                                 </h4>
                                 <p
                                    class="mensaje_espera_moda_confirmacion mt-3"
                                    style="
                                       text-align: center;
                                       color: red;
                                       font-weight: 600;
                                    "
                                 >
                                    Espere mientras termina el proceso
                                 </p>
                              </div>
                           </div>
                           <div class="row mt-2">
                              <div class="col-md-12">
                                 <div style="float: inline-end">
                                    <button
                                       class="btn me-2"
                                       type="button"
                                       id="btn_cerrar_ventana_confirmacion"
                                       style="background: #001b3b"
                                    >
                                       close
                                    </button>
                                    <button
                                       class="btn"
                                       type="button"
                                       id="btn_aplicar_ventana_confirmacion"
                                       style="background: red"
                                    >
                                       Remove
                                    </button>
                                 </div>
                              </div>
                           </div>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>

<div class="row cargando_pantalla " style=" margin: 0px; ">

   <div
      class="container"
      style="
         display: flex;
         justify-content: center;
         align-items: center;
         height: 45vh;
         box-shadow: 0 0 13px 0 rgba(31,17,173,.08);
         border-radius: 11px;
         background-color: white;
      "
   >
      <div style="text-align: center">
         <span
         class="spinner-border spinner-border-sm"
         style="height: 45px; width: 45px; margin-bottom: 10px"
         role="status"
         aria-hidden="true"
         ></span>
         <br />
         <strong>Please wait while the <span style=" font-weight: 600; ">"credit history"</span> screen loads...</strong>
         <br />
      </div>
   </div>

</div>


{**}

<div
   class="modal fade"
   id="modalDetailsCredits"
   data-bs-backdrop="static"
   data-bs-keyboard="false"
   tabindex="-1"
   aria-labelledby="staticBackdropLabel"
   aria-hidden="true"
>
   <div class="modal-dialog modal-dialog-centered" style=" max-width: 95%; width: 95%; ">
      <div class="modal-content">
         <div class="modal-header">
            <h5
               class="modal-title "
               id="staticBackdropLabel"
            >
               Credit history
            </h5>
            <button
               type="button"
               class="btn-close btn_cerrar_credito_details"
            ></button>
         </div>
         <div class="modal-body text-center">
             
            <div class="table-responsive">
               <table
                  class="table table-striped table-hover estilosTabla"
                  id="clx_datatable"
                  style="margin: 0px"
               >
                  <thead>
                     <tr>
                        <th class="centrar">Payment date</th>
                        <th class="centrar">Initial quotas</th>
                        <th class="centrar">Amount paid</th>
                        <th class="centrar">Mora paid</th>
                        <th class="centrar">Interest paid</th>
                        <th class="centrar">Final quotas</th>
                        <th class="centrar">Payment type</th>
                        <th class="centrar">Payment gateway URL</th>
                        <th class="centrar">Staff</th>
                        
                     </tr>
                  </thead>

                  <tbody class="tbody_envios_credito_detalle">
                     {*
                      <tr>
                        <td class="centrar">1</td>
                        <td class="centrar">28/abril/2025</td>
                        <td class="centrar">600.00</td>
                        <td class="centrar">413.38</td>
                        <td class="centrar">70.20</td>
                        <td class="centrar">5,656.82</td>
                      </tr>
                     *}

                  </tbody>
               </table>
            </div>

         </div>
      </div>
   </div>
</div>

{/block}

{block name="script"}

{literal}
<script>

   var URL_BASE = $("#URL_BASE").val();

   var ID_USER = $("#ID_USER").val();
   var url_dashboard = $("#url_dashboard").val();

   var roll_id = $("#roll_id").val();
   
   var abreviaciones_estados = [
      { value: 'AL', text: 'Alabama' },
      { value: 'AK', text: 'Alaska' },
      { value: 'AZ', text: 'Arizona' },
      { value: 'AR', text: 'Arkansas' },
      { value: 'CA', text: 'California' },
      { value: 'CO', text: 'Colorado' },
      { value: 'CT', text: 'Connecticut' },
      { value: 'DE', text: 'Delaware' },
      { value: 'FL', text: 'Florida' },
      { value: 'GA', text: 'Georgia' },
      { value: 'HI', text: 'Hawaii' },
      { value: 'ID', text: 'Idaho' },
      { value: 'IL', text: 'Illinois' },
      { value: 'IN', text: 'Indiana' },
      { value: 'IA', text: 'Iowa' },
      { value: 'KS', text: 'Kansas' },
      { value: 'KY', text: 'Kentucky' },
      { value: 'LA', text: 'Louisiana' },
      { value: 'ME', text: 'Maine' },
      { value: 'MD', text: 'Maryland' },
      { value: 'MA', text: 'Massachusetts' },
      { value: 'MI', text: 'Michigan' }, // Agregado
      { value: 'MN', text: 'Minnesota' }, // Agregado
      { value: 'MS', text: 'Mississippi' }, // Agregado
      { value: 'MO', text: 'Missouri' }, // Agregado
      { value: 'MT', text: 'Montana' }, // Agregado
      { value: 'NE', text: 'Nebraska' }, // Agregado
      { value: 'NV', text: 'Nevada' }, // Agregado
      { value: 'NH', text: 'New Hampshire' }, // Agregado
      { value: 'NJ', text: 'New Jersey' }, // Agregado
      { value: 'NM', text: 'New Mexico' }, // Agregado
      { value: 'NY', text: 'New York' }, // Agregado
      { value: 'NC', text: 'North Carolina' }, // Agregado
      { value: 'ND', text: 'North Dakota' }, // Agregado
      { value: 'OH', text: 'Ohio' }, // Agregado
      { value: 'OK', text: 'Oklahoma' }, // Agregado
      { value: 'OR', text: 'Oregon' }, // Agregado
      { value: 'PA', text: 'Pennsylvania' }, // Agregado
      { value: 'RI', text: 'Rhode Island' }, // Agregado
      { value: 'SC', text: 'South Carolina' }, // Agregado
      { value: 'SD', text: 'South Dakota' }, // Agregado
      { value: 'TN', text: 'Tennessee' }, // Agregado
      { value: 'TX', text: 'Texas' }, // Agregado
      { value: 'UT', text: 'Utah' }, // Agregado
      { value: 'VT', text: 'Vermont' }, // Agregado
      { value: 'VA', text: 'Virginia' }, // Agregado
      { value: 'WA', text: 'Washington' }, // Agregado
      { value: 'WV', text: 'West Virginia' }, // Agregado
      { value: 'WI', text: 'Wisconsin' }, // Agregado
      { value: 'WY', text: 'Wyoming' }, // Agregado
      { value: 'DC', text: 'District of Columbia' },  
   ];

   var UUID_ENC = $("#UUID_ENC").val();
   var UUID     = $("#UUID").val();
   var id_ifp   = $("#id_ifp").val();

   var COLOR_FONDO_VENTANA_CERRAR = "#001b3b";
   var COLOR_TEXT_VENTANA_CERRAR = "white";

   var COLOR_FONDO_VENTANA_CONFIRMACION = "red";
   var COLOR_TEXT_VENTANA_CONFIRMACION = "white";

   var COLOR_FONDO_VENTANA_IR = "#001b3b";
   var COLOR_TEXT_VENTANA_IR = "white";

   var menus_disponibles = {};

   var planes = [
      /*
      {
         no_fee: 1,
         payment_date: "2025-05-25",
         share_value: "600",
         capital: "413.38",
         interest: "70.20",
         capital_balance: "5556.82",
         state: "earring"
      },
      {
         no_fee: 2,
         payment_date: "2025-05-24",
         share_value: "800",
         capital: "913.38",
         interest: "170.20",
         capital_balance: "456.82",
         state: "earring"
      },
      */
   ];

   var list_credit_history_details = [];

   $(document).ready(function () {

      cargarPrincipal();
 
      $(".progress").hide();
      $("#emsg").hide();
      $("#emsgSuccess").hide();

      var _url = '{$_url}';
    
      //para activar el customers
      $country_hi = $(".country_hi");
      $country_hi.select2();

      $('#submit_modal_confirmacion_correo').on('click', function() {
          window.location = url_dashboard;    
      });

      $('.back').click(function() {
         window.location = URL_BASE + "credit/data-loans/" + UUID_ENC;
      });
 
      $('#btn_copiar_hipervinculo').click(function() {

         const url = $('.url_access').attr('href');

         navigator.clipboard.writeText(url)
            .then(() => {
                  alert('URL copied to clipboard: ' + url);  
            })
            .catch(err => {
                  console.error('Error copying URL: ', err);  
            });
      });

      $('.cursor_manito').click(function() {

         const atributo_data =  $(this).attr('data-id');

         if(atributo_data == "datos_prestamos")
         {
            window.location = URL_BASE + "credit/data-loans/" + UUID_ENC;
         }

         if(atributo_data == "historial_crediticio")
         {
            window.location = URL_BASE + "credit/credit-history/" + UUID_ENC;
         }
 
         if(atributo_data == "general_information")
         {
            if(menus_disponibles.general_information == 1)
            {
               window.location = URL_BASE + "credit/new-prospecting/" + UUID_ENC;
            }else{
               $("#modalMensaje").modal("show");
               $(".modal_titulo_mensaje").text("Prospecting stage");
               $(".modal_contenido_mensaje").text("You must complete each of the stages to reach that point.");
               $(".btn_cerrar_confirmacion_modal").attr("disabled", false);
            }
            
         }

         if(atributo_data == "referencia")
         {
            if(menus_disponibles.referencia == 1)
            {
               window.location = URL_BASE + "credit/reference-prospecting/" + UUID_ENC;
            }else{
               $("#modalMensaje").modal("show");
               $(".modal_titulo_mensaje").text("Prospecting stage");
               $(".modal_contenido_mensaje").text("You must complete each of the stages to reach that point.");
               $(".btn_cerrar_confirmacion_modal").attr("disabled", false);
            }
         }

         if(atributo_data == "documento_respaldo")
         {
            if(menus_disponibles.documento_respaldo == 1)
            {
               window.location = URL_BASE + "credit/supporting-document-prospecting/" + UUID_ENC;
            }else{
               $("#modalMensaje").modal("show");
               $(".modal_titulo_mensaje").text("Prospecting stage");
               $(".modal_contenido_mensaje").text("You must complete each of the stages to reach that point.");
               $(".btn_cerrar_confirmacion_modal").attr("disabled", false);
            }
         }

         if(atributo_data == "preaprobacion")
         {
            if(menus_disponibles.preaprobacion == 1)
            {
               window.location = URL_BASE + "credit/pre-approval-prospecting/" + UUID_ENC;
            }else{
               $("#modalMensaje").modal("show");
               $(".modal_titulo_mensaje").text("Prospecting stage");
               $(".modal_contenido_mensaje").text("You must complete each of the stages to reach that point.");
               $(".btn_cerrar_confirmacion_modal").attr("disabled", false);
            }
         }

         if(atributo_data == "plan_pago")
         {
            if(menus_disponibles.plan_pago == 1)
            {
               window.location = URL_BASE + "credit/payment-plan-prospecting/" + UUID_ENC;
            }else{
               $("#modalMensaje").modal("show");
               $(".modal_titulo_mensaje").text("Prospecting stage");
               $(".modal_contenido_mensaje").text("You must complete each of the stages to reach that point.");
               $(".btn_cerrar_confirmacion_modal").attr("disabled", false);
            }
         }

         if(atributo_data == "desembolzo")
         {
            if(menus_disponibles.desembolzo == 1)
            {
               window.location = URL_BASE + "credit/disbursement-prospecting/" + UUID_ENC;
            }else{
               $("#modalMensaje").modal("show");
               $(".modal_titulo_mensaje").text("Prospecting stage");
               $(".modal_contenido_mensaje").text("You must complete each of the stages to reach that point.");
               $(".btn_cerrar_confirmacion_modal").attr("disabled", false);
            }
         }

 
      });

      $('.btn_cerrar_confirmacion_modal').click(function() {
         $("#modalMensaje").modal("hide");
      });

      $('.abrir_modal_contacto').click(function() {
         $("#modal_asignar_clientes_contactos").modal("show");
      });
 
      $('.btn_cerrar_credito_details').click(function() {
         $("#modalDetailsCredits").modal("hide");
      });

      $('.guardar_siguiente').click(function() {

         window.location = URL_BASE + "credit/new-prospecting/" + UUID_ENC;
         return;

         $('input, select, button, textarea').prop('disabled', true);

         $('.nombre_completo_ig, .correo_electronico_ig, .telefono_ig, .grupo_ig').prop('disabled', false);

         $('.loading_guardar_siguiente').css('display', '');
         $('.guardar_siguiente').css('display', 'none');
    
         let clientes_ig = $(".clientes_ig").val();

         if(isEmpty(clientes_ig))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.clientes_ig');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "General contact information" the field "Customer" is required.');
            return;
         }

         let id_ig = $(".id_ig").val();

         if(isEmpty(id_ig))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.id_ig');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "General contact information" the field "ID" is required.');
            return;
         }

         let numero_credito_ig = $(".numero_credito_ig").val();

         if(isEmpty(numero_credito_ig))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.numero_credito_ig');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "General contact information" the field "Credit number" is required.');
            return;
         }

         let fecha_desembolso_ig = $(".fecha_desembolso_ig").val();

         if(isEmpty(fecha_desembolso_ig))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.fecha_desembolso_ig');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "General contact information" the field "Disbursement date" is required.');
            return;
         }

         let grupo_ig = $(".grupo_ig").val();

         if(isEmpty(grupo_ig))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.grupo_ig');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "General contact information" the field "Group" is required.');
            return;
         }

         let estado_ig = $(".estado_ig").val();

         if(isEmpty(estado_ig))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.estado_ig');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "General contact information" the field "State" is required.');
            return;
         }

         let monto_ld = $(".monto_ld").val();

         if(isEmpty(monto_ld))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.monto_ld');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "Loan details" the field "Amount" is required.');
            return;
         }

         let tasa_ld = $(".tasa_ld").val();

         if(isEmpty(tasa_ld))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.tasa_ld');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "Loan details" the field "Rate" is required.');
            return;
         }

         let cuotas_ld = $(".cuotas_ld").val();

         if(isEmpty(cuotas_ld))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.cuotas_ld');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "Loan details" the field "Fees" is required.');
            return;
         }

         let amortizacion_ld = $(".amortizacion_ld").val();

         if(isEmpty(amortizacion_ld))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.amortizacion_ld');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "Loan details" the field "Amortization" is required.');
            return;
         }

         let capital_pagado_mf = $(".capital_pagado_mf").val();

         if(isEmpty(capital_pagado_mf))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.capital_pagado_mf');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "Movements to date" the field "Paid-in capital" is required.');
            return;
         }

         let intereses_pagadas_ld = $(".intereses_pagadas_ld").val();

         if(isEmpty(intereses_pagadas_ld))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.intereses_pagadas_ld');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "Movements to date" the field "Interest paid" is required.');
            return;
         }

         let cuotas_pagadas_ld = $(".cuotas_pagadas_ld").val();

         if(isEmpty(cuotas_pagadas_ld))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.cuotas_pagadas_ld');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "Movements to date" the field "Fees paid" is required.');
            return;
         }

         let saldo_capital_mf = $(".saldo_capital_mf").val();

         if(isEmpty(saldo_capital_mf))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.saldo_capital_mf');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "Balances to date" the field "Capital balance" is required.');
            return;
         }

         let saldo_interes_ld = $(".saldo_interes_ld").val();

         if(isEmpty(saldo_interes_ld))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.saldo_interes_ld');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "Balances to date" the field "Interest balance" is required.');
            return;
         }

         let saldo_gasto_cobranza_ld = $(".saldo_gasto_cobranza_ld").val();

         if(isEmpty(saldo_gasto_cobranza_ld))
         {
             
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector('.saldo_gasto_cobranza_ld');
               
               if (targetDiv) {
                   targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            }

            toastr.error('!In "Balances to date" the field "Collection expense balance" is required.');
            return;
         }

         let validacionCaracteres = validateFormFields();

         if(validacionCaracteres == true)
         {
            return;
         }
 
         $("#emsg").hide();
         $("#emsgSuccess").hide();
 
         //$("#submit").prop("disabled", true); // Deshabilitar el botón
 
         let customer_id_ig = $(".customer_id_ig").val();
 
         var informacionEnviar = {
             customer_id_ig:                 customer_id_ig,
             clientes_ig:                    clientes_ig,
             id_ig:                          id_ig,
             numero_credito_ig:              numero_credito_ig,
             fecha_desembolso_ig:            fecha_desembolso_ig,
             grupo_ig:                       grupo_ig,
             estado_ig:                      estado_ig,
             monto_ld:                       monto_ld,
             tasa_ld:                        tasa_ld,
             cuotas_ld:                      cuotas_ld,
             amortizacion_ld:                amortizacion_ld,
             capital_pagado_mf:              capital_pagado_mf,
             intereses_pagadas_ld:           intereses_pagadas_ld,
             cuotas_pagadas_ld:              cuotas_pagadas_ld,
             saldo_capital_mf:               saldo_capital_mf,
             saldo_interes_ld:               saldo_interes_ld,
             saldo_gasto_cobranza_ld:        saldo_gasto_cobranza_ld,
         }; 

         console.log(JSON.stringify(informacionEnviar));
         console.log("return aqui abajo")
         return;

         //return;

         $.post(URL_BASE + 'forms/post-new-forms/', JSON.stringify(informacionEnviar)  ) //$( "#rform" ).serialize()
         .done(function (data) {

               $("#submit").prop("disabled", false); // Deshabilitar el botón
                
                   //console.log(data);
                   //console.log(data);
                   //return;

                   //$(".bloqueo_v1").attr("hidden", true);
                   //$(".bloqueo_v2").attr("hidden", true);
                   //$(".bloqueo_v3").attr("hidden", true);

                    try {
                       
                       const info = JSON.parse(data);
                      
                       if( info.type == "success")
                       {
                           toastr.success(info.message);

                           if(tenerPreguntaEnviarCorreo == 1)
                           {
                               $(".modal_correo").val(tenerCorreoElectronico);
                               $(".modal_codigo_acceso").val(tenerAccessCode);
                               $(".modal_codigo_verificacion").val(tenerVerificationCode);

                               let url_access = info.url_formulario_IRS;

                               $(".url_access").attr("href", url_access).find("span").text(url_access);

                               $("#modalFormIRS").modal("show");
                           }else{
                               window.location = info.redirect;    
                           }
 
                       }else{
                           //$('#ibox_form').unblock();
                           var body = $("html, body");
                           body.animate({ scrollTop:0 }, '1000', 'swing');
                           $("#emsgbody").html(info.message);
                           $("#emsg").show("slow");
                       }
                   } catch (error) {
                       //$('#ibox_form').unblock();
                       var body = $("html, body");
                       body.animate({ scrollTop:0 }, '1000', 'swing');
                       $("#emsgbody").html(data);
                       $("#emsg").show("slow");
                   }
         });

      });


    });

   function contadorPosicion()
   {
      //if(menus_disponibles.plan_pago == 1 || menus_disponibles.plan_pago == "1")
      //{
      //   menus_disponibles.desembolzo = "1";
      //}
   }

   function cargarPrincipal()
   {

      let data = {
         id_gip: id_ifp,
      };
 
      $.ajax({
            type: "POST",
            url: URL_BASE + "credit/get-data-credit-history",
            data: JSON.stringify(data),
            contentType: "application/json", // Tipo de contenido JSON
            success: function (response) {
   
               try {
                  let info = JSON.parse(response);

                  if (info.type == "success") {

                     menus_disponibles = info.menu_habilitados || {};
                     planes = info.list_credit_history || [];

                     list_history_credit = info.list_history_credit || [];

                     if(menus_disponibles.desembolzo == 2)
                     {
                        window.location = URL_BASE + "credit/new-prospecting/" + UUID_ENC;
                        return;
                     }
 
                     //let dataIGP = info.data_gip || {};
 
                     contadorPosicion();


                     if(list_history_credit.length == 0)
                     {
                        const newRow = '<tr><td colspan="7" class="centrar" style=" text-align: center; ">No information</td></tr>';

                        $(".tbody_envios").html(newRow);  
                     }else{

                        var newRow = "";

                        // Iterar sobre el arreglo y concatenar las filas
                        list_history_credit.forEach((element) => {

                           let {
                                 numero_credito,
                                 fecha_inicio,
                                 fecha_vencimiento,
                                 plazos,
                                 monto,
                                 descripcion_modalidad_cobro,
                                 plan_nombre,
                                 tasa_interes_descripcion,
                                 stage,
                           } = element;

                           //<th class="centrar">No. Credit</th>
                           //<th class="centrar">Start date</th>
                           //<th class="centrar">Expiration Date</th>
                           //<th class="centrar">Term</th>
                           //<th class="centrar">Amount</th>
                           //<th class="centrar">Interest rate</th>
                           //<th class="centrar">State</th>

                              newRow +=
                              "<tr>" +
                                 '<td class="centrar">' + numero_credito + "</td>" +
                                 '<td class="centrar">' + fecha_inicio + "</td>" +
                                 '<td class="centrar">' + fecha_vencimiento + "</td>" +
                                 '<td class="centrar">' + plazos + "</td>" +
                                 '<td class="centrar">' + monto + "</td>" +
                                 '<td class="centrar">' + tasa_interes_descripcion + "</td>" +
                                 '<td class="centrar">' + stage + "</td>" +
                                 
                              "</tr>";

                        });

                        $(".tbody_envios").html(newRow);  
                     }

                     //eventosVerDetalle();

                     $(".cargando_pantalla").css("display", "none");
                     $(".pantalla_cargada").css("display", "");
   
                  } else if (info.type == "error") {
                     //Swal.fire({
                     //   icon: "error",
                     //   title: "Oops...",
                     //   text: info.message,
                     //});

                     ventanaError("Opps there was an error", info.message);
                  }
               } catch (error) {
                  //Swal.fire({
                  //   icon: "error",
                  //   title: "Oops...",
                  //   text: error,
                  //});

                  ventanaError("Opps there was an error", error);
               }
            },
            error: function (xhr, status, error) {
               console.error("Error en la solicitud:", error);
               // Manejar errores aquí
               //Swal.fire({
               //   icon: "error",
               //   title: "Oops...",
               //   text: error,
               //});

               ventanaError("Opps there was an error", error);

            },
         });

       
   }

   function eventosVerDetalle()
   {

      $('.btn-show-details').off('click');

      $('.btn-show-details').on('click', function() {
         var dataId = $(this).data('id');
         console.log('ID de la referencia:', dataId);

         
        
         let BusquedadInformacion = list_credit_history_details.filter(function(item) {
            return item.ch_id == dataId;
         });

         console.log("BusquedadInformacion");
         console.log(BusquedadInformacion);

         if(isEmpty(BusquedadInformacion) == false)
         {            

            if(BusquedadInformacion.length == 0){

            }else{

               let newRow = "";

               // Iterar sobre el arreglo y concatenar las filas
               BusquedadInformacion.forEach((element) => {

                  let {
                     id,
                     ch_id,
                     cuota_inicial,
                     valor_pagado,
                     mora_pagada,
                     interes_pagado,
                     capital_pagado,
                     valor_pendiente,
                     tipo_caja,
                     url_link_pago,
                     estado_pago,
                     user_id_post,
                     fecha_post,
                     gip_id,
                     fullname
                  } = element;

                  
                  //<th class="centrar">Initial quotas</th>
                  //<th class="centrar">Amount paid</th>
                  //<th class="centrar">Mora paid</th>
                  //<th class="centrar">Interest paid</th>
                  //<th class="centrar">Final quotas</th>
                  //<th class="centrar">Payment type</th>
                  //<th class="centrar">Payment gateway URL</th>

                  if(isEmpty(url_link_pago) == true)
                  {
                     url_link_pago = "-/-";
                  }
            
                   newRow +=
                  "<tr>" +
                  '<td class="centrar">' + formatFecha(fecha_post) + "</td>" +
                  '<td class="centrar">$ ' + formatNumber(cuota_inicial) + "</td>" +
                  '<td class="centrar">$ ' + formatNumber(mora_pagada) + "</td>" +
                  '<td class="centrar">$ ' + formatNumber(interes_pagado) + "</td>" +
                  '<td class="centrar">$ ' + formatNumber(capital_pagado) + "</td>" +
                  '<td class="centrar">$ ' + formatNumber(valor_pendiente) + "</td>" +
                  '<td class="centrar">' + tipo_caja + "</td>" +
                  '<td class="centrar url-break">' + url_link_pago + "</td>" +
                  '<td class="centrar">' + fullname + "</td>" +
                  "</tr>";


               });

               $(".tbody_envios_credito_detalle").html(newRow);

               const style = document.createElement('style');
                  style.textContent = `
                     .url-break {
                           word-wrap: break-word;
                           overflow-wrap: break-word;
                           max-width: 200px; /* Ajusta este valor según el espacio disponible */
                     }
                  `;
                  document.head.appendChild(style);

               $("#modalDetailsCredits").modal("show");
            }
 
            //$("#addAval").modal("show");
         }

      });

       
 
   }

   // Función para formatear números como 1,000.00
   const formatNumber = (number) => {
      return Number(number).toLocaleString('en-US', {
         minimumFractionDigits: 2,
         maximumFractionDigits: 2
      });
   };

   // Función para formatear fecha YYYY-MM-DD a DD/MMMM/YYYY
   const formatFecha = (fecha) => {
      const meses = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"];
      const date = new Date(fecha);
      return `${date.getDate()}/${meses[date.getMonth()]}/${date.getFullYear()}`;
   };


   function isEmpty(value) {
       // Verificar si es null o undefined
       if (value == null) return true;

       // Verificar si es una cadena vacía
       if (typeof value === "string" && value.trim() === "") return true;

       // Verificar si es un array vacío
       if (Array.isArray(value) && value.length === 0) return true;

       // Verificar si es un objeto vacío
       if (typeof value === "object" && Object.keys(value).length === 0) return true;

       return false;
   }
 
   function validarSoloNumeros(input) {
       const number = parseInt(input, 10);
       return !isNaN(number) && number.toString() === input;
   }

   function validateEmail(email) {
      // Expresión regular para validar un formato de correo electrónico
      var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      
      if (emailPattern.test(email)) {
         return true;  // Es un correo válido
      } else {
         return false;  // No es un correo válido
      }
   }

   $("#btn_filtro_buscador_clientes").click(async function () {
            
      console.log("btn_filtro_buscador_clientes");

      let filtro = $(".buscador_asignar_clientes").val() || "";

      if (isEmpty(filtro) == true) {
         Swal.fire("the search is empty!");
         return;
      }

      let filtro_staff = filtro.toLowerCase();

      let informacion = {
         filtro: filtro_staff,
      };

      console.log("informacion");
      console.log(informacion);

      $('#btn_filtro_buscador_clientes').prop('disabled', true);

      $.ajax({
            type: "POST",
            url: URL_BASE + "credit/filtra-listado-customers",
            data: JSON.stringify(informacion), // Convertir datos a formato JSON
            contentType: "application/json", // Tipo de contenido JSON
            success: function (response) {

               $('#btn_filtro_buscador_clientes').prop('disabled', false);
               
               //console.log("Respuesta del servidor:", response);
               // Hacer algo con la respuesta del servidor

   
               try {
                  let info = JSON.parse(response);

                  if (info.type == "success") {

                     let data = info.data || [];

                     console.log("data");
                     console.log(data);
                     
                     let miHtml = tabla_html_customers(data);
                     console.log("miHtml");
                     console.log(miHtml);

                     $(".tbody_asignar_clientes").html(miHtml);
                     
                     add_evento_select_cliente_contactos(data);

                      
                  } else if (info.type == "error") {
                     Swal.fire({
                        icon: "error",
                        title: "Oops...",
                        text: info.message,
                     });
                  }
               } catch (error) {
                  Swal.fire({
                     icon: "error",
                     title: "Oops...",
                     text: error,
                  });
               }
            },
            error: function (xhr, status, error) {
               console.error("Error en la solicitud:", error);
               // Manejar errores aquí
               Swal.fire({
                  icon: "error",
                  title: "Oops...",
                  text: error,
               });

               $('#btn_filtro_buscador_clientes').prop('disabled', false);

            },
         });
   
     
   });

   function tabla_html_customers(arreglo) {
      let html = "";
   
      arreglo.forEach(function (element) {
         let { id, account, phone, email, address, company } = element;

         html +=
            "<tr>" +
            //
            "<td class='centrar'>" +
            account +
            "</td>" +
            //
            "<td class='centrar'>" +
            phone +
            "</td>" +
            //
            "<td class='centrar'>" +
            email +
            "</td>" +
            //
            "<td class='centrar'>" +
            address +
            "</td>" +
            //
            //
            "<td class='centrar'>" +
            company +
            "</td>" +
            //
            "<td class='centrar'>" +
            "<button class='btn  btn_add_cliente_contacts' type='button' data-cliente_id='" +
            id +
            "' style='border-color: #d3cac0;border: 1px solid #d3cac0;background-color: white;'>Add</button>" +
            "</td>" +
            "</tr>";
      });

      return html;
   }

   function add_evento_select_cliente_contactos(arreglo_data = [])
   {
      $(".btn_add_cliente_contacts")
      .off("click")
      .on("click", function () {

         let {

            cliente_id,

         } = $(this).data();

         if(isEmpty(cliente_id))
         {
            toastr.error("!Customer ID is required¡");
            return;
         }

         let findData = arreglo_data.find((item) => item.id == cliente_id);

         if(findData)
         {
            $(".customer_id_ig").val(findData.id);
            $(".nombre_completo_ig").val(findData.account);
            $(".correo_electronico_ig").val(findData.email);
            $(".grupo_id_ig").val(findData.gid);
            $(".grupo_ig").val(findData.gname);
            $(".telefono_ig").val(findData.phone);
            $(".ocupacion_economica_ei").val(findData.position);
 
            $("#modal_asignar_clientes_contactos").modal("hide");

            toastr.success("!Customer added successfully¡");
         } else {
            toastr.error("!Customer not found¡");
         }

         console.log("cliente_id");
         console.log(cliente_id);  
 
      });
   }

   function validateFormFields() {
      const fields = [
         { selector: '.clientes_ig', section: 'General contact information', name: 'Customer' },
         { selector: '.id_ig', section: 'General contact information', name: 'ID' },
         { selector: '.numero_credito_ig', section: 'General contact information', name: 'Credit number' },
         { selector: '.fecha_desembolso_ig', section: 'General contact information', name: 'Disbursement date' },
         { selector: '.grupo_ig', section: 'General contact information', name: 'Group' },
         { selector: '.estado_ig', section: 'General contact information', name: 'State' },
         { selector: '.monto_ld', section: 'Loan details', name: 'Amount' },
         { selector: '.tasa_ld', section: 'Loan details', name: 'Rate' },
         { selector: '.cuotas_ld', section: 'Loan details', name: 'Fees' },
         { selector: '.amortizacion_ld', section: 'Loan details', name: 'Amortization' },
         { selector: '.capital_pagado_mf', section: 'Movements to date', name: 'Paid-in capital' },
         { selector: '.intereses_pagadas_ld', section: 'Movements to date', name: 'Interest paid' },
         { selector: '.cuotas_pagadas_ld', section: 'Movements to date', name: 'Fees paid' },
         { selector: '.saldo_capital_mf', section: 'Balances to date', name: 'Capital balance' },
         { selector: '.saldo_interes_ld', section: 'Balances to date', name: 'Interest balance' },
         { selector: '.saldo_gasto_cobranza_ld', section: 'Balances to date', name: 'Collection expense balance' }
      ];

      for (const field of fields) {
         const value = $(field.selector).val() || "";
         if (value && value.length > 255) {
            toastr.options.onclick = function() {
               const targetDiv = document.querySelector(field.selector);
               if (targetDiv) {
                  targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
               }
            };
            toastr.error(`In "${field.section}" the field "${field.name}" cannot exceed 255 characters.`);
            return true;
         }
      }

      return false;
   }

   function serach_address(address, secundary, option = 1) {
      let url_modulo_api_direccion_smarty = $(
         ".url_modulo_api_direccion_smarty",
      ).val();
      let key_modulo_api_direccion_smarty = $(
         ".key_modulo_api_direccion_smarty",
      ).val();
      let host_modulo_api_direccion_smarty = $(
         ".host_modulo_api_direccion_smarty",
      ).val();
      let referer_modulo_api_direccion_smarty = $(
         ".referer_modulo_api_direccion_smarty",
      ).val();

      //console.log("url_modulo_api_direccion_smarty");
      //console.log(url_modulo_api_direccion_smarty);
      //console.log("key_modulo_api_direccion_smarty");
      //console.log(key_modulo_api_direccion_smarty);
      //console.log("host_modulo_api_direccion_smarty");
      //console.log(host_modulo_api_direccion_smarty);
      //console.log("referer_modulo_api_direccion_smarty");
      //console.log(referer_modulo_api_direccion_smarty);

      if (
         isEmpty(url_modulo_api_direccion_smarty) == true ||
         isEmpty(key_modulo_api_direccion_smarty) == true ||
         isEmpty(host_modulo_api_direccion_smarty) == true ||
         isEmpty(referer_modulo_api_direccion_smarty) == true
      ) {
         return;
      }

      var country_hi = $(".country_hi").val();
      let x = address.trim();
      if (x.length > 2 && country_hi === "United States") {
         var settings = {
            //"url": "https://us-autocomplete-pro.api.smarty.com/lookup?key=188805315395749398&search="+address+"&selected="+secundary+"&include_only_cities=&include_only_states=&include_only_zip_codes=&exclude_states=&prefer_cities=&prefer_states=&prefer_zip_codes=&source=all",
            url:
               url_modulo_api_direccion_smarty +
               "/lookup?key=" +
               key_modulo_api_direccion_smarty +
               "&search=" +
               address +
               "&selected=" +
               secundary +
               "&include_only_cities=&include_only_states=&include_only_zip_codes=&exclude_states=&prefer_cities=&prefer_states=&prefer_zip_codes=&source=all",
            method: "GET",
            timeout: 0,
            headers: {
               //"Host": "us-autocomplete-pro.api.smarty.com",
               //"Referer": "https://hispanosdeexitollc.com"
               Host: host_modulo_api_direccion_smarty,
               Referer: referer_modulo_api_direccion_smarty,
            },
         };

         $("#browsers").html("");
         $("#browsers").show();

         $.ajax(settings).done(function (response) {
            $.each(response.suggestions, function (k, v) {
               let text =
                  v.street_line +
                  " " +
                  v.secondary +
                  " " +
                  v.city +
                  ", " +
                  v.state +
                  " " +
                  v.zipcode;
               let line =
                  v.street_line +
                  " " +
                  v.secondary +
                  " (" +
                  v.entries +
                  ") " +
                  v.city +
                  ", " +
                  v.state +
                  " " +
                  v.zipcode;
               let line2 = v.street_line + " " + v.secondary;
               let entries =
                  v.entries > 1
                     ? '<a href="#" data-data1="' +
                     line +
                     '" data-data2="' +
                     line2 +
                     '" class="addresssec"><span class="badge bg-primary rounded-pill">+ ' +
                     v.entries +
                     " Address</span></a>"
                     : "";
               let option =
                  '<li class="list-group-item d-flex justify-content-between align-items-start "><div class="ms-2 me-auto address1" data-data1="' +
                  v.city +
                  '" data-data2="' +
                  v.state +
                  '" data-data3="' +
                  v.zipcode +
                  '" data-data4="' +
                  v.street_line +
                  " " +
                  v.secondary +
                  '"><div class="fw-bold">' +
                  text +
                  "</div></div>" +
                  entries +
                  "</li>";
               $("#browsers").append(option);
               x++;
            });
         });
      }
   }

   $("input[name='address']").on("input", function (e) {
      var address = $(this).val();
      var country_hi = $(".country_hi").val();
      let x = address.trim();
      if (x.length > 2 && country_hi === "United States") {
         address = address.replace(/,/g, "");
         address = address.replace(/ /g, "+");
         address = address.replace(/#/g, "%23");
         serach_address(address, "", 1);
      }
   });

   $(document).on("click", ".address1", function (e) {
      e.preventDefault();
      $(".ciudad_hi").val($(this).data("data1"));
       
      $(".zip_hi").val($(this).data("data3"));
      $(".direccion_completa_hi").val($(this).data("data4"));
      

      let estado = $(this).data("data2");

      let buscarEstado = abreviaciones_estados.find((data) => data.value == estado);
      
      if(buscarEstado)
      {
         $(".estado_hi").val(buscarEstado.text);
      }else{
         $(".estado_hi").val(estado);
      }

      $("#browsers").hide();
   });

   $(document).on("click", ".addresssec", function (e) {
      e.preventDefault();
      let address = $(this).data("data2");
      $("#address").val(address);
      let secundary = $(this).data("data1");
      secundary = secundary.replace(/,/g, "");
      secundary = secundary.replace(/ /g, "+");
      secundary = secundary.replace(/#/g, "%23");
      address = address.replace(/,/g, "");
      address = address.replace(/ /g, "+");
      address = address.replace(/#/g, "%23");
      serach_address(address, secundary, 2);
   });

   function ventanaError(titulo, mensaje) {
      $(".titulo_modal_confirmar").text(titulo);
      $(".mensaje_modal_confirmar").text(mensaje);
      $(".mensaje_espera_moda_confirmacion").text("");
      $(".tipo_modal_confirmar").val("registro_exito");
      $(".data_id").val("");

      $('#btn_aplicar_ventana_confirmacion').prop('disabled', false);
      $('#btn_close_ventana_confirmacion').prop('disabled', false);
      $('#btn_cerrar_ventana_confirmacion').prop('disabled', false);
 
      $('#btn_cerrar_ventana_confirmacion').css({
         'background-color': COLOR_FONDO_VENTANA_CERRAR,
         'color': COLOR_TEXT_VENTANA_CERRAR
      });

      $('#btn_aplicar_ventana_confirmacion').css({
         'background-color': COLOR_FONDO_VENTANA_CONFIRMACION,
         'color': COLOR_TEXT_VENTANA_CONFIRMACION,
         'display': "none"
      });
 
      $("#ventana_confirmacion").modal("show");
   }


 
 
</script>
{/literal}


{/block}