// Variables para almacenar las peticiones AJAX activas
var currentBusquedaRequest = null;
var currentProductsRequest = null;

$(document).ready(function () {
    // Verificar si se est� accediendo desde un dispositivo m�vil
    var esDispositivoMovil = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    try {
        if (esDispositivoMovil) { desplazamientoSuave("#zIdMicuenta"); }
    } catch (e) {

    }
});


var tieneRecoleccion = false;

function initProductos() {
    stNextProducts("todo", "0", "18");
    nextoffset = parseInt($("#nextOffset").val()) + 18;
    $("#nextOffset").val(nextoffset);

}

function stNextProducts(stCategoria, stStartRegister, stCantProdcutos) {
    // Cancelar la petición anterior si existe
    if (currentProductsRequest) {
        currentProductsRequest.abort();
    }

    // Ocultar el botón de más productos
    parent.$("#idmasproductos").hide();

    // Hacer la nueva petición AJAX
    currentProductsRequest = $.ajax({
        url: '/zcore/api/productos',
        type: 'POST',
        data: {
            categoria: stCategoria,
            startRegister: stStartRegister,
            cantRegistros: stCantProdcutos
        },
        success: function (response) {
            var jsonResponse = response;
            if (jsonResponse.length > 0) {

                if (stStartRegister == "0") {
                    parent.$("#zListaProdcutos").html("");
                }

                jsonResponse.forEach(function (item) {
                    appendProdcutos('xton', item["id"], item["urlf"], item["nombre"], item["precio"], item["preciodescuento"], item["cate"]);

                    if (item["mas"] == "no") {
                        parent.$("#idmasproductos").hide();
                    } else {
                        parent.$("#idmasproductos").show();
                    }

                });
            } else {
                parent.$("#idmasproductos").hide();
            }
        }
    });
}
function appendProdcutos(plantilla, id, urlf, nombre, precio, preciodescuento, cate) {

    switch (plantilla) {
        case "xton":
            var articuloCat = "";
            if (Number(preciodescuento) > 0) {
                articuloCat = $('<div class="col-lg-4 col-md-4 col-6 products-col-item"><div class="products-box"><div class="products-image"><a href="/producto/' + urlf + '"><img src="/img/productos/' + id + '/1.jpg" class="main-image" alt="image"><img src="/img/productos/' + id + '/2.jpg" class="hover-image" alt="image"></a><div class="sale-tag">%</div></div><div class="products-content"><span class="category">' + cate + '</span><h3 class="znombreproductos"><a href="#">' + nombre + '</a></h3><div class="price2"><span class="new-price">$' + precio + '</span><span class="old-price">$' + preciodescuento + '</span></div></div></div></div>');
            } else {
                articuloCat = $('<div class="col-lg-4 col-md-4 col-6 products-col-item"><div class="products-box"><div class="products-image"><a href="/producto/' + urlf + '"><img src="/img/productos/' + id + '/1.jpg" class="main-image" alt="image"><img src="/img/productos/' + id + '/2.jpg" class="hover-image" alt="image"></a></div><div class="products-content"><span class="category">' + cate + '</span><h3 class="znombreproductos"><a href="#">' + nombre + '</a></h3><div class="price2"><span class="new-price">$' + precio + '</span></div></div></div></div>');
            }
            parent.$("#zListaProdcutos").append(articuloCat);
            articuloCat.fadeIn();
            parent.$('#productsFilterModal').modal('hide');
            break;
    }

}

// FUNCION QUE CAMBIA LA INPUT EL CUAL LA FUNCION TOMA PARA SABER QUE CATEGORIA MOSTRAR EN EL CATALOGO
// SEP 2024 | 64MXG
function changeCate(newCate) {
    changeurl(newCate);
    parent.$("#zListaProdcutos").html('');
    parent.$("#nextOffset").val("0");
    parent.$("#idNextCate").val(newCate);
    nextOffset();
}

// FUNCION HACELA LLAMADA AJAX PARA CARGAR PRODUCTO DE INCIO Y LOS SIGUIENTES ARTICULOS AL CLICK BOTON MAS PRODCUTOS
// SEP 2024 | 64MXG
function nextOffset() {
    nextoffset = $("#nextOffset").val();
    nextCate = $("#idNextCate").val();
    stNextProducts(nextCate, nextoffset, 18);
    nextoffset = parseInt(nextoffset) + 18;
    $("#nextOffset").val(nextoffset);
}

