Passed
Push — master ( fd90c2...9b7fbb )
by Brian
05:32
created

AyeCode_UI_Settings::get_url_old()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 2
nop 0
dl 0
loc 16
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * A class for adjusting AyeCode UI settings on WordPress
4
 *
5
 * This class can be added to any plugin or theme and will add a settings screen to WordPress to control Bootstrap settings.
6
 *
7
 * @link https://github.com/AyeCode/wp-ayecode-ui
8
 *
9
 * @internal This file should not be edited directly but pulled from the github repo above.
10
 */
11
12
/**
13
 * Bail if we are not in WP.
14
 */
15
if ( ! defined( 'ABSPATH' ) ) {
16
	exit;
17
}
18
19
/**
20
 * Only add if the class does not already exist.
21
 */
22
if ( ! class_exists( 'AyeCode_UI_Settings' ) ) {
23
24
	/**
25
	 * A Class to be able to change settings for Font Awesome.
26
	 *
27
	 * Class AyeCode_UI_Settings
28
	 * @ver 1.0.0
29
	 * @todo decide how to implement textdomain
30
	 */
31
	class AyeCode_UI_Settings {
32
33
		/**
34
		 * Class version version.
35
		 *
36
		 * @var string
37
		 */
38
		public $version = '0.1.75';
39
40
		/**
41
		 * Class textdomain.
42
		 *
43
		 * @var string
44
		 */
45
		public $textdomain = 'aui';
46
47
		/**
48
		 * Latest version of Bootstrap at time of publish published.
49
		 *
50
		 * @var string
51
		 */
52
		public $latest = "4.5.3";
53
54
		/**
55
		 * Current version of select2 being used.
56
		 *
57
		 * @var string
58
		 */
59
		public $select2_version = "4.0.11";
60
61
		/**
62
		 * The title.
63
		 *
64
		 * @var string
65
		 */
66
		public $name = 'AyeCode UI';
67
68
		/**
69
		 * The relative url to the assets.
70
		 *
71
		 * @var string
72
		 */
73
		public $url = '';
74
75
		/**
76
		 * Holds the settings values.
77
		 *
78
		 * @var array
79
		 */
80
		private $settings;
81
82
		/**
83
		 * AyeCode_UI_Settings instance.
84
		 *
85
		 * @access private
86
		 * @since  1.0.0
87
		 * @var    AyeCode_UI_Settings There can be only one!
88
		 */
89
		private static $instance = null;
90
91
		/**
92
		 * Main AyeCode_UI_Settings Instance.
93
		 *
94
		 * Ensures only one instance of AyeCode_UI_Settings is loaded or can be loaded.
95
		 *
96
		 * @since 1.0.0
97
		 * @static
98
		 * @return AyeCode_UI_Settings - Main instance.
99
		 */
100
		public static function instance() {
101
			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof AyeCode_UI_Settings ) ) {
102
103
				self::$instance = new AyeCode_UI_Settings;
104
105
				add_action( 'init', array( self::$instance, 'init' ) ); // set settings
106
107
				if ( is_admin() ) {
108
					add_action( 'admin_menu', array( self::$instance, 'menu_item' ) );
109
					add_action( 'admin_init', array( self::$instance, 'register_settings' ) );
110
111
					// Maybe show example page
112
					add_action( 'template_redirect', array( self::$instance,'maybe_show_examples' ) );
113
				}
114
115
				add_action( 'customize_register', array( self::$instance, 'customizer_settings' ));
116
117
				do_action( 'ayecode_ui_settings_loaded' );
118
			}
119
120
			return self::$instance;
121
		}
122
123
		/**
124
		 * Setup some constants.
125
		 */
126
		public function constants(){
127
			define('AUI_PRIMARY_COLOR_ORIGINAL', "#1e73be");
128
			define('AUI_SECONDARY_COLOR_ORIGINAL', '#6c757d');
129
			if (!defined('AUI_PRIMARY_COLOR')) define('AUI_PRIMARY_COLOR', AUI_PRIMARY_COLOR_ORIGINAL);
130
			if (!defined('AUI_SECONDARY_COLOR')) define('AUI_SECONDARY_COLOR', AUI_SECONDARY_COLOR_ORIGINAL);
131
		}
132
133
		/**
134
		 * Initiate the settings and add the required action hooks.
135
		 */
136
		public function init() {
137
138
			// Maybe fix settings
139
			if ( ! empty( $_REQUEST['aui-fix-admin'] ) && !empty($_REQUEST['nonce']) && wp_verify_nonce( $_REQUEST['nonce'], "aui-fix-admin" ) ) {
140
				$db_settings = get_option( 'ayecode-ui-settings' );
141
				if ( ! empty( $db_settings ) ) {
142
					$db_settings['css_backend'] = 'compatibility';
143
					$db_settings['js_backend'] = 'core-popper';
144
					update_option( 'ayecode-ui-settings', $db_settings );
145
					wp_safe_redirect(admin_url("options-general.php?page=ayecode-ui-settings&updated=true"));
146
				}
147
			}
148
149
			$this->constants();
150
			$this->settings = $this->get_settings();
151
			$this->url = $this->get_url();
152
153
			/**
154
			 * Maybe load CSS
155
			 *
156
			 * We load super early in case there is a theme version that might change the colors
157
			 */
158
			if ( $this->settings['css'] ) {
159
				$priority = $this->is_bs3_compat() ? 100 : 1;
160
				add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_style' ), $priority );
161
			}
162
			if ( $this->settings['css_backend'] && $this->load_admin_scripts() ) {
163
				add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_style' ), 1 );
164
			}
165
166
			// maybe load JS
167
			if ( $this->settings['js'] ) {
168
				$priority = $this->is_bs3_compat() ? 100 : 1;
169
				add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ), $priority );
170
			}
171
			if ( $this->settings['js_backend'] && $this->load_admin_scripts() ) {
172
				add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ), 1 );
173
			}
174
175
			// Maybe set the HTML font size
176
			if ( $this->settings['html_font_size'] ) {
177
				add_action( 'wp_footer', array( $this, 'html_font_size' ), 10 );
178
			}
179
180
			// Maybe show backend style error
181
			if( $this->settings['css_backend'] != 'compatibility' || $this->settings['js_backend'] != 'core-popper' ){
182
				add_action( 'admin_notices', array( $this, 'show_admin_style_notice' ) );
183
			}
184
185
		}
186
187
		/**
188
		 * Show admin notice if backend scripts not loaded.
189
		 */
190
		public function show_admin_style_notice(){
191
			$fix_url = admin_url("options-general.php?page=ayecode-ui-settings&aui-fix-admin=true&nonce=".wp_create_nonce('aui-fix-admin'));
192
			$button = '<a href="'.esc_url($fix_url).'" class="button-primary">Fix Now</a>';
193
			$message = __( '<b>Style Issue:</b> AyeCode UI is disable or set wrong.')." " .$button;
194
			echo '<div class="notice notice-error aui-settings-error-notice"><p>'.$message.'</p></div>';
195
		}
196
197
		/**
198
		 * Check if we should load the admin scripts or not.
199
		 *
200
		 * @return bool
201
		 */
202
		public function load_admin_scripts(){
203
			$result = true;
204
205
			// check if specifically disabled
206
			if(!empty($this->settings['disable_admin'])){
207
				$url_parts = explode("\n",$this->settings['disable_admin']);
208
				foreach($url_parts as $part){
209
					if( strpos($_SERVER['REQUEST_URI'], trim($part)) !== false ){
210
						return false; // return early, no point checking further
211
					}
212
				}
213
			}
214
215
			return $result;
216
		}
217
218
		/**
219
		 * Add a html font size to the footer.
220
		 */
221
		public function html_font_size(){
222
			$this->settings = $this->get_settings();
223
			echo "<style>html{font-size:".absint($this->settings['html_font_size'])."px;}</style>";
224
		}
225
226
		/**
227
		 * Check if the current admin screen should load scripts.
228
		 * 
229
		 * @return bool
230
		 */
231
		public function is_aui_screen(){
232
//			echo '###';exit;
233
			$load = false;
234
			// check if we should load or not
235
			if ( is_admin() ) {
236
				// Only enable on set pages
237
				$aui_screens = array(
238
					'page',
239
					'post',
240
					'settings_page_ayecode-ui-settings',
241
					'appearance_page_gutenberg-widgets',
242
					'widgets',
243
					'ayecode-ui-settings',
244
					'site-editor'
245
				);
246
				$screen_ids = apply_filters( 'aui_screen_ids', $aui_screens );
247
248
				$screen = get_current_screen();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $screen is correct as get_current_screen() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
249
250
//				echo '###'.$screen->id;
251
252
				// check if we are on a AUI screen
253
				if ( $screen && in_array( $screen->id, $screen_ids ) ) {
0 ignored issues
show
introduced by
$screen is of type null, thus it always evaluated to false.
Loading history...
254
					$load = true;
255
				}
256
257
				//load for widget previews in WP 5.8
258
				if( !empty($_REQUEST['legacy-widget-preview'])){
259
					$load = true;
260
				}
261
			}
262
263
			return apply_filters( 'aui_load_on_admin' , $load );
264
		}
265
266
		/**
267
		 * Adds the styles.
268
		 */
269
		public function enqueue_style() {
270
271
272
			if( is_admin() && !$this->is_aui_screen()){
273
				// don't add wp-admin scripts if not requested to
274
			}else{
275
				$css_setting = current_action() == 'wp_enqueue_scripts' ? 'css' : 'css_backend';
276
277
				$rtl = is_rtl() ? '-rtl' : '';
278
279
				if($this->settings[$css_setting]){
280
					$compatibility = $this->settings[$css_setting]=='core' ? false : true;
281
					$url = $this->settings[$css_setting]=='core' ? $this->url.'assets/css/ayecode-ui'.$rtl.'.css' : $this->url.'assets/css/ayecode-ui-compatibility'.$rtl.'.css';
282
					wp_register_style( 'ayecode-ui', $url, array(), $this->version );
283
					wp_enqueue_style( 'ayecode-ui' );
284
285
					// flatpickr
286
					wp_register_style( 'flatpickr', $this->url.'assets/css/flatpickr.min.css', array(), $this->version );
287
288
					// fix some wp-admin issues
289
					if(is_admin()){
290
						$custom_css = "
291
                body{
292
                    background-color: #f1f1f1;
293
                    font-family: -apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,Oxygen-Sans,Ubuntu,Cantarell,\"Helvetica Neue\",sans-serif;
294
                    font-size:13px;
295
                }
296
                a {
297
				    color: #0073aa;
298
				    text-decoration: underline;
299
				}
300
                label {
301
				    display: initial;
302
				    margin-bottom: 0;
303
				}
304
				input, select {
305
				    margin: 1px;
306
				    line-height: initial;
307
				}
308
				th, td, div, h2 {
309
				    box-sizing: content-box;
310
				}
311
				p {
312
				    font-size: 13px;
313
				    line-height: 1.5;
314
				    margin: 1em 0;
315
				}
316
				h1, h2, h3, h4, h5, h6 {
317
				    display: block;
318
				    font-weight: 600;
319
				}
320
				h2,h3 {
321
				    font-size: 1.3em;
322
				    margin: 1em 0
323
				}
324
				.blocks-widgets-container .bsui *{
325
					box-sizing: border-box;
326
				}
327
				.bs-tooltip-top .arrow{
328
					margin-left:0px;
329
				}
330
				
331
				.custom-switch input[type=checkbox]{
332
				    display:none;
333
				}
334
                ";
335
336
						// @todo, remove once fixed :: fix for this bug https://github.com/WordPress/gutenberg/issues/14377
337
						$custom_css .= "
338
						.edit-post-sidebar input[type=color].components-text-control__input{
339
						    padding: 0;
340
						}
341
					";
342
						wp_add_inline_style( 'ayecode-ui', $custom_css );
343
					}
344
345
					// custom changes
346
					wp_add_inline_style( 'ayecode-ui', self::custom_css($compatibility) );
347
348
				}
349
			}
350
351
352
		}
353
354
		/**
355
		 * Get inline script used if bootstrap enqueued
356
		 *
357
		 * If this remains small then its best to use this than to add another JS file.
358
		 */
