Index: src/templates/Honeygrid/javascript/engine/widgets/cart_handler.js
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- src/templates/Honeygrid/javascript/engine/widgets/cart_handler.js	(revision 5b07020c47f9068ef915014f759b70d85ab8a802)
+++ src/templates/Honeygrid/javascript/engine/widgets/cart_handler.js	(date 1551282767000)
@@ -1,5 +1,5 @@
 /* --------------------------------------------------------------
- cart_handler.js 2018-10-17
+ cart_handler.js 2019-02-27
  Gambio GmbH
  http://www.gambio.de
  Copyright (c) 2018 Gambio GmbH
@@ -30,7 +30,7 @@
 
 		'use strict';
 
-// ########## VARIABLE INITIALIZATION ##########
+		// ########## VARIABLE INITIALIZATION ##########
 
 		var $this = $(this),
 			$body = $('body'),
@@ -70,7 +70,7 @@
 				attributImagesSwiper: false,
 				// Trigger the attribute images to this selectors
 				triggerAttrImagesTo: '#product_image_swiper, #product_thumbnail_swiper, '
-				+ '#product_thumbnail_swiper_mobile',
+					+ '#product_thumbnail_swiper_mobile',
 				// Class that gets added to the button on processing
 				processingClass: 'loading',
 				// Duration for that the success or fail class gets added to the button
@@ -103,10 +103,12 @@
 			},
 			options = $.extend(true, {}, defaults, data),
 			module = {},
-			mobile = $(window).width() <= 767;
+			mobile = $(window).width() <= 767,
+			changeListenerSet = false,
+			cookieObj;
 
 
-// ########## HELPER FUNCTIONS ##########
+		// ########## HELPER FUNCTIONS ##########
 
 		/**
 		 * Helper function that updates the button
@@ -184,14 +186,20 @@
 						break;
 				}
 			});
-			
+
 			// Dis- / Enable the buttons
-			if (disableButtons) {
-				var $buttons = $form.find(options.cartButtons);
-				if (data.success) {
+			if(disableButtons)
+			{
+				var $buttons  = $form.find(options.cartButtons);
+
+				if(data.success)
+				{
 					$buttons.removeClass('inactive');
 					$buttons.removeClass('btn-inactive');
-				} else {
+				}
+
+				else
+				{
 					$buttons.addClass('inactive');
 					$buttons.addClass('btn-inactive');
 				}
@@ -207,7 +215,7 @@
 					$errorField
 						.addClass('hidden')
 						.hide();
-					
+
 					if (showNoCombiSelectedMesssage
 						&& data.content.messageNoCombiSelected !== undefined
 						&& data.content.messageNoCombiSelected) {
@@ -223,8 +231,96 @@
 					}
 				}
 			}
-			
+
 			$window.trigger(jse.libs.template.events.STICKYBOX_CONTENT_CHANGE());
+
+			if(changeListenerSet === false && (changeListenerSet = true))
+			{
+				let addToCartWithQuantity = [], hiddenInput;
+
+			//	Adding every add to cart button that has a quantity input
+				$('button[name="btn-add-to-cart"]').parent().parent().each(function(index, row)
+				{
+				//	Quantity inputs are hidden if disabled
+					hiddenInput = $(row).find('input[type="hidden"]');
+
+					if(hiddenInput.length === 0)
+
+						addToCartWithQuantity.push($(row).find('input[name="products_qty"]'));
+				});
+
+			//	Setting OnChange listener on items with a selectable quantity
+				if(addToCartWithQuantity.length > 0)
+
+					addToCartWithQuantity.forEach(function(quantity)
+					{
+						quantity.bind('change', _quantityChange);
+					});
+
+			//	Adding prototype method for hash generation on strings
+				if(typeof String.prototype.hashCode === 'undefined')
+
+					String.prototype.hashCode = function()
+					{
+						let hash = 0;
+
+						if(this.length === 0)
+
+							return hash;
+
+						for(let index = 0, char = this.charCodeAt(index); index < this.length; char = this.charCodeAt(++index))
+						{
+							hash = ((hash << 5) - hash) + char;
+							hash = hash & hash;
+						}
+
+						return hash;
+					};
+
+				cookieObj = document.cookie.length && document.cookie.indexOf('category-quantities') !== -1
+						  ? JSON.parse((document.cookie + ';').match(new RegExp('category-quantities=.*;'))[0].split(/=|;/)[1])
+						  : {};
+			}
+
+			let productForm = $('form.form-horizontal.js-product-form.product-info'), productName, productPrice, hash;
+
+			if(productForm.length !== 0)
+			{
+				productName  = productForm.find('h1').html().trim();
+				productPrice = productForm.find('div.current-price-container').html().trim().match(/^[^\d]*([0-9,.]+).*$/ms)[1].replace(/,/g, '.') - 0;
+				hash         = (productName + productPrice).hashCode();
+
+				if(typeof cookieObj[hash] !== 'undefined')
+
+					$('#attributes-calc-quantity').val(cookieObj[hash]);
+			}
+		};
+
+		var _quantityChange = function()
+		{
+			let value = $(this).val(), row, productName, productPrice;
+
+		//	only numbers and "." are processed
+			if(value.match(/^[0-9.]+$/) !== null)
+			{
+			//	converting from string to int/double
+				value -= 0;
+
+			//	finding the name and price of the product
+				row          = $(this).parent().parent().parent().parent().parent();
+				productName  = row.find('a.product-url').html().trim();
+				productPrice = row.find('span.current-price-container').html().trim().match(/^[^\d]*([0-9,.]+).*$/ms)[1].replace(/,/g, '.') - 0;
+
+
+			//	generating cookie expire string (30min)
+				let date = new Date, expires;
+				date.setTime(date.getTime() + ((1 / 48) * 24 * 60 * 60 * 1000));
+				expires  = "; expires=" + date.toGMTString();
+
+				cookieObj[(productName + productPrice).hashCode()] = value;
+
+				document.cookie = "category-quantities=" + JSON.stringify(cookieObj) + expires + "; path=/";
+			}
 		};
 
 		/**
@@ -239,44 +335,44 @@
 		 */
 		var _addToSomewhere = function(data, $form, url, $button) {
 			function callback() {
-                jse.libs.xhr.post({url: url, data: data}, true).done(function(result) {
-                    try {
-                        // Fill the page with the result from the ajax
-                        _stateManager(result, $form, false);
+				jse.libs.xhr.post({url: url, data: data}, true).done(function(result) {
+					try {
+						// Fill the page with the result from the ajax
+						_stateManager(result, $form, false);
 
-                        // If the AJAX was successful execute
-                        // a custom functionality
-                        if (result.success) {
-                            switch (result.type) {
-                                case 'url':
-                                    if (result.url.substr(0, 4) !== 'http') {
-                                        location.href = jse.core.config.get('appUrl') + '/' + result.url;
-                                    } else {
-                                        location.href = result.url;
-                                    }
+						// If the AJAX was successful execute
+						// a custom functionality
+						if (result.success) {
+							switch (result.type) {
+								case 'url':
+									if (result.url.substr(0, 4) !== 'http') {
+										location.href = jse.core.config.get('appUrl') + '/' + result.url;
+									} else {
+										location.href = result.url;
+									}
 
-                                    break;
-                                case 'dropdown':
-                                    $body.trigger(jse.libs.template.events.CART_UPDATE(), [true]);
-                                    break;
-                                case 'layer':
-                                    jse.libs.template.modal.info({title: result.title, content: result.msg});
-                                    break;
-                                default:
-                                    break;
-                            }
-                        }
-                    } catch (ignore) {
-                    }
-                    _addButtonState($button, '-success');
-                }).fail(function() {
-                    _addButtonState($button, '-fail');
-                }).always(function() {
-                    // Reset the busy flag to be able to perform
-                    // further AJAX requests
-                    busy = false;
-                });
-            }
+									break;
+								case 'dropdown':
+									$body.trigger(jse.libs.template.events.CART_UPDATE(), [true]);
+									break;
+								case 'layer':
+									jse.libs.template.modal.info({title: result.title, content: result.msg});
+									break;
+								default:
+									break;
+							}
+						}
+					} catch (ignore) {
+					}
+					_addButtonState($button, '-success');
+				}).fail(function() {
+					_addButtonState($button, '-fail');
+				}).always(function() {
+					// Reset the busy flag to be able to perform
+					// further AJAX requests
+					busy = false;
+				});
+			}
 
 			if (!busy) {
 				// only execute the ajax
@@ -291,7 +387,7 @@
 		};
 
 
