Passed
Push — master ( 9b7fbb...c2254e )
by Brian
14:13
created

AyeCode_UI_Settings   F

Complexity

Total Complexity 237

Size/Duplication

Total Lines 3426
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2302
dl 0
loc 3426
rs 0.8
c 1
b 0
f 0
wmc 237

42 Methods

Rating   Name   Duplication   Size   Complexity  
A load_admin_scripts() 0 14 4
A bs3_compat_css() 0 35 3
A theme_js_settings() 0 5 1
A select2_params() 0 16 1
A customizer_settings() 0 33 1
A enqueue_flatpickr() 0 3 1
A minify_css() 0 40 2
A get_url() 0 14 3
A is_bs3_compat() 0 2 3
A instance() 0 25 5
A html_font_size() 0 3 1
A inline_script_file_browser() 0 19 1
A enqueue_iconpicker() 0 3 1
A minify_js() 0 23 2
F constants() 0 65 17
A is_block_theme() 0 6 3
A show_admin_style_notice() 0 5 1
B get_examples() 0 95 1
F css_overwrite() 0 178 36
B conditional_fields_js() 0 508 1
A sd_aui_colors() 0 12 3
A settings_page() 0 97 2
A menu_item() 0 5 1
A bs3_compat_js() 0 14 2
A select2_locale() 0 14 3
A get_url_old() 0 16 3
A get_colors() 0 43 3
A get_settings() 0 33 4
F css_secondary() 0 114 23
B enqueue_scripts() 0 49 8
A maybe_show_examples() 0 9 3
F css_primary() 0 142 24
A css_hex_lighten_darken() 0 17 4
B flatpickr_locale() 0 74 9
F init() 0 47 16
A register_settings() 0 2 1
B enqueue_style() 0 78 9
B inline_script() 0 985 4
B calendar_params() 0 70 1
A timeago_locale() 0 32 3
D custom_css() 0 68 18
A is_aui_screen() 0 33 5

How to fix   Complexity   

Complex Class

Complex classes like AyeCode_UI_Settings often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AyeCode_UI_Settings, and based on these observations, apply Extract Interface, too.

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.77';
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
		/**
93
		 * Main AyeCode_UI_Settings Instance.
94
		 *
95
		 * Ensures only one instance of AyeCode_UI_Settings is loaded or can be loaded.
96
		 *
97
		 * @since 1.0.0
98
		 * @static
99
		 * @return AyeCode_UI_Settings - Main instance.
100
		 */
101
		public static function instance() {
102
			if ( ! isset( self::$instance ) && ! ( self::$instance instanceof AyeCode_UI_Settings ) ) {
103
104
				self::$instance = new AyeCode_UI_Settings;
105
106
				add_action( 'init', array( self::$instance, 'init' ) ); // set settings
107
108
				if ( is_admin() ) {
109
					add_action( 'admin_menu', array( self::$instance, 'menu_item' ) );
110
					add_action( 'admin_init', array( self::$instance, 'register_settings' ) );
111
112
					// Maybe show example page
113
					add_action( 'template_redirect', array( self::$instance,'maybe_show_examples' ) );
114
115
					if ( defined( 'BLOCKSTRAP_VERSION' ) ) {
116
						add_filter( 'sd_aui_colors', array( self::$instance,'sd_aui_colors' ), 10, 3 );
117
					}
118
				}
119
120
				add_action( 'customize_register', array( self::$instance, 'customizer_settings' ));
121
122
				do_action( 'ayecode_ui_settings_loaded' );
123
			}
124
125
			return self::$instance;
126
		}
127
128
		/**
129
         * Add custom colors to the color selector.
130
         *
131
		 * @param $theme_colors
132
		 * @param $include_outlines
133
		 * @param $include_branding
134
		 *
135
		 * @return mixed
136
		 */
137
		public function sd_aui_colors( $theme_colors, $include_outlines, $include_branding ){
0 ignored issues
show
Unused Code introduced by
The parameter $include_outlines is not used and could be removed. ( Ignorable by Annotation )

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

137
		public function sd_aui_colors( $theme_colors, /** @scrutinizer ignore-unused */ $include_outlines, $include_branding ){

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $include_branding is not used and could be removed. ( Ignorable by Annotation )

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

137
		public function sd_aui_colors( $theme_colors, $include_outlines, /** @scrutinizer ignore-unused */ $include_branding ){

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
138
139
140
			$setting = wp_get_global_settings();
141
142
			if(!empty($setting['color']['palette']['custom'])){
143
				foreach($setting['color']['palette']['custom'] as $color){
144
					$theme_colors[$color['slug']] = esc_attr($color['name']);
145
				}
146
			}
147
148
			return $theme_colors;
149
		}
150
151
		/**
152
		 * Setup some constants.
153
		 */
154
		public function constants(){
155
			define( 'AUI_PRIMARY_COLOR_ORIGINAL', "#1e73be" );
156
			define( 'AUI_SECONDARY_COLOR_ORIGINAL', '#6c757d' );
157
			define( 'AUI_INFO_COLOR_ORIGINAL', '#17a2b8' );
158
			define( 'AUI_WARNING_COLOR_ORIGINAL', '#ffc107' );
159
			define( 'AUI_DANGER_COLOR_ORIGINAL', '#dc3545' );
160
			define( 'AUI_SUCCESS_COLOR_ORIGINAL', '#44c553' );
161
			define( 'AUI_LIGHT_COLOR_ORIGINAL', '#f8f9fa' );
162
			define( 'AUI_DARK_COLOR_ORIGINAL', '#343a40' );
163
			define( 'AUI_WHITE_COLOR_ORIGINAL', '#fff' );
164
			define( 'AUI_PURPLE_COLOR_ORIGINAL', '#ad6edd' );
165
			define( 'AUI_SALMON_COLOR_ORIGINAL', '#ff977a' );
166
			define( 'AUI_CYAN_COLOR_ORIGINAL', '#35bdff' );
167
			define( 'AUI_GRAY_COLOR_ORIGINAL', '#ced4da' );
168
			define( 'AUI_INDIGO_COLOR_ORIGINAL', '#502c6c' );
169
			define( 'AUI_ORANGE_COLOR_ORIGINAL', '#orange' );
170
			define( 'AUI_BLACK_COLOR_ORIGINAL', '#000' );
171
172
			if ( ! defined( 'AUI_PRIMARY_COLOR' ) ) {
173
				define( 'AUI_PRIMARY_COLOR', AUI_PRIMARY_COLOR_ORIGINAL );
174
			}
175
			if ( ! defined( 'AUI_SECONDARY_COLOR' ) ) {
176
				define( 'AUI_SECONDARY_COLOR', AUI_SECONDARY_COLOR_ORIGINAL );
177
			}
178
			if ( ! defined( 'AUI_INFO_COLOR' ) ) {
179
				define( 'AUI_INFO_COLOR', AUI_INFO_COLOR_ORIGINAL );
180
			}
181
			if ( ! defined( 'AUI_WARNING_COLOR' ) ) {
182
				define( 'AUI_WARNING_COLOR', AUI_WARNING_COLOR_ORIGINAL );
183
			}
184
			if ( ! defined( 'AUI_DANGER_COLOR' ) ) {
185
				define( 'AUI_DANGER_COLOR', AUI_DANGER_COLOR_ORIGINAL );
186
			}
187
			if ( ! defined( 'AUI_SUCCESS_COLOR' ) ) {
188
				define( 'AUI_SUCCESS_COLOR', AUI_SUCCESS_COLOR_ORIGINAL );
189
			}
190
			if ( ! defined( 'AUI_LIGHT_COLOR' ) ) {
191
				define( 'AUI_LIGHT_COLOR', AUI_LIGHT_COLOR_ORIGINAL );
192
			}
193
			if ( ! defined( 'AUI_DARK_COLOR' ) ) {
194
				define( 'AUI_DARK_COLOR', AUI_DARK_COLOR_ORIGINAL );
195
			}
196
			if ( ! defined( 'AUI_WHITE_COLOR' ) ) {
197
				define( 'AUI_WHITE_COLOR', AUI_WHITE_COLOR_ORIGINAL );
198
			}
199
			if ( ! defined( 'AUI_PURPLE_COLOR' ) ) {
200
				define( 'AUI_PURPLE_COLOR', AUI_PURPLE_COLOR_ORIGINAL );
201
			}
202
			if ( ! defined( 'AUI_SALMON_COLOR' ) ) {
203
				define( 'AUI_SALMON_COLOR', AUI_SALMON_COLOR_ORIGINAL );
204
			}
205
			if ( ! defined( 'AUI_CYAN_COLOR' ) ) {
206
				define( 'AUI_CYAN_COLOR', AUI_CYAN_COLOR_ORIGINAL );
207
			}
208
			if ( ! defined( 'AUI_GRAY_COLOR' ) ) {
209
				define( 'AUI_GRAY_COLOR', AUI_GRAY_COLOR_ORIGINAL );
210
			}
211
			if ( ! defined( 'AUI_INDIGO_COLOR' ) ) {
212
				define( 'AUI_INDIGO_COLOR', AUI_INDIGO_COLOR_ORIGINAL );
213
			}
214
			if ( ! defined( 'AUI_ORANGE_COLOR' ) ) {
215
				define( 'AUI_ORANGE_COLOR', AUI_ORANGE_COLOR_ORIGINAL );
216
			}
217
			if ( ! defined( 'AUI_BLACK_COLOR' ) ) {
218
				define( 'AUI_BLACK_COLOR', AUI_BLACK_COLOR_ORIGINAL );
219
			}
220
221
		}
222
223
        public static function get_colors( $original = false){
224
225
	        if ( ! defined( 'AUI_PRIMARY_COLOR' ) ) {
226
                return array();
227
	        }
228
	        if ( $original ) {
229
                return array(
230
	                'primary'   => AUI_PRIMARY_COLOR_ORIGINAL,
231
	                'secondary' => AUI_SECONDARY_COLOR_ORIGINAL,
232
	                'info'      => AUI_INFO_COLOR_ORIGINAL,
233
	                'warning'   => AUI_WARNING_COLOR_ORIGINAL,
234
	                'danger'    => AUI_DANGER_COLOR_ORIGINAL,
235
	                'success'   => AUI_SUCCESS_COLOR_ORIGINAL,
236
	                'light'     => AUI_LIGHT_COLOR_ORIGINAL,
237
	                'dark'      => AUI_DARK_COLOR_ORIGINAL,
238
	                'white'     => AUI_WHITE_COLOR_ORIGINAL,
239
	                'purple'    => AUI_PURPLE_COLOR_ORIGINAL,
240
	                'salmon'    => AUI_SALMON_COLOR_ORIGINAL,
241
	                'cyan'      => AUI_CYAN_COLOR_ORIGINAL,
242
	                'gray'      => AUI_GRAY_COLOR_ORIGINAL,
243
	                'indigo'    => AUI_INDIGO_COLOR_ORIGINAL,
244
	                'orange'    => AUI_ORANGE_COLOR_ORIGINAL,
245
	                'black'     => AUI_BLACK_COLOR_ORIGINAL,
246
                );
247
	        }
248
249
            return array(
250
	            'primary'   => AUI_PRIMARY_COLOR,
251
	            'secondary' => AUI_SECONDARY_COLOR,
252
	            'info'      => AUI_INFO_COLOR,
253
	            'warning'   => AUI_WARNING_COLOR,
254
	            'danger'    => AUI_DANGER_COLOR,
255
	            'success'   => AUI_SUCCESS_COLOR,
256
	            'light'     => AUI_LIGHT_COLOR,
257
	            'dark'      => AUI_DARK_COLOR,
258
	            'white'     => AUI_WHITE_COLOR,
259
	            'purple'    => AUI_PURPLE_COLOR,
260
	            'salmon'    => AUI_SALMON_COLOR,
261
	            'cyan'      => AUI_CYAN_COLOR,
262
	            'gray'      => AUI_GRAY_COLOR,
263
	            'indigo'    => AUI_INDIGO_COLOR,
264
	            'orange'    => AUI_ORANGE_COLOR,
265
	            'black'     => AUI_BLACK_COLOR,
266
            );
267
        }
268
269
		/**
270
		 * Initiate the settings and add the required action hooks.
271
		 */
272
		public function init() {
273
274
			// Maybe fix settings
275
			if ( ! empty( $_REQUEST['aui-fix-admin'] ) && !empty($_REQUEST['nonce']) && wp_verify_nonce( $_REQUEST['nonce'], "aui-fix-admin" ) ) {
276
				$db_settings = get_option( 'ayecode-ui-settings' );
277
				if ( ! empty( $db_settings ) ) {
278
					$db_settings['css_backend'] = 'compatibility';
279
					$db_settings['js_backend'] = 'core-popper';
280
					update_option( 'ayecode-ui-settings', $db_settings );
281
					wp_safe_redirect(admin_url("options-general.php?page=ayecode-ui-settings&updated=true"));
282
				}
283
			}
284
285
			$this->constants();
286
			$this->settings = $this->get_settings();
287
			$this->url = $this->get_url();
288
289
			/**
290
			 * Maybe load CSS
291
			 *
292
			 * We load super early in case there is a theme version that might change the colors
293
			 */
294
			if ( $this->settings['css'] ) {
295
				$priority = $this->is_bs3_compat() ? 100 : 1;
296
				add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_style' ), $priority );
297
			}
298
			if ( $this->settings['css_backend'] && $this->load_admin_scripts() ) {
299
				add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_style' ), 1 );
300
			}
301
302
			// maybe load JS
303
			if ( $this->settings['js'] ) {
304
				$priority = $this->is_bs3_compat() ? 100 : 1;
305
				add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ), $priority );
306
			}
307
			if ( $this->settings['js_backend'] && $this->load_admin_scripts() ) {
308
				add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ), 1 );
