/* COSTARICA // Eliminar cupones de BOGO o otras promos de checkout removeOldPromosCheckout() * Custom code goes here. * A template should always ship with an empty custom.js */ //var cities = ['San José', 'Heredia', 'Alajuela', 'Cartago', 'Puntarenas','Limón', 'Guanacanaste']; var provinces = JSON.parse( '{"San Jose":{"San José":["Carmen","Merced","Hospital","Catedral","Zapote","San Francisco de Dos Ríos","Uruca","Mata Redonda","Pavas","Hatillo","San Sebastián"],"Escazú":["Escazú","San Antonio","San Rafael"],"Desamparados":["Desamparados","San Miguel","San Juan de Dios","San Rafael Arriba","San Antonio","Frailes","Patarrá","San Cristóbal","Rosario","Damas","San Rafael Abajo","Gravilias","Los Guido"],"Puriscal":["Santiago","Mercedes Sur","Barbacoas","Grifo Alto","San Rafael","Candelarita","Desamparaditos","San Antonio","Chires"],"Tarrazú":["San Marcos","San Lorenzo","San Carlos"],"Aserrí":["Aserrí","Tarbaca","Vuelta de Jorco","San Gabriel","Legua","Monterrey","Salitrillos"],"Mora":["Colón","Guayabo","Tabarcia","Piedras Negras","Picagres","Jaris","Quitirrisí"],"Goicoechea":["Guadalupe","San Francisco","Calle Blancos","Mata de Plátano","Ipís","Rancho Redondo","Purral"],"Santa Ana":["Santa Ana","Salitral","Pozos","Uruca","Piedades","Brasil"],"Alajuelita":["Alajuelita","San Josecito","San Antonio","Concepción","San Felipe"],"Vásquez de Coronado":["San Isidro","San Rafael","Dulce Nombre de Jesús","Patalillo","Cascajal"],"Acosta":["San Ignacio","Guaitil","Palmichal","Cangrejal","Sabanillas"],"Tibás":["San Juan","Cinco Esquinas","Anselmo Llorente","León XIII","Colima"],"Moravia":["San Vicente","San Jerónimo","La Trinidad"],"Montes de Oca":["San Pedro","Sabanilla","Mercedes","San Rafael"],"Turrubares":["San Pablo","San Pedro","San Juan de Mata","San Luis","Carara"],"Dota":["Santa María","Jardín","Copey"],"Curridabat":["Curridabat","Granadilla","Sánchez","Tirrases"],"Pérez Zeledón":["San Isidro de El General","El General","Daniel Flores","Rivas","San Pedro","Platanares","Pejibaye","Cajón","Barú","Río Nuevo","Páramo","La Amistad"],"León Cortés Castro":["San Pablo","San Andrés","Llano Bonito","San Isidro","Santa Cruz","San Antonio"]},"Alajuela":{"Alajuela":["Alajuela","San José","Carrizal","San Antonio","Guácima","San Isidro","Sabanilla","San Rafael","Río Segundo","Desamparados","Turrúcares","Tambor","Garita","Sarapiquí"],"San Ramón":["San Ramón","Santiago","San Juan","Piedades Norte","Piedades Sur","San Rafael","San Isidro","Los Ángeles","Alfaro","Volio","Concepción","Zapotal","Peñas Blancas","San Lorenzo"],"Grecia":["Grecia","San Isidro","San José","San Roque","Tacares","Río Cuarto","Puente de Piedra","Bolívar"],"San Mateo":["San Mateo","Desmonte","Jesús María","Labrador"],"Atenas":["Atenas","Jesús","Mercedes","San Isidro","Concepción","San José","Santa Eulalia","Escobal"],"Naranjo":["Naranjo","San Miguel","San José","Cirrí Sur","San Jerónimo","San Juan","El Rosario","Palmitos"],"Palmares":["Palmares","Zaragoza","Buenos Aires","Santiago","Candelaria","Esquipulas","La Granja"],"Poás":["San Pedro","San Juan","San Rafael","Carrillos","Sabana Redonda"],"Orotina":["Orotina","El Mastate","Hacienda Vieja","Coyolar","La Ceiba"],"San Carlos":["Quesada","Florencia","Buenavista","Aguas Zarcas","Venecia","Pital","La Fortuna","La Tigra","La Palmera","Venado","Cutris","Monterrey","Pocosol"],"Zarcero":["Zarcero","Laguna","Tapezco","Guadalupe","Palmira","Zapote","Brisas"],"Valverde Vega":["Sarchí Norte","Sarchí Sur","Toro Amarillo","San Pedro","Rodríguez"],"Upala":["Upala","Aguas Claras","San José o Pizote","Bijagua","Delicias","Dos Ríos","Yolillal","Canalete"],"Los Chiles":["Los Chiles","Caño Negro","El Amparo","San Jorge"],"Guatuso":["San Rafael","Buenavista","Cote","Katira"],"Río Cuarto":["Río Cuarto"]},"Cartago":{"Cartago":["Oriental","Occidental","Carmen","San Nicolás","Aguacaliente o San Francisco","Guadalupe o Arenilla","Corralillo","Tierra Blanca","Dulce Nombre","Llano Grande","Quebradilla"],"Paraíso":["Paraíso","Santiago","Orosi","Cachí","Llanos de Santa Lucía"],"La Unión":["Tres Ríos","San Diego","San Juan","San Rafael","Concepción","Dulce Nombre","San Ramón","Río Azul"],"Jiménez":["Juan Viñas","Tucurrique","Pejibaye"],"Turrialba":["Turrialba","La Suiza","Peralta","Santa Cruz","Santa Teresita","Pavones","Tuis","Tayutic","Santa Rosa","Tres Equis","La Isabel","Chirripó"],"Alvarado":["Pacayas","Cervantes","Capellades"],"Oreamuno":["San Rafael","Cot","Potrero Cerrado","Cipreses","Santa Rosa"],"El Guarco":["Tejar","San Isidro","Tobosi","Patio de Agua"]},"Heredia":{"Heredia":["Heredia","Mercedes","San Francisco","Ulloa","Varablanca"],"Barva":["Barva","San Pedro","San Pablo","San Roque","Santa Lucía","San José de la Montaña"],"Santo Domingo":["Santo Domingo","San Vicente","San Miguel","Paracito","Santo Tomás","Santa Rosa","Tures","Para"],"Santa Bárbara":["Santa Bárbara","San Pedro","San Juan","Jesús","Santo Domingo","Puraba"],"San Rafael":["San Rafael","San Josécito","Santiago","Ángeles","Concepción"],"San Isidro":["San Isidro","San José","Concepción","San Francisco"],"Belén":["San Antonio","La Ribera","La Asunción"],"Flores":["San Joaquín","Barrantes","Llorente"],"San Pablo":["San Pablo","Rincón de Sabanilla"],"Sarapiquí":["Puerto Viejo","La Virgen","Horquetas","Llanuras del Gaspar","Cureña"]},"Guanacaste":{"Liberia":["Liberia","Cañas Dulces","Mayorga","Nacascolo","Curubandé"],"Nicoya":["Nicoya","Mansion","San Antonio","Quebrada Honda","Samara","Nosara","Belén de Nosarita"],"Santa Cruz":["Santa Cruz","Bolsón","Veintisiete de Abril","Tempate","Cartagena","Cuajiniquil","Diria","Cabo Velas","Tamarindo"],"Bagaces":["Bagaces","Fortuna","Mogote","Río Naranjo"],"Carrillo":["Filadelfia","Palmira","Sardinal","Belén"],"Cañas":["Cañas","Palmira","San Miguel","Bebedero","Porozal"],"Abangares":["Juntas","Sierra","San Juan","Colorado"],"Tilarán":["Tilarán","Quebrada Grande","Tronadora","Santa Rosa","Líbano","Tierras Morenas","Arenal"],"Nandayure":["Carmona","Santa Rita","Zapotal","San Pablo","Porvenir","Bejuco"],"La Cruz":["La Cruz","Santa Cecilia","Garita","Santa Elena"],"Hojancha":["Hojancha","Monte Romo","Puerto Carrillo","Huacas"]},"Puntarenas":{"Puntarenas":["Puntarenas","Pitahaya","Chomes","Lepanto","Paquera","Manzanillo","Guacimal","Barranca","Monte Verde","Isla del Coco","Cobano","Chacarita","Chira","Acapulco","El Roble","Arancibia"],"Esparza":["Espiritu Santo","San Juan Grande","Macacona","San Rafael","San Jerónimo","Caldera"],"Buenos Aires":["Buenos Aires","Volcan","Potrero Grande","Boruca","Pilas","Colinas","Changena","Briolley","Brunka"],"Montes de Oro":["Miramar","La Unión","San Isidro"],"Osa":["Puerto Cortés","Palmar","Sierpe","Bahia Ballena","Piedras Blancas","Bahía Drake"],"Quepos":["Quepos","Savegre","Naranjito"],"Golfito":["Golfito","Puerto Jiménez","Guaycará","Pavón"],"Coto Brus":["San Vito","Sabalito","Aguabuena","Limóncito","Pittier","Gutiérrez Braun"],"Parrita":["Parrita"],"Corredores":["Corredor","La Cuesta","Canoas","Laurel"],"Garabito":["Jacó","Tarcoles"]},"Limon":{"Limón":["Limón","Valle La Estrella","Río Blanco","Matama"],"Pococí":["Guapiles","Jiménez","La Rita","Roxana","Cariari","Colorado","La Colonia"],"Siquirres":["Siquirres","Pacuarito","Florida","Germania","Cairo","Alegría"],"Talamanca":["Bratsi","Sixaola","Cahuita","Telire"],"Matina":["Matina","Batán","Carrandi"],"Guácimo":["Guácimo","Mercedes","Pocora","Río Jiménez","Duacarí"]}}' ); var provin = "12"; var cantono = "12"; var provin1 = "12"; var cantono1 = "12"; var provinp = "12"; var cantonop = "12"; var provin1p = "12"; var cantono1p = "12"; var initial_cant = "12"; var initial_distr = "12"; var initial_cantp = "12"; var initial_distrp = "12"; var page_set = "none"; if ($('select[name="id_state"]').length > 0) { page_set = "order"; } if ($('select[name="shipping_address[id_state]"]').length > 0) { page_set = "supercheckout"; } if (page_set != "none") { $(document).ready(function () { if (page_set == "order") { initial_cant = $('input[name="canton"]').val(); initial_distr = $('input[name="district"]').val(); var canton_div = $('input[name="canton"]').parent(); $('input[name="canton"]').hide(); $(canton_div).append( '' ); $(document).on("change", 'select[name="id_state"]', function (e) { provin = $('select[name="id_state"] option:selected').html(); $("#canton_new").html(""); $.each(provinces[provin], function (key, value) { var option = ""; $("#canton_new").append(option); }); $("#canton_new").trigger("change"); }); $(document).on("change", "#canton_new", function (e) { var val = $("#canton_new option:selected").html(); $('input[name="canton"]').val($("#canton_new").val()); }); var district_div = $('input[name="district"]').parent(); $('input[name="district"]').hide(); $(district_div).append( '' ); $(document).on("change", "#canton_new", function (e) { cantono = $("#canton_new option:selected").html(); $("#district_new").html(""); $.each(provinces[provin][cantono], function (key, value) { var option = ""; $("#district_new").append(option); }); $("#district_new").trigger("change"); }); $(document).on("change", "#district_new", function (e) { var val = $("#district_new option:selected").html(); $('input[name="district"]').val($("#district_new").val()); }); // setDefaultsForPaymentDetailsSection(); //setDefaultsForUnsignedDetailsSection(); setTimeout(function () { $('select[name="id_state"]').trigger("change"); }, 100); setTimeout(function () { $("#canton_new").val(initial_cant); $("#canton_new").trigger("change"); }, 200); setTimeout(function () { $("#district_new").val(initial_distr); // $('#district_new').trigger('change'); }, 300); } /* var city_div = $('input[name="city"]').parent(); $('input[name="city"]').hide(); $(city_div).append(''); $.each(cities, function(key, value) { var option = ""; $('#city_new').append(option); console.log(value); }); $(document).on('change', '#city_new', function(e){ var val = $('#city_new option:selected').html(); var a = cities.indexOf(val); $('input[name="city"]').val($('#city_new').val()); console.log(val); }); $('#city_new').trigger('change'); */ if (page_set == "supercheckout") { initial_cant = $( '.shipping_update_form input[name="shipping_update_canton_holder"]' ).val(); initial_distr = $( '.shipping_update_form input[name="shipping_update_district_holder"]' ).val(); initial_cant = $( '.payment_update_form input[name="payment_update_canton_holder"]' ).val(); initial_distr = $( '.payment_update_form input[name="payment_update_district_holder"]' ).val(); // loadDeafultsP(); $(document).on( "change", '#shipping-new select[name="shipping_address[id_state]"]', function (e) { provin = $(this).find("option:selected").html(); $('#shipping-new select[name="shipping_new_canton"]').html(""); if (provinces[provin] != undefined) { $.each(provinces[provin], function (key, value) { var option = ""; $('#shipping-new select[name="shipping_new_canton"]').append( option ); }); } $('#shipping-new select[name="shipping_new_canton"]').trigger( "change" ); } ); $(document).on( "change", '#payment-new select[name="payment_address[id_state]"]', function (e) { provinp = $(this).find("option:selected").html(); $('#payment-new select[name="payment_new_canton"]').html(""); if (provinces[provinp] != undefined) { $.each(provinces[provinp], function (key, value) { var option = ""; $('#payment-new select[name="payment_new_canton"]').append( option ); }); } $('#payment-new select[name="payment_new_canton"]').trigger("change"); } ); $(document).on( "change", '.shipping_update_form select[name="shipping_address[id_state]"]', function (e) { provin1 = $(this).find("option:selected").html(); $('.shipping_update_form select[name="shipping_update_canton"]').html( "" ); if (provinces[provin1] != undefined) { $.each(provinces[provin1], function (key, value) { var option = ""; $( '.shipping_update_form select[name="shipping_update_canton"]' ).append(option); }); } $( '.shipping_update_form select[name="shipping_update_canton"]' ).trigger("change"); } ); $(document).on( "change", '.payment_update_form select[name="payment_address[id_state]"]', function (e) { provin1p = $(this).find("option:selected").html(); $('.payment_update_form select[name="payment_update_canton"]').html( "" ); if (provinces[provin1p] != undefined) { $.each(provinces[provin1p], function (key, value) { var option = ""; $( '.payment_update_form select[name="payment_update_canton"]' ).append(option); }); } $( '.payment_update_form select[name="payment_update_canton"]' ).trigger("change"); } ); //DIstricts $(document).on( "change", '#shipping-new select[name="shipping_new_canton"]', function (e) { cantono = $(this).find("option:selected").html(); $('#shipping-new select[name="shipping_new_district"]').html(""); if (provinces[provin][cantono] != undefined) { $.each(provinces[provin][cantono], function (key, value) { var option = ""; $('#shipping-new select[name="shipping_new_district"]').append( option ); }); } $('#shipping-new select[name="shipping_new_district"]').trigger( "change" ); $("#shipping_address_canton").val( $('#shipping-new select[name="shipping_new_canton"]').val() ); } ); $(document).on( "change", '#payment-new select[name="payment_new_canton"]', function (e) { cantonop = $(this).find("option:selected").html(); $('#payment-new select[name="payment_new_district"]').html(""); if (provinces[provinp][cantonop] != undefined) { $.each(provinces[provinp][cantonop], function (key, value) { var option = ""; $('#payment-new select[name="payment_new_district"]').append( option ); }); } $('#payment-new select[name="payment_new_district"]').trigger( "change" ); $("#payment_address_canton").val( $('#payment-new select[name="payment_new_canton"]').val() ); } ); $(document).on( "change", '.shipping_update_form select[name="shipping_update_canton"]', function (e) { cantono1 = $(this).find("option:selected").html(); $( '.shipping_update_form select[name="shipping_update_district"]' ).html(""); if (provinces[provin1][cantono1] != undefined) { $.each(provinces[provin1][cantono1], function (key, value) { var option = ""; $( '.shipping_update_form select[name="shipping_update_district"]' ).append(option); }); } $( '.shipping_update_form select[name="shipping_update_district"]' ).trigger("change"); $("#shipping_address_canton").val( $( '.shipping_update_form select[name="shipping_update_canton"]' ).val() ); } ); $(document).on( "change", '.payment_update_form select[name="payment_update_canton"]', function (e) { cantono1p = $(this).find("option:selected").html(); $('.payment_update_form select[name="payment_update_district"]').html( "" ); if (provinces[provin1p][cantono1p] != undefined) { $.each(provinces[provin1p][cantono1p], function (key, value) { var option = ""; $( '.payment_update_form select[name="payment_update_district"]' ).append(option); }); } $( '.payment_update_form select[name="payment_update_district"]' ).trigger("change"); $("#payment_address_canton").val( $('.payment_update_form select[name="payment_update_canton"]').val() ); } ); $(document).on( "change", '#shipping-new select[name="shipping_new_district"]', function (e) { $("#shipping_address_district").val( $('#shipping-new select[name="shipping_new_district"]').val() ); } ); $(document).on( "change", '#payment-new select[name="payment_new_district"]', function (e) { $("#payment_address_district").val( $('#payment-new select[name="payment_new_district"]').val() ); } ); $(document).on( "change", '.shipping_update_form select[name="shipping_update_district"]', function (e) { $("#shipping_address_district").val( $( '.shipping_update_form select[name="shipping_update_district"]' ).val() ); } ); $(document).on( "change", '.payment_update_form select[name="payment_update_district"]', function (e) { $("#payment_address_district").val( $( '.payment_update_form select[name="payment_update_district"]' ).val() ); } ); } }); } $(function () { payment_form = $("form").attr("id"); addLinkToSetDefaults(); }); function loadDeafultsP() { provin = $('#shipping-new select[name="shipping_address[id_state]"]') .find("option:selected") .html(); provinp = $('#payment-new select[name="payment_address[id_state]"]') .find("option:selected") .html(); provin1 = $('.shipping_update_form select[name="shipping_address[id_state]"]') .find("option:selected") .html(); provin1p = $('.payment_update_form select[name="payment_address[id_state]"]') .find("option:selected") .html(); if (provinces[provin] != "undefined") { $.each(provinces[provin], function (key, value) { var option = ""; $('#shipping-new select[name="shipping_new_canton"]').append(option); }); } if (provinces[provinp] != "undefined") { $.each(provinces[provinp], function (key, value) { var option = ""; $('#payment-new select[name="payment_new_canton"]').append(option); }); } if (provinces[provin1] != "undefined") { $.each(provinces[provin1], function (key, value) { var option = ""; $('.shipping_update_form select[name="shipping_update_canton"]').append( option ); }); } if (provinces[provin1p] != "undefined") { $.each(provinces[provin1p], function (key, value) { var option = ""; $('.payment_update_form select[name="payment_update_canton"]').append( option ); }); } $('.shipping_update_form select[name="shipping_update_canton"]').val( '.shipping_update_form select[name="shipping_update_canton_holder"]' ); $('.payment_update_form select[name="payment_update_canton"]').val( '.payment_update_form select[name="payment_update_canton_holder"]' ); cantono = $('#shipping-new select[name="shipping_new_canton"]') .find("option:selected") .html(); cantonop = $('#payment-new select[name="payment_new_canton"]') .find("option:selected") .html(); cantono1 = $('.shipping_update_form select[name="shipping_update_canton"]') .find("option:selected") .html(); cantono1p = $('.payment_update_form select[name="payment_update_canton"]') .find("option:selected") .html(); if (provinces[provin][cantono] != "undefined") { $.each(provinces[provin][cantono], function (key, value) { var option = ""; $('#shipping-new select[name="shipping_new_district"]').append(option); }); } if (provinces[provinp][cantonop] != "undefined") { $.each(provinces[provinp][cantonop], function (key, value) { var option = ""; $('#payment-new select[name="payment_new_district"]').append(option); }); } if (provinces[provin1][cantono1] != "undefined") { $.each(provinces[provin1][cantono1], function (key, value) { var option = ""; $('.shipping_update_form select[name="shipping_update_district"]').append( option ); }); } if (provinces[provin1p][cantono1p] != "undefined") { $.each(provinces[provin1p][cantono1p], function (key, value) { var option = ""; $('.payment_update_form select[name="payment_update_district"]').append( option ); }); } $('.shipping_update_form select[name="shipping_update_district"]').val( '.shipping_update_form select[name="shipping_update_district_holder"]' ); $('.payment_update_form select[name="payment_update_district"]').val( '.payment_update_form select[name="payment_update_district_holder"]' ); } function setDefaultsForAll() { if (payment_form === "payment_confirmation") { setDefaultsForUnsignedDetailsSection(); } else { setDefaultsForPaymentDetailsSection(); } } function addLinkToSetDefaults() { $(".section") .prev() .each(function (i) { legendText = $(this).text(); $(this).text(""); var setDefaultMethod = "setDefaultsFor" + capitalize($(this).next().attr("id")) + "()"; newlink = $(document.createElement("a")); newlink.attr({ id: "link-" + i, name: "link" + i, href: "#", }); newlink.append(document.createTextNode(legendText)); newlink.bind("click", function () { eval(setDefaultMethod); }); $(this).append(newlink); }); newbutton = $(document.createElement("input")); newbutton.attr({ id: "defaultAll", value: "Default All", type: "button", onClick: "setDefaultsForAll()", }); newbutton.bind("click", function () { setDefaultsForAll; }); $("#" + payment_form).append(newbutton); } function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function setDefaultsForPaymentDetailsSection() { $("input[name='transaction_type']").val("authorization"); // $("input[name='reference_number']").val(new Date().getTime()); $("#js_time").val(new Date().getTime()); $("input[name='amount']").val("10.00"); $("input[name='currency']").val("USD"); /* $("input[name='payment_method']").val("card"); $("input[name='bill_to_forename']").val("John"); $("input[name='bill_to_surname']").val("Doe"); $("input[name='bill_to_email']").val("null@cybersource.com"); $("input[name='bill_to_phone']").val("02890888888"); $("input[name='bill_to_address_line1']").val("1 Card Lane"); $("input[name='bill_to_address_city']").val("My City"); $("input[name='bill_to_address_state']").val("CA"); $("input[name='bill_to_address_country']").val("US"); $("input[name='bill_to_address_postal_code']").val("94043");*/ //2222 4200 0000 1113 var diff = $("#js_time").val() / 1000 - $("input[name='reference_number']").val(); $("#js_time_diff").val(diff); } function setDefaultsForUnsignedDetailsSection() { $("input[name='card_type']").val("001"); $("input[name='card_number']").val("4242424242424242"); $("input[name='card_expiry_date']").val("11-2020"); } $(document).ready(function () { /* if($('#category .category-image').length > 0) { if (prestashop.language.iso_code == 'en') { var url = "https://payless.cr/img/c/other/CR-Flash-sale-1000x200-ENG.jpg"; } if (prestashop.language.iso_code == 'es' || prestashop.language.iso_code == 'cb') { var url = "https://payless.cr/img/c/other/CR-Flash-sale-1000x200-SPA.jpg"; } flash sale if (prestashop.language.iso_code == 'en') { var url = "https://payless.cr/img/c/other/CR-Flash-sale-1000x200-ENG.jpg"; } if (prestashop.language.iso_code == 'es' || prestashop.language.iso_code == 'cb') { var url = "https://payless.cr/img/c/other/CR-Flash-sale-1000x200-SPA.jpg"; } //bts bogo if (prestashop.language.iso_code == 'en') { var url = "https://payless.cr/img/c/other/BTS-50-1000x200-ENG.jpg"; } if (prestashop.language.iso_code == 'es' || prestashop.language.iso_code == 'cb') { var url = "https://payless.cr/img/c/other/BTS-50-1000x200-SPA.jpg"; } GranLiquidacion-1000x200-ENG.jpg"; CAMBIO DE BANNERS PLP plp */ function get_program_banner_CrBannerUrlESP() { // Get today's date const today = new Date(); // Set the date for Mining Colombia const eventDate = new Date("2024-11-22 00:00:00"); // Set image URLs const eventImageUrl = "/img/c/other/40OffOnline-CR_SV-1000x200-SPA.jpg"; const defaultImageUrl = "https://payless.cr/img/c/other/40OffOnline-CR_SV-1000x200-ENG.jpg"; // Check if today is the event date and return the corresponding URL return today.toDateString() === eventDate.toDateString() ? eventImageUrl : defaultImageUrl; } function get_program_banner_CrBannerUrlENG() { // Get today's date const today = new Date(); // Set the date for Mining Colombia const eventDate = new Date("2024-11-22 00:00:00"); // Set image URLs const eventImageUrl = "/img/c/other/40OffOnline-CR_SV-1000x200-ENG.jpg"; const defaultImageUrl = "https://payless.cr/img/c/other/40OffOnline-GT_HN-1920x500-SPA.jpg"; // Check if today is the event date and return the corresponding URL return today.toDateString() === eventDate.toDateString() ? eventImageUrl : defaultImageUrl; } const urlArray = window.location.href.split("/"); if (prestashop.language.iso_code == "en") { let url = "https://payless.cr/img/c/other/CAM-CA 50_1000x200 ENG.jpg"; // bogo CAM-CA-50off-1000x200-ENG.jpg if (urlArray.includes("157-men")) { url = "/img/category/Hombres ENG.jpg"; } else if (urlArray.includes("169-women")) { url = "/img/category/Mujeres ENG.jpg"; } else if (urlArray.includes("231-girls")) { url = "/img/category/Ninas ENG.jpg"; } else if (urlArray.includes("171-athletics") || urlArray.includes("159-athletics") || urlArray.includes("231-athletics") || urlArray.includes("245-athletics")) { url = "/img/category/Atléticos ENG.jpg"; } else if (urlArray.includes("245-boys")) { url = "/img/category/Hombres ENG.jpg"; } else if (urlArray.includes("259-accessories")) { url = "/img/category/Accesorios ENG.jpg"; } $("#category .category-image img").attr("src", url); } if ( prestashop.language.iso_code == "es" || prestashop.language.iso_code == "cb" ) { let url = "https://payless.cr/img/c/other/CAM-CA 50_1000x200.jpg";; //CAM-CA-50off-1000x200-SPA.jpg if (urlArray.includes("157-hombres")) { url = "/img/category/Hombres ESP.jpg"; } else if (urlArray.includes("169-mujeres")) { url = "/img/category/Mujeres ESP.jpg"; } else if (urlArray.includes("231-ninas")) { url = "/img/category/Ninas ESP.jpg"; } else if (urlArray.includes("245-ninos")) { url = "/img/category/Ninos ESP.jpg"; } else if (urlArray.includes("259-accesorios")) { url = "/img/category/Accesorios ESP.jpg"; } else if (urlArray.includes("172-tenis-y-zapatos-deportivo") || urlArray.includes("159-tenis-y-zapatos-deportivo") || urlArray.includes("231-tenis-y-zapatos-deportivo") || urlArray.includes("245-tenis-y-zapatos-deportivo") ) { url = "/img/category/Atléticos ESP.jpg"; } $("#category .category-image img").attr("src", url); } $("body").on("click", ".js-increase-product-quantity", function () { // if(!$(this).hasClass('disabled')) { var that = this; $(".js-decrease-product-quantity, .js-increase-product-quantity").attr( "disabled", "disabled" ); setTimeout(function () { $( ".js-decrease-product-quantity, .js-increase-product-quantity" ).removeAttr("disabled"); }, 5000); }); $("body").on("click", ".js-decrease-product-quantity", function () { // if(!$(this).hasClass('disabled')) { var that = this; $(".js-decrease-product-quantity, .js-increase-product-quantity").attr( "disabled", "disabled" ); setTimeout(function () { $( ".js-decrease-product-quantity, .js-increase-product-quantity" ).removeAttr("disabled"); }, 5000); }); }); $(document).ready(function () { if ($("#module-supercheckout-supercheckout").length > 0) { var iqitpopup_c_payments_cr = {}; iqitpopup_c_payments_cr.script = (function () { var $el = $("#iqitpopup_c_payments_cr"); var $overlay = $("#iqitpopup_c_payments_cr_overlay"); var elHeight = $el.outerHeight(); var elWidth = $el.outerWidth(); var $wrapper = $(window); var offset = -30; var sizeData = { size: { width: $wrapper.width() + offset, height: $wrapper.height() + offset, }, }; function init() { setTimeout(function () { $el.addClass("showed-iqitpopup"); $overlay.addClass("showed-iqitpopupo"); }, iqitpopup.delay); $el .find(".iqit-btn-newsletter") .first() .click(function () { setCookie(); $overlay.removeClass("showed-iqitpopupo"); $el.removeClass("showed-iqitpopup"); }); /* $(document).on('click', '#iqitpopup_c_payments_cr .cross, #iqitpopup_c_payments_cr_overlay', function () { $overlay.removeClass('showed-iqitpopupo'); $el.removeClass('showed-iqitpopup'); if ($("#iqitpopup-checkbox").is(':checked')) { setCookie(); } });*/ doResize(sizeData, false); $wrapper.resize(function () { sizeData.size.width = $wrapper.width() + offset; sizeData.size.height = $wrapper.height() + offset; doResize(sizeData, true); }); } function doResize(ui, resize) { if (elWidth >= ui.size.width || elHeight >= ui.size.height) { var scale; scale = Math.min( ui.size.width / elWidth, ui.size.height / elHeight ); $el.css({ transform: "translate(-50%, -50%) scale(" + scale + ")", }); } else { if (resize) { $el.css({ transform: "translate(-50%, -50%) scale(1)", }); } } } function setCookie() { /* var name = iqitpopup.name; var value = '1'; var expire = new Date(); expire.setDate(expire.getDate() + iqitpopup.time); document.cookie = name + "=" + escape(value) + ";path=/;" + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))*/ } return { init: init }; })(); iqitpopup_c_payments_cr.script.init(); $(document).on( "click", '#payment-method input[name="payment_method"]', function () { iqitpopup_c_payments_cr.script.init(); } ); $("#module-supercheckout-supercheckout .button-agree").on( "click", function () { $("#iqitpopup_c_payments_cr_overlay").removeClass("showed-iqitpopupo"); $("#iqitpopup_c_payments_cr").removeClass("showed-iqitpopup"); } ); } }); /*------------------------*\ | - Marcas de Costa Rica - | \*------------------------*/ function removeBrands() { const pag = window.location.pathname; if (pag === "/es/marcas") { const items = document.querySelectorAll("div.ms-grid div.brand"); if (items) { items[5].remove(); items[16].remove(); items[19].remove(); items[20].remove(); items[29].remove(); items[33].remove(); } } } // Remover texto carrito function deleteTextCarrito() { const textoContenedor = document.querySelectorAll(".cart-grid-body > div")[1]; if (textoContenedor) { textoContenedor.remove(); } } // Remover texto HOME function deleteBannerText() { const bannerCntenedor = document.querySelector(".elementor-column-wrap"); if (bannerCntenedor) { bannerCntenedor.remove(); } } // Function manager function checkUrl() { const url = window.location.pathname; const homeUrl = window.location.pathname.replaceAll("/", ""); if (homeUrl === "en" || homeUrl === "es") { deleteBannerText(); } if (url.includes("cart")) { deleteTextCarrito(); //removeOldPromosCheckout(); removeEmptyTextCart(); } } // Ejecutar funcion document.addEventListener("DOMContentLoaded", () => { //removeOldPromosCheckout(); removeOnDesk(); removeOnMobile(); if (!checkIfCheckout()) { checkUrl(); removeBrands(); deleteCurrency(); if (window.innerWidth < 768) { document .querySelector( "#mobile-header-sticky > div > div.mobile-main-bar > div > div.languageContainer" ) .appendChild(document.querySelector("#language_selector")); } } }); function deleteCurrency() { const currency = document.querySelector("#currency_selector"); if (currency) { currency.remove(); } } function manageMutationVitrina() { const target = document.querySelector("#products"); if (!target) return; const config = { attributes: false, childList: true, subtree: true }; const callback = function (mutationsList, observer) { for (const mutation of mutationsList) { if (mutation.type === "childList") { debounce(repairSrcVitrina(), 1000); } } }; const observer = new MutationObserver(callback); observer.observe(target, config); } function repairSrcVitrina(intento = 0) { if (intento === 0) { setTimeout(() => repairSrcVitrina(1), 15000); setTimeout(() => repairSrcVitrina(1), 3000); } const changeAttr = ["data-src", "src", "data-full-size-image-url"]; const items = document.querySelectorAll(".thumbnail-container"); if (!items) return; items.forEach((item) => { const imgs = item.querySelectorAll("img"); imgs.forEach((img) => { if (!img.classList.contains("error")) return; if (img.classList.contains("fixed")) return; changeAttr.forEach((attr) => { const src = img.getAttribute(attr); if (src) { const newSrc = src.replace("payless.cr", "paylesscolombia.co"); img.setAttribute(attr, newSrc); } }); img.classList.add("fixed"); }); }); } document.addEventListener("DOMContentLoaded", () => { //removeOldPromosCheckout(); if (!checkIfCheckout()) { checkUrl(); addVerTodoItems(); convertAnchorsToTitleCase(); clicksQty(); setTimeout(() => { addQtyProducts(); }, 2500); removeEmptyTextCart(); insertWhatsappIcon(); repairSrcVitrina(); repairSrcProduct(); manageMutationVitrina(); const debouncedRepairSrcVitrina = debounce(repairSrcVitrina, 500); window.addEventListener("scroll", debouncedRepairSrcVitrina); } }); function checkIfCheckout() { const url = window.location.pathname; if (url.includes("/supercheckout/supercheckout")) { return true; } return false; } function debounce(func, wait, immediate) { let timeout; return function () { const context = this; const args = arguments; const later = function () { timeout = null; if (!immediate) func.apply(context, args); }; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; } function repairSrcProduct() { const changeAttr = [ "data-src", "src", "data-image-large-src", "data-image-medium-src", "data-image-small-src", ]; const items = document.querySelector(".images-container"); if (!items) return; const imgs = items.querySelectorAll("img"); imgs.forEach((img) => { if (img.classList.contains("fixed")) return; let srcReplaced = false; changeAttr.forEach((attr) => { const src = img.getAttribute(attr); if (src && !srcReplaced) { const testImg = new Image(); testImg.onload = () => { srcReplaced = true; }; testImg.onerror = () => { const newSrc = src.replace("payless.cr", "paylesscolombia.co"); img.setAttribute(attr, newSrc); srcReplaced = true; }; testImg.src = src; } }); if (srcReplaced) { img.classList.add("fixed"); } }); } function moveElementToTop() { const parent = document.querySelector("#content"); const elementSpa = document.querySelector(".elementor-element-teka90g"); const elementEng = document.querySelector(".elementor-element-cqkqnin"); const element = elementSpa ?? elementEng; if (!parent || !element) { return; } parent.insertBefore(element, parent.firstChild); } function insertWhatsappIcon() { const mainPage = document.getElementById("main-page-content"); if (!mainPage) return console.log("No main page found"); if (document.querySelector(".wp-icon")) { return console.log("Whatsapp icon already inserted"); } const imgSrc = "https://www.payless.cr/img/c/other/wp-icon.png"; const imgHoverSrc = "https://www.payless.cr/img/c/other/wp-hover.png"; const whatsappUrl = "https://api.whatsapp.com/send?phone=50670964289&text=Hola%20Payless!"; // Create anchor element const anchor = document.createElement("a"); anchor.href = whatsappUrl; anchor.target = "_blank"; anchor.style.position = "fixed"; anchor.style.bottom = "20px"; anchor.style.right = "20px"; anchor.style.zIndex = "9999"; anchor.style.cursor = "pointer"; anchor.style.transition = "all 0.3s ease-in-out"; anchor.style.display = "block"; // Ensure proper layout anchor.title = "Chat con nosotros en WhatsApp"; // Improved accessibility // Create image element const img = document.createElement("img"); img.classList.add("wp-icon"); img.src = imgSrc; img.style.width = "60px"; img.style.height = "60px"; img.alt = "WhatsApp Icon"; // Add hover effects img.addEventListener("mouseover", () => img.src = imgHoverSrc); img.addEventListener("mouseout", () => img.src = imgSrc); // Assemble elements anchor.appendChild(img); mainPage.appendChild(anchor); } function removeEmptyTextCart() { // aloha if (document.querySelector(".no-items")) { document.querySelector(".cart-toggle-details").textContent = document .querySelector(".cart-toggle-details") .textContent.replace(" Vacio", "") .replace("/", "") .replace(" Vacío", ""); document.querySelector(".cart-toggle-details").textContent = document .querySelector(".cart-toggle-details") .textContent.replace(" Empty", "") .replace("/", ""); } if (document.querySelector(".input-subscription")) { document.querySelector(".input-subscription").placeholder = "Escribe tu correo"; } } function addQtyProducts() { console.log("Adding quantity products"); const qtyProducts = document.querySelectorAll( ".input-group.form-control.input-qty" ); console.log("qty", qtyProducts); qtyProducts.forEach(function (quantity) { if (!quantity) return; quantity.setAttribute("value", 1); console.log(quantity); }); } function clicksQty() { const navItems = document.querySelectorAll(".nav-item"); navItems.forEach((item) => { item.addEventListener("click", () => { setTimeout(() => { addQtyProducts(); }, 1000); }); }); } function getCountry() { const url = window.location.href; const country = url.split("/")[3]; console.log(country); return country; } function clone() { if ($(".blockreassurance_product").length > 0) { if ( $("#main-product-wrapper .tabs.product-tabs .blockreassurance_product") .length == 0 ) { $(".blockreassurance_product").clone().appendTo(".tabs.product-tabs"); } } else { } } $(document).ready(function () { if (window.location.search == "?prueba") { formePartner2(); } clone(); topbarAnimateText(); topbarAnimateTextMobile(); var variable = $("body").attr("id"); if (variable == "category") { // formePartner(); } enviarePartner(); updateDate18years(); const closeCartButton = document.querySelector( ".search_menu_mobile_close button" ); if (!closeCartButton) return; closeCartButton.addEventListener("click", function (e) { e.preventDefault(); document .querySelector( "#mobile-header-sticky > div > div.mobile-main-bar > div > div.col.col-auto.col-mobile-btn.col-mobile-btn-menu.col-mobile-menu-push.show" ) .classList.remove("show"); }); }); const textsSpa = [ { title: "Envío gratuito", text: "a tu domicilio cuando compras dos o más artículos!", icon: "/modules/blockreassurance/views/img/img_perso/Icon-03.png", }, // { // title: "En esta temporada", // text: "Podrían ocurrir retrasos en los tiempos de tránsito. Gracias por tu paciencia y comprensión. 😊", // icon: "/modules/blockreassurance/views/img/img_perso/rejocDemora.png", // }, { title: "Pago 100% Seguro", text: "Estricta protección de los datos a través de todos los métodos de pago.", icon: "/modules/blockreassurance/views/img/img_perso/Icon-02.png", } ]; // text eng const textsEng = [ { title: "Free shipping", text: "to your home when you buy two or more articles!", icon: "/modules/blockreassurance/views/img/img_perso/Icon-03.png", }, // { // title: "In this season", // text: "Podrían ocurrir retrasos en los tiempos de tránsito. Gracias por tu paciencia y comprensión. 😊", // icon: "/modules/blockreassurance/views/img/img_perso/rejocDemora.png", // }, { title: "Secure payment", text: "Strict protection of data through all payment methods.", icon: "/modules/blockreassurance/views/img/img_perso/Icon-02.png", } ]; function topbarAnimateText() { const isEng = document.body.classList.contains("lang-en"); const textsArray = isEng ? textsEng : textsSpa; const texts = textsArray; const topbar = document.querySelector(".header-banner.textTop"); if (!topbar) return console.log("No topbar found"); if (topbar.classList.contains("carrousel-top")) return console.log("Already animated"); let index = 0; setInterval(() => { topbar.innerHTML = `   ${texts[index].title} ${texts[index].text} `; index = (index + 1) % texts.length; }, 5000); console.log("topbarAnimateText"); topbar.classList.add("carrousel-top"); } function calculateFreeShipping() { const products = document.querySelector( "span.cart-products-count-btn" ).textContent; const freeShippingProducts = 2; if (!products) { console.error("No products found"); return; } const isFree = parseInt(products) >= freeShippingProducts; // const isFree = true; // 22 nov // document.querySelectorAll('.freeshipping-body p').forEach(p => { // p.classList.length === 0 ? p.innerText = "Envío gratis todo el día 🎀" : "" // }) if (isFree) { if (window.innerWidth < 768) { const mobileContainer = document.querySelector( "#_mobile_blockcart-content" ); // mobile mobileContainer.querySelector(".notFree").classList.add("hidden"); mobileContainer.querySelector(".free").classList.remove("hidden"); const barThumbmobileContainer = mobileContainer.querySelector( ".freeshipping-bar-thumb" ); barThumbmobileContainer.classList.add("full"); barThumbmobileContainer.style.width = "100%"; return; } // desk const deskContainer = document.querySelector("#_desktop_blockcart-content"); if (!deskContainer.querySelector(".notFree")) return; deskContainer.querySelector(".notFree").classList.add("hidden"); deskContainer.querySelector(".free").classList.remove("hidden"); const barThumbdeskContainer = deskContainer.querySelector( ".freeshipping-bar-thumb" ); barThumbdeskContainer.classList.add("full"); barThumbdeskContainer.style.width = "100%"; return; } if (window.innerWidth < 768) { const mobileContainer = document.querySelector( "#_mobile_blockcart-content" ); // mobile const barThumbmobileContainer = mobileContainer.querySelector( ".freeshipping-bar-thumb" ); console.log("barThumbmobileContainer", barThumbmobileContainer); // mobileContainer.querySelector(".notFree").innerHTML = `Te falta agregar // ${ // freeShippingProducts - parseInt(products) < 0 // ? 0 // : freeShippingProducts - parseInt(products) // } // un articulo para ¡ENVÍO GRATIS!`; if (!mobileContainer.querySelector(".notFree")) return; mobileContainer.querySelector(".notFree").innerHTML = "Te falta agregar un articulo para ¡ENVÍO GRATIS!"; mobileContainer.querySelector(".notFree").classList.remove("hidden"); mobileContainer.querySelector(".free").classList.add("hidden"); // 2 products = 100% const percentage = (parseInt(products) / freeShippingProducts) * 100; console.log("percentage", percentage); barThumbmobileContainer.style.width = `${percentage}%`; barThumbmobileContainer.classList.remove("full"); return; } // desk const deskContainer = document.querySelector("#_desktop_blockcart-content"); const barThumbdeskContainer = deskContainer.querySelector( ".freeshipping-bar-thumb" ); console.log("barThumbdeskContainer", barThumbdeskContainer); // deskContainer.querySelector(".notFree").innerHTML = `Te falta ${ // freeShippingProducts - parseInt(products) < 0 // ? 0 // : freeShippingProducts - parseInt(products) // } producto para ¡ENVÍO GRATIS!`; if (!deskContainer.querySelector(".notFree")) return; deskContainer.querySelector(".notFree").innerHTML = "Te falta agregar un articulo para ¡ENVÍO GRATIS!"; deskContainer.querySelector(".notFree").classList.remove("hidden"); deskContainer.querySelector(".free").classList.add("hidden"); // 2 products = 100% const percentage = (parseInt(products) / freeShippingProducts) * 100; console.log("percentage", percentage); barThumbdeskContainer.style.width = `${percentage}%`; barThumbdeskContainer.classList.remove("full"); } function injectFreeShippingBox() { // Check if the box is already injected to avoid duplicates if (document.querySelector(".freeshippingbar-box")) return; var cartSubtotals = document.querySelector(".cart-subtotals"); if (cartSubtotals) { cartSubtotals.insertAdjacentHTML("afterend", freeShippingBoxHTML); // After injecting, you might want to call any functions to initialize the box or update its content calculateFreeShipping(); // Adjust this function for PrestaShop context } } function checkUrl() { document.querySelector("#blockcart").classList.add("mockup"); closeMobilemenu(); sendSearchOnClick(); calculateFreeShipping(); // Listen for PrestaShop cart update event and re-inject if necessary prestashop.on("updatedCart", function () { setTimeout(() => { openCartAfterAdd(); calculateFreeShipping(); }, 600); }); if (!document.querySelector(".cart-buttons .btn-primary")) return; document.querySelector(".cart-buttons .btn-primary").innerText = "Cerrar pedido"; } function changeQuantity( minimal_quantity, operator, id, id_attribute, quantincart ) { document.querySelector("#blockcart").classList.add("show-custom"); document.querySelector("#ps-shoppingcart").classList.add("show-custom"); var token = prestashop.static_token; //important for logged user if (operator == 1) { //subtract var actionURL = "/index.php"; var query = "controller=cart&add=1&action=update&ajax=true&qty=1&op=down&token=" + token + "&id_product=" + id + "&ipa=" + id_attribute; $.post(actionURL, query, null, "json") .then(function (resp) { prestashop.emit("updateCart", { reason: resp, }); console.log(resp); openCartAfterAdd(); }) .fail(function (resp) { prestashop.emit("handleError", { eventType: "addProductToCart", resp: resp, }); }); } else if (operator == 2) { //sum var actionURL = "/index.php"; var query = "controller=cart&add=1&action=update&ajax=true&qty=1&op=up&token=" + token + "&id_product=" + id + "&ipa=" + id_attribute; $.post(actionURL, query, null, "json") .then(function (resp) { prestashop.emit("updateCart", { reason: resp, }); console.log(resp); openCartAfterAdd(); }) .fail(function (resp) { prestashop.emit("handleError", { eventType: "addProductToCart", resp: resp, }); }); } else if (operator == 3) { //delete var actionURL = "/index.php"; var query = "controller=cart&add=1&action=update&ajax=true&qty=" + quantincart + "&op=down&token=" + token + "&id_product=" + id + "&ipa=" + id_attribute; $.post(actionURL, query, null, "json") .then(function (resp) { prestashop.emit("updateCart", { reason: resp, }); openCartAfterAdd(); }) .fail(function (resp) { prestashop.emit("handleError", { eventType: "addProductToCart", resp: resp, }); }); } } function formatPrice(price) { return price .toLocaleString("es-CO", { style: "currency", currency: "COP", }) .replace(",00", ""); } function openCartAfterAdd() { setTimeout(() => { const closeCartButton = document.querySelector( ".cart-buttons .btn.btn-secondary.btn-block" ); closeCartButton.addEventListener("click", function (e) { e.preventDefault(); document.querySelector("#blockcart").classList.remove("show"); }); document.querySelector("#blockcart").classList.add("show"); if (window.innerWidth < 1000) { document.querySelector("#mobile-cart-wrapper").classList.add("show"); } document.querySelector("#blockcart").classList.remove("show-custom"); document.querySelector("#ps-shoppingcart").classList.remove("show-custom"); }, 400); } // Eliminar cupones de BOGO o otras promos function removeOldPromosCheckout() { setTimeout(() => { const cartUrl = "/cart?action=show"; const today = new Date(); const cartUrlSpa = "/carrito?action=show"; const checkoutUrl = "/pedido"; const checkoutUrlEng = "/order"; const currentUrl = window.location.pathname + window.location.search; const eventDate = new Date("2024-10-25 00:00:00"); // if(today.toDateString() === eventDate.toDateString()){ // if (currentUrl.includes(cartUrl) || currentUrl.includes(cartUrlSpa)) { // const promoCodes = document.querySelectorAll(".promo-name li a"); // promoCodes.forEach((promoCode) => { // if ( // promoCode.parentNode // .querySelector("span") // .textContent.includes("BOGO") // ) { // setTimeout(() => { // promoCode.click(); // console.log("click"); // }, 1000); // } // }); // } // } if (currentUrl.includes(cartUrl) || currentUrl.includes(cartUrlSpa)) { const promoCodes = document.querySelectorAll(".promo-name li a"); promoCodes.forEach((promoCode) => { if ( promoCode.parentNode .querySelector("span") .textContent.includes("BOGO") //BOGO - Compra || || promoCode.parentNode .querySelector("span") .textContent.includes("Compra") ) { setTimeout(() => { promoCode.click(); console.log("click"); }, 1000); location.reload(); } }); } /* else if ( currentUrl.includes(checkoutUrl) || currentUrl.includes(checkoutUrlEng) ) { const promoCodes = document.querySelectorAll(".promo-name li a"); promoCodes.forEach((promoCode) => { setTimeout(() => { promoCode.click(); }, 2500); }); } */ }, 2400); } function formePartner() { console.log("cargueform"); $("#main-page-content").append( '
' + '
' + '
x
' + '
' + '' + '

