(function (yv, $, undefined) { "use strict"; var njQuery; // 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: 590 }); 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)); } }; //REVIEWs // Main class yv.ReviewsSlider = { // Slider config options slidesToShow: undefined, slidesToShift: 1, showButtons: undefined, showPaging: undefined, infinite: undefined, breakpoint: undefined, breakpoints: undefined, // Main slider elements containerReviews: undefined, viewReviews: undefined, wrapperReviews: 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.containerReviews = document.querySelector(sliderElements.containerReviews); this.viewReviews = document.querySelector(sliderElements.viewReviews); this.wrapperReviews = document.querySelector(sliderElements.wrapperReviews); this.slides = this.wrapperReviews.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 wrapperReviews this.wrapperReviews.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.wrapperReviews.style.left = "0px"; // Set the size of the viewReviews this.viewReviews.style.width = this.slideSize * this.slidesToShow + "px"; // Build slider navigation buttons if (this.showButtons) { this.prevReviews = "undefined"; this.nextReviews = "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 viewReviews this.handleBreakpoints(); // Slider is loaded this.containerReviews.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: 590, }); this.handleBreakpoints(); } }, // Update slider configurations and properties resizeSlider: function (options) { this.containerReviews?.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 wrapperReviews this.wrapperReviews.style.width = String(this.slideSize * this.slidesToLoad) + "px"; // Set initial position of the slider this.wrapperReviews.style.left = "0px"; // Set the size of the viewReviews this.viewReviews.style.width = this.slideSize * this.slidesToShow + "px"; // Build slider navigation buttons if (this.showButtons) { var buttons = this.containerReviews.querySelectorAll(".control-reviews"); if (buttons.length) buttons.forEach(function (element) { element.remove(); }); this.buildButtons(); } // Build slider navigation paging if (this.showPaging) { var paging = this.containerReviews.querySelector(".paging"); if (paging) paging.remove(); this.buildPaging(); } this.containerReviews.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.viewReviews.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.viewReviews.classList.add("grabbing"); this.startPos = this.wrapperReviews.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.wrapperReviews.style.left = this.wrapperReviews.offsetLeft - this.posX2 + "px"; }; // Event triggered when user release the mouse button/finger from the screen var dragEnd = function () { this.viewReviews.classList.remove("grabbing"); this.endPos = this.wrapperReviews.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.wrapperReviews.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.viewReviews.addEventListener("mousedown", dragStart); // Touch events this.viewReviews.addEventListener("touchstart", dragStart); this.viewReviews.addEventListener("touchmove", dragOut); this.viewReviews.addEventListener("touchend", dragEnd); // Transition events this.viewReviews.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.prevReviews) this.prevReviews.classList.add("hide-reviews"); } else { if ( this.prevReviews && this.prevReviews.classList.contains("hide-reviews") ) { this.prevReviews.classList.remove("hide-reviews"); } } if ( this.index == this.slidesLength - 1 - ((this.slidesLength - 1) % this.slidesToShift) ) { if (this.nextReviews) this.nextReviews.classList.add("hide-reviews"); } else { if ( this.nextReviews && this.nextReviews.classList.contains("hide-reviews") ) { this.nextReviews.classList.remove("hide-reviews"); } } } }, // Prevents the slider from going over the limit shiftLimit: function () { if (this.infinite) { if (this.index < 0) { if (this.slidesLength % this.slidesToShift != 0) { this.wrapperReviews.style.left = -( (this.slidesLength - (this.slidesLength % this.slidesToShift)) * this.slideSize ) + "px"; this.index = this.slidesLength - (this.slidesLength % this.slidesToShift); } else { this.wrapperReviews.style.left = -((this.slidesLength - this.slidesToShift) * this.slideSize) + "px"; this.index = this.slidesLength - this.slidesToShift; } } else if (this.index >= this.slidesLength) { this.wrapperReviews.style.left = "0px"; this.index = 0; } } else { if (this.index < 0) { this.wrapperReviews.style.left = "0px"; this.index = 0; } else if (this.index >= this.slidesLength) { if (this.slidesLength % this.slidesToShift != 0) { this.wrapperReviews.style.left = -( (this.slidesLength - (this.slidesLength % this.slidesToShift)) * this.slideSize ) + "px"; this.index = this.slidesLength - (this.slidesLength % this.slidesToShift); } else { this.wrapperReviews.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.wrapperReviews.classList.add("shifting"); if (this.allowShift) { this.allowShift = false; if (!action) { this.startPos = this.wrapperReviews.offsetLeft; } if (dir === 1) { this.wrapperReviews.style.left = this.startPos - this.slideSize * this.slidesToShift + "px"; this.index += this.slidesToShift; } else if (dir == -1) { this.wrapperReviews.style.left = this.startPos + this.slideSize * this.slidesToShift + "px"; this.index -= this.slidesToShift; } } this.shiftLimit(); }, // Event triggered after slide animations checkIndex: function () { this.wrapperReviews.classList.remove("shifting"); if (this.showPaging) this.updatePagingIndex(this.index); if (this.showButtons) this.hideButton(); var leftPosition = parseInt(this.wrapperReviews.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.wrapperReviews.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.wrapperReviews.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.containerReviews.insertAdjacentElement("beforeend", this.paging); }, // Create slider navigation buttons buildButtons: function () { // Previous button this.prevReviews = document.createElement("span"); this.prevReviews.setAttribute("id", "prev-reviews"); this.prevReviews.classList.add("control-reviews", "prev-reviews"); if (!this.infinite) this.prevReviews.classList.add("hide-reviews"); // Next button this.nextReviews = document.createElement("span"); this.nextReviews.setAttribute("id", "next-reviews"); this.nextReviews.classList.add("control-reviews", "next-reviews"); // Iserting the buttons in slider element this.viewReviews.insertAdjacentElement("beforebegin", this.prevReviews); this.viewReviews.insertAdjacentElement("afterend", this.nextReviews); // Init click events this.prevReviews.addEventListener( "click", function () { this.shiftSlide(-1); }.bind(this) ); this.nextReviews.addEventListener( "click", function () { this.shiftSlide(1); }.bind(this) ); }, }; yv.localization = { less: "(menos)", more: "(mais)", writeReview: "Escrever avaliação...", tryAgain: "Tentar novamente" , genericError: "Ocorreu um erro nesta operação. 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" } yv.load = { init: function () { //Evita script carregando mais de uma vez if (window.yvLoaded) return; window.yvLoaded = true; yv.commom.setInitialData(); 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(); this.loadjQuery(); }, canStart: function () { if (typeof (yv.vendorCustom.canStart) !== 'undefined') return yv.vendorCustom.canStart(); return typeof window.jQuery !== 'undefined'; }, 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(); //njQuery(document).ready(function () { //TODO: validar que vai carregar review na pagina antes de chamar loadComponents yv.libraries.loadComponents(); yv.vendorCustom.initialSetup(); if (typeof (yv.analyticsSupport) !== 'undefined' && typeof (yv.analyticsSupport.startABTest) !== 'undefined') yv.analyticsSupport.startABTest(); if (typeof (yv.analytics) !== 'undefined') { yv.analytics.start(); } 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(); } if (typeof (yv.quickReview) !== 'undefined') { yv.quickReview.startQuickReview(); } 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: false, infinite: false, breakpoint: 9999 }, { slidesToShow: 2, slidesToShift: 2, showButtons: true, showPaging: false, infinite: false, breakpoint: 940 }, { slidesToShow: 1, slidesToShift: 1, showButtons: true, showPaging: false, infinite: false, breakpoint: 690 } ], { container: '#yv-container', view: '#yv-view', wrapper: '#yv-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(); var element = njQuery(yv.vendorCustom.QaElement()); if (!element.length || !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.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); } yv.qa.loadQaActions(); njQuery('.yv-qa-focuslogin').focus(); }); } } }, loadQAData: function (r) { if (!r || !r.html) return; var element = njQuery(yv.vendorCustom.QaElement()); element.html(r.html); yv.utils.toggleLoading(true, element); yv.qa.loadQaActions(); yv.analyticsSupport.startReviewFormAnalytics(); //Carrega paginador yv.commom.loadPaging(yv.qa.loadQAData, yv.qa.loadQAData, '.yv-qa', '-qa'); }, loadQaActions: function () { njQuery('[data-action="reply-question"]').click(function () { var loginElement = njQuery(this).parents('.yv-begin-question').find('.yv-qa-showlogin'); var loginLoadElement = loginElement.find('.yv-loadlogin'); if (loginLoadElement.length) { //Novo modelo. Carrega login 'on demand' njQuery.jsonpx(yv.uriBuilder.general('/questionanswer/login'), function (r) { loginLoadElement.html(r.html); yv.social.loadSocialLogin(); }); } loginElement.slideDown(); }); njQuery('.yv-qa-focuslogin').one('focus', function () { var loginElement = njQuery(this).parent().siblings('.yv-qa-showlogin'); var loginLoadElement = loginElement.find('.yv-loadlogin'); if (loginLoadElement.length) { //Novo modelo. Carrega login 'on demand' yv.utils.toggleLoading(false, '#yv-question-form'); njQuery.jsonpx(yv.uriBuilder.general('/questionanswer/login'), function (r) { loginLoadElement.html(r.html); yv.social.loadSocialLogin(); }); } yv.utils.toggleLoading(true, '#yv-question-form'); loginElement.slideDown(); }); njQuery('[data-yv-action="send-question"]').click(function () { yv.qa.saveQuestion(this); }); njQuery('[data-yv-action="send-answer"]').click(function () { yv.qa.saveAnswer(njQuery(this)); }); njQuery('.yv-qa-vote-btn,[data-yv-action="likedislike"]').click(function () { yv.qa.likeDislikeQA(this); }); njQuery('[data-yv-action="send-answer-similar"]').click(function () { yv.qa.saveQuestionWhithoutSimiliar(); }); njQuery('.yv-a-showmore').click(function () { var _self = this; njQuery(_self).siblings(':hidden').show(500); njQuery(_self).hide() }); njQuery('.yv-qa-more').click(function () { yv.utils.goTo('.yv-qa'); }); if (yv.utils.qs["yv-qa-ask"] == 'true') { //Cliente quer fazer nova pergunta setTimeout(function () { njQuery('[name="yv-qa-question"]').focus(); }, 0); } yv.social.loadSocialLogin(); }, saveQuestion: function (ctx) { var qContext = njQuery(ctx).parent().siblings('.yv-qa-showlogin'); var question = qContext.parent().find('[name="yv-qa-question"]').val(); var user_name = qContext.find('[name="user-name"]:visible,[name="yv-exhibition-name"]:visible').val(); var user_email = qContext.find('[name="user-email"]').val(); //Só valida se o elemento existir var user_phone_element = qContext.find('[name="yv-user-phone"]:visible'); var user_phone = user_phone_element.length == 0 || user_phone_element.val().length > 0; if (!question || !user_name || !user_email || !user_phone) { qContext.parent().find('.yv-question.yv-help-block').show(); return; } if (qContext.find('[name="user-name"]:visible').length) { var validEle = qContext.find('[name="user-name"]:visible'); //Digitou e-mail no lugar do nome if (/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(validEle.val())) { validEle.parent('div').addClass('yv-has-error'); validEle.siblings('.yv-help-valid').show(); return; } } if (qContext.find('[name="user-email"]:visible').length) { var validEle = qContext.find('[name="user-email"]:visible'); //Não digitou e-mail válido if (!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(validEle.val())) { validEle.parent('div').addClass('yv-has-error'); validEle.siblings('.yv-help-valid').show(); return; } } //Existe campo de telefone if (qContext.find('[name="yv-user-phone"]:visible').length) { var validEle = qContext.find('[name="yv-user-phone"]:visible'); //Não digitou e-mail válido if (validEle.val().length == 0) { validEle.parent('div').addClass('yv-has-error'); validEle.siblings('.yv-help-valid').show(); return; } } //Disabilita botão para não enviar duas vezes njQuery(this).attr('disabled', 'disabled'); //Pega dados do formulário var data = njQuery('#yv-question-form :input').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(''); //Some com formulário e exibe "carregando" yv.utils.toggleLoading(false, '#yv-question-form'); yv.utils.goTo('#yv-question-form'); 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'); } //Envia de fato os dados para salvar var uri = yv.uriBuilder.general('/questionanswer/savequestion', '&productId=' + productId + '&' + data); njQuery.jsonpx(uri, function (result) { //Exibe confirmação yv.utils.toggleLoading(true, '#yv-question-form'); njQuery('#yv-question-form').html(result.html); njQuery('[data-yv-action="send-answer-similar"]').click(function () { yv.qa.saveQuestionWhithoutSimiliar(); }); }).fail(function (jqXHR, textStatus, err) { yv.utils.toggleLoading(true, '#yv-question-form'); njQuery('#yv-question-form').html('
' + yv.localization.genericError + '
'); }); }, likeDislikeQA: function (ctx) { var Id = njQuery(ctx).data('id'); var action = njQuery(ctx).data('action'); var uri = '/questionanswer/' + action; yv.utils.toggleLoading(false, ctx); njQuery.jsonpx(yv.uriBuilder.general(uri, '&id=' + Id), function (r) { if (r.html == 'true') { var counter = njQuery(ctx).siblings('.yv-qa-vote-text'); if (!counter || counter.length == 0) counter = njQuery(ctx).find('.yv-qa-vote-text'); if (!counter || !counter.length) counter = njQuery(ctx).siblings().find('.yv-qa-vote-text'); var total = parseInt(counter.text()); if (action.indexOf('dislike') > -1) total--; else total++; counter.text(total); } yv.utils.toggleLoading(true, ctx); }); }, saveQuestionWhithoutSimiliar: function () { //Disabilita botão para não enviar duas vezes njQuery(this).attr('disabled', 'disabled'); //Pega dados do formulário var data = njQuery('#yv-question-form :input').serialize() + yv.commom.getProductDetails(); //Some com formulário e exibe "carregando" yv.utils.toggleLoading(false, '#yv-question-form'); yv.utils.goTo('#yv-question-form'); //Envia de fato os dados para salvar var uri = yv.uriBuilder.general('/questionanswer/saveQuestionWithoutSimiliar', '&productId=' + window.yv.productId + '&' + data); njQuery.jsonpx(uri, function (result) { //Exibe confirmação yv.utils.toggleLoading(true, '#yv-question-form'); njQuery('#yv-question-form').html(result.html); }).fail(function (jqXHR, textStatus, err) { yv.utils.toggleLoading(true, '#yv-question-form'); njQuery('#yv-question-form').html('
' + yv.localization.genericError + '
'); }); }, saveAnswer: function (ctx) { var currentQuestion = ctx.parents('.yv-qa-sendanswer'); var questionId = currentQuestion.attr('data-yv-question'); var answer = currentQuestion.find('[name="comment"]').val(); var user_name = currentQuestion.find('[name="user-name"]:visible,[name="yv-exhibition-name"]:visible').val(); var user_email = currentQuestion.find('[name="user-email"]').val(); //Só valida se o elemento existir var user_phone_element = currentQuestion.find('[name="yv-user-phone"]:visible'); var user_phone = user_phone_element.length == 0 || user_phone_element.val().length > 0; if (!answer || !user_name || !user_email || !user_phone) { currentQuestion.find('.yv-question.yv-help-block').show(); return; } //Pega dados do formulário var data = njQuery(':input', currentQuestion).serialize(); //Some com formulário e exibe "carregando" yv.utils.toggleLoading(false, currentQuestion); yv.utils.goTo(currentQuestion); var productId = window.yv.productId || yv.utils.qs["idproduto"]; //Envia de fato os dados para salvar var uri = yv.uriBuilder.general('/questionanswer/saveanswer', '&productId=' + productId + '&' + data); njQuery.jsonpx(uri, function (result) { //Exibe confirmação yv.utils.toggleLoading(true, currentQuestion); njQuery(currentQuestion).html(result.html); }).fail(function (jqXHR, textStatus, err) { yv.utils.toggleLoading(true, currentQuestion); njQuery('#yv-question-form').html('
' + yv.localization.genericError + '
'); }); }, 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'); }); }); } } } yv.quickReview = { quickReviewSetResult: function(e, notToLoad) { if (notToLoad) { const shelfId = e const shelfs = document.querySelectorAll('.yv-review-quickreview[value="' + shelfId + '"]') shelfs.forEach(function (shelf) { if (!shelf.classList.contains('is-loaded')) { shelf.classList.toggle('is-loaded') shelf.classList.toggle('willNotLoad') } shelf.replaceChildren('') }) return } const shelfId = e.productId const shelfData = e.data const shelfs = document.querySelectorAll('.yv-review-quickreview[value="' + shelfId + '"]') shelfs.forEach(function (shelf) { if (!shelf.classList.contains('is-loaded')) { shelf.classList.toggle('is-loaded') shelf.addEventListener('mouseenter', function() { yv.quickReview.searchRelevantReview(njQuery(shelf)) }) } shelf.replaceChildren('') shelf.insertAdjacentHTML('beforeend', shelfData); }) }, showQuickReview: function(shelfsRes, shelfsNotToLoad) { shelfsRes.forEach(function(e) { if (e && e.productId && e.data) yv.quickReview.quickReviewSetResult(e) }) shelfsNotToLoad.forEach((e) => { if (e) yv.quickReview.quickReviewSetResult(e, true) }) }, getProductShelf: function(shelfsToLoad) { const endpoint = yv.uriBuilder.general('/review/productShelf', '&ids=' + shelfsToLoad.join(',')) yv.awaitEndpointShelfs = true yv.shelfsToLoad = shelfsToLoad njQuery.jsonpx(endpoint, function (res) { if (!res.html) return const parsedRes = JSON.parse(res.html) if (parsedRes.length === 0) { const shelfsNotToLoad = yv.shelfsToLoad yv.quickReview.showQuickReview([], shelfsNotToLoad); yv.awaitEndpointShelfs = false return } let shelfsNotToLoad = yv.shelfsToLoad if (parsedRes) yv.quickReview.showQuickReview(parsedRes, []); yv.shelfsToLoad.forEach((id) => { parsedRes.forEach((obj) => { if (id === obj.productId) { shelfsNotToLoad = shelfsNotToLoad.filter(item => item !== id) } }) }) yv.quickReview.showQuickReview([], shelfsNotToLoad); yv.awaitEndpointShelfs = false }); }, searchExecuteQuickReview: function() { const shelfsToLoad = yv.vendorCustom.quickReviewGetIds() if (shelfsToLoad && shelfsToLoad.length && !yv.awaitEndpointShelfs) { yv.quickReview.getProductShelf(shelfsToLoad) } return }, searchRelevantReview: function (product) { var productId = product.attr('value'); var url = yv.uriBuilder.general('/review/ReviewRelevant', '&productStoreId=' + productId); if (product.attr('data-content') == undefined) { njQuery.jsonpx(url, function (r) { if (!r.html) return; 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 () { setInterval(yv.quickReview.searchExecuteQuickReview, 500) if (njQuery('#yv-popover').length == 0) { njQuery('body') .append('
') } } } yv.validation = { validateSingleEle: function (ele) { var ele = njQuery(ele); var isValid = true; //Elementos do tipo radio e checkbox são validados... if (ele.is(':radio,:checkbox')) { if (njQuery("[name='" + ele.attr('name') + "']:checked").length == 0) isValid = false; } //Elementos do tipo input são validados... if (ele.is('input:text,textarea,select')) { //Só valida se o elemento estiver visível na tela if (ele.is(':visible') && ele.attr('name') != 'user-name' && ele.val().length == 0) isValid = false; } return isValid }, validateCreateErr: function (element, errmsg) { if (element.hasClass('yv-user-email') || element.hasClass('yv-user-name') || element.hasClass('yv-user-phone')) { if (element.siblings('.yv-help-block').length == 0) element.after(errmsg); } else if (element.parents('.yv-form-group')) { if (njQuery('[name=user-email]').parents('.yv-form-group').find('.yv-help-block').length == 1) if (element.parents('.yv-form-group').find('.yv-help-block:visible').length == 0) element.parents('.yv-form-group').append(errmsg); } else if (element.parent('.yv-radio-inline').length) { if (!element.parent().parent().hasClass('yv-form-group')) element.parent().parent().append(errmsg); } else { errmsg.insertAfter(element); } }, validateSetErr: function (ele, errmsg) { var element = njQuery(ele); element.closest('.yv-form-group').addClass('yv-has-error'); yv.validation.validateCreateErr(element, errmsg); element.change(function () { if (!yv.validation.validateSingleEle(this)) element.closest('.yv-form-group').addClass('yv-has-error'); else { element.closest('.yv-form-group').removeClass('yv-has-error'); element.parents('.yv-form-group').find('.yv-help-block').remove(); } }); }, isValidReviewForm: function (start) { //Busca a todos os elementos que são obrigatórios (required) var requiredElements = njQuery(start + ' [required]'); var emailElements = njQuery(start + ' .yv-user-email'); var isValid = true; //Valida cada um deles var errmsg = '' + yv.localization.requiredField + ''; njQuery.each(requiredElements, function (i, v) { if (!yv.validation.validateSingleEle(v)) { yv.validation.validateSetErr(v, errmsg); isValid = false; } }); //Valida campos de e-mail var errmsgEmail = '' + yv.localization.invalidEmail + ''; njQuery.each(emailElements, function (i, v) { var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; if (!re.test(emailElements.val())) { yv.validation.validateSetErr(v, errmsgEmail); isValid = false; } }); return isValid; }, isValidUser: function () { var hasUserName = false; var hasEmail = false; var phone = njQuery('[name="yv-user-phone"]:visible'); var hasPhone = phone.length && phone.val(); njQuery.each(njQuery('[name="user-name"]:visible,[name="yv-exhibition-name"]:visible'), function (i, v) { var x = njQuery(v); if (x && x.val()) { hasUserName = true; return false; } }); njQuery.each(njQuery('[name="user-email"]'), function (i, v) { var x = njQuery(v); if (x && x.val()) { hasEmail = true; return false; } }); return hasUserName && hasEmail; }, setInvalid: function (ctx, track) { yv.utils.goTo('.yv-help-block:visible'); njQuery(ctx).removeAttr("disabled"); //Busca quais campos estão inválidos var invalidFieldNames = []; njQuery('.yv-has-error:visible').find(':input') .each(function (i, v) { var itm = njQuery(v).attr('name'); if (invalidFieldNames.indexOf(itm) == -1) invalidFieldNames.push(itm); }); var invalidResult = JSON.stringify(invalidFieldNames); yv.analyticsSupport.trackWriteReview(track, invalidResult); }, validateForm: function () { var validReviewForm = yv.validation.isValidReviewForm('#yv-show-form'); var validUser = yv.validation.isValidUser(); if (!validReviewForm || !validUser) { if (!validReviewForm) yv.validation.setInvalid(this, 'errRequiredFields'); if (!validUser) yv.validation.setInvalid(this, 'errValidateUser'); return false; } return true; } } yv.review = { startQuickReviewProductPage: function () { if (njQuery(yv.vendorCustom.quickReviewProdElement()).length) { var element = njQuery(yv.vendorCustom.quickReviewProdElement()); if (element[0]) { element.show(); njQuery.jsonpx(yv.uriBuilder.general('/review/getquickreviewproduct', '&productStoreId=' + yv.productId), function (resp) { yv.vendorCustom.quickReviewProdBefore(); element.html(resp.html); njQuery(yv.vendorCustom.quickReviewProdElement()).click(function () { yv.utils.goTo('#yv-reviews'); yv.analyticsSupport.trackWriteReview('review-more'); }); njQuery('#yv-writereview,.yv-writereview').click(function (e) { yv.review.showWriteReview(); }); }); } } }, 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(); } }); } }, startReviewForm: function () { if (njQuery('#yv-show-form').length) { if (yv.utils.qs['yv-write-review']) { yv.review.showWriteReview(); 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) { this.loadReviews(); } }, loadReviews: function () { yv.vendorCustom.reviewsBefore(); //TODO: Isso deveria ficar no template njQuery('#yv-reviews').css('clear', 'both'); this.getReviews(); }, getReviews: function () { yv.utils.toggleLoading(false, '#yv-reviews'); var orderText = ""; var querystring = "&extFilters="; 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 (typeof yv.order != "undefined") { querystring += "&orderby="+yv.order; orderText = yv.order; } if (yv.utils.qs['yv-review-template']) { querystring += '&yv-review-template=' + yv.utils.qs['yv-review-template']; } var productId = window.yv.productId; njQuery.jsonpx(yv.uriBuilder.general('/review/GetReview', '&productStoreId=' + productId + querystring), function (r) { // yv.review.loadReviewData(r); var element = njQuery('#yv-reviews'); // if (typeof yv.order != "undefined") { // yv.review.settingsOrderSelect(orderText); // } element.html(r.html); yv.commom.toggleViewMore(); if (element.find('.yv-reviews-slide').length > 0) { yv.ReviewsSlider.build( [ { slidesToShow: 3, slidesToShift: 3, showButtons: true, showPaging: false, infinite: false, breakpoint: 9999 }, { slidesToShow: 2, slidesToShift: 2, showButtons: true, showPaging: false, infinite: false, breakpoint: 940 }, { slidesToShow: 1, slidesToShift: 1, showButtons: true, showPaging: false, infinite: false, breakpoint: 690 } ], { containerReviews: '#yv-reviews-container', viewReviews: '#yv-reviews-view', wrapperReviews: '#yv-reviews-wrapper', slides: '.yv-reviews-slide', button: '#yv-write-review' }, 20 ); element.show(); } var urlImageGif = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'dr6jj3uz9kog7.cloudfront.net/static/images/loading.gif' //TODO: deve haver um template padrão para isso njQuery('#yv-reviews').append('
') njQuery('#yv-writereview,.yv-writereview').off('click') //Evita duplicidade de click njQuery('#yv-writereview,.yv-writereview').click(function (e) { yv.review.showWriteReview(); }); //Abrir automaticamente o formulário if (njQuery('#yv-reviews').data('yvopen') == true) yv.review.showWriteReview(true); }); }, settingsOrderSelect: function(queryString) { var textUl = jQuery('.yv-dropdown-menu [data-yv-order="' + queryString + '"]').text(); if (queryString === "" ) jQuery('.yv-order-reviews-text').text("Select"); else jQuery('.yv-order-reviews-text').text(textUl); }, loadOrders: function() { window.yv.order = 0; njQuery('[data-yv-order]').click(function(v) { event.preventDefault(); window.yv.order = $(this).attr('data-yv-order'); // yv.analyticsSupport.writeToGA('Alterou ordernação','Produto: ' + yv.productName); yv.review.getReviews(); return false; }); }, loadShare: function () { njQuery('.yv-share').click(function () { var reviewId = njQuery(this).attr('data-yv-rid'); var media = njQuery(this).attr('data-yv-media'); var action = '/share/index/' + reviewId; var parameters = '&media=' + media; parameters += '¤tPage=' + window.location.href; var link = yv.uriBuilder.generalNoCb(action, parameters); window.open(link, 'new', 'height=600,width=600'); }); }, loadUserUploadedImages: function () { if (njQuery('[data-yvaction="userimg-reviewshow"]').length) { njQuery('.yv-reviewsingleimg a').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(); }); if (yv.filters && yv.filters.length > 0) { njQuery('.yv-clear-filters').show(); } else { njQuery('.yv-clear-filters').hide(); } njQuery('.yv-clear-filters').click(function(e) { yv.filters = []; yv.review.getReviews(); }); 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'); //Remove filtro de Nota (só pode escolher um por vez) window.yv.filters = njQuery.grep(window.yv.filters,function(v) { return v.FilterFieldId != "rating" }); console.log(window.yv.filters); window.yv.filters = njQuery.grep(window.yv.filters,function(v) { return v.FilterFieldId != fieldId; }); console.log(window.yv.filters); //Armazena novo filtro window.yv.filters.push({ FilterFieldId: fieldId, FilterFieldValueId: fieldValueId }); yv.analyticsSupport.writeToGA('Utilizou um filtro','Produto: ' + yv.productName); //Recarrega os reviews yv.review.getReviews(); return false; }); }, loadReviewData: function (r) { if (r.html && r.hasResults) { $('#yv-show-reviews').html(r.html); yv.commom.loadLikeUnlike(); yv.review.loadShare(); yv.review.loadOrders(); yv.review.loadFilters(); yv.review.loadUserUploadedImages(); yv.review.loadRichSnippets(); yv.commom.toggleViewMore(); yv.analyticsSupport.trackScrollReview(); njQuery("#yv-reviews").trigger("yourviews.reviewsload"); } else if (r.html && !r.hasResults) njQuery('#yv-show-reviews').html(r.html); njQuery('#yv-writereview,.yv-writereview').off('click') //Evita duplicidade de click njQuery('#yv-writereview,.yv-writereview').click(function () { yv.review.showWriteReview(); }); //Se houver querystring, abre editor de formulário yv.review.gotoWriteReview(); //Carrega paginador yv.commom.loadPaging(yv.review.loadReviewData, yv.review.loadReviewData, '#yv-reviews'); yv.utils.toggleLoading(true, '#yv-reviews'); }, saveReview: function (ctx, r) { njQuery(ctx).attr("disabled", true); if (!yv.validation.validateForm()) { njQuery(ctx).attr("disabled", false); yv.utils.goTo('.yv-has-error'); return; } //Pega dados do formulário var data = njQuery('#yv-form :input').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']); njQuery(".yv-login-frame").parent().hide(); } //Pega dados do produto data += yv.commom.getProductDetails(); //Some com formulário e exibe "carregando" yv.utils.toggleLoading(false, '#yv-review-form'); yv.utils.goTo('#yv-show-form'); //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"]) { yv.analyticsSupport.trackWriteReview('saveReviewSms'); //Tracking do sistema sms } else { yv.analyticsSupport.trackWriteReview('saveReview'); //Tracking do sistema normal } } //Envia de fato os dados para salvar var uri = yv.uriBuilder.general('/reviewformsave/SaveReviewForm', '&productId=' + window.yv.productId + '&' + data); njQuery.jsonpx(uri, function (result) { //Exibe confirmação yv.utils.toggleLoading(true, '#yv-review-form'); njQuery('#yv-review-notfound').hide(); njQuery('#yv-review-form').html(result.html); }) .fail(function () { yv.utils.toggleLoading(true, '#yv-review-form'); njQuery('#yv-show-form').html('
' + yv.localization.genericError + '
'); }); njQuery(ctx).removeAttr("disabled"); }, saveReviewStore: function (ctx, r) { njQuery(this).attr("disabled", true); if (!yv.validation.validateForm()) { yv.utils.goTo('.yv-has-error'); njQuery(this).attr("disabled", false); return; } //Pega dados do formulário var data = njQuery('#yv-form :input').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']); } //Some com formulário e exibe "carregando" yv.utils.toggleLoading(false, '#yv-review-form'); yv.utils.goTo('#yv-show-form'); //Envia de fato os dados para salvar var uri = yv.uriBuilder.general('/reviewformsave/SaveStoreReviewForm', '&' + data); njQuery.jsonpx(uri, function (result) { //Exibe confirmação yv.utils.toggleLoading(true, '#yv-review-form'); njQuery('#yv-review-notfound').hide(); njQuery('#yv-review-form').html(result.html); }) .fail(function () { toggleLoading(true, '#yv-review-form'); njQuery('#yv-show-form').html('
' + yv.localization.genericError + '
'); }); njQuery(this).removeAttr("disabled"); }, showWriteReview: function (doNotScroll) { var urlreviewform = '/reviewform/getreviewform'; njQuery('#yv-show-form').show(400); njQuery('#yv-write-review').hide(200); if (!doNotScroll) yv.utils.goTo('#yv-show-form'); //#region Busca por querystrings var categoriesForm = ''; 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']); urlreviewform = '/reviewform/getstorereviewform'; } //#endregion njQuery.jsonpx(yv.uriBuilder.general(urlreviewform, categoriesForm), function (r) { //Exibe o formulário recebido njQuery('#yv-show-form').html(r.html); //Inicia tracking de eventos do formulário yv.analyticsSupport.startReviewFormAnalytics(); //Ajusta label das estrelas yv.commom.startStarLabel(); //Carrega social login yv.social.loadSocialLogin(); //Carrega componente de upload if (typeof yv.uploader !== 'undefined') yv.uploader.startUploader(); //Exibe/esconde dicas para escrever review njQuery(".yv-panel-review-comment").hide(); njQuery("[name='review-comment']").focus(function () { njQuery(".yv-panel-review-comment").show() }); njQuery("[name='review-comment']").focusout(function () { njQuery(".yv-panel-review-comment").hide() }); //Se ainda não foi, faz o scroll para o form aberto if (!doNotScroll) yv.utils.goTo('#yv-form'); //Salvar review njQuery('#yv-sendform').click(function (r) { yv.review.saveReview(this, r); }); njQuery('#yv-sendstoreform').click(function (r) { yv.review.saveReviewStore(this, r); }); 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); } }) .fail(function (jqXHR, textStatus, err) { njQuery(this).removeAttr("disabled"); njQuery('#yv-show-form').html('
' + yv.localization.genericError + '

'); var additionalError = '[{err: "' + encodeURIComponent(textStatus) + '"}]'; yv.analyticsSupport.trackWriteReview('reviewform-error', additionalError); }); }, gotoWriteReview: function () { if (yv.utils.qs['yv-write-review']) { this.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); } }); } }, loadRichSnippets: function () { var uri = yv.uriBuilder.generalSecondary('/review/richsnippetsubstitute/').replace('callback=?','') + '&productStoreId=' + yv.productId njQuery.ajax({ url:uri, type:"POST", data: JSON.stringify({currentJson : encodeURIComponent(njQuery('[type="application/ld+json"]:contains("Product")').text()) }), contentType:"application/json; charset=utf-8", dataType:"json", success: function(r){ njQuery('[type="application/ld+json"]:contains("Product")').text(r); } }) } } yv.social = { loadSocialLogin: function () { njQuery('.yv-google-login').click(function (event) { yv.social.socialLoginClick(this, event, 'google'); }); njQuery('.yv-fb-login').click(function (event) { yv.social.socialLoginClick(this, event, 'facebook'); }); njQuery('.yv-social-logout').click(function (e) { e.preventDefault(); var loadingElement = njQuery(this).parents('.yv-logged'); //Chama backend para buscar novo cookie de UserCandidate yv.utils.toggleLoading(false, loadingElement); njQuery.jsonpx(yv.uriBuilder.general('/user/logout'), function (r) { //Após logout, exibe login novamente yv.social.userLogout(loadingElement.parent()); yv.utils.toggleLoading(true, loadingElement); }) .fail(function () { yv.utils.toggleLoading(true, loadingElement); loadingElement.text('Erro. Tente novamente mais tarde'); }); }); njQuery('.yv-user-name').focus(function (e) { njQuery(this).parents('.yv-login').find('.yv-user-email:hidden').parents('div:hidden').show(500); }); njQuery('[name="user-email"]').focus(function (e) { njQuery(this).siblings('.yv-help-valid').hide(); njQuery(this).parent('div').removeClass('yv-has-error'); }); njQuery('[name="yv-user-phone"]').focus(function (e) { njQuery(this).siblings('.yv-help-valid').hide(); njQuery(this).parent('div').removeClass('yv-has-error'); }); njQuery('[name="user-name"]').focus(function (e) { njQuery(this).siblings('.yv-help-valid').hide(); njQuery(this).parent('div').removeClass('yv-has-error'); }); njQuery('.yv-user-phone').mask('(00) 0000-00009'); njQuery('.yv-user-image[src*="genericuser."]').tooltip({ placement: 'yv-bottom', title: yv.localization.socialConnect }); }, socialLoginClick: function (clicked, e, network) { e.preventDefault(); var listenerSocial = function (message) { if (message && message.origin && message.origin.indexOf('service.yourviews.com.br') > -1) { if (message.data && message.data.length) { window.removeEventListener("message", listenerSocial, false); localStorage.setItem('__yv_xauth', message.data); var uri = yv.uriBuilder.general('/user/getuser', '&loadsocialnetworks=true'); var loadingElement = njQuery(clicked).parents('.yv-login'); yv.utils.toggleLoading(false, loadingElement); njQuery.jsonpx(uri, function (res) { if (res && res.hasResults) { localStorage.setItem("__yv_user", res.html); yv.social.socialLoginParse(clicked, njQuery.parseJSON(res.html), network); } yv.utils.toggleLoading(true, loadingElement); }); } } } window.addEventListener("message", listenerSocial, false); var uri = yv.uriBuilder.general('/User/SocialLogin', '&network=' + network); var child = window.open(uri, "_blank", "height=600,width=800"); /* var loginInterval = setInterval(function () { if (child.closed) { //Janela de autenticação foi fechada... clearInterval(loginInterval); //Verifica se tem as informações do usuário... var uri = yv.uriBuilder.general('/user/getuser'); var loadingElement = njQuery(clicked).parents('.yv-login'); yv.utils.toggleLoading(false, loadingElement); njQuery.jsonpx(uri, function (res) { if (res && res.hasResults) { yv.social.socialLoginParse(clicked, njQuery.parseJSON(res.html), network); } yv.utils.toggleLoading(true, loadingElement); }); } }, 200); */ }, userLogout: function (ctxElement) { var userElement = njQuery(ctxElement).find('.yv-login'); njQuery(userElement).find('[name="user-logintype"]').val('email'); njQuery(userElement).find('[name="user-name"],[name="yv-exhibition-name"]').val(''); njQuery(userElement).find('[name="user-email"]').val(''); njQuery(userElement).find('[name="yv-user-phone"]').val(''); njQuery(userElement).find('[name="user-image"]').val(''); njQuery(ctxElement).find('[name="yv-exhibition-name"]').val(''); var userLogged = njQuery(ctxElement).find('.yv-logged'); njQuery(userLogged).find('.yv-user-image').attr("src", ''); njQuery(userElement).show(); njQuery(userLogged).hide(); }, socialLoginParse: function (element, user, network) { if (user != null && user) { var userElement = njQuery(element).parents('.yv-login:visible'); if (userElement.length) { njQuery(userElement).find('[name="user-logintype"]').val(network); //Preenche os campos de formulário associado ao clique njQuery(userElement).find('[name="user-email"]').val(user.Email); if (user.ImageUrl) { njQuery(userElement).find('[name="user-image"]').val(user.ImageUrl); njQuery(userLogged).find('.yv-user-image').attr("src", user.ImageUrl); } //Preenche os campos visuais de login var userLogged = njQuery(userElement).siblings('.yv-logged'); //njQuery(userLogged).find('.yv-user-name').text(user.Name); //njQuery(userLogged).find('.yv-user-email').text(user.Name); //Muda a exibição para usuário logado njQuery(userElement).hide(); njQuery(userLogged).show(); } userElement = njQuery(element).parents('.yv-login-frame:visible'); if (userElement.length && user.ImageUrl) { userElement.find('.yv-user-image').attr("src", user.ImageUrl); userElement.find('.yv-show-socialmedia').hide(); var exhibName = userElement.find('[name="yv-exhibition-name"]'); if (exhibName.val().length == 0) //Apenas altera nome se não houver escrito algum exhibName.val(user.Name); } } } } yv.commom = { toggleViewMore: function () { 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.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.more); elemToAct.find('.yv-viewmore-expanded').hide(); var Height = elemToAct.css("height"); njQuery(elemToAct).data("height", Height); njQuery(elemToAct).data("expanded", false); } }); }, debugIsCorrect: function (element) { //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 ' + element + ' but no yv-debug querystring.'); return false; } } return true; }, loadPaging: function (previousCallb, nextCallb, elementToAct, buttonName) { var btn = buttonName || ''; njQuery('.yv-hasresults[data-action="paging-previous' + btn + '"]').click(function (e) { e.preventDefault(); yv.utils.toggleLoading(false, elementToAct); yv.utils.goTo(elementToAct); njQuery.jsonpx(njQuery(this).data('href') + "&callback=?", function (r) { previousCallb(r); }); }); njQuery('.yv-hasresults[data-action="paging-next' + btn + '"]').click(function (e) { e.preventDefault(); yv.utils.toggleLoading(false, elementToAct); yv.utils.goTo(elementToAct); njQuery.jsonpx(njQuery(this).data('href') + "&callback=?", function (r) { nextCallb(r); }); }); }, loadLikeUnlike: function () { njQuery('.yv-like').click(function () { yv.utils.toggleLoading(false, njQuery(this).parent()); var rid = njQuery(this).attr('data-yv-rid'); var action = njQuery(this).attr('data-yv-action'); var _self = this; var uri = yv.uriBuilder.general('/reviewlike/' + action + '/' + rid); njQuery.jsonpx(uri, function (r) { yv.utils.toggleLoading(true, njQuery(_self).parent()); if (!r.html) return; var parsedResp = njQuery.parseJSON(r.html); if (parsedResp) njQuery(_self).children('.yv-like-count').text(parsedResp.count); }).fail(function () { yv.utils.toggleLoading(true, njQuery(_self).parent()); }); }); }, 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(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 || []; window.yv.serviceAddr = ('https:' === document.location.protocol ? 'https://' : 'http://') + 'service.yourviews.com.br'; window.yv.staticServiceAddr = ('https:' === document.location.protocol ? 'https://' : 'http://') + 'staticfiles.yviews.com.br'; window.yv.productUrl = window.location.href; //TODO: analisar a remoção desse parâmetro window.yv.secondaryAddr = 'https://service2.yourviews.com.br'; yv.uriBuilder = { generalNoCb: function (action, parameters) { return yv.serviceAddr + action + "?storeKey=" + yv.storeKey + parameters; }, 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=?'; }, 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=?'; } }; }, setInitialData: function () { yv.storeKey = 'b93db19a-848f-4ca1-a4f9-4539393482fb'; yv.debug = false; yv.commom.yvData(); } } yv.vendorCustom = { quickReviewGetIds: function () { const asyncShelfs = yv.vendorCustom.quickReviewAsyncSetup() let allShelfs = [] if (asyncShelfs) { allShelfs = allShelfs.concat(asyncShelfs) } return allShelfs }, quickReviewAsyncSetup: function () { const shelfToInsert = document.querySelectorAll('.product-small.box [class*="add-to-wishlist-"]'); 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('data-fragment-ref') if (!itemId) return if(jQuery('.product-template-default').length) { if (!e.closest('.product-small').querySelector('.yv-review-quickreview')) { e.closest('.product-small')?.querySelector('.price-wrapper')?.insertAdjacentHTML( 'afterend', '
' ) allIds.push(itemId) } } else { if (!e.closest('.product-small').querySelector('.yv-review-quickreview')) { e.closest('.product-small')?.querySelector('.price-wrapper')?.insertAdjacentHTML( 'afterend', '
' ) allIds.push(itemId) } } }) } if (typeof (quickReviewToLoad) !== "undefined" && quickReviewToLoad.length) { quickReviewToLoad.forEach((qr) => { if (qr) { let itemId = qr.getAttribute('value') allIds.push(itemId) } }) } return allIds }, quickReviewProdElement: function () { return "#yv-review-quickreview"; }, reviewsElement: function () { return "#yv-reviews"; }, QaElement: function () { return ".yv-qa"; }, quickReviewProdBefore: function () { }, reviewsBefore: function () { }, waitFor: function(condition, action) { var count = 0 var timer = setInterval(function() { if (count == 50) clearInterval(timer) if (condition()) { clearInterval(timer) action() } count += 1 }, 200) }, initialSetup: function () { var ismobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase())); if (njQuery('body.product-template-default').length) { // informações sobre o produto yv.productId = document.querySelector('#main .shop-container .product').getAttribute('id').split('-').pop() // yv.productId = njQuery('.yith-wcwl-add-to-wishlist').attr('data-fragment-ref') yv.imageUrl = njQuery('.product .images img').attr('src') yv.productName = jQuery('[property="og:title"]').attr('content') yv.productPrice = njQuery('[itemprop="offers"] .price .amount').text() yv.categoryForm = njQuery('.woocommerce-breadcrumb a').map(function (i, v) { return jQuery(v).text() }).get() jQuery('.woocommerce-product-rating').remove(); jQuery('#reviews').remove(); // âncora da página de produto // njQuery('h1.product_title') if(ismobile ) { njQuery('.product-title-container.is-large').before('
'); } else { njQuery('.product-title-container.is-large').last().before('
'); } // avaliações njQuery('#yr-custom-content') .append('
') // perguntas & respostas njQuery('.yv-box.yourviews').append('
') // oculta elemento com mensagem de avaliações não encontradas this.waitFor( function() { if(njQuery('#yv-review-notfound').length){ njQuery('#yv-review-quickreview').hide() njQuery('#yv-review-notfound').hide() } //return njQuery('#yv-review-notfound').length }, function() { njQuery('#yv-review-notfound').parents('.yv-box.yourviews').hide() } ) } else if (njQuery('body.home').length) { // depoimentos dos clientes jQuery('body.home #footer').before('') njQuery('.col-inner [id*="cr-reviews-slider-"]').map(function(i, e) { e.remove() }) } // selo de loja confiável njQuery('#footer .section.dark .is-divider + .row.row-collapse') .append('
Loja Confiável
') // estrelas nas prateleiras // yv.vendorCustom.quickReviewAsyncSetup(); }, 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) { var offset = njQuery(element).offset(); if (!offset) return; njQuery('html, body').animate({ scrollTop: njQuery(element).offset().top - 200 }, 500); }, 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 (hide, element) { var elementToAttach = element || '.yv-main'; if (!hide) { var loadingCss = "
"; njQuery(loadingCss).css({ position: "absolute", width: "100%", height: "100%", top: 0, left: 0, background: "white", }).appendTo(njQuery(elementToAttach).css("position", "relative")); } else { njQuery(elementToAttach).find('#yv-loading-main').remove(); njQuery(elementToAttach).css("position", "") } }, getRandom: function () { var min = 1000000000000; var max = 9999999999999; return Math.round(Math.random() * (max - min) + min); } }; yv.libraries = { loadComponents: function () { yv.libraries.BootstrapJS(); yv.libraries.Css(); }, BootstrapJS: function () { //#region jsonpx (function ($) { // ###################### UTILITIES ## // Noop function noop() { } // Generic callback function genericCallback(data) { lastValue = [data]; } // Call if defined function callIfDefined(method, object, parameters) { return method && method.apply(object.context || object, parameters); } // Give joining character given url function qMarkOrAmp(url) { return /\?/.test(url) ? "&" : "?"; } var // String constants (for better minification) STR_ASYNC = "async", STR_CHARSET = "charset", STR_EMPTY = "", STR_ERROR = "error", STR_INSERT_BEFORE = "insertBefore", STR_JQUERY_JSONP = "_jqjsp", STR_ON = "on", STR_ON_CLICK = STR_ON + "click", STR_ON_ERROR = STR_ON + STR_ERROR, STR_ON_LOAD = STR_ON + "load", STR_ON_READY_STATE_CHANGE = STR_ON + "readystatechange", STR_READY_STATE = "readyState", STR_REMOVE_CHILD = "removeChild", STR_SCRIPT_TAG = ""; njQuery('head').append(upcSettings); var scriptUrl = yv.vendorCustom.uploadCareUrl != undefined ? yv.vendorCustom.uploadCareUrl() : "https://ucarecdn.com/widget/2.9.0/uploadcare/uploadcare.full.min.js"; var script_tag = document.createElement('script'); script_tag.setAttribute("type", "text/javascript"); script_tag.setAttribute("src", scriptUrl); if (script_tag.readyState) { script_tag.onreadystatechange = function () { // For old versions of IE if (this.readyState === 'complete' || this.readyState === 'loaded') { yv.uploader.loaded(); } }; } else { script_tag.onload = yv.uploader.loaded; } (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag); } } yv.load.init(); }(window.yv = window.yv || {}, window.jQuery));