359
		public function inline_script() {
360
			// Flatpickr calendar locale
361
			$flatpickr_locale = self::flatpickr_locale();
362
363
			ob_start();
364
			?>
365
			<script>
366
				/**
367
				 * An AUI bootstrap adaptation of GreedyNav.js ( by Luke Jackson ).
368
				 *
369
				 * Simply add the class `greedy` to any <nav> menu and it will do the rest.
370
				 * Licensed under the MIT license - http://opensource.org/licenses/MIT
371
				 * @ver 0.0.1
372
				 */
373
				function aui_init_greedy_nav(){
374
					jQuery('nav.greedy').each(function(i, obj) {
375
376
						// Check if already initialized, if so continue.
377
						if(jQuery(this).hasClass("being-greedy")){return true;}
378
379
						// Make sure its always expanded
380
						jQuery(this).addClass('navbar-expand');
381
382
						// vars
383
						var $vlinks = '';
384
						var $dDownClass = '';
385
						if(jQuery(this).find('.navbar-nav').length){
386
							if(jQuery(this).find('.navbar-nav').hasClass("being-greedy")){return true;}
387
							$vlinks = jQuery(this).find('.navbar-nav').addClass("being-greedy w-100").removeClass('overflow-hidden');
388
						}else if(jQuery(this).find('.nav').length){
389
							if(jQuery(this).find('.nav').hasClass("being-greedy")){return true;}
390
							$vlinks = jQuery(this).find('.nav').addClass("being-greedy w-100").removeClass('overflow-hidden');
391
							$dDownClass = ' mt-2 ';
392
						}else{
393
							return false;
394
						}
395
396
						jQuery($vlinks).append('<li class="nav-item list-unstyled ml-auto greedy-btn d-none dropdown ">' +
397
							'<a href="javascript:void(0)" data-toggle="dropdown" class="nav-link"><i class="fas fa-ellipsis-h"></i> <span class="greedy-count badge badge-dark badge-pill"></span></a>' +
398
							'<ul class="greedy-links dropdown-menu  dropdown-menu-right '+$dDownClass+'"></ul>' +
399
							'</li>');
400
401
						var $hlinks = jQuery(this).find('.greedy-links');
402
						var $btn = jQuery(this).find('.greedy-btn');
403
404
						var numOfItems = 0;
405
						var totalSpace = 0;
406
						var closingTime = 1000;
407
						var breakWidths = [];
408
409
						// Get initial state
410
						$vlinks.children().outerWidth(function(i, w) {
411
							totalSpace += w;
412
							numOfItems += 1;
413
							breakWidths.push(totalSpace);
414
						});
415
416
						var availableSpace, numOfVisibleItems, requiredSpace, buttonSpace ,timer;
417
418
						/*
419
						 The check function.
420
						 */
421
						function check() {
422
423
							// Get instant state
424
							buttonSpace = $btn.width();
425
							availableSpace = $vlinks.width() - 10;
426
							numOfVisibleItems = $vlinks.children().length;
427
							requiredSpace = breakWidths[numOfVisibleItems - 1];
428
429
							// There is not enough space
430
							if (numOfVisibleItems > 1 && requiredSpace > availableSpace) {
431
								$vlinks.children().last().prev().prependTo($hlinks);
432
								numOfVisibleItems -= 1;
433
								check();
434
								// There is more than enough space
435
							} else if (availableSpace > breakWidths[numOfVisibleItems]) {
436
								$hlinks.children().first().insertBefore($btn);
437
								numOfVisibleItems += 1;
438
								check();
439
							}
440
							// Update the button accordingly
441
							jQuery($btn).find(".greedy-count").html( numOfItems - numOfVisibleItems);
442
							if (numOfVisibleItems === numOfItems) {
443
								$btn.addClass('d-none');
444
							} else $btn.removeClass('d-none');
445
						}
446
447
						// Window listeners
448
						jQuery(window).on("resize",function() {
449
							check();
450
						});
451
452
						// do initial check
453
						check();
454
					});
455
				}
456
457
				function aui_select2_locale() {
458
					var aui_select2_params = <?php echo self::select2_locale(); ?>;
459
460
					return {
461
						'language': {
462
							errorLoading: function() {
463
								// Workaround for https://github.com/select2/select2/issues/4355 instead of i18n_ajax_error.
464
								return aui_select2_params.i18n_searching;
465
							},
466
							inputTooLong: function(args) {
467
								var overChars = args.input.length - args.maximum;
468
								if (1 === overChars) {
469
									return aui_select2_params.i18n_input_too_long_1;
470
								}
471
								return aui_select2_params.i18n_input_too_long_n.replace('%item%', overChars);
472
							},
473
							inputTooShort: function(args) {
474
								var remainingChars = args.minimum - args.input.length;
475
								if (1 === remainingChars) {
476
									return aui_select2_params.i18n_input_too_short_1;
477
								}
478
								return aui_select2_params.i18n_input_too_short_n.replace('%item%', remainingChars);
479
							},
480
							loadingMore: function() {
481
								return aui_select2_params.i18n_load_more;
482
							},
483
							maximumSelected: function(args) {
484
								if (args.maximum === 1) {
485
									return aui_select2_params.i18n_selection_too_long_1;
486
								}
487
								return aui_select2_params.i18n_selection_too_long_n.replace('%item%', args.maximum);
488
							},
489
							noResults: function() {
490
								return aui_select2_params.i18n_no_matches;
491
							},
492
							searching: function() {
493
								return aui_select2_params.i18n_searching;
494
							}
495
						}
496
					};
497
				}
498
499
				/**
500
				 * Initiate Select2 items.
501
				 */
502
				function aui_init_select2(){
503
					var select2_args = jQuery.extend({}, aui_select2_locale());
504
					jQuery("select.aui-select2").each(function() {
505
						if (!jQuery(this).hasClass("select2-hidden-accessible")) {
506
							jQuery(this).select2(select2_args);
507
						}
508
					});
509
				}
510
511
				/**
512
				 * A function to convert a time value to a "ago" time text.
513
				 *
514
				 * @param selector string The .class selector
515
				 */
516
				function aui_time_ago(selector) {
517
					var aui_timeago_params = <?php echo self::timeago_locale(); ?>;
518
519
					var templates = {
520
						prefix: aui_timeago_params.prefix_ago,
521
						suffix: aui_timeago_params.suffix_ago,
522
						seconds: aui_timeago_params.seconds,
523
						minute: aui_timeago_params.minute,
524
						minutes: aui_timeago_params.minutes,
525
						hour: aui_timeago_params.hour,
526
						hours: aui_timeago_params.hours,
527
						day: aui_timeago_params.day,
528
						days: aui_timeago_params.days,
529
						month: aui_timeago_params.month,
530
						months: aui_timeago_params.months,
531
						year: aui_timeago_params.year,
532
						years: aui_timeago_params.years
533
					};
534
					var template = function (t, n) {
535
						return templates[t] && templates[t].replace(/%d/i, Math.abs(Math.round(n)));
536
					};
537
538
					var timer = function (time) {
539
						if (!time)
540
							return;
541
						time = time.replace(/\.\d+/, ""); // remove milliseconds
542
						time = time.replace(/-/, "/").replace(/-/, "/");
543
						time = time.replace(/T/, " ").replace(/Z/, " UTC");
544
						time = time.replace(/([\+\-]\d\d)\:?(\d\d)/, " $1$2"); // -04:00 -> -0400
545
						time = new Date(time * 1000 || time);
546
547
						var now = new Date();
548
						var seconds = ((now.getTime() - time) * .001) >> 0;
549
						var minutes = seconds / 60;
550
						var hours = minutes / 60;
551
						var days = hours / 24;
552
						var years = days / 365;
553
554
						return templates.prefix + (
555
								seconds < 45 && template('seconds', seconds) ||
556
								seconds < 90 && template('minute', 1) ||
557
								minutes < 45 && template('minutes', minutes) ||
558
								minutes < 90 && template('hour', 1) ||
559
								hours < 24 && template('hours', hours) ||
560
								hours < 42 && template('day', 1) ||
561
								days < 30 && template('days', days) ||
562
								days < 45 && template('month', 1) ||
563
								days < 365 && template('months', days / 30) ||
564
								years < 1.5 && template('year', 1) ||
565
								template('years', years)
566
							) + templates.suffix;
567
					};
568
569
					var elements = document.getElementsByClassName(selector);
570
					if (selector && elements && elements.length) {
571
						for (var i in elements) {
572
							var $el = elements[i];
573
							if (typeof $el === 'object') {
574
								$el.innerHTML = '<i class="far fa-clock"></i> ' + timer($el.getAttribute('title') || $el.getAttribute('datetime'));
575
							}
576
						}
577
					}
578
579
					// update time every minute
580
					setTimeout(function() {
581
						aui_time_ago(selector);
582
					}, 60000);
583
584
				}
585
586
				/**
587
				 * Initiate tooltips on the page.
588
				 */
589
				function aui_init_tooltips(){
590
					jQuery('[data-toggle="tooltip"]').tooltip();
591
					jQuery('[data-toggle="popover"]').popover();
592
					jQuery('[data-toggle="popover-html"]').popover({
593
						html: true
594
					});
595
596
					// fix popover container compatibility
597
					jQuery('[data-toggle="popover"],[data-toggle="popover-html"]').on('inserted.bs.popover', function () {
598
						jQuery('body > .popover').wrapAll("<div class='bsui' />");
599
					});
600
				}
601
602
				/**
603
				 * Initiate flatpickrs on the page.
604
				 */
605
				$aui_doing_init_flatpickr = false;
606
				function aui_init_flatpickr(){
607
					if ( typeof jQuery.fn.flatpickr === "function" && !$aui_doing_init_flatpickr) {
608
						$aui_doing_init_flatpickr = true;
609
						<?php if ( ! empty( $flatpickr_locale ) ) { ?>try{flatpickr.localize(<?php echo $flatpickr_locale; ?>);}catch(err){console.log(err.message);}<?php } ?>
610
						jQuery('input[data-aui-init="flatpickr"]:not(.flatpickr-input)').flatpickr();
611
					}
612
					$aui_doing_init_flatpickr = false;
613
				}
614
615
				/**
616
				 * Initiate iconpicker on the page.
617
				 */
618
				$aui_doing_init_iconpicker = false;
619
				function aui_init_iconpicker(){
620
					if ( typeof jQuery.fn.iconpicker === "function" && !$aui_doing_init_iconpicker) {
621
						$aui_doing_init_iconpicker = true;
622
						jQuery('input[data-aui-init="iconpicker"]:not(.iconpicker-input)').iconpicker();
623
					}
624
					$aui_doing_init_iconpicker= false;
625
				}
626
627
				function aui_modal_iframe($title,$url,$footer,$dismissible,$class,$dialog_class,$body_class){
628
					if(!$body_class){$body_class = 'p-0';}
629
					var $body = '<div class="ac-preview-loading text-center position-absolute w-100 text-dark vh-100 overlay overlay-white p-0 m-0 d-none d-flex justify-content-center align-items-center"><div class="spinner-border" role="status"></div></div>';
630
					$body += '<iframe id="embedModal-iframe" class="w-100 vh-100 p-0 m-0" src="" width="100%" height="100%" frameborder="0" allowtransparency="true"></iframe>';
631
632
					$m = aui_modal($title,$body,$footer,$dismissible,$class,$dialog_class,$body_class);
633
					jQuery( $m ).on( 'shown.bs.modal', function ( e ) {
634
						iFrame = jQuery( '#embedModal-iframe') ;
635
636
						jQuery('.ac-preview-loading').addClass('d-flex');
637
						iFrame.attr({
638
							src: $url
639
						});
640
641
						//resize the iframe once loaded.
642
						iFrame.load(function() {
643
							jQuery('.ac-preview-loading').removeClass('d-flex');
644
						});
645
					});
646
647
					return $m;
648
649
				}
650
651
				function aui_modal($title,$body,$footer,$dismissible,$class,$dialog_class,$body_class) {
652
					if(!$class){$class = '';}
653
					if(!$dialog_class){$dialog_class = '';}
654
					if(!$body){$body = '<div class="text-center"><div class="spinner-border" role="status"></div></div>';}
655
					// remove it first
656
					jQuery('.aui-modal').modal('hide').modal('dispose').remove();
657
					jQuery('.modal-backdrop').remove();
658
659
					var $modal = '';
660
661
					$modal += '<div class="modal aui-modal fade shadow bsui '+$class+'" tabindex="-1">'+
662
						'<div class="modal-dialog modal-dialog-centered '+$dialog_class+'">'+
663
							'<div class="modal-content border-0 shadow">';
664
665
					if($title) {
666
						$modal += '<div class="modal-header">' +
667
						'<h5 class="modal-title">' + $title + '</h5>';
668
669
						if ($dismissible) {
670
							$modal += '<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
671
								'<span aria-hidden="true">&times;</span>' +
672
								'</button>';
673
						}
674
675
						$modal += '</div>';
676
					}
677
					$modal += '<div class="modal-body '+$body_class+'">'+
678
									$body+
679
								'</div>';
680
681
					if($footer){
682
						$modal += '<div class="modal-footer">'+
683
							$footer +
684
							'</div>';
685
					}
686
687
					$modal +='</div>'+
688
						'</div>'+
689
					'</div>';
690
691
					jQuery('body').append($modal);
692
693
					return jQuery('.aui-modal').modal('hide').modal({
694
						//backdrop: 'static'
695
					});
696
				}
697
698
				/**
699
				 * Show / hide fields depending on conditions.
700
				 */
701
				function aui_conditional_fields(form){
702
					jQuery(form).find(".aui-conditional-field").each(function () {
703
704
						var $element_require = jQuery(this).data('element-require');
705
706
						if ($element_require) {
707
708
							$element_require = $element_require.replace("&#039;", "'"); // replace single quotes
709
							$element_require = $element_require.replace("&quot;", '"'); // replace double quotes
710
							if (aui_check_form_condition($element_require,form)) {
711
								jQuery(this).removeClass('d-none');
712
							} else {
713
								jQuery(this).addClass('d-none');
714
							}
715
						}
716
					});
717
				}
718
719
				/**
720
				 * Check form condition
721
				 */
722
				function aui_check_form_condition(condition,form) {
723
					if (form) {
724
						condition = condition.replace(/\(form\)/g, "('"+form+"')");
725
					}
726
					return new Function("return " + condition+";")();
727
				}
728
729
				/**
730
				 * A function to determine if a element is on screen.
731
				 */
732
				jQuery.fn.aui_isOnScreen = function(){
733
734
					var win = jQuery(window);
735
736
					var viewport = {
737
						top : win.scrollTop(),
738
						left : win.scrollLeft()
739
					};
740
					viewport.right = viewport.left + win.width();
741
					viewport.bottom = viewport.top + win.height();
742
743
					var bounds = this.offset();
744
					bounds.right = bounds.left + this.outerWidth();
745
					bounds.bottom = bounds.top + this.outerHeight();
746
747
					return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
748
749
				};
750
751
				/**
752
				 * Maybe show multiple carousel items if set to do so.
753
				 */ 
754
				function aui_carousel_maybe_show_multiple_items($carousel){
755
					var $items = {};
756
					var $item_count = 0;
757
758
					// maybe backup
759
					if(!jQuery($carousel).find('.carousel-inner-original').length){
760
						jQuery($carousel).append('<div class="carousel-inner-original d-none">'+jQuery($carousel).find('.carousel-inner').html()+'</div>');
761
					}
762
763
					// Get the original items html
764
					jQuery($carousel).find('.carousel-inner-original .carousel-item').each(function () {
765
						$items[$item_count] = jQuery(this).html();
766
						$item_count++;
767
					});
768
769
					// bail if no items
770
					if(!$item_count){return;}
771
772
					if(jQuery(window).width() <= 576){
773
						// maybe restore original
774
						if(jQuery($carousel).find('.carousel-inner').hasClass('aui-multiple-items') && jQuery($carousel).find('.carousel-inner-original').length){
775
							jQuery($carousel).find('.carousel-inner').removeClass('aui-multiple-items').html(jQuery($carousel).find('.carousel-inner-original').html());
776
							jQuery($carousel).find(".carousel-indicators li").removeClass("d-none");
777
						}
778
779
					}else{
780
						// new items
781
						var $md_count = jQuery($carousel).data('limit_show');
782
						var $new_items = '';
783
						var $new_items_count = 0;
784
						var $new_item_count = 0;
785
						var $closed = true;
786
						Object.keys($items).forEach(function(key,index) {
787
788
							// close
789
							if(index != 0 && Number.isInteger(index/$md_count) ){
790
								$new_items += '</div></div>';
791
								$closed = true;
792
							}
793
794
							// open
795
							if(index == 0 || Number.isInteger(index/$md_count) ){
796
								$active = index == 0 ? 'active' : '';
797
								$new_items += '<div class="carousel-item '+$active+'"><div class="row m-0">';
798
								$closed = false;
799
								$new_items_count++;
800
								$new_item_count = 0;
801
							}
802
803
							// content
804
							$new_items += '<div class="col pr-1 pl-0">'+$items[index]+'</div>';
805
							$new_item_count++;
806
807
808
						});
809
810
						// close if not closed in the loop
811
						if(!$closed){
812
							// check for spares
813
							if($md_count-$new_item_count > 0){
814
								$placeholder_count = $md_count-$new_item_count;
815
								while($placeholder_count > 0){
816
									$new_items += '<div class="col pr-1 pl-0"></div>';
817
									$placeholder_count--;
818
								}
819
820
							}
821
822
							$new_items += '</div></div>';
823
						}
824
825
						// insert the new items
826
						jQuery($carousel).find('.carousel-inner').addClass('aui-multiple-items').html($new_items);
827
828
						// fix any lazyload images in the active slider
829
						jQuery($carousel).find('.carousel-item.active img').each(function () {
830
							// fix the srcset
831
							if(real_srcset = jQuery(this).attr("data-srcset")){
832
								if(!jQuery(this).attr("srcset")) jQuery(this).attr("srcset",real_srcset);
833
							}
834
							// fix the src
835
							if(real_src = jQuery(this).attr("data-src")){
836
								if(!jQuery(this).attr("srcset"))  jQuery(this).attr("src",real_src);
837
							}
838
						});
839
840
						// maybe fix carousel indicators
841
						$hide_count = $new_items_count-1;
842
						jQuery($carousel).find(".carousel-indicators li:gt("+$hide_count+")").addClass("d-none");
843
					}
844
845
					// trigger a global action to say we have
846
					jQuery( window ).trigger( "aui_carousel_multiple" );
847
				}
848
849
				/**
850
				 * Init Multiple item carousels.
851
				 */ 
852
				function aui_init_carousel_multiple_items(){
853
					jQuery(window).on("resize",function(){
854
						jQuery('.carousel-multiple-items').each(function () {
855
							aui_carousel_maybe_show_multiple_items(this);
856
						});
857
					});
858
859
					// run now
860
					jQuery('.carousel-multiple-items').each(function () {
861
						aui_carousel_maybe_show_multiple_items(this);
862
					});
863
				}
864
865
				/**
866
				 * Allow navs to use multiple sub menus.
867
				 */
868
				function init_nav_sub_menus(){
869
870
					jQuery('.navbar-multi-sub-menus').each(function(i, obj) {
871
						// Check if already initialized, if so continue.
872
						if(jQuery(this).hasClass("has-sub-sub-menus")){return true;}
873
874
						// Make sure its always expanded
875
						jQuery(this).addClass('has-sub-sub-menus');
876
877
						jQuery(this).find( '.dropdown-menu a.dropdown-toggle' ).on( 'click', function ( e ) {
878
							var $el = jQuery( this );
879
							$el.toggleClass('active-dropdown');
880
							var $parent = jQuery( this ).offsetParent( ".dropdown-menu" );
881
							if ( !jQuery( this ).next().hasClass( 'show' ) ) {
882
								jQuery( this ).parents( '.dropdown-menu' ).first().find( '.show' ).removeClass( "show" );
883
							}
884
							var $subMenu = jQuery( this ).next( ".dropdown-menu" );
885
							$subMenu.toggleClass( 'show' );
886
887
							jQuery( this ).parent( "li" ).toggleClass( 'show' );
888
889
							jQuery( this ).parents( 'li.nav-item.dropdown.show' ).on( 'hidden.bs.dropdown', function ( e ) {
890
								jQuery( '.dropdown-menu .show' ).removeClass( "show" );
891
								$el.removeClass('active-dropdown');
892
							} );
893
894
							if ( !$parent.parent().hasClass( 'navbar-nav' ) ) {
895
								$el.next().addClass('position-relative border-top border-bottom');
896
							}
897
898
							return false;
899
						} );
900
901
					});
902
903
				}
904
905
906
				/**
907
				 * Open a lightbox when an embed item is clicked.
908
				 */
909
				function aui_lightbox_embed($link,ele){
910
					ele.preventDefault();
911
912
					// remove it first
913
					jQuery('.aui-carousel-modal').remove();
914
915
					var $modal = '<div class="modal fade aui-carousel-modal bsui" tabindex="-1" role="dialog" aria-labelledby="aui-modal-title" aria-hidden="true"><div class="modal-dialog modal-dialog-centered modal-xl mw-100"><div class="modal-content bg-transparent border-0"><div class="modal-header"><h5 class="modal-title" id="aui-modal-title"></h5></div><div class="modal-body text-center"><i class="fas fa-circle-notch fa-spin fa-3x"></i></div></div></div></div>';
916
					jQuery('body').append($modal);
917
918
					jQuery('.aui-carousel-modal').modal({
919
						//backdrop: 'static'
920
					});
921
					jQuery('.aui-carousel-modal').on('hidden.bs.modal', function (e) {
922
						jQuery("iframe").attr('src', '');
923
					});
924
925
					$container = jQuery($link).closest('.aui-gallery');
926
927
					$clicked_href = jQuery($link).attr('href');
928
					$images = [];
929
					$container.find('.aui-lightbox-image').each(function() {
930
						var a = this;
931
						var href = jQuery(a).attr('href');
932
						if (href) {
933
							$images.push(href);
934
						}
935
					});
936
937
					if( $images.length ){
938
						var $carousel = '<div id="aui-embed-slider-modal" class="carousel slide" >';
939
940
						// indicators
941
						if($images.length > 1){
942
							$i = 0;
943
							$carousel  += '<ol class="carousel-indicators position-fixed">';
944
							$container.find('.aui-lightbox-image').each(function() {
945
								$active = $clicked_href == jQuery(this).attr('href') ? 'active' : '';
946
								$carousel  += '<li data-target="#aui-embed-slider-modal" data-slide-to="'+$i+'" class="'+$active+'"></li>';
947
								$i++;
948
949
							});
950
							$carousel  += '</ol>';
951
						}
952
953
954
955
						// items
956
						$i = 0;
957
						$carousel  += '<div class="carousel-inner">';
958
						$container.find('.aui-lightbox-image').each(function() {
959
							var a = this;
960
961
							$active = $clicked_href == jQuery(this).attr('href') ? 'active' : '';
962
							$carousel  += '<div class="carousel-item '+ $active+'"><div>';
963
964
965
							// image
966
							var css_height = window.innerWidth > window.innerHeight ? '90vh' : 'auto';
967
							var img = jQuery(a).find('img').clone().removeClass().addClass('mx-auto d-block w-auto mw-100 rounded').css('max-height',css_height).get(0).outerHTML;
968
							$carousel  += img;
969
							// captions
970
							if(jQuery(a).parent().find('.carousel-caption').length ){
971
								$carousel  += jQuery(a).parent().find('.carousel-caption').clone().removeClass('sr-only').get(0).outerHTML;
972
							}else if(jQuery(a).parent().find('.figure-caption').length ){
973
                                $carousel  += jQuery(a).parent().find('.figure-caption').clone().removeClass('sr-only').addClass('carousel-caption').get(0).outerHTML;
974
                            }
975
							$carousel  += '</div></div>';
976
							$i++;
977
978
						});
979
						$container.find('.aui-lightbox-iframe').each(function() {
980
							var a = this;
981
982
							$active = $clicked_href == jQuery(this).attr('href') ? 'active' : '';
983
							$carousel  += '<div class="carousel-item '+ $active+'"><div class="modal-xl mx-auto embed-responsive embed-responsive-16by9">';
984
985
986
							// iframe
987
							var css_height = window.innerWidth > window.innerHeight ? '95vh' : 'auto';
988
							var url = jQuery(a).attr('href');
989
							var iframe = '<iframe class="embed-responsive-item" style="height:'+css_height +'" src="'+url+'?rel=0&amp;showinfo=0&amp;modestbranding=1&amp;autoplay=1" id="video" allow="autoplay"></iframe>';
990
							var img = iframe ;//.css('height',css_height).get(0).outerHTML;
991
							$carousel  += img;
992
993
							$carousel  += '</div></div>';
994
							$i++;
995
996
						});
997
						$carousel  += '</div>';
998
999
1000
						// next/prev indicators
1001
						if($images.length > 1) {
1002
							$carousel += '<a class="carousel-control-prev" href="#aui-embed-slider-modal" role="button" data-slide="prev">';
1003
							$carousel += '<span class="carousel-control-prev-icon" aria-hidden="true"></span>';
1004
							$carousel += ' <a class="carousel-control-next" href="#aui-embed-slider-modal" role="button" data-slide="next">';
1005
							$carousel += '<span class="carousel-control-next-icon" aria-hidden="true"></span>';
1006
							$carousel += '</a>';
1007
						}
1008
1009
1010
						$carousel  += '</div>';
1011
1012
						var $close = '<button type="button" class="close text-white text-right position-fixed" style="font-size: 2.5em;right: 20px;top: 10px; z-index: 1055;" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
1013
1014
						jQuery('.aui-carousel-modal .modal-content').html($carousel).prepend($close);
1015
1016
						// enable ajax load
1017
						//gd_init_carousel_ajax();
1018
					}
1019
1020
				}
1021
1022
				/**
1023
				 * Init lightbox embed.
1024
				 */
1025
				function aui_init_lightbox_embed(){
1026
					// Open a lightbox for embeded items
1027
					jQuery('.aui-lightbox-image, .aui-lightbox-iframe').off('click').on("click",function(ele) {
1028
						aui_lightbox_embed(this,ele);
1029
					});
1030
				}
1031
1032
				/**
1033
				 * Show a toast.
1034
				 */
1035
				$aui_doing_toast = false;
1036
				function aui_toast($id,$type,$title,$title_small,$body,$time,$can_close){
1037
1038
					if($aui_doing_toast){setTimeout(function(){
1039
						aui_toast($id,$type,$title,$title_small,$body,$time,$can_close);
1040
					}, 500); return;}
1041
1042
					$aui_doing_toast = true;
1043
1044
					if($can_close == null){$can_close = false;}
1045
					if($time == '' || $time == null ){$time = 3000;}
1046
1047
					// if already setup then just show
1048
					if(document.getElementById($id)){
1049
						jQuery('#'+$id).toast('show');
1050
						setTimeout(function(){ $aui_doing_toast = false; }, 500);
1051
						return;
1052
					}
1053
1054
					var uniqid = Date.now();
1055
					if($id){
1056
						uniqid = $id;
1057
					}
1058
1059
					$op = "";
1060
					$tClass = '';
1061
					$thClass = '';
1062
					$icon = "";
1063
1064
					if ($type == 'success') {
1065
						$op = "opacity:.92;";
1066
						$tClass = 'alert alert-success';
1067
						$thClass = 'bg-transparent border-0 alert-success';
1068
						$icon = "<div class='h5 m-0 p-0'><i class='fas fa-check-circle mr-2'></i></div>";
1069
					} else if ($type == 'error' || $type == 'danger') {
1070
						$op = "opacity:.92;";
1071
						$tClass = 'alert alert-danger';
1072
						$thClass = 'bg-transparent border-0 alert-danger';
1073
						$icon = "<div class='h5 m-0 p-0'><i class='far fa-times-circle mr-2'></i></div>";
1074
					} else if ($type == 'info') {
1075
						$op = "opacity:.92;";
1076
						$tClass = 'alert alert-info';
1077
						$thClass = 'bg-transparent border-0 alert-info';
1078
						$icon = "<div class='h5 m-0 p-0'><i class='fas fa-info-circle mr-2'></i></div>";
1079
					} else if ($type == 'warning') {
1080
						$op = "opacity:.92;";
1081
						$tClass = 'alert alert-warning';
1082
						$thClass = 'bg-transparent border-0 alert-warning';
1083
						$icon = "<div class='h5 m-0 p-0'><i class='fas fa-exclamation-triangle mr-2'></i></div>";
1084
					}
1085
1086
1087
					// add container if not exist
1088
					if(!document.getElementById("aui-toasts")){
1089
						jQuery('body').append('<div class="bsui" id="aui-toasts"><div class="position-fixed aui-toast-bottom-right pr-3 mb-1" style="z-index: 500000;right: 0;bottom: 0;'+$op+'"></div></div>');
1090
					}
1091
1092
					$toast = '<div id="'+uniqid+'" class="toast fade hide shadow hover-shadow '+$tClass+'" style="" role="alert" aria-live="assertive" aria-atomic="true" data-delay="'+$time+'">';
1093
					if($type || $title || $title_small){
1094
						$toast += '<div class="toast-header '+$thClass+'">';
1095
						if($icon ){$toast += $icon;}
1096
						if($title){$toast += '<strong class="mr-auto">'+$title+'</strong>';}
1097
						if($title_small){$toast += '<small>'+$title_small+'</small>';}
1098
						if($can_close){$toast += '<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close"><span aria-hidden="true">×</span></button>';}
1099
						$toast += '</div>';
1100
					}
1101
					
1102
					if($body){
1103
						$toast += '<div class="toast-body">'+$body+'</div>';
1104
					}
1105
1106
					$toast += '</div>';
1107
1108
					jQuery('.aui-toast-bottom-right').prepend($toast);
1109
					jQuery('#'+uniqid).toast('show');
1110
					setTimeout(function(){ $aui_doing_toast = false; }, 500);
1111
				}
1112
1113
                /**
1114
                 * Animate a number.
1115
                 */
1116
                function aui_init_counters(){
1117
1118
                    const animNum = (EL) => {
1119
1120
                        if (EL._isAnimated) return; // Animate only once!
1121
                        EL._isAnimated = true;
1122
1123
                        let end = EL.dataset.auiend;
1124
                        let start = EL.dataset.auistart;
1125
                        let duration = EL.dataset.auiduration ? EL.dataset.auiduration : 2000;
1126
                        let seperator = EL.dataset.auisep ? EL.dataset.auisep: '';
1127
1128
                        jQuery(EL).prop('Counter', start).animate({
1129
                            Counter: end
1130
                        }, {
1131
                            duration: Math.abs(duration),
1132
                            easing: 'swing',
1133
                            step: function(now) {
1134
                                const text = seperator ?  (Math.ceil(now)).toLocaleString('en-US') : Math.ceil(now);
1135
                                const html = seperator ? text.split(",").map(n => `<span class="count">${n}</span>`).join(",") : text;
1136
                                if(seperator && seperator!=','){
1137
                                    html.replace(',',seperator);
1138
                                }
1139
                                jQuery(this).html(html);
1140
                            }
1141
                        });
1142
                    };
1143
1144
                    const inViewport = (entries, observer) => {
1145
                        // alert(1);
1146
                        entries.forEach(entry => {
1147
                            if (entry.isIntersecting) animNum(entry.target);
1148
                        });
1149
                    };
1150
1151
                    jQuery("[data-auicounter]").each((i, EL) => {
1152
                        const observer = new IntersectionObserver(inViewport);
1153
                        observer.observe(EL);
1154
                    });
1155
                }
1156
				
1157
1158
				/**
1159
				 * Initiate all AUI JS.
1160
				 */
1161
				function aui_init(){
1162
1163
                    // init counters
1164
                    aui_init_counters();
1165
1166
					// nav menu submenus
1167
					init_nav_sub_menus();
1168
					
1169
					// init tooltips
1170
					aui_init_tooltips();
1171
1172
					// init select2
1173
					aui_init_select2();
1174
1175
					// init flatpickr
1176
					aui_init_flatpickr();
1177
1178
					// init iconpicker
1179
					aui_init_iconpicker();
1180
1181
					// init Greedy nav
1182
					aui_init_greedy_nav();
1183
1184
					// Set times to time ago
1185
					aui_time_ago('timeago');
1186
					
1187
					// init multiple item carousels
1188
					aui_init_carousel_multiple_items();
1189
					
1190
					// init lightbox embeds
1191
					aui_init_lightbox_embed();
1192
				}
1193
1194
				// run on window loaded
1195
				jQuery(window).on("load",function() {
1196
					aui_init();
1197
				});
1198
1199
				/* Fix modal background scroll on iOS mobile device */
1200
				jQuery(function($) {
1201
					var ua = navigator.userAgent.toLowerCase();
1202
					var isiOS = ua.match(/(iphone|ipod|ipad)/);
1203
					if (isiOS) {
1204
						var pS = 0; pM = parseFloat($('body').css('marginTop'));
1205
1206
						$(document).on('show.bs.modal', function() {
1207
							pS = window.scrollY;
1208
							$('body').css({
1209
								marginTop: -pS,
1210
								overflow: 'hidden',
1211
								position: 'fixed',
1212
							});
1213
						}).on('hidden.bs.modal', function() {
1214
							$('body').css({
1215
								marginTop: pM,
1216
								overflow: 'visible',
1217
								position: 'inherit',
1218
							});
1219
							window.scrollTo(0, pS);
1220
						});
1221
					}
1222
				});
1223
1224
				/**
1225
				 * Show a "confirm" dialog to the user (using jQuery UI's dialog)
1226
				 *
1227
				 * @param {string} message The message to display to the user
1228
				 * @param {string} okButtonText OPTIONAL - The OK button text, defaults to "Yes"
1229
				 * @param {string} cancelButtonText OPTIONAL - The Cancel button text, defaults to "No"
1230
				 * @returns {Q.Promise<boolean>} A promise of a boolean value
1231
				 */
1232
				var aui_confirm = function (message, okButtonText, cancelButtonText, isDelete, large ) {
1233
					okButtonText = okButtonText || 'Yes';
1234
					cancelButtonText = cancelButtonText || 'Cancel';
1235
					message = message || 'Are you sure?';
1236
					sizeClass = large ? '' : 'modal-sm';
1237
					btnClass = isDelete ? 'btn-danger' : 'btn-primary';
1238
1239
					deferred = jQuery.Deferred();
1240
					var $body = "";
1241
					$body += "<h3 class='h4 py-3 text-center text-dark'>"+message+"</h3>";
1242
					$body += "<div class='d-flex'>";
1243
					$body += "<button class='btn btn-outline-secondary w-50 btn-round' data-dismiss='modal'  onclick='deferred.resolve(false);'>"+cancelButtonText+"</button>";
1244
					$body += "<button class='btn "+btnClass+" ml-2 w-50 btn-round' data-dismiss='modal'  onclick='deferred.resolve(true);'>"+okButtonText+"</button>";
1245
					$body += "</div>";
1246
					$modal = aui_modal('',$body,'',false,'',sizeClass);
1247
1248
					return deferred.promise();
1249
				};
1250
1251
                /**
1252
                 * Add a window scrolled data element.
1253
                 */
1254
                window.onscroll = function () {
1255
                    aui_set_data_scroll()
1256
                };
1257
1258
                /**
1259
                 * Set scroll data element.
1260
                 */
1261
                function aui_set_data_scroll(){
1262
                    document.documentElement.dataset.scroll = window.scrollY;
1263
                }
1264
1265
                // call data scroll function ASAP.
1266
                aui_set_data_scroll();
1267
			</script>
1268
			<?php
1269
			$output = ob_get_clean();
1270
1271
1272
1273
			/*
1274
			 * We only add the <script> tags for code highlighting, so we strip them from the output.
1275
			 */
1276
			return str_replace( array(
1277
				'<script>',
1278
				'</script>'
1279
			), '', self::minify_js($output) );
1280
		}