ÚNETE A PAYLESS Y ENTÉRATE DE NUESTRAS PROMOCIONES Y BENEFICIOS

' + '
' + '' + '' + '' + "" + ' " + ' " + '' + '' + 'Al dar clic en Suscribirme acepto la
Política de Tratamiento de Datos
' + "
" + "
" + "
" + "
" ); $("#main-page-content").append( '' ); enviarePartner(); cerrarePartner(); } function cerrarePartner() { $(".closes").click(function () { $(".velo").css("display", "none"); }); } function enviarePartner() { //Primer Form if (getCookie("id") !== "") { setTimeout(function () { $("#iqitpopup").css("display", "none"); $("#iqitpopup-overlay.showed-iqitpopupo").remove(); }, 200); } const formulario2 = document.querySelector( ".iqitpopup-newsletter-form.redesign form" ); if (!formulario2) return; const procesaTodo2 = (event) => { event.preventDefault(); const datos = new FormData(event.target); const datosCompletos = Object.fromEntries(datos.entries()); if (!validateData(datosCompletos)) return; fetch("https://digitalepartner.com/paylessform/insumos/default.php", { method: "POST", body: datos, }) .then((res) => res.json()) .then((data) => { var message = data.Message; var id = data.Id; if (message === undefined) { $(".iqitpopup-newsletter-form.redesign input").css("display", "none"); $(".iqitpopup-newsletter-form.redesign select").css( "display", "none" ); $(".iqitpopup-newsletter-form.redesign button").css( "display", "none" ); $(".iqitpopup-newsletter-form.redesign a").css("display", "none"); $(".iqitpopup-newsletter-form.redesign label").css("display", "none"); $(".iqitpopup-newsletter-form.redesign").append( "