309
			}
310
311
			// Maybe set the HTML font size
312
			if ( $this->settings['html_font_size'] ) {
313
				add_action( 'wp_footer', array( $this, 'html_font_size' ), 10 );
314
			}
315
316
			// Maybe show backend style error
317
			if( $this->settings['css_backend'] != 'compatibility' || $this->settings['js_backend'] != 'core-popper' ){
318
				add_action( 'admin_notices', array( $this, 'show_admin_style_notice' ) );
319
			}
320
321
		}
322
323
		/**
324
		 * Show admin notice if backend scripts not loaded.
325
		 */
326
		public function show_admin_style_notice(){
327
			$fix_url = admin_url("options-general.php?page=ayecode-ui-settings&aui-fix-admin=true&nonce=".wp_create_nonce('aui-fix-admin'));
328
			$button = '<a href="'.esc_url($fix_url).'" class="button-primary">Fix Now</a>';
329
			$message = __( '<b>Style Issue:</b> AyeCode UI is disable or set wrong.')." " .$button;
330
			echo '<div class="notice notice-error aui-settings-error-notice"><p>'.$message.'</p></div>';
331
		}
332
333
		/**
334
		 * Check if we should load the admin scripts or not.
335
		 *
336
		 * @return bool
337
		 */
338
		public function load_admin_scripts(){
339
			$result = true;
340
341
			// check if specifically disabled
342
			if(!empty($this->settings['disable_admin'])){
343
				$url_parts = explode("\n",$this->settings['disable_admin']);
344
				foreach($url_parts as $part){
345
					if( strpos($_SERVER['REQUEST_URI'], trim($part)) !== false ){
346
						return false; // return early, no point checking further
347
					}
348
				}
349
			}
350
351
			return $result;
352
		}
353
354
		/**
355
		 * Add a html font size to the footer.
356
		 */
357
		public function html_font_size(){
358
			$this->settings = $this->get_settings();
359
			echo "<style>html{font-size:".absint($this->settings['html_font_size'])."px;}</style>";
360
		}
361
362
		/**
363
		 * Check if the current admin screen should load scripts.
364
		 * 
365
		 * @return bool
366
		 */
367
		public function is_aui_screen(){
368
//			echo '###';exit;
369
			$load = false;
370
			// check if we should load or not
371
			if ( is_admin() ) {
372
				// Only enable on set pages
373
				$aui_screens = array(
374
					'page',
375
					'post',
376
					'settings_page_ayecode-ui-settings',
377
					'appearance_page_gutenberg-widgets',
378
					'widgets',
379
					'ayecode-ui-settings',
380
					'site-editor'
381
				);
382
				$screen_ids = apply_filters( 'aui_screen_ids', $aui_screens );
383
384
				$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...
385
386
//				echo '###'.$screen->id;
387
388
				// check if we are on a AUI screen
389
				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...
390
					$load = true;
391
				}
392
393
				//load for widget previews in WP 5.8
394
				if( !empty($_REQUEST['legacy-widget-preview'])){
395
					$load = true;
396
				}
397
			}
398
399
			return apply_filters( 'aui_load_on_admin' , $load );
400
		}
401
402
		/**
403
         * Check if the current theme is a block theme.
404
         *
405
		 * @return bool
406
		 */
407
		public static function is_block_theme() {
408
			if ( function_exists( 'wp_is_block_theme' && wp_is_block_theme() ) ) {
0 ignored issues
show
Bug introduced by
'wp_is_block_theme' && wp_is_block_theme() of type boolean is incompatible with the type string expected by parameter $function of function_exists(). ( Ignorable by Annotation )

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

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

1708
				/** @scrutinizer ignore-call */ 
1709
    $theme_js_settings = self::theme_js_settings();
Loading history...
1709
				if(isset($theme_js_settings[$active_theme])){
1710
					$js_default = $theme_js_settings[$active_theme];
1711
					$js_default_backend = isset($theme_js_settings[$active_theme."_backend"]) ? $theme_js_settings[$active_theme."_backend"] : $js_default;
1712
				}
1713
			}
1714
1715
			$defaults = array(
1716
				'css'       => 'compatibility', // core, compatibility
1717
				'js'        => $js_default, // js to load, core-popper, popper
1718
				'html_font_size'        => '16', // js to load, core-popper, popper
1719
				'css_backend'       => 'compatibility', // core, compatibility
1720
				'js_backend'        => $js_default_backend, // js to load, core-popper, popper
1721
				'disable_admin'     =>  '', // URL snippets to disable loading on admin
1722
			);
1723
1724
			$settings = wp_parse_args( $db_settings, $defaults );
1725
1726
			/**
1727
			 * Filter the Bootstrap settings.
1728
			 *
1729
			 * @todo if we add this filer people might use it and then it defeates the purpose of this class :/
1730
			 */
1731
			return $this->settings = apply_filters( 'ayecode-ui-settings', $settings, $db_settings, $defaults );
1732
		}
1733
1734
1735
		/**
1736
		 * The settings page html output.
1737
		 */
1738
		public function settings_page() {
1739
			if ( ! current_user_can( 'manage_options' ) ) {
1740
				wp_die( __( 'You do not have sufficient permissions to access this page.', 'aui' ) );
1741
			}
1742
			?>
1743
			<div class="wrap">
1744
				<h1><?php echo $this->name; ?></h1>
1745
				<p><?php _e("Here you can adjust settings if you are having compatibility issues.",'aui');?></p>
1746
				<form method="post" action="options.php">
1747
					<?php
1748
					settings_fields( 'ayecode-ui-settings' );
1749
					do_settings_sections( 'ayecode-ui-settings' );
1750
					?>
1751
1752
					<h2><?php _e( 'Frontend', 'aui' ); ?></h2>
1753
					<table class="form-table wpbs-table-settings">
1754
						<tr valign="top">
1755
							<th scope="row"><label
1756
									for="wpbs-css"><?php _e( 'Load CSS', 'aui' ); ?></label></th>
1757
							<td>
1758
								<select name="ayecode-ui-settings[css]" id="wpbs-css">
1759
									<option	value="compatibility" <?php selected( $this->settings['css'], 'compatibility' ); ?>><?php _e( 'Compatibility Mode (default)', 'aui' ); ?></option>
1760
									<option value="core" <?php selected( $this->settings['css'], 'core' ); ?>><?php _e( 'Full Mode', 'aui' ); ?></option>
1761
									<option	value="" <?php selected( $this->settings['css'], '' ); ?>><?php _e( 'Disabled', 'aui' ); ?></option>
1762
								</select>
1763
							</td>
1764
						</tr>
1765
1766
						<tr valign="top">
1767
							<th scope="row"><label
1768
									for="wpbs-js"><?php _e( 'Load JS', 'aui' ); ?></label></th>
1769
							<td>
1770
								<select name="ayecode-ui-settings[js]" id="wpbs-js">
1771
									<option	value="core-popper" <?php selected( $this->settings['js'], 'core-popper' ); ?>><?php _e( 'Core + Popper (default)', 'aui' ); ?></option>
1772
									<option value="popper" <?php selected( $this->settings['js'], 'popper' ); ?>><?php _e( 'Popper', 'aui' ); ?></option>
1773
									<option value="required" <?php selected( $this->settings['js'], 'required' ); ?>><?php _e( 'Required functions only', 'aui' ); ?></option>
1774
									<option	value="" <?php selected( $this->settings['js'], '' ); ?>><?php _e( 'Disabled (not recommended)', 'aui' ); ?></option>
1775
								</select>
1776
							</td>
1777
						</tr>
1778
1779
						<tr valign="top">
1780
							<th scope="row"><label
1781
									for="wpbs-font_size"><?php _e( 'HTML Font Size (px)', 'aui' ); ?></label></th>
1782
							<td>
1783
								<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" />
1784
								<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>
1785
							</td>
1786
						</tr>
1787
1788
					</table>
1789
1790
					<h2><?php _e( 'Backend', 'aui' ); ?> (wp-admin)</h2>
1791
					<table class="form-table wpbs-table-settings">
1792
						<tr valign="top">
1793
							<th scope="row"><label
1794
									for="wpbs-css-admin"><?php _e( 'Load CSS', 'aui' ); ?></label></th>
1795
							<td>
1796
								<select name="ayecode-ui-settings[css_backend]" id="wpbs-css-admin">
1797
									<option	value="compatibility" <?php selected( $this->settings['css_backend'], 'compatibility' ); ?>><?php _e( 'Compatibility Mode (default)', 'aui' ); ?></option>
1798
									<option value="core" <?php selected( $this->settings['css_backend'], 'core' ); ?>><?php _e( 'Full Mode (will cause style issues)', 'aui' ); ?></option>
1799
									<option	value="" <?php selected( $this->settings['css_backend'], '' ); ?>><?php _e( 'Disabled', 'aui' ); ?></option>
1800
								</select>
1801
							</td>
1802
						</tr>
1803
1804
						<tr valign="top">
1805
							<th scope="row"><label
1806
									for="wpbs-js-admin"><?php _e( 'Load JS', 'aui' ); ?></label></th>
1807
							<td>
1808
								<select name="ayecode-ui-settings[js_backend]" id="wpbs-js-admin">
1809
									<option	value="core-popper" <?php selected( $this->settings['js_backend'], 'core-popper' ); ?>><?php _e( 'Core + Popper (default)', 'aui' ); ?></option>
1810
									<option value="popper" <?php selected( $this->settings['js_backend'], 'popper' ); ?>><?php _e( 'Popper', 'aui' ); ?></option>
1811
									<option value="required" <?php selected( $this->settings['js_backend'], 'required' ); ?>><?php _e( 'Required functions only', 'aui' ); ?></option>
1812
									<option	value="" <?php selected( $this->settings['js_backend'], '' ); ?>><?php _e( 'Disabled (not recommended)', 'aui' ); ?></option>
1813
								</select>
1814
							</td>
1815
						</tr>
1816
1817
						<tr valign="top">
1818
							<th scope="row"><label
1819
									for="wpbs-disable-admin"><?php _e( 'Disable load on URL', 'aui' ); ?></label></th>
1820
							<td>
1821
								<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>
1822
								<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>
1823
1824
							</td>
1825
						</tr>
1826
1827
					</table>
1828
1829
					<?php
1830
					submit_button();
1831
					?>
1832
				</form>
1833
1834
				<div id="wpbs-version"><?php echo $this->version; ?></div>
1835
			</div>
1836
1837
			<?php
1838
		}