1281
1282
1283
		/**
1284
		 * JS to help with conflict issues with other plugins and themes using bootstrap v3.
1285
		 *
1286
		 * @TODO we may need this when other conflicts arrise.
1287
		 * @return mixed
1288
		 */
1289
		public static function bs3_compat_js() {
1290
			ob_start();
1291
			?>
1292
			<script>
1293
				<?php if( defined( 'FUSION_BUILDER_VERSION' ) ){ ?>
1294
				/* With Avada builder */
1295
1296
				<?php } ?>
1297
			</script>
1298
			<?php
1299
			return str_replace( array(
1300
				'<script>',
1301
				'</script>'
1302
			), '', ob_get_clean());
1303
		}
1304
1305
		/**
1306
		 * Get inline script used if bootstrap file browser enqueued.
1307
		 *
1308
		 * If this remains small then its best to use this than to add another JS file.
1309
		 */
1310
		public function inline_script_file_browser(){
1311
			ob_start();
1312
			?>
1313
			<script>
1314
				// run on doc ready
1315
				jQuery(document).ready(function () {
1316
					bsCustomFileInput.init();
1317
				});
1318
			</script>
1319
			<?php
1320
			$output = ob_get_clean();
1321
1322
			/*
1323
			 * We only add the <script> tags for code highlighting, so we strip them from the output.
1324
			 */
1325
			return str_replace( array(
1326
				'<script>',
1327
				'</script>'
1328
			), '', $output );
1329
		}
