(function($) {
	
	// Initialize Selectize.
	$(".sfwc_frontend_children_selectize").selectize({
		items: null, // Prevent Selectize from selecting the first item by default.
		placeholder: sfwc_vars_user_switcher.selectizePlaceholder + ' \u{21C4}',
		copyClassesToDropdown: true,
	});
	
	// Apply settings background color.
	$('body').append('<style>#sfwc-user-switcher-pane .selectize-control.single .selectize-input{background-color:' + sfwc_vars_user_switcher.switcherPaneSelectBgColor + ';}</style>');

	// Apply settings text color.
	$('body').append('<style>#sfwc-user-switcher-pane .selectize-control.single .selectize-input input::placeholder, #sfwc-user-switcher-pane .selectize-control.single .selectize-input .item {color:' + sfwc_vars_user_switcher.switcherPaneSelectTextColor + ';}</style>');

	
	
	/********
	 * AJAX
	 ********/
	
	$("#sfwc-user-switcher-pane #sfwc-loading-icon").hide();

	var page = 0;
	
	var ajaxAction;

	
	if( sfwc_vars_user_switcher.accountType == 'manager' ){
	
		var currentAccountType = 'manager';
		ajaxAction = 'frontend_populate_user_switcher_dropdown_with_subaccounts';
		
		// Run function only on first click after page load.
		$("#sfwc-user-switcher-pane .selectize-input").one("click", function () {
			getUsersPopulateSelectField();
		});
	}

	
	if ( typeof search_val == 'undefined' ) {
		var search_val = null;
	}

	var endReached = false;

	function wrapGetUsersPopulateSelectField() {
		
		$('#sfwc-user-switcher-pane .selectize-dropdown-content').on('scroll', function() {
			if( $(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight ) {
				//console.log('end reached');
				if (endReached != true ) {
					getUsersPopulateSelectField();
				}
				

			}
		})
		
		
		/**
		 * Trigger getUsersPopulateSelectField() function some seconds after user has finished typing.
		 */
		 
		// Timer setup.
		var typingTimerUserSwitcher;                // Timer identifier.
		var doneTypingIntervalUserSwitcher = 2000;  // Time in ms.
		var $inputUserSwitcher = $('#sfwc-user-switcher-pane .selectize-input input');
		
		// On keyup, start the countdown.
		$inputUserSwitcher.on('keyup', function (e) {
			
			var TextboxValue = $('#sfwc_frontend_children').selectize()[0].selectize.getTextboxValue();
			
			/**
			 * Reference: https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values
			 *
			 * Note: do not use "KeyCode" since it's deprecated. "key" property is fine.
			 */
			if (   e.key == "CapsLock"
				|| e.key == "Shift"
				|| e.key == "Tab"
				|| e.key == "Escape"
				|| e.key == "Control"
				|| e.key == "Meta" /* E.g. Windows, Command Key */
				|| e.key == "Pause"
				|| e.key == "Alt"
				|| e.key == "Fn"
				|| e.key == "Home" 
				|| e.key == "ArrowDown"
				|| e.key == "ArrowUp"
				|| e.key == "ArrowLeft"
				|| e.key == "ArrowRight"
				|| e.key == "Insert"
				|| e.key == "PageDown"
				|| e.key == "PageUp"
				|| e.key == "PageUp"
				|| e.key == "F1"
				|| e.key == "F2"
				|| e.key == "F3"
				|| e.key == "F4"
				|| e.key == "F5"
				|| e.key == "F6"
				|| e.key == "F7"
				|| e.key == "F8"
				|| e.key == "F9"
				|| e.key == "F10"
				|| e.key == "F11"
				|| e.key == "F12"
				|| e.key == "NumLock"
				|| e.key == "ScrollLock"
				|| (e.key = "Backspace" && TextboxValue.length == 0 && noMoreCharacters && noMoreCharacters == false ) /* Backspace when there are no characters */
			) {									
				// Do nothing when above key are pressed.
				// Do not return, we need this function to continue.
			 } else {
				
				if (e.key = "Backspace" && TextboxValue.length == 0) {
					noMoreCharacters = false;
				} else {
					noMoreCharacters = true;
				}
				
				clearTimeout(typingTimerUserSwitcher);
				typingTimerUserSwitcher = setTimeout(doneTypingUserSwitcher, doneTypingIntervalUserSwitcher);
			}
		});
		
		// On keydown, clear the countdown.
		$inputUserSwitcher.on('keydown', function () {
		  clearTimeout(typingTimerUserSwitcher);
		});

		// User has finished typing.
		function doneTypingUserSwitcher() {
			search_val = $('#sfwc-user-switcher-pane .selectize-input input').val();
			page = 0;
			getUsersPopulateSelectField();
		}
	}
	wrapGetUsersPopulateSelectField();


	/**
	 * Retrieve users via Ajax and populate Selectize form.
	 */
	function getUsersPopulateSelectField() {
		
		$.ajax({
			type: 'POST',
			data: {
				action: ajaxAction,
				ajax_user_id: sfwc_vars_user_switcher.userId,
				ajax_page: page + 1,
				ajax_search: search_val,
				nonce: sfwc_vars_user_switcher.nonce,
			},
			url: sfwc_vars_user_switcher.adminAjaxUrl,
			beforeSend: function () {
				
				// Temporarily disable dropdown items selection.
				$('#sfwc-user-switcher-pane .selectize-dropdown-content').css({ 'opacity' : '0.5', 'pointer-events' : 'none' });
				
				// Show loading icon.
				$("#sfwc-user-switcher-pane #sfwc-loading-icon").show();									
			},
			success: function (value) {									
				
				// Get value of search text.
				var TextboxValue = $('#sfwc_frontend_children').selectize()[0].selectize.getTextboxValue();									
				
				// Check if "value" contains any option tags, if not it means there are no more users to show.
				if ( value.indexOf('</option>') > -1 ) {
					
					endReached = false;
					
					page++;
					
					// Destroy previous Selectize instance.
					$('#sfwc_frontend_children').selectize()[0].selectize.destroy();
					
					//if ( ( search_val != null && page == 1 ) || changeAccountTypeRadio == true ) {
					if ( search_val != null && page == 1 ) {
						
						$('select#sfwc_frontend_children').html('');
					}
					
					// Append new options.
					$('select#sfwc_frontend_children').append(value);

					// Reinitialize Selectize with new values.
					$(".sfwc_frontend_children_selectize").selectize({
						items: null, // Prevent Selectize from selecting the first item by default.
						placeholder: sfwc_vars_user_switcher.selectizePlaceholder + ' \u{21C4}',
						copyClassesToDropdown: true,
					});
					
					// Set value of search text (if any).
					if ( TextboxValue.length > 0 ) {
						$( '#sfwc_frontend_children' ).selectize()[0].selectize.setTextboxValue( TextboxValue );
					}
					
					// Refresh Selectize options.
					$('#sfwc_frontend_children').selectize()[0].selectize.refreshOptions();
					
					// Keep scroll position.
					var $container = $('#sfwc-user-switcher-pane .selectize-dropdown-content');
					var $scrollTo = $('#sfwc-user-switcher-pane div.first-item-loaded:last').prevAll().eq(6); // 6 = number of visible items in selectize dropdown without scrolling (7) minus 1.
					jQuery(document).ready(function(){
						
						if ( $scrollTo.offset() && $scrollTo.offset() ) {
							$container.scrollTop(
								$scrollTo.offset().top - $container.offset().top + $container.scrollTop()
							);
						}
					});
					
					// Hide loading icon.
					$("#sfwc-user-switcher-pane #sfwc-loading-icon").hide();
					
					// Re-enable dropdown items selection.
					$('#sfwc-user-switcher-pane .selectize-dropdown-content').css({ 'opacity' : '1', 'pointer-events' : '' });
					
					wrapGetUsersPopulateSelectField();
					
				} else {
					endReached = true;
					$("#sfwc-user-switcher-pane #sfwc-loading-icon").hide();
					$('#sfwc-user-switcher-pane .selectize-dropdown-content').css({ 'opacity' : '1', 'pointer-events' : '' });
				}
			}
		});
	}
})( jQuery );