-// ########## EVENT HANDLER ##########
+		// ########## EVENT HANDLER ##########
 
 		/**
 		 * Handler for the submit form / click
@@ -349,9 +445,9 @@
 				}
 
 				ajax = jse.libs.xhr.get({
-					                        url: options.checkUrl + module,
-					                        data: formdata
-				                        }, true).done(function(result) {
+					url: options.checkUrl + module,
+					data: formdata
+				}, true).done(function(result) {
 					_stateManager(result, $form, true, showNoCombiSelectedMesssage);
 					$this.removeClass('loading');
 
@@ -378,7 +474,7 @@
 								$form.attr('action', options.priceOfferUrl).attr('method', options.priceOfferMethod);
 								$form.off('submit');
 								$form.submit();
-								
+
 								return;
 							default:
 								setTimeout(function() {
@@ -406,21 +502,21 @@
 				});
 			}
 		};
-		
+
 		/**
 		 * Keyup handler for quantity input field
-		 * 
+		 *
 		 * @param e
 		 * @private
 		 */
 		var _keyupHandler = function(e) {
 			clearTimeout(timeout);
-			
+
 			timeout = setTimeout(function() {
 				_submitHandler.call(this, e)
 			}.bind(this), 300);
 		};
-		
+
 		/**
 		 * Event handler for the add to cart button, that shows or hides the throbber.
 		 */