1330
1331
		/**
1332
		 * Adds the Font Awesome JS.
1333
		 */
1334
		public function enqueue_scripts() {
1335
1336
			if( is_admin() && !$this->is_aui_screen()){
1337
				// don't add wp-admin scripts if not requested to
1338
			}else {
1339
1340
				$js_setting = current_action() == 'wp_enqueue_scripts' ? 'js' : 'js_backend';
1341
1342
				// select2
1343
				wp_register_script( 'select2', $this->url . 'assets/js/select2.min.js', array( 'jquery' ), $this->select2_version );
1344
1345
				// flatpickr
1346
				wp_register_script( 'flatpickr', $this->url . 'assets/js/flatpickr.min.js', array(), $this->version );
1347
1348
				// flatpickr
1349
				wp_register_script( 'iconpicker', $this->url . 'assets/js/fa-iconpicker.min.js', array(), $this->version );
1350
				
1351
				// Bootstrap file browser
1352
				wp_register_script( 'aui-custom-file-input', $url = $this->url . 'assets/js/bs-custom-file-input.min.js', array( 'jquery' ), $this->select2_version );
1353
				wp_add_inline_script( 'aui-custom-file-input', $this->inline_script_file_browser() );
1354
1355
				$load_inline = false;
1356
1357
				if ( $this->settings[ $js_setting ] == 'core-popper' ) {
1358
					// Bootstrap bundle
1359
					$url = $this->url . 'assets/js/bootstrap.bundle.min.js';
1360
					wp_register_script( 'bootstrap-js-bundle', $url, array(
1361
						'select2',
1362
						'jquery'
1363
					), $this->version, $this->is_bs3_compat() );
1364
					// if in admin then add to footer for compatibility.
1365
					is_admin() ? wp_enqueue_script( 'bootstrap-js-bundle', '', null, null, true ) : wp_enqueue_script( 'bootstrap-js-bundle' );
1366
					$script = $this->inline_script();
1367
					wp_add_inline_script( 'bootstrap-js-bundle', $script );
1368
				} elseif ( $this->settings[ $js_setting ] == 'popper' ) {
1369
					$url = $this->url . 'assets/js/popper.min.js';
1370
					wp_register_script( 'bootstrap-js-popper', $url, array( 'select2', 'jquery' ), $this->version );
1371
					wp_enqueue_script( 'bootstrap-js-popper' );
1372
					$load_inline = true;
1373
				} else {
1374
					$load_inline = true;
1375
				}
1376
1377
				// Load needed inline scripts by faking the loading of a script if the main script is not being loaded
1378
				if ( $load_inline ) {
1379
					wp_register_script( 'bootstrap-dummy', '', array( 'select2', 'jquery' ) );
1380
					wp_enqueue_script( 'bootstrap-dummy' );
1381
					$script = $this->inline_script();
1382
					wp_add_inline_script( 'bootstrap-dummy', $script );
1383
				}
1384
			}
1385
1386
		}
1387
1388
		/**
1389
		 * Enqueue flatpickr if called.
1390
		 */
1391
		public function enqueue_flatpickr(){
1392
			wp_enqueue_style( 'flatpickr' );
1393
			wp_enqueue_script( 'flatpickr' );
1394
		}
1395
1396
		/**
1397
		 * Enqueue iconpicker if called.
1398
		 */
1399
		public function enqueue_iconpicker(){
1400
			wp_enqueue_style( 'iconpicker' );
1401
			wp_enqueue_script( 'iconpicker' );
1402
		}
1403
1404
		/**
1405
		 * Get the url path to the current folder.
1406
		 *
1407
		 * @return string
1408
		 */
1409
		public function get_url() {
1410
			$content_dir = wp_normalize_path( untrailingslashit( WP_CONTENT_DIR ) );
1411
			$content_url = untrailingslashit( WP_CONTENT_URL );
1412
1413
			// Replace http:// to https://.
1414
			if ( strpos( $content_url, 'http://' ) === 0 && strpos( plugins_url(), 'https://' ) === 0 ) {
1415
				$content_url = str_replace( 'http://', 'https://', $content_url );
1416
			}
1417
1418
			// Check if we are inside a plugin
1419
			$file_dir = str_replace( "/includes", "", wp_normalize_path( dirname( __FILE__ ) ) );
1420
			$url = str_replace( $content_dir, $content_url, $file_dir );
1421
1422
			return trailingslashit( $url );
1423
		}
1424
1425
		/**
1426
		 * Get the url path to the current folder.
1427
		 *
1428
		 * @return string
1429
		 */
1430
		public function get_url_old() {
1431
1432
			$url = '';
1433
			// check if we are inside a plugin
1434
			$file_dir = str_replace( "/includes","", wp_normalize_path( dirname( __FILE__ ) ) );
1435
1436
			// add check in-case user has changed wp-content dir name.
1437
			$wp_content_folder_name = basename(WP_CONTENT_DIR);
1438
			$dir_parts = explode("/$wp_content_folder_name/",$file_dir);
1439
			$url_parts = explode("/$wp_content_folder_name/",plugins_url());
1440
1441
			if(!empty($url_parts[0]) && !empty($dir_parts[1])){
1442
				$url = trailingslashit( $url_parts[0]."/$wp_content_folder_name/".$dir_parts[1] );
1443
			}
1444
1445
			return $url;
1446
		}
1447
1448
		/**
1449
		 * Register the database settings with WordPress.
1450
		 */
1451
		public function register_settings() {
1452
			register_setting( 'ayecode-ui-settings', 'ayecode-ui-settings' );
1453
		}
1454
1455
		/**
1456
		 * Add the WordPress settings menu item.
1457
		 * @since 1.0.10 Calling function name direct will fail theme check so we don't.
1458
		 */
1459
		public function menu_item() {
1460
			$menu_function = 'add' . '_' . 'options' . '_' . 'page'; // won't pass theme check if function name present in theme
1461
			call_user_func( $menu_function, $this->name, $this->name, 'manage_options', 'ayecode-ui-settings', array(
1462
				$this,
1463
				'settings_page'
1464
			) );
1465
		}
1466
1467
		/**
1468
		 * Get a list of themes and their default JS settings.
1469
		 *
1470
		 * @return array
1471
		 */
1472
		public function theme_js_settings(){
1473
			return array(
1474
				'ayetheme' => 'popper',
1475
				'listimia' => 'required',
1476
				'listimia_backend' => 'core-popper',
1477
				//'avada'    => 'required', // removed as we now add compatibility
1478
			);
1479
		}
1480
1481
		/**
1482
		 * Get the current Font Awesome output settings.
1483
		 *
1484
		 * @return array The array of settings.
1485
		 */
1486
		public function get_settings() {
1487
1488
			$db_settings = get_option( 'ayecode-ui-settings' );
1489
			$js_default = 'core-popper';
1490
			$js_default_backend = $js_default;
1491
1492
			// maybe set defaults (if no settings set)
1493
			if(empty($db_settings)){
1494
				$active_theme = strtolower( get_template() ); // active parent theme.
1495
				$theme_js_settings = self::theme_js_settings();
0 ignored issues
show
Bug Best Practice introduced by
The method AyeCode_UI_Settings::theme_js_settings() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1495
				/** @scrutinizer ignore-call */ 
1496
    $theme_js_settings = self::theme_js_settings();
Loading history...
1496
				if(isset($theme_js_settings[$active_theme])){
1497
					$js_default = $theme_js_settings[$active_theme];
1498
					$js_default_backend = isset($theme_js_settings[$active_theme."_backend"]) ? $theme_js_settings[$active_theme."_backend"] : $js_default;
1499
				}
1500
			}
1501
1502
			$defaults = array(
1503
				'css'       => 'compatibility', // core, compatibility
1504
				'js'        => $js_default, // js to load, core-popper, popper
1505
				'html_font_size'        => '16', // js to load, core-popper, popper
1506
				'css_backend'       => 'compatibility', // core, compatibility
1507
				'js_backend'        => $js_default_backend, // js to load, core-popper, popper
1508
				'disable_admin'     =>  '', // URL snippets to disable loading on admin
1509
			);
1510
1511
			$settings = wp_parse_args( $db_settings, $defaults );
1512
1513
			/**
1514
			 * Filter the Bootstrap settings.
1515
			 *
1516
			 * @todo if we add this filer people might use it and then it defeates the purpose of this class :/
1517
			 */
1518
			return $this->settings = apply_filters( 'ayecode-ui-settings', $settings, $db_settings, $defaults );
1519
		}
1520
1521
1522
		/**
1523
		 * The settings page html output.
1524
		 */
1525
		public function settings_page() {
1526
			if ( ! current_user_can( 'manage_options' ) ) {
1527
				wp_die( __( 'You do not have sufficient permissions to access this page.', 'aui' ) );
1528
			}
1529
			?>
1530
			<div class="wrap">
1531
				<h1><?php echo $this->name; ?></h1>
1532
				<p><?php _e("Here you can adjust settings if you are having compatibility issues.",'aui');?></p>
1533
				<form method="post" action="options.php">
1534
					<?php
1535
					settings_fields( 'ayecode-ui-settings' );
1536
					do_settings_sections( 'ayecode-ui-settings' );
1537
					?>
1538
1539
					<h2><?php _e( 'Frontend', 'aui' ); ?></h2>
1540
					<table class="form-table wpbs-table-settings">
1541
						<tr valign="top">
1542
							<th scope="row"><label
1543
									for="wpbs-css"><?php _e( 'Load CSS', 'aui' ); ?></label></th>
1544
							<td>
1545
								<select name="ayecode-ui-settings[css]" id="wpbs-css">
1546
									<option	value="compatibility" <?php selected( $this->settings['css'], 'compatibility' ); ?>><?php _e( 'Compatibility Mode (default)', 'aui' ); ?></option>
1547
									<option value="core" <?php selected( $this->settings['css'], 'core' ); ?>><?php _e( 'Full Mode', 'aui' ); ?></option>
1548
									<option	value="" <?php selected( $this->settings['css'], '' ); ?>><?php _e( 'Disabled', 'aui' ); ?></option>
1549
								</select>
1550
							</td>
1551
						</tr>
1552
1553
						<tr valign="top">
1554
							<th scope="row"><label
1555
									for="wpbs-js"><?php _e( 'Load JS', 'aui' ); ?></label></th>
1556
							<td>
1557
								<select name="ayecode-ui-settings[js]" id="wpbs-js">
1558
									<option	value="core-popper" <?php selected( $this->settings['js'], 'core-popper' ); ?>><?php _e( 'Core + Popper (default)', 'aui' ); ?></option>
1559
									<option value="popper" <?php selected( $this->settings['js'], 'popper' ); ?>><?php _e( 'Popper', 'aui' ); ?></option>
1560
									<option value="required" <?php selected( $this->settings['js'], 'required' ); ?>><?php _e( 'Required functions only', 'aui' ); ?></option>
1561
									<option	value="" <?php selected( $this->settings['js'], '' ); ?>><?php _e( 'Disabled (not recommended)', 'aui' ); ?></option>
1562
								</select>
1563
							</td>
1564
						</tr>
1565
1566
						<tr valign="top">
1567
							<th scope="row"><label
1568
									for="wpbs-font_size"><?php _e( 'HTML Font Size (px)', 'aui' ); ?></label></th>
1569
							<td>
1570
								<input type="number" name="ayecode-ui-settings[html_font_size]" id="wpbs-font_size" value="<?php echo absint( $this->settings['html_font_size']); ?>" placeholder="16" />
1571
								<p class="description" ><?php _e("Our font sizing is rem (responsive based) here you can set the html font size in-case your theme is setting it too low.",'aui');?></p>
1572
							</td>
1573
						</tr>
1574
1575
					</table>
1576
1577
					<h2><?php _e( 'Backend', 'aui' ); ?> (wp-admin)</h2>
1578
					<table class="form-table wpbs-table-settings">
1579
						<tr valign="top">
1580
							<th scope="row"><label
1581
									for="wpbs-css-admin"><?php _e( 'Load CSS', 'aui' ); ?></label></th>
1582
							<td>
1583
								<select name="ayecode-ui-settings[css_backend]" id="wpbs-css-admin">
1584
									<option	value="compatibility" <?php selected( $this->settings['css_backend'], 'compatibility' ); ?>><?php _e( 'Compatibility Mode (default)', 'aui' ); ?></option>
1585
									<option value="core" <?php selected( $this->settings['css_backend'], 'core' ); ?>><?php _e( 'Full Mode (will cause style issues)', 'aui' ); ?></option>
1586
									<option	value="" <?php selected( $this->settings['css_backend'], '' ); ?>><?php _e( 'Disabled', 'aui' ); ?></option>
1587
								</select>
1588
							</td>
1589
						</tr>
1590
1591
						<tr valign="top">
1592
							<th scope="row"><label
1593
									for="wpbs-js-admin"><?php _e( 'Load JS', 'aui' ); ?></label></th>
1594
							<td>
1595
								<select name="ayecode-ui-settings[js_backend]" id="wpbs-js-admin">
1596
									<option	value="core-popper" <?php selected( $this->settings['js_backend'], 'core-popper' ); ?>><?php _e( 'Core + Popper (default)', 'aui' ); ?></option>
1597
									<option value="popper" <?php selected( $this->settings['js_backend'], 'popper' ); ?>><?php _e( 'Popper', 'aui' ); ?></option>
1598
									<option value="required" <?php selected( $this->settings['js_backend'], 'required' ); ?>><?php _e( 'Required functions only', 'aui' ); ?></option>
1599
									<option	value="" <?php selected( $this->settings['js_backend'], '' ); ?>><?php _e( 'Disabled (not recommended)', 'aui' ); ?></option>
1600
								</select>
1601
							</td>
1602
						</tr>
1603
1604
						<tr valign="top">
1605
							<th scope="row"><label
1606
									for="wpbs-disable-admin"><?php _e( 'Disable load on URL', 'aui' ); ?></label></th>
1607
							<td>
1608
								<p><?php _e( 'If you have backend conflict you can enter a partial URL argument that will disable the loading of AUI on those pages. Add each argument on a new line.', 'aui' ); ?></p>
1609
								<textarea name="ayecode-ui-settings[disable_admin]" rows="10" cols="50" id="wpbs-disable-admin" class="large-text code" spellcheck="false" placeholder="myplugin.php &#10;action=go"><?php echo $this->settings['disable_admin'];?></textarea>
1610
1611
							</td>
1612
						</tr>
1613
1614
					</table>
1615
1616
					<?php
1617
					submit_button();
1618
					?>
1619
				</form>
1620
1621
				<div id="wpbs-version"><?php echo $this->version; ?></div>
1622
			</div>
1623
1624
			<?php
1625
		}
