/* global communityally_settings, tinyMCE */

jQuery(document).ready(function($) {
	let communityally_settings_wait_overlay = $('#accessally-wait-overlay');

	// <editor-fold defaultstate="collapsed" desc="serialize input values on submit">
	function serialize_value_in_container($container) {
		var values = [];
		$container.find('input[type="hidden"],input[type="text"],textarea').each(function(index, elem) {
			var $elem = $(elem),
				attr = $elem.attr('communityally-param');
			if (typeof attr !== typeof undefined && attr !== false) {
				values.push({ name : attr, value : $elem.val() });
			}
		});
		$container.find('input[type="radio"]:checked').each(function(index, elem) {
			var $elem = $(elem),
				attr = $elem.attr('name');
			if (typeof attr !== typeof undefined && attr !== false) {
				values.push({ name : attr, value : $elem.attr('value') });
			}
		});
		$container.find('input[type="checkbox"]:checked').each(function(index, elem) {
			var $elem = $(elem),
				attr = $elem.attr('communityally-param');
			if (typeof attr !== typeof undefined && attr !== false) {
				values.push({ name : attr, value : $elem.attr('value') });
			}
		});
		$container.find('select').each(function(index, elem) {
			var $elem = $(elem),
				attr = $elem.attr('communityally-param');
			if (typeof attr !== typeof undefined && attr !== false) {
				values.push({ name : attr, value : $elem.children(':selected').val() });
			}
		});
		return values;
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="data-dependency logic">
	function evaluate_dependency(collection, value, match_function, mismatch_function) {
		for (var index = 0; index < collection.length; ++index) {
			var $elem = $(collection[index]),
				dependency_value = $elem.attr('communityally-data-dependency-value'),
				dependency_value_not = $elem.attr('communityally-data-dependency-value-not'),
				key, matched = false;
			if (typeof dependency_value !== typeof undefined && dependency_value !== false) {
				dependency_value = dependency_value.split('|');
				matched = false;
				for (key in dependency_value) {
					if (dependency_value[key] === value) {
						matched = true;
						break;
					}
				}
				if (matched) {
					match_function($elem);
				} else {
					mismatch_function($elem);
				}
			}
			if (typeof dependency_value_not !== typeof undefined && dependency_value_not !== false) {
				if (dependency_value_not !== value) {
					match_function($elem);
				} else {
					mismatch_function($elem);
				}
			}
		}
	}
	$(document).on('change', '[communityally-data-dependency-source]', function() {
		var $element = $(this),
			value = 'no',
			dependency_name = $element.attr('communityally-data-dependency-source'),
			dependencies = $('[communityally-data-dependency="' + dependency_name + '"]');
		if($element.attr('type') === 'checkbox') {
			if ($element.is(':checked')){
				value = 'yes';
			}
		} else if ($element.attr('type') === 'radio') {
			if ($element.is(':checked')){	// only evaluate for the element that is checked
				value = $element.val();
			} else {
				return;
			}
		} else {
			value = $element.val();
		}

		if (value){
			value = value.replace(/\"/g, '\\"');
		}
		evaluate_dependency(dependencies.filter('[hide-toggle]'), value, function(elem) { elem.show(); }, function(elem) { elem.hide(); });
		evaluate_dependency(dependencies.filter('[readonly-toggle]'), value, function(elem) { elem.prop('readonly', false); }, function(elem) { elem.prop('readonly', true); });
		evaluate_dependency(dependencies.filter('[disable-toggle]'), value, function(elem) { elem.prop('disabled', false); }, function(elem) { elem.prop('disabled', true); });
	});

	$(document).on('touchend click', "[communityally-toggle-target]", function(e) {
		var selector = $(this).attr('communityally-toggle-target');
		$(selector).prop('checked', !$(selector).prop('checked')).change();
	});
	$(document).on('change propertychange keyup input paste', "[toggle-element]", function(e) {
		var $this = $(this),
			selector = $this.attr('toggle-element'),
			target = $(selector),
			toggle_class = $this.attr('toggle-class'),
			is_checked = $this.prop('checked'),
			orig_height = target.outerHeight(true),
			min_height = $this.attr('min-height'),
			min_height_element = $this.attr('min-height-element');
		if (typeof min_height_element !== typeof undefined && min_height_element !== false) {
			min_height_element = $(min_height_element).outerHeight(true);
			min_height = Math.max(min_height, min_height_element);
		}
		if (is_checked) {
			target.animate({height:orig_height + 'px'}, 200, function() {$(selector).css('overflow', 'visible').css('height', 'auto');}).addClass(toggle_class);
		} else {
			target.addClass(toggle_class).animate({height:min_height + 'px'}, 200, function() {$(selector).css('overflow', 'hidden');}).removeClass(toggle_class);
		}
		$("[accessally-edit-input]:focus").focusout();
	});
	function close_flex_param_customization_modal_window($modal_window) {
		$modal_window.hide();
		// re_enable_flex_drag_and_drop();
	}
	$(document).on('touchend click', '[accessally-flex-close-modal]', function(e) {
		var $this = $(this),
			modal_id = $this.attr('accessally-flex-close-modal'),
			$modal_window = $('[accessally-flex-customization-modal-window="' + modal_id + '"]');

		// restore_flex_param_customization_value_on_close($modal_window);
		close_flex_param_customization_modal_window($modal_window);
	});
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="Tab control">
	function change_tab($elem) {
		var selector = $elem.attr('tab-group'),
			target = $elem.attr('target'),
			active = $elem.attr('active-class'),
			click_target = $elem.attr('click-target'),
			$tabs = $('[' + selector + ']');
		$('[tab-group=' + selector + ']').removeClass(active);
		$elem.addClass(active);
		$tabs.filter('[' + selector + '!=' + target + ']').hide();
		$tabs.filter('[' + selector + '=' + target + ']').show();
		$('[tab-group-value="' + selector + '"]').val(target);
		if (typeof click_target !== typeof undefined && click_target !== false) {
			$(click_target).val(target).change();
		}
	}
	$(document).on('click touchend', '[tab-group]', function(e) {
		change_tab($(this));
	});
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="Save page-specific settings">
	function save_page_settings_on_click(page_slug) {
		save_page_settings_core(page_slug, false, false);
	}
	function save_page_settings_core(page_slug, additional_data, success_function) {
		var $tier_input_container = $('[communityally-page-submit-section="' + page_slug + '"]'),
			$error_container = $tier_input_container.find('.communityally-setting-error-container'),
			input_values = serialize_value_in_container($tier_input_container),
			data = {
				action: 'communityally_settings_save_page',
				page: page_slug,
				input: JSON.stringify(input_values),
				nonce: communityally_settings.nonce
			};
		if (additional_data) {
			for (let key in additional_data) {
				data[key] = additional_data[key];
			}
		}

		$error_container.html('');
		communityally_settings_wait_overlay.show();
		$.ajax({
			type: 'POST',
			url: communityally_settings.ajax_url,
			data: data,
			success: function(response) {
				try {
					var result = JSON.parse(response);
					if ('status' in result) {
						if ('success' === result['status']) {
							if ('code' in result) {
								for (var slug in result['code']) {
									var $current_container = $('[communityally-page-submit-section="' + slug + '"]');
									$current_container.after(result['code'][slug]);
									$current_container.remove();
								}
							}

							var $new_error_container = $('[communityally-page-submit-section="' + page_slug + '"] .communityally-setting-error-container');
							if (result['warnings'].length > 0) {
								$new_error_container.html(result['warnings']);
								scroll_element_into_view($new_error_container, false);
							}
							if (success_function) {
								success_function();
							} else {
								if ('message' in result) {
									alert(result['message']);
								}
							}
						} else if ('error' === result['status']) {
							throw result['message'];
						} else if ('multi-error' === result['status']) {
							for (var key in result['errors']) {
								$error_container.append('<div class="accessally-error-entry">' + esc_html(result['errors'][key]) + '</div>');
							}
							scroll_element_into_view($error_container, false);
							if ('message' in result) {
								alert(result['message']);
							}
						}
					} else {
						throw 'Invalid response. Please refresh the page and try again.';
					}
				} catch (e) {
					alert(e);
				} finally {
					if (!success_function) {
						communityally_settings_wait_overlay.hide();
					}
				}
			}
		});
	}
	$(document).on('click touchend', '[communityally-page-submit]', function(e){
		var page_slug = $(this).attr('communityally-page-submit');
		save_page_settings_on_click(page_slug);
	});
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="Dynamically generate the user profile edit link">
	$(document).on('click touchend', '#communityally-settings-user-profile-edit-link', function(e){
		let user_profile_id = $('#communityally-settings-select-user-profile').val();
		$(this).attr('href', communityally_settings.user_profile_edit_url + '&show-profile=' + user_profile_id);
	});
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="Dynamically generate the user profile edit link">
	$(document).on('click touchend', '#communityally-settings-user-profile-create-new', function(e){
		save_page_settings_core('general', { create_profile: 'yes' }, false);
	});
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="Emails Customization Modal">
	/** open customization modal */
	$(document).on('touchend click', '[accessally-flex-open-modal]', function(e){
		var modal_id = $(this).attr('accessally-flex-open-modal'),
			$modal_window = $('[accessally-flex-customization-modal-window="' + modal_id + '"]');
		trigger_flex_param_customization_open($modal_window);
	});
	let disabled_flex_sortable_elements = [];
	function trigger_flex_param_customization_open($modal_window) {
		// save_flex_param_customization_value_on_open($modal_window);
		convert_flex_param_customization_value_to_display($modal_window);
		initialize_richtext_input_element($modal_window);
		$modal_window.show();

		disabled_flex_sortable_elements = [];

		// disable drag and drop when the modal is open
		$modal_window.parents('[accessally-email-template-element-container]').each(function(index, elem) {
			var $elem = $(elem);
			if ($elem.sortable('instance')) {
				$elem.sortable('option', 'disabled', true);
			}
			disabled_flex_sortable_elements.push($elem);
		});
	}
	function convert_flex_param_customization_value_to_display($modal_window) {
		$modal_window.find('[accessally-flex-parameter-margin-all-direction]').each(function(index, elem) {
			var $elem = $(elem),
				variable_name = $elem.attr('accessally-flex-param-type'),
				identifier = $elem.attr('accessally-flex-parameter-margin-all-direction'),
				source_val = $elem.val(),
				parts = source_val.split(' '),
				i;
			for (i = parts.length; i < 4; ++i) {
				parts.push('0px');
			}
			$('#accessally-flex-parameter-margin-top-' + identifier + '-' + variable_name).val(sanitize_dimension_value(parts[0]));
			$('#accessally-flex-parameter-margin-right-' + identifier + '-' + variable_name).val(sanitize_dimension_value(parts[1]));
			$('#accessally-flex-parameter-margin-bottom-' + identifier + '-' + variable_name).val(sanitize_dimension_value(parts[2]));
			$('#accessally-flex-parameter-margin-left-' + identifier + '-' + variable_name).val(sanitize_dimension_value(parts[3]));
		});
		$modal_window.find('[accessally-flex-parameter-margin-top-bottom]').each(function(index, elem) {
			var $elem = $(elem),
				variable_name = $elem.attr('accessally-flex-param-type'),
				identifier = $elem.attr('accessally-flex-parameter-margin-top-bottom'),
				source_val = $elem.val(),
				parts = source_val.split(' '),
				i;
			for (i = parts.length; i < 4; ++i) {
				parts.push('0px');
			}
			$('#accessally-flex-parameter-margin-top-' + identifier + '-' + variable_name).val(sanitize_dimension_value(parts[0]));
			$('#accessally-flex-parameter-margin-bottom-' + identifier + '-' + variable_name).val(sanitize_dimension_value(parts[2]));
		});
		$modal_window.find('[accessally-flex-parameter-link-input]').each(function(index, elem) {
			var $elem = $(elem),
				variable_name = $elem.attr('accessally-flex-param-type'),
				identifier = $elem.attr('accessally-flex-parameter-link-input'),
				source_val = $elem.val();
			if (0 === source_val.indexOf('select-')) {
				$('#accessally-flex-parameter-link-input-type-' + identifier + '-' + variable_name).val(source_val).change();
				$('#accessally-flex-parameter-link-input-custom-url-' + identifier + '-' + variable_name).val('');
			} else {
				$('#accessally-flex-parameter-link-input-type-' + identifier + '-' + variable_name).val('custom').change();
				$('#accessally-flex-parameter-link-input-custom-url-' + identifier + '-' + variable_name).val(source_val);
			}
		});
	}

	/**
	 * Update modal values and preview styling
	 * from accessally-email.js */
	$(document).on('touchend click', '[accessally-flex-update-modal]', function(e) {
		var $this = $(this),
			unique_identifier = $this.attr('accessally-flex-update-modal'),
			$modal_window = $('[accessally-flex-customization-modal-window="' + unique_identifier + '"]');

		convert_flex_param_customization_display_to_value($modal_window);
		save_richtext_input_element($modal_window);
		update_flex_param_customization_value(unique_identifier);
		close_flex_param_customization_modal_window($modal_window);
	});
	function convert_flex_param_customization_display_to_value($modal_window) {
		$modal_window.find('[accessally-flex-parameter-margin-all-direction]').each(function(index, elem) {
			var $elem = $(elem),
				variable_name = $elem.attr('accessally-flex-param-type'),
				identifier = $elem.attr('accessally-flex-parameter-margin-all-direction'),
				val, temp;
			temp = $('#accessally-flex-parameter-margin-top-' + identifier + '-' + variable_name).val();
			val = sanitize_dimension_value(temp);

			temp = $('#accessally-flex-parameter-margin-right-' + identifier + '-' + variable_name).val();
			val += ' ' + sanitize_dimension_value(temp);

			temp = $('#accessally-flex-parameter-margin-bottom-' + identifier + '-' + variable_name).val();
			val += ' ' + sanitize_dimension_value(temp);

			temp = $('#accessally-flex-parameter-margin-left-' + identifier + '-' + variable_name).val();
			val += ' ' + sanitize_dimension_value(temp);
			$elem.val(val);
		});
		$modal_window.find('[accessally-flex-parameter-margin-top-bottom]').each(function(index, elem) {
			var $elem = $(elem),
				variable_name = $elem.attr('accessally-flex-param-type'),
				identifier = $elem.attr('accessally-flex-parameter-margin-top-bottom'),
				val, temp;
			temp = $('#accessally-flex-parameter-margin-top-' + identifier + '-' + variable_name).val();
			val = sanitize_dimension_value(temp);

			val += ' 0px';

			temp = $('#accessally-flex-parameter-margin-bottom-' + identifier + '-' + variable_name).val();
			val += ' ' + sanitize_dimension_value(temp);

			val += ' 0px';
			$elem.val(val);
		});
		$modal_window.find('[accessally-flex-parameter-link-input]').each(function(index, elem) {
			var $elem = $(elem),
				variable_name = $elem.attr('accessally-flex-param-type'),
				identifier = $elem.attr('accessally-flex-parameter-link-input'),
				val, type;
			type = $('#accessally-flex-parameter-link-input-type-' + identifier + '-' + variable_name).val();
			if ('custom' === type) {
				val = $('#accessally-flex-parameter-link-input-custom-url-' + identifier + '-' + variable_name).val();
			} else {
				val = type;
			}
			$elem.val(val);
		});
		$modal_window.find('[accessally-flex-parameter-max-width-input]').each(function(index, elem) {
			var $elem = $(elem),
				val = $elem.val();
			if (val) {	// do not change empty value
				$elem.val(sanitize_dimension_value(val));
			}
		});
	}
	function sanitize_dimension_value(val) {
		val = val.replace(/\s/g, '');
		if (val.length > 2) {
			if ('px' === val.substring(val.length - 2)) {
				return val;
			}
		}
		if (val.length > 1) {
			if ('%' === val.substring(val.length - 1)) {
				return val;
			}
		}
		if ('auto' === val.toLowerCase()) {
			return 'auto';
		}
		if (val.indexOf('.') > 0) {
			val = parseFloat(val);
			if (isNaN(val)) {
				return '0px';
			}
			return val.toFixed(2) + 'px';
		}
		val = parseInt(val);
		if (isNaN(val)) {
			return '0px';
		}
		return val + 'px';
	}

	/** from accessally-emails.js */
	function update_flex_param_customization_value(unique_identifier) {
		var $customization_element = $('[accessally-flex-customization="' + unique_identifier + '"]');
		$customization_element.find('[accessally-flex-param-type]').each(function(index, elem) {
			var $elem = $(elem),
				param_type = $elem.attr('accessally-flex-param-type');
			switch (param_type) {
				// case 'margin':
				// case 'padding':	// only used for bordered block
				// case 'width':
				// case 'height':
				// 	update_flex_root_element_css($elem, $customization_element, param_type);
				// 	break;
				case 'margin-top-bottom':
					update_flex_root_element_css($elem, $customization_element, 'margin');
					break;
				// case 'display':
				// 	update_flex_root_element_css($elem, $customization_element, param_type);
				// 	break;
				// case 'image-width':
				// 	update_flex_child_element_css($elem, $customization_element, 'width', '.accessally-image');
				// 	break;
				// case 'image-height':
				// 	update_flex_child_element_css($elem, $customization_element, 'height', '.accessally-image');
				// 	break;
				// case 'image-align':
				// 	update_flex_child_element_css($elem, $customization_element, 'text-align', '.accessally-image-container');
				// 	break;
				// case 'image-max-width':
				// 	update_flex_child_element_css($elem, $customization_element, 'max-width', '.accessally-image');
				// 	break;
				// case 'image-url':
				// 	update_flex_image_url_param($elem, $customization_element);
				// 	break;
				// case 'link-text':
				// 	update_flex_child_element_html($elem, $customization_element, '.accessally-email-link');
				// 	break;
				// case 'link-align':
				// 	update_flex_child_element_css($elem, $customization_element, 'text-align', '.accessally-email-link-container');
				// 	break;
				// case 'header-text':
				// 	update_flex_child_element_text($elem, $customization_element, '.accessally-header');
				// 	break;
				case 'regular-text':
					update_flex_child_element_html($elem, $customization_element, '.accessally-text');
					break;
				// case 'html-code':
				// 	update_flex_child_element_html($elem, $customization_element, '.accessally-html');
				// 	break;
				// case 'shared-block-id':
				// 	update_flex_shared_block_preview($elem, $customization_element);
				// 	break;
			}
		});
	}

	/** live update element preview helper functions */
	function update_flex_root_element_css($param_elem, $customization_element, type) {
		var val = $param_elem.val();
		if (val) {
			$customization_element.css(type, val);
		} else {
			$customization_element.css(type, '');
		}
	}
	function update_flex_child_element_html($param_elem, $customization_element, selector) {
		var val = $param_elem.val();
		try {
			$customization_element.find(selector).html(val);
		} catch (e) {
		}
	}

	/** Ajax save email customizations */
	$(document).on('touchend click', '[communityally-setting-email-save]', function (e){
		let email_type = $(this).attr('communityally-setting-email-save'),
			$container = $('#communityally-email-' + email_type), values, data;

			record_email_template_children_list();
			values = serialize_value_in_container($container);

		$('[communityally-email-settings-wait-overlay=' + email_type +']').show();
		data = {
			action: 'communityally_settings_save_email_template',
			email_type: email_type,
			input: JSON.stringify(values),
			nonce: communityally_settings.nonce
		};
		$.ajax({
			type: 'POST',
			url: communityally_settings.ajax_url,
			data: data,
			success: function (response) {
				$('[communityally-email-settings-wait-overlay=' + email_type +']').hide();
				alert('Settings are saved');
			}
		});
	});
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="Emails: add dynamic text">
	function close_email_template_add_dynamic_text_modal(modal_type) {
		current_add_dynamic_template_target = false;
		$('[accessally-email-add-dynamic-text-modal="' + modal_type + '"]').hide();
		return false;
	}
	$(document).on('touchend click', '[accessally-email-add-dynamic-text-close-modal]', function(e) {
		var modal_type = $(this).attr('accessally-email-add-dynamic-text-close-modal');
		close_email_template_add_dynamic_text_modal(modal_type);
	});
	var current_add_dynamic_template_target = false;
	$(document).on('click touchend', '[accessally-email-add-dynamic-text-button]', function(e) {
		var $this = $(this),
			modal_type = $this.parents('[accessally-email-modal-type]').attr('accessally-email-modal-type');
		current_add_dynamic_template_target = $(this).attr('accessally-email-add-dynamic-text-button');

		$('[accessally-email-add-dynamic-text-modal="' + modal_type + '"]').show();
	});

	/** refer to accessally-emails.js for other dynamic text types*/
	function get_dynamic_text_value(modal_type) {
		let selected_type = $('[accessally-email-add-dynamic-text-select-type="' + modal_type + '"]').val();
		return selected_type;
	}
	function insert_dynamic_text_regular_html_input(dynamic_text) {
		var $target = $('[accessally-email-add-dynamic-text-target="' + current_add_dynamic_template_target + '"]');
		if ($target.length <= 0) {
			return;
		}
		var current_val = $target.val(),
			new_selection_start = $target[0].selectionStart;

		if (new_selection_start >= 0) {
			current_val = current_val.substring(0, new_selection_start) + dynamic_text + current_val.substring(new_selection_start);
			new_selection_start += dynamic_text.length;
		} else {
			current_val = current_val + dynamic_text;
			new_selection_start = current_val.length;
		}
		$target.val(current_val);
		$target.focus();
		$target[0].selectionStart = new_selection_start;
		$target[0].selectionEnd = new_selection_start;
	}
	function insert_dynamic_text_tinymce_input(dynamic_text) {
		var target = tinyMCE.get(current_add_dynamic_template_target);
		if (!target) {
			return;
		}
		target.execCommand('mceInsertContent', false, dynamic_text);
		target.focus();
	}
	$(document).on('click touchend', '[accessally-email-add-dynamic-text-submit]', function(e) {
		var modal_type = $(this).attr('accessally-email-add-dynamic-text-submit'),
			dynamic_text = get_dynamic_text_value(modal_type);
		insert_dynamic_text_regular_html_input(dynamic_text);
		insert_dynamic_text_tinymce_input(dynamic_text);

		close_email_template_add_dynamic_text_modal(modal_type);
	});
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="Send test email">
	function close_send_test_email_modal() {
		current_send_test_email_param = false;
		$('#accessally-email-send-test-modal').hide();
		return false;
	}
	$(document).on('touchend click', '.accessally-email-send-test-close-modal', function(e) {
		close_send_test_email_modal();
	});
	var current_send_test_email_param = false;
	$(document).on('click touchend', '[accessally-email-send-test-button]', function(e) {
		current_send_test_email_param = $(this).attr('accessally-email-send-test-button');

		$('#accessally-email-send-test-modal').show();
	});

	$(document).on('click touchend', '#accessally-email-send-test-submit', function(e) {
		if (current_send_test_email_param) {
			record_email_template_children_list();
			let $container = $('#communityally-email-' + current_send_test_email_param),
				info = serialize_value_in_container($container),
				email = $('#accessally-email-send-test-email-address').val(),
				data = {
					action: 'communityally_send_test_email',
					nonce: communityally_settings.nonce,
					type: current_send_test_email_param,
					target: email,
					value: JSON.stringify(info)
				};
			communityally_settings_wait_overlay.show();
			$.ajax({
				type: "POST",
				url: communityally_settings.ajax_url,
				data: data,
				success: function(response) {
					try {
						var result = JSON.parse(response);
						if (typeof result === 'object' && 'status' in result) {
							if (result['status'] === 'success') {
								alert(result['message']);
							} else {
								throw result['message'];
							}
						} else {
							throw 'Send test email failed due to unknown error';
						}
					} catch (e) {
						alert(e);
					}
					communityally_settings_wait_overlay.hide();
				}
			});
		}
		close_send_test_email_modal();
	});
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="capture flex container children list">
	function record_email_template_children_list() {
		$('[accessally-email-template-parent-block]').each(function(index, input_elem) {
			var $input_elem = $(input_elem),
				container_block_id = $input_elem.attr('accessally-email-template-parent-block'),
				$container = $('#' + container_block_id),
				$child_elements = $container.children('[accessally-email-template-element]'),
				children_id_list = [];
			$child_elements.each(function(cindex, child) {
				children_id_list.push($(child).attr('accessally-email-template-element'));
			});
			$input_elem.val(children_id_list.join(','));
		});
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="Richtext editor Element">
	function initialize_richtext_input_element($modal_window) {
		$modal_window.find('.accessally-flex-richtext-placeholder').each(function(index, elem) {
			var $elem = $(elem),
				id = $elem.attr('id');
			$elem.removeClass('accessally-flex-richtext-placeholder');
			$elem.addClass('accessally-flex-wp-editor-initialized');
			wp.editor.remove(id); // prevent initialize() fail in case id already exist
			wp.editor.initialize(id,
				{
					wpautop: false,
					tinymce: { toolbar1: 'bold,italic,underline,separator,alignleft,aligncenter,alignright,separator,link,unlink' }
				}
			);
		});
		$modal_window.find('.accessally-flex-wp-editor-initialized').each(function(index, elem) {
			var $elem = $(elem),
				id = $elem.attr('id');
			tinyMCE.get(id).load();
		});
	}
	function save_richtext_input_element($modal_window) {
		$modal_window.find('.accessally-flex-wp-editor-initialized').each(function(index, elem) {
			var $elem = $(elem),
				id = $elem.attr('id');
			// get content will trigger a save in tinymce
			wp.editor.getContent(id);
		});
	}
	// </editor-fold>

	// <editor-fold defaultstate="collapsed" desc="Live update special page edit URL">
	$(document).on('change', '[communityally-setting-special-page-selection]', function(e){
		var $this = $(this),
			page_type = $this.attr('communityally-setting-special-page-selection'),
			val = $this.val(),
			$target = $('[communityally-setting-special-page-edit="' + page_type + '"]');
		$target.attr('href', communityally_settings.ajax_url + '?action=communityally_special_pages_edit&type=' + page_type + '&page_id=' + val);
	});
	// </editor-fold>
});