1839
1840
		public function customizer_settings($wp_customize){
1841
			$wp_customize->add_section('aui_settings', array(
1842
				'title'    => __('AyeCode UI','aui'),
1843
				'priority' => 120,
1844
			));
1845
1846
			//  =============================
1847
			//  = Color Picker              =
1848
			//  =============================
1849
			$wp_customize->add_setting('aui_options[color_primary]', array(
1850
				'default'           => AUI_PRIMARY_COLOR,
1851
				'sanitize_callback' => 'sanitize_hex_color',
1852
				'capability'        => 'edit_theme_options',
1853
				'type'              => 'option',
1854
				'transport'         => 'refresh',
1855
			));
1856
			$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'color_primary', array(
1857
				'label'    => __('Primary Color','aui'),
1858
				'section'  => 'aui_settings',
1859
				'settings' => 'aui_options[color_primary]',
1860
			)));
1861
1862
			$wp_customize->add_setting('aui_options[color_secondary]', array(
1863
				'default'           => '#6c757d',
1864
				'sanitize_callback' => 'sanitize_hex_color',
1865
				'capability'        => 'edit_theme_options',
1866
				'type'              => 'option',
1867
				'transport'         => 'refresh',
1868
			));
1869
			$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'color_secondary', array(
1870
				'label'    => __('Secondary Color','aui'),
1871
				'section'  => 'aui_settings',
1872
				'settings' => 'aui_options[color_secondary]',
1873
			)));
1874
		}
1875
1876
		/**
1877
		 * CSS to help with conflict issues with other plugins and themes using bootstrap v3.
1878
		 *
1879
		 * @return mixed
1880
		 */
1881
		public static function bs3_compat_css() {
1882
			ob_start();
1883
			?>
1884
			<style>
1885
			/* Bootstrap 3 compatibility */
1886
			body.modal-open .modal-backdrop.show:not(.in) {opacity:0.5;}
1887
			body.modal-open .modal.show:not(.in)  {opacity:1;z-index: 99999}
1888
			body.modal-open .modal.show:not(.in) .modal-content  {box-shadow: none;}
1889
			body.modal-open .modal.show:not(.in)  .modal-dialog {transform: initial;}
1890
1891
			body.modal-open .modal.bsui .modal-dialog{left: auto;}
1892
1893
			.collapse.show:not(.in){display: inherit;}
1894
			.fade.show{opacity: 1;}
1895
1896
			<?php if( defined( 'SVQ_THEME_VERSION' ) ){ ?>
1897
			/* KLEO theme specific */
1898
			.kleo-main-header .navbar-collapse.collapse.show:not(.in){display: block !important;}
1899
			<?php } ?>
1900
1901
			<?php if( defined( 'FUSION_BUILDER_VERSION' ) ){ ?>
1902
			/* With Avada builder */
1903
			body.modal-open .modal.in  {opacity:1;z-index: 99999}
1904
			body.modal-open .modal.bsui.in .modal-content  {box-shadow: none;}
1905
			.bsui .collapse.in{display: inherit;}
1906
			.bsui .collapse.in.row.show{display: flex;}
1907
			.bsui .collapse.in.row:not(.show){display: none;}
1908
1909
			<?php } ?>
1910
			</style>
1911
			<?php
1912
			return str_replace( array(
1913
				'<style>',
1914
				'</style>'
1915
			), '', self::minify_css( ob_get_clean() ) );
1916
		}
1917
1918
1919
		public static function custom_css($compatibility = true) {
1920
			$colors = array();
1921
			if ( defined( 'BLOCKSTRAP_VERSION' ) ) {
1922
1923
				$setting = wp_get_global_settings();
1924
				if(!empty($setting['color']['palette']['theme'])){
1925
					foreach($setting['color']['palette']['theme'] as $color){
1926
						$colors[$color['slug']] = esc_attr($color['color']);
1927
					}
1928
				}
1929
1930
				if(!empty($setting['color']['palette']['custom'])){
1931
					foreach($setting['color']['palette']['custom'] as $color){
1932
						$colors[$color['slug']] = esc_attr($color['color']);
1933
					}
1934
				}
1935
			}else{
1936
				$settings = get_option('aui_options');
1937
				$colors = array(
1938
					'primary'   => ! empty( $settings['color_primary'] ) ? $settings['color_primary'] : AUI_PRIMARY_COLOR,
1939
					'secondary' => ! empty( $settings['color_secondary'] ) ? $settings['color_secondary'] : AUI_SECONDARY_COLOR
1940
				);
1941
			}
1942
1943
			ob_start();
1944
1945
			?>
1946
			<style>
1947
				<?php
1948
1949
					// BS v3 compat
1950
					if( self::is_bs3_compat() ){
1951
					    echo self::bs3_compat_css();
1952
					}
1953
1954
                    if(!empty($colors)){
1955
                        $d_colors = self::get_colors(true);
1956
                        //print_r($d_colors );exit;
1957
//                        print_r($colors );exit;
1958
                        $is_fse = !empty($_REQUEST['postType']) && $_REQUEST['postType']=='wp_template';
1959
                        foreach($colors as $key => $color ){
1960
                            if((empty( $d_colors[$key]) ||  $d_colors[$key] != $color) || $is_fse ) {
1961
                                $var = $is_fse ? "var(--wp--preset--color--$key)" : $color;
1962
                                $compat = $is_fse ? '.editor-styles-wrapper' : $compatibility;
1963
                                echo self::css_overwrite($key,$var,$compat);
1964
                            }
1965
                        }
1966
                       // exit;
1967
                    }
1968
1969
					// Set admin bar z-index lower when modal is open.
1970
					echo ' body.modal-open #wpadminbar{z-index:999}.embed-responsive-16by9 .fluid-width-video-wrapper{padding:0 !important;position:initial}';
1971
1972
					if(is_admin()){
1973
						echo ' body.modal-open #adminmenuwrap{z-index:999} body.modal-open #wpadminbar{z-index:1025}';
1974
					}
1975
                ?>
1976
			</style>
1977
			<?php
1978
1979
1980
			/*
1981
			 * We only add the <script> tags for code highlighting, so we strip them from the output.
1982
			 */
1983
			return str_replace( array(
1984
				'<style>',
1985
				'</style>'
1986
			), '', self::minify_css( ob_get_clean() ) );
1987
		}
1988
1989
1990
1991
		/**
1992
		 * Check if we should add booststrap 3 compatibility changes.
1993
		 *
1994
		 * @return bool
1995
		 */
1996
		public static function is_bs3_compat(){
1997
			return defined('AYECODE_UI_BS3_COMPAT') || defined('SVQ_THEME_VERSION') || defined('FUSION_BUILDER_VERSION');
1998
		}
1999
2000
		/**
2001
         * Build the CSS to overwrite a bootstrap color variable.
2002
         *
2003
		 * @param $type
2004
		 * @param $color_code
2005
		 * @param $compatibility
2006
		 *
2007
		 * @return string
2008
		 */
