/* Definir un evento que permita chachar el momento en que una etiqueta cambie de clase, se utiliza para produtos favoritos en ficha tecnia */ var jsonEspe = ""; $.fn.classChange = function(cb) { return $(this).each((_, el) => { new MutationObserver(mutations => { mutations.forEach(mutation => cb && cb(mutation.target, $(mutation.target).prop(mutation.attributeName))); }).observe(el, { attributes: true, attributeFilter: ['class'] // verifica si se cambio la clase }); }); } function replaceEspaciosEnBlanco(text, busca, reemplaza) { while (text.toString().indexOf(busca) != -1) text = text.toString().replace(busca, reemplaza); return text; } function lockLoader(mensaje) { $("body").append('
' + mensaje + '' + '' + '' + '
'); } function lockLoaderDestroy() { $('#loader').remove(); } function topFunction() { document.body.scrollTop = 0; // For Safari document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera } /* devuelve boeano * true color claro * false color obscuro */ function getLightHex(color) { const hex = color.replace('#', ''); const c_r = parseInt(hex.substr(0, 2), 16); const c_g = parseInt(hex.substr(2, 2), 16); const c_b = parseInt(hex.substr(4, 2), 16); const brightness = ((c_r * 299) + (c_g * 587) + (c_b * 114)) / 1000; return brightness > 155; } /* Local Storage guardar en memoria de navegador la informacion de las pestañas en ves de las cookies esta informacion no se borrara del navegador para borrar la informaicon de local storage es necesario utilizar alguno de los dos ultimos metodos ya sea por elemento o toda la memoria Guardar informacion en Local Storage localStorage.setItem(key, value); leer informaci desde Local Storage let lastname = localStorage.getItem(key); eliminar datos de Local Storage localStorage.removeItem(key); eliminar toda la informacion All (Clear Local Storage) localStorage.clear(); Session storage guarda la informacion mientras este abierto el navegador una vez se cierre el navegador la sesion se eliminará Save Data to Session Storage sessionStorage.setItem("key", "value"); Read Data from Session Storage let lastname = sessionStorage.getItem("key"); Remove Data from Session Storage sessionStorage.removeItem("key"); Remove All (Clear session Storage) sessionStorage.clear(); */ $(document).ready(function() { //console.log("Obteniendo informacion"); if(sessionStorage.getItem("lineasUF")==null){ $.ajax({ url: $('#general').attr('origenURL') + "/getArbolNew.sp", data: { custNum: sessionStorage.getItem('custNum') }, cache: false, async: false }).done(function(json) { sessionStorage.setItem("lineasUF", json); }); } //console.log("construyecndo menu"); var targetContainer = $("#offcanvas-body"); var template = $("#menuLineasTemplate").html(); var as = JSON.parse(sessionStorage.getItem('lineasUF')); var html = Mustache.to_html(template, as); targetContainer.html(html); formatearTexto($( ' .nodosDatos a')); $('.lineaNegocio').each(function(){ var lineaNeg = $(this).attr('lineanegocio'); $(this).find('.nodosDatos a').each(function(){ $(this).attr('href',$(this).attr('href')+lineaNeg); }); }); //console.log("construyecndo menuMobil"); /* var targetContainer = $("#AcordeonCategorias"); var template = $("#menuLineasTemplate2").html(); var as = JSON.parse(sessionStorage.getItem('lineasUF')); var html = Mustache.to_html(template, as); //console.log(as); targetContainer.html(html); */ $('.hojaMenu').each(function(){ $(this).attr('href',$(this).attr('href')+$(this).closest('.lineaNeg').attr('clave')) }) $(function() { var busquedaPal=""; $("#busqueda").autocomplete({ source: function(request, response) { var origenURL = $('#general').attr('origenURL'); $.ajax({ type: "POST", cache: false, async: true, url: origenURL + '/predictivoUFJson.sp', data: { buscado: request.term }, success: function(data) { var jsonBusqueda= JSON.parse(data).items.slice(0,5); var jsonPredictivo= []; busquedaPal = request.term; predictivoArbol(jsonPredictivo, request.term,JSON.parse(sessionStorage.getItem('lineasUF')).lineas,"",""); console.log(jsonPredictivo); jsonPredictivo= jsonPredictivo.concat(jsonBusqueda); console.log(jsonPredictivo); response(jsonPredictivo); } }); }, select: function(event, ui) { var origenURL = $('#general').attr('origenURL'); if (ui.item.item){ url = origenURL + '/ficha/productoFicha.sp?itemNum=' + ui.item.value; }else{ url = origenURL+ ui.item.url; } window.location.href = url; } }).autocomplete("instance")._renderItem = function(ul, item) { var li=""; if (!item.item){ li = $("
  • ").append("
    "+ "
    " +item.label+ " "+item.linea+"
    "); }else{ textElement=formatearTextoString(item.label); busqueda =formatearTextoString(busquedaPal); var nuevaCadena = textElement.replace(busqueda, ""+busqueda+""); li = $("
  • ").append("
    "+ "
    " +"  " +nuevaCadena+ "
    "); } li.appendTo(ul); return li ; }; $("#busqueda").focus(function() { $(".ui-autocomplete").show(); }); }); $(".mapsLink").click(function() { //console.log($(this)); url = encodeURIComponent($(this).attr('direccion')); url = 'https://www.google.com/maps/search/?api=1&query=' + url; //console.log(url); $(this).attr('href', url); }); //$(".hostName").html(window.location.hostname); //$(".hostName").attr('href', window.location.protocol + '//' + window.location.host); $('#btnBuscar').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/catalogoBusqueda.sp?isPaginacion=1&pageNumber=1&palabra=' + $('#busqueda').val(); window.location.href = url; }); $(window).scroll(function() { if ($(window).scrollTop() != 0) { $('#menuLineasEscritorio').hide(); $('#BtnTop').show(); } else { $('#menuLineasEscritorio').show(); $('#BtnTop').hide(); } }); $('.cerrarSession').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/cierraSession.sp'; window.location.href = url; }); $('.miCuentaBtn').click(function() { lockLoader(''); //url = $('#general').attr('origenURL') + '/datos/informacionCuenta.sp'; url = $('#general').attr('origenURL') + '/datos/datosGenerales.sp'; window.location.href = url; }); $("#btncrearCuenta,#btncrearCuenta2").click(function() { $('.nav-tabs a[href="#registrate"]').tab('show'); $('#categorias').offcanvas('hide'); }); $("#btniniciarSesion,#btniniciarSesion2").click(function() { $('.nav-tabs a[href="#sesion"]').tab('show'); $('#categorias').offcanvas('hide');; }); $("#busqueda").keypress(function(event) { if (event.which == 13) { $('#btnBuscar').click(); } }); var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]')) var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) { return new bootstrap.Tooltip(tooltipTriggerEl) }); var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]')) var popoverList = popoverTriggerList.map(function(popoverTriggerEl) { return new bootstrap.Popover(popoverTriggerEl) }); $(".recuperar").click(function() { $(".formato-recuperacion").toggle("slow"); }); $(".recuperar-1").click(function() { $(".formato-recuperacion-1").toggle("slow"); }); $(".ojo-cerrado").click(function() { $(".ojo-cerrado").hide(); $(".ojo-abierto").show(); $("#contraseña").attr('type', 'text'); }); $(".ojo-abierto").click(function() { $(".ojo-cerrado").show(); $(".ojo-abierto").hide(); $("#contraseña").attr('type', 'password'); }); $('#misPedidos').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/carrito/muestraPedidosNew.sp'; window.location.href = url; }); $('#misPedidosFavoritos').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/favorito/pedidosFavoritos.sp'; window.location.href = url; }); $('#misProductosFavoritos').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/favorito/productsFavoritos.sp'; window.location.href = url; }); $('#compraPeriodica').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/favorito/compraPeriodicaUF.sp'; window.location.href = url; }); $('#miCentroCostos').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/administracionPersonal/seleccionTipoPresupuestoUF.sp'; window.location.href = url; }); $('#misLibroDirecciones').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/direccion/LibroDirecciones.sp'; window.location.href = url; }); $('#GarantiaDevolucion').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/carrito/muestraPedidosNew.sp'; window.location.href = url; }); $('#misPedidosMobil').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/carrito/muestraPedidosNew.sp'; window.location.href = url; }); $('#misPedidosFavoritosMobil').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/favorito/pedidosFavoritos.sp'; window.location.href = url; }); $('#misProductosFavoritosMobil').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/favorito/productsFavoritos.sp'; window.location.href = url; }); $('#compraPeriodicaMobil').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/favorito/compraPeriodicaUF.sp'; window.location.href = url; }); $('#miCentroCostosMobil').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/administracionPersonal/seleccionTipoPresupuestoUF.sp'; window.location.href = url; }); $('#misLibroDireccionesMobil').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/direccion/LibroDirecciones.sp'; window.location.href = url; }); $('#GarantiaDevolucionMobil').click(function() { lockLoader(''); url = $('#general').attr('origenURL') + '/carrito/muestraPedidosNew.sp'; window.location.href = url; }); /* Objeto .btnsfav debe tener los atributos folio y data-id, */ $('body').on('click','.btnsfav',function(){ var folio= $(this).attr('folio'); var heartIcon = $(this); var itemNum = $(this).data('id'); var itemFav = $(this).hasClass('activeProdFav'); $('#itemNumProdFav').val(itemNum); $('#nombresProdFav').val(itemNum); var msg="¿Deseá agregar a favoritos el artículo "+itemNum+"?"; //console.log(itemNum); if(itemFav){ msg="¿Deseá remover de favoritos el articulo "+itemNum+"?" } Swal.fire({ title: 'Productos favoritos', text:msg, showDenyButton: true, showCancelButton: false, confirmButtonText: 'Aceptar', denyButtonText: 'Cancelar', }).then((result) => { if (result.isConfirmed) { if (!itemFav){ addItemFav(itemNum,folio,heartIcon); } else{ removeItemFav(itemNum,folio,heartIcon); } } }); }); $('body').on('click','.btn-desabasto',function(){ Swal.fire({ title:"Desabasto", text:"Estimado cliente, este producto se encuentra en desabasto por parte del fabricante, por el momento no es posible confirmar la fecha en que estara disponible", icon: 'info', confirmButtonText: 'OK' }); }); $('body').on('click','.fichaLink',function() { var origenURL = $('#general').attr('origenURL'); url = origenURL + '/ficha/productoFicha.sp?itemNum=' + $(this).attr('itemNum').trim(); window.location.href = url; }); $('body').on('click','.btn-sobre-pedido',function(){ Swal.fire({ title:"Sobre pedido", html:"Estimado cliente, este producto es sobre pedido, si tiene un requerimiento de compra, favor de contactarnos.
    " /*
    Contáctanos + $(this).attr('numCont')+ "" */, icon: 'info', confirmButtonText: 'OK' }); }); $('body').on('click','.btn-disponibilidad',function(){ Swal.fire({ title:"Sin disponibilidad", text:"Estimado cliente, por el momento este producto no cuenta con existencias, consulta la fecha de llegada:
    ", html:"Los tiempos de entrega y disponibilidad que aquí se muestran están sujetos a cambio sin previo aviso y al cumplimiento de entrega del fabricante." /*+"

    Piezas por recibir :"+$(this).attr('piezasPorReci')+" Fecha:"+$(this).attr('fechaPorReci')*/ +"

    Si requiere más piezas, favor de contactarnos." /*
    Contáctanos "+ $(this).attr('numCont')+""*/, icon: 'warning', confirmButtonText: 'OK' }); }); //Login events $('#loginBtn').click(function (){ grecaptcha.enterprise.ready(async () => { const token = await grecaptcha.enterprise.execute('6Ld82OMqAAAAAPcnX6t0b3_2xTjv9CVII_4_BgAl', {action: 'login'}); $("#recapToken").val(token); $('#loginForm').submit(); }); }); //recupera contraseña $('#formContacto').click(function(){ grecaptcha.enterprise.ready(async () => { const token = await grecaptcha.enterprise.execute('6Ld82OMqAAAAAPcnX6t0b3_2xTjv9CVII_4_BgAl', {action: 'password_reset'}); paswordLost(token); }); }); //Menu events $('.nodoBack').on('click', function(){ $('.nodosDatos').show(); $('.nodoBack').removeClass('d-none').show(); $('.nodoHijos').hide(); $('.nodo').removeClass('d-none').addClass('nodo_hover'); $('#labelMenu').html('Categorías.'); }); $('.flechaHijos').on('click',function(){ var nodoDatos =$(this).parent(); var nodo = $(this).closest('.nodo'); var nodoHijos= nodo.children('.nodoHijos'); var nodoBack = nodo.parent().children('.nodoBack'); nodoHijos.children('li').addClass('nodo_hover'); nodo.removeClass('nodo_hover'); nodoDatos.hide(); nodoBack.hide(); if(nodo.hasClass('lineaNegocio')){ $('#labelMenu').html(nodoDatos.children('a').text()); } nodo.siblings().addClass('d-none'); nodoHijos.show('slide'); }); }); function removeItemFav(itemNum,folio,heartIcon){ var datos= "itemNum="+itemNum+"&folio="+folio; var origenURL= $('#general').attr('origenURL'); var ids="#"+itemNum; $.ajax({ url : origenURL+'/favorito/elimminaProdFav.sp', data : datos, type : 'POST', async: false, success : function(dataResponse) { if(dataResponse.includes("no")){ Swal.fire('Error!', 'No se pudo remover !', 'error'); }else{ Swal.fire('Correcto!', 'El articulo se elimino de su lista de favoritos.', 'success'); heartIcon.removeClass('activeProdFav').addClass('inactiveProdFav'); heartIcon.tooltip().attr('title','Agregar a favoritos.'); } }, error : function(XMLHttpRequest, textStatus, errorThrown) { Swal.fire('Error!', 'Error al procesar la solicitud!', 'error'); } }); } function esRFCValido(rfc) { var caract = new RegExp( /^([A-Z�&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/); if (caract.test(rfc) == false) { return false; } return true; } function addItemFav(itemNum,folio,heartIcon){ var user=$('#usuarioNumProdFav').val(); var origenURL= $('#general').attr('origenURL'); var form = $("#ProdfavoritoCompleto").serializeArray();// serializa en un array var cadena = JSON.stringify(form);// Convierte a JSON el arreglo serializado var direccion =origenURL+ "/favorito/guardaProductsFavoritos.sp";// direccion a la que se va a enviar var datos = "formulario=" + cadena+"&itemNum="+itemNum+"&cantidad=1&user="+user;// Forma url para enviar los datos del formulario $.ajax({ type : "POST",// metodo de envio url : direccion,// url destino cache : false, data : datos,// datos enviados success : function(response) { if(response.includes("Guardado")) { Swal.fire('Correcto!', 'El articulo se agrego a su lista de favoritos.', 'success'); heartIcon.removeClass('inactiveProdFav').addClass('activeProdFav'); } if(response=='Error en los datos') { Swal.fire('Error!', 'No se pudo remover !', 'error'); } },// en caso de error error : function(XMLHttpRequest, textStatus, errorThrown) { Swal.fire('Error!', 'Error al procesar la solicitud!', 'error'); } }); } function agregarListaFavorita(datos,origenURL){ if(datos.length<=0){ return; } $.ajax({ type: "POST", url: origenURL+'/favorito/agregaProducto.sp', data: datos, beforeSend: function(){ lockLoader(''); }, success: function(dataResponse){ lockLoaderDestroy(); Swal.fire({ customClass: 'swal-wide', showDenyButton: true, showCancelButton: false, showConfirmButton: false, denyButtonText: 'Salir', width:'75%', html:dataResponse }); }, error: function(XMLHttpRequest, textStatus, errorThrown){ Swal.fire('Error!', 'Se produjo un error guardar la lista', 'error'); console.log('%cFalla '+ errorThrown,'color:red;'); lockLoaderDestroy(); } }); } $(document).on('click','.guardarListaFav',function(){ var origenURL= $('#general').attr('origenURL'); var folio = $("#folio option:selected").val(); var name = $("#folio option:selected").attr('list-name'); if(folio == ""){ Swal.fire('Error!', 'no has seleccionado a la lista que quieres que pertenezca', 'error'); return false; } var form = $("#guardaFav").serializeArray(); var cadena = JSON.stringify(form); var direccion = origenURL+"/favorito/guardaItem.sp" var datos = "formulario="+cadena; $.ajax({ type:"POST", url: direccion, cache: false, data: datos, beforeSend: function(){ }, success: function(response){ if(response == "S"){ swal.close(); Swal.fire('Exito!', 'Se agregaron los productos a la lista: '+name+"", 'success'); }else{ swal.close(); alert(response); } }, error: function(XMLHttpRequest, textStatus, errorThrown){ Swal.fire('Error!', 'No se ha podido agregar los datos', 'error'); console.log("falla: "+errorThrown); } }); }); $(document).on('click','.crearListaFav',function (){ var origenURL= $('#general').attr('origenURL'); var item = $("#nombres").val(); var cantidad = $("#cantidadP").val(); var direccion = origenURL+"/favorito/altaCatalogo.sp"; var datos = "opc=0"; if(item != undefined && item != ""){ datos += "&itemNum="+item; } if(cantidad != undefined && cantidad != ""){ datos += "&cantidad="+cantidad; }console.log(datos); $.ajax({ type:"POST", url: direccion, data: datos, beforeSend: function(){ }, success: function(response){ swal.close() Swal.fire({ customClass: 'swal-wide', showDenyButton: true, showCancelButton: false, showConfirmButton: false, denyButtonText: 'Salir', html:response }); }, error: function(XMLHttpRequest, textStatus, errorThrown){ Swal.fire('Error!', 'Error en carga de recursos', 'error'); console.log(errorThrown); } }); }); $(document).on('click','.agregarNuevaLista',function (){ var origenURL= $('#general').attr('origenURL'); var publico = $("#publico").val(); var opc = $("#opc").val(); var nombre = $("#nombre").val(); if (nombre == "") { alert("La lista debe tener un nombre"); $("#nombre").focus(); return false; } var form = $("#favoritoCompleto").serializeArray();// serializa en un array var cadena = JSON.stringify(form);// Convierte a JSON el arreglo console.log("guardarFavoritoNuevoProceso, origenURL:"+origenURL) let direccion = "/blitz"+"/favorito/guardaFavorito.sp" if(origenURL !== null){direccion = origenURL+"/favorito/guardaFavorito.sp"} var datos = "formulario=" + cadena;// Forma url para enviar los datos del $("#contenedorModalPedido").modal('hide'); $("#nombreListaId").html(nombre); $.ajax({ type : "POST",// metodo de envio url : direccion,// url destino cache : false, data : datos,// datos enviados beforeSend : function() {}, success : function(response) { swal.close(); Swal.fire('Correcto','¡Se ha creado la lista!','success'); },// en caso de error error : function(XMLHttpRequest, textStatus, errorThrown) { console.log("falla: " + textStatus); swal.close(); } }); }); function isNumber(event){ var iKeyCode = (event.which) ? event.which : event.keyCode if (iKeyCode != 46 && iKeyCode > 31 && (iKeyCode < 48 || iKeyCode > 57)) return false; return true; } function isTextNumberSimbol(event) { var charCode = (event.which) ? event.which : event.keyCode; // Numbers (0-9) if ((charCode >= 48 && charCode <= 57)) { return true; } // Uppercase letters (A-Z) if (charCode >= 65 && charCode <= 90) { return true; } // Lowercase letters (a-z) if (charCode >= 97 && charCode <= 122) { return true; } // Spaces, period (.), semicolon (;), comma (,), dollar ($), and percentage (%) if (charCode === 32 || charCode === 46 || charCode === 59 || charCode === 44 ) { return true; } return false; } function formatearTexto(elem){ elem.each(function() { var texto = $(this).text().trim(); var textoModificado = texto.replace(/^(.)(.*)$/, function(_, primeraLetra, restoTexto) { return primeraLetra.toUpperCase() + restoTexto.toLowerCase(); }); $(this).text(textoModificado); }); } function formatearPrecio(elem){ $(elem).each(function(){ var precio = $(this).text().replace('$','').replace(',',''); var precioRedondeado = parseFloat(parseFloat(precio).toFixed(2)); var precioFormateado = precioRedondeado.toLocaleString('es-MX'); $(this).text(precioFormateado=='NaN'?'':'$'+precioFormateado); }) } function formatearTextoString(texto){ texto.trim(); return texto.replace(/^(.)(.*)$/, function(_, primeraLetra, restoTexto) { return primeraLetra.toUpperCase() + restoTexto.toLowerCase(); }); } function paswordLost(token){ var origenURL = $('#general').attr('origenURL'); var correoUF = $("#emailPL").val(); var numeroCliente = $("#clienteUfPL").val(); if (correoUF=="" || correoUF==null){ toastr.error('',"Ingresa tu correo", {timeOut: 10000}); return false; } if (numeroCliente=="" || numeroCliente==null){ toastr.error('',"Ingresa tu número de cliente", {timeOut: 10000}); return false; } btn= $(this); $.ajax ({ type: "POST", url: origenURL+'/passwordLost.sp', cache: false, data: "correo="+correoUF+"&numeroCliente=" + numeroCliente+"&recapToken="+token, beforeSend: function(){ $(btn).attr("disabled", true) }, success: function(dataResponse){ if(dataResponse.includes('email')){ $('#modalIniciarSesion').modal('hide'); Swal.fire('Email enviado',"Se ha enviado un correo con las instrucciones para restablecer tu contraseña.",'success'); }else{ toastr.error('',dataResponse, {timeOut: 10000}); } $(btn).attr("disabled", false) }, error: function(XMLHttpRequest, textStatus, errorThrown){ alert('FALLA:'+errorThrown); $(btn).attr("disabled", false) } }); return false; } function limpiarCookieCarrito(){ var origenURL = $('#general').attr('origenURL'); $.ajax({ type: "POST", url: origenURL + '/recuperarCarrito.sp', async:false, data: { recuperar: 'N' }, success: function(data) { localStorage.setItem('__mycart',''); } }); } function recuperarPedido(){ var origenURL = $('#general').attr('origenURL'); $.ajax({ type: "POST", url: origenURL + '/recuperarCarrito.sp', async:false, data: { recuperar: 'S' }, success: function(response) { jsonCart = JSON.parse(response); jsonCart = JSON.stringify(jsonCart); localStorage.setItem('__mycart',jsonCart); } }); } function getBannersMkt(vista,idseccion,nomseccion,origenURL,pathLogo){ $.ajax({ type : "POST", url : origenURL+"/AdminBanners/getImages.sp", cache : false, data : { vista : vista, seccion: idseccion }, success : function(dataResponse) { if(dataResponse=="" && idseccion==2 ){ $('#transition-timer-carousel').hide(); }else if(idseccion==2){ dataResponse.forEach(function(Imagenes, index) { var urlImg=pathLogo+"/BannersMkt/"+$.trim(Imagenes.nombre_campania)+"/"+$.trim(Imagenes.nombre_imagen); $("#carousel-inner-"+nomseccion).append(''); }); if ($('#carrusel-home .carousel-item').length !=0){ $('#carrusel-home .carousel-item').first().addClass('active'); $('#carrusel-home').show(''); } } else if(idseccion == 3 || idseccion==8 || idseccion==19){ dataResponse.forEach(function(Imagenes, index) { var urlImg=pathLogo+"/BannersMkt/"+$.trim(Imagenes.nombre_campania)+"/"+$.trim(Imagenes.nombre_imagen); $('.banerSec[data-seccion="'+idseccion+'"]').attr('src',urlImg); var url = '/busquedaArticulosBanners.sp?numCampania='+Imagenes.num_campania+'&buscarPor='+Imagenes.buscar_por+'&opc=0&searchInput=1' $('.banerSec[data-seccion="'+idseccion+'"]').parent().attr('href',url); }); } }, error : function(XMLHttpRequest, textStatus, errorThrown) { console.log('FALLA errorThrown:' + errorThrown); } }); } function getBannersDist(origenURL,pathLogo){ let direccion = "/AdminBanners/getImagesDist.sp" if(origenURL != ""){ direccion = origenURL+"/AdminBanners/getImagesDist.sp" } $.ajax({ type : "POST", url : direccion, cache : false, success : function(dataResponse) { //console.log(dataResponse); aplicaClase="bann_carusel"; if(dataResponse!=""){ dataResponse.forEach(function(Imagenes, index) { var urlImg=pathLogo+Imagenes.cust_num+"/"+Imagenes.nombre_imagen; $("#carousel-inner-home").append( ''); }); if ($('#carrusel-home .carousel-item').length !=0){ $('#carrusel-home .carousel-item').first().addClass('active'); $('#carrusel-home').show(''); } } }, error : function(XMLHttpRequest, textStatus, errorThrown) { console.log('FALLA errorThrown:' + errorThrown); } }); } function getBannersDistEditables(origenURL,pathLogo){ let direccion = "/AdminBanners/getImagesE.sp" if(origenURL != ""){ direccion = origenURL+"/AdminBanners/getImagesE.sp" } $.ajax({ type : "POST", url : direccion, cache : false, //modificar cinta y class success : function(dataResponse) { dataResponse.forEach(function(imagen,index){ console.log(imagen); let divCarrusel = $("
    ").addClass('carousel-item'); let srcImg=pathLogo+'/BannersMkt/'+$.trim(imagen.nombre_campania)+'/'+$.trim(imagen.nombre_imagen) let classCinto= $.trim(imagen.nombre_template.slice(1)); let numeroCinto=$.trim(imagen.nombre_template.charAt(0)); const baner=''+ ''+ ''+ '
    '+ '

    '+imagen.texto.split('<').join('<').split('>').join('>')+'

    ' '
    '+ '
    '; divCarrusel.append(baner); $("#carousel-inner-home").append(divCarrusel); }); if ($('#carrusel-home .carousel-item').length !=0){ $('#carrusel-home .carousel-item').first().addClass('active'); $('#carrusel-home').show(''); } }, error : function(XMLHttpRequest, textStatus, errorThrown) { console.log('FALLA errorThrown:' + errorThrown); } }); } //Puntaje popup function muestraPuntajeCatalogo(puntajes,container){ if( $.isEmptyObject(puntajes)){ return; } puntajes.puntajeComen.forEach(function(value) { var itemNum = value.itemNum; console.log(itemNum); var puntajeResumen = $('.puntajeResumen[data-itemNum="'+itemNum+'"]'); if(container!=null){ puntajeResumen = container.find('.puntajeResumen[data-itemNum="'+itemNum+'"]'); } if(!puntajeResumen.length){ return; } console.log('Puntaje valido'); var puntaje = value.suma/value.numComentarios; var numComen = value.numComentarios; if(numComen>=100){ numComen="+100"; } puntajeResumen.find('.starCard .fa-star').slice(0,Math.floor(puntaje)).addClass('text-warning'); puntajeResumen.find('.btnPopover i').after("("+numComen+")"); if(puntaje>Math.floor(puntaje)){ var residuo = puntaje -Math.floor(puntaje); puntajeResumen.find('.starCard .fa-star').not('.text-warning').first().addClass('text-warning-half'); puntajeResumen.find('.text-warning-half').css('background',' linear-gradient(to right, #ffc107 '+residuo*100+'%, #6c757d 5%)').css('-webkit-background-clip',' text'); } creaPopComentarios(puntajeResumen.find('.btnPopover'),puntajeResumen.find('.popover-coment'),numComen,puntaje,value.comentPorPuntaje[0]) puntajeResumen.show(); if(!puntajeResumen.hasClass('position-relative')){ puntajeResumen.addClass('d-flex'); } }); } function creaPopComentarios(popoverActivador,popoverBox,numComen,puntaje,comentPorPuntaje){ popoverBox.find('.titilePop').text('Comentarios totales: '+"("+numComen+")"); popoverBox.find('.starPop .fa-star').slice(0,Math.floor(puntaje)).addClass('text-warning'); popoverBox.find('.promedioPop').text(puntaje.toFixed(1)+' de 5'); if(puntaje>Math.floor(puntaje)){ //medias estrellas var residuo = puntaje -Math.floor(puntaje); popoverBox.find('.starPop .fa-star').not('.text-warning').first().addClass('text-warning-half'); popoverBox.find('.text-warning-half').css('background',' linear-gradient(to right, #ffc107 '+residuo*100+'%, #6c757d 5%)').css('-webkit-background-clip',' text'); } var star = comentPorPuntaje.reverse(); popoverBox.find('.progresComent').each(function(key){ porcent = star[key]*100/numComen; $(this).find('.progress-bar').css('width',porcent+'%'); $(this).find('.numStar').text(star[key]); }); var popoverActivador = popoverActivador[0]; var popover = new bootstrap.Popover(popoverActivador, { html: true, container: popoverActivador, placement:"bottom", trigger:'click', content: popoverBox }); } function creaMapaCatalogo(lineaNeg,nivelNodo,idNodo,origenURL){ var arbol = JSON.parse(sessionStorage.getItem('lineasUF')); var lineaClave=""; $.each(arbol.lineas, function(key, value) { if(value.clave==lineaNeg){ $('#lineaMapa').text(value.descripcion).attr('href',origenURL+'/busquedaEnArbolMs.sp?isPaginacion=1&pageNumber=1&nivelNodo=0&idNodo='+value.id+'&lineaNeg='+value.clave); lineaClave=value.clave; } if(nivelNodo=='1'){ $.each(value.hijos,function(key, value) { if(value.id==idNodo){ $('#lineaMapa').after(' > '); $('#familiaMapa').text(value.descripcion).attr('href',origenURL+'/busquedaEnArbolMs.sp?isPaginacion=1&pageNumber=1&nivelNodo=1&idNodo='+value.id+'&lineaNeg='+lineaClave); } }); } else if(nivelNodo=='2'){ $.each(value.hijos,function(key, value) { var nombre = value.descripcion; var idFam=value.id; $.each(value.hijos,function(key, value) { if(value.id==idNodo){ $('#lineaMapa').after(' > '); $('#familiaMapa').text(nombre).attr('href',origenURL+'/busquedaEnArbolMs.sp?isPaginacion=1&pageNumber=1&nivelNodo=1&idNodo='+idFam+'&lineaNeg='+lineaClave).after(' > '); $('#subFamiliaMapa').text(value.descripcion).attr('href',origenURL+'/busquedaEnArbolMs.sp?isPaginacion=1&pageNumber=1&nivelNodo=2&idNodo='+value.id+'&lineaNeg='+lineaClave); } }); }); } }); formatearTexto($('#busquedaArbol a')); } function predictivoArbol(jsonPredictivo,busqueda,nodo,clave,linea){ var limite = 5; if(jsonPredictivo.length >=limite){ return; }else{ $.each(nodo, function(key, value){ textElement=value.descripcion; if(value.nivel==0){ clave=value.clave; linea = "En "+ formatearTextoString(textElement); }else if(value.nivel==1) { var lineaAux=linea +" >"+ formatearTextoString(textElement); } if (textElement.toLowerCase().indexOf(busqueda.toLowerCase()) === 0 && jsonPredictivo.length "+nuevaCadena; if(value.nivel==0){ var lineaAux=""; } else if(value.nivel==2){ var lineaAux=linea; } var aux = { "label": nuevaCadena, "value": textElement, "url": "/busquedaEnArbolMs.sp?isPaginacion=1&pageNumber=1&nivelNodo="+value.nivel+"&idNodo="+value.id+"&lineaNeg="+clave, "item":false, "linea":lineaAux } jsonPredictivo.push(aux); } if(value.hijos.length>0){ if(value.nivel ==0){ predictivoArbol(jsonPredictivo,busqueda,value.hijos,clave,linea); } else{ predictivoArbol(jsonPredictivo,busqueda,value.hijos,clave,lineaAux); } } }); } } function getLineasPrincipales(){ $.ajax({ url: $('#general').attr('origenURL') + "/getLineasPrincipales.sp", data: { custNum: sessionStorage.getItem('custNum') }, cache: false, async: false, success : function(dataResponse) { $('#lineasPrincipales').html(dataResponse); formatearTexto($('.lineaPrincipalText')); origenURL=$('#general').attr('origenURL'); $('.linea__card').each(function(){ var arbol = JSON.parse(sessionStorage.getItem('lineasUF')); objLinea = $(this); $.each(arbol.lineas, function(key, value) { if(value.clave==objLinea.data('clave')){ url = origenURL+"/busquedaEnArbolMs.sp?isPaginacion=1&pageNumber=1&nivelNodo=0&idNodo="+value.id+"&lineaNeg="+value.clave; objLinea.attr('href',url); } }); }); }, error : function(XMLHttpRequest, textStatus, errorThrown) { console.log("Sin lineas principales"+errorThrown); } }); } function getPromocionesUF(clienteNum){ $.ajax({ url: $('#general').attr('origenURL') + "/carrusel/carruselPromocionesUF.sp", data: { custNum: sessionStorage.getItem('custNum'), clienteNum:clienteNum }, type:'POST', cache: false, async: false, success : function(dataResponse) { $('#promocionesUF').html(dataResponse); }, error : function(XMLHttpRequest, textStatus, errorThrown) { console.log("Promociones"+errorThrown); } }); } function agregarArticulo(btn,btnCart){ console.log('asas'); const btnData = $(btn).data(); const myCartBtn = $(btnCart); myCartBtn.data(btnData); myCartBtn.click(); myCartBtn.removeData(Object.keys(btnData)); }