PageSourceSearch

https://manufakturaczekolady.pl/app/plugins/codecanyon-BN4EIxgL-b2…/public/assets/js/public.js?ver=1666197338

js manufakturaczekolady.pl collected 2026-09-26 13:40:41 UTC 106,811 bytes, 2,645 lines download raw bytes

1/**
2*
3* JavaScript file that handles public side JS
4*
5*/
6
7(function($){
8
9	"use strict";
10
11	$( document ).ready(function() {
12
13		var isIndigo = $('#b2bking_indigo_order_form').val();
14		var isCream = $('#b2bking_indigo_order_form.b2bking_cream_order_form').val();
15
16		/* Fix for country selector SCROLL ISSUE in popup (e.g. login in Flatsome theme) */
17		$('.b2bking_country_field_selector select').on('select2:open', function (e) {
18	        const evt = "scroll.select2";
19	        $(e.target).parents().off(evt);
20	        $(window).off(evt);
21	      });
22
23		/* Conversations START */
24
25		// On load conversation, scroll to conversation end
26		// if conversation exists
27		if ($('#b2bking_conversation_messages_container').length){
28			$("#b2bking_conversation_messages_container").scrollTop($("#b2bking_conversation_messages_container")[0].scrollHeight);
29		}
30
31		// On clicking "Send message" inside conversation in My account
32		$('#b2bking_conversation_message_submit').on('click', function(){
33			// loader icon
34			$('<img class="b2bking_loader_icon_button" src="'+b2bking_display_settings.loadertransparenturl+'">').insertBefore('.b2bking_myaccount_conversation_endpoint_button_icon');
35			$('.b2bking_myaccount_conversation_endpoint_button_icon').remove();
36			// Run ajax request
37			var datavar = {
38	            action: 'b2bkingconversationmessage',
39	            security: b2bking_display_settings.security,
40	            message: $('#b2bking_conversation_user_new_message').val(),
41	            conversationid: $('#b2bking_conversation_id').val(),
42	        };
43
44			$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
45				location.reload();
46			});
47		});
48
49		// On clicking "New conversation" button
50		$('#b2bking_myaccount_make_inquiry_button').on('click', function(){
51			// hide make inquiry button
52			$('#b2bking_myaccount_make_inquiry_button').css('display','none');
53			// hide conversations
54			$('.b2bking_myaccount_individual_conversation_container').css('display','none');
55			// hide conversations pagination
56			$('.b2bking_myaccount_conversations_pagination_container').css('display','none');
57			// show new conversation panel
58			$('.b2bking_myaccount_new_conversation_container').css('display','block');
59		});
60
61		// On clicking "Close X" button
62		$('.b2bking_myaccount_new_conversation_close').on('click', function(){
63			// hide new conversation panel
64			$('.b2bking_myaccount_new_conversation_container').css('display','none');
65			// show new conversation button
66			$('#b2bking_myaccount_make_inquiry_button').css('display','inline-flex');
67			// show conversations
68			$('.b2bking_myaccount_individual_conversation_container').css('display','block');
69			// show pagination
70			$('.b2bking_myaccount_conversations_pagination_container').css('display','flex');
71			
72		});
73
74		// On clicking "Send inquiry" button
75		$('#b2bking_myaccount_send_inquiry_button').on('click', function(){
76			// if textarea empty OR title empty
77			if (!$.trim($("#b2bking_myaccount_textarea_conversation_start").val()) || !$.trim($("#b2bking_myaccount_title_conversation_start").val())) {
78				// Show "Text area or title is empty" message
79			} else {
80				// loader icon
81				$('<img class="b2bking_loader_icon_button" src="'+b2bking_display_settings.loadertransparenturl+'">').insertBefore('.b2bking_myaccount_start_conversation_button_icon');
82				$('.b2bking_myaccount_start_conversation_button_icon').remove();
83				// Run ajax request
84				var datavar = {
85		            action: 'b2bkingsendinquiry',
86		            security: b2bking_display_settings.security,
87		            message: $('#b2bking_myaccount_textarea_conversation_start').val(),
88		            title: $('#b2bking_myaccount_title_conversation_start').val(),
89		            type: $("#b2bking_myaccount_conversation_type").children("option:selected").val(),
90		        };
91
92		        // If DOKAN addon exists, pass vendor
93		        if (typeof b2bkingdokan_display_settings !== 'undefined') {
94		        	datavar.vendor = $('#b2bking_myaccount_conversation_vendor').val();
95		        }
96
97		        // If WCFM addon exists, pass vendor
98		        if (typeof b2bkingwcfm_display_settings !== 'undefined') {
99		        	datavar.vendor = $('#b2bking_myaccount_conversation_vendor').val();
100		        }
101
102		        // If MarketKing addon exists, pass vendor
103		        if (typeof marketking_display_settings !== 'undefined') {
104		        	datavar.vendor = $('#b2bking_myaccount_conversation_vendor').val();
105		        }
106
107
108
109				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
110					// redirect to conversation
111					window.location = response;
112				});
113			}
114		});
115
116		/* Conversations END */
117
118		/* Request a custom quote START*/
119
120		// On clicking "Request a Custom Quote" button
121		$('body').on('click', '#b2bking_request_custom_quote_button', function(){
122
123			// If DOKAN addon exists
124			if (typeof b2bkingdokan_display_settings !== 'undefined') {
125				// check number of vendors
126				var vendors = [];
127				$('.variation dd.variation-Vendor').each(function(){
128					let value = $(this).text().trim();
129					if (value.length !== 0){
130						if (!vendors.includes(value)){
131							vendors.push(value);
132						}
133					}
134				});
135				var vendorsNr = vendors.length;
136				if (parseInt(vendorsNr) > 1){
137					alert(b2bkingdokan_display_settings.request_many_vendors);
138					return;
139				}
140			}
141
142			// If WCFM addon exists
143			if (typeof b2bkingwcfm_display_settings !== 'undefined') {
144				// check number of vendors
145				var vendors = [];
146				$('.variation dd.variation-Store').each(function(){
147					let value = $(this).text().trim();
148					if (value.length !== 0){
149						if (!vendors.includes(value)){
150							vendors.push(value);
151						}
152					}
153				});
154
155				if (vendors.length == 0){
156					// try different structure
157					$('.wcfm_dashboard_item_title').each(function(){
158						let value = $(this).text().trim();
159						if (value.length !== 0){
160							if (!vendors.includes(value)){
161								vendors.push(value);
162							}
163						}
164					});
165				}
166
167				var vendorsNr = vendors.length;
168				if (parseInt(vendorsNr) > 1){
169					alert(b2bkingwcfm_display_settings.request_many_vendors);
170					return;
171				}
172			}
173
174			// If MarketKing addon exists
175			if (typeof marketking_display_settings !== 'undefined') {
176				// check number of vendors
177				var vendorsNr = $('#marketking_number_vendors_cart').val();
178				if (parseInt(vendorsNr) > 1){
179					alert(marketking_display_settings.request_many_vendors);
180					return;
181				}
182			}
183
184			// show hidden elements above the button
185			$('#b2bking_request_custom_quote_textarea, #b2bking_request_custom_quote_textarea_abovetext, .b2bking_custom_quote_field_container, .b2bking_request_custom_quote_text_label, #b2bking_request_custom_quote_name, #b2bking_request_custom_quote_email, .b2bking_custom_quote_field').css('display','block');
186			// replace the button text with "Send custom quote request"
187			$('#b2bking_request_custom_quote_button').text(b2bking_display_settings.send_quote_request);
188
189			// On clicking "Send custom quote request"
190			$('#b2bking_request_custom_quote_button').addClass('b2bking_send_custom_quote_button');
191		});
192
193		$('body').on('click', '.b2bking_send_custom_quote_button', function(){
194		
195
196			// if no fields are empty
197			let empty = 'no';
198			if ($('#b2bking_request_custom_quote_name').val() === '' || $('#b2bking_request_custom_quote_email').val() === ''){
199				empty = 'yes';		
200			}
201			// check all custom fields
202			var requiredids = jQuery('#b2bking_quote_required_ids').val();
203			let requiredidssplit = requiredids.split(',');
204			requiredidssplit.forEach(function(item){
205				if ($('#b2bking_field_'+item).val() === ''){
206					empty = 'yes';
207				}
208			});
209
210			if (empty === 'no'){
211
212				// validate email
213				if (validateEmail($('#b2bking_request_custom_quote_email').val())){
214
215					
216					// run ajax request
217					var quotetextids = jQuery('#b2bking_quote_text_ids').val();
218					var quotecheckboxids = jQuery('#b2bking_quote_checkbox_ids').val();
219					var quotefileids = jQuery('#b2bking_quote_file_ids').val();
220
221					let quotetextidssplit = quotetextids.split(',');
222					let quotecheckboxidssplit = quotecheckboxids.split(',');
223					let quotefileidssplit = quotefileids.split(',');
224
225					var datavar = {
226			            action: 'b2bkingrequestquotecart',
227			            security: b2bking_display_settings.security,
228			            message: jQuery('#b2bking_request_custom_quote_textarea').val(),
229			            name: jQuery('#b2bking_request_custom_quote_name').val(),
230			            email: jQuery('#b2bking_request_custom_quote_email').val(),
231			            title: b2bking_display_settings.custom_quote_request,
232			            type: 'quote',
233			        };
234
235			        datavar.quotetextids = quotetextids;
236			        datavar.quotecheckboxids = quotecheckboxids;
237			        datavar.quotefileids = quotefileids;
238
239			        quotetextidssplit.forEach(function(item){
240			        	let id = 'b2bking_field_'+item;
241			        	datavar[id] = jQuery('#b2bking_field_'+item).val();
242			        });
243
244			        quotecheckboxidssplit.forEach(function(item){
245			        	let id = 'b2bking_field_'+item;
246			        	let value = '';
247
248			        	jQuery('#b2bking_field_'+item+':checked').each(function() {
249			        	   value+=jQuery(this).parent().find('span').text()+', ';
250			        	});
251			        	value = value.slice(0, -2);
252
253			        	datavar[id] = value;
254			        });
255
256			        if (quotefileids !== ''){
257			        	// if there are files
258			        	var nroffiles = parseInt(quotefileidssplit.length);
259			        	var currentnr = 1;
260			        	if (currentnr <= nroffiles){
261			        		quotefileidssplit.forEach(function(item, index, array){
262
263			        			let id = 'b2bking_field_'+item;
264			        			var fd = new FormData();
265			        			var file = jQuery('#b2bking_field_'+item);
266			        			var individual_file = file[0].files[0];
267			        			fd.append("file", individual_file);
268			        			fd.append('action', 'b2bkingquoteupload'); 
269			        			fd.append('security', b2bking_display_settings.security); 
270
271			        			// disable button to prevent double-clicks
272			        			quote_button_loader();
273
274
275			        			jQuery.ajax({
276			        			    type: 'POST',
277			        			    url: b2bking_display_settings.ajaxurl,
278			        			    data: fd,
279			        			    contentType: false,
280			        			    processData: false,
281			        			    success: function(response){
282			        			        datavar[id] = response;
283			        			        if (currentnr === nroffiles){
284			        			        	// it is the last file
285
286			        			        	// If MARKETKING addon exists, pass vendor
287			        			        	if (typeof marketking_display_settings !== 'undefined') {
288			        			        		datavar.vendor = $('#marketking_cart_vendor').val();
289			        			        	}
290
291	        			        	        // If DOKAN addon exists, pass vendor
292	        			        	        if (typeof b2bkingdokan_display_settings !== 'undefined') {
293	        			        	        	var vendors = [];
294	        			        	        	$('.variation dd.variation-Vendor').each(function(){
295	        			        	        		let value = $(this).text();
296	        			        	        		if (!vendors.includes(value)){
297	        			        	        			vendors.push(value);
298	        			        	        		}
299	        			        	        	});
300	        			        	        	datavar.vendor = vendors[0];
301	        			        	        }
302
303	        			        	        // If WCFM addon exists, pass vendor
304	        			        	        if (typeof b2bkingwcfm_display_settings !== 'undefined') {
305	        			        	        	var vendors = [];
306	        			        	        	$('.variation dd.variation-Store').each(function(){
307	        			        	        		let value = $(this).text();
308	        			        	        		if (!vendors.includes(value)){
309	        			        	        			vendors.push(value);
310	        			        	        		}
311	        			        	        	});
312	        			        	        	datavar.vendor = vendors[0];
313	        			        	        }
314	        			        	        if (datavar.vendor === undefined){
315	        			        	        	// if nothing yet, check additional structures
316	        			        	        	var vendors2 = [];
317	        			        	        	$('.wcfm_dashboard_item_title').each(function(){
318	        			        	        		let value = $(this).text();
319	        			        	        		if (!vendors2.includes(value)){
320	        			        	        			vendors2.push(value);
321	        			        	        		}
322	        			        	        	});
323	        			        	        	datavar.vendor = vendors2[0];
324	        			        	        }
325	        			        	        
326	        			        			$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
327	        			        				let conversationurl = response;
328
329	        			        				// if user is logged in redirect to conversation, else show alert
330	        			        				if($('#b2bking_request_custom_quote_name').length){
331	        			        					alert(b2bking_display_settings.quote_request_success);
332	        			        					$('#b2bking_request_custom_quote_button').css('display','none');
333	        			        					location.reload();
334	        			        				} else {
335	        			        				    window.location = conversationurl;
336	        			        				}
337	        			        				
338	        			        			});
339			        			        }
340			        			        currentnr++;
341			        			    }
342			        			});
343			        		});
344
345			        	}
346			        } else {
347			        	// no files
348
349	        	        // If WCFM addon exists, pass vendor
350	        	        if (typeof b2bkingwcfm_display_settings !== 'undefined') {
351	        	        	var vendors = [];
352	        	        	$('.variation dd.variation-Store').each(function(){
353	        	        		let value = $(this).text();
354	        	        		if (!vendors.includes(value)){
355	        	        			vendors.push(value);
356	        	        		}
357	        	        	});
358	        	        	datavar.vendor = vendors[0];
359	        	        }
360
361	        	        // if nothing yet, check additional structures
362	        	        var vendors2 = [];
363	        	        $('.wcfm_dashboard_item_title').each(function(){
364	        	        	let value = $(this).text();
365	        	        	if (!vendors2.includes(value)){
366	        	        		vendors2.push(value);
367	        	        	}
368	        	        });
369	        	        datavar.vendor = vendors2[0];
370
371	        	        // If MARKETKING addon exists, pass vendor
372			        	if (typeof marketking_display_settings !== 'undefined') {
373			        		datavar.vendor = $('#marketking_cart_vendor').val();
374			        	}
375
376	        	        // If DOKAN addon exists, pass vendor
377	        	        if (typeof b2bkingdokan_display_settings !== 'undefined') {
378	        	        	var vendors = [];
379	        	        	$('.variation dd.variation-Vendor').each(function(){
380	        	        		let value = $(this).text();
381	        	        		if (!vendors.includes(value)){
382	        	        			vendors.push(value);
383	        	        		}
384	        	        	});
385	        	        	datavar.vendor = vendors[0];
386	        	        }
387
388	        	        quote_button_loader();
389
390	        			$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
391	        				let conversationurl = response;
392
393	        				// if user is logged in redirect to conversation, else show alert
394	        				if($('#b2bking_request_custom_quote_name').length){
395	        					alert(b2bking_display_settings.quote_request_success);
396	        					$('#b2bking_request_custom_quote_button').css('display','none');
397	        					location.reload();
398	        				} else {
399	        				    window.location = conversationurl;
400	        				}
401	        				
402	        			});
403			        }
404
405					
406				} else {
407					alert(b2bking_display_settings.quote_request_invalid_email);
408				}
409				
410			} else {
411				alert(b2bking_display_settings.quote_request_empty_fields);
412			}
413		});
414
415		function validateEmail(email) {
416			if ($('#b2bking_request_custom_quote_email').val() !== undefined){
417				var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
418				return regex.test(email);
419			} else {
420				return true;
421			}
422		}
423
424		function quote_button_loader(){
425			jQuery('#b2bking_request_custom_quote_button').attr('disabled', true);
426			jQuery('#b2bking_request_custom_quote_button').html(b2bking_display_settings.sending_please_wait);
427
428			// potentially problematic on certain themes 
429			/*
430			// add loader
431			var newbuttonhtml = '<img class="b2bking_loader_icon_button_quote" src="'+b2bking_display_settings.loadertransparenturl+'">'+b2bking_display_settings.sending_please_wait;
432			jQuery('#b2bking_request_custom_quote_button').html(newbuttonhtml);
433
434			// determine if loader icon color needs to be changed from white to black
435			var textcolor = jQuery('#b2bking_request_custom_quote_button').css('color');
436			textcolor = textcolor.split('(')[1].split(')')[0];
437
438			var r = parseInt(textcolor.split(',')[0]);  // extract red
439			var g = parseInt(textcolor.split(',')[1].trim());  // extract red
440			var b = parseInt(textcolor.split(',')[2].trim());  // extract red
441
442			var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709
443
444			if (luma < 55) {
445			    // change color of loader to black
446			    jQuery('.b2bking_loader_icon_button_quote').css('filter','invert(1)');
447			}
448			*/
449		}
450
451		/* Request a custom quote END*/
452
453		/* Offers START*/
454
455		// On clicking "add offer to cart"
456		$('.b2bking_offer_add').on('click',function(){
457			if (b2bking_display_settings.disableofferadd !== 1){
458				let offerId = $(this).val();
459				// replace icon with loader
460				$('<img class="b2bking_loader_icon_button" src="'+b2bking_display_settings.loadertransparenturl+'">').insertBefore($(this).find('.b2bking_myaccount_individual_offer_bottom_line_button_icon'));
461				$(this).find('.b2bking_myaccount_individual_offer_bottom_line_button_icon').remove();
462
463				// run ajax request
464				var datavar = {
465			            action: 'b2bkingaddoffer',
466			            security: b2bking_display_settings.security,
467			            offer: offerId,
468			        };
469
470				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
471					// redirect to cart
472					window.location = b2bking_display_settings.carturl;
473				});
474			}
475		});
476		
477		// offer download
478		$('.b2bking_offer_download').on('click',function(){
479			var logoimg = b2bking_display_settings.offers_logo;
480			var offernr = $(this).parent().parent().parent().find('#b2bking_offer_id').val();
481
482			// if images are lazy-loaded, replace
483			let logodatasrc = jQuery('#b2bking_img_logo').attr('data-src');
484			if (logodatasrc !== undefined && logodatasrc !== ''){
485				jQuery('#b2bking_img_logo').attr('src', logodatasrc);
486			}
487
488			jQuery('.b2bking_hidden_img').each(function(i){
489				let logodatasrcth = jQuery(this).attr('data-src');
490				if (logodatasrcth !== undefined && logodatasrcth !== ''){
491					jQuery(this).attr('src', logodatasrcth);
492				}
493			});
494
495
496			var imgToExport = document.getElementById('b2bking_img_logo');
497			var canvas = document.createElement('canvas');
498	        canvas.width = imgToExport.width; 
499	        canvas.height = imgToExport.height; 
500	        canvas.getContext('2d').drawImage(imgToExport, 0, 0);
501	  		var dataURL = canvas.toDataURL("image/png"); 
502
503	  		// get all thumbnails 
504	  		var thumbnails = [];
505	  		var thumbnr = 0;
506	  		
507	  		if (parseInt(b2bking_display_settings.offers_images_setting) === 1){
508		  		// get field;
509		  		let field = $(this).parent().parent().parent().find('.b2bking_offers_thumbnails_str').val();
510		  		let itemsArray = field.split('|');
511		  		// foreach condition, add condition, add new item
512		  		itemsArray.forEach(function(item){
513		  			if (item !== 'no'){
514		  				var idimg = 'b2bking_img_logo'+thumbnr+offernr;
515  						var imgToExport = document.getElementById(idimg);
516  						var canvas = document.createElement('canvas');
517  				        canvas.width = imgToExport.width; 
518  				        canvas.height = imgToExport.height; 
519  				        canvas.getContext('2d').drawImage(imgToExport, 0, 0);
520  				  		let datau = canvas.toDataURL("image/png"); 
521  				  		thumbnr++;
522  				  		thumbnails.push(datau);
523		  			} else {
524		  				thumbnails.push('no');
525		  			}
526		  		});
527		  	}
528
529		  	thumbnr = 0;
530			var customtext = $(this).parent().parent().parent().find('.b2bking_myaccount_individual_offer_custom_text').text();
531			customtext = customtext.replace('\t','').trim();
532
533			var customtextvendor = $(this).parent().parent().parent().find('.b2bking_myaccount_individual_offer_custom_text_vendor').text();
534			customtextvendor = customtextvendor.replace('\t','').trim();
535
536
537			var customtexttitle = b2bking_display_settings.offer_custom_text;
538			if (customtext.length === 0 && customtextvendor.length === 0){
539				customtexttitle = '';
540			}
541
542			
543	
544
545			var bodyarray = [];
546			bodyarray.push([{ text: b2bking_display_settings.item_name, style: 'tableHeader', margin: [7, 7, 7, 7] }, { text: b2bking_display_settings.item_quantity, style: 'tableHeader', margin: [7, 7, 7, 7] }, { text: b2bking_display_settings.unit_price, style: 'tableHeader', margin: [7, 7, 7, 7] }, { text: b2bking_display_settings.item_subtotal, style: 'tableHeader', margin: [7, 7, 7, 7] }]);
547
548			// get values
549			jQuery(this).parent().parent().parent().find('.b2bking_myaccount_individual_offer_element_line').each(function(i){
550				let tempvalues = [];
551
552				if (parseInt(b2bking_display_settings.offers_images_setting) === 1){
553					if (thumbnails[thumbnr] !== 'no'){
554						// add name + images
555						tempvalues.push([{ text: jQuery(this).find('.b2bking_myaccount_individual_offer_element_line_item_name').first().text(), margin: [7, 7, 7, 7] },{
556								image: thumbnails[thumbnr],
557								width: 40,
558								margin: [15, 5, 5, 5]
559							}]);
560					} else {
561						// add name only
562						tempvalues.push({ text: jQuery(this).find('.b2bking_myaccount_individual_offer_element_line_item_name').first().text(), margin: [7, 7, 7, 7] });
563					}
564					thumbnr++;
565				} else {
566					// add name only
567					tempvalues.push({ text: jQuery(this).find('.b2bking_myaccount_individual_offer_element_line_item_name').first().text(), margin: [7, 7, 7, 7] });
568				}
569
570
571				tempvalues.push({ text: jQuery(this).find('.b2bking_myaccount_individual_offer_element_line_item:nth-child(2)').text(), margin: [7, 7, 7, 7] });
572				tempvalues.push({ text: jQuery(this).find('.b2bking_myaccount_individual_offer_element_line_item:nth-child(3)').text(), margin: [7, 7, 7, 7] });
573				tempvalues.push({ text: jQuery(this).find('.b2bking_myaccount_individual_offer_element_line_item:nth-child(4)').text(), margin: [7, 7, 7, 7] });
574				bodyarray.push(tempvalues);
575			});
576
577
578
579			bodyarray.push(['','',{ text: b2bking_display_settings.offer_total+': ', margin: [7, 7, 7, 7], bold: true },{ text: jQuery(this).parent().parent().parent().find('.b2bking_myaccount_individual_offer_bottom_line_total strong').text(), margin: [7, 7, 7, 7], bold: true }]);
580
581			let imgobj = {
582						image: dataURL,
583						width: 150,
584						margin: [0, 0, 0, 30]
585					};
586
587
588			var contentarray =[
589					{ text: b2bking_display_settings.offer_details, fontSize: 14, bold: true, margin: [0, 20, 0, 20] },
590					{
591						style: 'tableExample',
592						table: {
593							headerRows: 1,
594							widths: ['*', '*', '*', '*'],
595							body: bodyarray,
596						},
597						layout: 'lightHorizontalLines'
598					},
599					{ text: b2bking_display_settings.offer_go_to, link: b2bking_display_settings.offers_endpoint_link, decoration: 'underline', fontSize: 13, bold: true, margin: [0, 20, 40, 8], alignment:'right' },
600					{ text: customtexttitle, fontSize: 14, bold: true, margin: [0, 50, 0, 8] },
601					{ text: customtextvendor, fontSize: 12, bold: false, margin: [0, 8, 0, 8] },
602					{ text: customtext, fontSize: 12, bold: false, margin: [0, 8, 0, 8] },
603
604				];
605
606			if (logoimg.length !== 0){
607				contentarray.unshift(imgobj);
608			}
609
610			
611			var docDefinition = {
612				content: contentarray
613			};
614			
615
616			if(b2bking_display_settings.pdf_download_lang === 'thai'){
617
618				pdfMake.fonts = {
619				  THSarabunNew: {
620				    normal: 'THSarabunNew.ttf',
621				    bold: 'THSarabunNew-Bold.ttf',
622				    italics: 'THSarabunNew-Italic.ttf',
623				    bolditalics: 'THSarabunNew-BoldItalic.ttf'
624				  }
625				};
626
627				docDefinition = {
628				  content: contentarray,
629				  defaultStyle: {
630				    font: 'THSarabunNew'
631				  }
632				}
633			}
634
635			if(b2bking_display_settings.pdf_download_lang === 'japanese'){
636
637				pdfMake.fonts = {
638				  Noto: {
639				    normal: 'Noto.ttf',
640				    bold: 'Noto.ttf',
641				    italics: 'Noto.ttf',
642				    bolditalics: 'Noto.ttf'
643				  }
644				};
645
646				docDefinition = {
647				  content: contentarray,
648				  defaultStyle: {
649				    font: 'Noto'
650				  }
651				}
652			}
653
654
655			pdfMake.createPdf(docDefinition).download('offer.pdf');
656		});
657		
658
659		/* Offers END */
660
661
662		/* Custom Registration Fields START */
663		// Dropdown
664		addCountryRequired(); // woocommerce_form_field does not allow required for country, so we add it here
665		// On load, show hide fields depending on dropdown option
666		showHideRegistrationFields();
667
668		$('.country_to_state').trigger('change');
669		$('#b2bking_registration_roles_dropdown').change(showHideRegistrationFields);
670		$('.b2bking_country_field_selector select').change(showHideRegistrationFields);
671		$('select#billing_country').change(showHideRegistrationFields);
672		function addCountryRequired(){
673			$('.b2bking_country_field_req_required').prop('required','true');
674			$('.b2bking_custom_field_req_required select').prop('required','true');
675		}
676		// on state change, reapply required
677		$('body').on('DOMSubtreeModified', '#billing_state_field', function(){
678			//let selectedValue = $('#b2bking_registration_roles_dropdown').val();
679			//$('.b2bking_custom_registration_'+selectedValue+' #billing_state_field.b2bking_custom_field_req_required #billing_state').prop('required','true');
680			//$('.b2bking_custom_registration_allroles #billing_state_field.b2bking_custom_field_req_required #billing_state').prop('required','true');
681		});
682
683		function showHideRegistrationFields(){
684
685			// Hide all custom fields. Remove 'required' for hidden fields with required
686			$('.b2bking_custom_registration_container').css('display','none');
687			$('.b2bking_custom_field_req_required').removeAttr('required');
688			$('.b2bking_custom_field_req_required select').removeAttr('required');
689			$('.b2bking_custom_field_req_required #billing_state').removeAttr('required');
690			
691			// Show fields of all roles. Set required
692			$('.b2bking_custom_registration_allroles').css('display','block');
693			$('.b2bking_custom_registration_allroles .b2bking_custom_field_req_required').prop('required','true');
694			$('.b2bking_custom_registration_allroles .b2bking_custom_field_req_required select').prop('required','true');
695			setTimeout(function(){
696				$('.b2bking_custom_registration_allroles .b2bking_custom_field_req_required #billing_state').prop('required','true');
697	        },125);
698
699			// Show all fields of the selected role. Set required
700			let selectedValue = $('#b2bking_registration_roles_dropdown').val();
701			$('.b2bking_custom_registration_'+selectedValue).css('display','block');
702			$('.b2bking_custom_registration_'+selectedValue+' .b2bking_custom_field_req_required').prop('required','true');
703			$('.b2bking_custom_registration_'+selectedValue+' .b2bking_custom_field_req_required select').prop('required','true');
704			setTimeout(function(){
705	        	$('.b2bking_custom_registration_'+selectedValue+' .b2bking_custom_field_req_required #billing_state').prop('required','true');
706	        },225);
707
708			// if there is more than 1 country
709			if(parseInt(b2bking_display_settings.number_of_countries) !== 1){
710				// check VAT available countries and selected country. If vat not available, remove vat and required
711				let vatCountries = $('#b2bking_vat_number_registration_field_countries').val();
712				let selectedCountry = $('.b2bking_country_field_selector select').val();
713				if (selectedCountry === undefined){
714					selectedCountry = $('select#billing_country').val();
715				}
716				if (vatCountries !== undefined){
717					if ( (! (vatCountries.includes(selectedCountry))) || selectedCountry.trim().length === 0 ){
718						// hide and remove required
719						$('.b2bking_vat_number_registration_field_container').css('display','none');
720						$('#b2bking_vat_number_registration_field').removeAttr('required');
721					}
722				}
723			}
724
725			// New for My Account VAT
726			if (parseInt(b2bking_display_settings.myaccountloggedin) === 1){
727				// check VAT countries
728				let vatCountries = $('#b2bking_custom_billing_vat_countries_field input').prop('placeholder');
729				let billingCountry = $('#billing_country').val();
730				if (vatCountries !== undefined){
731					if ( (! (vatCountries.includes(billingCountry))) || billingCountry.trim().length === 0){
732						$('.b2bking_vat_field_container, #b2bking_checkout_registration_validate_vat_button').removeClass('b2bking_vat_visible, b2bking_vat_hidden').addClass('b2bking_vat_hidden');
733						$('.b2bking_vat_field_required_1 input').removeAttr('required');
734					} else {
735						$('.b2bking_vat_field_container, #b2bking_checkout_registration_validate_vat_button').removeClass('b2bking_vat_visible, b2bking_vat_hidden').addClass('b2bking_vat_visible');
736						$('.b2bking_vat_field_required_1 .optional').after('<abbr class="required" title="required">*</abbr>');
737						$('.b2bking_vat_field_required_1 .optional').remove();
738						$('.b2bking_vat_field_required_1 input').prop('required','true');
739					}
740				}
741			}
742			
743		}
744
745		// when billing country is changed , trigger update checkout. Seems to be a change in how WooCommerce refreshes the page. In order for this to work well with tax exemptions, run update checkout
746		$('#billing_country').on('change', function() {
747			setTimeout(function(){
748				$(document.body).trigger("update_checkout");
749			},1750);
750		});
751        jQuery('body').on('change', 'input[name="payment_method"]', function(){
752        	if (parseInt(b2bking_display_settings.enable_payment_method_change_refresh) === 1){
753
754	        	setTimeout(function(){
755					jQuery(document.body).trigger("update_checkout");
756				},250);
757	        }
758        });
759		// Hook into updated checkout for WooCommerce
760		$( document ).on( 'updated_checkout', function() {
761
762		    // check VAT countries
763		    let vatCountries = $('#b2bking_custom_billing_vat_countries_field input').val();
764		    let billingCountry = $('#billing_country').val();
765		    if (vatCountries !== undefined){
766		    	if ( (! (vatCountries.includes(billingCountry))) || billingCountry.trim().length === 0){
767		    		$('.b2bking_vat_field_container').removeClass('b2bking_vat_visible, b2bking_vat_hidden').addClass('b2bking_vat_hidden');
768		    		$('.b2bking_vat_field_required_1 input').removeAttr('required');
769		    	} else {
770		    		$('.b2bking_vat_field_container').removeClass('b2bking_vat_visible, b2bking_vat_hidden').addClass('b2bking_vat_visible');
771		    		$('.b2bking_vat_field_required_1 .optional').after('<abbr class="required" title="required">*</abbr>');
772		    		$('.b2bking_vat_field_required_1 .optional').remove();
773		    		$('.b2bking_vat_field_required_1 input').prop('required','true');
774		    	}
775		    }
776		} );
777
778		// VALIDATE VAT AT CHECKOUT REGISTRATION
779		$('#b2bking_checkout_registration_validate_vat_button').on('click', function(){
780
781			$('#b2bking_checkout_registration_validate_vat_button').text(b2bking_display_settings.val
781idating);
782			var vatnumber = $('#b2bking_vat_number_registration_field').val();
783			if (vatnumber === undefined){
784				vatnumber = $('.b2bking_vat_field_container input[type="text"]').val().trim();
785			} else {
786				vatnumber = $('#b2bking_vat_number_registration_field').val().trim();
787			}
788			
789			var datavar = {
790	            action: 'b2bkingvalidatevat',
791	            security: b2bking_display_settings.security,
792	            vat: vatnumber,
793	            country: $('#billing_country').val(),
794	        };
795
796			$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
797				if (response === 'valid'){
798					createCookie('b2bking_validated_vat_status','validated_vat', false);
799					createCookie('b2bking_validated_vat_number', vatnumber, false);
800					$('#b2bking_vat_number_registration_field').prop('readonly', true);
801					$('#b2bking_checkout_registration_validate_vat_button').prop('disabled', true);
802					$('#b2bking_checkout_registration_validate_vat_button').text(b2bking_display_settings.vatvalid);
803					// refresh checkout for prices
804					$(document.body).trigger("update_checkout");
805				} else if (response === 'invalid'){
806
807					eraseCookie('b2bking_validated_vat_status');
808
809					$('#b2bking_checkout_registration_validate_vat_button').text(b2bking_display_settings.vatinvalid);
810				}
811			});
812		});
813
814		function createCookie(name, value, days) {
815		    var expires;
816
817		    if (days) {
818		        var date = new Date();
819		        date.setTime(date.getTime() + (days * 24 * 60 * 60 * parseFloat(b2bking_display_settings.cookie_expiration_days)));
820		        expires = "; expires=" + date.toGMTString();
821		    } else {
822		        expires = "";
823		    }
824		    document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
825		}
826
827		function eraseCookie(name) {
828		    createCookie(name, "", -1);
829		}
830
831		// if country is changed, re-run validation
832		$('.woocommerce-checkout #billing_country').change(function(){
833			eraseCookie('b2bking_validated_vat_status');
834			$('#b2bking_checkout_registration_validate_vat_button').text(b2bking_display_settings.validatevat);
835			$('#b2bking_vat_number_registration_field').prop('readonly', false);
836			$('#b2bking_vat_number_registration_field').val('');
837			$('#b2bking_checkout_registration_validate_vat_button').prop('disabled', false);
838			// refresh checkout for prices
839			$(document.body).trigger("update_checkout");
840		});
841
842		// Check if delivery country is different than shop country
843		if (parseInt(b2bking_display_settings.differentdeliverycountrysett
843ing) === 1){
844			// if setting is enabled
845			$('#shipping_country').change(exempt_vat_delivery_country);
846		}
847		function exempt_vat_delivery_country(){
848			var datavar = {
849	            action: 'b2bkingcheckdeliverycountryvat',
850	            security: b2bking_display_settings.security,
851	            deliverycountry: $('#shipping_country').val(),
852	        };
853
854			$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
855				setTimeout(function(){
856					$(document.body).trigger("update_checkout");
857				}, 250);
858			});
859		}
860
861		// add validation via JS to checkout
862		jQuery(function($){
863		    $('form.woocommerce-checkout').on( 'click', "#place_order", function(e){
864		   		var invalid = 'no';
865		        var fields = $(".b2bking_custom_field_req_required");
866		        $.each(fields, function(i, field) {
867			       	if ($(field).css('display') !== 'none' && $(field).parent().parent().css('display') !== 'none' && $(field).parent().css('display') !== 'none'){
868			       		if (!field.value || field.type === 'checkbox'){
869			       			let parent = $(field).parent();
870
871			       			let text = parent.find('label').text().slice(0,-2);
872			       			if (text === ''){
873			       				let parent = $(field).parent().parent();
874			       				let text = parent.find('label').text().slice(0,-2);
875			       				alert(text + ' ' + b2bking_display_settings.is_required);
876			       			} else {
877			       				alert(text + ' ' + b2bking_display_settings.is_required);
878			       			}
879			       			invalid = 'yes';
880			       		}
881			       	}
882		       }); 
883		    	
884		    	if (invalid === 'yes'){
885		    		e.preventDefault();
886		    		$('#b2bking_js_based_invalid').val('invalid');
887		    	} else {
888		    		$('#b2bking_js_based_invalid').val('0');
889		    	}     	
890   
891		    });
892		});
893
894		// force select a country on registration
895		$('button.woocommerce-form-register__submit').on('click',function(e){
896			if ($('.b2bking_country_field_selector').parent().css('display') !== 'none'){
897				if ($('.b2bking_country_field_selector select').val() === 'default'){
898					e.preventDefault();
899					alert(b2bking_display_settings.must_select_country);
900				}
901			}
902		});
903
904
905
906
907		/* Custom Registration Fields END */
908
909		/* Subaccounts START */
910		// On clicking 'New Subaccount'
911		$('.b2bking_subaccounts_container_top_button').on('click',function(){
912			// Hide subaccounts, show new subaccount
913			$('.b2bking_subaccounts_new_account_container').css('display','block');
914			$('.b2bking_subaccounts_account_container').css('display','none');
915			$('.b2bking_subaccounts_container_top_button').css('display','none');
916		});
917		// On clicking 'Close X', reverse
918		$('.b2bking_subaccounts_new_account_container_top_close').on('click',function(){
919			$('.b2bking_subaccounts_new_account_container').css('display','none');
920			$('.b2bking_subaccounts_account_container').css('display','block');
921			$('.b2bking_subaccounts_container_top_button').css('display','inline-flex');
922		});
923
924		// On clicking "Create new subaccount"
925		$('.b2bking_subaccounts_new_account_container_content_bottom_button').on('click',function(){
926			// clear displayed validation errors
927			$('.b2bking_subaccounts_new_account_container_content_bottom_validation_errors').html('');
928			let validationErrors = '';
929			// get username and email and password
930			let username = 123;
931			if (parseInt(b2bking_display_settings.disable_username_subaccounts) === 0){
932				username = $('input[name="b2bking_subaccounts_new_account_username"]').val().trim();
933			}
934			let email = $('input[name="b2bking_subaccounts_new_account_email_address"]').val().trim();
935			let password = $('input[name="b2bking_subaccounts_new_account_password"]').val().trim();
936
937			if (parseInt(b2bking_display_settings.disable_username_subaccounts) === 0){
938				// check against regex
939				if (/^(?!.*[_.]$)(?=.{8,30}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._-\d@]+$/.test(username) === false){
940					validationErrors += b2bking_display_settings.newSubaccountUsernameError;
941				}
942			}
943
944			if (/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email) === false){
945				validationErrors += b2bking_display_settings.newSubaccountEmailError;
946			}
947			if (/^(?=.*[A-Za-z])(?=.*[\d]).{8,}$/.test(password) === false){
948				validationErrors += b2bking_display_settings.newSubaccountPasswordError;
949			}
950
951			if (validationErrors !== ''){
952				// show errors
953				$('.b2bking_subaccounts_new_account_container_content_bottom_validation_errors').html(validationErrors);
954			} else {
955				// proceed with AJAX account registration request
956
957				// get all other data
958				let name = $('input[name="b2bking_subaccounts_new_account_name"]').val().trim();
959				let lastName = $('input[name="b2bking_subaccounts_new_account_last_name"]').val().trim();
960				let jobTitle = $('input[name="b2bking_subaccounts_new_account_job_title"]').val().trim();
961				let phone = $('input[name="b2bking_subaccounts_new_account_phone_number"]').val().trim();
962
963				// checkboxes are true or false
964				let checkboxBuy = $('input[name="b2bking_subaccounts_new_account_container_content_element_checkbox_buy"]').prop('checked'); 
965				let checkboxBuyApproval = $('input[name="b2bking_subaccounts_new_account_container_content_element_checkbox_buy_approval"]').prop('checked'); 
966				let checkboxViewOrders = $('input[name="b2bking_subaccounts_new_account_container_content_element_checkbox_view_orders"]').prop('checked');
967				let checkboxViewOffers = $('input[name="b2bking_subaccounts_new_account_container_
967content_element_checkbox_view_offers"]').prop('checked');
968				let checkboxViewConversations = $('input[name="b2bking_subaccounts_new_account_container_content_element_checkbox_view_conversations"]').prop('checked');
969				let checkboxViewLists = $('input[name="b2bking_subaccounts_new_account_container_content_element_checkbox_view_lists"]').prop('checked');
970
971				// replace icon with loader
972				// store icon
973				var buttonoriginal = $('.b2bking_subaccounts_new_account_container_content_bottom_button').html();
974				$('<img class="b2bking_loader_icon_button" src="'+b2bking_display_settings.loadertransparenturl+'">').insertBefore('.b2bking_subaccounts_new_account_container_content_bottom_button_icon');
975				$('.b2bking_subaccounts_new_account_container_content_bottom_button_icon').remove();
976
977				// send AJAX account creation request
978				var datavar = {
979		            action: 'b2bking_create_subaccount',
980		            security: b2bking_display_settings.security,
981		            username: username,
982		            password: password, 
983		            name: name,
984		            lastName: lastName,
985		            jobTitle: jobTitle,
986		            email: email,
987		            phone: phone,
988		            permissionBuy: checkboxBuy,
989		            permissionBuyApproval: checkboxBuyApproval,
990		            permissionViewOrders: checkboxViewOrders,
991		            permissionViewOffers: checkboxViewOffers,
992		            permissionViewConversations: checkboxViewConversations,
993		            permissionViewLists: checkboxViewLists,
994		        };
995
996				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
997					if (response.startsWith('error')){
998						console.log(response);
999						$('.b2bking_subaccounts_new_account_container_content_bottom_validation_errors').html(b2bking_display_settings.newSubaccountAccountError+': '+response);
1000						// hide loader, restore button
1001						$('.b2bking_subaccounts_new_account_container_content_bottom_button').html(buttonoriginal);
1002					} else if (response === 'error_maximum_subaccounts'){
1003						$('.b2bking_subaccounts_new_account_container_content_bottom_validation_errors').html(b2bking_display_settings.newSubaccountMaximumSubaccountsError);
1004						// hide loader, restore button
1005						$('.b2bking_subaccounts_new_account_container_content_bottom_button').html(buttonoriginal);
1006					} else {
1007						// go to subaccounts endpoint
1008						window.location = b2bking_display_settings.subaccountsurl;
1009					}
1010				});
1011			}
1012		});
1013
1014		// On clicking "Update subaccount"
1015		$('.b2bking_subaccounts_edit_account_container_content_bottom_button').on('click',function(){
1016			// get details and permissions
1017			let subaccountId = $('.b2bking_subaccounts_edit_account_container_content_bottom_button').val().trim();
1018			let name = $('input[name="b2bking_subaccounts_new_account_name"]').val().trim();
1019			let lastName = $('input[name="b2bking_subaccounts_new_account_last_name"]').val().trim();
1020			let jobTitle = $('input[name="b2bking_subaccounts_new_account_job_title"]').val().trim();
1021			let phone = $('input[name="b2bking_subaccounts_new_account_phone_number"]').val().trim();
1022
1023			// checkboxes are true or false
1024			let checkboxBuy = $('input[name="b2bking_subaccounts_new_account_container_
1024content_element_checkbox_buy"]').prop('checked'); 
1025			let checkboxBuyApproval = $('input[name="b2bking_subaccounts_new_account_container_content_element_checkbox_buy_approval"]').prop('checked'); 
1026			let checkboxViewOrders = $('input[name="b2bking_subaccounts_new_account_container_content_element_checkbox_view_orders"]').prop('checked');
1027			let checkboxViewOffers = $('input[name="b2bking_subaccounts_new_account_container_content_element_checkbox_view_offers"]').prop('checked');
1028			let checkboxViewConversations = $('input[name="b2bking_subaccounts_new_account_container_content_element_checkbox_view_conversations"]').prop('checked');
1029			let checkboxViewLists = $('input[name="b2bking_subaccounts_new_account_container_content_element_checkbox_view_lists"]').prop('checked');
1030
1031			// replace icon with loader
1032			$('<img class="b2bking_loader_icon_button" src="'+b2bking_display_settings.loadertransparenturl+'">').insertBefore('.b2bking_subaccounts_edit_account_container_content_bottom_button .b2bking_subaccounts_new_account_container_
1032content_bottom_button_icon');
1033			$('.b2bking_subaccounts_edit_account_container_content_bottom_button .b2bking_subaccounts_new_account_container_content_bottom_button_icon').remove();
1034
1035			// send AJAX account creation request
1036			var datavar = {
1037	            action: 'b2bking_update_subaccount',
1038	            security: b2bking_display_settings.security,
1039	            subaccountId: subaccountId,
1040	            name: name,
1041	            lastName: lastName,
1042	            jobTitle: jobTitle,
1043	            phone: phone,
1044	            permissionBuy: checkboxBuy,
1045	            permissionBuyApproval: checkboxBuyApproval,
1046	            permissionViewOrders: checkboxViewOrders,
1047	            permissionViewOffers: checkboxViewOffers,
1048	            permissionViewConversations: checkboxViewConversations,
1049	            permissionViewLists: checkboxViewLists,
1050	        };
1051
1052	        $.post(b2bking_display_settings.ajaxurl, datavar, function(response){
1053				// go to subaccounts endpoint
1054				window.location = b2bking_display_settings.subaccountsurl;
1055			});
1056		});
1057
1058		// on clicking close inside subaccount edit
1059		$('.b2bking_subaccounts_edit_account_container_top_close').on('click',function(){
1060			// go to subaccounts endpoint
1061			window.location = b2bking_display_settings.subaccountsurl;
1062		});
1063
1064		// on clicking delete user, run same function as reject user
1065		$('.b2bking_subaccounts_edit_account_container_content_bottom_button_delete').on('click', function(){
1066			if (confirm(b2bking_display_settings.are_you_sure_delete)){
1067				// replace icon with loader
1068				$('<img class="b2bking_loader_icon_button" src="'+b2bking_display_settings.loadertransparenturl+'">').insertBefore('.b2bking_subaccounts_edit_account_container_content_bottom_button_delete .b2bking_subaccounts_new_account_container_content_bottom_button_icon');
1069				$('.b2bking_subaccounts_edit_account_container_content_bottom_button_delete .b2bking_subaccounts_new_account_container_content_bottom_button_icon').remove();
1070
1071				var datavar = {
1072		            action: 'b2bkingrejectuser',
1073		            security: b2bking_display_settings.security,
1074		            user: $('.b2bking_subaccounts_edit_account_container_content_bottom_button').val().trim(),
1075		            issubaccount: 'yes',
1076		        };
1077
1078				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
1079					// go to subaccounts endpoint
1080					window.location = b2bking_display_settings.subaccountsurl;
1081				});
1082			}
1083		});
1084
1085		showHideApproval();
1086		$('input[name="b2bking_subaccounts_new_account_container_content_element_checkbox_buy').on('change', showHideApproval);
1087		function showHideApproval(){
1088			if($('input[name="b2bking_subaccounts_new_account_container_content_element_checkbox_buy').prop('checked')) {
1089		    	$('.b2bking_checkbox_permission_approval').css('display','flex');
1090		    } else {      
1091		    	$('.b2bking_checkbox_permission_approval').css('display','none');
1092		    }
1093		}	
1094
1095		// click on approve / reject order
1096		$('#b2bking_approve_order').on('click', function(){
1097
1098			let orderid = $('#b2bking_order_number').val();
1099
1100			if (confirm(b2bking_display_settings.approve_order_confirm)){
1101				var datavar = {
1102		            action: 'b2bking_approve_order',
1103		            security: b2bking_display_settings.security,
1104		            orderid: orderid
1105		        };
1106
1107		        console.log(datavar);
1108
1109
1110				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
1111					location.reload();
1112				});
1113			}
1114					
1115		});
1116
1117		$('#b2bking_reject_order').on('click', function(){
1118			let orderid = $('#b2bking_order_number').val();
1119
1120			if (confirm(b2bking_display_settings.reject_order_confirm)){
1121				var datavar = {
1122		            action: 'b2bking_reject_order',
1123		            security: b2bking_display_settings.security,
1124		            orderid: orderid
1125		        };
1126
1127
1128				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
1129					location.reload();
1130				});
1131			}
1132		});
1133
1134		/* Subaccounts END */
1135
1136		/* Bulk order form START */
1137
1138		/* Disallow entering numbers directly based on min max */
1139		$('body').on('input', '.b2bking_bulkorder_form_container_content_line_qty_indigo', function(e){
1140		    let v = parseInt($(this).val());
1141		    let min = parseInt($(this).attr('min'));
1142		    let max = parseInt($(this).attr('max'));
1143
1144		    if (v < min){
1145		        $(this).val(min);
1146		    } else if (v > max){
1147		        $(this).val(max);
1148		    }
1149		});
1150
1151		// On clicking "new line", prepend newline to button container
1152		var pricetextvar = b2bking_display_settings.currency_symbol+'0';
1153		if (parseInt(b2bking_display_settings.accountingsubtotals) === 1){
1154			pricetextvar = b2bking_display_settings.price0;
1155		}
1156		if (parseInt(b2bking_display_settings.quotes_enabled) === 1){
1157			pricetextvar = b2bking_display_settings.quote_text;
1158		}
1159
1160		$('.b2bking_bulkorder_form_container_newline_button').on('click', function() {
1161			// Clone template.
1162			var template = $('.b2bking_bulkorder_form_newline_template').html();
1163			template = template.replace('pricetext',pricetextvar);
1164			template = template.replace('display:none','display:initial');
1165			// add line
1166			$('.b2bking_bulkorder_form_container_newline_container').before(template);
1167		});
1168
1169		// on click 'save list' in bulk order form
1170		
1171		$('.b2bking_bulkorder_form_container_bottom_save_button').on('click', function(){
1172			let title = window.prompt(b2bking_display_settings.save_list_name, "");
1173
1174			if (title !== '' && title !== null){
1175
1176				let productString = ''; 
1177				// loop through all bulk order form lines
1178				document.querySelectorAll('.b2bking_bulkorder_form_container_
1178content_line_product').forEach(function(textinput) {
1179					var classList = $(textinput).attr('class').split(/\s+/);
1180					$.each(classList, function(index, item) {
1181						// foreach line if it has selected class, get selected product ID 
1182					    if (item.includes('b2bking_selected_product_id_')) {
1183					    	let productID = item.split('_')[4];
1184					    	let quantity = $(textinput).parent().find('.b2bking_bulkorder_form_container_content_line_qty').val();
1185				    		if (quantity > 0 || parseInt(b2bking_display_settings.lists_zero_qty) === 1){
1186					    		// set product
1187					    		productString+=productID+':'+quantity+'|';
1188					    	}
1189					    }
1190					});
1191				});
1192				// if not empty, send
1193				if (productString !== ''){
1194					// replace icon with loader
1195					var buttonoriginal = $('.b2bking_bulkorder_form_container_bottom_save_button').html();
1196					$('<img class="b2bking_loader_icon_button" src="'+b2bking_display_settings.loadertransparenturl+'">').insertBefore('.b2bking_bulkorder_form_container_bottom_save_button_icon');
1197					$('.b2bking_bulkorder_form_container_bottom_save_button_icon').remove();
1198
1199					// build pricelist to be saved
1200					let pricestringsend = '';
1201					Object.entries(prices).forEach(function (index) {
1202						let idstring = index[0];
1203						let price = index[1];
1204						let id = idstring.split('B2BKINGPRICE')[0];
1205						pricestringsend += id+':'+price+'|';
1206					});
1207
1208					var datavar = {
1209			            action: 'b2bking_bulkorder_save_list',
1210			            security: b2bking_display_settings.security,
1211			            productstring: productString,
1212			            title: title,
1213			            pricelist: pricestringsend
1214			        };
1215
1216
1217					$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
1218						// restore button
1219						$('.b2bking_bulkorder_form_container_bottom_save_button').html(buttonoriginal);
1220						alert(b2bking_display_settings.list_saved);
1221					});
1222				} else {
1223					alert(b2bking_display_settings.list_empty);
1224				}	
1225			}
1226		});
1227		
1228
1229		var latestSearchTime = Date.now();
1230
1231		$('body').on('input', '.b2bking_bulkorder_form_container_content_line_qty', function(e){
1232			let val = $(this).val();
1233			if(val % 1 != 0){
1234				$(this).val(parseInt(val));
1235			}
1236		});
1237
1238		$('body').on('input', '.b2bking_bulkorder_form_container_content_line_product', function(){
1239			let thisSearchTime = Date.now();
1240			latestSearchTime = thisSearchTime;
1241			let parent = $(this).parent();
1242			let inputValue = $(this).val();
1243			let searchbyval = $('#b2bking_bulkorder_searchby_select').val();
1244			if (typeof(searchbyval) === "undefined"){
1245				searchbyval = 'productname';
1246			}
1247			parent.find('.b2bking_bulkorder_form_container_content_line_livesearch').html('<img class="b2bking_loader_img" src="'+b2bking_display_settings.loaderurl+'">');
1248			parent.find('.b2bking_bulkorder_form_container_content_line_livesearch').css('display','block');
1249
1250			var excludeval = $('#b2bking_bulkorder_exclude').val();
1251			var categoryval = $('#b2bking_bulkorder_category').val();
1252			var sortby = $('#b2bking_bulkorder_sortby').val();
1253
1254
1255			if (inputValue.length > 0){ // min x chars
1256
1257				// set timer for 600ms before loading the ajax search (resource consuming)
1258				setTimeout(function(){
1259
1260					// if in the last 2 seconds there's been no new searches or input
1261					if (thisSearchTime === latestSearchTime){
1262						// run search AJAX function 
1263						let formids = getIdsInForm();
1264						var datavar = {
1265				            action: 'b2bking_ajax_search',
1266				            security: b2bking_display_settings.security,
1267				            searchValue: inputValue,
1268				            exclude: excludeval,
1269				            category: categoryval,
1270				            sortby: sortby,
1271				            searchby: searchbyval,
1272				            idsinform: JSON.stringify(formids),
1273				            dataType: 'json'
1274				        };
1275
1276						$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
1277							let display = '';
1278							let results = response;
1279							if (thisSearchTime === latestSearchTime){
1280								if (parseInt(results) !== 1234){ // 1234 Integer for Empty
1281									let resultsObject = JSON.parse(results);
1282									Object.keys(resultsObject).forEach(function (index) {
1283										if (index.includes('B2BKINGPRICE')){
1284											prices[index] = resultsObject[index];
1285										} else if (index.includes('B2BTIERPRICE')){
1286											pricetiers[index] = resultsObject[index];
1287										} else if (index.includes('B2BKINGSTOCK')){
1288											stock[index] = resultsObject[index];
1289										} else if (index.includes('B2BKINGIMAGE')){
1290											images[index] = resultsObject[index];
1291										} else {
1292											if (parseInt(b2bking_display_settings.bulkorderformimages) === 1){
1293												let img = index+'B2BKINGIMAGE';
1294												if (resultsObject[img] !== 'no' && resultsObject[img] !== '' && resultsObject[img] !== null){
1295													display += '<div class="b2bking_livesearch_product_result productid_'+index+'">'+resultsObject[index]+'<img class="b2bking_livesearch_image" src="'+resultsObject[img]+'"></div>';
1296												} else {
1297													display += '<div class="b2bking_livesearch_product_result productid_'+index+'">'+resultsObject[index]+'</div>';
1298												}
1299											} else {
1300												display += '<div class="b2bking_livesearch_product_result productid_'+index+'">'+resultsObject[index]+'</div>';
1301											}
1302											
1303										}
1304									});
1305
1306
1307								} else {
1308									display = b2bking_display_settings.no_products_found;
1309								}
1310								
1311								parent.find('.b2bking_bulkorder_form_container_content_line_livesearch').html(display);
1312							}
1313						});
1314					}
1315				}, 600);
1316				
1317			} else {
1318				parent.find('.b2bking_bulkorder_form_container_content_line_livesearch').css('display','none');
1319			}
1320		});
1321
1322		var prices = Object;
1323		var stock = Object;
1324		var pricetiers = Object;
1325		var images = Object;
1326		var currentline;
1327
1328		// let's populate prices initially from the html value
1329		let initialhtmlprices = $('#b2bking_initial_prices').val();
1330		if (initialhtmlprices !== undefined){
1331			let htmlprices = initialhtmlprices.split('|');
1332			htmlprices.forEach(function(textinput) {
1333				let idprice = textinput.split('-');
1334				if (idprice[0] !== ''){
1335					prices[idprice[0]+'B2BKINGPRICE'] = parseFloat(idprice[1]);
1336					pricetiers[idprice[0]+'B2BTIERPRICE'] = idprice[2];
1337					stock[idprice[0]+'B2BKINGSTOCK'] = parseInt(idprice[3]);
1338				}
1339				
1340			});
1341		}
1342
1343
1344		// on clicking on search result, set result in field
1345		$('body').on('click', '.b2bking_livesearch_product_result', function(){
1346			let title = $(this).text();
1347			let parent = $(this).parent().parent();
1348			currentline = parent;
1349			var classList = $(this).attr('class').split(/\s+/);
1350			$.each(classList, function(index, item) {
1351			    if (item.includes('productid')) {
1352
1353			        let productID = item.split('_')[1];
1354	        		// set input disabled
1355			        parent.find('.b2bking_bulkorder_form_container_content_line_product').val(title);
1356			        parent.find('.b2bking_bulkorder_form_container_content_line_product').css('color', b2bking_display_settings.colorsetting );
1357			        parent.find('.b2bking_bulkorder_form_container_content_line_product').css('font-weight', 'bold');
1358			        parent.find('.b2bking_bulkorder_form_container_content_line_product').addClass('b2bking_selected_product_id_'+productID);
1359			        parent.find('.b2bking_bulkorder_form_container_content_line_product').after('<button class="b2bking_bulkorder_clear">'+b2bking_display_settings.clearx+'</button>');
1360			        parent.find('.b2bking_bulkorder_form_container_content_line_qty').val(1);
1361
1362			        setTimeout(function(){
1363			        	parent.find('.b2bking_bulkorder_form_container_content_line_product').prop('disabled', true);
1364			        	parent.find('.b2bking_bulkorder_form_container_content_line_livesearch').css('display','none');
1365			        },125);
1366
1367			        // Set max stock on item
1368			        if (stock[productID+'B2BKINGSTOCK'] !== null){
1369			        	parent.find('.b2bking_bulkorder_form_container_content_line_qty').attr('max', stock[productID+'B2BKINGSTOCK']);
1370			        }
1371			        
1372			       
1373			    }
1374			});
1375			if (parseInt(b2bking_display_settings.quotes_enabled) !== 1){
1376				calculateBulkOrderTotals();
1377			}
1378		});
1379
1380		$('body').on('click', '.b2bking_bulkorder_clear', function(){
1381			let parent = $(this).parent();
1382			currentline = parent;
1383			let line = parent.find('.b2bking_bulkorder_form_container_content_line_product');
1384			let qty = parent.find('.b2bking_bulkorder_form_container_content_line_qty');
1385			line.prop('disabled', false);
1386			qty.removeAttr('max');
1387			line.removeAttr("style");
1388			line.val('');
1389			qty.val('');
1390			var classList = line.attr('class').split(/\s+/);
1391			$.each(classList, function(index, item) {
1392			    if (item.includes('b2bking_selected_product_id_')) {
1393			    	line.removeClass(item);
1394			    }
1395			});
1396
1397			if (parseInt(b2bking_display_settings.quotes_enabled) !== 1){
1398				calculateBulkOrderTotals();
1399			}
1400			$(this).remove();
1401
1402		});
1403
1404		// on click add to cart
1405		$('.b2bking_bulkorder_form_container_bottom_add_button').on('click', function(){
1406
1407			let productString = ''; 
1408			// loop through all bulk order form lines
1409			document.querySelectorAll('.b2bking_bulkorder_form_container_
1409content_line_product').forEach(function(textinput) {
1410				var classList = $(textinput).attr('class').split(/\s+/);
1411				$.each(classList, function(index, item) {
1412					// foreach line if it has selected class, get selected product ID 
1413				    if (item.includes('b2bking_selected_product_id_')) {
1414				    	let productID = item.split('_')[4];
1415				    	let quantity = $(textinput).parent().find('.b2bking_bulkorder_form_container_content_line_qty').val();
1416				    	if (quantity > 0){
1417				    		// set product
1418				    		productString+=productID+':'+quantity+'|';
1419				    	}
1420				    }
1421				});
1422			});
1423			// if not empty, send
1424			if (productString !== ''){
1425				// replace icon with loader
1426				$('<img class="b2bking_loader_icon_button" src="'+b2bking_display_settings.loadertransparenturl+'">').insertBefore('.b2bking_bulkorder_form_container_bottom_add_button_icon');
1427				$('.b2bking_bulkorder_form_container_bottom_add_button_icon').remove();
1428				var datavar = {
1429		            action: 'b2bking_bulkorder_add_cart',
1430		            security: b2bking_display_settings.security,
1431		            productstring: productString,
1432		        };
1433
1434				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
1435					window.location = b2bking_display_settings.carturl;
1436				});
1437			}
1438		});
1439
1440		// on product or quantity change, calculate totals
1441		$('body').on('input', '.b2bking_bulkorder_form_container_content_line_qty', function(){
1442			// enforce max (stock)
1443			var max = parseInt($(this).attr('max'));
1444
1445
1446			var textinput = $(this).parent().find('.b2bking_bulkorder_form_container_content_line_product');
1447			var classes = $(textinput).attr('class');
1448			var theme = '';
1449			if (classes === undefined){
1450				textinput = $(this).parent().parent().parent().find('.b2bking_bulkorder_form_container_content_line_product');
1451				classes = $(textinput).attr('class');
1452				theme = 'cream';
1453			}
1454
1455			var productID = 0;
1456			var classList = classes.split(/\s+/);
1457			$.each(classList, function(index, item) {
1458				// foreach line if it has selected class, get selected product ID 
1459			    if (item.includes('b2bking_selected_product_id_')) {
1460			    	productID = item.split('_')[4];
1461			    }
1462			});
1463
1464			let totalQuantity = $(this).val();
1465			var cartQuantity = 0;
1466
1467			if (b2bking_display_settings.cart_quantities[productID] !== undefined){
1468				cartQuantity = parseInt(b2bking_display_settings.cart_quantities[productID]);
1469				totalQuantity = parseInt(totalQuantity) + cartQuantity;
1470			}
1471
1472			if (parseInt(b2bking_display_settings.cart_quantities_cartqty) !== 0){
1473				cartQuantity = parseInt(b2bking_display_settings.cart_quantities_cartqty);
1474				totalQuantity = parseInt(totalQuantity) + cartQuantity;
1475			}
1476			
1477	        if (totalQuantity > max){
1478	            $(this).val((max-cartQuantity));
1479
1480	            let parent = $(this).parent();
1481	            // get max stock message
1482	            let newval = b2bking_display_settings.max_items_stock;
1483	            newval = newval.replace('%s', max);
1484
1485	            // if message is not set to max stock, set it
1486	            let currentval = parent.find('.b2bking_bulkorder_form_container_
1486content_line_product').val();
1487
1488	            if (currentval !== newval){
1489	            	let originalval = parent.find('.b2bking_bulkorder_form_container_content_line_product').val();
1490	            	let originalcolor = parent.find('.b2bking_bulkorder_form_container_content_line_product').css('color');
1491	            	
1492	            	parent.find('.b2bking_bulkorder_form_container_content_line_product').val(newval);
1493	            	parent.find('.b2bking_bulkorder_form_container_content_line_product').css('color','rgb(194 25 25)');
1494	            	setTimeout(function(){
1495	            		parent.find('.b2bking_bulkorder_form_container_content_line_product').val(originalval);
1496	            		parent.find('.b2bking_bulkorder_form_container_content_line_product').css('color',originalcolor);
1497	            	}, 1200);
1498	            }
1499	            
1500	        }
1501
1502			currentline = $(this).parent();
1503			if (theme === 'cream'){
1504				currentline = $(this).parent().parent().parent();
1505			}
1506			if (parseInt(b2bking_display_settings.quotes_enabled) !== 1){
1507				calculateBulkOrderTotals();
1508			}
1509		});
1510
1511		function getIdsInForm(){
1512			var ids = [];
1513
1514			// loop through all bulk order form lines
1515			document.querySelectorAll('.b2bking_bulkorder_form_container_
1515content_line_product').forEach(function(textinput) {
1516				var classList = $(textinput).attr('class').split(/\s+/);
1517				$.each(classList, function(index, item) {
1518					// foreach line if it has selected class, get selected product ID 
1519				    if (item.includes('b2bking_selected_product_id_')) {
1520				    	let productID = item.split('_')[4];
1521				    	ids.push(productID);
1522				    }
1523				});
1524			});
1525
1526			return ids;
1527
1528		}
1529
1530		
1531
1532		function calculateBulkOrderTotals(){
1533			let total = 0;
1534			// loop through all bulk order form lines
1535			let textinput = currentline.find('.b2bking_bulkorder_form_container_content_line_product');
1536
1537
1538			var classList = $(textinput).attr('class').split(/\s+/);
1539			$.each(classList, function(index, item) {
1540				// foreach line if it has selected class, get selected product ID 
1541			    if (item.includes('b2bking_selected_product_id_')) {
1542			    	let productID = item.split('_')[4];
1543			    	let quantity = $(textinput).parent().find('.b2bking_bulkorder_form_container_content_line_qty').val();
1544			    	if (quantity > 0){
1545	    				let index = productID + 'B2BKINGPRICE';
1546	    				let price = parseFloat(prices[index]);
1547
1548	    				// find if there's tiered pricing
1549	    				let indexTiers = productID + 'B2BTIERPRICE';    				
1550	    				let tieredprice = pricetiers[indexTiers];
1551	    				// if have tiered price
1552
1553	    				if (tieredprice !== 0){
1554	    					// get total quantity (form + cart)
1555	    					let totalQuantity = quantity;
1556	    					if (b2bking_display_settings.cart_quantities[productID] !== undefined){
1557	    						let cartQuantity = parseInt(b2bking_display_settings.cart_quantities[productID]);
1558	    						totalQuantity = parseInt(quantity) + cartQuantity;
1559	    					}
1560
1561	    					if (parseInt(b2bking_display_settings.cart_quantities_cartqty) !== 0){
1562	    						totalQuantity = parseInt(totalQuantity) + parseInt(b2bking_display_settings.cart_quantities_cartqty);
1563	    					}
1564
1565	    					// get all ranges
1566	    					let ranges = tieredprice.split(';');
1567	    					let quantities_array = [];
1568	    					let prices_array = [];
1569	    					// first eliminate all quantities larger than the total quantity
1570	    					$.each(ranges, function(index, item) {
1571	    						let tier_values = item.split(':');
1572	    						tier_values[0] = parseInt(tier_values[0]);
1573	    						tier_values[1] = parseFloat(tier_values[1]);
1574
1575	    						if (tier_values[0] <= totalQuantity ){
1576	    							quantities_array.push(tier_values[0]);
1577	    							prices_array[tier_values[0]] = tier_values[1];
1578	    						}
1579	    					});
1580	    					
1581	    					if (quantities_array.length > 0){
1582	    						// continue and try to find price
1583	    						let largest = Math.max(...quantities_array);
1584	    						let finalpricetier = prices_array[largest];
1585	    						// only set it if the tier price is smaller than the group price
1586	    						if (price > finalpricetier){
1587	    							price = finalpricetier;
1588	    						}
1589	    					}
1590	    				}
1591
1592	    				let subtotal = price * quantity;
1593	    				subtotal = parseFloat(subtotal.toFixed(2));
1594	    				setTimeout(function(){
1595	    					if (parseInt(b2bking_display_settings.accountingsubtotals) === 1){
1596	    						// get price html via WC PRICE
1597								var datavar = {
1598						            action: 'b2bking_accountingsubtotals',
1599						            security: b2bking_display_settings.security,
1600						            pricesent: subtotal,
1601						        };
1602
1603								$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
1604									$(textinput).parent().find('.b2bking_bulkorder_form_container_
1604content_line_subtotal').html(response);
1605								});
1606
1607	    					} else {
1608	    						$(textinput).parent().find('.b2bking_bulkorder_form_container_content_line_subtotal').text(b2bking_display_settings.currency_symbol+subtotal);
1609	    					}
1610	    				}, 100);
1611
1612			    	} else {
1613			    		$(textinput).parent().find('.b2bking_bulkorder_form_container_content_line_subtotal').text(b2bking_display_settings.currency_symbol+0);
1614			    	}
1615			    } else {
1616			    	if (isIndigo === undefined){
1617				    	if ($(textinput).val() === ''){
1618				    		$(textinput).parent().find('.b2bking_bulkorder_form_container_content_line_subtotal').text(b2bking_display_settings.currency_symbol+0);	
1619				    	}
1620				    }
1621			    }
1622			});
1623
1624			
1625
1626			document.querySelectorAll('.b2bking_bulkorder_form_container_content_line_product').forEach(function(textinput) {
1627				var classList = $(textinput).attr('class').split(/\s+/);
1628				$.each(classList, function(index, item) {
1629					// foreach line if it has selected class, get selected product ID 
1630				    if (item.includes('b2bking_selected_product_id_')) {
1631				    	let productID = item.split('_')[4];
1632				    	let quantity = $(textinput).parent().find('.b2bking_bulkorder_form_container_
1632content_line_qty').val();
1633				    	if (quantity > 0){
1634		    				let index = productID + 'B2BKINGPRICE';
1635		    				let price = parseFloat(prices[index]);
1636
1637
1638		    				// find if there's tiered pricing
1639		    				let indexTiers = productID + 'B2BTIERPRICE';
1640		    				let tieredprice = pricetiers[indexTiers];
1641
1642		    				// if have tiered price
1643		    				if (tieredprice !== 0){
1644		    					// get total quantity (form + cart)
1645		    					let totalQuantity = quantity;
1646		    					if (b2bking_display_settings.cart_quantities[productID] !== undefined){
1647		    						let cartQuantity = parseInt(b2bking_display_settings.cart_quantities[productID]);
1648		    						totalQuantity = parseInt(quantity) + cartQuantity;
1649		    					}
1650
1651		    					if (parseInt(b2bking_display_settings.cart_quantities_cartqty) !== 0){
1652		    						totalQuantity = parseInt(quantity) + parseInt(b2bking_display_settings.cart_quantities_cartqty);
1653		    					}
1654
1655		    					// get all ranges
1656		    					let ranges = tieredprice.split(';');
1657		    					let quantities_array = [];
1658		    					let prices_array = [];
1659		    					// first eliminate all quantities larger than the total quantity
1660		    					$.each(ranges, function(index, item) {
1661		    						let tier_values = item.split(':');
1662		    						tier_values[0] = parseInt(tier_values[0]);
1663		    						tier_values[1] = parseFloat(tier_values[1]);
1664
1665		    						if (tier_values[0] <= totalQuantity ){
1666		    							quantities_array.push(tier_values[0]);
1667		    							prices_array[tier_values[0]] = tier_values[1];
1668		    						}
1669		    					});
1670		    					
1671		    					if (quantities_array.length > 0){
1672		    						// continue and try to find price
1673		    						let largest = Math.max(...quantities_array);
1674		    						let finalpricetier = prices_array[largest];
1675		    						// only set it if the tier price is smaller than the group price
1676		    						if (price > finalpricetier){
1677		    							price = finalpricetier;
1678		    						}
1679		    					}
1680		    				}
1681
1682
1683		    				let subtotal = price * quantity;
1684		    				subtotal = parseFloat(subtotal.toFixed(2));
1685
1686		    				total = total + subtotal;
1687		    				total = parseFloat(total.toFixed(2));
1688				    	}
1689				    }
1690				});
1691
1692			});
1693
1694
1695			if (parseInt(b2bking_display_settings.accountingsubtotals) === 1){
1696				// get price html via WC PRICE
1697				var datavar = {
1698		            action: 'b2bking_accountingsubtotals',
1699		            security: b2bking_display_settings.security,
1700		            pricesent: total,
1701		        };
1702
1703				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
1704					$('.b2bking_bulkorder_form_container_bottom_total .woocommerce-Price-amount').html(response);
1705				});
1706
1707			} else {
1708				$('.b2bking_bulkorder_form_container_bottom_total .woocommerce-Price-amount').text(b2bking_display_settings.currency_symbol+total);	
1709			}
1710
1711		}
1712
1713		// if this is indigo order form
1714		if (isIndigo !== undefined){
1715			// add "selected" style to list items
1716			// get pricing details that will allow to calculate subtotals
1717			document.querySelectorAll('.b2bking_bulkorder_form_container_
1717content_line_product').forEach(function(textinput) {
1718				let inputValue = $(textinput).val().split(' (')[0];
1719				var datavar = {
1720		            action: 'b2bking_ajax_search',
1721		            security: b2bking_display_settings.security,
1722		            searchValue: inputValue,
1723		            searchType: 'purchaseListLoading',
1724		            dataType: 'json'
1725		        };
1726
1727				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
1728					let results = response;
1729					if (results !== '"empty"'){
1730						let resultsObject = JSON.parse(results);
1731						Object.keys(resultsObject).forEach(function (index) {
1732							if (index.includes('B2BKINGPRICE')){
1733								prices[index] = resultsObject[index];
1734							} else if (index.includes('B2BTIERPRICE')){
1735								pricetiers[index] = resultsObject[index];
1736							} else if (index.includes('B2BKINGSTOCK')){
1737								stock[index] = resultsObject[index];
1738							}
1739						});
1740					}
1741				});
1742				var productID = 0;
1743				var classList = $(textinput).attr('class').split(/\s+/);
1744				$.each(classList, function(index, item) {
1745				    if (item.includes('b2bking_selected_product_id_')) {
1746				    	productID = item.split('_')[4];
1747				    }
1748				});
1749
1750				// Set max stock on item
1751				if (stock[productID+'B2BKINGSTOCK'] !== null){
1752					$(textinput).parent().find('.b2bking_bulkorder_form_container_
1752content_line_qty').attr('max', stock[productID+'B2BKINGSTOCK']);
1753				}
1754
1755				currentline = $(textinput).parent();
1756				if (parseInt(b2bking_display_settings.quotes_enabled) !== 1){
1757					calculateBulkOrderTotals();
1758				}
1759				
1760			});
1761
1762			// plus minus buttons
1763			$('body').on('click', '.b2bking_cream_input_plus_button', function(){
1764				let input = $(this).parent().find('input');
1765				input[0].stepUp(1);
1766				$(input).trigger('input');
1767
1768			});
1769			$('body').on('click', '.b2bking_cream_input_minus_button', function(){
1770				let input = $(this).parent().find('input');
1771				input[0].stepDown(1);
1772				$(input).trigger('input');
1773			});
1774
1775			// add to cart button
1776			$('body').on('click', '.b2bking_bulkorder_indigo_add', function(){
1777
1778				// cancel add to cart function if this is view options button
1779				if ($(this).hasClass('b2bking_cream_view_options_button')){
1780					return;
1781				}
1782				if ($(this).hasClass('b2bking_none_in_stock')){
1783					return;
1784				}
1785				
1786
1787				// loader icon
1788				// if does not have none_in_stock class
1789				let thisbutton = $(this);
1790
1791				if (!$(this).hasClass('b2bking_none_in_stock')){
1792					$(this).html('<img class="b2bking_loader_icon_button_indigo" src="'+b2bking_display_settings.loadertransparenturl+'">');
1793				}
1794
1795				let textinput = $(this).parent().parent().find('.b2bking_bulkorder_form_container_
1795content_line_product');
1796
1797				var classes = $(textinput).attr('class');
1798				var theme = '';
1799				if (classes === undefined){
1800					textinput = $(this).parent().parent().parent().find('.b2bking_bulkorder_form_container_content_line_product');
1801					classes = $(textinput).attr('class');
1802					theme = 'cream';
1803				}
1804
1805
1806				var productID = 0;
1807				var classList = classes.split(/\s+/);
1808				$.each(classList, function(index, item) {
1809					// foreach line if it has selected class, get selected product ID 
1810				    if (item.includes('b2bking_selected_product_id_')) {
1811				    	productID = item.split('_')[4];
1812				    }
1813				});
1814				let qty = $(this).parent().parent().find('.b2bking_bulkorder_form_container_content_line_qty').val();
1815
1816
1817				// run stock quantity addable check			
1818				var datavar = {
1819		            action: 'b2bking_get_stock_quantity_addable',
1820		            security: b2bking_display_settings.security,
1821		            id: productID,
1822		        };
1823
1824		        var qtyaddable = 9999999;
1825				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
1826					qtyaddable = parseInt(response);
1827
1828					// if quantity addable is higher (or equal) than quantity requested, proceed
1829					if (qtyaddable === 9875678){ // number represents is sold individually, already in cart
1830						$(thisbutton).addClass('b2bking_none_in_stock');
1831						$(thisbutton).html(b2bking_display_settings.already_in_cart);
1832						$(thisbutton).parent().parent().find('.b2bking_bulkorder_form_container_
1832content_line_qty').val(0);
1833						$(thisbutton).parent().parent().find('.b2bking_bulkorder_form_container_content_line_qty').attr('max', 0);
1834
1835					} else if (qtyaddable >= qty && qty !== 0){
1836						var datavar = {
1837				            action: 'b2bking_bulkorder_add_cart_item',
1838				            security: b2bking_display_settings.security,
1839				            productid: productID,
1840				            productqty: qty,
1841				        };
1842
1843						$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
1844							if (response === 'success'){
1845								$(thisbutton).removeClass('b2bking_low_in_stock');
1846								$(thisbutton).removeClass('b2bking_none_in_stock');
1847
1848								// Refresh cart fragments
1849								$( document.body ).trigger( 'wc_fragment_refresh' );
1850
1851								// update product qty icon
1852								let currentqty = parseInt($(thisbutton).parent().parent().parent().find('.b2bking_cream_product_nr_icon').text());
1853								let newqty = parseInt(qty)+currentqty;
1854								$(thisbutton).parent().parent().parent().find('.b2bking_cream_product_nr_icon').text(newqty);
1855								$(thisbutton).parent().parent().parent().find('.b2bking_cream_product_nr_icon').removeClass('b2bking_cream_product_nr_icon_hidden');
1856
1857								let newqtyaddable = qtyaddable-qty;
1858		
1859								if (newqtyaddable > 0){
1860									// set button to 'Add more'
1861									$(thisbutton).html(b2bking_display_settings.add_more_indigo);
1862
1863									// if quantity left is lower than the quantity set in qty, lower qty to the qty left
1864									if (newqtyaddable < qty){
1865										$(thisbutton).parent().parent().find('.b2bking_bulkorder_form_container_
1865content_line_qty').val(newqtyaddable);
1866									}
1867								} else {
1868									// 0 left in stock, permanently grey button
1869									$(thisbutton).addClass('b2bking_none_in_stock');
1870									$(thisbutton).html('0 ' + b2bking_display_settings.left_in_stock);
1871									$(thisbutton).parent().parent().find('.b2bking_bulkorder_form_container_content_line_qty').val(0);
1872									$(thisbutton).parent().parent().find('.b2bking_bulkorder_form_container_content_line_qty').attr('max', 0);
1873
1874								}
1875								
1876								
1877							}
1878						});
1879					} else if (qtyaddable === 0){
1880						// 0 left in stock, permanently grey button
1881						$(thisbutton).addClass('b2bking_none_in_stock');
1882
1883						$(thisbutton).html('0 ' + b2bking_display_settings.left_in_stock);
1884						$(thisbutton).parent().parent().find('.b2bking_bulkorder_form_container_content_line_qty').val(0);
1885						$(thisbutton).parent().parent().find('.b2bking_bulkorder_form_container_content_line_qty').attr('max', 0);
1886
1887
1888					} else {
1889						// x left in stock, temporarily grey button
1890						$(thisbutton).html(b2bking_display_settings.left_in_stock_low_left + qtyaddable + b2bking_display_settings.left_in_stock_low_right);
1891						$(thisbutton).addClass('b2bking_low_in_stock');
1892						// set qty of the item to the qty left
1893						$(thisbutton).parent().parent().find('.b2bking_bulkorder_form_container_
1893content_line_qty').val(qtyaddable);
1894
1895						// restore button to default
1896						setTimeout(function(){
1897							$(thisbutton).removeClass('b2bking_low_in_stock');
1898							$(thisbutton).html(b2bking_display_settings.add_to_cart);
1899						}, 2500);
1900
1901					}
1902					
1903				});
1904
1905				
1906
1907			});
1908
1909			// search indigo form
1910			$('#b2bking_bulkorder_search_text_indigo').not('.b2bking_bulkorder_search_text_cream').on('input', function(){
1911
1912				let thisSearchTime = Date.now();
1913				latestSearchTime = thisSearchTime;
1914
1915		        if ($('#b2bking_bulkorder_search_text_indigo').length > 0){ // min x chars
1916
1917		        	// show loader
1918		        	$('.b2bking_bulkorder_form_container_content_indigo').html('<div class="b2bking_loader_indigo_content"><img class="b2bking_loader_icon_button_indigo" src="'+b2bking_display_settings.loadertransparenturl+'"></div>');
1919
1920
1921		        	// set timer for 600ms before loading the ajax search (resource consuming)
1922		        	setTimeout(function(){
1923
1924		        		// if in the last 2 seconds there's been no new searches or input
1925		        		if (thisSearchTime === latestSearchTime){
1926
1927		        			var excludeval = $('#b2bking_bulkorder_exclude').val();
1928		        			var categoryval = $('#b2bking_bulkorder_category').val();
1929		        			var sortby = $('#b2bking_bulkorder_sortby').val();
1930
1931
1932		        			var datavar = {
1933					            action: 'b2bking_ajax_search',
1934					            security: b2bking_display_settings.security,
1935					            searchValue: $('#b2bking_bulkorder_search_text_indigo').val(),
1936					            dataType: 'json',
1937					            theme: 'indigo',
1938					            exclude: excludeval,
1939					            sortby: sortby,
1940					            category: categoryval
1941					        };
1942
1943							$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
1944
1945								// 1. populate data for prices
1946								let display = '';
1947								let results = response;
1948								let html = '';
1949								if (thisSearchTime === latestSearchTime){
1950									if (parseInt(results) !== 1234){ // 1234 Integer for Empty
1951										let resultsObject = JSON.parse(results);
1952										Object.keys(resultsObject).forEach(function (index) {
1953											if (index.includes('B2BKINGPRICE')){
1954												prices[index] = resultsObject[index];
1955											} else if (index.includes('B2BTIERPRICE')){
1956												pricetiers[index] = resultsObject[index];
1957											} else if (index.includes('B2BKINGSTOCK')){
1958												stock[index] = resultsObject[index];
1959											} else if (index.includes('B2BKINGIMAGE')){
1960												images[index] = resultsObject[index];
1961											} else if (index.includes('HTML')){
1962												html = resultsObject[index];
1963											}									
1964										});
1965
1966										// 2. show html and products
1967										$('.b2bking_bulkorder_form_container_content_indigo').html(html);
1968
1969									} else {
1970										// no products found
1971
1972										$('.b2bking_bulkorder_form_container_content_indigo').html('<div class="b2bking_bulkorder_indigo_noproducts">'+b2bking_display_settings.no_products_found+'</div><div class="b2bking_bulkorder_form_container_bottom b2bking_bulkorder_form_container_bottom_indigo"></div>');
1973
1974									}
1975									
1976									
1977
1978
1979								}
1980							});
1981
1982						}
1983
1984					}, 400);
1985		        }
1986			});
1987
1988			// cream order form filters category
1989			$('.b2bking_orderform_filters').on('click', function(){
1990				if ($('.b2bking_bulkorder_form_cream_main_container').hasClass('b2bking_filters_open')){
1991					$('#b2bking_bulkorder_cream_filter_icon img').attr('src',b2bking_display_settings.filters);
1992					$('.b2bking_bulkorder_form_cream_main_container.b2bking_filters_open, .b2bking_bulkorder_form_container_cream_filters.b2bking_filters_open, .b2bking_bulkorder_form_cream_main_container_content.b2bking_filters_open').addClass('b2bking_filters_closed').removeClass('b2bking_filters_open');
1993				} else {
1994					$('#b2bking_bulkorder_cream_filter_icon img').attr('src',b2bking_display_settings.filters_close);
1995					$('.b2bking_bulkorder_form_cream_main_container.b2bking_filters_closed, .b2bking_bulkorder_form_container_
1995cream_filters.b2bking_filters_closed, .b2bking_bulkorder_form_cream_main_container_content.b2bking_filters_closed').addClass('b2bking_filters_open').removeClass('b2bking_filters_closed');
1996				}
1997			});
1998
1999			// show clear cream icon
2000			// on input, show clear if field not empty
2001			$('.b2bking_bulkorder_search_text_cream').on('input', function(){
2002				let value = $(this).val();
2003				if (value.length !== 0){
2004					// show clear
2005					$('.b2bking_bulkorder_cream_search_icon_clear').removeClass('b2bking_bulkorder_cream_search_icon_hide').addClass('b2bking_bulkorder_cream_search_icon_show');
2006					$('.b2bking_bulkorder_cream_search_icon_search').removeClass('b2bking_bulkorder_cream_search_icon_show').addClass('b2bking_bulkorder_cream_search_icon_hide');
2007				} else {
2008					// show icon
2009					$('.b2bking_bulkorder_cream_search_icon_clear').removeClass('b2bking_bulkorder_cream_search_icon_show').addClass('b2bking_bulkorder_cream_search_icon_hide');
2010					$('.b2bking_bulkorder_cream_search_icon_search').removeClass('b2bking_bulkorder_cream_search_icon_hide').addClass('b2bking_bulkorder_cream_search_icon_show');
2011
2012				}
2013			});
2014			$('.b2bking_bulkorder_cream_search_icon_clear').on('click', function(){
2015				$('.b2bking_bulkorder_search_text_cream').val('');
2016				$('.b2bking_bulkorder_search_text_cream').trigger('input');
2017				$('.b2bking_bulkorder_search_text_cream').focus();
2018			});
2019
2020			// on click filter category
2021			$('.b2bking_bulkorder_filters_list li').on('click', function(){
2022
2023				// get and set category
2024				let cat = $(this).val();
2025				$('#b2bking_bulkorder_category').val(cat);
2026				jQuery('#b2bking_bulkorder_search_text_indigo').trigger('input');
2027
2028				// underline selected item
2029				$('.b2bking_bulkorder_filters_list li').each(function (index) {
2030					$(this).css('text-decoration','none');
2031				});
2032				$(this).css('text-decoration','underline');
2033
2034				// close filters
2035				// $('.b2bking_orderform_filters').click();
2036			});
2037
2038			// on click filter sortby
2039			$('.b2bking_bulkorder_filters_list_sortby li').on('click', function(){
2040
2041				// get and set category
2042				let sortby = $(this).attr('value');
2043
2044				$('#b2bking_bulkorder_sortby').attr('value',sortby);
2045				jQuery('#b2bking_bulkorder_search_text_indigo').trigger('input');
2046
2047				// underline selected item
2048				$('.b2bking_bulkorder_filters_list_sortby li').each(function (index) {
2049					$(this).css('text-decoration','none');
2050				});
2051				$(this).css('text-decoration','underline');
2052
2053				// close filters
2054				// $('.b2bking_orderform_filters').click();
2055			});
2056
2057			// search cream form
2058			$('#b2bking_bulkorder_search_text_indigo.b2bking_bulkorder_search_text_cream').on('input', function(){
2059
2060				let thisSearchTime = Date.now();
2061				latestSearchTime = thisSearchTime;
2062
2063		        if ($('#b2bking_bulkorder_search_text_indigo').length > 0){ // min x chars
2064
2065		        	// show loader
2066		        	$('.b2bking_bulkorder_form_container_content_indigo').html('<div class="b2bking_loader_indigo_content b2bking_loader_cream_content"><img class="b2bking_loader_icon_button_indigo" src="'+b2bking_display_settings.loadertransparenturl+'"></div>');
2067
2068
2069		        	// set timer for 600ms before loading the ajax search (resource consuming)
2070		        	setTimeout(function(){
2071
2072		        		// if in the last 2 seconds there's been no new searches or input
2073		        		if (thisSearchTime === latestSearchTime){
2074
2075		        			var excludeval = $('#b2bking_bulkorder_exclude').val();
2076		        			var categoryval = $('#b2bking_bulkorder_category').val();
2077		        			var sortby = $('#b2bking_bulkorder_sortby').val();
2078
2079
2080		        			var datavar = {
2081					            action: 'b2bking_ajax_search',
2082					            security: b2bking_display_settings.security,
2083					            searchValue: $('#b2bking_bulkorder_search_text_indigo').val(),
2084					            dataType: 'json',
2085					            theme: 'cream',
2086					            sku: $('#b2bking_order_form_show_sku').val(),
2087					            stock: $('#b2bking_order_form_show_stock').val(),
2088					            exclude: excludeval,
2089					            category: categoryval,
2090					            sortby: sortby
2091					        };
2092
2093							$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
2094
2095								// 1. populate data for prices
2096								let display = '';
2097								let results = response;
2098								let html = '';
2099								if (thisSearchTime === latestSearchTime){
2100									if (parseInt(results) !== 1234){ // 1234 Integer for Empty
2101										let resultsObject = JSON.parse(results);
2102										Object.keys(resultsObject).forEach(function (index) {
2103											if (index.includes('B2BKINGPRICE')){
2104												prices[index] = resultsObject[index];
2105											} else if (index.includes('B2BTIERPRICE')){
2106												pricetiers[index] = resultsObject[index];
2107											} else if (index.includes('B2BKINGSTOCK')){
2108												stock[index] = resultsObject[index];
2109											} else if (index.includes('B2BKINGIMAGE')){
2110												images[index] = resultsObject[index];
2111											} else if (index.includes('HTML')){
2112												html = resultsObject[index];
2113											}									
2114										});
2115
2116										// 2. show html and products
2117										$('.b2bking_bulkorder_form_container_content_indigo').html(html);
2118
2119									} else {
2120										// no products found
2121
2122										$('.b2bking_bulkorder_form_container_content_indigo').html('<div class="b2bking_bulkorder_indigo_noproducts b2bking_bulkorder_cream_noproducts"><img class="b2bking_bulkorder_cream_noproducts_img" src="'+b2bking_display_settings.no_products_found_img+'"><div class="b2bking_cream_noproductsfound_text">'+b2bking_display_settings.no_products_found+'</div></div><div class="b2bking_bulkorder_form_container_bottom b2bking_bulkorder_form_container_bottom_indigo b2bking_bulkorder_form_container_bottom_cream"></div>');
2123
2124									}
2125									
2126									
2127
2128
2129								}
2130							});
2131
2132						}
2133
2134					}, 400);
2135		        }
2136			});
2137
2138		}
2139
2140
2141
2142		// show hide variations cream
2143		$('body').on('click', '.b2bking_cream_view_options_button', function(){
2144			let parentid = $(this).val();
2145
2146			if ($(this).hasClass('b2bking_cream_view_options_button_view')){
2147				// show variations
2148				$('.b2bking_bulkorder_form_container_content_line_cream_'+parentid).removeClass('b2bking_bulkorder_form_container_
2148content_line_cream_hidden').addClass('b2bking_cream_line_variation_colored');
2149				$(this).removeClass('b2bking_cream_view_options_button_view');
2150				$(this).addClass('b2bking_cream_view_options_button_hide');
2151				$(this).find('.b2bking_cream_view_options_text').removeClass('b2bking_text_active').addClass('b2bking_text_inactive');
2152				$(this).find('.b2bking_cream_hide_options_text').removeClass('b2bking_text_inactive').addClass('b2bking_text_active');
2153			} else {
2154				if ($(this).hasClass('b2bking_cream_view_options_button_hide')){
2155					// hide variations
2156					$('.b2bking_bulkorder_form_container_content_line_cream_'+parentid).addClass('b2bking_bulkorder_form_container_content_line_cream_hidden');
2157					$(this).addClass('b2bking_cream_view_options_button_view');
2158					$(this).removeClass('b2bking_cream_view_options_button_hide');
2159					$(this).find('.b2bking_cream_view_options_text').addClass('b2bking_text_active').removeClass('b2bking_text_inactive');
2160					$(this).find('.b2bking_cream_hide_options_text').addClass('b2bking_text_inactive').removeClass('b2bking_text_active');
2161				}
2162			}
2163
2164
2165		});
2166
2167
2168		$('body').on('click', '.b2bking_bulkorder_back_top', function(){
2169			$("html, body").animate({ scrollTop: 0 }, "slow");
2170		});
2171
2172		// trigger first search
2173		jQuery('#b2bking_bulkorder_search_text_indigo').trigger('input');
2174		
2175
2176		/* Bulk order form END */
2177
2178		/* Purchase Lists START */
2179
2180		// Download Purchase Lists
2181		// On clicking download price list
2182		$('.b2bking_download_list_button').on('click', function() {
2183			// get list id
2184			var classList = $(this).attr('class').split(/\s+/);
2185			$.each(classList, function(index, item) {
2186				// foreach line if it has selected class, get selected product ID 
2187			    if (item.includes('id_')) {
2188			    	let listid = item.split('_')[1];
2189			    	window.location = b2bking_display_settings.ajaxurl + '?action=b2bkingdownloadpurchaselist&list='+listid+'&security=' + b2bking_display_settings.security;
2190			    }
2191			});
2192	    });
2193
2194		// purchase lists data table
2195		if (typeof $('#b2bking_purchase_lists_table').DataTable === "function") { 
2196			$('#b2bking_purchase_lists_table').dataTable({
2197	            "language": {
2198	                "url": b2bking_display_settings.datatables_folder+b2bking_display_settings.purchase_lists_language_option+'.json'
2199	            }
2200	        });
2201		}
2202
2203		// on click 'trash' in purchase list
2204		$('.b2bking_bulkorder_form_container_bottom_delete_button').on('click', function(){
2205			if(confirm(b2bking_display_settings.are_you_sure_delete_list)){
2206				let listId = $(this).val();
2207
2208				// replace icon with loader
2209				$('<img class="b2bking_loader_icon_button" src="'+b2bking_display_settings.loadertransparenturl+'">').insertBefore('.b2bking_bulkorder_form_container_bottom_delete_button_icon');
2210				$('.b2bking_bulkorder_form_container_bottom_delete_button_icon').remove();
2211
2212				var datavar = {
2213		            action: 'b2bking_purchase_list_delete',
2214		            security: b2bking_display_settings.security,
2215		            listid: listId
2216		        };
2217
2218				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
2219					window.location = b2bking_display_settings.purchaselistsurl;
2220				});
2221			}
2222		});
2223
2224		
2225		// on click 'update' in purchase list
2226		$('.b2bking_bulkorder_form_container_bottom_update_button').on('click', function(){
2227			let listId = $(this).val();
2228
2229			let productString = ''; 
2230			// loop through all bulk order form lines
2231			document.querySelectorAll('.b2bking_bulkorder_form_container_
2231content_line_product').forEach(function(textinput) {
2232				var classList = $(textinput).attr('class').split(/\s+/);
2233				$.each(classList, function(index, item) {
2234					// foreach line if it has selected class, get selected product ID 
2235				    if (item.includes('b2bking_selected_product_id_')) {
2236				    	let productID = item.split('_')[4];
2237				    	let quantity = $(textinput).parent().find('.b2bking_bulkorder_form_container_content_line_qty').val();
2238				    	if (quantity > 0 || parseInt(b2bking_display_settings.lists_zero_qty) === 1){
2239				    		// set product
2240				    		productString+=productID+':'+quantity+'|';
2241				    	}
2242				    }
2243				});
2244			});
2245			// if not empty, send
2246			if (productString !== ''){
2247				// replace icon with loader
2248				var buttonoriginal = $('.b2bking_bulkorder_form_container_bottom_update_button').html();
2249				$('<img class="b2bking_loader_icon_button" src="'+b2bking_display_settings.loadertransparenturl+'">').insertBefore('.b2bking_bulkorder_form_container_bottom_update_button_icon');
2250				$('.b2bking_bulkorder_form_container_bottom_update_button_icon').remove();
2251
2252				var datavar = {
2253		            action: 'b2bking_purchase_list_update',
2254		            security: b2bking_display_settings.security,
2255		            productstring: productString,
2256		            listid: listId
2257		        };
2258
2259				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
2260					location.reload();
2261				});
2262			}
2263		});
2264
2265
2266		// if this is a purchase list
2267		let isPurchaseList = $('#b2bking_purchase_list_page').val();
2268		if (isPurchaseList !== undefined){
2269			// add "selected" style to list items
2270			$('.b2bking_bulkorder_form_container_content_line_product').css('color', b2bking_display_settings.colorsetting);
2271
2272			$('.b2bking_bulkorder_form_container_content_line_product').css('font-weight', 'bold' );
2273			// get pricing details that will allow to calculate subtotals
2274			document.querySelectorAll('.b2bking_bulkorder_form_container_content_line_product').forEach(function(textinput) {
2275				let inputValue = $(textinput).val().split(' (')[0];
2276				var datavar = {
2277		            action: 'b2bking_ajax_search',
2278		            security: b2bking_display_settings.security,
2279		            searchValue: inputValue,
2280		            searchType: 'purchaseListLoading',
2281		            dataType: 'json'
2282		        };
2283
2284				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
2285					let results = response;
2286					if (results !== '"empty"'){
2287						let resultsObject = JSON.parse(results);
2288						Object.keys(resultsObject).forEach(function (index) {
2289							if (index.includes('B2BKINGPRICE')){
2290								prices[index] = resultsObject[index];
2291							} else if (index.includes('B2BTIERPRICE')){
2292								pricetiers[index] = resultsObject[index];
2293							} else if (index.includes('B2BKINGSTOCK')){
2294								stock[index] = resultsObject[index];
2295							}
2296						});
2297					}
2298
2299					var productID = 0;
2300					var classList = $(textinput).attr('class').split(/\s+/);
2301					$.each(classList, function(index, item) {
2302					    if (item.includes('b2bking_selected_product_id_')) {
2303					    	productID = item.split('_')[4];
2304					    }
2305					});
2306
2307					// Set max stock on item
2308					if (stock[productID+'B2BKINGSTOCK'] !== null){
2309						$(textinput).parent().find('.b2bking_bulkorder_form_container_
2309content_line_qty').attr('max', stock[productID+'B2BKINGSTOCK']);
2310					}
2311
2312					currentline = $(textinput).parent();
2313					if (parseInt(b2bking_display_settings.quotes_enabled) !== 1){
2314						calculateBulkOrderTotals();
2315					}
2316				});
2317				
2318				
2319			});
2320
2321		}
2322		
2323
2324		$('body').on('click', '.b2bking_add_cart_to_purchase_list_button', function(){
2325
2326			let title = window.prompt(b2bking_display_settings.save_list_name, "");
2327			if (title !== '' && title !== null){
2328
2329				var datavar = {
2330		            action: 'b2bking_save_cart_to_purchase_list',
2331		            security: b2bking_display_settings.security,
2332		            title: title,
2333		            dataType: 'json'
2334		        };
2335
2336				$.post(b2bking_display_settings.ajaxurl, datavar, function(response){
2337					$('.b2bking_add_cart_to_purchase_list_button').text(b2bking_display_settings.list_saved);
2338					$('.b2bking_add_cart_to_purchase_list_button').prop('disabled', true);
2339				});
2340			}
2341		});
2342
2343		// Tiered Pricing Table Active Color Hover Script
2344		setTimeout(function(){
2345			if (parseInt(b2bking_display_settings.is_enabled_color_tiered) === 1){
2346				setHoverColorTable();
2347			}
2348		}, 200);
2349
2350		$('body').on('input', 'input[name=quantity]', function(){
2351			if (parseInt(b2bking_display_settings.is_enabled_color_tiered) === 1){
2352				setHoverColorTable();
2353			}
2354		});
2355		$('body').on('change', 'input[name=quantity]', function(){
2356			if (parseInt(b2bking_display_settings.is_enabled_color_tiered) === 1){
2357				setHoverColorTable();
2358			}
2359		});
2360
2361		$('body').on('change', 'select[name=quantity]', function(){
2362			if (parseInt(b2bking_display_settings.is_enabled_color_tiered) === 1){
2363				setHoverColorTable();
2364			}
2365		});
2366		$('body').on('change', '.variations select', function(){
2367			if (parseInt(b2bking_display_settings.is_enabled_color_tiered) === 1){
2368				setHoverColorTable();
2369			}
2370		});
2371
2372		// table is clickable, allow clicking ranges to set qty
2373		if (parseInt(b2bking_display_settings.table_is_clickable) === 1){
2374			jQuery('body').on('click', '.b2bking_tiered_price_table tbody tr', function(){
2375				var rangetext = jQuery(this).find('td:nth-child(1)').data('range');
2376				let values = rangetext.split(' - ');
2377				if (values.length === 2){
2378					var setqty = parseInt(values[1]);
2379				} else {
2380					// is of form 456+
2381					var setqty = parseInt(rangetext.split('+')[0]);
2382				}
2383
2384				// apply min, max, step values
2385				var min = $('input[name=quantity]').attr('min');
2386				var max = $('input[name=quantity]').attr('max');
2387				var step = $('input[name=quantity]').attr('step');
2388
2389				if (max === undefined || max === '') {
2390					max = 999999999;
2391				}
2392				if (min === undefined || min === '') {
2393					min = 1;
2394				}
2395
2396				setqty = setqty > parseFloat( max ) ? max : setqty;
2397				setqty = setqty < parseFloat( min ) ? min : setqty;
2398
2399				// if there is a step
2400				if (step !== undefined && step !== ''){
2401					let difference = setqty%step;
2402					let difmin = 0;
2403					let difmax = 0; 
2404
2405					// if current qty does not step
2406					if (parseInt(difference) !== 0) {
2407
2408						// get difmin and difmax = numbers to substract or increase to reach step
2409						if ((setqty - difference) % step === 0){
2410							difmin = difference;
2411							difmax = step - difmin;
2412						} else {
2413							difmax = difference;
2414							difmin = step - difmax
2415						}
2416
2417						// change it
2418						// if adding difference doesn't go over max, add it, else substract it
2419						//setqty = ((setqty + difmax) < parseFloat( max )) ? setqty+difmax : setqty-difmin;
2420
2421						// above is old algorithm. Here, since we get the max range value, we always want to substract it
2422						// EXCEPT when in the situation where there's a range in form of '40+', only 1 number, then we go up
2423						if (values.length === 2){
2424							setqty = setqty-difmin;
2425						} else {
2426							setqty = setqty+difmax;
2427						}
2428					}
2429				}
2430
2431
2432				$('input[name=quantity]').val(setqty);
2433				$('input[name=quantity]').trigger('input').trigger('change');
2434			});
2435		}
2436
2437		
2438		function setHoverColorTable(){
2439			// remove all colors from table
2440			$('.b2bking_has_color').removeClass('b2bking_has_color');
2441			// get product id from table
2442			if ($('.b2bking_shop_table').attr('class') !== undefined){
2443				var classList = $('.b2bking_shop_table').attr('class').split(/\s+/);
2444				var productid = 0;
2445				$.each(classList, function(index, item) {
2446					// foreach line if it has selected class, get selected product ID 
2447				    if (item.includes('b2bking_productid_')) {
2448				    	productid = parseInt(item.split('_')[2]);
2449				    }
2450				});
2451				// get input quantity
2452				if ($('input[name=quantity]').val() !== undefined){
2453					var inputQuantity = parseInt($('input[name=quantity]').val());
2454				} else if ($('select[name=quantity]').val() !== undefined){
2455					var inputQuantity = parseInt($('select[name=quantity]').val());
2456				}
2457				// get cart item quantity
2458				var cartQuantity = 0;
2459				if (parseInt(b2bking_display_settings.add_cart_quantity_tiered_table) === 1){
2460
2461					if (b2bking_display_settings.cart_quantities[productid] !== undefined){
2462						cartQuantity = parseInt(b2bking_display_settings.cart_quantities[productid]);
2463					}
2464					if (parseInt(b2bking_display_settings.cart_quantities_cartqty) !== 0){
2465						cartQuantity = parseInt(b2bking_display_settings.cart_quantities_cartqty);
2466					}
2467				}
2468
2469				// calculate total quantity of the item
2470				var totalQuantity = inputQuantity + cartQuantity;
2471				// go through all ranges and check quantity. 
2472				// first set it to original price
2473				$('.b2bking_tiered_active_price').text($('.summary .b2bking_tiered_range_replaced:first').text().split(' – ')[1]);
2474				// if can't be found,
2475				if ($('.summary .b2bking_tiered_range_replaced:first').text().split(' – ')[1] === undefined){
2476					$('.b2bking_tiered_active_price').text($('.b2bking_tiered_range_replaced:first').text().split(' – ')[1]);
2477				}
2478
2479				$('.b2bking_shop_table.b2bking_productid_'+productid+' tr td:nth-child(1)').each(function(){
2480					let rangeText = $(this).data('range');
2481					let values = rangeText.split(' - ');
2482
2483					if (values.length === 2){
2484						// is of form 123 - 456
2485						let first = parseInt(values[0]);
2486						let second = parseInt(values[1]);
2487						if (totalQuantity >= first && totalQuantity <= second){
2488							// set color
2489							$(this).parent().find('td').addClass('b2bking_has_color');
2490							if (parseInt(b2bking_display_settings.is_enabled_discount_table) === 1){
2491								$('.b2bking_tiered_active_price').text($(this).parent().find('td:nth-child(3)').text());
2492							} else {
2493								$('.b2bking_tiered_active_price').text($(this).parent().find('td:nth-child(2)').text());
2494							}
2495						}
2496					} else if (!rangeText.includes('+')){
2497						// exception if the user enters 1 as a quantity in the table
2498						if (totalQuantity === parseInt(rangeText)){
2499							$(this).parent().find('td').addClass('b2bking_has_color');
2500							if (parseInt(b2bking_display_settings.is_enabled_discount_table) === 1){
2501								$('.b2bking_tiered_active_price').text($(this).parent().find('td:nth-child(3)').text());
2502							} else {
2503								$('.b2bking_tiered_active_price').text($(this).parent().find('td:nth-child(2)').text());
2504							}
2505						}
2506					} else {
2507						// is of form 456+
2508						let valuePlus = parseInt(rangeText.split('+')[0]);
2509						if (totalQuantity >= valuePlus){
2510							// set color
2511							$(this).parent().find('td').addClass('b2bking_has_color');
2512							if (parseInt(b2bking_display_settings.is_enabled_discount_table) === 1){
2513								$('.b2bking_tiered_active_price').text($(this).parent().find('td:nth-child(3)').text());
2514							} else {
2515								$('.b2bking_tiered_active_price').text($(this).parent().find('td:nth-child(2)').text());
2516							}
2517						}
2518					}
2519				});
2520			}
2521		}
2522
2523
2524		//
2525
2526		/* Purchase Lists END */
2527
2528		/* Checkout Registration Fields Checkbox*/
2529		
2530		if (parseInt(b2bking_display_settings.ischeckout) === 1 && parseInt(b2bking_display_settings.val
2530idate_vat_checkout) !== 1){
2531			showHideCheckout();
2532
2533			$('#createaccount').change(showHideCheckout);
2534		}
2535
2536		function showHideCheckout(){
2537			if($('#createaccount').prop('checked') || typeof $('#createaccount').prop('checked') === 'undefined') {
2538		    	$('#b2bking_checkout_registration_main_container_fields, .b2bking_registration_roles_dropdown_section').css('display','block');
2539		    	$('.b2bking_custom_field_req_required').prop('required','true');
2540
2541		    } else {      
2542		    	$('#b2bking_checkout_registration_main_container_fields, .b2bking_registration_roles_dropdown_section').css('display','none');
2543		    	$('.b2bking_custom_field_req_required').removeAttr('required');
2544		    }
2545		}	
2546
2547		// Fix issue with tiered price range below pricing
2548		document.querySelectorAll('.b2bking_both_prices_price.b2bking_b2b_price_price').forEach(function(textinput) {
2549
2550			var str = jQuery(textinput).val();
2551			if (str !== undefined){
2552				if (parseInt(str.length) === 0){
2553					var classList = $(textinput).attr('class').split(/\s+/);
2554					$.each(classList, function(index, item) {
2555						// foreach line if it has selected class, get selected product ID 
2556					    if (item.includes('b2bking_b2b_price_id_')) {
2557					    	let productID = item.split('_')[4];
2558					    	// if empty price, find tiered range below and move it inside
2559					    	var htm = jQuery('.b2bking_tiered_price_range_replaced_'+productID).html();
2560					    	jQuery('.b2bking_tiered_price_range_replaced_'+productID).remove();
2561					    	jQuery('.b2bking_both_prices_price.b2bking_b2b_price_price.b2bking_b2b_price_id_'+productID).html(htm);
2562					    }
2563					});
2564				}
2565			}
2566		});
2567
2568
2569		// Support Required Multiple Quantity Step for Individual Variations
2570		$('body').on('show_variation', '.single_variation_wrap', function ( event, variation ) {
2571			var quantity_input_var = jQuery( this ).parent().find( '[name=quantity]' );
2572
2573			if (variation.step !== undefined){
2574				quantity_input_var.attr( 'step', variation.step ).trigger( 'change' );
2575			} else {
2576				// if no step, set it to 1
2577				quantity_input_var.attr( 'step', 1 ).trigger( 'change' );
2578			}
2579
2580			// modify current value
2581			var qty_val = parseFloat( quantity_input_var.val() );
2582
2583			if ( isNaN( qty_val ) ) {
2584				qty_val = variation.min_qty;
2585			} else {
2586				qty_val = qty_val > parseFloat( variation.max_qty ) ? variation.max_qty : qty_val;
2587				qty_val = qty_val < parseFloat( variation.min_qty ) ? variation.min_qty : qty_val;
2588			}
2589
2590			if (variation.max_qty === undefined || variation.max_qty === '') {
2591				variation.max_qty = 999999999;
2592			}
2593
2594			// if there is a step
2595			if (variation.step !== undefined){
2596				let difference = qty_val%variation.step;
2597				let difmin = 0;
2598				let difmax = 0; 
2599
2600				// if current qty does not step
2601				if (parseInt(difference) !== 0) {
2602
2603					// get difmin and difmax = numbers to substract or increase to reach step
2604					if ((qty_val - difference) % variation.step === 0){
2605						difmin = difference;
2606						difmax = variation.step - difmin;
2607					} else {
2608						difmax = difference;
2609						difmin = variation.step - difmax
2610					}
2611
2612					// change it
2613					// if adding difference doesn't go over max, add it, else substract it
2614					qty_val = ((qty_val + difmax) < parseFloat( variation.max_qty )) ? qty_val+difmax : qty_val-difmin;
2615				}
2616			}
2617
2618			// set val
2619			quantity_input_var.val(qty_val);
2620
2621
2622			/*
2623			var variation_id = variation.variation_id;
2624			var quantity_select_var = jQuery( this ).parent().find( '[name=quantity_pq_dropdown]' );
2625			var cur_val = quantity_input_var.val();
2626
2627			if(variation_id > 0 && product_quantities[ variation_id ] !== undefined) {
2628				
2629				var quantity_dropdown_var = jQuery( this ).parent().find( 'select[name=quantity_pq_dropdown]' );
2630				var max_qty_var = ( ( !isNaN (parseFloat( product_quantities[ variation_id ][ 'max_qty' ] ) ) && parseFloat( product_quantities[ variation_id ][ 'max_qty' ] ) > 0 ) ? parseFloat( product_quantities[ variation_id ][ 'max_qty' ] ) : ''  );
2631				var min_qty_var = ( !isNaN (parseFloat( product_quantities[ variation_id ][ 'min_qty' ] ) ) ? parseFloat( product_quantities[ variation_id ][ 'min_qty' ] ) : 1  );
2632				var default_var = ( !isNaN (parseFloat( product_quantities[ variation_id ][ 'default' ] ) ) ? parseFloat( product_quantities[ variation_id ][ 'default' ] ) 
2632: 1  );
2633				var lowest_var = ( !isNaN (parseFloat( product_quantities[ variation_id ][ 'lowest_qty' ] ) ) ? parseFloat( product_quantities[ variation_id ][ 'lowest_qty' ] ) : 1  );
2634				
2635				if ( quantity_dropdown_var.length <= 0 ) {
2636					quantity_input_var.prop( 'max', max_qty_var );
2637				}
2638			}
2639			*/
2640
2641
2642		});
2643	});
2644
2645})(jQuery);

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.