/*! * jQuery Smart Cart v3.0.1 * The smart interactive jQuery Shopping Cart plugin with PayPal payment support * http://www.techlaboratory.net/smartcart * * Created by Dipu Raj * http://dipuraj.me * * Licensed under the terms of the MIT License * https://github.com/techlab/SmartCart/blob/master/LICENSE * * New features: save to URL, shipping evaluation and * integration with AICS-ERP https://www.aics.com.br - 2020 * Marco Polezze - marco@bf.net.br */ // list of variables that will be filled in when pages were refreshed var CurCar=""; var CurZipCar=""; var CurValZipCar=""; var StartCart=""; var ValProductCart=""; var CookStore=""; var SavingCart=false; // some new helper functions function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i 0) ) { var ajaxSettings = $.extend(true, {}, { url: mi.options.ZipCodeURL + "?cook=" + getCookie("cooksessao") + "&zip="+mi.options.ZipCode+"&free="+mi.options.ZipFree+"&val="+ValProductCart+"&loc="+mi.options.ZipPlace+"&rnd="+Math.random(), type: "GET", beforeSend: function(){ mi.cart_element.addClass('calculando'); }, error: function(jqXHR, status, message){ mi.cart_element.removeClass('calculando'); mi._logError(message); }, success: function(res){ mi.cart_element.removeClass('calculando'); mi.options.ZipCodePrice = res * 1; if ((mi.options.ZipCodePrice==999.99)) { alert("Verifique seu CEP, Correio informa como inexistente!"); mi.options.ZipCodePrice=0; } mi._hasCartChange(); $('.nav-offcanvas').addClass('open'); } }, mi.options.submitSettings.ajaxSettings); $.ajax(ajaxSettings); } else if ((mi.options.ZipCode=="") && !mi.options.ZipFree) { //alert("O CEP precisa ser informado, por favor"); } else { alert("Adicione algum produto ao carrinho para calcular o frete, por favor");} } // EvaluateShip ;(function ($, window, document, undefined) { "use strict"; // Default options var defaults = { cart: [], // initial products on cart resultName: 'cart_list', // Submit name of the cart parameter theme: 'default', // theme for the cart, related css need to include for other than default theme combineProducts: true, // combine similar products on cart highlightEffect: true, // highlight effect on adding/updating product in cart cartItemTemplate: '

{product_name}

{product_desc}