2009
		public static function css_overwrite($type,$color_code,$compatibility){
2010
2011
            $is_var = false;
2012
			if(!$color_code){return '';}
2013
			if(!sanitize_hex_color($color_code)){
2014
				$color_code = esc_attr($color_code);
2015
				$is_var = true;
2016
//                echo '###1'.$color_code;//exit;
2017
			}
2018
			if(!$color_code){return '';}
2019
2020
            if($compatibility===true || $compatibility===1){
2021
	            $compatibility = '.bsui';
2022
            }elseif(!$compatibility){
2023
	            $compatibility = '';
2024
            }else{
2025
	            $compatibility = esc_attr($compatibility);
2026
            }
2027
2028
//            echo '####'.$color_code;exit;
2029
2030
			$type = sanitize_html_class($type);
2031
2032
			/**
2033
			 * c = color, b = background color, o = border-color, f = fill
2034
			 */
2035
			$selectors = array(
2036
				".btn-{$type}"                                              => array( 'b', 'o' ),
2037
				".btn-{$type}.disabled"                                     => array( 'b', 'o' ),
2038
				".btn-{$type}:disabled"                                     => array( 'b', 'o' ),
2039
				".btn-outline-{$type}"                                      => array( 'c', 'o' ),
2040
				".btn-outline-{$type}:hover"                                => array( 'b', 'o' ),
2041
				".btn-outline-{$type}:not(:disabled):not(.disabled).active" => array( 'b', 'o' ),
2042
				".btn-outline-{$type}:not(:disabled):not(.disabled):active" => array( 'b', 'o' ),
2043
				".show>.btn-outline-{$type}.dropdown-toggle"                => array( 'b', 'o' ),
2044
				".badge-{$type}"                                            => array( 'b' ),
2045
				".alert-{$type}"                                            => array( 'b', 'o' ),
2046
				".bg-{$type}"                                               => array( 'b', 'f' ),
2047
				".btn-link.btn-{$type}"                                     => array( 'c' ),
2048
			);
2049
2050
			if ( $type == 'primary' ) {
2051
				$selectors = $selectors + array(
2052
						'a'                                                                                                    => array( 'c' ),
2053
						'.btn-link'                                                                                            => array( 'c' ),
2054
						'.dropdown-item.active'                                                                                => array( 'b' ),
2055
						'.custom-control-input:checked~.custom-control-label::before'                                          => array(
2056
							'b',
2057
							'o'
2058
						),
2059
						'.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::before'                   => array(
2060
							'b',
2061
							'o'
2062
						),
2063
						'.nav-pills .nav-link.active'                                                                          => array( 'b' ),
2064
						'.nav-pills .show>.nav-link'                                                                           => array( 'b' ),
2065
						'.page-link'                                                                                           => array( 'c' ),
2066
						'.page-item.active .page-link'                                                                         => array(
2067
							'b',
2068
							'o'
2069
						),
2070
						'.progress-bar'                                                                                        => array( 'b' ),
2071
						'.list-group-item.active'                                                                              => array(
2072
							'b',
2073
							'o'
2074
						),
2075
						'.select2-container .select2-results__option--highlighted.select2-results__option[aria-selected=true]' => array( 'b' ),
2076
//				    '.custom-range::-webkit-slider-thumb' => array('b'), // these break the inline rules...
2077
//				    '.custom-range::-moz-range-thumb' => array('b'),
2078
//				    '.custom-range::-ms-thumb' => array('b'),
2079
					);
2080
			}
2081
2082
			$important_selectors = array(
2083
				".bg-{$type}" => array('b','f'),
2084
				".border-{$type}" => array('o'),
2085
				".text-{$type}" => array('c'),
2086
			);
2087
2088
			$color = array();
2089
			$color_i = array();
2090
			$background = array();
2091
			$background_i = array();
2092
			$border = array();
2093
			$border_i = array();
2094
			$fill = array();
2095
			$fill_i = array();
2096
2097
			$output = '';
2098
2099
			// build rules into each type
2100
			foreach($selectors as $selector => $types){
2101
				$selector = $compatibility ? $compatibility . " ".$selector : $selector;
2102
				$types = array_combine($types,$types);
2103
				if(isset($types['c'])){$color[] = $selector;}
2104
				if(isset($types['b'])){$background[] = $selector;}
2105
				if(isset($types['o'])){$border[] = $selector;}
2106
				if(isset($types['f'])){$fill[] = $selector;}
2107
			}
2108
2109
			// build rules into each type
2110
			foreach($important_selectors as $selector => $types){
2111
				$selector = $compatibility ? $compatibility . " ".$selector : $selector;
2112
				$types = array_combine($types,$types);
2113
				if(isset($types['c'])){$color_i[] = $selector;}
2114
				if(isset($types['b'])){$background_i[] = $selector;}
2115
				if(isset($types['o'])){$border_i[] = $selector;}
2116
				if(isset($types['f'])){$fill_i[] = $selector;}
2117
			}
2118
2119
			// add any color rules
2120
			if(!empty($color)){
2121
				$output .= implode(",",$color) . "{color: $color_code;} ";
2122
			}
2123
			if(!empty($color_i)){
2124
				$output .= implode(",",$color_i) . "{color: $color_code !important;} ";
2125
			}
2126
2127
			// add any background color rules
2128
			if(!empty($background)){
2129
				$output .= implode(",",$background) . "{background-color: $color_code;} ";
2130
			}
2131
			if(!empty($background_i)){
2132
				$output .= implode(",",$background_i) . "{background-color: $color_code !important;} ";
2133
			}
2134
2135
			// add any border color rules
2136
			if(!empty($border)){
2137
				$output .= implode(",",$border) . "{border-color: $color_code;} ";
2138
			}
2139
			if(!empty($border_i)){
2140
				$output .= implode(",",$border_i) . "{border-color: $color_code !important;} ";
2141
			}
2142
2143
			// add any fill color rules
2144
			if(!empty($fill)){
2145
				$output .= implode(",",$fill) . "{fill: $color_code;} ";
2146
			}
2147
			if(!empty($fill_i)){
2148
				$output .= implode(",",$fill_i) . "{fill: $color_code !important;} ";
2149
			}
2150
2151
2152
			$prefix = $compatibility ? $compatibility . " " : "";
2153
2154
            $transition = $is_var ? 'transition: color 0.15s ease-in-out,background-color 0.15s ease-in-out,border-color 0.15s ease-in-out,box-shadow 0.15s ease-in-out,filter 0.15s ease-in-out;' : '';
2155
			// darken
2156
			$darker_075 = $is_var ? $color_code.';filter:brightness(0.925)' : 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

2156
			$darker_075 = $is_var ? $color_code.';filter:brightness(0.925)' : self::css_hex_lighten_darken($color_code,/** @scrutinizer ignore-type */ "-0.075");
Loading history...
2157
			$darker_10 = $is_var ? $color_code.';filter:brightness(0.9)' : self::css_hex_lighten_darken($color_code,"-0.10");
2158
			$darker_125 = $is_var ? $color_code.';filter:brightness(0.875)' : self::css_hex_lighten_darken($color_code,"-0.125");
2159
2160
			// lighten
2161
			$lighten_25 = $is_var ? $color_code.';filter:brightness(1.25)' :self::css_hex_lighten_darken($color_code,"0.25");
2162
2163
			// opacity see https://css-tricks.com/8-digit-hex-codes/
2164
			$op_25 = $color_code."40"; // 25% opacity
2165
2166
2167
			// button states
2168
			$output .= $is_var ? $prefix ." .btn-{$type}{{$transition }} " : '';
2169
			$output .= $prefix ." .btn-{$type}:hover, $prefix .btn-{$type}:focus, $prefix .btn-{$type}.focus{background-color: ".$darker_075.";    border-color: ".$darker_10.";} ";
2170
//			$output .= $prefix ." .btn-{$type}:hover, $prefix .btn-{$type}:focus, $prefix .btn-{$type}.focus{background-color: #000;    border-color: #000;} ";
2171
			$output .= $prefix ." .btn-outline-{$type}:not(:disabled):not(.disabled):active:focus, $prefix .btn-outline-{$type}:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-outline-{$type}.dropdown-toggle:focus{box-shadow: 0 0 0 0.2rem $op_25;} ";
2172
			$output .= $prefix ." .btn-{$type}:not(:disabled):not(.disabled):active, $prefix .btn-{$type}:not(:disabled):not(.disabled).active, .show>$prefix .btn-{$type}.dropdown-toggle{background-color: ".$darker_10.";    border-color: ".$darker_125.";} ";
2173
			$output .= $prefix ." .btn-{$type}:not(:disabled):not(.disabled):active:focus, $prefix .btn-{$type}:not(:disabled):not(.disabled).active:focus, .show>$prefix .btn-{$type}.dropdown-toggle:focus {box-shadow: 0 0 0 0.2rem $op_25;} ";
2174
2175
			if ( $type == 'primary' ) {
2176
				// dropdown's
2177
				$output .= $prefix . " .dropdown-item.active, $prefix .dropdown-item:active{background-color: $color_code;} ";
2178
2179
				// input states
2180
				$output .= $prefix . " .form-control:focus{border-color: " . $lighten_25 . ";box-shadow: 0 0 0 0.2rem $op_25;} ";
2181
2182
				// page link
2183
				$output .= $prefix . " .page-link:focus{box-shadow: 0 0 0 0.2rem $op_25;} ";
2184
			}
2185
2186
			return $output;
2187
		}
2188
2189
		/**
2190
         *
2191
         * @deprecated 0.1.76 Use css_overwrite()
2192
         *
2193
		 * @param $color_code
2194
		 * @param $compatibility
2195
		 * @param $use_variable
2196
		 *
2197
		 * @return string
2198
		 */
2199
		public static function css_primary($color_code,$compatibility, $use_variable = false){
2200
2201
            if(!$use_variable){
2202
				$color_code = sanitize_hex_color($color_code);
2203
				if(!$color_code){return '';}
2204
			}
2205
2206
			/**
2207
			 * c = color, b = background color, o = border-color, f = fill
2208
			 */
2209
			$selectors = array(
2210
				'a' => array('c'),
2211
				'.btn-primary' => array('b','o'),
2212
				'.btn-primary.disabled' => array('b','o'),
2213
				'.btn-primary:disabled' => array('b','o'),
2214
				'.btn-outline-primary' => array('c','o'),
2215
				'.btn-outline-primary:hover' => array('b','o'),
2216
				'.btn-outline-primary:not(:disabled):not(.disabled).active' => array('b','o'),
2217
				'.btn-outline-primary:not(:disabled):not(.disabled):active' => array('b','o'),
2218
				'.show>.btn-outline-primary.dropdown-toggle' => array('b','o'),
2219
				'.btn-link' => array('c'),
2220
				'.dropdown-item.active' => array('b'),
2221
				'.custom-control-input:checked~.custom-control-label::before' => array('b','o'),
2222
				'.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::before' => array('b','o'),
2223
//				'.custom-range::-webkit-slider-thumb' => array('b'), // these break the inline rules...
2224
//				'.custom-range::-moz-range-thumb' => array('b'),
2225
//				'.custom-range::-ms-thumb' => array('b'),
2226
				'.nav-pills .nav-link.active' => array('b'),
2227
				'.nav-pills .show>.nav-link' => array('b'),
2228
				'.page-link' => array('c'),
2229
				'.page-item.active .page-link' => array('b','o'),
2230
				'.badge-primary' => array('b'),
2231
				'.alert-primary' => array('b','o'),
2232
				'.progress-bar' => array('b'),
2233
				'.list-group-item.active' => array('b','o'),
2234
				'.bg-primary' => array('b','f'),
2235
				'.btn-link.btn-primary' => array('c'),
2236
				'.select2-container .select2-results__option--highlighted.select2-results__option[aria-selected=true]' => array('b'),
2237
			);
2238
2239
			$important_selectors = array(
2240
				'.bg-primary' => array('b','f'),
2241
				'.border-primary' => array('o'),
2242
				'.text-primary' => array('c'),
2243
			);
2244
2245
			$color = array();
2246
			$color_i = array();
2247
			$background = array();
2248
			$background_i = array();
2249
			$border = array();
2250
			$border_i = array();
2251
			$fill = array();
2252
			$fill_i = array();
2253
2254
			$output = '';
2255
2256
			// build rules into each type
2257
			foreach($selectors as $selector => $types){
2258
				$selector = $compatibility ? ".bsui ".$selector : $selector;
2259
				$types = array_combine($types,$types);
2260
				if(isset($types['c'])){$color[] = $selector;}
2261
				if(isset($types['b'])){$background[] = $selector;}
2262
				if(isset($types['o'])){$border[] = $selector;}
2263
				if(isset($types['f'])){$fill[] = $selector;}
2264
			}
2265
2266
			// build rules into each type
2267
			foreach($important_selectors as $selector => $types){
2268
				$selector = $compatibility ? ".bsui ".$selector : $selector;
2269
				$types = array_combine($types,$types);
2270
				if(isset($types['c'])){$color_i[] = $selector;}
2271
				if(isset($types['b'])){$background_i[] = $selector;}
2272
				if(isset($types['o'])){$border_i[] = $selector;}
2273
				if(isset($types['f'])){$fill_i[] = $selector;}
2274
			}
2275
2276
			// add any color rules
2277
			if(!empty($color)){
2278
				$output .= implode(",",$color) . "{color: $color_code;} ";
2279
			}
2280
			if(!empty($color_i)){
2281
				$output .= implode(",",$color_i) . "{color: $color_code !important;} ";
2282
			}
2283
2284
			// add any background color rules
2285
			if(!empty($background)){
2286
				$output .= implode(",",$background) . "{background-color: $color_code;} ";
2287
			}
2288
			if(!empty($background_i)){
2289
				$output .= implode(",",$background_i) . "{background-color: $color_code !important;} ";
2290
			}
2291
2292
			// add any border color rules
2293
			if(!empty($border)){
2294
				$output .= implode(",",$border) . "{border-color: $color_code;} ";
2295
			}
2296
			if(!empty($border_i)){
2297
				$output .= implode(",",$border_i) . "{border-color: $color_code !important;} ";
2298
			}
2299
2300
			// add any fill color rules
2301
			if(!empty($fill)){
2302
				$output .= implode(",",$fill) . "{fill: $color_code;} ";
2303
			}
2304
			if(!empty($fill_i)){
2305
				$output .= implode(",",$fill_i) . "{fill: $color_code !important;} ";
2306
			}
2307
2308
2309
			$prefix = $compatibility ? ".bsui " : "";
2310
2311
			// darken
2312
			$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

2312
			$darker_075 = self::css_hex_lighten_darken($color_code,/** @scrutinizer ignore-type */ "-0.075");
Loading history...
2313
			$darker_10 = self::css_hex_lighten_darken($color_code,"-0.10");
2314
			$darker_125 = self::css_hex_lighten_darken($color_code,"-0.125");
2315
2316
			// lighten
2317
			$lighten_25 = self::css_hex_lighten_darken($color_code,"0.25");
2318
2319
			// opacity see https://css-tricks.com/8-digit-hex-codes/
2320
			$op_25 = $color_code."40"; // 25% opacity
2321
2322
2323
			// button states
2324
			$output .= $prefix ." .btn-primary:hover, $prefix .btn-primary:focus, $prefix .btn-primary.focus{background-color: ".$darker_075.";    border-color: ".$darker_10.";} ";
2325
			$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;} ";
2326
			$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.";} ";
2327
			$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;} ";
2328
2329
2330
			// dropdown's
2331
			$output .= $prefix ." .dropdown-item.active, $prefix .dropdown-item:active{background-color: $color_code;} ";
2332
2333
2334
			// input states
2335
			$output .= $prefix ." .form-control:focus{border-color: ".$lighten_25.";box-shadow: 0 0 0 0.2rem $op_25;} ";
2336
2337
			// page link
2338
			$output .= $prefix ." .page-link:focus{box-shadow: 0 0 0 0.2rem $op_25;} ";
2339
2340
			return $output;
2341
		}
2342
2343
		/**
2344
         *
2345
         * @deprecated 0.1.76 Use css_overwrite()
2346
         *
2347
		 * @param $color_code
2348
		 * @param $compatibility
2349
		 *
2350
		 * @return string
2351
		 */
