$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
error: function (jqXHR, exception) {
if (jqXHR.status === 401) {
alert('Debe iniciar sesión.');
} else if (jqXHR.status === 419) {
alert('Su sesión ha expirado.');
} else {
console.error('Uncaught Error #1.\n' + jqXHR.responseText);
}
}
});
// Asegurar que cartPopover exista antes de cualquier uso
if (typeof window.cartPopover !== 'function') {
window.cartPopover = function(){};
}
function redirect(url) {
document.location.href = url;
return false;
}
function arraysEqual(_arr1, _arr2) {
if (!Array.isArray(_arr1) || !Array.isArray(_arr2) || _arr1.length !== _arr2.length)
return false;
var arr1 = _arr1.concat().sort();
var arr2 = _arr2.concat().sort();
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i])
return false;
}
return true;
}
function laravelErrorMessages(data) {
// var errors = data.responseJSON;
// console.log(errors);
var response = JSON.parse(data.responseText);
var printError = '';
// var errorString = '
';
$.each(response.errors, function (key, value) {
// errorString += '- ' + value + '
';
$.each(value, function (key1, value1) {
printError += value1.capitalize() + "\n";
});
});
// errorString += '
';
// console.log(errorString);
alert(printError);
}
function laravelErrorMessagesTwo(response) {
// var errors = data.responseJSON;
// console.log(errors);
// var response = JSON.parse(data);
var printError = '';
// var errorString = '';
$.each(response.errors, function (key, value) {
// errorString += '- ' + value + '
';
$.each(value, function (key1, value1) {
printError += value1.capitalize() + "\n";
});
});
// errorString += '
';
// console.log(errorString);
alert(printError);
}
String.prototype.capitalize = function () {
return this.charAt(0).toUpperCase() + this.slice(1);
}
var product_notify = {
'submit': function (e, product_id) {
e.preventDefault();
$('#buttonNotifyProduct').prop('disabled', true).html(' Enviando...');
$.ajax({
url: '/producto-notify',
type: 'POST',
data: {
email: $('#notify_email').val(),
product_id: product_id,
product_variant_id: $('#product_variant_id').val()
},
success: function (data) {
$('#buttonNotifyProduct').prop('disabled', false).html(' Enviar');
if (data.success) {
$('#notify_email').val('');
$('#notifyModal').modal('hide');
toastr.success('', data.message, {
progressBar: true,
timeOut: 5000,
});
$('.close-modal').click();
if ($('.modal-backdrop').is(':visible')) {
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
};
} else {
toastr.error('', data.message, {
progressBar: true,
timeOut: 5000,
});
}
},
error: function (data) {
laravelErrorMessages(data);
$('#buttonNotifyProduct').prop('disabled', false).html(' Enviar');
}
// error: function(xhr, ajaxOptions, thrownError) {
// alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
// }
});
},
}
var cart = {
'add': function (url, quantity, currency_symbol, redirect, options) {
$('#buttonCart').prop('disabled', true).html('');
$('#buyNowCart').prop('disabled', true).html('');
$.ajax({
url: url,
type: 'POST',
data: {
quantity: quantity,
options: options
},
success: function (data) {
if (data.success) {
if (redirect) {
document.location.href = '/cart';
} else {
$('#buttonCart').prop('disabled', false).html('Agregar Al Carrito');
$('#buyNowCart').prop('disabled', false).html('Comprar Ahora');
// Trae los items del carrito
if (!window.isTemplateToro) {
cart_items('/carrito-items');
}
toastr.success('', data.message, {
progressBar: true,
timeOut: 5000,
});
}
} else {
$('#buttonCart').prop('disabled', false).html('Agregar Al Carrito');
$('#buyNowCart').prop('disabled', false).html('Comprar Ahora');
toastr.error('', data.message, {
progressBar: true,
timeOut: 5000,
});
if (data.redirect_url) {
document.location.href = data.redirect_url;
}
}
},
error: function (data) {
laravelErrorMessages(data);
$('#buttonCart').prop('disabled', false).html('Agregar Al Carrito');
$('#buyNowCart').prop('disabled', false).html('Comprar Ahora');
}
});
},
'submit': function (e) {
let cartForm;
e.preventDefault();
$('#buttonConfirmCart').prop('disabled', true).html('');
let pay_method_id = $('input:radio[name="payment_method_id"]:checked').val(); //captura el metodo de pago
cartForm = $('#cartForm').serialize();
$.ajax({
url: '/cart/confirm',
type: 'POST',
data: cartForm,
success: function (data) {
if (data.success) {
// redireccion post - cobrosya UY
if (data.redirect_post) {
openPostPage(data.url, data.data);
}
else
{
document.location.href = data.redirect_url;
}
} else {
$('#buttonConfirmCart').prop('disabled', false).html('Confirmar Compra ');
toastr.error('', data.msg, {
progressBar: true,
timeOut: 5000,
});
}
},
error: function (jqXHR, exception) {
if (jqXHR.status === 401) {
document.location.href = '/completa-tus-datos?goto=1&' + cartForm;
} else if (jqXHR.status === 419) {
alert('Ha expirado su sesión, favor recargar la página.');
} else if (jqXHR.status === 429) {
alert('Demasiadas solicitudes. Por favor, espere un momento.');
} else {
alert('Error Inesperado:.\n' + jqXHR.responseText);
$('#buttonConfirmCart').prop('disabled', false).html('Confirmar Compra ');
}
}
});
},
'data': function (e) {
let data_for_purchase, aditional_data, query_with_form;
let data_of_cart = window.location.search;
e.preventDefault();
$('#buttonConfirmCart').prop('disabled', true).html('');
data_for_purchase = $('.data_for_purchase').serialize();
query_with_form = data_for_purchase + '&' + data_of_cart;
$.ajax({
url: '/completa-tus-datos',
type: 'POST',
data: query_with_form,
success: function (data) {
if (data.success) {
aditional_data = data.aditional_data;
$.ajax({
url: data.redirect_url,
type: 'POST',
data: aditional_data,
success: function (data2) {
if (data2.success) {
document.location.href = data2.redirect_url;
} else {
$('#buttonConfirmCart').prop('disabled', false).html('Confirmar Compra ');
toastr.error('', data2.msg, {
progressBar: true,
timeOut: 5000,
});
setTimeout(function () {
document.location.href = data2.redirect_url;
}, 3000);
}
}
});
}
else
{
toastr.error('', data.msg, {
progressBar: true,
timeOut: 5000,
});
setTimeout(function () {
document.location.href = data.redirect_url;
}, 3000);
}
},
error: function (data) {
laravelErrorMessages(data);
$('#buttonConfirmCart').prop('disabled', false).html('Confirmar Compra ');
}
});
},
'shared_purchase_submit': function (e) {
let cartForm;
let order_token = $('#order_token').val();
e.preventDefault();
$('#buttonConfirmCart').prop('disabled', true).html('');
// let pay_method_id = $('input:radio[name="payment_method_id"]:checked').val(); //captura el metodo de pago
// if (pay_method_id == 10) //si es billetera personal solicita el numero de cel
// {
// let lineUser = requireLineUser();//captura el numero ingresado
// if (lineUser != false) {
// cartForm = $('#cartForm').serialize() + "&lineUser=" + lineUser;//agrega la linea del usuario al parametro
// } else {
// $('#buttonConfirmCart').prop('disabled', false).html('Confirmar Compra ');
// return false;
// }
// } else {
cartForm = $('#cartForm').serialize();
// }
$.ajax({
url: '/compra-compartida/'+order_token+'/pago',
type: 'POST',
data: cartForm,
success: function (data) {
if (data.success) {
// // redireccion post - cobrosya UY
// if (data.redirect_post) {
// openPostPage(data.url, data.data);
// }
// else
// {
document.location.href = data.redirect_url;
// }
} else {
$('#buttonConfirmCart').prop('disabled', false).html('Confirmar Compra ');
toastr.error('', data.msg, {
progressBar: true,
timeOut: 5000,
});
}
},
error: function (jqXHR, exception) {
// if (jqXHR.status === 401) {
// document.location.href = '/completa-tus-datos?goto=1&' + cartForm;
// } else {
alert('Uncaught Error #3.\n' + jqXHR.responseText);
$('#buttonConfirmCart').prop('disabled', false).html('Confirmar Compra ');
// }
}
});
}
// 'login_and_confirm': function (e) {
// let data_for_login, aditional_data, query_with_form;
// let data_of_cart = window.location.search;
// e.preventDefault();
// $('#login-cart').prop('disabled', true).html('');
// data_for_login = $('#login-form').serialize();
// query_with_form = data_for_login + '&' + data_of_cart;
// $.ajax({
// url: '/login-and-confirm',
// type: 'POST',
// data: query_with_form,
// success: function (data) {
// if (data.success) {
// aditional_data = data_of_cart + data.aditional_data;
// $.ajax({
// url: data.redirect_url,
// type: 'POST',
// data: aditional_data,
// success: function (data2) {
// if (data2.success) {
// document.location.href = data2.redirect_url;
// } else {
// $('#login-cart').prop('disabled', false).html('Iniciar Sesión');
// toastr.error('', data2.msg, {
// progressBar: true,
// timeOut: 5000,
// });
// setTimeout(function () {
// document.location.href = data2.redirect_url;
// }, 3000);
// }
// }
// });
// }
// else
// {
// $('#login-cart').prop('disabled', false).html('Iniciar Sesión');
// toastr.error('', data.msg, {
// progressBar: true,
// timeOut: 5000,
// });
// setTimeout(function () {
// document.location.href = data.redirect_url + data.aditional_data;
// }, 3000);
// }
// },
// error: function (data) {
// laravelErrorMessages(data);
// $('#login-cart').prop('disabled', false).html('Iniciar Sesión');
// }
// });
// }
}
function cart_items(url)
{
$.ajax({
url: url,
type: 'GET',
success: function (data) {
$('#cartTotal_temp3').html(data.total);
$('#cartTotal_temp4').html(Math.round(data.total));
$('.cartTotal').html(data.total);
$('#cartTotal').html(data.total + ' item(s)');
$('#cartTotalAmount').html(data.total_amount);
$('.cartTotalAmount').html(data.total_amount);
$('#cartTotal_temp32').html(data.total + ' Item(s) -' + data.total_amount);
$('#cart-item').empty().html(data.view);
$('#cart-item-mobile').empty().html(data.view);
if (data && data.view && typeof cartPopover === 'function') {
try { cartPopover(data.view); } catch (e) { console.warn('cartPopover failed:', e); }
}
},
});
}
// var wishlist = {
// 'add': function (url) {
// $.ajax({
// url: url,
// type: 'POST',
// success: function (data) {
// if (data.success) {
// toastr.success('', data.message, {
// progressBar: true,
// timeOut: 5000,
// });
// } else {
// toastr.error('', data.message, {
// progressBar: true,
// timeOut: 5000,
// });
// }
// },
// });
// },
// }
function requireLineUser() {
var answer = null;
answer = prompt('Ingrese su Número de línea sin el 0: \nEjemplo: 971xxxxxx');
if (answer == "") {
alert('Debe ingresar su número de línea.');
return false;
}
if (answer == null) {
return false;
} else {
if (!isNaN(answer) && answer != null) {
if (answer.length >= 10 ) {
alert('Solo debe ingresar 9 números.');
return false;
} else if (answer.length < 9) {
alert('Debe ingresar su número de línea.');
return false;
} else {
return answer;
}
} else {
alert('Debe ingresar solo números.');
return false;
}
}
}
function change_pay_method(value){
$('input[name="payment_method_id"]').val(value);
}
function openPostPage(url, data) {
var form = document.createElement('form');
document.body.appendChild(form);
//form.target = '_blank';
form.method = 'post';
form.action = url;
for (var name in data) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = data[name];
form.appendChild(input);
}
form.submit();
document.body.removeChild(form);
}
// Focus al option via js
function setSeletedOption(select, focus)
{
if (focus) {
document.querySelector('#'+select+' [value="' + focus + '"]').selected = true;
}
}
// eliminar via delete
function data_delete(url, text = '¿Desea eliminar el registro?') {
Swal.fire({
title: text,
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#d33',
cancelButtonColor: '#3085d6',
confirmButtonText: 'Sí, eliminar',
cancelButtonText: 'Cancelar'
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
type: "DELETE",
url: url,
success: function (data) {
if (data.success) {
Swal.fire({
title: '¡Eliminado!',
text: 'Eliminado correctamente.',
icon: 'success',
timer: 2000,
showConfirmButton: false
}).then(() => {
if (data.url) {
location.href = data.url
} else {
location.reload();
}
});
} else {
Swal.fire({
title: 'Error',
text: data.msg || 'Hubo un problema al procesar la eliminación.',
icon: 'error'
});
}
},
error: function() {
Swal.fire({
title: 'Error',
text: 'Hubo un problema al procesar la solicitud.',
icon: 'error'
});
}
});
}
});
}
function togglePassword(passButton)
{
//Mostrar/Ocultar text de la Pass
var passwordField = $(passButton).parent().find('input');
var passwordIcon = $(passButton).find('i').add($(passButton).find('svg')) ?? $(passButton).find('.passwordIcon');
if(typeof passwordField != 'undefined')
{
if (passwordField.attr('type') === 'password')
{
// Cambiar a texto (mostrar contraseña) - mostrar ojo abierto
passwordField.attr('type', 'text');
passwordIcon.removeClass('fa-eye-slash').addClass('fa-eye');
}
else
{
// Cambiar a password (ocultar contraseña) - mostrar ojo cerrado
passwordField.attr('type', 'password');
passwordIcon.removeClass('fa-eye').addClass('fa-eye-slash');
}
}
}
function checkLenghtPassword(input)
{
var passwordIcon = $(input).parent().find('button');
if(typeof passwordIcon != 'undefined')
{
if ($(input).val().length >= 1)
{
passwordIcon.show();
} else
{
passwordIcon.hide();
}
}
}
window.onpageshow = function(ev) {
if (window.performance) {
var navEntries = window.performance.getEntriesByType('navigation');
if (navEntries.length > 0 && navEntries[0].type === 'back_forward') {
cart_items('/carrito-items');
} else if (window.performance.navigation
&& window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
cart_items('/carrito-items');
}
}
var socialButtons = document.querySelectorAll('#register-google, #register-facebook');
socialButtons.forEach(function (button) {
button.addEventListener('click', function (event) {
// Obtener URL del boton o a href.
var url = button.getAttribute('data-url') || button.getAttribute('href');
socialLoginForm(event, url);
});
});
}
function socialLoginForm(event, url) {
event.preventDefault();
var termsButton = document.getElementById('terms_and_conditions');
if (termsButton.checked) {
window.location.href = url;
} else {
alert("Debe marcar la casilla de términos y condiciones");
}
}
$(document).on('click', '.modal-triggerTest', function () {
const url = $(this).data('url');
const modalType = $(this).data('modal-type');
if(modalType === 'purchase-without-registration'){
redirect(url);
}else{
$("#headingContactData, .guestCheckoutCard").hide()
$.get(url, function (html) {
$('#dynamic-modal-container').empty().append(html);
const modalTest = $('#dynamic-modal-container .modal');
modalTest.modal('show');
modalTest.addClass('show');
modalTest.css('display', 'block'); // Asegurar que el modal sea visible
encryptPassword();
}).fail(function () {
console.error('Error al cargar el modal.');
});
}
});