Tu suscripción ha sido exitosa

" ); setCookie("id", id, 30); setTimeout(function () { $("#iqitpopup").css("display", "none"); }, 20000); } else { console.log("error", message); } }); }; formulario2.addEventListener("submit", (e) => { e.preventDefault(); procesaTodo2(e); }); } // Function to transform text to title case function toTitleCase(str) { return str.toLowerCase().replace(/\b\w/g, (char) => char.toUpperCase()); } // Function to add "Ver todo" item function addVerTodoItems() { document.querySelectorAll("#iqitmegamenu-mobile li").forEach((li) => { const anchor = li.querySelector("a"); const innerUl = li.querySelector("ul"); if (anchor && innerUl) { const href = anchor.getAttribute("href"); const newLi = document.createElement("li"); const newAnchor = document.createElement("a"); newAnchor.setAttribute("href", href); newAnchor.textContent = "Ver Todo"; newAnchor.classList.add("verTodoLink"); newLi.appendChild(newAnchor); // Insert the new li at the first position of the inner ul innerUl.insertBefore(newLi, innerUl.firstChild); } }); } // Function to convert anchor text to title case function convertAnchorsToTitleCase() { document.querySelectorAll("#iqitmegamenu-mobile a").forEach((anchor) => { let text = anchor.textContent; text = text .toLowerCase() .split(/\s+/) .map((word) => { return word.charAt(0).toUpperCase() + word.slice(1); }) .join(" "); anchor.textContent = text; }); } function closeMobilemenu() { const btn = document.querySelector(".search_menu_mobile_close"); if (!btn) return; btn.addEventListener("click", function () { const backdrop = document.querySelector(".dropdown-backdrop"); backdrop && backdrop.click(); }); } function sendSearchOnClick() { const form = document.querySelector("#search_widget form"); const searchBtn = document.querySelector(".img_magnifier"); const input = document.querySelector("#search_widget input[name='s']"); if (!form || !searchBtn || !input) return; // input.addEventListener("input", function () { // this.value = this.value.trim(); // }); function submitSearch(e) { e.preventDefault(); // Prevent any default action if (input.value.trim() !== "") { form.submit(); } } // Handle both click and touch events searchBtn.addEventListener("click", submitSearch); searchBtn.addEventListener("touchend", submitSearch); // Prevent zoom on double-tap (for iOS) searchBtn.addEventListener("touchend", function (e) { e.preventDefault(); }); // Optional: Add focus to input when magnifier is clicked/touched searchBtn.addEventListener("click", function () { input.focus(); }); } function updateDate18years() { const dateContainer = document.getElementById("fecha"); if (!dateContainer) return; var date = new Date(); var year = date.getFullYear() - 18; var month = date.getMonth() + 1; var day = date.getDate(); if (month < 10) { month = "0" + month; } if (day < 10) { day = "0" + day; } var maxDate = year + "-" + month + "-" + day; document.getElementById("fecha").setAttribute("max", maxDate); } function validateData(data) { console.log("data", data); const form = document.querySelector( ".iqitpopup-newsletter-form.redesign form" ); const email = form.querySelector("#email1"); const nombre = form.querySelector("#nombre"); const celular = form.querySelector("#celular"); const fecha = form.querySelector("#fecha"); // Helper function to validate input function isValid(value, type) { const patterns = { email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, nombre: /^[a-zA-Z\s]{2,50}$/, celular: /^\d{10}$/, // Assuming 10-digit phone number fecha: /^\d{4}-\d{2}-\d{2}$/, // YYYY-MM-DD format }; // Check for suspicious patterns const suspiciousPatterns = [ /CLICK-ON-THE-LINK/i, /sites\.google\.com/i, /[А-Яа-я]/, // Cyrillic characters ]; if (suspiciousPatterns.some((pattern) => pattern.test(value))) { return false; } return patterns[type].test(value); } // Validate each field const fields = [ { element: email, type: "email" }, { element: nombre, type: "nombre" }, { element: celular, type: "celular" }, { element: fecha, type: "fecha" }, ]; let isFormValid = true; fields.forEach((field) => { if ( field.element.value === "" || !isValid(field.element.value, field.type) ) { field.element.setAttribute("required", "required"); field.element.classList.add("invalid"); isFormValid = false; } else { field.element.classList.remove("invalid"); } }); return isFormValid; } function setCookie(name, value, days) { const date = new Date(); date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); const expires = "expires=" + date.toUTCString(); document.cookie = name + "=" + value + ";" + expires + ";path=/"; } function getCookie(name) { const cookieName = name + "="; const decodedCookie = decodeURIComponent(document.cookie); const cookieArray = decodedCookie.split(";"); for (let i = 0; i < cookieArray.length; i++) { let cookie = cookieArray[i]; while (cookie.charAt(0) === " ") { cookie = cookie.substring(1); } if (cookie.indexOf(cookieName) === 0) { return cookie.substring(cookieName.length, cookie.length); } } return ""; } function formatPrice(price) { return price .toLocaleString("es-CO", { style: "currency", currency: "COP", }) .replace(",00", ""); } // Comparador function addVerProductoLinks() { // Select the table if (!document.querySelector("body#module-iqitcompare-comparator")) return; setTimeout(() => { const table = document.querySelector(".table.table-hover"); // Get the row containing the product cells const productRow = table.querySelector(".iqitcompare-product-tr"); // Get all product cells excluding the first one (which is empty) const productCells = productRow.querySelectorAll( ".iqitcompare-product-td:not(:first-child)" ); // Create a new row at the end of the table const newRow = table.insertRow(-1); // Insert an empty cell at the beginning of the new row to align with the table structure newRow.insertCell(0); // Loop through each product cell to extract the URL and create the anchor link productCells.forEach((cell) => { // Get the product link element const productLink = cell.querySelector(".pack-product-name a"); // Extract the href attribute (product URL) const productURL = productLink ? productLink.href : "#"; // Create a new cell in the new row const newCell = newRow.insertCell(-1); // Create the anchor element const anchor = document.createElement("a"); anchor.classList.add("product_link"); anchor.href = productURL; anchor.textContent = "Ver producto"; // Append the anchor to the new cell newCell.appendChild(anchor); }); }, 500); $(".product-slider").slick({ slidesToShow: 4, slidesToScroll: 1, dots: true, arrows: true, infinite: true, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 3, arrows: true, }, }, { breakpoint: 768, settings: { slidesToShow: 2, arrows: false, }, }, { breakpoint: 480, settings: { slidesToShow: 2, arrows: false, }, }, ], }); } // Ensure the DOM is fully loaded before running the script document.addEventListener("DOMContentLoaded", addVerProductoLinks); /* Sliders TALLAS */ // Function to handle the click event on carousel items function onCarouselItemClick(event) { const selectedAttributeId = event.target.getAttribute( "data-id-product-attribute" ); const productId = event.target.closest(".owl-carousel").id.split("-")[2]; // Select the form within the correct article element based on productId const form = document.querySelector( `article[data-id-product="${productId}"] .product-add-cart form` ); if (form) { // Remove any previous attribute input let existingInput = form.querySelector( 'input[name="id_product_attribute"]' ); if (existingInput) { form.removeChild(existingInput); } // Append the new input with the selected attribute ID const newInput = document.createElement("input"); newInput.type = "hidden"; newInput.name = "id_product_attribute"; newInput.value = selectedAttributeId; form.appendChild(newInput); // Update the form action URL to reflect the selected attribute const url = new URL(form.action); url.searchParams.set("id_product_attribute", selectedAttributeId); form.action = url.toString(); } // Highlight the selected size in the carousel, limited to the same product const carouselItems = event.target .closest(".owl-carousel") .querySelectorAll(".carousel-item"); carouselItems.forEach((item) => { item.classList.remove("selected"); }); // Add the 'selected' class to the clicked item event.target.classList.add("selected"); } // Function to initialize the Owl Carousel function initializeOwlCarousel() { // if (!document.getElementById("category")) { // console.log("Not category page"); // return; // } $(".product-combinations .owl-carousel").owlCarousel({ items: 5, loop: 0, margin: 5, nav: true, dots: false, responsive: { 0: { items: 3, margin: 0 }, 600: { items: 4 }, 1000: { items: 4, mouseDrag: false }, }, onInitialized: function () { // Process items and set up listeners after the carousel is fully initialized qtyFromZeroToOne(); //hideOneSize(); processCarouselItems(); setupCarouselListeners(); //preselectCurrentSize(); }, }); } function preselectCurrentSize() { // Find all 'Add to Cart' forms on the page const forms = document.querySelectorAll('form[action*="/carrito?add=1"]'); forms.forEach(form => { try { const actionUrl = form.getAttribute('action'); if (!actionUrl) { console.warn('Add to cart form found without action URL:', form); return; // Skip this form if it has no action } const url = new URL(actionUrl); const idProductAttribute = url.searchParams.get('id_product_attribute'); if (idProductAttribute) { // Find the parent product article to scope the search for the carousel item const productArticle = form.closest('article[data-id-product]'); if (!productArticle) { return; // Skip if we can't find the containing product } // Find the corresponding carousel item within this product's container const carouselItem = productArticle.querySelector( `.carousel-item[data-id-product-attribute="${idProductAttribute}"]` ); if (carouselItem) { // Remove 'selected' class from any previously selected item within the same carousel const carouselContainer = carouselItem.closest('.owl-carousel'); // Adjust selector if needed if (carouselContainer) { const previouslySelected = carouselContainer.querySelector('.carousel-item.selected'); if (previouslySelected) { previouslySelected.classList.remove('selected'); } } // Add the 'selected' class to the target item carouselItem.classList.add('selected'); // --- START: Scroll carousel to selected item --- if (carouselContainer && typeof $ === 'function' && $(carouselContainer).data('owl.carousel')) { try { const owlItem = carouselItem.closest('.owl-item'); // Find the direct parent .owl-item if (owlItem) { const itemIndex = $(owlItem).index(); // Get the 0-based index of the .owl-item if (itemIndex !== -1) { console.log(`Scrolling carousel to item index: ${itemIndex}`); // Trigger the Owl Carousel 'to' event to navigate $(carouselContainer).trigger('to.owl.carousel', [itemIndex, 300, true]); } } } catch(carouselError) { console.error('Error triggering Owl Carousel scroll:', carouselError); } } } } } catch (error) { console.error('Error in preselectCurrentSize for form:', form, error); } }); } // Function to process carousel item text and extract the Latam size function processCarouselItems() { document.querySelectorAll(".carousel-item").forEach((item) => { const sizeText = item.textContent.trim(); const latamSize = sizeText.split("/")[1]; if (latamSize) { item.textContent = latamSize.trim(); } }); } // Function to set up event listeners for carousel items function setupCarouselListeners() { document.querySelectorAll(".carousel-item").forEach((item) => { item.addEventListener("click", onCarouselItemClick); }); } // Function to remove empty size combinations function removeEmptySizes() { document.querySelectorAll(".product-combinations").forEach((combination) => { if (!combination.querySelector(".carousel-item")) { combination.remove(); } }); } function qtyFromZeroToOne() { const inputs_qty = document.querySelectorAll( "#category .product-add-cart .input-qty" ); if (!inputs_qty) return; inputs_qty.forEach((input) => { input.value = "1"; }); } function hideOneSize() { const carouselContainer = document.querySelectorAll(".thumbnail-container"); carouselContainer.forEach((carousel) => { const items = carousel.querySelectorAll(".carousel-item"); if (items.length < 2) { carousel.classList.add("only-one"); } }); } function updateCheckoutLink() { const currentUrl = window.location.href; const validUrls = [ "https://www.payless.cr/en/cart?action=show", "https://www.payless.cr/es/carrito?action=show", "https://www.payless.cr/carrito?action=show" ]; if (validUrls.includes(currentUrl)) { const elements = document.querySelectorAll( ".checkout.cart-detailed-actions a, div#ps-shoppingcart .cart-buttons a, div#_mobile_blockcart-content .cart-buttons a" ); elements.forEach((element) => { if (!element) return; element.href = "https://www.payless.cr/es/module/supercheckout/supercheckout"; }); } } // Initialize on DOM ready document.addEventListener("DOMContentLoaded", () => { updateCheckoutLink(); document.querySelector("#rev_slider_8_3_wrapper")?.remove(); document.querySelector("div#rev_slider_6_3_wrapper")?.remove(); document.querySelector("div#rev_slider_8_4_wrapper")?.remove(); }); function topbarAnimateTextMobile() { const isEng = document.body.classList.contains("lang-en"); const topbar = document.querySelector( "#mobile-header-sticky .header-banner.textTop" ); if (!topbar) return console.log("No topbar found"); if (topbar.classList.contains("carrousel-top")) return console.log("Already animated"); const textsArray = isEng ? textsEng : textsSpa; const texts = textsArray; let index = 0; setInterval(() => { topbar.innerHTML = `   ${texts[index].title} ${texts[index].text} `; index = (index + 1) % texts.length; }, 5000); console.log("topbarAnimateText"); topbar.classList.add("carrousel-top"); } function formePartner2() { console.log("cargueform"); $("#main-page-content").append( '
' + '
' + '
x
' + '
' + '
' + "" + "
" + '
' + '