function changeurl(url) {
    var new_url = "/productos/" + url;
    window.history.pushState("data", "Title", new_url);
    document.title = url;
}


function changeImgPrincipal(idCatart, imgNumber) {
    var urlImg = "/img/productos/" + idCatart + "/" + imgNumber + ".jpg";
    parent.$("#zIdImgPrincipal").attr("src", urlImg);
}


// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// FUNCIONES PARA PRODCUTOS

function talla() {
    var seleccion = $("#tallasycolores").val();
    var seleccion2 = $("#zFormFavoritos").val();
    $.ajax({
        url: '/zcore/api/tallas',
        type: 'POST',
        data: {
            idart: seleccion, seleccion2
        },
        success: function (response) {
            //var jsonResponse = JSON.parse(response);
            var jsonResponse = response;
            if (jsonResponse.length > 0) {
                parent.$("#zPrecioPublico").html("");
                parent.$("#zPrecioTachado").html("");
                jsonResponse.forEach(function (item) {
                    parent.$("#zPrecioPublico").html(item["preciopublico"]);

                    if (Number(item["preciotachado"]) > 0) {
                        parent.$("#zPrecioTachado").html(item["preciotachado"]);
                    } else {
                        parent.$("#zPrecioTachado").html("");
                    }

                    parent.$("#zExi").html(item["existencia"]);
                    parent.$("#zCa").attr("max", item["existencia"]);
                    parent.$("#idtallasycolores").val(item["id"]);
                    parent.$("#zFIdtallasycolores").val(item["id"]);

                    parent.$("#zBotonAgregarCarrito").show();

                    zFavoritosVerificar();
                });
            } else {
            }
        }
    });
}


// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// FUNCIONES PARA ENVIO CLICK

