try{ //redireccionamientos if (document.location.href.toLowerCase().indexOf("mi-musimundo/search") != -1) { try { const __queryString = window.location.search; const __urlParams = new URLSearchParams(__queryString); fetch( "https://u.braindw.com/els/musimundoapi?ft="+ __urlParams.get('text')+"&qt=1&sc=none&refreshmetadata=false&exclusive=0", { credentials: "include", method: "GET", } ) .then(function (resp) { return resp.text(); }) .then(function (data) { data = JSON.parse(data); console.log('search',data.hits.total); if(data.hits.total==0) { window.location.href = '/search?text='+ __urlParams.get('text'); console.log('redirect') } }) .catch(function (ex) {console.log('red',ex); }); } catch (e) { } } if (document.location.href.toLowerCase().indexOf("search?text=sucursales") != -1) { window.location = '/sucursales'; } // if (document.location.href.toLowerCase().indexOf("search?text=cyber") != -1 || // document.location.href.toLowerCase().indexOf("search?text=ciber") != -1 || // document.location.href.toLowerCase().indexOf("search?text=descuentos") != -1 || // document.location.href.toLowerCase().indexOf("search?text=ofertas") != -1 || // document.location.href.toLowerCase().indexOf("search?text=promociones") != -1 || // document.location.href.toLowerCase().indexOf("search?text=hot sale") != -1 || // document.location.href.toLowerCase().indexOf("search?text=hot%20sale") != -1 || // document.location.href.toLowerCase().indexOf("search?text=black friday") != -1 || // document.location.href.toLowerCase().indexOf("search?text=black%20friday") != -1 || // document.location.href.toLowerCase().indexOf("search?text=monday") != -1) { // window.location = '/ofertas/cybermonday/c/101020'; // } // if (document.location.href.toLowerCase().indexOf("search?text=Black Friday") != -1 || // document.location.href.toLowerCase().indexOf("search?text=black") != -1 || // document.location.href.toLowerCase().indexOf("search?text=black friday") != -1 || // document.location.href.toLowerCase().indexOf("search?text=Friday") != -1 || // document.location.href.toLowerCase().indexOf("search?text=friday") != -1 || // document.location.href.toLowerCase().indexOf("search?text=ofertas") != -1 || // document.location.href.toLowerCase().indexOf("search?text=descuentos") != -1 || // document.location.href.toLowerCase().indexOf("search?text=promociones") != -1 || // document.location.href.toLowerCase().indexOf("search?text=Black") != -1 || // document.location.href.toLowerCase().indexOf("search?text=Black friday") != -1) { // window.location = '/ofertas/black-friday/c/300139'; // } // if (document.location.href.toLowerCase().indexOf("search?text=Navidad") != -1 || // document.location.href.toLowerCase().indexOf("search?text=navidad") != -1 || // document.location.href.toLowerCase().indexOf("search?text=Regalos de navidad") != -1 || // document.location.href.toLowerCase().indexOf("search?text=regalos de navidad") != -1 || // document.location.href.toLowerCase().indexOf("search?text=Regalos para navidad") != -1 || // document.location.href.toLowerCase().indexOf("search?text=regalos para navidad") != -1 || // document.location.href.toLowerCase().indexOf("search?text=Regalos para navidad económicos") != -1 || // document.location.href.toLowerCase().indexOf("search?text=regalos para navidad económicos") != -1 || // document.location.href.toLowerCase().indexOf("search?text=regalos") != -1 || // document.location.href.toLowerCase().indexOf("search?text=Regalos") != -1|| // document.location.href.toLowerCase().indexOf("search?text=Regalos para navidad niños") != -1|| // document.location.href.toLowerCase().indexOf("search?text=regalos para navidad niños") != -1) { // window.location = '/ofertas/los-mejores-regalos-para-navidad-descuentos/c/3001258'; // } /* * INICIO: #3906 Musimundo: redirigir Palabras clave día del niño 2024 a /3001367 - zendesk 4818 */ // Lista de palabras a redirigir let listWordSearchToRedirect = [ "Día del niño", "Día de la niñez", "Dia del niño", "Regalos día del niño", "Regalos para el día del niño", "Niñez", "Niño", "Niña", "Ofertas y promociones para el Día del Niño", "Ofertas día del niño", "Ofertas en regalos día del niño", "Día del niño regalos", "Ofertas electro día del Niño", "Electro día del Niño ofertas", "Regalos día del Niño 2024", "Regalos tecnológicos Día del Niño", "Descuentos electro Día del Niño", "Regalos tecnológicos Día del Niño", "Regalos tecno dia del niño", "Consola ps5", "play station 5", "ps5", "joystick", "juegos de ps", "juegos para play", "juegos para ps5" ]; /* * Normalizamos el texto de busqueda (quitamos acentos y caracteres) y pasamos a lowercase * https://es.stackoverflow.com/questions/62031/eliminar-signos-diacr%C3%ADticos-en-javascript-eliminar-tildes-acentos-ortogr%C3%A1ficos */ let wordToCheck = decodeURI(document.location.search.replace("?text=", "")).normalize('NFD').replace(/[\u0300-\u036f]/g,"").toLowerCase(); if (listWordSearchToRedirect.find(wordTC => wordTC.normalize('NFD').replace(/[\u0300-\u036f]/g,"").toLowerCase() == wordToCheck)?.length > 0) { window.location = '/ofertas/los-mejores-regalos-dia-de-la-ninez/c/3001367'; } /* * FIN: #3906 Musimundo: redirigir Palabras clave día del niño 2024 a /3001367 - zendesk 4818 */ /* * INICIO: #4021 Musimundo: redirigir Palabras claves día de la madre 2024 - Zendesk 5253 */ // Lista de palabras a redirigir let listWordSearchToRedirectDiaMadre = [ "Día de la madre", "Día de la Madre", "Dia de las madres", "Día de mamá", "Regalos para mamá", "Regalos para madres", "Los mejores regalos para mamá", "Ofertas para día de la madre", "Ofertas para mamá", "Ideas regalos día de la madre", "Ideas de regalos para mamá", "Ofertas para regalar a mamá", "Regalos tecnológicos día de la madre", "Regalos tecno para mamá" ]; /* * Normalizamos el texto de busqueda (quitamos acentos y caracteres) y pasamos a lowercase * https://es.stackoverflow.com/questions/62031/eliminar-signos-diacr%C3%ADticos-en-javascript-eliminar-tildes-acentos-ortogr%C3%A1ficos */ let wordToCheckDiaMadre = decodeURI(document.location.search.replace("?text=", "")).normalize('NFD').replace(/[\u0300-\u036f]/g,"").toLowerCase(); if (listWordSearchToRedirectDiaMadre.find(wordTC => wordTC.normalize('NFD').replace(/[\u0300-\u036f]/g,"").toLowerCase() == wordToCheckDiaMadre)?.length > 0) { window.location = '/ofertas/los-mejores-regalos-para-mama/c/3001298'; } /* * FIN: #4021 Musimundo: redirigir Palabras claves día de la madre 2024 - Zendesk 5253 */ } catch{} var _bdwProductCardCategoriesCodes = ''; var ProductNameNew = ""; var bdwMobile = { Android: function () { return navigator.userAgent.match(/Android/i); }, BlackBerry: function () { return navigator.userAgent.match(/BlackBerry/i); }, iOS: function () { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Opera: function () { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function () { return navigator.userAgent.match(/IEMobile/i); }, any: function () { return (bdwMobile.Android() || bdwMobile.BlackBerry() || bdwMobile.iOS() || bdwMobile.Opera() || bdwMobile.Windows()); } }; if (bdwMobile.any() !== null) { var grandfather = document.querySelector(".yCmsContentSlot.Section4"); if (grandfather) { var child = document.createElement("div"); child.className = "bdw-juga-en-serio"; var father = document.createElement("div"); father.className = "content"; father.appendChild(child); grandfather.appendChild(father); } } function showPopup() { $("#cboxOverlay").append( " " + ' " ); } let timer; const runTimer = () => { timer = window.setTimeout( () => { $("#braindw_loader").hide(); $("#cboxOverlay").hide(); }, 5000); } if (location.href.indexOf("losmasvendidos") > -1) { showPopup(); $("#cboxOverlay").show(); $("#braindw_loader").show(); runTimer(); } function braindwCloseLoader() { $("#braindw_loader").hide(); $("#cboxOverlay").hide(); } function BraindwLoadEvent() { $("._braindwTriggerClick").unbind("click"); $("._braindwTriggerClick").attr("onclick", "").unbind("click"); $("._braindwTriggerClick").one("click", function (event) { var bdwAttrCat = "banner"; var bdwAttrEti = "default"; var bdwAttrSku = ""; try { bdwAttrCat = $(this).attr("bw_section"); } catch (err) {} try { bdwAttrEti = $(this).attr("bw-title"); } catch (err) {} try { bdwAttrSku = $(this).attr("bw-code"); } catch (err) {} BraindwPushEvent(bdwAttrCat, bdwAttrEti, bdwAttrSku); }); } function BraindwPushEvent(cat, eti, sku) { try { dataLayer.push({ event: "ga-braindw", eventCategory: "ga-braindw", eventAction: "click-" + cat, eventLabel: sku, }); } catch (err) {} } function bdwGetSucCookie() { var companyDL = "amba"; try { if (dataLayer[0].app != null && dataLayer[0].app != undefined) { companyDL = dataLayer[0].app.zonaCatalogo; if (companyDL.indexOf("ASIGNAR") > -1) { if ( dataLayer[0].app.zonaFacturacion != undefined && dataLayer[0].app.zonaFacturacion.toLowerCase() != "" ) { companyDL = dataLayer[0].app.zonaFacturacion.toLowerCase(); if ( dataLayer[0].app.zonaFacturacion.toLowerCase() != "emsa" && dataLayer[0].app.zonaFacturacion.toLowerCase() != "carsa" ) companyDL = "amba"; } else companyDL = "amba"; } } } catch (e) { console.log(e); } if (companyDL.toLowerCase() == "comun") companyDL = "amba"; return companyDL; } function GetFoundWords() { var t = "", e = /(<([^>]+)>)/gi, n = document.body.innerText; n = n.replace(e, " ").toLowerCase(); var r = "{wordstofind}".split(","); for (i = 0; i < r.length; i++) - 1 != n.indexOf(r[i]) && (t += r[i] + ","); return t; } function braindwLoadScript(t, e, n) { if (window.location.href.toLowerCase().indexOf('/accstorefront-stg.musimundo.com/') > 0) { var url = "https://accstorefront-stg.musimundo.com/store-location"; }else{ var url = "https://www.musimundo.com/store-location"; } $.ajax({ url: url, dataType: "json", cache: false, async: true, timeout: 9000, data: "", type: "GET", success: function (data) { //data = jQuery.parseJSON(data); var state = data.geoZone.provincia.value; try { bdwGetProvinciaOc8ne(state); localStorage.setItem('bdw_user_state', state); localStorage.setItem('bdwCompany', bdwGetSucCookie()); //braindw_pushInfo(); } catch (e) {} if(window.location.href.toLowerCase().indexOf('/c-blocked/') > 0) { var r = ($guadex = function (t) { r._.push(t); }), bdwsc = bdwGetSucCookie(), a = (r.s = t.createElement(e)), o = t.getElementsByTagName(e)[0]; (r.set = function (t) { r.set._.push(t); }), (r._ = []), (r.set._ = []), (a.async = !0), a.setAttribute("charset", "utf-8"), (a.src = _SURLBNDW + "/tracking/track?HASH=musimundo_hybris_produccion&branchOffice=" + bdwsc + "&wordsfound=" + GetFoundWords() + "&buyer={CLIENT.BUYER}&name=&lastname=&gender=&country=&state=" + state + "&city=&minify=0&email=&u=" + escape(window.location) + "&hs=" + new Date()), (r.t = +new Date()), (a.type = "text/javascript"), o.parentNode.insertBefore(a, o); } else if(window.location.href.toLowerCase().indexOf('login') ==-1 && window.location.href.toLowerCase().indexOf('checkout') ==-1 && window.location.href.toLowerCase().indexOf('order') ==-1 && window.location.href.toLowerCase().indexOf('account') ==-1) { var source = ""; if (window.location.href.toLowerCase().indexOf('/accstorefront-stg.musimundo.com/') > 0) { source = "https://storage.cdn.braindw.com/musimundo_hybris_produccion/script/files/2023/08/24/mc_stg.js"; }else{ //source = "https://storage.cdn.braindw.com/musimundo_hybris_produccion/script/files/2023/08/25/mc_3.js"; //source="https://storage.cdn.braindw.com/musimundo_hybris_produccion/script/files/2023/08/26/mc_4.js"; source = "https://storage.cdn.braindw.com/musimundo_hybris_produccion/script/files/2023/12/12/mc_5.js"; } var r = ($guadex = function (t) { r._.push(t); }), bdwsc = bdwGetSucCookie(), a = (r.s = t.createElement(e)), o = t.getElementsByTagName(e)[0]; (r.set = function (t) { r.set._.push(t); }), (r._ = []), (r.set._ = []), (a.async = !0), a.setAttribute("charset", "utf-8"), (a.src = source), (r.t = +new Date()), (a.type = "text/javascript"), o.parentNode.insertBefore(a, o); } }, error: function (xhr, ajaxOptions, thrownError) {}, }); } function braindNdwGetProperty(t) { if (t.toLowerCase() == "og:price") { try { var sprice = $("div.prod-price-container span.price-e.conpromo:visible") .first() .text() .trim(); if (sprice == "") { sprice = $("div.prod-price span.price-e:visible").first().text().trim(); } if (sprice == "") { if ( $(".normal") .find(".priceNumberAlignRightThree") .first() .text() .trim() != "" ) return $(".normal") .find(".priceNumberAlignRightThree") .first() .text() .trim(); else return $(".internet") .find(".priceNumberAlignRightTwo") .first() .text() .trim(); } else { if (sprice.indexOf("$") == -1 && sprice.length > 0) sprice = "$" + sprice; } return sprice; } catch (err) { return ""; } } else if (t.toLowerCase() == "og:pricesale") { try { var sprices = $("div.prod-price-container span.price-mas:visible") .first() .text() .trim(); if (sprices === "") if ( $(".normal") .find(".priceNumberAlignRightThree") .first() .text() .trim() != "" ) return $(".internet") .find(".priceNumberAlignRightTwo") .first() .text() .trim(); if (sprices.indexOf("$") == -1 && sprices.length > 0) sprices = "$" + sprices; return sprices; } catch (err) { return ""; } } else if (t.toLowerCase() == "og:promotion") { try { var description = $( ".prod-price-container a.product-promo-label-big-link:visible" ) .first() .text() .trim(); if (description === "") return $(".exclusivo").first().text(); return description; } catch (err) { return ""; } } else if (t.toLowerCase() == "og:brand") { try { $(".list_atributes li").each(function () { var a = $(this).find("span").text(); if (a.toLowerCase().indexOf("marca:") > -1) { return a.trim().split(":")[1].trim(); } }); return ""; } catch (err) { return ""; } } else if (t.toLowerCase() == "og:categoriescodes") { try { var cl = ""; var linkListCategories = document .getElementById("breadcrumb") .getElementsByTagName("a"); for (var ii = 0; ii < linkListCategories.length; ii++) { var a = $(linkListCategories[ii]).attr("href").split("/")[ $(linkListCategories[ii]).attr("href").split("/").length - 1 ]; cl += a + ","; } return cl; } catch (err) { return ""; } } var e = document.getElementsByTagName("meta"); for (i = 0; i < e.length; i++) if ( null != e[i].getAttribute("property") && e[i].getAttribute("property").toLowerCase() == t.toLowerCase() ) { if (e[i].getAttribute("content") != "") return e[i].getAttribute("content"); else { try { if (t.toLowerCase() == "og:title") { if (document.getElementById("GA_item_name").value != "") return document.getElementById("GA_item_name").value; else return skuJson_0.skus[0].skuname; } else if (t.toLowerCase() == "og:image") { return skuJson_0.skus[0].image; } else if (t.toLowerCase() == "og:url") { return $("link[rel=canonical]").attr("href").replace('"', ""); } else if (t.toLowerCase() == "og:category") { return ""; } else if (t.toLowerCase() == "og:categorycode") { return ""; } else if (t.toLowerCase() == "og:brand") { return ""; } } catch (ex) {} } } return ""; } var _HASHBNDW = "musimundo_hybris_produccion", _PROTOCOLBNDW = "", _URLBNDW2 = "https://s2.braindw.com", _URLBNDW = "", _SURLBNDW = "//static-s.braindw.com"; var bdwUsuarioProvincia = ""; switch (window.location.protocol) { case "https:": _PROTOCOLBNDW = "https:"; break; case "http:": default: _PROTOCOLBNDW = "http:"; } (_URLBNDW = _PROTOCOLBNDW + "//s.braindw.com"), braindwLoadScript(document, "script", escape(window.location)), (window.onpopstate = function (t) { braindwLoadScript(document, "script", escape(document.location)); }), (function (t, e) { var n = ($braindw = function (t) { n._.push(t); }), r = (n.s = t.createElement(e)), a = t.getElementsByTagName(e)[0]; (n.set = function (t) { n.set._.push(t); }), (n._ = []), (n.set._ = []), (r.async = !0), r.setAttribute("charset", "utf-8"); var o = encodeURIComponent(braindNdwGetProperty("og:title")), i = escape(braindNdwGetProperty("og:image")), s = escape(braindNdwGetProperty("og:url")), c = escape(braindNdwGetProperty("og:category")); cc = escape(braindNdwGetProperty("og:categorycode")); bd = escape(braindNdwGetProperty("og:brand")); if (bd == "") { try { $(".list_atributes li").each(function () { var a = $(this).find("span").text(); if (a.toLowerCase().indexOf("marca:") > -1) { bd = a.trim().split(":")[1].trim(); } }); } catch (err) {} } po = escape(braindNdwGetProperty("og:price")); ps = escape(braindNdwGetProperty("og:pricesale")); pm = escape(braindNdwGetProperty("og:promotion")); pol = ""; if (ps != "" && ps.length > 1 && po != "") { pol = po; po = ps; } else { pol = ""; ps = ""; } if (i.indexOf("/logo.png") > -1) { o = ""; i = ""; } categoriescodes = braindNdwGetProperty("og:categoriescodes"); codprod = escape(braindNdwGetProperty("og:codeproduct")); if (codprod == "") { if ($(".mus-pro-code").length > 0) { codprod = $(".mus-pro-code").html().trim(); } else if ($("#product-details-panel-app .product-details-panel__code").length > 0) { codprod = $("#product-details-panel-app .product-details-panel__code").html().trim(); } } if (s == "") s = document.URL.replace('"', ""); if (i) { i = $(".img--container img").attr("src"); } if (cc == "") { $("#breadcrumb li a").each(function (i, item) { if ($(this).attr("href") != "") { if (i == 0) cpcode = $(this).attr("href").split("/")[ $(this).attr("href").split("/").length - 1 ]; else if (i == 1) cc = $(this).attr("href").split("/")[ $(this).attr("href").split("/").length - 1 ]; } }); } if (o == "") o = $(".mus-pro-name.strong").text().trim(); if (o == "" && $("#product-details-panel-app .product-details-panel__name").length > 0) o = $("#product-details-panel-app .product-details-panel__name").html().trim(); if (bd == "") bd = $(".mus-pro-brand span").last().text(); if (bd == "" && $("#product-details-panel-app .product-details-panel__brand #product_brand span").length > 0) bd = $("#product-details-panel-app .product-details-panel__brand #product_brand span").html().trim(); if ( document.URL == "https://www.musimundo.com/" || document.URL.indexOf("/p/") == -1 ) s = ""; s = s.replace('"', "").replace("%22", ""); if (s != "") { if (s.toLowerCase().indexOf("home.aspx") == -1) { var currentUrlCapture = _URLBNDW2 + "/tracking/capture?HASH=" + _HASHBNDW + "&og:title=" + o + "&og:image=" + i + "&og:url=" + s + "&og:category=" + c + "&og:categorycode=" + cc + "&og:codeproduct=" + codprod + "&og:brand=" + bd + "&og:price=" + po + "&og:pricesale=" + ps + "&og:priceold=" + pol + "&og:promotion=" + pm + "&og:categoriescodes={categoriescodes}" + "&hs=" + new Date(); localStorage.setItem('bdwSearchCode', codprod); BdwProcessProductCardCapture(codprod,currentUrlCapture,categoriescodes); console.log('capturepersistencia'); getVisitedProducts(); //currentUrlCapture = currentUrlCapture.replace('{categoriescodes}',categoriescodes) // (r.src =currentUrlCapture), // (n.t = +new Date()), // (r.type = "text/javascript"), // "" != o && "" != i && a.parentNode.insertBefore(r, a); } } })(document, "script"); function BraindwDisableDay() { var t = _URLBNDW + "/tracking/", e = new XMLHttpRequest(); e.open("GET", t, !0), (e.onreadystatechange = function () { 4 == e.readyState && 200 == e.status && console.log(e.responseText); }), e.send("HASH=" + _HASHBNDW); } function braindwGetUrlParameter(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); var results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } function braindw_getProduct() { let result = null; try { let ProductCode = ""; let Title = ""; let PriceOnline = ""; let Brand = ""; let Category = ""; let CategoryCode = ""; let UrlImage = ""; let UrlProduct = window.location.href; if (UrlProduct.indexOf("?") > -1) { UrlProduct = UrlProduct.split("?")[0]; } let sku_current = document.getElementsByClassName("mus-pro-code"); if (sku_current && sku_current[0]) { ProductCode = sku_current[0].textContent.trim(); } else if ($("#product-details-panel-app .product-details-panel__code").length > 0) { ProductCode = $("#product-details-panel-app .product-details-panel__code").html().trim(); } let tit_current = document.getElementsByClassName("mus-pro-name"); if (tit_current && tit_current[0]) { Title = tit_current[0].textContent.trim(); } else if ($("#product-details-panel-app .product-details-panel__name").length > 0) { Title = $("#product-details-panel-app .product-details-panel__name").html().trim(); } let internet = document.getElementsByClassName("mus-pro-price-number"); if ($("#product-details-panel-app .product-price-panel-pdp__price").length > 0 ) { PriceOnline = $("#product-details-panel-app .product-price-panel-pdp__price").html().trim().replace(".", "") .replace("$", "") .replace(",", "."); } else if (internet && internet[0]) { let spnTextContent = internet[0].textContent; PriceOnline = spnTextContent .substr(spnTextContent.lastIndexOf("$") + 1) .trim(); } let listAttrs = document.getElementsByClassName("mus-pro-brand"); if (listAttrs && listAttrs[0]) { Brand = listAttrs[0].textContent.trim(); } else if ($("#product-details-panel-app .product-details-panel__brand #product_brand span").length > 0 ) { Brand = $("#product-details-panel-app .product-details-panel__brand #product_brand span").html().trim(); } if (document.getElementById("primary_image") != null) { let metaUrl = document.getElementById("primary_image").getElementsByTagName("img")[0].src; if (metaUrl) { UrlImage = metaUrl; if (metaUrl.indexOf("https") == -1) //UrlImage = "https://www.musimundo.com" + metaUrl; UrlImage = UrlImage.replace('http://', 'https://'); } } if (document.getElementById("breadcrumb") != null) { let linkListCategories = document.getElementById("breadcrumb").getElementsByTagName("a"); if (linkListCategories.length > 1) { CategoryCode = linkListCategories[1].href.split("/")[ linkListCategories[1].href.split("/").length - 1 ]; Category = linkListCategories[1].text; } } if ( ProductCode && Title && PriceOnline && Brand && Category && CategoryCode && UrlImage && UrlProduct ) { result = { ProductCode: ProductCode, Title: Title, PriceOnline: PriceOnline, Brand: Brand, Category: Category, CategoryCode: CategoryCode, UrlImage: UrlImage, UrlProduct: UrlProduct, }; } } catch (e) { console.log("braindw_getProduct error ", e); } return result; } function braindw_getCategory() { let result = null; var braindw_url = document.URL; if ( braindw_url.indexOf("/p/") > -1 || braindw_url.indexOf("/cart") > -1 || braindw_url.indexOf("/checkout/orderConfirmation") > -1 ) return result; try { let Title = ""; let CategoryCode = ""; if (document.getElementById("breadcrumb") != null) { let linkListCategories = document.getElementById("breadcrumb").getElementsByTagName("a"); if (linkListCategories.length > 1) { CategoryCode = linkListCategories[1].href.split("/")[ linkListCategories[1].href.split("/").length - 1 ]; Title = linkListCategories[1].text; } } if (Title && CategoryCode) { result = { Title: Title, CategoryCode: CategoryCode, }; } } catch (e) { console.log("braindw_getCategory error ", e); } return result; } function braindw_getCatOpened() { let result = null; var braindw_url = document.URL; let CartNumber = ""; let Items = []; if (braindw_url.indexOf("/cart") != -1) { CartNumber = ""; Items = []; try { let productRows = document .querySelectorAll("ul.mus-cart-items")[0] .getElementsByTagName("li"); if (productRows && productRows.length > 0) { for (let i = 0; i < productRows.length; i++) { let cartItem = {}; let inpQuantity = ""; var qtyprod = productRows[i] .getElementsByClassName("qty")[0] .getElementsByTagName("option"); for (var brandw_i = 0; brandw_i < qtyprod.length; brandw_i++) { if (qtyprod[brandw_i].selected) { inpQuantity = qtyprod[brandw_i].text; break; } } let productTitle = productRows[i] .getElementsByClassName("mus-pro-name")[0] .textContent.trim(); let productCode = productRows[i] .getElementsByClassName("mus-pro-code")[0] .textContent.trim(); let imgUrl = productRows[i] .getElementsByClassName("mus-pro-thumb fleft")[0] .getElementsByTagName("img")[0] .getAttribute("src"); // Payment let payments = ""; //$(productRows[i]).find('.pagandocon'); // fata //let pric = $($('.mus-pro-total')[i]).text().trim().replace('$', ''); let pric = productRows[i] .getElementsByClassName("mus-pro-total")[0] .textContent.trim() .replace("$", ""); cartItem.ProductTitle = productTitle.trim(); cartItem.ProductCode = productCode.trim(); cartItem.ProductUrlImage = imgUrl; cartItem.Event = "Load"; cartItem.ProductQuantity = inpQuantity; cartItem.ProductPrice = pric; Items.push(cartItem); } } result = { CartNumber: CartNumber, Items: Items, }; } catch (e) { console.log("braindw_getCatOpened", e); } } else { if (braindw_url.indexOf("/checkout/multi/delivery-pickup/") != -1) { CartNumber = ""; Items = []; try { let productRows = document .getElementsByClassName("mus-side-cart-items")[0] .getElementsByTagName("li"); if (productRows && productRows.length > 0) { for (let i = 0; i < productRows.length; i++) { let cartItem = {}; let inpQuantity = "1"; let obP = productRows[i].getElementsByTagName("p"); for (let b = 0; b < obP.length; b++) { if (obP[b].innerText.toLowerCase().indexOf("unidad") != -1) { inpQuantity = obP[b].innerText.toLowerCase(); inpQuantity = inpQuantity .replace("unidades", "") .replace("unidad", "") .trim(); } } var qtyprod = "1"; let productTitle = productRows[i] .getElementsByClassName("mus-pro-name")[0] .textContent.trim(); let productCode = productRows[i] .getElementsByClassName("mus-pro-code")[0] .textContent.trim(); let imgUrl = productRows[i] .getElementsByTagName("img")[0] .getAttribute("src"); //let pric = $($('.mus-pro-total')[i]).text().trim().replace('$', '') let pric = productRows[i] .getElementsByClassName("mus-pro-total")[0] .textContent.trim() .replace("$", ""); cartItem.ProductTitle = productTitle.trim(); cartItem.ProductCode = productCode.trim(); cartItem.ProductUrlImage = imgUrl; cartItem.Event = "Load"; cartItem.ProductQuantity = inpQuantity; cartItem.ProductPrice = pric; Items.push(cartItem); } } result = { CartNumber: CartNumber, Items: Items, }; } catch (e) { console.log("braindw_getCatOpened", e); } } } return result; } function braindw_getCatClosed() { let result = null; var braindw_url = document.URL; if (braindw_url.toLowerCase().indexOf("/checkout/orderconfirmation") == -1) return result; try { let CartNumber = braindw_url.split("/")[braindw_url.split("/").length - 1]; let Items = []; let productRows = document .querySelectorAll("ul.mus-cart-items")[0] .getElementsByTagName("li"); if (productRows && productRows.length > 0) { for (let i = 0; i < productRows.length; i++) { let cartItem = {}; let inpQuantity = ""; inpQuantity = productRows[i] .getElementsByClassName("mus-pro-stock right")[0] .textContent.trim() .split(" ")[0]; let productTitle = productRows[i] .getElementsByClassName("mus-pro-name")[0] .textContent.trim(); let productCode = productRows[i] .getElementsByClassName("mus-pro-code")[0] .textContent.trim(); let imgUrl = productRows[i] .getElementsByClassName("mus-pro-thumb")[0] .getElementsByTagName("img")[0] .getAttribute("src"); // Payment let payments = ""; //$(productRows[i]).find('.pagandocon'); // fata let pric = $($(".mus-pro-total")[i]).text().trim().replace("$", ""); cartItem.ProductTitle = productTitle.trim(); cartItem.ProductCode = productCode.trim(); cartItem.ProductUrlImage = imgUrl; cartItem.Event = "Close"; cartItem.ProductQuantity = inpQuantity; cartItem.ProductPrice = pric; Items.push(cartItem); } } result = { CartNumber: CartNumber, Items: Items, }; } catch (e) { console.log("braindw_getCatClosed", e); } return result; } function braindw_getSearch() { let result = null; try { var braindw_url = document.URL; if (braindw_url.toLowerCase().indexOf("/search") === -1) return result; result = { searchterm: braindwGetUrlParameter("text"), }; } catch (e) { console.log(e); } return result; } function braindw_countCoupon() { var countCoupon = 0; let isHome = new RegExp(/.*?:\/\/(.*).musimundo.com\/$/); if (isHome.test(document.URL)) { if (localStorage.getItem("bdw_count_coupon") === null) { localStorage.setItem('bdw_count_coupon', 1); } else { countCoupon = parseInt(localStorage.getItem("bdw_count_coupon")) + 1; localStorage.setItem('bdw_count_coupon', countCoupon); } } } try { setTimeout("braindw_pushInfo();",1500); braindw_countCoupon(); } catch (e) { console.log("PushInfo>" + e); } let storageEmailKey = 'bdw-user-mail'; function GetEmail() { return localStorage.getItem(storageEmailKey) ?? ''; } function GetSessionDate() { let result = null; try { let SalesChannel = bdwGetSucCookie(); result = { SalesChannel: SalesChannel, }; } catch (e) { console.log('GetSessionDate error ', e); } return result; } _URLBNDW = window.location.protocol + '//s.braindw.com'; function SendPersistency(e, url, user) { let _company = ""; if (localStorage.getItem("bdwCompany") != null && localStorage.getItem("bdwCompany") != undefined) { _company = localStorage.getItem("bdwCompany"); } let _COMPANYHASHBNDW = ""; if (_company == "amba"){ _COMPANYHASHBNDW = "amba_produccion"; } if (_company == "carsa"){ _COMPANYHASHBNDW = "carsa_produccion"; } let n = { emailguest: GetEmail(), dataset: encodeURI(JSON.stringify(e)), page: "", url: (url) ? url : window.location.href.split("?")[0], urlb: `${_URLBNDW}/Script/braindw/${_HASHBNDW}?hs=Sat Apr 21 2018 10:00:38 GMT-0300 (Hora estándar de Argentina)`, BranchOffice: bdwGetSucCookie(), firstName: (typeof user === "undefined") ? "" : user.name, lastName: (typeof user === "undefined") ? "" : user.lastname, document: (typeof user === "undefined") ? "" : user.dni, phoneNumber: (typeof user === "undefined") ? "" : user.phone }; fetch('https://p.braindw.com/Api/Data/Capture', { method: "POST", body: JSON.stringify(n), credentials: 'include', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }) .then((resp) => resp.json()) .then(function (data) { }) .catch(function (ex) { console.log(ex); }); if(_COMPANYHASHBNDW != ""){ let dataJson = { emailguest: GetEmail(), dataset: encodeURI(JSON.stringify(e)), page: "", url: (url) ? url : window.location.href.split("?")[0], urlb: `${_URLBNDW}/Script/braindw/${_COMPANYHASHBNDW}?hs=Sat Apr 21 2018 10:00:38 GMT-0300 (Hora estándar de Argentina)`, BranchOffice: bdwGetSucCookie(), firstName: (typeof user === "undefined") ? "" : user.name, lastName: (typeof user === "undefined") ? "" : user.lastname, document: (typeof user === "undefined") ? "" : user.dni, phoneNumber: (typeof user === "undefined") ? "" : user.phone }; fetch('https://p.braindw.com/Api/Data/Capture', { method: "POST", body: JSON.stringify(dataJson), credentials: 'include', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }) .then((resp) => resp.json()) .then(function (data) { }) .catch(function (ex) { console.log(ex); }); } } function PushTermNotFound(term, display) { try { if (term && term !== '') { let e = { sessionDate: GetSessionDate() }; e.search = { searchterm: term, displayResult: display }; SendPersistency(e); } } catch (e) { console.log('BDW ' + e); } } $(".addToCartButton").click(function (e) { var producto = {}; var url = location.href; var productSelector = $(this).closest(".mus-product-box-out"); var IsFicha = url.indexOf("/p/") !== -1; if (IsFicha) { productSelector = $(this).closest("#productPageDetailsId"); producto = buildProductFicha(productSelector); } else { producto = buildProductCatalogo(productSelector); } var _bndwOb = document.createElement("script"); _bndwOb.async = true; _bndwOb.src = _URLBNDW2 + "/tracking/capture?HASH=" + _HASHBNDW + "&iscart=1&og:title=" + producto.title + "&og:image=" + producto.image + "&og:url=" + url + "&og:category=" + producto.category + "&og:categoriescodes=" + "{categoriescodes}"+//braindNdwGetProperty("og:categoriescodes") + "&og:codeproduct=" + producto.codprod + "&og:brand=" + producto.brand + "&og:price=" + producto.price + "&og:pricesale=" + producto.priceSale + "&og:priceold=" + producto.priceold + "&og:promotion=" + producto.promotion + "&hs=" + new Date(); _bndwOb.charset = "UTF-8"; //document.head.appendChild(_bndwOb); BdwProcessProductCardCapture(producto.codprod,_bndwOb.src,braindNdwGetProperty("og:categoriescodes")); ProductCartAdd(producto.codprod); }); function ProductCartAdd(idProduct) { var skusString = localStorage.getItem('bdw-cartP'); var skuslist = []; if (!skusString) { localStorage.setItem('bdw-cartP', idProduct); } else { skuslist = localStorage.getItem('bdw-cartP').split(','); if (skuslist.findIndex(item => item === idProduct) !== -1) { skuslist.splice(skuslist.findIndex(item => item === idProduct), 1); } skuslist.unshift(idProduct); skuslist = skuslist.slice(0, 30); localStorage.setItem('bdw-cartP', skuslist.toString()); } //Para LastAddToCartBraindw y ListAddToCartBraindw localStorageAddToCartFromListBDW(idProduct); //Para LastAddToCartBraindw y ListAddToCartBraindw } function buildProductCatalogo(element) { return { title: $(element).find(".mus-pro-name").length > 0 ? $(element).find(".mus-pro-name").html().trim() : "", image: $($(element).find(".mus-pro-thumb ")).find("img").length > 0 ? $($(element).find(".mus-pro-thumb ")).find("img").attr("src") : "", category: "", categoryCode: bdwGetSucCookie(), codprod: $(element).find(".mus-pro-code").length > 0 ? $(element).find(".mus-pro-code").html().trim() : "", brand: "", price: $($(element).find(".mus-pro-price-number ")).find("span").length > 0 ? $($(element).find(".mus-pro-price-number ")) .find("span") .html() .trim() : "", priceSale: "", priceold: "", promotion: "", }; } function buildProductFicha(element) { var title = ""; var image = ""; var codprod = ""; var price = ""; if ($(element).find(".mus-pro-name").length > 0) { title = $(element).find(".mus-pro-name").html().trim(); } else if ($("#product-details-panel-app .product-details-panel__name").length > 0) { title = $("#product-details-panel-app .product-details-panel__name").html().trim(); } if ($(element).find(".mus-pro-code").length > 0) { codprod = $(element).find(".mus-pro-code").html().trim(); } else if ($("#product-details-panel-app .product-details-panel__code").length > 0) { codprod = $("#product-details-panel-app .product-details-panel__code").html().trim(); } if ($(element).find(".img--container img").length > 0) { image = $(element).find(".img--container img").attr("src"); } else if ($("#primary_image .img--container img").length > 0) { image = $("#primary_image .img--container img").attr("src"); } if ($(element).find(".mus-pro-quotes-price.strong").length > 0) { price = $(element).find(".mus-pro-quotes-price.strong").html() ; } else if ($("#product-details-panel-app .product-price-panel-pdp__price").length > 0) { price = $("#product-details-panel-app .product-price-panel-pdp__price").html().trim(); } return { title: title, image: image, category: "", categoryCode: bdwGetSucCookie(), codprod: codprod, brand: "", price: price, priceSale: "", priceold: "", promotion: "", }; } function BdwvalidateEmail(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } function BdwCookiePush(email) { if (BdwvalidateEmail(email)) { try { fetch( "https://s.braindw.com/tracking/SetCookiesNdway?email=" + email + "&company=musimundo", { credentials: "include", mode: "no-cors", method: "POST", } ) .then(function (resp) { return resp.text(); }) .then(function (data) { return false; }) .catch(function (ex) { console.log(ex); }); } catch (e) {} } } var bdwParamSC = bdwGetSucCookie(); switch (bdwParamSC.toLowerCase()) { case 'carsa': bdwParamSC = 'carsa'; break; case 'emsa': bdwParamSC = 'emsa'; break; default: bdwParamSC = 'none'; break; } // Bot Oct8ne var oct8ne = document.createElement("script"); oct8ne.server = "backoffice.oct8ne.com/"; oct8ne.type = "text/javascript"; oct8ne.async = true; oct8ne.allowedDepartmentsId = "14886"; let braindwOct8neOptions = { carroMonto: 0, carroCategoria: "", carroGarantia: false, carroUltimoPaso: false, productoCategoria: "", productoCodigo: "", productoPrecio: 0, usuarioEmpresa: bdwGetSucCookie(), usuarioCarroAbierto: false, usuarioEmail: "", usuarioProvincia: "", }; var oct8neIntervalCounter = 0; const bdwLocalStorageMail = "bdw-user-mail"; const oct8neMailInterval = setInterval(() => { oct8neIntervalCounter++; //Agrego el mail al objeto de oct8ne if (localStorage.getItem(bdwLocalStorageMail) !== null) { if (typeof oct8ne !== "undefined" && oct8ne.options === undefined) { oct8ne.options = { user: { //opcional 'no customizable' name: "", email: localStorage.getItem(bdwLocalStorageMail), }, context: { "usuarioSc": bdwParamSC } }; } else if (typeof oct8ne !== "undefined") { oct8ne.options.user = { name: "", email: localStorage.getItem(bdwLocalStorageMail), }; try { oct8ne.options.context = { "usuarioSc": bdwParamSC }; } catch (eeCb) {} } } if (oct8neIntervalCounter >= 10) clearInterval(oct8neMailInterval); if ( !document.querySelector(".braindw_btn_mail") && !document.querySelector("#loginForm .positive") && !document.querySelector("#registerForm .positive") && !document.querySelector(".braindw_btnmail") ) return; //Guardo el mail en LocalStorage console.log("bdw-test1"); var braindwBarBottom = document.querySelector('.braindw_bar_bottom'); if (braindwBarBottom) { braindwBarBottom.style.height = '100%'; } var braindwInputMail = document.querySelector('.braindw_input_mail'); if (braindwInputMail) { braindwInputMail.style.minWidth = '300px'; } var braindwInputMail = document.querySelector('.braindw_bar_icons a'); if (braindwInputMail) { braindwInputMail.style.minWidth = '640px'; } if (document.querySelector(".braindw_btn_mail")) { console.log("bdw-test2"); document .querySelector(".braindw_btn_mail") .addEventListener("click", () => { const mail = document.querySelector("#email").value; if (mail.includes("@") && mail.trim() != "") { localStorage.setItem(bdwLocalStorageMail, mail); } }); } if (document.querySelector("#loginForm .positive")) { document .querySelector("#loginForm .positive") .addEventListener("click", () => { const mail = document.querySelector("#j_username").value; if (mail.includes("@") && mail.trim() != "") { localStorage.setItem(bdwLocalStorageMail, mail); BdwCookiePush(mail); } }); } if (document.querySelector("#registerForm .positive")) { document .querySelector("#registerForm .positive") .addEventListener("click", () => { const mail = document.querySelector("[id='register.email']").value; if (mail.includes("@") && mail.trim() != "") { localStorage.setItem(bdwLocalStorageMail, mail); BdwCookiePush(mail); } }); } if (document.querySelector(".braindw_btnmail")) { document.querySelector(".braindw_btnmail").addEventListener("click", () => { const mail = document.querySelector(".braindw_inptmail").value; if (mail.includes("@") && mail.trim() != "") { localStorage.setItem(bdwLocalStorageMail, mail); BdwCookiePush(mail); } }); } if (document.querySelector("#guestForm .positive")) { document.querySelector("#guestForm .positive").addEventListener("click", () => { const mail = document.querySelector("#guest\\.email").value; if (mail.includes("@") && mail.trim() != "") { localStorage.setItem(bdwLocalStorageMail, mail); BdwCookiePush(mail); } }); } clearInterval(oct8neMailInterval); }, 3000); // Variables gloabales con los valores const currURL = location.protocol + "//" + location.host + location.pathname; let bdwTotalPrice = 0, bdwHasGarantia = false, bdwCategoriesCarro = "", bdwCategoriesProducto = "", bdwIsInLastCheckout = false, bdwProductoPrecio = 0, bdwProductoCodigo = ""; // Script de oct8ne /* var oct8ne = document.createElement("script"); oct8ne.options = { context: { carroMonto: bdwTotalPrice, carroCategoria: bdwCategories, carroGarantia: bdwHasGarantia, carroUltimoPaso: bdwIsInLastCheckout, productoCodigo: bdwProductoCodigo, productoPrecio: bdwProductoPrecio, }, }; oct8ne.server = "backoffice.oct8ne.com/"; oct8ne.type = "text/javascript"; oct8ne.async = true; oct8ne.license = "4FC6AE7AA6D95B78888BC09C966FFAE5"; oct8ne.src = (document.location.protocol == "https:" ? "https://" : "http://") + "static.oct8ne.com/api/v2/oct8ne-api-2.3.js?" + Math.round(new Date().getTime() / 86400000); oct8ne.locale = "es-ES"; oct8ne.baseUrl = "//www.musimundo.com"; oct8ne.allowedDepartmentsId = "14886"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(oct8ne, s); // Funcion para abrir el chat const bdwOpenChat = () => { try { oct8ne.open(); } catch (e) { console.error(e); } }; */ // Metodo que modifica las variables de contexto const bdwSetChatVariables = () => { bdwGetIsInLastCheckout(); bdwGetTotalPrice(); bdwGetCategoriesInCart(); bdwGetSearchedProduct(); bdwGetGarantiaFinanciamiento(); try { oct8ne.customData = { carroMonto: bdwTotalPrice, carroCategoria: bdwCategoriesCarro, carroGarantia: bdwHasGarantia, carroUltimoPaso: bdwIsInLastCheckout, productoCategoria: bdwCategoriesProducto, productoCodigo: bdwProductoCodigo, productoPrecio: bdwProductoPrecio, usuarioEmpresa: bdwGetSucCookie(), usuarioCarroAbierto: false, usuarioEmail: "", usuarioProvincia: bdwUsuarioProvincia, usuarioSc: bdwParamSC, }; oct8ne.license = "4FC6AE7AA6D95B78888BC09C966FFAE5"; oct8ne.src = (document.location.protocol == "https:" ? "https://" : "http://") + "static.oct8ne.com/api/v2/oct8ne-api-2.3.js?" + Math.round(new Date().getTime() / 86400000); oct8ne.locale = "es-ES"; oct8ne.baseUrl = "//musimundo.com"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(oct8ne, s); /* if ( typeof oct8ne !== "undefined" && oct8ne.allowedDepartmentsId === undefined ) braindwOct8neOptions.carroMonto = bdwTotalPrice; braindwOct8neOptions.carroCategoria = bdwCategoriesCarro; braindwOct8neOptions.carroGarantia = bdwHasGarantia; braindwOct8neOptions.carroUltimoPaso = bdwIsInLastCheckout; braindwOct8neOptions.productoCodigo = bdwProductoCodigo; braindwOct8neOptions.productoPrecio = bdwProductoPrecio; braindwOct8neOptions.productoCategoria = bdwCategoriesProducto; braindwOct8neOptions.usuarioProvincia = bdwUsuarioProvincia; Object.keys(braindwOct8neOptions).forEach((item) => { oct8ne.updateTriggerValue(item, braindwOct8neOptions[item]); }); */ } catch (e) { console.log(e.message); } }; // Funcion que setea la provincia del usuario var bdwGetProvinciaOc8ne = (provincia) => { try { if (provincia !== null && provincia !== undefined) { bdwUsuarioProvincia = provincia; bdwSetChatVariables(); } } catch (e) {} }; // Aca arranca. function braindw_pushInfo() { try { let _bwDataset = {}; // get product let _currentProduct = braindw_getProduct(); if (_currentProduct) { _bwDataset.product = _currentProduct; } // get category let _currentCategory = braindw_getCategory(); if (_currentCategory) { _bwDataset.category = _currentCategory; } // get cart let _currentCartOpened = braindw_getCatOpened(); if (_currentCartOpened) { _bwDataset.cartOpened = _currentCartOpened; } else { _currentCartOpened = braindw_getCatClosed(); if (_currentCartOpened) _bwDataset.cartOpened = _currentCartOpened; } let _emailGuest = ""; if (Json_user != null) { if (Json_user.SetUser != null) { if ( Json_user.SetUser.UserEmail != null && Json_user.SetUser.UserEmail != "" ) { _emailGuest = Json_user.SetUser.UserEmail; BdwCookiePush(_emailGuest); } } } let _userState = ""; if (localStorage.getItem("bdw_user_state") != null && localStorage.getItem("bdw_user_state") != undefined) { _userState = localStorage.getItem("bdw_user_state"); } let _company = ""; if (localStorage.getItem("bdwCompany") != null && localStorage.getItem("bdwCompany") != undefined) { _company = localStorage.getItem("bdwCompany"); } let _urlbComanyHash = ""; if (_company == "amba"){ _urlbComanyHash = "https://s.braindw.com/Script/braindw/amba_produccion?"; } if (_company == "carsa"){ _urlbComanyHash = "https://s.braindw.com/Script/braindw/carsa_produccion?"; } //search let _searchTerm = braindw_getSearch(); if (_searchTerm) { _bwDataset.search = _searchTerm; } let braindwDataJSON = { emailguest: _emailGuest, userState: _userState, company: _company, dataset: encodeURI(JSON.stringify(_bwDataset)), page: "", //,document.documentElement.innerHTML, url: window.location.href.split("?")[0], urlb: "https://s.braindw.com/Script/braindw/musimundo_hybris_produccion?", }; fetch('https://p.braindw.com/Api/Data/Capture', { method: "POST", body: JSON.stringify(braindwDataJSON), credentials: 'include', timeout: 5000, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }) .then((resp) => resp.json()) .then(function (data) { }) .catch(function (ex) { console.log("BDW - Error: ", ex); }); if(_urlbComanyHash != ""){ let bdwDataJSON = { emailguest: _emailGuest, userState: _userState, company: _company, dataset: encodeURI(JSON.stringify(_bwDataset)), page: "", //,document.documentElement.innerHTML, url: window.location.href.split("?")[0], urlb: _urlbComanyHash, }; fetch('https://p.braindw.com/Api/Data/Capture', { method: "POST", body: JSON.stringify(bdwDataJSON), credentials: 'include', timeout: 5000, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }) .then((resp) => resp.json()) .then(function (data) { }) .catch(function (ex) { console.log("BDW - Error: ", ex); }); } } catch (err) { console.log("BDW - Error: ", err); } } // Funcion que setea el precio del carro const bdwGetTotalPrice = () => { if ( currURL == "https://www.musimundo.com/cart" || currURL == "https://www.musimundo.com/login/checkout" || currURL == "https://www.musimundo.com/checkout/multi/delivery-pickup/choose" ) { try { if (Json_onProductOnCart == undefined) return; let totalPrice = 0; Json_onProductOnCart.forEach((product) => { const price = parseFloat(product.price); totalPrice += price; }); bdwTotalPrice = totalPrice; } catch (e) { console.log(e); } } }; // Funcion que checkea si estan en ultimo paso de checkout const bdwGetIsInLastCheckout = () => { if (currURL.includes("/checkout/multi/payment-method/add")) bdwIsInLastCheckout = true; }; // Funcion que setea las categorias de los productos en el carrito const bdwGetCategoriesInCart = () => { if ( currURL == "https://www.musimundo.com/cart" || currURL == "https://www.musimundo.com/login/checkout" || currURL == "https://www.musimundo.com/checkout/multi/delivery-pickup/choose" ) { try { const products = Json_onProductOnCart; const productsCategories = products.map((i) => i.category); let categoriesText = ""; productsCategories.forEach((category) => { categoriesText += category + ", "; //if (productsCategories.includes(category)) bdwOpenChat(); }); bdwCategoriesCarro = categoriesText.trim(); } catch (e) { console.log(e); } } }; // Funcion que setea la categoria, codigo y precio en grilla de producto const bdwGetSearchedProduct = () => { if (currURL.includes("/p/")) { try { let priceString = $("#product-details-panel-app .product-price-panel-pdp__price").length > 0 ? $("#product-details-panel-app .product-price-panel-pdp__price").html().trim() : "0"; let codigo = ""; if ($(".mus-pro-code").length > 0) { codigo = $(".mus-pro-code").html().trim(); } else if ($("#product-details-panel-app .product-details-panel__code").length > 0) { codigo = $("#product-details-panel-app .product-details-panel__code").html().trim(); } const category = document .querySelectorAll(".breadcrumb li")[ document.querySelectorAll(".breadcrumb li").length - 3 ].innerText.toLowerCase(); const precio = parseFloat( priceString.replace(".", "") .replace("$", "") .replace(",", ".")); bdwCategoriesProducto = category; bdwProductoCodigo = codigo; bdwProductoPrecio = precio; } catch (e) { console.log(e); } } }; // Funcion que checkea si hay garantia o financiamiento en checkout const bdwGetGarantiaFinanciamiento = () => { if ( currURL == "https://www.musimundo.com/cart" && document.querySelectorAll(".mus-garanty-option").length > 0 ) { bdwHasGarantia = true; } }; //************************************************************************************// //****************BLOQUE DE FUNCIONES AUXILIARES CUSTOMERLABS*************************// //************************************************************************************// //if (document.location.href.indexOf("bdwtest") > -1) { var habilitar=false; if (habilitar) { try { try { ! function (t, e, r, c, a, n, s) { t.ClAnalyticsObject = a, t[a] = t[a] || [], t[a].methods = ["trackSubmit", "trackClick", "pageview", "identify", "track"], t[a].factory = function (e) { return function () { var r = Array.prototype.slice.call(arguments); return r.unshift(e), t[a].push(r), t[a] } }; for (var i = 0; i < t[a].methods.length; i++) { var o = t[a].methods[i]; t[a][o] = t[a].factory(o) }; n = e.createElement(r), s = e.getElementsByTagName(r)[0], n.async = 1, n.crossOrigin = "anonymous", n.src = c, s.parentNode.insertBefore(n, s) }(window, document, "script", "//cdn.js.customerlabs.co/cl4284msyp2jiq.js", "_cl"); _cl.SNIPPET_VERSION = "1.0.0"; } catch (e) { console.log("[CustomerLabsScript] [error]"); } var GlobalData = "", CLprice = 0, CLproductcode = "", CLstate = "", CLlink = "", CLproductName = "", CLbrand = "", CLproductcategory = "", CLTotalPrice = "", CLCartItems = "", CLCartNumber = "", CLEmail = "", CLCategoryTree = "", CLCategoryName = "", CLCategoryCode = ""; var BraindwDomReady = function (callback) { document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback); }; var validation = { isEmailAddress: function (str) { var pattern = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; return pattern.test(str); // returns a boolean }, isNotEmpty: function (str) { var pattern = /\S+/; return pattern.test(str); // returns a boolean }, isNumber: function (str) { var pattern = /^-?\d+\.?\d*$/; return pattern.test(str); // returns a boolean }, isSame: function (str1, str2) { return str1 === str2; } }; // Funcion que setea el precio del carro var CLSetTotalPrice = () => { if ( currURL == "https://www.musimundo.com/cart" ) { try { if (Json_onProductOnCart == undefined) return; let totalPrice = 0; Json_onProductOnCart.forEach((product) => { const price = parseFloat(product.price); totalPrice += price; }); localStorage.setItem("totalprice", totalPrice); } catch (e) { console.log(e); } } }; var CLGetTotalPrice = () => { var braindw_url = document.URL; if (braindw_url.toLowerCase().indexOf("/checkout/orderconfirmation") > -1) { try { var total = localStorage.getItem("totalprice"); if (total) { CLTotalPrice = total; } else { CLTotalPrice = ""; } } catch (e) { console.log(e); } } }; function CLgetCatClosed() { var braindw_url = document.URL; if (braindw_url.toLowerCase().indexOf("/checkout/orderconfirmation") == -1) return ""; try { let CartNumber = braindw_url.split("/")[braindw_url.split("/").length - 1]; CLCartItems = CLGetCartItems(); CLCartNumber = CartNumber; } catch (e) { console.log("braindw_getCatClosed", e); } } // Funcion que setea la categoria, codigo y precio en grilla de producto const CLGetProductDetails = () => { if (currURL.includes("/p/")) { try { let priceString = $("#product-details-panel-app .product-price-panel-pdp__price").length > 0 ? $("#product-details-panel-app .product-price-panel-pdp__price").html().trim() : "0"; let codigo = ""; if ($(".mus-pro-code").length > 0) { codigo = $(".mus-pro-code").html().trim(); } else if ($("#product-details-panel-app .product-details-panel__code").length > 0) { codigo = $("#product-details-panel-app .product-details-panel__code").html().trim(); } const category = document .querySelectorAll(".breadcrumb li")[ document.querySelectorAll(".breadcrumb li").length - 3 ].innerText.toLowerCase(); const precio = parseFloat( priceString.replace(".", "") .replace("$", "") .replace(",", ".")); const nombre = $("#product-details-panel-app .product-details-panel__name").length > 0 ? $("#product-details-panel-app .product-details-panel__name").html().trim() : ""; const brand = $("#product-details-panel-app .product-details-panel__brand #product_brand span").length > 0 ? $("#product-details-panel-app .product-details-panel__brand #product_brand span").html().trim() : ""; const url = document.location.href; const state = localStorage.getItem("bdw_user_state"); CLproductcode = codigo; CLproductName = nombre; CLbrand = brand; CLproductcategory = category; CLlink = url; CLstate = state; CLprice = precio; } catch (e) { console.log(e); } } }; // Funcion que setea la categoria, codigo y precio en grilla de producto const CLGetProductDetailsPLP = (element) => { var rgxCat = new RegExp('.*?:\/\/(.*).musimundo.*\/c\/.*$'); if (rgxCat.test(location.href)) { try { var element = element.parentNode; var father = element.offsetParent; var code = father.getElementsByClassName("mus-pro-code")[0].innerText; var found = Json_products.filter(function (item) { return item.id === code; }); if (found) { const codigo = found[0].id const nombre = found[0].name; const brand = found[0].brand; const url = father.href; const category = found[0].category; const precio = found[0].price; GlobalData.CustomerLabsProductDetails = { productDetails: { "price": Number(precio), "productId": codigo, "link": url, "productName": nombre, "brand": brand, "category": category, "BranchOffice": bdwGetSucCookie().toUpperCase(), } }; } } catch (e) { console.log(e); } } }; function CLGetCategory() { let result = null; var braindw_url = document.URL; var rgxCat = new RegExp('.*?:\/\/(.*).musimundo.*\/c\/.*$'); if (rgxCat.test(location.href)) { try { let Title = ""; let CategoryCode = ""; if (document.getElementById("breadcrumb") != null) { let linkListCategories = document.getElementById("breadcrumb").getElementsByTagName("a"); if (linkListCategories.length > 1) { CategoryCode = linkListCategories[1].href.split("/")[ linkListCategories[1].href.split("/").length - 1 ]; Title = linkListCategories[1].text; } } if (Title && CategoryCode) { CLCategoryName = Title; CLCategoryCode = CategoryCode; } } catch (e) { console.log("CLGetCategory error ", e); } } } function CLGetEmail() { var email = localStorage.getItem("bdw-user-mail"); if (email) { CLEmail = email; } else { CLEmail = "" } } function CLSetCartItems() { if (document.location.href.indexOf("https://www.musimundo.com/cart") > -1) { localStorage.setItem("cart_items", JSON.stringify(Json_onProductOnCart)); } } function CLGetCartItems() { var CartItems = JSON.parse(localStorage.getItem("cart_items")); return CartItems; } function CLGetCategoryTreeCodes() { var cl = ""; var rgxCat = new RegExp('.*?:\/\/(.*).musimundo.*\/c\/.*$'); if (rgxCat.test(location.href)) { var linkListCategories = document.getElementById("breadcrumb").getElementsByTagName("a"); for (var ii = 0; ii < linkListCategories.length; ii++) { var a = $(linkListCategories[ii]).attr("href").split("/")[ $(linkListCategories[ii]).attr("href").split("/").length - 1 ]; cl += a + ","; } CLCategoryTree = cl; } else { CLCategoryTree = cl; return; } } function CLGetCurrentCategory() { var cl = ""; var linkListCategories = document .getElementById("breadcrumb") .getElementsByTagName("a"); for (var ii = 0; ii < linkListCategories.length; ii++) { var a = $(linkListCategories[ii]).attr("href").split("/")[ $(linkListCategories[ii]).attr("href").split("/").length - 1 ]; cl += a + ","; } CLCategoryTree = cl; } function CLGetOpenCarttems() { var Items = JSON.parse(localStorage.getItem("OpenCartItems")) || []; var item = GlobalData.CustomerLabsProductDetails.productDetails; Items = AlreadyExists(Items, item); Items.push(item); localStorage.setItem("OpenCartItems", JSON.stringify(Items)); return Items; } function AlreadyExists(Items, i) { var filtered = Items.filter(function (item) { return item.productId !== i.productId; }); return filtered; } function BdwInterceptorRequest(url, method, callback) { var __XHROpenFn = window.XMLHttpRequest.prototype.open; window.XMLHttpRequest.prototype.open = function ( method, url, async, user, password ) { var event = new CustomEvent("request.open", { detail: { xhr: this, request: this, method: method, url: url, async: async, }, }); window.dispatchEvent(event); return __XHROpenFn.apply(this, arguments); }; window.addEventListener("request.open", handleXHR); function handleXHR(ev) { if ( ev.detail.method.toLowerCase() == method && ev.detail.url.indexOf(url) > -1 ) { ev.detail.xhr.onload = function () { if (ev.detail.xhr.readyState === 4 && ev.detail.xhr.status === 200) { callback(ev.detail.xhr.responseText); } else { console.error(xhr.statusText); } }; } } } try { BdwInterceptorRequest("delete/", "post", function (data) { setTimeout(function () { //var CItems = Json_onProductOnCart; //CLOpenCart(CItems; // console.log("CLOpenCartEvent"); }, 1000) }); } catch (e) { console.log("[InterceptorRequestOpenCartUpdate] [error]"); } // Metodo que modifica las variables de contexto para CustomerLabs var braindw_url = document.URL; const SetCustomerLabsVariables = () => { CLGetProductDetails(); CLGetEmail(); CLGetCategoryTreeCodes(); CLGetCategory(); CLgetCatClosed(); CLGetTotalPrice(); try { GlobalData = { CustomerLabsProductDetails: {}, CustomerLabsCheckOutDetails: {}, CustomerLabsUserDetails: {}, CustomerLabsCategoryDetails: {} }; GlobalData.CustomerLabsProductDetails = { productDetails: { "price": Number(CLprice), "productId": CLproductcode, "link": CLlink, "productName": CLproductName, "brand": CLbrand, "category": CLproductcategory, "BranchOffice": bdwGetSucCookie().toUpperCase() } }; GlobalData.CustomerLabsCheckOutDetails = { checkOutDetails: { "currencyCode": 'ARS', "BranchOffice": bdwGetSucCookie().toUpperCase(), "orderFormId": CLCartNumber, "email": CLEmail, "TotalPrice": Number(CLTotalPrice), "add": { "products": CLCartItems, } } }; GlobalData.CustomerLabsUserDetails = { customProperties: { "user_traits": { "t": "Object", "v": { "email": { "t": "string", "v": CLEmail }, "BranchOffice": { "t": "string", "v": bdwGetSucCookie().toUpperCase(), } } }, "identify_by_email": { "t": "string", "v": CLEmail, "ib": true } } }; GlobalData.CustomerLabsCategoryDetails = { "customProperties": { "categoryId": { "t": "string", "v": CLCategoryCode }, "Name": { "t": "string", "v": CLCategoryName }, "categories": { "t": "string", "v": CLCategoryTree }, "url": { "t": "string", "v": window.location.href }, "BranchOffice": { "t": "string", "v": bdwGetSucCookie().toUpperCase(), } } }; } catch (e) { console.log(e.message); } }; //************************************************************************************// //**************FUNCIONES DESTINADAS AL PUSHEO DE EVENTOS CUSTOMERLABS*****************// //************************************************************************************// //Metodo de customerlabs que pushea el evento de BDW-Closecart function CLCloseCart() { var eventName = "BDW-Closecart"; var finalProperties = {} var properties = CloseCartProperties(); finalProperties["customProperties"] = customFields(properties); finalProperties["productProperties"] = productFields(properties); console.log("BDW-Closecart"); _cl.trackClick(eventName, finalProperties) } //Metodo de customerlabs que pushea el evento de BDW-Opencart function CLOpenCart(Items, action) { var eventName = "BDW-Opencart"; var finalProperties = {} var properties = AddtoCartProperties(action, Items); finalProperties["customProperties"] = customFields(properties); finalProperties["productProperties"] = productFields(properties); console.log(finalProperties); _cl.trackClick(eventName, finalProperties); } //Metodo de customerlabs que pushea el evento de BDW-Productclicked function CLProduct() { var finalProperties = {} var eventName = "BDW-Productclicked"; var properties = ProductProperties(eventName); finalProperties["customProperties"] = customFields(properties); console.log("BDW-Productclicked"); _cl.trackClick(eventName, finalProperties); } //Metodo de customerlabs que pushea el evento de BDW-ProductAddedtoCart function CLProductAddedtoCart() { var finalProperties = {} var eventName = "BDW-ProductAddedtoCart"; var properties = ProductProperties(eventName); finalProperties["customProperties"] = customFields(properties); console.log("BDW-ProductAddedtoCart"); _cl.trackClick(eventName, finalProperties); } //Metodo de customerlabs que pushea el evento de BDW-identifiedUser function CLUser() { var properties = UserProperties(); console.log("BDW-identifiedUser"); _cl.identify(properties); localStorage.setItem("BDW-identifiedUser", "1"); } function CLCategory() { var eventName = "BDW-Categoryviewed"; var properties = CategoryProperties(); console.log(eventName); _cl.trackClick(eventName, properties) } function ProductProperties(eventName) { var properties = { "event": eventName, "ecommerce": GlobalData.CustomerLabsProductDetails.productDetails, "gtm.uniqueEventId": 51 }; console.log(properties); return properties; } function AddtoCartProperties(action, Items) { const email = localStorage.getItem("bdw-user-mail"); if (email == undefined && email == "") { email = ""; } var properties = { "event": "addToCart", "ecommerce": { "currencyCode": "ARS", "BranchOffice": bdwGetSucCookie().toUpperCase(), "Action": action, "email": email, "add": { "products": Items } }, "gtm.uniqueEventId": 51 } console.log(properties); return properties; } function CloseCartProperties() { var properties = { "event": "Close cart", "ecommerce": GlobalData.CustomerLabsCheckOutDetails.checkOutDetails, "gtm.uniqueEventId": 51 } console.log(properties); return properties; } function UserProperties() { var properties = GlobalData.CustomerLabsUserDetails; console.log(properties); return properties; } function CategoryProperties() { var properties = GlobalData.CustomerLabsCategoryDetails; console.log(properties); return properties; } function customFields(properties) { var customStructure = {} var customProps = properties.ecommerce; for (key in customProps) { switch (key) { case "currencyCode": customStructure["currency"] = customProps[key] break; case "BranchOffice": customStructure["BranchOffice"] = customProps[key] break; case "orderFormId": customStructure["orderFormId"] = customProps[key] break; case "email": customStructure["email"] = customProps[key] break; case "add": break; default: let isnum = validation.isNumber(customProps[key]); var type = (Number.isFinite(customProps[key]) || isnum) ? "number" : "string" customStructure[key] = { "t": type, "v": customProps[key] } } } //console.log(customStructure); return customStructure } function productFields(properties) { var productsArr = properties.ecommerce.add.products; var products = [] for (let i = 0; i < productsArr.length; i++) { var productsStructure = {} for (key in productsArr[i]) { switch (key) { case "name": productsStructure["product_name"] = { "t": "string", "v": productsArr[i]["name"] } break; case "id": productsStructure["product_id"] = { "t": "string", "v": productsArr[i]["id"] } break; case "price": productsStructure["product_price"] = { "t": "number", "v": productsArr[i]["price"] } break; case "category": productsStructure["product_category"] = { "t": "string", "v": productsArr[i]["category"] } break; case "brand": productsStructure["product_brand"] = { "t": "string", "v": productsArr[i]["brand"] } break; default: let isnum = /^\d+$/.test(productsArr[i][key]); var type = (Number.isFinite(productsArr[i][key]) || isnum) ? "number" : "string" productsStructure["product_" + key] = { "t": type, "v": productsArr[i][key] } } } products.push(productsStructure); } return products } BraindwDomReady(function () { if (bdwGetSucCookie()) { SetCustomerLabsVariables(); CLSetCartItems(); CLSetTotalPrice(); setTimeout(function () { try { if (currURL.includes("/p/")) { CLProduct(); $(".addToCartButton").click(function (e) { CLProductAddedtoCart(); }); } if (document.location.href.toLowerCase().indexOf("/checkout/orderconfirmation") > -1) { CLCloseCart(); } if ( currURL == "https://www.musimundo.com/cart" || currURL == "https://www.musimundo.com/login/checkout" || currURL == "https://www.musimundo.com/checkout/multi/delivery-pickup/choose" ) { var CItems = Json_onProductOnCart; if (CItems.length > 0) { var ni = localStorage.getItem("nitemscart"); if (ni) { if (CItems.length > ni) { CLOpenCart(CItems, "added"); console.log("CLOpenCart"); localStorage.setItem("nitemscart", CItems.length); } if (CItems.length < ni) { CLOpenCart(CItems, "removed"); console.log("CLOpenCart"); localStorage.setItem("nitemscart", CItems.length); } if (CItems.length == ni) { console.log("sin modificación"); } } else { CLOpenCart(CItems, "added"); console.log("CLOpenCart"); localStorage.setItem("nitemscart", CItems.length); } } } var email = localStorage.getItem("bdw-user-mail"); var identifiedUser = localStorage.getItem("BDW-identifiedUser"); if (email && identifiedUser !== "1") { if (bdwGetSucCookie()) { CLUser(); console.log("CLUserEvent"); } } var rgxCat = new RegExp('.*?:\/\/(.*).musimundo.*\/c\/.*$'); if (rgxCat.test(location.href)) { CLCategory(); $(".addToCartButton").click(function (e) { CLGetProductDetailsPLP(this); setTimeout(function () { CLProductAddedtoCart(); }, 500); }); } } catch (e) { console.log("[CustomerLabsEvents] [error]"); } }, 4000); } }) } catch (e) { console.log("[BloquecompletoCustomerLAbs] [error]"); } } else{ console.log("customerlabs is not enabled") } function bdwDatalayerClick(termSearch, mapItems, area) { let countMap = mapItems.length; dataLayer.push({'event': 'select_item', 'search_term': termSearch, 'site_search_counter_results': countMap, 'search_term_sort': 'default sort', 'search_term_page': '1', 'item_list_name': area, 'item_list_id': area, 'items': mapItems} ); } function bdwDataProd(response, action) { action.includes('catalog') ? area = 'search_result' : area = 'auto-suggest-dropdown'; if(window.location.href.includes('bdwssearch=true') || window.location.href.includes('bdwsearch=true') && localStorage.getItem('bdw-lastS')){ var mapItems = []; let termSearch = localStorage.getItem('bdw-lastS'); response.hits.forEach(function (element, index) { let item = { 'index': index, 'item_id': element._source.code, 'item_name': element._source.title, 'coupon': '', 'discount': element._source.discountPrice, 'price':element._source.price, 'currency':'ARG', 'item_list_name':area, 'item_list_id':area, 'affiliation':'Musimundo', 'item_brand':element._source.brand, 'item_category':element._source.category, 'item_category2':element._source.category2, 'item_category3':element._source.category3, 'item_variant':'', 'quantity':'1' } mapItems.push(item); }); bdwDatalayerClick(termSearch, mapItems, area); } } function BdwProcessProductCardCapture(code,urlCapture,categoriesDefault) { var urlJS = urlCapture.replace('{categoriescodes}',categoriesDefault); console.log(urlCapture,'urlCapture'); try { console.log('BDW Procesando codigo',code); //code="CODC176472E140728"; fetch( "https://u.braindw.com/els/musimundoapi?ft="+code+"&qt=1&sc=none&refreshmetadata=false&exclusive=0", { credentials: "include", method: "GET", } ) .then(function (resp) { return resp.text(); }) .then(function (data) { data = JSON.parse(data); console.log(data); if(data!=null) { if(window.location.href.includes('bdwssearch=true')){ bdwDataProd(data.hits, 'desplegable'); } if(window.location.href.includes('bdwsearch=true')){ bdwDataProd(data.hits, 'catalog'); } console.log('BDW Procesando respuesta codigo',data.hits.hits[0]._source.code); if(data.hits.total>0 && data.hits.hits[0]._source.code==code) { var categories = data.hits.hits[0]._source.categoryTree; var listCategories = categories.split(','); var arrayObj = []; for(var i=0;i x==listCategories[i]); if(index === -1) arrayObj.push(listCategories[i]); } _bdwProductCardCategoriesCodes = arrayObj.join(); } } if(_bdwProductCardCategoriesCodes.length>0) { console.log('BDW CATEGORYTREE OK',code,_bdwProductCardCategoriesCodes); BDWAddScriptFromURL(urlCapture.replace('{categoriescodes}',_bdwProductCardCategoriesCodes)); } else { BDWAddScriptFromURL(urlJS); } }) .catch(function (ex) { BDWAddScriptFromURL(urlJS); }); } catch (e) { BDWAddScriptFromURL(urlJS);} } function BDWAddScriptFromURL(urlJS) { console.log('BDW Add JS ',urlJS); var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = urlJS.replace('musimundo_hybris_produccion',_HASHBNDW); document.head.appendChild(script); } if (document.URL.toLowerCase().indexOf("/search") !== -1){ var bdwSearch = braindwGetUrlParameter("text"); window.addEventListener("load", (event) => { if($('.mus-friendly-title').length > 0){ //pregunta si tiene el mensaje "no se encontraro resultados" PushTermNotFound(bdwSearch, 0); }else{ PushTermNotFound(bdwSearch, 1); } }); if (bdwSearch.toLowerCase() === "realidad aumentada") { location.href = "https://www.musimundo.com/realidadaumentada"; } if (bdwSearch.toLowerCase() === "ofertas") { location.href = "https://www.musimundo.com/super-ofertas/c/superofertas"; } if (bdwSearch.toLowerCase() === "precios justos") { location.href = "https://www.musimundo.com/ofertas/precios-justos/c/101089"; } if (bdwSearch.toLowerCase() === "día del niño" || bdwSearch.toLowerCase() === "día del niño" || bdwSearch.toLowerCase() === "dia del niño" || bdwSearch.toLowerCase() === "día de la niñez" || bdwSearch.toLowerCase() === "dia de la niñez" || bdwSearch.toLowerCase() === "día de las infancias" || bdwSearch.toLowerCase() === "dia de las infancias" || bdwSearch.toLowerCase() === "niños" || bdwSearch.toLowerCase() === "niñas" || bdwSearch.toLowerCase() === "regalos para niños" || bdwSearch.toLowerCase() === "regalos para niñas") { location.href = "https://www.musimundo.com/ofertas/los-mejores-regalos-dia-de-la-ninez/c/3001367"; } if (bdwSearch.toLowerCase() === "dia de la madre 2023" || bdwSearch.toLowerCase() === "dia de la madre en argentina" || bdwSearch.toLowerCase() === "dia de la madre 2023 argentina" || bdwSearch.toLowerCase() === "regalo dia de la madre" || bdwSearch.toLowerCase() === "regalo para el dia de la madre" || bdwSearch.toLowerCase() === "ideas de regalo para el dia de la madre" || bdwSearch.toLowerCase() === "cuando es el día de la madre" || bdwSearch.toLowerCase() === "cuando es el dia de la madre en argentina") { //location.href = "https://www.musimundo.com/ofertas/los-mejores-regalos-para-mama/c/3001298"; location.href = "https://www.musimundo.com/diadelamadre"; } if (bdwSearch.toLowerCase() === "día del padre" || bdwSearch.toLowerCase() === "dia del padre" || bdwSearch.toLowerCase() === "regalos para papa" || bdwSearch.toLowerCase() === "regalos para papá" || bdwSearch.toLowerCase() === "regalos dia del padre" || bdwSearch.toLowerCase() === "regalos día del padre" || bdwSearch.toLowerCase() === "regalo para papá" || bdwSearch.toLowerCase() === "regalo para papa" || bdwSearch.toLowerCase() === "regalo papá" || bdwSearch.toLowerCase() === "regalo papa" || bdwSearch.toLowerCase() === "regalo del día del padre" || bdwSearch.toLowerCase() === "regalo del dia del padre" || bdwSearch.toLowerCase() === "ofertas día del padre" || bdwSearch.toLowerCase() === "ofertas dia del padre" || bdwSearch.toLowerCase() === "regalos para papá moderno" || bdwSearch.toLowerCase() === "regalos para papa moderno" || bdwSearch.toLowerCase() === "ofertas para papá moderno" || bdwSearch.toLowerCase() === "ofertas para papa moderno" || bdwSearch.toLowerCase() === "ofertas en cuidado personal día del padre" || bdwSearch.toLowerCase() === "ofertas en cuidado personal dia del padre" || bdwSearch.toLowerCase() === "regalos") { location.href = "https://www.musimundo.com/ofertas/ofertas-dia-del-padre/c/300104"; } if (bdwSearch.toLowerCase() === "electrofans") { location.href = "https://www.musimundo.com/ofertas/electrofans/c/101027"; } if (bdwSearch.toLowerCase() === "hotsale" || bdwSearch.toLowerCase() === "hot sale") { location.href = "https://www.musimundo.com/hotsale"; } } //se agrega Utms // var bdwUtms = [ // { // "id": "BDW-CheckOut-Carrusel-1", // "utm": "?utm_source=braindw&utm_medium=gondola-completatucompra-checkout&utm_campaign=gondola-completatucompra-checkout" // }, // { // "id": "BDW-CheckOut-Carrusel-3", // "utm": "?utm_source=braindw&utm_medium=gondola-cross-recomendados-checkout&utm_campaign=gondola-cross-recomendados-checkout" // }, // { // "id": "BDW-CheckOut-Carrusel-2", // "utm": "?utm_source=braindw&utm_medium=gondola-checkout-envio-domicilio&utm_campaign=gondola-checkout-envio-domicilio" // }, // { // "id": "BDW-CheckOut-Carrusel-4", // "utm": "?utm_source=braindw&utm_medium=braindw-gondola-masvistos-checkout&utm_campaign=braindw-gondola-masvistos-checkout" // }, // { // "id": "BDW-Home-Carrusel-5", // "utm": "?utm_source=braindw&utm_medium=gondola-masvendidos-home&utm_campaign=gondola-masvendidos-home" // }, // { // "id": "BDW-Home-Carrusel-6", // "utm": "?utm_source=braindw&utm_medium=gondola-masvistos-home&utm_campaign=gondola-masvistos-home" // }, // { // "id": "BDW-Home-Carrusel-1", // "utm": "?utm_source=braindw&utm_medium=mi-musimundo&utm_campaign=ultima-busqueda" // }, // { // "id": "BDW-Home-Carrusel-2", // "utm": "?utm_source=braindw&utm_medium=mi-musimundo&utm_campaign=producto-visto" // }, // { // "id": "BDW-Home-Carrusel-3", // "utm": "?utm_source=braindw&utm_medium=mi-musimundo&utm_campaign=ultima-categoria" // }, // { // "id": "BDW-Home-Carrusel-7", // "utm": "?utm_source=braindw&utm_medium=mi-musimundo&utm_campaign=producto-agregado" // }, // { // "id": "BDW-Home-Carrusel-8", // "utm": "?utm_source=braindw&utm_medium=gondola-mejorestv-home&utm_campaign=gondola-mejorestv-home" // }, // { // "id": "BDW-PDP-Carrusel-5", // "utm": "?utm_source=braindw&utm_medium=gondola-masvendidos-categoria-producto&utm_campaign=gondola-masvendidos-categoria-producto" // } // , // { // "id": "BDW-PDP-Carrusel-4", // "utm": "?utm_source=braindw&utm_medium=gondola-cross-intermedia&utm_campaign=gondola-cross-intermedia" // }, // { // "id": "BDW-PDP-Carrusel-1", // "utm": "?utm_source=braindw&utm_medium=gondola-cross-selling&utm_campaign=gondola-cross-selling" // }, // { // "id": "BDW-PLP-Carrusel-2", // "utm": "?utm_source=braindw&utm_medium=góndola-masvendidos-cateogoria&utm_campaign=góndola-masvendidos-cateogoria" // } // , // { // "id": "BDW-PLP-Carrusel", // "utm": "?utm_source=braindw&utm_medium=banner-header-categoria&utm_campaign=banner-header-categoria" // } // , // { // "id": "BDW-SNR-Carrusel-3", // "utm": "?utm_source=braindw&utm_medium=góndola-SNR-masvistos&utm_campaign=góndola-SNR-masvistos" // } // ]; try { //se comenta lógica a pedido de Musi // setTimeout(function () { // document.querySelectorAll(`[id^="BDW"] .product-carousel`).forEach(function(item){ // var utm = bdwUtms.find(x => x.id == item.parentElement.id); // if (utm) { // item.querySelectorAll('a.js-bind-ga-carousel-item').forEach(function(i){ // if(i.href.indexOf('?') == -1){ // i.href +=utm.utm; // }else{ // let utm2 = utm.utm.replace('?','&'); // i.href +=utm2; // } // }); // } // }); // },8000); if (document.URL.indexOf('/search') > -1) { /*setTimeout(function () { document.querySelectorAll('.productGrid .productListerGridItem a').forEach(function (item) { item.href += "?utm_source=braindw&utm_medium=mi-musimundo&utm_campaign=mi-musimundo"; }); }, 6000);*/ var textoBuscado = ''; if(document.location.href.indexOf('/search')>-1){ textoBuscado = decodeURI(document.location.href.split('=')[1].split('&voice')[0]); }else{ textoBuscado = decodeURI(document.location.href.split('=')[1]); } if(textoBuscado && textoBuscado !== 'braindw&utm_medium' && textoBuscado !== 'true' ){ localStorage.setItem("bdw-lastS", textoBuscado); } } /*BdwInterceptorRequest("search/autocomplete/SearchBox?term=", "get", function (data) { setTimeout(function () { document.querySelectorAll('.ui-autocomplete .suggestions a').forEach(function(item) { item.href += "?utm_source=braindw&utm_medium=mi-musimundo&utm_campaign=mi-musimundo"; }); }, 8000); });*/ } catch (e) { console.log("[InterceptorRequestOpenCartUpdate] [error]"); } // fin Utms function getVisitedProducts() { var sku = ""; //Para LastAddToCartBraindw y ListAddToCartBraindw const substring = "?braindw="; var listBDWName = ""; //Para LastAddToCartBraindw y ListAddToCartBraindw var url = window.location.pathname.split("/"); if (url[url.length - 2] == "p") { //Para LastAddToCartBraindw y ListAddToCartBraindw if(window.location.href.includes(substring)){ var urlCarrusel = window.location.href.split("?braindw="); listBDWName = urlCarrusel[1]; } //Para LastAddToCartBraindw y ListAddToCartBraindw if ($(".span_8 .mus-pro-desc .mus-pro-code").length > 0) { sku = $(".span_8 .mus-pro-desc .mus-pro-code").html().trim(); } else if ($("#product-details-panel-app .product-details-panel__code").length > 0) { sku = $("#product-details-panel-app .product-details-panel__code").html().trim(); } if (!localStorage.getItem("bdw-productsView")) { localStorage.setItem("bdw-productsView", '["' + sku + '"]'); } else { var allSkus = JSON.parse( localStorage.getItem("bdw-productsView") ).reverse(); var repeated = allSkus.filter((item) => item == sku).length > 0 ? true : false; if (!repeated) { allSkus.push(sku); } else { allSkus.push(allSkus.splice(allSkus.indexOf(sku), 1)[0]); } if (allSkus.length > 30) { allSkus = allSkus.slice(allSkus.length - 30, allSkus.length); } localStorage.setItem( "bdw-productsView", JSON.stringify(allSkus.reverse()) ); } } //Para LastAddToCartBraindw y ListAddToCartBraindw if(listBDWName !== ""){ let productViewlistBraindw = JSON.parse(localStorage.getItem('_productViewlistBraindw')) || {}; if (productViewlistBraindw[sku]) { delete productViewlistBraindw[sku]; } productViewlistBraindw[sku] = { listname: listBDWName }; localStorage.setItem('_productViewlistBraindw', JSON.stringify(productViewlistBraindw)); } /** * Limpiar localStorage productos agregados al carrito desde carrusel */ cleanLocalStorageAddToCartFromListBDW(); //Para LastAddToCartBraindw y ListAddToCartBraindw } var bdwToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9hbm9ueW1vdXMiOiIiLCJuYmYiOjE3MzMwMjYxNDgsImV4cCI6MTczMzAyNjQ0OCwiaWF0IjoxNzMzMDI2MTQ4fQ.JN8gf47KVejA9iDVBb7lo4IMnrRhER_dWR8frBVV64I'; // Cupon function braindw_hidepop(){ $('#braindw_register').css("display", "none"); } function ValidoMail(email){ var caract = new RegExp(/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/); if (caract.test(email) == false) return false; return true; } function SendEmail() { try { if ($('.braindw_inptmail').last().val() == '' || !ValidoMail($('.braindw_inptmail').last().val())) { alert('Por favor completa el email'); } else { var hash = $('#hash').val(); var idgroup = $('#idgroup').val(); var email = $('.braindw_inptmail').last().val(); var token = bdwToken; BdwCookiePush(email); $('#braindw_register').css("display", "none"); $('#braindw_registerOk').css("display", "block"); fetch(document.querySelector('#braindw_email').getAttribute("value") + '?hash=' + hash + '&idgroup=' + idgroup + '&email=' + email + '&token=' + token + "&data=", { credentials: "include", mode: 'no-cors', method: 'POST', }) .then(function(resp) { return resp.text(); }) .then(function(data) { document.querySelector('#braindw_register').style.display = "none"; document.querySelector('#braindw_registerOk').style.display = "block"; return false; }) .catch(function(ex) { console.log(ex); }); switch(bdwGetSucCookie()){ case 'carsa': localStorage.setItem('sendEmailCarsa', 'true'); break; case 'emsa': localStorage.setItem('sendEmailEmsa', 'true'); break; case 'amba': localStorage.setItem('sendEmailAmba', 'true'); break; } } window.setTimeout("$('#braindw_registerOk').css('display', 'none');", 3000); return false; } catch(err) { console.log(err); location.reload(); } } var cuponEmsa = `

DESCUBRÍ LAS MEJORES OFERTAS

suscribite a nuestro newsletter

Por favor completá el email
`; var cuponCarsa=`

DESCUBRÍ LAS MEJORES OFERTAS

suscribite a nuestro newsletter

Por favor completá el email
`; var cuponAmba=`

DESCUBRÍ LAS MEJORES OFERTAS

suscribite a nuestro newsletter

Por favor completá el email
`; if (bdwGetSucCookie() === 'emsa' && null === localStorage.getItem("sendEmailEmsa") && parseInt(localStorage.getItem("bdw_count_coupon")) < 3) { $('#header').before(cuponEmsa); } if (bdwGetSucCookie() === 'amba' && null === localStorage.getItem("sendEmailAmba") && parseInt(localStorage.getItem("bdw_count_coupon")) < 3 ) { $('#header').before(cuponCarsa); } if (bdwGetSucCookie() === 'carsa' && null === localStorage.getItem("sendEmailCarsa") && parseInt(localStorage.getItem("bdw_count_coupon")) < 3 ) { $('#header').before(cuponAmba); } if (document.URL.indexOf(/c/) > -1) { var pathCat = document.querySelectorAll("#breadcrumb .container ul li a"); if (pathCat) { var categoryArr = pathCat[pathCat.length -1].href.split('/') localStorage.setItem('bdw-lastC', categoryArr[categoryArr.length - 1]) } } //Para LastAddToCartBraindw y ListAddToCartBraindw function localStorageAddToCartFromListBDW(sku) { var braindw_list = ""; let productlist_bdw = JSON.parse(localStorage.getItem('_productViewlistBraindw')) || {}; if (productlist_bdw[sku]) { braindw_list = productlist_bdw[sku].listname; let listAddToCartBraindw = JSON.parse(localStorage.getItem('ListAddToCartBraindw')) || {}; const currentDate = new Date().getTime(); listAddToCartBraindw[sku] = { blockName: braindw_list, creationDate: currentDate }; localStorage.setItem('ListAddToCartBraindw', JSON.stringify(listAddToCartBraindw)); const lastAddToCartBlock = braindw_list; localStorage.setItem('LastAddToCartBraindw', lastAddToCartBlock); } } function cleanLocalStorageAddToCartFromListBDW() { try { let now = new Date().getTime(); var oneDay = 24 * 60 * 60 * 1000; let listAddToCartBraindw = JSON.parse(localStorage.getItem('ListAddToCartBraindw')) || {}; let arrayToCheck = Object.keys(listAddToCartBraindw ).map(function(itm) { listAddToCartBraindw[itm].productCode = itm; return listAddToCartBraindw[itm];}); arrayToCheck.forEach(elm => { if((now - elm.creationDate) > oneDay ) { delete listAddToCartBraindw[elm.productCode]; } }); localStorage.setItem('ListAddToCartBraindw', JSON.stringify(listAddToCartBraindw)); // Si no hay eleimentos en listAddToCartBraindw limpio lastAddToCartBlock if(!listAddToCartBraindw || !Object.keys(listAddToCartBraindw).length){ localStorage.removeItem("LastAddToCartBraindw"); } } catch (errorClnLclStr) { } } //Para LastAddToCartBraindw y ListAddToCartBraindw