2352
		public static function css_secondary($color_code,$compatibility){;
2353
			$color_code = sanitize_hex_color($color_code);
2354
			if(!$color_code){return '';}
2355
			/**
2356
			 * c = color, b = background color, o = border-color, f = fill
2357
			 */
2358
			$selectors = array(
2359
				'.btn-secondary' => array('b','o'),
2360
				'.btn-secondary.disabled' => array('b','o'),
2361
				'.btn-secondary:disabled' => array('b','o'),
2362
				'.btn-outline-secondary' => array('c','o'),
2363
				'.btn-outline-secondary:hover' => array('b','o'),
2364
				'.btn-outline-secondary.disabled' => array('c'),
2365
				'.btn-outline-secondary:disabled' => array('c'),
2366
				'.btn-outline-secondary:not(:disabled):not(.disabled):active' => array('b','o'),
2367
				'.btn-outline-secondary:not(:disabled):not(.disabled).active' => array('b','o'),
2368
				'.btn-outline-secondary.dropdown-toggle' => array('b','o'),
2369
				'.badge-secondary' => array('b'),
2370
				'.alert-secondary' => array('b','o'),
2371
				'.btn-link.btn-secondary' => array('c'),
2372
			);
2373
2374
			$important_selectors = array(
2375
				'.bg-secondary' => array('b','f'),
2376
				'.border-secondary' => array('o'),
2377
				'.text-secondary' => array('c'),
2378
			);
2379
2380
			$color = array();
2381
			$color_i = array();
2382
			$background = array();
2383
			$background_i = array();
2384
			$border = array();
2385
			$border_i = array();
2386
			$fill = array();
2387
			$fill_i = array();
2388
2389
			$output = '';
2390
2391
			// build rules into each type
2392
			foreach($selectors as $selector => $types){
2393
				$selector = $compatibility ? ".bsui ".$selector : $selector;
2394
				$types = array_combine($types,$types);
2395
				if(isset($types['c'])){$color[] = $selector;}
2396
				if(isset($types['b'])){$background[] = $selector;}
2397
				if(isset($types['o'])){$border[] = $selector;}
2398
				if(isset($types['f'])){$fill[] = $selector;}
2399
			}
2400
2401
			// build rules into each type
2402
			foreach($important_selectors as $selector => $types){
2403
				$selector = $compatibility ? ".bsui ".$selector : $selector;
2404
				$types = array_combine($types,$types);
2405
				if(isset($types['c'])){$color_i[] = $selector;}
2406
				if(isset($types['b'])){$background_i[] = $selector;}
2407
				if(isset($types['o'])){$border_i[] = $selector;}
2408
				if(isset($types['f'])){$fill_i[] = $selector;}
2409
			}
2410
2411
			// add any color rules
2412
			if(!empty($color)){
2413
				$output .= implode(",",$color) . "{color: $color_code;} ";
2414
			}
2415
			if(!empty($color_i)){
2416
				$output .= implode(",",$color_i) . "{color: $color_code !important;} ";
2417
			}
2418
2419
			// add any background color rules
2420
			if(!empty($background)){
2421
				$output .= implode(",",$background) . "{background-color: $color_code;} ";
2422
			}
2423
			if(!empty($background_i)){
2424
				$output .= implode(",",$background_i) . "{background-color: $color_code !important;} ";
2425
			}
2426
2427
			// add any border color rules
2428
			if(!empty($border)){
2429
				$output .= implode(",",$border) . "{border-color: $color_code;} ";
2430
			}
2431
			if(!empty($border_i)){
2432
				$output .= implode(",",$border_i) . "{border-color: $color_code !important;} ";
2433
			}
2434
2435
			// add any fill color rules
2436
			if(!empty($fill)){
2437
				$output .= implode(",",$fill) . "{fill: $color_code;} ";
2438
			}
2439
			if(!empty($fill_i)){
2440
				$output .= implode(",",$fill_i) . "{fill: $color_code !important;} ";
2441
			}
2442
2443
2444
			$prefix = $compatibility ? ".bsui " : "";
2445
2446
			// darken
2447
			$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

2447
			$darker_075 = self::css_hex_lighten_darken($color_code,/** @scrutinizer ignore-type */ "-0.075");
Loading history...
2448
			$darker_10 = self::css_hex_lighten_darken($color_code,"-0.10");
2449
			$darker_125 = self::css_hex_lighten_darken($color_code,"-0.125");
2450
2451
			// lighten
2452
			$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...
2453
2454
			// opacity see https://css-tricks.com/8-digit-hex-codes/
2455
			$op_25 = $color_code."40"; // 25% opacity
2456
2457
2458
			// button states
2459
			$output .= $prefix ." .btn-secondary:hover{background-color: ".$darker_075.";    border-color: ".$darker_10.";} ";
2460
			$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;} ";
2461
			$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.";} ";
2462
			$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;} ";
2463
2464
2465
			return $output;
2466
		}
2467
2468
		/**
2469
		 * Increases or decreases the brightness of a color by a percentage of the current brightness.
2470
		 *
2471
		 * @param   string  $hexCode        Supported formats: `#FFF`, `#FFFFFF`, `FFF`, `FFFFFF`
2472
		 * @param   float   $adjustPercent  A number between -1 and 1. E.g. 0.3 = 30% lighter; -0.4 = 40% darker.
2473
		 *
2474
		 * @return  string
2475
		 */
2476
		public static function css_hex_lighten_darken($hexCode, $adjustPercent) {
2477
			$hexCode = ltrim($hexCode, '#');
2478
2479
			if (strlen($hexCode) == 3) {
2480
				$hexCode = $hexCode[0] . $hexCode[0] . $hexCode[1] . $hexCode[1] . $hexCode[2] . $hexCode[2];
2481
			}
2482
2483
			$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

2483
			$hexCode = array_map('hexdec', /** @scrutinizer ignore-type */ str_split($hexCode, 2));
Loading history...
2484
2485
			foreach ($hexCode as & $color) {
2486
				$adjustableLimit = $adjustPercent < 0 ? $color : 255 - $color;
2487
				$adjustAmount = ceil($adjustableLimit * $adjustPercent);
2488
2489
				$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

2489
				$color = str_pad(dechex(/** @scrutinizer ignore-type */ $color + $adjustAmount), 2, '0', STR_PAD_LEFT);
Loading history...
2490
			}
2491
2492
			return '#' . implode($hexCode);
2493
		}
2494
2495
		/**
2496
		 * Check if we should display examples.
2497
		 */
2498
		public function maybe_show_examples(){
2499
			if(current_user_can('manage_options') && isset($_REQUEST['preview-aui'])){
2500
				echo "<head>";
2501
				wp_head();
2502
				echo "</head>";
2503
				echo "<body>";
2504
				echo $this->get_examples();
2505
				echo "</body>";
2506
				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...
2507
			}
2508
		}
2509
2510
		/**
2511
		 * Get developer examples.
2512
		 *
2513
		 * @return string
2514
		 */
2515
		public function get_examples(){
2516
			$output = '';
2517
2518
2519
			// open form
2520
			$output .= "<form class='p-5 m-5 border rounded'>";
2521
2522
			// input example
2523
			$output .= aui()->input(array(
2524
				'type'  =>  'text',
2525
				'id'    =>  'text-example',
2526
				'name'    =>  'text-example',
2527
				'placeholder'   => 'text placeholder',
2528
				'title'   => 'Text input example',
2529
				'value' =>  '',
2530
				'required'  => false,
2531
				'help_text' => 'help text',
2532
				'label' => 'Text input example label'
2533
			));
2534
2535
			// input example
2536
			$output .= aui()->input(array(
2537
				'type'  =>  'url',
2538
				'id'    =>  'text-example2',
2539
				'name'    =>  'text-example',
2540
				'placeholder'   => 'url placeholder',
2541
				'title'   => 'Text input example',
2542
				'value' =>  '',
2543
				'required'  => false,
2544
				'help_text' => 'help text',
2545
				'label' => 'Text input example label'
2546
			));
2547
2548
			// checkbox example
2549
			$output .= aui()->input(array(
2550
				'type'  =>  'checkbox',
2551
				'id'    =>  'checkbox-example',
2552
				'name'    =>  'checkbox-example',
2553
				'placeholder'   => 'checkbox-example',
2554
				'title'   => 'Checkbox example',
2555
				'value' =>  '1',
2556
				'checked'   => true,
2557
				'required'  => false,
2558
				'help_text' => 'help text',
2559
				'label' => 'Checkbox checked'
2560
			));
2561
2562
			// checkbox example
2563
			$output .= aui()->input(array(
2564
				'type'  =>  'checkbox',
2565
				'id'    =>  'checkbox-example2',
2566
				'name'    =>  'checkbox-example2',
2567
				'placeholder'   => 'checkbox-example',
2568
				'title'   => 'Checkbox example',
2569
				'value' =>  '1',
2570
				'checked'   => false,
2571
				'required'  => false,
2572
				'help_text' => 'help text',
2573
				'label' => 'Checkbox un-checked'
2574
			));
2575
2576
			// switch example
2577
			$output .= aui()->input(array(
2578
				'type'  =>  'checkbox',
2579
				'id'    =>  'switch-example',
2580
				'name'    =>  'switch-example',
2581
				'placeholder'   => 'checkbox-example',
2582
				'title'   => 'Switch example',
2583
				'value' =>  '1',
2584
				'checked'   => true,
2585
				'switch'    => true,
2586
				'required'  => false,
2587
				'help_text' => 'help text',
2588
				'label' => 'Switch on'
2589
			));
2590
2591
			// switch example
2592
			$output .= aui()->input(array(
2593
				'type'  =>  'checkbox',
2594
				'id'    =>  'switch-example2',
2595
				'name'    =>  'switch-example2',
2596
				'placeholder'   => 'checkbox-example',
2597
				'title'   => 'Switch example',
2598
				'value' =>  '1',
2599
				'checked'   => false,
2600
				'switch'    => true,
2601
				'required'  => false,
2602
				'help_text' => 'help text',
2603
				'label' => 'Switch off'
2604
			));
2605
2606
			// close form
2607
			$output .= "</form>";
2608
2609
			return $output;
2610
		}
2611
2612
		/**
2613
		 * Calendar params.
2614
		 *
2615
		 * @since 0.1.44
2616
		 *
2617
		 * @return array Calendar params.
2618
		 */