function envioClick() {
    parent.$('#zPaqueterias').LoadingOverlay("show", { image: "/zcore/loading.svg", imageAnimation: false });

    var varEnvioPropio = parent.$("#zoEnvioPropio").val();

    var varTipo = parent.$("#zoIdMetodoEntrega").val();
    var varOrigen = parent.$("#zoInputOrden").val();
    var varIdd = parent.$("#zoIdAddress").val();
    var varValue = parent.$("#zoGrandTotal").val();


    if (varEnvioPropio == "0") {

        if (varTipo == "r") {

            console.log(varTipo);
            console.log(varOrigen);
            console.log(varIdd);
            console.log(varValue);


            $.ajax({
                url: '/zcore/api/enviopropio',
                type: 'POST',
                data: {
                    tipo: varTipo,
                    origen: varOrigen,
                    idd: varIdd,
                    value: varValue,
                },
                success: function (response) {
                    var jsonResponse = response;
                    if (jsonResponse.length > 0) {
                        parent.$("#zPaqueterias").html("");
                        jsonResponse.forEach(function (item) {

                            if (varTipo == "e") {
                                parent.$('#zPaqueterias').append('<tr onclick="agregarEnvioClick(\'' + item["idRate"] + '\', \'' + item["carrier"] + '\', \'' + item["product"] + '\', \'' + item["deliveryDays"] + '\', \'' + item["price"] + '\');"><td><strong>' + item["carrier"] + '</strong><br />' + item["product"] + ' ' + item["deliveryDays"] + ' dias.</td><td width="80" class="zTextright" ><strong>' + item["price"] + '</strong></td></tr>');
                            }

                            if (varTipo == "r") {
                                parent.$("#zIdInfoEnvioCarrier").html("");
                                parent.$("#zIdInfoEnvioProduct").html("");
                                parent.$("#zIdInfoEnvioPrice").html("0");
                                parent.$("#zoEnvio").html("0");
                                calcularTotal();
                                zofCrearPrefencia();
                            }

                        });
                    } else {
                       // console.log(response);
                    }
                    setTimeout(function () {
                        parent.$('#zPaqueterias').LoadingOverlay("hide");
                    }, 1500);
                }
            });
        }

        if (varTipo == "e") {
            $.ajax({
                url: '/zcore/api/enviopropio',
                type: 'POST',
                data: {
                    tipo: varTipo,
                    origen: varOrigen,
                    idd: varIdd,
                    value: varValue,
                },
                success: function (response) {
                    var jsonResponse = response;
                    if (jsonResponse.length > 0) {
                        parent.$("#zPaqueterias").html("");
                        jsonResponse.forEach(function (item) {

                            if (varTipo == "e") {
                                parent.$('#zPaqueterias').append('<tr onclick="agregarEnvioClick(\'' + item["idRate"] + '\', \'' + item["carrier"] + '\', \'' + item["product"] + '\', \'' + item["deliveryDays"] + '\', \'' + item["price"] + '\');"><td><strong>' + item["carrier"] + '</strong><br />' + item["product"] + ' ' + item["deliveryDays"] + ' dias.</td><td width="80" class="zTextright" ><strong>' + item["price"] + '</strong></td></tr>');
                            }

                            if (varTipo == "r") {
                                parent.$("#zIdInfoEnvioCarrier").html("");
                                parent.$("#zIdInfoEnvioProduct").html("");
                                parent.$("#zIdInfoEnvioPrice").html("0");
                                parent.$("#zoEnvio").html("0");
                                calcularTotal();
                                zofCrearPrefencia();
                            }

                        });
                    } else {

                    }
                    setTimeout(function () {
                        parent.$('#zPaqueterias').LoadingOverlay("hide");
                    }, 1500);
                }
            });
        }



    } else {
        $.ajax({
            url: '/zcore/api/enviopropio',
            type: 'POST',
            data: {

            },
            success: function (response) {
                var jsonResponse = response;
                if (jsonResponse.length > 0) {
                    parent.$("#zPaqueterias").html("");
                    jsonResponse.forEach(function (item) {

                        if (varTipo == "e") {
                            parent.$('#zPaqueterias').append('<tr onclick="agregarEnvioClick(\'' + item["idRate"] + '\', \'' + item["carrier"] + '\', \'' + item["product"] + '\', \'' + item["deliveryDays"] + '\', \'' + item["price"] + '\');"><td><strong>' + item["carrier"] + '</strong><br />' + item["product"] + ' ' + item["deliveryDays"] + ' dias.</td><td width="80" class="zTextright" ><strong>' + item["price"] + '</strong></td></tr>');
                        }

                        if (varTipo == "r") {
                            parent.$("#zIdInfoEnvioCarrier").html("");
                            parent.$("#zIdInfoEnvioProduct").html("");
                            parent.$("#zIdInfoEnvioPrice").html("0");
                            parent.$("#zoEnvio").html("0");
                            calcularTotal();
                            zofCrearPrefencia();
                        }

                    });
                } else {

                }
                setTimeout(function () {
                    parent.$('#zPaqueterias').LoadingOverlay("hide");
                }, 1500);
            }
        });
    }

}

function agregarEnvioClick(varIdrate, varCarrier, varProduct, varDeliverydays, varPrice) {
    parent.$("#zoIdHaveShipping").html("1");
    parent.$('#zPaqueterias').LoadingOverlay("show", { image: "/zcore/loading.svg", imageAnimation: false });

    var varOrden = parent.$("#zoInputOrden").val();
    var varOrigen = parent.$("#zoInputOrigen").val();
    var varIdAddress = parent.$('#zoIdAddress').val();
    var fixedPrice = parseFloat(varPrice).toFixed(2);

    parent.$("#zIdInfoEnvioCarrier").html(varCarrier);
    parent.$("#zIdInfoEnvioProduct").html(varProduct + " " + varDeliverydays);
    parent.$("#zoEnvio").html(fixedPrice);
    parent.$("#zIdInfoEnvioPrice").html("$" + fixedPrice);

    $.ajax({
        url: '/zcore/api/envio_agregar',
        type: 'POST',
        data: {
            orden: varOrden,
            origen: varOrigen,
            idAddress: varIdAddress,
            idRate: varIdrate,
            carrier: varCarrier,
            product: varProduct + ' ' + varDeliverydays,
            price: varPrice,
            codigo: 'e',
        },
        success: function (response) {
            var jsonResponse = response;

            if (jsonResponse.length > 0) {
                jsonResponse.forEach(function (item) {
                });

            }
            parent.$('#zPaqueterias').html("");
            parent.$("#idHaveShipping").val("1");
            parent.$("#zBCambiarEnvio").show();
            $('#collapseThree').collapse('hide');
            calcularTotal();
            zofCrearPrefencia();
        }
    });
}

// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// FUNCIONES PARA CALCULAR EL TOTAL

function calcularTotal() {
    var subtotal = Number(parent.$('#zoSubTotal').html());

    var descuento = parseFloat(parent.$('#zoDescuento').html());
    var envio = parseFloat(parent.$('#zoEnvio').html());
    var total = (subtotal) + envio;

    parent.$('#zoTotal').html(total.toFixed(2));
    validarCarrito();
}

function validarCarrito() {
    var productos = parent.$('#idHaveProductos').val();
    var direccion = parent.$('#idHaveAdress').val();
    var envio = parent.$('#idHaveShipping').val();

    if (envio == "1") {
        parent.$("#zBCambiarEnvio").show();
    }

    if (productos == "1" && direccion == "1" && envio == "1") {
        parent.$('#zBGenerarOrdenCarrito').show();
    }
}

function desplazamientoSuave(targetId) {
    //$('html, body').animate({
    //	scrollTop: parent.$(targetId).offset().top
    //}, 400);
}


// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// FUNCION ACTUALIZAR UBICACION EN INFORMACION DE ORDEN

function actualizarUbicacionInfoOrdenes() {
    var varid = parent.$("#idAddress").val();
    $.ajax({
        url: '/zcore/api/ubicacion_info',
        type: 'POST',
        data: {
            idaddress: varid,
        },
        success: function (response) {
            var jsonResponse = response;
            if (jsonResponse.length > 0) {
                jsonResponse.forEach(function (item) {
                    parent.$("#zIdInfoUbicacion1").html(item["calle"] + " " + item["exterior"] + " " + item["interior"]);
                    parent.$("#zIdInfoUbicacion2").html(item["estado"] + " " + item["municipio"] + " " + item["colonia"] + " " + item["cp"]);
                });
            } else {

            }
        }
    });
    calcularTotal();
}

//--------------------------------------------- FUNCIONES PARA METODO DE ENTREGA
//---------------------------------------------
$('.zBMetodosEntrega').on('click', function () {
    parent.$('#zIdMetodoEntregaIcono').html("");
    parent.$('#zIdMetodoEntrega').html("");
    var dTipo = $(this).data('tipo');
    parent.$("#zoIdMetodoEntrega").val(dTipo);
    parent.$("#wallet_container").html("");

    // Remueve la clase 'clicked' de todos los elementos
    $('.zBMetodosEntrega').removeClass('clicked');
    // Agrega la clase 'clicked' al elemento clickeado
    $(this).addClass('clicked');


    //--------------------- INICIALIZAMOS METODO DE ENTREGA
    parent.$('#zIdMetodoEntregaIcono').html("");
    parent.$("#zIdMetodoEntrega").html("");

    //--------------------- VERIFICAMOS EL METODO DE ENTREGA SELECCIONADO
    if ($(this).data('tipo') === "e") {
        parent.$('#zIdMetodoEntregaIcono').append('<img src="/zcore/img/delivery.png" alt="SMARTTARGET" width="50" />');
        parent.$("#zIdMetodoEntrega").html("Env&iacute;o a domicilio");
        parent.$('#zSeccionPaqueterias').show();
    } else {
        parent.$('#zIdMetodoEntregaIcono').append('<img src="/zcore/img/location.png" alt="SMARTTARGET" width="50" />');
        parent.$("#zIdMetodoEntrega").html("Recolecci&oacute;n en tienda");
        parent.$('#zSeccionPaqueterias').hide();
    }
    zofRecibirUbicaciones();
});