', cartItemQtyTemplate: '{display_price} × {display_quantity} = {display_amount}', productContainerSelector: '.sc-product-item', productElementSelector: '*', // input, textarea, select, div, p addCartSelector: '.sc-add-to-cart', ZipCodeSelector: '.submit-zip', // button ZipCode: '', ZipFree: false, ZipPlace: '', // ZipCodeURL: '/bin/CalcFrete.pas', // callback ZipCodePrice: 0, // shipping value zipSetting : { ZipCodeParam: 'shippingZip', // form field ProdInStore: 'product_store', // form field }, paramSettings : { // Map the paramters productPrice: 'product_price', productQuantity: 'product_quantity', productName: 'product_name', productStore: 'product_store', productId: 'product_id', }, lang: { // Language variables cartTitle: "", checkout: 'FINALIZAR COMPRA', clear: 'Limpar carrinho', subtotal: 'Valor total:', shiptotal: 'Frete:', cartRemove:'×', cartEmpty: 'Carrinho vazio' }, submitSettings: { submitType: 'form', // form, paypal, ajax ajaxURL: '/bin/CriaCarrinho.pas', // Ajax submit URL ajaxSettings: {} // Ajax extra settings for submit call }, currencySettings: { locales: 'pt-br', // A string with a BCP 47 language tag, or an array of such strings currencyOptions: { style: 'currency', currency: 'BRL', currencyDisplay: 'symbol' } // extra settings for the currency formatter. Refer: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString }, toolbarSettings: { showToolbar: true, showCheckoutButton: true, showClearButton: false, showCartSummary:true, checkoutButtonStyle: 'default', // default, paypal, image checkoutButtonImage: '', // image for the checkout button toolbarExtraButtons: [] // Extra buttons to show on toolbar, array of jQuery input/buttons elements }, debug: false }; // The plugin constructor function SmartCart(element, options) { // Merge user settings with default, recursively this.options = $.extend(true, {}, defaults, options); // Cart array this.cart = []; // Cart element this.cart_element = $(element); // Call initial method this.init(); } $.extend(SmartCart.prototype, { init: function () { // Set the elements this._setElements(); // Add toolbar this._setToolbar(); // Assign plugin events this._setEvents(); // Set initial products var mi = this; var stor=GetCart(mi); if ((stor!==null) && (stor!=="") && (stor!=="{}") && (stor!=="NOK")) { //alert(stor); var load = $.parseJSON(stor); $.each( load, function( i, n ) { mi._addToCart(n,false); }); } $(this.options.cart).each(function(i, p) { p = mi._addToCart(p); }); this.options.ZipCode = CurZipCar; this.options.ZipCodePrice = CurValZipCar *1; // Call UI sync this._hasCartChange(); }, // PRIVATE FUNCTIONS /* * Set basic elements for the cart */ _setElements: function () { // The element store all cart data and submit with form var cartListElement = $(''); this.cart_element.append(cartListElement); // Set the cart main element this.cart_element.addClass('panel panel-default sc-cart sc-theme-' + this.options.theme); this.cart_element.append('
' + this.options.lang.cartTitle + ' 0
'); this.cart_element.append('
'); }, /* * Set the toolbar for the cart */ _setToolbar: function () { if(this.options.toolbarSettings.showToolbar !== true) { return false; } var toolbar = $('
').addClass('panel-footer sc-toolbar'); var toolbarButtonPanel = $('
'); var toolbarSummaryPanel = $('
'); // Checkout Button if(this.options.toolbarSettings.showCheckoutButton){ var btnCheckout = ''; switch(this.options.toolbarSettings.checkoutButtonStyle){ case 'paypal': btnCheckout = ''; break; case 'image': btnCheckout = ''; break; default: btnCheckout = ' '; break; } toolbarButtonPanel.append(btnCheckout); } // Clear Button if(this.options.toolbarSettings.showClearButton){ var btnClear = $(''); elmMain.attr('data-unique-key', p.unique_key); elmMain.append(this._formatTemplate(this.options.cartItemTemplate, p)); var itemSummary = '
' + this._getMoneyFormatted(p[this.options.paramSettings.productPrice]) + ''; itemSummary += ' × '; itemSummary += ' = ' + this._getMoneyFormatted(productAmount) + '
'; elmMain.append(itemSummary); cartList.append(elmMain); } // Apply the highlight effect if(this.options.highlightEffect === true){ elmMain.addClass('sc-highlight'); setTimeout(function() { elmMain.removeClass('sc-highlight'); },500); } this._hasCartChange(); //this._getShippingDetails($(this)); // 4 //this._getCartSubtotal(); //EvaluateShip(mi); SaveCart(JSON.stringify(this.cart)); }, /* * Handles the changes in the cart */ _hasCartChange: function () { $('.sc-cart-count',this.cart_element).text(this.cart.length); $('.sc-cart-count').text(this.cart.length); // In case to use 'cart.length' in another div - In navbar for example. $('.sc-cart-subtotal',this.element).text(this._getCartSubtotal()); $('.sc-cart-shiptotal',this.element).text(this._getMoneyFormatted(this.options.ZipCodePrice)); if(this.cart.length === 0){ $('.sc-cart-item-list',this.cart_element).empty().append($('
' + this.options.lang.cartEmpty + '
')); $(this.options.productContainerSelector).removeClass('sc-added-item'); $('.sc-cart-checkout, .sc-cart-clear').addClass('disabled'); // Trigger "cartEmpty" event this._triggerEvent("cartEmpty"); }else{ $('.sc-cart-item-list > .sc-cart-empty-msg',this.cart_element).remove(); $('.sc-cart-checkout, .sc-cart-clear').removeClass('disabled'); } // Update cart value to the cart hidden element $('#' + this.options.resultName, this.cart_element).val(JSON.stringify(this.cart)); }, /* * Calculates the cart subtotal */ _getCartSubtotal: function () { var mi = this; var subtotal = 0; $.each(this.cart, function( i, p ) { if(mi._getValidateNumber(p[mi.options.paramSettings.productPrice])){ subtotal += (p[mi.options.paramSettings.productPrice] - 0) * (p[mi.options.paramSettings.productQuantity] - 0); } }); ValProductCart = subtotal; if (mi.options.ZipCodePrice>0) {subtotal=subtotal+mi.options.ZipCodePrice;} return this._getMoneyFormatted(subtotal); }, /* * Cart submit functionalities */ _submitCart: function () { var mi = this; var formElm = this.cart_element.parents('form'); if(!formElm){ this._logError( 'Form not found to submit' ); return false; } switch(this.options.submitSettings.submitType){ case 'ajax': var ajaxURL = (this.options.submitSettings.ajaxURL && this.options.submitSettings.ajaxURL.length > 0) ? this.options.submitSettings.ajaxURL : formElm.attr( 'action' ); //alert(ajaxURL); var ajaxSettings = $.extend(true, {}, { url: ajaxURL, type: "POST", data: formElm.serialize(), beforeSend: function(){ mi.cart_element.addClass('loading'); }, error: function(jqXHR, status, message){ mi.cart_element.removeClass('loading'); mi._logError(message); }, success: function(res){ mi.cart_element.removeClass('loading'); mi._triggerEvent("cartSubmitted", [mi.cart]); mi._clearCart(); } }, this.options.submitSettings.ajaxSettings); $.ajax(ajaxSettings); break; case 'paypal': formElm.children('.sc-paypal-input').remove(); // Add paypal specific fields for cart products $.each(this.cart, function( i, p ) { var itemNumber = i + 1; formElm.append('') .append('') .append('') .append(''); }); formElm.submit(); this._triggerEvent("cartSubmitted", [this.cart]); break; default: formElm.submit(); this._triggerEvent("cartSubmitted", [this.cart]); break; } return true; }, // HELPER FUNCTIONS /* * Get the content of an HTML element irrespective of its type */ _getContent: function (elm) { if(elm.is(":checkbox, :radio")){ return elm.is(":checked") ? elm.val() : ''; } else if (elm.is("[value], select")){ return elm.val(); } else if (elm.is("img")){ return elm.attr('src'); } else { return elm.text(); } return ''; }, /* * Compare equality of two product objects */ _isObjectsEqual: function (o1, o2) { if (Object.getOwnPropertyNames(o1).length !== Object.getOwnPropertyNames(o2).length) { return false; } for (var p in o1) { if(p === 'unique_key' || p === this.options.paramSettings.productQuantity) { continue; } if (typeof o1[p] === typeof undefined && typeof o2[p] === typeof undefined) { continue; } if (o1[p] !== o2[p]){ return false; } } return true; }, /* * Format money */ _getMoneyFormatted: function (n) { n = n - 0; return Number(n.toFixed(2)).toLocaleString(this.options.currencySettings.locales, this.options.currencySettings.currencyOptions); }, /* * Get the value of an element and empty value if the element not exists */ _getValueOrEmpty: function (v) { return (v && typeof v !== typeof undefined) ? v : ''; }, /* * Validate Number */ _getValidateNumber: function (n) { n = n - 0; if(n && n > 0){ return true; } return false; }, /* * Small templating function */ _formatTemplate: function (t, o){ var r = t.split("{"), fs = ''; for(var i=0; i < r.length; i++){ var vr = r[i].substring(0, r[i].indexOf("}")); if(vr.length > 0){ fs += r[i].replace(vr + '}', this._getValueOrEmpty(o[vr])); }else{ fs += r[i]; } } return fs; }, /* * Event raiser */ _triggerEvent: function (name, params) { // Trigger an event var e = $.Event(name); this.cart_element.trigger(e, params); if (e.isDefaultPrevented()) { return false; } return e.result; }, /* * Get unique key */ _getUniqueKey: function () { var d = new Date(); return d.getTime(); }, /* * Log message to console */ _logMessage: function (msg) { if(this.options.debug !== true) { return false; } // Log message console.log(msg); }, /* * Log error to console and terminate execution */ _logError: function (msg) { if(this.options.debug !== true) { return false; } // Log error $.error(msg); }, // PUBLIC FUNCTIONS /* * Public function to sumbit the cart */ submit: function () { this._submitCart(); }, /* * Public function to clear the cart */ clear: function () { this._clearCart(); } }); // Wrapper for the plugin $.fn.smartCart = function(options) { var args = arguments; var instance; if (options === undefined || typeof options === 'object') { return this.each( function() { if ( !$.data( this, "smartCart") ) { $.data( this, "smartCart", new SmartCart( this, options ) ); } }); } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') { instance = $.data(this[0], 'smartCart'); if (options === 'destroy') { $.data(this, 'smartCart', null); } if (instance instanceof SmartCart && typeof instance[options] === 'function') { return instance[options].apply( instance, Array.prototype.slice.call( args, 1 ) ); } else { return this; } } }; })(jQuery, window, document);