2619
		public static function calendar_params() {
2620
			$params = array(
2621
				'month_long_1' => __( 'January', 'aui' ),
2622
				'month_long_2' => __( 'February', 'aui' ),
2623
				'month_long_3' => __( 'March', 'aui' ),
2624
				'month_long_4' => __( 'April', 'aui' ),
2625
				'month_long_5' => __( 'May', 'aui' ),
2626
				'month_long_6' => __( 'June', 'aui' ),
2627
				'month_long_7' => __( 'July', 'aui' ),
2628
				'month_long_8' => __( 'August', 'aui' ),
2629
				'month_long_9' => __( 'September', 'aui' ),
2630
				'month_long_10' => __( 'October', 'aui' ),
2631
				'month_long_11' => __( 'November', 'aui' ),
2632
				'month_long_12' => __( 'December', 'aui' ),
2633
				'month_s_1' => _x( 'Jan', 'January abbreviation', 'aui' ),
2634
				'month_s_2' => _x( 'Feb', 'February abbreviation', 'aui' ),
2635
				'month_s_3' => _x( 'Mar', 'March abbreviation', 'aui' ),
2636
				'month_s_4' => _x( 'Apr', 'April abbreviation', 'aui' ),
2637
				'month_s_5' => _x( 'May', 'May abbreviation', 'aui' ),
2638
				'month_s_6' => _x( 'Jun', 'June abbreviation', 'aui' ),
2639
				'month_s_7' => _x( 'Jul', 'July abbreviation', 'aui' ),
2640
				'month_s_8' => _x( 'Aug', 'August abbreviation', 'aui' ),
2641
				'month_s_9' => _x( 'Sep', 'September abbreviation', 'aui' ),
2642
				'month_s_10' => _x( 'Oct', 'October abbreviation', 'aui' ),
2643
				'month_s_11' => _x( 'Nov', 'November abbreviation', 'aui' ),
2644
				'month_s_12' => _x( 'Dec', 'December abbreviation', 'aui' ),
2645
				'day_s1_1' => _x( 'S', 'Sunday initial', 'aui' ),
2646
				'day_s1_2' => _x( 'M', 'Monday initial', 'aui' ),
2647
				'day_s1_3' => _x( 'T', 'Tuesday initial', 'aui' ),
2648
				'day_s1_4' => _x( 'W', 'Wednesday initial', 'aui' ),
2649
				'day_s1_5' => _x( 'T', 'Friday initial', 'aui' ),
2650
				'day_s1_6' => _x( 'F', 'Thursday initial', 'aui' ),
2651
				'day_s1_7' => _x( 'S', 'Saturday initial', 'aui' ),
2652
				'day_s2_1' => __( 'Su', 'aui' ),
2653
				'day_s2_2' => __( 'Mo', 'aui' ),
2654
				'day_s2_3' => __( 'Tu', 'aui' ),
2655
				'day_s2_4' => __( 'We', 'aui' ),
2656
				'day_s2_5' => __( 'Th', 'aui' ),
2657
				'day_s2_6' => __( 'Fr', 'aui' ),
2658
				'day_s2_7' => __( 'Sa', 'aui' ),
2659
				'day_s3_1' => __( 'Sun', 'aui' ),
2660
				'day_s3_2' => __( 'Mon', 'aui' ),
2661
				'day_s3_3' => __( 'Tue', 'aui' ),
2662
				'day_s3_4' => __( 'Wed', 'aui' ),
2663
				'day_s3_5' => __( 'Thu', 'aui' ),
2664
				'day_s3_6' => __( 'Fri', 'aui' ),
2665
				'day_s3_7' => __( 'Sat', 'aui' ),
2666
				'day_s5_1' => __( 'Sunday', 'aui' ),
2667
				'day_s5_2' => __( 'Monday', 'aui' ),
2668
				'day_s5_3' => __( 'Tuesday', 'aui' ),
2669
				'day_s5_4' => __( 'Wednesday', 'aui' ),
2670
				'day_s5_5' => __( 'Thursday', 'aui' ),
2671
				'day_s5_6' => __( 'Friday', 'aui' ),
2672
				'day_s5_7' => __( 'Saturday', 'aui' ),
2673
				'am_lower' => __( 'am', 'aui' ),
2674
				'pm_lower' => __( 'pm', 'aui' ),
2675
				'am_upper' => __( 'AM', 'aui' ),
2676
				'pm_upper' => __( 'PM', 'aui' ),
2677
				'firstDayOfWeek' => (int) get_option( 'start_of_week' ),
2678
				'time_24hr' => false,
2679
				'year' => __( 'Year', 'aui' ),
2680
				'hour' => __( 'Hour', 'aui' ),
2681
				'minute' => __( 'Minute', 'aui' ),
2682
				'weekAbbreviation' => __( 'Wk', 'aui' ),
2683
				'rangeSeparator' => __( ' to ', 'aui' ),
2684
				'scrollTitle' => __( 'Scroll to increment', 'aui' ),
2685
				'toggleTitle' => __( 'Click to toggle', 'aui' )
2686
			);
2687
2688
			return apply_filters( 'ayecode_ui_calendar_params', $params );
2689
		}
2690
2691
		/**
2692
		 * Flatpickr calendar localize.
2693
		 *
2694
		 * @since 0.1.44
2695
		 *
2696
		 * @return string Calendar locale.
2697
		 */
2698
		public static function flatpickr_locale() {
2699
			$params = self::calendar_params();
2700
2701
			if ( is_string( $params ) ) {
0 ignored issues
show
introduced by
The condition is_string($params) is always false.
Loading history...
2702
				$params = html_entity_decode( $params, ENT_QUOTES, 'UTF-8' );
2703
			} else {
2704
				foreach ( (array) $params as $key => $value ) {
2705
					if ( ! is_scalar( $value ) ) {
2706
						continue;
2707
					}
2708
2709
					$params[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
2710
				}
2711
			}
2712
2713
			$day_s3 = array();
2714
			$day_s5 = array();
2715
2716
			for ( $i = 1; $i <= 7; $i ++ ) {
2717
				$day_s3[] = addslashes( $params[ 'day_s3_' . $i ] );
2718
				$day_s5[] = addslashes( $params[ 'day_s3_' . $i ] );
2719
			}
2720
2721
			$month_s = array();
2722
			$month_long = array();
2723
2724
			for ( $i = 1; $i <= 12; $i ++ ) {
2725
				$month_s[] = addslashes( $params[ 'month_s_' . $i ] );
2726
				$month_long[] = addslashes( $params[ 'month_long_' . $i ] );
2727
			}
2728
2729
ob_start();
2730
if ( 0 ) { ?><script><?php } ?>
2731
{
2732
	weekdays: {
2733
		shorthand: ['<?php echo implode( "','", $day_s3 ); ?>'],
2734
		longhand: ['<?php echo implode( "','", $day_s5 ); ?>'],
2735
	},
2736
	months: {
2737
		shorthand: ['<?php echo implode( "','", $month_s ); ?>'],
2738
		longhand: ['<?php echo implode( "','", $month_long ); ?>'],
2739
	},
2740
	daysInMonth: [31,28,31,30,31,30,31,31,30,31,30,31],
2741
	firstDayOfWeek: <?php echo (int) $params[ 'firstDayOfWeek' ]; ?>,
2742
	ordinal: function (nth) {
2743
		var s = nth % 100;
2744
		if (s > 3 && s < 21)
2745
			return "th";
2746
		switch (s % 10) {
2747
			case 1:
2748
				return "st";
2749
			case 2:
2750
				return "nd";
2751
			case 3:
2752
				return "rd";
2753
			default:
2754
				return "th";
2755
		}
2756
	},
2757
	rangeSeparator: '<?php echo addslashes( $params[ 'rangeSeparator' ] ); ?>',
2758
	weekAbbreviation: '<?php echo addslashes( $params[ 'weekAbbreviation' ] ); ?>',
2759
	scrollTitle: '<?php echo addslashes( $params[ 'scrollTitle' ] ); ?>',
2760
	toggleTitle: '<?php echo addslashes( $params[ 'toggleTitle' ] ); ?>',
2761
	amPM: ['<?php echo addslashes( $params[ 'am_upper' ] ); ?>','<?php echo addslashes( $params[ 'pm_upper' ] ); ?>'],
2762
	yearAriaLabel: '<?php echo addslashes( $params[ 'year' ] ); ?>',
2763
	hourAriaLabel: '<?php echo addslashes( $params[ 'hour' ] ); ?>',
2764
	minuteAriaLabel: '<?php echo addslashes( $params[ 'minute' ] ); ?>',
2765
	time_24hr: <?php echo ( $params[ 'time_24hr' ] ? 'true' : 'false' ) ; ?>
2766
}
2767
<?php if ( 0 ) { ?></script><?php } ?>
2768
<?php
2769
			$locale = ob_get_clean();
2770
2771
			return apply_filters( 'ayecode_ui_flatpickr_locale', trim( $locale ) );
2772
		}
2773
2774
		/**
2775
		 * Select2 JS params.
2776
		 *
2777
		 * @since 0.1.44
2778
		 *
2779
		 * @return array Select2 JS params.
2780
		 */
2781
		public static function select2_params() {
2782
			$params = array(
2783
				'i18n_select_state_text'    => esc_attr__( 'Select an option&hellip;', 'aui' ),
2784
				'i18n_no_matches'           => _x( 'No matches found', 'enhanced select', 'aui' ),
2785
				'i18n_ajax_error'           => _x( 'Loading failed', 'enhanced select', 'aui' ),
2786
				'i18n_input_too_short_1'    => _x( 'Please enter 1 or more characters', 'enhanced select', 'aui' ),
2787
				'i18n_input_too_short_n'    => _x( 'Please enter %item% or more characters', 'enhanced select', 'aui' ),
2788
				'i18n_input_too_long_1'     => _x( 'Please delete 1 character', 'enhanced select', 'aui' ),
2789
				'i18n_input_too_long_n'     => _x( 'Please delete %item% characters', 'enhanced select', 'aui' ),
2790
				'i18n_selection_too_long_1' => _x( 'You can only select 1 item', 'enhanced select', 'aui' ),
2791
				'i18n_selection_too_long_n' => _x( 'You can only select %item% items', 'enhanced select', 'aui' ),
2792
				'i18n_load_more'            => _x( 'Loading more results&hellip;', 'enhanced select', 'aui' ),
2793
				'i18n_searching'            => _x( 'Searching&hellip;', 'enhanced select', 'aui' )
2794
			);
2795
2796
			return apply_filters( 'ayecode_ui_select2_params', $params );
2797
		}
2798
2799
		/**
2800
		 * Select2 JS localize.
2801
		 *
2802
		 * @since 0.1.44
2803
		 *
2804
		 * @return string Select2 JS locale.
2805
		 */
2806
		public static function select2_locale() {
2807
			$params = self::select2_params();
2808
2809
			foreach ( (array) $params as $key => $value ) {
2810
				if ( ! is_scalar( $value ) ) {
2811
					continue;
2812
				}
2813
2814
				$params[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
2815
			}
2816
2817
			$locale = json_encode( $params );
2818
2819
			return apply_filters( 'ayecode_ui_select2_locale', trim( $locale ) );
2820
		}
2821
2822
		/**
2823
		 * Time ago JS localize.
2824
		 *
2825
		 * @since 0.1.47
2826
		 *
2827
		 * @return string Time ago JS locale.
2828
		 */
2829
		public static function timeago_locale() {
2830
			$params = array(
2831
				'prefix_ago' => '',
2832
				'suffix_ago' => ' ' . _x( 'ago', 'time ago', 'aui' ),
2833
				'prefix_after' => _x( 'after', 'time ago', 'aui' ) . ' ',
2834
				'suffix_after' => '',
2835
				'seconds' => _x( 'less than a minute', 'time ago', 'aui' ),
2836
				'minute' => _x( 'about a minute', 'time ago', 'aui' ),
2837
				'minutes' => _x( '%d minutes', 'time ago', 'aui' ),
2838
				'hour' => _x( 'about an hour', 'time ago', 'aui' ),
2839
				'hours' => _x( 'about %d hours', 'time ago', 'aui' ),
2840
				'day' => _x( 'a day', 'time ago', 'aui' ),
2841
				'days' => _x( '%d days', 'time ago', 'aui' ),
2842
				'month' => _x( 'about a month', 'time ago', 'aui' ),
2843
				'months' => _x( '%d months', 'time ago', 'aui' ),
2844
				'year' => _x( 'about a year', 'time ago', 'aui' ),
2845
				'years' => _x( '%d years', 'time ago', 'aui' ),
2846
			);
2847
2848
			$params = apply_filters( 'ayecode_ui_timeago_params', $params );
2849
2850
			foreach ( (array) $params as $key => $value ) {
2851
				if ( ! is_scalar( $value ) ) {
2852
					continue;
2853
				}
2854
2855
				$params[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
2856
			}
2857
2858
			$locale = json_encode( $params );
2859
2860
			return apply_filters( 'ayecode_ui_timeago_locale', trim( $locale ) );
2861
		}
2862
2863
		/**
2864
		 * JavaScript Minifier
2865
		 *
2866
		 * @param $input
2867
		 *
2868
		 * @return mixed
2869
		 */
2870
		public static function minify_js($input) {
2871
			if(trim($input) === "") return $input;
2872
			return preg_replace(
2873
				array(
2874
					// Remove comment(s)
2875
					'#\s*("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')\s*|\s*\/\*(?!\!|@cc_on)(?>[\s\S]*?\*\/)\s*|\s*(?<![\:\=])\/\/.*(?=[\n\r]|$)|^\s*|\s*$#',
2876
					// Remove white-space(s) outside the string and regex
2877
					'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/)|\/(?!\/)[^\n\r]*?\/(?=[\s.,;]|[gimuy]|$))|\s*([!%&*\(\)\-=+\[\]\{\}|;:,.<>?\/])\s*#s',
2878
					// Remove the last semicolon
2879
					'#;+\}#',
2880
					// Minify object attribute(s) except JSON attribute(s). From `{'foo':'bar'}` to `{foo:'bar'}`
2881
					'#([\{,])([\'])(\d+|[a-z_][a-z0-9_]*)\2(?=\:)#i',
2882
					// --ibid. From `foo['bar']` to `foo.bar`
2883
					'#([a-z0-9_\)\]])\[([\'"])([a-z_][a-z0-9_]*)\2\]#i'
2884
				),
2885
				array(
2886
					'$1',
2887
					'$1$2',
2888
					'}',
2889
					'$1$3',
2890
					'$1.$3'
2891
				),
2892
				$input);
2893
		}
2894
2895
		/**
2896
		 * Minify CSS
2897
		 *
2898
		 * @param $input
2899
		 *
2900
		 * @return mixed
2901
		 */
2902
		public static function minify_css($input) {
2903
			if(trim($input) === "") return $input;
2904
			return preg_replace(
2905
				array(
2906
					// Remove comment(s)
2907
					'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')|\/\*(?!\!)(?>.*?\*\/)|^\s*|\s*$#s',
2908
					// Remove unused white-space(s)
2909
					'#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/))|\s*+;\s*+(})\s*+|\s*+([*$~^|]?+=|[{};,>~]|\s(?![0-9\.])|!important\b)\s*+|([[(:])\s++|\s++([])])|\s++(:)\s*+(?!(?>[^{}"\']++|"(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')*+{)|^\s++|\s++\z|(\s)\s+#si',
2910
					// Replace `0(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)` with `0`
2911
					'#(?<=[\s:])(0)(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)#si',
2912
					// Replace `:0 0 0 0` with `:0`
2913
					'#:(0\s+0|0\s+0\s+0\s+0)(?=[;\}]|\!important)#i',
2914
					// Replace `background-position:0` with `background-position:0 0`
2915
					'#(background-position):0(?=[;\}])#si',
2916
					// Replace `0.6` with `.6`, but only when preceded by `:`, `,`, `-` or a white-space
2917
					'#(?<=[\s:,\-])0+\.(\d+)#s',
2918
					// Minify string value
2919
					'#(\/\*(?>.*?\*\/))|(?<!content\:)([\'"])([a-z_][a-z0-9\-_]*?)\2(?=[\s\{\}\];,])#si',
2920
					'#(\/\*(?>.*?\*\/))|(\burl\()([\'"])([^\s]+?)\3(\))#si',
2921
					// Minify HEX color code
2922
					'#(?<=[\s:,\-]\#)([a-f0-6]+)\1([a-f0-6]+)\2([a-f0-6]+)\3#i',
2923
					// Replace `(border|outline):none` with `(border|outline):0`
2924
					'#(?<=[\{;])(border|outline):none(?=[;\}\!])#',
2925
					// Remove empty selector(s)
2926
					'#(\/\*(?>.*?\*\/))|(^|[\{\}])(?:[^\s\{\}]+)\{\}#s'
2927
				),
2928
				array(
2929
					'$1',
2930
					'$1$2$3$4$5$6$7',
2931
					'$1',
2932
					':0',
2933
					'$1:0 0',
2934
					'.$1',
2935
					'$1$3',
2936
					'$1$2$4$5',
2937
					'$1$2$3',
2938
					'$1:0',
2939
					'$1$2'
2940
				),
2941
				$input);
2942
		}