//--------------------------------------------- FUNCION VERIFICAR SI TENEMOS RECOLECCION
//--------------------------------------------- 
function zofTieneRecoleccion() {
    $.ajax({
        url: '/zcore/api/tienerecoleccion',
        type: 'POST',
        success: function (response) {
            var jsonResponse = response;
            if (jsonResponse.length > 0) {
                jsonResponse.forEach(function (item) {
                    if (item["codigo"] == '200' && item["acceso"] == 'true') {
                        tieneRecoleccion = true;
                        parent.$("#zSeccionMetodoEntrega").show();
                        parent.$("#zSeccionMetodoEntregaHead").show();
                    } else {
                        tieneRecoleccion = false;
                        parent.$("#zSeccionMetodoEntrega").hide();
                        parent.$("#zSeccionMetodoEntregaHead").hide();
                    }
                });
            }
        }
    });
}

//--------------------------------------------- FUNCION APLICAR METODO ENTREGA SELECCIONADO
//--------------------------------------------- 
function zofRecibirUbicaciones() {
    parent.$('#zTableUbicaciones').html("");
    var varTipo = parent.$("#zoIdMetodoEntrega").val();
    $.ajax({
        url: '/zcore/api/recibirubicaciones',
        type: 'POST',
        data: {
            orden: parent.$("#zoInputOrden").val(),
            tipo: varTipo,
            idcliente: parent.$("#zoIdCliente").val(),

        },
        success: function (response) {
            var jsonResponse = response;
            if (jsonResponse.length > 0) {
                jsonResponse.forEach(function (item) {
                    var htmlString = '<tr class="selectable-row" data-id="' + item['id'] + '" data-nombre="' + item['nombre'] + '" data-calle="' + item['calle'] + '" data-exterior="' + item['exterior'] + '" data-interior="' + item['interior'] + '" data-estado="' + item['estado'] + '" data-municipio="' + item['municipio'] + '"><td><div class="form-check"><input class="form-check-input" type="radio" name="zIdUbicaciones" id="zIdUbicaciones_' + item['id'] + '" value="' + item['id'] + '"><label class="form-check-label" for="exampleRadios1"><strong>' + item['nombre'] + ' | ' + item['calle'] + ' ' + item['exterior'] + ' ' + item['interior'] + '</strong></label><br />' + item['estado'] + ' ' + item['municipio'] + ' ' + item['colonia'] + ' ' + item['cp'] + '<br />' + item['cruces'] + ' | ' + item['observaciones'] + '</div></td></tr>';
                    parent.$('#zTableUbicaciones').append(htmlString);
                });
                parent.$('#zFormaAgregarUbicacion').hide();
                parent.$('#collapseTwo').collapse('show');
            } else {
                parent.$('#collapseTwo').collapse('show');
                // console.log(response);
            }
        }
    });

}


//--------------------------------------------- FUNCION CREAR PREFERENCIA MP
//--------------------------------------------- 
function zofCrearPrefencia() {
    var varOrden = parent.$("#zoInputOrden").val();
    $.ajax({
        url: '/zcore/api/mpbrick',
        type: 'POST',
        data: {
            orden: varOrden,
        },
        success: function (response) {
            var jsonResponse = response;
            if (jsonResponse.length > 0) {
                jsonResponse.forEach(function (item) {
                    parent.$('#zoMPPreferenceId').val(item["preferencia"]);
                    if (item["codigo"] === "200") {
                        parent.$("#wallet_container").html('');
                        mpBrick();
                        desplazamientoSuave("zIdHeadOrderInformation");
                    }
                });
            } else {

            }
        }
    });

}

//--------------------------------------------- FUNCION VALIDAR INFORMACION INICIAL
//--------------------------------------------- 
function zofValidarInfoInical() {
    parent.$('#zIdMetodoEntregaIcono').html("");
    parent.$('#zIdMetodoEntrega').html("");
    var varTipoEntrega = parent.$("#zoIdMetodoEntrega").val();
    var varOrden = parent.$("#zoInputOrden").val();
    var varidHaveShipping = parent.$("#zoIdHaveShipping").val();

    switch (varTipoEntrega) {
        case "e":
            parent.$('#zIdMetodoEntregaIcono').append('<img src="/zcore/img/delivery.png" alt="SMARTTARGET" width="50" />');
            parent.$("#zIdMetodoEntrega").html("Env&iacute;o a domicilio");
            break;
        case "r":
            parent.$('#zIdMetodoEntregaIcono').append('<img src="/zcore/img/location.png" alt="SMARTTARGET" width="50" />');
            parent.$("#zIdMetodoEntrega").html("Recolecci&oacute;n en tienda");
            break;
        default:
    }

    if (parent.$("#zoIdHaveProductos").val() == "1") {
        parent.$("#zSeccionMetodoEntrega").show();
    }

    if (varTipoEntrega != "" && varOrden != "") {
        zofCrearPrefencia();
    }

    if (varidHaveShipping == "1") {
        parent.$("#zBCambiarEnvio").show();
        parent.$("#zSeccionMetodoEntrega").show();
    }
}

