Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var neemuPlugin=neemuPlugin||{};(function(window,document,undefined,$){var _nm = window._nm =window._nm||{};_nm.buildDate='21_06_2016';(function(window, document) {
- /**
- * Copyright (c) 2015 - Neemu Serviços em Tecnologia da Informação S.A
- *
- * LICENSE: This software is the confidential and proprietary information of
- * Neemu S.A ("Confidential Information"). You shall not disclose such
- * Confidential Information and shall use it only in accordance with the terms
- * of the license agreement you entered into with Neemu S.A.
- */
- if (!Function.prototype.bind) {
- Function.prototype.bind = function(oThis) {
- if (typeof this !== 'function') {
- // closest thing possible to the ECMAScript 5
- // internal IsCallable function
- throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
- }
- var aArgs = Array.prototype.slice.call(arguments, 1),
- fToBind = this,
- fNOP = function() {},
- fBound = function() {
- return fToBind.apply(this instanceof fNOP && oThis
- ? this
- : oThis,
- aArgs.concat(Array.prototype.slice.call(arguments)));
- };
- fNOP.prototype = this.prototype;
- fBound.prototype = new fNOP();
- return fBound;
- };
- }
- if (!String.prototype.trim) {
- String.prototype.trim = function () {
- return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
- };
- }
- // Passos para a produção do ECMA-262, Edition 5, 15.4.4.14
- // Referência: http://es5.github.io/#x15.4.4.14
- if (!Array.prototype.indexOf) {
- Array.prototype.indexOf = function(elementoDePesquisa, pontoInicial) {
- var k;
- //1. Deixe-o ser o resultado da chamada de toObject
- // passando o valor de this como argumento.
- if (this == null) {
- throw new TypeError('"this" é nulo (null) ou não foi definido (undefined');
- }
- var O = Object(this);
- // 2. Deixar o tamanhoValor ser o resultado da
- // chamada do método interno Get de 0 com o
- // argumento "length"
- // 3. Deixar o tamanhoValor ser um ToUint32(tamanhoValor).
- var tamanho = O.length >>> 0;
- // 4. se o tamanho é 0, retorna -1.
- if (tamanho === 0) {
- return -1;
- }
- // 5. Se o argumento pontoInicial for passado, use o ToInteger(pontoInicial); senao use 0.
- var n = + pontoInicial || 0;
- if (Math.abs(n) === Infinity) {
- n = 0;
- }
- //6. Se n >= tamanho, retorna -1.
- if (n >= tamanho) {
- return -1;
- }
- // 7. Se n>= 0, entao k seja n.
- // 8. Senao, n<0, k seja tamanho - abs(n).
- // Se k é menor que 0, entao k seja 0.
- k = Math.max(n >= 0 ? n : tamanho - Math.abs(n), 0);
- // 9. Repita, enquanto k < tamanho
- while (k < tamanho) {
- // a. Deixe Pk ser ToString(k).
- // isto é implicito para operandos LHS de um operador
- // b. Deixe o kPresent ser o resultado da chamada do método interno de 0 com argumento Pk
- // Este passo pode ser combinado com c.
- // c. Se kPresent é true, entao
- // i. Deixe o elementK ser o resultado da chamada do metodo interno Get de 0 com argumento ToString(k)
- // ii. Deixe o resultado ser aplicado pelo Algoritmo de
- // Comparação de Igualdade Estrita (Strict Equality Comparison) para o elementoDePesquisa e elementK
- // iii. caso verdadeiro, retorne k.
- if (k in O && O[k] === elementoDePesquisa) {
- return k;
- }
- k++;
- }
- return -1;
- };
- }
- if (!window.getComputedStyle) {
- window.getComputedStyle = function(el, pseudo) {
- this.el = el;
- this.getPropertyValue = function(prop) {
- var re = /(\-([a-z]){1})/g;
- if (prop == 'float') prop = 'styleFloat';
- if (re.test(prop)) {
- prop = prop.replace(re, function () {
- return arguments[2].toUpperCase();
- });
- }
- return el.currentStyle[prop] ? el.currentStyle[prop] : null;
- }
- return this;
- }
- }
- if (!document.getElementsByClassName) {
- var indexOf = [].indexOf || function(prop) {
- for (var i = 0; i < this.length; i++) {
- if (this[i] === prop) return i;
- }
- return -1;
- };
- getElementsByClassName = function(className, context) {
- var elems = document.querySelectorAll ? context.querySelectorAll("." + className) : (function() {
- var all = context.getElementsByTagName("*"),
- elements = [],
- i = 0;
- for (; i < all.length; i++) {
- if (all[i].className && (" " + all[i].className + " ").indexOf(" " + className + " ") > -1 && indexOf.call(elements, all[i]) === -1) elements.push(all[i]);
- }
- return elements;
- })();
- return elems;
- };
- document.getElementsByClassName = function(className) {
- return getElementsByClassName(className, document);
- };
- var Element = Element || null;
- if(Element) {
- Element.prototype.getElementsByClassName = function(className) {
- return getElementsByClassName(className, this);
- };
- }
- }
- // Production steps of ECMA-262, Edition 5, 15.4.4.19
- // Reference: http://es5.github.io/#x15.4.4.19
- if (!Array.prototype.map) {
- Array.prototype.map = function(callback, thisArg) {
- var T, A, k;
- if (this == null) {
- throw new TypeError(' this is null or not defined');
- }
- // 1. Let O be the result of calling ToObject passing the |this|
- // value as the argument.
- var O = Object(this);
- // 2. Let lenValue be the result of calling the Get internal
- // method of O with the argument "length".
- // 3. Let len be ToUint32(lenValue).
- var len = O.length >>> 0;
- // 4. If IsCallable(callback) is false, throw a TypeError exception.
- // See: http://es5.github.com/#x9.11
- if (typeof callback !== 'function') {
- throw new TypeError(callback + ' is not a function');
- }
- // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
- if (arguments.length > 1) {
- T = thisArg;
- }
- // 6. Let A be a new array created as if by the expression new Array(len)
- // where Array is the standard built-in constructor with that name and
- // len is the value of len.
- A = new Array(len);
- // 7. Let k be 0
- k = 0;
- // 8. Repeat, while k < len
- while (k < len) {
- var kValue, mappedValue;
- // a. Let Pk be ToString(k).
- // This is implicit for LHS operands of the in operator
- // b. Let kPresent be the result of calling the HasProperty internal
- // method of O with argument Pk.
- // This step can be combined with c
- // c. If kPresent is true, then
- if (k in O) {
- // i. Let kValue be the result of calling the Get internal
- // method of O with argument Pk.
- kValue = O[k];
- // ii. Let mappedValue be the result of calling the Call internal
- // method of callback with T as the this value and argument
- // list containing kValue, k, and O.
- mappedValue = callback.call(T, kValue, k, O);
- // iii. Call the DefineOwnProperty internal method of A with arguments
- // Pk, Property Descriptor
- // { Value: mappedValue,
- // Writable: true,
- // Enumerable: true,
- // Configurable: true },
- // and false.
- // In browsers that support Object.defineProperty, use the following:
- // Object.defineProperty(A, k, {
- // value: mappedValue,
- // writable: true,
- // enumerable: true,
- // configurable: true
- // });
- // For best browser support, use the following:
- A[k] = mappedValue;
- }
- // d. Increase k by 1.
- k++;
- }
- // 9. return A
- return A;
- };
- }
- /**
- * Module which contains utilitarian functions
- *
- * @author Javier Zambrano <javier@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @version 2.2.0
- * @param {Object} window
- * @param {Object} document
- * @return {Object}
- */
- function Commons(){}
- var cm = Commons.prototype;
- /**
- * Default ajax request
- *
- * @author Andrew C. Pacifico <andrewpacifico@neemu.com>
- * @method ajax
- * @param {Object} options A set of key/value pairs that configure
- * the Ajax request.
- * @param {Object} options.url A string containing the URL to which the request
- * is sent. This parameter is obrigatory.
- * @param {Object} options.type The method of request. The default value is 'GET'
- * @param {Object} options.data Data to be sent to the server. It is converted
- * to a query string,
- * @return {Void}
- */
- cm.ajax = function(options) {
- var callback = (typeof options.callback === 'function')
- ? options.callback
- : function(data) {};
- var requestData = (typeof options.data === 'object') ? options.data : {};
- var requestMethod = (
- options.type === undefined
- || (
- options.type.toUpperCase() !== 'GET'
- && options.type.toUpperCase() !== 'POST'
- )
- )
- ? 'GET'
- : options.type.toUpperCase();
- if (typeof options.url !== 'string' && options.url === '') {
- return;
- }
- var xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function() {
- if (xhr.readyState == XMLHttpRequest.DONE) {
- if(xhr.status == 200) {
- var responseData;
- try {
- responseData = JSON.parse(xhr.responseText);
- } catch(e) {
- responseData = xhr.responseText;
- }
- callback(responseData);
- } else if(xhr.status == 400) {
- console.log('There was an error 400')
- } else {
- console.log('something else other than 200 was returned')
- }
- }
- }
- // encode request data
- var query = [];
- for(var param in requestData) {
- query.push(param + '=' + encodeURIComponent(requestData[param]));
- }
- var encodedData = query.join('&');
- var url = (requestMethod === 'POST')
- ? options.url
- : options.url +
- (options.url.indexOf('?') >= 0 ? '&' : '?') +
- encodedData;
- xhr.open(requestMethod, url, true);
- if (requestMethod === 'POST') {
- xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
- xhr.send(encodedData);
- } else {
- xhr.send();
- }
- }
- ;
- /**
- * Ajax request using JSONP
- * @author Ivanildo de castro <ivanildocastro@neemu.com>
- * @since 1.0.0
- * @param {Object} options
- * - {String} url
- * - {Boolean} async[optional],
- * - {Function} success
- * - {Object} data[optional]
- * @return {Void}
- */
- cm.ajaxJsonp = function(options){
- //-----------------------------------------------------------------------------------------
- var
- url = (typeof options.url === 'string')?options.url:'',
- async = (typeof options.async === 'boolean')?options.async:true,
- callback = options.success?options.success:function(){},
- data = (typeof options.data === 'object')?options.data:'',
- //-----------------------------------------------------------------------------------------
- callbackName = 'jsonp_neemu_callback_' + (new Date()).getTime(),
- scriptTag = document.createElement('script');
- //-----------------------------------------------------------------------------------------
- var head = document.head || document.getElementsByTagName('head')[0];
- window[callbackName] = function(data){
- try{
- delete window[callbackName];
- }catch(e){
- window[callbackName] = undefined;
- }
- head.removeChild(scriptTag);
- if(typeof callback === 'function' && !scriptTag.ajaxAbort){
- callback(data);
- }
- }.bind(this);
- //-----------------------------------------------------------------------------------------
- if(data){
- var query = [];
- for(var i in data){
- query.push(i+'='+data[i]);
- }
- data = query.join('&');
- }
- //-----------------------------------------------------------------------------------------
- url = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName + '&'+data;
- //-----------------------------------------------------------------------------------------
- scriptTag.async = async;
- scriptTag.src = url;
- scriptTag.setAttribute('ajax_jsonp', 'neemu_plugin');
- head.appendChild(scriptTag);
- //-----------------------------------------------------------------------------------------
- }
- ;
- /**
- * Aborta a requst jsonp do método ajaxJsonp
- * @author Ivanildo de castro <ivanildocastro@neemu.com>
- * @since 2.2.0
- */
- cm.ajaxJsonpAbort = function(){
- var o = this.querySelectorAll('script[ajax_jsonp=neemu_plugin]');
- for(var i = 0;i<o.length;i++){
- o[i].ajaxAbort = true;
- }
- };
- /**
- * Simulates a ajax request using JSONP
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {String} url
- * @return {Void}
- */
- cm.ajaxRequestJsonp = function(url) {
- document
- .getElementsByTagName("head")[0]
- .appendChild(this.createElement("script", {
- "src": url
- }));
- };
- /**
- * Remove a list of items from a given array.
- *
- * @author Andrew C. Pacifico <andrewpacifico@neemu.com>
- * @param {Array} array The array to remove the elements.
- * @param {Array} items The list elements to remove.
- */
- cm.arrayRemove = function(array, items) {
- for (var i = 0, len = items.length; i < len; ++i) {
- var index = array.indexOf(items[i]);
- if (index !== -1) {
- array.splice(index, 1);
- }
- }
- }
- ;
- /**
- * Randomize the elements of a given array.
- *
- * @author Andrew C. Pacifico <andrewpacifico@neemu.com>
- * @param {Array} array The array to shuffle the elements.
- * @return {Array} The shuffled array
- */
- cm.arrayShuffle = function(array) {
- var currentIndex = array.length, temporaryValue, randomIndex ;
- // While there remain elements to shuffle...
- while (0 !== currentIndex) {
- // Pick a remaining element...
- randomIndex = Math.floor(Math.random() * currentIndex);
- currentIndex -= 1;
- // And swap it with the current element.
- temporaryValue = array[currentIndex];
- array[currentIndex] = array[randomIndex];
- array[randomIndex] = temporaryValue;
- }
- return array;
- }
- ;
- /**
- * Sort a array of objects by specific field that object
- *
- * @since 1.0.0
- * @{@link http://stackoverflow.com/a/979325}
- * @example
- *
- * var testArray = [
- * {
- * index : "2",
- * name : "title2"
- * },
- * {
- * index : "1",
- * name : "title1"
- * }
- * ];
- *
- * testArray.sort(_nm.commons.arraySortBy(
- * "index", // field sort
- * false // ascending
- * ));
- *
- * // returns
- * [
- * {
- * index : "1",
- * name : "title1"
- * },
- * {
- * index : "2",
- * name : "title2"
- * }
- * ]
- *
- * @param {String} field
- * @param {Boolean} reverse
- * @param {Function} primer
- * @return {Array}
- */
- cm.arraySortBy = function(field, reverse, primer) {
- // default primer as parseInt
- if (primer === undefined) {
- primer = parseInt;
- }
- var key = primer
- ? function(x) { return primer(x[field]) }
- : function(x) { return x[field] };
- reverse = !reverse ? 1 : -1;
- return function (a, b) {
- return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
- }
- };
- /**
- * Check one condition periodically until it is true or reaches
- * the retry limit
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @since 1.0.0
- * @param {Integer} max maximum number of retry
- * @param {Integer} time time interval between retry
- * @param {Function} fnCheck callback check
- * @param {Function} fnCallback callback which will be executed if the
- * check function is true
- * @return {Void}
- */
- cm.checkConditionInterval = function(max, time, fnCheck, fnCallback) {
- var qtty = 0,
- response,
- returnType = "success",
- fnCheckInterval = setInterval(function() {
- qtty++;
- try {
- response = fnCheck();
- } catch(e) {
- response = false;
- }
- if (response !== false || qtty >= max) {
- clearInterval(fnCheckInterval);
- if(qtty >= max) {
- returnType = "error";
- }
- fnCallback(returnType, response);
- }
- }, time);
- };
- /**
- * Remove a cookie
- *
- * reference: https://developer.mozilla.org/en-US/docs/DOM/document.cookie
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @since 1.0.0
- * @param {String} name
- * @param {String} host
- * @return {Void}
- */
- cm.deleteCookie = function(name, host) {
- this.setCookie(name, '', -1, '/', host);
- };
- /**
- * Returns a cookie by your name
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @author Andrews Lince <jhozefem@neemu.com>
- * @since 1.0.0
- * @param {String} name
- * @return {Void}
- */
- cm.getCookie = function(name) {
- var cValue = document.cookie.replace(
- new RegExp(
- "(?:(?:^|.*;)\\s*"
- + encodeURIComponent(name).replace(/[\-\.\+\*]/g, "\\$&")
- + "\\s*\\=\\s*([^;]*).*$)|^.*$"
- ),
- "$1"
- );
- cValue = this.decodeUrl(cValue);
- return cValue || undefined;
- };
- /**
- * Set a cookie on the browser
- *
- * @author Jhozefem Popntes <jhozefem@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {String} cName
- * @param {String} sValue
- * @param {Integer} vEnd
- * @param {String} sPath
- * @param {String} sDomain
- * @param {Boolean} bSecure
- * @return {Void}
- */
- cm.setCookie = function(cName, sValue, vEnd, sPath, sDomain, bSecure) {
- if (vEnd != Infinity && typeof(vEnd) == 'number') {
- var minutes = vEnd;
- vEnd = new Date();
- vEnd.setTime(vEnd.getTime() + (minutes * 60 * 1000));
- }
- if (!cName || /^(?:expires|max\-age|path|domain|secure)$/i.test(cName)) {
- return false;
- }
- var sExpires = "";
- if (vEnd) {
- switch (vEnd.constructor) {
- case Number:
- sExpires = (vEnd === Infinity)
- ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT"
- : "; max-age=" + vEnd;
- break;
- case String:
- sExpires = "; expires=" + vEnd;
- break;
- case Date:
- //sExpires = "; expires=" + vEnd.toUTCString();
- sExpires = "; expires=" + vEnd.toString();
- break;
- }
- }
- document.cookie = encodeURIComponent(cName)
- + "=" + encodeURIComponent(sValue)
- + sExpires
- + (sDomain ? "; domain=" + sDomain : "")
- + (sPath ? "; path=" + sPath : "")
- + (bSecure ? "; secure" : "");
- return true;
- };
- /**
- * Call a function after which the HTML page is totally loaded
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @since 1.0.0
- * @param {Function} callbackFunction
- * @return {Void}
- */
- cm.domReady = function(callbackFunction) {
- var win = window;
- if(document.readyState === "complete") {
- callbackFunction();
- } else if (win.addEventListener) {
- win.addEventListener("load", callbackFunction);
- } else {
- win.attachEvent("onload", callbackFunction);
- }
- };
- /**
- * Cria animações com os style do DOM element
- * @author Ivanildo de Castro <ivanildocastro@neemu.com>
- * @since 2.1.0
- * @param {Object} element
- * @param {Object} properties
- * @param {Integer} time
- * @param {Function} callback[optional]
- */
- cm.animate = function(element, properties, time, callback){
- if(typeof element === 'object' && element.nodeType === 1 && typeof properties === 'object'){
- var options = {}, o, property, start, end;
- for(var i in properties){
- property = i.replace(/-[a-z]{1}/g, function($1){
- return $1[1].toUpperCase();
- });
- start = parseInt(
- element.style[property] ||
- window
- .getComputedStyle(element,null)
- .getPropertyValue(property.replace(/[A-Z]{1}/g, function($1){
- return '-' + $1.toLowerCase();
- }))
- );
- if(!start && ['height', 'width'].indexOf(property) !== -1){
- var propertyOffset = 'offset'+property.replace(/^[A-z]{1}/, function($1){
- return $1.toUpperCase();
- });
- start = element[propertyOffset];
- }else if(!start){
- start = 0;
- }
- end = properties[i];
- end = (end > start)?(end - start):(start - end);
- o = {
- start:start,
- step:(end/time),
- end:properties[i]
- };
- o.step = ((o.start < o.end)?1:-1) * o.step;
- options[property] = o;
- }
- setTimeout(
- function(element, options, timeStart, time, callback){
- timeStart++;
- if(timeStart > time){
- if(typeof callback === 'function'){
- callback.call(element, element);
- }
- }else{
- for(var i in options){
- var
- o = options[i],
- start = o.start + o.step;
- o.start = start;
- element.style[i] = start + 'px';
- }
- setTimeout(
- arguments.callee.bind(
- this,
- element,
- options,
- timeStart,
- time,
- callback), 1);
- }
- }.bind(
- {},
- element,
- options,
- 0,
- time,
- callback
- ), 1);
- }
- };
- /**
- * Cria animações de alerta vibrante :)
- * @author Ivanildo de Castro <ivanildocastro@neemu.com>
- * @since 2.1.0
- * @param {Object} element
- * @param {Integer} intShakes
- * @param {Integer} intDistance
- * @param {Integer} intDuration
- * @param {Function} callback[optional]
- * @param {Integer} count(Obs.:controle interno da função, nuca será necessário usar externamente)
- */
- cm.shake = function(element, intShakes, intDistance, intDuration, callback, count){
- if(!element.inShakes){
- element.inShakes = true;
- count = (!count && count === undefined)?intShakes:count;
- if(count > 0){
- var
- thisShake = arguments.callee,
- marginLeftInitial = parseInt(
- element.style.marginLeft ||
- window.getComputedStyle(element,null).getPropertyValue('margin-left')
- );
- //1# animação
- this.animate(
- element,
- {marginLeft:marginLeftInitial + (intDistance*-1)},
- parseInt(((intDuration/intShakes)/4)),
- //2# animação
- this.animate.bind(
- this,
- element,
- {marginLeft:marginLeftInitial + intDistance},
- parseInt((intDuration/intShakes)/2),
- //3# animação
- this.animate.bind(
- this,
- element,
- {marginLeft:marginLeftInitial},
- parseInt(((intDuration/intShakes)/4)),
- //4# loop
- function(){
- delete element.inShakes;
- thisShake.call(
- this,
- element,
- intShakes,
- intDistance,
- intDuration,
- callback,
- count - 1
- )
- }.bind(this)
- )
- )
- );
- }else{
- delete element.inShakes;
- }
- //para executar quando iniciar a animação
- if(typeof callback === 'function' && count === 0){
- callback(element);
- }
- }
- };
- /**
- * Manage the event register in a object
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {Array} objects
- * @param {String} event
- * @param {Function} callback
- * @return {Void}
- */
- cm.addEventListener = function(objects, event, callback) {
- var type = Object.prototype.toString.call(objects);
- if(type !== "[object NodeList]" && type !== "[object Array]") {
- objects = [ objects ];
- }
- for(var index = 0; index < objects.length; index++) {
- if(objects[index] === undefined) {
- break;
- }
- if(typeof(objects[index].addEventListener) === "function") {
- objects[index].addEventListener(event, callback, false);
- } else {
- objects[index].attachEvent("on" + event, callback);
- }
- }
- };
- /**
- * Remove the event in a object
- * @author Ivanildo de Castro <ivanildocastro@neemu.com>
- * @since 1.0.0
- * @param {Array} objects
- * @param {String} event
- * @param {Function} callback
- * @return {Void}
- */
- cm.removeEventListener = function(objects, event, callback) {
- var type = Object.prototype.toString.call(objects);
- if(type !== "[object NodeList]" && type !== "[object Array]") {
- objects = [ objects ];
- }
- for(var index = 0; index < objects.length; index++) {
- if(objects[index] === undefined) {
- break;
- }
- if(typeof(objects[index].removeEventListener) === "function") {
- objects[index].removeEventListener(event, callback, false);
- } else {
- objects[index].detachEvent("on" + event, callback);
- }
- }
- };
- /**
- * Param de executar o evento para os demais filhos do objeto
- * @author Ivanildo de Castro <ivanildocastro@neemu.com>
- * @since 2.1.0
- * @param {Object} event
- */
- cm.stopPropagation = function(event){
- if(event.preventDefault){
- event.preventDefault();
- }
- if(event.stopPropagation){
- event.stopPropagation();
- }
- event.cancelBubble = true;
- };
- /**
- * Format a number from currency option
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {Number} value
- * @param {String} currency
- * @return {String}
- */
- cm.formatCurrency = function(value, currency) {
- // checks if value is valid
- if(value === undefined) {
- return value;
- }
- // sets the default currency which brazilian
- // if (currency === undefined) {
- // // currency = "BRL";
- // currency = "";
- // }
- var finalValue = "";
- value = value.toString();
- // checks if the value is rounded and has no decimal places
- if (
- !this.strstr(value, ",")
- && !this.strstr(value, ".")
- ) {
- value = value + ".00";
- }
- //removendo if else que não vai ser preciso pela condições
- //if(value.match(/[^0-9]+/g) != null) {
- value = value.replace(/[^0-9,\.]+/g, '');
- if(value.indexOf(",") !== -1) {
- value = value.replace(/\./g, "").replace(",", ".");
- }
- finalValue = parseFloat(value);
- //} else {
- // finalValue = (parseFloat(value) / 100);
- //}
- // return finalValue.toFixed(2) + " " + currency.trim();
- return finalValue.toFixed(2);
- };
- /**
- * Get all the url parameters (by query string)
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @return {Object}
- */
- cm.getRequestParams = function() {
- var requestParams = {},
- reqParts = [],
- nextIndex = 0,
- currentRequestParams = this.decodeUrl(window.location.search)
- .substr(1).split("&");
- for (var i = 0; i < currentRequestParams.length; i++) {
- reqParts = currentRequestParams[i].split("=");
- nextIndex = i + 1;
- // validate if the next index contains "="
- if (
- currentRequestParams[nextIndex] !== undefined
- && !this.strstr(currentRequestParams[nextIndex], "=")
- ) {
- // append the valur from the next index
- reqParts[1] += "&" + currentRequestParams[nextIndex];
- // remove next index
- currentRequestParams.splice(nextIndex, 1);
- }
- requestParams[reqParts[0]] = reqParts[1];
- }
- return requestParams;
- };;
- /**
- * Checks if is a mobile environment
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @since 1.0.0
- * @return {Boolean} [description]
- */
- cm.isMobile = function() {
- var check = false;
- (function(a){
- if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) {
- check = true;
- }
- })(navigator.userAgent||navigator.vendor||window.opera);
- return check;
- };
- /**
- * Checks if the current page is a neemu search (with and without ajax)
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {String} email
- * @return {Boolean}
- */
- cm.isNeemuSearch = function(){
- return (window.NeemuSearch !== undefined)
- ? true
- : false;
- };
- /**
- * Checks if the current page is a neemu search
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {String} string
- * @return {Boolean}
- */
- cm.isSearchFilter = function(string) {
- return (
- this.strstr(string, "common_filter")
- || this.strstr(string, "range_filter")
- )
- ? true
- : false;
- };
- /**
- * Performs a regex validation in a string and returns if is a valid
- * email or not
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {String} email
- * @return {Boolean}
- */
- cm.isValidEmail = function(email) {
- var isValidEmail = false,
- regexPattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
- if (email !== undefined && typeof(email) === "string") {
- isValidEmail = regexPattern.test(email);
- }
- return isValidEmail;
- };
- /**
- * Checks if a variable exists
- *
- * @author Javier Ferreira <javier@neemu.com>
- * @since 1.0.0
- * @param {Mixed} variable
- * @return {Boolean}
- */
- cm.isset = function(variable) {
- return variable !== undefined && variable !== null;
- };
- /**
- * Include a script (js or css) in the page and register the file in a
- * queue, for manage this files
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {String} source
- * @param {Function} callback
- * @return {Void}
- */
- cm.loadFile = function(source, callback) {
- var file = undefined,
- doc = document;
- if (this.strstr(source, ".js")) {
- file = doc.createElement('script');
- file.setAttribute("type","text/javascript");
- file.setAttribute("async", 'true');
- file.setAttribute("src", source);
- } else if (this.strstr(source, ".css")) {
- file = doc.createElement("link");
- file.setAttribute("rel", "stylesheet");
- file.setAttribute("type", "text/css");
- file.setAttribute("href", source);
- }
- // append in the HEAD element
- if (file !== undefined) {
- doc.getElementsByTagName('head')[0].appendChild(file);
- if(typeof(file.readyState) !== "undefined") {
- file.onreadystatechange = function() {
- if(
- file.readyState === "loaded"
- || file.readyState === "complete"
- ) {
- file.onreadystatechange = null;
- if(typeof(callback) === "function") {
- callback();
- }
- }
- };
- } else {
- file.onload = function() {
- file.onload = null;
- if(typeof(callback) === "function") {
- callback();
- }
- };
- }
- }
- return file;
- };
- /**
- * Adiciona class ao objeto DOM
- * @author Ivanildo de Castro <ivanildocastro@neemu.com>
- * @since 2.0.0
- * @param {Object} element
- * @param {String} className
- * @return {Void}
- */
- cm.addClass = function(element, className){
- var array = (typeof element === 'object' && element.length)?element:[element];
- for(var i = 0; i < array.length ; i++){
- var c = array[i].className + '';
- c = c.trim().replace(/\s+/g, ' ');
- if(!(new RegExp('\\b'+className.trim()+'\\b','gi')).test(c)){
- c += ' '+className;
- }
- array[i].className = c;
- }
- }
- ;
- /**
- * Creates a HTML element
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {String} type DOM element
- * @param {Object} opt Objetos que representam os atributos do no
- * @return {Node}
- * @example
- * createElement("div", {
- * id : "neemu",
- * style : "margin-top:20px; color:red;"
- * });
- */
- cm.createElement = function(type, opt) {
- var element = document.createElement(type);
- for (var name in opt) {
- if (name === "html") {
- element.innerHTML = opt[name];
- } else {
- element.setAttribute(name, opt[name]);
- }
- }
- return element;
- };
- /**
- * Encode a JSON object to the base 64 value
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {Object} value
- * @return {String}
- */
- cm.encode = function(value) {
- var json = this.parseObjectToJSON(value);
- return (window.btoa)
- ? window.btoa(unescape(encodeURIComponent(json)))
- : this.base64Encode(json);
- };
- /**
- * Checks if the object has some property
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {Object} obj
- * @return {Boolean}
- */
- cm.objectIsEmpty = function(obj) {
- return (Object.getOwnPropertyNames(obj).length === 0)
- ? true
- : false;
- };
- /**
- * Merge the properties of two objects
- *
- * reference: http://stackoverflow.com/a/171256
- * @since 1.0.0
- * @param {Object} obj1
- * @param {Object} obj2
- * @return {Object}
- */
- cm.objectMerge = function(obj1, obj2) {
- var obj3 = {};
- for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
- for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
- return obj3;
- };
- /**
- * Turn a object to the json string
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @since 1.0.0
- * @param {Object} obj
- * @return {String}
- */
- cm.parseObjectToJSON = function(obj) {
- /**
- * Prepare a string between double quotes to json
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @since 1.0.0
- * @param {String} string
- * @return {String}
- */
- function quoteString (string) {
- var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
- meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' };
- escapable.lastIndex = 0;
- return escapable.test(string) ?
- '"' + string.replace(escapable, function(a)
- {
- var c = meta[a];
- return typeof c === 'string' ?
- c
- : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
- }) + '"' : '"' + string + '"';
- };
- var type = typeof (obj);
- if (type != "object" || obj === null) {
- if (type == "string") {
- obj = quoteString(obj);
- }
- return String(obj);
- } else {
- var value,
- json = [],
- isArray = (obj && obj.constructor == Array);
- for (var prop in obj) {
- value = obj[prop];
- type = typeof(value);
- if (!isArray && (type == "function" || value === undefined)) {
- value = '';
- type = 'string';
- }
- if (type == "string") {
- value = quoteString(value);
- } else if (type == "object" && value !== null) {
- value = this.parseObjectToJSON(value);
- }
- if(type != "function" && value !== undefined) {
- json.push((isArray ? "" : '"' + prop + '":') + String(value));
- }
- }
- return (isArray ? "[" : "{") + String(json) + (isArray ? "]" : "}");
- }
- };
- /**
- * Remove class do objeto DOM
- * @author Ivanildo de Castro <ivanildocastro@neemu.com>
- * @since 2.0.0
- * @param {Object} element
- * @param {String} className
- * @return {Void}
- */
- cm.removeClass = function(element, className){
- var array = (typeof element === 'object' && element.length)?element:[element];
- for(var i = 0; i < array.length ; i++){
- var c = array[i].className + '';
- array[i].className = c.replace(new RegExp('\s*'+className+'\s*','gi'), '').trim();
- }
- };
- /**
- * Defines the sku availability from value
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {Boolean|Integer|String} value
- * @return {Boolean}
- */
- cm.processAvailability = function(value) {
- var availability = false;
- switch (typeof(value)) {
- case "string" :
- if (!isNaN(value) && (parseInt(value) > 0)) {
- availability = true;
- } else if (value.toLowerCase() === "true") {
- availability = true;
- }
- break;
- case "number" :
- if (value > 0) {
- availability = true;
- }
- break;
- case "boolean" :
- availability = value;
- break;
- }
- return (availability)
- ? 1
- : 0;
- };
- cm.querySelectorAll = (function(){
- function isIE(v){
- var t = new RegExp('msie[ ]+'+v);
- return t.test(navigator.userAgent.toLowerCase());
- }
- function toArray(o){
- if(o.length){
- var
- oo = [],
- i;
- for(i=0;i<o.length;i++){
- oo.push(o[i]);
- }
- return oo;
- }
- return [];
- }
- /**
- * Classe de obter o elemento
- * @author ivanildo de castro
- */
- function QuerySelectorAll(){
- }
- var q = QuerySelectorAll.prototype;
- /**
- * Obtem o elemento pelo seletor
- * @param {String} selector
- * @param {Object} parent[optional]
- * @return {Array}
- */
- q.get = function(selector, parent){
- var elements = [];
- if(typeof selector === 'string' && selector.trim().length){
- selector = this.checkSelector(selector);
- var lengthi = selector.length, i, j, nElements;
- if(lengthi){
- elements = [(parent || document)];
- for(i = 0;i < lengthi;i++){
- nElements = [];
- for(j = 0;j < elements.length;j++){
- nElements = nElements.concat(this.getBy(elements[j], selector[i]));
- }
- elements = nElements;
- if(elements.length === 0){
- break;
- }
- }
- }
- }
- return elements;
- };
- /**
- * Verifica o selector e retorna o array com o selector no formato
- * @param {String} selector
- * @return {Array}
- */
- q.checkSelector = function(selector){
- return selector.replace(/(\[[^\[\]]*\])/g, function($1){
- return $1.replace(/\s+/g,'');
- }).replace(/\s*\>\s*/g, ' >').match(/[^ ]+/g);
- };
- /**
- * Obtem o elemento pelo seu tipo
- * @param {Object} parent
- * @param {String} selector
- * @return {Array}
- */
- q.getBy = function(parent, selector){
- if(selector[0] === '>'){
- return this.getByChild(parent, selector.substring(1));
- }
- var
- type = selector[0],
- subSelector = this.getSubSelector(selector),
- elements = [];
- selector = subSelector[0].substring(1);
- subSelector = subSelector.slice(1);
- if(type === '#'){
- elements = this.getById(parent, selector, subSelector);
- }else if(type === '.'){
- elements = this.getByClass(parent, selector, subSelector);
- }else if(type === '['){
- elements = this.getByAttr(parent, '['+selector, subSelector);
- }else{
- elements = this.getByTag(parent, type+selector, subSelector);
- }
- return elements
- };
- /**
- * Obtem o elemento pelo ID
- * @param {Object} parent
- * @param {String} selector
- * @param {Array} subSelector
- * @return {Array}
- */
- q.getById = function(parent, selector, subSelector){
- subSelector = (subSelector || []);
- subSelector.unshift('#'+selector);
- return this.checkElementIsValid(
- toArray(parent.getElementsByTagName('*')),
- subSelector
- );
- };
- /**
- * Obtem o elemento pela CLASSE
- * @param {Object} parent
- * @param {String} selector
- * @param {Array} subSelector
- * @return {Array}
- */
- q.getByClass = function(parent, selector, subSelector){
- var elements = toArray(parent.getElementsByClassName(selector));
- if(subSelector && subSelector.length){
- elements = this.checkElementIsValid(elements, subSelector);
- }
- return elements;
- };
- /**
- * Obtem o elemento pelo ATRIBUTO
- * @param {Object} parent
- * @param {String} selector
- * @param {Array} subSelector
- * @return {Array}
- */
- q.getByAttr = function(parent, selector, subSelector){
- var
- i,
- elements = toArray(parent.getElementsByTagName('*'))
- elAttr = [];
- for(i=0;i<elements.length;i++){
- if(this.checkElementHasAttribute(elements[i], selector)){
- elAttr.push(elements[i]);
- }
- }
- elements = elAttr;
- if(subSelector && subSelector.length){
- elements = this.checkElementIsValid(elements, subSelector);
- }
- return elements;
- };
- /**
- * Obtem o elemento pela TAG
- * @param {Object} parent
- * @param {String} selector
- * @param {Array} subSelector
- * @return {Array}
- */
- q.getByTag = function(parent, selector, subSelector){
- var elements = toArray(parent.getElementsByTagName(selector));
- if(subSelector && subSelector.length){
- elements = this.checkElementIsValid(elements, subSelector);
- }
- return elements;
- };
- /**
- * Obtem o elemento filho
- * @param {Object} parent
- * @param {String} selector
- */
- q.getByChild = function(parent, selector){
- return this.checkElementIsValid(
- toArray(parent.childNodes),
- this.getSubSelector(selector)
- );
- };
- /**
- * Verifica se são elementos válidos
- * @param {Array} elements
- * @param {Array} selector
- * @return {Array}
- */
- q.checkElementIsValid = function(elements, selector){
- var nElements = [], element;
- for(var i = 0;i < elements.length ;i++){
- element = elements[i];
- if(element.nodeType === 1 && this.checkSubSelector(element, selector)){
- nElements.push(element);
- }
- }
- return nElements;
- };
- /**
- * Check for element if sub selector is valid
- * @param {Object} element
- * @param {Array} selector
- * @return {Boolean}
- */
- q.checkSubSelector = function(element, selector){
- var found = true, i, subSelector, type, tester;
- for(i=0;i<selector.length;i++){
- subSelector = selector[i];
- type = subSelector[0];
- tester = new RegExp('\\b'+subSelector.substring(1)+'\\b', 'gi');
- if(
- (type === '.' && !tester.test(element.className)) ||//class
- (type === '#' && !tester.test(element.id)) ||//id
- (type === '[' && !this.checkElementHasAttribute(element, subSelector)) ||//attriute
- (['.', '#', '['].indexOf(type) === -1 && element.nodeName !== subSelector.toUpperCase())//tag
- ){
- found = false;
- }
- }
- return found;
- };
- /**
- * Verifica se tem o atributo no elemento e se o valor confere
- * @param {Object} element
- * @param {String} attribute
- * @return boolean
- */
- q.checkElementHasAttribute = function(element, attribute){
- var
- attrs = attribute.match(/\w+(\=[\'\"]?[^\'\"\]\[]+[\'\"]?)?/gi),
- attr, value, attrCompare, valueCompare,found = true;
- if(!attrs){
- return false;
- }
- for(i=0;i<attrs.length;i++){
- attr = attrs[i].split('=');
- attrCompare = attr[0];
- valueCompare = (attr[1] || '').replace(/[\'\"\s]/g, '');
- value = (element.getAttribute(attrCompare) || '').trim();
- if(!valueCompare){
- if(!element.hasAttribute(attrCompare)){
- found = false;
- }
- }else if(!(new RegExp('\\b'+valueCompare+'\\b', 'gi')).test(value)){
- found = false;
- }
- }
- return found;
- };
- /**
- * Obtem os seletores usados no get
- * @param {String} selector
- * @return {Array}
- */
- q.getSubSelector = function(selector){
- return selector.match(/(\#|\.|[A-z]?)[\w\-]+|\[[^\[\]]*\]/gi);
- };
- q = new QuerySelectorAll();
- return q.get.bind(q);
- })()
- ;
- /**
- * Generate a random value by user agent, referrer, cookie and native
- * javascript method (Math.random())
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @since 1.0.0
- * @return {Number}
- */
- cm.random = function() {
- var value;
- value = this.parseStringToNumber(navigator.userAgent)
- + this.parseStringToNumber(document.referrer)
- + this.parseStringToNumber(document.cookie.substr(0, 100))
- + parseInt(Math.random() * 1e6);
- return value % Math.pow(10, 12);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @version 2.1.13
- * @param {Number} min
- * @param {Number} max
- * @return {Number}
- */
- cm.randomBetween = function(min, max) {
- return Math.floor(Math.random() * (max - min + 1)) + min;
- };;
- /**
- * Remove a HTML element
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {HTMLElement} element
- * @return {Void}
- */
- cm.removeElement = function(element) {
- if (element) {
- element.parentNode.removeChild(element);
- }
- };
- /**
- * Encode a value for base 36
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {String} value
- * @return {String}
- */
- cm.base36encode = function(value) {
- var nvalue = "",
- modvalue,
- map = [
- "0", "1", "2", "3", "4", "5", "6", "7", "8",
- "9", "A", "B", "C", "D", "E", "F", "G", "H",
- "I", "J", "K", "L", "M", "N", "O", "P", "Q",
- "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
- ];
- while (value > 0) {
- modvalue = value % 36;
- value = Math.floor(value / 36);
- nvalue = map[modvalue] + nvalue;
- }
- return nvalue;
- };
- // discuss at: http://phpjs.org/functions/base64_decode/
- // original by: Tyler Akins (http://rumkin.com)
- // improved by: Thunder.m
- // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // input by: Aman Gupta
- // input by: Brett Zamir (http://brett-zamir.me)
- // bugfixed by: Onno Marsman
- // bugfixed by: Pellentesque Malesuada
- // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
- // returns 1: 'Kevin van Zonneveld'
- // example 2: base64_decode('YQ===');
- // returns 2: 'a'
- // example 3: base64_decode('4pyTIMOgIGxhIG1vZGU=');
- // returns 3: '✓ à la mode'
- cm.base64Decode = function(data) {
- var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
- var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
- ac = 0,
- dec = '',
- tmp_arr = [];
- if (!data) {
- return data;
- }
- data += '';
- do {
- // unpack four hexets into three octets using index points in b64
- h1 = b64.indexOf(data.charAt(i++));
- h2 = b64.indexOf(data.charAt(i++));
- h3 = b64.indexOf(data.charAt(i++));
- h4 = b64.indexOf(data.charAt(i++));
- bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
- o1 = bits >> 16 & 0xff;
- o2 = bits >> 8 & 0xff;
- o3 = bits & 0xff;
- if (h3 == 64) {
- tmp_arr[ac++] = String.fromCharCode(o1);
- } else if (h4 == 64) {
- tmp_arr[ac++] = String.fromCharCode(o1, o2);
- } else {
- tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
- }
- } while (i < data.length);
- dec = tmp_arr.join('');
- return decodeURIComponent(escape(dec.replace(/\0+$/, '')));
- };
- // discuss at: http://phpjs.org/functions/base64_encode/
- // original by: Tyler Akins (http://rumkin.com)
- // improved by: Bayron Guevara
- // improved by: Thunder.m
- // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // improved by: Rafał Kukawski (http://kukawski.pl)
- // bugfixed by: Pellentesque Malesuada
- // example 1: base64_encode('Kevin van Zonneveld');
- // returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
- // example 2: base64_encode('a');
- // returns 2: 'YQ=='
- // example 3: base64_encode('✓ à la mode');
- // returns 3: '4pyTIMOgIGxhIG1vZGU='
- cm.base64Encode = function(data) {
- var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
- var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
- ac = 0,
- enc = '',
- tmp_arr = [];
- if (!data) {
- return data;
- }
- data = unescape(encodeURIComponent(data));
- do {
- // pack three octets into four hexets
- o1 = data.charCodeAt(i++);
- o2 = data.charCodeAt(i++);
- o3 = data.charCodeAt(i++);
- bits = o1 << 16 | o2 << 8 | o3;
- h1 = bits >> 18 & 0x3f;
- h2 = bits >> 12 & 0x3f;
- h3 = bits >> 6 & 0x3f;
- h4 = bits & 0x3f;
- // use hexets to index into b64, and append result to encoded string
- tmp_arr[ac++] = b64.charAt(h1)
- + b64.charAt(h2)
- + b64.charAt(h3)
- + b64.charAt(h4);
- } while (i < data.length);
- enc = tmp_arr.join('');
- var r = data.length % 3;
- return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
- };
- /**
- * Decodes a URL, using the methods decodeURIComponent() and unescape()
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @since 1.0.0
- * @param {String} url
- * @return {String}
- */
- cm.decodeUrl = function(url) {
- var durl;
- try {
- durl = decodeURIComponent(decodeURI(url.replace(/\+/g, '%20')));
- } catch(e) {
- durl = unescape(url);
- }
- return durl;
- };
- /**
- * Get current url
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @return {String}
- */
- cm.getUrl = function(){
- return this.decodeUrl(window.location.href);
- };
- /**
- * Get a parameter value by your name
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {String} param
- * @param {String} url
- * @return {String}
- */
- cm.getUrlParamValue = function(param, url) {
- if (url === undefined) {
- url = this.decodeUrl(window.location.href);
- }
- param = param.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
- var match = url.match('[?&]' + param + '=([^&]*)');
- return match ? match[1] : null;
- };
- /**
- * Get all the url parameters (by query string)
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {String} value
- * @return {Object}
- */
- cm.getUrlVars = function(value) {
- var vars = {},
- url = (value && typeof(value) === "string")
- ? encodeURI(value)
- : this.decodeUrl(window.location.href);
- var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
- var keyEncode = decodeURI(key);
- var valueEncode = decodeURI(value);
- vars[keyEncode] = valueEncode;
- });
- return vars;
- };
- /**
- * Turn a string to the integer value
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @since 1.0.0
- * @param {String} value [description]
- * @return {Number}
- */
- cm.parseStringToNumber = function(value) {
- var number = 0;
- if (typeof(value) == "string") {
- var vLength = value.length;
- for (var i = 0, len = vLength; i < len; i++) {
- number += value.charCodeAt(i);
- }
- }
- return number;
- };
- /**
- * Remove accents from a string
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {String} str
- * @return {String}
- */
- cm.removeAccents = function(str) {
- var mapaAcentosHex = {
- a : /[\xE0-\xE6]/g,
- e : /[\xE8-\xEB]/g,
- i : /[\xEC-\xEF]/g,
- o : /[\xF2-\xF6]/g,
- u : /[\xF9-\xFC]/g,
- c : /\xE7/g,
- n : /\xF1/g
- };
- for (var letra in mapaAcentosHex) {
- var expressaoRegular = mapaAcentosHex[letra];
- str = str.replace(expressaoRegular, letra);
- }
- return str;
- };
- /**
- * Remove HTML tags from a string
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @since 1.0.0
- * @param {String} value
- * @return {String}
- */
- cm.removeHtmlTag = function(value) {
- return value.replace(/<(?:.|\s)*?>/g, '');
- };
- /**
- * Remove espaços em branco desnecessário
- * @author Ivanildo de Castro <ivanildocastro@neemu.com>
- * @since 1.0.0
- * @param {String} text
- * @return {String}
- */
- cm.removeWhiteSpaces = function(text){
- if(typeof text === 'string'){
- return text.trim().replace(/\s+/g, ' ');
- }
- return text;
- };
- /**
- * Checks is exists some occurrence of a string another string
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {String} haystack
- * @param {String} needle
- * @return {Boolean}
- */
- cm.strstr = function(haystack, needle) {
- return (needle && haystack.indexOf(needle) != -1)
- ? true
- : false;
- };
- // discuss at: http://phpjs.org/functions/utf8_encode/
- // original by: Webtoolkit.info (http://www.webtoolkit.info/)
- // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // improved by: sowberry
- // improved by: Jack
- // improved by: Yves Sucaet
- // improved by: kirilloid
- // bugfixed by: Onno Marsman
- // bugfixed by: Onno Marsman
- // bugfixed by: Ulrich
- // bugfixed by: Rafal Kukawski
- // bugfixed by: kirilloid
- // example 1: utf8_encode('Kevin van Zonneveld');
- // returns 1: 'Kevin van Zonneveld'
- cm.utf8Encode = function(argString) {
- if (argString === null || typeof argString === 'undefined') {
- return '';
- }
- var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
- var utftext = '',
- start, end, stringl = 0;
- start = end = 0;
- stringl = string.length;
- for (var n = 0; n < stringl; n++) {
- var c1 = string.charCodeAt(n);
- var enc = null;
- if (c1 < 128) {
- end++;
- } else if (c1 > 127 && c1 < 2048) {
- enc = String.fromCharCode(
- (c1 >> 6) | 192, (c1 & 63) | 128
- );
- } else if ((c1 & 0xF800) != 0xD800) {
- enc = String.fromCharCode(
- (c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
- );
- } else { // surrogate pairs
- if ((c1 & 0xFC00) != 0xD800) {
- throw new RangeError('Unmatched trail surrogate at ' + n);
- }
- var c2 = string.charCodeAt(++n);
- if ((c2 & 0xFC00) != 0xDC00) {
- throw new RangeError('Unmatched lead surrogate at ' + (n - 1));
- }
- c1 = ((c1 & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000;
- enc = String.fromCharCode(
- (c1 >> 18) | 240, ((c1 >> 12) & 63) | 128, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
- );
- }
- if (enc !== null) {
- if (end > start) {
- utftext += string.slice(start, end);
- }
- utftext += enc;
- start = end = n + 1;
- }
- }
- if (end > start) {
- utftext += string.slice(start, stringl);
- }
- return utftext;
- };
- /**
- * Checks if the current user agent is a search bot
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @return {Boolean}
- */
- cm.userAgentIsBot = function() {
- var userAgent = navigator.userAgent;
- return (
- this.strstr(userAgent, "Googlebot")
- || this.strstr(userAgent, "BingPreview")
- )
- ? true
- : false;
- };
- window._nm = (window._nm || {});
- window._nm.commons = new Commons();
- })(window, document);
- _nm.VERSION = "2.13.9";
- _nm.url = window.location.href;
- _nm.isMobile = false;
- _nm.callbacks = {
- beforeLogRequests: []
- };
- window.neemuCallback = function(data){}
- /**
- * Copyright (c) 2015 - Neemu Serviços em Tecnologia da Informação S.A
- *
- * LICENSE: This software is the confidential and proprietary information of
- * Neemu S.A ("Confidential Information"). You shall not disclose such
- * Confidential Information and shall use it only in accordance with the terms
- * of the license agreement you entered into with Neemu S.A.
- *
- * Module which implements some prototype functions, for given
- * crossbrowser support
- *
- * @author Javier Zambrano <javier@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @version 1.0.0
- */
- if (!String.prototype.trim) {
- /**
- * Implements trim function, to remove blank spaces around the strings
- *
- * @author Javier Zambrano <javier@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @return {String}
- */
- String.prototype.trim = function () {
- return this.replace(/^\s+/,'').replace(/\s+$/, '');
- };
- }
- if(!Array.prototype.slice) {
- /**
- * Implements a function to remove a specific position from a array
- *
- * @author Javier Zambrano <javier@neemu.com>
- * @since 1.0.0
- * @param {Integer} begin
- * @param {Integer} end
- * @return {Array}
- */
- Array.prototype.slice = function(begin, end) {
- // IE < 9 gets unhappy with an undefined end argument
- end = (typeof end !== 'undefined')
- ? end
- : this.length;
- // For native Array objects, we use the native slice function
- if (Object.prototype.toString.call(this) === "[object Array]") {
- return Array.prototype.slice.call(this, begin, end);
- }
- // For array like object we handle it ourselves.
- var i, cloned = [],
- size, len = this.length;
- // Handle negative value for "begin"
- var start = begin || 0;
- start = (start >= 0)
- ? start
- : len + start;
- // Handle negative value for "end"
- var upTo = (end)
- ? end
- : len;
- if (end < 0) {
- upTo = len + end;
- }
- // Actual expected size of the slice
- size = upTo - start;
- if (size > 0) {
- cloned = new Array(size);
- if (this.charAt) {
- for (i = 0; i < size; i++) {
- cloned[i] = this.charAt(start + i);
- }
- } else {
- for (i = 0; i < size; i++) {
- cloned[i] = this[start + i];
- }
- }
- }
- return cloned;
- };
- }
- if (!Object.keys) {
- /**
- * Returns only keys from a array
- *
- * @since 2.0.0
- * @{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys}
- * @return {Array}
- */
- Object.keys = (function() {
- "use strict";
- var hasOwnProperty = Object.prototype.hasOwnProperty,
- hasDontEnumBug = !({ toString: null }).propertyIsEnumerable("toString"),
- dontEnums = [
- "toString",
- "toLocaleString",
- "valueOf",
- "hasOwnProperty",
- "isPrototypeOf",
- "propertyIsEnumerable",
- "constructor"
- ],
- dontEnumsLength = dontEnums.length;
- return function(obj) {
- if (typeof obj !== "object" && (typeof obj !== "function" || obj === null)) {
- throw new TypeError("Object.keys called on non-object");
- }
- var result = [], prop, i;
- for (prop in obj) {
- if (hasOwnProperty.call(obj, prop)) {
- result.push(prop);
- }
- }
- if (hasDontEnumBug) {
- for (i = 0; i < dontEnumsLength; i++) {
- if (hasOwnProperty.call(obj, dontEnums[i])) {
- result.push(dontEnums[i]);
- }
- }
- }
- return result;
- };
- }());
- }
- /**
- * Copyright (c) 2015 - Neemu Serviços em Tecnologia da Informação S.A
- *
- * LICENSE: This software is the confidential and proprietary information of
- * Neemu S.A ("Confidential Information"). You shall not disclose such
- * Confidential Information and shall use it only in accordance with the terms
- * of the license agreement you entered into with Neemu S.A.
- */
- /**
- * Module implemented to extract the page information, process this
- * data and send this to log service
- *
- * @author Javier Zambrano <javier@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @version 2.0.0
- * @param {Object} window
- * @param {Object} document
- * @param {undefined} undefined
- * @return {Object}
- */
- _nm.extraction = (function (window, document, undefined) {
- /**
- * Constante to define the page type
- *
- * @since 2.0.0
- * @type {String}
- */
- var PAGE_CHECKOUT_CONFIRMATION = "checkoutConfirmacao",
- PAGE_NEEMU_PAGES_INDEX = "neemu-pages-index",
- PAGE_ADD_TO_CART = "adicionarcarrinho",
- PAGE_DEPARTMENT = "departamento",
- PAGE_NEEMU_PAGES = "neemupages",
- PAGE_NAVIGATION = "navigation",
- PAGE_COMPARISON = "comparador",
- PAGE_CHECKOUT = "checkout",
- PAGE_CHECKOUT_CART = "carrinho",
- PAGE_REC_PRINT = "recprint",
- PAGE_PRODUCT = "produto",
- PAGE_SEARCH = "busca",
- PAGE_LOGIN = "login",
- PAGE_GENERAL = "geral",
- PAGE_HOME = "home",
- PAGE_NOT_FOUND = "404",
- PAGE_HOTSITE = "hotsite",
- PAGE_WISHLIST = "wishlist",
- PAGE_COLLECTION_GERAL = 'colGeral',
- PAGE_COLLECTION_HOME = 'colHome',
- PAGE_COLLECTION_SEARCH = 'colSearch',
- PAGE_COLLECTION_DETAILS = 'colDetails',
- PAGE_COLLECTION_AUTHOR = 'colAuthor',
- PAGE_COLLECTION_REGISTER = 'colRegister',
- PAGE_COLLECTION_RELATED = 'colRelated',
- PAGE_COLLECTION_TAG = 'colTag';
- /**
- * @since 2.0.0
- * @type {Object}
- */
- var storeConfig = {};
- /**
- * @since 2.0.0
- * @type {Object}
- */
- var finalJson = {};
- /**
- * @since 2.0.0
- * @type {Object}
- */
- var info = {
- general : {
- pgType : PAGE_GENERAL
- },
- department : {
- cId : "",
- tree : []
- },
- checkoutConfirmation : {},
- checkoutInformation : {},
- autocomplete : {},
- quickFilter : {},
- navigation : {},
- product : {},
- search : {},
- hotsite : {},
- user : {},
- rec : {},
- filters : [],
- skuList : [],
- skuListFinal : [],
- wishlist : {}
- };
- /**
- * @since 2.0.0
- * @type {String}
- */
- var sid = "";
- /**
- * @since 2.0.0
- * @type {String}
- */
- var agent = "";
- /**
- * @since 2.0.0
- * @type {String}
- */
- var protocol = "";
- /**
- * @since 2.0.0
- * @type {String}
- */
- var logServer = "";
- /**
- * @since 2.0.0
- * @type {Boolean}
- */
- var pauseExtraction = false;
- /**
- * @since 2.0.0
- * @type {Boolean}
- */
- var loadInitRecommendation = false;
- /**
- * @since 2.0.0
- * @type {Object}
- */
- var $_ME;
- /************ [ METHODS FROM LOAD COOKIE INFORMATIONS - BEGIN ] ***********/
- var setMe = function(o) {
- $_ME = o;
- };
- var loadDepartmentList = function(value, cname) {
- cname = cname || "department_list";
- value = value || $_ME.info.department.cId;
- if (value) {
- value = value.toString();
- }
- if (value && (typeof(value) !== "string" || value.trim() !== "")) {
- var departmentList = _nm.commons.getCookie(cname),
- departmentOld = departmentList, // armazenando para tratamento do valor atual
- departmentValue = value;
- // no começo da string, sempre o produto atual está no inÃcio
- departmentList = departmentValue;
- if (departmentOld !== undefined) {
- var departmentListSplit = departmentOld.split("|");
- for(var i = 0, len = departmentListSplit.length, lim = 10, qtt = 1; i < len; i++) {
- /**
- * não pode adicionar a query atual novamente na lista e
- * nem os valores undefined que estão guardados
- */
- if (
- departmentListSplit[i] != departmentValue
- && departmentListSplit[i] !== undefined
- && departmentListSplit[i].trim() !== ""
- && departmentListSplit[i].indexOf("%")== -1
- ) {
- departmentList += "|" + departmentListSplit[i];
- qtt++;
- if (qtt >= lim) {
- break;
- }
- }
- }
- }
- _nm.commons.setCookie(
- cname,
- departmentList,
- 43200, // 30 dias
- '/',
- '.' + _nm.conf.store.host
- );
- }
- };
- var loadQueryList = function(value, cname) {
- cname = cname || "query_list";
- value = value || $_ME.info.search.q;
- // preenchimento do query_list
- if (typeof value == "string" && value.trim() !== "")
- {
- var queryValue = _nm.commons.removeAccents(value).toLowerCase(),
- queryList = _nm.commons.getCookie(cname),
- queryListOld = queryList, // armazenando para tratamento do valor atual
- lim = 10; // limite de valores no cookie
- if (_nm.conf.store.host === "mobly.com.br") {
- lim = 20;
- }
- // limitando em 20 caracteres
- if (queryValue.length > 20) {
- queryValue = "";
- }
- if (queryListOld !== undefined && queryValue.trim() !== "") {
- var queryListSplit = queryListOld.split("|");
- // no começo da string, sempre o produto atual está no inÃcio
- queryList = queryValue;
- for(var i = 0, len = queryListSplit.length, qtt = 1; i < len; i++) {
- queryListSplit[i] = _nm.commons.removeAccents(queryListSplit[i]);
- // limitando em 20 caracteres
- if (queryListSplit[i].length > 20) {
- queryListSplit[i] = "";
- }
- // não pode adicionar a query atual novamente na lista e nem os valores undefined que estão guardados
- if (
- queryListSplit[i] !== queryValue
- && queryListSplit[i] !== undefined
- && queryListSplit[i].trim() !== ""
- && queryListSplit[i].indexOf("%") == -1
- ) {
- queryList += "|" + queryListSplit[i];
- qtt++;
- if (qtt >= lim) {
- break;
- }
- }
- }
- }
- if (!queryList) {
- queryList = queryValue;
- }
- // novo valor do query_list calculado
- _nm.commons.setCookie(
- cname,
- queryList,
- 43200, // 30 dias
- '/',
- '.' + _nm.conf.store.host
- );
- }
- };
- var loadClickList = function(value, cname) {
- cname = cname || "click_list";
- value = value || $_ME.info.product.id;
- if(value) {
- value = value.toString();
- }
- // preenchimento do click_list
- if (typeof(value) === "string" && value.trim() !== "") {
- var clickValue = _nm.commons.removeAccents(value);
- var clickList = _nm.commons.getCookie(cname);
- var clickListOld = clickList; // armanazenando para tratamento do valor atual
- var lim = 10; // limite de valores no cookie
- if(_nm.conf.store.host == "mobly.com.br") {
- lim = 20;
- }
- // limitando em 20 caracteres
- if(clickValue.length > 20) {
- clickValue = "";
- }
- if (clickListOld !== undefined && clickValue.trim() !== "") {
- var clickListSplit = clickListOld.split("|");
- // no começo da string, sempre o produto atual está no inÃcio
- clickList = clickValue;
- for(var i = 0, len = clickListSplit.length, qtt = 1; i < len; i++) {
- clickListSplit[i] = _nm.commons.removeAccents(clickListSplit[i]);
- // limitando em 20 caracteres
- if(clickListSplit[i].length > 20) {
- clickListSplit[i] = "";
- }
- /**
- * não pode adicionar a click atual novamente na lista e
- * nem os valores undefined que estão guardados
- */
- if(
- clickListSplit[i] != clickValue
- && clickListSplit[i] != "undefined"
- && clickListSplit[i].trim() != ""
- && clickListSplit[i].indexOf("%") == -1
- ) {
- clickList += "|" + clickListSplit[i];
- qtt++;
- if(qtt >= lim) {
- break;
- }
- }
- }
- }
- if(!clickList) {
- clickList = clickValue;
- }
- // novo valor do click_list calculado
- _nm.commons.setCookie(
- cname,
- clickList,
- 43200, // 30 dias
- '/',
- '.' + _nm.conf.store.host
- );
- }
- };
- var loadPurchaseList = function(values, cname) {
- cname = cname || "nm_purchase_list";
- values = values || $_ME.info.skuList;
- var purchaseList = _nm.commons.getCookie(cname);
- for(var j = 0, len_j = values.length; j < len_j; j++) {
- var value = values[j];
- value = (typeof(value) === "object")
- ? value.sku.toString()
- : value.toString();
- // preenchimento do nm_purchase_list
- if (typeof(value) === "string" && value.trim() !== "") {
- var purchaseValue = _nm.commons.removeAccents(value);
- var purchaseListOld = purchaseList; // armanazenando para tratamento do valor atual
- var lim = 10; // limite de valores no cookie
- // limitando em 20 caracteres
- if(purchaseValue.length > 20) {
- purchaseValue = "";
- }
- if (purchaseListOld !== undefined && purchaseValue.trim() !== "") {
- var purchaseListSplit = purchaseListOld.split('|');
- // no começo da string, sempre o produto atual está no inÃcio
- purchaseList = purchaseValue;
- for(var i = 0, len = purchaseListSplit.length, qtt = 1; i < len; i++) {
- purchaseListSplit[i] = _nm.commons.removeAccents(purchaseListSplit[i]);
- // limitando em 20 caracteres
- if(purchaseListSplit[i].length > 20) {
- purchaseListSplit[i] = "";
- }
- /**
- * não pode adicionar a purchase atual novamente na
- * lista e nem os valores undefined que estão guardados
- */
- if(
- purchaseListSplit[i] != purchaseValue
- && purchaseListSplit[i] != "undefined"
- && purchaseListSplit[i].trim() != ""
- && purchaseListSplit[i].indexOf("%") == -1
- ) {
- purchaseList += "|" + purchaseListSplit[i];
- qtt++;
- if(qtt >= lim) {
- break;
- }
- }
- }
- }
- if(!purchaseList) {
- purchaseList = purchaseValue;
- }
- }
- }
- // novo valor do purchase_list calculado
- _nm.commons.setCookie(
- cname,
- purchaseList,
- 43200, // 30 dias
- '/',
- '.' + _nm.conf.store.host
- );
- };
- /**
- * Pega o skuList do carrinho e cria um cookie dos produtos do carrinho
- * @return {Void}
- */
- var loadCartList = function(cname) {
- cname = cname || "cart_list";
- var cartList = "";
- if(Object.prototype.toString.call($_ME.info.skuList) === "[object Array]"){
- for(var cont = 0, tamanho = $_ME.info.skuList.length; cont < tamanho; cont++) {
- if(
- typeof($_ME.info.skuList[cont].id) === "string"
- && typeof($_ME.info.skuList[cont].sku) === "string"
- ) {
- if($_ME.info.skuList[cont].id !== $_ME.info.skuList[cont].sku) {
- cartList += $_ME.info.skuList[cont].id + ":" + $_ME.info.skuList[cont].sku;
- } else {
- cartList += $_ME.info.skuList[cont].id;
- }
- if(cont+1 != tamanho) {
- cartList += "|";
- }
- }
- }
- }
- _nm.commons.setCookie(
- cname,
- cartList,
- null,
- '/',
- '.' + _nm.conf.store.host
- );
- };
- /************ [ METHODS FROM LOAD COOKIE INFORMATIONS - END ] *************/
- /**
- * Correct common errors in emails
- * @since v2.8.4
- * @param {String} email E-mail to be correct
- * @return {String} Corrected e-mail
- */
- var correctEmail = function(email) {
- return email
- .replace("gmail.con", "gmail.com")
- .replace("com.bbr", "com.br");
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @version 2.1.0
- * @return {Void}
- */
- var initializeLogInformation = function() {
- $_ME.finalJson = {};
- // $_ME.info.skuList = [];
- // $_ME.info.skuListFinal = [];
- // $_ME.info.product.skus = [];
- // $_ME.info.search = {};
- _nm.callbacks = {
- beforeLogRequests: []
- };
- $_ME.info = {
- general : {
- pgType : PAGE_GENERAL
- },
- department : {
- cId : "",
- tree : []
- },
- checkoutConfirmation : {},
- checkoutInformation : {},
- autocomplete : {},
- quickFilter : {},
- navigation : {},
- product : {},
- search : {},
- hotsite : {},
- user : {},
- rec : {},
- filters : [],
- skuList : [],
- skuListFinal : [],
- wishlist : {}
- };
- };
- var parseIsPaused = function() {
- return $_ME.pauseExtraction;
- };
- /**
- * Sets flag value for pausing the parse process
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var pauseParse = function() {
- $_ME.pauseExtraction = true;
- };
- /**
- * Sets flag value for continue the parse process
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var continueParse = function() {
- $_ME.pauseExtraction = false;
- // continue the parse process
- generateLogInformation.call($_ME, {
- data: $_ME.info,
- callback: function(data) {
- send.call($_ME, getLogRequestUrl.call($_ME, data));
- }
- });
- };
- /**
- * Convert filters from intersect search version (using ids) to the
- * normal format (using strings)
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.12.5
- * @param {Object} searchInformation
- * @return {Void}
- */
- var convertSearchFilters = function(searchInformation) {
- var newFilters = [];
- var multipleValuesSeparator = "|";
- for (var nmA in searchInformation.filters) {
- var newObjFilter = {};
- for (var nmB in searchInformation.filters[nmA]) {
- if (typeof(searchInformation.filters[nmA][nmB]) !== "function") {
- var selectedValue = searchInformation.filters[nmA][nmB];
- // filtros contÃnuos
- var rangeSeparator = ":";
- if (_nm.commons.strstr(selectedValue, rangeSeparator)) {
- /**
- * mais de um filtro selecionado para o mesmo
- * atributo (range_filter[11]=67|234|22)
- */
- if (
- _nm.commons.strstr(
- selectedValue,
- multipleValuesSeparator
- )
- ) {
- var listValues = selectedValue.split(
- multipleValuesSeparator
- );
- var found = false;
- var valores = [];
- for (var i = 0; i < listValues.length; i++) {
- var valueParts = listValues[i].split(rangeSeparator);
- // intersect format
- if (valueParts.length === 3) {
- var allowedValues = window.nmFilterInfo[nmB].values[valueParts[2]];
- for (var j = 0; j < allowedValues.length; j++) {
- if (listValues[i] === allowedValues[j]) {
- valores.push(
- valueParts[0] + ":" + valueParts[1]
- );
- if (!found) {
- found = true;
- }
- }
- }
- }
- }
- if (found) {
- newObjFilter[window.nmFilterInfo[nmB].name] =
- valores.join("|");
- newFilters.push(newObjFilter);
- break;
- }
- }
- else {
- var valueParts = selectedValue.split(rangeSeparator);
- // intersect format
- if (valueParts.length === 3) {
- var allowedValues = window.nmFilterInfo[nmB].values[valueParts[2]];
- for (var i = 0; i < allowedValues.length; i++) {
- if (selectedValue === allowedValues[i]) {
- newObjFilter[window.nmFilterInfo[nmB].name] =
- valueParts[0] + ":" + valueParts[1];
- newFilters.push(newObjFilter);
- break;
- }
- }
- }
- // old search api version
- else {
- }
- }
- }
- else {
- /**
- * mais de um filtro selecionado para o mesmo
- * atributo (common_filter[11]=67|234|22)
- */
- if (
- _nm.commons.strstr(
- selectedValue,
- multipleValuesSeparator
- )
- ) {
- var listValues = selectedValue.split(
- multipleValuesSeparator
- );
- var found = false;
- var valores = [];
- for (var i = 0; i < listValues.length; i++) {
- if (
- window.nmFilterInfo.hasOwnProperty(nmB) &&
- window.nmFilterInfo[nmB].values.hasOwnProperty(
- listValues[i]
- )
- ) {
- valores.push(String(
- window.nmFilterInfo[nmB].values[listValues[i]]
- ));
- if (!found) {
- found = true;
- }
- }
- }
- if (found) {
- newObjFilter[window.nmFilterInfo[nmB].name] =
- valores.join("|");
- newFilters.push(newObjFilter);
- break;
- }
- }
- /**
- * apenas um filtro selecionado (common_filter[11]=67)
- */
- else {
- if (
- window.nmFilterInfo.hasOwnProperty(nmB) &&
- window.nmFilterInfo[nmB].values.hasOwnProperty(
- selectedValue
- )
- ) {
- newObjFilter[window.nmFilterInfo[nmB].name] = String(
- window.nmFilterInfo[nmB].values[selectedValue]
- );
- newFilters.push(newObjFilter);
- break;
- }
- }
- }
- }
- }
- }
- return newFilters;
- };
- /**
- * Checks if is necessary parser the object "_neemu" (neemu protocol)
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.13.4
- * @return {Boolean}
- */
- var neemuProtocolIsEnabled = function(window, storeConfig) {
- return (
- window._neemu !== undefined &&
- storeConfig.isNeemuProtocol !== false
- );
- };
- /**
- * Defines the informations which will be sent to log
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} opt
- * @return {Void}
- */
- var generateLogInformation = function (opt) {
- var win = window,
- queryString = win.location.search;
- // parse the "_neemu" object (neemu protocol)
- if (neemuProtocolIsEnabled(window, $_ME.storeConfig)) {
- parseApiObject();
- }
- // create recommendation areas
- if (
- $_ME.storeConfig.rec !== undefined
- && $_ME.storeConfig.rec.enable !== false
- && window.neemuPlugin.recommendation !== undefined
- && window.neemuPlugin.recommendation.pageType !== undefined
- ) {
- initRecommendation.call($_ME, neemuPlugin.recommendation.pageType);
- }
- /********************** [ GENERAL INFORMATION ] ***********************/
- /*
- var nmSid = (
- _nm.conf.preset !== undefined
- && _nm.commons.strstr(_nm.conf.preset, "chaordic")
- )
- ? _nm.commons.getCookie("chaordic_browserId")
- : $_ME.sid;
- */
- var extras = $_ME.info.general.extras || {};
- if(
- _nm.conf.preset !== undefined &&
- _nm.commons.strstr(_nm.conf.preset, "chaordic")
- ){
- extras["chaordic_browserId"] = _nm.commons.getCookie("chaordic_browserId");
- extras["chaordic_anonymousUserId"] = _nm.commons.getCookie("chaordic_anonymousUserId");
- extras["chaordic_session"] = _nm.commons.getCookie("chaordic_session");
- }
- $_ME.info.general.storeId = _nm.conf.store.id,
- $_ME.info.general.version = _nm.VERSION + "-" + _nm.buildDate,
- $_ME.info.general.chn = getChannel();
- $_ME.info.general.sid = $_ME.sid;//nmSid;
- $_ME.info.general.aid = window.nmExtractionAccessId || "";
- $_ME.info.general.agent = navigator.userAgent;
- $_ME.info.general.url = _nm.commons.getUrl();
- $_ME.info.general.referrer = _nm.commons.decodeUrl(document.referrer);
- $_ME.info.general.ts = Date.now ? Date.now() : (new Date()).getTime();
- $_ME.info.general.extras = extras;
- // verificando se o referrer tem o protocolo
- if($_ME.info.general.referrer.indexOf('http') != 0 && $_ME.info.general.referrer != '') {
- $_ME.info.general.referrer = 'http://' + $_ME.info.general.referrer;
- }
- /************************ [ USER INFORMATION ] ************************/
- // geolocation
- if ($_ME.info.user.geolocation !== undefined) {
- $_ME.info.general.uGeo = $_ME.info.user.geolocation;
- }
- // logged id
- if ($_ME.info.user.loggedId !== undefined) {
- $_ME.info.general.uId = $_ME.info.user.loggedId.toString();
- }
- // name
- if ($_ME.info.user.name !== undefined) {
- $_ME.info.general.uName = $_ME.info.user.name;
- }
- // email
- if (
- $_ME.info.user.email !== undefined
- && _nm.commons.isValidEmail($_ME.info.user.email)
- ) {
- $_ME.info.general.uEmail = correctEmail.call(
- this,
- $_ME.info.user.email
- );
- }
- // checks if user is not logged on store, but is logged on neemu cookie
- if (
- typeof($_ME.info.general.uName) === "undefined" &&
- typeof($_ME.info.general.uEmail) === "undefined" &&
- neemuUserIsLogged()
- ) {
- var cookieUser = getNeemuLoggedUser();
- if (cookieUser.name !== undefined) {
- $_ME.info.general.uName = cookieUser.name;
- }
- if (cookieUser.email !== undefined) {
- $_ME.info.general.uEmail = cookieUser.email;
- $_ME.info.general.uId = "neemu" + $_ME.info.general.uEmail;
- }
- }
- $_ME.finalJson.general = $_ME.info.general;
- // detect page type
- switch ($_ME.info.general.pgType) {
- case PAGE_DEPARTMENT :
- // checks whether it is necessary order the tree departments
- if (
- // check is has greater then one departament
- $_ME.info.department.tree.length > 1
- // checks if the tree department is disorderly
- && parseInt($_ME.info.department.tree[0].index) > parseInt($_ME.info.department.tree[1].index)
- ) {
- $_ME.info.department.tree.sort(_nm.commons.arraySortBy(
- "index", // field sort
- false // ascending
- ));
- }
- // processing category names
- var cNames = [];
- for (var i = 0; i < $_ME.info.department.tree.length; i++) {
- cNames.push($_ME.info.department.tree[i].name);
- }
- $_ME.info.department.tree = cNames;
- // checks if category id was informed
- if ($_ME.info.department.cId === "") {
- $_ME.info.department.cId = cNames.join(" | ");
- }
- $_ME.finalJson.info = $_ME.info.department;
- break;
- case PAGE_PRODUCT :
- /******************* [ PRODUCT INFORMATION ] ******************/
- $_ME.finalJson.info = $_ME.info.product;
- /********************* [ SKU INFORMATION ] ********************/
- if ($_ME.info.skuList) {
- // convert sku index to the count index
- for (var prop in $_ME.info.skuList) {
- if (typeof($_ME.info.skuList[prop]) === "object") {
- $_ME.info.skuListFinal.push($_ME.info.skuList[prop]);
- }
- }
- $_ME.info.product.skus = $_ME.info.skuListFinal;
- }
- /**************** [ AUTOCOMPLETE INFORMATION ] ****************/
- var acTypeClick = _nm.commons.getUrlParamValue("typeclick");
- if (acTypeClick !== null) {
- $_ME.finalJson.ac = {
- type : 3,
- prefix : _nm.commons.getUrlParamValue("p"),
- pos : _nm.commons.getUrlParamValue("ac_pos"),
- rank : parseInt(_nm.commons.getUrlParamValue("ranking"))
- };
- }
- var origin = _nm.commons.getUrlParamValue("nm_origem");
- if (origin !== null) {
- /*************** [ NEEMU MAIL INFORMATION ] ***************/
- /**
- * TODO: o JSON do Neemu Mail será implementado depois,
- * a pedido do Cristian Rossi
- */
- /*if (_nm.commons.strstr(origin, "neemumail")) {
- finalJson.neemumailInformation = {
- campaign : origin.replace("neemumail_", ""),
- campaignId : _nm.commons.getUrlParamValue("nm_campanha"),
- ranking : _nm.commons.getUrlParamValue("nm_ranking_rec")
- };
- }*/
- /************* [ RECOMMENDATION INFORMATION ] *************/
- if (_nm.commons.strstr(origin, "rec")) {
- // get ranking
- var recRanking =
- _nm.commons.getUrlParamValue("nm_ranking_rec");
- var recList = {
- pgName : _nm.commons.getUrlParamValue("nm_rec_page") || "",
- scName : _nm.commons.getUrlParamValue("nm_rec_showcase") || "",
- scId : _nm.commons.getUrlParamValue("nm_rec_vid") || "",
- rank : recRanking,
- id : _nm.commons.getUrlParamValue("nm_rec_id") || "",
- scenario : _nm.commons.getUrlParamValue("nm_rec_scenario") || "",
- seg : _nm.commons.getUrlParamValue("nm_rec_segment") || "",
- cName : _nm.commons.getUrlParamValue("nm_rec_category") || "",
- chn : $_ME.info.general.chn
- };
- if(typeof recList.rank == 'string') {
- recList.rank = parseInt(recList.rank);
- }
- if(typeof recList.scId == 'string') {
- recList.scId = parseInt(recList.scId);
- }
- recList.tree = [
- [
- recList.chn,
- recList.scenario,
- recList.seg,
- recList.pgName,
- recList.cName,
- recList.scName,
- recList.scId
- ],
- [
- recList.chn,
- recList.scenario,
- recList.seg,
- recList.pgName,
- recList.cName,
- recList.scId,
- recList.scName
- ],
- [
- recList.chn,
- recList.scenario,
- recList.pgName,
- recList.scName,
- recList.cName,
- recList.seg,
- recList.scId
- ]
- ];
- // prime offer
- var primeOffer = _nm.commons.getUrlParamValue("nm_primeoffer");
- if (primeOffer!== null) {
- recList.primeoffer = primeOffer;
- }
- $_ME.finalJson.rec = {
- list : [recList]
- };
- }
- }
- break;
- case PAGE_CHECKOUT :
- $_ME.finalJson.info = $_ME.info.checkoutInformation;
- break;
- case PAGE_CHECKOUT_CART :
- $_ME.finalJson.info = {
- skus : $_ME.info.skuList
- };
- // sets the sku list for the recommendation
- if(
- $_ME.info.skuList
- && neemuPlugin.recommendation !== undefined
- && neemuPlugin.recommendation.skuRecommendation === undefined
- ) {
- neemuPlugin.recommendation.skuRecommendation = { id: '', sku: '' };
- for(var i = 0; i < $_ME.info.skuList.length; i++) {
- neemuPlugin.recommendation.skuRecommendation.id += $_ME.info.skuList[i].id + ';';
- neemuPlugin.recommendation.skuRecommendation.sku += $_ME.info.skuList[i].sku + ';';
- }
- }
- break;
- case PAGE_CHECKOUT_CONFIRMATION :
- $_ME.finalJson.info = $_ME.info.checkoutConfirmation;
- $_ME.finalJson.info.skus = $_ME.info.skuList;
- break;
- case PAGE_COMPARISON :
- $_ME.finalJson.comparisonInformation = {
- skuList : $_ME.info.skuList
- };
- break;
- case PAGE_NAVIGATION :
- $_ME.finalJson.info = $_ME.info.navigation;
- $_ME.finalJson.info.pIds = $_ME.info.search.pIds;
- break;
- case PAGE_HOTSITE :
- $_ME.finalJson.info = $_ME.info.hotsite;
- break;
- case PAGE_NEEMU_PAGES_INDEX :
- case PAGE_NEEMU_PAGES :
- case PAGE_SEARCH :
- if (
- $_ME.info.search.filters !== undefined &&
- $_ME.info.general.apiSearchVersion !== undefined
- ) {
- var newFilters = convertSearchFilters($_ME.info.search);
- delete $_ME.info.search.filters;
- $_ME.info.search.filters = newFilters;
- }
- if ($_ME.info.autocomplete.type !== undefined) {
- $_ME.finalJson.ac = $_ME.info.autocomplete;
- }
- if (!_nm.commons.objectIsEmpty($_ME.info.quickFilter)) {
- $_ME.finalJson.qf = $_ME.info.quickFilter;
- }
- $_ME.finalJson.info = $_ME.info.search;
- break;
- case PAGE_WISHLIST :
- $_ME.finalJson.info = $_ME.info.wishlist;
- case PAGE_COLLECTION_HOME:
- case PAGE_COLLECTION_SEARCH:
- case PAGE_COLLECTION_DETAILS:
- case PAGE_COLLECTION_AUTHOR:
- case PAGE_COLLECTION_REGISTER:
- case PAGE_COLLECTION_RELATED:
- case PAGE_COLLECTION_TAG:
- this.generateCollectionLogInformation(this.info.general.pgType);
- break;
- }
- // var nameObj = LOGLABEL[opt.type];
- // logInfo[nameObj] = opt.data;
- // /*define se a recomendacao é teste no objeto*/
- // if (neemu.rec !== undefined) {
- // var recHasTest = neemu.rec.getRecTest();
- // setRecTestGeneral.call(this, recHasTest);
- // }
- // if (
- // typeof _nm.conf.parse !== 'undefined'
- // && typeof _nm.conf.parse.general !== 'undefined'
- // && typeof _nm.conf.parse.general.testAB !== 'undefined'
- //) {
- // logInformation.generalInfo.testab =
- // neemu.parse.exec(_nm.conf.parse.general.testAB);
- // }
- // /* verificando se existe clique da rec guardado em cookie */
- // var recDataClick = logInformation.recDataClickCookie;
- // if (recDataClick !== false && getPageType() == CART_PAGE) {
- // if (recDataClick.sku === '') {
- // recDataClick.sku = recDataClick.pid;
- // }
- // logInfo[nameObj].rec_atc_pid = recDataClick.pid;
- // logInfo[nameObj].rec_atc_sku = recDataClick.sku;
- // logInfo[nameObj].rec_atc_vtr = recDataClick.vtr;
- // logInfo[nameObj].rec_atc_pos = recDataClick.pos;
- // }
- if (
- (
- /**
- * checks if the page should have the global variable
- * "neemu_product_list"
- */
- $_ME.info.general.pgType === PAGE_SEARCH
- || $_ME.info.general.pgType === PAGE_NEEMU_PAGES
- || $_ME.info.general.pgType === PAGE_NEEMU_PAGES_INDEX
- )
- && (
- // checks if the result search is greater than zero
- window.neemuNumResultadosTotal !== undefined
- && neemuNumResultadosTotal > 0
- )
- // checks if the sku_list is not loaded
- && $_ME.finalJson.info.pIds
- && !$_ME.finalJson.info.pIds.length
- ) {
- var qtyRepeats = 0;
- var qtyRepeatsMax = 20;
- var extractionInterval = setInterval(function() {
- qtyRepeats++;
- if (
- qtyRepeats < qtyRepeatsMax
- && (window.neemu_product_list !== undefined)
- ) {
- // populate the skulist
- $_ME.finalJson.info.pIds = window.neemu_product_list;
- // send log information
- opt.callback.call($_ME, $_ME.finalJson);
- // stop the repetition
- clearInterval(extractionInterval);
- }
- }, 300);
- } else {
- opt.callback.call($_ME, $_ME.finalJson);
- }
- };
- /**
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {Integer} testValue
- * @return {Boolean}
- */
- var isAllowTest = function(testValue) {
- var value = _nm.commons.parseStringToNumber($_ME.sid),
- allow = false;
- value = value % 100;
- if (testValue > value) {
- allow = true;
- }
- return allow;
- };
- /**
- * Generate a aleatory code for the user session
- *
- * @author Jhozefem Pontes <jhozefem@neemu.com>
- * @since 2.0.0
- * @return {String}
- */
- var getSessionId = function() {
- // checks if the cookie already is saved
- var sid = _nm.commons.getCookie("neemu_sid");
- if (sid == undefined || sid == "undefined") {
- var dt = new Date(),
- t = _nm.commons.base36encode(dt.getTime()),
- r = _nm.commons.base36encode(_nm.commons.random());
- for (var i = t.length; i < 8; i++) { t = "0" + t; }
- for (var i = r.length; i < 4; i++) { r = "0" + r; }
- sid = t + r;
- }
- // sets the cookie
- _nm.commons.setCookie('neemu_sid', sid, Infinity, "/", "." + conf.store.host);
- return sid;
- };
- /**
- * Generate a aleatory code for the user access
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.8.0
- * @return {String}
- */
- var getAccessId = function() {
- var accessId = "";
- /**
- * TODO: verificação comentada temporariamente, pois estava gerando o
- * mesmo accessId durante as paginações.
- */
- // if (window.nmExtractionAccessId !== undefined) {
- // accessId = window.nmExtractionAccessId;
- // } else {
- // part 1
- var sid = getSessionId.call(this);
- // part 2
- var year = new Date().getFullYear();
- var secondsYear = new Date().getTime() - new Date(year, 1, 1).getTime();
- var secondsYearB36 = _nm.commons.base36encode(secondsYear);
- // part 3
- var randomNumber = _nm.commons.randomBetween(1, 60466175).toString();
- var randomNumberB36 = _nm.commons.base36encode(randomNumber);
- accessId = sid + secondsYearB36 + randomNumberB36;
- // }
- return accessId;
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @version 2.1.11
- * @return {String}
- */
- var getChannel = function() {
- return (_nm.isMobile)
- ? "site-mobile"
- : "site"
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @param {Object} data
- * @param {Boolean} erro
- * @return {String}
- */
- var getLogRequestUrl = function(data, erro) {
- if (erro === undefined) {
- erro = false;
- }
- var logRequestUrl = $_ME.protocol;
- logRequestUrl += $_ME.logServer;
- logRequestUrl += '/grava.php?callback=neemuCallback';
- logRequestUrl += '&psid=1';
- logRequestUrl += '&sid=' + $_ME.sid;
- logRequestUrl += '&log' + ((erro) ? 'Erro' : '') + '=' + _nm.commons.encode(data);
- return logRequestUrl;
- }
- /**
- * Recupera informações gerais e a URL FINAL do grava.php
- * @param {Object} opt
- */
- var getUrlFinal = function(opt) {
- if (opt.log) {
- // execute store parse
- $_ME.storeConfig.parse(_nm);
- if (!$_ME.pauseExtraction) {
- generateLogInformation.call($_ME, {
- data: opt.data,
- callback: function(data) {
- send.call($_ME, getLogRequestUrl.call($_ME, data));
- }
- });
- }
- } else {
- send.call($_ME, getLogRequestUrl.call($_ME, opt.data, true));
- }
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Boolean}
- */
- var canSendExtraction = function() {
- var host = window.location.host;
- return (
- !_nm.commons.userAgentIsBot() &&
- (
- _nm.commons.strstr(host, _nm.conf.store.host) ||
- _nm.commons.strstr(host, "neemu.com") ||
- _nm.commons.strstr(host, "teste")
- ) &&
- (
- window.neemuExtractInfo === undefined ||
- window.neemuExtractInfo == 1
- )
- )
- ? true
- : false;
- };
- /**
- * Adicionar grava no header e enviar
- * @param {String} source url final
- */
- var send = function(source) {
- // executing callbacks
- for (var i = 0; i < _nm.callbacks.beforeLogRequests.length; i++) {
- _nm.callbacks.beforeLogRequests[i].call(this);
- }
- // validate the send extraction
- if (canSendExtraction.call($_ME)) {
- var scriptTag = _nm.commons.createElement('script', {
- 'src': source
- });
- var head = document.getElementsByTagName('head')[0];
- head.appendChild(scriptTag);
- // indicates which the page already was extracted
- window.nmPageLoggedTest = 1;
- /**
- * checks if is necessary copy the url from log to the clipboard
- * (only on Internet Explorer), to help in the debug process of
- * the extraction
- */
- if (
- (
- $_ME.storeConfig.copyLogUrlOnIE !== undefined
- && $_ME.storeConfig.copyLogUrlOnIE === true
- )
- && _nm.commons.strstr(source, "&log=")
- && _nm.commons.strstr(navigator.userAgent.toLowerCase(), "msie")
- ) {
- if (confirm("Você gostaria de salvar a URL do grava no clipboard?")) {
- if (window.clipboardData.setData("Text", source.split("&log=")[1])) {
- alert("URL do grava salva com sucesso!");
- }
- }
- }
- }
- // remoção do SID e PSID antigos
- _nm.commons.deleteCookie("sessao_logsite", _nm.conf.store.host);
- _nm.commons.deleteCookie("sessao_logsite_permanente", _nm.conf.store.host);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @version 2.0.0
- * @return {Void}
- */
- var process = function () {
- // block empty search (only if necessary)
- if (
- _nm.blockEmptySearch !== undefined
- && (
- window.searchBlocked === undefined
- || window.searchBlocked !== true
- )
- ) {
- _nm.blockEmptySearch.set($_ME.storeConfig.blockEmptySearch);
- }
- // recommendation test
- if (
- $_ME.storeConfig.rec !== undefined
- && $_ME.storeConfig.rec.test !== undefined
- ) {
- _nm.rec.setRecTest.call($_ME, isAllowTest($_ME.storeConfig.rec.test));
- }
- // sets the "neemuPlugin" informations
- if (window.neemuPlugin !== undefined) {
- neemuPlugin.session_id = $_ME.sid;
- neemuPlugin.neemuClientMainhost = _nm.conf.store.host;
- }
- getUrlFinal.call($_ME, {
- log : true,
- data : info
- });
- };
- /**
- * Inicia o processo de extração
- * @author Javier Zambrano
- * @author Andrews Lince <andrews@neemu.com>
- * @since 1.0.0
- * @param {Object} opt objeto com informações do conf
- */
- var startLog = function(opt) {
- initializeLogInformation.call($_ME);
- // chaordic features
- if (opt.chaordic) {
- _nm.chaordic.init(opt);
- }
- if (
- $_ME.storeConfig.debug !== undefined
- && $_ME.storeConfig.debug === true
- ) {
- process.call($_ME);
- } else {
- try {
- process.call($_ME);
- } catch(e) {
- // format stack trace
- var traceArray = (e.stack || e.message).split("\n");
- for (var i = 0; i < traceArray.length; i++) {
- traceArray[i] = traceArray[i].trim();
- }
- getUrlFinal.call($_ME, {
- log : false,
- data : {
- url : _nm.commons.getUrl(),
- message : e.message,
- stackTrace : traceArray,
- userAgent : $_ME.agent,
- canal : getChannel(),
- pageType : ($_ME.info.general.pgType || "genericError"),
- version : _nm.VERSION ? _nm.VERSION + "-" + _nm.buildDate : 0
- }
- });
- }
- }
- };
- /**
- * Initialize the configurated preset from the store
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.12.18
- * @return {Void}
- */
- var loadPreset = function(extractionConfig) {
- if (
- extractionConfig.preset !== undefined &&
- typeof(_nm.preset[extractionConfig.preset].init) === "function"
- ) {
- _nm.preset[extractionConfig.preset].init(extractionConfig);
- }
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} opt
- * @return {Void}
- */
- var init = function(opt) {
- loadPreset(opt);
- // checks if the page already was extracted
- if (
- window.nmPageLoggedTest === undefined
- || (
- window.nmPageLoggedTest !== undefined
- && window.nmPageLoggedTest !== 1
- )
- ) {
- window.nmExtractionAccessId = getAccessId.call(this);
- var fnStartLog = function(opt) {
- var execute = true;
- if (opt.blackList !== undefined) {
- var sizeBlackList = opt.blackList.length, i = 0;
- for (i; i < sizeBlackList; i++) {
- var urlBlackSite = opt.blackList[i];
- if (_nm.commons.strstr(_nm.commons.getUrl(), urlBlackSite)) {
- execute = false;
- }
- }
- }
- if (execute) {
- // register store configurations
- $_ME.storeConfig = opt;
- // register the user session id
- $_ME.sid = getSessionId.call(this);
- // register the user agent
- $_ME.agent = navigator.userAgent || navigator.vendor || window.opera;
- // register the protocol
- $_ME.protocol = window.location.protocol + "//";
- // register the log server
- $_ME.logServer = opt.store.logServer + "/" +
- getStoreIdByEnv(opt.store.id, window.location.host);
- // detect if is mobile device
- _nm.isMobile = _nm.commons.isMobile();
- /**
- * TODO: esse trecho parece que era necessário por conta do módulo
- * especÃfico da vtex. Verificar com o Jhozefem se isso ainda
- * precisa estar na API ou se essas coisas serão passadas pelo
- * time de operação.
- */
- // if (opt.autocomplete && typeof opt.autocomplete == 'object') {
- // if (opt.type && opt.type == 'vtex') {
- // if (opt.autocomplete && typeof opt.autocomplete == 'object') {
- // vtex.removeAutocomplete();
- // }
- // }
- // addAutocomplete.call(this, opt.autocomplete);
- // }
- if (opt.domReady) {
- _nm.commons.domReady(function() {
- startLog.call($_ME, opt);
- });
- } else {
- startLog.call($_ME, opt);
- }
- }
- }
- /**
- * add configuration "waitInitExtraction" by default
- * for neemu protocol
- */
- if (
- _nm.neemuProtocolLoaded &&
- !opt.preset &&
- opt.waitInitExtraction === undefined
- ) {
- opt.waitInitExtraction = {
- times: 20,
- delay: 250,
- fnCallback: function(_nm) {
- return window._neemu !== undefined
- }
- };
- }
- if (opt.waitInitExtraction !== undefined) {
- _nm.commons.checkConditionInterval(
- opt.waitInitExtraction.times,
- opt.waitInitExtraction.delay,
- function(){
- return opt.waitInitExtraction.fnCallback(_nm);
- },
- function() {
- fnStartLog(opt);
- }
- );
- } else {
- fnStartLog(opt);
- }
- }
- };
- /**
- * Process the store id by according with environment
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.10.9
- * @param {String} storeId Store id from store
- * @param {String} host current host from URL
- * @return {String}
- */
- var getStoreIdByEnv = function(storeId, host) {
- // store production by default
- var storeIdByEnv = storeId;
- // neemu development
- if (_nm.commons.strstr(host, "local.")) {
- storeIdByEnv += "-dev";
- }
- // neemu staging
- else if (_nm.commons.strstr(host, "valid.neemu.com")) {
- storeIdByEnv += "-stg";
- }
- // neemu production
- else if (_nm.commons.strstr(host, ".neemu.com")) {
- storeIdByEnv += "-prd";
- }
- return storeIdByEnv;
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {String} pageType
- * @return {Void}
- */
- var initRecommendation = function(pageType) {
- if (
- _nm.rec !== undefined
- && neemuPlugin !== undefined
- && $_ME.storeConfig.rec !== undefined
- && neemuPlugin.recommendation !== undefined
- && $_ME.storeConfig.rec.hasOwnProperty(pageType)
- ) {
- loadInitRecommendation = true;
- _nm.rec.insert({
- url : $_ME.storeConfig.rec.url,
- page : pageType,
- test : $_ME.storeConfig.rec.test,
- info : $_ME.storeConfig.rec[pageType],
- allowMobile : $_ME.storeConfig.rec.allowMobile || false
- });
- }
- };
- /**
- * Returns the pagetype
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.12.10
- * @return {String}
- */
- var getPageType = function() {
- return $_ME.info.general.pgType;
- };
- var setPageType = function(pageType) {
- $_ME.info.general.pgType = pageType;
- /**
- * disregards page types of user action tracking
- */
- if (
- pageType !== PAGE_REC_PRINT
- && pageType !== PAGE_ADD_TO_CART
- ) {
- if (neemuPlugin.recommendation === undefined) {
- neemuPlugin.recommendation = {};
- }
- // navigation >> departamento
- if (pageType === PAGE_NAVIGATION) {
- neemuPlugin.recommendation.pageType = "departamento";
- }
- // checks if the page type is search and if is a not found search
- else if (
- pageType === PAGE_SEARCH
- && window.neemuNumResultadosTotal !== undefined
- && window.neemuNumResultadosTotal === 0
- ) {
- neemuPlugin.recommendation.pageType = PAGE_NOT_FOUND;
- }
- neemuPlugin.recommendation.pageType =
- (
- (neemuPlugin.recommendation.pageType !== undefined)
- ? neemuPlugin.recommendation.pageType
- : pageType
- );
- }
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * @return {Void}
- */
- var _setAccount = function(data) {
- // $_ME.sid = _nm.commons.getSessionId();
- };
- /**
- * Identifies the logged user by cookie from Neemu
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.12.18
- * @return {Boolean}
- */
- var neemuUserIsLogged = function() {
- return (
- _nm.commons.getCookie("neemuDataUserName") !== undefined ||
- _nm.commons.getCookie("neemuDataUserEmail") !== undefined
- )
- };
- /**
- * Returns the informations from logged Neemu user
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.12.18
- * @return {Boolean}
- */
- var getNeemuLoggedUser = function() {
- var neemuLoggedUser = {},
- name = _nm.commons.getCookie("neemuDataUserName"),
- email = _nm.commons.getCookie("neemuDataUserEmail");
- if (name !== undefined) {
- neemuLoggedUser.name = name;
- }
- if (email !== undefined) {
- neemuLoggedUser.email = email;
- }
- return neemuLoggedUser;
- };
- /**
- * Saves the user informations in cookie, by 30 days
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.12.18
- * @param {Object} data
- * - name
- * - email
- * @return {Boolean}
- */
- var setNeemuLoggedUser = function(data) {
- if (data.name !== undefined) {
- _nm.commons.setCookie(
- "neemuDataUserName",
- data.name,
- 43200, // 30 dias
- "/",
- "." + _nm.conf.store.host
- );
- }
- if (data.email !== undefined) {
- _nm.commons.setCookie(
- "neemuDataUserEmail",
- data.email,
- 43200, // 30 dias
- "/",
- "." + _nm.conf.store.host
- );
- }
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @param {Object} data
- * - geolocation
- * - loggedId
- * - name
- * - email
- * @return {Void}
- */
- var _setUser = function(data) {
- setNeemuLoggedUser(data);
- $_ME.info.user = data;
- };
- var _addProductSearch = function(param1, param2) {
- if ($_ME.info.search.pIds === undefined) {
- $_ME.info.search.pIds = [];
- }
- if(typeof(param1) != 'undefined' && typeof(param2) != 'undefined') {
- var sku = {};
- sku[param2] = param1;
- $_ME.info.search.pIds.push(sku);
- }
- else if(typeof(param1) == 'object') {
- for(var i = 0; i < param1.length; i++) {
- var sku = {};
- sku[param1[i].ranking] = param1[i].id;
- $_ME.info.search.pIds.push(sku);
- }
- }
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.1.0
- * @param {Object} data
- * @return {Object}
- */
- var castOfSearchInformations = function(data) {
- // cast from integer values
- data.pg = parseInt(data.pg);
- data.qty = parseInt(data.qty);
- data.qtyAnd = parseInt(data.qtyAnd);
- if (data.hasSuggest!== undefined) {
- data.hasSuggest = parseInt(data.hasSuggest);
- }
- return data;
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.1.0
- * @return {Void}
- */
- var getSearchSort = function() {
- var searchSort = _nm.commons.getUrlParamValue("sort");
- if (searchSort !== null) {
- $_ME.info.search.sort = parseInt(searchSort);
- $_ME.info.navigation.sort = parseInt(searchSort);
- }
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.1.0
- * @param {Object} data
- * @return {Object}
- */
- var _setNeemuPagesInformation = function(data) {
- if (data.q === data.qOrig) {
- delete data.qOrig;
- }
- data = castOfSearchInformations(data);
- // merge search information
- $_ME.info.search = _nm.commons.objectMerge($_ME.info.search, data);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.1.0
- * @param {Object} data
- * @return {Object}
- */
- var _setNeemuPagesIndexInformation = function(data) {
- if (data.q === data.qOrig) {
- delete data.qOrig;
- }
- data = castOfSearchInformations(data);
- // merge search information
- $_ME.info.search = _nm.commons.objectMerge($_ME.info.search, data);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.1.0
- * @return {Void}
- */
- var _setNavigationInformation = function(data) {
- data = castOfSearchInformations(data);
- // sort
- getSearchSort.call($_ME);
- // defines the category id for neemu recommendation
- if (!neemuPlugin.departmentInformation) {
- neemuPlugin.departmentInformation = {};
- }
- neemuPlugin.departmentInformation.categoryId = data.cId;
- $_ME.info.navigation = _nm.commons.objectMerge($_ME.info.navigation, data);
- $_ME.loadDepartmentList(data.cId);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @param {Object} data
- * - query
- * - qtyResults
- * - processTime
- * @return {Void}
- */
- var _setSearchInformation = function(data) {
- var w = window,
- queryString = w.location.search
- requestParams = _nm.commons.getRequestParams();
- // old version of search (without mustache)
- if (w.neemuQuery !== undefined) {
- $_ME.info.search.pg = 0;
- $_ME.info.search.qty = parseInt(w.neemuNumResultadosTotal) || 0;
- $_ME.info.search.qtyAnd = parseInt(w.neemuNumResultadosAnd) || 0;
- $_ME.info.search.q = w.neemuQuery || "";
- $_ME.info.search.hasSuggest = parseInt(w.neemuSugestaoConsulta) || 0;
- // dyd you mean
- if (w.neemuVqd !== "0") {
- $_ME.info.search.qOrig = w.neemuQOriginal;
- }
- // product ids
- var productList = w.neemu_product_list || [],
- pIds = [];
- for (var i = 0; i < productList.length; i++) {
- var obj = {};
- obj[String(productList[i].ranking)] = productList[i].id
- pIds.push(obj);
- }
- $_ME.info.search.pIds = pIds;
- // page number
- var urlPgNumber = _nm.commons.getUrlParamValue("page");
- if (w.nmPgNumber === undefined) {
- w.nmPgNumber = (urlPgNumber !== null)
- ? parseInt(urlPgNumber)
- : 1;
- } else if (
- typeof $_ME.info.search.pIds[0] !== undefined &&
- !$_ME.info.search.pIds[0].hasOwnProperty("1")
- ) {
- w.nmPgNumber = (urlPgNumber !== null)
- ? parseInt(urlPgNumber)
- : w.nmPgNumber + 1;
- }
- $_ME.info.search.pg = w.nmPgNumber;
- // sort
- var searchSort = _nm.commons.getUrlParamValue("sort");
- if (searchSort !== null) {
- $_ME.info.search.sort = parseInt(searchSort);
- }
- // origin
- // var searchOrigin = _nm.commons.getUrlParamValue("origem");
- // if (searchOrigin !== null) {
- // $_ME.info.search.origin = searchOrigin;
- // }
- if (w.neemuOrigin !== undefined) {
- $_ME.info.search.origin = w.neemuOrigin;
- }
- // filters
- if (_nm.commons.isSearchFilter(queryString)) {
- var searchFilters = [];
- for (var paramName in requestParams) {
- if (_nm.commons.isSearchFilter(paramName)) {
- var objFilter = {};
- objFilter[paramName.match(/\[(.*)\]/)[1]] =
- requestParams[paramName].trim();
- searchFilters.push(objFilter);
- }
- }
- $_ME.info.search.filters = searchFilters;
- }
- // a/b test
- if (w.neemuTesteAB !== undefined) {
- $_ME.info.general.testab = w.neemuTesteAB;
- }
- /******************** [ AUTOCOMPLETE INFORMATION ] ********************/
- var acTypeClick = _nm.commons.getUrlParamValue("typeclick");
- if (acTypeClick !== null) {
- $_ME.info.autocomplete = {
- type : parseInt(acTypeClick),
- prefix : _nm.commons.getUrlParamValue("p"),
- q : _nm.commons.getUrlParamValue("q"),
- pos : _nm.commons.getUrlParamValue("ac_pos"),
- rank : parseInt(_nm.commons.getUrlParamValue("ranking"))
- };
- // autocomplete with category
- var categoryFilter = _nm.commons.getUrlParamValue("common_filter[Categoria]");
- if (categoryFilter !== null) {
- $_ME.info.autocomplete.type = 2;
- }
- }
- /******************** [ QUICK FILTER INFORMATION ] ********************/
- /**
- * TODO: verificar com a Adriana como mandar essa informação
- * de quick filter, pois nem sempre vem uma categoria.
- */
- /******************** [ NEEMU PAGES INFORMATION ] *********************/
- if (
- w.neemuPageType !== undefined &&
- _nm.commons.strstr(w.neemuPageType, PAGE_NEEMU_PAGES)
- ) {
- // remove unnecessary fields
- delete $_ME.info.search.type;
- delete $_ME.info.search.pg;
- $_ME.info.general.pgType = w.neemuPageType;
- $_ME.info.search.q = w.location.pathname.slice(1);
- }
- /********************* [ NAVIGATION INFORMATION ] *********************/
- if (w.neemuCategoria !== undefined && w.neemuCategoria.id !== "") {
- delete $_ME.info.search.query;
- $_ME.info.general.pgType = PAGE_NAVIGATION;
- $_ME.info.search.categoryId = w.neemuCategoria.id;
- $_ME.info.search.categoryName = w.neemuCategoria.name;
- $_ME.info.search.type = w.neemuNavType.replace("nav_", "");
- // departmentList
- loadDepartmentList.call($_ME, $_ME.info.search.categoryId);
- } else {
- // queryList
- loadQueryList.call($_ME, $_ME.info.search.query);
- }
- }
- // new version of search (with mustache)
- else {
- // checks if is necessary consider the original query
- if (data.q === data.qOrig) {
- delete data.qOrig;
- }
- data = castOfSearchInformations(data);
- if (data.qty === 0) {
- neemuPlugin.recommendation.pageType = PAGE_NOT_FOUND;
- }
- // merge search information
- $_ME.info.search = _nm.commons.objectMerge($_ME.info.search, data);
- // sort
- getSearchSort.call($_ME);
- // filters
- if (_nm.commons.isSearchFilter(queryString)) {
- var searchFilters = [];
- var searchFiltersKeys = [];
- for (var paramName in requestParams) {
- if (_nm.commons.isSearchFilter(paramName)) {
- var objFilter = {};
- var filterName = paramName.match(/\[(.*)\]/)[1];
- var filterValue = requestParams[paramName].trim();
- objFilter[filterName] = filterValue;
- searchFilters.push(objFilter);
- searchFiltersKeys.push({
- name: filterName,
- value: filterValue
- });
- }
- }
- $_ME.info.search.filters = searchFilters;
- }
- /******************** [ AUTOCOMPLETE INFORMATION ] ********************/
- var acTypeClick = _nm.commons.getUrlParamValue("typeclick");
- if (acTypeClick !== null) {
- $_ME.info.autocomplete = {
- type : parseInt(acTypeClick),
- prefix : _nm.commons.getUrlParamValue("p"),
- q : data.q || _nm.commons.getUrlParamValue("q"),
- pos : _nm.commons.getUrlParamValue("ac_pos"),
- rank : parseInt(_nm.commons.getUrlParamValue("ranking"))
- };
- }
- /******************** [ QUICK FILTER INFORMATION ] ********************/
- var origin = _nm.commons.getUrlParamValue("origem");
- if (origin === "co") {
- $_ME.info.quickFilter = {
- type : 2 // click
- };
- $_ME.info.quickFilter.hasFilter = 0;
- // checks if exists filters
- if (searchFilters && searchFilters.length) {
- $_ME.info.quickFilter.hasFilter = 1;
- $_ME.info.quickFilter[searchFiltersKeys[0].name] =
- searchFiltersKeys[0].value;
- }
- }
- }
- $_ME.loadQueryList();
- };
- /**
- * @author Leticia Santos <leticia.n.santos@neemu.com>
- * @since 2.12.29
- * @param {Object} data
- * @return {Void}
- */
- var _setWishlistInformation = function(data) {
- var w = window;
- // old version of search (without mustache)
- if (w.neemuQuery !== undefined) {
- // product ids
- var productList = w.neemu_product_list || [],
- pIds = [];
- for (var i = 0; i < productList.length; i++) {
- var obj = {};
- obj[String(productList[i].ranking)] = productList[i].id
- pIds.push(obj);
- }
- $_ME.info.wishlist.pIds = pIds;
- // page number
- var urlPgNumber = _nm.commons.getUrlParamValue("page");
- if (w.nmPgNumber === undefined) {
- w.nmPgNumber = (urlPgNumber !== null)
- ? parseInt(urlPgNumber)
- : 1;
- } else if (
- typeof $_ME.info.search.pIds[0] !== undefined &&
- !$_ME.info.wishlist.pIds[0].hasOwnProperty("1")
- ) {
- w.nmPgNumber = (urlPgNumber !== null)
- ? parseInt(urlPgNumber)
- : w.nmPgNumber + 1;
- }
- $_ME.info.wishlist.pg = w.nmPgNumber;
- } else {
- //TODO
- }
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var _setHomePageType = function() {
- setPageType.call($_ME, PAGE_HOME);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var _setSearchPageType = function() {
- setPageType.call($_ME, PAGE_SEARCH);
- // set store search type
- $_ME.info.search.type = _nm.conf.store.id;
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var _setSearchNeemuPageType = function() {
- setPageType.call($_ME, PAGE_SEARCH);
- // set neemu search type
- $_ME.info.search.type = "neemuSearch";
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var _setDepartmentPageType = function() {
- setPageType.call($_ME, PAGE_DEPARTMENT);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var _setRecPrintPageType = function() {
- setPageType.call($_ME, PAGE_REC_PRINT);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var _setAddToCartPageType = function() {
- setPageType.call($_ME, PAGE_ADD_TO_CART);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var _setProductPageType = function() {
- setPageType.call($_ME, PAGE_PRODUCT);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var _setCartPageType = function() {
- setPageType.call($_ME, PAGE_CHECKOUT_CART);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var _setCheckoutPageType = function() {
- setPageType.call($_ME, PAGE_CHECKOUT);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var _setCheckoutConfirmationPageType = function() {
- setPageType.call($_ME, PAGE_CHECKOUT_CONFIRMATION);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var _setComparisonPageType = function() {
- setPageType.call($_ME, PAGE_COMPARISON);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.1.0
- * @return {Void}
- */
- var _setNavigationPageType = function() {
- setPageType.call($_ME, PAGE_NAVIGATION);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.1.0
- * @return {Void}
- */
- var _setNeemuPagesPageType = function() {
- setPageType.call($_ME, PAGE_NEEMU_PAGES);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.1.0
- * @return {Void}
- */
- var _setNeemuPagesIndexPageType = function() {
- setPageType.call($_ME, PAGE_NEEMU_PAGES_INDEX);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.1.0
- * @return {Void}
- */
- var _setHotsitePageType = function() {
- setPageType.call($_ME, PAGE_HOTSITE);
- };
- /**
- * @author Leticia Santos <leticia.n.santos@neemu.com>
- * @since 2.12.29
- * @return {Void}
- */
- var _setWishlistPageType = function() {
- setPageType.call($_ME, PAGE_WISHLIST);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - id
- * - title
- * - img
- * - stock
- * - url
- * - cId
- * - price
- * - sPrice
- * - cPrice
- * - price
- * - inst
- * - qty
- * - amount
- * @return {Void}
- */
- var _setProductInformation = function(data) {
- // checks if is necessary process sku availability
- if (data.stock !== undefined) {
- data.stock = _nm.commons.processAvailability(data.stock);
- // checks if the product is unavailable
- if (!data.stock) {
- neemuPlugin.recommendation.pageType = "produtoInd";
- }
- }
- // checks if is necessary remove campaign price
- if (data.cPrice !== undefined) {
- if (data.cPrice === "") {
- delete data.cPrice;
- } else {
- data.cPrice = data.cPrice;
- }
- }
- // format old price
- if (data.price !== undefined) {
- data.price = _nm.commons.formatCurrency(data.price);
- }
- // format sale price
- if (data.sPrice !== undefined) {
- data.sPrice = _nm.commons.formatCurrency(data.sPrice);
- }
- if (data.inst !== undefined) {
- // format installment value
- if (data.inst.amount !== undefined) {
- data.inst.amount = _nm.commons.formatCurrency(data.inst.amount);
- }
- data.inst.qty = parseInt(data.inst.qty);
- data.inst = [ data.inst ];
- }
- // recommendation information
- if (undefined === neemuPlugin.productInformation) {
- neemuPlugin.productInformation = {};
- }
- neemuPlugin.productInformation.id = data.id;
- neemuPlugin.productInformation.availability = data.stock;
- neemuPlugin.productInformation.productTypeId = data.cId;
- $_ME.info.product = data;
- $_ME.loadClickList();
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - title
- * @return {Void}
- */
- var _setHotsiteInformation = function(data) {
- // set the default type as "neemu"
- if (data.type === undefined) {
- data.type = 'neemu';
- }
- $_ME.info.hotsite = data;
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - position
- * - id
- * - productTypeId
- * - price
- * - name
- * - sku
- * @return {Void}
- */
- var _setComparisonInformation = function(data) {
- // format price (only if necessary)
- if (
- typeof(data.price) === "string"
- && !_nm.commons.strstr(data.price, " ")
- ) {
- data.price = _nm.commons.formatCurrency(data.price);
- }
- $_ME.info.skuList.push(data);
- }
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * - name
- * @return {Void}
- */
- var _setCheckoutStep = function(data) {
- $_ME.info.checkoutInformation = {
- step : data.name
- };
- };
- /**
- * SET INFORMATIONS
- */
- var track = function() {
- /**
- * permitindo que a extração seja feita mais de 1 vez na página (por
- * causa do ajax)
- */
- window.nmPageLoggedTest = 0;
- // running extraction
- _nm.extraction.init.call(this, _nm.conf);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - infoName
- * - infoValue
- * @return {Void}
- */
- var _addCustomInformation = function(data) {
- $_ME.info.general[data.infoName] = data.infoValue;
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var _addHomeInformation = function(data) {
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - cId
- * - tree
- * - level
- * - name
- * @return {Void}
- */
- var _addDepartmentInformation = function(data) {
- $_ME.info.department.cId = data.cId.toString() || "";
- // defines the category id for neemu recommendation
- if (!neemuPlugin.departmentInformation) {
- neemuPlugin.departmentInformation = {};
- }
- neemuPlugin.departmentInformation.categoryId = $_ME.info.department.cId;
- if (
- data.tree !== undefined
- && data.tree.index !== undefined
- && data.tree.name !== undefined
- ) {
- $_ME.info.department.tree.push({
- index : data.tree.index.toString(),
- name : data.tree.name
- });
- }
- $_ME.loadDepartmentList();
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - name
- * - value
- * @return {Void}
- */
- var _addFilterInformation = function(data) {
- $_ME.info.filters.push(data);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - sku
- * - stock
- * - price
- * - sPrice
- * - inst
- * - qty
- * - amount
- * @return {Void}
- */
- var _addSku = function(data) {
- // cast the availability for a boolean value
- if (data.stock !== undefined) {
- data.stock = _nm.commons.processAvailability.call(
- $_ME,
- data.stock
- );
- }
- if (data.price !== undefined) {
- data.price = _nm.commons.formatCurrency(data.price);
- }
- // checks if sale price for this sku was nor informed
- if (data.sPrice === undefined) {
- // uses sale price from product for this sku
- data.sPrice = $_ME.info.product.sPrice;
- }
- data.sPrice = _nm.commons.formatCurrency(data.sPrice);
- if (data.inst !== undefined) {
- // format installment value
- if (data.inst.amount !== undefined) {
- data.inst.amount = _nm.commons.formatCurrency(data.inst.amount);
- }
- data.inst.qty = parseInt(data.inst.qty);
- data.inst = [ data.inst ];
- }
- $_ME.info.skuList[data.sku] = data;
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.1.10
- * @param {Array} data
- * @return {Void}
- */
- var _addSearchSkuList = function(data) {
- $_ME.info.search.pIds = data;
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - sku
- * - specName
- * - specValue
- * @return {Void}
- */
- var _addSkuSpec = function(data) {
- $_ME.info.skuList[data.sku][data.specName] = data.specValue;
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - skuId
- * - $_ME.info.ame
- * - $_ME.info.alue
- * @return {Void}
- */
- var _addCustomSkuInformation = function(data) {
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - id
- * - price
- * - qty
- * - sku
- * @return {Void}
- */
- var _addCartItem = function(data) {
- // cast of the quantity for a boolean value
- if (data.qty) {
- data.qty = parseInt(data.qty);
- }
- // format price (only if necessary)
- if (
- typeof(data.price) === "string"
- && !_nm.commons.strstr(data.price, " ")
- ) {
- data.price = _nm.commons.formatCurrency(data.price);
- }
- $_ME.info.skuList.push(data);
- $_ME.loadCartList();
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - order
- * - totalAmount
- * - shippingAmount
- * - city
- * - state
- * - coutry
- * @return {Void}
- */
- var _addOrder = function(data) {
- data.ship = _nm.commons.formatCurrency(data.ship);
- data.amount = _nm.commons.formatCurrency(data.amount);
- $_ME.info.checkoutConfirmation = data;
- $_ME.loadPurchaseList();
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - skuId
- * - price
- * - qty
- * - productId
- * @return {Void}
- */
- var _addOrderItem = function(data) {
- // cast of the quantity for a boolean value
- if (data.qty) {
- data.qty = parseInt(data.qty);
- }
- // format price (only if necessary)
- if (
- typeof(data.price) === "string"
- && !_nm.commons.strstr(data.price, " ")
- ) {
- data.price = _nm.commons.formatCurrency(data.price);
- }
- data.price = data.price;
- if (window.neemuPlugin.recommendation.skuRecommendation === undefined) {
- window.neemuPlugin.recommendation.skuRecommendation = {
- id : "",
- sku : ""
- };
- }
- window.neemuPlugin.recommendation.skuRecommendation.id += data.id + ";";
- window.neemuPlugin.recommendation.skuRecommendation.sku += data.sku + ";";
- $_ME.info.skuList.push(data);
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @return {Void}
- */
- var parseApiObject = function() {
- if (window._neemu !== undefined) {
- var commandsLoaded = [];
- var neemuLength = window._neemu.length;
- for (var i = 0; i < neemuLength; i++) {
- var command = window._neemu[i][0].trim();
- commandsLoaded[command] = true;
- if (window["_nm"][command] !== undefined) {
- window["_nm"][command].apply(
- ($_ME || window),
- window._neemu[i].slice(1)
- );
- }
- }
- }
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - product (product information)
- * - cId (cateogry id)
- * - cPrice (campaign price)
- * - id (product id)
- * - title (product title)
- * - sPrice (sale price)
- * - pgName (page name)
- * - scName (showcase name)
- * - rank (product ranking)
- * - img (url from product image)
- * - stock (product availability)
- * - skus (sku list)
- * - sPrice (sku price)
- * - sku (sku number)
- * - stock (sku availability)
- * - rec (recommendation information)
- * - segment (showcase segment)
- * @param {Function} fnCallback
- * @return {Void}
- */
- var trackAddToCart = function(data, fnCallback) {
- // sets the addToCart page type
- _setAddToCartPageType();
- if (data.product !== undefined) {
- for (var i = 0; i < data.product.length; i++) {
- if (data.product[i].rank !== undefined) {
- data.product[i].rank = parseInt(data.product[i].rank);
- }
- if (data.product[i].sPrice !== undefined) {
- data.product[i].sPrice = _nm.commons.formatCurrency(data.product[i].sPrice);
- }
- if (data.product[i].stock !== undefined) {
- data.product[i].stock = _nm.commons.processAvailability(
- data.product[i].stock
- );
- }
- if (data.product[i].skus !== undefined) {
- if (data.product[i].skus.length) {
- for (var j = 0; j < data.product[i].skus.length; j++) {
- data.product[i].skus[j].sPrice =
- _nm.commons.formatCurrency(
- data.product[i].skus[j].sPrice
- );
- }
- }
- }
- }
- }
- sendRequestExtras.call($_ME, {
- params : {
- log : _nm.commons.base64Encode(_nm.commons.parseObjectToJSON({
- general : $_ME.info.general,
- product : data.product,
- rec : {
- list : [
- getRecListFromTrack.call($_ME, {
- chn : $_ME.info.general.chn,
- scName : data.rec.nm_rec_showcase,
- scId : data.rec.nm_rec_vid,
- scenario : data.rec.nm_rec_scenario,
- pgName : data.rec.nm_rec_page,
- cName : data.rec.nm_rec_category,
- seg : data.rec.nm_rec_segment,
- rank : data.rec.nm_ranking_rec
- })
- ]
- }
- }))
- }
- });
- fnCallback();
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - loadDelay
- * - status
- * - recList[]
- * - type
- * - access[]
- * - scenario
- * - segment
- * - page
- * - category
- * @return {Void}
- */
- var trackRecPrint = function(options) {
- // sets the recview page type
- _setRecPrintPageType();
- var recList = options.recList,
- recListLength = recList.length,
- recPrint = {
- general : $_ME.info.general,
- info : {
- rTime : options.loadDelay,
- rCode : options.status,
- oType : neemuPlugin.recommendation.pageType,
- oInfo : "",
- list : []
- }
- };
- for (var i = 0; i < recListLength; i++) {
- var scenario = (recList[i].access !== undefined && recList[i].access.scenario !== undefined) ? recList[i].access.scenario : "",
- segment = (recList[i].access !== undefined && recList[i].access.segment !== undefined) ? recList[i].access.segment : "",
- cName = (recList[i].access !== undefined && recList[i].access.category !== undefined) ? recList[i].access.category : "";
- recPrint.info.list[i] = getRecListFromTrack.call($_ME, {
- chn : $_ME.info.general.chn,
- scName : recList[i].type,
- scId : recList[i].vid,
- scenario : scenario,
- pgName : neemuPlugin.recommendation.pageType,
- cName : cName,
- seg : segment
- });
- }
- if (recPrint.info.oType == "produto") {
- // recPrint.info.oInfo = _nm.commons.getUrlParamValue("nm_rec_id");
- recPrint.info.oInfo = neemuPlugin.productInformation.id;
- } else if (recPrint.info.oType == "departamento") {
- recPrint.info.oInfo = $_ME.info.department.categoryId;
- } else if (recPrint.info.oType == "busca") {
- recPrint.info.oInfo = $_ME.info.search.query;
- }
- sendRequestExtras.call($_ME, {
- params : {
- log : _nm.commons.base64Encode(_nm.commons.parseObjectToJSON(recPrint))
- }
- });
- };
- /**
- * @author Andrews Lince <andrews@neemu.com>
- * @version 2.1.0
- * @param {Object} data
- * - chn (channel)
- * - scName (showcase name)
- * - scId (showcase id)
- * - scenario (scenario)
- * - pgName (page name)
- * - cName (category name)
- * - seg (segment)
- * - rank (ranking)
- * @return {Object}
- */
- var getRecListFromTrack = function(data) {
- // default values
- var recInfo = {
- chn : data.chn,
- scName : data.scName,
- scId : data.scId,
- scenario : data.scenario,
- pgName : data.pgName,
- cName : data.cName,
- seg : data.seg,
- tree : [
- [
- data.chn,
- data.scenario,
- data.seg,
- data.pgName,
- data.cName,
- data.scName,
- data.scId
- ],
- [
- data.chn,
- data.scenario,
- data.seg,
- data.pgName,
- data.cName,
- data.scId,
- data.scName
- ],
- [
- data.chn,
- data.scenario,
- data.pgName,
- data.scName,
- data.cName,
- data.seg,
- data.scId
- ]
- ]
- };
- // checks if ranking was informed
- if (data.rank !== undefined) {
- recInfo.rank = data.rank;
- }
- return recInfo;
- };
- /**
- * Send a ajax request (using JSONP) for tracking of the user's action
- *
- * @author Andrews Lince <andrews@neemu.com>
- * @since 2.0.0
- * @param {Object} data
- * - params
- * @return {Void}
- */
- var sendRequestExtras = function(data) {
- var url = "//" + _nm.conf.store.logServer + "/" + _nm.conf.store.id + "/extras",
- count = 0,
- paramsLength = 0;
- if (data.params !== undefined) {
- paramsLength = Object.keys(data.params).length;
- if (paramsLength) {
- url += "?";
- for (var paramName in data.params) {
- if (count > 0) {
- url += "&";
- }
- url += paramName + "=" + data.params[paramName];
- paramsLength++;
- }
- }
- _nm.commons.ajaxRequestJsonp(url);
- }
- };
- // public methods
- return {
- // constants
- PAGE_CHECKOUT_CONFIRMATION : PAGE_CHECKOUT_CONFIRMATION,
- PAGE_NAVIGATION : PAGE_NAVIGATION,
- PAGE_NEEMU_PAGES_INDEX : PAGE_NEEMU_PAGES_INDEX,
- PAGE_CHECKOUT_CART : PAGE_CHECKOUT_CART,
- PAGE_NEEMU_PAGES : PAGE_NEEMU_PAGES,
- PAGE_DEPARTMENT : PAGE_DEPARTMENT,
- PAGE_COMPARISON : PAGE_COMPARISON,
- PAGE_REC_PRINT : PAGE_REC_PRINT,
- PAGE_CHECKOUT : PAGE_CHECKOUT,
- PAGE_GENERAL : PAGE_GENERAL,
- PAGE_PRODUCT : PAGE_PRODUCT,
- PAGE_SEARCH : PAGE_SEARCH,
- PAGE_LOGIN : PAGE_LOGIN,
- PAGE_HOME : PAGE_HOME,
- PAGE_HOTSITE : PAGE_HOTSITE,
- PAGE_WISHLIST : PAGE_WISHLIST,
- PAGE_COLLECTION_GERAL : PAGE_COLLECTION_GERAL,
- PAGE_COLLECTION_HOME : PAGE_COLLECTION_HOME,
- PAGE_COLLECTION_SEARCH : PAGE_COLLECTION_SEARCH,
- PAGE_COLLECTION_DETAILS : PAGE_COLLECTION_DETAILS,
- PAGE_COLLECTION_AUTHOR : PAGE_COLLECTION_AUTHOR,
- PAGE_COLLECTION_REGISTER : PAGE_COLLECTION_REGISTER,
- PAGE_COLLECTION_RELATED : PAGE_COLLECTION_RELATED,
- PAGE_COLLECTION_TAG : PAGE_COLLECTION_TAG,
- // neemu protocol methods
- _setCheckoutConfirmationPageType : _setCheckoutConfirmationPageType,
- _setNeemuPagesIndexInformation : _setNeemuPagesIndexInformation,
- _setNeemuPagesIndexPageType : _setNeemuPagesIndexPageType,
- _setNeemuPagesInformation : _setNeemuPagesInformation,
- _addDepartmentInformation : _addDepartmentInformation,
- _setComparisonInformation : _setComparisonInformation,
- _setNavigationInformation : _setNavigationInformation,
- _setSearchNeemuPageType : _setSearchNeemuPageType,
- _setProductInformation : _setProductInformation,
- _setDepartmentPageType : _setDepartmentPageType,
- _setNeemuPagesPageType : _setNeemuPagesPageType,
- _setNavigationPageType : _setNavigationPageType,
- _setComparisonPageType : _setComparisonPageType,
- _setWishlistPageType : _setWishlistPageType,
- _setHotsitePageType : _setHotsitePageType,
- _setWishlistInformation : _setWishlistInformation,
- _setHotsiteInformation : _setHotsiteInformation,
- _setSearchInformation : _setSearchInformation,
- _addFilterInformation : _addFilterInformation,
- _addCustomInformation : _addCustomInformation,
- _setCheckoutPageType : _setCheckoutPageType,
- _addHomeInformation : _addHomeInformation,
- _setProductPageType : _setProductPageType,
- _setSearchPageType : _setSearchPageType,
- _addProductSearch : _addProductSearch,
- _addSearchSkuList : _addSearchSkuList,
- _setCartPageType : _setCartPageType,
- _setCheckoutStep : _setCheckoutStep,
- _setHomePageType : _setHomePageType,
- _addOrderItem : _addOrderItem,
- _addCartItem : _addCartItem,
- _setAccount : _setAccount,
- _addSkuSpec : _addSkuSpec,
- _addOrder : _addOrder,
- _setUser : _setUser,
- _addSku : _addSku,
- loadDepartmentList : loadDepartmentList,
- getNeemuLoggedUser : getNeemuLoggedUser,
- setNeemuLoggedUser : setNeemuLoggedUser,
- neemuUserIsLogged : neemuUserIsLogged,
- loadPurchaseList : loadPurchaseList,
- parseIsPaused : parseIsPaused,
- loadClickList : loadClickList,
- loadQueryList : loadQueryList,
- continueParse : continueParse,
- loadCartList : loadCartList,
- getPageType : getPageType,
- pauseParse : pauseParse,
- setMe : setMe,
- initializeLogInformation: initializeLogInformation,
- parseApiObject : parseApiObject,
- trackAddToCart : trackAddToCart,
- trackRecPrint : trackRecPrint,
- track : track,
- info : info,
- init : init
- };
- })(window, document, undefined);
- // _nm.extraction = extraction;
- _nm.extraction.setMe(_nm.extraction);
- //check for change on hash of location
- _nm.commons.addEventListener(window, "hashchange", function(){
- _nm.extraction.track();
- });
- //on change of url browser
- /*
- (function(history){
- if(!window.requestChangeUrl){
- window.requestChangeUrl = true;
- var ps = history.pushState;
- history.pushState = function(data, title, url){
- ps.apply(history, arguments);
- _nm.extraction.track();
- };
- }
- })(window.history);
- */
- /**
- * Código da loja
- * @type {String}
- */
- var nmStoreId = "ceatotem";
- /**
- * Obtém o pageType da página atual
- * @author Operação Neemu <operacao@neemu.com>
- * @param {Object} _nm
- * @return {String}
- */
- function nmGetPageType(_nm) {
- return '';
- };
- /**
- * Verifica se o usuário está logado
- * @author Operação Neemu <operacao@neemu.com>
- * @param {Object} _nm
- * @return {Boolean}
- */
- function nmUserIsLogged(_nm) {
- return false;
- }
- /**
- * Método para obter as informações do usuário logado
- * @author Operação Neemu <operacao@neemu.com>
- * @param {Object} _nm
- * @return {Object}
- * - loggedId
- * - email
- * - name
- */
- function nmGetUserInfo(_nm) {
- return {};
- };
- /**
- * Executa todo o processo de extração das informações das páginas
- * @author Operação Neemu <operacao@neemu.com>
- * @param {Object} _nm
- * @return {Void}
- */
- function nmExecuteExtraction(_nm) {
- switch (neemuGetPageType(_nm)) {
- case _nm.extraction.PAGE_HOME :
- _nm.extraction._setHomePageType();
- break;
- case _nm.extraction.PAGE_SEARCH :
- // busca neemu
- if (_nm.commons.isNeemuSearch()) {
- // define o tipo da página como "busca neemu"
- _nm.extraction._setSearchNeemuPageType();
- // processa as informações da página de busca
- _nm.extraction._setSearchInformation();
- }
- // busca do cliente
- else {
- // define o tipo da página como "busca do cliente"
- _nm.extraction._setSearchPageType();
- /**
- * Objeto com as informações de busca
- * @type {Object}
- * @example
- *
- * {
- * sort: 1,
- * pg: 1,
- * qty: 234,
- * qtyAnd: 234,
- * q: "notebook",
- * pIds: [
- * {
- * "1": "123"
- * },
- * {
- * "2": "456"
- * }
- * ...
- * ],
- * filters: [
- * {
- * "Categoria": "4938756"
- * },
- * {
- * "Marca": "Philco|Samsung"
- * }
- * ]
- * }
- */
- var searchInfo = {};
- // seta as informações da página de busca do cliente
- _nm.extraction._setSearchInformation(searchInfo);
- }
- break;
- case _nm.extraction.PAGE_PRODUCT :
- /**
- * Objeto com as informações de produto
- * @type {Object}
- * @example
- *
- * {
- * id: "1239876",
- * title: "IT Sabrina Sato Diva A105",
- * cName: "Óculos de Sol",
- * cId: "654",
- * stock: 1,
- * price: "420.00",
- * sPrice: "323.00",
- * img: "https://media.eotica.com.br/catalog/product/o/c/oculos-it-a105-c3-1-gs.jpg",
- * inst: [
- * {
- * qty: 4,
- * amount: "230.00"
- * }
- * ],
- * skus: [
- * {
- * stock: 1,
- * sPrice: "215.00",
- * sku: "2134876"
- * }
- * ]
- * }
- */
- var productInformation = {};
- extraction._setProductPageType();
- extraction._setProductInformation(productInformation);
- break;
- case _nm.extraction.PAGE_DEPARTMENT :
- extraction._setDepartmentPageType();
- var breadcrumb = commons.querySelectorAll('#informeAquiOSeletorDoBreadcrumb');
- for(var i = 1, len = breadcrumb.length; i < len; i++) {
- /**
- * Objeto com as informações do departamento
- * @type {Object}
- * @example
- *
- * {
- * cId: "213786",
- * tree: [
- * {
- * index: 1,
- * name: "Categoria 1"
- * },
- * {
- * index: 2,
- * name: "Categoria 2"
- * },
- * {
- * index: 3,
- * name: "Categoria 3"
- * }
- * ]
- * }
- */
- var departmentInformation = {};
- extraction._addDepartmentInformation(departmentInformation);
- }
- break;
- case _nm.extraction.PAGE_CHECKOUT :
- _nm.extraction._setCheckoutPageType();
- _nm.extraction._setCheckoutStep({
- name : ""
- });
- break;
- case _nm.extraction.PAGE_CHECKOUT_CART :
- _nm.extraction._setCartPageType();
- var products = [];
- for(var i = 0; i < products.length; i++) {
- _nm.extraction._addCartItem({
- id: "",
- sku: "",
- price: _nm.commons.formatCurrency(""),
- qty: 1
- });
- }
- break;
- case _nm.extraction.PAGE_CHECKOUT_CONFIRMATION :
- _nm.extraction._setCheckoutConfirmationPageType();
- var products = [];
- for(var i = 0, len_i = products.length; i < len_i; i++) {
- _nm.extraction._addOrderItem({
- id: '',
- sku: '',
- qty: 1,
- price: _nm.commons.formatCurrency('')
- });
- }
- break;
- }
- }
- /**
- * Configurações da loja
- */
- var conf = {
- store : {
- id : nmStoreId,
- host : nmStoreId + ".com.br",
- logServer : "laas.neemu.com"
- },
- parse : function(_nm) {
- // verifica se o usuário está logado
- if (nmUserIsLogged(_nm)) {
- // seta as informações do usuário logado
- _nm.extraction._setUser(nmGetUserInfo(_nm));
- }
- nmExecuteExtraction(_nm);
- window.neemuPlugin = window.neemuPlugin || {};
- window.neemuPlugin.recommendation = {
- recList: [{
- type: 'viu-viu',
- div: 'mais-procurados',
- gid: '1'
- }],
- recListReserve: [{
- type: 'populares',
- gid: '1'
- }]
- };
- _nm.commons.loadFile('http://raas.neemu.com/cea/rec.js');
- }
- };
- _nm.conf=conf;window._nm=_nm;})(window,document, undefined,window.jQuery);_nm.extraction.init(_nm.conf);
Add Comment
Please, Sign In to add comment