@@ -428,14 +524,14 @@
 			const $btn = $(this);
 			const $btnFake = $this.find(".btn-add-to-cart-fake");
 			let formReady = true;
-			
+
 			$(".properties-selection-form select").each(function() {
 				const val = $(this).val();
 				if (!val || val < 1) {
 					formReady = false;
 				}
 			});
-			
+
 			if (formReady) {
 				$btn.hide();
 				$btnFake.show()
@@ -443,7 +539,7 @@
 					.prepend('<span class="throbbler"></span>');
 			}
 		};
-		
+
 		/**
 		 * Cart dropdown oben event handler for the body.
 		 */
@@ -452,15 +548,15 @@
 			const $btnFake = $this.find(".btn-add-to-cart-fake");
 			const fakeOrigLabel = $btnFake.html();
 			const productCount = $(".cart-products-count").html();
-			
+
 			const textPhrases = JSON.parse($('#product-details-text-phrases').html());
 			console.log(textPhrases['productsInCartSuffix']);
-			
+
 			$btnFake.html("<i class=\"fa fa-check\"></i> " + parseInt(productCount)
 				+ textPhrases['productsInCartSuffix'])
 				.prop("disabled", true)
 				.addClass("btn-buy-complete");
-			
+
 			setTimeout(function() {
 				$btnFake.html(fakeOrigLabel)
 					.removeClass("btn-buy-complete")
@@ -469,7 +565,7 @@
 				$(".throbbler", $btn).remove();
 				$btn.show();
 			}, 5000);
-			
+
 			if (mobile && $(".btn-go-to-cart").length == 0) {
 				const $btnGoTocart = $("<a></a>").addClass("btn btn-block btn-primary btn-lg btn-go-to-cart")
 					.attr("href", "shopping_cart.php")
@@ -479,7 +575,7 @@
 		};
 
 
-// ########## INITIALIZATION ##########
+		// ########## INITIALIZATION ##########
 
 		/**
 		 * Init function of the widget
@@ -488,7 +584,7 @@
 		module.init = function(done) {
 
 			var $forms = $this.find('form');
-			
+
 			if (options.page === 'product-info') {
 				$forms.find("[name=btn-add-to-cart]").on('mouseup', _addToCartThrobberHandler);
 				$("body").on('CART_DROPDOWN_OPEN', _cartDropdownOpenHandler);
@@ -509,7 +605,7 @@
 			$forms.not('.no-status-check').each(function() {
 				_submitHandler.call($(this));
 			});
-			
+
 			done();
 		};
 