function mpBrick() {
    var preferencia = parent.$("#zoMPPreferenceId").val();
    mp.bricks().create("wallet", "wallet_container", {
        initialization: {
            preferenceId: preferencia,
        },
        customization: {
            texts: {
                valueProp: 'smart_option',
            },
        },
    });
}


// --------------------------------------------------------------------- FUNCIONES DE FAVORITOS

function zFavoritos() {
    parent.$("#idmasproductos").hide();
    $.ajax({
        url: '/zcore/api/favoritos',
        type: 'POST',
        data: {
            idCatart: parent.$("#id").val(),
            idTallaColor: parent.$("#idtallasycolores").val(),
        },
        success: function (response) {
            //var jsonResponse = JSON.parse(response);
            var jsonResponse = response;
            // console.log(jsonResponse);
            if (jsonResponse.length > 0) {
                jsonResponse.forEach(function (item) {
                    parent.$("#zBIdFavoritos").html("");
                    if (item["estatus"] == true) {
                        parent.$("#zBIdFavoritos").append("<i class='bx bxs-heart'></i> Esta en tus favoritos");
                        parent.$("#zBIdFavoritos").removeClass("zBFavoritosGris").addClass("zBFavoritosRojo");
                    } else {
                        parent.$("#zBIdFavoritos").html("<i class='bx bxs-heart'></i> Agregar a mis favoritos");
                        parent.$("#zBIdFavoritos").removeClass("zBFavoritosRojo").addClass("zBFavoritosGris");
                    }
                });
            } else {
            }
        }
    });
}

function zFavoritosVerificar() {
    parent.$("#idmasproductos").hide();
    $.ajax({
        url: '/zcore/api/favoritosverificar',
        type: 'POST',
        data: {
            idCatart: parent.$("#id").val(),
            idTallaColor: parent.$("#idtallasycolores").val(),
        },
        success: function (response) {
            //var jsonResponse = JSON.parse(response);
            var jsonResponse = response;
            if (jsonResponse.length > 0) {
                jsonResponse.forEach(function (item) {
                    parent.$("#zBIdFavoritos").html("");
                    if (item["estatus"] == true) {
                        parent.$("#zBIdFavoritos").append("<i class='bx bxs-heart'></i> Esta en tus favoritos");
                        parent.$("#zBIdFavoritos").removeClass("zBFavoritosGris").addClass("zBFavoritosRojo");
                    } else {
                        parent.$("#zBIdFavoritos").html("<i class='bx bxs-heart'></i> Agregar a mis favoritos");
                        parent.$("#zBIdFavoritos").removeClass("zBFavoritosRojo").addClass("zBFavoritosGris");
                    }
                });
            } else {
            }
        }
    });
}

parent.$("#zBIdFavoritos").click(function () {
    zFavoritos();
});


//--------------------------------------------- FUNCION PARA EL BUSCADOR
//--------------------------------------------- 

function zJSBusqueda() {
    // Cancelar la petición anterior si existe
    if (currentBusquedaRequest) {
        currentBusquedaRequest.abort();
    }

    // Limpiar la lista de productos y ocultar el botón de más productos
    parent.$('#zListaProdcutos').html('');
    parent.$("#idmasproductos").hide();

    // Hacer la nueva petición AJAX
    currentBusquedaRequest = $.ajax({
        url: '/zcore/api/zbuscador',
        type: 'POST',
        data: {
            zbuscador: parent.$('#zIBusqueda').val()
        },
        success: function (response) {
            var jsonResponse = response;
            if (jsonResponse.length > 0) {
                jsonResponse.forEach(function (item) {
                    appendProdcutos('xton', item["id"], item["urlf"], item["nombre"], item["precio"], item["preciodescuento"], item["cate"]);
                });
            }
        }
    });
}