ÚNETE A PAYLESS Y OBTEN UN 10% DE DESCUENTO

' + '' + '' + '' + '' + "" + '' + "

Género

" + "" + "

Tienes Hijos

" + "" + "
" + "" + "
" + '' + '' + "
" + "
" + "
" + "
" ); $("#main-page-content").append( '' ); enviarePartner(); cerrarePartner(); clickse(); } function clickse() { $(".genero").click(function () { $(".genero1").toggle(); }); $(".publicidad").click(function () { $(".publicidad1").toggle(); }); $(".hijos").click(function () { $(".hijos1").toggle(); }); $("#inputm, #inputn, #inputl").on("click", function () { $(".publicidad1 #inputo").prop("checked", false); }); $("#inputo").on("click", function () { $(".publicidad1 input").prop("checked", false); $(this).prop("checked", true); }); $("#inputf, #inputg, #inputh, #inputh").on("click", function () { $(".hijos1 #inputj").prop("checked", false); $(".hijos1 #inputk").prop("checked", false); }); $("#inputj").on("click", function () { $(".hijos1 input").prop("checked", false); $(this).prop("checked", true); }); $("#inputk").on("click", function () { $(".hijos1 input").prop("checked", false); $(this).prop("checked", true); }); } // remove on desk width > 1000 div#rev_slider_4_2_wrapper function removeOnDesk() { if (window.innerWidth > 1000) { document.querySelector("div#rev_slider_4_2_wrapper")?.remove(); } } // remove on mobile width < 1000 div#rev_slider_3_1_forcefullwidth function removeOnMobile() { if (window.innerWidth < 1000) { document.querySelector("div#rev_slider_3_1_forcefullwidth")?.remove(); } } (function () { document.querySelector(".block-iqitlinksmanager-6 a")?.setAttribute("target", "_blank"); })(); document.addEventListener('DOMContentLoaded', function () { // Check if url has a test_filter attribute if yes add the css and execute the js if (window.location.href.indexOf("test_filter") > -1 && window.innerWidth > 1024) { console.log("test_filter"); // Add css const style = document.createElement("style"); style.innerHTML = ` .category-image img { width: 100%; } .optimize-loading { opacity: 0 !important } /* --- Styles for Toggleable Content Panel --- */ /* Floating Toggle Button */ #content-panel-toggle-btn { position: fixed; bottom: 149.3px; right: 30px; z-index: 1045; background-color: #f89549; color: white; border: none; border-radius: 20px; width: fit-content; padding: 8.2px; height: 41.2px; font-size: 24px; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 8px rgba(0,0,0,0.15); cursor: pointer; transition: background-color 0.3s ease, transform 0.3s ease; } #content-panel-toggle-btn:hover { background-color: #259db5; /* A slightly darker shade for hover */ transform: scale(1.1); } /* Page Overlay for Fade Effect */ #page-content-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0); /* Initially transparent */ visibility: hidden; /* Initially hidden and not interactive */ opacity: 0; z-index: 1030; /* Below panel and button, above page content */ transition: background-color 0.3s ease-in-out, visibility 0s 0.3s linear, opacity 0.3s ease-in-out; /* Delay visibility change until fade-out is complete */ } /* Content Wrapper as Sliding Panel */ .sliding-panel { /* We'll add .sliding-panel class via JS for specificity */ position: fixed !important; top: 0 !important; right: 0 !important; left: auto !important; /* Override Bootstrap's attempts to make it full-width or left-aligned */ width: 320px !important; /* Adjust as needed, e.g., 400px or 30vw */ max-width: 90vw !important; /* Ensure it's not too wide on small screens */ height: 100vh !important; /* Full viewport height */ transform: translateX(100%); /* Initially off-screen to the right */ opacity: 0; visibility: hidden; /* Initially hidden */ background-color: #ffffff; /* Or your theme's panel background color */ padding: 20px; box-shadow: -3px 0 15px rgba(0,0,0,0.1); overflow-y: auto; /* Allow content within the panel to scroll */ z-index: 1040; /* Above overlay, below toggle button */ transition: transform 0.3s ease-in-out, opacity 0.3s ease-in-out, visibility 0s 0.3s linear; /* Delay visibility change for proper animation */ /* Resetting some potentially inherited styles that might conflict */ float: none !important; margin: 0 !important; } /* --- Active States (when panel is open) --- */ /* When body has .content-panel-active class */ body.content-panel-active { overflow: hidden; /* Prevent main page from scrolling when panel is open */ } body.content-panel-active #page-content-overlay { background: rgba(0, 0, 0, 0.5); /* Semi-transparent black */ visibility: visible; opacity: 1; transition-delay: 0s; /* Remove delay for fade-in */ } body.content-panel-active .sliding-panel { transform: translateX(0%); /* Slide into view */ opacity: 1; visibility: visible; transition-delay: 0s; /* Remove delay for slide-in */ } /* Optional: Change toggle button icon or style when panel is open */ /* For example, if you used an arrow and wanted to rotate it: */ /* body.content-panel-active #content-panel-toggle-btn { transform: rotate(180deg); } */ /* Or change the icon via JavaScript if you have two icons (e.g., menu and close) */ ` document.head.appendChild(style); if (document.getElementById("content-panel-toggle-btn")) { const toggle_content_panel = document.getElementById("toggle_content_panel"); const content_wrapper = document.getElementById("content-wrapper"); const toggleBtn = document.getElementById('content-panel-toggle-btn'); const contentWrapperPanel = document.getElementById('left-column'); const pageOverlay = document.getElementById('page-content-overlay'); const body = document.body; // First, check if all required elements are actually on the page if (!toggleBtn || !contentWrapperPanel || !pageOverlay) { console.warn('Toggle panel interactive elements not found. Please ensure #content-panel-toggle-btn, #content-wrapper, and #page-content-overlay exist in your HTML.'); // Stop the script if elements are missing } toggle_content_panel.style.display = 'block'; content_wrapper.classList.remove('col-md-9'); // Add the .sliding-panel class to the content-wrapper. // This class is used in our CSS to apply panel-specific styles. contentWrapperPanel.classList.add('sliding-panel'); // Function to open the panel function openPanel() { body.classList.add('content-panel-active'); // Activates styles for overlay and panel visibility toggleBtn.setAttribute('aria-expanded', 'true'); // For accessibility } // Function to close the panel function closePanel() { body.classList.remove('content-panel-active'); // Deactivates the panel toggleBtn.setAttribute('aria-expanded', 'false'); // For accessibility } // Event listener for the toggle button toggleBtn.addEventListener('click', function () { if (body.classList.contains('content-panel-active')) { closePanel(); } else { openPanel(); } }); // Event listener for the page overlay (to close panel when clicking outside of it) pageOverlay.addEventListener('click', function () { closePanel(); }); // Optional: Event listener for the 'Escape' key to close the panel document.addEventListener('keydown', function (event) { if (event.key === 'Escape' && body.classList.contains('content-panel-active')) { closePanel(); } }); } } });