(function (yv, $) {
"use strict"
let njQuery = window.jQuery
// yv.productId = window.location.href.split('/').at(-2).split('-').pop()
// if(!document.querySelector('body.bg-base')) {
// var yvs = window.parent.document.createElement("script");
// yvs.type = "text/javascript";
// yvs.async = true;
// yvs.id = "_yvsrc";
// yvs.src = "//service.yourviews.com.br/script/e1196951-82af-4378-977b-6abe2826c5ac/yvapi.js";
// var yvs_script = window.parent.document.getElementsByTagName("script")[0];
// yvs_script.parentNode.insertBefore(yvs, yvs_script);
// return
// }
if (yv.isLoaded) return
yv.isLoaded = true
yv.localization = {
// Traditional portuguese translation
portuguese: {
less: 'menos',
more: 'mais',
writeReview: 'escrever avaliação',
tryAgain: 'tentar novamente',
genericError: 'Ocorreu um erro! Por favor, Tente novamente mais tarde',
socialConnect: 'Conecte-se com as redes sociais para utilizar sua foto',
requiredField: 'campo obrigatório',
invalidEmail: 'e-mail inválido'
},
// Standard english translation
english: {
less: 'less',
more: 'more',
writeReview: 'write review',
tryAgain: 'try again',
genericError: 'An error has occurred! Please try again later',
socialConnect: 'Connect with social media to use your photo',
requiredField: 'required field',
invalidEmail: 'invalid e-mail'
}
}
// Main class
yv.Slider = {
// Slider config options
slidesToShow: undefined,
slidesToShift: 1,
showButtons: undefined,
showPaging: undefined,
infinite: undefined,
breakpoint: undefined,
breakpoints: undefined,
// Main slider elements
container: undefined,
view: undefined,
wrapper: undefined,
slides: undefined,
// Initial slider position values
index: 0,
posX1: 0,
posX2: 0,
startPos: 0,
endPos: 0,
limit: 50,
allowShift: true,
// Initial slider element properties
slideSize: 0,
slidesLength: 0,
slidesToLoad: 0,
prev: undefined,
next: undefined,
paging: undefined,
// Build the slider with the parameters
build: function (options, sliderElements, slidesToLoad) {
if (!options || !sliderElements) return;
// Save all breakpoints
this.breakpoints = JSON.parse(JSON.stringify(options));
// Slider config options
this.slidesToShow = options[0].slidesToShow;
this.slidesToShift = options[0].slidesToShift || 1;
this.showButtons = options[0].showButtons;
this.showPaging = options[0].showPaging;
this.infinite = options[0].infinite;
this.breakpoint = options[0].breakpoint;
// Main slider elements
this.container = document.querySelector(sliderElements.container);
this.view = document.querySelector(sliderElements.view);
this.wrapper = document.querySelector(sliderElements.wrapper);
this.slides = this.wrapper.querySelectorAll(sliderElements.slides);
// Initial slider position values
this.index = 0;
this.posX1 = 0;
this.posX2 = 0;
this.startPos = 0;
this.endPos = 0;
this.limit = 50;
this.allowShift = true;
// Initial slider element properties
this.slideSize = 0;
this.slidesLength = 0;
this.slidesToLoad = slidesToLoad || this.slidesLength;
// Set the slider size
this.slideSize = (
Number(getComputedStyle(this.slides[0]).marginLeft.replace('px', '')) +
Number(getComputedStyle(this.slides[0]).marginRight.replace('px', '')) +
Number(getComputedStyle(this.slides[0]).width.replace('px', ''))
);
// Set the total amount of slides
this.slidesLength = this.slides.length;
// Set the total size of the wrapper
this.wrapper.style.width = String(this.slideSize * this.slidesToLoad) + 'px';
// Set the max number of slides to load
if (!isNaN(this.slidesToLoad) && this.slidesToLoad != null) {
if (this.slidesToLoad < this.slidesLength) {
for (var i = 0; i < this.slidesLength; i++) {
if (i >= this.slidesToLoad) this.slides[i].remove();
}
this.slidesLength = this.slidesToLoad;
}
}
// Set initial position of the slider
this.wrapper.style.left = '0px';
// Set the size of the view
this.view.style.width = (this.slideSize * this.slidesToShow) + 'px';
// Build slider navigation buttons
if (this.showButtons) {
this.prev = 'undefined';
this.next = 'undefined';
this.buildButtons();
}
// Build slider navigation paging
if (this.showPaging) {
this.paging = 'undefined';
this.buildPaging();
}
// Automaticaly initialize the slider events
this.initDragEvents();
// Adjust the slider view
this.handleBreakpoints();
// Slider is loaded
this.container.classList.add('loaded');
},
// Handle breakpoints in the page
handleBreakpoints: function () {
if (this.breakpoints.length > 1) {
for (var i = 0; i < this.breakpoints.length; i++) {
if (this.breakpoints[i + 1] != undefined) {
if (
window.innerWidth <= this.breakpoints[i].breakpoint &&
window.innerWidth > this.breakpoints[i + 1].breakpoint
) {
var breakpoint = JSON.parse(JSON.stringify(this.breakpoints[i]));
this.resizeSlider(breakpoint);
}
} else {
if (
window.innerWidth <= this.breakpoints[i].breakpoint &&
window.innerWidth > 0
) {
var breakpoint = JSON.parse(JSON.stringify(this.breakpoints[i]));
this.resizeSlider(breakpoint);
}
}
}
} else {
this.breakpoints.push({
slidesToShow: 1,
slidesToShift: 1,
showButtons: this.showButtons,
showPaging: this.showPaging,
infinite: this.infinite,
breakpoint: 500
});
this.handleBreakpoints();
}
},
// Update slider configurations and properties
resizeSlider: function (options) {
this.container.classList.remove('loaded');
// Slider config options
this.slidesToShow = options.slidesToShow;
this.slidesToShift = options.slidesToShift || 1;
this.showButtons = options.showButtons;
this.showPaging = options.showPaging;
this.infinite = options.infinite;
this.breakpoint = options.breakpoint;
// Initial slider position values
this.index = 0;
this.posX1 = 0;
this.posX2 = 0;
this.startPos = 0;
this.endPos = 0;
this.limit = 50;
this.allowShift = true;
// Initial slider element properties
this.slideSize = 0;
// Set the slider size
this.slideSize = (
Number(getComputedStyle(this.slides[0]).marginLeft.replace('px', '')) +
Number(getComputedStyle(this.slides[0]).marginRight.replace('px', '')) +
Number(getComputedStyle(this.slides[0]).width.replace('px', ''))
);
// Set the total size of the wrapper
this.wrapper.style.width = String(this.slideSize * this.slidesToLoad) + 'px';
// Set initial position of the slider
this.wrapper.style.left = '0px';
// Set the size of the view
this.view.style.width = (this.slideSize * this.slidesToShow) + 'px';
// Build slider navigation buttons
if (this.showButtons) {
var buttons = this.container.querySelectorAll('.control');
if (buttons.length) buttons.forEach(function (element) { element.remove() });
this.buildButtons();
}
// Build slider navigation paging
if (this.showPaging) {
var paging = this.container.querySelector('.paging');
if (paging) paging.remove();
this.buildPaging();
}
this.container.classList.add('loaded');
},
// Fix problems with keyboard events
initKeysEvents: function (elementNames) {
// Fix the tab press on the end of inputs inside forms inside the slider
this.view.addEventListener('keydown', function (event) {
if (event.key === 'Tab') {
var eventInput = event.target;
elementNames.forEach(function (element) {
if (element === eventInput.name) {
event.preventDefault();
this.shiftSlide(1);
}
})
}
})
},
// Init drag events with mouse tochscreen
initDragEvents: function () {
// Event triggered on press the left mouse button/touch the screen
var dragStart = function (event) {
this.view.classList.add('grabbing');
this.startPos = this.wrapper.offsetLeft;
if (event.type === 'touchstart') {
var touchStart = event;
this.posX1 = touchStart.touches[0].clientX;
} else if (event.type === 'mousedown') {
var mouseDown = event;
this.posX1 = mouseDown.clientX;
document.addEventListener('mouseup', dragEnd);
document.addEventListener('mousemove', dragOut);
}
}
// Event triggered on move the mouse/finger across the screen
var dragOut = function (event) {
if (event.type === 'touchmove') {
var touchMove = event;
this.posX2 = this.posX1 - touchMove.touches[0].clientX;
this.posX1 = touchMove.touches[0].clientX;
} else if (event.type === 'mousemove') {
var mouseMove = event;
this.posX2 = this.posX1 - mouseMove.clientX;
this.posX1 = mouseMove.clientX;
}
this.wrapper.style.left = (this.wrapper.offsetLeft - this.posX2) + 'px';
}
// Event triggered when user release the mouse button/finger from the screen
var dragEnd = function () {
this.view.classList.remove('grabbing');
this.endPos = this.wrapper.offsetLeft;
if (this.endPos - this.startPos < -this.limit) {
this.shiftSlide(1, 'drag');
} else if (this.endPos - this.startPos > this.limit) {
this.shiftSlide(-1, 'drag');
} else {
this.wrapper.style.left = (this.startPos) + 'px';
}
document.removeEventListener('mouseup', dragEnd);
document.removeEventListener('mousemove', dragOut);
}
// Bind this in the handler functions
dragStart = dragStart.bind(this);
dragOut = dragOut.bind(this);
dragEnd = dragEnd.bind(this);
// Mouse events
this.view.addEventListener('mousedown', dragStart);
// Touch events
this.view.addEventListener('touchstart', dragStart);
this.view.addEventListener('touchmove', dragOut);
this.view.addEventListener('touchend', dragEnd);
// Transition events
this.view.addEventListener('transitionend', function () { this.checkIndex() }.bind(this));
// Resize events
window.addEventListener('resize', function () { this.handleBreakpoints() }.bind(this));
},
// Hide slider buttons on the screen depending on position
hideButton: function () {
if (!this.infinite) {
if (this.index == 0) {
if (this.prev) this.prev.classList.add('hide');
} else {
if (this.prev && this.prev.classList.contains('hide')) {
this.prev.classList.remove('hide');
}
}
if (this.index == (this.slidesLength - 1) - ((this.slidesLength - 1) % this.slidesToShift)) {
if (this.next) this.next.classList.add('hide');
} else {
if (this.next && this.next.classList.contains('hide')) {
this.next.classList.remove('hide');
}
}
}
},
// Prevents the slider from going over the limit
shiftLimit: function () {
if (this.infinite) {
if (this.index < 0) {
if (this.slidesLength % this.slidesToShift != 0) {
this.wrapper.style.left = -(
(this.slidesLength - (this.slidesLength % this.slidesToShift)) * this.slideSize
) + 'px';
this.index = this.slidesLength - (this.slidesLength % this.slidesToShift);
} else {
this.wrapper.style.left = -(
(this.slidesLength - this.slidesToShift) * this.slideSize
) + 'px';
this.index = this.slidesLength - this.slidesToShift;
}
} else if (this.index >= this.slidesLength) {
this.wrapper.style.left = '0px';
this.index = 0;
}
} else {
if (this.index < 0) {
this.wrapper.style.left = '0px';
this.index = 0;
} else if (this.index >= this.slidesLength) {
if (this.slidesLength % this.slidesToShift != 0) {
this.wrapper.style.left = -(
(this.slidesLength - (this.slidesLength % this.slidesToShift)) * this.slideSize
) + 'px';
this.index = this.slidesLength - (this.slidesLength % this.slidesToShift);
} else {
this.wrapper.style.left = -(
(this.slidesLength - this.slidesToShift) * this.slideSize
) + 'px';
this.index = this.slidesLength - this.slidesToShift;
}
}
}
},
// Change the slider depending on the drag/click button event
shiftSlide: function (dir, action) {
this.wrapper.classList.add('shifting');
if (this.allowShift) {
this.allowShift = false;
if (!action) { this.startPos = this.wrapper.offsetLeft; }
if (dir === 1) {
this.wrapper.style.left = (
this.startPos - (this.slideSize * this.slidesToShift)
) + 'px'
this.index += this.slidesToShift;
} else if (dir == -1) {
this.wrapper.style.left = (
this.startPos + (this.slideSize * this.slidesToShift)
) + 'px';
this.index -= this.slidesToShift;
}
}
this.shiftLimit();
},
// Event triggered after slide animations
checkIndex: function () {
this.wrapper.classList.remove('shifting');
if (this.showPaging) this.updatePagingIndex(this.index);
if (this.showButtons) this.hideButton();
var leftPosition = parseInt(this.wrapper.style.left);
if (leftPosition % this.slideSize !== 0) this.jumpSlide(this.index);
this.allowShift = true;
},
// Update index when pass sliders
updatePagingIndex: function (index) {
if (this.paging) {
this.paging.querySelectorAll('.index').forEach(function (element) {
var elementIndex = Number(
element.classList.toString().replace(/\D/g, '')
);
if (elementIndex === index) {
if (!element.classList.contains('active')) {
element.classList.add('active');
}
} else {
if (element.classList.contains('active')) {
element.classList.remove('active');
}
}
});
}
},
// Event triggered on the paging navigation
jumpSlide: function (index) {
this.wrapper.classList.add('shifting');
this.allowShift = false;
if (index < 0 && this.infinite) {
index = this.slidesLength - 1;
} else if (index >= this.slidesLength && this.infinite) {
index = 0;
} else if (index < 0) {
index = 0;
} else if (index >= this.slidesLength) {
index = this.slidesLength - 1;
}
this.wrapper.style.left = -(index * this.slideSize) + 'px';
this.index = index;
},
// Create slider paging navigation
buildPaging: function () {
this.paging = document.createElement('div');
this.paging.classList.add('paging');
for (var i = 0; i < this.slidesLength; i++) {
if (i % this.slidesToShift == 0) {
var pagingItem = document.createElement("span");
pagingItem.classList.add('index');
pagingItem.classList.add(i);
if (i == 0) pagingItem.classList.add('active');
pagingItem.addEventListener('click', function (pagingItem) {
this.jumpSlide(Number(pagingItem.currentTarget.classList.toString().replace(/\D/g, '')))
}.bind(this));
this.paging.insertAdjacentElement('beforeend', pagingItem);
}
}
this.container.insertAdjacentElement('beforeend', this.paging);
},
// Create slider navigation buttons
buildButtons: function () {
// Previous button
this.prev = document.createElement('span');
this.prev.setAttribute('id', 'prev');
this.prev.classList.add('control', 'prev');
if (!this.infinite) this.prev.classList.add('hide');
// Next button
this.next = document.createElement('span');
this.next.setAttribute('id', 'next');
this.next.classList.add('control', 'next');
// Iserting the buttons in slider element
this.view.insertAdjacentElement('beforebegin', this.prev);
this.view.insertAdjacentElement('afterend', this.next);
// Init click events
this.prev.addEventListener('click', function () { this.shiftSlide(-1) }.bind(this));
this.next.addEventListener('click', function () { this.shiftSlide(1) }.bind(this));
}
};
yv.load = {
init: function () {
// Validates if the script exists on the page
yv.debug = false
yv.storeKey = 'e1196951-82af-4378-977b-6abe2826c5ac'
yv.endpoint = {}
yv.endpoint.standard = 'https://service.yourviews.com.br'
yv.endpoint.customstyle = yv.endpoint.standard + '/script/style?storeKey=' + yv.storeKey
yv.endpoint.reviews = yv.endpoint.standard + '/review/GetReview?storeKey=' + yv.storeKey
yv.endpoint.form = yv.endpoint.standard + '/reviewform/getreviewform?storeKey=' + yv.storeKey
yv.commom.yvData();
if (typeof yv === 'undefined') {
yv.utils.safeLog("yv variable not found.");
return;
} else {
if (yv.debug && yv.utils.qs["yv-debug"] !== 'true') {
yv.utils.safeLog("debug mode but no debug tag found. YV will not load.");
return;
}
}
if (yv.load.canStart()) {
yv.load.initScriptLoad();
} else {
//Aguarda os recursos necessários carregarem antes de iniciar o script YV.
var tmr = setInterval(function () {
if (yv.load.canStart()) {
yv.utils.safeLog("late load");
yv.load.initScriptLoad();
clearInterval(tmr);
}
}, 200);
}
},
initScriptLoad: function () {
if (typeof (yv.analyticsSupport) !== 'undefined')
yv.analyticsSupport.init();
if (window.jQuery) {
njQuery = window.jQuery;
yv.load.start();
} else {
yv.load.loadjQuery();
}
},
canStart: function () {
return true
},
loadjQuery: function () {
//Let's our own version of jQuery
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src", yv.staticServiceAddr + "/static/commom/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState === 'complete' || this.readyState === 'loaded') {
yv.load.jQueryLoaded();
}
};
} else {
script_tag.onload = yv.load.jQueryLoaded;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
},
jQueryLoaded: function () {
njQuery = window.jQuery.noConflict(true); yv.load.start();
},
start: function () {
if (typeof (yv.vendorCustom.preload) !== 'undefined') yv.vendorCustom.preload();
//window.__RUNTIME__?.route?.pageContext.id ||
yv.libraries.loadComponents();
setTimeout(() => {
yv.vendorCustom.initialSetup();
}, 2000)
if (
typeof (yv.analyticsSupport) !== 'undefined'
&& typeof (yv.analyticsSupport.startABTest) !== 'undefined') {
yv.analyticsSupport.startABTest();
}
if (typeof (yv.analytics) !== 'undefined') {
yv.analytics.start();
}
if (typeof (yv.social) !== 'undefined') {
yv.social.loadSocialActions();
}
// if (typeof (yv.review) !== 'undefined') {
// yv.review.startQuickReviewProductPage();
// yv.review.startReviews();
// yv.review.startReviewForm();
// yv.review.loadReviewShelf();
// yv.review.loadReviewPhotoGrid();
// }
// if (typeof (yv.qa) !== 'undefined') {
// yv.qa.startQa();
// }
// setTimeout(() => {
if (typeof (yv.quickReview) !== 'undefined') {
yv.awaitJSONPX = false
yv.quickReview.startQuickReview();
}
// }, 2000)
// if (typeof (yv.storeReviews) !== 'undefined') {
// yv.storeReviews.startTestimonial();
// yv.storeReviews.startStoreReview();
// }
if (
typeof (yv.review) !== 'undefined'
&& typeof (yv.review.loadStoreLocationSummary) !== 'undefined') {
yv.review.loadStoreLocationSummary();
}
yv.utils.debugLog("yv.started");
}
};
yv.storeReviews = {
startTestimonial: function () {
if (njQuery('#yv-testimonial').length) {
var element = njQuery('#yv-testimonial');
//Verifica se está no modo debug
var debug = element.data('debug');
if (debug && debug == true) {
if (yv.utils.qs["yv-debug"] != 'true') //Se estiver e não houver querystring, não carrega
{
yv.utils.safeLog('Debugging mode for Testimonial but no yv-debug querystring. Testimonial will not load');
return;
}
}
var qty = element.data('qty') || 9;
njQuery.jsonpx(yv.uriBuilder.general('/storereview/testimonial', '&qty=' + qty), function (r) {
element.html(r.html);
yv.commom.toggleViewMore();
if (element.find('.yv-slide').length > 0) {
yv.Slider.build(
[
{
slidesToShow: 3,
slidesToShift: 3,
showButtons: true,
showPaging: true,
infinite: true,
breakpoint: 9999
},
{
slidesToShow: 2,
slidesToShift: 2,
showButtons: true,
showPaging: true,
infinite: true,
breakpoint: 990
},
{
slidesToShow: 1,
slidesToShift: 1,
showButtons: true,
showPaging: true,
infinite: true,
breakpoint: 690
}
],
{
container: '.yv-testimonial__container',
view: '.yv-testimonial__container__view',
wrapper: '.yv-testimonial__container__view__wrapper',
slides: '.yv-slide',
},
qty
);
element.show();
}
});
}
},
startStoreReview: function () {
yv.storeReviews.loadStampModal();
var element = njQuery('.yv-storereviews');
if (!element || element.length == 0) return;
//Verifica se está no modo debug
var debug = element.data('debug');
if (debug && debug == true) {
//Se estiver e não houver querystring, não carrega
if (yv.utils.qs["yv-debug"] != 'true') {
yv.utils.safeLog('Debugging mode for store reviews but no yv-debug querystring. Store reviews will not load');
return;
}
}
yv.utils.toggleLoading(false, '.yv-store-review');
njQuery.jsonpx(yv.uriBuilder.general('/storereview/reviews'), function (r) {
yv.storeReviews.loadStoreReviewResult(r);
yv.utils.toggleLoading(true, '.yv-store-review');
});
},
loadStoreReviewResult: function (r) {
var element = njQuery('.yv-storereviews');
element.html(r.html);
yv.commom.loadPaging(yv.storeReviews.loadStoreReviewResult, yv.storeReviews.loadStoreReviewResult, '.yv-store-review');
},
loadStoreReview: function () {
var element = njQuery('.yv-storereviews');
if (!element || element.length == 0) return;
//Verifica se está no modo debug
var debug = element.data('debug');
if (debug && debug == true) {
if (yv.utils.qs["yv-debug"] != 'true') //Se estiver e não houver querystring, não carrega
{
yv.utils.safeLog('Debugging mode for store reviews but no yv-debug querystring. Store reviews will not load');
return;
}
}
yv.utils.toggleLoading(false, '.yv-store-review');
njQuery.jsonpx(yv.uriBuilder.general('/storereview/reviews'), function (r) {
yv.storeReviews.loadStoreReviewResult(r);
yv.utils.toggleLoading(true, '.yv-store-review');
});
},
loadStampModal: function () {
var baseUrl = 'https://www.lojaconfiavel.com/trustedstore/modal/';
njQuery('[data-lcname],img[title="Loja Confiável"][src*="Footer.jpg"],img[title="Loja Confiável"][src*="Footer.jpg"]').click(function (event) {
var storeName = '';
var tgt = njQuery(event.target);
if (tgt[0].hasAttribute('data-lcname')) {
storeName = njQuery(tgt).attr('data-lcname');
} else {
var linkElement = njQuery(event.target).parent();
if (linkElement) {
var attrElement = linkElement.attr('href');
if (attrElement) {
if (attrElement.indexOf('?') > -1) {
storeName = attrElement.split('utm_source=')[1];
} else {
var splitted = attrElement.split('/');
storeName = splitted[splitted.length - 1];
}
}
}
}
if (storeName != '') {
if (!njQuery('.yv-trustedstore-modal').length) {
var modalBody = "
";
njQuery('body').append(modalBody);
njQuery('.yv-modal-close,.yv-trustedstore-modal').click(function (r) {
njQuery('.yv-trustedstore-modal').modal('hide');
njQuery('.yv-modal-backdrop.yv-fade.yv-in').remove();
});
}
njQuery('.yv-trustedstore-modal').modal('show');
event.preventDefault();
return false;
}
});
}
}
yv.qa = {
startQa: function () {
yv.qa.loadAnswered();
yv.qa.loadQaActions();
var element = document.querySelector(yv.vendorCustom.QaElement());
if (!element || !yv.commom.debugIsCorrect(element)) { return; }
var tpl = '';
if (yv.utils.qs['yv-qa-template']) {
tpl = '&yv-qa-template=' + yv.utils.qs['yv-qa-template'];
}
njQuery.jsonpx(yv.uriBuilder.generalSecondary('/questionanswer', '&productId=' + yv.productId + tpl), function (r) {
if (!r.html) return
yv.utils.toggleLoading(element)
yv.qa.loadQAData(r)
yv.qa.startQAAnchor();
});
},
loadAnswered: function () {
if (njQuery('#yv-show-form').length) {
if (yv.utils.qs['questionId']) {
yv.analyticsSupport.startReviewFormAnalytics();
var qid = yv.utils.qs['questionId'];
var u = yv.utils.qs['yv-u'];
var param = '&questionId=' + qid + '&yv-u=' + u;
njQuery.jsonpx(yv.uriBuilder.general('/questionanswer/getquestion', param), function (r) {
njQuery('#yv-show-form').html(r.html);
if (yv.analyticsSupport.trackAnswer != 'undefined') {
var additionalData = '[{localaddr: "' + encodeURIComponent(window.location.href) + '"}]';
yv.analyticsSupport.trackAnswer('clickEmail', additionalData);
}
njQuery('.yv-qa-focuslogin').focus();
});
}
}
},
loadQAData: function (r) {
if (!r || !r.html) return;
const element = document.querySelector(yv.vendorCustom.QaElement());
element.replaceChildren('')
element.insertAdjacentHTML('beforeend', r.html);
yv.utils.toggleLoading(element);
yv.analyticsSupport.startReviewFormAnalytics();
},
// Carrega o elemento de login quando o usuário começa à digitar
loadLoginElement: function (eventIpt) {
const boxForm = eventIpt.closest('[yv-role="form-box-qa"], [yv-role="form-box-reply"]')
const formQuestion = boxForm.querySelector('[yv-role="form-question"], [yv-role="form-answer"]')
const formLogin = boxForm.querySelector('[yv-role="form-login"]')
if (!formLogin) {
njQuery.jsonpx(yv.uriBuilder.general('/questionanswer/login'), function (r) {
formQuestion.insertAdjacentHTML('afterend', r.html)
});
}
},
// Retorna todos os inputs de pergunta
getAllQaInputs: function (boxForm) {
let storeInputs = []
let productInputs = []
let questionInputs = []
let answerInputs = []
let loginInputs = []
let allReviewInputs = []
storeInputs = document.querySelectorAll(boxForm + ' [yv-role="form-store"] [yv-role="form-input"]')
productInputs = document.querySelectorAll(boxForm + ' [yv-role="form-product"] [yv-role="form-input"]')
questionInputs = document.querySelectorAll(boxForm + ' [yv-role="form-question"] [yv-role="form-input"]')
answerInputs = document.querySelectorAll(boxForm + ' [yv-role="form-answer"] [yv-role="form-input"]')
document.querySelectorAll(boxForm + ' [yv-role="form-login"]').forEach(function (e) {
if (!e.classList.contains('hide')) {
loginInputs = e.querySelectorAll('[yv-role="form-input"]')
}
})
if (storeInputs.length) storeInputs.forEach(function (e) { allReviewInputs.push(e) })
if (productInputs.length) productInputs.forEach(function (e) { allReviewInputs.push(e) })
if (loginInputs.length) loginInputs.forEach(function (e) { allReviewInputs.push(e) })
if (questionInputs.length) questionInputs.forEach(function (e) { allReviewInputs.push(e) })
if (answerInputs.length) answerInputs.forEach(function (e) { allReviewInputs.push(e) })
return allReviewInputs
},
// Salva pergunta na base
saveQuestion: function (eventBtn, boxForm) {
if (eventBtn && eventBtn.disabled) return
eventBtn.setAttribute('disabled', true)
if (!yv.validation.validateForm(boxForm)) {
eventBtn.removeAttribute('disabled')
return
}
const allReviewInputs = yv.qa.getAllQaInputs(boxForm)
eventBtn.removeAttribute('disabled')
var data = njQuery(allReviewInputs).serialize() + yv.commom.getProductDetails()
if (yv.categoryForm && yv.categoryForm.length > 0) {
data += njQuery([].concat(yv.categoryForm).reverse()).map(function (i, v) {
return "&formId=" + encodeURIComponent(v);
}).get().join('');
}
var productId = window.yv.productId || yv.utils.qs["idproduto"];
if (yv.utils.qs['questionId'] && yv.analyticsSupport.trackAnswer != 'undefined') {
yv.analyticsSupport.trackAnswer('saveAnswer');
yv.utils.safeLog('saveAnswer');
}
var uri = yv.uriBuilder.general('/questionanswer/savequestion', '&productId=' + productId + '&' + data);
njQuery.jsonpx(uri, function (result) {
njQuery('[yv-role="form-box-qa"]')
.html(result.html);
}).fail(function (jqXHR, textStatus, err) {
njQuery('[yv-role="form-box-qa"]')
.html('
Falha no envio do formulário
' + yv.localization.portuguese.genericError + '
');
});
},
// Esconde o botão de escrever resposta após envio da resposta
hideAnswerButton: function (answerBtn) {
if (!answerBtn.classList.contains('is-hide')) answerBtn.classList.toggle('is-hide')
},
// Salva resposta na base
saveAnswer: function (eventBtn, boxForm) {
if (eventBtn && eventBtn.disabled) return
eventBtn.setAttribute('disabled', true)
const replyElement = eventBtn.parentElement
const questionId = replyElement.parentElement.getAttribute('yv-data')
if (!yv.validation.validateForm(boxForm)) {
eventBtn.removeAttribute('disabled')
return
}
const allReviewInputs = yv.qa.getAllQaInputs(boxForm)
eventBtn.removeAttribute('disabled')
const data = njQuery(allReviewInputs).serialize()
const productId = window.yv.productId || yv.utils.qs["idproduto"]
const uri = yv.uriBuilder.general('/questionanswer/saveanswer', '&productId=' + productId + '&' + data + '&questionId=' + questionId)
njQuery.jsonpx(uri, function (res) {
if (res.html) {
replyElement.replaceChildren('')
replyElement.insertAdjacentHTML('beforeend', res.html)
yv.qa.hideAnswerButton(replyElement.parentElement.querySelector('[yv-role="question"] [yv-role="button-reply"]'))
}
}).fail(function (jqXHR, textStatus, err) {
replyElement.replaceChildren('')
replyElement.insertAdjacentHTML('beforeend', '
Falha no envio do formulário
' + yv.localization.portuguese.genericError + '
')
yv.qa.hideAnswerButton(replyElement.parentElement.querySelector('[yv-role="question"] [yv-role="button-reply"]'))
});
},
// Funções dos botões de perguntas & respostas
loadQaActions: function () {
if (yv.qaActionsLoaded) return
yv.commom.loadPaging(yv.qa.loadQAData, yv.qa.loadQAData, yv.vendorCustom.QaElement());
document.addEventListener('click', function (e) {
const eventBtn = e.target.closest('[yv-action]')
if (!eventBtn) return
if (e.detail === 1) {
if (eventBtn && eventBtn.getAttribute('yv-action') == 'write-question') {
yv.qa.loadLoginElement(eventBtn)
} else if (eventBtn && eventBtn.getAttribute('yv-action') == 'write-answer') {
yv.qa.loadLoginElement(eventBtn)
} else if (eventBtn && eventBtn.getAttribute('yv-action') == 'send-question') {
yv.qa.saveQuestion(eventBtn, '[yv-role="form-box-qa"]')
} else if (eventBtn && eventBtn.getAttribute('yv-action') == 'send-answer') {
yv.qa.saveAnswer(eventBtn, '[yv-role="form-box-reply"]:not(.is-hide)')
} else if (eventBtn && eventBtn.getAttribute('yv-action') == 'send-similar-answer') {
yv.qa.saveQuestionWhithoutSimiliar(eventBtn)
}
}
})
yv.qaActionsLoaded = true;
},
saveQuestionWhithoutSimiliar: function (eventBtn) {
eventBtn.setAttribute('disabled', true)
const boxForm = eventBtn.closest('[yv-role="form-box-qa"]')
const allQaInputs = boxForm.querySelectorAll('input')
const data = njQuery(allQaInputs).serialize() + yv.commom.getProductDetails();
const uri = yv.uriBuilder.general(
'/questionanswer/saveQuestionWithoutSimiliar',
'&productId=' + window.yv.productId + '&' + data
)
yv.utils.goTo(boxForm)
yv.utils.toggleLoading(boxForm)
njQuery.jsonpx(uri, function (res) {
boxForm.replaceChildren('')
boxForm.insertAdjacentHTML('beforeend', res.html)
yv.utils.toggleLoading(boxForm)
}).fail(function (jqXHR, textStatus, err) {
boxForm.replaceChildren('')
boxForm.insertAdjacentHTML(
'beforeend',
'
Falha no envio do formulário
' + yv.localization.portuguese.genericError + '
'
)
yv.utils.toggleLoading(boxForm)
})
},
startQAAnchor: function () {
var mainElement = njQuery('.yv-qa-anchor');
if (mainElement.length) {
njQuery.jsonpx(yv.uriBuilder.general('/questionanswer/QuestionAnchor', '&idProductStore=' + yv.productId),
function (resp) {
mainElement.html(resp.html);
mainElement.click(function () {
yv.utils.goTo('.yv-qa');
yv.analyticsSupport.trackWriteReview('qa-more');
});
});
}
}
}
//subsitituir quickreview.js por esse abaixo
//e trocar scripts das prateleiras no vendorCustom
yv.quickReview = {
quickReviewSetResult: function (e) {
const shelfId = e.productId
const shelfData = e.data
const shelfs = document.querySelectorAll('.yv-review-quickreview:not(.is-loaded)[value="' + shelfId + '"]')
shelfs.forEach(function (shelf) {
if (!shelf.classList.contains('is-loaded')) {
shelf.classList.add('is-loaded')
shelf.addEventListener('mouseenter', function () {
yv.quickReview.searchRelevantReview(njQuery(shelf))
})
}
shelf.replaceChildren('')
shelf.insertAdjacentHTML('beforeend', shelfData);
yv.awaitJSONPX = false
})
},
showQuickReview: function (shelfsRes) {
shelfsRes.forEach(function (e) {
if (e && e.productId && e.data) yv.quickReview.quickReviewSetResult(e)
})
},
getProductShelf: function (shelfsNotLoaded) {
const endpoint = yv.uriBuilder.general('/review/productShelf', '&ids=' + shelfsNotLoaded.join(','))
yv.awaitJSONPX = true
njQuery.jsonpx(endpoint, function (res) {
if (!res.html) return
const parsedRes = JSON.parse(res.html)
if (parsedRes) yv.quickReview.showQuickReview(parsedRes);
});
},
searchExecuteQuickReview: function () {
const shelfsToLoad = yv.vendorCustom.quickReviewGetIds()
if (shelfsToLoad && shelfsToLoad.length && !yv.awaitJSONPX) {
yv.quickReview.getProductShelf(shelfsToLoad)
}
return
},
searchRelevantReview: function (product) {
if (yv.awaitJSONPX) return
if (product.attr('data-content') != undefined) return
if (!product.attr('data-product-id')) return
var productId = product.attr('data-product-id');
var url = yv.uriBuilder.general('/review/ReviewRelevant', '&productStoreId=' + productId);
yv.awaitJSONPX = true
njQuery.jsonpx(url, function (r) {
yv.awaitJSONPX = false
if (!r.html) {
product.attr('data-content', "");
}else{
product.on('shown.bs.popover', function () {
setTimeout(function () {
product.popover('hide');
}, 12000);
});
product.popover({
content: r.html,
trigger: 'hover',
html: true,
title: 'O que as pessoas acham',
placement: "auto yv-bottom",
container: '#yv-popover'
}).popover('show');
product.attr('data-content', r.html);
}
});
},
startQuickReview: function () {
if (yv.quickReviewStarted == true) return
setInterval(yv.quickReview.searchExecuteQuickReview, 500)
yv.quickReviewStarted = true;
if (njQuery('#yv-popover').length == 0) {
njQuery('body')
.append('')
}
}
}
yv.validation = {
// Pega todos os campos invalidos, manda para o analytics e volta para primeiro input inválido
setInvalidInput: function (form, errorTrack) {
const invalidInputNames = []
yv.utils.goTo(form + ' [yv-role="input-field"].has-error')
const invalidFields = document.querySelectorAll(form + ' [yv-role="input-field"].has-error')
invalidFields.forEach(function (e, i) {
const invalidInputs = e.querySelectorAll('[yv-role="form-input"]')
invalidInputs.forEach(function (e, i) {
if (!invalidInputNames.includes(e.name)) {
invalidInputNames.push(e.name)
}
})
})
const invalidInputResult = JSON.stringify(invalidInputNames)
yv.analyticsSupport.trackWriteReview(errorTrack, invalidInputResult)
},
// Insere erro no input se ele for inválido
setError: function (e, errorMessage, validation) {
const field = e.closest('[yv-role="input-field"]')
const label = field.querySelector('[yv-role="input-label"]')
const errorElement = '' + errorMessage + ''
if (!field.classList.contains('has-error')) {
field.classList.toggle('has-error')
}
if (!label.querySelector('[yv-role="input-error"]')) {
label.insertAdjacentHTML('beforeend', errorElement)
}
e.addEventListener('change', function (v) {
const targetInput = v.target
if (!validation(targetInput)) {
if (!field.classList.contains('has-error')) {
field.classList.toggle('has-error')
}
if (!label.querySelector('[yv-role="input-error"]')) {
label.insertAdjacentHTML('beforeend', errorElement)
}
} else {
if (field.classList.contains('has-error')) {
field.classList.toggle('has-error')
}
if (label.querySelector('[yv-role="input-error"]')) {
label.querySelector('[yv-role="input-error"]').remove()
}
}
})
},
// Valida se o input é não nulo e válido antes do seu envio
validateEmptyInput: function (input) {
let isValid = true
if (input.type == 'radio' || input.type == 'checkbox') {
if (!document.querySelectorAll('[name="' + input.name + '"]:checked').length) {
isValid = false
}
}
if (input.type == 'text' || input.type == 'textarea' || input.type == 'hidden') {
if (!input.value) {
isValid = false
}
}
return isValid
},
validateEmailInput: function (input) {
let isValid = true
const rgx = /^[a-z0-9.]+@[a-z0-9]+\.[a-z]+(\.[a-z]+)?$/i
if (!rgx.test(input.value)) isValid = false
return isValid
},
// Realiza validação do usuário
isValidUser: function (loginForm) {
let isValid = true
const loginForms = document.querySelectorAll(loginForm)
let userPhone = ''
let userName = ''
let userEmail = ''
loginForms.forEach(function (e) {
if (!e.classList.contains('hide')) {
userPhone = e.querySelector(loginForm + ' [yv-role="form-input"][name="yv-user-phone"]')
userName = e.querySelector(loginForm + ' [yv-role="form-input"][name="user-name"]')
userEmail = e.querySelector(loginForm + ' [yv-role="form-input"][name="user-email"]')
if (!userName) userName = e.querySelector(loginForm + ' [yv-role="form-input"][name="yv-exhibition-name"]')
}
})
return userName.value && userEmail.value ? true : false
},
// Valida campos do formulário de login
isValidLogin: function (loginForm) {
let isValid = true
const invalidEmail = yv.localization.portuguese.invalidEmail
const errorMessage = yv.localization.portuguese.requiredField
let requiredElements = []
const loginForms = document.querySelectorAll(loginForm)
if (!loginForms.length) return isValid = false
loginForms.forEach(function (e) {
if (!e.classList.contains('hide')) {
requiredElements = e.querySelectorAll(loginForm + ' [yv-role="form-input"]')
}
})
requiredElements.forEach(function (e, i) {
if (e.type != 'hidden' && e.getAttribute('name') == 'user-email') {
if (!yv.validation.validateEmailInput(e)) {
yv.validation.setError(e, invalidEmail, yv.validation.validateEmailInput)
isValid = false
}
} else if (e.type != 'hidden') {
if (!yv.validation.validateEmptyInput(e)) {
yv.validation.setError(e, errorMessage, yv.validation.validateEmptyInput)
isValid = false
}
}
})
return isValid
},
// Valida campos dos formulários
isValidForm: function (productForm) {
let isValid = true
const requiredElements = document.querySelectorAll(productForm + ' [yv-role="form-input"][required]')
const errorMessage = yv.localization.portuguese.requiredField
requiredElements.forEach(function (e, i) {
if (e.type != 'hidden' && !yv.validation.validateEmptyInput(e)) {
yv.validation.setError(e, errorMessage, yv.validation.validateEmptyInput)
isValid = false
}
})
return isValid
},
// Realiza a validação de todos os formulários
validateForm: function (formBox) {
let isValid = true
const validStoreForm = yv.validation.isValidForm(formBox + ' [yv-role="form-store"]')
const validProductForm = yv.validation.isValidForm(formBox + ' [yv-role="form-product"]')
const validQuestionForm = yv.validation.isValidForm(formBox + ' [yv-role="form-question"]')
const validAnswerForm = yv.validation.isValidForm(formBox + ' [yv-role="form-answer"]')
const validLoginForm = yv.validation.isValidLogin(formBox + ' [yv-role="form-login"]')
const validUser = yv.validation.isValidUser(formBox + ' [yv-role="form-login"]');
if (!validProductForm || !validQuestionForm || !validAnswerForm || !validUser || !validStoreForm || !validLoginForm) {
if (!validProductForm) {
yv.validation.setInvalidInput(formBox + ' [yv-role="form-product"]', 'errRequiredFields')
} else if (!validQuestionForm) {
yv.validation.setInvalidInput(formBox + ' [yv-role="form-question"]', 'errRequiredFields')
} else if (!validAnswerForm) {
yv.validation.setInvalidInput(formBox + ' [yv-role="form-answer"]', 'errRequiredFields')
} else if (!validUser) {
yv.validation.setInvalidInput(formBox + ' [yv-role="form-login"]', 'errValidateUser')
} else if (!validStoreForm) {
yv.validation.setInvalidInput(formBox + ' [yv-role="form-store"]', 'errValidateUser')
}
if (isValid) isValid = false
}
return isValid
}
}
// layout F
yv.review = {
// nova estrutura em JS puro e alterada
loadRichSnippets: function () {
// Evita chamada duplicada
if (yv.alreadInsertedRichSnippet) return;
yv.alreadInsertedRichSnippet = true;
// Procura pelo snippet de produto
yv.review.searchProductSnippet()
},
searchProductSnippet: function() {
var count = 0
const search = setInterval(() => {
var productSnippet = null
// Seletor do JSON-LD da página
productSnippet = [...document.querySelectorAll('[type="application/ld+json"]')].filter(e => (JSON.parse(e.innerHTML)['@type'] === "Product")).pop()
if (productSnippet) {
clearInterval(search)
yv.review.requestRichSnippets(productSnippet, 'json-ld')
}
productSnippet = [...document.querySelectorAll('[itemtype="http://schema.org/Product"]')]
if (productSnippet.length == 1) {
yv.review.requestRichSnippets(...productSnippet, 'microdata')
clearInterval(search)
}else if (productSnippet.length > 1) {
yv.utils.safeLog("Mora than one review snippets microdata found");
clearInterval(search)
}
if (count >= 8){
clearInterval(search)
yv.utils.safeLog("Structured data not found");
yv.review.requestRichSnippets(productSnippet, '')
}
count++
},250)
},
requestRichSnippets: function(productSnippet, snippetFormat) {
// Valida se tem o productId
if (yv.productId)
var params = 'idProductstore=' + yv.productId;
else {
yv.utils.safeLog('Product ID not found!');
return
}
// Product availability
var outOfStock = '.alert-stock';
if (document.querySelectorAll(outOfStock).length)
params = params + "&availability=false";
// Verifica se precisa fazer o merge
var appendJson = true;
if (snippetFormat === ''){
appendJson = false;
}
// Valida o JSON-LD caso seja
if (snippetFormat === 'json-ld'){
try{
JSON.parse(productSnippet.innerHTML)
}catch(e){
yv.utils.safeLog("JSON-LD malformed");
}
}
// Endpoint
var uri = yv.uriBuilder.generalSecondary('/review/richsnippetgeneric/').replace('callback=?','') + params;
// Request
yv.utils.safeLog('Trying to insert Review Snippets');
console.time('[Yourviews] - Fetch')
fetch(uri, {
'method':'POST',
'headers' : {
'Content-Type': 'application/json; charset=utf-8'
},
'body':JSON.stringify({ currentJson: "" }),
})
.then((response) => {
console.timeEnd('[Yourviews] - Fetch')
if (!response.ok) throw Error (response.statusText)
return response.json()
})
.then((response) => {
// Merge review snippets
if (appendJson) {
// Merge review snippets JSON-LD
if (snippetFormat === 'json-ld'){
const JSONElement = JSON.parse(new DOMParser().parseFromString(response, "text/html").querySelector("script").innerHTML)
if (JSONElement){
const JSONProductSnippet = JSON.parse(productSnippet.innerHTML)
JSONProductSnippet["aggregateRating"] = JSONElement["aggregateRating"]
JSONProductSnippet["review"] = JSONElement["review"]
productSnippet.innerHTML = JSON.stringify(JSONProductSnippet)
productSnippet.setAttribute('yourviews-rich-snippet-added','true')
}
yv.utils.safeLog('Review Snippets JSON-LD Merged!')
} else if (snippetFormat === 'microdata'){
// Merge review snippets Microdata
const JSONElement = JSON.parse(new DOMParser().parseFromString(response, "text/html").querySelector("script").innerHTML)
if (JSONElement){
const productMicrodata = document.querySelector('[itemtype="http://schema.org/Product"]')
const reviewsArray = JSONElement.review
const aggregateRatingHTML = ``
productMicrodata.insertAdjacentHTML('beforeend',aggregateRatingHTML)
reviewsArray.forEach((r) => {
let reviewHTML = `
`
productMicrodata.insertAdjacentHTML('beforeend',reviewHTML)
})
productMicrodata.setAttribute('yourviews-rich-snippet-added','true')
}
yv.utils.safeLog('Review Snippets Microdata Merged!');
}
} else {
// Append review snippets JSON-LD
document.querySelector('head').insertAdjacentHTML('beforeend', response)
yv.utils.safeLog('Review Snippets JSON-LD Added!');
}
})
},
startQuickReviewProductPage: function () {
const quickReviewAnchor = document.querySelector('#yv-review-quickreview')
if (quickReviewAnchor) {
if (quickReviewAnchor.classList.contains('is-hide')) quickReviewAnchor.classList.toggle('is-hide')
njQuery.jsonpx(
yv.uriBuilder.general('/review/getquickreviewproduct', '&productStoreId=' + yv.productId),
function (res) {
yv.vendorCustom.quickReviewProdBefore()
quickReviewAnchor.insertAdjacentHTML(
'beforeend',
res.html
)
quickReviewAnchor.addEventListener('click', function () {
yv.utils.goTo(yv.vendorCustom.reviewsElement())
njQuery('.data.item.title[aria-controls="reviews"]').click();
yv.analyticsSupport.trackWriteReview('review-more')
})
}
);
}
},
loadReviewShelf: function () {
if (njQuery('.yv-reviewshelf').length && yv.categoryIds && yv.categoryIds.length) {
var tag = njQuery('.yv-reviewshelf').attr('data-tag');
var qtd = njQuery('.yv-reviewshelf').attr('data-qty');
var ids = { categories: yv.categoryIds, qty: qtd, tag: tag };
var uri = yv.uriBuilder.general('/review/reviewshelf', '&' + njQuery.param(ids, true));
njQuery.jsonpx(uri, function (r) {
if (r && r.html) {
njQuery('.yv-reviewshelf').html(r.html);
yv.commom.toggleViewMore();
}
});
}
},
loadStoreLocationSummary: function () {
if (njQuery('.yv-seller-reviews').length && njQuery('.yv-seller-reviews').length > 0 && (njQuery('.yv-seller-reviews').data('yvsellerid') || (yv.idInternalStoreLocation && yv.idInternalStoreLocation != 'undefined'))) {
if (!yv.idInternalStoreLocation) {
yv.idInternalStoreLocation = njQuery('.yv-seller-reviews').data('yvsellerid');
}
var uri = yv.uriBuilder.general('/storelocationsummary/getstorelocationsummary', '&idInternalStoreLocation=' + yv.idInternalStoreLocation);
njQuery.jsonpx(uri, function (r) {
if (r && r.html) {
njQuery('.yv-seller-reviews').html(r.html);
var hasClickEvent = njQuery._data(njQuery('.yv-viewmore-btn').get(0), "events");
//verifica se não existe o evento de click na class viewmore, estava bugando o evento caso add no listener de click 2 vezes.
if (!hasClickEvent || !hasClickEvent.click) {
yv.commom.toggleViewMore();
};
}
});
}
},
startReviewForm: function () {
const reviewBox = document.querySelector('#yv-show-form') || document.querySelector('[yv-role="form-box-review"]')
if (reviewBox) {
if (yv.utils.qs['yv-write-review']) {
yv.review.showWriteReview();
yv.review.loadReviewsActions();
var additionalData = '[{localaddr: "' + encodeURIComponent(window.location.href) + '"}]';
if (yv.utils.qs['yv-sms']) {
yv.analyticsSupport.trackWriteReview('clickSms', additionalData);
} else {
yv.analyticsSupport.trackWriteReview('clickEmail', additionalData);
}
}
}
},
startReviews: function () {
if (njQuery(yv.vendorCustom.reviewsElement()).length) {
yv.review.loadReviews();
yv.review.loadReviewsActions();
yv.commom.loadLikeUnlike();
yv.commom.loadPaging(yv.review.loadReviewData, yv.review.loadReviewData, yv.vendorCustom.reviewsElement());
}
},
loadReviews: function () {
yv.vendorCustom.reviewsBefore();
var urlImageGif = (
'https:' == document.location.protocol
? 'https://'
: 'http://'
) + 'staticfiles.yviews.com.br/static/images/loading.gif'
yv.review.getReviews();
},
setOrderText: function (order) {
switch (order) {
case '1':
return 'Mais recentes'
case '2':
return 'Avaliações negativas'
case '3':
return 'Avaliações positivas'
case '4':
return 'Mais úteis'
default:
return 'Selecione'
}
},
getReviews: function () {
var querystring = "&extendedField=";
if (typeof yv.filters != "undefined" && yv.filters.length > 0) {
var querysFilters = "";
njQuery.each(yv.filters, function (i, v) {
if ((typeof v.FilterFieldId != 'undefined') && (typeof v.FilterFieldValueId != 'undefined'))
querysFilters += v.FilterFieldId + ":" + v.FilterFieldValueId + ",";
});
querystring += querysFilters;
}
if (yv.utils.qs['yv-review-template']) {
querystring += '&yv-review-template=' + yv.utils.qs['yv-review-template'];
}
var productId = window.yv.productId;
if (yv.order) querystring += "&orderby=" + yv.order;
njQuery.jsonpx(yv.uriBuilder.general('/review/GetReview', '&productStoreId=' + productId + querystring), function (r) {
yv.review.loadReviewData(r);
const dropLabel = document.querySelector('[yv-role="dropdown-menu"] [yv-role="dropdown-label"]')
if (dropLabel) {
const orderText = yv.order ? yv.review.setOrderText(yv.order) : 'Selecione'
dropLabel.innerText = orderText
}
yv.utils.toggleLoading(yv.vendorCustom.reviewsElement())
});
},
loadUserUploadedImages: function () {
if (njQuery('[data-yvaction="userimg-reviewshow"]').length) {
njQuery('[yv-action="open-modal"]').simpleLightbox(
{
fileExt: false,
widthRatio: 0.7,
heightRatio: 0.6,
additionalHtml: '
'
});
}
},
loadFilters: function () {
window.yv.filters = window.yv.filters || [];
//Esconde todos os botões "fechar" dos filtros
njQuery('.yv-filter-close').hide();
//Para cada filtro existente, exibe o botão "fechar"
njQuery.each(yv.filters, function (i, v) {
njQuery('.yv-filter-close[data-yv-efvid="' + v.FilterFieldValueId + '"]').show();
});
njQuery('.yv-filter-close').click(function (e) {
var fieldValueId = njQuery(this).attr('data-yv-efvid');
//Remove o filtro clicado
yv.filters = njQuery.grep(yv.filters, function (o) { return o.FilterFieldValueId == fieldValueId }, true);
yv.review.getReviews();
});
njQuery('.yv-filter').click(function (event) {
event.preventDefault();
//Busca os valores de Ids do objeto clicado
var fieldValueId = njQuery(this).attr('data-yv-efvid');
var fieldId = njQuery(this).siblings('.yv-filter-heading').attr('data-yv-efid');
//Armazena novo filtro
window.yv.filters.push({ FilterFieldId: fieldId, FilterFieldValueId: fieldValueId });
//Recarrega os reviews
yv.review.getReviews();
return false;
});
},
// Função que carrega as ações dos reviews
loadReviewsActions: function () {
if (yv.reviewsActionsLoaded) return
document.addEventListener('click', function (e) {
const eventBtn = e.target.closest('[yv-action]')
if (!eventBtn) return
const yvAction = eventBtn.getAttribute('yv-action')
switch (yvAction) {
case 'write-review':
yv.review.showWriteReview();
break
case 'send-review':
yv.review.saveReview(eventBtn, '[yv-role="form-box-review"]')
break
case 'send-storeform':
yv.review.saveReviewStore(eventBtn, '[yv-role="form-box-review"]')
break
default:
break
}
})
yv.reviewsActionsLoaded = true;
},
// Função que carrega o percentual de recomendações das avaliações da página
updateChartBox: function () {
const chartBox = document.querySelector('[yv-role="chart-box"]')
if (chartBox) {
const chartBoxLabel = chartBox.querySelector('[yv-role="chart-box-label"]')
const chartBoxValue = chartBox.querySelector('[yv-role="chart-box-value"]')
const recommend = Number(chartBox.querySelector('[yv-role="chart-box-recommend"]').getAttribute('value'))
const notRecommend = Number(chartBox.querySelector('[yv-role="chart-box-notrecommend"]').getAttribute('value'))
let totalRecommend = Number((recommend * 100) / (recommend + notRecommend)).toFixed(1)
if (totalRecommend > 100 || totalRecommend == 'NaN') totalRecommend = 100
chartBoxValue.setAttribute('stroke-dasharray', totalRecommend + ', 100')
chartBoxLabel.innerHTML = totalRecommend + '%'
}
},
loadReviewData: function (r) {
const reviews = document.querySelector(yv.vendorCustom.reviewsElement())
if (r.html && r.hasResults) {
reviews.replaceChildren('')
reviews.insertAdjacentHTML('beforeend', r.html)
yv.review.loadRichSnippets();
yv.review.updateChartBox();
yv.review.loadFilters();
yv.review.loadUserUploadedImages();
yv.commom.toggleViewMore();
yv.analyticsSupport.trackScrollReview();
} else if (r.html && !r.hasResults) {
reviews.replaceChildren('')
reviews.insertAdjacentHTML('beforeend', r.html)
}
// Se houver querystring, abre editor de formulário
yv.review.gotoWriteReview();
yv.utils.toggleLoading(yv.vendorCustom.reviewsElement())
},
getAllReviewInputs: function (formBox) {
let storeInputs = []
let productInputs = []
let questionInputs = []
let answerInputs = []
let loginInputs = []
let uploadcareInputs = []
let allReviewInputs = []
storeInputs = document.querySelectorAll(formBox + ' [yv-role="form-store"] [yv-role="form-input"]')
productInputs = document.querySelectorAll(formBox + ' [yv-role="form-product"] [yv-role="form-input"]')
questionInputs = document.querySelectorAll(formBox + ' [yv-role="form-question"] [yv-role="form-input"]')
answerInputs = document.querySelectorAll(formBox + ' [yv-role="form-answer"] [yv-role="form-input"]')
uploadcareInputs = document.querySelectorAll(formBox + ' [yv-role="form-upload"]')
document.querySelectorAll(formBox + ' [yv-role="form-login"]').forEach(function (e) {
if (!e.classList.contains('hide')) {
loginInputs = e.querySelectorAll('[yv-role="form-input"]')
}
})
if (storeInputs.length) storeInputs.forEach(function (e) { allReviewInputs.push(e) })
if (productInputs.length) productInputs.forEach(function (e) { allReviewInputs.push(e) })
if (loginInputs.length) loginInputs.forEach(function (e) { allReviewInputs.push(e) })
if (questionInputs.length) questionInputs.forEach(function (e) { allReviewInputs.push(e) })
if (answerInputs.length) answerInputs.forEach(function (e) { allReviewInputs.push(e) })
if (uploadcareInputs.length) uploadcareInputs.forEach(function (e) { allReviewInputs.push(e) })
return allReviewInputs
},
saveReview: function (eventBtn, boxForm) {
if (eventBtn && eventBtn.disabled == true) return
const eventContainer = eventBtn.closest(boxForm)
eventBtn.setAttribute('disabled', true)
if (!yv.validation.validateForm(boxForm)) {
eventBtn.removeAttribute('disabled')
return
}
yv.utils.toggleLoading(boxForm)
const allReviewInputs = yv.review.getAllReviewInputs(boxForm)
// Pega dados do formulário
let data = njQuery(allReviewInputs).serialize();
// Se for um review proveniente de sms coloca na query string pra tracking
if (yv.utils.qs["yv-sms"]) {
data += '&yv-sms=' + encodeURIComponent(yv.utils.qs['yv-sms']);
}
// Se houver, pega id da ordem
if (yv.utils.qs["yv-o"]) {
data += '&yv-o=' + encodeURIComponent(yv.utils.qs['yv-o']);
}
// Se houver, pega id do sku
if (yv.utils.qs["yv-sku"]) {
data += '&yv-sku=' + encodeURIComponent(yv.utils.qs['yv-sku']);
}
// Se houver, pega id da solicitação
if (yv.utils.qs["yv-rr"]) {
data += '&yv-rr=' + encodeURIComponent(yv.utils.qs['yv-rr']);
}
// Pega dados do produto
data += yv.commom.getProductDetails();
// Tracking para quando salvar review
if (yv.utils.qs['yv-sr']) {
// Tracking do sistema de "Avaliar também"
yv.analyticsSupport.trackEvent('saveReview', 'alsoreview');
} else {
if (yv.utils.qs["yv-sms"]) {
// Tracking do sistema sms
yv.analyticsSupport.trackWriteReview('saveReviewSms');
} else {
// Tracking do sistema normal
yv.analyticsSupport.trackWriteReview('saveReview');
}
}
// Envia de fato os dados para salvar
const uri = yv.uriBuilder.general('/reviewformsave/SaveReviewForm', '&productId=' + yv.productId + '&' + data);
njQuery.jsonpx(uri, function (res) {
eventContainer.replaceChildren('')
eventContainer.insertAdjacentHTML('beforeend', res.html)
yv.utils.toggleLoading(boxForm)
})
.fail(function () {
eventContainer.replaceChildren('')
eventContainer.insertAdjacentHTML(
'beforeend',
'
Falha no envio do formulário
' + yv.localization.portuguese.genericError + '
'
)
yv.utils.toggleLoading(boxForm)
});
},
saveReviewStore: function (eventBtn, boxForm) {
if (eventBtn && eventBtn.disabled == true) return
const eventContainer = eventBtn.closest(boxForm)
eventBtn.setAttribute('disabled', true)
if (!yv.validation.validateForm(boxForm)) {
eventBtn.removeAttribute('disabled')
return
}
yv.utils.toggleLoading(boxForm)
const allReviewInputs = yv.review.getAllReviewInputs(boxForm)
// Pega dados do formulário
let data = njQuery(allReviewInputs).serialize();
// Se houver, pega id da ordem
if (yv.utils.qs["yv-o"]) {
data += '&yv-o=' + encodeURIComponent(yv.utils.qs['yv-o']);
}
// Se houver, pega id da solicitação
if (yv.utils.qs["yv-srr"]) {
data += '&yv-srr=' + encodeURIComponent(yv.utils.qs['yv-srr']);
}
// Envia de fato os dados para salvar
const uri = yv.uriBuilder.general('/reviewformsave/SaveStoreReviewForm', '&' + data);
njQuery.jsonpx(uri, function (res) {
eventContainer.replaceChildren('')
eventContainer.insertAdjacentHTML('beforeend', res.html)
yv.utils.toggleLoading(boxForm)
})
.fail(function () {
eventContainer.replaceChildren('')
eventContainer.insertAdjacentHTML(
'beforeend',
'
Falha no envio do formulário
' + yv.localization.portuguese.genericError + '
'
)
yv.utils.toggleLoading(boxForm)
})
},
showWriteReview: function (doNotScroll) {
const reviewBox = document.querySelector('#yv-show-form') || document.querySelector('[yv-role="form-box-review"]')
let uri = '/reviewform/getreviewform'
let categoriesForm = ''
yv.utils.goTo(reviewBox)
yv.utils.toggleLoading(reviewBox)
if (yv.categoryForm && yv.categoryForm.length > 0) {
categoriesForm = njQuery([].concat(yv.categoryForm).reverse()).map(function (i, v) {
return "&formId=" + encodeURIComponent(v);
}).get().join('');
}
if (yv.utils.qs['yv-u']) categoriesForm += "&yv-user=" + yv.utils.qs['yv-u'];
if (yv.utils.qs['yv-sr']) categoriesForm += '&yv-sr=true';
if (yv.utils.qs['yv-o']) categoriesForm += '&yv-o=' + encodeURIComponent(yv.utils.qs['yv-o']);
if (yv.utils.qs['yv-sms']) categoriesForm += '&yv-sms=' + encodeURIComponent(yv.utils.qs['yv-sms']);
if (yv.utils.qs['yv-nps-score']) categoriesForm += '&yv-nps-score=' + encodeURIComponent(yv.utils.qs['yv-nps-score']);
if (yv.utils.qs['yv-rr']) categoriesForm += '&yv-rr=' + encodeURIComponent(yv.utils.qs['yv-rr']);
if (yv.productId) {
categoriesForm += '&productId=' + yv.productId;
} else {
if (yv.utils.qs["productId"]) {
yv.productId = yv.utils.qs["productId"];
categoriesForm += '&productId=' + yv.productId;
} else if (yv.utils.qs["idproduto"]) {
yv.productId = yv.utils.qs["idproduto"];
categoriesForm += '&productId=' + yv.productId;
}
}
if (yv.utils.qs['yv-srr']) {
categoriesForm += '&yv-srr=' + encodeURIComponent(yv.utils.qs['yv-srr']);
uri = '/reviewform/getstorereviewform';
}
njQuery.jsonpx(yv.uriBuilder.general(uri, categoriesForm), function (res) {
// exibe o formulário recebido
if (reviewBox.id.includes('yv-show-form')) {
reviewBox.removeAttribute('style')
reviewBox.replaceChildren('')
reviewBox.insertAdjacentHTML('beforeend', '')
reviewBox.firstElementChild.insertAdjacentHTML('beforeend', res.html)
} else {
reviewBox.replaceChildren('')
reviewBox.insertAdjacentHTML('beforeend', res.html)
}
// inicia tracking de eventos do formulário
yv.analyticsSupport.startReviewFormAnalytics();
// ajusta label das estrelas
// yv.commom.startStarLabel();
// carrega componente de upload
if (typeof yv.uploader !== 'undefined') yv.uploader.startUploader();
if (yv.utils.qs['yv-sc']) njQuery('#star' + yv.utils.qs['yv-sc']).prop("checked", true);
if (yv.utils.qs['yv-nps-score']) {
var input = njQuery('.nps .yv-radio-inline:contains("' + yv.utils.qs['yv-nps-score'] + '"):first input');
if (input) input.prop("checked", true);
}
yv.utils.toggleLoading(reviewBox)
})
.fail(function (jqXHR, textStatus, err) {
njQuery(this).removeAttr("disabled");
njQuery('[yv-role="form-box-review"]')
.html('
Falha no carregamento do formulário
' + yv.localization.portuguese.genericError + '
')
.append('')
var additionalError = '[{err: "' + encodeURIComponent(textStatus) + '"}]';
yv.analyticsSupport.trackWriteReview('reviewform-error', additionalError);
yv.utils.toggleLoading(reviewBox)
});
},
gotoWriteReview: function () {
if (yv.utils.qs['yv-write-review']) {
yv.review.showWriteReview();
yv.analyticsSupport.trackWriteReview('clickEmail');
}
},
loadReviewPhotoGrid: function () {
var anchor = njQuery('.yv-photogrid-anchor');
if (anchor.length) {
var qtd = anchor.attr('data-qty');
var ids = { qty: qtd };
var uri = yv.uriBuilder.general('/reviewphotos/photogrid', '&' + njQuery.param(ids, true));
njQuery.jsonpx(uri, function (r) {
if (r && r.html) {
anchor.html(r.html);
}
});
}
},
}
yv.social = {
userLogout: function (eventBtn) {
const loginForm = eventBtn.closest('[yv-role="form-login"]')
const boxForm = loginForm.parentElement
const errorElement = '
Falha ao trocar de usuário
Tente novamente mais tarde
'
njQuery.jsonpx(yv.uriBuilder.general('/user/logout'), function (e) {
yv.social.toggleLogin(boxForm)
})
.fail(function () {
loginForm.innerHTML(errorElement)
});
},
toggleLogin: function (boxForm) {
const loginForms = boxForm.querySelectorAll('[yv-role="form-login"]')
loginForms.forEach(function (form) {
form.classList.toggle('hide')
const formInputs = form.querySelectorAll('[yv-role="form-input"]')
formInputs.forEach(function (input) {
if (input.name == 'user-logintype') {
input.setAttribute('value', 'email')
} else {
input.setAttribute('value', '')
}
})
})
},
toggleLoginSocialNetwork: function (eventBtn, user, network) {
const boxForm = eventBtn.closest('[yv-role="form-login"]').parentElement
yv.social.toggleLogin(boxForm)
const loginForm = boxForm.querySelector('[yv-role="form-login"].logged')
if (loginForm) {
const userLoginType = loginForm.querySelector('[yv-role="form-input"][name="user-logintype"]')
const userDisplayImage = loginForm.querySelector('[yv-role="display-image"]')
const userImage = loginForm.querySelector('[yv-role="form-input"][name="user-image"]')
const userEmail = loginForm.querySelector('[yv-role="form-input"][name="user-email"]')
const userName = loginForm.querySelector('[yv-role="form-input"][name="yv-exhibition-name"]')
userLoginType.setAttribute('value', network)
if (user.ImageUrl) {
userDisplayImage.style.backgroundImage = 'url("' + user.ImageUrl + '")'
userImage.setAttribute('value', user.ImageUrl)
}
if (user) {
userEmail.setAttribute('value', user.Email)
userName.setAttribute('value', user.Name)
}
}
},
loginSocialNetwork: function (eventBtn, network) {
const loginListener = function (e) {
if (e.data && e.origin.indexOf('service.yourviews.com.br') > -1) {
const uri = yv.uriBuilder.general('/user/getuser', '&loadsocialnetworks=true')
window.removeEventListener('message', loginListener, false)
localStorage.setItem('__yv_xauth', e.data)
njQuery.jsonpx(uri, function (res) {
if (res && res.hasResults) {
localStorage.setItem('__yv_user', res.html)
yv.social.toggleLoginSocialNetwork(eventBtn, JSON.parse(res.html), network)
}
});
}
}
window.addEventListener('message', loginListener, false)
const loginWindow = window.open(
yv.uriBuilder.general('/User/SocialLogin', '&network=' + network),
'_blank',
'width=800, height=600'
);
},
shareSocialNetwork: function (eventBtn, network) {
const id = eventBtn.getAttribute('yv-data')
const route = '/share/index/' + id
const parameters = '&media=' + network + '¤tPage=' + window.location.href
window.open(
yv.uriBuilder.generalNoCb(route, parameters),
'new',
'width=600, height=600'
)
},
// Funções dos botões de login e compartilhamento em redes sociais
loadSocialActions: function () {
document.addEventListener('click', function (e) {
const eventBtn = e.target.closest('[yv-action]')
if (eventBtn && eventBtn.getAttribute('yv-action') == 'social-login-facebook') {
yv.social.loginSocialNetwork(eventBtn, 'facebook')
} else if (eventBtn && eventBtn.getAttribute('yv-action') == 'social-login-google') {
yv.social.loginSocialNetwork(eventBtn, 'google')
} else if (eventBtn && eventBtn.getAttribute('yv-action') == 'social-share-facebook') {
yv.social.shareSocialNetwork(eventBtn, 'facebook')
} else if (eventBtn && eventBtn.getAttribute('yv-action') == 'social-share-twitter') {
yv.social.shareSocialNetwork(eventBtn, 'twitter')
} else if (eventBtn && eventBtn.getAttribute('yv-action') == 'social-share-product') {
const shareLink = eventBtn.getAttribute('yv-data')
window.open(shareLink, 'newwindow', 'width=600, height=600')
} else if (eventBtn && eventBtn.getAttribute('yv-action') == 'social-logout') {
yv.social.userLogout(eventBtn)
}
})
}
}
yv.commom = {
toggleViewMore: function () {
njQuery('.yv-viewmore-btn').each(function () {
var elemToAct = njQuery(this).parent();
var expanded = elemToAct.data('expanded');
if (!expanded) {
njQuery(this).html("...(" + yv.localization.portuguese.more + ")");
}
});
njQuery('.yv-viewmore-btn').click(function () {
//Seleciona a div "pai" do texto, para redimensioná-la.
var elemToAct = njQuery(this).parent();
var expanded = njQuery(elemToAct).data("expanded");
if (!expanded) {
njQuery(this).html("(" + yv.localization.portuguese.less + ")");
elemToAct.find('.yv-viewmore-expanded').show();
//Salva o height atual
var originalHeight = elemToAct.css("height");
njQuery(elemToAct).data("height", originalHeight);
//Marca como o elemento como expandido
njQuery(elemToAct).data("expanded", true);
//Remove o height do elemento, para revelar o texto inteiro
elemToAct.css("height", "initial");
}
else {
njQuery(this).html("...(" + yv.localization.portuguese.more + ")");
elemToAct.find('.yv-viewmore-expanded').hide();
var Height = elemToAct.css("height");
njQuery(elemToAct).data("height", Height);
njQuery(elemToAct).data("expanded", false);
}
});
},
//Verifica se está no modo debug
debugIsCorrect: function (element) {
const debug = element.getAttribute('debug');
if (debug) {
if (yv.utils.qs["yv-debug"] != 'true') //Se estiver e não houver querystring, não carrega
{
yv.utils.safeLog('Debugging mode for ' + element + ' but no yv-debug querystring.');
return false;
}
}
return true;
},
loadPaging: function (prevCallb, nextCallb, element) {
let targetElement = element
if (typeof (element) == 'string') targetElement = document.querySelector(element)
if (targetElement) {
targetElement.addEventListener('click', function (event) {
const eventBtn = event.target.closest('[yv-action]')
if (eventBtn && eventBtn.disabled) return
if (eventBtn && eventBtn.getAttribute('yv-action') == 'prev-page') {
const uri = eventBtn.getAttribute('yv-data')
if (targetElement) {
yv.utils.toggleLoading(targetElement)
yv.utils.goTo(targetElement)
}
njQuery.jsonpx(uri + "&callback=?", function (r) {
prevCallb(r);
});
} else if (eventBtn && eventBtn.getAttribute('yv-action') == 'next-page') {
const uri = eventBtn.getAttribute('yv-data')
if (targetElement) {
yv.utils.toggleLoading(targetElement)
yv.utils.goTo(targetElement)
}
njQuery.jsonpx(uri + "&callback=?", function (r) {
nextCallb(r);
});
}
})
}
},
// Mostra/Esconde o elemento de responder pergunta do usuário
toggleReplyElement: function (eventBtn, eventBtnLabel, isBlocked) {
const replyElement = eventBtn.closest('[yv-role="question"]').querySelector('[yv-role="form-box-reply"]')
const loginForms = replyElement.querySelectorAll('[yv-role="form-login"]')
if (!replyElement.classList.contains('is-hide')) {
replyElement.classList.toggle('is-hide')
eventBtnLabel.innerText = 'Responder'
if (loginForms.length) {
loginForms.forEach(function (loginForm) { loginForm.remove() })
}
} else {
replyElement.classList.toggle('is-hide')
eventBtnLabel.innerText = 'Cancelar'
yv.utils.goTo(replyElement)
}
},
// Realiza o envio da curtida para a base
loadLikeUnlike: function () {
document.addEventListener('click', function (e) {
const eventBtn = e.target.closest('[yv-action]')
if (eventBtn && eventBtn.getAttribute('yv-role') == 'button-reply') {
const action = eventBtn.getAttribute('yv-action')
const eventBtnLabel = eventBtn.querySelector('[yv-role="button-label"]')
if (action == 'reply-question') {
yv.commom.toggleReplyElement(eventBtn, eventBtnLabel)
}
} else if (eventBtn && eventBtn.getAttribute('yv-role') == 'button-like') {
if (eventBtn && eventBtn.disabled) return
yv.utils.toggleLoading(eventBtn.parentElement)
const action = eventBtn.getAttribute('yv-action')
const id = eventBtn.getAttribute('yv-data')
const eventBtnLabel = eventBtn.querySelector('[yv-role="button-label"]')
let uri = ''
if (action == 'like' || action == 'dislike') {
uri = yv.uriBuilder.general('/reviewlike/' + action + '/' + id);
}
if (action == 'likequestion' || action == 'dislikequestion' || action == 'likeanswer' || action == 'dislikeanswer') {
uri = yv.uriBuilder.general('/questionanswer/' + action, '&id=' + id);
}
if (uri) {
njQuery.jsonpx(uri, function (res) {
if (eventBtn && eventBtn.disabled) eventBtn.setAttribute('disabled', true)
if (!res.html) return yv.utils.toggleLoading(eventBtn.parentElement)
const parsedRes = JSON.parse(res.html);
if (parsedRes) {
if (parsedRes.count) {
eventBtnLabel.innerText = '(' + parsedRes.count + ')'
} else {
let currentValue = Number(eventBtnLabel.innerText.replace(/\D/g, ''))
currentValue += 1
eventBtnLabel.innerText = '(' + currentValue + ')'
}
}
yv.utils.toggleLoading(eventBtn.parentElement)
})
}
}
})
},
getProductDetails: function () {
var productData = '&productName=' + yv.utils.safeSubstr(yv.productName, 100);
productData += '&imageUrl=' + yv.utils.safeSubstr(yv.imageUrl, 200);
productData += '&productPrice=' + yv.utils.safeSubstr(yv.productPrice, 30);
productData += '&productId=' + yv.utils.safeSubstr(yv.productId, 97);
productData += '&productUrl=' + yv.utils.safeSubstr(yv.productUrl || window.location.href, 200);
return productData;
},
startStarLabel: function () {
njQuery('.yv-star-lbl').hover(function () {
var textHovered = njQuery(this).attr('title');
njQuery(this).parent().siblings('.yv-star-description').html(textHovered);
}, function () {
var inputProductStore = njQuery(this).parent().find('.inputIdProductStore').val();
var toSearchInput = ".yv-star-radio:checked ";
var toSearchStarDescription = ".yv-star-description ";
if (inputProductStore != undefined && inputProductStore != 0 && inputProductStore != "") {
toSearchInput += "." + inputProductStore;
toSearchStarDescription += "." + inputProductStore;
}
var optionSelected = njQuery(this).parent().find(toSearchInput);
var starDescription = njQuery(this).parent().siblings(toSearchStarDescription);
if (optionSelected.length > 0) {
var textToSet = optionSelected.next().attr('title');
starDescription.html(textToSet);
}
else
starDescription.html('');
})
},
yvData: function () {
//window.yv = window.yv || [];
yv.serviceAddr = ('https:' === document.location.protocol ? 'https://' : 'http://') + 'service.yourviews.com.br';
yv.staticServiceAddr = ('https:' === document.location.protocol ? 'https://' : 'http://') + 'staticfiles.yviews.com.br';
yv.productUrl = window.location.href; //TODO: analisar a remoção desse parâmetro
yv.secondaryAddr = 'https://service2.yourviews.com.br';
yv.uriBuilder = {
generalNoCb: function (action, parameters) {
return yv.serviceAddr + action + "?storeKey=" + yv.storeKey + parameters;
},
generalSecondary: function (action, parameters) {
var caching = '';
if (yv.utils.qs['yv-cache'])
caching = "&yv-cache=" + yv.utils.getRandom();
var templatePreview = '';
if (yv.utils.qs['yv-preview'])
templatePreview = "&yv-preview=" + yv.utils.qs['yv-preview'];
return yv.secondaryAddr + action + "?storeKey=" + yv.storeKey + (parameters ? parameters : '')
+ caching
+ templatePreview
+ '&callback=?';
},
general: function (action, parameters) {
var caching = '';
if (yv.utils.qs['yv-cache'])
caching = "&yv-cache=" + yv.utils.getRandom();
var templatePreview = '';
if (yv.utils.qs['yv-preview'])
templatePreview = "&yv-preview=" + yv.utils.qs['yv-preview'];
return yv.serviceAddr + action + "?storeKey=" + yv.storeKey + (parameters ? parameters : '')
+ caching
+ templatePreview
+ '&callback=?';
}
};
},
}
yv.vendorCustom = {
canStart: function () {
return true;
},
quickReviewGetIds: function () {
const asyncShelfs = yv.vendorCustom.quickReviewAsyncSetup()
let allShelfs = []
if (asyncShelfs) {
allShelfs = allShelfs.concat(asyncShelfs)
}
return allShelfs
},
quickReviewAsyncSetup: function () {
const shelfToInsert = document.querySelectorAll('_seletor_');
const quickReviewToLoad = document.querySelectorAll('.yv-review-quickreview:not(.is-loaded)');
const allIds = []
if (typeof (shelfToInsert) !== "undefined" && shelfToInsert.length) {
shelfToInsert.forEach(function (e) {
let itemId = e.getAttribute('_seletor_')
if (!itemId) return
if (!e.closest('_seletor_').querySelector('.yv-review-quickreview')) {
e.closest('_seletor_').querySelector('_seletor_').insertAdjacentHTML(
'afterend',
''
)
allIds.push(itemId)
}
})
}
if (typeof (quickReviewToLoad) !== "undefined" && quickReviewToLoad.length) {
quickReviewToLoad.forEach((qr) => {
if (qr) {
let itemId = qr.getAttribute('value')
if (!itemId) return
allIds.push(itemId)
}
})
}
return allIds
},
QaElement: function () {
return ".yv-qa";
},
quickReviewProdElement: function () {
return "#yv-review-quickreview";
},
quickReviewProdBefore: function () {
},
reviewsElement: function () {
return "#yv-reviews";
},
reviewsBefore: function () { },
elementsToInsert: [
{
element: "#yv-testimonial",
selector: "SELETOR_AQUI",
where: "beforebegin",
elementHTML: "",
loadFunctions: [
yv.storeReviews.startTestimonial,
yv.storeReviews.startStoreReview,
],
type: "home",
isLoaded: false,
isLoading: false
},
{
element: "#yv-review-quickreview",
selector: "SELETOR_AQUI",
where: "afterend",
elementHTML: "",
loadFunctions: [yv.review.startQuickReviewProductPage],
type: "product",
isLoaded: false,
isLoading: false
},
{
element: "#yv-reviews",
selector: "SELETOR_AQUI",
where: "beforeend",
elementHTML: "",
loadFunctions: [
yv.review.startReviews,
yv.review.startReviewForm,
yv.review.loadReviewShelf,
yv.review.loadReviewPhotoGrid,
],
type: "product",
isLoaded: false,
isLoading: false
},
{
element: ".yv-qa",
selector: "#yv-reviews",
where: "afterend",
elementHTML: "",
loadFunctions: [yv.qa.startQa],
type: "product",
isLoaded: false,
isLoading: false
},
{
element: "#yv-show-form",
selector: "SELETOR_AQUI",
where: "",
elementHTML:
"
Por favor aguarde...
",
loadFunctions: [yv.review.startReviewForm],
type: "form",
isLoaded: false,
isLoading: false
},
{
element: '[title="Loja Confiável"]',
selector: "SELETOR_AQUI",
where: "beforeend",
elementHTML: 'html_do_selo_aqui',
loadFunctions: [],
type: "any",
isLoaded: false,
isLoading: false
}
],
initialSetup: function () {
setTimeout(() => {
yv.vendorCustom.startUrlWatcher();
yv.vendorCustom.startSpa();
}, 1000)
},
createChangePageListener: function() {
if (yv.changePageListenerActive) return
var pushState = history.pushState;
var replaceState = history.replaceState;
history.pushState = function() {
pushState.apply(history, arguments);
window.dispatchEvent(new Event('pushstate'));
window.dispatchEvent(new Event('locationchange'));
};
history.replaceState = function() {
replaceState.apply(history, arguments);
window.dispatchEvent(new Event('replacestate'));
window.dispatchEvent(new Event('locationchange'));
};
window.addEventListener('popstate', function() {
window.dispatchEvent(new Event('locationchange'))
});
yv.changePageListenerActive = true
yv.vendorCustom.checkChangePage();
},
startSpa: function () {
var count = 0;
yv.loadElementsSPA = setInterval(() => {
yv.vendorCustom.elementsToInsert.forEach((obj) => {
if (obj.type == "product") {
if (njQuery('#yv-productId').length && typeof yv.productId == "undefined") {
yv.vendorCustom.getYvVariables()
}
if (yv.oldProductId === yv.productId) {
yv.vendorCustom.clearYvVariables();
return
}
if (typeof yv.productId != "undefined" && yv.productId.length > 0) {
yv.vendorCustom.executeElementsSpa(obj)
}
}else{
yv.vendorCustom.executeElementsSpa(obj)
}
});
count++;
if (count >= 20) {
clearInterval(yv.loadElementsSPA);
yv.utils.safeLog(`loadSPA ended`);
}
}, 500);
},
executeElementsSpa: function (obj) {
if(window.parent.document.querySelector(obj.element) && obj.isLoading) {
let element = window.parent.document.querySelector(obj.element)
if(element.innerHTML != '') {
obj.isLoaded = true
obj.isLoading = false
}
}
if(window.parent.document.querySelector(obj.element) && obj.isLoaded) {
let element = window.parent.document.querySelector(obj.element)
if(element.innerHTML == '') {
obj.isLoaded = false
obj.isLoading = false
}
}
if (window.parent.document.querySelector(obj.element) && !obj.isLoading && !obj.isLoaded) {
obj.loadFunctions.forEach((f) => f());
obj.isLoading = true;
yv.utils.safeLog(`${obj.element} loaded!`);
} else if (obj.where == "replace"){
if (window.parent.document.querySelector(obj.selector) && !obj.isLoading && !obj.isLoaded) {
window.parent.document.querySelector(obj.selector).innerHTML = obj.elementHTML;
obj.loadFunctions.forEach((f) => f());
obj.isLoading = true;
yv.utils.safeLog(`${obj.element} loaded!`);
}
}else{
if (window.parent.document.querySelector(obj.selector) && !obj.isLoading && !obj.isLoaded) {
window.parent.document.querySelector(obj.selector).insertAdjacentHTML(obj.where, obj.elementHTML);
obj.loadFunctions.forEach((f) => f());
obj.isLoading = true;
yv.utils.safeLog(`${obj.element} loaded!`);
}
}
},
getYvVariables: function () {
yv.productName = njQuery("#yv-productName").val()
yv.productPrice = "R$ " + njQuery("#yv-productPrice").val().toString().replace('.', ',')
yv.productId = njQuery("#yv-productId").val()
yv.imageUrl = njQuery("#yv-productImage").val()
yv.productUrl = window.location.href;
},
clearYvVariables: function () {
yv.productId = undefined
yv.productName = undefined
yv.productPrice = undefined
yv.imageUrl = undefined
yv.categoryForm = []
yv.productUrl = undefined
},
clearElements: function () {
yv.vendorCustom.elementsToInsert.forEach((obj) => {
window.parent.document.querySelector(obj.element)?.remove()
obj.isLoaded = false;
obj.isLoading = false;
})
},
onLocationChange: function () {
try { clearInterval(yv.loadElementsSPA); } catch (_) {}
yv.oldProductId = yv.productId;
yv.vendorCustom.clearYvVariables();
yv.vendorCustom.clearElements();
setTimeout(() => {
yv.vendorCustom.startSpa();
}, 4000)
},
startUrlWatcher: function () {
if (yv._urlWatcherStarted) return;
yv._urlWatcherStarted = true;
// tenta observar o parent; se der erro (cross-origin), usa a janela atual
let getHref = () => location.href;
try {
if (window.parent && window.parent !== window) {
// acessa para testar mesma origem
void window.parent.location.href;
getHref = () => window.parent.location.href;
}
} catch (_) { /* permanece na janela atual */ }
let lastHref = getHref();
setInterval(() => {
let now;
try { now = getHref(); } catch (_) { now = location.href; }
if (now !== lastHref) {
lastHref = now;
yv.vendorCustom.onLocationChange();
}
}, 400);
},
sendAnalytics: function () { return false; }
}
yv.analytics = {
supported: function () { //TODO: remover essas dependencias no futuro.
//Requires IE 8+, jQuery and Tag Manager
return (typeof (window.jQuery) !== 'undefined' &&
typeof (yv.vendorCustom.sendAnalytics) !== 'undefined' &&
yv.vendorCustom.sendAnalytics() &&
typeof (JSON) !== "undefined" && typeof (JSON.stringify) !== "undefined");
},
getData: function () {
var dataToSend = [];
//Fetch data from tag manager
if (typeof (dataLayer) !== 'undefined') {
jQuery.each(dataLayer, function (i, v) {
if (!v.event || v.event.indexOf('gtm') == -1) dataToSend.push(v);
});
}
//Send some customized, vendor specific info, if necessary
var custom = yv.vendorCustom.getCustomAnalytics ? yv.vendorCustom.getCustomAnalytics() : null;
if (custom)
dataToSend.push(custom);
//Transform into JSON
var additData = encodeURIComponent(JSON.stringify(dataToSend));
return additData;
},
getCategory: function () {
var result = null;
if (typeof dataLayer === 'undefined') return result; //GTM not loaded yet
if (yv.vendorCustom.getAnalyticsCategory)
result = yv.vendorCustom.getAnalyticsCategory(dataLayer);
else {
jQuery.each(dataLayer, function (i, v) {
if (typeof v.event != 'undefined' && v.event.indexOf('gtm') == -1)
result = v.event;
});
}
return result;
},
start: function () {
if (!yv.analytics.supported()) return;
var n = null;
var t = 0;
//Wait a few time for loading tag manager
var tmr = window.setInterval(function () {
n = yv.analytics.getCategory();
t++;
if (n != null || t >= 100) { //20 seconds
window.clearInterval(tmr);
var url = window.yv.uriBuilder.general('/tracking', '&n=' + yv.analytics.getCategory() + '&ts=analytics&d=' + yv.analytics.getData());
(new Image()).src = url;
}
}, 200);
}
};
yv.analyticsSupport = {
trackScrollReview: function () {
njQuery(window).bind('scroll.yvreviewscroll', function () {
var itm = njQuery('#yv-show-reviews .yv-row:first');
if (itm.length == 0) return;
var hT = itm.offset().top,
hH = itm.outerHeight(),
wH = njQuery(window).height(),
wS = njQuery(this).scrollTop();
if (wS > (hT + hH - wH)) {
njQuery(window).unbind('.yvreviewscroll');
var ids = njQuery('*[data-yv-action="like"]').map(function () {
return njQuery(this).data('yv-rid');
}).get();
var readedReviews = JSON.stringify(ids);
yv.analyticsSupport.trackEvent('readreview', 'review', null, readedReviews);
}
});
},
trackEvent: function (trackname, tracksystem, additionalData, readedReviewIds) {
var dataToSend = '&n=' + trackname + '&ts=' + tracksystem + '&g=' + yv.utils.qs['yv-write-review'];
if (additionalData)
dataToSend += '&d=' + additionalData;
if (readedReviewIds)
dataToSend += '&rr=' + readedReviewIds;
(new Image()).src = yv.uriBuilder.general('/Tracking', dataToSend);
},
init: function () {
//var url = yv.uriBuilder.general('/tracking/setup',yv.analyticsSupport.getUtms());
//(new Image()).src = url;
},
getUtms: function () {
var result = '';
var utms = yv.utils.qs["utm_source"];
if (utms) result = "&utms=" + utms;
var utmm = yv.utils.qs["utm_media"];
if (utmm) result = "&utmm=" + utmm;
var utmc = yv.utils.qs["utm_campaign"];
if (utmc) result = "&utmc=" + utmc;
return result;
},
trackWriteReview: function (trackname, additionalData) {
var dataToSend = "";
if (trackname.indexOf("Sms") !== -1) {
dataToSend = '&n=' + trackname + '&ts=sms&g=' + yv.utils.qs['yv-write-review'];
}
else {
dataToSend = '&n=' + trackname + '&ts=email&g=' + yv.utils.qs['yv-write-review'];
}
if (additionalData)
dataToSend += '&d=' + additionalData;
(new Image()).src = yv.uriBuilder.general('/tracking', dataToSend);
},
startReviewFormAnalytics: function () {
njQuery('.yv-bootstrap input, .yv-bootstrap textarea, .yv-bootstrap a, .yv-bootstrap button').bind('click', function (e) {
var elem = njQuery(e.currentTarget);
var form = njQuery(elem).parents('form');
if (elem && form && form.length > 0) {
var formid = form.attr('id');
var currentForm = njQuery(form).find('input').serialize();
var interaction = '[{ name: "' + elem.attr('name') + '", type:"' + e.type + '",id:"' + elem.attr('id') + '" ,currentForm: "' + encodeURIComponent(currentForm) + '"}]'
yv.analyticsSupport.trackWriteReview(formid, interaction);
}
});
},
internalWriteToGA: function (eventCategory, eventAction, eventLabel, nonInteraction) {
//old ga.js
if (window._gaq && window._gat) {
var oldTrackers = window._gat._getTrackers();
for (var i = 0; i < oldTrackers.length ; i++) {
oldTrackers[i]._trackEvent(eventCategory, eventAction, eventLabel, null, nonInteraction);
}
}
//New analytics.js
var currentGa = window.ga || window[window.GoogleAnalyticsObject] || null;
if (!currentGa) return;
var allGAs = currentGa.getAll();
var eventType = 'event';
for (var i = 0; i < allGAs.length; i++) {
allGAs[i].send(eventType, eventCategory, eventAction, eventLabel, {
nonInteraction: nonInteraction
});
}
},
writeToGA: function (eventAction, eventLabel) {
yv.analyticsSupport.internalWriteToGA("Yourviews", eventAction, eventLabel, false);
},
writeToGANonInteractive: function (eventAction, eventLabel) {
yv.analyticsSupport.internalWriteToGA("Yourviews", eventAction, eventLabel, true);
},
startABTest: function () {
var abTest = window.yv?.abTest || {};
abTest.enabled = '/*replace yv_abtest_enabled/*';
if (abTest && abTest.enabled == 'true') {
njQuery.jsonpx(yv.uriBuilder.general('/script/checkabtest'), function (resp) {
if (resp) {
if (resp.html === '2') {
if (typeof yv.vendorCustom.runTestGroup != 'undefined') {
yv.vendorCustom.runTestGroup();
}
var custom_css = njQuery("", {
rel: "stylesheet",
type: "text/css",
href: yv.uriBuilder.general("/script/abteststyle")
});
document.head.appendChild(custom_css[0]);
yv.analyticsSupport.writeToGANonInteractive("ABTest", "Test B");
}
else {
yv.analyticsSupport.writeToGANonInteractive("ABTest", "Test A");
}
}
});
}
},
trackAnswer: function (trackname, additionalData) {
var dataToSend = "";
dataToSend = '&n=' + trackname + '&ts=Question&g=' + yv.utils.qs['yv-write-answer'];
if (additionalData)
dataToSend += '&d=' + additionalData;
(new Image()).src = yv.uriBuilder.general('/tracking', dataToSend);
},
};
yv.utils = {
qs: (function (a) {
if (a === "") return {};
var b = {};
for (var i = 0; i < a.length; ++i) {
var p = a[i].split('=');
if (p.length !== 2) continue;
var replaced = p[1].replace(/\+/g, " ");
var decodedVal = '';
try {
decodedVal = decodeURIComponent(replaced);
} catch (e) {
// safeLog('Error when decoding string. Using default instead.');
}
b[p[0]] = decodedVal;
}
return b;
})(window.location.search.substr(1).split('&')),
safeLog: function (msg) {
if (typeof console !== 'undefined' && window.console && window.console.log)
console.log("[Yourviews] " + msg);
},
safeSubstr: function (val, len) {
var result = '';
if (typeof val != 'undefined' && val) {
if (val.length > len)
result = val.substr(0, len) + '...';
else
result = val;
}
result = result.replace(/<(?:.|\n)*?>/gm, '');
result = encodeURIComponent(result);
return result;
},
goTo: function (element) {
let targetElement = element
if (typeof (element) == 'string') {
targetElement = document.querySelector(element)
}
const options = {
top: targetElement.offsetTop - 100,
left: 0,
behavior: 'smooth'
}
window.scrollTo(options)
},
debugLog: function (msg) {
if (
typeof console !== 'undefined' &&
window.console &&
window.console.log &&
yv.utils.qs["yv-debug"] === 'true'
) {
console.log("[Yourviews debug] " + msg);
}
},
toggleLoading: function (element) {
let targetElement = element
let loadElement = undefined
if (typeof (element) == 'string') {
targetElement = document.querySelector(element)
loadElement = targetElement.querySelector('[yv-role="loader"]')
} else {
loadElement = targetElement.querySelector('[yv-role="loader"]')
}
if (targetElement.classList.contains('is-loading')) {
targetElement.removeAttribute('style')
if (loadElement) loadElement.remove()
} else {
targetElement.style.position = 'relative'
targetElement.insertAdjacentHTML(
'beforeend',
'