2943
2944
		/**
2945
		 * Get the conditional fields JavaScript.
2946
		 *
2947
		 * @return mixed
2948
		 */
2949
		public function conditional_fields_js() {
2950
			ob_start();
2951
			?>
2952
<script>
2953
/**
2954
 * Conditional Fields
2955
 */
2956
var aui_cf_field_rules = [], aui_cf_field_key_rules = {}, aui_cf_field_default_values = {};
2957
2958
jQuery(function($) {
2959
    aui_cf_field_init_rules($);
2960
});
2961
2962
/**
2963
 * Conditional fields init.
2964
 */
2965
function aui_cf_field_init_rules($) {
2966
    if (!$('[data-has-rule]').length) {
2967
        return;
2968
    }
2969
    $('input.select2-search__field').attr('data-ignore-rule','');
2970
    $('[data-rule-key]').on('change keypress keyup gdclear', 'input, textarea', function() {
2971
        aui_cf_field_apply_rules($(this));
2972
    });
2973
2974
    $('[data-rule-key]').on('change gdclear', 'select', function() {
2975
        aui_cf_field_apply_rules($(this));
2976
    });
2977
2978
    $('[data-rule-key]').on('change.select2', 'select', function() {
2979
        aui_cf_field_apply_rules($(this));
2980
    });
2981
2982
    aui_cf_field_setup_rules($);
2983
}
2984
2985
/**
2986
 * Setup conditional field rules.
2987
 */
2988
function aui_cf_field_setup_rules($) {
2989
    var aui_cf_field_keys = [];
2990
2991
    $('[data-rule-key]').each(function() {
2992
        var key = $(this).data('rule-key'), irule = parseInt($(this).data('has-rule'));
2993
        if (key) {
2994
            aui_cf_field_keys.push(key);
2995
        }
2996
2997
        var parse_conds = {};
2998
        if ($(this).data('rule-fie-0')) {
2999
            $(this).find('input,select,textarea').each(function() {
3000
                if ($(this).attr('required') || $(this).attr('oninvalid')) {
3001
                    $(this).addClass('aui-cf-req');
3002
                    if ($(this).attr('required')) {
3003
                        $(this).attr('data-rule-req', true);
3004
                    }
3005
                    if ($(this).attr('oninvalid')) {
3006
                        $(this).attr('data-rule-oninvalid', $(this).attr('oninvalid'));
3007
                    }
3008
                }
3009
            });
3010
            for (var i = 0; i < irule; i++) {
3011
                var field = $(this).data('rule-fie-' + i);
3012
                if (typeof parse_conds[i] === 'undefined') {
3013
                    parse_conds[i] = {};
3014
                }
3015
                parse_conds[i]['action'] = $(this).data('rule-act-' + i);
3016
                parse_conds[i]['field'] = $(this).data('rule-fie-' + i);
3017
                parse_conds[i]['condition'] = $(this).data('rule-con-' + i);
3018
                parse_conds[i]['value'] = $(this).data('rule-val-' + i);
3019
            }
3020
3021
            $.each(parse_conds, function(j, data) {
3022
                var item = {
3023
                    'field': {
3024
                        key: key,
3025
                        action: data.action,
3026
                        field: data.field,
3027
                        condition: data.condition,
3028
                        value: data.value,
3029
                        rule: {
3030
                            key: key,
3031
                            action: data.action,
3032
                            condition: data.condition,
3033
                            value: data.value
3034
                        }
3035
                    }
3036
                };
3037
                aui_cf_field_rules.push(item);
3038
            });
3039
        }
3040
        aui_cf_field_default_values[$(this).data('rule-key')] = aui_cf_field_get_default_value($(this));
3041
    });
3042
3043
    $.each(aui_cf_field_keys, function(i, fkey) {
3044
        aui_cf_field_key_rules[fkey] = aui_cf_field_get_children(fkey);
3045
    });
3046
3047
    $('[data-rule-key]:visible').each(function() {
3048
        var conds = aui_cf_field_key_rules[$(this).data('rule-key')];
3049
        if (conds && conds.length) {
3050
            var $main_el = $(this), el = aui_cf_field_get_element($main_el);
3051
            if ($(el).length) {
3052
                aui_cf_field_apply_rules($(el));
3053
            }
3054
        }
3055
    });
3056
}
3057
3058
/**
3059
 * Apply conditional field rules.
3060
 */
3061
function aui_cf_field_apply_rules($el) {
3062
    if (!$el.parents('[data-rule-key]').length) {
3063
        return;
3064
    }
3065
3066
    if ($el.data('no-rule')) {
3067
        return;
3068
    }
3069
3070
    var key = $el.parents('[data-rule-key]').data('rule-key');
3071
    var conditions = aui_cf_field_key_rules[key];
3072
    if (typeof conditions === 'undefined') {
3073
        return;
3074
    }
3075
    var field_type = aui_cf_field_get_type($el.parents('[data-rule-key]')), current_value = aui_cf_field_get_value($el);
3076
    var $keys = {}, $keys_values = {}, $key_rules = {};
3077
3078
    jQuery.each(conditions, function(index, condition) {
3079
        if (typeof $keys_values[condition.key] == 'undefined') {
3080
            $keys_values[condition.key] = [];
3081
            $key_rules[condition.key] = {}
3082
        }
3083
3084
        $keys_values[condition.key].push(condition.value);
3085
        $key_rules[condition.key] = condition;
3086
    });
3087
3088
    jQuery.each(conditions, function(index, condition) {
3089
        if (typeof $keys[condition.key] == 'undefined') {
3090
            $keys[condition.key] = {};
3091
        }
3092
3093
        if (condition.condition === 'empty') {
3094
            var field_value = Array.isArray(current_value) ? current_value.join('') : current_value;
3095
            if (!field_value || field_value === '') {
3096
                $keys[condition.key][index] = true;
3097
            } else {
3098
                $keys[condition.key][index] = false;
3099
            }
3100
        } else if (condition.condition === 'not empty') {
3101
            var field_value = Array.isArray(current_value) ? current_value.join('') : current_value;
3102
            if (field_value && field_value !== '') {
3103
                $keys[condition.key][index] = true;
3104
            } else {
3105
                $keys[condition.key][index] = false;
3106
            }
3107
        } else if (condition.condition === 'equals to') {
3108
            var field_value = (Array.isArray(current_value) && current_value.length === 1) ? current_value[0] : current_value;
3109
            if (((condition.value && condition.value == condition.value) || (condition.value === field_value)) && aui_cf_field_in_array(field_value, $keys_values[condition.key])) {
3110
                $keys[condition.key][index] = true;
3111
            } else {
3112
                $keys[condition.key][index] = false;
3113
            }
3114
        } else if (condition.condition === 'not equals') {
3115
            var field_value = (Array.isArray(current_value) && current_value.length === 1) ? current_value[0] : current_value;
3116
            if (jQuery.isNumeric(condition.value) && parseInt(field_value) !== parseInt(condition.value) && field_value && !aui_cf_field_in_array(field_value, $keys_values[condition.key])) {
3117
                $keys[condition.key][index] = true;
3118
            } else if (condition.value != field_value && !aui_cf_field_in_array(field_value, $keys_values[condition.key])) {
3119
                $keys[condition.key][index] = true;
3120
            } else {
3121
                $keys[condition.key][index] = false;
3122
            }
3123
        } else if (condition.condition === 'greater than') {
3124
            var field_value = (Array.isArray(current_value) && current_value.length === 1) ? current_value[0] : current_value;
3125
            if (jQuery.isNumeric(condition.value) && parseInt(field_value) > parseInt(condition.value)) {
3126
                $keys[condition.key][index] = true;
3127
            } else {
3128
                $keys[condition.key][index] = false;
3129
            }
3130
        } else if (condition.condition === 'less than') {
3131
            var field_value = (Array.isArray(current_value) && current_value.length === 1) ? current_value[0] : current_value;
3132
            if (jQuery.isNumeric(condition.value) && parseInt(field_value) < parseInt(condition.value)) {
3133
                $keys[condition.key][index] = true;
3134
            } else {
3135
                $keys[condition.key][index] = false;
3136
            }
3137
        } else if (condition.condition === 'contains') {
3138
            switch (field_type) {
3139
                case 'multiselect':
3140
                    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)))) {
3141
                        $keys[condition.key][index] = true;
3142
                    } else {
3143
                        $keys[condition.key][index] = false;
3144
                    }
3145
                    break;
3146
                case 'checkbox':
3147
                    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)))) {
3148
                        $keys[condition.key][index] = true;
3149
                    } else {
3150
                        $keys[condition.key][index] = false;
3151
                    }
