PageSourceSearch

https://www.razomforukraine.org/wp-content/plugins/events-manager/includes/js/events-manager.js?ver=7.4.5

js razomforukraine.org collected 2026-09-24 08:39:21 UTC 436,550 bytes, 4,796 lines download raw bytes

1jQuery(document).ready( function($){
2
3	// backcompat changes 6.x to 5.x
4	if( $('#recurrence-frequency').length > 0  ){
5		$('#recurrence-frequency').addClass('em-recurrence-frequency');
6		$('.event-form-when .interval-desc').each( function(){
7			this.classList.add(this.id);
8		});
9		$('.event-form-when .alternate-selector').each( function(){
10			this.classList.add('em-' + this.id);
11		});
12		$('#recurrence-interval').addClass('em-recurrence-interval');
13	}
14	$('#em-wrapper').addClass('em');
15
16	// Add keyboard accessibility for em-icon button spans
17	$(document).on('keydown', 'span.em-icon[role="button"]', function(e){
18		if( e.key === 'Enter' || e.keyCode === 13 ){
19			e.preventDefault();
20			$(this).trigger('click');
21		}
22	});
23
24	/* Time Entry - legacy @deprecated */
25	$('#start-time').each(function(i, el){
26		$(el).addClass('em-time-input em-time-start').next('#end-time').addClass('em-time-input em-time-end').parent().addClass('em-time-range');
27	});
28
29	/*
30	 * ADMIN AREA AND PUBLIC FORMS (Still polishing this section up, note that form ids and classes may change accordingly)
31	 */
32	//Events List
33	//Approve/Reject Links
34	$('.events-table').on('click', '.em-event-delete', function(){
35		if( !confirm("Are you sure you want to delete?") ){ return false; }
36		window.location.href = this.href;
37	});
38	//Forms
39	$('#event-form #event-image-delete, #location-form #location-image-delete').on('click', function(){
40		var el = $(this);
41		if( el.is(':checked') ){
42			el.closest('.event-form-image, .location-form-image').find('#event-image-img, #location-image-img').hide();
43		}else{
44			el.closest('.event-form-image, .location-form-image').find('#event-image-img, #location-image-img').show();
45		}
46	});
47
48	//Manual Booking
49	$(document).on('click', 'a.em-booking-button', function(e){
50		e.preventDefault();
51		var button = $(this);
52		if( button.text() != EM.bb_booked && $(this).text() != EM.bb_booking){
53			button.text(EM.bb_booking);
54			var button_data = button.attr('id').split('_');
55			$.ajax({
56				url: EM.ajaxurl,
57				dataType: 'jsonp',
58				data: {
59					event_id : button_data[1],
60					_wpnonce : button_data[2],
61					action : 'booking_add_one'
62				},
63				success : function(response, statusText, xhr, $form) {
64					if(response.result){
65						button.text(EM.bb_booked);
66						button.addClass('disabled');
67					}else{
68						button.text(EM.bb_error);
69					}
70					if(response.message != '') alert(response.message);
71					$(document).triggerHandler('em_booking_button_response', [response, button]);
72				},
73				error : function(){ button.text(EM.bb_error); }
74			});
75		}
76		return false;
77	});
78	$(document).on('click', 'a.em-cancel-button', function(e){
79		e.preventDefault();
80		var button = $(this);
81		if( button.text() != EM.bb_cancelled && button.text() != EM.bb_canceling){
82			button.text(EM.bb_canceling);
83			// old method is splitting id with _ and second/third items are id and nonce, otherwise supply it all via data attributes
84			var button_data = button.attr('id').split('_');
85			let button_ajax = {};
86			if( button_data.length < 3 || !('booking_id' in button[0].dataset) ){
87				// legacy support
88				button_ajax = {
89					booking_id : button_data[1],
90					_wpnonce : button_data[2],
91					action : 'booking_cancel',
92				};
93			}
94			let ajax_data = Object.assign( button_ajax, button[0].dataset);
95			$.ajax({
96				url: EM.ajaxurl,
97				dataType: 'jsonp',
98				data: ajax_data,
99				success : function(response, statusText, xhr, $form) {
100					if(response.result){
101						button.text(EM.bb_cancelled);
102						button.addClass('disabled');
103					}else{
104						button.text(EM.bb_cancel_error);
105					}
106				},
107				error : function(){ button.text(EM.bb_cancel_error); }
108			});
109		}
110		return false;
111	});
112	$(document).on('click', 'a.em-booking-button-action', function(e){
113		e.preventDefault();
114		var button = $(this);
115		var button_data = {
116			_wpnonce : button.attr('data-nonce'),
117			action : button.attr('data-action'),
118		}
119		if( button.attr('data-event-id') ) button_data.event_id =  button.attr('data-event-id');
120		if( button.attr('data-booking-id') ) button_data.booking_id =  button.attr('data-booking-id');
121		if( button.text() != EM.bb_booked && $(this).text() != EM.bb_booking){
122			if( button.attr('data-loading') ){
123				button.text(button.attr('data-loading'));
124			}else{
125				button.text(EM.bb_booking);
126			}
127			$.ajax({
128				url: EM.ajaxurl,
129				dataType: 'jsonp',
130				data: button_data,
131				success : function(response, statusText, xhr, $form) {
132					if(response.result){
133						if( button.attr('data-success') ){
134							button.text(button.attr('data-success'));
135						}else{
136							button.text(EM.bb_booked);
137						}
138						button.addClass('disabled');
139					}else{
140						if( button.attr('data-error') ){
141							button.text(button.attr('data-error'));
142						}else{
143							button.text(EM.bb_error);
144						}
145					}
146					if(response.message != '') alert(response.message);
147					$(document).triggerHandler('em_booking_button_action_response', [response, button]);
148				},
149				error : function(){
150					if( button.attr('data-error') ){
151						button.text(button.attr('data-error'));
152					}else{
153						button.text(EM.bb_error);
154					}
155				}
156			});
157		}
158		return false;
159	});
160
161	//Datepicker - legacy
162	var load_ui_css; //load jquery ui css?
163	if( $('.em-date-single, .em-date-range, #em-date-start').length > 0 ){
164		load_ui_css = true;
165	}
166	if( load_ui_css ) em_load_jquery_css();
167
168	//previously in em-admin.php
169	$('#em-wrapper input.select-all').on('change', function(){
170		if($(this).is(':checked')){
171			$('input.row-selector').prop('checked', true);
172			$('input.select-all').prop('checked', true);
173		}else{
174			$('input.row-selector').prop('checked', false);
175			$('input.select-all').prop('checked', false);
176		}
177	});
178
179	/* Load any maps */
180	if( $('.em-location-map').length > 0 || $('.em-locations-map').length > 0 || $('#em-map').length > 0 || $('.em-search-geo').length > 0 ){
181		em_maps_load();
182	}
183
184	/* Location Type Selection */
185	$('.em-location-types .em-location-types-select').on('change', function(){
186		let el = $(this);
187		if( el.val() == 0 ){
188			$('.em-location-type').hide();
189		}else{
190			let location_type = el.find('option:selected').data('display-class');
191			$('.em-location-type').hide();
192			$('.em-location-type.'+location_type).show();
193			if( location_type != 'em-location-type-place' ){
194				jQuery('#em-location-reset a').trigger('click');
195			}
196		}
197		if( el.data('active') !== '' && el.val() !== el.data('active') ){
198			$('.em-location-type-delete-active-alert').hide();
199			$('.em-location-type-delete-active-alert').show();
200		}else{
201			$('.em-location-type-delete-active-alert').hide();
202		}
203	}).trigger('change');
204
205	//Finally, add autocomplete here
206	if( jQuery( 'div.em-location-data [name="location_name"]' ).length > 0 ){
207		$('div.em-location-data [name="location_name"]').em_selectize({
208			plugins: ["restore_on_backspace"],
209			valueField: "id",
210			labelField: "label",
211			searchField: "label",
212			create:true,
213			createOnBlur: true,
214			maxItems:1,
215			persist: false,
216			addPrecedence : true,
217			selectOnTab : true,
218			diacritics : true,
219			render: {
220				item: function (item, escape) {
221					return "<div>" + escape(item.label) + "</div>";
222				},
223				option: function (item, escape) {
224					let meta = '';
225					if( typeof(item.address) !== 'undefined' ) {
226						if (item.address !== '' && item.town !== '') {
227							meta = escape(item.address) + ', ' + escape(item.town);
228						} else if (item.address !== '') {
229							meta = escape(item.address);
230						} else if (item.town !== '') {
231							meta = escape(item.town);
232						}
233					}
234					return  '<div class="em-locations-autocomplete-item">' +
235						'<div class="em-locations-autocomplete-label">' + escape(item.label) + '</div>' +
236						'<div style="font-size:11px; text-decoration:italic;">' + meta + '</div>' +
237						'</div>';
238
239				},
240			},
241			load: function (query, callback) {
242				if (!query.length) return callback();
243				$.ajax({
244					url: EM.locationajaxurl,
245					data: {
246						q : query,
247						method : 'selectize'
248					},
249					dataType : 'json',
250					type: "POST",
251					error: function () {
252						callback();
253					},
254					success: function ( data ) {
255						callback( data );
256					},
257				});
258			},
259			onItemAdd : function (value, data) {
260				this.clearCache();
261				var option = this.options[value];
262				if( value === option.label ){
263					jQuery('input#location-address').focus();
264					return;
265				}
266				jQuery("input#location-name" ).val(option.value);
267				jQuery('input#location-address').val(option.address);
268				jQuery('input#location-town').val(option.town);
269				jQuery('input#location-state').val(option.state);
270				jQuery('input#location-region').val(option.region);
271				jQuery('input#location-postcode').val(option.postcode);
272				jQuery('input#location-latitude').val(option.latitude);
273				jQuery('input#location-longitude').val(option.longitude);
274				if( typeof(option.country) === 'undefined' || option.country === '' ){
275					jQuery('select#location-country option:selected').removeAttr('selected');
276				}else{
277					jQuery('select#location-country option[value="'+option.country+'"]').attr('selected', 'selected');
278				}
279				jQuery("input#location-id" ).val(option.id).trigger('change');
280				jQuery('div.em-location-data input, div.em-location-data select').prop('readonly', true).css('opacity', '0.5');
281				jQuery('#em-location-reset').show();
282				jQuery('#em-location-search-tip').hide();
283				// selectize stuff
284				this.disable();
285				this.$control.blur();
286				jQuery('div.em-location-data [class^="em-selectize"]').each( function(){
287					if( 'selectize' in this ) {
288						this.selectize.disable();
289					}
290				})
291				// trigger hook
292				jQuery(document).triggerHandler('em_locations_autocomplete_selected', [event, option]);
293			}
294		});
295		jQuery('#em-location-reset a').on('click', function(){
296			jQuery('div.em-location-data input, div.em-location-data select').each( function(){
297				this.style.removeProperty('opacity')
298				this.readOnly = false;
299				if( this.type == 'text' ) this.value = '';
300			});
301			jQuery('div.em-location-data option:selected').removeAttr('selected');
302			jQuery('input#location-id').val('');
303			jQuery('#em-location-reset').hide();
304			jQuery('#em-location-search-tip').show();
305			jQuery('#em-map').hide();
306			jQuery('#em-map-404').show();
307			if(typeof(marker) !== 'undefined'){
308				marker.setPosition(new google.maps.LatLng(0, 0));
309				infoWindow.close();
310				marker.setDraggable(true);
311			}
312			// clear selectize autocompleter values, re-enable any selectize ddms
313			let $selectize = $("div.em-location-data input#location-name")[0].selectize;
314			$selectize.enable();
315			$selectize.clear(true);
316			$selectize.clearOptions();
317			jQuery('div.em-location-data select.em-selectize').each( function(){
318				if( 'selectize' in this ){
319					this.selectize.enable();
320					this.selectize.clear(true);
321				}
322			});
323			// return true
324			return false;
325		});
326		if( jQuery('input#location-id').val() != '0' && jQuery('input#location-id').val() != '' ){
327			jQuery('div.em-location-data input, div.em-location-data select').each( function(){
328				this.style.setProperty('opacity','0.5', 'important')
329				this.readOnly = true;
330			});
331			jQuery('#em-location-reset').show();
332			jQuery('#em-location-search-tip').hide();
333			jQuery('div.em-location-data select.em-selectize, div.em-location-data input.em-selectize-autocomplete').each( function(){
334				if( 'selectize' in this ) this.selectize.disable();
335			});
336		}
337	}
338
339	// Add click handler for recurrence conversion links
340	document.querySelectorAll( '.em-convert-recurrence-link' ).forEach( link => {
341		link.addEventListener( 'click', function ( e ) {
342			if ( !confirm( EM.convert_recurring_warning ) ) {
343				e.preventDefault();
344				return false;
345			}
346			let nonce = this.getAttribute( 'data-nonce' );
347			if ( nonce ) {
348				this.href = this.href.replace( 'nonce=x', 'nonce=' + nonce );
349			}
350		} );
351	} );
352
353	// trigger selectize loader
354	em_setup_ui_elements(document);
355
356	/* Done! */
357	$(document).triggerHandler('em_javascript_loaded');
358});
359
360/**
361 * Sets up external UI libraries and adds them to elements within the supplied container. This can be a jQuery or DOM element, subfunctions will either handle accordingly or this function will ensure it's the right one to pass on..
362 * @param jQuery|DOMElement container
363 */
364function em_setup_ui_elements ( $container ) {
365	let container = ( $container instanceof jQuery ) ? $container[0] : $container;
366	// Selectize
367	em_setup_selectize( $container );
368	// Tippy
369	em_setup_tippy( $container );
370	// Moment JS
371	em_setup_moment_times( $container );
372	// Date & Time Pickers
373	if( container.querySelector('.em-datepicker') ){
374		em_setup_datepicker( container );
375	}
376	if( container.querySelector(".em-time-input") ){
377		em_setup_timepicker( container );
378	}
379	// Phone numbers
380	em_setup_phone_inputs( container );
381	// let other things hook in
382	document.dispatchEvent( new CustomEvent( 'em_setup_ui_elements', { detail: { container : container } } ) );
383}
384
385/**
386 * Unsetup containers with UI elements, primarily useful if intending on duplicating an element which would require re-setup.
387 * @param $container
388 */
389function em_unsetup_ui_elements( $container ) {
390	let container = $container instanceof jQuery ? $container[0] : $container;
391	em_unsetup_selectize( container );
392	em_unsetup_tippy( container );
393	em_unsetup_datepicker( container );
394	em_unsetup_timepicker( container );
395	em_unsetup_phone_inputs( container );
396	// let other things hook in
397	document.dispatchEvent( new CustomEvent( 'em_unsetup_ui_elements', { detail: { container : container } } ) );
398}
399
400/* Local JS Timezone related placeholders */
401/* Moment JS Timzeone PH */
402function em_setup_moment_times( container_element ) {
403	container = jQuery(container_element);
404	if( window.moment ){
405		var replace_specials = function( day, string ){
406			// replace things not supported by moment
407			string = string.replace(/##T/g, Intl.DateTimeFormat().resolvedOptions().timeZone);
408			string = string.replace(/#T/g, "GMT"+day.format('Z'));
409			string = string.replace(/###t/g, day.utcOffset()*-60);
410			string = string.replace(/##t/g, day.isDST());
411			string = string.replace(/#t/g, day.daysInMonth());
412			return string;
413		};
414		container.find('.em-date-momentjs').each( function(){
415			// Start Date
416			var el = jQuery(this);
417			var day_start = moment.unix(el.data('date-start'));
418			var date_start_string = replace_specials(day_start, day_start.format(el.data('date-format')));
419			if( el.data('date-start') !== el.data('date-end') ){
420				// End Date
421				var day_end = moment.unix(el.data('date-end'));
422				var day_end_string = replace_specials(day_start, day_end.format(el.data('date-format')));
423				// Output
424				var date_string = date_start_string + el.data('date-separator') + day_end_string;
425			}else{
426				var date_string = date_start_string;
427			}
428			el.text(date_string);
429		});
430		var get_date_string = function(ts, format){
431			let date = new Date(ts * 1000);
432			let minutes = date.getMinutes();
433			if( format == 24 ){
434				let hours = date.getHours();
435				hours = hours < 10 ? '0' + hours : hours;
436				minutes = minutes < 10 ? '0' + minutes : minutes;
437				return hours + ':' + minutes;
438			}else{
439				let hours = date.getHours() % 12;
440				let ampm = hours >= 12 ? 'PM' : 'AM';
441				if( hours === 0 ) hours = 12; // the hour '0' should be '12'
442				minutes = minutes < 10 ? '0'+minutes : minutes;
443				return hours + ':' + minutes + ' ' + ampm;
444			}
445		}
446		container.find('.em-time-localjs').each( function(){
447			var el = jQuery(this);
448			var strTime = get_date_string( el.data('time'), el.data('time-format') );
449			if( el.data('time-end') ){
450				var separator = el.data('time-separator') ? el.data('time-separator') : ' - ';
451				strTime = strTime + separator + get_date_string( el.data('time-end'), el.data('time-format') );
452			}
453			el.text(strTime);
454		});
455	}
456};
457
458function em_load_jquery_css( wrapper = false ){
459	if( EM.ui_css && jQuery('link#jquery-ui-em-css').length == 0 ){
460		var script = document.createElement("link");
461		script.id = 'jquery-ui-em-css';
462		script.rel = "stylesheet";
463		script.href = EM.ui_css;
464		document.body.appendChild(script);
465		if( wrapper ){
466			em_setup_jquery_ui_wrapper();
467		}
468	}
469}
470
471function em_setup_jquery_ui_wrapper(){
472	if( jQuery('#em-jquery-ui').length === 0 ){
473		jQuery('body').append('<div id="em-jquery-ui" class="em">');
474	}
475}
476
477/* Useful function for adding the em_ajax flag to a url, regardless of querystring format */
478var em_ajaxify = function(url){
479	if ( url.search('em_ajax=0') != -1){
480		url = url.replace('em_ajax=0','em_ajax=1');
481	}else if( url.search(/\?/) != -1 ){
482		url = url + "&em_ajax=1";
483	}else{
484		url = url + "?em_ajax=1";
485	}
486	return url;
487};
488
489// load externals after DOM load, supplied by EM.assets, only if selector matches
490var em_setup_scripts = function( $container = false ) {
491	let container = $container || document;
492	if( EM && 'assets' in EM ) {
493		let baseURL = EM.url + '/includes/external/';
494		for ( const [selector, assets] of Object.entries(EM.assets) ) {
495			// load scripts if one element exists for selector
496			if ( container.querySelector(selector) ) {
497				if ('css' in assets) {
498					// Iterate through assets.css object and add stylesheet to head
499					for (const [id, value] of Object.entries(assets.css)) {
500						// Check if the stylesheet with the given ID already exists
501						if (!document.getElementById( id + '-css' )) {
502							// Create a new link element for the stylesheet
503							const link = document.createElement('link');
504							link.id = id + '-css';
505							link.rel = 'stylesheet';
506							link.href = value.match(/^http/) ? value : baseURL + value;
507
508							// Append the stylesheet to the document head
509							document.head.appendChild(link);
510						}
511					}
512				}
513				if ('js' in assets) {
514					// add a tracking of all assets to load, and execute loaded hooks after all assets are loaded and in order of dependence
515					let loaded = {};
516					let loadedListener = function( id ) {
517						loaded[id] = false;
518						if ( Object.entries( loaded ).length === Object.entries( assets.js ).length ) {
519							// all items for this asset loaded, so we go through all the entries and fire their events
520							for ( id of Object.keys( loaded ) ) {
521								loadAsset( id )
522							}
523						}
524					};
525					let loadAsset = function( id ) {
526						if ( !loaded[id] ) {
527							let asset = assets.js[id];
528							if ( typeof asset === 'object' && 'event' in asset ) {
529								if ( asset?.requires) {
530									loadAsset( asset.requires );
531								}
532								document.dispatchEvent( new CustomEvent( asset.event, {
533									detail: {
534										container: container,
535									}
536								} ) );
537							}
538							loaded[id] = true;
539						}
540					};
541					// Iterate through assets.js object and add script to head
542					for ( const [ id, value ] of Object.entries(assets.js)) {
543						// Check if the script with the given ID already exists
544						if ( !document.getElementById( id + '-js' ) ) {
545							// Create a new script element for the JavaScript file
546							const script = document.createElement('script');
547							script.id = id + '-js';
548							script.async = true;
549							if ( typeof value === 'object' ) {
550								// add locale data
551								if ( 'locale' in value && value.locale ) {
552									script.dataset.locale = value.locale;
553								}
554								script.src = value.url.match(/^http/g) ? value.url : baseURL + value.url;
555							} else {
556								script.src = value.match(/^http/g) ? value : baseURL + value;
557							}
558							// listen for loads so we execute the real onload hooks once all files are loaded (or errorred out)
559							script.onload = () => loadedListener(id);
560							script.onerror = () => loadedListener(id);
561							// Append the script to the document head
562							document.head.appendChild(script);
563						}
564					}
565				}
566			}
567		}
568	}
569}
570document.addEventListener('DOMContentLoaded', () => em_setup_scripts( document ));
571
572// WP List Tables front-end stuff
573const setupListTable = function( listTable ) {
574	// handle checks of multiple items using shift
575	const checkboxes = listTable.querySelectorAll( 'tbody .check-column input[type="checkbox"]' );
576	// The export and settings modals carry the same form class, so match the main form only.
577	const listTableForm = listTable.querySelector('form.em-list-table-form:not(.em-list-table-export-form):not(.em-list-table-settings-form)');
578	if ( !listTableForm ) {
579		return;
580	}
581	let lastChecked;
582
583	//Pagination link clicks
584	listTable.querySelectorAll('.tablenav-pages a').forEach( el => {
585		el.addEventListener('click', function ( e ) {
586			e.preventDefault();
587			//get page no from url, change page, submit form
588			let match = el.href.match(/#[0-9]+/);
589			if ( match != null && match.length > 0 ) {
590				let pno = match[0].replace('#', '');
591				listTableForm.querySelector('input[name=pno]').val(pno);
592			} else {
593				// new way
594				let url = new URL(el.href);
595				if ( url.searchParams.has('paged') ) {
596					listTableForm.querySelectorAll('input[name=pno], input[name=paged]').forEach( el => el.value = url.searchParams.get('paged') );
597				} else {
598					listTableForm.querySelectorAll('input[name=pno], input[name=paged]').forEach( el => el.value = 1 );
599				}
600			}
601			listTableForm.requestSubmit();
602			return false;
603		});
604	});
605	// Pagination - Input page number
606	listTable.querySelectorAll('.tablenav-pages input[name=paged]').forEach( function ( input ){
607		input.addEventListener('change', function (e) {
608			e.preventDefault();
609			let last = listTableForm.querySelector('.tablenav-pages a.last-page');
610			if ( last ) {
611				// check val isn't more than last page
612				let url = new URL(last.href);
613				if ( url.searchParams.has('paged') ) {
614					let lastPage = parseInt(url.searchParams.get('paged'));
615					if ( parseInt(input.value) > lastPage ) {
616						input.value = lastPage;
617					}
618				}
619			} else {
620				// make sure it's less than current page, we're on last page already
621				let lastPage = listTableForm.querySelector('input[name=pno]');
622				if (lastPage && lastPage.value && parseInt(input.value) > parseInt(lastPage.value)) {
623					input.value = lastPage.value;
624					e.preventDefault();
625					return false;
626				}
627			}
628			listTableForm.querySelectorAll('input[name=pno]').forEach( el => el.value = input.value );
629			listTableForm.requestSubmit();
630			return false;
631		});
632	});
633
634	// handle checkboxes
635	listTable.addEventListener('click', function(e){
636		// handle selecting all checkboxes
637		if( e.target.matches('.manage-column.column-cb input') ){
638			listTable.querySelectorAll('.check-column input').forEach( function( checkbox ){
639				checkbox.checked = e.target.checked;
640				checkbox.closest('tr').classList.toggle('selected', e.target.checked);
641				// enable/disable bulk actions filter
642				listTable.querySelector('.tablenav .bulkactions-input').querySelectorAll('input,select,button').forEach( function(el){
643					e.target.checked ? el.removeAttribute('disabled') : el.setAttribute('disabled', true);
644					e.target.checked ? el.classList.remove('disabled') : el.classList.add('disabled', true);
645				});
646			});
647		} else if ( e.target.matches('tbody .check-column input[type="checkbox"]') ) {
648			// handle multiple checks
649			let inBetween = false;
650			if ( e.shiftKey ) {
651				checkboxes.forEach(checkbox => {
652					if ( checkbox === e.target || checkbox === lastChecked ) {
653						inBetween = !inBetween;
654					}
655					if ( inBetween || checkbox === lastChecked ) {
656						checkbox.checked = lastChecked.checked;
657					}
658					checkbox.closest('tr').classList.toggle('selected', checkbox.checked);
659				});
660			} else {
661				e.target.closest('tr').classList.toggle('selected', e.target.checked);
662			}
663			// enable/disable bulk actions filter
664			let somethingSelected = e.target.checked || listTable.querySelectorAll( 'tbody .check-column input[type="checkbox"]:checked' ).length > 0;
665			listTable.querySelector('.tablenav .bulkactions-input').querySelectorAll('input,select,button').forEach( function(el){
666				somethingSelected ? el.removeAttribute('disabled') : el.setAttribute('disabled', true);
667				somethingSelected ? el.classList.remove('disabled') : el.classList.add('disabled', true);
668			});
669			lastChecked = e.target;
670		} else if ( e.target.closest('tbody td.column-primary') ) {
671			// handle row expand/collapse
672			if ( e.target.matches('a[href],button:not(.toggle-row)') ) return true; // allow links to pass
673			e.preventDefault();
674			let rowExpandTrigger = e.target.closest('td.column-primary');
675			let row = rowExpandTrigger.closest('tr');
676			if( row.classList.contains('expanded') ) {
677				row.classList.remove('expanded');
678				row.classList.add('collapsed');
679				rowExpandTrigger.querySelector('button.toggle-row').classList.remove('expanded');
680			} else {
681				row.classList.add('expanded');
682				row.classList.remove('collapsed');
683				rowExpandTrigger.querySelector('button.toggle-row').classList.add('expanded');
684			}
685		}
686	});
687	// disable filter since no checkboxes initially selected
688	listTable.querySelectorAll('.tablenav .bulkactions-input').forEach( (el) => {
689		el.querySelectorAll('input,select,button').forEach(function (el) {
690			el.setAttribute('disabled', true);
691			el.classList.add('disabled', true);
692		})
693	});
694
695	// Sorting by headers
696	listTable.querySelector('thead').addEventListener('click', function( e ) {
697		// get th element
698		let th = e.target.tagName.toLowerCase() === 'th' ? e.target : e.target.closest('th');
699		if( th && (th.classList.contains('sorted') || th.classList.contains('sortable')) ) {
700			e.preventDefault();
701			// add args to form and submit it
702			let params = ( new URL( th.querySelector('a').href) ).searchParams;
703			if ( params.get('orderby') ) {
704				listTableForm.querySelector('input[name="orderby"]').value = params.get('orderby');
705				let order = params.get('order') ? params.get('order') : 'asc';
706				listTableForm.querySelector('input[name="order"]').value = order;
707				listTableForm.requestSubmit();
708			}
709		}
710	});
711
712	// show/hide filters trigger
713	let filterTrigger = listTable.querySelector('button.filters-trigger');
714	if( filterTrigger ) {
715		filterTrigger.addEventListener('click', function(e){
716			e.preventDefault();
717			if( filterTrigger.classList.contains('hidden') ) {
718				listTable.querySelectorAll('div.actions.filters').forEach( filter => filter.classList.remove('hidden') );
719				filterTrigger.classList.remove('hidden');
720				filterTrigger.setAttribute('aria-label', filterTrigger.dataset.labelHide);
721				if( '_tippy' in filterTrigger ){
722					filterTrigger._tippy.setContent( filterTrigger.dataset.labelHide );
723				}
724			} else {
725				listTable.querySelectorAll('div.actions.filters').forEach( filter => filter.classList.add('hidden') );
726				filterTrigger.classList.add('hidden');
727				filterTrigger.setAttribute('aria-label', filterTrigger.dataset.labelShow);
728				if( '_tippy' in filterTrigger ){
729					filterTrigger._tippy.setContent( filterTrigger.dataset.labelShow );
730				}
731			}
732		});
733		listTable.addEventListener('em_resize', function(){
734			if( listTable.classList.contains('size-small') ) {
735				filterTrigger.classList.remove('hidden'); // force hide click
736				filterTrigger.click();
737			}
738		});
739	}
740
741	// EXPAND/COLLAPSE - RESPONSIVE
742	// handle expand/collapse in responsive mode when clicking the expand/collapse (all)
743	let expandTrigger = listTable.querySelector('button.small-expand-trigger');
744	if( expandTrigger ) {
745		// detect click and add expand class to table, expanded class to trigger
746		expandTrigger.addEventListener('click', function(e){
747			e.preventDefault();
748			if( expandTrigger.classList.contains('expanded') ) {
749				listTable.querySelectorAll('tbody tr.expanded, tbody button.toggle-row.expanded').forEach( el => el.classList.remove('expanded') );
750				listTable.classList.remove('expanded');
751				expandTrigger.classList.remove('expanded');
752			} else {
753				listTable.querySelectorAll('tbody tr, tbody button.toggle-row').forEach( el => {
754					el.classList.add('expanded');
755					el.classList.remove('collapsed');
756				});
757				listTable.classList.add('expanded');
758				expandTrigger.classList.add('expanded');
759			}
760		});
761	}
762
763	// handle filters when pressing enter, submitting a search
764	listTable.querySelectorAll('.tablenav .actions input[type="text"]').forEach( function (input) {
765		input.addEventListener('keypress', function (e) {
766			let keycode = (e.keyCode ? e.keyCode : e.which);
767			if (keycode === 13) {
768				e.preventDefault();
769				listTableForm.requestSubmit();
770			}
771		});
772	});
773
774	// handle size breakpoints
775	let breakpoints = {
776		'xsmall' : 465,
777		'small' : 640,
778		'medium' : 930,
779		'large' : false,
780	}
781	// submissions
782	EM_ResizeObserver( breakpoints, [ listTable ] );
783
784	//Widgets and filter submissions
785	listTableForm.addEventListener('submit', function (e) {
786		e.preventDefault();
787		//append loading spinner
788		listTable.classList.add('em-working');
789		let loadingDiv = document.createElement('div');
790		loadingDiv.id = 'em-loading';
791		listTable.append(loadingDiv);
792		listTable.querySelectorAll('.em-list-table-error-notice').forEach( el => el.remove() );
793		//ajax call
794		fetch( EM.ajaxurl, { method: 'POST', body: new FormData(listTableForm) } ).then( function( response ) {
795			if ( response.ok ) {
796				return response.text();
797			} else {
798				throw new Error('Network Response ' + response.status);
799			}
800		}).then( function( data ) {
801			if ( !data ) {
802				throw new Error('Empty string received');
803			}
804			if (!listTable.classList.contains('frontend')) {
805				// remove modals as they are supplied again on the backend
806				listTableForm.querySelectorAll('.em-list-table-trigger').forEach(function ( trigger ) {
807					let modal = document.querySelector(trigger.rel);
808					if( modal ) {
809						modal.remove();
810					}
811				});
812			}
813			// get new data as DOM object
814			let wrapper = document.createElement('div');
815			wrapper.innerHTML = data;
816			let newListTable = wrapper.firstElementChild;
817			// replace old table with new table
818			listTable.replaceWith( newListTable );
819			// fire hook - note that form and data should not be used! This is for backward compatibility with an old jQuery hook being fired. Expect future consequences if you use them, obtain everything from listTable or prevListTable!
820			document.dispatchEvent( new CustomEvent('em_list_table_filtered', { detail: { prevListTable: listTable, listTable: newListTable, form: newListTable.firstElementChild, data: data } }) );
821		}).catch( function( error ) {
822			let div = document.createElement('div');
823			div.innerHTML = '<p>There was an unexpected error retrieving table data with error <code>' + error.message + '</code>
823, please try again or contact an administrator.</p>';
824			div.setAttribute('class', 'em-warning error em-list-table-error-notice');
825			listTable.querySelector('.table-wrap').before(div);
826			loadingDiv.remove();
827			listTable.classList.remove('em-working');
828		});
829		return false;
830	});
831
832	//Settings & Export Modal
833
834	/**
835	 * Handle trigger of settings and export modals.
836	 */
837	listTable.querySelectorAll('.em-list-table-trigger').forEach( trigger => {
838		trigger.addEventListener('click', function (e) {
839			e.preventDefault();
840			let modal = document.querySelector( trigger.getAttribute('rel') );
841			openModal(modal);
842		});
843	});
844
845	/**
846	 * Handle submission of settings forms, by copying over hidden input values such as cols and limit to main form.
847	 */
848	listTable.querySelectorAll('.em-list-table-settings form').forEach( form => {
849		form.addEventListener('submit', function (e) {
850			e.preventDefault();
851			//we know we'll deal with cols, so wipe hidden value from main
852			let modal = form.closest('.em-modal');
853			let match = listTableForm.querySelector("[name=cols]");
854			match.value = '';
855			let tableCols = form.querySelectorAll('.em-list-table-cols-selected .item');
856			tableCols.forEach( function (item_match) {
857				if (!item_match.classList.contains('hidden')) {
858					if (match.value !== '') {
859						match.value = match.value + ',' + item_match.getAttribute('data-value');
860					} else {
861						match.value = item_match.getAttribute('data-value');
862					}
863				}
864			});
865			// sync row count
866			let limit = form.querySelector('select[name="limit"]');
867			if( limit ) {
868				listTableForm.querySelector('[name="limit"]').value = limit.value;
869			}
870			// sync custom inputs
871			form.querySelectorAll('[data-setting]').forEach( function( input ) {
872				listTableForm.querySelectorAll('[name="'+input.name+'"]').forEach( el => el.remove() );
873				let persisted = input.cloneNode(true);
874				persisted.classList.add('hidden')
875				listTableForm.appendChild( persisted );
876			});
877			closeModal(modal);
878			// send events out
879			modal.dispatchEvent( new CustomEvent('submitted') );
880			listTable.dispatchEvent( new CustomEvent( 'em_list_table_settings_submitted', {
881				detail: {
882					listTableForm: listTableForm,
883					form: form,
884					modal: modal
885				},
886				bubbles: true
887			}) );
888			// submit main form
889			listTableForm.requestSubmit();
890		});
891	});
892
893	/**
894	 * Handle submission of export forms, by copying over filters and hidden inputs with the data-persist attribute from main list table form.
895	 */
896	listTable.querySelectorAll('.em-list-table-export > form').forEach( function( exportForm ) {
897		exportForm.addEventListener('submit', function(e) {
898			var formFilters = this.querySelector('.em-list-table-filters');
899			if ( formFilters ) {
900				// get all filter inputs in main list table form and copy over so export inherits all filters to output right results
901				let filters = listTableForm.querySelectorAll('.em-list-table-filters [name]');
902				formFilters.innerHTML = ''; // Empty the filters, none to copy over
903				if( filters ) {
904					filters.forEach( function( filter ) {
905						formFilters.appendChild( filter.cloneNode(true) );
906					});
907				}
908				let peristentData = listTableForm.querySelectorAll('[data-persist]');
909				if( peristentData ) {
910					peristentData.forEach( function( filter ) {
911						formFilters.appendChild( filter.cloneNode(true) );
912					});
913				}
914			}
915		});
916	});
917
918	// sortables
919	listTable.querySelectorAll(".em-list-table-cols-sortable").forEach( function(sortable) {
920		Sortable.create( sortable );
921	});
922
923	// add trigger
924	document.dispatchEvent( new CustomEvent('em_list_table_setup', { detail: { listTable: listTable, listTableForm: listTableForm } }) );
925
926	// add extra listeners that we might want to block such as in bulk actions and row actions
927
928	/* ----------------- Row/Bulk Action Handlers ----------------- */
929
930	const actionMessages = listTableForm.dataset.actionMessages ? JSON.parse( listTableForm.dataset.actionMessages ) : {};
931	let isBulkAction = false;
932
933	listTable.addEventListener('click', function( e ) {
934		if( e.target.matches('a[data-row_action]') ) {
935			e.preventDefault();
936			let el = e.target;
937			let tr = el.closest('tr');
938
939			if( !isBulkAction ) {
940				let confirmation = []
941				// check if we need to confirm something specific
942				if ( el.dataset.confirmation && el.dataset.confirmation in actionMessages ) {
943					confirmation.push( actionMessages[el.dataset.confirmation] );
944				}
945				// check context of action and warn then propagate if upstream
946				if ( el.dataset.row_action in actionMessages ) {
947					confirmation.push( actionMessages[el.dataset.row_action] );
948				}
949
950				if ( confirmation.length > 0 ) {
951					if ( !confirm( confirmation.join("\n\n") ) ) {
952						return false;
953					}
954				}
955			}
956
957			// close dropdown if applicable
958			let dropdown = el.closest('[data-tippy-root], .em-tooltip-ddm-content');
959			if ( dropdown ) {
960				if ( '_tippy' in dropdown ) {
961					dropdown._tippy.hide();
962				}
963			}
964
965			// handle upstream rows, add a loading class to them so they don't get double-tapped, no checks necessary here since we have clicked a single row item
966			if( el.dataset.upstream ) {
967				// block any same upstream_id row so it's loading already pending refresh
968				listTable.querySelectorAll('tr[data-id="' + tr.dataset.id + '"]').forEach( tr => tr.classList.add('loading') );
969			}
970
971			// prep and fetch/refresh
972			let formData = new FormData( listTableForm );
973			for( const [key, value] of Object.entries(el.dataset) ) {
974				formData.set(key, value);
975			}
976			formData.set('view', listTable.dataset.view);
977			formData.set('action', listTable.dataset.basename + '_row');
978			listTableRowAction( tr, formData );
979
980			return false; // stop propagation
981		}
982	});
983
984	// Action links (approve/reject etc.) - circumvent if a warning is required
985	listTable.addEventListener( 'click', function( e ) {
986		if( e.target.matches('a[data-row_action]') ) {
987			e.preventDefault();
988		}
989	});
990
991	listTable.querySelectorAll('button.em-list-table-bulk-action').forEach( function( button ) {
992		button.addEventListener('click', function (e) {
993			e.preventDefault(); // override default
994			let actionSelector = listTableForm.querySelector('select.bulk-action-selector');
995			let action = actionSelector.options[actionSelector.selectedIndex];
996			
997			// check if we need to confirm
998			if ( action.dataset.confirm ) {
999				if ( !confirm( action.dataset.confirm ) ) {
1000					isBulkAction = false; // just in case
1001					return false;
1002				}
1003			}
1004
1005			isBulkAction = true;
1006			// find all checked items and perform action on them if the action actually exists for that row (e.g. you can't re-approve an approved booking)
1007			let rows = listTableForm.querySelectorAll('tbody .check-column input:checked');
1008			rows.forEach( function ( checkbox ) {
1009				let actionTrigger = checkbox.parentElement.querySelector('[data-row_action="' + action.value + '"]');
1010				// check if sibling has the relevant action
1011				if( actionTrigger ) {
1012					let tr = checkbox.closest('tr');
1013					if ( actionTrigger.dataset.upstream ) {
1014						// check if not already in an upstream process, proceed if not
1015						if ( !tr.classList.contains('loading') ) { // if loading, already in upstream from another row
1016							// trigger the first booking id row in this table, it'll handle upstream stuff
1017							actionTrigger.click();
1018						}
1019					} else {
1020						// regular action, just click it
1021						actionTrigger.click();
1022					}
1023				}
1024			});
1025			isBulkAction = false;
1026		});
1027	});
1028
1029
1030	// add a listener to refresh related booking rows if upstream
1031	listTable.addEventListener('em_list_table_row_action_complete', function(e){
1032		if ( e.detail.upstream ) {
1033			// find any rows other than the current one and trigger a refresh
1034			let currentRow = e.detail.currentRow;
1035			let formData = e.detail.formData;
1036			if( formData.get('row_action') === 'delete' ) {
1037				let feedback = currentRow.querySelector('.column-primary span.em-icon-trash.em-tooltip');
1038				if ( feedback ) {
1039					listTable.querySelectorAll('tr[data-id="' + formData.get('row_id') + '"]').forEach( function( tr ) {
1040						// apply to all rows of same booking_id except the one we just updated
1041						if ( tr !== currentRow ) {
1042							let td = tr.querySelector('.column-primary');
1043							td.prepend(feedback.cloneNode(true));
1044							em_setup_tippy(td);
1045						}
1046						tr.classList.remove('faded-out');
1047						tr.classList.remove('loading');
1048					});
1049				}
1050			} else if( formData.get('row_action') !== 'refresh' ) {
1051				let feedback = currentRow.querySelector('.column-primary span.em-icon.em-tooltip').getAttribute('aria-label');
1052				formData.set('row_action', 'refresh'); // this is a special action that just refreshes the row
1053				formData.set('feedback', feedback);
1054				listTable.querySelectorAll('tr[data-id="' + formData.get('row_id') + '"]').forEach( function( tr ) {
1055					// apply to all rows of same booking_id except the one we just updated
1056					if( tr !== currentRow ) {
1057						listTableRowAction(tr, formData);
1058						// delete current booking_id and reset isUpstreamAction if we're done
1059						delete isUpstreamAction[e.detail.booking_id];
1060						if (Object.keys(isUpstreamAction).length) {
1061							isUpstreamAction = false;
1062						}
1063					}
1064				});
1065			}
1066		}
1067	});
1068
1069	// setup rows with actions if there are any
1070	listTable.querySelectorAll('td.column-actions a').forEach( (action) => {
1071		action.classList.add('em-tooltip');
1072		action.setAttribute('aria-label', action.innerText);
1073	});
1074}
1075
1076let listTableRowAction = function( tr, formData, upstream = false ){
1077	let listTable = tr.closest('.em-list-table');
1078	tr.classList.add('loading');
1079	formData.set('row_id', tr.dataset.id );
1080	fetch( EM.ajaxurl, { method: 'post', body : formData } ).then( function( response ) {
1081		return response.text();
1082	}).then( function( html ) {
1083		tr.classList.add('faded-out');
1084		if ( formData.get('row_action') === 'delete' ) {
1085			// the text provided is the icon, nothing else
1086			tr.querySelectorAll('th.check-column input[type="checkbox"], .em-list-table-actions').forEach( el => el.remove() );
1087			let td = tr.querySelector('.column-primary');
1088			let wrapper = document.createElement('div');
1089			wrapper.innerHTML = html;
1090			let icon = wrapper.firstElementChild;
1091			em_setup_tippy(wrapper); // no actions to set up
1092			td.prepend(icon);
1093		} else {
1094			tr.innerHTML = html
1095			setupListTableExtras(tr);
1096		}
1097		tr.classList.remove('faded-out');
1098		tr.classList.remove('loading');
1099		listTable.dispatchEvent( new CustomEvent('em_list_table_row_action_complete', { detail: { currentRow: tr, formData: formData, upstream: upstream } } ) );
1100	});
1101}
1102
1103const setupListTableExtras = function( listTable ) {
1104	// setup rows with actions if there are any
1105	listTable.querySelectorAll('td.column-actions a').forEach( (action) => {
1106		action.classList.add('em-tooltip');
1107		action.setAttribute('aria-label', action.innerText);
1108	});
1109	// remove tooltips within tooltips in cell tooltips
1110	listTable.querySelectorAll('td .em-list-table-col-tooltip .em-list-table-col-tooltip').forEach( (subtip) => {
1111		subtip.querySelectorAll('.em-tooltip').forEach( el => el.remove() );
1112		subtip.querySelectorAll('.em-tooltip-content').forEach( el => el.classList.remove('hidden') );
1113	});
1114	// set up tippy, selectize etc.
1115	em_setup_tippy( listTable );
1116	em_setup_selectize( listTable );
1117}
1118
1119document.addEventListener('em_list_table_filtered', function(e){
1120	setupListTable( e.detail.listTable );
1121	// re-setup tippy, selectize etc.
1122	setupListTableExtras( e.detail.listTable );
1123});
1124
1125// init
1126document.addEventListener('DOMContentLoaded', function() {
1127	// add back-compat stuff
1128	document.querySelectorAll('.em_obj div.tablenav').forEach( function( tablenav ){
1129		let em_obj = tablenav.closest('.em_obj');
1130		em_obj.classList.add('em-list-table','legacy', 'frontend');
1131		em_obj.querySelector('& > form')?.classList.add('em-list-table-form');
1132	});
1133	// find tables, one table failing to set up should not leave the rest of the page unwired
1134	document.querySelectorAll('.em-list-table').forEach( function( listTable ) {
1135		try {
1136			setupListTable( listTable );
1137		} catch ( error ) {
1138			console.error( error );
1139		}
1140	});
1141});
1142
1143// add extra setup to bookings list table
1144document.addEventListener('em_list_table_setup'  , function(e){
1145	let listTable = e.detail.listTable;
1146	let listTableForm = e.detail.listTableForm;
1147	if( listTable.classList.contains('em-bookings-table') ) {
1148
1149		// handle submitting the settings modal form with booking-speficic extras
1150		listTable.addEventListener('em_list_table_settings_submitted', function(e){
1151			let form = e.detail.form;
1152			let listTableForm = e.detail.listTableForm;
1153			// get the views ddm and sync it to the table filter
1154			let views_select = form.querySelector('select[name="view"]');
1155			if ( views_select ) {
1156				let view_radio = listTableForm.querySelector('[name="view"][value="' + views_select.value + '"]');
1157				if( view_radio ) {
1158					view_radio.checked = true; // this doesn't trigger an event as we don't want that
1159				}
1160				let view_option = listTableForm.querySelector('button.em-bookings-table-view-option[data-view]');
1161				if ( view_option ) {
1162					view_option.setAttribute('data-view', views_select.value);
1163					view_option.innerText = views_select.options[views_select.selectedIndex].innerText;
1164				}
1165			}
1166		});
1167
1168		// setup views dropdown to switch between different booking table views
1169		let views_ddm_options = {
1170			theme : 'light-border',
1171			allowHTML : true,
1172			interactive : true,
1173			trigger : 'manual',
1174			placement : 'bottom',
1175			zIndex : 1000000,
1176			touch: true,
1177		};
1178		let tooltip_vars = { theme : 'light-border', appendTo : 'parent', touch : false, };
1179
1180		// TODO unify this with the search view dropdown JS to remove redundant code
1181		listTable.querySelectorAll('.em-bookings-table-views-trigger').forEach( function( trigger ){
1182			tooltip_vars.content = trigger.parentElement.getAttribute('aria-label');
1183			let views_tooltip = tippy(trigger.parentElement, tooltip_vars);
1184			let views_content = trigger.parentElement.querySelector('.em-bookings-table-views-options');
1185			let views_content_parent = views_content.parentElement;
1186			let tippy_content = document.createElement('div');
1187			views_ddm_options.content = tippy_content;
1188			let views_ddm = tippy(trigger, views_ddm_options);
1189			views_ddm.setProps({
1190				onShow(instance){
1191					views_tooltip.disable();
1192					tippy_content.append(views_content);
1193				},
1194				onShown(instance){ // keyboard support
1195					views_content.querySelector('input:checked').focus();
1196				},
1197				onHidden(instance){
1198					views_tooltip.enable();
1199					if( views_content.parentElement !== views_content_parent ) {
1200						views_content_parent.append(views_content);
1201					}
1202				}
1203			});
1204			let tippy_listener = function(e){
1205				if( e.type === 'keydown' && !(e.which === 13 || e.which === 40) ) return false;
1206				e.preventDefault();
1207				e.stopPropagation();
1208				trigger._tippy.show();
1209				views_tooltip.hide();
1210			}
1211			trigger.addEventListener('click', tippy_listener);
1212			trigger.addEventListener('keydown', tippy_listener);
1213			trigger.firstElementChild.addEventListener('focus', function(e){
1214				views_ddm.hide();
1215				views_tooltip.enable();
1216				views_tooltip.show();
1217			});
1218			trigger.firstElementChild.addEventListener('blur', function(){
1219				views_tooltip.hide();
1220			});
1221
1222			// TODO Remove this dependence on jQuery. Copied it from the search.js file, but it seems that even a vanilla document.addEventListener('blur') isn't intercepting these blur/focus events.
1223			let $ = jQuery;
1224			$views = $(listTable).find('.em-bookings-table-views');
1225			$views.on('focus blur', '.em-bookings-table-views-options input', function(){
1226				if( document.activeElement === this ){
1227					this.parentElement.classList.add('focused');
1228				}else{
1229					this.parentElement.classList.remove('focused');
1230				}
1231			});
1232
1233			$views.on('keydown click', '.em-bookings-table-views-options input', function( e ){
1234				// get relevant vars
1235				if( e.type === 'keydown' && e.which !== 13 ){
1236					if ( [37, 38, 39, 40].indexOf(e.which) !== -1 ) {
1237						if (e.which === 38) {
1238							if (this.parentElement.previousElementSibling) {
1239								this.parentElement.previousElementSibling.focus();
1240							}
1241						} else if (e.which === 40) {
1242							if (this.parentElement.nextElementSibling) {
1243								this.parentElement.nextElementSibling.focus();
1244							}
1245						}
1246						return false;
1247					} else if ( e.which === 9 ) {
1248						// focus out
1249						views_ddm.hide();
1250					}
1251					return true;
1252				}
1253				this.checked = true;
1254				let input = $(this);
1255				// mark label selected
1256				input.closest('fieldset').find('label').removeClass('checked');
1257				input.parent().addClass('checked');
1258				// get other reference elements we need
1259				let views_wrapper = $(this).closest('.em-bookings-table-views');
1260				let view_type = this.value;
1261				let trigger = views_wrapper.children('.em-bookings-table-views-trigger');
1262				let trigger_option = trigger.children('.em-search-view-option');
1263				// change view, if different
1264				if( view_type !== trigger_option.attr('data-view') ){
1265					trigger_option.attr('data-view', this.value).text(this.parentElement.innerText);
1266					// remove cols value if it's just a switch in view, so we get default cols (if there is one)
1267					listTableForm.querySelector('input[name="cols"][type="hidden"]').value = '';
1268					// set the view type and trigger a form submit
1269					listTableForm.requestSubmit();
1270				}
1271				views_ddm.hide();
1272			});
1273		});
1274	}
1275});
1276
1277// backcompat for em_bookings_filtered jQuery trigger
1278document.addEventListener('em_list_table_filtered', function( e ){
1279	if( e.detail.listTable.classList.contains('em-bookings-table') && window.jQuery ) {
1280		jQuery(document).triggerHandler('em_bookings_filtered', [jQuery(e.detail.data), e.detail.listTable, jQuery(e.detail.form)]); // backwards compatibility
1281	}
1282})
1283
1284function em_setup_datepicker( container ){
1285	wrap = jQuery(container);
1286
1287	//apply datepickers - jQuery UI (backcompat)
1288	let dateDivs = wrap.find('.em-date-single, .em-date-range');
1289	if( dateDivs.length > 0 ){
1290		//default picker vals
1291		var datepicker_vals = {
1292			dateFormat: "yy-mm-dd",
1293			changeMonth: true,
1294			changeYear: true,
1295			firstDay : EM.firstDay,
1296			yearRange:'c-100:c+15',
1297			beforeShow : function( el, inst ){
1298				em_setup_jquery_ui_wrapper();
1299				inst.dpDiv.appendTo('#em-jquery-ui');
1300			}
1301		};
1302		if( EM.dateFormat ) datepicker_vals.dateFormat = EM.dateFormat;
1303		if( EM.yearRange ) datepicker_vals.yearRange = EM.yearRange;
1304		jQuery(document).triggerHandler('em_datepicker', datepicker_vals);
1305		//apply datepickers to elements
1306		dateDivs.find('input.em-date-input-loc').each(function(i,dateInput){
1307			//init the datepicker
1308			var dateInput = jQuery(dateInput);
1309			var dateValue = dateInput.nextAll('input.em-date-input').first();
1310			var dateValue_value = dateValue.val();
1311			dateInput.datepicker(datepicker_vals);
1312			dateInput.datepicker('option', 'altField', dateValue);
1313			//now set the value
1314			if( dateValue_value ){
1315				var this_date_formatted = jQuery.datepicker.formatDate( EM.dateFormat, jQuery.datepicker.parseDate('yy-mm-dd', dateValue_value) );
1316				dateInput.val(this_date_formatted);
1317				dateValue.val(dateValue_value);
1318			}
1319			//add logic for texts
1320			dateInput.on('change', function(){
1321				if( jQuery(this).val() == '' ){
1322					jQuery(this).nextAll('.em-date-input').first().val('');
1323				}
1324			});
1325		});
1326		//deal with date ranges
1327		dateDivs.filter('.em-date-range').find('input.em-date-input-loc[type="text"]').each(function(i,dateInput){
1328			//finally, apply start/end logic to this field
1329			dateInput = jQuery(dateInput);
1330			if( dateInput.hasClass('em-date-start') ){
1331				dateInput.datepicker('option','onSelect', function( selectedDate ) {
1332					//get corresponding end date input, we expect ranges to be contained in .em-date-range with a start/end input element
1333					var startDate = jQuery(this);
1334					var endDate = startDate.parents('.em-date-range').find('.em-date-end').first();
1335					var startValue = startDate.nextAll('input.em-date-input').first().val();
1336					var endValue = endDate.nextAll('input.em-date-input').first().val();
1337					startDate.trigger('em_datepicker_change');
1338					if( startValue > endValue && endValue != '' ){
1339						endDate.datepicker( "setDate" , selectedDate );
1340						endDate.trigger('change').trigger('em_datepicker_change');
1341					}
1342					endDate.datepicker( "option", 'minDate', selectedDate );
1343				});
1344			}else if( dateInput.hasClass('em-date-end') ){
1345				var startInput = dateInput.parents('.em-date-range').find('.em-date-start').first();
1346				if( startInput.val() != '' ){
1347					dateInput.datepicker('option', 'minDate', startInput.val());
1348				}
1349			}
1350		});
1351	}
1352
1353	// datpicker - new format
1354	let datePickerDivs = wrap.find('.em-datepicker, .em-datepicker-range');
1355	if( datePickerDivs.length > 0 ){
1356		// wrappers and locale
1357		// flatpickr appends its calendar to this wrapper; create it in the SAME document as
1358		// the container so calendars for inputs inside the Gutenberg editor-canvas iframe
1359		// render in the iframe, not the parent (where they'd be invisible / mispositioned).
1360		// In the classic editor container.ownerDocument === document, so behaviour is unchanged.
1361		let containerDoc = ( container && container.ownerDocument ) || document;
1362		let wrapperEl = containerDoc.getElementById('em-flatpickr');
1363		if( ! wrapperEl ){
1364			wrapperEl = containerDoc.createElement('div');
1365			wrapperEl.className = 'em pixelbones em-flatpickr';
1366			wrapperEl.id = 'em-flatpickr';
1367			containerDoc.body.appendChild( wrapperEl );
1368		}
1369		let datepicker_wrapper = jQuery( wrapperEl );
1370		// locale
1371		if( 'locale' in EM.datepicker ){
1372			flatpickr.localize(flatpickr.l10ns[EM.datepicker.locale]);
1373			flatpickr.l10ns.default.firstDayOfWeek = EM.firstDay;
1374		}
1375		//default picker vals
1376		let datepicker_onChanging;
1377		let datepicker_options = {
1378			appendTo : datepicker_wrapper[0],
1379			dateFormat: "Y-m-d",
1380			disableMoble : "true",
1381			allowInput : true,
1382			onChange : [function( selectedDates, dateStr, instance ){
1383				if ( datepicker_onChanging !== selectedDates) {
1384					let wrapper = jQuery(instance.input).closest('.em-datepicker');
1385					let data_wrapper = wrapper.find('.em-datepicker-data');
1386					let inputs = data_wrapper.find('input');
1387					let dateFormat = function(d) {
1388						let month = '' + (d.getMonth() + 1),
1389							day = '' + d.getDate(),
1390							year = d.getFullYear();
1391						if (month.length < 2) month = '0' + month;
1392						if (day.length < 2) day = '0' + day;
1393						return [year, month, day].join('-');
1394					}
1395					if ( selectedDates.length === 0 ){
1396						if ( instance.config.mode === 'single' && wrapper.hasClass('em-datepicker-until') ) {
1397							let input = instance.input.classList.contains('em-date-input-start') ? inputs[0] : input
1397s[1];
1398							input.setAttribute('value', '');
1399							if ( inputs.filter(input => input.value !== '').length === 0 ) {
1400								wrapper.removeClass('has-value');
1401							}
1402						} else {
1403							wrapper.removeClass('has-value');
1404							inputs.attr('value', '');
1405							if( instance.config.mode === 'multiple' ) {
1406								// empty pill selection
1407								let datesEl = instance.input.closest('.em-datepicker').querySelector('.em-datepicker-dates');
1408								if (datesEl) {
1409									datesEl.querySelectorAll('.item:not(.clear-all)').forEach( el => el.remove() );
1410									datesEl.classList.remove('has-value');
1411								}
1412							}
1413						}
1414					} else {
1415						wrapper.addClass('has-value');
1416						if ( instance.config.mode === 'range' && selectedDates[1] !== undefined ) {
1417							// deal with end date
1418							inputs[0].setAttribute('value', dateFormat(selectedDates[0]));
1419							inputs[1].setAttribute('value', dateFormat(selectedDates[1]));
1420						} else if ( instance.config.mode === 'single' && wrapper.hasClass('em-datepicker-until') ){
1421							if( instance.input.classList.contains('em-date-input-start') ){
1422								inputs[0].setAttribute('value', dateFormat(selectedDates[0]));
1423								// set min-date of other datepicker
1424								let fp;
1425								if( wrapper.attr('data-until-id') ){
1426									let fp_inputData = jQuery('#' + wrapper.attr('data-until-id') + ' .em-date-input-end');
1427									fp = fp_inputData[0]._flatpickr;
1428								}else {
1429									fp = wrapper.find('.em-date-input-end')[0]._flatpickr;
1430								}
1431								if( fp.selectedDates[0] !== undefined && fp.selectedDates[0] < selectedDates[0] ){
1432									fp.setDate(selectedDates[0], false);
1433									inputs[1].setAttribute('value', dateFormat(fp.selectedDates[0]));
1434								}
1435								fp.set('minDate', selectedDates[0]);
1436							}else{
1437								inputs[1].setAttribute('value', dateFormat(selectedDates[0]));
1438							}
1439						} else if ( instance.config.mode === 'multiple' ){
1440							inputs[0].setAttribute('value', dateStr);
1441							// Sort the selected dates chronologically
1442							selectedDates.sort(function(a, b) { return a - b; });
1443							// Build pill selection for multiple dates
1444							let datesEl = instance.input.closest('.em-datepicker').querySelector('.em-datepicker-dates');
1445							datesEl.classList.add('has-value');
1446							if ( datesEl ) {
1447								// Remove existing date pills but preserve the clear-all button
1448								datesEl.querySelectorAll('.item:not(.clear-all)').forEach(el => el.remove());
1449	
1450								// Sort dates chronologically
1451								selectedDates.sort((a, b) => a - b);
1452	
1453								// Group sequential dates into ranges
1454								let groups = [], currentGroup = [];
1455								selectedDates.forEach((date, i) => {
1456									if (currentGroup.length === 0) {
1457										currentGroup.push(date);
1458									} else {
1459										let lastDate = currentGroup[currentGroup.length - 1];
1460										let diffDays = (date - lastDate) / (1000 * 3600 * 24);
1461										if (diffDays === 1) {
1462											currentGroup.push(date);
1463										} else {
1464											groups.push(currentGroup);
1465											currentGroup = [date];
1466										}
1467									}
1468									if (i === selectedDates.length - 1) groups.push(currentGroup);
1469								});
1470	
1471								// Insert pills and maintain date values
1472								groups.forEach(group => {
1473									let div = document.createElement('div');
1474									div.className = 'item';
1475									let formattedDates = group.map(date => instance.formatDate(date, 'Y-m-d'));
1476									div.dataset.date = formattedDates.join(',');
1477									let startText = instance.formatDate(group[0], instance.config.altFormat);
1478									let endText = instance.formatDate(group[group.length - 1], instance.config.altFormat);
1479									div.innerHTML = `<span>${group.length > 1 ? startText + ' - ' + endText : startText}</span><a href="#" class="remove" tabindex="-1" title="Remove">×</a>`;
1480									datesEl.insertBefore(div, datesEl.querySelector('.clear-all'));
1481								});
1482							}
1483						} else {
1484							inputs[0].setAttribute('value', dateFormat(selectedDates[0]));
1485						}
1486					}
1487					inputs.trigger('change');
1488					let current_date = data_wrapper.attr('date-value');
1489					data_wrapper.attr('data-value', inputs.toArray().map(input => input.value).filter(value => value !== '').join(','));
1490					if( current_date === dateStr ) data_wrapper.trigger('change');
1491					wrapper[0].dispatchEvent( new CustomEvent('datepicker-onChange', { detail: { selectedDates : selectedDates, dateStr: dateStr, instance: instance } }) );
1492				}
1493				datepicker_onChanging = null; // reset regardless, since it's to prevent onClose firing this twice
1494			}],
1495			onClose : function( selectedDates, dateStr, instance ){
1496				// deal with single date choice and clicking out
1497				if( instance.config.mode === 'range' && selectedDates[1] !== undefined ){
1498					if(selectedDates.length === 1){
1499						instance.setDate([selectedDates[0],selectedDates[0]], true); // wouldn't have been triggered with a single date selection
1500					}
1501				} else {
1502					// trigger an onChange
1503					datepicker_options.onChange[0](selectedDates, dateStr, instance);
1504					datepicker_onChanging = selectedDates; // set flag to prevent onChange firing twice
1505				}
1506			},
1507			locale : {},
1508		};
1509		if( EM.datepicker.format !== datepicker_options.dateFormat ){
1510			datepicker_options.altFormat = EM.datepicker.format;
1511			datepicker_options.altInput = true;
1512		}
1513		jQuery(document).triggerHandler('em_datepicker_options', datepicker_options);
1514		//apply datepickers to elements
1515		datePickerDivs.each( function(i,datePickerDiv) {
1516			// hide fallback fields, show range or single
1517			datePickerDiv = jQuery(datePickerDiv);
1518			datePickerDiv.find('.em-datepicker-data').addClass('hidden');
1519			let isRange = datePickerDiv.hasClass('em-datepicker-range');
1520			let altOptions = {};
1521			if( datePickerDiv.attr('data-datepicker') ){
1522				altOptions = JSON.parse(datePickerDiv.attr('data-datepicker'));
1523				if( typeof altOptions !== 'object' ){
1524					altOptions = {};
1525				}
1526			}
1527			let otherOptions = {};
1528			if( datePickerDiv.find('script.datepicker-options').length > 0 ){
1529				otherOptions = JSON.parse( datePickerDiv.find('script.datepicker-options').text() );
1530				if( typeof altOptions !== 'object' ){
1531					otherOptions = {};
1532				}
1533			}
1534			let options = Object.assign({}, datepicker_options, altOptions, otherOptions); // clone, mainly shallow concern for 'mode'
1535			options.mode = isRange ? 'range' : 'single';
1536			if ( datePickerDiv.hasClass('em-datepicker-multiple') ) {
1537				options.mode = 'multiple';
1538			}
1539			if( isRange && 'onClose' in options ){
1540				options.onClose = [function( selectedDates, dateStr, instance ){
1541					if(selectedDates.length === 1){ // deal with single date choice and clicking out
1542						instance.setDate([selectedDates[0],selectedDates[0]], true);
1543					}
1544				}];
1545			}
1546			if( datePickerDiv.attr('data-separator') ) options.locale.rangeSeparator = datePickerDiv.attr('data-separator');
1547			if( datePickerDiv.attr('data-format') ) options.altFormat = datePickerDiv.attr('data-format');
1548			let FPs = datePickerDiv.find('.em-date-input');
1549			//if ( FPs.hasClass(flatpickr-input) ) return; // already initialized
1550			if ( FPs[0].tagName.toLowerCase() === 'input' ) {
1551				FPs.attr('type', 'text');
1552			} else {
1553				options.wrap = true;
1554				FPs.find('input[type="hidden"]').attr('type', 'text');
1555			}
1556			FPs.flatpickr(options);
1557		});
1558		em_setup_datepicker_dates( datePickerDivs );
1559		// fire trigger
1560		jQuery(document).triggerHandler('em_flatpickr_loaded', [wrap]);
1561		container.dispatchEvent( new CustomEvent('em_datepicker_loaded', { bubbles: true, detail: { container: wrap, datepickers: datePickerDivs } } ) );
1562	}
1563}
1564
1565function em_setup_datepicker_dates( container ) {
1566	let datePickerContainer = jQuery(container);
1567	let datePickerDivs = datePickerContainer.first().hasClass('em-datepicker') ? datePickerContainer : datePickerContainer.find('.em-datepicker, .em-datepicker-range') ;
1568	// add values to elements, done once all datepickers instantiated so we don't get errors with date range els in separate divs
1569	datePickerDivs.each( function(i,datePickerDiv) {
1570		datePickerDiv = jQuery(datePickerDiv);
1571		let FPs = datePickerDiv.find('.em-date-input');
1572		//if ( FPs.hasClass(flatpickr-input) ) return;
1573		let inputs = datePickerDiv.find('.em-datepicker-data input');
1574		inputs.attr('type', 'hidden'); // hide so not tabbable
1575		if( datePickerDiv.hasClass('em-datepicker-until') ){
1576			let start_fp = FPs.filter('.em-date-input-start')[0]._flatpickr;
1577			let end_fp;
1578			if( datePickerDiv.attr('data-until-id') ){
1579				end_fp = jQuery('#' + datePickerDiv.attr('data-until-id') + ' .em-date-input-end')[0]._flatpickr;
1580			}else{
1581				end_fp = FPs.filter('.em-date-input-end')[0]._flatpickr;
1582				if( inputs[1] && inputs[1].value ) {
1583					end_fp.setDate(inputs[1].value, false, 'Y-m-d');
1584				}
1585			}
1586			if( inputs[0] && inputs[0].value ){
1587				start_fp.setDate(inputs[0].value, false, 'Y-m-d');
1588				end_fp.set('minDate', inputs[0].value);
1589			}
1590			start_fp._inputData = inputs[0] ? [inputs[0]] : [];
1591			end_fp._inputData = inputs[1] ? [inputs[1]] : [];
1592		}else if( datePickerDiv.hasClass('em-datepicker-multiple') ){
1593			// handle multiple pre-loaded dates
1594			if( inputs[0] && inputs[0].value ){
1595				let datesArray = inputs[0].value.split(',');
1596				FPs[0]._flatpickr.setDate(datesArray, true, 'Y-m-d');
1597			}
1598			FPs[0]._flatpickr._inputData = [ inputs[0] ];
1599		}else{
1600			let dates = [];
1601			FPs[0]._flatpickr._inputData = [];
1602			inputs.each( function( i, input ){
1603				if( input.value ){
1604					dates.push(input.value);
1605					FPs[0]._flatpickr._inputData.push(input);
1606				}
1607			});
1608			FPs[0]._flatpickr.setDate(dates, false, 'Y-m-d');
1609		}
1610	});
1611}
1612
1613/**
1614 * Deregister the datepicker
1615 * @param wrap
1616 */
1617function em_unsetup_datepicker( wrap ) {
1618	wrap.querySelectorAll(".em-datepicker .em-date-input.flatpickr-input").forEach( function( el ){
1619		if( '_flatpickr' in el ){
1620			el._flatpickr.destroy();
1621		}
1622	});
1623}
1624
1625/**
1626 * Handle the remove button for each date selection pill
1627 */
1628document.addEventListener('click', function(e) {
1629	if ( !e.target.closest('.em-datepicker-dates .item:not(.clear-all) .remove') ) return;
1630
1631	e.preventDefault();
1632	const pill = e.target.closest('.item');
1633	const datesContainer = pill.closest('.em-datepicker-dates');
1634	const datepickerContainer = datesContainer.closest('.em-datepicker');
1635	const dateInput = datepickerContainer.querySelector('.em-date-input');
1636
1637	// Remove pill
1638	pill.remove();
1639
1640	// Rebuild dates array from remaining pills
1641	const newDates = [];
1642	datesContainer.querySelectorAll('.item:not(.clear-all)').forEach(item => {
1643		const dates = item.dataset.date.split(',');
1644		dates.forEach(date => newDates.push(date));
1645	});
1646
1647	// Update Flatpickr instance
1648	const fp = datepickerContainer.querySelector('.em-date-input')._flatpickr;
1649	if (fp) fp.setDate(newDates, true, 'Y-m-d');
1650
1651	// Update hidden input
1652	const altInput = datepickerContainer.querySelector('.em-datepicker-data input');
1653	if (altInput) {
1654		altInput.value = newDates.join(',');
1655		altInput.dispatchEvent(new Event('change'));
1656	}
1657});
1658
1659/**
1660 * Handle the Clear All button
1661 */
1662document.addEventListener('click', function(e) {
1663	if ( !e.target.closest('.em-datepicker-dates .clear-all') ) return;
1664
1665	e.preventDefault();
1666	const datesContainer = e.target.closest('.em-datepicker-dates');
1667	const datepickerContainer = datesContainer.closest('.em-datepicker');
1668	const fp = datepickerContainer.querySelector('.em-date-input')._flatpickr;
1669
1670	// Remove all pills
1671	datesContainer.querySelectorAll('.item:not(.clear-all)').forEach( item => item.remove() );
1672
1673	// Clear Flatpickr instance
1674	if (fp) fp.clear();
1675
1676	// Update hidden input
1677	const altInput = datepickerContainer.querySelector('.em-datepicker-data input');
1678	if (altInput) {
1679		altInput.value = '';
1680		altInput.dispatchEvent(new Event('change'));
1681	}
1682});
1683
1684
1685
1686function em_setup_timepicker( container ){
1687	wrap = jQuery(container);
1688	var timepicker_options = {
1689		step:15,
1690		// Append the dropdown list to the input's OWN document so it renders inside the
1691		// Gutenberg editor-canvas iframe rather than the parent body. In the classic editor
1692		// ownerDocument === document, so this matches the plugin's default "body" target.
1693		appendTo: function( input ){
1694			var el = input instanceof jQuery ? input[0] : input;
1695			return jQuery( ( el && el.ownerDocument && el.ownerDocument.body ) || document.body );
1696		}
1697	}
1698	timepicker_options.timeFormat = EM.show24hours == 1 ? 'G:i':'g:i A';
1699	jQuery(document).triggerHandler('em_timepicker_options', timepicker_options);
1700	wrap.find(".em-time-input").em_timepicker(timepicker_options).each( function(i, el){
1701		this.dataset.seconds = this.value ? jQuery(this).em_timepicker('getSecondsFromMidnight') : '';
1702	});
1703
1704	/**
1705	 * A function that retargets an the change event to the .em-time-range enclosing div whilst maintinaing the originally triggered target.
1706	 * This is done because the em_timepicker short-circuits the bubbling.
1707	 *
1708	 * @param {Event} e - The original event to be retargeted.
1709	 */
1710	let retargetEvent = function(e) {
1711		e.stopPropagation();
1712		const customEvent = new CustomEvent('change', {
1713			bubbles: true,
1714			cancelable: true,
1715			detail: { target: e.target }
1716		});
1717
1718		// Override the target getter to return the original element
1719		Object.defineProperty(customEvent, 'target', {
1720			configurable: true,
1721			get: () => e.target,
1722		});
1723		e.target.closest('.em-time-range').dispatchEvent( customEvent );
1724	};
1725
1726	// Keep the duration between the two inputs.
1727	wrap.find(".em-time-range input.em-time-start").each( function(i, el){
1728		var time = jQuery(el);
1729		time.data('oldTime', time.em_timepicker('getSecondsFromMidnight'));
1730	}).on('change', function( e ) {
1731		var start = jQuery(this);
1732		var wrapper = start.closest('.em-time-range');
1733		var end = wrapper.find('.em-time-end').first();
1734		if ( end.val() ) { // Only update when second input has a value.
1735			// Calculate duration.
1736			var oldTime = start.data('oldTime');
1737			var duration = (end.em_timepicker('getSecondsFromMidnight') - oldTime) * 1000;
1738			var time = start.em_timepicker('getSecondsFromMidnight');
1739			if(  this.value && end.em_timepicker('getSecondsFromMidnight') >= oldTime ){
1740				// Calculate and update the time in the second input.
1741				end.em_timepicker('setTime', new Date(start.em_timepicker('getTime').getTime() + duration));
1742			}
1743			start.data('oldTime', time);
1744		}
1745		if ( start.val() || end.val() ) {
1746			wrapper.find('.em-time-all-day').prop('checked', false).prop('indeterminate', false);
1747		}
1748		this.dataset.seconds = start.val() ? start.em_timepicker('getSecondsFromMidnight') : '';
1749		retargetEvent(e);
1750	});
1751	// Validate.
1752	container.querySelectorAll('.em-time-range').forEach( el => el.addEventListener('change', function (e) {
1753		if ( e.target.matches('input.em-time-end') ) {
1754			let end = jQuery(e.target);
1755			e.target.dataset.seconds = end.val() ? end.em_timepicker('getSecondsFromMidnight') : '';
1756			em_validate_end_time( e.target );
1757		} else if ( e.target.matches('input.em-time-all-day') ) {
1758			e.currentTarget.querySelectorAll('.em-time-input').forEach(function (input) {
1759				input.readOnly = e.target.checked;
1760			});
1761			if ( e.target.checked ) {
1762				// set 12am and 11:59pm for start/end times
1763				e.currentTarget.querySelectorAll('.em-time-start').forEach( el => jQuery(el).em_timepicker('setTime', new Date('2000-01-01 00:00:00') ) );
1764				e.currentTarget.querySelectorAll('.em-time-end').forEach( el => jQuery(el).em_timepicker('setTime', new Date('2000-01-01 23:59:59') ) );
1765			}
1766		}
1767	}) );
1768	// Re-validate on either date changing, so that a multi-day event no longer flags an end time earlier than its start time.
1769	wrap.find('input[name="event_start_date"], input[name="event_end_date"]').off('change.em_timepicker').on('change.em_timepicker', function () {
1770		jQuery(this).closest('.event-form-when').find('.em-time-range input.em-time-end').each( function () {
1771			em_validate_end_time( this );
1772		});
1773	});
1774	// listen to and dispatch the event
1775	wrap.find(".em-time-range input.em-time-end").on('change', retargetEvent );
1776}
1777
1778/**
1779 * Flags an end time that falls before its start time, which is only an error when the event starts and ends on the same day.
1780 * Global because the timeranges editor clears the error class off a whole editor and has to put this one back.
1781 *
1782 * @param {HTMLInputElement} el
1783 */
1784function em_validate_end_time( el ) {
1785	let range = el.closest('.em-time-range');
1786	let start = jQuery( range ? range.querySelector('input.em-time-start') : null );
1787	let end = jQuery(el);
1788	if ( !start.val() ) {
1789		return;
1790	}
1791	if ( !end.val() ) {
1792		el.classList.remove('error');
1793		return;
1794	}
1795	// Ticket availability dates its own range, everything else is dated by the event.
1796	let range_dates = range ? range.querySelectorAll('input[type="date"]') : [];
1797	let dates_wrapper = el.closest('.event-form-when');
1798	let start_date_element = range_dates.length === 2 ? range_dates[0] : ( dates_wrapper ? dates_wrapper.querySelector('input[name="event_start_date"]') : null );
1799	let end_date_element = range_dates.length === 2 ? range_dates[1] : ( dates_wrapper ? dates_wrapper.querySelector('input[name="event_end_date"]') : null );
1800	let start_date = start_date_element ? start_date_element.value : '';
1801	let end_date = end_date_element ? end_date_element.value : '';
1802	// A recurrence set crosses midnight on its duration in days rather than a date range, and reconciles its own times.
1803	let hasError = !el.closest('.em-recurrence-set') && start.em_timepicker('getTime') > end.em_timepicker('getTime') && ( !end_date || start_date === end_date );
1804	el.classList.toggle('error', hasError);
1805}
1806
1807function em_unsetup_timepicker( container ) {
1808	jQuery(container).find('.em-time-range input.em-time-end, .em-time-range input.em-time-start').unbind(['click','focus','change']); //clear all timepickers - consequently, also other click/blur/change events, recreate the further down
1809}
1810
1811let em_close_other_selectized = function(){
1812	// find all other selectized items and close them
1813	let control = this.classList.contains('selectize-control') ? this.closest('.em-selectize.selectize-control') : this;
1814	document.querySelectorAll('.em-selectize.dropdown-active').forEach( function( el ){
1815		if( el !== control && 'selectize' in el.previousElementSibling) {
1816			el.previousElementSibling.selectize.close();
1817		}
1818	});
1819}
1820
1821document.addEventListener('events_manager_js_loaded', function(){
1822	EM_Selectize.define('multidropdown', function( options ) {
1823		if( !this.$input.hasClass('multidropdown') ) return;
1824		let s = this;
1825		let s_setup = s.setup;
1826		let s_refreshOptions = s.refreshOptions;
1827		let s_open = s.open;
1828		let s_close = s.close;
1829		let placeholder;
1830		let placeholder_text
1831		let placeholder_default;
1832		let placeholder_label;
1833		let counter;
1834		let isClosing = false;
1835		this.changeFunction = function() {
1836			let items = s.getValue();
1837			let selected_text = this.$input.attr('data-selected-text') ? this.$input.attr('data-selected-text') : '%d Selected';
1838			counter.children('span.selected-text').text(selected_text.replace('%d', items.length));
1839			if( items.length > 0 ) {
1840				counter.removeClass('hidden');
1841				placeholder_text.text( placeholder_label );
1842				s.$control_input.attr('placeholder', s.$input.attr('placeholder'));
1843			} else {
1844				counter.addClass('hidden');
1845				placeholder_text.text( placeholder_default );
1846			}
1847		}
1848		this.setup = function() {
1849			s_setup.apply(s);
1850			s.isDropdownClosingPlaceholder = false;
1851			// add section to top of selection to show the dropdown text
1852			placeholder = jQuery('<div class="em-selectize-placeholder"></div>').prependTo(s.$wrapper);
1853			let clear_text = this.$input.attr('data-clear-text') ? this.$input.attr('data-clear-text') : 'Clear Selection';
1854			counter = jQuery('<span class="placeholder-count hidden"><a href="#" class="remove" tabindex="-1">X</a><span class="selected-text"></span><span class="clear-selection">' + clear_text + '</span></div>').prependTo(placeholder);
1855			placeholder_text = jQuery('<span class="placeholder-text"></span>').appendTo(placeholder);
1856			placeholder_default = s.$input.attr('data-default') ? s.$input.attr('data-default') : s.$input.attr('placeholder');
1857			placeholder_label = s.$input.attr('data-label') ? s.$input.attr('data-label') : s.$input.attr('placeholder');
1858			placeholder_text.text( placeholder_default );
1859			s.$dropdown.prepend(s.$control_input.parent());
1860			s.on('dropdown_close', function() {
1861				s.$wrapper.removeClass('dropdown-active');
1862			});
1863			s.on('dropdown_open', function() {
1864				s.$wrapper.addClass('dropdown-active');
1865				s.$control_input.val('');
1866			});
1867			s.on('change', this.changeFunction);
1868			placeholder.on('focus blur click', function (e) {
1869				// only if we're clicking on the placeholder
1870				if( this.matches('.em-selectize-placeholder') ) {
1871					if ( !s.isOpen && e.type !== 'blur' ){
1872						s.open();
1873					} else if ( s.isOpen && e.type !== 'focus' ) {
1874						s.close();
1875					}
1876				}
1877			}).on('focus blur click mousedown mouseup', function( e ){
1878				if( this.matches('.em-selectize-placeholder') ) {
1879					// stope selectize doing anything to our own open/close actions
1880					e.stopPropagation();
1881					e.preventDefault();
1882					if( e.type === 'click' ) {
1883						em_close_other_selectized.call( this.closest('.selectize-control') );
1884						if ( s.isOpen && s.$control_input.val() && !this.matches('.placeholder-count') && !this.closest('.placeholder-count') ) {
1885							isClosing = true;
1886							s.close();
1887						}
1888					} else {
1889						isClosing = false;
1890					}
1891					return false;
1892				}
1893			});
1894			counter.on( 'click' , function( e ){
1895				e.preventDefault();
1896				e.stopPropagation();
1897				s.clear();
1898				if( s.isOpen ) s.refreshOptions();
1899			});
1900			this.changeFunction();
1901		}
1902
1903		// prevent dropdown from closing when no options are found, because the search input shows within the dropdown in multidropdown
1904		this.refreshOptions = function ( ...args ) {
1905			s_refreshOptions.apply(s, args);
1906			if ( !this.hasOptions && this.lastQuery ) {
1907				// intervene on closing only if not in a closing process caused by our own listeners
1908				if( isClosing === false ) {
1909					this.$wrapper.addClass("dropdown-active");
1910					s.isOpen = true;
1911				}
1912				this.$wrapper.addClass("no-options");
1913				isClosing = false;
1914			} else {
1915				this.$wrapper.removeClass("no-options");
1916			}
1917		};
1918	});
1919});
1920
1921function em_setup_selectize( container_element ){
1922	container = jQuery(container_element); // in case we were given a dom object
1923
1924	container.find('.em-selectize.selectize-control').on( 'click', em_close_other_selectized );
1925
1926	let optionRender = function (item, escape) {
1927		let html = '<div class="option"';
1928		if( 'data' in item ){
1929			// any key/value object pairs wrapped in a 'data' key within JSON object in the data-data attribute is added automatically as a data-key="value" attribute
1930			Object.entries(item.data).forEach( function( item_data ){
1931				html += ' data-'+ escape(item_data[0]) + '="'+ escape(item_data[1]) +'"';
1932			});
1933		}
1934		html +=	'>';
1935		if( this.$input.hasClass('checkboxes') ){
1936			html += item.text.replace(/^(\s+)?/i, '$1<span></span> ');
1937		}else{
1938			html += item.text;
1939		}
1940		html += '</div>';
1941		return html;
1942	};
1943
1944	// Selectize General
1945	container.find('select:not([multiple]).em-selectize, .em-selectize select:not([multiple])').em_selectize({
1946		selectOnTab : false,
1947		render: {
1948			option: optionRender,
1949		},
1950	}).on('change', ( e ) => {
1951		e.target.selectize?.$input[0].parentElement.dispatchEvent( new CustomEvent('change', { bubbles: true, cancelable: true, detail : { target: e.target, selectize: e.target.selectize } }) )
1952	});
1953	container.find('select[multiple].em-selectize, .em-selectize select[multiple]').em_selectize({
1954		selectOnTab : false,
1955		hideSelected : false,
1956		plugins: ["remove_button", 'click2deselect','multidropdown'],
1957		diacritics : true,
1958		render: {
1959			item: function (item, escape) {
1960				return '<div class="item"><span>' + item.text.replace(/^\s+/i, '') + '</span></div>';
1961			},
1962			option : optionRender,
1963			optgroup : function (item, escape) {
1964				let html = '<div class="optgroup" data-group="' + escape(item.label) + '"';
1965				if( 'data' in item ){
1966					// any key/value object pairs wrapped in a 'data' key within JSON object in the data-data attribute is added automatically as a data-key="value" attribute
1967					Object.entries(item.data).forEach( function( item_data ){
1968						html += ' data-'+ escape(item_data[0]) + '="'+ escape(item_data[1]) +'"';
1969					});
1970				}
1971				html +=	'>';
1972				return html + item.html + '</div>';
1973			}
1974
1975		},
1976	}).on('change', ( e ) => {
1977		e.target.selectize?.$input[0].parentElement.dispatchEvent( new CustomEvent('change', { bubbles: true, cancelable: true, detail : { target: e.target, selectize: e.target.selectize } }) )
1978	});
1979	container.find('.em-selectize:not(.always-open)').each( function(){
1980		if( 'selectize' in this ){
1981			let s = this.selectize;
1982			this.selectize.$wrapper.on('keydown', function(e) {
1983				if( e.keyCode === 9 ) {
1984					s.blur();
1985				}
1986			});
1987		}
1988	});
1989	container.find('.em-selectize.always-open').each( function(){
1990		//extra behaviour for selectize "always open mode"
1991		if( 'selectize' in this ){
1992			let s = this.selectize;
1993			s.open();
1994			s.advanceSelection = function(){}; // remove odd item shuffling
1995			s.setActiveItem = function(){}; // remove odd item shuffling
1996			// add event listener to fix remove button issues due to above hacks
1997			this.selectize.$control.on('click', '.remove', function(e) {
1998				if ( s.isLocked  ) return;
1999				var $item = jQuery(e.currentTarget).parent();
2000				s.removeItem($item.attr('data-value'));
2001				s.refreshOptions();
2002				return false;
2003			});
2004		}
2005	});
2006
2007	// Sortables - selectize and sorting columns, usually in list tables
2008	container.find('.em-list-table-modal .em-list-table-cols').each( function(){
2009		let parent = jQuery(this);
2010		let sortables = jQuery(this).find('.em-list-table-cols-sortable');
2011		parent.find('.em-selectize.always-open').each( function() {
2012			//extra behaviour for selectize column picker
2013			if ('selectize' in this) {
2014				let selectize = this.selectize;
2015				// add event listener to fix remove button issues due to above hacks
2016				selectize.on('item_add', function (value, item) {
2017					let col = item.clone();
2018					let option  = selectize.getOption(value);
2019					let type = option.attr('data-type');
2020					col.appendTo(sortables);
2021					col.attr('data-type', type);
2022					if( option.attr('data-header') ) {
2023						col.children('span:first-child').text( option.attr('data-header') );
2024					}
2025					jQuery('<input type="hidden" name="cols[' + value + ']" value="1">').appendTo(col);
2026				});
2027				selectize.on('item_remove', function (value) {
2028					parent.find('.item[data-value="'+ value +'"]').remove();
2029				});
2030				parent.on('click', '.em-list-table-cols-selected .item .remove', function(){
2031					let value = this.parentElement.getAttribute('data-value');
2032					selectize.removeItem(value, true);
2033				});
2034			}
2035		});
2036	});
2037}
2038
2039function em_unsetup_selectize( container ) {
2040	container.querySelectorAll('.em-selectize').forEach( function( el ) {
2041		//extra behaviour for selectize "always open mode"
2042		if ( 'selectize' in el ) {
2043			el.selectize.destroy();
2044		}
2045	});
2046}
2047
2048function em_setup_tippy( container_element ){
2049	let container = jQuery(container_element);
2050	var tooltip_vars = {
2051		theme : 'light-border',
2052		appendTo : 'parent',
2053		content(reference) {
2054			if( reference.dataset.content ){
2055				try {
2056					let content = container[0].querySelector(reference.dataset.content);
2057					if (content) {
2058						content.classList.remove('hidden');
2059						return content;
2060					}
2061				} catch ( error ) {
2062					console.log('Invlid tooltip selector in %o : %o', reference, error);
2063				}
2064			};
2065			return reference.getAttribute('aria-label') ?? reference.title ?? '';
2066		},
2067		'touch' : ['hold', 300],
2068		allowHTML : true,
2069	};
2070	jQuery(document).trigger('em-tippy-vars',[tooltip_vars, container]);
2071	container.find('.em-tooltip').each( ( i, tooltip ) => tippy( tooltip, tooltip_vars ) );
2072	// Set up Tippy DDMs
2073	let tippy_ddm_options = {
2074		theme : 'light-border',
2075		arrow : false,
2076		allowHTML : true,
2077		interactive : true,
2078		trigger : 'manual',
2079		placement : 'bottom',
2080		zIndex : 1000000,
2081		touch : true,
2082	};
2083	jQuery(document).trigger('em-tippy-ddm-vars',[tippy_ddm_options, container]);
2084	container.find('.em-tooltip-ddm').each( function(){
2085		let ddm_content, ddm_content_sibling;
2086		if( this.getAttribute('data-content') ){
2087			ddm_content = document.getElementById(this.getAttribute('data-content'))
2088			ddm_content_sibling = ddm_content.previousElementSibling;
2089		}else{
2090			ddm_content = this.nextElementSibling;
2091			ddm_content_sibling = ddm_content.previousElementSibling;
2092		}
2093		let tippy_content = document.createElement('div');
2094		// allow for custom width
2095		let button_width = this.getAttribute('data-button-width');
2096		if( button_width ){
2097			if( button_width == 'match' ){
2098				tippy_ddm_options.maxWidth = this.clientWidth;
2099				ddm_content.style.width = this.clientWidth + 'px';
2100			}else{
2101				tippy_ddm_options.maxWidth = this.getAttribute('data-button-width');
2102			}
2103		}
2104		tippy_ddm_options.content = tippy_content;
2105		let tippy_ddm = tippy(this, tippy_ddm_options);
2106		tippy_ddm.props.distance = 50;
2107		tippy_ddm.setProps({
2108			onShow(instance){
2109				if( instance.reference.getAttribute('data-tooltip-class') ) {
2110					instance.popper.classList.add( instance.reference.getAttribute('data-tooltip-class') );
2111				}
2112				instance.popper.classList.add( 'em-tooltip-ddm-display' );
2113				tippy_content.append(ddm_content);
2114				ddm_content.classList.remove('em-tooltip-ddm-content');
2115			},
2116			onShown(instance){ // keyboard support
2117				ddm_content.firstElementChild.focus();
2118			},
2119			onHidden(instance){
2120				if( ddm_content.previousElementSibling !== ddm_content_sibling ) {
2121					ddm_content_sibling.after(ddm_content);
2122					ddm_content.classList.add('em-tooltip-ddm-content');
2123				}
2124			},
2125		});
2126		let tippy_listener = function(e){
2127			if( e.type === 'keydown' && !(e.which === 13 || e.which === 40) ) return false;
2128			e.preventDefault();
2129			e.stopPropagation();
2130			this._tippy.show();
2131		}
2132		this.addEventListener('click', tippy_listener);
2133		this.addEventListener('keydown', tippy_listener);
2134		tippy_content.addEventListener('blur', function(){
2135			tippy_content.hide();
2136		});
2137		tippy_content.addEventListener('mouseover', function(){
2138			ddm_content.firstElementChild.blur();
2139		});
2140	});
2141}
2142
2143function em_unsetup_tippy( container ) {
2144	container.querySelectorAll('.em-tooltip-ddm').forEach( function( el ){
2145		if ( '_tippy' in el ) {
2146			el._tippy.destroy();
2147		}
2148	});
2149}
2150
2151/*
2152 * MAP FUNCTIONS
2153 */
2154var em_maps_loaded = false;
2155var maps = {};
2156var maps_markers = {};
2157var maps_infoWindows = {};
2158var content
2159//loads maps script if not already loaded and executes EM maps script
2160function em_maps_load(){
2161	if( !em_maps_loaded ){
2162		if ( jQuery('script#google-maps').length == 0 && ( typeof google !== 'object' || typeof google.maps !== 'object' ) ){
2163			let script = document.createElement("script");
2164			script.type = "text/javascript";
2165			script.id = "google-maps";
2166			script.async = true;
2167			let proto = (EM.is_ssl) ? 'https:' : 'http:';
2168			if( typeof EM.google_maps_api !== 'undefined' ){
2169				script.src = proto + '//maps.google.com/maps/api/js?loading=async&v=quarterly&libraries=places&callback=em_maps&key='+EM.google_maps_api;
2170			}else{
2171				script.src = proto + '//maps.google.com/maps/api/js?loading=async&v=quarterly&libraries=places&callback=em_maps';
2172			}
2173			document.body.appendChild(script);
2174		}else if( typeof google === 'object' && typeof google.maps === 'object' && !em_maps_loaded ){
2175			em_maps();
2176		}else if( jQuery('script#google-maps').length > 0 ){
2177			jQuery(window).load(function(){ if( !em_maps_loaded ) em_maps(); }); //google isn't loaded so wait for page to load resources
2178		}
2179	}
2180}
2181jQuery(document).on('em_view_loaded_map', function( e, view, form ){
2182	if( !em_maps_loaded ){
2183		em_maps_load();
2184	}else{
2185		let map = view.find('div.em-locations-map');
2186		em_maps_load_locations( map[0] );
2187	}
2188});
2189/*
2190 * Custom JSON map styling vs Advanced Markers. Google forbids the legacy `styles` property when a `mapId` is present, and Advanced Markers require a `mapId` — the two are mutually exclusive. So when the site has custom JSON styling configured we build a raster map with NO mapId (so the styles apply) and fall back to the legacy google.maps.Marker that a raster map can host; otherwise we keep the mapId + Advanced Markers path.
2191 */
2192function em_map_get_styles( map_id ){
2193	if( typeof EM.google_map_id_styles == 'object' && typeof EM.google_map_id_styles[map_id] !== 'undefined' ){
2194		return EM.google_map_id_styles[map_id];
2195	}
2196	if( typeof EM.google_maps_styles !== 'undefined' ){
2197		return EM.google_maps_styles;
2198	}
2199	return null;
2200}
2201function em_map_create( el, map_options, map_id ){
2202	let styles = em_map_get_styles( map_id );
2203	if( styles ){
2204		map_options = jQuery.extend({}, map_options, { styles: styles });
2205		delete map_options.mapId; // styles are ignored (and warned about) while a mapId is present
2206	}
2207	let map = new google.maps.Map( el, map_options );
2208	map.em_styled = !!styles;
2209	return map;
2210}
2211function em_map_create_marker( AdvancedMarkerElement, map, marker_options, map_id ){
2212	let marker;
2213	if( map.em_styled ){
2214		// a styled raster map cannot host Advanced Markers, so use the legacy marker
2215		marker = new google.maps.Marker({
2216			position: marker_options.position,
2217			map: map,
2218			title: marker_options.title,
2219			draggable: !!marker_options.gmpDraggable,
2220		});
2221		marker.em_advanced = false;
2222	}else{
2223		marker = new AdvancedMarkerElement( marker_options );
2224		marker.em_advanced = true;
2225	}
2226	marker.em_map_id = map_id;
2227	return marker;
2228}
2229function em_marker_position( marker ){
2230	return ( typeof marker.getPosition === 'function' ) ? marker.getPosition() : marker.position;
2231}
2232//re-usable function to load global location maps
2233async function em_maps_load_locations( element ){
2234	const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
2235	let el = element;
2236	let map_id = el.getAttribute('id').replace('em-locations-map-','');
2237	let em_data;
2238	if ( document.getElementById('em-locations-map-coords-'+map_id) ) {
2239		em_data = JSON.parse( document.getElementById('em-locations-map-coords-'+map_id).text );
2240	} else {
2241		let coords_data = el.parentElement.querySelector('.em-locations-map-coords');
2242		if ( coords_data ) {
2243			em_data = JSON.parse( coords_data.text );
2244		} else {
2245			em_data = {};
2246		}
2247	}
2248	jQuery.getJSON(document.URL, em_data , function( data ) {
2249		if( data.length > 0 ){
2250			//define default options and allow option for extension via event triggers
2251			let map_options = {
2252				mapTypeId: google.maps.MapTypeId.ROADMAP,
2253				mapId: 'em-locations-map-' + map_id
2254			};
2255			jQuery(document).triggerHandler('em_maps_locations_map_options', map_options);
2256			let marker_options = {};
2257			jQuery(document).triggerHandler('em_maps_location_marker_options', marker_options);
2258
2259			maps[map_id] = em_map_create(el, map_options, map_id);
2260			maps_markers[map_id] = [];
2261
2262			let bounds = new google.maps.LatLngBounds();
2263
2264			jQuery.map( data, function( location, i ){
2265				if( !(location.location_latitude == 0 && location.location_longitude == 0) ){
2266					let latitude = parseFloat( location.location_latitude );
2267					let longitude = parseFloat( location.location_longitude );
2268					let location_position = new google.maps.LatLng( latitude, longitude );
2269					//extend the default marker options
2270					jQuery.extend(marker_options, {
2271						position: location_position,
2272						map: maps[map_id]
2273					})
2274					let marker = em_map_create_marker(AdvancedMarkerElement, maps[map_id], marker_options, map_id);
2275					maps_markers[map_id] = marker;
2276					em_map_InfoWindow ( location.location_name, location.location_balloon, marker );
2277					//extend bounds
2278					bounds.extend(new google.maps.LatLng(latitude,longitude))
2279				}
2280			});
2281			// Zoom in to the bounds
2282			maps[map_id].fitBounds(bounds);
2283
2284			//Call a hook if exists
2285			if( jQuery ) {
2286				jQuery(document).triggerHandler('em_maps_locations_hook', [maps[map_id], data, map_id, maps_markers[map_id]]);
2287			}
2288			document.dispatchEvent( new CustomEvent('em_maps_locations_hook', {
2289				detail: {
2290					map : maps[map_id],
2291					data : data,
2292					id : map_id,
2293					markers : maps_markers[map_id],
2294					el : el,
2295				},
2296				cancellable : true,
2297			}));
2298		} else {
2299			el.firstElementChild.innerHTML = 'No locations found';
2300			if( jQuery ) {
2301				jQuery(document).triggerHandler('em_maps_locations_hook_not_found', [ jQuery(el) ]);
2302			}
2303			document.dispatchEvent( new CustomEvent('em_maps_locations_hook_not_found', {
2304				detail: {
2305					id : map_id,
2306					el : el
2307				},
2308				cancellable : true,
2309			}));
2310		}
2311	});
2312}
2313async function em_maps_load_location(el){
2314	el = jQuery(el);
2315	const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
2316	let mapId = el.attr('id');
2317	let map_id = mapId.replace('em-location-map-','');
2318	let map_title = el.attr('title');
2319	let em_LatLng = new google.maps.LatLng( jQuery('#em-location-map-coords-'+map_id+' .lat').text(), jQuery('#em-location-map-coords-'+map_id+' .lng').text());
2320	//extend map and markers via event triggers
2321	let map_options = {
2322		zoom: 14,
2323		center: em_LatLng,
2324		mapTypeId: google.maps.MapTypeId.ROADMAP,
2325		mapTypeControl: false,
2326		gestureHandling: 'cooperative',
2327		mapId: mapId,
2328	};
2329	jQuery(document).triggerHandler('em_maps_location_map_options', map_options);
2330	maps[map_id] = em_map_create( document.getElementById('em-location-map-'+map_id), map_options, map_id);
2331	let marker_options = {
2332		position: em_LatLng,
2333		map: maps[map_id],
2334		title: map_title,
2335	};
2336	jQuery(document).triggerHandler('em_maps_location_marker_options', marker_options);
2337	let marker = em_map_create_marker(AdvancedMarkerElement, maps[map_id], marker_options, map_id);
2338	maps_markers[map_id] = marker;
2339	let content = jQuery('#em-location-map-info-'+map_id + ' .em-map-balloon-content').get(0);
2340	em_map_InfoWindow( map_title, content, marker, true );
2341
2342	//JS Hook for handling map after instantiation
2343	//Example hook, which you can add elsewhere in your theme's JS - jQuery(document).on('em_maps_location_hook', function(){ alert('hi');} );
2344	jQuery(document).triggerHandler('em_maps_location_hook', [maps[map_id], infoWindow, maps_markers[map_id], map_id]);
2345	//map resize listener
2346	jQuery(window).on('resize', function(e) {
2347		google.maps.event.trigger(maps[map_id], "resize");
2348		maps[map_id].setCenter(em_marker_position(maps_markers[map_id]));
2349		maps[map_id].panBy(40,-70);
2350	});
2351}
2352jQuery(document).on('em_search_ajax', function(e, vars, wrapper){
2353	if( em_maps_loaded ){
2354		wrapper.find('div.em-location-map').each( function(index, el){ em_maps_load_location(el); } );
2355		wrapper.find('div.em-locations-map').each( function(index, el){ em_maps_load_locations(el); });
2356	}
2357});
2358//Load single maps (each map is treated as a seperate map).
2359async function em_maps() {
2360	/**
2361	 * InfoWindow object - Location info bubble on map, showing the current map
2362	 */
2363	let infoWindow;
2364	//Find all the maps on this page and load them
2365	jQuery('div.em-location-map').each( function(index, el){ em_maps_load_location(el); } );
2366	jQuery('div.em-locations-map').each( function(index, el){ em_maps_load_locations(el); } );
2367
2368	//Location stuff - only needed if inputs for location exist
2369	if( jQuery('select#location-select-id, input#location-address').length > 0 ){
2370		const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
2371		let map
2372		let marker;
2373
2374		// refresh map with current location info
2375		let refresh_map_location = function(){
2376			let location_latitude = jQuery('#location-latitude').val();
2377			let location_longitude = jQuery('#location-longitude').val();
2378			let hasCoords = location_latitude != 0 || location_longitude != 0;
2379			if( hasCoords ){
2380				let position = new google.maps.LatLng(location_latitude, location_longitude); //the location coords
2381				marker.position = position;
2382				let mapTitle = (jQuery('input#location-name').length > 0) ? jQuery('input#location-name').val():jQuery('input#title').val();
2383				mapTitle = em_esc_attr(mapTitle);
2384				marker.title = mapTitle ;
2385				marker.gmpDraggable = true;
2386				jQuery('#em-map').show();
2387				jQuery('#em-map-404').hide();
2388				google.maps.event.trigger(map, 'resize');
2389				map.setCenter(position);
2390				map.panBy(40,-55);
2391				infoWindow?.close();
2392				infoWindow = em_map_InfoWindow( mapTitle, em_esc_attr(jQuery('#location-address').val()) + '<br>' + em_esc_attr(jQuery('#location-town').val()), marker, true );
2393				jQuery(document).triggerHandler('em_maps_location_hook', [map, infoWindow, marker, 0]);
2394			} else {
2395				jQuery('#em-map').hide();
2396				jQuery('#em-map-404').show();
2397			}
2398		};
2399
2400		// Add listeners for changes to address or location ID
2401
2402		// get or refresh the map by location id
2403		let get_map_by_id = function(id){
2404			if(jQuery('#em-map').length > 0){
2405				jQuery('#em-map-404 .em-loading-maps').show();
2406				jQuery.getJSON(document.URL,{ em_ajax_action:'get_location', id:id }, function(data){
2407					let hasCoords = data.location_latitude != 0 && data.location_longitude != 0;
2408					if( hasCoords ){
2409						loc_latlng = new google.maps.LatLng(data.location_latitude, data.location_longitude);
2410						marker.position = loc_latlng;
2411						marker.title = data.location_name;
2412						marker.gmpDraggable = false;
2413						jQuery('#em-map').show();
2414						jQuery('#em-map-404').hide();
2415						jQuery('#em-map-404 .em-loading-maps').hide();
2416						map.setCenter(loc_latlng);
2417						map.panBy(40,-55);
2418						infoWindow?.close();
2419						infoWindow = em_map_InfoWindow( data.location_name, data.location_balloon, marker, true );
2420						google.maps.event.trigger(map, 'resize');
2421						jQuery(document).triggerHandler('em_maps_location_hook', [map, infoWindow, marker, 0]);
2422					}else{
2423						jQuery('#em-map').hide();
2424						jQuery('#em-map-404').show();
2425						jQuery('#em-map-404 .em-loading-maps').hide();
2426					}
2427				});
2428			}
2429		};
2430		jQuery('#location-select-id, input#location-id').on('change', function() { get_map_by_id( jQuery(this).val() ); } );
2431
2432		// detect changes to address fields and build a coordinate from geocoding
2433		jQuery('#location-name, #location-town, #location-address, #location-state, #location-postcode, #location-country').on('change', function(){
2434			//build address
2435			if( jQuery(this).prop('readonly') === true ) return;
2436			let addresses = [ jQuery('#location-address').val(), jQuery('#location-town').val(), jQuery('#location-state').val(), jQuery('#location-postcode').val() ];
2437			let address = '';
2438			jQuery.each( addresses, function(i, val){
2439				if( val != '' ){
2440					address = ( address == '' ) ? address+val:address+', '+val;
2441				}
2442			});
2443			if( address == '' ){ //in case only name is entered, no address
2444				jQuery('#em-map').hide();
2445				jQuery('#em-map-404').show();
2446				return false;
2447			}
2448			//do country last, as it's using the text version
2449			if( jQuery('#location-country option:selected').val() != 0 ){
2450				address = ( address == '' ) ? address+jQuery('#location-country option:selected').text():address+', '+jQuery('#location-country option:selected').text();
2451			}
2452			//add working indcator whilst we search
2453			jQuery('#em-map-404 .em-loading-maps').show();
2454			//search!
2455			if( address != '' && jQuery('#em-map').length > 0 ){
2456				let geocoder = new google.maps.Geocoder();
2457				geocoder.geocode( { 'address': address }, function(results, status) {
2458					if (status == google.maps.GeocoderStatus.OK) {
2459						jQuery('#location-latitude').val(results[0].geometry.location.lat());
2460						jQuery('#location-longitude').val(results[0].geometry.location.lng());
2461					}
2462					refresh_map_location();
2463				});
2464			}
2465		});
2466		
2467		// Check if we are on a location editing page, and if address was previously entered, if so we check location coords
2468		let location_latitude = jQuery('#location-latitude').val();
2469		let location_longitude = jQuery('#location-longitude').val();
2470		let hasCoords = location_latitude != 0 || location_longitude != 0;
2471		if ( !hasCoords  ) {
2472			// check if there's any address items that were added previously
2473			if ( document.getElementById('location-address')?.value != '' && (document.getElementById('location-address')?.value != '' || document.getElementById('location-town')?.value != '' || document.getElementById('location-state')?.value != '' || document.getElementById('location-postcode')?.value != '' ) ) {
2474				// trigger a change so we reload the address and coords
2475				jQuery('#location-address').trigger('change');
2476				if ( 'google_maps_resave_location' in EM ) {
2477					alert(EM.google_maps_resave_location);
2478				}
2479			}
2480		}
2481
2482		// Load map initially
2483		if(jQuery('#em-map').length > 0){
2484			let em_LatLng = new google.maps.LatLng(0, 0);
2485			let map_options = {
2486				zoom: 14,
2487				center: em_LatLng,
2488				mapTypeId: google.maps.MapTypeId.ROADMAP,
2489				mapTypeControl: false,
2490				gestureHandling: 'cooperative',
2491				mapId: 'em-map',
2492			};
2493			// the location editor keeps Advanced Markers (mapId) for the draggable coordinate picker; custom front-end JSON styling is intentionally not applied here (it can't coexist with a mapId, and a dark style hinders coordinate picking)
2494			map = new google.maps.Map( document.getElementById('em-map'), map_options);
2495			marker = new AdvancedMarkerElement({
2496				position: em_LatLng,
2497				map: map,
2498				gmpDraggable: true,
2499			});
2500			google.maps.event.addListener(marker, 'dragend', function() {
2501				let position = marker.position;
2502				jQuery('#location-latitude').val(position.lat);
2503				jQuery('#location-longitude').val(position.lng);
2504				map.setCenter(position);
2505				map.panBy(40,-55);
2506			});
2507			if( jQuery('#location-select-id').length > 0 ){
2508				jQuery('#location-select-id').trigger('change');
2509			}else{
2510				refresh_map_location();
2511			}
2512			jQuery(document).triggerHandler('em_map_loaded', [map, infoWindow, marker]);
2513		}
2514		//map resize listener
2515		jQuery(window).on('resize', function(e) {
2516			google.maps.event.trigger(map, "resize");
2517			map.setCenter(marker.position);
2518			map.panBy(40,-55);
2519		});
2520	}
2521	em_maps_loaded = true; //maps have been loaded
2522	jQuery(document).triggerHandler('em_maps_loaded');
2523}
2524
2525function em_map_InfoWindow( title, content, marker, open = false ) {
2526	let title_content = document.createElement("div");
2527	let map_id = ('em_map_id' in marker) ? marker.em_map_id : marker.map.mapId.replace(/em-location-maps?-/,'');
2528	title_content.className = "em-map-balloon-title";
2529	title_content.innerHTML = title;
2530	if ( typeof content === 'string' ) {
2531		let wrapper = document.createElement("div");
2532		wrapper.innerHTML = content;
2533		content = wrapper;
2534	}
2535	// wrap content in div with class if not already done
2536	content.classList.add('em-map-balloon-content');
2537	let infoWindow = new google.maps.InfoWindow( {
2538		content: content,
2539		headerContent: title_content,
2540	} );
2541	infoWindow.addListener('domready', function() {
2542		marker.map.panBy(40,-70);
2543	});
2544	if ( !( map_id in maps_infoWindows ) ) {
2545		maps_infoWindows[ map_id ] = [];
2546	}
2547	maps_infoWindows[ map_id ].push( infoWindow );
2548	let open_options = {
2549		shouldFocus: false,
2550		anchor: marker,
2551		map: marker.map,
2552	};
2553	let click_event = ( ('em_advanced' in marker) ? marker.em_advanced : !(marker instanceof google.maps.Marker) ) ? 'gmp-click' : 'click';
2554	marker.addListener(click_event, () => {
2555		maps_infoWindows[ map_id ]?.forEach( ( infoWindow ) => infoWindow.close() );
2556		infoWindow.open( open_options );
2557	});
2558	if ( open ) {
2559		maps_infoWindows[ map_id ]?.forEach( ( infoWindow ) => infoWindow.close() );
2560		infoWindow.open( open_options );
2561	}
2562	return infoWindow;
2563}
2564
2565/**
2566 * @deprecated use em_map_infowindow instead
2567 * @param marker
2568 * @param message
2569 * @param map
2570 */
2571function em_map_infobox(marker, message, map) {
2572	let iw = new google.maps.InfoWindow({ content: message });
2573	google.maps.event.addListener(marker, 'click', function() {
2574		if( infoWindow ) infoWindow.close();
2575		infoWindow = iw;
2576		iw.open(map,marker);
2577	});
2578}
2579
2580function em_esc_attr( str ){
2581	if( typeof str !== 'string' ) return '';
2582	return str.replace(/</gi,'&lt;').replace(/>/gi,'&gt;');
2583}
2584
2585// Modal Open/Close
2586let openModal = function( modal, onOpen = null ){
2587	modal = jQuery(modal);
2588	modal.appendTo(document.body);
2589	setTimeout( function(){
2590		modal.addClass('active').find('.em-modal-popup').addClass('active');
2591		jQuery(document).triggerHandler('em_modal_open', [modal]);
2592		document.dispatchEvent( new CustomEvent('em_modal_open', { detail: { modal: modal } }) );
2593		if( typeof onOpen === 'function' ){
2594			setTimeout( onOpen, 200); // timeout allows css transition
2595		}
2596	}, 100); // timeout allows css transition
2597};
2598let closeModal = function( modal, onClose = null ){
2599	modal = jQuery(modal);
2600	modal.removeClass('active').find('.em-modal-popup').removeClass('active');
2601	setTimeout( function(){
2602		if( modal.attr('data-parent') ){
2603			let wrapper = jQuery('#' + modal.attr('data-parent') );
2604			if( wrapper.length ) {
2605				modal.appendTo(wrapper);
2606			}
2607		}
2608		modal[0].dispatchEvent( new CustomEvent('em_modal_close', { bubbles: true, detail: { modal: modal } } ) );
2609		if( typeof onClose === 'function' ){
2610			onClose();
2611		}
2612	}, 500); // timeout allows css transition
2613}
2614jQuery(document).on('click', '.em-modal .em-close-modal', function(e){
2615	let modal = jQuery(this).closest('.em-modal');
2616	if( !modal.attr('data-prevent-close') ) {
2617		closeModal(modal);
2618	}
2619});
2620jQuery(document).on('click', '.em-modal', function(e){
2621	var target = jQuery(e.target);
2622	if( target.hasClass('em-modal') ) {
2623		let modal = jQuery(this);
2624		if( !modal.attr('data-prevent-close') ){
2625			closeModal(modal);
2626		}
2627	}
2628});
2629
2630function EM_Alert( content ){
2631	// find the alert modal, create if not
2632	let modal = document.getElementById('em-alert-modal');
2633	if( modal === null ){
2634		modal = document.createElement('div');
2635		modal.setAttribute('class', "em pixelbones em-modal");
2636		modal.id = 'em-alert-modal';
2637		modal.innerHTML = '<div class="em-modal-popup"><header><a class="em-close-modal"></a><div class="em-modal-title">&nbsp;</div></header><div class="em-modal-content" id="em-alert-modal-content"></div></div>';
2638		document.body.append(modal);
2639	}
2640	document.getElementById('em-alert-modal-content').innerHTML = content;
2641	openModal(modal);
2642};
2643
2644//Events Search
2645jQuery(document).ready( function($){
2646	// handle the views tip/ddm
2647	let views_ddm_options = {
2648		theme : 'light-border',
2649		allowHTML : true,
2650		interactive : true,
2651		trigger : 'manual',
2652		placement : 'bottom',
2653		zIndex : 1000000,
2654		touch: true,
2655	};
2656	$(document).trigger('em-search-views-trigger-vars',[views_ddm_options]);
2657	let tooltip_vars = { theme : 'light-border', appendTo : 'parent', touch : false, };
2658	$(document).trigger('em-tippy-vars',[tooltip_vars]);
2659
2660	// sync main search texts to advanced search
2661	let search_forms = $('.em-search:not(.em-search-advanced)');
2662	search_forms.each( function(){
2663		/*
2664		 * Important references we'll reuse in scope
2665		 */
2666		let search = $(this);
2667		let search_id = search.attr('id').replace('em-search-', '');
2668		let search_form = search.find('.em-search-form').first();
2669		let search_advanced = search.find('.em-search-advanced'); // there should only be one anyway
2670
2671		/*
2672		 * Counter functions
2673		 */
2674		const update_input_count = function( input, qty = 1 ){
2675			let el = jQuery(input);
2676			let total = qty > 0 ? qty : null;
2677			el.attr('data-advanced-total-input', total);
2678			update_search_totals();
2679		};
2680
2681		const update_search_totals = function( applied = false ){
2682			// set everything to 0, recount
2683			search.find('span.total-count').remove();
2684			// find all fields with total attributes and sum them up
2685			let total = 0;
2686			search_advanced.find('[data-advanced-total-input]').each( function(){
2687				let total_input = this.getAttribute('data-advanced-total-input');
2688				total += Math.abs( total_input );
2689			});
2690			search.attr('data-advanced-total', total);
2691			update_trigger_count( applied );
2692			// find all sections with totals and display them (added above)
2693			search_advanced.find('.em-search-advanced-section').each( function(){
2694				let section = $(this);
2695				let section_total = 0;
2696				section.attr('data-advanced-total', 0);
2697				// go through all set qtys and calculate
2698				section.find('[data-advanced-total-input]').each( function(){
2699					let total_input = this.getAttribute('data-advanced-total-input');
2700					section_total += Math.abs( total_input );
2701				});
2702				section.attr('data-advanced-total', section_total);
2703				update_section_count(section);
2704			});
2705			// update triggers, search, clear button etc.
2706			if( total > 0 || !search.attr('data-advanced-previous-total') || total != search.attr('data-advanced-previous-total') ){
2707				update_submit_buttons( true );
2708			}
2709			update_clear_button_count();
2710		}
2711
2712		const update_trigger_count = function( applied = false ){
2713			let triggers = jQuery('.em-search-advanced-trigger[data-search-advanced-id="em-search-advanced-'+ search_id +'"]'); // search like this ato apply to external triggers
2714			triggers.find('span.total-count').remove();
2715			let total = search.attr('data-advanced-total');
2716			if( total > 0 ){
2717				let trigger_count = jQuery('<span class="total-count">'+ total + '</span>').appendTo(triggers);
2718				if( !applied ){
2719					trigger_count.addClass('tentative');
2720				}
2721			}
2722		};
2723
2724		const update_submit_buttons = function( enabled = false ){
2725			// update the clear link
2726			let submit_button = search_advanced.find('button[type="submit"]');
2727			let main_submit_button = search.find('.em-search-main-bar button[type="submit"]');
2728			let submit_buttons = submit_button.add( main_submit_button ); // merge together to apply chanegs
2729			if( enabled ){
2730				submit_buttons.removeClass('disabled').attr('aria-disabled', 'false');
2731			}else{
2732				submit_buttons.addClass('disabled').attr('aria-disabled', 'true');
2733			}
2734		};
2735
2736		const update_section_count = function( section ){
2737			let section_total = section.attr('data-advanced-total');
2738			section.find('header span.total-count').remove();
2739			if( section_total > 0 ){
2740				$('<span class="total-count">'+ section_total +'</span>').appendTo( section.find('header') );
2741			}
2742		};
2743
2744		const update_clear_button_count = function(){
2745			// update the clear link
2746			let clear_link = search_advanced.find('button[type="reset"]');
2747			if( !clear_link.attr('data-placeholder') ){
2748				clear_link.attr('data-placeholder', clear_link.text());
2749			}
2750			let total = search.attr('data-advanced-total');
2751			if( total > 0 ){
2752				clear_link.text( clear_link.attr('data-placeholder') + ' (' + total + ')' ).prop('disabled', false);
2753				clear_link.removeClass('disabled').attr('aria-disabled', 'false');
2754			}else{
2755				clear_link.text( clear_link.attr('data-placeholder') );
2756				clear_link.addClass('disabled').attr('aria-disabled', 'true');
2757			}
2758		};
2759
2760		/*
2761		 * Triggers
2762		 */
2763		search.find('.em-search-views-trigger').each( function(){
2764			tooltip_vars.content = this.parentElement.getAttribute('aria-label');
2765			let views_tooltip = tippy(this.parentElement, tooltip_vars);
2766			let views_content = this.parentElement.querySelector('.em-search-views-options');
2767			let views_content_parent = views_content.parentElement;
2768			let tippy_content = document.createElement('div');
2769			views_ddm_options.content = tippy_content;
2770			let views_ddm = tippy(this, views_ddm_options);
2771			views_ddm.setProps({
2772				onShow(instance){
2773					views_tooltip.disable();
2774					tippy_content.append(views_content);
2775				},
2776				onShown(instance){ // keyboard support
2777					views_content.querySelector('input:checked').focus();
2778				},
2779				onHidden(instance){
2780					views_tooltip.enable();
2781					if( views_content.parentElement !== views_content_parent ) {
2782						views_content_parent.append(views_content);
2783					}
2784				}
2785			});
2786			let tippy_listener = function(e){
2787				if( e.type === 'keydown' && !(e.which === 13 || e.which === 40) ) return false;
2788				e.preventDefault();
2789				e.stopPropagation();
2790				this._tippy.show();
2791				views_tooltip.hide();
2792			}
2793			this.addEventListener('click', tippy_listener);
2794			this.addEventListener('keydown', tippy_listener);
2795			this.firstElementChild.addEventListener('focus', function(e){
2796				views_ddm.hide();
2797				views_tooltip.enable();
2798				views_tooltip.show();
2799			});
2800			this.firstElementChild.addEventListener('blur', function(){
2801				views_tooltip.hide();
2802			});
2803
2804			search.on('focus blur', '.em-search-views-options input', function(){
2805				if( document.activeElement === this ){
2806					this.parentElement.classList.add('focused');
2807				}else{
2808					this.parentElement.classList.remove('focused');
2809				}
2810			});
2811
2812			search[0].addEventListener('change', function(){
2813				update_submit_buttons(true);
2814			});
2815
2816			search.on('keydown click', '.em-search-views-options input', function( e ){
2817				// get relevant vars
2818				if( e.type === 'keydown' && e.which !== 13 ){
2819					if ( [37, 38, 39, 40].indexOf(e.which) !== -1 ) {
2820						if (e.which === 38) {
2821							if (this.parentElement.previousElementSibling) {
2822								this.parentElement.previousElementSibling.focus();
2823							}
2824						} else if (e.which === 40) {
2825							if (this.parentElement.nextElementSibling) {
2826								this.parentElement.nextElementSibling.focus();
2827							}
2828						}
2829						return false;
2830					} else if ( e.which === 9 ) {
2831						// focus out
2832						views_ddm.hide();
2833					}
2834					return true;
2835				}
2836				this.checked = true;
2837				let input = $(this);
2838				// mark label selected
2839				input.closest('fieldset').find('label').removeClass('checked');
2840				input.parent().addClass('checked');
2841				// get other reference elements we need
2842				let views_wrapper = $(this).closest('.em-search-views');
2843				let view_type = this.value;
2844				let trigger = views_wrapper.children('.em-search-views-trigger');
2845				let trigger_option = trigger.children('.em-search-view-option');
2846				// change view, if different
2847				if( view_type !== trigger_option.attr('data-view') ){
2848					trigger_option.attr('data-view', this.value).text(this.parentElement.innerText);
2849					// remove custom search vals from current view so it's not used into another view
2850					$('#em-view-'+search_id).find('#em-view-custom-data-search-'+search_id).remove();
2851					// trigger custom event in case form disabled due to no search vals
2852					search_form.find('button[type="submit"]').focus();
2853					search_form.trigger('forcesubmit');
2854				}
2855				views_ddm.hide();
2856			});
2857		});
2858
2859		search.find('.em-search-sort-trigger').each( function(){
2860			tooltip_vars.content = this.parentElement.getAttribute('aria-label');
2861			let views_tooltip = tippy(this.parentElement, tooltip_vars);
2862			search.on('keydown click', '.em-search-sort-option', function( e ){
2863				// get other reference elements we need
2864				let order = this.dataset.sort === 'ASC' ? 'DESC' : 'ASC';
2865				this.setAttribute('data-sort', order);
2866				this.parentElement.querySelector('input[name="order"]').value = order;
2867				// trigger custom event in case form disabled due to no search vals
2868				search_form.find('button[type="submit"]').focus();
2869				search_form.trigger('forcesubmit');
2870			});
2871		});
2872
2873		// add trigger logic for advanced popup modal
2874		let search_advanced_trigger_click = function( e ){
2875			if( search.hasClass('advanced-mode-inline') ){
2876				// inline
2877				if( !search_advanced.hasClass('visible') ){
2878					search_advanced.slideDown().addClass('visible');
2879					if( '_tippy' in this ){
2880						this._tippy.setContent(this.getAttribute('data-label-hide'));
2881					}
2882				}else{
2883					search_advanced.slideUp().removeClass('visible');
2884					if( '_tippy' in this ){
2885						this._tippy.setContent(this.getAttribute('data-label-show'));
2886					}
2887				}
2888			}else{
2889				// wrap modal popup element in a form, so taht it's 'accessible' with keyboard
2890				if( !search_advanced.hasClass('active') ) {
2891					let form_wrapper = $('<form action="" method="post" class="em-search-advanced-form" id="em-search-form-advanced-' + search_id + '"></form>');
2892					form_wrapper.appendTo(search_advanced);
2893					search_advanced.find('.em-modal-popup').appendTo(form_wrapper);
2894					// open modal
2895					let button = this;
2896					openModal(search_advanced, function () {
2897						// Do this instead
2898						button.blur();
2899						search_advanced.find('input.em-search-text').focus();
2900					});
2901				}
2902			}
2903		};
2904		search.on('click', 'button.em-search-advanced-trigger:not([data-search-advanced-id],[data-parent-trigger])', search_advanced_trigger_click);
2905		search_form.on('search_advanced_trigger', search_advanced_trigger_click);
2906
2907		search_advanced.on('em_modal_close', function(){
2908			search_advanced.find('.em-modal-popup').appendTo(search_advanced);
2909			search_advanced.children('form').remove();
2910			let trigger = search.find('button.em-search-advanced-trigger').focus();
2911			if( trigger.length > 0 && '_tippy' in trigger[0] ){
2912				trigger[0]._tippy.hide();
2913			}
2914		});
2915
2916		// add header toggle logic to expand/collapse sections - add directly to elements since they move around the DOM due to modal
2917		search_advanced.find('.em-search-advanced-section > header').on('click', function(){
2918			let header = $(this);
2919			let section = header.closest('section');
2920			let content = header.siblings('.em-search-section-content');
2921			if( section.hasClass('active') ){
2922				content.slideUp();
2923				section.removeClass('active');
2924			}else{
2925				content.slideDown();
2926				section.addClass('active');
2927			}
2928		});
2929
2930		/*
2931		 *  Advanced Search Field Listeners - Main Search Form
2932		 */
2933
2934		let search_form_advanced_calculate_totals_inputs = function( input ){
2935			// for textboxes we only need to add or remove 1 advanced
2936			let el = $(input);
2937			let qty = el.val() !== '' ? 1:0;
2938			update_input_count( el, qty );
2939		};
2940
2941		// These are for the main search bar, syncing information back into the advanced form
2942		search.on('change input', '.em-search-main-bar input.em-search-text', function( e ){
2943			// sync advanced input field with same text
2944			let advanced_search_input = search_advanced.find('input.em-search-text');
2945			if ( advanced_search_input.length === 0 ) {
2946				search_form_advanced_calculate_totals_inputs(this);
2947			} else {
2948				advanced_search_input.val( this.value );
2949				// recalculate totals from here
2950				search_form_advanced_calculate_totals_inputs(advanced_search_input[0]);
2951			}
2952			// any change without advanced form should show the search form still
2953			update_submit_buttons( true);
2954		});
2955		search.on('change', '.em-search-main-bar input.em-search-geo-coords', function(){
2956			let el = $(this);
2957			let advanced_geo = search_advanced.find('div.em-search-geo');
2958			// copy over value and class names
2959			let advanced_geo_coords = advanced_geo.find('input.em-search-geo-coords');
2960			if( advanced_geo_coords.length > 0 ) {
2961				advanced_geo_coords.val(el.val()).attr('class', el.attr('class'));
2962				let geo_text = el.siblings('input.em-search-geo').first();
2963				advanced_geo.find('input.em-search-geo').val(geo_text.val()).attr('class', geo_text.attr('class'));
2964				// calculate totals from here
2965				search_form_advanced_calculate_totals_inputs(advanced_geo_coords);
2966			} else {
2967				// calculate totals from here
2968				search_form_advanced_calculate_totals_inputs(this);
2969			}
2970		});
2971		search.find('.em-search-main-bar .em-datepicker input.em-search-scope.flatpickr-input').each( function(){
2972			if( !('_flatpickr' in this) ) return;
2973			this._flatpickr.config.onClose.push( function( selectedDates, dateStr, instance ) {
2974				// any change without advanced form should show the search form
2975				let advanced_datepicker = search_advanced.find('.em-datepicker input.em-search-scope.flatpickr-input');
2976				if( advanced_datepicker.length === 0 ) {
2977					// update counter
2978					let qty = dateStr ? 1:0;
2979					update_input_count(instance.input, qty);
2980				} else {
2981					// update advanced search form datepicker values, trigger a close for it to handle the rest
2982					advanced_datepicker[0]._flatpickr.setDate( selectedDates, true );
2983					advanced_datepicker[0]._flatpickr.close();
2984				}
2985			});
2986		});
2987
2988		search.find('select.em-selectize').each(function () {
2989			if( 'selectize' in this ) {
2990				this.selectize.on('change', function () {
2991					search_advanced_selectize_change(this);
2992				});
2993			}
2994		});
2995
2996		/*
2997		 *  Advanced Search Field Listeners - Advanced Search Form
2998		 */
2999
3000		// regular text advanced or hidden inputs that represent another ui
3001		search_advanced.on('change input', 'input.em-search-text', function( e ){
3002			if( e.type === 'change' ){
3003				// copy over place info on change only, not on each keystroke
3004				search.find('.em-search-main input.em-search-text').val( this.value );
3005			}
3006			search_form_advanced_calculate_totals_inputs(this);
3007		});
3008		search_advanced.on('change', 'input.em-search-geo-coords', function( e ){
3009			search_form_advanced_calculate_totals_inputs(this);
3010			//update values in main search
3011			let el = $(this);
3012			let main = search.find('.em-search-main div.em-search-geo');
3013			if( main.length > 0 ){
3014				// copy over value and class names
3015				main.find('input.em-search-geo-coords').val( el.val() ).attr('class', el.attr('class'));
3016				let geo_text = el.siblings('input.em-search-geo');
3017				main.find('input.em-search-geo').val(geo_text.val()).attr('class', geo_text.attr('class'));
3018			}
3019		});
3020		search_advanced.on('clear_search', function(){
3021			let text = $(this).find('input.em-search-text');
3022			if( text.length === 0 ) {
3023				// select geo from main if it exists, so we keep counts synced
3024				text = search.find('input.em-search-text');
3025			}
3026			text.val('').attr('value', null).trigger('change'); // value attr removed as well due to compat issues in Chrome (possibly more)
3027		});
3028		/* Not sure we should be calculating this... since it's always set to something.
3029		search_advanced.on('change', 'select.em-search-geo-unit, select.em-search-geo-distance', function( e ){
3030			// combine both values into parent, if value set then it's a toggle
3031			let el = jQuery(this);
3032			let qty = el.val() ? 1 : null;
3033			el.closest('.em-search-geo-units').attr('data-advanced-total-input', qty);
3034			update_search_totals();
3035		});
3036		 */
3037		search_advanced.on('change', 'input[type="checkbox"]', function( e ){
3038			let el = $(this);
3039			let qty = el.prop('checked') ? 1:0;
3040			update_input_count( el, qty );
3041		});
3042		search_advanced.on('calculate_totals', function(){
3043			search_advanced.find('input.em-search-text, input.em-search-geo-coords').each( function(){
3044				search_form_advanced_calculate_totals_inputs(this);
3045			});
3046			search_advanced.find('input[type="checkbox"]').trigger('change');
3047		});
3048		search_advanced.on('clear_search', function(){
3049			let geo = $(this).find('input.em-search-geo');
3050			if( geo.length === 0 ) {
3051				// select geo from main if it exists, so we keep counts synced
3052				geo = search.find('input.em-search-geo');
3053			}
3054			geo.removeClass('off').removeClass('on').val('');
3055			geo.siblings('input.em-search-geo-coords').val('').trigger('change');
3056			search_advanced.find('input[type="checkbox"]').prop("checked", false).trigger('change').prop("checked", false); // set checked after trigger because something seems to be checking during event
3057		});
3058
3059		// datepicker advanced logic
3060		search_advanced.find('.em-datepicker input.em-search-scope.flatpickr-input').each( function(){
3061			if( !('_flatpickr' in this) ) return;
3062			this._flatpickr.config.onClose.push( function( selectedDates, dateStr, instance ) {
3063				// check previous value against current value, no change, no go
3064				let previous_value = instance.input.getAttribute('data-previous-value');
3065				if( previous_value !== dateStr ){
3066					// update counter
3067					let qty = dateStr ? 1:0;
3068					update_input_count(instance.input, qty);
3069					// update main search form datepicker values
3070					let main_datepicker = search.find('.em-search-main-bar .em-datepicker input.em-search-scope.flatpickr-input');
3071					if( main_datepicker.length > 0 ) {
3072						main_datepicker[0]._flatpickr.setDate(selectedDates, true);
3073					}
3074					// set for next time
3075					instance.input.setAttribute('data-previous-value', dateStr);
3076				}
3077			});
3078		});
3079		search_advanced.on('calculate_totals', function(){
3080			search_advanced.find('.em-datepicker input.em-search-scope.flatpickr-input').first().each( function(){
3081				let qty = this._flatpickr.selectedDates.length > 0 ? 1 : 0;
3082				update_input_count(this, qty);
3083			});
3084		});
3085		search_advanced.on('clear_search', function(){
3086			let datepickers = search_advanced.find('.em-datepicker input.em-search-scope.flatpickr-input');
3087			if( datepickers.length === 0 ) {
3088				// find datepickers on main form so syncing is sent up
3089				datepickers = search.find('.em-datepicker input.em-search-scope.flatpickr-input');
3090			}
3091			datepickers.each(function () {
3092				this._flatpickr.clear();
3093				update_input_count(this, 0);
3094			});
3095		});
3096		// clear the date total for calendars, before anything is done
3097		let scope_calendar_check = function(){
3098			search.find('.em-datepicker input.em-search-scope.flatpickr-input').each( function(){
3099				if( search.attr('data-view') == 'calendar' ){
3100					this.setAttribute('data-advanced-total-input', 0);
3101					this._flatpickr.input.disabled = true;
3102				}else{
3103					this._flatpickr.input.disabled = false;
3104					let qty = this._flatpickr.selectedDates.length > 0 ? 1 : 0;
3105					this.setAttribute('data-advanced-total-input', qty);
3106				}
3107			});
3108		};
3109		$(document).on('em_search_loaded', scope_calendar_check);
3110		scope_calendar_check();
3111
3112		// selectize advanced
3113		let search_advanced_selectize_change = function( selectize ){
3114			let qty = selectize.items.length;
3115			// handle 'all' default values
3116			if( qty == 1 && !selectize.items[0] ){
3117				qty = 0;
3118			}
3119			if ( selectize.$input.closest('.em-search-advanced').length === 0 ) {
3120				// sync advanced input field with same text
3121				let classSearch = '.' + selectize.$input.attr('class').replaceAll(' ', '.').trim();
3122				let advanced_search_input = search_advanced.find( classSearch );
3123				if ( advanced_search_input.length > 0 ) {
3124					// copy over values
3125					advanced_search_input[0].selectize.setValue( selectize.items );
3126					// recalculate totals from here
3127					search_advanced_selectize_change(advanced_search_input[0].selectize);
3128				}
3129			}
3130			update_input_count( selectize.$input, qty );
3131		};
3132
3133		search_advanced.find('select.em-selectize').each(function () {
3134			if( 'selectize' in this ) {
3135				this.selectize.on('change', function () {
3136					search_advanced_selectize_change(this);
3137				});
3138			}
3139		});
3140		search_advanced.on('calculate_totals', function(){
3141			$(this).find('select.em-selectize').each( function(){
3142				search_advanced_selectize_change(this.selectize);
3143			});
3144		});
3145		search_advanced.on('clear_search', function(){
3146			let clearSearch = function(){
3147				this.selectize.clear();
3148				this.selectize.refreshItems();
3149				this.selectize.refreshOptions(false);
3150				this.selectize.blur();
3151			};
3152			search_advanced.find('select.em-selectize').each( clearSearch );
3153			search.find('.em-search-main-bar select.em-selectize').each( clearSearch );
3154		});
3155
3156		// location-specific stuff for dropdowns (powered by selectize)
3157		let locations_selectize_load_complete = function(){
3158			if( 'selectize' in this ) {
3159				this.selectize.settings.placeholder = this.selectize.settings.original_placeholder;
3160				this.selectize.updatePlaceholder();
3161				// get options from select again
3162				let options = [];
3163				this.selectize.$input.find('option').each( function(){
3164					let value = this.value !== null ? this.value : this.innerHTML;
3165					options.push({ value : value, text: this.innerHTML});
3166				});
3167				this.selectize.addOption(options);
3168				this.selectize.refreshOptions(false);
3169			}
3170		};
3171		let locations_selectize_load_start = function(){
3172			if( 'selectize' in this ){
3173				this.selectize.clearOptions();
3174				if( !('original_placeholder' in this.selectize.settings) ) this.selectize.settings.original_placeholder = this.selectize.settings.placeholder;
3175				this.selectize.settings.placeholder = EM.txt_loading;
3176				this.selectize.updatePlaceholder();
3177			}
3178		};
3179		$('.em-search-advanced select[name=country], .em-search select[name=country]').on('change', function(){
3180			var el = $(this);
3181			let wrapper = el.closest('.em-search-location');
3182			wrapper.find('select[name=state]').html('<option value="">'+EM.txt_loading+'</option>');
3183			wrapper.find('select[name=region]').html('<option value="">'+EM.txt_loading+'</option>');
3184			wrapper.find('select[name=town]').html('<option value="">'+EM.txt_loading+'</option>');
3185			wrapper.find('select[name=state], select[name=region], select[name=town]').each( locations_selectize_load_start );
3186			if( el.val() != '' ){
3187				wrapper.find('.em-search-location-meta').slideDown();
3188				var data = {
3189					action : 'search_states',
3190					country : el.val(),
3191					return_html : true,
3192				};
3193				wrapper.find('select[name=state]').load( EM.ajaxurl, data, locations_selectize_load_complete );
3194				data.action = 'search_regions';
3195				wrapper.find('select[name=region]').load( EM.ajaxurl, data, locations_selectize_load_complete );
3196				data.action = 'search_towns';
3197				wrapper.find('select[name=town]').load( EM.ajaxurl, data, locations_selectize_load_complete );
3198			}else{
3199				wrapper.find('.em-search-location-meta').slideUp();
3200			}
3201		});
3202		$('.em-search-advanced select[name=region], .em-search select[name=region]').on('change', function(){
3203			var el = $(this);
3204			let wrapper = el.closest('.em-search-location');
3205			wrapper.find('select[name=state]').html('<option value="">'+EM.txt_loading+'</option>');
3206			wrapper.find('select[name=town]').html('<option value="">'+EM.txt_loading+'</option>');
3207			wrapper.find('select[name=state], select[name=town]').each( locations_selectize_load_start );
3208			var data = {
3209				action : 'search_states',
3210				region : el.val(),
3211				country : wrapper.find('select[name=country]').val(),
3212				return_html : true
3213			};
3214			wrapper.find('select[name=state]').load( EM.ajaxurl, data, locations_selectize_load_complete );
3215			data.action = 'search_towns';
3216			wrapper.find('select[name=town]').load( EM.ajaxurl, data, locations_selectize_load_complete );
3217		});
3218		$('.em-search-advanced select[name=state], .em-search select[name=state]').on('change', function(){
3219			var el = $(this);
3220			let wrapper = el.closest('.em-search-location');
3221			wrapper.find('select[name=town]').html('<option value="">'+EM.txt_loading+'</option>').each( locations_selectize_load_start );
3222			var data = {
3223				action : 'search_towns',
3224				state : el.val(),
3225				region : wrapper.find('select[name=region]').val(),
3226				country : wrapper.find('select[name=country]').val(),
3227				return_html : true
3228			};
3229			wrapper.find('select[name=town]').load( EM.ajaxurl, data, locations_selectize_load_complete );
3230		});
3231
3232		/*
3233		 *  Clear & Search Actions
3234		 */
3235		// handle clear link for advanced
3236		search_advanced.on( 'click', 'button[type="reset"]', function(){
3237			// clear text search advanced, run clear hook for other parts to hook into
3238			if( search.attr('data-advanced-total') == 0 ) return;
3239			// search text and geo search
3240			search_advanced.find('input.em-search-text, input.em-search-geo').val('').attr('data-advanced-total-input', null).trigger('change');
3241			// other implementations hook here and do what you need
3242			search.trigger('clear_search');
3243			search_advanced.trigger('clear_search');
3244			// remove counters, set data counters to 0, hide section and submit form without search settings
3245			update_search_totals(true); // in theory, this is 0 and removes everything
3246			if( search_advanced.hasClass('em-modal') ) {
3247				search_advanced_trigger_click();
3248			}
3249			search_advanced.append('<input name="clear_search" type="hidden" value="1">');
3250			search_advanced.find('button[type="submit"]').trigger('forceclick');
3251			update_clear_button_count();
3252		}).each( function(){
3253			search_advanced.trigger('calculate_totals');
3254			update_search_totals(true);
3255		});
3256		const on_update_trigger_count = function(e, applied = true){
3257			update_trigger_count( applied );
3258		};
3259		search.on('update_trigger_count', on_update_trigger_count);
3260		search_advanced.on('update_trigger_count', on_update_trigger_count);
3261
3262		// handle submission for advanced
3263		search_advanced.on( 'click forceclick', 'button[type="submit"]', function(e){
3264			e.preventDefault();
3265			if( this.classList.contains('disabled') && e.type !== 'forceclick' ) return false;
3266			// close attach back to search form
3267			if( search_advanced.hasClass('em-modal') ) {
3268				closeModal(search_advanced, function () {
3269					// submit for search
3270					search_form.submit();
3271				});
3272			}else{
3273				search_form.submit();
3274			}
3275			return false; // we handled it
3276		});
3277
3278		search.on('submit forcesubmit', '.em-search-form', function(e){
3279			if ( search.hasClass('no-ajax') ) {
3280				return true;
3281			}
3282			e.preventDefault();
3283			let form = $(this);
3284			let submit_buttons = form.find('button[type="submit"]');
3285			if( e.type !== 'forcesubmit' && submit_buttons.hasClass('disabled') ) return false;
3286			let wrapper = form.closest('.em-search');
3287			if( wrapper.hasClass('em-search-legacy') ){
3288				em_submit_legacy_search_form(form);
3289			}else{
3290				let view = $('#em-view-'+search_id);
3291				let view_type = form.find('[name="view"]:checked, [name="view"][type="hidden"], .em-search-view-option-hidden').val();
3292				if( Array.isArray(view_type) ) view_type = view_type.shift();
3293				// copy over custom view information, remove it further down
3294				let custom_view_data = view.find('#em-view-custom-data-search-'+search_id).clone();
3295				let custom_view_data_container = $('<div class="em-view-custom-data"></div>');
3296				custom_view_data.children().appendTo(custom_view_data_container);
3297				custom_view_data.remove();
3298				custom_view_data_container.appendTo(form);
3299				// add loading stuff
3300				view.append('<div class="em-loading"></div>');
3301				submit_buttons.each( function(){
3302					if( EM.txt_searching !== this.innerHTML ) {
3303						this.setAttribute('data-button-text', this.innerHTML);
3304						this.innerHTML = EM.txt_searching;
3305					}
3306				});
3307				var vars = form.serialize();
3308				$.ajax( EM.ajaxurl, {
3309					type : 'POST',
3310					dataType : 'html',
3311					data : vars,
3312					success : function(responseText){
3313						submit_buttons.each( function(){
3314							this.innerHTML = this.getAttribute('data-button-text');
3315						});
3316						view = EM_View_Updater( view, responseText );
3317						// update view definitions
3318						view.attr('data-view', view_type);
3319						search.attr('data-view', view_type);
3320						search_advanced.attr('data-view', view_type);
3321						jQuery(document).triggerHandler('em_view_loaded_'+view_type, [view, form, e]);
3322						jQuery(document).triggerHandler('em_search_loaded', [view, form, e]); // ajax has loaded new results
3323						jQuery(document).triggerHandler('em_search_result', [vars, view, e]); // legacy for backcompat, use the above
3324						wrapper.find('.count.tentative').removeClass('tentative');
3325						// deactivate submit button until changes are made again
3326						submit_buttons.addClass('disabled').attr('aria-disabled', 'true');
3327						// update search totals
3328						update_search_totals(true);
3329						search.attr('data-advanced-previous-total', search.attr('data-advanced-total')); // so we know if filters were used in previous search
3330						update_submit_buttons(false);
3331						custom_view_data_container.remove(); // remove data so it's reloaded again later
3332						search.find('input[name="clear_search"]').remove();
3333					}
3334				});
3335			}
3336			return false;
3337		});
3338
3339		// observe resizing
3340		EM_ResizeObserver( EM.search.breakpoints, [search[0]]);
3341	});
3342
3343	// handle external triggers, e.g. a calendar shortcut for a hidden search form
3344	$(document).on('click', '.em-search-advanced-trigger[data-search-advanced-id], .em-search-advanced-trigger[data-parent-trigger]', function(){
3345		if( this.getAttribute('data-search-advanced-id') ){
3346			// trigger the search form by parent
3347			let search_advanced_form = document.getElementById( this.getAttribute('data-search-advanced-id') );
3348			if( search_advanced_form ){
3349				let search_form = search_advanced_form.closest('form.em-search-form');
3350				if( search_form ){
3351					search_form.dispatchEvent( new CustomEvent('search_advanced_trigger') );
3352					return;
3353				}
3354			}
3355		} else if( this.getAttribute('data-parent-trigger') ) {
3356			let trigger = document.getElementById(this.getAttribute('data-parent-trigger'));
3357			if ( trigger ) {
3358				trigger.click();
3359				return;
3360			}
3361		}
3362		console.log('Cannot locate a valid advanced search form trigger for %o', this);
3363	});
3364
3365	$(document).on('click', '.em-view-container .em-ajax.em-pagination a.page-numbers', function(e){
3366		let a = $(this);
3367		let view = a.closest('.em-view-container');
3368		let href = a.attr('href');
3369		//add data-em-ajax att if it exists
3370		let data = a.closest('.em-pagination').attr('data-em-ajax');
3371		if( data ){
3372			href += href.includes('?') ? '&' : '?';
3373			href += data;
3374		}
3375		// build querystring from url
3376		let url_params = new URL(href, window.location.origin).searchParams;
3377		if( view.attr('data-view') ) {
3378			url_params.set('view', view.attr('data-view'));
3379		}
3380		// start ajax
3381		view.append('<div class="loading" id="em-loading"></div>');
3382		$.ajax( EM.ajaxurl, {
3383			type : 'POST',
3384			dataType : 'html',
3385			data : url_params.toString(),
3386			success : function(responseText) {
3387				view = EM_View_Updater( view, responseText );
3388				view.find('.em-pagination').each( function(){
3389					paginationObserver.observe(this);
3390				});
3391				jQuery(document).triggerHandler('em_page_loaded', [view]);
3392				view[0].scrollIntoView({ behavior: "smooth" });
3393			}
3394		});
3395		e.preventDefault();
3396		return false;
3397	});
3398
3399	const paginationObserver = new ResizeObserver( function( entries ){
3400		for (let entry of entries) {
3401			let el = entry.target;
3402			if( !el.classList.contains('observing') ) {
3403				el.classList.add('observing'); // prevent endless loop on resizing within this check
3404				// check if any pagination parts are overflowing
3405				let overflowing = false;
3406				el.classList.remove('overflowing');
3407				for ( const item of el.querySelectorAll('.not-current')) {
3408					if( item.scrollHeight > item.clientHeight || item.scrollWidth > item.clientWidth ){
3409						overflowing = true;
3410						break; // break if one has overflown
3411					}
3412				};
3413				// add or remove overflow classes
3414				if( overflowing ){
3415					el.classList.add('overflowing')
3416				}
3417				el.classList.remove('observing');
3418			}
3419		}
3420	});
3421	$('.em-pagination').each( function(){
3422		paginationObserver.observe(this);
3423	});
3424
3425	/* START Legacy */
3426	// deprecated - hide/show the advanced search advanced link - relevant for old template overrides
3427	$(document).on('click change', '.em-search-legacy .em-toggle', function(e){
3428		e.preventDefault();
3429		//show or hide advanced search, hidden by default
3430		var el = $(this);
3431		var rel = el.attr('rel').split(':');
3432		if( el.hasClass('show-search') ){
3433			if( rel.length > 1 ){ el.closest(rel[1]).find(rel[0]).slideUp(); }
3434			else{ $(rel[0]).slideUp(); }
3435			el.find('.show, .show-advanced').show();
3436			el.find('.hide, .hide-advanced').hide();
3437			el.removeClass('show-search');
3438		}else{
3439			if( rel.length > 1 ){ el.closest(rel[1]).find(rel[0]).slideDown(); }
3440			else{ $(rel[0]).slideDown(); }
3441			el.find('.show, .show-advanced').hide();
3442			el.find('.hide, .hide-advanced').show();
3443			el.addClass('show-search');
3444		}
3445	});
3446	// handle search form submission
3447	let em_submit_legacy_search_form = function( form ){
3448		if( this.em_search && this.em_search.value == EM.txt_search){ this.em_search.value = ''; }
3449		var results_wrapper = form.closest('.em-search-wrapper').find('.em-search-ajax');
3450		if( results_wrapper.length == 0 ) results_wrapper = $('.em-search-ajax');
3451		if( results_wrapper.length > 0 ){
3452			results_wrapper.append('<div class="loading" id="em-loading"></div>');
3453			var submitButton = form.find('.em-search-submit button');
3454			submitButton.attr('data-button-text', submitButton.val()).val(EM.txt_searching);
3455			var img = submitButton.children('img');
3456			if( img.length > 0 ) img.attr('src', img.attr('src').replace('search-mag.png', 'search-loading.gif'));
3457			var vars = form.serialize();
3458			$.ajax( EM.ajaxurl, {
3459				type : 'POST',
3460				dataType : 'html',
3461				data : vars,
3462				success : function(responseText){
3463					submitButton.val(submitButton.attr('data-button-text'));
3464					if( img.length > 0 ) img.attr('src', img.attr('src').replace('search-loading.gif', 'search-mag.png'));
3465					results_wrapper.replaceWith(responseText);
3466					if( form.find('input[name=em_search]').val() == '' ){ form.find('input[name=em_search]').val(EM.txt_search); }
3467					//reload results_wrapper
3468					results_wrapper = form.closest('.em-search-wrapper').find('.em-search-ajax');
3469					if( results_wrapper.length == 0 ) results_wrapper = $('.em-search-ajax');
3470					jQuery(document).triggerHandler('em_search_ajax', [vars, results_wrapper, e]); //ajax has loaded new results
3471				}
3472			});
3473			e.preventDefault();
3474			return false;
3475		}
3476	};
3477	if( $('.em-search-ajax').length > 0 ){
3478		$(document).on('click', '.em-search-ajax a.page-numbers', function(e){
3479			var a = $(this);
3480			var data = a.closest('.em-pagination').attr('data-em-ajax');
3481			var wrapper = a.closest('.em-search-ajax');
3482			var wrapper_parent = wrapper.parent();
3483			var qvars = a.attr('href').split('?');
3484			var vars = qvars[1];
3485			//add data-em-ajax att if it exists
3486			if( data != '' ){
3487				vars = vars != '' ? vars+'&'+data : data;
3488			}
3489			vars += '&legacy=1';
3490			wrapper.append('<div class="loading" id="em-loading"></div>');
3491			$.ajax( EM.ajaxurl, {
3492				type : 'POST',
3493				dataType : 'html',
3494				data : vars,
3495				success : function(responseText) {
3496					wrapper.replaceWith(responseText);
3497					wrapper = wrapper_parent.find('.em-search-ajax');
3498					jQuery(document).triggerHandler('em_search_ajax', [vars, wrapper, e]); //ajax has loaded new results
3499				}
3500			});
3501			e.preventDefault();
3502			return false;
3503		});
3504	}
3505	/* END Legacy */
3506});
3507
3508/*
3509* CALENDAR
3510*/
3511jQuery(document).ready( function($){
3512
3513	const em_calendar_init = function( calendar ){
3514		calendar = $(calendar);
3515		if( !calendar.attr('id') || !calendar.attr('id').match(/^em-calendar-[0-9]+$/) ){
3516			calendar.attr('id', 'em-calendar-' + Math.floor(Math.random() * 10000)); // retroactively add id to old templates
3517		}
3518		calendar.find('a').off("click");
3519		calendar.on('click', 'a.em-calnav, a.em-calnav-today', function(e){
3520			e.preventDefault();
3521			const el = $(this);
3522			if( el.attr('href') === '') return; // do nothing if disabled or no link provided
3523			el.closest('.em-calendar').prepend('<div class="loading" id="em-loading"></div>');
3524			let url = el.attr('href');
3525			const view_id = el.closest('[data-view-id]').data('view-id');
3526			const custom_data = $('form#em-view-custom-data-calendar-'+ view_id);
3527			let form_data = new FormData();
3528			if( custom_data.length > 0 ){
3529				form_data = new FormData(custom_data[0]);
3530				let $URL = new URL(url, window.location.origin);
3531				let url_params = $URL.searchParams;
3532				for (const [key, value] of url_params.entries()) {
3533					if( key === 'mo' ) {
3534						form_data.set('month', value);
3535					} else if ( key === 'yr' ) {
3536						form_data.set('year', value);
3537					} else {
3538						form_data.set(key, value);
3539					}
3540				}
3541				// remove mo and yr from URL
3542				$URL.searchParams.delete('mo');
3543				$URL.searchParams.delete('yr');
3544				url = $URL.toString();
3545			}
3546			if ( calendar.attr('data-timezone') ) {
3547				form_data.set('calendar_timezone', calendar.attr('data-timezone') );
3548			}
3549			form_data.set('id', view_id);
3550			form_data.set('ajaxCalendar', 1); // AJAX trigger
3551			form_data.set('em_ajax', 1); // AJAX trigger
3552			// check advanced trigger
3553			if( calendar.hasClass('with-advanced') ){
3554				form_data.set('has_advanced_trigger', 1);
3555			}
3556			$.ajax({
3557				url: url,
3558				data: form_data,
3559				processData: false,
3560				contentType: false,
3561				method: 'POST',
3562				success: function( data ){
3563					let view = EM_View_Updater( calendar, data );
3564					if( view.hasClass('em-view-container') ){
3565						calendar = view.find('.em-calendar');
3566					}else{
3567						calendar = view;
3568					}
3569					calendar[0].dispatchEvent( new CustomEvent( 'em_calendar_load', { bubbles: true } ) );
3570				},
3571				dataType: 'html'
3572			});
3573		} );
3574		calendar[0].addEventListener('reload', () => {
3575			calendar_trigger_ajax( calendar, calendar.attr('data-year'), calendar.attr('data-month') );
3576		});
3577		let calendar_trigger_ajax = function( calendar, year, month ){
3578			let link = calendar.find('.em-calnav-next');
3579			let url = new URL(link.attr('href'), window.location.origin);
3580			url.searchParams.set('mo', month);
3581			url.searchParams.set('yr', year);
3582			link.attr('href', url.toString()).trigger('click');
3583		};
3584		let calendar_resize_monthpicker = function( instance, text ){
3585			let span = $('<span class="marker">'+ text +'</span>');
3586			span.insertAfter(instance);
3587			let width = span.width() + 40;
3588			span.remove();
3589			instance.style.setProperty('width', width+'px', 'important');
3590		}
3591		let calendar_month_init = function(){
3592			let month_form = calendar.find('.month form');
3593			calendar.find('.event-style-pill .em-cal-event').on('click', function( e ){
3594				e.preventDefault();
3595				if( !(calendar.hasClass('preview-tooltips') && calendar.data('preview-tooltips-trigger')) && !(calendar.hasClass('preview-modal')) ) {
3596					let link = this.getAttribute('data-event-url');
3597					if (link !== null) {
3598						window.location.href = link;
3599					}
3600				}
3601				// select this date, all others no
3602				e.target.closest('.em-cal-body').querySelectorAll('.em-cal-day-date').forEach( calDate => calDate.classList.remove('selected') );
3603				e.target.closest('.em-cal-day').querySelector('.em-cal-day-date')?.classList.add('selected');
3604			});
3605			if( month_form.length > 0 ){
3606				month_form.find('input[type="submit"]').hide();
3607				let select = $('<select style="display:none;visibility:hidden;"></select>').appendTo(month_form);
3608				let option = $('<option></option>').appendTo(select);
3609				let current_datetime = calendar.find('select[name="month"]').val() + calendar.find('select[name="year"]').val();
3610				let month = calendar.find('select[name="month"]');
3611				let year = calendar.find('select[name="year"]');
3612				let monthpicker = calendar.find('.em-month-picker');
3613				let monthpicker_value = monthpicker.val() + '-02'; // store this for further down before we change the value below
3614				let month_value = monthpicker.data('month-value');
3615				monthpicker.prop('type', 'text').prop('value', month_value);
3616				calendar_resize_monthpicker( monthpicker[0], month_value );
3617				let monthpicker_wrapper = $('#em-flatpickr');
3618				if( monthpicker_wrapper.length === 0 ) {
3619					monthpicker_wrapper = $('<div class="em pixelbones" id="em-flatpickr"></div>').appendTo('body');
3620				}
3621				let minDate = null;
3622				if( calendar.data('scope') === 'future' ){
3623					minDate = new Date();
3624					minDate.setMonth(minDate.getMonth()-1);
3625				}
3626				// locale
3627				if( 'locale' in EM.datepicker ){
3628					flatpickr.localize(flatpickr.l10ns[EM.datepicker.locale]);
3629					flatpickr.l10ns.default.firstDayOfWeek = EM.firstDay;
3630				}
3631				let fp = monthpicker.flatpickr({
3632					appendTo : monthpicker_wrapper[0],
3633					dateFormat : EM?.calendar?.month_format,
3634					minDate : minDate,
3635					disableMobile: "true",
3636					plugins: [
3637						new monthSelectPlugin({
3638							shorthand: true,
3639							dateFormat: EM?.calendar?.month_format || 'F Y',
3640							altFormat: EM?.calendar?.month_format || 'F Y',
3641						})
3642					],
3643					onChange: function(selectedDates, dateStr, instance) {
3644						calendar_resize_monthpicker( instance.input, dateStr );
3645						calendar_trigger_ajax( calendar, selectedDates[0].getFullYear(), selectedDates[0].getMonth()+1);
3646					},
3647				});
3648				// this bit fixes issues if the supplied text value has a mismatch with the real text value due to localization differences between WP and flatpickr
3649				fp.setDate( new Date( monthpicker_value ) );
3650				// add classes to month picker
3651				monthpicker.addClass('select-toggle');
3652			}
3653			if( calendar.hasClass('preview-tooltips') ){
3654				let tooltip_vars = {
3655					theme : 'light-border',
3656					allowHTML : true,
3657					interactive : true,
3658					trigger : 'mouseenter focus click',
3659					content(reference) {
3660						return document.createElement('div');
3661					},
3662					onShow( instance ){
3663						const id = instance.reference.getAttribute('data-event-id');
3664						const template = calendar.find('section.em-cal-events-content .em-cal-event-content[data-event-id="'+id+'"]');
3665						instance.props.content.append(template.first().clone()[0]);
3666					},
3667					onHide( instance ){
3668						instance.props.content.innerHTML = '';
3669					}
3670				};
3671				if( calendar.data('preview-tooltips-trigger') ) {
3672					tooltip_vars.trigger = calendar.data('preview-tooltips-trigger');
3673				}
3674				$(document).trigger('em-tippy-cal-event-vars',[tooltip_vars]);
3675				tippy(calendar.find('.em-cal-event').toArray(), tooltip_vars);
3676			}else if( calendar.hasClass('preview-modal') ){
3677				// Modal
3678				calendar.find('.em-cal-event').on('click', function( e ){
3679					const id = this.getAttribute('data-event-id');
3680					const modal = calendar.find('section.em-cal-events-content .em-cal-event-content[data-event-id="'+id+'"]');
3681					modal.attr('data-calendar-id', calendar.attr('id'));
3682					openModal(modal);
3683					// select this date, all others no
3684					e.target.closest('.em-cal-body').querySelectorAll('.em-cal-day-date').forEach( calDate => calDate.classList.remove('selected') );
3685					e.target.closest('.em-cal-day').querySelector('.em-cal-day-date')?.classList.add('selected');
3686				});
3687			}
3688			// responsive mobile view for date clicks
3689			if( calendar.hasClass('responsive-dateclick-modal') ){
3690				calendar.find('.eventful .em-cal-day-date, .eventful-post .em-cal-day-date, .eventful-pre .em-cal-day-date').on('click', function( e ){
3691					//if( calendar.hasClass('size-small') || calendar.hasClass('size-medium') ){
3692					e.preventDefault();
3693					const id = this.getAttribute('data-timestamp');
3694					const modal = calendar.find('.em-cal-date-content[data-calendar-date="'+id+'"], .em-cal-date-content[data-timestamp="'+id+'"]');
3695					modal.attr('data-calendar-id', calendar.attr('id'));
3696					openModal(modal);
3697					// select this date, all others no
3698					e.target.closest('.em-cal-body').querySelectorAll('.em-cal-day-date').forEach( calDate => calDate.classList.remove('selected') );
3699					e.target.closest('.em-cal-day').querySelector('.em-cal-day-date')?.classList.add('selected');
3700				});
3701			}
3702			// observe resizing if not fixed
3703			if( !calendar.hasClass('size-fixed') ){
3704				EM_ResizeObserver( EM.calendar.breakpoints, [calendar[0], calendar[0]]);
3705			}
3706			// even aspect, because aspect ratio can screw up widths vs row template heights
3707			let calendar_body = calendar.find('.em-cal-body');
3708			if( calendar_body.hasClass('even-aspect') ) {
3709				let ro_function = function (el) {
3710					let width = el.firstElementChild.getBoundingClientRect().width;
3711					if (width > 0) {
3712						el.style.setProperty('--grid-auto-rows', 'minmax(' + width + 'px, auto)');
3713					}
3714				}
3715				let ro = new ResizeObserver(function (entries) {
3716					for (let entry of entries) {
3717						ro_function(entry.target);
3718					}
3719				});
3720				ro.observe(calendar_body[0]);
3721				ro_function(calendar_body[0]);
3722			}
3723
3724			// figure out colors
3725			calendar.find('.date-day-colors').each( function(){
3726				let colors = JSON.parse(this.getAttribute('data-colors'));
3727				let day = $(this).siblings('.em-cal-day-date.colored');
3728				let sides = {
3729					1 : { 1 : '--date-border-color', 'class' : 'one' },
3730					2 : { 1 : '--date-border-color-top', 2 : '--date-border-color-bottom', 'class' : 'two' },
3731					3 : { 1 : '--date-border-color-top', 2 : '--date-border-color-right', 3 : '--date-border-color-bottom', 'class' : 'three' },
3732					4 : { 1 : '--date-border-color-top', 2 : '--date-border-color-right', 3 : '--date-border-color-bottom', 4 : '--date-border-color-left', 'class' : 'four' },
3733				};
3734				for (let i = 0; i < colors.length; i += 4) {
3735					const ring_colors = colors.slice(i, i + 4);
3736					// add a ring
3737					let outer_ring = day.children().first();
3738					let new_ring = $('<div class="ring"></div>').prependTo(day);
3739					outer_ring.appendTo(new_ring);
3740					new_ring.addClass( sides[ring_colors.length].class );
3741					for ( let it = 0; it < ring_colors.length; it++ ){
3742						new_ring.css(sides[ring_colors.length][it+1], ring_colors[it]);
3743					}
3744				}
3745			});
3746
3747			if( calendar.hasClass('with-advanced') ){
3748				const trigger = calendar.find('.em-search-advanced-trigger');
3749				const search_advanced = $('#'+trigger.attr('data-search-advanced-id'));
3750				search_advanced.triggerHandler('update_trigger_count');
3751			}
3752		}
3753		calendar_month_init();
3754		$(document).triggerHandler('em_calendar_loaded', [calendar]);
3755	};
3756	$('.em-calendar').each( function(){
3757		let calendar = $(this);
3758		em_calendar_init( calendar );
3759	});
3760	$(document).on('em_calendar_load', '.em-calendar', function(){
3761		em_calendar_init( this );
3762	});
3763	$(document).on('em_view_loaded_calendar', function( e, view, form ){
3764		let calendar;
3765		if( view.hasClass('em-calendar') ){
3766			calendar = view;
3767		}else {
3768			calendar = view.find('.em-calendar').first();
3769		}
3770		em_calendar_init( calendar );
3771	});
3772});
3773
3774let EM_View_Updater = function( element, html ){
3775	let content = jQuery(html);
3776	let view = element.hasClass('em-view-container') ? element : element.parent('.em-view-container');
3777	if( view.length > 0 ){
3778		if( content.hasClass('em-view-container') ){
3779			view.replaceWith(content);
3780			view = content;
3781		}else{
3782			view.empty().append(content);
3783		}
3784	}else{
3785		// create a view if possible
3786		if( content.hasClass('em-view-container') ){
3787			element.replaceWith(content);
3788			view = content;
3789		}else if( content.attr('data-view-id') ){
3790			let view = jQuery('<div class="em em-view-container"></div>');
3791			let view_id = content.attr('data-view-id');
3792			view.attr('data-view-id', view_id);
3793			view.attr('id', 'em-view-'+ view_id);
3794			view.attr('data-view-type', content.attr('data-view-type'));
3795			view.append(content);
3796			element.replaceWith(view);
3797		}
3798	}
3799	em_setup_ui_elements( view[0] );
3800	return view;
3801}
3802
3803/**
3804 * Resize watcher for EM elements. Supply an object (localized array) of name > breakpoint, in order of least to largest and it'll add size-{name} class name according to the breakpoint.
3805 * An object item with value false will represent any screensize, i.e. it should be the last value when all breakpoints aren't met.
3806 * @param breakpoints
3807 * @param elements
3808 * @constructor
3809 */
3810let EM_ResizeObserver = function( breakpoints, elements ){
3811	const ro = new ResizeObserver( function( entries ){
3812		for (let entry of entries) {
3813			let el = entry.target;
3814			if( !el.classList.contains('size-fixed') ) {
3815				for (const [name, breakpoint] of Object.entries(breakpoints)) {
3816					if (el.offsetWidth <= breakpoint || breakpoint === false) {
3817						for (let breakpoint_name of Object.keys(breakpoints)) {
3818							if (breakpoint_name !== name) el.classList.remove('size-' + breakpoint_name);
3819						}
3820						// add class and trigger event only once
3821						if(	!el.classList.contains('size-' + name) ) {
3822							el.classList.add('size-' + name);
3823							el.dispatchEvent( new CustomEvent('em_resize') );
3824						}
3825						break;
3826					}
3827				}
3828			}
3829		}
3830	});
3831	elements.forEach( function( el ){
3832		if( typeof el !== 'undefined' ){
3833			ro.observe(el);
3834		}
3835	});
3836	return ro;
3837};
3838
3839// event list and event page (inc. some extra booking form logic) - todo/cleanup
3840jQuery(document).ready( function($){
3841	// Events List
3842	let breakpoints = {
3843		'small' : 600,
3844		'large' : false,
3845	}
3846	const events_ro = EM_ResizeObserver( breakpoints, $('.em-list').toArray() );
3847	$(document).on('em_page_loaded em_view_loaded_list em_view_loaded_list-grouped em_view_loaded_grid', function( e, view ){
3848		let new_elements = view.find('.em-list').each( function(){
3849			if( !this.classList.contains('size-fixed') ){
3850				events_ro.observe( this );
3851			}
3852		});
3853	});
3854
3855	$(document).on('click', '.em-grid .em-item[data-href]', function(e){
3856		if( e.target.type !== 'a' ){
3857			window.location.href = this.getAttribute('data-href');
3858		}
3859	});
3860
3861	// Single event area
3862	breakpoints = {
3863		'small' : 600,
3864		'medium' : 900,
3865		'large' : false,
3866	}
3867	const event_ro = EM_ResizeObserver( breakpoints, $('.em-item-single').toArray() );
3868	$(document).on('em_view_loaded', function( e, view ){
3869		let new_elements = view.find('.em-event-single').each( function(){
3870			if( !this.classList.contains('size-fixed') ){
3871				event_ro.observe( this );
3872			}
3873		});
3874	});
3875	// booking form area (WIP)
3876	$(document).on("click", ".em-event-booking-form .em-login-trigger a", function( e ){
3877		e.preventDefault();
3878		var parent = $(this).closest('.em-event-booking-form');
3879		parent.find('.em-login-trigger').hide();
3880		parent.find('.em-login-content').fadeIn();
3881		let login_form = parent.find('.em-login');
3882		login_form[0].scrollIntoView({
3883			behavior: 'smooth'
3884		});
3885		login_form.first().find('input[name="log"]').focus();
3886
3887	});
3888	$(document).on("click", ".em-event-booking-form .em-login-cancel", function( e ){
3889		e.preventDefault();
3890		let parent = $(this).closest('.em-event-booking-form');
3891		parent.find('.em-login-content').hide();
3892		parent.find('.em-login-trigger').show();
3893	});
3894	EM_ResizeObserver( {'small': 500, 'large' : false}, $('.em-login').toArray());
3895
3896});
3897
3898// handle generic ajax submission forms vanilla style
3899document.addEventListener('DOMContentLoaded', function () {
3900	document.querySelectorAll('form.em-ajax-form').forEach( function(el){
3901		el.addEventListener('submit', function(e){
3902			e.preventDefault();
3903			let form = e.currentTarget;
3904			let formData =  new FormData(form);
3905			let button = form.querySelector('button[type="submit"]');
3906			let loader;
3907
3908			if( form.classList.contains('no-overlay-spinner') ){
3909				form.classList.add('loading');
3910			}else{
3911				let loader = document.createElement('div');
3912				loader.id = 'em-loading';
3913				form.append(loader);
3914			}
3915
3916			var request = new XMLHttpRequest();
3917			if( form.getAttribute('data-api-url') ){
3918				request.open('POST', form.getAttribute('data-api-url'), true);
3919				request.setRequestHeader('X-WP-Nonce', EM.api_nonce);
3920			}else{
3921				request.open('POST', EM.ajaxurl, true);
3922			}
3923
3924			request.onload = function() {
3925				if( loader ) loader.remove();
3926				if (this.status >= 200 && this.status < 400) {
3927					// Success!
3928					try {
3929						let data = JSON.parse(this.response);
3930						let notice;
3931						if( !form.classList.contains('no-inline-notice') ){
3932							notice = form.querySelector('.em-notice');
3933							if( !notice ){
3934								notice = document.createElement('div');
3935								form.prepend(notice);
3936								if( formData.get('action') ){
3937									form.dispatchEvent( new CustomEvent( 'em_ajax_form_success_' + formData.get('action'), {
3938										detail : {
3939											form : form,
3940											notice : notice,
3941											response : data,
3942										}
3943									}) );
3944								}
3945							}
3946							notice.innerHTML = '';
3947							notice.setAttribute('class', 'em-notice');
3948						}
3949						if( data.result ){
3950							if( !form.classList.contains('no-inline-notice') ){
3951								notice.classList.add('em-notice-success');
3952								notice.innerHTML = data.message;
3953								form.replaceWith(notice);
3954							}else{
3955								form.classList.add('load-successful');
3956								form.classList.remove('loading');
3957								if( data.message ){
3958									EM_Alert(data.message);
3959								}
3960							}
3961						}else{
3962							if( !form.classList.contains('no-inline-notice') ){
3963								notice.classList.add('em-notice-error');
3964								notice.innerHTML = data.errors;
3965							}else{
3966								EM_Alert(data.errors);
3967							}
3968						}
3969					} catch(e) {
3970						alert( 'Error Encountered : ' + e);
3971					}
3972				} else {
3973					alert('Error encountered... please see debug logs or contact support.');
3974				}
3975				form.classList.remove('loading');
3976			};
3977
3978			request.onerror = function() {
3979				alert('Connection error encountered... please see debug logs or contact support.');
3980			};
3981
3982			request.send( formData );
3983			return false;
3984		});
3985	});
3986});
3987
3988// phone numbers
3989let em_setup_phone_inputs = function( container ){};
3990let em_unsetup_phone_inputs = function( container ){};
3991if ( EM.phone ) {
3992
3993	let getCountry = function() {
3994		var timezones = {
3995			"Africa/Abidjan": { c : ["CI", "BF", "GH", "GM", "GN", "ML", "MR", "SH", "SL", "SN", "TG"] },
3996			"Africa/Accra": { c : ["GH"] },
3997			"Africa/Addis_Ababa": { c : ["ET"] },
3998			"Africa/Algiers": { c : ["DZ"] },
3999			"Africa/Asmara": { c : ["ER"] },
4000			"Africa/Asmera": { c : ["ER"] },
4001			"Africa/Bamako": { c : ["ML"] },
4002			"Africa/Bangui": { c : ["CF"] },
4003			"Africa/Banjul": { c : ["GM"] },
4004			"Africa/Bissau": { c : ["GW"] },
4005			"Africa/Blantyre": { c : ["MW"] },
4006			"Africa/Brazzaville": { c : ["CG"] },
4007			"Africa/Bujumbura": { c : ["BI"] },
4008			"Africa/Cairo": { c : ["EG"] },
4009			"Africa/Casablanca": { c : ["MA"] },
4010			"Africa/Ceuta": { c : ["ES"] },
4011			"Africa/Conakry": { c : ["GN"] },
4012			"Africa/Dakar": { c : ["SN"] },
4013			"Africa/Dar_es_Salaam": { c : ["TZ"] },
4014			"Africa/Djibouti": { c : ["DJ"] },
4015			"Africa/Douala": { c : ["CM"] },
4016			"Africa/El_Aaiun": { c : ["EH"] },
4017			"Africa/Freetown": { c : ["SL"] },
4018			"Africa/Gaborone": { c : ["BW"] },
4019			"Africa/Harare": { c : ["ZW"] },
4020			"Africa/Johannesburg": { c : ["ZA", "LS", "SZ"] },
4021			"Africa/Juba": { c : ["SS"] },
4022			"Africa/Kampala": { c : ["UG"] },
4023			"Africa/Khartoum": { c : ["SD"] },
4024			"Africa/Kigali": { c : ["RW"] },
4025			"Africa/Kinshasa": { c : ["CD"] },
4026			"Africa/Lagos": { c : ["NG", "AO", "BJ", "CD", "CF", "CG", "CM", "GA", "GQ", "NE"] },
4027			"Africa/Libreville": { c : ["GA"] },
4028			"Africa/Lome": { c : ["TG"] },
4029			"Africa/Luanda": { c : ["AO"] },
4030			"Africa/Lubumbashi": { c : ["CD"] },
4031			"Africa/Lusaka": { c : ["ZM"] },
4032			"Africa/Malabo": { c : ["GQ"] },
4033			"Africa/Maputo": { c : ["MZ", "BI", "BW", "CD", "MW", "RW", "ZM", "ZW"] },
4034			"Africa/Maseru": { c : ["LS"] },
4035			"Africa/Mbabane": { c : ["SZ"] },
4036			"Africa/Mogadishu": { c : ["SO"] },
4037			"Africa/Monrovia": { c : ["LR"] },
4038			"Africa/Nairobi": { c : ["KE", "DJ", "ER", "ET", "KM", "MG", "SO", "TZ", "UG", "YT"] },
4039			"Africa/Ndjamena": { c : ["TD"] },
4040			"Africa/Niamey": { c : ["NE"] },
4041			"Africa/Nouakchott": { c : ["MR"] },
4042			"Africa/Ouagadougou": { c : ["BF"] },
4043			"Africa/Porto-Novo": { c : ["BJ"] },
4044			"Africa/Sao_Tome": { c : ["ST"] },
4045			"Africa/Timbuktu": { c : ["ML"] },
4046			"Africa/Tripoli": { c : ["LY"] },
4047			"Africa/Tunis": { c : ["TN"] },
4048			"Africa/Windhoek": { c : ["NA"] },
4049			"America/Adak": { c : ["US"] },
4050			"America/Anchorage": { c : ["US"] },
4051			"America/Anguilla": { c : ["AI"] },
4052			"America/Antigua": { c : ["AG"] },
4053			"America/Araguaina": { c : ["BR"] },
4054			"America/Argentina/Buenos_Aires": { c : ["AR"] },
4055			"America/Argentina/Catamarca": { c : ["AR"] },
4056			"America/Argentina/ComodRivadavia": { c : ["AR"] },
4057			"America/Argentina/Cordoba": { c : ["AR"] },
4058			"America/Argentina/Jujuy": { c : ["AR"] },
4059			"America/Argentina/La_Rioja": { c : ["AR"] },
4060			"America/Argentina/Mendoza": { c : ["AR"] },
4061			"America/Argentina/Rio_Gallegos": { c : ["AR"] },
4062			"America/Argentina/Salta": { c : ["AR"] },
4063			"America/Argentina/San_Juan": { c : ["AR"] },
4064			"America/Argentina/San_Luis": { c : ["AR"] },
4065			"America/Argentina/Tucuman": { c : ["AR"] },
4066			"America/Argentina/Ushuaia": { c : ["AR"] },
4067			"America/Aruba": { c : ["AW"] },
4068			"America/Asuncion": { c : ["PY"] },
4069			"America/Atikokan": { c : ["CA"] },
4070			"America/Atka": {},
4071			"America/Bahia": { c : ["BR"] },
4072			"America/Bahia_Banderas": { c : ["MX"] },
4073			"America/Barbados": { c : ["BB"] },
4074			"America/Belem": { c : ["BR"] },
4075			"America/Belize": { c : ["BZ"] },
4076			"America/Blanc-Sablon": { c : ["CA"] },
4077			"America/Boa_Vista": { c : ["BR"] },
4078			"America/Bogota": { c : ["CO"] },
4079			"America/Boise": { c : ["US"] },
4080			"America/Buenos_Aires": { c : ["AR"] },
4081			"America/Cambridge_Bay": { c : ["CA"] },
4082			"America/Campo_Grande": { c : ["BR"] },
4083			"America/Cancun": { c : ["MX"] },
4084			"America/Caracas": { c : ["VE"] },
4085			"America/Catamarca": {},
4086			"America/Cayenne": { c : ["GF"] },
4087			"America/Cayman": { c : ["KY"] },
4088			"America/Chicago": { c : ["US"] },
4089			"America/Chihuahua": { c : ["MX"] },
4090			"America/Coral_Harbour": { c : ["CA"] },
4091			"America/Cordoba": { c: ['AR'] },
4092			"America/Costa_Rica": { c : ["CR"] },
4093			"America/Creston": { c : ["CA"] },
4094			"America/Cuiaba": { c : ["BR"] },
4095			"America/Curacao": { c : ["CW"] },
4096			"America/Danmarkshavn": { c : ["GL"] },
4097			"America/Dawson": { c : ["CA"] },
4098			"America/Dawson_Creek": { c : ["CA"] },
4099			"America/Denver": { c : ["US"] },
4100			"America/Detroit": { c : ["US"] },
4101			"America/Dominica": { c : ["DM"] },
4102			"America/Edmonton": { c : ["CA"] },
4103			"America/Eirunepe": { c : ["BR"] },
4104			"America/El_Salvador": { c : ["SV"] },
4105			"America/Ensenada": {},
4106			"America/Fort_Nelson": { c : ["CA"] },
4107			"America/Fort_Wayne": {},
4108			"America/Fortaleza": { c : ["BR"] },
4109			"America/Glace_Bay": { c : ["CA"] },
4110			"America/Godthab": {},
4111			"America/Goose_Bay": { c : ["CA"] },
4112			"America/Grand_Turk": { c : ["TC"] },
4113			"America/Grenada": { c : ["GD"] },
4114			"America/Guadeloupe": { c : ["GP"] },
4115			"America/Guatemala": { c : ["GT"] },
4116			"America/Guayaquil": { c : ["EC"] },
4117			"America/Guyana": { c : ["GY"] },
4118			"America/Halifax": { c : ["CA"] },
4119			"America/Havana": { c : ["CU"] },
4120			"America/Hermosillo": { c : ["MX"] },
4121			"America/Indiana/Indianapolis": { c : ["US"] },
4122			"America/Indiana/Knox": { c : ["US"] },
4123			"America/Indiana/Marengo": { c : ["US"] },
4124			"America/Indiana/Petersburg": { c : ["US"] },
4125			"America/Indiana/Tell_City": { c : ["US"] },
4126			"America/Indiana/Vevay": { c : ["US"] },
4127			"America/Indiana/Vincennes": { c : ["US"] },
4128			"America/Indiana/Winamac": { c : ["US"] },
4129			"America/Indianapolis": {},
4130			"America/Inuvik": { c : ["CA"] },
4131			"America/Iqaluit": { c : ["CA"] },
4132			"America/Jamaica": { c : ["JM"] },
4133			"America/Jujuy": {},
4134			"America/Juneau": { c : ["US"] },
4135			"America/Kentucky/Louisville": { c : ["US"] },
4136			"America/Kentucky/Monticello": { c : ["US"] },
4137			"America/Knox_IN": {},
4138			"America/Kralendijk": { c : ["BQ"] },
4139			"America/La_Paz": { c : ["BO"] },
4140			"America/Lima": { c : ["PE"] },
4141			"America/Los_Angeles": { c : ["US"] },
4142			"America/Louisville": {},
4143			"America/Lower_Princes": { c : ["SX"] },
4144			"America/Maceio": { c : ["BR"] },
4145			"America/Managua": { c : ["NI"] },
4146			"America/Manaus": { c : ["BR"] },
4147			"America/Marigot": { c : ["MF"] },
4148			"America/Martinique": { c : ["MQ"] },
4149			"America/Matamoros": { c : ["MX"] },
4150			"America/Mazatlan": { c : ["MX"] },
4151			"America/Mendoza": {},
4152			"America/Menominee": { c : ["US"] },
4153			"America/Merida": { c : ["MX"] },
4154			"America/Metlakatla": { c : ["US"] },
4155			"America/Mexico_City": { c : ["MX"] },
4156			"America/Miquelon": { c : ["PM"] },
4157			"America/Moncton": { c : ["CA"] },
4158			"America/Monterrey": { c : ["MX"] },
4159			"America/Montevideo": { c : ["UY"] },
4160			"America/Montreal": { c : ["CA"] },
4161			"America/Montserrat": { c : ["MS"] },
4162			"America/Nassau": { c : ["BS"] },
4163			"America/New_York": { c : ["US"] },
4164			"America/Nipigon": { c : ["CA"] },
4165			"America/Nome": { c : ["US"] },
4166			"America/Noronha": { c : ["BR"] },
4167			"America/North_Dakota/Beulah": { c : ["US"] },
4168			"America/North_Dakota/Center": { c : ["US"] },
4169			"America/North_Dakota/New_Salem": { c : ["US"] },
4170			"America/Nuuk": { c : ["GL"] },
4171			"America/Ojinaga": { c : ["MX"] },
4172			"America/Panama": { c : ["PA", "CA", "KY"] },
4173			"America/Pangnirtung": { c : ["CA"] },
4174			"America/Paramaribo": { c : ["SR"] },
4175			"America/Phoenix": { c : ["US", "CA"] },
4176			"America/Port-au-Prince": { c : ["HT"] },
4177			"America/Port_of_Spain": { c : ["TT"] },
4178			"America/Porto_Acre": {},
4179			"America/Porto_Velho": { c : ["BR"] },
4180			"America/Puerto_Rico": { c : ["PR", "AG", "CA", "AI","AW","BL","BQ","CW","DM","GD","GP","KN","LC","MF","MS","SX","TT","VC","VG","VI"] },
4181			"America/Punta_Arenas": { c : ["CL"] },
4182			"America/Rainy_River": { c : ["CA"] },
4183			"America/Rankin_Inlet": { c : ["CA"] },
4184			"America/Recife": { c : ["BR"] },
4185			"America/Regina": { c : ["CA"] },
4186			"America/Resolute": { c : ["CA"] },
4187			"America/Rio_Branco": { c : ["BR"] },
4188			"America/Rosario": {},
4189			"America/Santa_Isabel": {},
4190			"America/Santarem": { c : ["BR"] },
4191			"America/Santiago": { c : ["CL"] },
4192			"America/Santo_Domingo": { c : ["DO"] },
4193			"America/Sao_Paulo": { c : ["BR"] },
4194			"America/Scoresbysund": { c : ["GL"] },
4195			"America/Shiprock": {},
4196			"America/Sitka": { c : ["US"] },
4197			"America/St_Barthelemy": { c : ["BL"] },
4198			"America/St_Johns": { c : ["CA"] },
4199			"America/St_Kitts": { c : ["KN"] },
4200			"America/St_Lucia": { c : ["LC"] },
4201			"America/St_Thomas": { c : ["VI"] },
4202			"America/St_Vincent": { c : ["VC"] },
4203			"America/Swift_Current": { c : ["CA"] },
4204			"America/Tegucigalpa": { c : ["HN"] },
4205			"America/Thule": { c : ["GL"] },
4206			"America/Thunder_Bay": { c : ["CA"] },
4207			"America/Tijuana": { c : ["MX"] },
4208			"America/Toronto": { c : ["CA", "BS"] },
4209			"America/Tortola": { c : ["VG"] },
4210			"America/Vancouver": { c : ["CA"] },
4211			"America/Virgin": { c : ["VI"] },
4212			"America/Whitehorse": { c : ["CA"] },
4213			"America/Winnipeg": { c : ["CA"] },
4214			"America/Yakutat": { c : ["US"] },
4215			"America/Yellowknife": { c : ["CA"] },
4216			"Antarctica/Casey": { c : ["AQ"] },
4217			"Antarctica/Davis": { c : ["AQ"] },
4218			"Antarctica/DumontDUrville": { c : ["AQ"] },
4219			"Antarctica/Macquarie": { c : ["AU"] },
4220			"Antarctica/Mawson": { c : ["AQ"] },
4221			"Antarctica/McMurdo": { c : ["AQ"] },
4222			"Antarctica/Palmer": { c : ["AQ"] },
4223			"Antarctica/Rothera": { c : ["AQ"] },
4224			"Antarctica/South_Pole": { c : ["AQ"] },
4225			"Antarctica/Syowa": { c : ["AQ"] },
4226			"Antarctica/Troll": { c : ["AQ"] },
4227			"Antarctica/Vostok": { c : ["AQ"] },
4228			"Arctic/Longyearbyen": { c : ["SJ"] },
4229			"Asia/Aden": { c : ["YE"] },
4230			"Asia/Almaty": { c : ["KZ"] },
4231			"Asia/Amman": { c : ["JO"] },
4232			"Asia/Anadyr": { c : ["RU"] },
4233			"Asia/Aqtau": { c : ["KZ"] },
4234			"Asia/Aqtobe": { c : ["KZ"] },
4235			"Asia/Ashgabat": { c : ["TM"] },
4236			"Asia/Ashkhabad": {},
4237			"Asia/Atyrau": { c : ["KZ"] },
4238			"Asia/Baghdad": { c : ["IQ"] },
4239			"Asia/Bahrain": { c : ["BH"] },
4240			"Asia/Baku": { c : ["AZ"] },
4241			"Asia/Bangkok": { c : ["TH", "KH", "LA", "VN"] },
4242			"Asia/Barnaul": { c : ["RU"] },
4243			"Asia/Beirut": { c : ["LB"] },
4244			"Asia/Bishkek": { c : ["KG"] },
4245			"Asia/Brunei": { c : ["BN"] },
4246			"Asia/Calcutta": {},
4247			"Asia/Chita": { c : ["RU"] },
4248			"Asia/Choibalsan": { c : ["MN"] },
4249			"Asia/Chongqing": {},
4250			"Asia/Chungking": {},
4251			"Asia/Colombo": { c : ["LK"] },
4252			"Asia/Dacca": {},
4253			"Asia/Damascus": { c : ["SY"] },
4254			"Asia/Dhaka": { c : ["BD"] },
4255			"Asia/Dili": { c : ["TL"] },
4256			"Asia/Dubai": { c : ["AE", "OM"] },
4257			"Asia/Dushanbe": { c : ["TJ"] },
4258			"Asia/Famagusta": { c : ["CY"] },
4259			"Asia/Gaza": { c : ["PS"] },
4260			"Asia/Harbin": {},
4261			"Asia/Hebron": { c : ["PS"] },
4262			"Asia/Ho_Chi_Minh": { c : ["VN"] },
4263			"Asia/Hong_Kong": { c : ["HK"] },
4264			"Asia/Hovd": { c : ["MN"] },
4265			"Asia/Irkutsk": { c : ["RU"] },
4266			"Asia/Istanbul": {},
4267			"Asia/Jakarta": { c : ["ID"] },
4268			"Asia/Jayapura": { c : ["ID"] },
4269			"Asia/Jerusalem": { c : ["IL"] },
4270			"Asia/Kabul": { c : ["AF"] },
4271			"Asia/Kamchatka": { c : ["RU"] },
4272			"Asia/Karachi": { c : ["PK"] },
4273			"Asia/Kashgar": {},
4274			"Asia/Kathmandu": { c : ["NP"] },
4275			"Asia/Katmandu": {},
4276			"Asia/Khandyga": { c : ["RU"] },
4277			"Asia/Kolkata": { c : ["IN"] },
4278			"Asia/Krasnoyarsk": { c : ["RU"] },
4279			"Asia/Kuala_Lumpur": { c : ["MY"] },
4280			"Asia/Kuching": { c : ["MY"] },
4281			"Asia/Kuwait": { c : ["KW"] },
4282			"Asia/Macao": {},
4283			"Asia/Macau": { c : ["MO"] },
4284			"Asia/Magadan": { c : ["RU"] },
4285			"Asia/Makassar": { c : ["ID"] },
4286			"Asia/Manila": { c : ["PH"] },
4287			"Asia/Muscat": { c : ["OM"] },
4288			"Asia/Nicosia": { c : ["CY"] },
4289			"Asia/Novokuznetsk": { c : ["RU"] },
4290			"Asia/Novosibirsk": { c : ["RU"] },
4291			"Asia/Omsk": { c : ["RU"] },
4292			"Asia/Oral": { c : ["KZ"] },
4293			"Asia/Phnom_Penh": { c : ["KH"] },
4294			"Asia/Pontianak": { c : ["ID"] },
4295			"Asia/Pyongyang": { c : ["KP"] },
4296			"Asia/Qatar": { c : ["QA", "BH"] },
4297			"Asia/Qostanay": { c : ["KZ"] },
4298			"Asia/Qyzylorda": { c : ["KZ"] },
4299			"Asia/Rangoon": {},
4300			"Asia/Riyadh": { c : ["SA", "AQ", "KW", "YE"] },
4301			"Asia/Saigon": {},
4302			"Asia/Sakhalin": { c : ["RU"] },
4303			"Asia/Samarkand": { c : ["UZ"] },
4304			"Asia/Seoul": { c : ["KR"] },
4305			"Asia/Shanghai": { c : ["CN"] },
4306			"Asia/Singapore": { c : ["SG", "MY"] },
4307			"Asia/Srednekolymsk": { c : ["RU"] },
4308			"Asia/Taipei": { c : ["TW"] },
4309			"Asia/Tashkent": { c : ["UZ"] },
4310			"Asia/Tbilisi": { c : ["GE"] },
4311			"Asia/Tehran": { c : ["IR"] },
4312			"Asia/Tel_Aviv": {},
4313			"Asia/Thimbu": {},
4314			"Asia/Thimphu": { c : ["BT"] },
4315			"Asia/Tokyo": { c : ["JP"] },
4316			"Asia/Tomsk": { c : ["RU"] },
4317			"Asia/Ujung_Pandang": {},
4318			"Asia/Ulaanbaatar": { c : ["MN"] },
4319			"Asia/Ulan_Bator": {},
4320			"Asia/Urumqi": { c : ["CN"] },
4321			"Asia/Ust-Nera": { c : ["RU"] },
4322			"Asia/Vientiane": { c : ["LA"] },
4323			"Asia/Vladivostok": { c : ["RU"] },
4324			"Asia/Yakutsk": { c : ["RU"] },
4325			"Asia/Yangon": { c : ["MM"] },
4326			"Asia/Yekaterinburg": { c : ["RU"] },
4327			"Asia/Yerevan": { c : ["AM"] },
4328			"Atlantic/Azores": { c : ["PT"] },
4329			"Atlantic/Bermuda": { c : ["BM"] },
4330			"Atlantic/Canary": { c : ["ES"] },
4331			"Atlantic/Cape_Verde": { c : ["CV"] },
4332			"Atlantic/Faeroe": {},
4333			"Atlantic/Faroe": { c : ["FO"] },
4334			"Atlantic/Jan_Mayen": { c : ["SJ"] },
4335			"Atlantic/Madeira": { c : ["PT"] },
4336			"Atlantic/Reykjavik": { c : ["IS"] },
4337			"Atlantic/South_Georgia": { c : ["GS"] },
4338			"Atlantic/St_Helena": { c : ["SH"] },
4339			"Atlantic/Stanley": { c : ["FK"] },
4340			"Australia/ACT": {},
4341			"Australia/Adelaide": { c : ["AU"] },
4342			"Australia/Brisbane": { c : ["AU"] },
4343			"Australia/Broken_Hill": { c : ["AU"] },
4344			"Australia/Canberra": {},
4345			"Australia/Currie": {},
4346			"Australia/Darwin": { c : ["AU"] },
4347			"Australia/Eucla": { c : ["AU"] },
4348			"Australia/Hobart": { c : ["AU"] },
4349			"Australia/LHI": {},
4350			"Australia/Lindeman": { c : ["AU"] },
4351			"Australia/Lord_Howe": { c : ["AU"] },
4352			"Australia/Melbourne": { c : ["AU"] },
4353			"Australia/NSW": {},
4354			"Australia/North": {},
4355			"Australia/Perth": { c : ["AU"] },
4356			"Australia/Queensland": {},
4357			"Australia/South": {},
4358			"Australia/Sydney": { c : ["AU"] },
4359			"Australia/Tasmania": {},
4360			"Australia/Victoria": {},
4361			"Australia/West": {},
4362			"Australia/Yancowinna": {},
4363			"Brazil/Acre": {},
4364			"Brazil/DeNoronha": {},
4365			"Brazil/East": {},
4366			"Brazil/West": {},
4367			CET: { c : ["XK"] },
4368			CST6CDT: {},
4369			"Canada/Atlantic": {},
4370			"Canada/Central": {},
4371			"Canada/Eastern": { c : ["CA"] },
4372			"Canada/Mountain": {},
4373			"Canada/Newfoundland": {},
4374			"Canada/Pacific": {},
4375			"Canada/Saskatchewan": {},
4376			"Canada/Yukon": {},
4377			"Chile/Continental": {},
4378			"Chile/EasterIsland": {},
4379			Cuba: {},
4380			EET: {},
4381			EST: {},
4382			EST5EDT: {},
4383			Egypt: {},
4384			Eire: {},
4385			"Etc/GMT": { c : ["AC"] },
4386			"Etc/GMT+0": {},
4387			"Etc/GMT+1": {},
4388			"Etc/GMT+10": {},
4389			"Etc/GMT+11": {},
4390			"Etc/GMT+12": {},
4391			"Etc/GMT+2": {},
4392			"Etc/GMT+3": {},
4393			"Etc/GMT+4": {},
4394			"Etc/GMT+5": {},
4395			"Etc/GMT+6": {},
4396			"Etc/GMT+7": {},
4397			"Etc/GMT+8": {},
4398			"Etc/GMT+9": {},
4399			"Etc/GMT-0": {},
4400			"Etc/GMT-1": {},
4401			"Etc/GMT-10": {},
4402			"Etc/GMT-11": {},
4403			"Etc/GMT-12": {},
4404			"Etc/GMT-13": {},
4405			"Etc/GMT-14": {},
4406			"Etc/GMT-2": {},
4407			"Etc/GMT-3": {},
4408			"Etc/GMT-4": {},
4409			"Etc/GMT-5": {},
4410			"Etc/GMT-6": {},
4411			"Etc/GMT-7": {},
4412			"Etc/GMT-8": {},
4413			"Etc/GMT-9": {},
4414			"Etc/GMT0": {},
4415			"Etc/Greenwich": {},
4416			"Etc/UCT": {},
4417			"Etc/UTC": {},
4418			"Etc/Universal": {},
4419			"Etc/Zulu": {},
4420			"Europe/Amsterdam": { c : ["NL"] },
4421			"Europe/Andorra": { c : ["AD"] },
4422			"Europe/Astrakhan": { c : ["RU"] },
4423			"Europe/Athens": { c : ["GR"] },
4424			"Europe/Belfast": { c : ["GB"] },
4425			"Europe/Belgrade": { c : ["RS", "BA", "HR", "ME", "MK", "SI"] },
4426			"Europe/Berlin": { c : ["DE"] },
4427			"Europe/Bratislava": { c : ["SK"] },
4428			"Europe/Brussels": { c : ["BE"] },
4429			"Europe/Bucharest": { c : ["RO"] },
4430			"Europe/Budapest": { c : ["HU"] },
4431			"Europe/Busingen": { c : ["DE"] },
4432			"Europe/Chisinau": { c : ["MD"] },
4433			"Europe/Copenhagen": { c : ["DK"] },
4434			"Europe/Dublin": { c : ["IE"] },
4435			"Europe/Gibraltar": { c : ["GI"] },
4436			"Europe/Guernsey": { c : ["GG"] },
4437			"Europe/Helsinki": { c : ["FI", "AX"] },
4438			"Europe/Isle_of_Man": { c : ["IM"] },
4439			"Europe/Istanbul": { c : ["TR"] },
4440			"Europe/Jersey": { c : ["JE"] },
4441			"Europe/Kaliningrad": { c : ["RU"] },
4442			"Europe/Kiev": { c : ["UA"] },
4443			"Europe/Kirov": { c : ["RU"] },
4444			"Europe/Lisbon": { c : ["PT"] },
4445			"Europe/Ljubljana": { c : ["SI"] },
4446			"Europe/London": { c : ["GB", "GG", "IM", "JE"] },
4447			"Europe/Luxembourg": { c : ["LU"] },
4448			"Europe/Madrid": { c : ["ES"] },
4449			"Europe/Malta": { c : ["MT"] },
4450			"Europe/Mariehamn": { c : ["AX"] },
4451			"Europe/Minsk": { c : ["BY"] },
4452			"Europe/Monaco": { c : ["MC"] },
4453			"Europe/Moscow": { c : ["RU"] },
4454			"Europe/Nicosia": {},
4455			"Europe/Oslo": { c : ["NO", "SJ", "BV"] },
4456			"Europe/Paris": { c : ["FR"] },
4457			"Europe/Podgorica": { c : ["ME"] },
4458			"Europe/Prague": { c : ["CZ", "SK"] },
4459			"Europe/Riga": { c : ["LV"] },
4460			"Europe/Rome": { c : ["IT", "SM", "VA"] },
4461			"Europe/Samara": { c : ["RU"] },
4462			"Europe/San_Marino": { c : ["SM"] },
4463			"Europe/Sarajevo": { c : ["BA"] },
4464			"Europe/Saratov": { c : ["RU"] },
4465			"Europe/Simferopol": { c : ["RU", "UA"] },
4466			"Europe/Skopje": { c : ["MK"] },
4467			"Europe/Sofia": { c : ["BG"] },
4468			"Europe/Stockholm": { c : ["SE"] },
4469			"Europe/Tallinn": { c : ["EE"] },
4470			"Europe/Tirane": { c : ["AL"] },
4471			"Europe/Tiraspol": {},
4472			"Europe/Ulyanovsk": { c : ["RU"] },
4473			"Europe/Uzhgorod": { c : ["UA"] },
4474			"Europe/Vaduz": { c : ["LI"] },
4475			"Europe/Vatican": { c : ["VA"] },
4476			"Europe/Vienna": { c : ["AT"] },
4477			"Europe/Vilnius": { c : ["LT"] },
4478			"Europe/Volgograd": { c : ["RU"] },
4479			"Europe/Warsaw": { c : ["PL"] },
4480			"Europe/Zagreb": { c : ["HR"] },
4481			"Europe/Zaporozhye": { c : ["UA"] },
4482			"Europe/Zurich": { c : ["CH", "DE", "LI"] },
4483			Factory: {},
4484			GB: { c : ["GB"] },
4485			"GB-Eire": { c : ["GB"] },
4486			GMT: { c : ["AC"] },
4487			"GMT+0": {},
4488			"GMT-0": {},
4489			GMT0: {},
4490			Greenwich: {},
4491			HST: {},
4492			Hongkong: {},
4493			Iceland: {},
4494			"Indian/Antananarivo": { c : ["MG"] },
4495			"Indian/Chagos": { c : ["IO"] },
4496			"Indian/Christmas": { c : ["CX"] },
4497			"Indian/Cocos": { c : ["CC"] },
4498			"Indian/Comoro": { c : ["KM"] },
4499			"Indian/Kerguelen": { c : ["TF", "HM"] },
4500			"Indian/Mahe": { c : ["SC"] },
4501			"Indian/Maldives": { c : ["MV"] },
4502			"Indian/Mauritius": { c : ["MU"] },
4503			"Indian/Mayotte": { c : ["YT"] },
4504			"Indian/Reunion": { c : ["RE", "TF"] },
4505			Iran: {},
4506			Israel: {},
4507			Jamaica: {},
4508			Japan: {},
4509			Kwajalein: {},
4510			Libya: {},
4511			MET: {},
4512			MST: {},
4513			MST7MDT: {},
4514			"Mexico/BajaNorte": {},
4515			"Mexico/BajaSur": {},
4516			"Mexico/General": {},
4517			NZ: { c : ["NZ"] },
4518			"NZ-CHAT": {},
4519			Navajo: {},
4520			PRC: {},
4521			PST8PDT: {},
4522			"Pacific/Apia": { c : ["WS"] },
4523			"Pacific/Auckland": { c : ["NZ", "AQ"] },
4524			"Pacific/Bougainville": { c : ["PG"] },
4525			"Pacific/Chatham": { c : ["NZ"] },
4526			"Pacific/Chuuk": { c : ["FM"] },
4527			"Pacific/Easter": { c : ["CL"] },
4528			"Pacific/Efate": { c : ["VU"] },
4529			"Pacific/Enderbury": {},
4530			"Pacific/Fakaofo": { c : ["TK"] },
4531			"Pacific/Fiji": { c : ["FJ"] },
4532			"Pacific/Funafuti": { c : ["TV"] },
4533			"Pacific/Galapagos": { c : ["EC"] },
4534			"Pacific/Gambier": { c : ["PF"] },
4535			"Pacific/Guadalcanal": { c : ["SB"] },
4536			"Pacific/Guam": { c : ["GU", "MP"] },
4537			"Pacific/Honolulu": { c : ["US", "UM"] },
4538			"Pacific/Johnston": { c : ["UM"] },
4539			"Pacific/Kanton": { c : ["KI"] },
4540			"Pacific/Kiritimati": { c : ["KI"] },
4541			"Pacific/Kosrae": { c : ["FM"] },
4542			"Pacific/Kwajalein": { c : ["MH"] },
4543			"Pacific/Majuro": { c : ["MH"] },
4544			"Pacific/Marquesas": { c : ["PF"] },
4545			"Pacific/Midway": { c : ["UM"] },
4546			"Pacific/Nauru": { c : ["NR"] },
4547			"Pacific/Niue": { c : ["NU"] },
4548			"Pacific/Norfolk": { c : ["NF"] },
4549			"Pacific/Noumea": { c : ["NC"] },
4550			"Pacific/Pago_Pago": { c : ["AS", "UM"] },
4551			"Pacific/Palau": { c : ["PW"] },
4552			"Pacific/Pitcairn": { c : ["PN"] },
4553			"Pacific/Pohnpei": { c : ["FM"] },
4554			"Pacific/Ponape": {},
4555			"Pacific/Port_Moresby": { c : ["PG", "AQ"] },
4556			"Pacific/Rarotonga": { c : ["CK"] },
4557			"Pacific/Saipan": { c : ["MP"] },
4558			"Pacific/Samoa": { c : ["WS"] },
4559			"Pacific/Tahiti": { c : ["PF"] },
4560			"Pacific/Tarawa": { c : ["KI"] },
4561			"Pacific/Tongatapu": { c : ["TO"] },
4562			"Pacific/Truk": {},
4563			"Pacific/Wake": { c : ["UM"] },
4564			"Pacific/Wallis": { c : ["WF"] },
4565			"Pacific/Yap": {},
4566			Poland: {},
4567			Portugal: {},
4568			ROC: {},
4569			ROK: {},
4570			Singapore: { c : ["SG"] },
4571			Turkey: {},
4572			UCT: {},
4573			"US/Alaska": {},
4574			"US/Aleutian": {},
4575			"US/Arizona": { c : ["US"] },
4576			"US/Central": {},
4577			"US/East-Indiana": {},
4578			"US/Eastern": {},
4579			"US/Hawaii": { c : ["US"] },
4580			"US/Indiana-Starke": {},
4581			"US/Michigan": {},
4582			"US/Mountain": {},
4583			"US/Pacific": {},
4584			"US/Samoa": { c : ["WS"] },
4585			UTC: {},
4586			Universal: {},
4587			"W-SU": {},
4588			WET: {},
4589			Zulu: {
4590			}
4591		};
4592
4593		const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
4594
4595		if (timezone === "" || !timezone) {
4596			return null;
4597		}
4598
4599		return timezones[timezone].c[0];
4600	}
4601
4602	let utilsScriptLoaded;
4603
4604	em_setup_phone_inputs = async function ( container, overriding_options = {} ) {
4605		if ( !EM.phone ) return false;
4606		if( !utilsScriptLoaded ) {
4607			import( EM.url + '/includes/external/intl-tel-input/js/intlTelInputWithUtils.js' ).then( () => {
4608				utilsScriptLoaded = true;
4609				em_setup_phone_inputs( container );
4610			});
4611			return false;
4612		} // on initial load, we wait for scripts to load
4613		container.querySelectorAll('input.em-phone-intl[type="tel"]').forEach( function(input){
4614			// change name and allow a hidden field for submission
4615			let alt = document.createElement('input');
4616			let name = input.name;
4617			if( name ) {
4618				// check if there's an ending ] in the name if so modify the name within the last brackets
4619				let lastBracket = name.lastIndexOf(']');
4620				if( lastBracket > -1 ) {
4621					input.name = name.substring(0, lastBracket) + '_intl]';
4622				} else {
4623					input.name = name + '_intl';
4624				}
4625				alt.name = name;
4626			}
4627			input.classList.add('em-intl-tel');
4628			// copy all classes and remove ones we know we don't want
4629			alt.setAttribute('class', input.getAttribute('class') + ' em-intl-tel-full');
4630			alt.classList.remove('em-intl-tel');
4631			alt.type = 'hidden';
4632			if( input.id ) {
4633				alt.id = input.id + '-full'
4634			}
4635			alt.value = input.value;
4636			// add data-name to the full input if it exists, for use in dynamic input forms for JS submission within forms
4637			if( input.getAttribute('data-name') ) {
4638				alt.setAttribute('data-name', input.getAttribute('data-name'));
4639				input.removeAttribute('data-name');
4640			}
4641			input.after(alt);
4642
4643			let default_options = Object.assign({
4644				autoPlaceholder: 'aggressive',
4645				separateDialCode : true,
4646			}, EM.phone.options);
4647			let options = Object.assign( default_options, overriding_options );
4648
4649			if( EM.phone.detectJS || options.detectJS ) {
4650				let country = getCountry();
4651				if( country ) {
4652					options.initialCountry = country;
4653				} else if ( EM.phone.initialCountry ) {
4654					options.initialCountry = EM.phone.initialCountry;
4655				}
4656			}
4657			if( options.onlyCountries ) {
4658				if( Array.isArray(options.onlyCountries) && options.onlyCountries.length > 0 ) {
4659					// make sure initial country is not excluded
4660					if (!options.onlyCountries.includes(options.initialCountry && options.initialCountry)) {
4661						options.onlyCountries.push(options.initialCountry);
4662					}
4663				} else {
4664					options.onlyCountries = [];
4665				}
4666			}
4667
4668			let iti = EM.intlTelInput( input, options);
4669			if ( !input?.checkVisibility() ) {
4670				// if the input is hidden, we need some trickery to correctly obtain the padding by adding a clone of the minimum into the array
4671				// intl-tel-input does this, but because it's not wrapped in an em element the padding isn't correctly styled via CSS
4672				let body = document.body;
4673				let container = document.createElement('div');
4674				container.style.visibility = "hidden";
4675				container.classList.add('em');
4676				body.appendChild( container );
4677				let containerClone = input.parentNode.cloneNode( false );
4678				container.appendChild( containerClone );
4679				let countryContainerClone = iti.ui.countryContainer.cloneNode();
4680				containerClone.appendChild( countryContainerClone );
4681				let selectedCountryClone = iti.ui.selectedCountry.cloneNode( true );
4682				countryContainerClone.appendChild( selectedCountryClone );
4683				let width = selectedCountryClone.offsetWidth + 12; // add extra padding
4684				input.style.setProperty('padding-left', width + 'px', 'important' );
4685				body.removeChild( container );
4686			}
4687			//iti.countryContainer.querySelector('button')?.setAttribute('data-nostyle', '');
4688			let pixels = parseInt( input.style.paddingLeft.replace('px', '') ); // pad this an extra px
4689			input.style.setProperty('padding-left', pixels + 'px', 'important' );
4690
4691			// do some basic inline validation
4692			input.addEventListener('change', function( e ){
4693				alt.value = iti.getNumber();
4694				if ( input.value.trim() ) {
4695					let wrapper = input.closest('.iti')
4696					if ( iti.isValidNumber() ) {
4697						wrapper.classList.remove("invalid-number");
4698						if ( wrapper.nextElementSibling && wrapper.nextElementSibling.classList.contains('em-inline-error') ) {
4699							wrapper.nextElementSibling.remove();
4700						}
4701					} else {
4702						wrapper.classList.add("invalid-number");
4703						const errorCode = iti.getValidationError();
4704						let errorMsg;
4705						if( !(wrapper.nextElementSibling && wrapper.nextElementSibling.classList.contains('em-inline-error')) ) {
4706							// create a div em-form-error class name and append after input
4707							errorMsg = document.createElement('div');
4708							errorMsg.classList.add('em-inline-error');
4709							wrapper.after(errorMsg);
4710						} else {
4711							errorMsg = wrapper.nextElementSibling;
4712						}
4713						errorMsg.innerHTML = '<span class="em-icon"></span> ' + EM.phone.error;
4714						errorMsg.classList.remove("hide");
4715					}
4716				}
4717			});
4718			
4719			// trigger changes
4720			input.addEventListener('countrychange', function( e ){
4721				alt.value = iti.getNumber();
4722				// check input padding inline style and set it to important
4723				if( input.getAttribute('style') ) {
4724					let pixels = parseInt(input.style.paddingLeft.replace('px', '')); // pad this an extra px
4725					input.style.setProperty('padding-left', pixels + 'px', 'important' );
4726				}
4727			});
4728
4729			input.addEventListener('open:countrydropdown', function( e ) {
4730				document.querySelectorAll('.iti.iti--container.iti--fullscreen-popup').forEach( function( el ) {
4731					if ( !el.closest('.em') ) {
4732						// wrap in an .em div
4733						let div = document.createElement('div');
4734						div.classList.add('em');
4735						el.parentNode.insertBefore(div, el);
4736						div.appendChild(el);
4737						el.querySelector('input.iti__search-input')?.focus();
4738					}
4739				});
4740			});
4741
4742		});
4743	};
4744
4745	em_unsetup_phone_inputs = function( container ) {
4746		container.querySelectorAll( 'input.em-phone-intl[type="tel"]' ).forEach( function(el){
4747			let iti = EM.intlTelInput?.getInstance(el);
4748			if ( iti ) {
4749				iti.destroy();
4750				// remove alt field as well and unset the _intl suffix, which may have a trailing ] so needs a preg
4751				el.name = el.name.replace(/_intl]$/, ']').replace(/_intl$/, '');
4752				el.parentElement.querySelector('input.em-intl-tel-full')?.remove();
4753			}
4754		});
4755	};
4756}
4757
4758/*!
4759 * jquery-timepicker v1.13.16 - Copyright (c) 2020 Jon Thornton - https://www.jonthornton.com/jquery-timepicker/
4760 * Did a search/replace of timepicker to em_timepicker to prevent conflicts.
4761 */
4762(function(){"use strict";function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function(obj){return typeof obj}}else{_typeof=function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor)}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly)symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable});keys.push.apply(keys,symbols)}return keys}
4762function _objectSpread2(target){for(var i=1;i<arguments.length;i++){var source=arguments[i]!=null?arguments[i]:{};if(i%2){ownKeys(Object(source),true).forEach(function(key){_defineProperty(target,key,source[key])})}else if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source))}else{ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key))})}}return target}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(n);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function _createForOfIteratorHelper(o){if(typeof Symbol==="undefined"||o[Symbol.iterator]==null){if(Array.isArray(o)||(o=_unsupportedIterableToArray(o))){var i=0;var F=function(){};return{s:F,n:function(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},e:function(e){throw e},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var it,normalCompletion=true,didErr=false,err;return{s:function(){it=o[Symbol.iterator]()},n:function(){var step=it.next();normalCompletion=step.done;return step},e:function(e){didErr=true;err=e},f:function(){try{if(!normalCompletion&&it.return!=null)it.return()}finally{if(didErr)throw err}}}}var ONE_DAY=86400;var roundingFunction=function roundingFunction(seconds,settings){if(seconds===null){return null}else if(typeof settings.step!=="number"){return seconds}else{var offset=seconds%(settings.step*60);var start=settings.minTime||0;offset-=start%(settings.step*60);if(offset>=settings.step*30){seconds+=settings.step*60-offset}else{seconds-=offset}return _moduloSeconds(seconds,settings)}};function _moduloSeconds(seconds,settings){if(seconds==ONE_DAY&&settings.show2400){return seconds}return seconds%ONE_DAY}var DEFAULT_SETTINGS={appendTo:"body",className:null,closeOnWindowScroll:false,disableTextInput:false,disableTimeRanges:[],disableTouchKeyboard:false,durationTime:null,forceRoundTime:false,lang:{},listWidth:null,maxTime:null,minTime:null,noneOption:false,orientation:"l",roundingFunction:roundingFunction,scrollDefault:null,selectOnBlur:false,show2400:false,showDuration:false,showOn:["click","focus"],showOnFocus:true,step:30,stopScrollPropagation:false,timeFormat:"g:ia",typeaheadHighlight:true,useSelect:false,wrapHours:true};var DEFAULT_LANG={am:"am",pm:"pm",AM:"AM",PM:"PM",decimal:".",mins:"mins",hr:"hr",hrs:"hrs"};var Timepicker=function(){function Timepicker(targetEl){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,Timepicker);this._handleFormatValue=this._handleFormatValue.bind(this);this._handleKeyUp=this._handleKeyUp.bind(this);this.targetEl=targetEl;var attrOptions=Timepicker.extractAttrOptions(targetEl,Object.keys(DEFAULT_SETTINGS));this.settings=this.parseSettings(_objectSpread2(_objectSpread2(_objectSpread2({},DEFAULT_SETTINGS),options),attrOptions))}_createClass(Timepicker,[{key:"hideMe",value:function hideMe(){if(this.settings.useSelect){this.targetEl.blur();return}if(!this.list||!Timepicker.isVisible(this.list)){return}if(this.settings.selectOnBlur){this._selectValue()}this.list.hide();var hideTimepickerEvent=new CustomEvent("hideTimepicker");this.targetEl.dispatchEvent(hideTimepickerEvent)}},{key:"_findRow",value:function _findRow(value){if(!value&&value!==0){return false}var out=false;var value=this.settings.roundingFunction(value,this.settings);if(!this.list){return false}this.list.find("li").each(function(i,obj){var parsed=Number.parseInt(obj.dataset.time);if(Number.isNaN(parsed)){return}if(parsed==value){out=obj;return false}});return out}},{key:"_hideKeyboard",value:function _hideKeyboard(){return(window.navigator.msMaxTouchPoints||"ontouchstart"in document)&&this.settings.disableTouchKeyboard}},{key:"_setTimeValue",value:function _setTimeValue(value,source){if(this.targetEl.nodeName==="INPUT"){if(value!==null||this.targetEl.value!=""){this.targetEl.value=value}var tp=this;var settings=tp.settings;if(settings.useSelect&&source!="select"&&tp.list){tp.list.val(tp._roundAndFormatTime(tp.time2int(value)))}}
4762var selectTimeEvent=new Event("selectTime");if(this.selectedValue!=value){this.selectedValue=value;var changeTimeEvent=new Event("changeTime");var changeEvent=new CustomEvent("change",{detail:"em_timepicker"});if(source=="select"){this.targetEl.dispatchEvent(selectTimeEvent);this.targetEl.dispatchEvent(changeTimeEvent);this.targetEl.dispatchEvent(changeEvent)}else if(["error","initial"].indexOf(source)==-1){this.targetEl.dispatchEvent(changeTimeEvent)}return true}else{if(["error","initial"].indexOf(source)==-1){this.targetEl.dispatchEvent(selectTimeEvent)}return false}}},{key:"_getTimeValue",value:function _getTimeValue(){if(this.targetEl.nodeName==="INPUT"){return this.targetEl.value}else{return this.selectedValue}}},{key:"_selectValue",value:function _selectValue(){var tp=this;var settings=tp.settings;var list=tp.list;var cursor=list.find(".ui-em_timepicker-selected");if(cursor.hasClass("ui-em_timepicker-disabled")){return false}if(!cursor.length){return true}var timeValue=cursor.get(0).dataset.time;if(timeValue){var parsedTimeValue=Number.parseInt(timeValue);if(!Number.isNaN(parsedTimeValue)){timeValue=parsedTimeValue}}if(timeValue!==null){if(typeof timeValue!="string"){timeValue=tp._int2time(timeValue)}tp._setTimeValue(timeValue,"select")}return true}},{key:"time2int",value:function time2int(timeString){if(timeString===""||timeString===null||timeString===undefined)return null;if(timeString instanceof Date){return timeString.getHours()*3600+timeString.getMinutes()*60+timeString.getSeconds()}if(typeof timeString!="string"){return timeString}timeString=timeString.toLowerCase().replace(/[\s\.]/g,"");if(timeString.slice(-1)=="a"||timeString.slice(-1)=="p"){timeString+="m"}var pattern=/^(([^0-9]*))?([0-9]?[0-9])(([0-5][0-9]))?(([0-5][0-9]))?(([^0-9]*))$/;var hasDelimetersMatch=timeString.match(/\W/);if(hasDelimetersMatch){pattern=/^(([^0-9]*))?([0-9]?[0-9])(\W+([0-5][0-9]?))?(\W+([0-5][0-9]))?(([^0-9]*))$/}var time=timeString.match(pattern);if(!time){return null}var hour=parseInt(time[3]*1,10);var ampm=time[2]||time[9];var hours=hour;var minutes=time[5]*1||0;var seconds=time[7]*1||0;if(!ampm&&time[3].length==2&&time[3][0]=="0"){ampm="am"}if(hour<=12&&ampm){ampm=ampm.trim();var isPm=ampm==this.settings.lang.pm||ampm==this.settings.lang.PM;if(hour==12){hours=isPm?12:0}else{hours=hour+(isPm?12:0)}}else{var t=hour*3600+minutes*60+seconds;if(t>=ONE_DAY+(this.settings.show2400?1:0)){if(this.settings.wrapHours===false){return null}hours=hour%24}}var timeInt=hours*3600+minutes*60+seconds;if(hour<12&&!ampm&&this.settings._twelveHourTime&&this.settings.scrollDefault){var delta=timeInt-this.settings.scrollDefault();if(delta<0&&delta>=ONE_DAY/-2){timeInt=(timeInt+ONE_DAY/2)%ONE_DAY}}return timeInt}},{key:"parseSettings",value:function parseSettings(settings){var _this=this;settings.lang=_objectSpread2(_objectSpread2({},DEFAULT_LANG),settings.lang);this.settings=settings;if(settings.minTime){settings.minTime=this.time2int(settings.minTime)}if(settings.maxTime){settings.maxTime=this.time2int(settings.maxTime)}if(settings.listWidth){settings.listWidth=this.time2int(settings.listWidth)}if(settings.durationTime&&typeof settings.durationTime!=="function"){settings.durationTime=this.time2int(settings.durationTime)}if(settings.scrollDefault=="now"){settings.scrollDefault=function(){return settings.roundingFunction(_this.time2int(new Date),settings)}}else if(settings.scrollDefault&&typeof settings.scrollDefault!="function"){var val=settings.scrollDefault;settings.scrollDefault=function(){return settings.roundingFunction(_this.time2int(val),settings)}}else if(settings.minTime){settings.scrollDefault=function(){return settings.roundingFunction(settings.minTime,settings)}}if(typeof settings.timeFormat==="string"&&settings.timeFormat.match(/[gh]/)){settings._twelveHourTime=true}if(settings.showOnFocus===false&&settings.showOn.indexOf("focus")!=-1){settings.showOn.splice(settings.showOn.indexOf("focus"),1)}if(!settings.disableTimeRanges){settings.disableTimeRanges=[]}if(settings.disableTimeRanges.length>0){for(var i in settings.disableTimeRanges){settings.disableTimeRanges[i]=[this.time2int(sett
4762ings.disableTimeRanges[i][0]),this.time2int(settings.disableTimeRanges[i][1])]}settings.disableTimeRanges=settings.disableTimeRanges.sort(function(a,b){return a[0]-b[0]});for(var i=settings.disableTimeRanges.length-1;i>0;i--){if(settings.disableTimeRanges[i][0]<=settings.disableTimeRanges[i-1][1]){settings.disableTimeRanges[i-1]=[Math.min(settings.disableTimeRanges[i][0],settings.disableTimeRanges[i-1][0]),Math.max(settings.disableTimeRanges[i][1],settings.disableTimeRanges[i-1][1])];settings.disableTimeRanges.splice(i,1)}}}return settings}},{key:"_disableTextInputHandler",value:function _disableTextInputHandler(e){switch(e.keyCode){case 13:case 9:return;default:e.preventDefault()}}},{key:"_int2duration",value:function _int2duration(seconds,step){seconds=Math.abs(seconds);var minutes=Math.round(seconds/60),duration=[],hours,mins;if(minutes<60){duration=[minutes,this.settings.lang.mins]}else{hours=Math.floor(minutes/60);mins=minutes%60;if(step==30&&mins==30){hours+=this.settings.lang.decimal+5}duration.push(hours);duration.push(hours==1?this.settings.lang.hr:this.settings.lang.hrs);if(step!=30&&mins){duration.push(mins);duration.push(this.settings.lang.mins)}}return duration.join(" ")}},{key:"_roundAndFormatTime",value:function _roundAndFormatTime(seconds){seconds=this.settings.roundingFunction(seconds,this.settings);if(seconds!==null){return this._int2time(seconds)}}},{key:"_int2time",value:function _int2time(timeInt){if(typeof timeInt!="number"){return null}var seconds=parseInt(timeInt%60),minutes=parseInt(timeInt/60%60),hours=parseInt(timeInt/(60*60)%24);var time=new Date(1970,0,2,hours,minutes,seconds,0);if(isNaN(time.getTime())){return null}if(typeof this.settings.timeFormat==="function"){return this.settings.timeFormat(time)}var output="";var hour,code;for(var i=0;i<this.settings.timeFormat.length;i++){code=this.settings.timeFormat.charAt(i);switch(code){case"a":output+=time.getHours()>11?this.settings.lang.pm:this.settings.lang.am;break;case"A":output+=time.getHours()>11?this.settings.lang.PM:this.settings.lang.AM;break;case"g":hour=time.getHours()%12;output+=hour===0?"12":hour;break;case"G":hour=time.getHours();if(timeInt===ONE_DAY)hour=this.settings.show2400?24:0;output+=hour;break;case"h":hour=time.getHours()%12;if(hour!==0&&hour<10){hour="0"+hour}output+=hour===0?"12":hour;break;case"H":hour=time.getHours();if(timeInt===ONE_DAY)hour=this.settings.show2400?24:0;output+=hour>9?hour:"0"+hour;break;case"i":var minutes=time.getMinutes();output+=minutes>9?minutes:"0"+minutes;break;case"s":seconds=time.getSeconds();output+=seconds>9?seconds:"0"+seconds;break;case"\\":i++;output+=this.settings.timeFormat.charAt(i);break;default:output+=code}}return output}},{key:"_setSelected",value:function _setSelected(){var list=this.list;list.find("li").removeClass("ui-em_timepicker-selected");var timeValue=this.time2int(this._getTimeValue());if(timeValue===null){return}var selected=this._findRow(timeValue);if(selected){var selectedRect=selected.getBoundingClientRect();var listRect=list.get(0).getBoundingClientRect();var topDelta=selectedRect.top-listRect.top;if(topDelta+selectedRect.height>listRect.height||topDelta<0){var newScroll=list.scrollTop()+(selectedRect.top-listRect.top)-selectedRect.height;list.scrollTop(newScroll)}var parsed=Number.parseInt(selected.dataset.time);if(this.settings.forceRoundTime||parsed===timeValue){selected.classList.add("ui-em_timepicker-selected")}}}},{key:"_isFocused",value:function _isFocused(el){return el===document.activeElement}},{key:"_handleFormatValue",value:function _handleFormatValue(e){if(e&&e.detail=="em_timepicker"){return}this._formatValue(e)}},{key:"_formatValue",value:function _formatValue(e,origin){if(this.targetEl.value===""){this._setTimeValue(null,origin);return}if(this._isFocused(this.targetEl)&&(!e||e.type!="change")){return}var settings=this.settings;var seconds=this.time2int(this.targetEl.value);if(seconds===null){var timeFormatErrorEvent=new CustomEvent("timeFormatError");this.targetEl.dispatchEvent(timeFormatErrorEvent);return}var rangeError=false;if(settings.minTime!==null&&settings.maxTime!==null&&(seconds<settings.minTime||seconds>
4762settings.maxTime)){rangeError=true}var _iterator=_createForOfIteratorHelper(settings.disableTimeRanges),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var range=_step.value;if(seconds>=range[0]&&seconds<range[1]){rangeError=true;break}}}catch(err){_iterator.e(err)}finally{_iterator.f()}if(settings.forceRoundTime){var roundSeconds=settings.roundingFunction(seconds,settings);if(roundSeconds!=seconds){seconds=roundSeconds;origin=null}}var prettyTime=this._int2time(seconds);if(rangeError){this._setTimeValue(prettyTime);var timeRangeErrorEvent=new CustomEvent("timeRangeError");this.targetEl.dispatchEvent(timeRangeErrorEvent)}else{this._setTimeValue(prettyTime,origin)}}},{key:"_generateNoneElement",value:function _generateNoneElement(optionValue,useSelect){var label,className,value;if(_typeof(optionValue)=="object"){label=optionValue.label;className=optionValue.className;value=optionValue.value}else if(typeof optionValue=="string"){label=optionValue;value=""}else{$.error("Invalid noneOption value")}var el;if(useSelect){el=document.createElement("option");el.value=value}else{el=document.createElement("li");el.dataset.time=String(value)}el.innerText=label;el.classList.add(className);return el}},{key:"_handleKeyUp",value:function _handleKeyUp(e){if(!this.list||!Timepicker.isVisible(this.list)||this.settings.disableTextInput){return true}if(e.type==="paste"||e.type==="cut"){setTimeout(function(){if(this.settings.typeaheadHighlight){this._setSelected()}else{this.list.hide()}},0);return}switch(e.keyCode){case 96:case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 65:case 77:case 80:case 186:case 8:case 46:if(this.settings.typeaheadHighlight){this._setSelected()}else{this.list.hide()}break}}}],[{key:"extractAttrOptions",value:function extractAttrOptions(element,keys){var output={};var _iterator2=_createForOfIteratorHelper(keys),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var key=_step2.value;if(key in element.dataset){output[key]=element.dataset[key]}}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}return output}},{key:"isVisible",value:function isVisible(elem){var el=elem[0];return el.offsetWidth>0&&el.offsetHeight>0}},{key:"hideAll",value:function hideAll(){var _iterator3=_createForOfIteratorHelper(document.getElementsByClassName("ui-em_timepicker-input")),_step3;try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var el=_step3.value;var tp=el.em_timepickerObj;if(tp){tp.hideMe()}}}catch(err){_iterator3.e(err)}finally{_iterator3.f()}}}]);return Timepicker}();(function(factory){if((typeof exports==="undefined"?"undefined":_typeof(exports))==="object"&&exports&&(typeof module==="undefined"?"undefined":_typeof(module))==="object"&&module&&module.exports===exports){factory(require("jquery"))}else if(typeof define==="function"&&define.amd){define(["jquery"],factory)}else{factory(jQuery)}})(function($){var _lang={};var methods={init:function init(options){return this.each(function(){var self=$(this);var tp=new Timepicker(this,options);var settings=tp.settings;_lang=settings.lang;this.em_timepickerObj=tp;self.addClass("ui-em_timepicker-input");if(settings.useSelect){_render(self)}else{self.prop("autocomplete","off");if(settings.showOn){for(var i in settings.showOn){self.on(settings.showOn[i]+".em_timepicker",methods.show)}}self.on("change.em_timepicker",tp._handleFormatValue);self.on("keydown.em_timepicker",_keydownhandler);self.on("keyup.em_timepicker",tp._handleKeyUp);if(settings.disableTextInput){self.on("keydown.em_timepicker",tp._disableTextInputHandler)}self.on("cut.em_timepicker",tp._handleKeyUp);self.on("paste.em_timepicker",tp._handleKeyUp);tp._formatValue(null,"initial")}})},show:function show(e){var self=$(this);var tp=self[0].em_timepickerObj;var settings=tp.settings;if(e){e.preventDefault()}if(settings.useSelect){tp.list.trigger("focus");return}if(tp._hideKeyboard()){self.trigger("blur")}var list=tp.list;if(self.prop("readonly")){return}if(!list||list.length===0||typeof settings.durationTime==="function"){_render(self);list=tp.list}if(Timepicker.isVisible(list)){return}if(self.is("input")){tp.selectedValue=self.val()}tp._setSelected();Timepicker.hideAll();if(typeof settings.listWidth=="number"){list.width(self.outerWidth()*settings.listWidth)}list.show();var listOffset={};if(settings.orientation.match(/r/)){listOffset.left=self.offset().left+self.outerWidth()-list.outerWidth()+parseInt(list.css("marginLeft").replace("px",""),10)}else if(settings.orientation.match(/l/)){listOffset.left=self.offset().left+parseInt(list.css("marginLeft").replace("px",""),10)}else if(settings.orientation.match(/c/)){listOffset.left=self.offset().left+(self.outerWidth()-list.outerWidth())/2+parseInt(list.css("marginLeft").replace("px",""),10)}var verticalOrientation;if(settings.orientation.match(/t/)){verticalOrientation="t"}else if(settings.orientation.match(/b/)){verticalOrientation="b"}else if(self.offset().top+self.outerHeight(true)+list.outerHeight()>$(window).height()+$(window).scrollTop()){verticalOrientation="t"}else{verticalOrientation="b"}if(verticalOrientation=="t"){list.addClass("ui-em_timepicker-positioned-top");listOffset.top=self.offset().top-list.outerHeight()+parseInt(list.css("marginTop").replace("px",""),10)}else{list.removeClass("ui-em_timepicker-positioned-top");listOffset.top=self.offset().top+self.outerHeight()+parseInt(list.css("marginTop").replace("px",""),10)}list.offset(listOffset);var selected=list.find(".ui-em_timepicker-selected");if(!selected.length){var timeInt=tp.time2int(tp._getTimeValue());if(timeInt!==null){selected=$(tp._findRow(timeInt))}else if(settings.scrollDefault){selected=$(tp._findRow(settings.scrollDefault()))}}if(!selected.length||selected.hasClass("ui-em_timepicker-disabled")){selected=list.find("li:not(.ui-em_timepicker-disabled):first")}if(selected&&selected.length){var topOffset=list.scrollTop()+selected.position().top-selected.outerHeight();list.scrollTop(topOffset)}else{list.scrollTop(0)}if(settings.stopScrollPropagation){$(document).on("wheel.ui-em_timepicker",".ui-em_timepicker-wrapper",function(e){e.preventDefault();var currentScroll=$(this).scrollTop();$(this).scrollTop(currentScroll+e.originalEvent.deltaY)})}$(document).on("mousedown.ui-em_timepicker",_closeHandler);$(window).on("resize.ui-em_timepicker",_closeHandler);if(settings.closeOnWindowScroll){$(document).on("scroll.ui-em_timepicker",_closeHandler)}self.trigger("showTimepicker");return this},hide:function hide(e){var tp=this[0].em_timepickerObj;if(tp){tp.hideMe()}Timepicker.hideAll();return this},option:function option(key,value){if(typeof key=="string"&&typeof value=="undefined"){var tp=this[0].em_timepickerObj;return tp.settings[key]}return this.each(function(){var self=$(this);var tp=self[0].em_timepickerObj;var settings=tp.settings;var list=tp.list;
4762if(_typeof(key)=="object"){settings=$.extend(settings,key)}else if(typeof key=="string"){settings[key]=value}settings=tp.parseSettings(settings);tp.settings=settings;tp._formatValue({type:"change"},"initial");if(list){list.remove();tp.list=null}if(settings.useSelect){_render(self)}})},getSecondsFromMidnight:function getSecondsFromMidnight(){var tp=this[0].em_timepickerObj;return tp.time2int(tp._getTimeValue())},getTime:function getTime(relative_date){var tp=this[0].em_timepickerObj;var time_string=tp._getTimeValue();if(!time_string){return null}var offset=tp.time2int(time_string);if(offset===null){return null}if(!relative_date){relative_date=new Date}var time=new Date(relative_date);time.setHours(offset/3600);time.setMinutes(offset%3600/60);time.setSeconds(offset%60);time.setMilliseconds(0);return time},isVisible:function isVisible(){var tp=this[0].em_timepickerObj;return!!(tp&&tp.list&&Timepicker.isVisible(tp.list))},setTime:function setTime(value){var tp=this[0].em_timepickerObj;var settings=tp.settings;if(settings.forceRoundTime){var prettyTime=tp._roundAndFormatTime(tp.time2int(value))}else{var prettyTime=tp._int2time(tp.time2int(value))}if(value&&prettyTime===null&&settings.noneOption){prettyTime=value}tp._setTimeValue(prettyTime,"initial");tp._formatValue({type:"change"},"initial");if(tp&&tp.list){tp._setSelected()}return this},remove:function remove(){var self=this;if(!self.hasClass("ui-em_timepicker-input")){return}var tp=self[0].em_timepickerObj;var settings=tp.settings;self.removeAttr("autocomplete","off");self.removeClass("ui-em_timepicker-input");self.removeData("em_timepicker-obj");self.off(".em_timepicker");if(tp.list){tp.list.remove()}if(settings.useSelect){self.show()}tp.list=null;return this}};function _render(self){var tp=self[0].em_timepickerObj;var list=tp.list;var settings=tp.settings;if(list&&list.length){list.remove();tp.list=null}if(settings.useSelect){list=$("<select></select>",{class:"ui-em_timepicker-select"});if(self.attr("name")){list.attr("name","ui-em_timepicker-"+self.attr("name"))}var wrapped_list=list}else{list=$("<ul></ul>",{class:"ui-em_timepicker-list"});var wrapped_list=$("<div></div>",{class:"ui-em_timepicker-wrapper",tabindex:-1});wrapped_list.css({display:"none",position:"absolute"}).append(list)}if(settings.noneOption){if(settings.noneOption===true){settings.noneOption=settings.useSelect?"Time...":"None"}if($.isArray(settings.noneOption)){for(var i in settings.noneOption){if(parseInt(i,10)==i){var noneElement=tp._generateNoneElement(settings.noneOption[i],settings.useSelect);list.append(noneElement)}}}else{var noneElement=tp._generateNoneElement(settings.noneOption,settings.useSelect);list.append(noneElement)}}if(settings.className){wrapped_list.addClass(settings.className)}if((settings.minTime!==null||settings.durationTime!==null)&&settings.showDuration){var stepval=typeof settings.step=="function"?"function":settings.step;wrapped_list.addClass("ui-em_timepicker-with-duration");wrapped_list.addClass("ui-em_timepicker-step-"+settings.step)}var durStart=settings.minTime;if(typeof settings.durationTime==="function"){durStart=tp.time2int(settings.durationTime())}else if(settings.durationTime!==null){durStart=settings.durationTime}var start=settings.minTime!==null?settings.minTime:0;var end=settings.maxTime!==null?settings.maxTime:start+ONE_DAY-1;if(end<start){end+=ONE_DAY}if(end===ONE_DAY-1&&$.type(settings.timeFormat)==="string"&&settings.show2400){end=ONE_DAY}var dr=settings.disableTimeRanges;var drCur=0;var drLen=dr.length;var stepFunc=settings.step;if(typeof stepFunc!="function"){stepFunc=function stepFunc(){return settings.step}}for(var i=start,j=0;i<=end;j++,i+=stepFunc(j)*60){var timeInt=i;var timeString=tp._int2time(timeInt);if(settings.useSelect){var row=$("<option></option>",{value:timeString});row.text(timeString)}else{var row=$("<li></li>");row.addClass(timeInt%ONE_DAY<ONE_DAY/2?"ui-em_timepicker-am":"ui-em_timepicker-pm");row.attr("data-time",roundingFunction(timeInt,settings));row.text(timeString)}if((settings.minTime!==null||settings.durationTime!==null)&&settings.showDuration){var durationString=tp._int2duration(i-durStart,settings.step);if(settings.useSelect){row.text(row.text()+" ("+durationString+")")}else{var duration=$("<span></span>",{class:"ui-em_timepicker-duration"});duration.text(" ("+durationString+")");row.append(duration)}}if(drCur<drLen){if(timeInt>=dr[drCur][1]){drCur+=1}if(dr[drCur]&&timeInt>=dr[drCur][0]&&timeInt<dr[drCur][1]){if(settings.useSelect){row.prop("disabled",true)}else{row.addClass("ui-em_timepicker-disabled")}}}list.append(row)}wrapped_list.data("em_timepicker-input",self);tp.list=wrapped_list;if(settings.useSelect){if(self.val()){list.val(tp._roundAndFormatTime(tp.time2int(self.val())))}list.on("focus",function(){$(this).data("em_timepicker-input").trigger("showTimepicker")});list.on("blur",function(){$(this).data("em_timepicker-input").trigger("hideTimepicker")});list.on("change",function(){tp._setTimeValue($(this).val(),"select")});tp._setTimeValue(list.val(),"initial");self.hide().after(list)}else{var appendTo=settings.appendTo;if(typeof appendTo==="string"){appendTo=$(appendTo)}else if(typeof appendTo==="function"){appendTo=appendTo(self)}appendTo.append(wrapped_list);tp._setSelected();list.on("mousedown click","li",function(e){self.off("focus.em_timepicker");self.on("focus.em_timepicker-ie-hack",function(){self.off("focus.em_timepicker-ie-hack");self.on("focus.em_timepicker",methods.show)});if(!tp._hideKeyboard()){self[0].focus()}list.find("li").removeClass("ui-em_timepicker-selected");$(this).addClass("ui-em_timepicker-selected");if(tp._selectValue()){self.trigger("hideTimepicker");list.on("mouseup.em_timepicker click.em_timepicker","li",function(e){list.off("mouseup.em_timepicker click.em_timepicker");wrapped_list.hide()})}})}}function _closeHandler(e){if(e.target==window){return}var target=$(e.target);if(target.closest(".ui-em_timepicker-input").length||target.closest(".ui-em_timepicker-wrapper").length){return}Timepicker.hideAll();$(document).off(".ui-em_timepicker");$(window).off(".ui-em_timepicker")}function _keydownhandler(e){var self=$(this);var tp=self[0].em_timepickerObj;var list=tp.list;if(!list||!Timepicker.isVisible(list)){if(e.keyCode==40){methods.show.call(self.get(0));list=tp.list;if(!tp._hideKeyboard()){self.trigger("focus")}}else{return true}}switch(e.keyCode){case 13:if(tp._selectValue()){tp._formatValue({type:"change"});tp.hideMe()}e.preventDefault();return false;case 38:var selected=list.find(".ui-em_timepicker-selected");if(!selected.length){list.find("li").each(function(i,obj){if($(obj).position().top>0){selected=$(obj);return false}});selected.addClass("ui-em_timepicker-selected")}else if(!selected.is(":first-child")){selected.removeClass("ui-em_timepicker-selected");selected.prev().addClass("ui-em_timepicker-selected");if(selected.prev().position().top<selected.outerHeight()){list.scrollTop(list.scrollTop()-selected.outerHeight())}}return false;case 40:selected=list.find(".ui-em_timepicker-selected");if(selected.length===0){list.find("li").each(function(i,obj){if($(obj).position().top>0){selected=$(obj);return false}});selected.addClass("ui-em_timepicker-selected")}else if(!selected.is(":last-child")){selected.removeClass("ui-em_timepicker-selected");selected.next().addClass("ui-em_timepicker-selected");if(selected.next().position().top+2*selected.outerHeight()>list.outerHeight()){list.scrollTop(list.scrollTop()+selected.outerHeight())}}return false;case 27:list.find("li").removeClass("ui-em_timepicker-selected");tp.hideMe();break;case 9:tp.hideMe();break;default:return true}}$.fn.em_timepicker=function(method){if(!this.length)return this;if(methods[method]){if(!this.hasClass("ui-em_timepicker-input")){return this}return methods[method].apply(this,Array.prototype.slice.call(arguments,1
4762))}else if(_typeof(method)==="object"||!method){return methods.init.apply(this,arguments)}else{$.error("Method "+method+" does not exist on jQuery.em_timepicker")}};$.fn.em_timepicker.defaults=DEFAULT_SETTINGS})})();
4763
4764/*!
4765 * flatpickr v4.6.13,, @license MIT
vendor: 49,431 bytes, lines 4766-4767
4766 */
4767!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e="undefined"!=typeof globalThis?globalThis:e||self).flatpickr=n()}(this,(function(){"use strict";var e=function(){return(e=Object.assign||function(e){for(var n,t=1,a=arguments.length;t<a;t++)for(var i in n=arguments[t])Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i]);return e}).apply(this,arguments)};function n(){for(var e=0,n=0,t=arguments.length;n<t;n++)e+=arguments[n].length;var a=Array(e),i=0;for(n=0;n<t;n++)for(var o=arguments[n],r=0,l=o.length;r<l;r++,i++)a[i]=o[r];return a}var t=["onChange","onClose","onDayCreate","onDestroy","onKeyDown","onMonthChange","onOpen","onParseConfig","onReady","onValueUpdate","onYearChange","onPreCalendarPosition"],a={_disable:[],allowInput:!1,allowInvalidPreload:!1,altFormat:"F j, Y",altInput:!1,altInputClass:"form-control input",animate:"object"==typeof window&&-1===window.navigator.userAgent.indexOf("MSIE"),ariaDateFormat:"F j, Y",autoFillDefaultTime:!0,clickOpens:!0,closeOnSelect:!0,conjunction:", ",dateFormat:"Y-m-d",defaultHour:12,defaultMinute:0,defaultSeconds:0,disable:[],disableMobile:!1,enableSeconds:!1,enableTime:!1,errorHandler:function(e){return"undefined"!=typeof console&&console.warn(e)},getWeek:function(e){var n=new Date(e.getTime());n.setHours(0,0,0,0),n.setDate(n.getDate()+3-(n.getDay()+6)%7);var t=new Date(n.getFullYear(),0,4);return 1+Math.round(((n.getTime()-t.getTime())/864e5-3+(t.getDay()+6)%7)/7)},hourIncrement:1,ignoredFocusElements:[],inline:!1,locale:"default",minuteIncrement:5,mode:"single",monthSelectorType:"dropdown",nextArrow:"<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M13.207 8.472l-7.854 7.854-0.707-0.707 7.146-7.146-7.146-7.148 0.707-0.707 7.854 7.854z' /></svg>",noCalendar:!1,now:new Date,onChange:[],onClose:[],onDayCreate:[],onDestroy:[],onKeyDown:[],onMonthChange:[],onOpen:[],onParseConfig:[],onReady:[],onValueUpdate:[],onYearChange:[],onPreCalendarPosition:[],plugins:[],position:"auto",positionElement:void 0,prevArrow:"<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M5.207 8.471l7.146 7.147-0.707 0.707-7.853-7.854 7.854-7.853 0.707 0.707-7.147 7.146z' /></svg>",shorthandCurrentMonth:!1,showMonths:1,static:!1,time_24hr:!1,weekNumbers:!1,wrap:!1},i={weekdays:{shorthand:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],longhand:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},months:{shorthand:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],longhand:["January","February","March","April","May","June","July","August","September","October","November","December"]},daysInMonth:[31,28,31,30,31,30,31,31,30,31,30,31],firstDayOfWeek:0,ordinal:function(e){var n=e%100;if(n>3&&n<21)return"th";switch(n%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}},rangeSeparator:" to ",weekAbbreviation:"Wk",scrollTitle:"Scroll to increment",toggleTitle:"Click to toggle",amPM:["AM","PM"],yearAriaLabel:"Year",monthAriaLabel:"Month",hourAriaLabel:"Hour",minuteAriaLabel:"Minute",time_24hr:!1},o=function(e,n){return void 0===n&&(n=2),("000"+e).slice(-1*n)},r=function(e){return!0===e?1:0};function l(e,n){var t;return function(){var a=this,i=arguments;clearTimeout(t),t=setTimeout((function(){return e.apply(a,i)}),n)}}var c=function(e){return e instanceof Array?e:[e]};function s(e,n,t){if(!0===t)return e.classList.add(n);e.classList.remove(n)}function d(e,n,t){var a=window.document.createElement(e);return n=n||"",t=t||"",a.className=n,void 0!==t&&(a.textContent=t),a}function u(e){for(;e.firstChild;)e.removeChild(e.firstChild)}function f(e,n){return n(e)?e:e.parentNode?f(e.parentNode,n):void 0}function m(e,n){var t=d("div","numInputWrapper"),a=d("input","numInput "+e),i=d("span","arrowUp"),o=d("span","arrowDown");if(-1===navigator.userAgent.indexOf("MSIE 9.0")?a.type="number":(a.type="text",a.pattern="\\d*"),void 0!==n)for(var r in n)a.setAttribute(r,n[r]);return t.appendChild(a),t.appendChild(i),t.appendChild(o),t}function g(e){try{return"function"==typeof e.composedPath?e.composedPath()[0]:e.target}catch(n){return e.target}}var p=function(){},h=function(e,n,t){return t.months[n?"shorthand":"longhand"][e]},v={D:p,F:function(e,n,t){e.setMonth(t.months.longhand.indexOf(n))},G:function(e,n){e.setHours((e.getHours()>=12?12:0)+parseFloat(n))},H:function(e,n){e.setHours(parseFloat(n))},J:function(e,n){e.setDate(parseFloat(n))},K:function(e,n,t){e.setHours(e.getHours()%12+12*r(new RegExp(t.amPM[1],"i").test(n)))},M:function(e,n,t){e.setMonth(t.months.shorthand.indexOf(n))},S:function(e,n){e.setSeconds(parseFloat(n))},U:function(e,n){return new Date(1e3*parseFloat(n))},W:function(e,n,t){var a=parseInt(n),i=new Date(e.getFullYear(),0,2+7*(a-1),0,0,0,0);return i.setDate(i.getDate()-i.getDay()+t.firstDayOfWeek),i},Y:function(e,n){e.setFullYear(parseFloat(n))},Z:function(e,n){return new Date(n)},d:function(e,n){e.setDate(parseFloat(n))},h:function(e,n){e.setHours((e.getHours()>=12?12:0)+parseFloat(n))},i:function(e,n){e.setMinutes(parseFloat(n))},j:function(e,n){e.setDate(parseFloat(n))},l:p,m:function(e,n){e.setMonth(parseFloat(n)-1)},n:function(e,n){e.setMonth(parseFloat(n)-1)},s:function(e,n){e.setSeconds(parseFloat(n))},u:function(e,n){return new Date(parseFloat(n))},w:p,y:function(e,n){e.setFullYear(2e3+parseFloat(n))}},D={D:"",F:"",G:"(\\d\\d|\\d)",H:"(\\d\\d|\\d)",J:"(\\d\\d|\\d)\\w+",K:"",M:"",S:"(\\d\\d|\\d)",U:"(.+)",W:"(\\d\\d|\\d)",Y:"(\\d{4})",Z:"(.+)",d:"(\\d\\d|\\d)",h:"(\\d\\d|\\d)",i:"(\\d\\d|\\d)",j:"(\\d\\d|\\d)",l:"",m:"(\\d\\d|\\d)",n:"(\\d\\d|\\d)",s:"(\\d\\d|\\d)",u:"(.+)",w:"(\\d\\d|\\d)",y:"(\\d{2})"},w={Z:function(e){return e.toISOString()},D:function(e,n,t){return n.weekdays.shorthand[w.w(e,n,t)]},F:function(e,n,t){return h(w.n(e,n,t)-1,!1,n)},G:function(e,n,t){return o(w.h(e,n,t))},H:function(e){return o(e.getHours())},J:function(e,n){return void 0!==n.ordinal?e.getDate()+n.ordinal(e.getDate()):e.getDate()},K:function(e,n){return n.amPM[r(e.getHours()>11)]},M:function(e,n){return h(e.getMonth(),!0,n)},S:function(e){return o(e.getSeconds())},U:function(e){return e.getTime()/1e3},W:function(e,n,t){return t.getWeek(e)},Y:function(e){return o(e.getFullYear(),4)},d:function(e){return o(e.getDate())},h:function(e){return e.getHours()%12?e.getHours()%12:12},i:function(e){return o(e.getMinutes())},j:function(e){return e.getDate()},l:function(e,n){return n.weekdays.longhand[e.getDay()]},m:function(e){return o(e.getMonth()+1)},n:function(e){return e.getMonth()+1},s:function(e){return e.getSeconds()},u:function(e){return e.getTime()},w:function(e){return e.getDay()},y:function(e){return String(e.getFullYear()).substring(2)}},b=function(e){var n=e.config,t=void 0===n?a:n,o=e.l10n,r=void 0===o?i:o,l=e.isMobile,c=void 0!==l&&l;return function(e,n,a){var i=a||r;return void 0===t.formatDate||c?n.split("").map((function(n,a,o){return w[n]&&"\\"!==o[a-1]?w[n](e,i,t):"\\"!==n?n:""})).join(""):t.formatDate(e,n,i)}},C=function(e){var n=e.config,t=void 0===n?a:n,o=e.l10n,r=void 0===o?i:o;return function(e,n,i,o){if(0===e||e){var l,c=o||r,s=e;if(e instanceof Date)l=new Date(e.getTime());else if("string"!=typeof e&&void 0!==e.toFixed)l=new Date(e);else if("string"==typeof e){var d=n||(t||a).dateFormat,u=String(e).trim();if("today"===u)l=new Date,i=!0;else if(t&&t.parseDate)l=t.parseDate(e,d);else if(/Z$/.test(u)||/GMT$/.test(u))l=new Date(e);else{for(var f=void 0,m=[],g=0,p=0,h="";g<d.length;g++){var w=d[g],b="\\"===w,C="\\"===d[g-1]||b;if(D[w]&&!C){h+=D[w];var M=new RegExp(h).exec(e);M&&(f=!0)&&m["Y"!==w?"push":"unshift"]({fn:v[w],val:M[++p]})}else b||(h+=".")}l=t&&t.noCalendar?new Date((new Date).setHours(0,0,0,0)):new Date((new Date).getFullYear(),0,1,0,0,0,0),m.forEach((function(e){var n=e.fn,t=e.val;return l=n(l,t,c)||l})),l=f?l:void 0}}if(l instanceof Date&&!isNaN(l.getTime()))return!0===i&&l.setHours(0,0,0,0),l;t.errorHandler(new Error("Invalid date provided: "+s))}}};function M(e,n,t){return void 0===t&&(t=!0),!1!==t?new Date(e.getTime()).setHours(0,0,0,0)-new Date(n.getTime()).setHours(0,0,0,0):e.getTime()-n.getTime()}var y=function(e,n,t){return 3600*e+60*n+t},x=864e5;function E(e){var n=e.defaultHour,t=e.defaultMinute,a=e.defaultSeconds;if(void 0!==e.minDate){var i=e.minDate.getHours(),o=e.minDate.getMinutes(),r=e.minDate.getSeconds();n<i&&(n=i),n===i&&t<o&&(t=o),n===i&&t===o&&a<r&&(a=e.minDate.getSeconds())}if(void 0!==e.maxDate){var l=e.maxDate.getHours(),c=e.maxDate.getMinutes();(n=Math.min(n,l))===l&&(t=Math.min(c,t)),n===l&&t===c&&(a=e.maxDate.getSeconds())}return{hours:n,minutes:t,seconds:a}}"function"!=typeof Object.assign&&(Object.assign=function(e){for(var n=[],t=1;t<arguments.length;t++)n[t-1]=arguments[t];if(!e)throw TypeError("Cannot convert undefined or null to object");for(var a=function(n){n&&Object.keys(n).forEach((function(t){return e[t]=n[t]}))},i=0,o=n;i<o.length;i++){var r=o[i];a(r)}return e});function k(p,v){var w={config:e(e({},a),I.defaultConfig),l10n:i};function k(){var e;return(null===(e=w.calendarContainer)||void 0===e?void 0:e.getRootNode()).activeElement||document.activeElement}function T(e){return e.bind(w)}function S(){var e=w.config;!1===e.weekNumbers&&1===e.showMonths||!0!==e.noCalendar&&window.requestAnimationFrame((function(){if(void 0!==w.calendarContainer&&(w.calendarContainer.style.visibility="hidden",w.calendarContainer.style.display="block"),void 0!==w.daysContainer){var n=(w.days.offsetWidth+1)*e.showMonths;w.daysContainer.style.width=n+"px",w.calendarContainer.style.width=n+(void 0!==w.weekWrapper?w.weekWrapper.offsetWidth:0)+"px",w.calendarContainer.style.removeProperty("visibility"),w.calendarContainer.style.removeProperty("display")}}))}function _(e){if(0===w.selectedDates.length){var n=void 0===w.config.minDate||M(new Date,w.config.minDate)>=0?new Date:new Date(w.config.minDate.getTime()),t=E(w.config);n.setHours(t.hours,t.minutes,t.seconds,n.getMilliseconds()),w.selectedDates=[n],w.latestSelectedDateObj=n}void 0!==e&&"blur"!==e.type&&function(e){e.preventDefault();var n="keydown"===e.type,t=g(e),a=t;void 0!==w.amPM&&t===w.amPM&&(w.amPM.textContent=w.l10n.amPM[r(w.amPM.textContent===w.l10n.amPM[0])]);var i=parseFloat(a.getAttribute("min")),l=parseFloat(a.getAttribute("max")),c=parseFloat(a.getAttribute("step")),s=parseInt(a.value,10),d=e.delta||(n?38===e.which?1:-1:0),u=s+c*d;if(void 0!==a.value&&2===a.value.length){var f=a===w.hourElement,m=a===w.minuteElement;u<i?(u=l+u+r(!f)+(r(f)&&r(!w.amPM)),m&&L(void 0,-1,w.hourElement)):u>l&&(u=a===w.hourElement?u-l-r(!w.amPM):i,m&&L(void 0,1,w.hourElement)),w.amPM&&f&&(1===c?u+s===23:Math.abs(u-s)>c)&&(w.amPM.textContent=w.l10n.amPM[r(w.amPM.textContent===w.l10n.amPM[0])]),a.value=o(u)}}(e);var a=w._input.value;O(),ye(),w._input.value!==a&&w._debouncedChange()}function O(){if(void 0!==w.hourElement&&void 0!==w.minuteElement){var e,n,t=(parseInt(w.hourElement.value.slice(-2),10)||0)%24,a=(parseInt(w.minuteElement.value,10)||0)%60,i=void 0!==w.secondElement?(parseInt(w.secondElement.value,10)||0)%60:0;void 0!==w.amPM&&(e=t,n=w.amPM.textContent,t=e%12+12*r(n===w.l10n.amPM[1]));var o=void 0!==w.config.minTime||w.config.minDate&&w.minDateHasTime&&w.latestSelectedDateObj&&0===M(w.latestSelectedDateObj,w.config.minDate,!0),l=void 0!==w.config.maxTime||w.config.maxDate&&w.maxDateHasTime&&w.latestSelectedDateObj&&0===M(w.latestSelectedDateObj,w.config.maxDate,!0);if(void 0!==w.config.maxTime&&void 0!==w.config.minTime&&w.config.minTime>w.config.maxTime){var c=y(w.config.minTime.getHours(),w.config.minTime.getMinutes(),w.config.minTime.getSeconds()),s=y(w.config.maxTime.getHours(),w.config.maxTime.getMinutes(),w.config.maxTime.getSeconds()),d=y(t,a,i);if(d>s&&d<c){var u=function(e){var n=Math.floor(e/3600),t=(e-3600*n)/60;return[n,t,e-3600*n-60*t]}(c);t=u[0],a=u[1],i=u[2]}}else{if(l){var f=void 0!==w.config.maxTime?w.config.maxTime:w.config.maxDate;(t=Math.min(t,f.getHours()))===f.getHours()&&(a=Math.min(a,f.getMinutes())),a===f.getMinutes()&&(i=Math.min(i,f.getSeconds()))}if(o){var m=void 0!==w.config.minTime?w.config.minTime:w.config.minDate;(t=Math.max(t,m.getHours()))===m.getHours()&&a<m.getMinutes()&&(a=m.getMinutes()),a===m.getMinutes()&&(i=Math.max(i,m.getSeconds()))}}A(t,a,i)}}function F(e){var n=e||w.latestSelectedDateObj;n&&n instanceof Date&&A(n.getHours(),n.getMinutes(),n.getSeconds())}function A(e,n,t){void 0!==w.latestSelectedDateObj&&w.latestSelectedDateObj.setHours(e%24,n,t||0,0),w.hourElement&&w.minuteElement&&!w.isMobile&&(w.hourElement.value=o(w.config.time_24hr?e:(12+e)%12+12*r(e%12==0)),w.minuteElement.value=o(n),void 0!==w.amPM&&(w.amPM.textContent=w.l10n.amPM[r(e>=12)]),void 0!==w.secondElement&&(w.secondElement.value=o(t)))}function N(e){var n=g(e),t=parseInt(n.value)+(e.delta||0);(t/1e3>1||"Enter"===e.key&&!/[^\d]/.test(t.toString()))&&ee(t)}function P(e,n,t,a){return n instanceof Array?n.forEach((function(n){return P(e,n,t,a)})):e instanceof Array?e.forEach((function(e){return P(e,n,t,a)})):(e.addEventListener(n,t,a),void w._handlers.push({remove:function(){return e.removeEventListener(n,t,a)}}))}function Y(){De("onChange")}function j(e,n){var t=void 0!==e?w.parseDate(e):w.latestSelectedDateObj||(w.config.minDate&&w.config.minDate>w.now?w.config.minDate:w.config.maxDate&&w.config.maxDate<w.now?w.config.maxDate:w.now),a=w.currentYear,i=w.currentMonth;try{void 0!==t&&(w.currentYear=t.getFullYear(),w.currentMonth=t.getMonth())}catch(e){e.message="Invalid date supplied: "+t,w.config.errorHandler(e)}n&&w.currentYear!==a&&(De("onYearChange"),q()),!n||w.currentYear===a&&w.currentMonth===i||De("onMonthChange"),w.redraw()}function H(e){var n=g(e);~n.className.indexOf("arrow")&&L(e,n.classList.contains("arrowUp")?1:-1)}function L(e,n,t){var a=e&&g(e),i=t||a&&a.parentNode&&a.parentNode.firstChild,o=we("increment");o.delta=n,i&&i.dispatchEvent(o)}function R(e,n,t,a){var i=ne(n,!0),o=d("span",e,n.getDate().toString());return o.dateObj=n,o.$i=a,o.setAttribute("aria-label",w.formatDate(n,w.config.ariaDateFormat)),-1===e.indexOf("hidden")&&0===M(n,w.now)&&(w.todayDateElem=o,o.classList.add("today"),o.setAttribute("aria-current","date")),i?(o.tabIndex=-1,be(n)&&(o.classList.add("selected"),w.selectedDateElem=o,"range"===w.config.mode&&(s(o,"startRange",w.selectedDates[0]&&0===M(n,w.selectedDates[0],!0)),s(o,"endRange",w.selectedDates[1]&&0===M(n,w.selectedDates[1],!0)),"nextMonthDay"===e&&o.classList.add("inRange")))):o.classList.add("flatpickr-disabled"),"range"===w.config.mode&&function(e){return!("range"!==w.config.mode||w.selectedDates.length<2)&&(M(e,w.selectedDates[0])>=0&&M(e,w.selectedDates[1])<=0)}(n)&&!be(n)&&o.classList.add("inRange"),w.weekNumbers&&1===w.config.showMonths&&"prevMonthDay"!==e&&a%7==6&&w.weekNumbers.insertAdjacentHTML("beforeend","<span class='flatpickr-day'>"+w.config.getWeek(n)+"</span>"),De("onDayCreate",o),o}function W(e){e.focus(),"range"===w.config.mode&&oe(e)}function B(e){for(var n=e>0?0:w.config.showMonths-1,t=e>0?w.config.showMonths:-1,a=n;a!=t;a+=e)for(var i=w.daysContainer.children[a],o=e>0?0:i.children.length-1,r=e>0?i.children.length:-1,l=o;l!=r;l+=e){var c=i.children[l];if(-1===c.className.indexOf("hidden")&&ne(c.dateObj))return c}}function J(e,n){var t=k(),a=te(t||document.body),i=void 0!==e?e:a?t:void 0!==w.selectedDateElem&&te(w.selectedDateElem)?w.selectedDateElem:void 0!==w.todayDateElem&&te(w.todayDateElem)?w.todayDateElem:B(n>0?1:-1);void 0===i?w._input.focus():a?function(e,n){for(var t=-1===e.className.indexOf("Month")?e.dateObj.getMonth():w.currentMonth,a=n>0?w.config.showMonths:-1,i=n>0?1:-1,o=t-w.currentMonth;o!=a;o+=i)for(var r=w.daysContainer.children[o],l=t-w.currentMonth===o?e.$i+n:n<0?r.children.length-1:0,c=r.children.length,s=l;s>=0&&s<c&&s!=(n>0?c:-1);s+=i){var d=r.children[s];if(-1===d.className.indexOf("hidden")&&ne(d.dateObj)&&Math.abs(e.$i-s)>=Math.abs(n))return W(d)}w.changeMonth(i),J(B(i),0)}(i,n):W(i)}function K(e,n){for(var t=(new Date(e,n,1).getDay()-w.l10n.firstDayOfWeek+7)%7,a=w.utils.getDaysInMonth((n-1+12)%12,e),i=w.utils.getDaysInMonth(n,e),o=window.document.createDocumentFragment(),r=w.config.showMonths>1,l=r?"prevMonthDay hidden":"prevMonthDay",c=r?"nextMonthDay hidden":"nextMonthDay",s=a+1-t,u=0;s<=a;s++,u++)o.appendChild(R("flatpickr-day "+l,new Date(e,n-1,s),0,u));for(s=1;s<=i;s++,u++)o.appendChild(R("flatpickr-day",new Date(e,n,s),0,u));for(var f=i+1;f<=42-t&&(1===w.config.showMonths||u%7!=0);f++,u++)o.appendChild(R("flatpickr-day "+c,new Date(e,n+1,f%i),0,u));var m=d("div","dayContainer");return m.appendChild(o),m}function U(){if(void 0!==w.daysContainer){u(w.daysContainer),w.weekNumbers&&u(w.weekNumbers);for(var e=document.createDocumentFragment(),n=0;n<w.config.showMonths;n++){var t=new Date(w.currentYear,w.currentMonth,1);t.setMonth(w.currentMonth+n),e.appendChild(K(t.getFullYear(),t.getMonth()))}w.daysContainer.appendChild(e),w.days=w.daysContainer.firstChild,"range"===w.config.mode&&1===w.selectedDates.length&&oe()}}function q(){if(!(w.config.showMonths>1||"dropdown"!==w.config.monthSelectorType)){var e=function(e){return!(void 0!==w.config.minDate&&w.currentYear===w.config.minDate.getFullYear()&&e<w.config.minDate.getMonth())&&!(void 0!==w.config.maxDate&&w.currentYear===w.config.maxDate.getFullYear()&&e>w.config.maxDate.getMonth())};w.monthsDropdownContainer.tabIndex=-1,w.monthsDropdownContainer.innerHTML="";for(var n=0;n<12;n++)if(e(n)){var t=d("option","flatpickr-monthDropdown-month");t.value=new Date(w.currentYear,n).getMonth().toString(),t.textContent=h(n,w.config.shorthandCurrentMonth,w.l10n),t.tabIndex=-1,w.currentMonth===n&&(t.selected=!0),w.monthsDropdownContainer.appendChild(t)}}}function $(){var e,n=d("div","flatpickr-month"),t=window.document.createDocumentFragment();w.config.showMonths>1||"static"===w.config.monthSelectorType?e=d("span","cur-month"):(w.monthsDropdownContainer=d("select","flatpickr-monthDropdown-months"),w.monthsDropdownContainer.setAttribute("aria-label",w.l10n.monthAriaLabel),P(w.monthsDropdownContainer,"change",(function(e){var n=g(e),t=parseInt(n.value,10);w.changeMonth(t-w.currentMonth),De("onMonthChange")})),q(),e=w.monthsDropdownContainer);var a=m("cur-year",{tabindex:"-1"}),i=a.getElementsByTagName("input")[0];i.setAttribute("aria-label",w.l10n.yearAriaLabel),w.config.minDate&&i.setAttribute("min",w.config.minDate.getFullYear().toString()),w.config.maxDate&&(i.setAttribute("max",w.config.maxDate.getFullYear().toString()),i.disabled=!!w.config.minDate&&w.config.minDate.getFullYear()===w.config.maxDate.getFullYear());var o=d("div","flatpickr-current-month");return o.appendChild(e),o.appendChild(a),t.appendChild(o),n.appendChild(t),{container:n,yearElement:i,monthElement:e}}function V(){u(w.monthNav),w.monthNav.appendChild(w.prevMonthNav),w.config.showMonths&&(w.yearElements=[],w.monthElements=[]);for(var e=w.config.showMonths;e--;){var n=$();w.yearElements.push(n.yearElement),w.monthElements.push(n.monthElement),w.monthNav.appendChild(n.container)}w.monthNav.appendChild(w.nextMonthNav)}function z(){w.weekdayContainer?u(w.weekdayContainer):w.weekdayContainer=d("div","flatpickr-weekdays");for(var e=w.config.showMonths;e--;){var n=d("div","flatpickr-weekdaycontainer");w.weekdayContainer.appendChild(n)}return G(),w.weekdayContainer}function G(){if(w.weekdayContainer){var e=w.l10n.firstDayOfWeek,t=n(w.l10n.weekdays.shorthand);e>0&&e<t.length&&(t=n(t.splice(e,t.length),t.splice(0,e)));for(var a=w.config.showMonths;a--;)w.weekdayContainer.children[a].innerHTML="\n      <span class='flatpickr-weekday'>\n        "+t.join("</span><span class='flatpickr-weekday'>")+"\n      </span>\n      "}}function Z(e,n){void 0===n&&(n=!0);var t=n?e:e-w.currentMonth;t<0&&!0===w._hidePrevMonthArrow||t>0&&!0===w._hideNextMonthArrow||(w.currentMonth+=t,(w.currentMonth<0||w.currentMonth>11)&&(w.currentYear+=w.currentMonth>11?1:-1,w.currentMonth=(w.currentMonth+12)%12,De("onYearChange"),q()),U(),De("onMonthChange"),Ce())}function Q(e){return w.calendarContainer.contains(e)}function X(e){if(w.isOpen&&!w.config.inline){var n=g(e),t=Q(n),a=!(n===w.input||n===w.altInput||w.element.contains(n)||e.path&&e.path.indexOf&&(~e.path.indexOf(w.input)||~e.path.indexOf(w.altInput)))&&!t&&!Q(e.relatedTarget),i=!w.config.ignoredFocusElements.some((function(e){return e.contains(n)}));a&&i&&(w.config.allowInput&&w.setDate(w._input.value,!1,w.config.altInput?w.config.altFormat:w.config.dateFormat),void 0!==w.timeContainer&&void 0!==w.minuteElement&&void 0!==w.hourElement&&""!==w.input.value&&void 0!==w.input.value&&_(),w.close(),w.config&&"range"===w.config.mode&&1===w.selectedDates.length&&w.clear(!1))}}function ee(e){if(!(!e||w.config.minDate&&e<w.config.minDate.getFullYear()||w.config.maxDate&&e>w.config.maxDate.getFullYear())){var n=e,t=w.currentYear!==n;w.currentYear=n||w.currentYear,w.config.maxDate&&w.currentYear===w.config.maxDate.getFullYear()?w.currentMonth=Math.min(w.config.maxDate.getMonth(),w.currentMonth):w.config.minDate&&w.currentYear===w.config.minDate.getFullYear()&&(w.currentMonth=Math.max(w.config.minDate.getMonth(),w.currentMonth)),t&&(w.redraw(),De("onYearChange"),q())}}function ne(e,n){var t;void 0===n&&(n=!0);var a=w.parseDate(e,void 0,n);if(w.config.minDate&&a&&M(a,w.config.minDate,void 0!==n?n:!w.minDateHasTime)<0||w.config.maxDate&&a&&M(a,w.config.maxDate,void 0!==n?n:!w.maxDateHasTime)>0)return!1;if(!w.config.enable&&0===w.config.disable.length)return!0;if(void 0===a)return!1;for(var i=!!w.config.enable,o=null!==(t=w.config.enable)&&void 0!==t?t:w.config.disable,r=0,l=void 0;r<o.length;r++){if("function"==typeof(l=o[r])&&l(a))return i;if(l instanceof Date&&void 0!==a&&l.getTime()===a.getTime())return i;if("string"==typeof l){var c=w.parseDate(l,void 0,!0);return c&&c.getTime()===a.getTime()?i:!i}if("object"==typeof l&&void 0!==a&&l.from&&l.to&&a.getTime()>=l.from.getTime()&&a.getTime()<=l.to.getTime())return i}return!i}function te(e){return void 0!==w.daysContainer&&(-1===e.className.indexOf("hidden")&&-1===e.className.indexOf("flatpickr-disabled")&&w.daysContainer.contains(e))}function ae(e){var n=e.target===w._input,t=w._input.value.trimEnd()!==Me();!n||!t||e.relatedTarget&&Q(e.relatedTarget)||w.setDate(w._input.value,!0,e.target===w.altInput?w.config.altFormat:w.config.dateFormat)}function ie(e){var n=g(e),t=w.config.wrap?p.contains(n):n===w._input,a=w.config.allowInput,i=w.isOpen&&(!a||!t),o=w.config.inline&&t&&!a;if(13===e.keyCode&&t){if(a)return w.setDate(w._input.value,!0,n===w.altInput?w.config.altFormat:w.config.dateFormat),w.close(),n.blur();w.open()}else if(Q(n)||i||o){var r=!!w.timeContainer&&w.timeContainer.contains(n);switch(e.keyCode){case 13:r?(e.preventDefault(),_(),fe()):me(e);break;case 27:e.preventDefault(),fe();break;case 8:case 46:t&&!w.config.allowInput&&(e.preventDefault(),w.clear());break;case 37:case 39:if(r||t)w.hourElement&&w.hourElement.focus();else{e.preventDefault();var l=k();if(void 0!==w.daysContainer&&(!1===a||l&&te(l))){var c=39===e.keyCode?1:-1;e.ctrlKey?(e.stopPropagation(),Z(c),J(B(1),0)):J(void 0,c)}}break;case 38:case 40:e.preventDefault();var s=40===e.keyCode?1:-1;w.daysContainer&&void 0!==n.$i||n===w.input||n===w.altInput?e.ctrlKey?(e.stopPropagation(),ee(w.currentYear-s),J(B(1),0)):r||J(void 0,7*s):n===w.currentYearElement?ee(w.currentYear-s):w.config.enableTime&&(!r&&w.hourElement&&w.hourElement.focus(),_(e),w._debouncedChange());break;case 9:if(r){var d=[w.hourElement,w.minuteElement,w.secondElement,w.amPM].concat(w.pluginElements).filter((function(e){return e})),u=d.indexOf(n);if(-1!==u){var f=d[u+(e.shiftKey?-1:1)];e.preventDefault(),(f||w._input).focus()}}else!w.config.noCalendar&&w.daysContainer&&w.daysContainer.contains(n)&&e.shiftKey&&(e.preventDefault(),w._input.focus())}}if(void 0!==w.amPM&&n===w.amPM)switch(e.key){case w.l10n.amPM[0].charAt(0):case w.l10n.amPM[0].charAt(0).toLowerCase():w.amPM.textContent=w.l10n.amPM[0],O(),ye();break;case w.l10n.amPM[1].charAt(0):case w.l10n.amPM[1].charAt(0).toLowerCase():w.amPM.textContent=w.l10n.amPM[1],O(),ye()}(t||Q(n))&&De("onKeyDown",e)}function oe(e,n){if(void 0===n&&(n="flatpickr-day"),1===w.selectedDates.length&&(!e||e.classList.contains(n)&&!e.classList.contains("flatpickr-disabled"))){for(var t=e?e.dateObj.getTime():w.days.firstElementChild.dateObj.getTime(),a=w.parseDate(w.selectedDates[0],void 0,!0).getTime(),i=Math.min(t,w.selectedDates[0].getTime()),o=Math.max(t,w.selectedDates[0].getTime()),r=!1,l=0,c=0,s=i;s<o;s+=x)ne(new Date(s),!0)||(r=r||s>i&&s<o,s<a&&(!l||s>l)?l=s:s>a&&(!c||s<c)&&(c=s));Array.from(w.rContainer.querySelectorAll("*:nth-child(-n+"+w.config.showMonths+") > ."+n)).forEach((function(n){var i,o,s,d=n.dateObj.getTime(),u=l>0&&d<l||c>0&&d>c;if(u)return n.classList.add("notAllowed"),void["inRange","startRange","endRange"].forEach((function(e){n.classList.remove(e)}));r&&!u||(["startRange","inRange","endRange","notAllowed"].forEach((function(e){n.classList.remove(e)})),void 0!==e&&(e.classList.add(t<=w.selectedDates[0].getTime()?"startRange":"endRange"),a<t&&d===a?n.classList.add("startRange"):a>t&&d===a&&n.classList.add("endRange"),d>=l&&(0===c||d<=c)&&(o=a,s=t,(i=d)>Math.min(o,s)&&i<Math.max(o,s))&&n.classList.add("inRange")))}))}}function re(){!w.isOpen||w.config.static||w.config.inline||de()}function le(e){return function(n){var t=w.config["_"+e+"Date"]=w.parseDate(n,w.config.dateFormat),a=w.config["_"+("min"===e?"max":"min")+"Date"];void 0!==t&&(w["min"===e?"minDateHasTime":"maxDateHasTime"]=t.getHours()>0||t.getMinutes()>0||t.getSeconds()>0),w.selectedDates&&(w.selectedDates=w.selectedDates.filter((function(e){return ne(e)})),w.selectedDates.length||"min"!==e||F(t),ye()),w.daysContainer&&(ue(),void 0!==t?w.currentYearElement[e]=t.getFullYear().toString():w.currentYearElement.removeAttribute(e),w.currentYearElement.disabled=!!a&&void 0!==t&&a.getFullYear()===t.getFullYear())}}function ce(){return w.config.wrap?p.querySelector("[data-input]"):p}function se(){"object"!=typeof w.config.locale&&void 0===I.l10ns[w.config.locale]&&w.config.errorHandler(new Error("flatpickr: invalid locale "+w.config.locale)),w.l10n=e(e({},I.l10ns.default),"object"==typeof w.config.locale?w.config.locale:"default"!==w.config.locale?I.l10ns[w.config.locale]:void 0),D.D="("+w.l10n.weekdays.shorthand.join("|")+")",D.l="("+w.l10n.weekdays.longhand.join("|")+")",D.M="("+w.l10n.months.shorthand.join("|")+")",D.F="("+w.l10n.months.longhand.join("|")+")",D.K="("+w.l10n.amPM[0]+"|"+w.l10n.amPM[1]+"|"+w.l10n.amPM[0].toLowerCase()+"|"+w.l10n.amPM[1].toLowerCase()+")",void 0===e(e({},v),JSON.parse(JSON.stringify(p.dataset||{}))).time_24hr&&void 0===I.defaultConfig.time_24hr&&(w.config.time_24hr=w.l10n.time_24hr),w.formatDate=b(w),w.parseDate=C({config:w.config,l10n:w.l10n})}function de(e){if("function"!=typeof w.config.position){if(void 0!==w.calendarContainer){De("onPreCalendarPosition");var n=e||w._positionElement,t=Array.prototype.reduce.call(w.calendarContainer.children,(function(e,n){return e+n.offsetHeight}),0),a=w.calendarContainer.offsetWidth,i=w.config.position.split(" "),o=i[0],r=i.length>1?i[1]:null,l=n.getBoundingClientRect(),c=window.innerHeight-l.bottom,d="above"===o||"below"!==o&&c<t&&l.top>t,u=window.pageYOffset+l.top+(d?-t-2:n.offsetHeight+2);if(s(w.calendarContainer,"arrowTop",!d),s(w.calendarContainer,"arrowBottom",d),!w.config.inline){var f=window.pageXOffset+l.left,m=!1,g=!1;"center"===r?(f-=(a-l.width)/2,m=!0):"right"===r&&(f-=a-l.width,g=!0),s(w.calendarContainer,"arrowLeft",!m&&!g),s(w.calendarContainer,"arrowCenter",m),s(w.calendarContainer,"arrowRight",g);var p=window.document.body.offsetWidth-(window.pageXOffset+l.right),h=f+a>window.document.body.offsetWidth,v=p+a>window.document.body.offsetWidth;if(s(w.calendarContainer,"rightMost",h),!w.config.static)if(w.calendarContainer.style.top=u+"px",h)if(v){var D=function(){for(var e=null,n=0;n<document.styleSheets.length;n++){var t=document.styleSheets[n];if(t.cssRules){try{t.cssRules}catch(e){continue}e=t;break}}return null!=e?e:(a=document.createElement("style"),document.head.appendChild(a),a.sheet);var a}();if(void 0===D)return;var b=window.document.body.offsetWidth,C=Math.max(0,b/2-a/2),M=D.cssRules.length,y="{left:"+l.left+"px;right:auto;}";s(w.calendarContainer,"rightMost",!1),s(w.calendarContainer,"centerMost",!0),D.insertRule(".flatpickr-calendar.centerMost:before,.flatpickr-calendar.centerMost:after"+y,M),w.calendarContainer.style.left=C+"px",w.calendarContainer.style.right="auto"}else w.calendarContainer.style.left="auto",w.calendarContainer.style.right=p+"px";else w.calendarContainer.style.left=f+"px",w.calendarContainer.style.right="auto"}}}else w.config.position(w,e)}function ue(){w.config.noCalendar||w.isMobile||(q(),Ce(),U())}function fe(){w._input.focus(),-1!==window.navigator.userAgent.indexOf("MSIE")||void 0!==navigator.msMaxTouchPoints?setTimeout(w.close,0):w.close()}function me(e){e.preventDefault(),e.stopPropagation();var n=f(g(e),(function(e){return e.classList&&e.classList.contains("flatpickr-day")&&!e.classList.contains("flatpickr-disabled")&&!e.classList.contains("notAllowed")}));if(void 0!==n){var t=n,a=w.latestSelectedDateObj=new Date(t.dateObj.getTime()),i=(a.getMonth()<w.currentMonth||a.getMonth()>w.currentMonth+w.config.showMonths-1)&&"range"!==w.config.mode;if(w.selectedDateElem=t,"single"===w.config.mode)w.selectedDates=[a];else if("multiple"===w.config.mode){var o=be(a);o?w.selectedDates.splice(parseInt(o),1):w.selectedDates.push(a)}else"range"===w.config.mode&&(2===w.selectedDates.length&&w.clear(!1,!1),w.latestSelectedDateObj=a,w.selectedDates.push(a),0!==M(a,w.selectedDates[0],!0)&&w.selectedDates.sort((function(e,n){return e.getTime()-n.getTime()})));if(O(),i){var r=w.currentYear!==a.getFullYear();w.currentYear=a.getFullYear(),w.currentMonth=a.getMonth(),r&&(De("onYearChange"),q()),De("onMonthChange")}if(Ce(),U(),ye(),i||"range"===w.config.mode||1!==w.config.showMonths?void 0!==w.selectedDateElem&&void 0===w.hourElement&&w.selectedDateElem&&w.selectedDateElem.focus():W(t),void 0!==w.hourElement&&void 0!==w.hourElement&&w.hourElement.focus(),w.config.closeOnSelect){var l="single"===w.config.mode&&!w.config.enableTime,c="range"===w.config.mode&&2===w.selectedDates.length&&!w.config.enableTime;(l||c)&&fe()}Y()}}w.parseDate=C({config:w.config,l10n:w.l10n}),w._handlers=[],w.pluginElements=[],w.loadedPlugins=[],w._bind=P,w._setHoursFromDate=F,w._positionCalendar=de,w.changeMonth=Z,w.changeYear=ee,w.clear=function(e,n){void 0===e&&(e=!0);void 0===n&&(n=!0);w.input.value="",void 0!==w.altInput&&(w.altInput.value="");void 0!==w.mobileInput&&(w.mobileInput.value="");w.selectedDates=[],w.latestSelectedDateObj=void 0,!0===n&&(w.currentYear=w._initialDate.getFullYear(),w.currentMonth=w._initialDate.getMonth());if(!0===w.config.enableTime){var t=E(w.config),a=t.hours,i=t.minutes,o=t.seconds;A(a,i,o)}w.redraw(),e&&De("onChange")},w.close=function(){w.isOpen=!1,w.isMobile||(void 0!==w.calendarContainer&&w.calendarContainer.classList.remove("open"),void 0!==w._input&&w._input.classList.remove("active"));De("onClose")},w.onMouseOver=oe,w._createElement=d,w.createDay=R,w.destroy=function(){void 0!==w.config&&De("onDestroy");for(var e=w._handlers.length;e--;)w._handlers[e].remove();if(w._handlers=[],w.mobileInput)w.mobileInput.parentNode&&w.mobileInput.parentNode.removeChild(w.mobileInput),w.mobileInput=void 0;else if(w.calendarContainer&&w.calendarContainer.parentNode)if(w.config.static&&w.calendarContainer.parentNode){var n=w.calendarContainer.parentNode;if(n.lastChild&&n.removeChild(n.lastChild),n.parentNode){for(;n.firstChild;)n.parentNode.insertBefore(n.firstChild,n);n.parentNode.removeChild(n)}}else w.calendarContainer.parentNode.removeChild(w.calendarContainer);w.altInput&&(w.input.type="text",w.altInput.parentNode&&w.altInput.parentNode.removeChild(w.altInput),delete w.altInput);w.input&&(w.input.type=w.input._type,w.input.classList.remove("flatpickr-input"),w.input.removeAttribute("readonly"));["_showTimeInput","latestSelectedDateObj","_hideNextMonthArrow","_hidePrevMonthArrow","__hideNextMonthArrow","__hidePrevMonthArrow","isMobile","isOpen","selectedDateElem","minDateHasTime","maxDateHasTime","days","daysContainer","_input","_positionElement","innerContainer","rContainer","monthNav","todayDateElem","calendarContainer","weekdayContainer","prevMonthNav","nextMonthNav","monthsDropdownContainer","currentMonthElement","currentYearElement","navigationCurrentMonth","selectedDateElem","config"].forEach((function(e){try{delete w[e]}catch(e){}}))},w.isEnabled=ne,w.jumpToDate=j,w.updateValue=ye,w.open=function(e,n){void 0===n&&(n=w._positionElement);if(!0===w.isMobile){if(e){e.preventDefault();var t=g(e);t&&t.blur()}return void 0!==w.mobileInput&&(w.mobileInput.focus(),w.mobileInput.click()),void De("onOpen")}if(w._input.disabled||w.config.inline)return;var a=w.isOpen;w.isOpen=!0,a||(w.calendarContainer.classList.add("open"),w._input.classList.add("active"),De("onOpen"),de(n));!0===w.config.enableTime&&!0===w.config.noCalendar&&(!1!==w.config.allowInput||void 0!==e&&w.timeContainer.contains(e.relatedTarget)||setTimeout((function(){return w.hourElement.select()}),50))},w.redraw=ue,w.set=function(e,n){if(null!==e&&"object"==typeof e)for(var a in Object.assign(w.config,e),e)void 0!==ge[a]&&ge[a].forEach((function(e){return e()}));else w.config[e]=n,void 0!==ge[e]?ge[e].forEach((function(e){return e()})):t.indexOf(e)>-1&&(w.config[e]=c(n));w.redraw(),ye(!0)},w.setDate=function(e,n,t){void 0===n&&(n=!1);void 0===t&&(t=w.config.dateFormat);if(0!==e&&!e||e instanceof Array&&0===e.length)return w.clear(n);pe(e,t),w.latestSelectedDateObj=w.selectedDates[w.selectedDates.length-1],w.redraw(),j(void 0,n),F(),0===w.selectedDates.length&&w.clear(!1);ye(n),n&&De("onChange")},w.toggle=function(e){if(!0===w.isOpen)return w.close();w.open(e)};var ge={locale:[se,G],showMonths:[V,S,z],minDate:[j],maxDate:[j],positionElement:[ve],clickOpens:[function(){!0===w.config.clickOpens?(P(w._input,"focus",w.open),P(w._input,"click",w.open)):(w._input.removeEventListener("focus",w.open),w._input.removeEventListener("click",w.open))}]};function pe(e,n){var t=[];if(e instanceof Array)t=e.map((function(e){return w.parseDate(e,n)}));else if(e instanceof Date||"number"==typeof e)t=[w.parseDate(e,n)];else if("string"==typeof e)switch(w.config.mode){case"single":case"time":t=[w.parseDate(e,n)];break;case"multiple":t=e.split(w.config.conjunction).map((function(e){return w.parseDate(e,n)}));break;case"range":t=e.split(w.l10n.rangeSeparator).map((function(e){return w.parseDate(e,n)}))}else w.config.errorHandler(new Error("Invalid date supplied: "+JSON.stringify(e)));w.selectedDates=w.config.allowInvalidPreload?t:t.filter((function(e){return e instanceof Date&&ne(e,!1)})),"range"===w.config.mode&&w.selectedDates.sort((function(e,n){return e.getTime()-n.getTime()}))}function he(e){return e.slice().map((function(e){return"string"==typeof e||"number"==typeof e||e instanceof Date?w.parseDate(e,void 0,!0):e&&"object"==typeof e&&e.from&&e.to?{from:w.parseDate(e.from,void 0),to:w.parseDate(e.to,void 0)}:e})).filter((function(e){return e}))}function ve(){w._positionElement=w.config.positionElement||w._input}function De(e,n){if(void 0!==w.config){var t=w.config[e];if(void 0!==t&&t.length>0)for(var a=0;t[a]&&a<t.length;a++)t[a](w.selectedDates,w.input.value,w,n);"onChange"===e&&(w.input.dispatchEvent(we("change")),w.input.dispatchEvent(we("input")))}}function we(e){var n=document.createEvent("Event");return n.initEvent(e,!0,!0),n}function be(e){for(var n=0;n<w.selectedDates.length;n++){var t=w.selectedDates[n];if(t instanceof Date&&0===M(t,e))return""+n}return!1}function Ce(){w.config.noCalendar||w.isMobile||!w.monthNav||(w.yearElements.forEach((function(e,n){var t=new Date(w.currentYear,w.currentMonth,1);t.setMonth(w.currentMonth+n),w.config.showMonths>1||"static"===w.config.monthSelectorType?w.monthElements[n].textContent=h(t.getMonth(),w.config.shorthandCurrentMonth,w.l10n)+" ":w.monthsDropdownContainer.value=t.getMonth().toString(),e.value=t.getFullYear().toString()})),w._hidePrevMonthArrow=void 0!==w.config.minDate&&(w.currentYear===w.config.minDate.getFullYear()?w.currentMonth<=w.config.minDate.getMonth():w.currentYear<w.config.minDate.getFullYear()),w._hideNextMonthArrow=void 0!==w.config.maxDate&&(w.currentYear===w.config.maxDate.getFullYear()?w.currentMonth+1>w.config.maxDate.getMonth():w.currentYear>w.config.maxDate.getFullYear()))}function Me(e){var n=e||(w.config.altInput?w.config.altFormat:w.config.dateFormat);return w.selectedDates.map((function(e){return w.formatDate(e,n)})).filter((function(e,n,t){return"range"!==w.config.mode||w.config.enableTime||t.indexOf(e)===n})).join("range"!==w.config.mode?w.config.conjunction:w.l10n.rangeSeparator)}function ye(e){void 0===e&&(e=!0),void 0!==w.mobileInput&&w.mobileFormatStr&&(w.mobileInput.value=void 0!==w.latestSelectedDateObj?w.formatDate(w.latestSelectedDateObj,w.mobileFormatStr):""),w.input.value=Me(w.config.dateFormat),void 0!==w.altInput&&(w.altInput.value=Me(w.config.altFormat)),!1!==e&&De("onValueUpdate")}function xe(e){var n=g(e),t=w.prevMonthNav.contains(n),a=w.nextMonthNav.contains(n);t||a?Z(t?-1:1):w.yearElements.indexOf(n)>=0?n.select():n.classList.contains("arrowUp")?w.changeYear(w.currentYear+1):n.classList.contains("arrowDown")&&w.changeYear(w.currentYear-1)}return function(){w.element=w.input=p,w.isOpen=!1,function(){var n=["wrap","weekNumbers","allowInput","allowInvalidPreload","clickOpens","time_24hr","enableTime","noCalendar","altInput","shorthandCurrentMonth","inline","static","enableSeconds","disableMobile"],i=e(e({},JSON.parse(JSON.stringify(p.dataset||{}))),v),o={};w.config.parseDate=i.parseDate,w.config.formatDate=i.formatDate,Object.defineProperty(w.config,"enable",{get:function(){return w.config._enable},set:function(e){w.config._enable=he(e)}}),Object.defineProperty(w.config,"disable",{get:function(){return w.config._disable},set:function(e){w.config._disable=he(e)}});var r="time"===i.mode;if(!i.dateFormat&&(i.enableTime||r)){var l=I.defaultConfig.dateFormat||a.dateFormat;o.dateFormat=i.noCalendar||r?"H:i"+(i.enableSeconds?":S":""):l+" H:i"+(i.enableSeconds?":S":"")}if(i.altInput&&(i.enableTime||r)&&!i.altFormat){var s=I.defaultConfig.altFormat||a.altFormat;o.altFormat=i.noCalendar||r?"h:i"+(i.enableSeconds?":S K":" K"):s+" h:i"+(i.enableSeconds?":S":"")+" K"}Object.defineProperty(w.config,"minDate",{get:function(){return w.config._minDate},set:le("min")}),Object.defineProperty(w.config,"maxDate",{get:function(){return w.config._maxDate},set:le("max")});var d=function(e){return function(n){w.config["min"===e?"_minTime":"_maxTime"]=w.parseDate(n,"H:i:S")}};Object.defineProperty(w.config,"minTime",{get:function(){return w.config._minTime},set:d("min")}),Object.defineProperty(w.config,"maxTime",{get:function(){return w.config._maxTime},set:d("max")}),"time"===i.mode&&(w.config.noCalendar=!0,w.config.enableTime=!0);Object.assign(w.config,o,i);for(var u=0;u<n.length;u++)w.config[n[u]]=!0===w.config[n[u]]||"true"===w.config[n[u]];t.filter((function(e){return void 0!==w.config[e]})).forEach((function(e){w.config[e]=c(w.config[e]||[]).map(T)})),w.isMobile=!w.config.disableMobile&&!w.config.inline&&"single"===w.config.mode&&!w.config.disable.length&&!w.config.enable&&!w.config.weekNumbers&&/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);for(u=0;u<w.config.plugins.length;u++){var f=w.config.plugins[u](w)||{};for(var m in f)t.indexOf(m)>-1?w.config[m]=c(f[m]).map(T).concat(w.config[m]):void 0===i[m]&&(w.config[m]=f[m])}i.altInputClass||(w.config.altInputClass=ce().className+" "+w.config.altInputClass);De("onParseConfig")}(),se(),function(){if(w.input=ce(),!w.input)return void w.config.errorHandler(new Error("Invalid input element specified"));w.input._type=w.input.type,w.input.type="text",w.input.classList.add("flatpickr-input"),w._input=w.input,w.config.altInput&&(w.altInput=d(w.input.nodeName,w.config.altInputClass),w._input=w.altInput,w.altInput.placeholder=w.input.placeholder,w.altInput.disabled=w.input.disabled,w.altInput.required=w.input.required,w.altInput.tabIndex=w.input.tabIndex,w.altInput.type="text",w.input.setAttribute("type","hidden"),!w.config.static&&w.input.parentNode&&w.input.parentNode.insertBefore(w.altInput,w.input.nextSibling));w.config.allowInput||w._input.setAttribute("readonly","readonly");ve()}(),function(){w.selectedDates=[],w.now=w.parseDate(w.config.now)||new Date;var e=w.config.defaultDate||("INPUT"!==w.input.nodeName&&"TEXTAREA"!==w.input.nodeName||!w.input.placeholder||w.input.value!==w.input.placeholder?w.input.value:null);e&&pe(e,w.config.dateFormat);w._initialDate=w.selectedDates.length>0?w.selectedDates[0]:w.config.minDate&&w.config.minDate.getTime()>w.now.getTime()?w.config.minDate:w.config.maxDate&&w.config.maxDate.getTime()<w.now.getTime()?w.config.maxDate:w.now,w.currentYear=w._initialDate.getFullYear(),w.currentMonth=w._initialDate.getMonth(),w.selectedDates.length>0&&(w.latestSelectedDateObj=w.selectedDates[0]);void 0!==w.config.minTime&&(w.config.minTime=w.parseDate(w.config.minTime,"H:i"));void 0!==w.config.maxTime&&(w.config.maxTime=w.parseDate(w.config.maxTime,"H:i"));w.minDateHasTime=!!w.config.minDate&&(w.config.minDate.getHours()>0||w.config.minDate.getMinutes()>0||w.config.minDate.getSeconds()>0),w.maxDateHasTime=!!w.config.maxDate&&(w.config.maxDate.getHours()>0||w.config.maxDate.getMinutes()>0||w.config.maxDate.getSeconds()>0)}(),w.utils={getDaysInMonth:function(e,n){return void 0===e&&(e=w.currentMonth),void 0===n&&(n=w.currentYear),1===e&&(n%4==0&&n%100!=0||n%400==0)?29:w.l10n.daysInMonth[e]}},w.isMobile||function(){var e=window.document.createDocumentFragment();if(w.calendarContainer=d("div","flatpickr-calendar"),w.calendarContainer.tabIndex=-1,!w.config.noCalendar){if(e.appendChild((w.monthNav=d("div","flatpickr-months"),w.yearElements=[],w.monthElements=[],w.prevMonthNav=d("span","flatpickr-prev-month"),w.prevMonthNav.innerHTML=w.config.prevArrow,w.nextMonthNav=d("span","flatpickr-next-month"),w.nextMonthNav.innerHTML=w.config.nextArrow,V(),Object.defineProperty(w,"_hidePrevMonthArrow",{get:function(){return w.__hidePrevMonthArrow},set:function(e){w.__hidePrevMonthArrow!==e&&(s(w.prevMonthNav,"flatpickr-disabled",e),w.__hidePrevMonthArrow=e)}}),Object.defineProperty(w,"_hideNextMonthArrow",{get:function(){return w.__hideNextMonthArrow},set:function(e){w.__hideNextMonthArrow!==e&&(s(w.nextMonthNav,"flatpickr-disabled",e),w.__hideNextMonthArrow=e)}}),w.currentYearElement=w.yearElements[0],Ce(),w.monthNav)),w.innerContainer=d("div","flatpickr-innerContainer"),w.config.weekNumbers){var n=function(){w.calendarContainer.classList.add("hasWeeks");var e=d("div","flatpickr-weekwrapper");e.appendChild(d("span","flatpickr-weekday",w.l10n.weekAbbreviation));var n=d("div","flatpickr-weeks");return e.appendChild(n),{weekWrapper:e,weekNumbers:n}}(),t=n.weekWrapper,a=n.weekNumbers;w.innerContainer.appendChild(t),w.weekNumbers=a,w.weekWrapper=t}w.rContainer=d("div","flatpickr-rContainer"),w.rContainer.appendChild(z()),w.daysContainer||(w.daysContainer=d("div","flatpickr-days"),w.daysContainer.tabIndex=-1),U(),w.rContainer.appendChild(w.daysContainer),w.innerContainer.appendChild(w.rContainer),e.appendChild(w.innerContainer)}w.config.enableTime&&e.appendChild(function(){w.calendarContainer.classList.add("hasTime"),w.config.noCalendar&&w.calendarContainer.classList.add("noCalendar");var e=E(w.config);w.timeContainer=d("div","flatpickr-time"),w.timeContainer.tabIndex=-1;var n=d("span","flatpickr-time-separator",":"),t=m("flatpickr-hour",{"aria-label":w.l10n.hourAriaLabel});w.hourElement=t.getElementsByTagName("input")[0];var a=m("flatpickr-minute",{"aria-label":w.l10n.minuteAriaLabel});w.minuteElement=a.getElementsByTagName("input")[0],w.hourElement.tabIndex=w.minuteElement.tabIndex=-1,w.hourElement.value=o(w.latestSelectedDateObj?w.latestSelectedDateObj.getHours():w.config.time_24hr?e.hours:function(e){switch(e%24){case 0:case 12:return 12;default:return e%12}}(e.hours)),w.minuteElement.value=o(w.latestSelectedDateObj?w.latestSelectedDateObj.getMinutes():e.minutes),w.hourElement.setAttribute("step",w.config.hourIncrement.toString()),w.minuteElement.setAttribute("step",w.config.minuteIncrement.toString()),w.hourElement.setAttribute("min",w.config.time_24hr?"0":"1"),w.hourElement.setAttribute("max",w.config.time_24hr?"23":"12"),w.hourElement.setAttribute("maxlength","2"),w.minuteElement.setAttribute("min","0"),w.minuteElement.setAttribute("max","59"),w.minuteElement.setAttribute("maxlength","2"),w.timeContainer.appendChild(t),w.timeContainer.appendChild(n),w.timeContainer.appendChild(a),w.config.time_24hr&&w.timeContainer.classList.add("time24hr");if(w.config.enableSeconds){w.timeContainer.classList.add("hasSeconds");var i=m("flatpickr-second");w.secondElement=i.getElementsByTagName("input")[0],w.secondElement.value=o(w.latestSelectedDateObj?w.latestSelectedDateObj.getSeconds():e.seconds),w.secondElement.setAttribute("step",w.minuteElement.getAttribute("step")),w.secondElement.setAttribute("min","0"),w.secondElement.setAttribute("max","59"),w.secondElement.setAttribute("maxlength","2"),w.timeContainer.appendChild(d("span","flatpickr-time-separator",":")),w.timeContainer.appendChild(i)}w.config.time_24hr||(w.amPM=d("span","flatpickr-am-pm",w.l10n.amPM[r((w.latestSelectedDateObj?w.hourElement.value:w.config.defaultHour)>11)]),w.amPM.title=w.l10n.toggleTitle,w.amPM.tabIndex=-1,w.timeContainer.appendChild(w.amPM));return w.timeContainer}());s(w.calendarContainer,"rangeMode","range"===w.config.mode),s(w.calendarContainer,"animate",!0===w.config.animate),s(w.calendarContainer,"multiMonth",w.config.showMonths>1),w.calendarContainer.appendChild(e);var i=void 0!==w.config.appendTo&&void 0!==w.config.appendTo.nodeType;if((w.config.inline||w.config.static)&&(w.calendarContainer.classList.add(w.config.inline?"inline":"static"),w.config.inline&&(!i&&w.element.parentNode?w.element.parentNode.insertBefore(w.calendarContainer,w._input.nextSibling):void 0!==w.config.appendTo&&w.config.appendTo.appendChild(w.calendarContainer)),w.config.static)){var l=d("div","flatpickr-wrapper");w.element.parentNode&&w.element.parentNode.insertBefore(l,w.element),l.appendChild(w.element),w.altInput&&l.appendChild(w.altInput),l.appendChild(w.calendarContainer)}w.config.static||w.config.inline||(void 0!==w.config.appendTo?w.config.appendTo:window.document.body).appendChild(w.calendarContainer)}(),function(){w.config.wrap&&["open","close","toggle","clear"].forEach((function(e){Array.prototype.forEach.call(w.element.querySelectorAll("[data-"+e+"]"),(function(n){return P(n,"click",w[e])}))}));if(w.isMobile)return void function(){var e=w.config.enableTime?w.config.noCalendar?"time":"datetime-local":"date";w.mobileInput=d("input",w.input.className+" flatpickr-mobile"),w.mobileInput.tabIndex=1,w.mobileInput.type=e,w.mobileInput.disabled=w.input.disabled,w.mobileInput.required=w.input.required,w.mobileInput.placeholder=w.input.placeholder,w.mobileFormatStr="datetime-local"===e?"Y-m-d\\TH:i:S":"date"===e?"Y-m-d":"H:i:S",w.selectedDates.length>0&&(w.mobileInput.defaultValue=w.mobileInput.value=w.formatDate(w.selectedDates[0],w.mobileFormatStr));w.config.minDate&&(w.mobileInput.min=w.formatDate(w.config.minDate,"Y-m-d"));w.config.maxDate&&(w.mobileInput.max=w.formatDate(w.config.maxDate,"Y-m-d"));w.input.getAttribute("step")&&(w.mobileInput.step=String(w.input.getAttribute("step")));w.input.type="hidden",void 0!==w.altInput&&(w.altInput.type="hidden");try{w.input.parentNode&&w.input.parentNode.insertBefore(w.mobileInput,w.input.nextSibling)}catch(e){}P(w.mobileInput,"change",(function(e){w.setDate(g(e).value,!1,w.mobileFormatStr),De("onChange"),De("onClose")}))}();var e=l(re,50);w._debouncedChange=l(Y,300),w.daysContainer&&!/iPhone|iPad|iPod/i.test(navigator.userAgent)&&P(w.daysContainer,"mouseover",(function(e){"range"===w.config.mode&&oe(g(e))}));P(w._input,"keydown",ie),void 0!==w.calendarContainer&&P(w.calendarContainer,"keydown",ie);w.config.inline||w.config.static||P(window,"resize",e);void 0!==window.ontouchstart?P(window.document,"touchstart",X):P(window.document,"mousedown",X);P(window.document,"focus",X,{capture:!0}),!0===w.config.clickOpens&&(P(w._input,"focus",w.open),P(w._input,"click",w.open));void 0!==w.daysContainer&&(P(w.monthNav,"click",xe),P(w.monthNav,["keyup","increment"],N),P(w.daysContainer,"click",me));if(void 0!==w.timeContainer&&void 0!==w.minuteElement&&void 0!==w.hourElement){var n=function(e){return g(e).select()};P(w.timeContainer,["increment"],_),P(w.timeContainer,"blur",_,{capture:!0}),P(w.timeContainer,"click",H),P([w.hourElement,w.minuteElement],["focus","click"],n),void 0!==w.secondElement&&P(w.secondElement,"focus",(function(){return w.secondElement&&w.secondElement.select()})),void 0!==w.amPM&&P(w.amPM,"click",(function(e){_(e)}))}w.config.allowInput&&P(w._input,"blur",ae)}(),(w.selectedDates.length||w.config.noCalendar)&&(w.config.enableTime&&F(w.config.noCalendar?w.latestSelectedDateObj:void 0),ye(!1)),S();var n=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);!w.isMobile&&n&&de(),De("onReady")}(),w}function T(e,n){for(var t=Array.prototype.slice.call(e).filter((function(e){return e
4767&&1===e.nodeType})),a=[],i=0;i<t.length;i++){var o=t[i];try{if(null!==o.getAttribute("data-fp-omit"))continue;void 0!==o._flatpickr&&(o._flatpickr.destroy(),o._flatpickr=void 0),o._flatpickr=k(o,n||{}),a.push(o._flatpickr)}catch(e){console.error(e)}}return 1===a.length?a[0]:a}"undefined"!=typeof HTMLElement&&"undefined"!=typeof HTMLCollection&&"undefined"!=typeof NodeList&&(HTMLCollection.prototype.flatpickr=NodeList.prototype.flatpickr=function(e){return T(this,e)},HTMLElement.prototype.flatpickr=function(e){return T([this],e)});var I=function(e,n){return"string"==typeof e?T(window.document.querySelectorAll(e),n):e instanceof Node||e&&1===e.nodeType?T([e],n):T(e,n)};return I.defaultConfig={},I.l10ns={en:e({},i),default:e({},i)},I.localize=function(n){I.l10ns.default=e(e({},I.l10ns.default),n)},I.setDefaults=function(n){I.defaultConfig=e(e({},I.defaultConfig),n)},I.parseDate=C({}),I.formatDate=b({}),I.compareDates=M,"undefined"!=typeof jQuery&&void 0!==jQuery.fn&&(jQuery.fn.flatpickr=function(e){return T(this,e)}),Date.prototype.fp_incr=function(e){return new Date(this.getFullYear(),this.getMonth(),this.getDate()+("string"==typeof e?parseInt(e,10):e))},"undefined"!=typeof window&&(window.flatpickr=I),I}));
4768(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):(global=typeof globalThis!=="undefined"?globalThis:global||self,global.monthSelectPlugin=factory())})(this,function(){"use strict";var __assign=function(){__assign=Object.assign||function __assign(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};var monthToStr=function(monthNumber,shorthand,locale){return locale.months[shorthand?"shorthand":"longhand"][monthNumber]};function clearNode(node){while(node.firstChild)node.removeChild(node.firstChild)}function getEventTarget(event){try{if(typeof event.composedPath==="function"){var path=event.composedPath();return path[0]}return event.target}catch(error){return event.target}}var defaultConfig={shorthand:false,dateFormat:"F Y",altFormat:"F Y",theme:"light"};function monthSelectPlugin(pluginConfig){var config=__assign(__assign({},defaultConfig),pluginConfig);return function(fp){fp.config.dateFormat=config.dateFormat;fp.config.altFormat=config.altFormat;var self={monthsContainer:null};function clearUnnecessaryDOMElements(){if(!fp.rContainer)return;clearNode(fp.rContainer);for(var index=0;index<fp.monthElements.length;index++){var element=fp.monthElements[index];if(!element.parentNode)continue;element.parentNode.removeChild(element)}}function build(){if(!fp.rContainer)return;self.monthsContainer=fp._createElement("div","flatpickr-monthSelect-months");self.monthsContainer.tabIndex=-1;buildMonths();fp.rContainer.appendChild(self.monthsContainer);fp.calendarContainer.classList.add("flatpickr-monthSelect-theme-"+config.theme)}function buildMonths(){if(!self.monthsContainer)return;clearNode(self.monthsContainer);var frag=document.createDocumentFragment();for(var i=0;i<12;i++){var month=fp.createDay("flatpickr-monthSelect-month",new Date(fp.currentYear,i),0,i);if(month.dateObj.getMonth()===(new Date).getMonth()&&month.dateObj.getFullYear()===(new Date).getFullYear())month.classList.add("today");month.textContent=monthToStr(i,config.shorthand,fp.l10n);month.addEventListener("click",selectMonth);frag.appendChild(month)}self.monthsContainer.appendChild(frag);if(fp.config.minDate&&fp.currentYear===fp.config.minDate.getFullYear())fp.prevMonthNav.classList.add("flatpickr-disabled");else fp.prevMonthNav.classList.remove("flatpickr-disabled");if(fp.config.maxDate&&fp.currentYear===fp.config.maxDate.getFullYear())fp.nextMonthNav.classList.add("flatpickr-disabled");else fp.nextMonthNav.classList.remove("flatpickr-disabled")}function bindEvents(){fp._bind(fp.prevMonthNav,"click",function(e){e.preventDefault();e.stopPropagation();fp.changeYear(fp.currentYear-1);selectYear();buildMonths()});fp._bind(fp.nextMonthNav,"click",function(e){e.preventDefault();e.stopPropagation();fp.changeYear(fp.currentYear+1);selectYear();buildMonths()});fp._bind(self.monthsContainer,"mouseover",function(e){if(fp.config.mode==="range")fp.onMouseOver(getEventTarget(e),"flatpickr-monthSelect-month")})}function setCurrentlySelected(){if(!fp.rContainer)return;if(!fp.selectedDates.length)return;var currentlySelected=fp.rContainer.querySelectorAll(".flatpickr-monthSelect-month.selected");for(var index=0;
4768index<currentlySelected.length;index++){currentlySelected[index].classList.remove("selected")}var targetMonth=fp.selectedDates[0].getMonth();var month=fp.rContainer.querySelector(".flatpickr-monthSelect-month:nth-child("+(targetMonth+1)+")");if(month){month.classList.add("selected")}}function selectYear(){var selectedDate=fp.selectedDates[0];if(selectedDate){selectedDate=new Date(selectedDate);selectedDate.setFullYear(fp.currentYear);if(fp.config.minDate&&selectedDate<fp.config.minDate){selectedDate=fp.config.minDate}if(fp.config.maxDate&&selectedDate>fp.config.maxDate){selectedDate=fp.config.maxDate}fp.currentYear=selectedDate.getFullYear()}fp.currentYearElement.value=String(fp.currentYear);if(fp.rContainer){var months=fp.rContainer.querySelectorAll(".flatpickr-monthSelect-month");months.forEach(function(month){month.dateObj.setFullYear(fp.currentYear);if(fp.config.minDate&&month.dateObj<fp.config.minDate||fp.config.maxDate&&month.dateObj>fp.config.maxDate){month.classList.add("flatpickr-disabled")}else{month.classList.remove("flatpickr-disabled")}})}setCurrentlySelected()}function selectMonth(e){e.preventDefault();e.stopPropagation();var eventTarget=getEventTarget(e);if(!(eventTarget instanceof Element))return;if(eventTarget.classList.contains("flatpickr-disabled"))return;if(eventTarget.classList.contains("notAllowed"))return;setMonth(eventTarget.dateObj);if(fp.config.closeOnSelect){var single=fp.config.mode==="single";var range=fp.config.mode==="range"&&fp.selectedDates.length===2;if(single||range)fp.close()}}function setMonth(date){var selectedDate=new Date(fp.currentYear,date.getMonth(),date.getDate());var selectedDates=[];switch(fp.config.mode){case"single":selectedDates=[selectedDate];break;case"multiple":selectedDates.push(selectedDate);break;case"range":if(fp.selectedDates.length===2){selectedDates=[selectedDate]}else{selectedDates=fp.selectedDates.concat([selectedDate]);selectedDates.sort(function(a,b){return a.getTime()-b.getTime()})}break}fp.setDate(selectedDates,true);setCurrentlySelected()}var shifts={37:-1,39:1,40:3,38:-3};function onKeyDown(_,__,___,e){var shouldMove=shifts[e.keyCode]!==undefined;if(!shouldMove&&e.keyCode!==13){return}if(!fp.rContainer||!self.monthsContainer)return;var currentlySelected=fp.rContainer.querySelector(".flatpickr-monthSelect-month.selected");var index=Array.prototype.indexOf.call(self.monthsContainer.children,document.activeElement);if(index===-1){var target=currentlySelected||self.monthsContainer.firstElementChild;target.focus();index=target.$i}if(shouldMove){self.monthsContainer.children[(12+index+shifts[e.keyCode])%12].focus()}else if(e.keyCode===13&&self.monthsContainer.contains(document.activeElement)){setMonth(document.activeElement.dateObj)}}function closeHook(){var _a;if(((_a=fp.config)===null||_a===void 0?void 0:_a.mode)==="range"&&fp.selectedDates.length===1)fp.clear(false);if(!fp.selectedDates.length)buildMonths()}function stubCurrentMonth(){config._stubbedCurrentMonth=fp._initialDate.getMonth();fp._initialDate.setMonth(config._stubbedCurrentMonth);fp.currentMonth=config._stubbedCurrentMonth}function unstubCurrentMonth(){if(!config._stubbedCurrentMonth)return;fp._initialDate.setMonth(config._stubbedCurrentMonth);fp.currentMonth=config._stubbedCurrentMonth;delete config._stubbedCurrentMonth}function destroyPluginInstance(){if(self.monthsContainer!==null){var months=self.monthsContainer.querySelectorAll(".flatpickr-monthSelect-month");for(var index=0;index<months.length;index++){months[index].removeEventListener("click",selectMonth)}}}return{onParseConfig:function(){fp.config.enableTime=false},onValueUpdate:setCurrentlySelected,onKeyDown:onKeyDown,onReady:[stubCurrentMonth,clearUnnecessaryDOMElements,build,bindEvents,setCurrentlySelected,function(){fp.config.onClose.push(closeHook);fp.loadedPlugins.push("monthSelect")}],onDestroy:[unstubCurrentMonth,destroyPluginInstance,function(){fp.config.onClose=fp.config.onClose.filter(function(hook){return hook!==closeHook})}]}}}return monthSelectPlugin});
4769
4770/*!
4771 * popperjs v2.11.5 - MIT License - https://github.com/popperjs/popper-core
4772 */
4773!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Popper={})}(this,(function(e){"use strict";function t(e){if(null==e)return window;if("[object Window]"!==e.toString()){var t=e.ownerDocument;return t&&t.defaultView||window}return e}function n(e){return e instanceof t(e).Element||e instanceof Element}function r(e){return e instanceof t(e).HTMLElement||e instanceof HTMLElement}function o(e){return"undefined"!=typeof ShadowRoot&&(e instanceof t(e).ShadowRoot||e instanceof ShadowRoot)}var i=Math.max,a=Math.min,s=Math.round;function f(e,t){void 0===t&&(t=!1);var n=e.getBoundingClientRect(),o=1,i=1;if(r(e)&&t){var a=e.offsetHeight,f=e.offsetWidth;f>0&&(o=s(n.width)/f||1),a>0&&(i=s(n.height)/a||1)}return{width:n.width/o,height:n.height/i,top:n.top/i,right:n.right/o,bottom:n.bottom/i,left:n.left/o,x:n.left/o,y:n.top/i}}function c(e){var n=t(e);return{scrollLeft:n.pageXOffset,scrollTop:n.pageYOffset}}function p(e){return e?(e.nodeName||"").toLowerCase():null}function u(e){return((n(e)?e.ownerDocument:e.document)||window.document).documentElement}function l(e){return f(u(e)).left+c(e).scrollLeft}function d(e){return t(e).getComputedStyle(e)}function h(e){var t=d(e),n=t.overflow,r=t.overflowX,o=t.overflowY;return/auto|scroll|overlay|hidden/.test(n+o+r)}function m(e,n,o){void 0===o&&(o=!1);var i,a,d=r(n),m=r(n)&&function(e){var t=e.getBoundingClientRect(),n=s(t.width)/e.offsetWidth||1,r=s(t.height)/e.offsetHeight||1;return 1!==n||1!==r}(n),v=u(n),g=f(e,m),y={scrollLeft:0,scrollTop:0},b={x:0,y:0};return(d||!d&&!o)&&(("body"!==p(n)||h(v))&&(y=(i=n)!==t(i)&&r(i)?{scrollLeft:(a=i).scrollLeft,scrollTop:a.scrollTop}:c(i)),r(n)?((b=f(n,!0)).x+=n.clientLeft,b.y+=n.clientTop):v&&(b.x=l(v))),{x:g.left+y.scrollLeft-b.x,y:g.top+y.scrollTop-b.y,width:g.width,height:g.height}}function v(e){var t=f(e),n=e.offsetWidth,r=e.offsetHeight;return Math.abs(t.width-n)<=1&&(n=t.width),Math.abs(t.height-r)<=1&&(r=t.height),{x:e.offsetLeft,y:e.offsetTop,width:n,height:r}}function g(e){return"html"===p(e)?e:e.assignedSlot||e.parentNode||(o(e)?e.host:null)||u(e)}function y(e){return["html","body","#document"].indexOf(p(e))>=0?e.ownerDocument.body:r(e)&&h(e)?e:y(g(e))}function b(e,n){var r;void 0===n&&(n=[]);var o=y(e),i=o===(null==(r=e.ownerDocument)?void 0:r.body),a=t(o),s=i?[a].concat(a.visualVie
vendor: 17,313 bytes, lines 4773-4777
4773wport||[],h(o)?o:[]):o,f=n.concat(s);return i?f:f.concat(b(g(s)))}function x(e){return["table","td","th"].indexOf(p(e))>=0}function w(e){return r(e)&&"fixed"!==d(e).position?e.offsetParent:null}function O(e){for(var n=t(e),i=w(e);i&&x(i)&&"static"===d(i).position;)i=w(i);return i&&("html"===p(i)||"body"===p(i)&&"static"===d(i).position)?n:i||function(e){var t=-1!==navigator.userAgent.toLowerCase().indexOf("firefox");if(-1!==navigator.userAgent.indexOf("Trident")&&r(e)&&"fixed"===d(e).position)return null;var n=g(e);for(o(n)&&(n=n.host);r(n)&&["html","body"].indexOf(p(n))<0;){var i=d(n);if("none"!==i.transform||"none"!==i.perspective||"paint"===i.contain||-1!==["transform","perspective"].indexOf(i.willChange)||t&&"filter"===i.willChange||t&&i.filter&&"none"!==i.filter)return n;n=n.parentNode}return null}(e)||n}var j="top",E="bottom",D="right",A="left",L="auto",P=[j,E,D,A],M="start",k="end",W="viewport",B="popper",H=P.reduce((function(e,t){return e.concat([t+"-"+M,t+"-"+k])}),[]),T=[].concat(P,[L]).reduce((function(e,t){return e.concat([t,t+"-"+M,t+"-"+k])}),[]),R=["beforeRead","read","afterRead","beforeMain","main","afterMain","beforeWrite","write","afterWrite"];function S(e){var t=new Map,n=new Set,r=[];function o(e){n.add(e.name),[].concat(e.requires||[],e.requiresIfExists||[]).forEach((function(e){if(!n.has(e)){var r=t.get(e);r&&o(r)}})),r.push(e)}return e.forEach((function(e){t.set(e.name,e)})),e.forEach((function(e){n.has(e.name)||o(e)})),r}function C(e){return e.split("-")[0]}function q(e,t){var n=t.getRootNode&&t.getRootNode();if(e.contains(t))return!0;if(n&&o(n)){var r=t;do{if(r&&e.isSameNode(r))return!0;r=r.parentNode||r.host}while(r)}return!1}function V(e){return Object.assign({},e,{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height})}function N(e,r){return r===W?V(function(e){var n=t(e),r=u(e),o=n.visualViewport,i=r.clientWidth,a=r.clientHeight,s=0,f=0;return o&&(i=o.width,a=o.height,/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||(s=o.offsetLeft,f=o.offsetTop)),{width:i,height:a,x:s+l(e),y:f}}(e)):n(r)?function(e){var t=f(e);return t.top=t.top+e.clientTop,t.left=t.left+e.clientLeft,t.bottom=t.top+e.clientHeight,t.right=t.left+e.clientWidth,t.width=e.clientWidth,t.height=e.clientHeight,t.x=t.left,t.y=t.top,t}(r):V(function(e){var t,n=u(e),r=c(e),o=null==(t=e.ownerDocument)?void 0:t.body,a=i(n.scrollWidth,n.clientWidth,o?o.scrollWidth:0,o?o.clientWidth:0),s=i(n.scrollHeight,n.clientHeight,o?o.scrollHeight:0,o?o.clientHeight:0),f=-r.scrollLeft+l(e),p=-r.scrollTop;return"rtl"===d(o||n).direction&&(f+=i(n.clientWidth,o?o.clientWidth:0)-a),{width:a,height:s,x:f,y:p}}(u(e)))}function I(e,t,o){var s="clippingParents"===t?function(e){var t=b(g(e)),o=["absolute","fixed"].indexOf(d(e).position)>=0&&r(e)?O(e):e;return n(o)?t.filter((function(e){return n(e)&&q(e,o)&&"body"!==p(e)})):[]}(e):[].concat(t),f=[].concat(s,[o]),c=f[0],u=f.reduce((function(t,n){var r=N(e,n);return t.top=i(r.top,t.top),t.right=a(r.right,t.right),t.bottom=a(r.bottom,t.bottom),t.left=i(r.left,t.left),t}),N(e,c));return u.width=u.right-u.left,u.height=u.bottom-u.top,u.x=u.left,u.y=u.top,u}function _(e){return e.split("-")[1]}function F(e){return["top","bottom"].indexOf(e)>=0?"x":"y"}function U(e){var t,n=e.reference,r=e.element,o=e.placement,i=o?C(o):null,a=o?_(o):null,s=n.x+n.width/2-r.width/2,f=n.y+n.height/2-r.height/2;switch(i){case j:t={x:s,y:n.y-r.height};break;case E:t={x:s,y:n.y+n.height};break;case D:t={x:n.x+n.width,y:f};break;case A:t={x:n.x-r.width,y:f};break;default:t={x:n.x,y:n.y}}var c=i?F(i):null;if(null!=c){var p="y"===c?"height":"width";switch(a){case M:t[c]=t[c]-(n[p]/2-r[p]/2);break;case k:t[c]=t[c]+(n[p]/2-r[p]/2)}}return t}function z(e){return Object.assign({},{top:0,right:0,bottom:0,left:0},e)}function X(e,t){return t.reduce((function(t,n){return t[n]=e,t}),{})}function Y(e,t){void 0===t&&(t={});var r=t,o=r.placement,i=void 0===o?e.placement:o,a=r.boundary,s=void 0===a?"clippingParents":a,c=r.rootBoundary,p=void 0===c?W:c,l=r.elementContext,d=void 0===l?B:l,h=r.altBoundary,m=void 0!==h&&h,v=r.padding,g=void 0===v?0:v,y=z("number"!=typeof g?g:X(g,P)),b=d===B?"reference":B,x=e.rects.popper,w=e.elements[m?b:d],O=I(n(w)?w:w.contextElement||u(e.elements.popper),s,p),A=f(e.elements.reference),L=U({reference:A,element:x,strategy:"absolute",placement:i}),M=V(Object.assign({},x,L)),k=d===B?M:A,H={top:O.top-k.top+y.top,bottom:k.bottom-O.bottom+y.bottom,left:O.left-k.left+y.left,right:k.right-O.right+y.right},T=e.modifiersData.offset;if(d===B&&T){var R=T[i];Object.keys(H).forEach((function(e){var t=[D,E].indexOf(e)>=0?1:-1,n=[j,E].indexOf(e)>=0?"y":"x";H[e]+=R[n]*t}))}return H}var G={placement:"bottom",modifiers:[],strategy:"absolute"};function J(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return!t.some((function(e){return!(e&&"function"==typeof e.getBoundingClientRect)}))}function K(e){void 0===e&&(e={});var t=e,r=t.defaultModifiers,o=void 0===r?[]:r,i=t.defaultOptions,a=void 0===i?G:i;return function(e,t,r){void 0===r&&(r=a);var i,s,f={placement:"bottom",orderedModifiers:[],options:Object.assign({},G,a),modifiersData:{},elements:{reference:e,popper:t},attributes:{},styles:{}},c=[],p=!1,u={state:f,setOptions:function(r){var i="function"==typeof r?r(f.options):r;l(),f.options=Object.assign({},a,f.options,i),f.scrollParents={reference:n(e)?b(e):e.contextElement?b(e.contextElement):[],popper:b(t)};var s,p,d=function(e){var t=S(e);return R.reduce((function(e,n){return e.concat(t.filter((function(e){return e.phase===n})))}),[])}((s=[].concat(o,f.options.modifiers),p=s.reduce((function(e,t){var n=e[t.name];return e[t.name]=n?Object.assign({},n,t,{options:Object.assign({},n.options,t.options),data:Object.assign({},n.data,t.data)}):t,e}),{}),Object.keys(p).map((function(e){return p[e]}))));return f.orderedModifiers=d.filter((function(e){return e.enabled})),f.orderedModifiers.forEach((function(e){var t=e.name,n=e.options,r=void 0===n?{}:n,o=e.effect;if("function"==typeof o){var i=o({state:f,name:t,instance:u,options:r}),a=function(){};c.push(i||a)}})),u.update()},forceUpdate:function(){if(!p){var e=f.elements,t=e.reference,n=e.popper;if(J(t,n)){f.rects={reference:m(t,O(n),"fixed"===f.options.strategy),popper:v(n)},f.reset=!1,f.placement=f.options.placement,f.orderedModifiers.forEach((function(e){return f.modifiersData[e.name]=Object.assign({},e.data)}));for(var r=0;r<f.orderedModifiers.length;r++)if(!0!==f.reset){var o=f.orderedModifiers[r],i=o.fn,a=o.options,s=void 0===a?{}:a,c=o.name;"function"==typeof i&&(f=i({state:f,options:s,name:c,instance:u})||f)}else f.reset=!1,r=-1}}},update:(i=function(){return new Promise((function(e){u.forceUpdate(),e(f)}))},function(){return s||(s=new Promise((function(e){Promise.resolve().then((function(){s=void 0,e(i())}))}))),s}),destroy:function(){l(),p=!0}};if(!J(e,t))return u;function l(){c.forEach((function(e){return e()})),c=[]}return u.setOptions(r).then((function(e){!p&&r.onFirstUpdate&&r.onFirstUpdate(e)})),u}}var Q={passive:!0};var Z={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:function(e){var n=e.state,r=e.instance,o=e.options,i=o.scroll,a=void 0===i||i,s=o.resize,f=void 0===s||s,c=t(n.elements.popper),p=[].concat(n.scrollParents.reference,n.scrollParents.popper);return a&&p.forEach((function(e){e.addEventListener("scroll",r.update,Q)})),f&&c.addEventListener("resize",r.update,Q),function(){a&&p.forEach((function(e){e.removeEventListener("scroll",r.update,Q)})),f&&c.removeEventListener("resize",r.update,Q)}},data:{}};var $={name:"popperOffsets",enabled:!0,phase:"read",fn:function(e){var t=e.state,n=e.name;t.modifiersData[n]=U({reference:t.rects.reference,element:t.rects.popper,strategy:"absolute",placement:t.placement})},data:{}},ee={top:"auto",right:"auto",bottom:"auto",left:"auto"};function te(e){var n,r=e.popper,o=e.popperRect,i=e.placement,a=e.variation,f=e.offsets,c=e.position,p=e.gpuAcceleration,l=e.adaptive,h=e.roundOffsets,m=e.isFixed,v=f.x,g=void 0===v?0:v,y=f.y,b=void 0===y?0:y,x="function"==typeof h?h({x:g,y:b}):{x:g,y:b};g=x.x,b=x.y;var w=f.hasOwnProperty("x"),L=f.hasOwnProperty("y"),P=A,M=j,W=window;if(l){var B=O(r),H="clientHeight",T="clientWidth";if(B===t(r)&&"static"!==d(B=u(r)).position&&"absolute"===c&&(H="scrollHeight",T="scrollWidth"),B=B,i===j||(i===A||i===D)&&a===k)M=E,b-=(m&&B===W&&W.visualViewport?W.visualViewport.height:B[H])-o.height,b*=p?1:-1;if(i===A||(i===j||i===E)&&a===k)P=D,g-=(m&&B===W&&W.visualViewport?W.visualViewport.width:B[T])-o.width,g*=p?1:-1}var R,S=Object.assign({position:c},l&&ee),C=!0===h?function(e){var t=e.x,n=e.y,r=window.devicePixelRatio||1;return{x:s(t*r)/r||0,y:s(n*r)/r||0}}({x:g,y:b}):{x:g,y:b};return g=C.x,b=C.y,p?Object.assign({},S,((R={})[M]=L?"0":"",R[P]=w?"0":"",R.transform=(W.devicePixelRatio||1)<=1?"translate("+g+"px, "+b+"px)":"translate3d("+g+"px, "+b+"px, 0)",R)):Object.assign({},S,((n={})[M]=L?b+"px":"",n[P]=w?g+"px":"",n.transform="",n))}var ne={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:function(e){var t=e.state,n=e.options,r=n.gpuAcceleration,o=void 0===r||r,i=n.adaptive,a=void 0===i||i,s=n.roundOffsets,f=void 0===s||s,c={placement:C(t.placement),variation:_(t.placement),popper:t.elements.popper,popperRect:t.rects.popper,gpuAcceleration:o,isFixed:"fixed"===t.options.strategy};null!=t.modifiersData.popperOffsets&&(t.styles.popper=Object.assign({},t.styles.popper,te(Object.assign({},c,{offsets:t.modifiersData.popperOffsets,position:t.options.strategy,adaptive:a,roundOffsets:f})))),null!=t.modifiersData.arrow&&(t.styles.arrow=Object.assign({},t.styles.arrow,te(Object.assign({},c,{offsets:t.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:f})))),t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-placement":t.placement})},data:{}};var re={name:"applyStyles",enabled:!0,phase:"write",fn:function(e){var t=e.state;Object.keys(t.elements).forEach((function(e){var n=t.styles[e]||{},o=t.attributes[e]||{},i=t.elements[e];r(i)&&p(i)&&(Object.assign(i.style,n),Object.keys(o).forEach((function(e){var t=o[e];!1===t?i.removeAttribute(e):i.setAttribute(e,!0===t?"":t)})))}))},effect:function(e){var t=e.state,n={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(t.elements.popper.style,n.popper),t.styles=n,t.elements.arrow&&Object.assign(t.elements.arrow.style,n.arrow),function(){Object.keys(t.elements).forEach((function(e){var o=t.elements[e],i=t.attributes[e]||{},a=Object.keys(t.styles.hasOwnProperty(e)?t.styles[e]:n[e]).reduce((function(e,t){return e[t]="",e}),{});r(o)&&p(o)&&(Object.assign(o.style,a),Object.keys(i).forEach((function(e){o.removeAttribute(e)})))}))}},requires:["computeStyles"]};var oe={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:function(e){var t=e.state,n=e.options,r=e.name,o=n.offset,i=void 0===o?[0,0]:o,a=T.reduce((function(e,n){return e[n]=function(e,t,n){var r=C(e),o=[A,j].indexOf(r)>=0?-1:1,i="function"==typeof n?n(Object.assign({},t,{placement:e})):n,a=i[0],s=i[1];return a=a||0,s=(s||0)*o,[A,D].indexOf(r)>=0?{x:s,y:a}:{x:a,y:s}}(n,t.rects,i),e}),{}),s=a[t.placement],f=s.x,c=s.y;null!=t.modifiersData.popperOffsets&&(t.modifiersData.popperOffsets.x+=f,t.modifiersData.popperOffsets.y+=c),t.modifiersData[r]=a}},ie={left:"right",right:"left",bottom:"top",top:"bottom"};function ae(e){return e.replace(/left|right|bottom|top/g,(function(e){return ie[e]}))}var se={start:"end",end:"start"};function fe(e){return e.replace(/start|end/g,(function(e){return se[e]}))}function ce(e,t){void 0===t&&(t={});var n=t,r=n.placement,o=n.boundary,i=n.rootBoundary,a=n.padding,s=n.flipVariations,f=n.allowedAutoPlacements,c=void 0===f?T:f,p=_(r),u=p?s?H:H.filter((function(e){return _(e)===p})):P,l=u.filter((function(e){return c.indexOf(e)>=0}));0===l.length&&(l=u);var d=l.reduce((function(t,n){return t[n]=Y(e,{placement:n,boundary:o,rootBoundary:i,padding:a})[C(n)],t}),{});return Object.keys(d).sort((function(e,t){return d[e]-d[t]}))}var pe={name:"flip",enabled:!0,phase:"main",fn:function(e){var t=e.state,n=e.options,r=e.name;if(!t.modifiersData[r]._skip){for(var o=n.mainAxis,i=void 0===o||o,a=n.altAxis,s=void 0===a||a,f=n.fallbackPlacements,c=n.padding,p=n.boundary,u=n.rootBoundary,l=n.altBoundary,d=n.flipVariations,h=void 0===d||d,m=n.allowedAutoPlacements,v=t.options.placement,g=C(v),y=f||(g===v||!h?[ae(v)]:function(e){if(C(e)===L)return[];var t=ae(e);return[fe(e),t,fe(t)]}(v)),b=[v].concat(y).reduce((function(e,n){return e.concat(C(n)===L?ce(t,{placement:n,boundary:p,rootBoundary:u,padding:c,flipVariations:h,allowedAutoPlacements:m}):n)}),[]),x=t.rects.reference,w=t.rects.popper,O=new Map,P=!0,k=b[0],W=0;W<b.length;W++){var B=b[W],H=C(B),T=_(B)===M,R=[j,E].indexOf(H)>=0,S=R?"width":"height",q=Y(t,{placement:B,boundary:p,rootBoundary:u,altBoundary:l,padding:c}),V=R?T?D:A:T?E:j;x[S]>w[S]&&(V=ae(V));var N=ae(V),I=[];if(i&&I.push(q[H]<=0),s&&I.push(q[V]<=0,q[N]<=0),I.every((function(e){return e}))){k=B,P=!1;break}O.set(B,I)}if(P)for(var F=function(e){var t=b.find((function(t){var n=O.get(t);if(n)return n.slice(0,e).every((function(e){return e}))}));if(t)return k=t,"break"},U=h?3:1;U>0;U--){if("break"===F(U))break}t.placement!==k&&(t.modifiersData[r]._skip=!0,t.placement=k,t.reset=!0)}},requiresIfExists:["offset"],data:{_skip:!1}};function ue(e,t,n){return i(e,a(t,n))}var le={name:"preventOverflow",enabled:!0,phase:"main",fn:function(e){var t=e.state,n=e.options,r=e.name,o=n.mainAxis,s=void 0===o||o,f=n.altAxis,c=void 0!==f&&f,p=n.boundary,u=n.rootBoundary,l=n.altBoundary,d=n.padding,h=n.tether,m=void 0===h||h,g=n.tetherOffset,y=void 0===g?0:g,b=Y(t,{boundary:p,rootBoundary:u,padding:d,altBoundary:l}),x=C(t.placement),w=_(t.placement),L=!w,P=F(x),k="x"===P?"y":"x",W=t.modifiersData.popperOffsets,B=t.rects.reference,H=t.rects.popper,T="function"==typeof y?y(Object.assign({},t.rects,{placement:t.placement})):y,R="number"==typeof T?{mainAxis:T,altAxis:T}:Object.assign({mainAxis:0,altAxis:0},T),S=t.modifiersData.offset?t.modifiersData.offset[t.placement]:null,q={x:0,y:0};if(W){if(s){var V,N="y"===P?j:A,I="y"===P?E:D,U="y"===P?"height":"width",z=W[P],X=z+b[N],G=z-b[I],J=m?-H[U]/2:0,K=w===M?B[U]:H[U],Q=w===M?-H[U]:-B[U],Z=t.elements.arrow,$=m&&Z?v(Z):{width:0,height:0},ee=t.modifiersData["arrow#persistent"]?t.modifiersData["arrow#persistent"].padding:{top:0,right:0,bottom:0,left:0},te=ee[N],ne=ee[I],re=ue(0,B[U],$[U]),oe=L?B[U]/2-J-re-te-R.mainAxis:K-re-te-R.mainAxis,ie=L?-B[U]/2+J+re+ne+R.mainAxis:Q+re+ne+R.mainAxis,ae=t.elements.arrow&&O(t.elements.arrow),se=ae?"y"===P?ae.clientTop||0:ae.clientLeft||0:0,fe=null!=(V=null==S?void 0:S[P])?V:0,ce=z+ie-fe,pe=ue(m?a(X,z+oe-fe-se):X,z,m?i(G,ce):G);W[P]=pe,q[P]=pe-z}if(c){var le,de="x"===P?j:A,he="x"===P?E:D,me=W[k],ve="y"===k?"height":"width",ge=me+b[de],ye=me-b[he],be=-1!==[j,A].indexOf(x),xe=null!=(le=null==S?void 0:S[k])?le:0,we=be?ge:me-B[ve]-H[ve]-xe+R.altAxis,Oe=be?me+B[ve]+H[ve]-xe-R.altAxis:ye,je=m&&be?function(e,t,n){var r=ue(e,t,n);return r>n?n:r}(we,me,Oe):ue(m?we:ge,me,m?Oe:ye);W[k]=je,q[k]=je-me}t.modifiersData[r]=q}},requiresIfExists:["offset"]};var de={name:"arrow",enabled:!0,phase:"main",fn:function(e){var t,n=e.state,r=e.name,o=e.options,i=n.elements.arrow,a=n.modifiersData.popperOffsets,s=C(n.placement),f=F(s),c=[A,D].indexOf(s)>=0?"height":"width";if(i&&a){var p=function(e,t){return z("number"!=typeof(e="function"==typeof e?e(Object.assign({},t.rects,{placement:t.placement})):e)?e:X(e,P))}(o.padding,n),u=v(i),l="y"===f?j:A,d="y"===f?E:D,h=n.rects.reference[c]+n.rects.reference[f]-a[f]-n.rects.popper[c],m=a[f]-n.rects.reference[f],g=O(i),y=g?"y"===f?g.clientHeight||0:g.clientWidth||0:0,b=h/2-m/2,x=p[l],w=y-u[c]-p[d],L=y/2-u[c]/2+b,M=ue(x,L,w),k=f;n.modifiersData[r]=((t={})[k]=M,t.centerOffset=M-L,t)}},effect:function(e){var t=e.state,n=e.options.element,r=void 0===n?"[data-popper-arrow]":n;null!=r&&("string"!=typeof r||(r=t.elements.popper.querySelector(r)))&&q(t.elements.popper,r)&&(t.elements.arrow=r)},requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function he(e,t,n){return void 0===n&&(n={x:0,y:0}),{top:e.top-t.height-n.y,right:e.right-t.width+n.x,bottom:e.bottom-t.height+n.y,left:e.left-t.width-n.x}}function me(e){return[j,D,E,A].some((function(t){return e[t]>=0}))}var ve={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:function(e){var t=e.state,n=e.name,r=t.rects.reference,o=t.rects.popper,i=t.modifiersData.preventOverflow,a=Y(t,{elementContext:"reference"}),s=Y(t,{altBoundary:!0}),f=he(a,r),c=he(s,o,i),p=me(f),u=me(c);t.modifiersData[n]={referenceClippingOffsets:f,popperEscapeOffsets:c,isReferenceHidden:p,hasPopperEscaped:u},t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-reference-hidden":p,"data-popper-escaped":u})}},ge=K({defaultModifiers:[Z,$,ne,re]}),ye=[Z,$,ne,re,oe,pe,le,de,ve],be=K({defaultModifiers:ye});e.applyStyles=re,e.arrow=de,e.computeStyles=ne,e.createPopper=be,e.createPopperLite=ge,e.defaultModifiers=ye,e.detectOverflow=Y,e.eventListeners=Z,e.flip=pe,e.hide=ve,e.offset=oe,e.popperGenerator=K,e.popperOffsets=$,e.preventOverflow=le,Object.defineProperty(e,"__esModule",{value:!0})}));
4774
4775/*!
4776 * tippy.js v6.3.7 - MIT License - https://github.com/atomiks/tippyjs
4777 */
vendor: 25,668 bytes, line 4778
4778!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("@popperjs/core")):"function"==typeof define&&define.amd?define(["@popperjs/core"],e):(t=t||self).tippy=e(t.Popper)}(this,(function(t){"use strict";var e="undefined"!=typeof window&&"undefined"!=typeof document,n=!!e&&!!window.msCrypto,r={passive:!0,capture:!0},o=function(){return document.body};function i(t,e,n){if(Array.isArray(t)){var r=t[e];return null==r?Array.isArray(n)?n[e]:n:r}return t}function a(t,e){var n={}.toString.call(t);return 0===n.indexOf("[object")&&n.indexOf(e+"]")>-1}function s(t,e){return"function"==typeof t?t.apply(void 0,e):t}function u(t,e){return 0===e?t:function(r){clearTimeout(n),n=setTimeout((function(){t(r)}),e)};var n}function p(t,e){var n=Object.assign({},t);return e.forEach((function(t){delete n[t]})),n}function c(t){return[].concat(t)}function f(t,e){-1===t.indexOf(e)&&t.push(e)}function l(t){return t.split("-")[0]}function d(t){return[].slice.call(t)}function v(t){return Object.keys(t).reduce((function(e,n){return void 0!==t[n]&&(e[n]=t[n]),e}),{})}function m(){return document.createElement("div")}function g(t){return["Element","Fragment"].some((function(e){return a(t,e)}))}function h(t){return a(t,"MouseEvent")}function b(t){return!(!t||!t._tippy||t._tippy.reference!==t)}function y(t){return g(t)?[t]:function(t){return a(t,"NodeList")}(t)?d(t):Array.isArray(t)?t:d(document.querySelectorAll(t))}function w(t,e){t.forEach((function(t){t&&(t.style.transitionDuration=e+"ms")}))}function x(t,e){t.forEach((function(t){t&&t.setAttribute("data-state",e)}))}function E(t){var e,n=c(t)[0];return null!=n&&null!=(e=n.ownerDocument)&&e.body?n.ownerDocument:document}function O(t,e,n){var r=e+"EventListener";["transitionend","webkitTransitionEnd"].forEach((function(e){t[r](e,n)}))}function C(t,e){for(var n=e;n;){var r;if(t.contains(n))return!0;n=null==n.getRootNode||null==(r=n.getRootNode())?void 0:r.host}return!1}var T={isTouch:!1},A=0;function L(){T.isTouch||(T.isTouch=!0,window.performance&&document.addEventListener("mousemove",D))}function D(){var t=performance.now();t-A<20&&(T.isTouch=!1,document.removeEventListener("mousemove",D)),A=t}function k(){var t=document.activeElement;if(b(t)){var e=t._tippy;t.blur&&!e.state.isVisible&&t.blur()}}var R=Object.assign({appendTo:o,aria:{content:"auto",expanded:"auto"},delay:0,duration:[300,250],getReferenceClientRect:null,hideOnClick:!0,ignoreAttributes:!1,interactive:!1,interactiveBorder:2,interactiveDebounce:0,moveTransition:"",offset:[0,10],onAfterUpdate:function(){},onBeforeUpdate:function(){},onCreate:function(){},onDestroy:function(){},onHidden:function(){},onHide:function(){},onMount:function(){},onShow:function(){},onShown:function(){},onTrigger:function(){},onUntrigger:function(){},onClickOutside:function(){},placement:"top",plugins:[],popperOptions:{},render:null,showOnCreate:!1,touch:!0,trigger:"mouseenter focus",triggerTarget:null},{animateFill:!1,followCursor:!1,inlinePositioning:!1,sticky:!1},{allowHTML:!1,animation:"fade",arrow:!0,content:"",inertia:!1,maxWidth:350,role:"tooltip",theme:"",zIndex:9999}),P=Object.keys(R);function j(t){var e=(t.plugins||[]).reduce((function(e,n){var r,o=n.name,i=n.defaultValue;o&&(e[o]=void 0!==t[o]?t[o]:null!=(r=R[o])?r:i);return e}),{});return Object.assign({},t,e)}function M(t,e){var n=Object.assign({},e,{content:s(e.content,[t])},e.ignoreAttributes?{}:function(t,e){return(e?Object.keys(j(Object.assign({},R,{plugins:e}))):P).reduce((function(e,n){var r=(t.getAttribute("data-tippy-"+n)||"").trim();if(!r)return e;if("content"===n)e[n]=r;else try{e[n]=JSON.parse(r)}catch(t){e[n]=r}return e}),{})}(t,e.plugins));return n.aria=Object.assign({},R.aria,n.aria),n.aria={expanded:"auto"===n.aria.expanded?e.interactive:n.aria.expanded,content:"auto"===n.aria.content?e.interactive?null:"describedby":n.aria.content},n}function V(t,e){t.innerHTML=e}function I(t){var e=m();return!0===t?e.className="tippy-arrow":(e.className="tippy-svg-arrow",g(t)?e.appendChild(t):V(e,t)),e}function S(t,e){g(e.content)?(V(t,""),t.appendChild(e.content)):"function"!=typeof e.content&&(e.allowHTML?V(t,e.content):t.textContent=e.content)}function B(t){var e=t.firstElementChild,n=d(e.children);return{box:e,content:n.find((function(t){return t.classList.contains("tippy-content")})),arrow:n.find((function(t){return t.classList.contains("tippy-arrow")||t.classList.contains("tippy-svg-arrow")})),backdrop:n.find((function(t){return t.classList.contains("tippy-backdrop")}))}}function N(t){var e=m(),n=m();n.className="tippy-box",n.setAttribute("data-state","hidden"),n.setAttribute("tabindex","-1");var r=m();function o(n,r){var o=B(e),i=o.box,a=o.content,s=o.arrow;r.theme?i.setAttribute("data-theme",r.theme):i.removeAttribute("data-theme"),"string"==typeof r.animation?i.setAttribute("data-animation",r.animation):i.removeAttribute("data-animation"),r.inertia?i.setAttribute("data-inertia",""):i.removeAttribute("data-inertia"),i.style.maxWidth="number"==typeof r.maxWidth?r.maxWidth+"px":r.maxWidth,r.role?i.setAttribute("role",r.role):i.removeAttribute("role"),n.content===r.content&&n.allowHTML===r.allowHTML||S(a,t.props),r.arrow?s?n.arrow!==r.arrow&&(i.removeChild(s),i.appendChild(I(r.arrow))):i.appendChild(I(r.arrow)):s&&i.removeChild(s)}return r.className="tippy-content",r.setAttribute("data-state","hidden"),S(r,t.props),e.appendChild(n),n.appendChild(r),o(t.props,t.props),{popper:e,onUpdate:o}}N.$$tippy=!0;var H=1,U=[],_=[];function z(e,a){var p,g,b,y,A,L,D,k,P=M(e,Object.assign({},R,j(v(a)))),V=!1,I=!1,S=!1,N=!1,z=[],F=u(wt,P.interactiveDebounce),W=H++,X=(k=P.plugins).filter((function(t,e){return k.indexOf(t)===e})),Y={id:W,reference:e,popper:m(),popperInstance:null,props:P,state:{isEnabled:!0,isVisible:!1,isDestroyed:!1,isMounted:!1,isShown:!1},plugins:X,clearDelayTimeouts:function(){clearTimeout(p),clearTimeout(g),cancelAnimationFrame(b)},setProps:function(t){if(Y.state.isDestroyed)return;at("onBeforeUpdate",[Y,t]),bt();var n=Y.props,r=M(e,Object.assign({},n,v(t),{ignoreAttributes:!0}));Y.props=r,ht(),n.interactiveDebounce!==r.interactiveDebounce&&(pt(),F=u(wt,r.interactiveDebounce));n.triggerTarget&&!r.triggerTarget?c(n.triggerTarget).forEach((function(t){t.removeAttribute("aria-expanded")})):r.triggerTarget&&e.removeAttribute("aria-expanded");ut(),it(),J&&J(n,r);Y.popperInstance&&(Ct(),At().forEach((function(t){requestAnimationFrame(t._tippy.popperInstance.forceUpdate)})));at("onAfterUpdate",[Y,t])},setContent:function(t){Y.setProps({content:t})},show:function(){var t=Y.state.isVisible,e=Y.state.isDestroyed,n=!Y.state.isEnabled,r=T.isTouch&&!Y.props.touch,a=i(Y.props.duration,0,R.duration);if(t||e||n||r)return;if(et().hasAttribute("disabled"))return;if(at("onShow",[Y],!1),!1===Y.props.onShow(Y))return;Y.state.isVisible=!0,tt()&&($.style.visibility="visible");it(),dt(),Y.state.isMounted||($.style.transition="none");if(tt()){var u=rt(),p=u.box,c=u.content;w([p,c],0)}L=function(){var t;if(Y.state.isVisible&&!N){if(N=!0,$.offsetHeight,$.style.transition=Y.props.moveTransition,tt()&&Y.props.animation){var e=rt(),n=e.box,r=e.content;w([n,r],a),x([n,r],"visible")}st(),ut(),f(_,Y),null==(t=Y.popperInstance)||t.forceUpdate(),at("onMount",[Y]),Y.props.animation&&tt()&&function(t,e){mt(t,e)}(a,(function(){Y.state.isShown=!0,at("onShown",[Y])}))}},function(){var t,e=Y.props.appendTo,n=et();t=Y.props.interactive&&e===o||"parent"===e?n.parentNode:s(e,[n]);t.contains($)||t.appendChild($);Y.state.isMounted=!0,Ct()}()},hide:function(){var t=!Y.state.isVisible,e=Y.state.isDestroyed,n=!Y.state.isEnabled,r=i(Y.props.duration,1,R.duration);if(t||e||n)return;if(at("onHide",[Y],!1),!1===Y.props.onHide(Y))return;Y.state.isVisible=!1,Y.state.isShown=!1,N=!1,V=!1,tt()&&($.style.visibility="hidden");if(pt(),vt(),it(!0),tt()){var o=rt(),a=o.box,s=o.content;Y.props.animation&&(w([a,s],r),x([a,s],"hidden"))}st(),ut(),Y.props.animation?tt()&&function(t,e){mt(t,(function(){!Y.state.isVisible&&$.parentNode&&$.parentNode.contains($)&&e()}))}(r,Y.unmount):Y.unmount()},hideWithInteractivity:function(t){nt().addEventListener("mousemove",F),f(U,F),F(t)},enable:function(){Y.state.isEnabled=!0},disable:function(){Y.hide(),Y.state.isEnabled=!1},unmount:function(){Y.state.isVisible&&Y.hide();if(!Y.state.isMounted)return;Tt(),At().forEach((function(t){t._tippy.unmount()})),$.parentNode&&$.parentNode.removeChild($);_=_.filter((function(t){return t!==Y})),Y.state.isMounted=!1,at("onHidden",[Y])},destroy:function(){if(Y.state.isDestroyed)return;Y.clearDelayTimeouts(),Y.unmount(),bt(),delete e._tippy,Y.state.isDestroyed=!0,at("onDestroy",[Y])}};if(!P.render)return Y;var q=P.render(Y),$=q.popper,J=q.onUpdate;$.setAttribute("data-tippy-root",""),$.id="tippy-"+Y.id,Y.popper=$,e._tippy=Y,$._tippy=Y;var G=X.map((function(t){return t.fn(Y)})),K=e.hasAttribute("aria-expanded");return ht(),ut(),it(),at("onCreate",[Y]),P.showOnCreate&&Lt(),$.addEventListener("mouseenter",(function(){Y.props.interactive&&Y.state.isVisible&&Y.clearDelayTimeouts()})),$.addEventListener("mouseleave",(function(){Y.props.interactive&&Y.props.trigger.indexOf("mouseenter")>=0&&nt().addEventListener("mousemove",F)})),Y;function Q(){var t=Y.props.touch;return Array.isArray(t)?t:[t,0]}function Z(){return"hold"===Q()[0]}function tt(){var t;return!(null==(t=Y.props.render)||!t.$$tippy)}function et(){return D||e}function nt(){var t=et().parentNode;return t?E(t):document}function rt(){return B($)}function ot(t){return Y.state.isMounted&&!Y.state.isVisible||T.isTouch||y&&"focus"===y.type?0:i(Y.props.delay,t?0:1,R.delay)}function it(t){void 0===t&&(t=!1),$.style.pointerEvents=Y.props.interactive&&!t?"":"none",$.style.zIndex=""+Y.props.zIndex}function at(t,e,n){var r;(void 0===n&&(n=!0),G.forEach((function(n){n[t]&&n[t].apply(n,e)})),n)&&(r=Y.props)[t].apply(r,e)}function st(){var t=Y.props.aria;if(t.content){var n="aria-"+t.content,r=$.id;c(Y.props.triggerTarget||e).forEach((function(t){var e=t.getAttribute(n);if(Y.state.isVisible)t.setAttribute(n,e?e+" "+r:r);else{var o=e&&e.replace(r,"").trim();o?t.setAttribute(n,o):t.removeAttribute(n)}}))}}function ut(){!K&&Y.props.aria.expanded&&c(Y.props.triggerTarget||e).forEach((function(t){Y.props.interactive?t.setAttribute("aria-expanded",Y.state.isVisible&&t===et()?"true":"false"):t.removeAttribute("aria-expanded")}))}function pt(){nt().removeEventListener("mousemove",F),U=U.filter((function(t){return t!==F}))}function ct(t){if(!T.isTouch||!S&&"mousedown"!==t.type){var n=t.composedPath&&t.composedPath()[0]||t.target;if(!Y.props.interactive||!C($,n)){if(c(Y.props.triggerTarget||e).some((function(t){return C(t,n)}))){if(T.isTouch)return;if(Y.state.isVisible&&Y.props.trigger.indexOf("click")>=0)return}else at("onClickOutside",[Y,t]);!0===Y.props.hideOnClick&&(Y.clearDelayTimeouts(),Y.hide(),I=!0,setTimeout((function(){I=!1})),Y.state.isMounted||vt())}}}function ft(){S=!0}function lt(){S=!1}function dt(){var t=nt();t.addEventListener("mousedown",ct,!0),t.addEventListener("touchend",ct,r),t.addEventListener("touchstart",lt,r),t.addEventListener("touchmove",ft,r)}function vt(){var t=nt();t.removeEventListener("mousedown",ct,!0),t.removeEventListener("touchend",ct,r),t.removeEventListener("touchstart",lt,r),t.removeEventListener("touchmove",ft,r)}function mt(t,e){var n=rt().box;function r(t){t.target===n&&(O(n,"remove",r),e())}if(0===t)return e();O(n,"remove",A),O(n,"add",r),A=r}function gt(t,n,r){void 0===r&&(r=!1),c(Y.props.triggerTarget||e).forEach((function(e){e.addEventListener(t,n,r),z.push({node:e,eventType:t,handler:n,options:r})}))}function ht(){var t;Z()&&(gt("touchstart",yt,{passive:!0}),gt("touchend",xt,{passive:!0})),(t=Y.props.trigger,t.split(/\s+/).filter(Boolean)).forEach((function(t){if("manual"!==t)switch(gt(t,yt),t){case"mouseenter":gt("mouseleave",xt);break;case"focus":gt(n?"focusout":"blur",Et);break;case"focusin":gt("focusout",Et)}}))}function bt(){z.forEach((function(t){var e=t.node,n=t.eventType,r=t.handler,o=t.options;e.removeEventListener(n,r,o)})),z=[]}function yt(t){var e,n=!1;if(Y.state.isEnabled&&!Ot(t)&&!I){var r="focus"===(null==(e=y)?void 0:e.type);y=t,D=t.currentTarget,ut(),!Y.state.isVisible&&h(t)&&U.forEach((function(e){return e(t)})),"click"===t.type&&(Y.props.trigger.indexOf("mouseenter")<0||V)&&!1!==Y.props.hideOnClick&&Y.state.isVisible?n=!0:Lt(t),"click"===t.type&&(V=!n),n&&!r&&Dt(t)}}function wt(t){var e=t.target,n=et().contains(e)||$.contains(e);"mousemove"===t.type&&n||function(t,e){var n=e.clientX,r=e.clientY;return t.every((function(t){var e=t.popperRect,o=t.popperState,i=t.props.interactiveBorder,a=l(o.placement),s=o.modifiersData.offset;if(!s)return!0;var u="bottom"===a?s.top.y:0,p="top"===a?s.bottom.y:0,c="right"===a?s.left.x:0,f="left"===a?s.right.x:0,d=e.top-r+u>i,v=r-e.bottom-p>i,m=e.left-n+c>i,g=n-e.right-f>i;return d||v||m||g}))}(At().concat($).map((function(t){var e,n=null==(e=t._tippy.popperInstance)?void 0:e.state;return n?{popperRect:t.getBoundingClientRect(),popperState:n,props:P}:null})).filter(Boolean),t)&&(pt(),Dt(t))}function xt(t){Ot(t)||Y.props.trigger.indexOf("click")>=0&&V||(Y.props.interactive?Y.hideWithInteractivity(t):Dt(t))}function Et(t){Y.props.trigger.indexOf("focusin")<0&&t.target!==et()||Y.props.interactive&&t.relatedTarget&&$.contains(t.relatedTarget)||Dt(t)}function Ot(t){return!!T.isTouch&&Z()!==t.type.indexOf("touch")>=0}function Ct(){Tt();var n=Y.props,r=n.popperOptions,o=n.placement,i=n.offset,a=n.getReferenceClientRect,s=n.moveTransition,u=tt()?B($).arrow:null,p=a?{getBoundingClientRect:a,contextElement:a.contextElement||et()}:e,c=[{name:"offset",options:{offset:i}},{name:"preventOverflow",options:{padding:{top:2,bottom:2,left:5,right:5}}},{name:"flip",options:{padding:5}},{name:"computeStyles",options:{adaptive:!s}},{name:"$$tippy",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:function(t){var e=t.state;if(tt()){var n=rt().box;["placement","reference-hidden","escaped"].forEach((function(t){"placement"===t?n.setAttribute("data-placement",e.placement):e.attributes.popper["data-popper-"+t]?n.setAttribute("data-"+t,""):n.removeAttribute("data-"+t)})),e.attributes.popper={}}}}];tt()&&u&&c.push({name:"arrow",options:{element:u,padding:3}}),c.push.apply(c,(null==r?void 0:r.modifiers)||[]),Y.popperInstance=t.createPopper(p,$,Object.assign({},r,{placement:o,onFirstUpdate:L,modifiers:c}))}function Tt(){Y.popperInstance&&(Y.popperInstance.destroy(),Y.popperInstance=null)}function At(){return d($.querySelectorAll("[data-tippy-root]"))}function Lt(t){Y.clearDelayTimeouts(),t&&at("onTrigger",[Y,t]),dt();var e=ot(!0),n=Q(),r=n[0],o=n[1];T.isTouch&&"hold"===r&&o&&(e=o),e?p=setTimeout((function(){Y.show()}),e):Y.show()}function Dt(t){if(Y.clearDelayTimeouts(),at("onUntrigger",[Y,t]),Y.state.isVisible){if(!(Y.props.trigger.indexOf("mouseenter")>=0&&Y.props.trigger.indexOf("click")>=0&&["mouseleave","mousemove"].indexOf(t.type)>=0&&V)){var e=ot(!1);e?g=setTimeout((function(){Y.state.isVisible&&Y.hide()}),e):b=requestAnimationFrame((function(){Y.hide()}))}}else vt()}}function F(t,e){void 0===e&&(e={});var n=R.plugins.concat(e.plugins||[]);document.addEventListener("touchstart",L,r),window.addEventListener("blur",k);var o=Object.assign({},e,{plugins:n}),i=y(t).reduce((function(t,e){var n=e&&z(e,o);return n&&t.push(n),t}),[]);return g(t)?i[0]:i}F.defaultProps=R,F.setDefaultProps=function(t){Object.keys(t).forEach((function(e){R[e]=t[e]}))},F.currentInput=T;var W=Object.assign({},t.applyStyles,{effect:function(t){var e=t.state,n={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};Object.assign(e.elements.popper.style,n.popper),e.styles=n,e.elements.arrow&&Object.assign(e.elements.arrow.style,n.arrow)}}),X={mouseover:"mouseenter",focusin:"focus",click:"click"};var Y={name:"animateFill",defaultValue:!1,fn:function(t){var e;if(null==(e=t.props.render)||!e.$$tippy)return{};var n=B(t.popper),r=n.box,o=n.content,i=t.props.animateFill?function(){var t=m();return t.className="tippy-backdrop",x([t],"hidden"),t}():null;return{onCreate:function(){i&&(r.insertBefore(i,r.firstElementChild),r.setAttribute("data-animatefill",""),r.style.overflow="hidden",t.setProps({arrow:!1,animation:"shift-away"}))},onMount:function(){if(i){var t=r.style.transitionDuration,e=Number(t.replace("ms",""));o.style.transitionDelay=Math.round(e/10)+"ms",i.style.transitionDuration=t,x([i],"visible")}},onShow:function(){i&&(i.style.transitionDuration="0ms")},onHide:function(){i&&x([i],"hidden")}}}};var q={clientX:0,clientY:0},$=[];function J(t){var e=t.clientX,n=t.clientY;q={clientX:e,clientY:n}}var G={name:"followCursor",defaultValue:!1,fn:function(t){var e=t.reference,n=E(t.props.triggerTarget||e),r=!1,o=!1,i=!0,a=t.props;function s(){return"initial"===t.props.followCursor&&t.state.isVisible}function u(){n.addEventListener("mousemove",f)}function p(){n.removeEventListener("mousemove",f)}function c(){r=!0,t.setProps({getReferenceClientRect:null}),r=!1}function f(n){var r=!n.target||e.contains(n.target),o=t.props.followCursor,i=n.clientX,a=n.clientY,s=e.getBoundingClientRect(),u=i-s.left,p=a-s.top;!r&&t.props.interactive||t.setProps({getReferenceClientRect:function(){var t=e.getBoundingClientRect(),n=i,r=a;"initial"===o&&(n=t.left+u,r=t.top+p);var s="horizontal"===o?t.top:r,c="vertical"===o?t.right:n,f="horizontal"===o?t.bottom:r,l="vertical"===o?t.left:n;return{width:c-l,height:f-s,top:s,right:c,bottom:f,left:l}}})}function l(){t.props.followCursor&&($.push({instance:t,doc:n}),function(t){t.addEventListener("mousemove",J)}(n))}function d(){0===($=$.filter((function(e){return e.instance!==t}))).filter((function(t){return t.doc===n})).length&&function(t){t.removeEventListener("mousemove",J)}(n)}return{onCreate:l,onDestroy:d,onBeforeUpdate:function(){a=t.props},onAfterUpdate:function(e,n){var i=n.followCursor;r||void 0!==i&&a.followCursor!==i&&(d(),i?(l(),!t.state.isMounted||o||s()||u()):(p(),c()))},onMount:function(){t.props.followCursor&&!o&&(i&&(f(q),i=!1),s()||u())},onTrigger:function(t,e){h(e)&&(q={clientX:e.clientX,clientY:e.clientY}),o="focus"===e.type},onHidden:function(){t.props.followCursor&&(c(),p(),i=!0)}}}};var K={name:"inlinePositioning",defaultValue:!1,fn:function(t){var e,n=t.reference;var r=-1,o=!1,i=[],a={name:"tippyInlinePositioning",enabled:!0,phase:"afterWrite",fn:function(o){var a=o.state;t.props.inlinePositioning&&(-1!==i.indexOf(a.placement)&&(i=[]),e!==a.placement&&-1===i.indexOf(a.placement)&&(i.push(a.placement),t.setProps({getReferenceClientRect:function(){return function(t){return function(t,e,n,r){if(n.length<2||null===t)return e;if(2===n.length&&r>=0&&n[0].left>n[1].right)return n[r]||e;switch(t){case"top":case"bottom":var o=n[0],i=n[n.length-1],a="top"===t,s=o.top,u=i.bottom,p=a?o.left:i.left,c=a?o.right:i.right;return{top:s,bottom:u,left:p,right:c,width:c-p,height:u-s};case"left":case"right":var f=Math.min.apply(Math,n.map((function(t){return t.left}))),l=Math.max.apply(Math,n.map((function(t){return t.right}))),d=n.filter((function(e){return"left"===t?e.left===f:e.right===l})),v=d[0].top,m=d[d.length-1].bottom;return{top:v,bottom:m,left:f,right:l,width:l-f,height:m-v};default:return e}}(l(t),n.getBoundingClientRect(),d(n.getClientRects()),r)}(a.placement)}})),e=a.placement)}};function s(){var e;o||(e=function(t,e){var n;return{popperOptions:Object.assign({},t.popperOptions,{modifiers:[].concat(((null==(n=t.popperOptions)?void 0:n.modifiers)||[]).filter((function(t){return t.name!==e.name})),[e])})}}(t.props,a),o=!0,t.setProps(e),o=!1)}return{onCreate:s,onAfterUpdate:s,onTrigger:function(e,n){if(h(n)){var o=d(t.reference.getClientRects()),i=o.find((function(t){return t.left-2<=n.clientX&&t.right+2>=n.clientX&&t.top-2<=n.clientY&&t.bottom+2>=n.clientY})),a=o.indexOf(i);r=a>-1?a:r}},onHidden:function(){r=-1}}}};var Q={name:"sticky",defaultValue:!1,fn:function(t){var e=t.reference,n=t.popper;function r(e){return!0===t.props.sticky||t.props.sticky===e}var o=null,i=null;function a(){var s=r("reference")?(t.popperInstance?t.popperInstance.state.elements.reference:e).getBoundingClientRect():null,u=r("popper")?n.getBoundingClientRect():null;(s&&Z(o,s)||u&&Z(i,u))&&t.popperInstance&&t.popperInstance.update(),o=s,i=u,t.state.isMounted&&requestAnimationFrame(a)}return{onMount:function(){t.props.sticky&&a()}}}};function Z(t,e){return!t||!e||(t.top!==e.top||t.right!==e.right||t.bottom!==e.bottom||t.left!==e.left)}return e&&function(t){var e=document.createElement("style");e.textContent=t,e.setAttribute("data-tippy-stylesheet","");var n=document.head,r=document.querySelector("head>style,head>link");r?n.insertBefore(e,r):n.appendChild(e)}('.tippy-box[data-animation=fade][data-state=hidden]{opacity:0}[data-tippy-root]{max-width:calc(100vw - 10px)}.tippy-box{position:relative;background-color:#333;color:#fff;border-radius:4px;font-size:14px;line-height:1.4;white-space:normal;outline:0;transition-property:transform,visibility,opacity}.tippy-box[data-placement^=top]>.tippy-arrow{bottom:0}.tippy-box[data-placement^=top]>.tippy-arrow:before{bottom:-7px;left:0;border-width:8px 8px 0;border-top-color:initial;transform-origin:center top}.tippy-box[data-placement^=bottom]>.tippy-arrow{top:0}.tippy-box[data-placement^=bottom]>.tippy-arrow:before{top:-7px;left:0;border-width:0 8px 8px;border-bottom-color:initial;transform-origin:center bottom}.tippy-box[data-placement^=left]>.tippy-arrow{right:0}.tippy-box[data-placement^=left]>.tippy-arrow:before{border-width:8px 0 8px 8px;border-left-color:initial;right:-7px;transform-origin:center left}.tippy-box[data-placement^=right]>.tippy-arrow{left:0}.tippy-box[data-placement^=right]>.tippy-arrow:before{left:-7px;border-width:8px 8px 8px 0;border-right-color:initial;transform-origin:center right}.tippy-box[data-inertia][data-state=visible]{transition-timing-function:cubic-bezier(.54,1.5,.38,1.11)}.tippy-arrow{width:16px;height:16px;color:#333}.tippy-arrow:before{content:"";position:absolute;border-color:transparent;border-style:solid}.tippy-content{position:relative;padding:5px 9px;z-index:1}'),F.setDefaultProps({plugins:[Y,G,K,Q],render:N}),F.createSingleton=function(t,e){var n;void 0===e&&(e={});var r,o=t,i=[],a=[],s=e.overrides,u=[],f=!1;function l(){a=o.map((function(t){return c(t.props.triggerTarget||t.reference)})).reduce((function(t,e){return t.concat(e)}),[])}function d(){i=o.map((function(t){return t.reference}))}function v(t){o.forEach((function(e){t?e.enable():e.disable()}))}function g(t){return o.map((function(e){var n=e.setProps;return e.setProps=function(o){n(o),e.reference===r&&t.setProps(o)},function(){e.setProps=n}}))}function h(t,e){var n=a.indexOf(e);if(e!==r){r=e;var u=(s||[]).concat("content").reduce((function(t,e){return t[e]=o[n].props[e],t}),{});t.setProps(Object.assign({},u,{getReferenceClientRect:"function"==typeof u.getReferenceClientRect?u.getReferenceClientRect:function(){var t;return null==(t=i[n])?void 0:t.getBoundingClientRect()}}))}}v(!1),d(),l();var b={fn:function(){return{onDestroy:function(){v(!0)},onHidden:function(){r=null},onClickOutside:function(t){t.props.showOnCreate&&!f&&(f=!0,r=null)},onShow:function(t){t.props.showOnCreate&&!f&&(f=!0,h(t,i[0]))},onTrigger:function(t,e){h(t,e.currentTarget)}}}},y=F(m(),Object.assign({},p(e,["overrides"]),{plugins:[b].concat(e.plugins||[]),triggerTarget:a,popperOptions:Object.assign({},e.popperOptions,{modifiers:[].concat((null==(n=e.popperOptions)?void 0:n.modifiers)||[],[W])})})),w=y.show;y.show=function(t){if(w(),!r&&null==t)return h(y,i[0]);if(!r||null!=t){if("number"==typeof t)return i[t]&&h(y,i[t]);if(o.indexOf(t)>=0){var e=t.reference;return h(y,e)}return i.indexOf(t)>=0?h(y,t):void 0}},y.showNext=function(){var t=i[0];if(!r)return y.show(0);var e=i.indexOf(r);y.show(i[e+1]||t)},y.showPrevious=function(){var t=i[i.length-1];if(!r)return y.show(t);var e=i.indexOf(r),n=i[e-1]||t;y.show(n)};var x=y.setProps;return y.setProps=function(t){s=t.overrides||s,x(t)},y.setInstances=function(t){v(!0),u.forEach((function(t){return t()})),o=t,v(!1),d(),l(),u=g(y),y.setProps({triggerTarget:a})},u=g(y),y},F.delegate=function(t,e){var n=[],o=[],i=!1,a=e.target,s=p(e,["target"]),u=Object.assign({},s,{trigger:"manual",touch:!1}),f=Object.assign({touch:R.touch},s,{showOnCreate:!0}),l=F(t,u);function d(t){if(t.target&&!i){var n=t.target.closest(a);if(n){var r=n.getAttribute("data-tippy-trigger")||e.trigger||R.trigger;if(!n._tippy&&!("touchstart"===t.type&&"boolean"==typeof f.touch||"touchstart"!==t.type&&r.indexOf(X[t.type])<0)){var s=F(n,f);s&&(o=o.concat(s))}}}}function v(t,e,r,o){void 0===o&&(o=!1),t.addEventListener(e,r,o),n.push({node:t,eventType:e,handler:r,options:o})}return c(l).forEach((function(t){var e=t.destroy,a=t.enable,s=t.disable;t.destroy=function(t){void 0===t&&(t=!0),t&&o.forEach((function(t){t.destroy()})),o=[],n.forEach((function(t){var e=t.node,n=t.eventType,r=t.handler,o=t.options;e.removeEventListener(n,r,o)})),n=[],e()},t.enable=function(){a(),o.forEach((function(t){return t.enable()})),i=!1},t.disable=function(){s(),o.forEach((function(t){return t.disable()})),i=!0},function(t){var e=t.reference;v(e,"touchstart",d,r),v(e,"mouseover",d),v(e,"focusin",d),v(e,"click",d)}(t)})),l},F.hideAll=function(t){var e=void 0===t?{}:t,n=e.exclude,r=e.duration;_.forEach((function(t){var e=!1;if(n&&(e=b(n)?t.reference===n:t.popper===n.popper),!e){var o=t.props.duration;t.setProps({duration:r}),t.hide(),t.state.isDestroyed||t.setProps({duration:o})}}))},F.roundArrow='<svg width="16" height="6" xmlns="http://www.w3.org/2000/svg"><path d="M0 6s1.796-.013 4.67-3.615C5.851.9 6.93.006 8 0c1.07-.006 2.148.887 3.343 2.385C14.233 6.005 16 6 16 6H0z"></svg>',F}));
4779
4780/**
4781 * Selectize (v0.15.2)
4782 * https://selectize.dev
4783 */
4784(function(root,factory){if(typeof define==="function"&&define.amd){define(["jquery"],factory)}else if(typeof module==="object"&&typeof module.exports==="object"){module.exports=factory(require("jquery"))}else{root.EM_Selectize=factory(root.jQuery)}})(this,function($){"use strict";var highlight=function($element,pattern){if(typeof pattern==="string"&&!pattern.length)return;var regex=typeof pattern==="string"?new RegExp(pattern,"i"):pattern;var highlight=function(node){var skip=0;if(node.nodeType===3){var pos=node.data.search(regex);if(pos>=0&&node.data.length>0){var match=node.data.match(regex);var spannode=document.createElement("span");spannode.className="highlight";var middlebit=node.splitText(pos);var endbit=middlebit.splitText(match[0].length);var middleclone=middlebit.cloneNode(true);spannode.appendChild(middleclone);middlebit.parentNode.replaceChild(spannode,middlebit);skip=1}}else if(node.nodeType===1&&node.childNodes&&!/(script|style)/i.test(node.tagName)&&(node.className!=="highlight"||node.tagName!=="SPAN")){for(var i=0;i<node.childNodes.length;++i){i+=highlight(node.childNodes[i])}}return skip};return $element.each(function(){highlight(this)})};$.fn.removeHighlight=function(){return this.find("span.highlight").each(function(){this.parentNode.firstChild.nodeName;var parent=this.parentNode;parent.replaceChild(this.firstChild,this);parent.normalize()}).end()};var MicroEvent=function(){};MicroEvent.prototype={on:function(event,fct){this._events=this._events||{};this._events[event]=this._events[event]||[];this._events[event].push(fct)},off:function(event,fct){var n=arguments.length;if(n===0)return delete this._events;if(n===1)return delete this._events[event];this._events=this._events||{};if(event in this._events===false)return;this._events[event].splice(this._events[event].indexOf(fct),1)},trigger:function(event){const events=this._events=this._events||{};if(event in events===false)return;for(var i=0;i<events[event].length;i++){events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}}};MicroEvent.mixin=function(destObject){var props=["on","off","trigger"];for(var i=0;i<props.length;i++){destObject.prototype[props[i]]=MicroEvent.prototype[props[i]]}};var MicroPlugin={};MicroPlugin.mixin=function(Interface){Interface.plugins={};Interface.prototype.initializePlugins=function(plugins){var i,n,key;var self=this;var queue=[];self.plugins={names:[],settings:{},requested:{},loaded:{}};if(utils.isArray(plugins)){for(i=0,n=plugins.length;i<n;i++){if(typeof plugins[i]==="string"){queue.push(plugins[i])}else{self.plugins.settings[plugins[i].name]=plugins[i].options;queue.push(plugins[i].name)}}}else if(plugins){for(key in plugins){if(plugins.hasOwnProperty(key)){self.plugins.settings[key]=plugins[key];queue.push(key)}}}while(queue.length){self.require(queue.shift())}};Interface.prototype.loadPlugin=function(name){var self=this;var plugins=self.plugins;var plugin=Interface.plugins[name];if(!Interface.plugins.hasOwnProperty(name)){throw new Error('Unable to find "'+name+'" plugin')}plugins.requested[name]=true;plugins.loaded[name]=plugin.fn.apply(self,[self.plugins.settings[name]||{}]);plugins.names.push(name)};Interface.prototype.require=function(name){var self=this;var plugins=self.plugins;if(!self.plugins.loaded.hasOwnProperty(name)){if(plugins.requested[name]){throw new Error('Plugin has circular dependency ("'+name+'")')}self.loadPlugin(name)}return plugins.loaded[name]};Interface.define=function(name,fn){Interface.plugins[name]={name:name,fn:fn}}};var utils={isArray:Array.isArray||function(vArg){return Object.prototype.toString.call(vArg)==="[object Array]"}};var Sifter=function(items,settings){this.items=items;this.settings=settings||{diacritics:true}};Sifter.prototype.tokenize=function(query,respect_word_boundaries){query=trim(String(query||"").toLowerCase());if(!query||!query.length)return[];var i,n,regex,letter;var tokens=[];var words=query.split(/ +/);for(i=0,n=words.length;i<n;i++){regex=escape_regex(words[i]);if(this.settings.diacritics){for(letter in DIACRITICS){if(DIACRITICS.hasOwnProperty(letter)){regex=regex.replace(new RegExp(letter,"g"),DIACRITICS[letter])}}}if(respect_word_boundaries)regex="\\b"+regex;tokens.push({string:words[i],regex:new RegExp(regex,"i")})}return tokens}
4784;Sifter.prototype.iterator=function(object,callback){var iterator;if(is_array(object)){iterator=Array.prototype.forEach||function(callback){for(var i=0,n=this.length;i<n;i++){callback(this[i],i,this)}}}else{iterator=function(callback){for(var key in this){if(this.hasOwnProperty(key)){callback(this[key],key,this)}}}}iterator.apply(object,[callback])};Sifter.prototype.getScoreFunction=function(search,options){var self,fields,tokens,token_count,nesting;self=this;search=self.prepareSearch(search,options);tokens=search.tokens;fields=search.options.fields;token_count=tokens.length;nesting=search.options.nesting;var scoreValue=function(value,token){var score,pos;if(!value)return 0;value=String(value||"");pos=value.search(token.regex);if(pos===-1)return 0;score=token.string.length/value.length;if(pos===0)score+=.5;return score};var scoreObject=function(){var field_count=fields.length;if(!field_count){return function(){return 0}}if(field_count===1){return function(token,data){return scoreValue(getattr(data,fields[0],nesting),token)}}return function(token,data){for(var i=0,sum=0;i<field_count;i++){sum+=scoreValue(getattr(data,fields[i],nesting),token)}return sum/field_count}}();if(!token_count){return function(){return 0}}if(token_count===1){return function(data){return scoreObject(tokens[0],data)}}if(search.options.conjunction==="and"){return function(data){var score;for(var i=0,sum=0;i<token_count;i++){score=scoreObject(tokens[i],data);if(score<=0)return 0;sum+=score}return sum/token_count}}else{return function(data){for(var i=0,sum=0;i<token_count;i++){sum+=scoreObject(tokens[i],data)}return sum/token_count}}};Sifter.prototype.getSortFunction=function(search,options){var i,n,self,field,fields,fields_count,multiplier,multipliers,get_field,implicit_score,sort;self=this;search=self.prepareSearch(search,options);sort=!search.query&&options.sort_empty||options.sort;get_field=function(name,result){if(name==="$score")return result.score;return getattr(self.items[result.id],name,options.nesting)};fields=[];if(sort){for(i=0,n=sort.length;i<n;i++){if(search.query||sort[i].field!=="$score"){fields.push(sort[i])}}}if(search.query){implicit_score=true;for(i=0,n=fields.length;i<n;i++){if(fields[i].field==="$score"){implicit_score=false;break}}if(implicit_score){fields.unshift({field:"$score",direction:"desc"})}}else{for(i=0,n=fields.length;i<n;i++){if(fields[i].field==="$score"){fields.splice(i,1);break}}}multipliers=[];for(i=0,n=fields.length;i<n;i++){multipliers.push(fields[i].direction==="desc"?-1:1)}fields_count=fields.length;if(!fields_count){return null}else if(fields_count===1){field=fields[0].field;multiplier=multipliers[0];return function(a,b){return multiplier*cmp(get_field(field,a),get_field(field,b))}}else{return function(a,b){var i,result,a_value,b_value,field;for(i=0;i<fields_count;i++){field=fields[i].field;result=multipliers[i]*cmp(get_field(field,a),get_field(field,b));if(result)return result}return 0}}};Sifter.prototype.prepareSearch=function(query,options){if(typeof query==="object")return query;options=extend({},options);var option_fields=options.fields;var option_sort=options.sort;var option_sort_empty=options.sort_empty;if(option_fields&&!is_array(option_fields))options.fields=[option_fields];if(option_sort&&!is_array(option_sort))options.sort=[option_sort];if(option_sort_empty&&!is_array(option_sort_empty))options.sort_empty=[option_sort_empty];return{options:options,query:String(query||"").toLowerCase(),tokens:this.tokenize(query,options.respect_word_boundaries),total:0,items:[]}};Sifter.prototype.search=function(query,options){var self=this,value,score,search,calculateScore;var fn_sort;var fn_score;search=this.prepareSearch(query,options);options=search.options;query=search.query;fn_score=options.score||self.getScoreFunction(search);if(query.length){self.iterator(self.items,function(item,id){score=fn_score(item);if(options.filter===false||score>0){search.items.push({score:score,id:id})}})}else{self.iterator(self.items,function(item,id){search.items.push({score:1,id:id})})}fn_sort=self.getSortFunction(search,options);if(fn_sort)search.items.sort(fn_sort);search.total=search.items.length;if(typeof options.limit==="number"){search.items=search.items.slice(0,options.limit)}return search};var cmp=function(a,b){if(typeof a==="number"&&typeof b==="number"){return a>b?1:a<b?-1:0}a=asciifold(String(a||""));b=asciifold(String(b||""));if(a>b)return 1;if(b>a)return-1;return 0};var extend=function(a,b){var i,n,k,object;for(i=1,n=arguments.length;i<n;i++){object=arguments[i];if(!object)continue;for(k in object){if(object.hasOwnProperty(k)){a[k]=object[k]}}}return a};var getattr=function(obj,name,nesting){if(!obj||!name)return;if(!nesting)return obj[name];var names=name.split(".");while(names.length&&(obj=obj[names.shift()]));return obj};var trim=function(str){return(str+"").replace(/^\s+|\s+$|/g,"")};var escape_regex=function(str){return(str+"").replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")};var is_array=Array.isArray||typeof $!=="undefined"&&$.isArray||function(object){return Object.prototype.toString.call(object)==="[object Array]"};var DIACRITICS={a:"[aḀḁĂăÂâǍǎȺⱥȦȧẠạÄäÀàÁáĀāÃãÅåąĄÃąĄ]",b:"[b␢βΒB฿𐌁ᛒ]",c:"[cĆćĈĉČčĊċC̄c̄ÇçḈḉȻȼƇƈɕᴄCc]",d:"[dĎďḊḋḐḑḌḍḒḓḎḏĐđD̦d̦ƉɖƊɗƋƌᵭᶁᶑȡᴅDdð]",e:"[eÉéÈèÊêḘḙĚěĔĕẼẽḚḛẺẻĖėËëĒēȨȩĘęᶒɆɇȄȅẾếỀềỄễỂểḜḝḖḗḔḕȆȇẸẹỆệⱸᴇEeɘǝƏƐε]",f:"[fƑƒḞḟ]",g:"[gɢ₲ǤǥĜĝĞğĢģƓɠĠġ]",h:"[hĤĥĦħḨḩẖẖḤḥḢḣɦʰǶƕ]",i:"[iÍíÌìĬĭÎîǏǐÏïḮḯĨĩĮįĪīỈỉȈȉȊȋỊịḬḭƗɨɨ̆ᵻᶖİiIıɪIi]",j:"[jȷĴĵɈɉʝɟʲ]",k:"[kƘƙꝀꝁḰḱǨǩḲḳḴḵκϰ₭]",l:"[lŁłĽľĻļĹĺḶḷḸḹḼḽḺḻĿŀȽƚⱠⱡⱢɫɬᶅɭȴʟLl]",n:"[nŃńǸǹŇňÑñṄṅŅņṆṇṊṋṈṉN̈n̈ƝɲȠƞᵰᶇɳȵɴNnŊŋ]",o:"[oØøÖöÓóÒòÔôǑǒŐőŎŏȮȯỌọƟɵƠơỎỏŌō
4784ÕõǪǫȌȍՕօ]",p:"[pṔṕṖṗⱣᵽƤƥᵱ]",q:"[qꝖꝗʠɊɋꝘꝙq̃]",r:"[rŔŕɌɍŘřŖŗṘṙȐȑȒȓṚṛⱤɽ]",s:"[sŚśṠṡṢṣꞨꞩŜŝŠšŞşȘșS̈s̈]",t:"[tŤťṪṫŢţṬṭƮʈȚțṰṱṮṯƬƭ]",u:"[uŬŭɄʉỤụÜüÚúÙùÛûǓǔŰűŬŭƯưỦủŪūŨũŲųȔȕ∪]",v:"[vṼṽṾṿƲʋꝞꝟⱱʋ]",w:"[wẂẃẀẁŴŵẄẅẆẇẈẉ]",x:"[xẌẍẊẋχ]",y:"[yÝýỲỳŶŷŸÿỸỹẎẏỴỵɎɏƳƴ]",z:"[zŹźẐẑŽžŻżẒẓẔẕƵƶ]"};var asciifold=function(){var i,n,k,chunk;var foreignletters="";var lookup={};for(k in DIACRITICS){if(DIACRITICS.hasOwnProperty(k)){chunk=DIACRITICS[k].substring(2,DIACRITICS[k].length-1);foreignletters+=chunk;for(i=0,n=chunk.length;i<n;i++){lookup[chunk.charAt(i)]=k}}}var regexp=new RegExp("["+foreignletters+"]","g");return function(str){return str.replace(regexp,function(foreignletter){return lookup[foreignletter]}).toLowerCase()}}();function uaDetect(platform,re){if(navigator.userAgentData){return platform===navigator.userAgentData.platform}return re.test(navigator.userAgent)}var IS_MAC=uaDetect("macOS",/Mac/);var KEY_A=65;var KEY_COMMA=188;var KEY_RETURN=13;var KEY_ESC=27;var KEY_LEFT=37;var KEY_UP=38;var KEY_P=80;var KEY_RIGHT=39;var KEY_DOWN=40;var KEY_N=78;var KEY_BACKSPACE=8;var KEY_DELETE=46;var KEY_SHIFT=16;var KEY_CMD=IS_MAC?91:17;var KEY_CTRL=IS_MAC?18:17;var KEY_TAB=9;var TAG_SELECT=1;var TAG_INPUT=2;var SUPPORTS_VALIDITY_API=!uaDetect("Android",/android/i)&&!!document.createElement("input").validity;var isset=function(object){return typeof object!=="undefined"};var hash_key=function(value){if(typeof value==="undefined"||value===null)return null;if(typeof value==="boolean")return value?"1":"0";return value+""};var escape_html=function(str){return(str+"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")};var escape_replace=function(str){return(str+"").replace(/\$/g,"$$$$")};var hook={};hook.before=function(self,method,fn){var original=self[method];self[method]=function(){fn.apply(self,arguments);return original.apply(self,arguments)}};hook.after=function(self,method,fn){var original=self[method];self[method]=function(){var result=original.apply(self,arguments);fn.apply(self,arguments);return result}};var once=function(fn){var called=false;return function(){if(called)return;called=true;fn.apply(this,arguments)}};var debounce=function(fn,delay){var timeout;return function(){var self=this;var args=arguments;window.clearTimeout(timeout);timeout=window.setTimeout(function(){fn.apply(self,args)},delay)}};var debounce_events=function(self,types,fn){var type;var trigger=self.trigger;var event_args={};self.trigger=function(){var type=arguments[0];if(types.indexOf(type)!==-1){event_args[type]=arguments}else{return trigger.apply(self,arguments)}};fn.apply(self,[]);self.trigger=trigger;for(type in event_args){if(event_args.hasOwnProperty(type)){trigger.apply(self,event_args[type])}}};var watchChildEvent=function($parent,event,selector,fn){$parent.on(event,selector,function(e){var child=e.target;while(child&&child.parentNode!==$parent[0]){child=child.parentNode}e.currentTarget=child;return fn.apply(this,[e])})};var getInputSelection=function(input){var result={};if(input===undefined){console.warn("WARN getInputSelection cannot locate input control");return result}if("selectionStart"in input){result.start=input.selectionStart;result.length=input.selectionEnd-result.start}else if(document.selection){input.focus();var sel=document.selection.createRange();var selLen=document.selection.createRange().text.length;sel.moveStart("character",-input.value.length);result.start=sel.text.length-selLen;result.length=selLen}return result};var transferStyles=function($from,$to,properties){var i,n,styles={};if(properties){for(i=0,n=properties.length;i<n;i++){styles[properties[i]]=$from.css(properties[i])}}else{styles=$from.css()}$to.css(styles)};var measureString=function(str,$parent){if(!str){return 0}if(!Selectize.$testInput){Selectize.$testInput=$("<span />").css({position:"absolute",width:"auto",padding:0,whiteSpace:"pre"});$("<div />").css({position:"absolute",width:0,height:0,overflow:"hidden"}).append(Selectize.$testInput).appendTo("body")}Selectize.$testInput.text(str);transferStyles($parent,Selectize.$testInput,["letterSpacing","fontSize","fontFamily","fontWeight","textTransform"]);return Selectize.$testInput.width()};var autoGrow=function($input){var currentWidth=null;var update=function(e,options){var value,keyCode,printable,width;var placeholder,placeholderWidth;var shift,character,selection;e=e||window.event||{};options=options||{};if(e.metaKey||e.altKey)return;if(!options.force&&$input.data("grow")===false)return;value=$input.val();if(e.type&&e.type.toLowerCase()==="keydown"){keyCode=e.keyCode;printable=keyCode>=48&&keyCode<=57||keyCode>=65&&keyCode<=90||keyCode>=96&&keyCode<=111||keyCode>=186&&keyCode<=222||keyCode===32;if(keyCode===KEY_DELETE||keyCode===KEY_BACKSPACE){selection=getInputSelection($input[0]);if(selection.length){value=value.substring(0,selection.start)+value.substring(selection.start+selection.length)}else if(keyCode===KEY_BACKSPACE&&selection.start){value=value.substring(0,selection.start-1)+value.substring(selection.start+1)}else if(keyCode===KEY_DELETE&&typeof selection.start!=="undefined"){value=value.substring(0,selection.start)+value.substring(selection.start+1)}}else if(printable){shift=e.shiftKey;character=String.fromCharCode(e.keyCode);if(shift)character=character.toUpperCase();else character=character.toLowerCase();value+=character}}placeholder=$input.attr("placeholder");if(placeholder){placeholderWidth=measureString(placeholder,$input)+4}else{placeholderWidth=0}width=Math.max(measureString(value,$input),placeholderWidth)+4;if(width!==currentWidth){currentWidth=width;$input.width(width);$input.triggerHandler("resize")}};
4784$input.on("keydown keyup update blur",update);update()};var domToString=function(d){var tmp=document.createElement("div");tmp.appendChild(d.cloneNode(true));return tmp.innerHTML};var logError=function(message,options){if(!options)options={};var component="Selectize";console.error(component+": "+message);if(options.explanation){if(console.group)console.group();console.error(options.explanation);if(console.group)console.groupEnd()}};var isJSON=function(data){try{JSON.parse(str)}catch(e){return false}return true};var Selectize=function($input,settings){var key,i,n,dir,input,self=this;input=$input[0];input.selectize=self;var computedStyle=window.getComputedStyle&&window.getComputedStyle(input,null);dir=computedStyle?computedStyle.getPropertyValue("direction"):input.currentStyle&&input.currentStyle.direction;dir=dir||$input.parents("[dir]:first").attr("dir")||"";$.extend(self,{order:0,settings:settings,$input:$input,tabIndex:$input.attr("tabindex")||"",tagType:input.tagName.toLowerCase()==="select"?TAG_SELECT:TAG_INPUT,rtl:/rtl/i.test(dir),eventNS:".selectize"+ ++Selectize.count,highlightedValue:null,isBlurring:false,isOpen:false,isDisabled:false,isRequired:$input.is("[required]"),isInvalid:false,isLocked:false,isFocused:false,isInputHidden:false,isSetup:false,isShiftDown:false,isCmdDown:false,isCtrlDown:false,ignoreFocus:false,ignoreBlur:false,ignoreHover:false,hasOptions:false,currentResults:null,lastValue:"",lastValidValue:"",lastOpenTarget:false,caretPos:0,loading:0,loadedSearches:{},isDropdownClosing:false,$activeOption:null,$activeItems:[],optgroups:{},options:{},userOptions:{},items:[],renderCache:{},onSearchChange:settings.loadThrottle===null?self.onSearchChange:debounce(self.onSearchChange,settings.loadThrottle)});self.sifter=new Sifter(this.options,{diacritics:settings.diacritics});if(self.settings.options){for(i=0,n=self.settings.options.length;i<n;i++){self.registerOption(self.settings.options[i])}delete self.settings.options}if(self.settings.optgroups){for(i=0,n=self.settings.optgroups.length;i<n;i++){self.registerOptionGroup(self.settings.optgroups[i])}delete self.settings.optgroups}self.settings.mode=self.settings.mode||(self.settings.maxItems===1?"single":"multi");if(typeof self.settings.hideSelected!=="boolean"){self.settings.hideSelected=self.settings.mode==="multi"}self.initializePlugins(self.settings.plugins);self.setupCallbacks();self.setupTemplates();self.setup()};MicroEvent.mixin(Selectize);MicroPlugin.mixin(Selectize);$.extend(Selectize.prototype,{setup:function(){var self=this;var settings=self.settings;var eventNS=self.eventNS;var $window=$(window);var $document=$(document);var $input=self.$input;var $wrapper;var $control;var $control_input;var $dropdown;var $dropdown_content;var $dropdown_parent;var inputMode;var timeout_blur;var timeout_focus;var classes;var classes_plugins;var inputId;inputMode=self.settings.mode;classes=$input.attr("class")||"";$wrapper=$("<div>
4784").addClass(settings.wrapperClass).addClass(classes+" selectize-control").addClass(inputMode);$control=$("<div>").addClass(settings.inputClass+" selectize-input items").appendTo($wrapper);$control_input=$('<input type="select-one" autocomplete="new-password" autofill="no" />').appendTo($control).attr("tabindex",$input.is(":disabled")?"-1":self.tabIndex);$dropdown_parent=$(settings.dropdownParent||$wrapper);$dropdown=$("<div>").addClass(settings.dropdownClass).addClass(inputMode+" selectize-dropdown").hide().appendTo($dropdown_parent);$dropdown_content=$("<div>").addClass(settings.dropdownContentClass+" selectize-dropdown-content").attr("tabindex","-1").appendTo($dropdown);if(inputId=$input.attr("id")){$control_input.attr("id",inputId+"-selectized");$("label[for='"+inputId+"']").attr("for",inputId+"-selectized")}if(self.settings.copyClassesToDropdown){$dropdown.addClass(classes)}$wrapper.css({width:$input[0].style.width});if(self.plugins.names.length){classes_plugins="plugin-"+self.plugins.names.join(" plugin-");
4784$wrapper.addClass(classes_plugins);$dropdown.addClass(classes_plugins)}if((settings.maxItems===null||settings.maxItems>1)&&self.tagType===TAG_SELECT){$input.attr("multiple","multiple")}if(self.settings.placeholder){$control_input.attr("placeholder",settings.placeholder)}if(!self.settings.search){$control_input.attr("readonly",true);$control_input.attr("inputmode","none");$control.css("cursor","pointer")}if(!self.settings.splitOn&&self.settings.delimiter){var delimiterEscaped=self.settings.delimiter.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");self.settings.splitOn=new RegExp("\\s*"+delimiterEscaped+"+\\s*")}if($input.attr("autocorrect")){$control_input.attr("autocorrect",$input.attr("autocorrect"))}if($input.attr("autocapitalize")){$control_input.attr("autocapitalize",$input.attr("autocapitalize"))}if($input.is("input")){$control_input[0].type=$input[0].type}self.$wrapper=$wrapper;self.$control=$control;self.$control_input=$control_input;self.$dropdown=$dropdown;self.$dropdown_content=$dropdown_content;$dropdown.on("mouseenter mousedown mouseup click","[data-disabled]>[data-selectable]",function(e){e.stopImmediatePropagation()});$dropdown.on("mouseenter","[data-selectable]",function(){return self.onOptionHover.apply(self,arguments)});$dropdown.on("mouseup click","[data-selectable]",function(){return self.onOptionSelect.apply(self,arguments)});watchChildEvent($control,"mouseup","*:not(input)",function(){return self.onItemSelect.apply(self,arguments)});autoGrow($control_input);$control.on({mousedown:function(){return self.onMouseDown.apply(self,arguments)},click:function(){return self.onClick.apply(self,arguments)}});$control_input.on({mousedown:function(e){if(self.$control_input.val()!==""||self.settings.openOnFocus){e.stopPropagation()}},keydown:function(){return self.onKeyDown.apply(self,arguments)},keypress:function(){return self.onKeyPress.apply(self,arguments)},input:function(){return self.onInput.apply(self,arguments)},resize:function(){self.positionDropdown.apply(self,[])},focus:function(){self.ignoreBlur=false;return self.onFocus.apply(self,arguments)},paste:function(){return self.onPaste.apply(self,arguments)}});$document.on("keydown"+eventNS,function(e){self.isCmdDown=e[IS_MAC?"metaKey":"ctrlKey"];self.isCtrlDown=e[IS_MAC?"altKey":"ctrlKey"];self.isShiftDown=e.shiftKey});$document.on("keyup"+eventNS,function(e){if(e.keyCode===KEY_CTRL)self.isCtrlDown=false;if(e.keyCode===KEY_SHIFT)self.isShiftDown=false;if(e.keyCode===KEY_CMD)self.isCmdDown=false});$document.on("mousedown"+eventNS,function(e){if(self.isFocused){if(e.target===self.$dropdown[0]||e.target.parentNode===self.$dropdown[0]){return false}if(!self.$dropdown.has(e.target).length&&e.target!==self.$control[0]){self.blur(e.target)}}});$window.on(["scroll"+eventNS,"resize"+eventNS].join(" "),function(){if(self.isOpen){self.positionDropdown.apply(self,arguments)}});$window.on("mousemove"+eventNS,function(){self.ignoreHover=self.settings.ignoreHover});var inputPlaceholder=$("<div></div>");var inputChildren=$input.children().detach();$input.replaceWith(inputPlaceholder);inputPlaceholder.replaceWith($input);this.revertSettings={$children:inputChildren,tabindex:$input.attr("tabindex")};$input.attr("tabindex",-1).hide().after(self.$wrapper);if(Array.isArray(settings.items)){self.lastValidValue=settings.items;self.setValue(settings.items);delete settings.items}if(SUPPORTS_VALIDITY_API){$input.on("invalid"+eventNS,function(e){e.preventDefault();self.isInvalid=true;self.refreshState()})}self.updateOriginalInput();self.refreshItems();self.refreshState();self.updatePlaceholder();self.isSetup=true;if($input.is(":disabled")){self.disable()}self.on("change",this.onChange);$input.data("selectize",self);$input.addClass("selectized");self.trigger("initialize");if(settings.preload===true){self.onSearchChange("")}},setupTemplates:function(){var self=this;var field_label=self.settings.labelField;var field_value=self.settings.valueField;var field_optgroup=self.settings.optgroupLabelField;var templates={optgroup:function(data){return'<div class="optgroup">'+data.html+"</div>"},optgroup_header:function(data,escape){return'<div class="optgroup-header">'+escape(data[field_optgroup])+"</div>"},option:function(data,escape){var classes=data.classes?" "+data.classes:"";classes+=data[field_value]===""?" selectize-dropdown-emptyoptionlabel":"";var styles=data.styles?' style="'+data.styles+'"':"";return"<div"+styles+' class="option'+classes+'">'+escape(data[field_label])+"</div>"},item:function(data,escape){return'<div class="item">'+escape(data[field_label])+"</div>"},option_create:function(data,escape){return'<div class="create">Add <strong>'+escape(data.input)+"</strong>&#x2026;</div>"}};self.settings.render=$.extend({},templates,self.settings.render)},setupCallbacks:function(){var key,fn,callbacks={initialize:"onInitialize",change:"onChange",item_add:"onItemAdd",item_remove:"onItemRemove",clear:"onClear",option_add:"onOptionAdd",option_remove:"onOptionRemove",option_clear:"onOptionClear",optgroup_add:"onOptionGroupAdd",optgroup_remove:"onOptionGroupRemove",optgroup_clear:"onOptionGroupClear",dropdown_open:"onDropdownOpen",dropdown_close:"onDropdownClose",type:"onType",load:"onLoad",focus:"onFocus",blur:"onBlur",dropdown_item_activate:"onDropdownItemActivate",dropdown_item_deactivate:"onDropdownItemDeactivate"};for(key in callbacks){if(callbacks.hasOwnProperty(key)){fn=this.settings[callbacks[key]];if(fn)this.on(key,fn)}}},onClick:function(e){var self=this;if(self.isDropdownClosing){return}if(!self.isFocused||!self.isOpen){self.focus();e.preventDefault()}},onMouseDown:function(e){var self=this;var defaultPrevented=e.isDefaultPrevented();var $target=$(e.target);if(!self.isFocused){if(!defaultPrevented){window.setTimeout(function(){self.focus()},0)}}if(e.target!==self.$control_input[0]||self.$control_input.val()===""){if(self.settings.mode==="single"){self.isOpen?self.close():self.open()}else{if(!defaultPrevented){self.setActiveItem(null)}if(!self.settings.openOnFocus){if(self.isOpen&&e.target===self.lastOpenTarget){self.close();self.lastOpenTarget=false}else if(!self.isOpen){self.refreshOptions();self.open();self.lastOpenTarget=e.target}else{self.lastOpenTarget=e.target}}}return false}},onChange:function(){var self=this;if(self.getValue()!==""){self.lastValidValue=self.getValue()}this.$input.trigger("input");this.$input.trigger("change")},onPaste:function(e){var self=this;if(self.isFull()||self.isInputHidden||self.isLocked){e.preventDefault();return}if(self.settings.splitOn){setTimeout(function(){var pastedText=self.$control_input.val();if(!pastedText.match(self.settings.splitOn)){return}var splitInput=pastedText.trim().split(self.settings.splitOn);for(var i=0,n=splitInput.length;i<n;i++){self.createItem(splitInput[i])}},0)}},onKeyPress:function(e){if(this.isLocked)return e&&e.preventDefault();var character=String.fromCharCode(e.keyCode||e.which);if(this.settings.create&&this.settings.mode==="multi"&&character===this.settings.delimiter){this.createItem();e.preventDefault();return false}},onKeyDown:function(e){var isInput=e.target===this.$control_input[0];var self=this;if(self.isLocked){if(e.keyCode!==KEY_TAB){e.preventDefault()}return}switch(e.keyCode){case KEY_A:if(self.isCmdDown){self.selectAll();return}break;case KEY_ESC:if(self.isOpen){e.preventDefault();e.stopPropagation();self.close()}return;case KEY_N:if(!e.ctrlKey||e.altKey)break;case KEY_DOWN:if(!self.isOpen&&self.hasOptions){self.open()}else if(self.$activeOption){self.ignoreHover=true;var $next=self.getAdjacentOption(self.$activeOption,1);if($next.length)self.setActiveOption($next,true,true)}e.preventDefault();return;case KEY_P:if(!e.ctrlKey||e.altKey)break;case KEY_UP:if(self.$activeOption){self.ignoreHover=true;var $prev=self.getAdjacentOption(self.$activeOption,-1);if($prev.length)self.setActiveOption($prev,true,true)}e.preventDefault();return;case KEY_RETURN:if(self.isOpen&&self.$activeOption){self.onOptionSelect({currentTarget:self.$activeOption});e.preventDefault()}return;case KEY_LEFT:self.advanceSelection(-1,e);return;case KEY_RIGHT:self.advanceSelection(1,e);return;case KEY_TAB:if(self.settings.selectOnTab&&self.isOpen&&self.$activeOption){self.onOptionSelect({currentTarget:self.$activeOption});if(!self.isFull()){e.preventDefault()}}if(self.settings.create&&self.createItem()&&self.settings.showAddOptionOnCreate){e.preventDefault()}return;case KEY_BACKSPACE:case KEY_DELETE:self.deleteSelection(e);return}if((self.isFull()||self.isInputHidden)&&!(IS_MAC?e.metaKey:e.ctrlKey)){e.preventDefault();return}},onInput:function(e){var self=this;var value=self.$control_input.val()||"";if(self.lastValue!==value){self.lastValue=value;self.onSearchChange(value);self.refreshOptions();self.trigger("type",value)}},onSearchChange:function(value){var self=this;var fn=self.settings.load;if(!fn)return;if(self.loadedSearches.hasOwnProperty(value))return;self.loadedSearches[value]=true;self.load(function(callback){fn.apply(self,[value,callback])})},onFocus:function(e){var self=this;var wasFocused=self.isFocused;if(self.isDisabled){self.blur();e&&e.preventDefault();return false}if(self.ignoreFocus)return;self.isFocused=true;if(self.settings.preload==="focus")self.onSearchChange("");
4784if(!wasFocused)self.trigger("focus");if(!self.$activeItems.length){self.showInput();self.setActiveItem(null);self.refreshOptions(!!self.settings.openOnFocus)}self.refreshState()},onBlur:function(e,dest){var self=this;if(!self.isFocused)return;self.isFocused=false;if(self.ignoreFocus){return}var deactivate=function(){self.close();self.setTextboxValue("");self.setActiveItem(null);self.setActiveOption(null);self.setCaret(self.items.length);self.refreshState();dest&&dest.focus&&dest.focus();self.isBlurring=false;self.ignoreFocus=false;self.trigger("blur")};self.isBlurring=true;self.ignoreFocus=true;if(self.settings.create&&self.settings.createOnBlur){self.createItem(null,false,deactivate)}else{deactivate()}},onOptionHover:function(e){if(this.ignoreHover)return;this.setActiveOption(e.currentTarget,false)},onOptionSelect:function(e){var value,$target,$option,self=this;if(e.preventDefault){e.preventDefault();e.stopPropagation()}$target=$(e.currentTarget);if($target.hasClass("create")){self.createItem(null,function(){if(self.settings.closeAfterSelect){self.close()}})}else{value=$target.attr("data-value");if(typeof value!=="undefined"){self.lastQuery=null;self.setTextboxValue("");self.addItem(value);if(self.settings.closeAfterSelect){self.close()}else if(!self.settings.hideSelected&&e.type&&/mouse/.test(e.type)){self.setActiveOption(self.getOption(value))}}}},onItemSelect:function(e){var self=this;if(self.isLocked)return;if(self.settings.mode==="multi"){e.preventDefault();self.setActiveItem(e.currentTarget,e)}},load:function(fn){var self=this;var $wrapper=self.$wrapper.addClass(self.settings.loadingClass);self.loading++;fn.apply(self,[function(results){self.loading=Math.max(self.loading-1,0);if(results&&results.length){self.addOption(results);self.refreshOptions(self.isFocused&&!self.isInputHidden)}if(!self.loading){$wrapper.removeClass(self.settings.loadingClass)}self.trigger("load",results)}])},getTextboxValue:function(){var $input=this.$control_input;return $input.val()},setTextboxValue:function(value){var $input=this.$control_input;var changed=$input.val()!==value;if(changed){$input.val(value).triggerHandler("update");this.lastValue=value}},getValue:function(){if(this.tagType===TAG_SELECT&&this.$input.attr("multiple")){return this.items}else{return this.items.join(this.settings.delimiter)}},setValue:function(value,silent){const items=Array.isArray(value)?value:[value];if(items.join("")===this.items.join("")){return}var events=silent?[]:["change"];debounce_events(this,events,function(){this.clear(silent);this.addItems(value,silent)})},setMaxItems:function(value){if(value===0)value=null;this.settings.maxItems=value;this.settings.mode=this.settings.mode||(this.settings.maxItems===1?"single":"multi");this.refreshState()},setActiveItem:function($item,e){var self=this;var eventName;var i,idx,begin,end,item,swap;var $last;if(self.settings.mode==="single")return;$item=$($item);if(!$item.length){$(self.$activeItems).removeClass("active");self.$activeItems=[];if(self.isFocused){self.showInput()}return}eventName=e&&e.type.toLowerCase();if(eventName==="mousedown"&&self.isShiftDown&&self.$activeItems.length){$last=self.$control.children(".active:last");begin=Array.prototype.indexOf.apply(self.$control[0].childNodes,[$last[0]]);end=Array.prototype.indexOf.apply(self.$control[0].childNodes,[$item[0]]);if(begin>end){swap=begin;begin=end;end=swap}for(i=begin;i<=end;i++){item=self.$control[0].childNodes[i];if(self.$activeItems.indexOf(item)===-1){$(item).addClass("active");self.$activeItems.push(item)}}e.preventDefault()}else if(eventName==="mousedown"&&self.isCtrlDown||eventName==="keydown"&&this.isShiftDown){if($item.hasClass("active")){idx=self.$activeItems.indexOf($item[0]);self.$activeItems.splice(idx,1);$item.removeClass("active")}else{self.$activeItems.push($item.addClass("active")[0])}}else{$(self.$activeItems).removeClass("active");self.$activeItems=[$item.addClass("active")[0]]}self.hideInput();if(!this.isFocused){self.focus()}},setActiveOption:function($option,scroll,animate){var height_menu,height_item,y;var scroll_top,scroll_bottom;var self=this;if(self.$activeOption){self.$activeOption.removeClass("active");self.trigger("dropdown_item_deactivate",self.$activeOption.attr("data-value"))}self.$activeOption=null;$option=$($option);if(!$option.length)return;self.$activeOption=$option.addClass("active");if(self.isOpen)self.trigger("dropdown_item_activate",self.$activeOption.attr("data-value"));if(scroll||!isset(scroll)){height_menu=self.$dropdown_content.height();height_item=self.$activeOption.outerHeight(true);scroll=self.$dropdown_content.scrollTop()||0;y=self.$activeOption.offset().top-self.$dropdown_content.offset().top+scroll;scroll_top=y;scroll_bottom=y-height_menu+height_item;if(y+height_item>height_menu+scroll){self.$dropdown_content.stop().animate({scrollTop:scroll_bottom},animate?self.settings.scrollDuration:0)}else if(y<scroll){self.$dropdown_content.stop().animate({scrollTop:scroll_top},animate?self.settings.scrollDuration:0)}}},selectAll:function(){var self=this;if(self.settings.mode==="single")return;self.$activeItems=Array.prototype.slice.apply(self.$control.children(":not(input)").addClass("active"));if(self.$activeItems.length){self.hideInput();self.close()}self.focus()},hideInput:function(){var self=this;self.setTextboxValue("");self.$control_input.css({opacity:0,position:"absolute",left:self.rtl?1e4:0});self.isInputHidden=true},showInput:function(){this.$control_input.css({opacity:1,position:"relative",left:0});this.isInputHidden=false},focus:function(){var self=this;if(self.isDisabled)return self;self.ignoreFocus=true;self.$control_input[0].focus();window.setTimeout(function(){self.ignoreFocus=false;self.onFocus()},0);return self},blur:function(dest){this.$control_input[0].blur();this.onBlur(null,dest);return this},getScoreFunction:function(query){return this.sifter.getScoreFunction(query,this.get
4784SearchOptions())},getSearchOptions:function(){var settings=this.settings;var sort=settings.sortField;if(typeof sort==="string"){sort=[{field:sort}]}return{fields:settings.searchField,conjunction:settings.searchConjunction,sort:sort,nesting:settings.nesting,filter:settings.filter,respect_word_boundaries:settings.respect_word_boundaries}},search:function(query){var i,value,score,result,calculateScore;var self=this;var settings=self.settings;var options=this.getSearchOptions();if(settings.score){calculateScore=self.settings.score.apply(this,[query]);if(typeof calculateScore!=="function"){throw new Error('Selectize "score" setting must be a function that returns a function')}}if(query!==self.lastQuery){if(settings.normalize)query=query.normalize("NFD").replace(/[\u0300-\u036f]/g,"");self.lastQuery=query;result=self.sifter.search(query,$.extend(options,{score:calculateScore}));self.currentResults=result}else{result=$.extend(true,{},self.currentResults)}if(settings.hideSelected){for(i=result.items.length-1;i>=0;i--){if(self.items.indexOf(hash_key(result.items[i].id))!==-1){result.items.splice(i,1)}}}return result},refreshOptions:function(triggerDropdown){var i,j,k,n,groups,groups_order,option,option_html,optgroup,optgroups,html,html_children,has_create_option;var $active,$active_before,$create;if(typeof triggerDropdown==="undefined"){triggerDropdown=true}var self=this;var query=self.$control_input.val().trim();var results=self.search(query);var $dropdown_content=self.$dropdown_content;var active_before=self.$activeOption&&hash_key(self.$activeOption.attr("data-value"));n=results.items.length;if(typeof self.settings.maxOptions==="number"){n=Math.min(n,self.settings.maxOptions)}groups={};groups_order=[];for(i=0;i<n;i++){option=self.options[results.items[i].id];option_html=self.render("option",option);optgroup=option[self.settings.optgroupField]||"";optgroups=Array.isArray(optgroup)?optgroup:[optgroup];for(j=0,k=optgroups&&optgroups.length;j<k;j++){optgroup=optgroups[j];if(!self.optgroups.hasOwnProperty(optgroup)&&typeof self.settings.optionGroupRegister==="function"){var regGroup;if(regGroup=self.settings.optionGroupRegister.apply(self,[optgroup])){self.registerOptionGroup(regGroup)}}if(!self.optgroups.hasOwnProperty(optgroup)){optgroup=""}if(!groups.hasOwnProperty(optgroup)){groups[optgroup]=document.createDocumentFragment();groups_order.push(optgroup)}groups[optgroup].appendChild(option_html)}}if(this.settings.lockOptgroupOrder){groups_order.sort(function(a,b){var a_order=self.optgroups[a]&&self.optgroups[a].$order||0;var b_order=self.optgroups[b]&&self.optgroups[b].$order||0;return a_order-b_order})}html=document.createDocumentFragment();for(i=0,n=groups_order.length;i<n;i++){optgroup=groups_order[i];if(self.optgroups.hasOwnProperty(optgroup)&&groups[optgroup].childNodes.length){html_children=document.createDocumentFragment();html_children.appendChild(self.render("optgroup_header",self.optgroups[optgroup]));html_children.appendChild(groups[optgroup]);html.appendChild(self.render("optgroup",$.extend({},self.optgroups[optgroup],{html:domToString(html_children),dom:html_children})))}else{html.appendChild(groups[optgroup])}}$dropdown_content.html(html);if(self.settings.highlight){$dropdown_content.removeHighlight();if(results.query.length&&results.tokens.length){for(i=0,n=results.tokens.length;i<n;i++){highlight($dropdown_content,results.tokens[i].regex)}}}if(!self.settings.hideSelected){self.$dropdown.find(".selected").removeClass("selected");for(i=0,n=self.items.length;i<n;i++){self.getOption(self.items[i]).addClass("selected")}}if(self.settings.dropdownSize.sizeType!=="auto"&&self.isOpen){self.setupDropdownHeight()}has_create_option=self.canCreate(query);if(has_create_option){if(self.settings.showAddOptionOnCreate){$dropdown_content.prepend(self.render("option_create",{input:query}));$create=$($dropdown_content[0].childNodes[0])}}self.hasOptions=results.items.length>0||has_create_option&&self.settings.showAddOptionOnCreate||self.settings.setFirstOptionActive;if(self.hasOptions){if(results.items.length>0){$active_before=active_before&&self.getOption(active_before);if(results.query!==""&&self.settings.setFirstOptionActive){$active=$dropdown_content.find("[data-selectable]:first")}else if(results.query!==""&&$active_before&&$active_before.length){$active=$active_before}else if(self.settings.mode==="single"&&self.items.length){$active=self.getOption(self.items[0])}if(!$active||!$active.length){if($create&&!self.settings.addPrecedence){$active=self.getAdjacentOption($create,1)}else{$active=$dropdown_content.find("[data-selectable]:first")}}}else{$active=$create}self.setActiveOption($active);if(triggerDropdown&&!self.isOpen){self.open()}}else{self.setActiveOption(null);if(triggerDropdown&&self.isOpen){self.close()}}},addOption:function(data){var i,n,value,self=this;if(Array.isArray(data)){for(i=0,n=data.length;i<n;i++){self.addOption(data[i])}return}if(value=self.registerOption(data)){self.userOptions[value]=true;self.lastQuery=null;self.trigger("option_add",value,data)}},registerOption:function(data){var key=hash_key(data[this.settings.valueField]);if(typeof key==="undefined"||key===null||this.options.hasOwnProperty(key))return false;data.$order=data.$order||++this.order;this.options[key]=data;return key},registerOptionGroup:function(data){var key=hash_key(data[this.settings.optgroupValueField]);if(!key)return false;data.$order=data.$order||++this.order;this.optgroups[key]=data;return key},addOptionGroup:function(id,data){data[this.settings.optgroupValueField]=id;if(id=this.registerOptionGroup(data)){this.trigger("optgroup_add",id,data)}},removeOptionGroup:function(id){if(this.optgroups.hasOwnProperty(id)){delete this.optgroups[id];this.renderCache={};this.trigger("optgroup_remove",id)}},clearOptionGroups:function(){this.optgroups={};this.renderCache={};this.trigger("optgroup_clear")},updateOption:function(value,data){var self=this;var $item,$item_new;var value_new,index_item,cache_items,cache_options,order_old;value=hash_key(value);value_new=hash_key(data[self.settings.valueField]);if(value===null)return;if(!self.options.hasOwnProperty(value))return;if(typeof value_new!=="string")throw new Error("Value must be set in option data");order_old=self.options[value].$order;if(value_new!==value){delete self.options[value];index_item=self.items.indexOf(value);if(index_item!==-1){self.items.splice(index_item,1,value_new)}}data.$order=data.$order||order_old;self.options[value_new]=data;cache_items=self.renderCache["item"];cache_options=self.renderCache["option"];if(cache_items){delete cache_items[value];delete cache_items[value_new]}if(cache_options){delete cache_options[value];delete cache_options[value_new]}if(self.items.indexOf(value_new)!==-1){$item=self.getItem(value);$item_new=$(self.render("item",data));if($item.hasClass("active"))$item_new.addClass("active");$item.replaceWith($item_new)}self.lastQuery=null;if(self.isOpen){self.refreshOptions(false)}},removeOption:function(value,silent){var self=this;value=hash_key(value);var cache_items=self.renderCache["item"];var cache_options=self.renderCache["option"];if(cache_items)delete cache_items[value];if(cache_options)delete cache_options[value];delete self.userOptions[value];delete self.options[value];self.lastQuery=null;self.trigger("option_remove",value);self.removeItem(value,silent)},clearOptions:function(silent){var self=this;self.loadedSearches={};self.userOptions={};self.renderCache={};var options=self.options;$.each(self.options,function(key,value){if(self.items.indexOf(key)==-1){delete options[key]}});self.options=self.sifter.items=options;self.lastQuery=null;self.trigger("option_clear");self.clear(silent)},getOption:function(value){return this.getElementWithValue(value,this.$dropdown_content.find("[data-selectable]"))},getFirstOption:function(){var $options=this.$dropdown.find("[data-selectable]");return $options.length>0?$options.eq(0):$()},getAdjacentOption:function($option,direction){var $options=this.$dropdown.find("[data-selectable]");var index=$options.index($option)+direction;return index>=0&&index<$options.length?$options.eq(index):$()},getElementWithValue:function(value,$els){value=hash_key(value);if(typeof value!=="undefined"&&value!==null){for(var i=0,n=$els.length;i<n;i++){if($els[i].getAttribute("data-value")===value){return $($els[i])}}}return $()},getElementWithTextContent:function(textContent,ignoreCase,$els){textContent=hash_key(textContent);if(typeof textContent!=="undefined"&&textContent!==null){for(var i=0,n=$els.length;i<n;i++){var eleTextContent=$els[i].textContent;if(ignoreCase==true){eleTextContent=eleTextContent!==null?eleTextContent.toLowerCase():null;textContent=textContent.toLowerCase()}if(eleTextContent===textContent){return $($els[i])}}}return $()},getItem:function(value){return this.getElementWithValue(value,this.$control.children())},getFirstItemMatchedByTextContent:function(textContent,ignoreCase){ignoreCase=ignoreCase!==null&&ignoreCase===true?true:false;return this.getElementWithTextContent(textContent,ignoreCase,this.$dropdown_content.find("[data-selectable]"))},addItems:function(values,silent){this.buffer=document.createDocumentFragment();var childNodes=this.$control[0].childNodes;for(var i=0;i<childNodes.length;i++){this.buffer.appendChild(childNodes[i])}var items=Array.isArray(values)?values:[values];for(var i=0,n=items.length;i<n;i++){this.isPending=i<n-1;this.addItem(items[i],silent)}var control=this.$control[0];control.insertBefore(this.buffer,control.firstChild);this.buffer=null},addItem:function(value,silent){var events=silent?[]:["change"];debounce_events(this,events,function(){var $item,$option,$options;var self=this;var inputMode=self.settings.mode;var i,active,value_next,wasFull;value=hash_key(value);if(self.items.indexOf(value)!==-1){if(inputMode==="single")self.close();return}if(!self.options.hasOwnProperty(value))return;if(inputMode==="single")self.clear(silent);if(inputMode==="multi"&&self.isFull())return;$item=$(self.render("item",self.options[value]));wasFull=self.isFull();self.items.splice(self.caretPos,0,value);self.insertAtCaret($item);if(!self.isPending||!wasFull&&self.isFull()){self.refreshState()}if(self.isSetup){$options=self.$dropdown_content.find("[data-selectable]");if(!self.isPending){$option=self.getOption(value);value_next=self.getAdjacentOption($option,1).attr("data-value");self.refreshOptions(self.isFocused&&inputMode!=="single");if(value_next){self.setActiveOption(self.getOption(value_next))}}if(!$options.length||self.isFull()){self.close()}else if(!self.isPending){self.positionDropdown()}self.updatePlaceholder();self.trigger("item_add",value,$item);if(!self.isPending){self.updateOriginalInput({silent:silent})}}})},removeItem:function(value,silent){var self=this;var $item,i,idx;$item=value instanceof $?value:self.getItem(value);value=hash_key($item.attr("data-value"));i=self.items.indexOf(value);if(i!==-1){self.trigger("item_before_remove",value,$item);
4784$item.remove();if($item.hasClass("active")){$item.removeClass("active");idx=self.$activeItems.indexOf($item[0]);self.$activeItems.splice(idx,1);$item.removeClass("active")}self.items.splice(i,1);self.lastQuery=null;if(!self.settings.persist&&self.userOptions.hasOwnProperty(value)){self.removeOption(value,silent)}if(i<self.caretPos){self.setCaret(self.caretPos-1)}self.refreshState();self.updatePlaceholder();self.updateOriginalInput({silent:silent});self.positionDropdown();self.trigger("item_remove",value,$item)}},createItem:function(input,triggerDropdown){var self=this;var caret=self.caretPos;input=input||(self.$control_input.val()||"").trim();var callback=arguments[arguments.length-1];if(typeof callback!=="function")callback=function(){};if(typeof triggerDropdown!=="boolean"){triggerDropdown=true}if(!self.canCreate(input)){callback();return false}self.lock();var setup=typeof self.settings.create==="function"?this.settings.create:function(input){var data={};data[self.settings.labelField]=input;var key=input;if(self.settings.formatValueToKey&&typeof self.settings.formatValueToKey==="function"){key=self.settings.formatValueToKey.apply(this,[key]);if(key===null||typeof key==="undefined"||typeof key==="object"||typeof key==="function"){throw new Error('Selectize "formatValueToKey" setting must be a function that returns a value other than object or function.')}}data[self.settings.valueField]=key;return data};var create=once(function(data){self.unlock();if(!data||typeof data!=="object")return callback();var value=hash_key(data[self.settings.valueField]);if(typeof value!=="string")return callback();self.setTextboxValue("");self.addOption(data);self.setCaret(caret);self.addItem(value);self.refreshOptions(triggerDropdown&&self.settings.mode!=="single");callback(data)});var output=setup.apply(this,[input,create]);if(typeof output!=="undefined"){create(output)}return true},refreshItems:function(silent){this.lastQuery=null;if(this.isSetup){this.addItem(this.items,silent)}this.refreshState();this.updateOriginalInput({silent:silent})},refreshState:function(){this.refreshValidityState();this.refreshClasses()},refreshValidityState:function(){if(!this.isRequired)return false;var invalid=!this.items.length;this.isInvalid=invalid;this.$control_input.prop("required",invalid);this.$input.prop("required",!invalid)},refreshClasses:function(){var self=this;var isFull=self.isFull();var isLocked=self.isLocked;self.$wrapper.toggleClass("rtl",self.rtl);self.$control.toggleClass("focus",self.isFocused).toggleClass("disabled",self.isDisabled).toggleClass("required",self.isRequired).toggleClass("invalid",self.isInvalid).toggleClass("locked",isLocked).toggleClass("full",isFull).toggleClass("not-full",!isFull).toggleClass("input-active",self.isFocused&&!self.isInputHidden).toggleClass("dropdown-active",self.isOpen).toggleClass("has-options",!$.isEmptyObject(self.options)).toggleClass("has-items",self.items.length>0);self.$control_input.data("grow",!isFull&&!isLocked)},isFull:function(){return this.settings.maxItems!==null&&this.items.length>=this.settings.maxItems},updateOriginalInput:function(opts){var i,n,existing,fresh,old,$options,label,value,values,self=this;opts=opts||{};if(self.tagType===TAG_SELECT){$options=self.$input.find("option");existing=[];fresh=[];old=[];values=[];$options.get().forEach(function(option){existing.push(option.value)});self.items.forEach(function(item){label=self.options[item][self.settings.labelField]||"";values.push(item);if(existing.indexOf(item)!=-1){return}fresh.push('<option value="'+escape_html(item)+'" selected="selected">'+escape_html(label)+"</option>")});old=existing.filter(function(value){return values.indexOf(value)<0}).map(function(value){return'option[value="'+value+'"]'});if(existing.length-old.length+fresh.length===0&&!self.$input.attr("multiple")){fresh.push('<option value="" selected="selected"></option>')}self.$input.find(old.join(", ")).remove();self.$input.append(fresh.join(""))}else{self.$input.val(self.getValue());self.$input.attr("value",self.$input.val())}if(self.isSetup){if(!opts.silent){self.trigger("change",self.$input.val())}}},updatePlaceholder:function(){if(!this.settings.placeholder)return;var $input=this.$control_input;if(this.items.length){$input.removeAttr("placeholder")}else{$input.attr("placeholder",this.settings.placeholder)}$input.triggerHandler("update",{force:true})},open:function(){var self=this;if(self.isLocked||self.isOpen||self.settings.mode==="multi"&&self.isFull())return;self.focus();self.isOpen=true;self.refreshState();self.$dropdown.css({visibility:"hidden",display:"block"});self.setupDropdownHeight();self.positionDropdown();self.$dropdown.css({visibility:"visible"});self.trigger("dropdown_open",self.$dropdown)},close:function(){var self=this;var trigger=self.isOpen;if(self.settings.mode==="single"&&self.items.length){self.hideInput();if(self.isBlurring){self.$control_input[0].blur()}}self.isOpen=false;self.$dropdown.hide();self.setActiveOption(null);self.refreshState();if(trigger)self.trigger("dropdown_close",self.$dropdown)},positionDropdown:function(){var $control=this.$control;var offset=this.settings.dropdownParent==="body"?$control.offset():$control.position();offset.top+=$control.outerHeight(true);var w=$control[0].getBoundingClientRect().width;if(this.settings.minWidth&&this.settings.minWidth>w){w=this.settings.minWidth}
4784this.$dropdown.css({width:w,top:offset.top,left:offset.left})},setupDropdownHeight:function(){if(typeof this.settings.dropdownSize==="object"&&this.settings.dropdownSize.sizeType!=="auto"){var height=this.settings.dropdownSize.sizeValue;if(this.settings.dropdownSize.sizeType==="numberItems"){var $items=this.$dropdown_content.find("*").not(".optgroup, .highlight").not(this.settings.ignoreOnDropwdownHeight);var totalHeight=0;var marginTop=0;var marginBottom=0;var separatorHeight=0;for(var i=0;i<height;i++){var $item=$($items[i]);if($item.length===0){break}totalHeight+=$item.outerHeight(true);if(typeof $item.data("selectable")=="undefined"){if($item.hasClass("optgroup-header")){var styles=window.getComputedStyle($item.parent()[0],":before");if(styles){marginTop=styles.marginTop?Number(styles.marginTop.replace(/\W*(\w)\w*/g,"$1")):0;marginBottom=styles.marginBottom?Number(styles.marginBottom.replace(/\W*(\w)\w*/g,"$1")):0;separatorHeight=styles.borderTopWidth?Number(styles.borderTopWidth.replace(/\W*(\w)\w*/g,"$1")):0}}height++}}var paddingTop=this.$dropdown_content.css("padding-top")?Number(this.$dropdown_content.css("padding-top").replace(/\W*(\w)\w*/g,"$1")):0;var paddingBottom=this.$dropdown_content.css("padding-bottom")?Number(this.$dropdown_content.css("padding-bottom").replace(/\W*(\w)\w*/g,"$1")):0;height=totalHeight+paddingTop+paddingBottom+marginTop+marginBottom+separatorHeight+"px"}else if(this.settings.dropdownSize.sizeType!=="fixedHeight"){console.warn('Selectize.js - Value of "sizeType" must be "fixedHeight" or "numberItems');return}this.$dropdown_content.css({height:height,maxHeight:"none"})}},clear:function(silent){var self=this;if(!self.items.length)return;self.$control.children(":not(input)").remove();self.items=[];self.lastQuery=null;self.setCaret(0);self.setActiveItem(null);self.updatePlaceholder();self.updateOriginalInput({silent:silent});self.refreshState();self.showInput();self.trigger("clear")},insertAtCaret:function($el){var caret=Math.min(this.caretPos,this.items.length);var el=$el[0];var target=this.buffer||this.$control[0];if(caret===0){target.insertBefore(el,target.firstChild)}else{target.insertBefore(el,target.childNodes[caret])}this.setCaret(caret+1)},deleteSelection:function(e){var i,n,direction,selection,values,caret,option_select,$option_select,$tail;var self=this;direction=e&&e.keyCode===KEY_BACKSPACE?-1:1;selection=getInputSelection(self.$control_input[0]);if(self.$activeOption&&!self.settings.hideSelected){if(typeof self.settings.deselectBehavior==="string"&&self.settings.deselectBehavior==="top"){option_select=self.getFirstOption().attr("data-value")}else{option_select=self.getAdjacentOption(self.$activeOption,-1).attr("data-value")}}values=[];if(self.$activeItems.length){$tail=self.$control.children(".active:"+(direction>0?"last":"first"));caret=self.$control.children(":not(input)").index($tail);if(direction>0){caret++}for(i=0,n=self.$activeItems.length;i<n;i++){values.push($(self.$activeItems[i]).attr("data-value"))}if(e){e.preventDefault();e.stopPropagation()}}else if((self.isFocused||self.settings.mode==="single")&&self.items.length){if(direction<0&&selection.start===0&&selection.length===0){values.push(self.items[self.caretPos-1])}else if(direction>0&&selection.start===self.$control_input.val().length){values.push(self.items[self.caretPos])}}if(!values.length||typeof self.settings.onDelete==="function"&&self.settings.onDelete.apply(self,[values])===false){return false}if(typeof caret!=="undefined"){self.setCaret(caret)}while(values.length){self.removeItem(values.pop())}self.showInput();self.positionDropdown();self.refreshOptions(true);if(option_select){$option_select=self.getOption(option_select);if($option_select.length){self.setActiveOption($option_select)}}return true},advanceSelection:function(direction,e){var tail,selection,idx,valueLength,cursorAtEdge,$tail;var self=this;if(direction===0)return;if(self.rtl)direction*=-1;tail=direction>0?"last":"first";selection=getInputSelection(self.$control_input[0]);if(self.isFocused&&!self.isInputHidden){valueLength=self.$control_input.val().length;cursorAtEdge=direction<0?selection.start===0&&selection.length===0:selection.start===valueLength;if(cursorAtEdge&&!valueLength){self.advanceCaret(direction,e)}}else{$tail=self.$control.children(".active:"+tail);if($tail.length){idx=self.$control.children(":not(input)").index($tail);self.setActiveItem(null);self.setCaret(direction>0?idx+1:idx)}}},advanceCaret:function(direction,e){var self=this,fn,$adj;if(direction===0)return;fn=direction>0?"next":"prev";if(self.isShiftDown){$adj=self.$control_input[fn]();if($adj.length){self.hideInput();self.setActiveItem($adj);e&&e.preventDefault()}}else{self.setCaret(self.caretPos+direction)}},setCaret:function(i){var self=this;if(self.settings.mode==="single"){i=self.items.length}else{i=Math.max(0,Math.min(self.items.length,i))}if(!self.isPending){var j,n,fn,$children,$child;$children=self.$control.children(":not(input)");for(j=0,n=$children.length;j<n;
4784j++){$child=$($children[j]).detach();if(j<i){self.$control_input.before($child)}else{self.$control.append($child)}}}self.caretPos=i},lock:function(){this.close();this.isLocked=true;this.refreshState()},unlock:function(){this.isLocked=false;this.refreshState()},disable:function(){var self=this;self.$input.prop("disabled",true);self.$control_input.prop("disabled",true).prop("tabindex",-1);self.isDisabled=true;self.lock()},enable:function(){var self=this;self.$input.prop("disabled",false);self.$control_input.prop("disabled",false).prop("tabindex",self.tabIndex);self.isDisabled=false;self.unlock()},destroy:function(){var self=this;var eventNS=self.eventNS;var revertSettings=self.revertSettings;self.trigger("destroy");self.off();self.$wrapper.remove();self.$dropdown.remove();self.$input.html("").append(revertSettings.$children).removeAttr("tabindex").removeClass("selectized").attr({tabindex:revertSettings.tabindex}).show();self.$control_input.removeData("grow");self.$input.removeData("selectize");if(--Selectize.count==0&&Selectize.$testInput){Selectize.$testInput.remove();Selectize.$testInput=undefined}$(window).off(eventNS);$(document).off(eventNS);$(document.body).off(eventNS);delete self.$input[0].selectize},render:function(templateName,data){var value,id,label;var html="";var cache=false;var self=this;var regex_tag=/^[\t \r\n]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i;if(templateName==="option"||templateName==="item"){value=hash_key(data[self.settings.valueField]);cache=!!value}if(cache){if(!isset(self.renderCache[templateName])){self.renderCache[templateName]={}}if(self.renderCache[templateName].hasOwnProperty(value)){return self.renderCache[templateName][value]}}html=$(self.settings.render[templateName].apply(this,[data,escape_html]));if(templateName==="option"||templateName==="option_create"){if(!data[self.settings.disabledField]){html.attr("data-selectable","")}}else if(templateName==="optgroup"){id=data[self.settings.optgroupValueField]||"";html.attr("data-group",id);if(data[self.settings.disabledField]){html.attr("data-disabled","")}}if(templateName==="option"||templateName==="item"){html.attr("data-value",value||"")}if(cache){self.renderCache[templateName][value]=html[0]}return html[0]},clearCache:function(templateName){var self=this;if(typeof templateName==="undefined"){self.renderCache={}}else{delete self.renderCache[templateName]}},canCreate:function(input){var self=this;if(!self.settings.create)return false;var filter=self.settings.createFilter;return input.length&&(typeof filter!=="function"||filter.apply(self,[input]))&&(typeof filter!=="string"||new RegExp(filter).test(input))&&(!(filter instanceof RegExp)||filter.test(input))}});Selectize.count=0;Selectize.defaults={options:[],optgroups:[],plugins:[],delimiter:",",splitOn:null,persist:true,diacritics:true,create:false,showAddOptionOnCreate:true,createOnBlur:false,createFilter:null,highlight:true,openOnFocus:true,maxOptions:1e3,maxItems:null,hideSelected:null,addPrecedence:false,selectOnTab:true,preload:false,allowEmptyOption:false,showEmptyOptionInDropdown:false,emptyOptionLabel:"--",setFirstOptionActive:false,closeAfterSelect:false,closeDropdownThreshold:250,scrollDuration:60,deselectBehavior:"previous",loadThrottle:300,loadingClass:"loading",dataAttr:"data-data",optgroupField:"optgroup",valueField:"value",labelField:"text",disabledField:"disabled",optgroupLabelField:"label",optgroupValueField:"value",lockOptgroupOrder:false,sortField:"$order",searchField:["text"],searchConjunction:"and",respect_word_boundaries:true,mode:null,wrapperClass:"",inputClass:"",dropdownClass:"",dropdownContentClass:"",dropdownParent:null,copyClassesToDropdown:true,dropdownSize:{sizeType:"auto",sizeValue:"auto"},normalize:false,ignoreOnDropwdownHeight:"img, i",search:true,render:{}};$.fn.em_selectize=function(settings_user){var defaults=$.fn.em_selectize.defaults;var settings=$.extend({},defaults,settings_user);var attr_data=settings.dataAttr;var field_label=settings.labelField;var field_value=settings.valueField;var field_disabled=settings.disabledField;var field_optgroup=settings.optgroupField;var field_optgroup_label=settings.optgroupLabelField;var field_optgroup_value=settings.optgroupValueField;var init_textbox=function($input,settings_element){var i,n,values,option;var data_raw=$input.attr(attr_data);if(!data_raw){var value=($input.val()||"").trim();if(!settings.allowEmptyOption&&!value.length)return;values=value.split(settings.delimiter);for(i=0,n=values.length;i<n;i++){option={};option[field_label]=values[i];option[field_value]=values[i];settings_element.options.push(option)}settings_element.items=values}else{settings_element.options=JSON.parse(data_raw);for(i=0,n=settings_element.options.length;i<n;i++){settings_element.items.push(settings_element.options[i][field_value])}}};var init_select=function($input,settings_element){var i,n,tagName,$children,order=0;var options=settings_element.options;var optionsMap={};var readData=function($el){var data=attr_data&&$el.attr(attr_data);var allData=$el.data();var obj={};if(typeof data==="string"&&data.length){if(isJSON(data)){Object.assign(obj,JSON.parse(data))}else{obj[data]=data}
4784}Object.assign(obj,allData);return obj||null};var addOption=function($option,group){$option=$($option);var value=hash_key($option.val());if(!value&&!settings.allowEmptyOption)return;if(optionsMap.hasOwnProperty(value)){if(group){var arr=optionsMap[value][field_optgroup];if(!arr){optionsMap[value][field_optgroup]=group}else if(!Array.isArray(arr)){optionsMap[value][field_optgroup]=[arr,group]}else{arr.push(group)}}return}var option=readData($option)||{};option[field_label]=option[field_label]||$option.text();option[field_value]=option[field_value]||value;option[field_disabled]=option[field_disabled]||$option.prop("disabled");option[field_optgroup]=option[field_optgroup]||group;option.styles=$option.attr("style")||"";option.classes=$option.attr("class")||"";optionsMap[value]=option;options.push(option);if($option.is(":selected")){settings_element.items.push(value)}};var addGroup=function($optgroup){var i,n,id,optgroup,$options;$optgroup=$($optgroup);id=$optgroup.attr("label");if(id){optgroup=readData($optgroup)||{};optgroup[field_optgroup_label]=id;optgroup[field_optgroup_value]=id;optgroup[field_disabled]=$optgroup.prop("disabled");settings_element.optgroups.push(optgroup)}$options=$("option",$optgroup);for(i=0,n=$options.length;i<n;i++){addOption($options[i],id)}};settings_element.maxItems=$input.attr("multiple")?null:1;$children=$input.children();for(i=0,n=$children.length;i<n;i++){tagName=$children[i].tagName.toLowerCase();if(tagName==="optgroup"){addGroup($children[i])}else if(tagName==="option"){addOption($children[i])}}};return this.each(function(){if(this.selectize)return;var instance;var $input=$(this);var tag_name=this.tagName.toLowerCase();var placeholder=$input.attr("placeholder")||$input.attr("data-placeholder");if(!placeholder&&!settings.allowEmptyOption){placeholder=$input.children('option[value=""]').text()}if(settings.allowEmptyOption&&settings.showEmptyOptionInDropdown&&!$input.children('option[value=""]').length){var input_html=$input.html();var label=escape_html(settings.emptyOptionLabel||"--");$input.html('<option value="">'+label+"</option>"+input_html)}var settings_element={placeholder:placeholder,options:[],optgroups:[],items:[]};if(tag_name==="select"){init_select($input,settings_element)}else{init_textbox($input,settings_element)}instance=new Selectize($input,$.extend(true,{},defaults,settings_element,settings_user));instance.settings_user=settings_user})};$.fn.em_selectize.defaults=Selectize.defaults;$.fn.em_selectize.support={validity:SUPPORTS_VALIDITY_API};Selectize.define("auto_position",function(){var self=this;const POSITION={top:"top",bottom:"bottom"};self.positionDropdown=function(){return function(){const $control=this.$control;const offset=this.settings.dropdownParent==="body"?$control.offset():$control.position();offset.top+=$control.outerHeight(true);const dropdownHeight=this.$dropdown.prop("scrollHeight")+5;const controlPosTop=this.$control.get(0).getBoundingClientRect().top;const wrapperHeight=this.$wrapper.height();const position=controlPosTop+dropdownHeight+wrapperHeight>window.innerHeight?POSITION.top:POSITION.bottom;const styles={width:$control.outerWidth(),left:offset.left};if(position===POSITION.top){const styleToAdd={bottom:offset.top,top:"unset"};if(this.settings.dropdownParent==="body"){styleToAdd.top=offset.top-this.$dropdown.outerHeight(true)-$control.outerHeight(true);styleToAdd.bottom="unset"}Object.assign(styles,styleToAdd);this.$dropdown.addClass("selectize-position-top");this.$control.addClass("selectize-position-top")}else{Object.assign(styles,{top:offset.top,bottom:"unset"});this.$dropdown.removeClass("selectize-position-top");this.$control.removeClass("selectize-position-top")}this.$dropdown.css(styles)}}()});Selectize.define("auto_select_on_type",function(options){var self=this;self.onBlur=function(){var originalBlur=self.onBlur;return function(e){var $matchedItem=self.getFirstItemMatchedByTextContent(self.lastValue,true);if(typeof $matchedItem.attr("data-value")!=="undefined"&&self.getValue()!==$matchedItem.attr("data-value")){self.setValue($matchedItem.attr("data-value"))}return originalBlur.apply(this,arguments)}}()});Selectize.define("autofill_disable",function(options){var self=this;self.setup=function(){var original=self.setup;return function(){original.apply(self,arguments);self.$control_input.attr({autocomplete:"new-password",autofill:"no"})}}()});Selectize.define("clear_button",function(options){var self=this;options=$.extend({title:"Clear",className:"clear",label:"×",html:function(data){return'<a class="'+data.className+'" title="'+data.title+'"> '+data.label+"</a>"}},options);self.setup=function(){var original=self.setup;return function(){original.apply(self,arguments);self.$button_clear=$(options.html(options));if(self.settings.mode==="single")self.$wrapper.addClass("single");self.$wrapper.append(self.$button_clear);if(self.getValue()===""||self.getValue().length===0){self.$wrapper.find("."+options.className).css("display","none")}self.on("change",function(){if(self.getValue()===""||self.getValue().length===0){self.$wrapper.find("."+options.className).css("display","none")}else{self.$wrapper.find("."+options.className).css("display","")}});self.$wrapper.on("click","."+options.className,function(e){e.preventDefault();e.stopImmediatePropagation();e.stopPropagation();if(self.isLocked)return;self.clear();self.$wrapper.find("."+options.className).css("display","none")})}}()});Selectize.define("drag_drop",function(options){if(!$.fn.sortable)throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".');if(this.settings.mode!=="multi")return;var self=this;self.lock=function(){var original=self.lock;return function(){var sortable=self.$control.data("sortable");if(sortable)sortable.disable();return original.apply(self,arguments)}}();self.unlock=function(){var original=self.unlock;return function(){var sortable=self.$control.data("sortable");if(sortable)sortable.enable();return original.apply(self,arguments)}}();self.setup=function(){var original=self.setup;return function(){original.apply(this,arguments);
4784var $control=self.$control.sortable({items:"[data-value]",forcePlaceholderSize:true,disabled:self.isLocked,start:function(e,ui){ui.placeholder.css("width",ui.helper.css("width"));$control.addClass("dragging")},stop:function(){$control.removeClass("dragging");var active=self.$activeItems?self.$activeItems.slice():null;var values=[];$control.children("[data-value]").each(function(){values.push($(this).attr("data-value"))});self.isFocused=false;self.setValue(values);self.isFocused=true;self.setActiveItem(active);self.positionDropdown()}})}}()});Selectize.define("dropdown_header",function(options){var self=this;options=$.extend({title:"Untitled",headerClass:"selectize-dropdown-header",titleRowClass:"selectize-dropdown-header-title",labelClass:"selectize-dropdown-header-label",closeClass:"selectize-dropdown-header-close",html:function(data){return'<div class="'+data.headerClass+'">'+'<div class="'+data.titleRowClass+'">'+'<span class="'+data.labelClass+'">'+data.title+"</span>"+'<a href="javascript:void(0)" class="'+data.closeClass+'">&#xd7;</a>'+"</div>"+"</div>"}},options);self.setup=function(){var original=self.setup;return function(){original.apply(self,arguments);self.$dropdown_header=$(options.html(options));self.$dropdown.prepend(self.$dropdown_header);self.$dropdown_header.find("."+options.closeClass).on("click",function(){self.close()})}}()});Selectize.define("optgroup_columns",function(options){var self=this;options=$.extend({equalizeWidth:true,equalizeHeight:true},options);this.getAdjacentOption=function($option,direction){var $options=$option.closest("[data-group]").find("[data-selectable]");var index=$options.index($option)+direction;return index>=0&&index<$options.length?$options.eq(index):$()};this.onKeyDown=function(){var original=self.onKeyDown;return function(e){var index,$option,$options,$optgroup;if(this.isOpen&&(e.keyCode===KEY_LEFT||e.keyCode===KEY_RIGHT)){self.ignoreHover=true;$optgroup=this.$activeOption.closest("[data-group]");index=$optgroup.find("[data-selectable]").index(this.$activeOption);if(e.keyCode===KEY_LEFT){$optgroup=$optgroup.prev("[data-group]")}else{$optgroup=$optgroup.next("[data-group]")}$options=$optgroup.find("[data-selectable]");$option=$options.eq(Math.min($options.length-1,index));if($option.length){this.setActiveOption($option)}return}return original.apply(this,arguments)}}();var getScrollbarWidth=function(){var div;var width=getScrollbarWidth.width;var doc=document;if(typeof width==="undefined"){div=doc.createElement("div");div.innerHTML='<div style="width:50px;height:50px;position:absolute;left:-50px;top:-50px;overflow:auto;"><div style="width:1px;height:100px;"></div></div>';div=div.firstChild;doc.body.appendChild(div);width=getScrollbarWidth.width=div.offsetWidth-div.clientWidth;doc.body.removeChild(div)}return width};var equalizeSizes=function(){var i,n,height_max,width,width_last,width_parent,$optgroups;$optgroups=$("[data-group]",self.$dropdown_content);n=$optgroups.length;if(!n||!self.$dropdown_content.width())return;if(options.equalizeHeight){height_max=0;for(i=0;i<n;i++){height_max=Math.max(height_max,$optgroups.eq(i).height())}$optgroups.css({height:height_max})}if(options.equalizeWidth){width_parent=self.$dropdown_content.innerWidth()-getScrollbarWidth();width=Math.round(width_parent/n);$optgroups.css({width:width});if(n>1){width_last=width_parent-width*(n-1);$optgroups.eq(n-1).css({width:width_last})}}};if(options.equalizeHeight||options.equalizeWidth){hook.after(this,"positionDropdown",equalizeSizes);hook.after(this,"refreshOptions",equalizeSizes)}});Selectize.define("remove_button",function(options){if(this.settings.mode==="single")return;options=$.extend({label:"&#xd7;",title:"Remove",className:"remove",append:true},options);var multiClose=function(thisRef,options){var self=thisRef;var html='<a href="javascript:void(0)" class="'+options.className+'" tabindex="-1" title="'+escape_html(options.title)+'">'+options.label+"</a>";var append=function(html_container,html_element){var pos=html_container.search(/(<\/[^>]+>\s*)$/);return html_container.substring(0,pos)+html_element+html_container.substring(pos)};thisRef.setup=function(){var original=self.setup;return function(){if(options.append){var render_item=self.settings.render.item;self.settings.render.item=function(data){return append(render_item.apply(thisRef,arguments),html)}}original.apply(thisRef,arguments);thisRef.$control.on("click","."+options.className,function(e){e.preventDefault();if(self.isLocked)return;var $item=$(e.currentTarget).parent();self.setActiveItem($item);if(self.deleteSelection()){self.setCaret(self.items.length)}return false})}}()};multiClose(this,options)});Selectize.define("restore_on_backspace",function(options){var self=this;options.text=options.text||function(option){return option[this.settings.labelField]};this.onKeyDown=function(){var original=self.onKeyDown;return function(e){var index,option;if(e.keyCode===KEY_BACKSPACE&&this.$control_input.val()===""&&!this.$activeItems.length){index=this.caretPos-1;if(index>=0&&index<this.items.length){option=this.options[this.items[index]];if(this.deleteSelection(e)){this.setTextboxValue(options.text.apply(this,[option]));this.refreshOptions(true)}e.preventDefault();return}}return original.apply(this,arguments)}}()});Selectize.define("select_on_focus",function(options){var self=this;self.on("focus",function(){var originalFocus=self.onFocus;return function(e){var value=self.getItem(self.getValue()).text();self.clear();self.setTextboxValue(value);self.$control_input.select();setTimeout(function(){if(self.settings.selectOnTab){self.setActiveOption(self.getFirstItemMatchedByTextContent(value))}self.settings.score=null},0);return originalFocus.apply(this,arguments)}}());self.onBlur=function(){var originalBlur=self.onBlur;return function(e){if(self.getValue()===""&&self.lastValidValue!==self.getValue()){self.setValue(self.lastValidValue)}setTimeout(function(){self.settings.score=function(){return function(){return 1}}},0);return originalBlur.apply(this,arguments)}}();self.settings.score=function(){return function(){return 1}}});Selectize.define("tag_limit",function(options){const self=this;options.tagLimit=options.tagLimit;this.onBlur=function(e){const original=self.onBlur;return function(e){original.apply(this,e);if(!e)return;const $control=this.$control;
4784const $items=$control.find(".item");const limit=options.tagLimit;if(limit===undefined||$items.length<=limit)return;$items.toArray().forEach(function(item,index){if(index<limit)return;$(item).hide()});$control.append("<span><b>"+($items.length-limit)+"</b></span>")}}();this.onFocus=function(e){const original=self.onFocus;return function(e){original.apply(this,e);if(!e)return;const $control=this.$control;const $items=$control.find(".item");$items.show();$control.find("span").remove()}}()});return Selectize});
4785/*!
4786 * selectize click2deselect (custom)
4787 */
4788/* Selectize deselect function */
4789EM_Selectize.define("click2deselect",function(options){var self=this;var setup=self.setup;this.setup=function(){setup.apply(self,arguments);let just_added;self.$dropdown.each(function(){this.addEventListener("click",function(e){let target=e.target.matches(".selected[data-selectable]")?e.target:e.target.closest(".selected[data-selectable]");if(target!==null){let value=target.getAttribute("data-value");if(value!==just_added){self.removeItem(value);self.refreshItems();self.refreshOptions()}}just_added=false;return false})});self.on("item_remove",function(value){self.getOption(value).removeClass("selected")});self.on("item_add",function(value){just_added=value})}});
4790
4791/*! Sortable 1.15.2 - MIT | git://github.com/SortableJS/Sortable.git */
4792!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).Sortable=e()}(this,function(){"use strict";function e(e,t){var n,o=Object.keys(e);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(e),t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),o.push.apply(o,n)),o}function I(o){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?e(Object(i),!0).forEach(function(t){var e,n;e=o,t=i[n=t],n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach(function(t){Object.defineProperty(o,t,Object.getOwnPropertyDescriptor(i,t))})}return o}function o(t){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function a(){return(a=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n,o=arguments[e];for(n in o)Object.prototype.hasOwnProperty.call(o,n)&&(t[n]=o[n])}return t}).apply(this,arguments)}function i(t,e){if(null==t)return{};var n,o=function(t,e){if(null==t)return{};for(var n,o={},i=Object.keys(t),r=0;r<i.length;r++)n=i[r],0<=e.indexOf(n)||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols)for(var i=Object.getOwnPropertySymbols(t),r=0;r<i.length;r++)n=i[r],0<=e.indexOf(n)||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n]);return o}function r(t){return function(t){if(Array.isArray(t))return l(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return l(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Map"===(n="Object"===n&&t.constructor?t.constructor.name:n)||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?l(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=new Array(e);n<e;n++)o[n]=t[n];return o}function t(t){if("undefined"!=typeof window&&window.navigator)return!!navigator.userAgent.match(t)}var y=t(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),w=t(/Edge/i),s=t(/firefox/i),u=t(/safari/i)&&!t(/chrome/i)&&!t(/android/i),n=t(/iP(ad|od|hone)/i),c=t(/chrome/i)&&t(/android/i),d={capture:!1,passive:!1};function h(t,e,n){t.addEventListener(e,n,!y&&d)}function f(t,e,n){t.removeEventListener(e,n,!y&&d)}function p(t,e){if(e&&(">"===e[0]&&(e=e.substring(1)),t))try{if(t.matches)return t.matches(e);
vendor: 41,754 bytes, lines 4792-4796
4792if(t.msMatchesSelector)return t.msMatchesSelector(e);if(t.webkitMatchesSelector)return t.webkitMatchesSelector(e)}catch(t){return}}function P(t,e,n,o){if(t){n=n||document;do{if(null!=e&&(">"!==e[0]||t.parentNode===n)&&p(t,e)||o&&t===n)return t}while(t!==n&&(t=(i=t).host&&i!==document&&i.host.nodeType?i.host:i.parentNode))}var i;return null}var g,m=/\s+/g;function k(t,e,n){var o;t&&e&&(t.classList?t.classList[n?"add":"remove"](e):(o=(" "+t.className+" ").replace(m," ").replace(" "+e+" "," "),t.className=(o+(n?" "+e:"")).replace(m," ")))}function R(t,e,n){var o=t&&t.style;if(o){if(void 0===n)return document.defaultView&&document.defaultView.getComputedStyle?n=document.defaultView.getComputedStyle(t,""):t.currentStyle&&(n=t.currentStyle),void 0===e?n:n[e];o[e=!(e in o||-1!==e.indexOf("webkit"))?"-webkit-"+e:e]=n+("string"==typeof n?"":"px")}}function v(t,e){var n="";if("string"==typeof t)n=t;else do{var o=R(t,"transform")}while(o&&"none"!==o&&(n=o+" "+n),!e&&(t=t.parentNode));var i=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return i&&new i(n)}function b(t,e,n){if(t){var o=t.getElementsByTagName(e),i=0,r=o.length;if(n)for(;i<r;i++)n(o[i],i);return o}return[]}function O(){var t=document.scrollingElement;return t||document.documentElement}function X(t,e,n,o,i){if(t.getBoundingClientRect||t===window){var r,a,l,s,c,u,d=t!==window&&t.parentNode&&t!==O()?(a=(r=t.getBoundingClientRect()).top,l=r.left,s=r.bottom,c=r.right,u=r.height,r.width):(l=a=0,s=window.innerHeight,c=window.innerWidth,u=window.innerHeight,window.innerWidth);if((e||n)&&t!==window&&(i=i||t.parentNode,!y))do{if(i&&i.getBoundingClientRect&&("none"!==R(i,"transform")||n&&"static"!==R(i,"position"))){var h=i.getBoundingClientRect();a-=h.top+parseInt(R(i,"border-top-width")),l-=h.left+parseInt(R(i,"border-left-width")),s=a+r.height,c=l+r.width;break}}while(i=i.parentNode);return o&&t!==window&&(o=(e=v(i||t))&&e.a,t=e&&e.d,e&&(s=(a/=t)+(u/=t),c=(l/=o)+(d/=o))),{top:a,left:l,bottom:s,right:c,width:d,height:u}}}function Y(t,e,n){for(var o=M(t,!0),i=X(t)[e];o;){var r=X(o)[n];if(!("top"===n||"left"===n?r<=i:i<=r))return o;if(o===O())break;o=M(o,!1)}return!1}function B(t,e,n,o){for(var i=0,r=0,a=t.children;r<a.length;){if("none"!==a[r].style.display&&a[r]!==Ft.ghost&&(o||a[r]!==Ft.dragged)&&P(a[r],n.draggable,t,!1)){if(i===e)return a[r];i++}r++}return null}function F(t,e){for(var n=t.lastElementChild;n&&(n===Ft.ghost||"none"===R(n,"display")||e&&!p(n,e));)n=n.previousElementSibling;return n||null}function j(t,e){var n=0;if(!t||!t.parentNode)return-1;for(;t=t.previousElementSibling;)"TEMPLATE"===t.nodeName.toUpperCase()||t===Ft.clone||e&&!p(t,e)||n++;return n}function E(t){var e=0,n=0,o=O();if(t)do{var i=v(t),r=i.a,i=i.d}while(e+=t.scrollLeft*r,n+=t.scrollTop*i,t!==o&&(t=t.parentNode));return[e,n]}function M(t,e){if(!t||!t.getBoundingClientRect)return O();var n=t,o=!1;do{if(n.clientWidth<n.scrollWidth||n.clientHeight<n.scrollHeight){var i=R(n);if(n.clientWidth<n.scrollWidth&&("auto"==i.overflowX||"scroll"==i.overflowX)||n.clientHeight<n.scrollHeight&&("auto"==i.overflowY||"scroll"==i.overflowY)){if(!n.getBoundingClientRect||n===document.body)return O();if(o||e)return n;o=!0}}}while(n=n.parentNode);return O()}function D(t,e){return Math.round(t.top)===Math.round(e.top)&&Math.round(t.left)===Math.round(e.left)&&Math.round(t.height)===Math.round(e.height)&&Math.round(t.width)===Math.round(e.width)}function S(e,n){return function(){var t;g||(1===(t=arguments).length?e.call(this,t[0]):e.apply(this,t),g=setTimeout(function(){g=void 0},n))}}function H(t,e,n){t.scrollLeft+=e,t.scrollTop+=n}function _(t){var e=window.Polymer,n=window.jQuery||window.Zepto;return e&&e.dom?e.dom(t).cloneNode(!0):n?n(t).clone(!0)[0]:t.cloneNode(!0)}function C(t,e){R(t,"position","absolute"),R(t,"top",e.top),R(t,"left",e.left),R(t,"width",e.width),R(t,"height",e.height)}function T(t){R(t,"position",""),R(t,"top",""),R(t,"left",""),R(t,"width",""),R(t,"height","")}function L(n,o,i){var r={};return Array.from(n.children).forEach(function(t){var e;P(t,o.draggable,n,!1)&&!t.animated&&t!==i&&(e=X(t),r.left=Math.min(null!==(t=r.left)&&void 0!==t?t:1/0,e.left),r.top=Math.min(null!==(t=r.top)&&void 0!==t?t:1/0,e.top),r.right=Math.max(null!==(t=r.right)&&void 0!==t?t:-1/0,e.right),r.bottom=Math.max(null!==(t=r.bottom)&&void 0!==t?t:-1/0,e.bottom))}),r.width=r.right-r.left,r.height=r.bottom-r.top,r.x=r.left,r.y=r.top,r}var K="Sortable"+(new Date).getTime();function x(){var e,o=[];return{captureAnimationState:function(){o=[],this.options.animation&&[].slice.call(this.el.children).forEach(function(t){var e,n;"none"!==R(t,"display")&&t!==Ft.ghost&&(o.push({target:t,rect:X(t)}),e=I({},o[o.length-1].rect),!t.thisAnimationDuration||(n=v(t,!0))&&(e.top-=n.f,e.left-=n.e),t.fromRect=e)})},addAnimationState:function(t){o.push(t)},removeAnimationState:function(t){o.splice(function(t,e){for(var n in t)if(t.hasOwnProperty(n))for(var o in e)if(e.hasOwnProperty(o)&&e[o]===t[n][o])return Number(n);return-1}(o,{target:t}),1)},animateAll:function(t){var c=this;if(!this.options.animation)return clearTimeout(e),void("function"==typeof t&&t());var u=!1,d=0;o.forEach(function(t){var e=0,n=t.target,o=n.fromRect,i=X(n),r=n.prevFromRect,a=n.prevToRect,l=t.rect,s=v(n,!0);s&&(i.top-=s.f,i.left-=s.e),n.toRect=i,n.thisAnimationDuration&&D(r,i)&&!D(o,i)&&(l.top-i.top)/(l.left-i.left)==(o.top-i.top)/(o.left-i.left)&&(t=l,s=r,r=a,a=c.options,e=Math.sqrt(Math.pow(s.top-t.top,2)+Math.pow(s.left-t.left,2))/Math.sqrt(Math.pow(s.top-r.top,2)+Math.pow(s.left-r.left,2))*a.animation),D(i,o)||(n.prevFromRect=o,n.prevToRect=i,e=e||c.options.animation,c.animate(n,l,i,e)),e&&(u=!0,d=Math.max(d,e),clearTimeout(n.animationResetTimer),n.animationResetTimer=setTimeout(function(){n.animationTime=0,n.prevFromRect=null,n.fromRect=null,n.prevToRect=null,n.thisAnimationDuration=null},e),n.thisAnimationDuration=e)}),clearTimeout(e),u?e=setTimeout(function(){"function"==typeof t&&t()},d):"function"==typeof t&&t(),o=[]},animate:function(t,e,n,o){var i,r;o&&(R(t,"transition",""),R(t,"transform",""),i=(r=v(this.el))&&r.a,r=r&&r.d,i=(e.left-n.left)/(i||1),r=(e.top-n.top)/(r||1),t.animatingX=!!i,t.animatingY=!!r,R(t,"transform","translate3d("+i+"px,"+r+"px,0)"),this.forRepaintDummy=t.offsetWidth,R(t,"transition","transform "+o+"ms"+(this.options.easing?" "+this.options.easing:"")),R(t,"transform","translate3d(0,0,0)"),"number"==typeof t.animated&&clearTimeout(t.animated),t.animated=setTimeout(function(){R(t,"transition",""),R(t,"transform",""),t.animated=!1,t.animatingX=!1,t.animatingY=!1},o))}}}var A=[],N={initializeByDefault:!0},W={mount:function(e){for(var t in N)!N.hasOwnProperty(t)||t in e||(e[t]=N[t]);A.forEach(function(t){if(t.pluginName===e.pluginName)throw"Sortable: Cannot mount plugin ".concat(e.pluginName," more than once")}),A.push(e)},pluginEvent:function(e,n,o){var t=this;this.eventCanceled=!1,o.cancel=function(){t.eventCanceled=!0};var i=e+"Global";A.forEach(function(t){n[t.pluginName]&&(n[t.pluginName][i]&&n[t.pluginName][i](I({sortable:n},o)),n.options[t.pluginName]&&n[t.pluginName][e]&&n[t.pluginName][e](I({sortable:n},o)))})},initializePlugins:function(n,o,i,t){for(var e in A.forEach(function(t){var e=t.pluginName;(n.options[e]||t.initializeByDefault)&&((t=new t(n,o,n.options)).sortable=n,t.options=n.options,n[e]=t,a(i,t.defaults))}),n.options){var r;n.options.hasOwnProperty(e)&&(void 0!==(r=this.modifyOption(n,e,n.options[e]))&&(n.options[e]=r))}},getEventProperties:function(e,n){var o={};return A.forEach(function(t){"function"==typeof t.eventProperties&&a(o,t.eventProperties.call(n[t.pluginName],e))}),o},modifyOption:function(e,n,o){var i;return A.forEach(function(t){e[t.pluginName]&&t.optionListeners&&"function"==typeof t.optionListeners[n]&&(i=t.optionListeners[n].call(e[t.pluginName],o))}),i}};function z(t){var e=t.sortable,n=t.rootEl,o=t.name,i=t.targetEl,r=t.cloneEl,a=t.toEl,l=t.fromEl,s=t.oldIndex,c=t.newIndex,u=t.oldDraggableIndex,d=t.newDraggableIndex,h=t.originalEvent,f=t.putSortable,p=t.extraEventProperties;if(e=e||n&&n[K]){var g,m=e.options,t="on"+o.charAt(0).toUpperCase()+o.substr(1);!window.CustomEvent||y||w?(g=document.createEvent("Event")).initEvent(o,!0,!0):g=new CustomEvent(o,{bubbles:!0,cancelable:!0}),g.to=a||n,g.from=l||n,g.item=i||n,g.clone=r,g.oldIndex=s,g.newIndex=c,g.oldDraggableIndex=u,g.newDraggableIndex=d,g.originalEvent=h,g.pullMode=f?f.lastPutMode:void 0;var v,b=I(I({},p),W.getEventProperties(o,e));for(v in b)g[v]=b[v];n&&n.dispatchEvent(g),m[t]&&m[t].call(e,g)}}function G(t,e){var n=(o=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{}).evt,o=i(o,U);W.pluginEvent.bind(Ft)(t,e,I({dragEl:V,parentEl:Z,ghostEl:$,rootEl:Q,nextEl:J,lastDownEl:tt,cloneEl:et,cloneHidden:nt,dragStarted:gt,putSortable:st,activeSortable:Ft.active,originalEvent:n,oldIndex:ot,oldDraggableIndex:rt,newIndex:it,newDraggableIndex:at,hideGhostForTarget:Rt,unhideGhostForTarget:Xt,cloneNowHidden:function(){nt=!0},cloneNowShown:function(){nt=!1},dispatchSortableEvent:function(t){q({sortable:e,name:t,originalEvent:n})}},o))}var U=["evt"];function q(t){z(I({putSortable:st,cloneEl:et,targetEl:V,rootEl:Q,oldIndex:ot,oldDraggableIndex:rt,newIndex:it,newDraggableIndex:at},t))}var V,Z,$,Q,J,tt,et,nt,ot,it,rt,at,lt,st,ct,ut,dt,ht,ft,pt,gt,mt,vt,bt,yt,wt=!1,Et=!1,Dt=[],St=!1,_t=!1,Ct=[],Tt=!1,xt=[],Ot="undefined"!=typeof document,Mt=n,At=w||y?"cssFloat":"float",Nt=Ot&&!c&&!n&&"draggable"in document.createElement("div"),It=function(){if(Ot){if(y)return!1;var t=document.createElement("x");return t.style.cssText="pointer-events:auto","auto"===t.style.pointerEvents}}(),Pt=function(t,e){var n=R(t),o=parseInt(n.width)-parseInt(n.paddingLeft)-parseInt(n.paddingRight)-parseInt(n.borderLeftWidth)-parseInt(n.borderRightWidth),i=B(t,0,e),r=B(t,1,e),a=i&&R(i),l=r&&R(r),s=a&&parseInt(a.marginLeft)+parseInt(a.marginRight)+X(i).width,t=l&&parseInt(l.marginLeft)+parseInt(l.marginRight)+X(r).width;if("flex"===n.display)return"column"===n.flexDirection||"column-reverse"===n.flexDirection?"vertical":"horizontal";if("grid"===n.display)return n.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(i&&a.float&&"none"!==a.float){e="left"===a.float?"left":"right";return!r||"both"!==l.clear&&l.clear!==e?"horizontal":"vertical"}return i&&("block"===a.display||"flex"===a.display||"table"===a.display||"grid"===a.display||o<=s&&"none"===n[At]||r&&"none"===n[At]&&o<s+t)?"vertical":"horizontal"},kt=function(t){function l(r,a){return function(t,e,n,o){var i=t.options.group.name&&e.options.group.name&&t.options.group.name===e.options.group.name;if(null==r&&(a||i))return!0;if(null==r||!1===r)return!1;if(a&&"clone"===r)return r;if("function"==typeof r)return l(r(t,e,n,o),a)(t,e,n,o);e=(a?t:e).options.group.name;return!0===r||"string"==typeof r&&r===e||r.join&&-1<r.indexOf(e)}}var e={},n=t.group;n&&"object"==o(n)||(n={name:n}),e.name=n.name,e.checkPull=l(n.pull,!0),e.checkPut=l(n.put),e.revertClone=n.revertClone,t.group=e},Rt=function(){!It&&$&&R($,"display","none")},Xt=function(){!It&&$&&R($,"display","")};Ot&&!c&&document.addEventListener("click",function(t){if(Et)return t.preventDefault(),t.stopPropagation&&t.stopPropagation(),t.stopImmediatePropagation&&t.stopImmediatePropagation(),Et=!1},!0);function Yt(t){if(V){t=t.touches?t.touches[0]:t;var e=(i=t.clientX,r=t.clientY,Dt.some(function(t){var e=t[K].options.emptyInsertThreshold;if(e&&!F(t)){var n=X(t),o=i>=n.left-e&&i<=n.right+e,e=r>=n.top-e&&r<=n.bottom+e;return o&&e?a=t:void 0}}),a);if(e){var n,o={};for(n in t)t.hasOwnProperty(n)&&(o[n]=t[n]);o.target=o.rootEl=e,o.preventDefault=void 0,o.stopPropagation=void 0,e[K]._onDragOver(o)}}var i,r,a}function Bt(t){V&&V.parentNode[K]._isOutsideThisEl(t.target)}function Ft(t,e){if(!t||!t.nodeType||1!==t.nodeType)throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(t));this.el=t,this.options=e=a({},e),t[K]=this;var n,o,i={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(t.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return Pt(t,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(t,e){t.setData("Text",e.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:!1!==Ft.supportPointer&&"PointerEvent"in window&&!u,emptyInsertThreshold:5};for(n in W.initializePlugins(this,t,i),i)n in e||(e[n]=i[n]);for(o in kt(e),this)"_"===o.charAt(0)&&"function"==typeof this[o]&&(this[o]=this[o].bind(this));this.nativeDraggable=!e.forceFallback&&Nt,this.nativeDraggable&&(this.options.touchStartThreshold=1),e.supportPointer?h(t,"pointerdown",this._onTapStart):(h(t,"mousedown",this._onTapStart),h(t,"touchstart",this._onTapStart)),this.nativeDraggable&&(h(t,"dragover",this),h(t,"dragenter",this)),Dt.push(this.el),e.store&&e.store.get&&this.sort(e.store.get(this)||[]),a(this,x())}function jt(t,e,n,o,i,r,a,l){var s,c,u=t[K],d=u.options.onMove;return!window.CustomEvent||y||w?(s=document.createEvent("Event")).initEvent("move",!0,!0):s=new CustomEvent("move",{bubbles:!0,cancelable:!0}),s.to=e,s.from=t,s.dragged=n,s.draggedRect=o,s.related=i||e,s.relatedRect=r||X(e),s.willInsertAfter=l,s.originalEvent=a,t.dispatchEvent(s),c=d?d.call(u,s,a):c}function Ht(t){t.draggable=!1}function Lt(){Tt=!1}function Kt(t){return setTimeout(t,0)}function Wt(t){return clearTimeout(t)}Ft.prototype={constructor:Ft,_isOutsideThisEl:function(t){this.el.contains(t)||t===this.el||(mt=null)},_getDirection:function(t,e){return"function"==typeof this.options.direction?this.options.direction.call(this,t,e,V):this.options.direction},_onTapStart:function(e){if(e.cancelable){var n=this,o=this.el,t=this.options,i=t.preventOnFilter,r=e.type,a=e.touches&&e.touches[0]||e.pointerType&&"touch"===e.pointerType&&e,l=(a||e).target,s=e.target.shadowRoot&&(e.path&&e.path[0]||e.composedPath&&e.composedPath()[0])||l,c=t.filter;if(!function(t){xt.length=0;var e=t.getElementsByTagName("input"),n=e.length;for(;n--;){var o=e[n];o.checked&&xt.push(o)}}(o),!V&&!(/mousedown|pointerdown/.test(r)&&0!==e.button||t.disabled)&&!s.isContentEditable&&(this.nativeDraggable||!u||!l||"SELECT"!==l.tagName.toUpperCase())&&!((l=P(l,t.draggable,o,!1))&&l.animated||tt===l)){if(ot=j(l),rt=j(l,t.draggable),"function"==typeof c){if(c.call(this,e,l,this))return q({sortable:n,rootEl:s,name:"filter",targetEl:l,toEl:o,fromEl:o}),G("filter",n,{evt:e}),void(i&&e.cancelable&&e.preventDefault())}else if(c=c&&c.split(",").some(function(t){if(t=P(s,t.trim(),o,!1))return q({sortable:n,rootEl:t,name:"filter",targetEl:l,fromEl:o,toEl:o}),G("filter",n,{evt:e}),!0}))return void(i&&e.cancelable&&e.preventDefault());t.handle&&!P(s,t.handle,o,!1)||this._prepareDragStart(e,a,l)}}},_prepareDragStart:function(t,e,n){var o,i=this,r=i.el,a=i.options,l=r.ownerDocument;n&&!V&&n.parentNode===r&&(o=X(n),Q=r,Z=(V=n).parentNode,J=V.nextSibling,tt=n,lt=a.group,ct={target:Ft.dragged=V,clientX:(e||t).clientX,clientY:(e||t).clientY},ft=ct.clientX-o.left,pt=ct.clientY-o.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,V.style["will-change"]="all",o=function(){G("delayEnded",i,{evt:t}),Ft.eventCanceled?i._onDrop():(i._disableDelayedDragEvents(),!s&&i.nativeDraggable&&(V.draggable=!0),i._triggerDragStart(t,e),q({sortable:i,name:"choose",originalEvent:t}),k(V,a.chosenClass,!0))},a.ignore.split(",").forEach(function(t){b(V,t.trim(),Ht)}),h(l,"dragover",Yt),h(l,"mousemove",Yt),h(l,"touchmove",Yt),h(l,"mouseup",i._onDrop),h(l,"touchend",i._onDrop),h(l,"touchcancel",i._onDrop),s&&this.nativeDraggable&&(this.options.touchStartThreshold=4,V.draggable=!0),G("delayStart",this,{evt:t}),!a.delay||a.delayOnTouchOnly&&!e||this.nativeDraggable&&(w||y)?o():Ft.eventCanceled?this._onDrop():(h(l,"mouseup",i._disableDelayedDrag),h(l,"touchend",i._disableDelayedDrag),h(l,"touchcancel",i._disableDelayedDrag),h(l,"mousemove",i._delayedDragTouchMoveHandler),h(l,"touchmove",i._delayedDragTouchMoveHandler),a.supportPointer&&h(l,"pointermove",i._delayedDragTouchMoveHandler),i._dragStartTimer=setTimeout(o,a.delay)))},_delayedDragTouchMoveHandler:function(t){t=t.touches?t.touches[0]:t;Math.max(Math.abs(t.clientX-this._lastX),Math.abs(t.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){V&&Ht(V),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;f(t,"mouseup",this._disableDelayedDrag),f(t,"touchend",this._disableDelayedDrag),f(t,"touchcancel",this._disableDelayedDrag),f(t,"mousemove",this._delayedDragTouchMoveHandler),f(t,"touchmove",this._delayedDragTouchMoveHandler),f(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||"touch"==t.pointerType&&t,!this.nativeDraggable||e?this.options.supportPointer?h(document,"pointermove",this._onTouchMove):h(document,e?"touchmove":"mousemove",this._onTouchMove):(h(V,"dragend",this),h(Q,"dragstart",this._onDragStart));try{document.selection?Kt(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch(t){}},_dragStarted:function(t,e){var n;wt=!1,Q&&V?(G("dragStarted",this,{evt:e}),this.nativeDraggable&&h(document,"dragover",Bt),n=this.options,t||k(V,n.dragClass,!1),k(V,n.ghostClass,!0),Ft.active=this,t&&this._appendGhost(),q({sortable:this,name:"start",originalEvent:e})):this._nulling()},_emulateDragOver:function(){if(ut){this._lastX=ut.clientX,this._lastY=ut.clientY,Rt();for(var t=document.elementFromPoint(ut.clientX,ut.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(ut.clientX,ut.clientY))!==e;)e=t;if(V.parentNode[K]._isOutsideThisEl(t),e)do{if(e[K])if(e[K]._onDragOver({clientX:ut.clientX,clientY:ut.clientY,target:t,rootEl:e})&&!this.options.dragoverBubble)break}while(e=(t=e).parentNode);Xt()}},_onTouchMove:function(t){if(ct){var e=this.options,n=e.fallbackTolerance,o=e.fallbackOffset,i=t.touches?t.touches[0]:t,r=$&&v($,!0),a=$&&r&&r.a,l=$&&r&&r.d,e=Mt&&yt&&E(yt),a=(i.clientX-ct.clientX+o.x)/(a||1)+(e?e[0]-Ct[0]:0)/(a||1),l=(i.clientY-ct.clientY+o.y)/(l||1)+(e?e[1]-Ct[1]:0)/(l||1);if(!Ft.active&&!wt){if(n&&Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))<n)return;this._onDragStart(t,!0)}$&&(r?(r.e+=a-(dt||0),r.f+=l-(ht||0)):r={a:1,b:0,c:0,d:1,e:a,f:l},r="matrix(".concat(r.a,",").concat(r.b,",").concat(r.c,",").concat(r.d,",").concat(r.e,",").concat(r.f,")"),R($,"webkitTransform",r),R($,"mozTransform",r),R($,"msTransform",r),R($,"transform",r),dt=a,ht=l,ut=i),t.cancelable&&t.preventDefault()}},_appendGhost:function(){if(!$){var t=this.options.fallbackOnBody?document.body:Q,e=X(V,!0,Mt,!0,t),n=this.options;if(Mt){for(yt=t;"static"===R(yt,"position")&&"none"===R(yt,"transform")&&yt!==document;)yt=yt.parentNode;yt!==document.body&&yt!==document.documentElement?(yt===document&&(yt=O()),e.top+=yt.scrollTop,e.left+=yt.scrollLeft):yt=O(),Ct=E(yt)}k($=V.cloneNode(!0),n.ghostClass,!1),k($,n.fallbackClass,!0),k($,n.dragClass,!0),R($,"transition",""),R($,"transform",""),R($,"box-sizing","border-box"),R($,"margin",0),R($,"top",e.top),R($,"left",e.left),R($,"width",e.width),R($,"height",e.height),R($,"opacity","0.8"),R($,"position",Mt?"absolute":"fixed"),R($,"zIndex","100000"),R($,"pointerEvents","none"),Ft.ghost=$,t.appendChild($),R($,"transform-origin",ft/parseInt($.style.width)*100+"% "+pt/parseInt($.style.height)*100+"%")}},_onDragStart:function(t,e){var n=this,o=t.dataTransfer,i=n.options;G("dragStart",this,{evt:t}),Ft.eventCanceled?this._onDrop():(G("setupClone",this),Ft.eventCanceled||((et=_(V)).removeAttribute("id"),et.draggable=!1,et.style["will-change"]="",this._hideClone(),k(et,this.options.chosenClass,!1),Ft.clone=et),n.cloneId=Kt(function(){G("clone",n),Ft.eventCanceled||(n.options.removeCloneOnHide||Q.insertBefore(et,V),n._hideClone(),q({sortable:n,name:"clone"}))}),e||k(V,i.dragClass,!0),e?(Et=!0,n._loopId=setInterval(n._emulateDragOver,50)):(f(document,"mouseup",n._onDrop),f(document,"touchend",n._onDrop),f(document,"touchcancel",n._onDrop),o&&(o.effectAllowed="move",i.setData&&i.setData.call(n,o,V)),h(document,"drop",n),R(V,"transform","translateZ(0)")),wt=!0,n._dragStartId=Kt(n._dragStarted.bind(n,e,t)),h(document,"selectstart",n),gt=!0,u&&R(document.body,"user-select","none"))},_onDragOver:function(n){var o,i,r,t,e,a=this.el,l=n.target,s=this.options,c=s.group,u=Ft.active,d=lt===c,h=s.sort,f=st||u,p=this,g=!1;if(!Tt){if(void 0!==n.preventDefault&&n.cancelable&&n.preventDefault(),l=P(l,s.draggable,a,!0),O("dragOver"),Ft.eventCanceled)return g;if(V.contains(n.target)||l.animated&&l.animatingX&&l.animatingY||p._ignoreWhileAnimating===l)return A(!1);if(Et=!1,u&&!s.disabled&&(d?h||(i=Z!==Q):st===this||(this.lastPutMode=lt.checkPull(this,u,V,n))&&c.checkPut(this,u,V,n))){if(r="vertical"===this._getDirection(n,l),o=X(V),O("dragOverValid"),Ft.eventCanceled)return g;if(i)return Z=Q,M(),this._hideClone(),O("revert"),Ft.eventCanceled||(J?Q.insertBefore(V,J):Q.appendChild(V)),A(!0);var m=F(a,s.draggable);if(m&&(S=n,c=r,x=X(F((D=this).el,D.options.draggable)),D=L(D.el,D.options,$),!(c?S.clientX>D.right+10||S.clientY>x.bottom&&S.clientX>x.left:S.clientY>D.bottom+10||S.clientX>x.right&&S.clientY>x.top)||m.animated)){if(m&&(t=n,e=r,C=X(B((_=this).el,0,_.options,!0)),_=L(_.el,_.options,$),e?t.clientX<_.left-10||t.clientY<C.top&&t.clientX<C.right:t.clientY<_.top-10||t.clientY<C.bottom&&t.clientX<C.left)){var v=B(a,0,s,!0);if(v===V)return A(!1);if(E=X(l=v),!1!==jt(Q,a,V,o,l,E,n,!1))return M(),a.insertBefore(V,v),Z=a,N(),A(!0)}else if(l.parentNode===a){var b,y,w,E=X(l),D=V.parentNode!==a,S=(S=V.animated&&V.toRect||o,x=l.animated&&l.toRect||E,_=(e=r)?S.left:S.top,t=e?S.right:S.bottom,C=e?S.width:S.height,v=e?x.left:x.top,S=e?x.right:x.bottom,x=e?x.width:x.height,!(_===v||t===S||_+C/2===v+x/2)),_=r?"top":"left",C=Y(l,"top","top")||Y(V,"top","top"),v=C?C.scrollTop:void 0;if(mt!==l&&(y=E[_],St=!1,_t=!S&&s.invertSwap||D),0!==(b=function(t,e,n,o,i,r,a,l){var s=o?t.clientY:t.clientX,c=o?n.height:n.width,t=o?n.top:n.left,o=o?n.bottom:n.right,n=!1;if(!a)if(l&&bt<c*i){if(St=!St&&(1===vt?t+c*r/2<s:s<o-c*r/2)?!0:St)n=!0;else if(1===vt?s<t+bt:o-bt<s)return-vt}else if(t+c*(1-i)/2<s&&s<o-c*(1-i)/2)return function(t){return j(V)<j(t)?1:-1}(e);if((n=n||a)&&(s<t+c*r/2||o-c*r/2<s))return t+c/2<s?1:-1;return 0}(n,l,E,r,S?1:s.swapThreshold,null==s.invertedSwapThreshold?s.swapThreshold:s.invertedSwapThreshold,_t,mt===l)))for(var T=j(V);(w=Z.children[T-=b])&&("none"===R(w,"display")||w===$););if(0===b||w===l)return A(!1);vt=b;var x=(mt=l).nextElementSibling,D=!1,S=jt(Q,a,V,o,l,E,n,D=1===b);if(!1!==S)return 1!==S&&-1!==S||(D=1===S),Tt=!0,setTimeout(Lt,30),M(),D&&!x?a.appendChild(V):l.parentNode.insertBefore(V,D?x:l),C&&H(C,0,v-C.scrollTop),Z=V.parentNode,void 0===y||_t||(bt=Math.abs(y-X(l)[_])),N(),A(!0)}}else{if(m===V)return A(!1);if((l=m&&a===n.target?m:l)&&(E=X(l)),!1!==jt(Q,a,V,o,l,E,n,!!l))return M(),m&&m.nextSibling?a.insertBefore(V,m.nextSibling):a.appendChild(V),Z=a,N(),A(!0)}if(a.contains(V))return A(!1)}return!1}function O(t,e){G(t,p,I({evt:n,isOwner:d,axis:r?"vertical":"horizontal",revert:i,dragRect:o,targetRect:E,canSort:h,fromSortable:f,target:l,completed:A,onMove:function(t,e){return jt(Q,a,V,o,t,X(t),n,e)},changed:N},e))}function M(){O("dragOverAnimationCapture"),p.captureAnimationState(),p!==f&&f.captureAnimationState()}function A(t){return O("dragOverCompleted",{insertion:t}),t&&(d?u._hideClone():u._showClone(p),p!==f&&(k(V,(st||u).options.ghostClass,!1),k(V,s.ghostClass,!0)),st!==p&&p!==Ft.active?st=p:p===Ft.active&&st&&(st=null),f===p&&(p._ignoreWhileAnimating=l),p.animateAll(function(){O("dragOverAnimationComplete"),p._ignoreWhileAnimating=null}),p!==f&&(f.animateAll(),f._ignoreWhileAnimating=null)),(l===V&&!V.animated||l===a&&!l.animated)&&(mt=null),s.dragoverBubble||n.rootEl||l===document||(V.parentNode[K]._isOutsideThisEl(n.target),t||Yt(n)),!s.dragoverBubble&&n.stopPropagation&&n.stopPropagation(),g=!0}function N(){it=j(V),at=j(V,s.draggable),q({sortable:p,name:"change",toEl:a,newIndex:it,newDraggableIndex:at,originalEvent:n})}},_ignoreWhileAnimating:null,_offMoveEvents:function(){f(document,"mousemove",this._onTouchMove),f(document,"touchmove",this._onTouchMove),f(document,"pointermove",this._onTouchMove),f(document,"dragover",Yt),f(document,"mousemove",Yt),f(document,"touchmove",Yt)},_offUpEvents:function(){var t=this.el.ownerDocument;f(t,"mouseup",this._onDrop),f(t,"touchend",this._onDrop),f(t,"pointerup",this._onDrop),f(t,"touchcancel",this._onDrop),f(document,"selectstart",this)},_onDrop:function(t){var e=this.el,n=this.options;it=j(V),at=j(V,n.draggable),G("drop",this,{evt:t}),Z=V&&V.parentNode,it=j(V),at=j(V,n.draggable),Ft.eventCanceled||(St=_t=wt=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),Wt(this.cloneId),Wt(this._dragStartId),this.nativeDraggable&&(f(document,"drop",this),f(e,"dragstart",this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),u&&R(document.body,"user-select",""),R(V,"transform",""),t&&(gt&&(t.cancelable&&t.preventDefault(),n.dropBubble||t.stopPropagation()),$&&$.parentNode&&$.parentNode.removeChild($),(Q===Z||st&&"clone"!==st.lastPutMode)&&et&&et.parentNode&&et.parentNode.removeChild(et),V&&(this.nativeDraggable&&f(V,"dragend",this),Ht(V),V.style["will-change"]="",gt&&!wt&&k(V,(st||this).options.ghostClass,!1),k(V,this.options.chosenClass,!1),q({sortable:this,name:"unchoose",toEl:Z,newIndex:null,newDraggableIndex:null,originalEvent:t}),Q!==Z?(0<=it&&(q({rootEl:Z,name:"add",toEl:Z,fromEl:Q,originalEvent:t}),q({sortable:this,name:"remove",toEl:Z,originalEvent:t}),q({rootEl:Z,name:"sort",toEl:Z,fromEl:Q,originalEvent:t}),q({sortable:this,name:"sort",toEl:Z,originalEvent:t})),st&&st.save()):it!==ot&&0<=it&&(q({sortable:this,name:"update",toEl:Z,originalEvent:t}),q({sortable:this,name:"sort",toEl:Z,originalEvent:t})),Ft.active&&(null!=it&&-1!==it||(it=ot,at=rt),q({sortable:this,name:"end",toEl:Z,originalEvent:t}),this.save())))),this._nulling()},_nulling:function(){G("nulling",this),Q=V=Z=$=J=et=tt=nt=ct=ut=gt=it=at=ot=rt=mt=vt=st=lt=Ft.dragged=Ft.ghost=Ft.clone=Ft.active=null,xt.forEach(function(t){t.checked=!0}),xt.length=dt=ht=0},handleEvent:function(t){switch(t.type){case"drop":case"dragend":this._onDrop(t);break;case"dragenter":case"dragover":V&&(this._onDragOver(t),function(t){t.dataTransfer&&(t.dataTransfer.dropEffect="move");t.cancelable&&t.preventDefault()}(t));break;case"selectstart":t.preventDefault()}},toArray:function(){for(var t,e=[],n=this.el.children,o=0,i=n.length,r=this.options;o<i;o++)P(t=n[o],r.draggable,this.el,!1)&&e.push(t.getAttribute(r.dataIdAttr)||function(t){var e=t.tagName+t.className+t.src+t.href+t.textContent,n=e.length,o=0;for(;n--;)o+=e.charCodeAt(n);return o.toString(36)}(t));return e},sort:function(t,e){var n={},o=this.el;this.toArray().forEach(function(t,e){e=o.children[e];P(e,this.options.draggable,o,!1)&&(n[t]=e)},this),e&&this.captureAnimationState(),t.forEach(function(t){n[t]&&(o.removeChild(n[t]),o.appendChild(n[t]))}),e&&this.animateAll()},save:function(){var t=this.options.store;t&&t.set&&t.set(this)},closest:function(t,e){return P(t,e||this.options.draggable,this.el,!1)},option:function(t,e){var n=this.options;if(void 0===e)return n[t];var o=W.modifyOption(this,t,e);n[t]=void 0!==o?o:e,"group"===t&&kt(n)},destroy:function(){G("destroy",this);var t=this.el;t[K]=null,f(t,"mousedown",this._onTapStart),f(t,"touchstart",this._onTapStart),f(t,"pointerdown",this._onTapStart),this.nativeDraggable&&(f(t,"dragover",this),f(t,"dragenter",this)),Array.prototype.forEach.call(t.querySelectorAll("[draggable]"),function(t){t.removeAttribute("draggable")}),this._onDrop(),this._disableDelayedDragEvents(),Dt.splice(Dt.indexOf(this.el),1),this.el=t=null},_hideClone:function(){nt||(G("hideClone",this),Ft.eventCanceled||(R(et,"display","none"),this.options.removeCloneOnHide&&et.parentNode&&et.parentNode.removeChild(et),nt=!0))},_showClone:function(t){"clone"===t.lastPutMode?nt&&(G("showClone",this),Ft.eventCanceled||(V.parentNode!=Q||this.options.group.revertClone?J?Q.insertBefore(et,J):Q.appendChild(et):Q.insertBefore(et,V),this.options.group.revertClone&&this.animate(V,et),R(et,"display",""),nt=!1)):this._hideClone()}},Ot&&h(document,"touchmove",function(t){(Ft.active||wt)&&t.cancelable&&t.preventDefault()}),Ft.utils={on:h,off:f,css:R,find:b,is:function(t,e){return!!P(t,e,t,!1)},extend:function(t,e){if(t&&e)for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t},throttle:S,closest:P,toggleClass:k,clone:_,index:j,nextTick:Kt,cancelNextTick:Wt,detectDirection:Pt,getChild:B},Ft.get=function(t){return t[K]},Ft.mount=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];(e=e[0].constructor===Array?e[0]:e).forEach(function(t){if(!t.prototype||!t.prototype.constructor)throw"Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(t));t.utils&&(Ft.utils=I(I({},Ft.utils),t.utils)),W.mount(t)})},Ft.create=function(t,e){return new Ft(t,e)};var zt,Gt,Ut,qt,Vt,Zt,$t=[],Qt=!(Ft.version="1.15.2");function Jt(){$t.forEach(function(t){clearInterval(t.pid)}),$t=[]}function te(){clearInterval(Zt)}var ee,ne=S(function(n,t,e,o){if(t.scroll){var i,r=(n.touches?n.touches[0]:n).clientX,a=(n.touches?n.touches[0]:n).clientY,l=t.scrollSensitivity,s=t.scrollSpeed,c=O(),u=!1;Gt!==e&&(Gt=e,Jt(),zt=t.scroll,i=t.scrollFn,!0===zt&&(zt=M(e,!0)));var d=0,h=zt;do{var f=h,p=X(f),g=p.top,m=p.bottom,v=p.left,b=p.right,y=p.width,w=p.height,E=void 0,D=void 0,S=f.scrollWidth,_=f.scrollHeight,C=R(f),T=f.scrollLeft,p=f.scrollTop,D=f===c?(E=y<S&&("auto"===C.overflowX||"scroll"===C.overflowX||"visible"===C.overflowX),w<_&&("auto"===C.overflowY||"scroll"===C.overflowY||"visible"===C.overflowY)):(E=y<S&&("auto"===C.overflowX||"scroll"===C.overflowX),w<_&&("auto"===C.overflowY||"scroll"===C.overflowY)),T=E&&(Math.abs(b-r)<=l&&T+y<S)-(Math.abs(v-r)<=l&&!!T),p=D&&(Math.abs(m-a)<=l&&p+w<_)-(Math.abs(g-a)<=l&&!!p);if(!$t[d])for(var x=0;x<=d;x++)$t[x]||($t[x]={});$t[d].vx==T&&$t[d].vy==p&&$t[d].el===f||($t[d].el=f,$t[d].vx=T,$t[d].vy=p,clearInterval($t[d].pid),0==T&&0==p||(u=!0,$t[d].pid=setInterval(function(){o&&0===this.layer&&Ft.active._onTouchMove(Vt);var t=$t[this.layer].vy?$t[this.layer].vy*s:0,e=$t[this.layer].vx?$t[this.layer].vx*s:0;"function"==typeof i&&"continue"!==i.call(Ft.dragged.parentNode[K],e,t,n,Vt,$t[this.layer].el)||H($t[this.layer].el,e,t)}.bind({layer:d}),24))),d++}while(t.bubbleScroll&&h!==c&&(h=M(h,!1)));Qt=u}},30),c=function(t){var e=t.originalEvent,n=t.putSortable,o=t.dragEl,i=t.activeSortable,r=t.dispatchSortableEvent,a=t.hideGhostForTarget,t=t.unhideGhostForTarget;e&&(i=n||i,a(),e=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:e,e=document.elementFromPoint(e.clientX,e.clientY),t(),i&&!i.el.contains(e)&&(r("spill"),this.onSpill({dragEl:o,putSortable:n})))};function oe(){}function ie(){}oe.prototype={startIndex:null,dragStart:function(t){t=t.oldDraggableIndex;this.startIndex=t},onSpill:function(t){var e=t.dragEl,n=t.putSortable;this.sortable.captureAnimationState(),n&&n.captureAnimationState();t=B(this.sortable.el,this.startIndex,this.options);t?this.sortable.el.insertBefore(e,t):this.sortable.el.appendChild(e),this.sortable.animateAll(),n&&n.animateAll()},drop:c},a(oe,{pluginName:"revertOnSpill"}),ie.prototype={onSpill:function(t){var e=t.dragEl,t=t.putSortable||this.sortable;t.captureAnimationState(),e.parentNode&&e.parentNode.removeChild(e),t.animateAll()},drop:c},a(ie,{pluginName:"removeOnSpill"});var re,ae,le,se,ce,ue=[],de=[],he=!1,fe=!1,pe=!1;function ge(n,o){de.forEach(function(t,e){e=o.children[t.sortableIndex+(n?Number(e):0)];e?o.insertBefore(t,e):o.appendChild(t)})}function me(){ue.forEach(function(t){t!==le&&t.parentNode&&t.parentNode.removeChild(t)})}return Ft.mount(new function(){function t(){for(var t in this.defaults={scroll:!0,forceAutoScrollFallback:!1,scrollSensitivity:30,scrollSpeed:10,bubbleScroll:!0},this)"_"===t.charAt(0)&&"function"==typeof this[t]&&(this[t]=this[t].bind(this))}return t.prototype={dragStarted:function(t){t=t.originalEvent;this.sortable.nativeDraggable?h(document,"dragover",this._handleAutoScroll):this.options.supportPointer?h(document,"pointermove",this._handleFallbackAutoScroll):t.touches?h(document,"touchmove",this._handleFallbackAutoScroll):h(document,"mousemove",this._handleFallbackAutoScroll)},dragOverCompleted:function(t){t=t.originalEvent;this.options.dragOverBubble||t.rootEl||this._handleAutoScroll(t)},drop:function(){this.sortable.nativeDraggable?f(document,"dragover",this._handleAutoScroll):(f(document,"pointermove",this._handleFallbackAutoScroll),f(document,"touchmove",this._handleFallbackAutoScroll),f(document,"mousemove",this._handleFallbackAutoScroll)),te(),Jt(),clearTimeout(g),g=void 0},nulling:function(){Vt=Gt=zt=Qt=Zt=Ut=qt=null,$t.length=0},_handleFallbackAutoScroll:function(t){this._handleAutoScroll(t,!0)},_handleAutoScroll:function(e,n){var o,i=this,r=(e.touches?e.touches[0]:e).clientX,a=(e.touches?e.touches[0]:e).clientY,t=document.elementFromPoint(r,a);Vt=e,n||this.options.forceAutoScrollFallback||w||y||u?(ne(e,this.options,t,n),o=M(t,!0),!Qt||Zt&&r===Ut&&a===qt||(Zt&&te(),Zt=setInterval(function(){var t=M(document.elementFromPoint(r,a),!0);t!==o&&(o=t,Jt()),ne(e,i.options,t,n)},10),Ut=r,qt=a)):this.options.bubbleScroll&&M(t,!0)!==O()?ne(e,this.options,M(t,!1),!1):Jt()}},a(t,{pluginName:"scroll",initializeByDefault:!0})}),Ft.mount(ie,oe),Ft.mount(new function(){function t(){this.defaults={swapClass:"sortable-swap-highlight"}}return t.prototype={dragStart:function(t){t=t.dragEl;ee=t},dragOverValid:function(t){var e=t.completed,n=t.target,o=t.onMove,i=t.activeSortable,r=t.changed,a=t.cancel;i.options.swap&&(t=this.sortable.el,i=this.options,n&&n!==t&&(t=ee,ee=!1!==o(n)?(k(n,i.swapClass,!0),n):null,t&&t!==ee&&k(t,i.swapClass,!1)),r(),e(!0),a())},drop:function(t){var e,n,o=t.activeSortable,i=t.putSortable,r=t.dragEl,a=i||this.sortable,l=this.options;ee&&k(ee,l.swapClass,!1),ee&&(l.swap||i&&i.options.swap)&&r!==ee&&(a.captureAnimationState(),a!==o&&o.captureAnimationState(),n=ee,t=(e=r).parentNode,l=n.parentNode,t&&l&&!t.isEqualNode(n)&&!l.isEqualNode(e)&&(i=j(e),r=j(n),t.isEqualNode(l)&&i<r&&r++,t.insertBefore(n,t.children[i]),l.insertBefore(e,l.children[r])),a.animateAll(),a!==o&&o.animateAll())},nulling:function(){ee=null}},a(t,{pluginName:"swap",eventProperties:function(){return{swapItem:ee}}})}),Ft.mount(new function(){function t(o){for(var t in this)"_"===t.charAt(0)&&"function"==typeof this[t]&&(this[t]=this[t].bind(this));o.options.avoidImplicitDeselect||(o.options.supportPointer?h(document,"pointerup",this._deselectMultiDrag):(h(document,"mouseup",this._deselectMultiDrag),h(document,"touchend",this._deselectMultiDrag))),h(document,"keydown",this._checkKeyDown),h(document,"keyup",this._checkKeyUp),this.defaults={selectedClass:"sortable-selected",multiDragKey:null,avoidImplicitDeselect:!1,setData:function(t,e){var n="";ue.length&&ae===o?ue.forEach(function(t,e){n+=(e?", ":"")+t.textContent}):n=e.textContent,t.setData("Text",n)}}}return t.prototype={multiDragKeyDown:!1,isMultiDrag:!1,delayStartGlobal:function(t){t=t.dragEl;le=t},delayEnded:function(){this.isMultiDrag=~ue.indexOf(le)},setupClone:function(t){var e=t.sortable,t=t.cancel;if(this.isMultiDrag){for(var n=0;n<ue.length;n++)de.push(_(ue[n])),de[n].sortableIndex=ue[n].sortableIndex,de[n].draggable=!1,de[n].style["will-change"]="",k(de[n],this.options.selectedClass,!1),ue[n]===le&&k(de[n],this.options.chosenClass,!1);e._hideClone(),t()}},clone:function(t){var e=t.sortable,n=t.rootEl,o=t.dispatchSortableEvent,t=t.cancel;this.isMultiDrag&&(this.options.removeCloneOnHide||ue.length&&ae===e&&(ge(!0,n),o("clone"),t()))},showClone:function(t){var e=t.cloneNowShown,n=t.rootEl,t=t.cancel;this.isMultiDrag&&(ge(!1,n),de.forEach(function(t){R(t,"display","")}),e(),ce=!1,t())},hideClone:function(t){var e=this,n=(t.sortable,t.cloneNowHidden),t=t.cancel;this.isMultiDrag&&(de.forEach(function(t){R(t,"display","none"),e.options.removeCloneOnHide&&t.parentNode&&t.parentNode.removeChild(t)}),n(),ce=!0,t())},dragStartGlobal:function(t){t.sortable;!this.isMultiDrag&&ae&&ae.multiDrag._deselectMultiDrag(),ue.forEach(function(t){t.sortableIndex=j(t)}),ue=ue.sort(function(t,e){return t.sortableIndex-e.sortableIndex}),pe=!0},dragStarted:function(t){var e,n=this,t=t.sortable;this.isMultiDrag&&(this.options.sort&&(t.captureAnimationState(),this.options.animation&&(ue.forEach(function(t){t!==le&&R(t,"position","absolute")}),e=X(le,!1,!0,!0),ue.forEach(function(t){t!==le&&C(t,e)}),he=fe=!0)),t.animateAll(function(){he=fe=!1,n.options.animation&&ue.forEach(function(t){T(t)}),n.options.sort&&me()}))},dragOver:function(t){var e=t.target,n=t.completed,t=t.cancel;fe&&~ue.indexOf(e)&&(n(!1),t())},revert:function(t){var n,o,e=t.fromSortable,i=t.rootEl,r=t.sortable,a=t.dragRect;1<ue.length&&(ue.forEach(function(t){r.addAnimationState({target:t,rect:fe?X(t):a}),T(t),t.fromRect=a,e.removeAnimationState(t)}),fe=!1,n=!this.options.removeCloneOnHide,o=i,ue.forEach(function(t,e){e=o.children[t.sortableIndex+(n?Number(e):0)];e?o.insertBefore(t,e):o.appendChild(t)}))},dragOverCompleted:function(t){var e,n=t.sortable,o=t.isOwner,i=t.insertion,r=t.activeSortable,a=t.parentEl,l=t.putSortable,t=this.options;i&&(o&&r._hideClone(),he=!1,t.animation&&1<ue.length&&(fe||!o&&!r.options.sort&&!l)&&(e=X(le,!1,!0,!0),ue.forEach(function(t){t!==le&&(C(t,e),a.appendChild(t))}),fe=!0),o||(fe||me(),1<ue.length?(o=ce,r._showClone(n),r.options.animation&&!ce&&o&&de.forEach(function(t){r.addAnimationState({target:t,rect:se}),t.fromRect=se,t.thisAnimationDuration=null})):r._showClone(n)))},dragOverAnimationCapture:function(t){var e=t.dragRect,n=t.isOwner,t=t.activeSortable;ue.forEach(function(t){t.thisAnimationDuration=null}),t.options.animation&&!n&&t.multiDrag.isMultiDrag&&(se=a({},e),e=v(le,!0),se.top-=e.f,se.left-=e.e)},dragOverAnimationComplete:function(){fe&&(fe=!1,me())},drop:function(t){var e=t.originalEvent,n=t.rootEl,o=t.parentEl,i=t.sortable,r=t.dispatchSortableEvent,a=t.oldIndex,l=t.putSortable,s=l||this.sortable;if(e){var c,u,d,h=this.options,f=o.children;if(!pe)if(h.multiDragKey&&!this.multiDragKeyDown&&this._deselectMultiDrag(),k(le,h.selectedClass,!~ue.indexOf(le)),~ue.indexOf(le))ue.splice(ue.indexOf(le),1),re=null,z({sortable:i,rootEl:n,name:"deselect",targetEl:le,originalEvent:e});else{if(ue.push(le),z({sortable:i,rootEl:n,name:"select",targetEl:le,originalEvent:e}),e.shiftKey&&re&&i.el.contains(re)){var p=j(re),t=j(le);if(~p&&~t&&p!==t)for(var g,m=p<t?(g=p,t):(g=t,p+1);g<m;g++)~ue.indexOf(f[g])||(k(f[g],h.selectedClass,!0),ue.push(f[g]),z({sortable:i,rootEl:n,name:"select",targetEl:f[g],originalEvent:e}))}else re=le;ae=s}pe&&this.isMultiDrag&&(fe=!1,(o[K].options.sort||o!==n)&&1<ue.length&&(c=X(le),u=j(le,":not(."+this.options.selectedClass+")"),!he&&h.animation&&(le.thisAnimationDuration=null),s.captureAnimationState(),he||(h.animation&&(le.fromRect=c,ue.forEach(function(t){var e;t.thisAnimationDuration=null,t!==le&&(e=fe?X(t):c,t.fromRect=e,s.addAnimationState({target:t,rect:e}))})),me(),ue.forEach(function(t){f[u]?o.insertBefore(t,f[u]):o.appendChild(t),u++}),a===j(le)&&(d=!1,ue.forEach(function(t){t.sortableIndex!==j(t)&&(d=!0)}),d&&(r("update"),r("sort")))),ue.forEach(function(t){T(t)}),s.animateAll()),ae=s),(n===o||l&&"clone"!==l.lastPutMode)&&de.forEach(function(t){t.parentNode&&t.parentNode.removeChild(t)})}},nullingGlobal:function(){this.isMultiDrag=pe=!1,de.length=0},destroyGlobal:function(){this._deselectMultiDrag(),f(document,"pointerup",this._deselectMultiDrag),f(document,"mouseup",this._deselectMultiDrag),f(document,"touchend",this._deselectMultiDrag),f(document,"keydown",this._checkKeyDown),f(document,"keyup",this._checkKeyUp)},_deselectMultiDrag:function(t){if(!(void 0!==pe&&pe||ae!==this.sortable||t&&P(t.target,this.options.draggable,this.sortable.el,!1)||t&&0!==t.button))for(;ue.length;){var e=ue[0];k(e,this.options.selectedClass,!1),ue.shift(),z({sortable:this.sortable,rootEl:this.sortable.el,name:"deselect",targetEl:e,originalEvent:t})}},_checkKeyDown:function(t){t.key===this.options.multiDragKey&&(this.multiDragKeyDown=!0)},_checkKeyUp:function(t){t.key===this.options.multiDragKey&&(this.multiDragKeyDown=!1)}},a(t,{pluginName:"multiDrag",utils:{select:function(t){var e=t.parentNode[K];e&&e.options.multiDrag&&!~ue.indexOf(t)&&(ae&&ae!==e&&(ae.multiDrag._deselectMultiDrag(),ae=e),k(t,e.options.selectedClass,!0),ue.push(t))},deselect:function(t){var e=t.parentNode[K],n=ue.indexOf(t);e&&e.options.multiDrag&&~n&&(k(t,e.options.selectedClass,!1),ue.splice(n,1))}},eventProperties:function(){var n=this,o=[],i=[];return ue.forEach(function(t){var e;o.push({multiDragElement:t,index:t.sortableIndex}),e=fe&&t!==le?-1:fe?j(t,":not(."+n.options.selectedClass+")"):j(t),i.push({multiDragElement:t,index:e})}),{items:r(ue),clones:[].concat(de),oldIndicies:o,newIndicies:i}},optionListeners:{multiDragKey:function(t){return"ctrl"===(t=t.toLowerCase())?t="Control":1<t.length&&(t=t.charAt(0).toUpperCase()+t.substr(1)),t}}})}),Ft});
4793
4794// final JS calls after everything has been loaded
4795document.dispatchEvent( new CustomEvent('events_manager_js_loaded') );
4796//# sourceMappingURL=events-manager.js.map

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.