/* === INIT ECOMMERCE FUNCTIONS === */ document.body.onload = createParduxFoot(); document.body.onload = createCookieConsent(); jQuery(document).ready(function () { $(document).on('click', '.pdx-btn-add-cart', function(e){ e.preventDefault(); var variant = $(this).attr('data-variant'); var quantity = $(this).attr('data-quantity'); var selVariantElement = $('#pdx-variant-select'); var qtyElement = $('#pdx-add-cart-qty'); if (!variant && selVariantElement.length > 0) { var variant = $('#pdx-variant-select').val(); } if(!quantity && qtyElement.length > 0) { var quantity = qtyElement.val(); } var shoppingCartUrl = $(this).attr('data-shopping-cart-url'); AddToCartCookie({variant: variant, quantity: quantity, gocart: false, shoppingCartUrl: shoppingCartUrl}); fbAddToCart({ value: $(this).attr('data-price'), content_ids: $(this).attr('data-product'), content_type: 'product' }); gaAddToCart({ id_prod: variant, name_prod: $(this).attr('data-title'), price_prod: $(this).attr('data-price'), quantity_prod: quantity }); // tiktok events if (typeof ttAddToCart === "function") { ttAddToCart({ value: $(this).attr('data-price'), content_ids: $(this).attr('data-product'), content_type: 'product' }); } // end tiktok events }); $(document).on('click', '.pdx-btn-add-wishlist', function(e){ e.preventDefault(); var product = $(this).data('product'); var wishlistUrl = $(this).data('wishlist-url'); AddToWishlistCookie({product: product, wishlistUrl: wishlistUrl}); fbAddToWishlist({ value: $(this).data('price'), content_ids: product, content_type: 'product' }); // tiktok events if (typeof ttAddToWishlist === "function") { ttAddToWishlist({ value: $(this).data('price'), content_ids: product, content_type: 'product' }); } // end tiktok events }); $('#pdx-btn-load-more').on('click', function(e) { e.preventDefault(); var url = $(this).data('url'); var page = $(this).data('page'); var ajaxUrl = url+'&page='+parseInt(page); $(this).attr('ajax-url', ajaxUrl); ajaxHandler(this); }); $('input.disablecopypaste').bind('copy paste', function (e) { e.preventDefault(); }); }); function createParduxFoot() { if (typeof disableFooter == 'undefined') { var f = document.createElement('div'); f.setAttribute('style', 'background-color:'+(typeof colorParduxFooterBg !== 'undefined' ? colorParduxFooterBg : '#000000' )+';padding:4px 10px;text-align:center;width:100%'); f.innerHTML = '

Powered by PARDUX

'; document.body.appendChild(f); } } function setCookieConsent(cname, cvalue, exdays) { const d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); let expires = "expires=" + d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/; SameSite=Strict"; } function getCookieConsent(cname) { let name = cname + "="; let decodedCookie = decodeURIComponent(document.cookie); let ca = decodedCookie.split(';'); for (let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } function createCookieConsent() { if (typeof createCookieConsentOverwrite === 'function') { createCookieConsentOverwrite(); return; } let concent = getCookieConsent("cookie-concent"); if (concent == "") { const newDiv = document.createElement("div"); newDiv.setAttribute("id", "consent-modal") newDiv.style.cssText = 'z-index: 16000161; border-radius: 0.25rem;text-align: center; position: fixed; background-color: rgb(255, 255, 255); border: 1px solid rgb(166, 166, 166); padding: 10px; bottom: 8px; left: 8px; box-shadow: rgba(0, 0, 0, 0.2) 5px 5px 5px; width: 300px;'; const title = document.createElement("h5"); var text = document.createTextNode("Utilizamos cookies"); title.appendChild(text) const textE = document.createElement("p"); textE.style.cssText = 'margin: 0 0 20px 0;font-size: 0.8em;' text = document.createTextNode("Podemos utilizarlas para el análisis de las preferencias de nuestros visitantes y el correcto funcionamiento de nuestro sitio web."); textE.appendChild(text) const accionDiv = document.createElement("div"); accionDiv.style.cssText = 'display: flex;justify-content: space-around;'; const bottomB = document.createElement("button"); text = document.createTextNode("Lo necesario"); bottomB.style.cssText = 'cursor: pointer; border-radius: 5px; box-shadow: 0 -3px rgba(0,0,0,.1) inset; transition: opacity .45s cubic-bezier(.25,1,.33,1); color: #fff; font-weight: 600; font-size: 12px; padding: 10px 12px; position: relative; top: 0; margin-bottom: 10px; opacity: 1; line-height: 20px; background-color: #555;' bottomB.appendChild(text) bottomB.onclick = function () { setCookieConsent("cookie-concent", true, 365); document.getElementById("consent-modal").remove(); return false; }; accionDiv.appendChild(bottomB); const bottomA = document.createElement("button"); bottomA.style.cssText = 'cursor: pointer; border-radius: 5px; box-shadow: 0 -3px rgba(0,0,0,.1) inset; transition: opacity .45s cubic-bezier(.25,1,.33,1); color: #fff; font-weight: 600; font-size: 12px; padding: 10px 12px; position: relative; top: 0; margin-bottom: 10px; opacity: 1; line-height: 20px; background-color: #000;' text = document.createTextNode("Aceptar todo"); bottomA.appendChild(text) bottomA.onclick = function () { setCookieConsent("cookie-concent", true, 365); document.getElementById("consent-modal").remove(); return false; }; accionDiv.appendChild(bottomA); newDiv.appendChild(title); newDiv.appendChild(textE); newDiv.appendChild(accionDiv); document.body.appendChild(newDiv); } } function getFeatureSearch(feature1Element, feature2Element, feature3Element) { var featureSearch = (feature1Element.length > 0) ? feature1Element.val() : ''; featureSearch = (feature2Element.length > 0) ? featureSearch + '__' + feature2Element.val() : featureSearch; featureSearch = (feature3Element.length > 0) ? featureSearch + '__' + feature3Element.val() : featureSearch; return featureSearch; } function getVariantDataSearch() { var featureSearch = getFeatureSearch($('#pdx-feature1Select'), $('#pdx-feature2Select'), $('#pdx-feature3Select')); setVariantData(variantsData[featureSearch]); buildAdditionalInformationFields({data:variantsData[featureSearch]['additionalInformationFields'], variantId:variantsData[featureSearch]['variantId']}); $('#pdx-feature1Select').on('change', function(e){ e.preventDefault(); var featureSearch = getFeatureSearch($(this), $('#pdx-feature2Select'), $('#pdx-feature3Select')); setVariantData(variantsData[featureSearch]); buildAdditionalInformationFields({data:variantsData[featureSearch]['additionalInformationFields'], variantId:variantsData[featureSearch]['variantId']}); }); $('#pdx-feature2Select').on('change', function(e){ e.preventDefault(); var featureSearch = getFeatureSearch($('#pdx-feature1Select'), $(this), $('#pdx-feature3Select')); setVariantData(variantsData[featureSearch]); buildAdditionalInformationFields({data:variantsData[featureSearch]['additionalInformationFields'], variantId:variantsData[featureSearch]['variantId']}); }); $('#pdx-feature3Select').on('change', function(e){ e.preventDefault(); var featureSearch = getFeatureSearch($('#pdx-feature1Select'), $('#pdx-feature2Select'), $(this)); setVariantData(variantsData[featureSearch]); buildAdditionalInformationFields({data:variantsData[featureSearch]['additionalInformationFields'], variantId:variantsData[featureSearch]['variantId']}); }); } function buildAdditionalInformationFields(params) { if (typeof buildAdditionalInformationFieldsOverwrite === 'function') { buildAdditionalInformationFieldsOverwrite(params); return; } let variantId = params.variantId; let data = params.data; let elements = ''; if (data && data.length > 0) { $('#pdx-addition-information-div').show(); for (let i = 0; i < data.length; i++) { const field = data[i]; if (field.type != 'hidden') { elements += ``; } if (field.type == 'select') { const options = field.optionsField.split(','); const selectOptions = options.map(option => ``).join(''); elements += ` `; } else { elements += ``; } } } else { $('#pdx-addition-information-div').hide(); } $('#pdx-addition-information-fields').html(elements); return; } function cookieAdditionalInformation() { $('#pdx-variant-add-cart').click(()=>{ let data = getCookie('additional_information'); data = data ? JSON.parse(data) : {}; let inputs = $('.pdx-input-additional-information'); if (inputs.length > 0) { for (let i = 0; i < inputs.length; i++) { const element = $(inputs[i]); const obj = {}; const id = encodeURIComponent(element.attr('id')); const value = encodeURIComponent(element.val()); const type = encodeURIComponent(element.data('type')); if (!value && element.attr('required')) { // Evita que se realice el agregar al carrito event.stopPropagation(); showErrorMessage({ title: 'Información', message: 'Para añadir el producto al carrito, es necesario completar el campo '+element.attr('id')+'.', identifier: 'Error', }); return; } obj[id] = value; obj['type'] = type; if (data[element.data('variantid')]) { if (i == 0) { data[element.data('variantid')] = []; } data[element.data('variantid')].push(obj); } else { data[element.data('variantid')] = [obj]; } } setCookie('additional_information', JSON.stringify(data), 4320); } }); } function setVariantData(variantData) { setReservations(variantData); if (typeof setVariantDataOverwrite === 'function') { setVariantDataOverwrite(variantData); return; } var variantPrice = '$' + parsePrice(variantData.price) + ''; if (variantData.compareAtPrice > variantData.price) { var discount = 100 - ((variantData.price * 100) / variantData.compareAtPrice); variantPrice = variantPrice + '$' + parsePrice(variantData.compareAtPrice) + '
' + Math.ceil(discount) + '% Desc.
'; } $('#pdx-variant-price').html(variantPrice); var variantStock = '
  • SIN STOCK
  • '; if (variantData.stock > 0) { variantStock = '
  • ' + variantData.stock + ' unidad(es) EN STOCK
  • '; } $('#pdx-variant-stock').html(variantStock); $('#pdx-variant-add-cart').attr('data-variant', variantData.variantId); $('#pdx-variant-add-cart').attr('data-price', variantData.price); var variantSku = 'SKU: '+ variantData.sku + ''; $('#pdx-variant-sku').html(variantSku); var variantWeight = 'Peso: '+ variantData.weight + ' ' + variantData.weightUnitPrefix + ''; $('#pdx-variant-weight').html(variantWeight); if (document.getElementById('pdx-variant-image-' + variantData.variantId)) { $('#pdx-variant-image-' + variantData.variantId).click(); } else if (document.getElementById('pdx-main-image')) { $('#pdx-main-image').click(); } } function getCookie(cname) { var name = cookie_prefix + cname + "="; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ''; } function setCookie(cname, cvalue, mins) { var expires; var hostname = window.location.hostname; var secure = env != 'dev'; if (mins) { var date = new Date(); date.setTime(date.getTime() + (mins * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ''; } if (secure) { document.cookie = cookie_prefix+cname+"="+cvalue+expires+";path=/;domain="+hostname+";secure=true;sameSite=strict"; } else { document.cookie = cookie_prefix+cname+"="+cvalue+expires+";path=/;domain="+hostname+";sameSite=strict"; } } function deleteCookie(cname) { var hostname = window.location.hostname; var secure = env != 'dev'; if (secure) { document.cookie = cookie_prefix+cname+"=123; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/;domain="+hostname+";secure=true;sameSite=strict"; } else { document.cookie = cookie_prefix+cname+"=123; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/;sameSite=strict"; } } function AddToWishlistCookie(params) { var wishlist = getCookie('wishlist'); var exist = false; if (wishlist !== '') { $.each(wishlist.split('&'), function(key, val) { if (val == params.product) { exist = true; } }); var wishlist = wishlist + '&' + params.product } else { var wishlist = params.product } if (!exist) { //Cookie de 90 dias setCookie('wishlist', wishlist, 129600); if (params.nomessage) { } else { notifyWishlist({ wishlistUrl: params.wishlistUrl }); } } else { notifyWishlist({ wishlistUrl: params.wishlistUrl }); } wishlistCount(); } function AddToCartCookie(params) { var cart = getCookie('shopping_cart'); var exist = false; if (cart !== '') { $.each(cart.split('&'), function(key, val) { var data = val.split(':'); if (data[0] == params.variant) { exist = true; } }); var cart = cart + '&' + params.variant + ':' + Math.ceil(params.quantity); } else { var cart = params.variant + ':' + Math.ceil(params.quantity); } if (!exist) { //Cookie de 30 dias setCookie('shopping_cart', cart, 4320); if (params.nomessage) { } else if(params.gocart) { redireccion({url: params.shoppingCartUrl}); } else { notifyShoppingCart({ shoppingCartUrl: params.shoppingCartUrl }); } } else { if (params.nomessage) { } else if(params.gocart) { redireccion({url: params.shoppingCartUrl}); } else { notifyShoppingCart({ shoppingCartUrl: params.shoppingCartUrl }); } } } function shoppingCartCount() { if (typeof shoppingCartCountOverwrite === 'function') { shoppingCartCountOverwrite(); } else { var shopping_cart = getCookie('shopping_cart'); var count = (shopping_cart != '') ? shopping_cart.split('&').length : 0; $('#pdx-shopping-cart-count').html(count); } } function updateShoppingCartTable() { if (typeof updateShoppingCartTableOverwrite === 'function') { updateShoppingCartTableOverwrite(); } else { deleteCookie('shopping_cart'); var cells, variant, price, qantity, subtotal, a, i; var total = 0; for (var a = document.querySelectorAll('table.pdx-shopping-cart-table tbody tr'), i = 0; a[i]; ++i) { cells = a[i].querySelectorAll('[calculate]'); variant = parseFloatHTML(cells[0]); price = parseFloatHTML(cells[1]); quantity = parseFloat($(cells[2]).val()); subtotal = price * quantity; cells[3].innerHTML = parsePrice(subtotal); total += subtotal; //Renovamos las cookies AddToCartCookie({ variant: variant, quantity: quantity, nomessage: true }); } document.querySelector('#subtotal').innerHTML = parsePrice(total); document.querySelector('#tax').innerHTML = parsePrice(0.00); document.querySelector('#total').innerHTML = parsePrice(total); } } function updateWishlistCookie() { deleteCookie('wishlist'); for (var a = document.querySelectorAll('table.pdx-wishlist-table tbody tr'), i = 0; a[i]; ++i) { cells = a[i].querySelectorAll('[calculate]'); var product = parseFloatHTML(cells[0]); AddToWishlistCookie({ product: product, nomessage: true }); } } function deleteTableRow(params) { $(params.element).closest('tr').fadeOut('slow', function() { $(params.element).closest('tr').remove(); if (params.updateShoppingCartTable) { updateShoppingCartTable(); shoppingCartCount(); } if (params.updateWishlistCookie) { updateWishlistCookie(); wishlistCount(); } }); } function wishlistCount() { if (typeof wishlistCountOverwrite === 'function') { shoppingCartCountOverwrite(); } else { var wl = getCookie('wishlist') var count = (wl != '') ? wl.split('&').length : 0; $('#pdx-wishlist-count').html(count); } } /* === END ECOMMERCE FUNCTIONS === */ /* === INIT TRANSACTIONS FUNCTIONS === */ function endSubscribe(params) { fbLead(params); $('#subscribe_email').val(''); if (typeof endSubscribeOverwrite === 'function') { endSubscribeOverwrite(params); } else { alert(params.message); redireccion(params); } } function endRegistration(params) { fbCompleteRegistration(); if (typeof endRegistrationOverwrite === 'function') { endRegistrationOverwrite(params); } else { redireccion(params); } } function endSendMessage(params) { $('#contact_form_fullName').val(''); $('#contact_form_email').val(''); $('#contact_form_phone').val(''); $('#contact_form_subject').val(''); $('#contact_form_message').val(''); if (typeof endSendMessageOverwrite === 'function') { endSendMessageOverwrite(params); } else { alert(params.message); redireccion(params); } } function endSendProductReview(params) { $('#product_review_form_fullName').val(''); $('#product_review_form_email').val(''); $('#product_review_form_review').val(''); $('#product_review_form_score').val(''); if (typeof endSendProductReviewOverwrite === 'function') { endSendProductReviewOverwrite(params); } else { alert(params.message); } } function endResetPassword(params) { $('#reset_password_form_email').val(''); if (typeof endResetPasswordOverwrite === 'function') { endResetPasswordOverwrite(params); } else { alert(params.message); redireccion(params); } } /* === END TRANSACTIONS FUNCTIONS === */ /* === INIT RENDER AJAX FUNCTIONS === */ function renderProductsAjax(params) { if (typeof renderProductsAjaxOverwrite === 'function') { renderProductsAjaxOverwrite(params); } else { if (params.page <= 1) { $('#pdx-products-contaniner-list').html(params.body); if (window.history.replaceState) { window.history.replaceState('', '', params.url); } } else { $('#pdx-products-contaniner-list').append(params.body); } if (params.count < params.limit) { $('#pdx-btn-load-more').hide(); } else { $('#pdx-btn-load-more').data('page', params.page + 1); $('#pdx-btn-load-more').show(); } } } function renderCollectionsAjax(params) { if (typeof renderCollectionsAjaxOverwrite === 'function') { renderCollectionsAjaxOverwrite(params); } else { if (params.page <= 1) { $('#pdx-collections-contaniner-list').html(params.body); if (window.history.replaceState) { window.history.replaceState('', '', params.url); } } else { $('#pdx-collections-contaniner-list').append(params.body); } if (params.count < params.limit) { $('#pdx-btn-load-more').hide(); } else { $('#pdx-btn-load-more').data('page', params.page + 1); $('#pdx-btn-load-more').show(); } } } function renderCollectionAjax(params) { if (typeof renderCollectionAjaxOverwrite === 'function') { renderCollectionAjaxOverwrite(params); } else { if (params.page <= 1) { $('#pdx-collection-products-contaniner-list').html(params.body); if (window.history.replaceState) { window.history.replaceState('', '', params.url); } } else { $('#pdx-collection-products-contaniner-list').append(params.body); } if (params.pagination.currentPage >= params.pagination.totPages) { $('#pdx-btn-load-more').hide(); } else { $('#pdx-btn-load-more').data('page', params.page + 1); $('#pdx-btn-load-more').show(); } } } function renderBlogAjax(params) { if (typeof renderBlogAjaxOverwrite === 'function') { renderBlogAjaxOverwrite(params); } else { if (params.page <= 1) { $('#pdx-blog-posts-contaniner-list').html(params.body); if (window.history.replaceState) { window.history.replaceState('', '', params.url); } } else { $('#pdx-blog-posts-contaniner-list').append(params.body); } if (params.count < params.limit) { $('#pdx-btn-load-more').hide(); } else { $('#pdx-btn-load-more').data('page', params.page + 1); $('#pdx-btn-load-more').show(); } } } function renderLogin(params) { if (typeof renderLoginOverwrite === 'function') { renderLoginOverwrite(params); } else { $('#pdx-login-container').html(params.body); if (!isMobile()) { $('#login_form_password').focus(); } } //Iniciamos onlyLetters onlyLetters(); } function renderRegister(params) { if (typeof renderRegisterOverwrite === 'function') { renderRegisterOverwrite(params); } else { $('#pdx-login-container').html(params.body); if (!isMobile()) { $('#registration_form_firstName').focus(); } } //Iniciamos onlyLetters onlyLetters(); $('input.disablecopypaste').bind('copy paste', function (e) { e.preventDefault(); }); } function isMobile() { try{ document.createEvent("TouchEvent"); return true; } catch(e){ return false; } } /* === END RENDER AJAX FUNCTIONS === */ /* === INIT NOTIFICATIONS FUNCTIONS === */ function showErrorMessage(params) { if (typeof showErrorMessageOverwrite === 'function') { showErrorMessageOverwrite(params); } else { alert(params.message); } } function notifyShoppingCart(params) { if (typeof notifyShoppingCartOverwrite === 'function') { notifyShoppingCartOverwrite(params); } else { alert('Producto agregado al carrito'); } } function notifyWishlist(params) { if (typeof notifyWishlistOverwrite === 'function') { notifyWishlistOverwrite(params); } else { alert('Producto agregado a favoritos'); } } /* === END NOTIFICATIONS FUNCTIONS === */ /* === INIT GENERAL FUNCTIONS === */ function redireccion(params) { window.location.href = params.url; } function parseFloatHTML(element) { return parseFloat(element.innerHTML.replace(/[^\d\.\-]+/g, '')) || 0; } function parsePrice(number) { return (Math.round(number*100)/100).toFixed(2).replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1,'); } function updateNumber(e) { var activeElement = document.activeElement; if (activeElement.hasAttribute('calculate')) { if (e.keyCode == 46 || e.keyCode == 8 || e.keyCode == 13 || e.keyCode == 37 || e.keyCode == 39 || e.keyCode == 9 || e.keyCode == 189 || e.keyCode == 190 || e.keyCode == 110) { } else { if (e.keyCode < 95) { if (e.keyCode < 48 || e.keyCode > 57) { e.preventDefault(); } } else { if (e.keyCode < 96 || e.keyCode > 105) { e.preventDefault(); } } } var value = parseFloat(activeElement.value); var wasPrice = activeElement.value == parsePrice(parseFloatHTML(activeElement)); if (!isNaN(value) && (e.keyCode == 38 || e.keyCode == 40 || e.wheelDeltaY)) { e.preventDefault(); value += e.keyCode == 38 ? 1 : e.keyCode == 40 ? -1 : Math.round(e.wheelDelta * 0.025); value = Math.max(value, 0); activeElement.value = wasPrice ? parsePrice(value) : value; } } } function onlyLetters() { $('.prdx-only-letters').keydown(function(e) { var letters = /^[ a-zA-ZÀ-ÿ\u00C0-\u00FF]*$/; if(e.key.match(letters)) { } else { e.preventDefault(); } }); } function fade(element) { $(element).hide(); $(element).fadeIn('slow'); } function submitForm(params) { if (params.idForm) { $('#'+params.idForm).submit(); } else if (params.nameForm) { $('[name='+params.nameForm+']').submit(); } else { $('#'+params.idSubmitBtn).click(); } } function removeURLParameter(url, parameter) { var urlparts = url.split('?'); if (urlparts.length >= 2) { var prefix = encodeURIComponent(parameter)+'='; var pars = urlparts[1].split(/[&;]/g); for (var i= pars.length; i-- > 0;) { if (pars[i].lastIndexOf(prefix, 0) !== -1) { pars.splice(i, 1); } } url = urlparts[0]+'?'+pars.join('&'); return url; } else { return url; } } function removeQueryParameter(query, parameter) { var prefix = encodeURIComponent(parameter)+'='; var pars = query.split(/[&;]/g); for (var i = pars.length; i-- > 0;) { if (pars[i].lastIndexOf(prefix, 0) !== -1) { pars.splice(i, 1); } } var url = pars.join('&'); return url; } /* === END GENERAL FUNCTIONS === */ /* === START RESERVATION FUNCTIONS === */ function messagesReservations(messageKey) { if (typeof messagesReservationsOverwrite === 'function') { messagesReservationsOverwrite(variantData); return; } let messages = { date_invalid: 'Debe ingresar una fecha válida', date_not_available: 'Lamentablemente, no hay disponibilidad en la fecha seleccionada. Por favor, elige otra fecha para tu reserva.', }; return messages[messageKey]; } async function getReservationsDaysDisabled(params) { if (typeof getReservationsDaysDisabledOverwrite === 'function') { getReservationsDaysDisabledOverwrite(params); return; } // Trae la informacion de los bloqueos de la variante y dias que ya estan reservados let blocks = []; let route = Routing.generate('tor_reservation_check_availability_request', { variantId: params.variantId, type: 'days', }); await $.get(route, function(data) { if (data.error) { showErrorMessage(data.params); return; } else { blocks = data.params.dates; } }); return { days: blocks, }; } async function getReservationsHoursDisabled(params) { if (typeof getReservationsHoursDisabledOverwrite === 'function') { getReservationsHoursDisabledOverwrite(params); return; } // Trae la informacion de los bloqueos de la variante y dias que ya estan reservados let blocks = []; let route = Routing.generate('tor_reservation_check_availability_request', { variantId: params.variantId, date: params.date, quantity: params.quantity, type: 'hours', }); await $.get(route, function(data) { if (data.error) { showErrorMessage(data.params); return; } else { blocks = data.params.hours; } }); return { hours: blocks, }; } async function checkReservationsAvailabilityDay(params) { if (typeof checkReservationsAvailabilityDayOverwrite === 'function') { checkReservationsAvailabilityDayOverwrite(params); return; } // Consulta la disponibilidad de ese dia let result = false; let route = Routing.generate('tor_reservation_check_availability_request', { variantId: params.variantId, date: params.date, quantity: params.quantity, type: 'specific-day', }); await $.get(route, function(data) { if (data.error) { showErrorMessage(data.params); return; } else { result = data.params.availability; } }); return result; } function buildHourSelect(params) { if (typeof buildHourSelectOverwrite === 'function') { buildHourSelectOverwrite(params); return; } return `
  • `; } async function setReservations(variantData) { if (!variantData.isReservable) { return; } if (!variantData.dataReservation.config) { return; } if (typeof setReservationsOverwrite === 'function') { setReservationsOverwrite(variantData); return; } let config = variantData.dataReservation.config; let type = variantData.dataReservation.type; let schedule = config.schedule; let messageError = messagesReservations('date_invalid'); let messageErrorDateNotAvailable = messagesReservations('date_not_available'); // let daysDisabled = await getReservationsDaysDisabled({variantId: variantData.variantId }); daysDisabled = daysDisabled ? daysDisabled.days : []; // functions function pad(number) { // Agrega un cero delante de los números de una sola cifra return number < 10 ? `0${number}` : number; } function loadLogicScript() { $('.btn-hour').off('click').click(function(){ $('.btn-hour').removeClass('btn-primary').addClass('btn-outline-primary'); $(this).addClass('btn-primary').removeClass('btn-outline-primary'); $('.col-next').hide(); $(this).parents('li').find('.col-next').fadeIn(); $('.pdx-btn-add-cart').attr('disabled', true); }); $('.btn-next').off('click').click(() => { $('.pdx-btn-add-cart').attr('disabled', false); let calendarDate = $('#calendar').val(); let hour = $('.btn-hour.btn-primary').text(); let startDate = new Date(`${calendarDate} ${hour}`); let endDate = new Date(`${calendarDate} ${hour}`); let timeInMinutes = 0; switch (config.unit) { case "minutes": timeInMinutes = parseInt(config.quantity); break; case "hours": timeInMinutes = parseInt(config.quantity) * 60; break; case "days": timeInMinutes = parseInt(config.quantity) * 24 * 60; break; default: timeInMinutes = 1; } endDate.setMinutes(endDate.getMinutes() + timeInMinutes); let startDateFormatted = `${startDate.getFullYear()}-${pad(startDate.getMonth() + 1)}-${pad(startDate.getDate())} ${pad(startDate.getHours())}:${pad(startDate.getMinutes())}`; let endDateFormatted = `${endDate.getFullYear()}-${pad(endDate.getMonth() + 1)}-${pad(endDate.getDate())} ${pad(endDate.getHours())}:${pad(endDate.getMinutes())}`; $('#startDateReservation').val(startDateFormatted); $('#endDateReservation').val(endDateFormatted); }); } // $('.pdx-btn-add-cart').attr('disabled', true); // let fpConfig = { inline: true, minDate: 'today', locale: 'es', onChange: async function(selectedDates, dateStr, instance) { $('#section-hours').hide(); // Si tiene configurado dias if (config.unit == 'days') { // COnsultar disponibilidad de ese día let state = config.limitOptionsReservations == 'unlimited' ? true : await checkReservationsAvailabilityDay({ variantId: variantData.variantId, date: dateStr, quantity: $('#pdx-add-cart-qty').val(), }); if (state) { $('.pdx-btn-add-cart').attr('disabled', false); $('#startDateReservation').val(dateStr + ' 00:00'); let end = modifyDate(new Date(dateStr), `+${config.quantity} ${config.unit}`); end = formatDate(end, 'Y-m-d'); $('#endDateReservation').val(end + ' 23:59'); } else { $('.pdx-btn-add-cart').attr('disabled', true); $('#section-hours').hide(); $('#calendar').val(''); flatpickr($('#calendar'), fpConfig); showErrorMessage({message: messageErrorDateNotAvailable}); } return; } // const now = new Date(); // Obtener la fecha actual $('.pdx-btn-add-cart').attr('disabled', true); const weekDay = selectedDates[0].toLocaleDateString('en-US', { weekday: 'long' }).toLowerCase(); const scheduleDay = schedule[weekDay]; const timeStart = new Date(`2000-01-01T${scheduleDay.start}:00`); // 8:00 const timeEnd = new Date(`2000-01-01T${scheduleDay.end}:00`); //17:00 let hoursDisabled = config.limitOptionsReservations == 'unlimited' ? [] : await getReservationsHoursDisabled({variantId: variantData.variantId, date: dateStr, quantity: $('#pdx-add-cart-qty').val()}); hoursDisabled = hoursDisabled ? hoursDisabled.hours : []; let timeInMinutes = 0; switch (config.unit) { case "minutes": timeInMinutes = parseInt(config.quantity); break; case "hours": timeInMinutes = parseInt(config.quantity) * 60; break; } $('#list-hours').html(''); for (let hour = timeStart; hour <= timeEnd; hour.setMinutes(hour.getMinutes() + timeInMinutes)) { const currentHour = hour.toLocaleTimeString('en-US', { hourCycle: "h23", hour: "numeric", minute: "numeric" }); if (now <= new Date(`${dateStr}T${currentHour}:00`)) { let disabledHour = false; if (hoursDisabled && hoursDisabled.indexOf(currentHour) !== -1) { disabledHour = true; } let element = buildHourSelect({hour: currentHour, isDisabled: disabledHour}); $('#list-hours').append(element); } } loadLogicScript(); $('#section-hours').fadeIn(); }, disable: [function(date) { // Verificamos la configuración de la semana para desactivar los días que estén habilitados como false if (!schedule) { return false; } let dayOnSchedule = schedule[date.toLocaleString('en-US', {weekday: 'long'}).toLowerCase()]; const dayConfig = dayOnSchedule; return !dayConfig.enabled; }] }; // Deshabilitar dias ocuapdos o bloqueados daysDisabled.forEach(element => { fpConfig.disable.push(element); }); // Inhabilitar hoy let now = new Date(); let todayName = now.toLocaleString('en-US', {weekday: 'long'}).toLowerCase(); // monday let timeNow = schedule[todayName]['end']; // 17:00 if (timeNow) { const [hours, minutes] = timeNow.split(':'); const timeToCheck = new Date(); // Crear una nueva instancia de Date timeToCheck.setHours(hours); timeToCheck.setMinutes(minutes); timeToCheck.setSeconds(0); if (now > timeToCheck) { fpConfig.disable.push(formatDate(now,'Y-m-d')); } } // flatpickr($('#calendar'), fpConfig); $('.plus, .minus').click(function() { // Reiniciar $('.pdx-btn-add-cart').attr('disabled', true); $('#section-hours').hide(); $('#calendar').val(''); flatpickr($('#calendar'), fpConfig); }); $('#pdx-feature1Select').click(function() { // Reiniciar $('.pdx-btn-add-cart').attr('disabled', true); $('#section-hours').hide(); $('#calendar').val(''); flatpickr($('#calendar'), fpConfig); }); // Agregar cookie $('#pdx-variant-add-cart').click(()=>{ var data = getCookie('reservation_information'); data = data ? JSON.parse(data) : {}; var inputs = $('.input-reservable'); var obj = {}; var id = variantData.variantId; var type = variantData.dataReservation.type; obj.type = type; obj.dates = { startDate:$('#startDateReservation').val(), endDate:$('#endDateReservation').val(), }; data[id] = obj; setCookie('reservation_information', JSON.stringify(data), 4320); }); } function modifyDate(date, timeString) { var sign = timeString.charAt(0); // Obtener el signo (+ o -) var parts = timeString.substr(1).split(' '); // Eliminar el signo y dividir en partes var amount = parseInt(parts[0]); var unit = parts[1]; if (sign === '-') { amount = -amount; // Invertir el valor si el signo es negativo } switch (unit) { case 'years': date.setFullYear(date.getFullYear() + amount); break; case 'months': date.setMonth(date.getMonth() + amount); break; case 'weeks': date.setDate(date.getDate() + amount * 7); break; case 'days': date.setDate(date.getDate() + amount); break; case 'hours': date.setHours(date.getHours() + amount); break; case 'minutes': date.setMinutes(date.getMinutes() + amount); break; case 'seconds': date.setSeconds(date.getSeconds() + amount); break; default: // Unidad desconocida break; } return date; } function formatDate(date, format) { var formatTokens = { 'Y': date.getFullYear(), 'm': ('0' + (date.getMonth() + 1)).slice(-2), 'd': ('0' + date.getDate()).slice(-2), 'H': ('0' + date.getHours()).slice(-2), 'i': ('0' + date.getMinutes()).slice(-2), 's': ('0' + date.getSeconds()).slice(-2) }; var formattedDate = format.replace(/(Y|m|d|H|i|s)/g, function(match) { return formatTokens[match]; }); return formattedDate; } /* === START RESERVATION FUNCTIONS === */ /* === START OTP FUNCTIONS === */ function showModalOTPVerify(params) { if (typeof showModalOTPVerifyOverwrite === 'function') { showModalOTPVerifyOverwrite(params); return; } showModal(params); } function wantEnterWithPassword(params) { if (typeof wantEnterWithPasswordOverwrite === 'function') { wantEnterWithPasswordOverwrite(params); return; } $('#btn_enter_with_password').click(function() { closeModal({ closeAllModals: true }); renderLogin(params); }); } function renderRegisterAfterOTP(params) { if (typeof renderRegisterAfterOTPOverwrite === 'function') { renderRegisterAfterOTPOverwrite(params); return; } closeModal({ closeAllModals: true }); renderRegister(params); } /* === END OTP FUNCTIONS === */ // TIKTOK FUNCTIONS function ttAddToCart(params) { let data = { event_name: 'AddToCart', params: params }; ttPostEvent(data); } function ttAddToWishlist(params) { let data = { event_name: 'AddToWishlist', params: params, }; ttPostEvent(data); } function ttPostEvent(params) { var options = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(params) }; let route = Routing.generate('ads_tiktok_event'); fetch(route, options).then(function(response) {}).catch(function(error) {}); } function ttPostCustomEvent(params) { var options = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(params) }; let route = Routing.generate('ads_tiktok_custom_event'); fetch(route, options).then(function(response) {}).catch(function(error) {}); } // END TIKTOK FUNCTIONS