1626
1627
		public function customizer_settings($wp_customize){
1628
			$wp_customize->add_section('aui_settings', array(
1629
				'title'    => __('AyeCode UI','aui'),
1630
				'priority' => 120,
1631
			));
1632
1633
			//  =============================
1634
			//  = Color Picker              =
1635
			//  =============================
1636
			$wp_customize->add_setting('aui_options[color_primary]', array(
1637
				'default'           => AUI_PRIMARY_COLOR,
1638
				'sanitize_callback' => 'sanitize_hex_color',
1639
				'capability'        => 'edit_theme_options',
1640
				'type'              => 'option',
1641
				'transport'         => 'refresh',
1642
			));
1643
			$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'color_primary', array(
1644
				'label'    => __('Primary Color','aui'),
1645
				'section'  => 'aui_settings',
1646
				'settings' => 'aui_options[color_primary]',
1647
			)));
1648
1649
			$wp_customize->add_setting('aui_options[color_secondary]', array(
1650
				'default'           => '#6c757d',
1651
				'sanitize_callback' => 'sanitize_hex_color',
1652
				'capability'        => 'edit_theme_options',
1653
				'type'              => 'option',
1654
				'transport'         => 'refresh',
1655
			));
1656
			$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'color_secondary', array(
1657
				'label'    => __('Secondary Color','aui'),
1658
				'section'  => 'aui_settings',
1659
				'settings' => 'aui_options[color_secondary]',
1660
			)));
1661
		}
1662
1663
		/**
1664
		 * CSS to help with conflict issues with other plugins and themes using bootstrap v3.
1665
		 *
1666
		 * @return mixed
1667
		 */
1668
		public static function bs3_compat_css() {
1669
			ob_start();
1670
			?>
1671
			<style>
1672
			/* Bootstrap 3 compatibility */
1673
			body.modal-open .modal-backdrop.show:not(.in) {opacity:0.5;}
1674
			body.modal-open .modal.show:not(.in)  {opacity:1;z-index: 99999}
1675
			body.modal-open .modal.show:not(.in) .modal-content  {box-shadow: none;}
1676
			body.modal-open .modal.show:not(.in)  .modal-dialog {transform: initial;}
1677
1678
			body.modal-open .modal.bsui .modal-dialog{left: auto;}
1679
1680
			.collapse.show:not(.in){display: inherit;}
1681
			.fade.show{opacity: 1;}
1682
1683
			<?php if( defined( 'SVQ_THEME_VERSION' ) ){ ?>
1684
			/* KLEO theme specific */
1685
			.kleo-main-header .navbar-collapse.collapse.show:not(.in){display: block !important;}
1686
			<?php } ?>
1687
1688
			<?php if( defined( 'FUSION_BUILDER_VERSION' ) ){ ?>
1689
			/* With Avada builder */
1690
			body.modal-open .modal.in  {opacity:1;z-index: 99999}
1691
			body.modal-open .modal.bsui.in .modal-content  {box-shadow: none;}
1692
			.bsui .collapse.in{display: inherit;}
1693
			.bsui .collapse.in.row.show{display: flex;}
1694
			.bsui .collapse.in.row:not(.show){display: none;}
1695
1696
			<?php } ?>
1697
			</style>
1698
			<?php
1699
			return str_replace( array(
1700
				'<style>',
1701
				'</style>'
1702
			), '', self::minify_css( ob_get_clean() ) );
1703
		}
1704
1705
1706
		public static function custom_css($compatibility = true) {
1707
			$settings = get_option('aui_options');
1708
1709
			ob_start();
1710
1711
			$primary_color = !empty($settings['color_primary']) ? $settings['color_primary'] : AUI_PRIMARY_COLOR;
1712
			$secondary_color = !empty($settings['color_secondary']) ? $settings['color_secondary'] : AUI_SECONDARY_COLOR;
1713
				//AUI_PRIMARY_COLOR_ORIGINAL
1714
			?>
1715
			<style>
1716
				<?php
1717
1718
					// BS v3 compat
1719
					if( self::is_bs3_compat() ){
1720
					    echo self::bs3_compat_css();
1721
					}
1722
1723
					if(!is_admin() && $primary_color != AUI_PRIMARY_COLOR_ORIGINAL){
1724
						echo self::css_primary($primary_color,$compatibility);
1725
					}
1726
1727
					if(!is_admin() && $secondary_color != AUI_SECONDARY_COLOR_ORIGINAL){
1728
						echo self::css_secondary($settings['color_secondary'],$compatibility);
1729
					}
1730
1731
					// Set admin bar z-index lower when modal is open.
1732
					echo ' body.modal-open #wpadminbar{z-index:999}.embed-responsive-16by9 .fluid-width-video-wrapper{padding:0 !important;position:initial}';
1733
1734
					if(is_admin()){
1735
						echo ' body.modal-open #adminmenuwrap{z-index:999} body.modal-open #wpadminbar{z-index:1025}';
1736
					}
1737
                ?>
1738
			</style>
1739
			<?php
1740
1741
1742
			/*
1743
			 * We only add the <script> tags for code highlighting, so we strip them from the output.
1744
			 */
1745
			return str_replace( array(
1746
				'<style>',
1747
				'</style>'
1748
			), '', self::minify_css( ob_get_clean() ) );
1749
		}
1750
1751
		/**
1752
		 * Check if we should add booststrap 3 compatibility changes.
1753
		 *
1754
		 * @return bool
1755
		 */
1756
		public static function is_bs3_compat(){
1757
			return defined('AYECODE_UI_BS3_COMPAT') || defined('SVQ_THEME_VERSION') || defined('FUSION_BUILDER_VERSION');
1758
		}