3152
                    break;
3153
                default:
3154
                    if (typeof $keys[condition.key][index] === 'undefined') {
3155
                        if (current_value && current_value.indexOf(condition.value) >= 0 && aui_cf_field_in_array(current_value, $keys_values[condition.key], false, true)) {
3156
                            $keys[condition.key][index] = true;
3157
                        } else {
3158
                            $keys[condition.key][index] = false;
3159
                        }
3160
                    }
3161
                    break;
3162
            }
3163
        }
3164
    });
3165
3166
    jQuery.each($keys, function(index, field) {
3167
        if (aui_cf_field_in_array(true, field)) {
3168
            aui_cf_field_apply_action($el, $key_rules[index], true);
3169
        } else {
3170
            aui_cf_field_apply_action($el, $key_rules[index], false);
3171
        }
3172
    });
3173
3174
    /* Trigger field change */
3175
    if ($keys.length) {
3176
        $el.trigger('aui_cf_field_on_change');
3177
    }
3178
}
3179
3180
/**
3181
 * Get the field element.
3182
 */
3183
function aui_cf_field_get_element($el) {
3184
    var el = $el.find('input:not("[data-ignore-rule]"),textarea,select'), type = aui_cf_field_get_type($el);
3185
    if (type && window._aui_cf_field_elements && typeof window._aui_cf_field_elements == 'object' && typeof window._aui_cf_field_elements[type] != 'undefined') {
3186
        el = window._aui_cf_field_elements[type];
3187
    }
3188
    return el;
3189
}
3190
3191
/**
3192
 * Get the field type.
3193
 */
3194
function aui_cf_field_get_type($el) {
3195
    return $el.data('rule-type');
3196
}
3197
3198
/**
3199
 * Get the field value.
3200
 */
3201
function aui_cf_field_get_value($el) {
3202
    var current_value = $el.val();
3203
3204
    if ($el.is(':checkbox')) {
3205
        current_value = '';
3206
        if ($el.parents('[data-rule-key]').find('input:checked').length > 1) {
3207
            $el.parents('[data-rule-key]').find('input:checked').each(function() {
3208
                current_value = current_value + jQuery(this).val() + ' ';
3209
            });
3210
        } else {
3211
            if ($el.parents('[data-rule-key]').find('input:checked').length >= 1) {
3212
                current_value = $el.parents('[data-rule-key]').find('input:checked').val();
3213
            }
3214
        }
3215
    }
3216
3217
    if ($el.is(':radio')) {
3218
        current_value = $el.parents('[data-rule-key]').find('input[type=radio]:checked').val();
3219
    }
3220
3221
    return current_value;
3222
}
3223
3224
/**
3225
 * Get the field default value.
3226
 */
3227
function aui_cf_field_get_default_value($el) {
3228
    var value = '', type = aui_cf_field_get_type($el);
3229
3230
    switch (type) {
3231
        case 'text':
3232
        case 'number':
3233
        case 'date':
3234
        case 'textarea':
3235
        case 'select':
3236
            value = $el.find('input:text,input[type="number"],textarea,select').val();
3237
            break;
3238
        case 'phone':
3239
        case 'email':
3240
        case 'color':
3241
        case 'url':
3242
        case 'hidden':
3243
        case 'password':
3244
        case 'file':
3245
            value = $el.find('input[type="' + type + '"]').val();
3246
            break;
3247
        case 'multiselect':
3248
            value = $el.find('select').val();
3249
            break;
3250
        case 'radio':
3251
            if ($el.find('input[type="radio"]:checked').length >= 1) {
3252
                value = $el.find('input[type="radio"]:checked').val();
3253
            }
3254
            break;
3255
        case 'checkbox':
3256
            if ($el.find('input[type="checkbox"]:checked').length >= 1) {
3257
                if ($el.find('input[type="checkbox"]:checked').length > 1) {
3258
                    var values = [];
3259
                    values.push(value);
3260
                    $el.find('input[type="checkbox"]:checked').each(function() {
3261
                        values.push(jQuery(this).val());
3262
                    });
3263
                    value = values;
3264
                } else {
3265
                    value = $el.find('input[type="checkbox"]:checked').val();
3266
                }
3267
            }
3268
            break;
3269
        default:
3270
            if (window._aui_cf_field_default_values && typeof window._aui_cf_field_default_values == 'object' && typeof window._aui_cf_field_default_values[type] != 'undefined') {
3271
                value = window._aui_cf_field_default_values[type];
3272
            }
3273
            break;
3274
    }
3275
    return {
3276
        type: type,
3277
        value: value
3278
    };
3279
}
3280
3281
/**
3282
 * Reset field default value.
3283
 */
3284
function aui_cf_field_reset_default_value($el) {
3285
    var type = aui_cf_field_get_type($el), key = $el.data('rule-key'), field = aui_cf_field_default_values[key];
3286
3287
    switch (type) {
3288
        case 'text':
3289
        case 'number':
3290
        case 'date':
3291
        case 'textarea':
3292
            $el.find('input:text,input[type="number"],textarea').val(field.value);
3293
            break;
3294
        case 'phone':
3295
        case 'email':
3296
        case 'color':
3297
        case 'url':
3298
        case 'hidden':
3299
        case 'password':
3300
        case 'file':
3301
            $el.find('input[type="' + type + '"]').val(field.value);
3302
            break;
3303
        case 'select':
3304
            $el.find('select').find('option').prop('selected', false);
3305
            $el.find('select').val(field.value);
3306
            $el.find('select').trigger('change');
3307
            break;
3308
        case 'multiselect':
3309
            $el.find('select').find('option').prop('selected', false);
3310
            if ((typeof field.value === 'object' || typeof field.value === 'array') && !field.value.length && $el.find('select option:first').text() == '') {
3311
                $el.find('select option:first').remove(); // Clear first option to show placeholder.
3312
            }
3313
            jQuery.each(field.value, function(i, v) {
3314
                $el.find('select').find('option[value="' + v + '"]').attr('selected', true);
3315
            });
3316
            $el.find('select').trigger('change');
3317
            break;
3318
        case 'checkbox':
3319
            if ($el.find('input[type="checkbox"]:checked').length >= 1) {
3320
                $el.find('input[type="checkbox"]:checked').prop('checked', false);
3321
                if (Array.isArray(field.value)) {
3322
                    jQuery.each(field.value, function(i, v) {
3323
                        $el.find('input[type="checkbox"][value="' + v + '"]').attr('checked', true);
3324
                    });
3325
                } else {
3326
                    $el.find('input[type="checkbox"][value="' + field.value + '"]').attr('checked', true);
3327
                }
3328
            }
3329
            break;
3330
        case 'radio':
3331
            if ($el.find('input[type="radio"]:checked').length >= 1) {
3332
                setTimeout(function() {
3333
                    $el.find('input[type="radio"]:checked').prop('checked', false);
3334
                    $el.find('input[type="radio"][value="' + field.value + '"]').attr('checked', true);
3335
                }, 100);
3336
            }
3337
            break;
3338
        default:
3339
            jQuery(document.body).trigger('aui_cf_field_reset_default_value', type, $el, field);
3340
            break;
3341
    }
3342
3343
    if (!$el.hasClass('aui-cf-field-has-changed')) {
3344
        var el = aui_cf_field_get_element($el);
3345
        if (type === 'radio' || type === 'checkbox') {
3346
            el = el.find(':checked');
3347
        }
3348
        if (el) {
3349
            el.trigger('change');
3350
            $el.addClass('aui-cf-field-has-changed');
3351
        }
3352
    }
3353
}
3354
3355
/**
3356
 * Get the field children.
3357
 */
3358
function aui_cf_field_get_children(field_key) {
3359
    var rules = [];
3360
    jQuery.each(aui_cf_field_rules, function(j, rule) {
3361
        if (rule.field.field === field_key) {
3362
            rules.push(rule.field.rule);
3363
        }
3364
    });
3365
    return rules;
3366
}
3367
3368
/**
3369
 * Check in array field value.
3370
 */
3371
function aui_cf_field_in_array(find, item, exact, match) {
3372
    var found = false, key;
3373
    exact = !!exact;
3374
3375
    for (key in item) {
3376
        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)) {
3377
            found = true;
3378
            break;
3379
        }
3380
    }
3381
    return found;
3382
}
3383
3384
/**
3385
 * App the field condition action.
3386
 */
3387
function aui_cf_field_apply_action($el, rule, isTrue) {
3388
    var $destEl = jQuery('[data-rule-key="' + rule.key + '"]');
3389
3390
    if (rule.action === 'show' && isTrue) {
3391
        if ($destEl.is(':hidden')) {
3392
            aui_cf_field_reset_default_value($destEl);
3393
        }
3394
        aui_cf_field_show_element($destEl);
3395
    } else if (rule.action === 'show' && !isTrue) {
3396
        aui_cf_field_hide_element($destEl);
3397
    } else if (rule.action === 'hide' && isTrue) {
3398
        aui_cf_field_hide_element($destEl);
3399
    } else if (rule.action === 'hide' && !isTrue) {
3400
        if ($destEl.is(':hidden')) {
3401
            aui_cf_field_reset_default_value($destEl);
3402
        }
3403
        aui_cf_field_show_element($destEl);
3404
    }
3405
    return $el.removeClass('aui-cf-field-has-changed');
3406
}
3407
3408
/**
3409
 * Show field element.
3410
 */
3411
function aui_cf_field_show_element($el) {
3412
    $el.removeClass('d-none').show();
3413
3414
    $el.find('.aui-cf-req').each(function() {
3415
        if (jQuery(this).data('rule-req')) {
3416
            jQuery(this).removeAttr('required').prop('required', true);
3417
        }
3418
        if (jQuery(this).data('rule-oninvalid')) {
3419
            jQuery(this).removeAttr('oninvalid').attr('oninvalid', jQuery(this).data('rule-oninvalid'));
3420
        }
3421
    });
3422
3423
    if (window && window.navigator.userAgent.indexOf("MSIE") !== -1) {
3424
        $el.css({
3425
            "visibility": "visible"
3426
        });
3427
    }
3428
}
3429
3430
/**
3431
 * Hide field element.
3432
 */
3433
function aui_cf_field_hide_element($el) {
3434
    $el.addClass('d-none').hide();
3435
3436
    $el.find('.aui-cf-req').each(function() {
3437
        if (jQuery(this).data('rule-req')) {
3438
            jQuery(this).removeAttr('required');
3439
        }
3440
        if (jQuery(this).data('rule-oninvalid')) {
3441
            jQuery(this).removeAttr('oninvalid');
3442
        }
3443
    });
3444
3445
    if (window && window.navigator.userAgent.indexOf("MSIE") !== -1) {
3446
        $el.css({
3447
            "visibility": "hidden"
3448
        });
3449
    }
3450
}
3451
<?php do_action( 'aui_conditional_fields_js', $this ); ?>
3452
</script>
3453
			<?php
3454
			$output = ob_get_clean();
3455
3456
			return str_replace( array( '<script>', '</script>' ), '', self::minify_js( $output ) );
3457
		}
3458
	}
3459
3460
	/**
3461
	 * Run the class if found.
3462
	 */
3463
	AyeCode_UI_Settings::instance();
3464
}