PageSourceSearch

https://www.scalabad.no/scripts4.0/viewmodels/variant/productvariantmatrixview.js

js scalabad.no collected 2026-10-08 01:16:08 UTC 22,103 bytes, 540 lines download raw bytes

1mcWeb.productVariantMatrix = new function () {
2    var $ = jQuery;
3    var self = this;
4
5    self.service = new WebApiService("ProductVariant");
6    self.productListService = new WebApiService("ProductList");
7
8    self.bindingsApplied = false;
9    this.events = {
10        onNewOrderbookDateAdded: "mcWeb.productVariantMatrix.onNewOrderbookDateAdded",
11        onOrderbookDateChanged: "mcWeb.productVariantMatrix.onOrderbookDateChanged",
12        onDoAddToCart: "mcWeb.productVariantMatrix.onDoAddToCart",
13        onShowNextItem: "mcWeb.productVariantMatrix.onShowNextItem",
14        onGoToNextPage: "mcWeb.productVariantMatrix.onGoToNextPage"
15    };
16    self.pubsubDone = false;
17
18    self.loadExplicit = function(plid, useOrderbook) {
19        self.plid = plid;
20        self.openedForOrderbook = useOrderbook;
21
22        var myElement = jQuery('.main-container .WebPubElement[data-plid=' + plid + ']');
23        var nextElement = myElement.next('.WebPubElement[data-plid]');
24        var prevElement = myElement.prev('.WebPubElement[data-plid]');
25        var currentPlid = 0;
26        var nextPlid = 0;
27        var prevPlid = 0;
28
29        if (nextElement.length > 0)
30            nextPlid = nextElement.data('plid');
31
32        if (prevElement.length > 0)
33            prevPlid = prevElement.data('plid');
34
35        currentPlid = myElement.data('plid');
36
37        $('#UpdateIcon').show();
38        var url = "/WebPages/D4/Product/ProductVariantMatrixView.aspx";
39        if (useOrderbook != undefined && useOrderbook) {
40            url = url + "?orderbook=1&nextplid=" + nextPlid + "&prevplid=" + prevPlid + "&currentplid=" + currentPlid;
41
42        } else {
43            url = url + "?nextplid=" + nextPlid + "&prevplid=" + prevPlid + "&currentplid=" + currentPlid;
44        }
45
46        $("#lightbox-placeholder").load(url, function () {
47
48            $('#UpdateIcon').hide();
49            if ($("#product-variant-matrix").length < 1) {
50                return;
51            }//Module not active
52            self.activateViewExplicit(plid);
53        });
54
55        if (!self.pubsubDone) {
56            self.registerSubscriptions();
57        }
58    };
59
60    self.loadVariantMatrixQuantity = function (plid, useOrderbook) {
61        self.plid = plid;
62        self.openedForOrderbook = useOrderbook;
63
64        var myElement = jQuery('.main-container .WebPubElement[data-plid=' + plid + ']');
65        var nextElement = myElement.next('.WebPubElement[data-plid]');
66        var prevElement = myElement.prev('.WebPubElement[data-plid]');
67        if (nextElement.length > 0)
68            nextPlid = nextElement.data('plid');
69
70        if (prevElement.length > 0)
71            prevPlid = prevElement.data('plid');
72
73        currentPlid = myElement.data('plid');
74
75        $('#UpdateIcon').show();
76        var url = "/WebPages/D4/Variant/ProductVariantMatrixViewQuantity.aspx?plid=" + plid;
77
78        $("#lightbox-placeholder").load(url, function () {
79
80            $('#UpdateIcon').hide();
81            if ($("#product-variant-matrix").length < 1) {
82                return;
83            }//Module not active
84            self.activateVariantMatrixQuantityViewExplicit(plid);
85        });
86    };
87
88    self.registerSubscriptions = function() {
89        PubSub.subscribe(mcWeb.ajaxRenderEngine.events.onFieldContentChanged, self.updateAmountDefaults);
90        PubSub.subscribe(mcWeb.productVariantMatrix.events.onShowNextItem,
91            function(message, item) {
92                mcWeb.productVariantMatrix.loadExplicit(self.nextPlid, self.openedForOrderbook);
93            });
94        PubSub.subscribe(mcWeb.productVariantMatrix.events.onNewOrderbookDateAdded,
95            function(data, message) {
96                self.activateViewExplicit(self.plid);
97            });
98        self.pubsubDone = true;
99    };
100
101    self.load = function () {
102        $('#UpdateIcon').show();
103
104        $("#lightbox-placeholder").load("/WebPages/D4/Product/ProductVariantMatrixView.aspx", function () {
105
106            if ($("#product-variant-matrix").length < 1) {
107                $('#UpdateIcon').hide();
108                return;
109            }//Module not active
110
111            self.activateView();
112        });
113        if (!self.pubsubDone) {
114            self.registerSubscriptions();
115        }
116    };
117
118    self.contentChangedPubSubRegistered = false;
119
120    self.loadFromList = function (plid) {
121        $('#UpdateIcon').show();
122        self.currentPlid = plid;
123
124
125        if (!self.pubsubDone) {
126            self.registerSubscriptions();
127        }
128
129        $("#lightbox-placeholder").load("/WebPages/D4/Product/ProductVariantMatrixView.aspx", function () {
130
131            if ($("#product-variant-matrix").length < 1) {
132                $('#UpdateIcon').hide();
133                return;
134            }//Module not active
135
136            self.activateView();
137        });
138    };
139
140    self.activateViewExplicit = function (plid) {
141        var data = { motherProduktLagerId: plid, allowNonVariants: true };
142        self.service.GetAction("GetProductOrVariantChildList", data).then(function (result) {
143
144            //we must use data from the GetProductVariantChildList to update the amount-boxes
145
146            self.variantList = result;
147
148            if (result != null) {
149                self.cartAmounts = result.CartAmounts;
150                if (self.bindingsApplied) {
151                    ko.cleanNode(document.getElementById("product-variant-matrix"))
152                }
153                self.vm = new viewModelVariants(result);
154                ko.applyBindings(self.vm, document.getElementById("product-variant-matrix"));
155                self.bindingsApplied = true;
156            }
157            PubSub.publish(mcWeb.lightbox.events.onShowLightbox, { css: 'matrix-popup', variantData: result });
158        });
159
160    };
161
162    self.activateVariantMatrixQuantityViewExplicit = function (plid) {
163        var data = { motherProduktLagerId: plid, allowNonVariants: true };
164        self.service.GetAction("GetProductOrVariantChildList", data).then(function (result) {
165
166            //we must use data from the GetProductVariantChildList to update the amount-boxes
167
168            self.variantList = result;
169
170            if (result != null) {
171                if (self.bindingsApplied) {
172                    ko.cleanNode(document.getElementById("product-variant-matrix"))
173                }
174                self.vm = new viewModelVariants(result);
175                ko.applyBindings(self.vm, document.getElementById("product-variant-matrix"));
176                self.bindingsApplied = true;
177            }
178            PubSub.publish(mcWeb.lightbox.events.onShowLightbox, { css: 'matrix-popup product-variant-matrix-modal', variantData: result });
179        });
180
181    };
182
183
184    self.addToCartAndNavigateNext = function() {
185        self.addToCartAndNavigate(self.plid, true);
186    };
187
188    self.addToCartAndNavigatePrevious = function() {
189        self.addToCartAndNavigate(self.plid, false);
190    };
191
192    self.addToCartAndNavigate = function (currentPlid, goToNext) {
193        var myElement = jQuery('.main-container .WebPubElement[data-plid=' + currentPlid + ']');
194        var nextElement = myElement.next('.WebPubElement[data-plid]');
195        var prevElement = myElement.prev('.WebPubElement[data-plid]');
196
197        var elementToGoTo = goToNext ? nextElement[0] : prevElement[0];
198
199            if (myElement.length > 0 && elementToGoTo) {
200                var pubEvents = self.vm && (self.vm.ShowAntallDefaultZero() === true || self.vm.ShowAntallDefaultZeroInVariantMatrix())
201                    ? mcWeb.productVariantMatrix.events.onDoAddToCart
202                    : mcWeb.productVariantMatrix.events.onGoToNextPage;
203
204                PubSub.publish(pubEvents, $(elementToGoTo).data('plid'));
205        }
206    };
207
208    self.updateAmountDefaults = function(message, options) {
209        if (options != undefined && options != null && options.AreaName == "OrderBookMatrix") {
210            if (self.cartAmounts != undefined && self.cartAmounts != null && self.variantList != undefined && self.variantList != null) {
211
212                self.cartAmounts.Carts.forEach(function(cartid, index) {
213                    self.variantList.VariantChilds.forEach(function(item, productindex) {
214                        var amountBoxes = jQuery('.WebPubElement[data-area="OrderBookMatrix"] input[data-cart=' + cartid + '][data-plid=' + item.ProduktLagerId + ']');
215
216                        if (amountBoxes.length <= 0)
217                            return;
218
219                        var amountBox = amountBoxes[0];
220
221                        if (productindex >= self.cartAmounts.ValuesArray[index].length ||
222                            jQuery(amountBox).data('plid') != self.variantList.VariantChilds[productindex].ProduktLagerId)
223                            return;
224                            
225                        var cartAmount = self.cartAmounts.ValuesArray[index][productindex];
226                        if (cartAmount == null || cartAmount == undefined)
227                            return;
228
229                        var box = jQuery(amountBox);
230                        box.data('origval', cartAmount.Amount);
231                        box.data('cartrowid', cartAmount.CartRowId);
232
233                        amountBox.value = cartAmount.Amount;
234                            
235                    });
236                });
237                //iterate the first boxes for each row, then call the script that calculates the sum for that row
238                var cartid = self.cartAmounts.Carts[0];
239                var amountBoxes = jQuery('.WebPubElement[data-area="OrderBookMatrix"] input[data-cart=' + cartid+']');//gets all amount boxes for one cart
240                amountBoxes.each(function(productindex, item) {
241                    mcWeb.productVariantMatrix.updateQuantitySum(jQuery(item));
242                });
243                
244            }
245            PubSub.publish(mcWeb.lightbox.events.contentChanged);
246            $("#product-variant-matrix .qty-container input[type='text']").attr("autocomplete", "off");
247
248            $("#product-variant-matrix .qty-container input[type='text']").on("focus", function () {
249                $("#product-variant-matrix .qty-container input[data-cart='" + $(this).attr("data-cart") + "']").parent().addClass("active-col");
250                $(this).parent().addClass("active-cell");
251            });
252            $("#product-variant-matrix .qty-container input[type='text']").on("blur", function () {
253                $("#product-variant-matrix .qty-container input[data-cart='" + $(this).attr("data-cart") + "']").parent().removeClass("active-col");
254                $(this).parent().removeClass("active-cell");
255            });
256            $('#product-variant-matrix .orderbook-area button').prop('tabIndex', -1);
257
258        }
259    };
260
261    self.updateQuantitySum = function(me) {
262        var parentDiv = me.parents(".qty-carts");
263        if (parentDiv.length > 0) {
264            var amnts = parentDiv.find("input.quantity-desimals");
265            var summaryBox = parentDiv.find("input.summary");
266            if (amnts.length > 0 && summaryBox.length > 0) {
267                var total = 0.0;
268                for (var i = 0; i < amnts.length; i++) {
269                    var amntbx = amnts[i];
270                    var amntnmb = parseFloat(amntbx.value);
271                         
272                    total += amntnmb;
273                }
274
275                summaryBox.val(total);
276            }
277        }
278
279    };
280
281	self.activateView = function () {
282		var plid = $('#variant-matrix-button').data('plid');
283        if (self.plid != undefined && self.plid > 0) {
284            plid = self.plid;
285        }
286		var data = { motherProduktLagerId: plid };
287		self.service.GetAction("GetProductVariantChildList", data).then(function (result) {
288
289			if (result !== null) {
290                ko.applyBindings(new viewModelVariants(result), document.getElementById("product-variant-matrix"));
291			} else {
292				//Hide list and show not found label
293				$('#product-variant-matrix > fieldset').hide();
294				$('#product-variant-matrix-notfound').show();
295			}
296            $('#UpdateIcon').hide();
297			PubSub.publish(mcWeb.lightbox.events.onShowLightbox, { css: 'matrix-popup' });
298		});
299	};
300
301	self.validateValue = function (obj) {
302		if (isNaN(obj.value) || obj.value == '')
303			obj.value = 0;
304	};
305
306	self.focusTextbox = function (obj) {
307		$(obj).data("element-value", obj.value);
308		obj.value = "";
309	};
310
311	self.blureTextbox = function (obj) {
312		if (obj.value == 0)
313			obj.value = $(obj).data("element-value");
314	};
315
316    self.setActiveItem = function(item) {
317        var list = mcWeb.productVariantMatrix.vm.SorterList();
318        var selectedName = "";
319        for (var i = 0; i < list.length; i++) {
320            var listitem = list[i];
321            if (i == item.Index) {
322                listitem.Selected(true);
323                selectedName = listitem.Name;
324            }
325            else listitem.Selected(false);
326        }
327        mcWeb.productVariantMatrix.vm.SorterText(mcWeb.productVariantMatrix.vm.SortText + " " + selectedName);
328    };
329	var viewModelVariants = function (json) { //Internal
330		var view = this;
331
332        view.ShowAntallDefaultZero = ko.observable(json.ShowAntallDefaultZero);
333        view.ShowAntallDefaultZeroInVariantMatrix = ko.observable(json.ShowAntallDefaultZeroInVariantMatrix);
334		view.ShowRetailPrice = ko.observable(json.ShowRetailPrice);
335		view.ShowCustomerPrice = ko.observable(json.ShowCustomerPrice);
336		view.Attributt1Txt = ko.observable(json.Attributt1Txt);
337		view.Attributt2Txt = ko.observable(json.Attributt2Txt);
338		view.VariantChilds = ko.observableArray(json.VariantChilds);
339	    view.ProduktDesc1 = ko.observable(json.ProduktDesc1);
340	    view.ProduktDesc2 = ko.observable(json.ProduktDesc2);
341	    view.VareNr = ko.observable(json.VareNr);
342	    view.plid = json.Plid;
343	    view.Link = json.Link;
344	    view.SorterList = ko.observableArray(json.SorterList);
345        if (view.SorterList().length > 0) {
346            for (var i = 0; i < view.SorterList().length; i++) {
347                var item = view.SorterList()[i];
348                item.Selected = ko.observable(item.Selected);
349            }
350        }
351	    var selectedItem = view.SorterList()[json.SelectedSorterIndex];
352	    view.SortText = json.SorterText;
353
354        if(json.OrderbookCartsMissing){
355            var buttonTarget = jQuery("#vmatrix-add-delivery-date-button");
356            var width = jQuery(window).width();
357            var height = jQuery(window).height();
358
359            if(width > 150 && height > 150){
360                width = width /2 - 150;
361                height = height /2 - 75;
362            }
363            //mcWeb.orderbookManager.showAddNewOrderbookDate({ left: buttonTarget.offset().left, top: buttonTarget.offset().top});
364            mcWeb.orderbookManager.showAddNewOrderbookDate({ left: width, top: height});
365        }
366
367        if(selectedItem != undefined && selectedItem != null)
368	    {
369            view.SorterText = ko.observable(json.SorterText + " " + selectedItem.Name);
370        }
371        else view.SorterText = "";
372
373	    view.addToCart2 = function() {
374	        view.addToCartInner(false,null);
375	    };
376
377        view.addToCartInner = function(skipWindowClose, completionMessage){
378	    $('#UpdateIcon').show();
379	        PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
380	        var amountBoxes = jQuery('#product-variant-matrix .qty-container input.QuantityTextBox');
381	        var updateExisting = true;
382            if (amountBoxes.length <= 0) {
383                amountBoxes = jQuery('#product-variant-matrix input.quantity-desimal
383s');
384                updateExisting = false;
385            }   
386	        var amounts = [];
387	        $(amountBoxes).each(function (index, item) {
388	            var $box = jQuery(item);
389	            var amount = $box.val();
390	            var cartid = $box.data("cart");
391	            var plid = $box.data("plid");
392                var origval = $box.data("origval");
393                var cartRowId = $box.data("cartrowid");
394                if (cartRowId === undefined)
395                    cartRowId = 0;
396
397	            var origValStr = "";
398	            if(origval != undefined)
399	                origValStr = origval.toString();
400                if (!updateExisting) {
401                    if (cartid == undefined) {
402                        cartid = 0;//use default cart
403                    }
404                }
405
406                var amountNormalized = amount.replace(',', '.'); // it might come in with comma as decimal separator, making the comparison later fail. 
407                var isDecimal = document.querySelectorAll('#product-variant-matrix input.quantity-desimals').length > 0;
408                var valueToCompare = isDecimal ? amountNormalized : amount;
409
410                if (origValStr != valueToCompare && !(origValStr == "" && valueToCompare == 0)) {
411                    if (cartid > 0 || (!updateExisting && valueToCompare > 0)) {
412	                    amounts.push({
413	                        Amount: amount,
414	                        CartId: cartid,
415                            Plid: plid,
416                            CartRowId: cartRowId
417	                    });
418	                }
419	            }
420	        });
421
422            if (amounts.length > 0) {
423                self.service.PostAction("AddToCarts", { Data: amounts, UpdateExisting: updateExisting }).then(function (result) {
424                    $('#UpdateIcon').hide();
425                    PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
426                    if (result != null && result.Success == true) {
427                        view.closeWindowOrNavigate(skipWindowClose, completionMessage);
428                    } else {
429                        view.showError(result);
430                    }
431                });
432            }
433            else {
434                $('#UpdateIcon').hide();
435                PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
436                view.closeWindowOrNavigate(skipWindowClose, completionMessage);
437            }
438        };
439
440        view.closeWindowOrNavigate = function (skipWindowClose, completionMessage) {
441            if (!skipWindowClose) {
442                if (location.hash === "") {
443                    PubSub.publish(mcWeb.cartsmall.events.onUpdateCart);
444                    PubSub.publish(mcWeb.events.freeShippingTxt.onUpdateFreeShipping);
445                    view.cancelAndCloseWindow();
446                }
447                else {
448                    var page = document.location.href.replace(location.hash, "");
449                    page = page.replace("#", "");
450                    window.location = page;
451                }
452            } else {
453                PubSub.publish(mcWeb.cartsmall.events.onUpdateCart);
454                PubSub.publish(mcWeb.events.freeShippingTxt.onUpdateFreeShipping);
455                PubSub.publish(completionMessage);
456            }
457        };
458
459	    view.addToCartAndGoToNext = function(message, item) {
460	        self.nextPlid  = item;
461	        view.addToCartInner(true, mcWeb.productVariantMatrix.events.onShowNextItem);	      
462        };
463
464        view.onGoToNextPageEmpty = function (message, item) {
465            self.nextPlid = item;
466            view.closeWindowOrNavigate(true, mcWeb.productVariantMatrix.events.onShowNextItem);
467        }
468        
469	    view.onChangeSort = function(item, event) {
470	        try {
471
472	            var data = {
473	                sortType: item.Val,
474	                order: item.Direction
475	            };
476
477	            self.productListService.GetAction("SetVariantSortType", data)
478                    .then(function (result) {
479	                    mcWeb.ajaxRenderEngine.reloadLightboxFields();
480	                    self.setActiveItem(item);
481	                });
482	        } catch (e) {
483	            console.error(e);
484	        }
485	    };
486        
487
488	    PubSub.unsubscribe(mcWeb.productVariantMatrix.events.onDoAddToCart);
489        PubSub.subscribe(mcWeb.productVariantMatrix.events.onDoAddToCart, view.addToCartAndGoToNext);	
490
491        PubSub.subscribe(mcWeb.productVariantMatrix.events.onGoToNextPage, view.onGoToNextPageEmpty);
492
493	    view.showError = function(result) {
494	        //Show error
495	        $('#UpdateIcon').hide();
496	        $('#product-variant-matrix > fieldset').hide();
497	        $('#product-variant-matrix-error').show();
498	        if (result != null)
499	            $('#product-variant-matrix-error-message').html(result.Message);
500	    };
501
502	    view.postProcessing = function(elements) {
503	        $('#UpdateIcon').hide();
504	    };
505
506		view.cancelAndCloseWindow = function () {
507			PubSub.publish(mcWeb.lightbox.events.onHideLightbox);
508		};
509
510        view.addDeliveryDate = function (vm, evt) {
511            var buttonTarget = $(evt.currentTarget);
512            mcWeb.orderbookManager.showAddNewOrderbookDate({ left: buttonTarget.offset().left, top: buttonTarget.offset().top});
513	     
514	    };
515
516	  
517
518		view.retryAddToCart = function () {
519			$('#product-variant-matrix > fieldset').show();
520			$('#product-variant-matrix-error').hide();
521		};
522
523	    view.showQuickView = function() {
524	        var nodeid = parseInt(jQuery("#hidden-nodeid").text());
525	        var areaName = "QuickView";
526            var quickview = mcWeb.ajaxRenderEngine.getQuickview("rhs");
527            quickview.init({areaName: areaName, nodeId: nodeid});
528            quickview.show(view.plid, 0);
529	    };
530
531	    view.addToFavourites = function() {//todo: check which fav-cart we want to use
532	        mcWeb.productlist.fav.add(null, view.plid, 1, false,0);
533	    };
534
535        view.showProduct = function() {
536            //todo: check if any changes have been made without being added to the cart
537            window.location.href = view.Link;
538        };
539	};
540};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.