1759
1760
		public static function css_primary($color_code,$compatibility){;
1761
			$color_code = sanitize_hex_color($color_code);
1762
			if(!$color_code){return '';}
1763
			/**
1764
			 * c = color, b = background color, o = border-color, f = fill
1765
			 */
1766
			$selectors = array(
1767
				'a' => array('c'),
1768
				'.btn-primary' => array('b','o'),
1769
				'.btn-primary.disabled' => array('b','o'),
1770
				'.btn-primary:disabled' => array('b','o'),
1771
				'.btn-outline-primary' => array('c','o'),
1772
				'.btn-outline-primary:hover' => array('b','o'),
1773
				'.btn-outline-primary:not(:disabled):not(.disabled).active' => array('b','o'),
1774
				'.btn-outline-primary:not(:disabled):not(.disabled):active' => array('b','o'),
1775
				'.show>.btn-outline-primary.dropdown-toggle' => array('b','o'),
1776
				'.btn-link' => array('c'),
1777
				'.dropdown-item.active' => array('b'),
1778
				'.custom-control-input:checked~.custom-control-label::before' => array('b','o'),
1779
				'.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::before' => array('b','o'),
1780
//				'.custom-range::-webkit-slider-thumb' => array('b'), // these break the inline rules...
1781
//				'.custom-range::-moz-range-thumb' => array('b'),
1782
//				'.custom-range::-ms-thumb' => array('b'),
1783
				'.nav-pills .nav-link.active' => array('b'),
1784
				'.nav-pills .show>.nav-link' => array('b'),
1785
				'.page-link' => array('c'),
1786
				'.page-item.active .page-link' => array('b','o'),
1787
				'.badge-primary' => array('b'),
1788
				'.alert-primary' => array('b','o'),
1789
				'.progress-bar' => array('b'),
1790
				'.list-group-item.active' => array('b','o'),
1791
				'.bg-primary' => array('b','f'),
1792
				'.btn-link.btn-primary' => array('c'),
1793
				'.select2-container .select2-results__option--highlighted.select2-results__option[aria-selected=true]' => array('b'),
1794
			);
1795
1796
			$important_selectors = array(
1797
				'.bg-primary' => array('b','f'),
1798
				'.border-primary' => array('o'),
1799
				'.text-primary' => array('c'),
1800
			);
1801
1802
			$color = array();
1803
			$color_i = array();
1804
			$background = array();
1805
			$background_i = array();
1806
			$border = array();
1807
			$border_i = array();
1808
			$fill = array();
1809
			$fill_i = array();
1810
1811
			$output = '';
1812
1813
			// build rules into each type
1814
			foreach($selectors as $selector => $types){
1815
				$selector = $compatibility ? ".bsui ".$selector : $selector;
1816
				$types = array_combine($types,$types);
1817
				if(isset($types['c'])){$color[] = $selector;}
1818
				if(isset($types['b'])){$background[] = $selector;}
1819
				if(isset($types['o'])){$border[] = $selector;}
1820
				if(isset($types['f'])){$fill[] = $selector;}
1821
			}
1822
1823
			// build rules into each type
1824
			foreach($important_selectors as $selector => $types){
1825
				$selector = $compatibility ? ".bsui ".$selector : $selector;
1826
				$types = array_combine($types,$types);
1827
				if(isset($types['c'])){$color_i[] = $selector;}
1828
				if(isset($types['b'])){$background_i[] = $selector;}
1829
				if(isset($types['o'])){$border_i[] = $selector;}
1830
				if(isset($types['f'])){$fill_i[] = $selector;}
1831
			}
1832
1833
			// add any color rules
1834
			if(!empty($color)){
1835
				$output .= implode(",",$color) . "{color: $color_code;} ";
1836
			}
1837
			if(!empty($color_i)){
1838
				$output .= implode(",",$color_i) . "{color: $color_code !important;} ";
1839
			}
1840
1841
			// add any background color rules
1842
			if(!empty($background)){
1843
				$output .= implode(",",$background) . "{background-color: $color_code;} ";
1844
			}
1845
			if(!empty($background_i)){
1846
				$output .= implode(",",$background_i) . "{background-color: $color_code !important;} ";
1847
			}
1848
1849
			// add any border color rules
1850
			if(!empty($border)){
1851
				$output .= implode(",",$border) . "{border-color: $color_code;} ";
1852
			}
1853
			if(!empty($border_i)){
1854
				$output .= implode(",",$border_i) . "{border-color: $color_code !important;} ";
1855
			}
1856
1857
			// add any fill color rules
1858
			if(!empty($fill)){
1859
				$output .= implode(",",$fill) . "{fill: $color_code;} ";
1860
			}
1861
			if(!empty($fill_i)){
1862
				$output .= implode(",",$fill_i) . "{fill: $color_code !important;} ";
1863
			}
1864
1865
1866
			$prefix = $compatibility ? ".bsui " : "";
1867
1868
			// darken
1869
			$darker_075 = self::css_hex_lighten_darken($color_code,"-0.075");
0 ignored issues
show
Bug introduced by
'-0.075' of type string is incompatible with the type double expected by parameter $adjustPercent of AyeCode_UI_Settings::css_hex_lighten_darken(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1869
			$darker_075 = self::css_hex_lighten_darken($color_code,/** @scrutinizer ignore-type */ "-0.075");
Loading history...
1870
			$darker_10 = self::css_hex_lighten_darken($color_code,"-0.10");
1871
			$darker_125 = self::css_hex_lighten_darken($color_code,"-0.125");
1872
1873
			// lighten
1874
			$lighten_25 = self::css_hex_lighten_darken($color_code,"0.25");
1875
1876
			// opacity see https://css-tricks.com/8-digit-hex-codes/
1877
			$op_25 = $color_code."40"; // 25% opacity
1878
1879
1880
			// button states
1881
			$output .= $prefix ." .btn-primary:hover, $prefix .btn-primary:focus, $prefix .btn-primary.focus{background-color: ".$darker_075.";    border-color: ".$darker_10.";} ";
1882
			$output .= $prefix ." .btn-outline-primary:not(:disabled):not(.disabled):active:focus, $prefix .btn-outline-primary:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-outline-primary.dropdown-toggle:focus{box-shadow: 0 0 0 0.2rem $op_25;} ";
1883
			$output .= $prefix ." .btn-primary:not(:disabled):not(.disabled):active, $prefix .btn-primary:not(:disabled):not(.disabled).active, .show>$prefix .btn-primary.dropdown-toggle{background-color: ".$darker_10.";    border-color: ".$darker_125.";} ";
1884
			$output .= $prefix ." .btn-primary:not(:disabled):not(.disabled):active:focus, $prefix .btn-primary:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-primary.dropdown-toggle:focus {box-shadow: 0 0 0 0.2rem $op_25;} ";
1885
1886
1887
			// dropdown's
1888
			$output .= $prefix ." .dropdown-item.active, $prefix .dropdown-item:active{background-color: $color_code;} ";
1889
1890
1891
			// input states
1892
			$output .= $prefix ." .form-control:focus{border-color: ".$lighten_25.";box-shadow: 0 0 0 0.2rem $op_25;} ";
1893
1894
			// page link
1895
			$output .= $prefix ." .page-link:focus{box-shadow: 0 0 0 0.2rem $op_25;} ";
1896
1897
			return $output;
1898
		}
1899
1900
		public static function css_secondary($color_code,$compatibility){;
1901
			$color_code = sanitize_hex_color($color_code);
1902
			if(!$color_code){return '';}
1903
			/**
1904
			 * c = color, b = background color, o = border-color, f = fill
1905
			 */
1906
			$selectors = array(
1907
				'.btn-secondary' => array('b','o'),
1908
				'.btn-secondary.disabled' => array('b','o'),
1909
				'.btn-secondary:disabled' => array('b','o'),
1910
				'.btn-outline-secondary' => array('c','o'),
1911
				'.btn-outline-secondary:hover' => array('b','o'),
1912
				'.btn-outline-secondary.disabled' => array('c'),
1913
				'.btn-outline-secondary:disabled' => array('c'),
1914
				'.btn-outline-secondary:not(:disabled):not(.disabled):active' => array('b','o'),
1915
				'.btn-outline-secondary:not(:disabled):not(.disabled).active' => array('b','o'),
1916
				'.btn-outline-secondary.dropdown-toggle' => array('b','o'),
1917
				'.badge-secondary' => array('b'),
1918
				'.alert-secondary' => array('b','o'),
1919
				'.btn-link.btn-secondary' => array('c'),
1920
			);
1921
1922
			$important_selectors = array(
1923
				'.bg-secondary' => array('b','f'),
1924
				'.border-secondary' => array('o'),
1925
				'.text-secondary' => array('c'),
1926
			);
1927
1928
			$color = array();
1929
			$color_i = array();
1930
			$background = array();
1931
			$background_i = array();
1932
			$border = array();
1933
			$border_i = array();
1934
			$fill = array();
1935
			$fill_i = array();
1936
1937
			$output = '';
1938
1939
			// build rules into each type
1940
			foreach($selectors as $selector => $types){
1941
				$selector = $compatibility ? ".bsui ".$selector : $selector;
1942
				$types = array_combine($types,$types);
1943
				if(isset($types['c'])){$color[] = $selector;}
1944
				if(isset($types['b'])){$background[] = $selector;}
1945
				if(isset($types['o'])){$border[] = $selector;}
1946
				if(isset($types['f'])){$fill[] = $selector;}
1947
			}
1948
1949
			// build rules into each type
1950
			foreach($important_selectors as $selector => $types){
1951
				$selector = $compatibility ? ".bsui ".$selector : $selector;
1952
				$types = array_combine($types,$types);
1953
				if(isset($types['c'])){$color_i[] = $selector;}
1954
				if(isset($types['b'])){$background_i[] = $selector;}
1955
				if(isset($types['o'])){$border_i[] = $selector;}
1956
				if(isset($types['f'])){$fill_i[] = $selector;}
1957
			}
1958
1959
			// add any color rules
1960
			if(!empty($color)){
1961
				$output .= implode(",",$color) . "{color: $color_code;} ";
1962
			}
1963
			if(!empty($color_i)){
1964
				$output .= implode(",",$color_i) . "{color: $color_code !important;} ";
1965
			}
1966
1967
			// add any background color rules
1968
			if(!empty($background)){
1969
				$output .= implode(",",$background) . "{background-color: $color_code;} ";
1970
			}
1971
			if(!empty($background_i)){
1972
				$output .= implode(",",$background_i) . "{background-color: $color_code !important;} ";
1973
			}
1974
1975
			// add any border color rules
1976
			if(!empty($border)){
1977
				$output .= implode(",",$border) . "{border-color: $color_code;} ";
1978
			}
1979
			if(!empty($border_i)){
1980
				$output .= implode(",",$border_i) . "{border-color: $color_code !important;} ";
1981
			}
1982
1983
			// add any fill color rules
1984
			if(!empty($fill)){
1985
				$output .= implode(",",$fill) . "{fill: $color_code;} ";
1986
			}
1987
			if(!empty($fill_i)){
1988
				$output .= implode(",",$fill_i) . "{fill: $color_code !important;} ";
1989
			}
1990
1991
1992
			$prefix = $compatibility ? ".bsui " : "";
1993
1994
			// darken
1995
			$darker_075 = self::css_hex_lighten_darken($color_code,"-0.075");
0 ignored issues
show
Bug introduced by
'-0.075' of type string is incompatible with the type double expected by parameter $adjustPercent of AyeCode_UI_Settings::css_hex_lighten_darken(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1995
			$darker_075 = self::css_hex_lighten_darken($color_code,/** @scrutinizer ignore-type */ "-0.075");
Loading history...
1996
			$darker_10 = self::css_hex_lighten_darken($color_code,"-0.10");
1997
			$darker_125 = self::css_hex_lighten_darken($color_code,"-0.125");
1998
1999
			// lighten
2000
			$lighten_25 = self::css_hex_lighten_darken($color_code,"0.25");
0 ignored issues
show
Unused Code introduced by
The assignment to $lighten_25 is dead and can be removed.
Loading history...
2001
2002
			// opacity see https://css-tricks.com/8-digit-hex-codes/
2003
			$op_25 = $color_code."40"; // 25% opacity
2004
2005
2006
			// button states
2007
			$output .= $prefix ." .btn-secondary:hover{background-color: ".$darker_075.";    border-color: ".$darker_10.";} ";
2008
			$output .= $prefix ." .btn-outline-secondary:not(:disabled):not(.disabled):active:focus, $prefix .btn-outline-secondary:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-outline-secondary.dropdown-toggle:focus{box-shadow: 0 0 0 0.2rem $op_25;} ";
2009
			$output .= $prefix ." .btn-secondary:not(:disabled):not(.disabled):active, $prefix .btn-secondary:not(:disabled):not(.disabled).active, .show>$prefix .btn-secondary.dropdown-toggle{background-color: ".$darker_10.";    border-color: ".$darker_125.";} ";
2010
			$output .= $prefix ." .btn-secondary:not(:disabled):not(.disabled):active:focus, $prefix .btn-secondary:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-secondary.dropdown-toggle:focus {box-shadow: 0 0 0 0.2rem $op_25;} ";
2011
2012
2013
			return $output;
2014
		}
2015
2016
		/**
2017
		 * Increases or decreases the brightness of a color by a percentage of the current brightness.
2018
		 *
2019
		 * @param   string  $hexCode        Supported formats: `#FFF`, `#FFFFFF`, `FFF`, `FFFFFF`
2020
		 * @param   float   $adjustPercent  A number between -1 and 1. E.g. 0.3 = 30% lighter; -0.4 = 40% darker.
2021
		 *
2022
		 * @return  string
2023
		 */
2024
		public static function css_hex_lighten_darken($hexCode, $adjustPercent) {
2025
			$hexCode = ltrim($hexCode, '#');
2026
2027
			if (strlen($hexCode) == 3) {
2028
				$hexCode = $hexCode[0] . $hexCode[0] . $hexCode[1] . $hexCode[1] . $hexCode[2] . $hexCode[2];
2029
			}
2030
2031
			$hexCode = array_map('hexdec', str_split($hexCode, 2));
0 ignored issues
show
Bug introduced by
It seems like str_split($hexCode, 2) can also be of type true; however, parameter $array of array_map() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2031
			$hexCode = array_map('hexdec', /** @scrutinizer ignore-type */ str_split($hexCode, 2));
Loading history...
2032
2033
			foreach ($hexCode as & $color) {
2034
				$adjustableLimit = $adjustPercent < 0 ? $color : 255 - $color;
2035
				$adjustAmount = ceil($adjustableLimit * $adjustPercent);
2036
2037
				$color = str_pad(dechex($color + $adjustAmount), 2, '0', STR_PAD_LEFT);
0 ignored issues
show
Bug introduced by
$color + $adjustAmount of type double is incompatible with the type integer expected by parameter $num of dechex(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2037
				$color = str_pad(dechex(/** @scrutinizer ignore-type */ $color + $adjustAmount), 2, '0', STR_PAD_LEFT);
Loading history...
2038
			}
2039
2040
			return '#' . implode($hexCode);
2041
		}
2042
2043
		/**
2044
		 * Check if we should display examples.
2045
		 */
2046
		public function maybe_show_examples(){
2047
			if(current_user_can('manage_options') && isset($_REQUEST['preview-aui'])){
2048
				echo "<head>";
2049
				wp_head();
2050
				echo "</head>";
2051
				echo "<body>";
2052
				echo $this->get_examples();
2053
				echo "</body>";
2054
				exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
2055
			}
2056
		}
2057
2058
		/**
2059
		 * Get developer examples.
2060
		 *
2061
		 * @return string
2062
		 */
2063
		public function get_examples(){
2064
			$output = '';
2065
2066
2067
			// open form
2068
			$output .= "<form class='p-5 m-5 border rounded'>";
2069
2070
			// input example
2071
			$output .= aui()->input(array(
2072
				'type'  =>  'text',
2073
				'id'    =>  'text-example',
2074
				'name'    =>  'text-example',
2075
				'placeholder'   => 'text placeholder',
2076
				'title'   => 'Text input example',
2077
				'value' =>  '',
2078
				'required'  => false,
2079
				'help_text' => 'help text',
2080
				'label' => 'Text input example label'
2081
			));
2082
2083
			// input example
2084
			$output .= aui()->input(array(
2085
				'type'  =>  'url',
2086
				'id'    =>  'text-example2',
2087
				'name'    =>  'text-example',
2088
				'placeholder'   => 'url placeholder',
2089
				'title'   => 'Text input example',
2090
				'value' =>  '',
2091
				'required'  => false,
2092
				'help_text' => 'help text',
2093
				'label' => 'Text input example label'
2094
			));
2095
2096
			// checkbox example
2097
			$output .= aui()->input(array(
2098
				'type'  =>  'checkbox',
2099
				'id'    =>  'checkbox-example',
2100
				'name'    =>  'checkbox-example',
2101
				'placeholder'   => 'checkbox-example',
2102
				'title'   => 'Checkbox example',
2103
				'value' =>  '1',
2104
				'checked'   => true,
2105
				'required'  => false,
2106
				'help_text' => 'help text',
2107
				'label' => 'Checkbox checked'
2108
			));
2109
2110
			// checkbox example
2111
			$output .= aui()->input(array(
2112
				'type'  =>  'checkbox',
2113
				'id'    =>  'checkbox-example2',
2114
				'name'    =>  'checkbox-example2',
2115
				'placeholder'   => 'checkbox-example',
2116
				'title'   => 'Checkbox example',
2117
				'value' =>  '1',
2118
				'checked'   => false,
2119
				'required'  => false,
2120
				'help_text' => 'help text',
2121
				'label' => 'Checkbox un-checked'
2122
			));
2123
2124
			// switch example
2125
			$output .= aui()->input(array(
2126
				'type'  =>  'checkbox',
2127
				'id'    =>  'switch-example',
2128
				'name'    =>  'switch-example',
2129
				'placeholder'   => 'checkbox-example',
2130
				'title'   => 'Switch example',
2131
				'value' =>  '1',
2132
				'checked'   => true,
2133
				'switch'    => true,
2134
				'required'  => false,
2135
				'help_text' => 'help text',
2136
				'label' => 'Switch on'
2137
			));
2138
2139
			// switch example
2140
			$output .= aui()->input(array(
2141
				'type'  =>  'checkbox',
2142
				'id'    =>  'switch-example2',
2143
				'name'    =>  'switch-example2',
2144
				'placeholder'   => 'checkbox-example',
2145
				'title'   => 'Switch example',
2146
				'value' =>  '1',
2147
				'checked'   => false,
2148
				'switch'    => true,
2149
				'required'  => false,
2150
				'help_text' => 'help text',
2151
				'label' => 'Switch off'
2152
			));
2153
2154
			// close form
2155
			$output .= "</form>";
2156
2157
			return $output;
2158
		}
2159
2160
		/**
2161
		 * Calendar params.
2162
		 *
2163
		 * @since 0.1.44
2164
		 *
2165
		 * @return array Calendar params.
2166
		 */
2167
		public static function calendar_params() {
2168
			$params = array(
2169
				'month_long_1' => __( 'January', 'aui' ),
2170
				'month_long_2' => __( 'February', 'aui' ),
2171
				'month_long_3' => __( 'March', 'aui' ),
2172
				'month_long_4' => __( 'April', 'aui' ),
2173
				'month_long_5' => __( 'May', 'aui' ),
2174
				'month_long_6' => __( 'June', 'aui' ),
2175
				'month_long_7' => __( 'July', 'aui' ),
2176
				'month_long_8' => __( 'August', 'aui' ),
2177
				'month_long_9' => __( 'September', 'aui' ),
2178
				'month_long_10' => __( 'October', 'aui' ),
2179
				'month_long_11' => __( 'November', 'aui' ),
2180
				'month_long_12' => __( 'December', 'aui' ),
2181
				'month_s_1' => _x( 'Jan', 'January abbreviation', 'aui' ),
2182
				'month_s_2' => _x( 'Feb', 'February abbreviation', 'aui' ),
2183
				'month_s_3' => _x( 'Mar', 'March abbreviation', 'aui' ),
2184
				'month_s_4' => _x( 'Apr', 'April abbreviation', 'aui' ),
2185
				'month_s_5' => _x( 'May', 'May abbreviation', 'aui' ),
2186
				'month_s_6' => _x( 'Jun', 'June abbreviation', 'aui' ),
2187
				'month_s_7' => _x( 'Jul', 'July abbreviation', 'aui' ),
2188
				'month_s_8' => _x( 'Aug', 'August abbreviation', 'aui' ),
2189
				'month_s_9' => _x( 'Sep', 'September abbreviation', 'aui' ),
2190
				'month_s_10' => _x( 'Oct', 'October abbreviation', 'aui' ),
2191
				'month_s_11' => _x( 'Nov', 'November abbreviation', 'aui' ),
2192
				'month_s_12' => _x( 'Dec', 'December abbreviation', 'aui' ),
2193
				'day_s1_1' => _x( 'S', 'Sunday initial', 'aui' ),
2194
				'day_s1_2' => _x( 'M', 'Monday initial', 'aui' ),
2195
				'day_s1_3' => _x( 'T', 'Tuesday initial', 'aui' ),
2196
				'day_s1_4' => _x( 'W', 'Wednesday initial', 'aui' ),
2197
				'day_s1_5' => _x( 'T', 'Friday initial', 'aui' ),
2198
				'day_s1_6' => _x( 'F', 'Thursday initial', 'aui' ),
2199
				'day_s1_7' => _x( 'S', 'Saturday initial', 'aui' ),
2200
				'day_s2_1' => __( 'Su', 'aui' ),
2201
				'day_s2_2' => __( 'Mo', 'aui' ),
2202
				'day_s2_3' => __( 'Tu', 'aui' ),
2203
				'day_s2_4' => __( 'We', 'aui' ),
2204
				'day_s2_5' => __( 'Th', 'aui' ),
2205
				'day_s2_6' => __( 'Fr', 'aui' ),
2206
				'day_s2_7' => __( 'Sa', 'aui' ),
2207
				'day_s3_1' => __( 'Sun', 'aui' ),
2208
				'day_s3_2' => __( 'Mon', 'aui' ),
2209
				'day_s3_3' => __( 'Tue', 'aui' ),
2210
				'day_s3_4' => __( 'Wed', 'aui' ),
2211
				'day_s3_5' => __( 'Thu', 'aui' ),
2212
				'day_s3_6' => __( 'Fri', 'aui' ),
2213
				'day_s3_7' => __( 'Sat', 'aui' ),
2214
				'day_s5_1' => __( 'Sunday', 'aui' ),
2215
				'day_s5_2' => __( 'Monday', 'aui' ),
2216
				'day_s5_3' => __( 'Tuesday', 'aui' ),
2217
				'day_s5_4' => __( 'Wednesday', 'aui' ),
2218
				'day_s5_5' => __( 'Thursday', 'aui' ),
2219
				'day_s5_6' => __( 'Friday', 'aui' ),
2220
				'day_s5_7' => __( 'Saturday', 'aui' ),
2221
				'am_lower' => __( 'am', 'aui' ),
2222
				'pm_lower' => __( 'pm', 'aui' ),
2223
				'am_upper' => __( 'AM', 'aui' ),
2224
				'pm_upper' => __( 'PM', 'aui' ),
2225
				'firstDayOfWeek' => (int) get_option( 'start_of_week' ),
2226
				'time_24hr' => false,
2227
				'year' => __( 'Year', 'aui' ),
2228
				'hour' => __( 'Hour', 'aui' ),
2229
				'minute' => __( 'Minute', 'aui' ),
2230
				'weekAbbreviation' => __( 'Wk', 'aui' ),
2231
				'rangeSeparator' => __( ' to ', 'aui' ),
2232
				'scrollTitle' => __( 'Scroll to increment', 'aui' ),
2233
				'toggleTitle' => __( 'Click to toggle', 'aui' )
2234
			);
2235
2236
			return apply_filters( 'ayecode_ui_calendar_params', $params );
2237
		}
2238
2239
		/**
2240
		 * Flatpickr calendar localize.
2241
		 *
2242
		 * @since 0.1.44
2243
		 *
2244
		 * @return string Calendar locale.
2245
		 */
2246
		public static function flatpickr_locale() {
2247
			$params = self::calendar_params();
2248
2249
			if ( is_string( $params ) ) {
0 ignored issues
show
introduced by
The condition is_string($params) is always false.
Loading history...
2250
				$params = html_entity_decode( $params, ENT_QUOTES, 'UTF-8' );
2251
			} else {
2252
				foreach ( (array) $params as $key => $value ) {
2253
					if ( ! is_scalar( $value ) ) {
2254
						continue;
2255
					}
2256
2257
					$params[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
2258
				}
2259
			}
2260
2261
			$day_s3 = array();
2262
			$day_s5 = array();
2263
2264
			for ( $i = 1; $i <= 7; $i ++ ) {
2265
				$day_s3[] = addslashes( $params[ 'day_s3_' . $i ] );
2266
				$day_s5[] = addslashes( $params[ 'day_s3_' . $i ] );
2267
			}
2268
2269
			$month_s = array();
2270
			$month_long = array();
2271
2272
			for ( $i = 1; $i <= 12; $i ++ ) {
2273
				$month_s[] = addslashes( $params[ 'month_s_' . $i ] );
2274
				$month_long[] = addslashes( $params[ 'month_long_' . $i ] );
2275
			}
2276
2277
ob_start();
2278
if ( 0 ) { ?><script><?php } ?>
2279
{
2280
	weekdays: {
2281
		shorthand: ['<?php echo implode( "','", $day_s3 ); ?>'],
2282
		longhand: ['<?php echo implode( "','", $day_s5 ); ?>'],
2283
	},
2284
	months: {
2285
		shorthand: ['<?php echo implode( "','", $month_s ); ?>'],
2286
		longhand: ['<?php echo implode( "','", $month_long ); ?>'],
2287
	},
2288
	daysInMonth: [31,28,31,30,31,30,31,31,30,31,30,31],
2289
	firstDayOfWeek: <?php echo (int) $params[ 'firstDayOfWeek' ]; ?>,
2290
	ordinal: function (nth) {
2291
		var s = nth % 100;
2292
		if (s > 3 && s < 21)
2293
			return "th";
2294
		switch (s % 10) {
2295
			case 1:
2296
				return "st";
2297
			case 2:
2298
				return "nd";
2299
			case 3:
2300
				return "rd";
2301
			default:
2302
				return "th";
2303
		}
2304
	},
2305
	rangeSeparator: '<?php echo addslashes( $params[ 'rangeSeparator' ] ); ?>',
2306
	weekAbbreviation: '<?php echo addslashes( $params[ 'weekAbbreviation' ] ); ?>',
2307
	scrollTitle: '<?php echo addslashes( $params[ 'scrollTitle' ] ); ?>',
2308
	toggleTitle: '<?php echo addslashes( $params[ 'toggleTitle' ] ); ?>',
2309
	amPM: ['<?php echo addslashes( $params[ 'am_upper' ] ); ?>','<?php echo addslashes( $params[ 'pm_upper' ] ); ?>'],
2310
	yearAriaLabel: '<?php echo addslashes( $params[ 'year' ] ); ?>',
2311
	hourAriaLabel: '<?php echo addslashes( $params[ 'hour' ] ); ?>',
2312
	minuteAriaLabel: '<?php echo addslashes( $params[ 'minute' ] ); ?>',
2313
	time_24hr: <?php echo ( $params[ 'time_24hr' ] ? 'true' : 'false' ) ; ?>
2314
}
2315
<?php if ( 0 ) { ?></script><?php } ?>
2316
<?php
2317
			$locale = ob_get_clean();
2318
2319
			return apply_filters( 'ayecode_ui_flatpickr_locale', trim( $locale ) );
2320
		}
2321
2322
		/**
2323
		 * Select2 JS params.
2324
		 *
2325
		 * @since 0.1.44
2326
		 *
2327
		 * @return array Select2 JS params.
2328
		 */
2329
		public static function select2_params() {
2330
			$params = array(
2331
				'i18n_select_state_text'    => esc_attr__( 'Select an option&hellip;', 'aui' ),
2332
				'i18n_no_matches'           => _x( 'No matches found', 'enhanced select', 'aui' ),
2333
				'i18n_ajax_error'           => _x( 'Loading failed', 'enhanced select', 'aui' ),
2334
				'i18n_input_too_short_1'    => _x( 'Please enter 1 or more characters', 'enhanced select', 'aui' ),
2335
				'i18n_input_too_short_n'    => _x( 'Please enter %item% or more characters', 'enhanced select', 'aui' ),
2336
				'i18n_input_too_long_1'     => _x( 'Please delete 1 character', 'enhanced select', 'aui' ),
2337
				'i18n_input_too_long_n'     => _x( 'Please delete %item% characters', 'enhanced select', 'aui' ),
2338
				'i18n_selection_too_long_1' => _x( 'You can only select 1 item', 'enhanced select', 'aui' ),
2339
				'i18n_selection_too_long_n' => _x( 'You can only select %item% items', 'enhanced select', 'aui' ),
2340
				'i18n_load_more'            => _x( 'Loading more results&hellip;', 'enhanced select', 'aui' ),
2341
				'i18n_searching'            => _x( 'Searching&hellip;', 'enhanced select', 'aui' )
2342
			);
2343
2344
			return apply_filters( 'ayecode_ui_select2_params', $params );
2345
		}
2346
2347
		/**
2348
		 * Select2 JS localize.
2349
		 *
2350
		 * @since 0.1.44
2351
		 *
2352
		 * @return string Select2 JS locale.
2353
		 */
2354
		public static function select2_locale() {
2355
			$params = self::select2_params();
2356
2357
			foreach ( (array) $params as $key => $value ) {
2358
				if ( ! is_scalar( $value ) ) {
2359
					continue;
2360
				}
2361
2362
				$params[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
2363
			}
2364
2365
			$locale = json_encode( $params );
2366
2367
			return apply_filters( 'ayecode_ui_select2_locale', trim( $locale ) );
2368
		}
2369
2370
		/**
2371
		 * Time ago JS localize.
2372
		 *
2373
		 * @since 0.1.47
2374
		 *
2375
		 * @return string Time ago JS locale.
2376
		 */
2377
		public static function timeago_locale() {
2378
			$params = array(
2379
				'prefix_ago' => '',
2380
				'suffix_ago' => ' ' . _x( 'ago', 'time ago', 'aui' ),
2381
				'prefix_after' => _x( 'after', 'time ago', 'aui' ) . ' ',
2382
				'suffix_after' => '',
2383
				'seconds' => _x( 'less than a minute', 'time ago', 'aui' ),
2384
				'minute' => _x( 'about a minute', 'time ago', 'aui' ),
2385
				'minutes' => _x( '%d minutes', 'time ago', 'aui' ),
2386
				'hour' => _x( 'about an hour', 'time ago', 'aui' ),
2387
				'hours' => _x( 'about %d hours', 'time ago', 'aui' ),
2388
				'day' => _x( 'a day', 'time ago', 'aui' ),
2389
				'days' => _x( '%d days', 'time ago', 'aui' ),
2390
				'month' => _x( 'about a month', 'time ago', 'aui' ),
2391
				'months' => _x( '%d months', 'time ago', 'aui' ),
2392
				'year' => _x( 'about a year', 'time ago', 'aui' ),
2393
				'years' => _x( '%d years', 'time ago', 'aui' ),
2394
			);
2395
2396
			$params = apply_filters( 'ayecode_ui_timeago_params', $params );
2397
2398
			foreach ( (array) $params as $key => $value ) {
2399
				if ( ! is_scalar( $value ) ) {
2400
					continue;
2401
				}
2402
2403
				$params[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
2404
			}
2405
2406
			$locale = json_encode( $params );
2407
2408
			return apply_filters( 'ayecode_ui_timeago_locale', trim( $locale ) );
2409
		}
2410
2411
		/**
2412
		 * JavaScript Minifier
2413
		 *
2414
		 * @param $input
2415
		 *
2416
		 * @return mixed
2417
		 */
2418
		public static function minify_js($input) {
2419
			if(trim($input) === "") return $input;
2420
			return preg_replace(
2421
				array(
2422
					// Remove comment(s)
2423
					'#\s*("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')\s*|\s*\/\*(?!\!|@cc_on)(?>[\s\S]*?\*\/)\s*|\s*(?<![\:\=])\/\/.*(?=[\n\r]|$)|^\s*|\s*$#',
2424
					// Remove white-space(s) outside the string and regex
2425
					'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/)|\/(?!\/)[^\n\r]*?\/(?=[\s.,;]|[gimuy]|$))|\s*([!%&*\(\)\-=+\[\]\{\}|;:,.<>?\/])\s*#s',
2426
					// Remove the last semicolon
2427
					'#;+\}#',
2428
					// Minify object attribute(s) except JSON attribute(s). From `{'foo':'bar'}` to `{foo:'bar'}`
2429
					'#([\{,])([\'])(\d+|[a-z_][a-z0-9_]*)\2(?=\:)#i',
2430
					// --ibid. From `foo['bar']` to `foo.bar`
2431
					'#([a-z0-9_\)\]])\[([\'"])([a-z_][a-z0-9_]*)\2\]#i'
2432
				),
2433
				array(
2434
					'$1',
2435
					'$1$2',
2436
					'}',
2437
					'$1$3',
2438
					'$1.$3'
2439
				),
2440
				$input);
2441
		}
2442
2443
		/**
2444
		 * Minify CSS
2445
		 *
2446
		 * @param $input
2447
		 *
2448
		 * @return mixed
2449
		 */
2450
		public static function minify_css($input) {
2451
			if(trim($input) === "") return $input;
2452
			return preg_replace(
2453
				array(
2454
					// Remove comment(s)
2455
					'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')|\/\*(?!\!)(?>.*?\*\/)|^\s*|\s*$#s',
2456
					// Remove unused white-space(s)
2457
					'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/))|\s*+;\s*+(})\s*+|\s*+([*$~^|]?+=|[{};,>~]|\s(?![0-9\.])|!important\b)\s*+|([[(:])\s++|\s++([])])|\s++(:)\s*+(?!(?>[^{}"\']++|"(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')*+{)|^\s++|\s++\z|(\s)\s+#si',
2458
					// Replace `0(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)` with `0`
2459
					'#(?<=[\s:])(0)(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)#si',
2460
					// Replace `:0 0 0 0` with `:0`
2461
					'#:(0\s+0|0\s+0\s+0\s+0)(?=[;\}]|\!important)#i',
2462
					// Replace `background-position:0` with `background-position:0 0`
2463
					'#(background-position):0(?=[;\}])#si',
2464
					// Replace `0.6` with `.6`, but only when preceded by `:`, `,`, `-` or a white-space
2465
					'#(?<=[\s:,\-])0+\.(\d+)#s',
2466
					// Minify string value
2467
					'#(\/\*(?>.*?\*\/))|(?<!content\:)([\'"])([a-z_][a-z0-9\-_]*?)\2(?=[\s\{\}\];,])#si',
2468
					'#(\/\*(?>.*?\*\/))|(\burl\()([\'"])([^\s]+?)\3(\))#si',
2469
					// Minify HEX color code
2470
					'#(?<=[\s:,\-]\#)([a-f0-6]+)\1([a-f0-6]+)\2([a-f0-6]+)\3#i',
2471
					// Replace `(border|outline):none` with `(border|outline):0`
2472
					'#(?<=[\{;])(border|outline):none(?=[;\}\!])#',
2473
					// Remove empty selector(s)
2474
					'#(\/\*(?>.*?\*\/))|(^|[\{\}])(?:[^\s\{\}]+)\{\}#s'
2475
				),
2476
				array(
2477
					'$1',
2478
					'$1$2$3$4$5$6$7',
2479
					'$1',
2480
					':0',
2481
					'$1:0 0',
2482
					'.$1',
2483
					'$1$3',
2484
					'$1$2$4$5',
2485
					'$1$2$3',
2486
					'$1:0',
2487
					'$1$2'
2488
				),
2489
				$input);
2490
		}
2491
2492
		/**
2493
		 * Get the conditional fields JavaScript.
2494
		 *
2495
		 * @return mixed
2496
		 */
2497
		public function conditional_fields_js() {
2498
			ob_start();
2499
			?>
2500
<script>
2501
/**
2502
 * Conditional Fields
2503
 */
2504
var aui_cf_field_rules = [], aui_cf_field_key_rules = {}, aui_cf_field_default_values = {};
2505
2506
jQuery(function($) {
2507
    aui_cf_field_init_rules($);
2508
});
2509
2510
/**
2511
 * Conditional fields init.
2512
 */
2513
function aui_cf_field_init_rules($) {
2514
    if (!$('[data-has-rule]').length) {
2515
        return;
2516
    }
2517
    $('input.select2-search__field').attr('data-ignore-rule','');
2518
    $('[data-rule-key]').on('change keypress keyup gdclear', 'input, textarea', function() {
2519
        aui_cf_field_apply_rules($(this));
2520
    });
2521
2522
    $('[data-rule-key]').on('change gdclear', 'select', function() {
2523
        aui_cf_field_apply_rules($(this));
2524
    });
2525
2526
    $('[data-rule-key]').on('change.select2', 'select', function() {
2527
        aui_cf_field_apply_rules($(this));
2528
    });
2529
2530
    aui_cf_field_setup_rules($);
2531
}
2532
2533
/**
2534
 * Setup conditional field rules.
2535
 */
2536
function aui_cf_field_setup_rules($) {
2537
    var aui_cf_field_keys = [];
2538
2539
    $('[data-rule-key]').each(function() {
2540
        var key = $(this).data('rule-key'), irule = parseInt($(this).data('has-rule'));
2541
        if (key) {
2542
            aui_cf_field_keys.push(key);
2543
        }
2544
2545
        var parse_conds = {};
2546
        if ($(this).data('rule-fie-0')) {
2547
            $(this).find('input,select,textarea').each(function() {
2548
                if ($(this).attr('required') || $(this).attr('oninvalid')) {
2549
                    $(this).addClass('aui-cf-req');
2550
                    if ($(this).attr('required')) {
2551
                        $(this).attr('data-rule-req', true);
2552
                    }
2553
                    if ($(this).attr('oninvalid')) {
2554
                        $(this).attr('data-rule-oninvalid', $(this).attr('oninvalid'));
2555
                    }
2556
                }
2557
            });
2558
            for (var i = 0; i < irule; i++) {
2559
                var field = $(this).data('rule-fie-' + i);
2560
                if (typeof parse_conds[i] === 'undefined') {
2561
                    parse_conds[i] = {};
2562
                }
2563
                parse_conds[i]['action'] = $(this).data('rule-act-' + i);
2564
                parse_conds[i]['field'] = $(this).data('rule-fie-' + i);
2565
                parse_conds[i]['condition'] = $(this).data('rule-con-' + i);
2566
                parse_conds[i]['value'] = $(this).data('rule-val-' + i);
2567
            }
2568
2569
            $.each(parse_conds, function(j, data) {
2570
                var item = {
2571
                    'field': {
2572
                        key: key,
2573
                        action: data.action,
2574
                        field: data.field,
2575
                        condition: data.condition,
2576
                        value: data.value,
2577
                        rule: {
2578
                            key: key,
2579
                            action: data.action,
2580
                            condition: data.condition,
2581
                            value: data.value
2582
                        }
2583
                    }
2584
                };
2585
                aui_cf_field_rules.push(item);
2586
            });
2587
        }
2588
        aui_cf_field_default_values[$(this).data('rule-key')] = aui_cf_field_get_default_value($(this));
2589
    });
2590
2591
    $.each(aui_cf_field_keys, function(i, fkey) {
2592
        aui_cf_field_key_rules[fkey] = aui_cf_field_get_children(fkey);
2593
    });
2594
2595
    $('[data-rule-key]:visible').each(function() {
2596
        var conds = aui_cf_field_key_rules[$(this).data('rule-key')];
2597
        if (conds && conds.length) {
2598
            var $main_el = $(this), el = aui_cf_field_get_element($main_el);
2599
            if ($(el).length) {
2600
                aui_cf_field_apply_rules($(el));
2601
            }
2602
        }
2603
    });
2604
}
2605
2606
/**
2607
 * Apply conditional field rules.
2608
 */
2609
function aui_cf_field_apply_rules($el) {
2610
    if (!$el.parents('[data-rule-key]').length) {
2611
        return;
2612
    }
2613
2614
    if ($el.data('no-rule')) {
2615
        return;
2616
    }
2617
2618
    var key = $el.parents('[data-rule-key]').data('rule-key');
2619
    var conditions = aui_cf_field_key_rules[key];
2620
    if (typeof conditions === 'undefined') {
2621
        return;
2622
    }
2623
    var field_type = aui_cf_field_get_type($el.parents('[data-rule-key]')), current_value = aui_cf_field_get_value($el);
2624
    var $keys = {}, $keys_values = {}, $key_rules = {};
2625
2626
    jQuery.each(conditions, function(index, condition) {
2627
        if (typeof $keys_values[condition.key] == 'undefined') {
2628
            $keys_values[condition.key] = [];
2629
            $key_rules[condition.key] = {}
2630
        }
2631
2632
        $keys_values[condition.key].push(condition.value);
2633
        $key_rules[condition.key] = condition;
2634
    });
2635
2636
    jQuery.each(conditions, function(index, condition) {
2637
        if (typeof $keys[condition.key] == 'undefined') {
2638
            $keys[condition.key] = {};
2639
        }
2640
2641
        if (condition.condition === 'empty') {
2642
            var field_value = Array.isArray(current_value) ? current_value.join('') : current_value;
2643
            if (!field_value || field_value === '') {
2644
                $keys[condition.key][index] = true;
2645
            } else {
2646
                $keys[condition.key][index] = false;
2647
            }
2648
        } else if (condition.condition === 'not empty') {
2649
            var field_value = Array.isArray(current_value) ? current_value.join('') : current_value;
2650
            if (field_value && field_value !== '') {
2651
                $keys[condition.key][index] = true;
2652
            } else {
2653
                $keys[condition.key][index] = false;
2654
            }
2655
        } else if (condition.condition === 'equals to') {
2656
            var field_value = (Array.isArray(current_value) && current_value.length === 1) ? current_value[0] : current_value;
2657
            if (((condition.value && condition.value == condition.value) || (condition.value === field_value)) && aui_cf_field_in_array(field_value, $keys_values[condition.key])) {
2658
                $keys[condition.key][index] = true;
2659
            } else {
2660
                $keys[condition.key][index] = false;
2661
            }
2662
        } else if (condition.condition === 'not equals') {
2663
            var field_value = (Array.isArray(current_value) && current_value.length === 1) ? current_value[0] : current_value;
2664
            if (jQuery.isNumeric(condition.value) && parseInt(field_value) !== parseInt(condition.value) && field_value && !aui_cf_field_in_array(field_value, $keys_values[condition.key])) {
2665
                $keys[condition.key][index] = true;
2666
            } else if (condition.value != field_value && !aui_cf_field_in_array(field_value, $keys_values[condition.key])) {
2667
                $keys[condition.key][index] = true;
2668
            } else {
2669
                $keys[condition.key][index] = false;
2670
            }
2671
        } else if (condition.condition === 'greater than') {
2672
            var field_value = (Array.isArray(current_value) && current_value.length === 1) ? current_value[0] : current_value;
2673
            if (jQuery.isNumeric(condition.value) && parseInt(field_value) > parseInt(condition.value)) {
2674
                $keys[condition.key][index] = true;
2675
            } else {
2676
                $keys[condition.key][index] = false;
2677
            }
2678
        } else if (condition.condition === 'less than') {
2679
            var field_value = (Array.isArray(current_value) && current_value.length === 1) ? current_value[0] : current_value;
2680
            if (jQuery.isNumeric(condition.value) && parseInt(field_value) < parseInt(condition.value)) {
2681
                $keys[condition.key][index] = true;
2682
            } else {
2683
                $keys[condition.key][index] = false;
2684
            }
2685
        } else if (condition.condition === 'contains') {
2686
            switch (field_type) {
2687
                case 'multiselect':
2688
                    if (current_value && ((!Array.isArray(current_value) && current_value.indexOf(condition.value) >= 0) || (Array.isArray(current_value) && aui_cf_field_in_array(condition.value, current_value)))) {
2689
                        $keys[condition.key][index] = true;
2690
                    } else {
2691
                        $keys[condition.key][index] = false;
2692
                    }
2693
                    break;
2694
                case 'checkbox':
2695
                    if (current_value && ((!Array.isArray(current_value) && current_value.indexOf(condition.value) >= 0) || (Array.isArray(current_value) && aui_cf_field_in_array(condition.value, current_value)))) {
2696
                        $keys[condition.key][index] = true;
2697
                    } else {
2698
                        $keys[condition.key][index] = false;
2699
                    }
2700
                    break;
2701
                default:
2702
                    if (typeof $keys[condition.key][index] === 'undefined') {
2703
                        if (current_value && current_value.indexOf(condition.value) >= 0 && aui_cf_field_in_array(current_value, $keys_values[condition.key], false, true)) {
2704
                            $keys[condition.key][index] = true;
2705
                        } else {
2706
                            $keys[condition.key][index] = false;
2707
                        }
2708
                    }
2709
                    break;
2710
            }
2711
        }
2712
    });
2713
2714
    jQuery.each($keys, function(index, field) {
2715
        if (aui_cf_field_in_array(true, field)) {
2716
            aui_cf_field_apply_action($el, $key_rules[index], true);
2717
        } else {
2718
            aui_cf_field_apply_action($el, $key_rules[index], false);
2719
        }
2720
    });
2721
2722
    /* Trigger field change */
2723
    if ($keys.length) {
2724
        $el.trigger('aui_cf_field_on_change');
2725
    }
2726
}
2727
2728
/**
2729
 * Get the field element.
2730
 */
2731
function aui_cf_field_get_element($el) {
2732
    var el = $el.find('input:not("[data-ignore-rule]"),textarea,select'), type = aui_cf_field_get_type($el);
2733
    if (type && window._aui_cf_field_elements && typeof window._aui_cf_field_elements == 'object' && typeof window._aui_cf_field_elements[type] != 'undefined') {
2734
        el = window._aui_cf_field_elements[type];
2735
    }
2736
    return el;
2737
}
2738
2739
/**
2740
 * Get the field type.
2741
 */
2742
function aui_cf_field_get_type($el) {
2743
    return $el.data('rule-type');
2744
}
2745
2746
/**
2747
 * Get the field value.
2748
 */
2749
function aui_cf_field_get_value($el) {
2750
    var current_value = $el.val();
2751
2752
    if ($el.is(':checkbox')) {
2753
        current_value = '';
2754
        if ($el.parents('[data-rule-key]').find('input:checked').length > 1) {
2755
            $el.parents('[data-rule-key]').find('input:checked').each(function() {
2756
                current_value = current_value + jQuery(this).val() + ' ';
2757
            });
2758
        } else {
2759
            if ($el.parents('[data-rule-key]').find('input:checked').length >= 1) {
2760
                current_value = $el.parents('[data-rule-key]').find('input:checked').val();
2761
            }
2762
        }
2763
    }
2764
2765
    if ($el.is(':radio')) {
2766
        current_value = $el.parents('[data-rule-key]').find('input[type=radio]:checked').val();
2767
    }
2768
2769
    return current_value;
2770
}
2771
2772
/**
2773
 * Get the field default value.
2774
 */
2775
function aui_cf_field_get_default_value($el) {
2776
    var value = '', type = aui_cf_field_get_type($el);
2777
2778
    switch (type) {
2779
        case 'text':
2780
        case 'number':
2781
        case 'date':
2782
        case 'textarea':
2783
        case 'select':
2784
            value = $el.find('input:text,input[type="number"],textarea,select').val();
2785
            break;
2786
        case 'phone':
2787
        case 'email':
2788
        case 'color':
2789
        case 'url':
2790
        case 'hidden':
2791
        case 'password':
2792
        case 'file':
2793
            value = $el.find('input[type="' + type + '"]').val();
2794
            break;
2795
        case 'multiselect':
2796
            value = $el.find('select').val();
2797
            break;
2798
        case 'radio':
2799
            if ($el.find('input[type="radio"]:checked').length >= 1) {
2800
                value = $el.find('input[type="radio"]:checked').val();
2801
            }
2802
            break;
2803
        case 'checkbox':
2804
            if ($el.find('input[type="checkbox"]:checked').length >= 1) {
2805
                if ($el.find('input[type="checkbox"]:checked').length > 1) {
2806
                    var values = [];
2807
                    values.push(value);
2808
                    $el.find('input[type="checkbox"]:checked').each(function() {
2809
                        values.push(jQuery(this).val());
2810
                    });
2811
                    value = values;
2812
                } else {
2813
                    value = $el.find('input[type="checkbox"]:checked').val();
2814
                }
2815
            }
2816
            break;
2817
        default:
2818
            if (window._aui_cf_field_default_values && typeof window._aui_cf_field_default_values == 'object' && typeof window._aui_cf_field_default_values[type] != 'undefined') {
2819
                value = window._aui_cf_field_default_values[type];
2820
            }
2821
            break;
2822
    }
2823
    return {
2824
        type: type,
2825
        value: value
2826
    };
2827
}
2828
2829
/**
2830
 * Reset field default value.
2831
 */
2832
function aui_cf_field_reset_default_value($el) {
2833
    var type = aui_cf_field_get_type($el), key = $el.data('rule-key'), field = aui_cf_field_default_values[key];
2834
2835
    switch (type) {
2836
        case 'text':
2837
        case 'number':
2838
        case 'date':
2839
        case 'textarea':
2840
            $el.find('input:text,input[type="number"],textarea').val(field.value);
2841
            break;
2842
        case 'phone':
2843
        case 'email':
2844
        case 'color':
2845
        case 'url':
2846
        case 'hidden':
2847
        case 'password':
2848
        case 'file':
2849
            $el.find('input[type="' + type + '"]').val(field.value);
2850
            break;
2851
        case 'select':
2852
            $el.find('select').find('option').prop('selected', false);
2853
            $el.find('select').val(field.value);
2854
            $el.find('select').trigger('change');
2855
            break;
2856
        case 'multiselect':
2857
            $el.find('select').find('option').prop('selected', false);
2858
            if ((typeof field.value === 'object' || typeof field.value === 'array') && !field.value.length && $el.find('select option:first').text() == '') {
2859
                $el.find('select option:first').remove(); // Clear first option to show placeholder.
2860
            }
2861
            jQuery.each(field.value, function(i, v) {
2862
                $el.find('select').find('option[value="' + v + '"]').attr('selected', true);
2863
            });
2864
            $el.find('select').trigger('change');
2865
            break;
2866
        case 'checkbox':
2867
            if ($el.find('input[type="checkbox"]:checked').length >= 1) {
2868
                $el.find('input[type="checkbox"]:checked').prop('checked', false);
2869
                if (Array.isArray(field.value)) {
2870
                    jQuery.each(field.value, function(i, v) {
2871
                        $el.find('input[type="checkbox"][value="' + v + '"]').attr('checked', true);
2872
                    });
2873
                } else {
2874
                    $el.find('input[type="checkbox"][value="' + field.value + '"]').attr('checked', true);
2875
                }
2876
            }
2877
            break;
2878
        case 'radio':
2879
            if ($el.find('input[type="radio"]:checked').length >= 1) {
2880
                setTimeout(function() {
2881
                    $el.find('input[type="radio"]:checked').prop('checked', false);
2882
                    $el.find('input[type="radio"][value="' + field.value + '"]').attr('checked', true);
2883
                }, 100);
2884
            }
2885
            break;
2886
        default:
2887
            jQuery(document.body).trigger('aui_cf_field_reset_default_value', type, $el, field);
2888
            break;
2889
    }
2890
2891
    if (!$el.hasClass('aui-cf-field-has-changed')) {
2892
        var el = aui_cf_field_get_element($el);
2893
        if (type === 'radio' || type === 'checkbox') {
2894
            el = el.find(':checked');
2895
        }
2896
        if (el) {
2897
            el.trigger('change');
2898
            $el.addClass('aui-cf-field-has-changed');
2899
        }
2900
    }
2901
}
2902
2903
/**
2904
 * Get the field children.
2905
 */
2906
function aui_cf_field_get_children(field_key) {
2907
    var rules = [];
2908
    jQuery.each(aui_cf_field_rules, function(j, rule) {
2909
        if (rule.field.field === field_key) {
2910
            rules.push(rule.field.rule);
2911
        }
2912
    });
2913
    return rules;
2914
}
2915
2916
/**
2917
 * Check in array field value.
2918
 */
2919
function aui_cf_field_in_array(find, item, exact, match) {
2920
    var found = false, key;
2921
    exact = !!exact;
2922
2923
    for (key in item) {
2924
        if ((exact && item[key] === find) || (!exact && item[key] == find) || (match && (typeof find === 'string' || typeof find === 'number') && (typeof item[key] === 'string' || typeof item[key] === 'number') && find.length && find.indexOf(item[key]) >= 0)) {
2925
            found = true;
2926
            break;
2927
        }
2928
    }
2929
    return found;
2930
}
2931
2932
/**
2933
 * App the field condition action.
2934
 */
2935
function aui_cf_field_apply_action($el, rule, isTrue) {
2936
    var $destEl = jQuery('[data-rule-key="' + rule.key + '"]');
2937
2938
    if (rule.action === 'show' && isTrue) {
2939
        if ($destEl.is(':hidden')) {
2940
            aui_cf_field_reset_default_value($destEl);
2941
        }
2942
        aui_cf_field_show_element($destEl);
2943
    } else if (rule.action === 'show' && !isTrue) {
2944
        aui_cf_field_hide_element($destEl);
2945
    } else if (rule.action === 'hide' && isTrue) {
2946
        aui_cf_field_hide_element($destEl);
2947
    } else if (rule.action === 'hide' && !isTrue) {
2948
        if ($destEl.is(':hidden')) {
2949
            aui_cf_field_reset_default_value($destEl);
2950
        }
2951
        aui_cf_field_show_element($destEl);
2952
    }
2953
    return $el.removeClass('aui-cf-field-has-changed');
2954
}
2955
2956
/**
2957
 * Show field element.
2958
 */
2959
function aui_cf_field_show_element($el) {
2960
    $el.removeClass('d-none').show();
2961
2962
    $el.find('.aui-cf-req').each(function() {
2963
        if (jQuery(this).data('rule-req')) {
2964
            jQuery(this).removeAttr('required').prop('required', true);
2965
        }
2966
        if (jQuery(this).data('rule-oninvalid')) {
2967
            jQuery(this).removeAttr('oninvalid').attr('oninvalid', jQuery(this).data('rule-oninvalid'));
2968
        }
2969
    });
2970
2971
    if (window && window.navigator.userAgent.indexOf("MSIE") !== -1) {
2972
        $el.css({
2973
            "visibility": "visible"
2974
        });
2975
    }
2976
}
2977
2978
/**
2979
 * Hide field element.
2980
 */
2981
function aui_cf_field_hide_element($el) {
2982
    $el.addClass('d-none').hide();
2983
2984
    $el.find('.aui-cf-req').each(function() {
2985
        if (jQuery(this).data('rule-req')) {
2986
            jQuery(this).removeAttr('required');
2987
        }
2988
        if (jQuery(this).data('rule-oninvalid')) {
2989
            jQuery(this).removeAttr('oninvalid');
2990
        }
2991
    });
2992
2993
    if (window && window.navigator.userAgent.indexOf("MSIE") !== -1) {
2994
        $el.css({
2995
            "visibility": "hidden"
2996
        });
2997
    }
2998
}
2999
<?php do_action( 'aui_conditional_fields_js', $this ); ?>
3000
</script>
3001
			<?php
3002
			$output = ob_get_clean();
3003
3004
			return str_replace( array( '<script>', '</script>' ), '', self::minify_js( $output ) );
3005
		}
3006
	}
3007
3008
	/**
3009
	 * Run the class if found.
3010
	 */
3011
	AyeCode_UI_Settings::instance();
3012
}