<?php
/*
 * Plugin Name: Foodle Add-on for Democracy Poll
 * Description: Enhances the Democracy Poll plugin from Kama to interactively display the results of polls in various ways, depending on shortcode parameters, incl. additional functions.
 *
 * Author: Michael Finkenberger
 * Author URI: 
 * Plugin URI: https://de.wordpress.org/plugins/foodle-for-democracy-poll/
 *
 * Text Domain: foodle-for-democracy-poll
 * Domain Path: /languages
 *
 * Requires at least: 5.3
 * Tested up to: 7.0
 * Requires PHP: 7.4
 *
 * Licence: GPLv2 or later
 *
 * Version: 2.5.24.0
 * Date: 21.03.2026
*/



if(!defined('ABSPATH')) die(); // no direct access

const FOODLE_VERSION = '2.5.24.0';
global $foodle_title;                    // just the administrator's choice
global $foodle_admin_menu_color;         // color value
global $foodle_help_tooltips;            // boolean
global $foodle_frontend_tooltips;        // boolean
global $foodle_warnings_removed;         // boolean
global $foodle_no_safety_query;          // boolean
global $foodle_undefined_error;          // translated (WordPress action hook 'init')
global $foodle_sorting;                  // translated (WordPress action hook 'init')
global $thanks_for_using_foodle;         // translated (WordPress action hook 'init')
global $foodle_like_me_1;                // translated (WordPress action hook 'init')
global $foodle_like_me_2;                // translated (WordPress action hook 'init')
global $foodle_results_text_default;     // translated (WordPress action hook 'init')
global $foodle_results_text;             // just the administrator's choice or the default
global $foodle_bar_graph_text_default;   // translated (WordPress action hook 'init')
global $foodle_bar_graph_text;           // just the administrator's choice or the default
global $foodle_unknown_user;             // translated (WordPress action hook 'init')
global $foodle_roles_metafields;         // the Foodle functions for other roles
global $foodle_roles_sorting;            // the Foodle functions for other roles
global $foodle_roles_sproles;            // the Foodle functions for other roles
global $foodle_roles_email;              // the Foodle functions for other roles
global $foodle_roles_usage;              // the Foodle functions for other roles
global $foodle_roles_settings;           // the Foodle functions for other roles
global $foodle_roles_tips;               // the Foodle functions for other roles
global $foodle_roles_deleteun;           // the Foodle functions for other roles
global $foodle_email_link_admins;        // the Foodle email link for administrators
global $foodle_email_link_non_admins;    // the Foodle email link for non-administrators
global $foodle_show_vote_date_admins;    // the Foodle voting date for administrators
global $foodle_show_vote_time_admins;    // the Foodle voting hour for administrators
global $foodle_show_vote_date_specview;  // the Foodle voting date for selected special viewers
global $foodle_show_vote_time_specview;  // the Foodle voting hour for selected special viewers
global $foodle_scroll_up_button_visible; // array of boolean

// Set the global booleans
$foodle_help_tooltips = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['help-tooltips']) ) ) ? get_option('foodle_settings')['help-tooltips'] : true;
$foodle_frontend_tooltips = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['frontend-tooltips']) ) ) ? get_option('foodle_settings')['frontend-tooltips'] : true;
$foodle_warnings_removed = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['remove-warnings']) ) ) ? get_option('foodle_settings')['remove-warnings'] : false;
$foodle_no_safety_query = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['no-safety-query']) ) ) ? get_option('foodle_settings')['no-safety-query'] : false;
$foodle_roles_metafields = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-roles-metafields']) ) ) ? get_option('foodle_settings')['foodle-roles-metafields'] : true;
$foodle_roles_sorting = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-roles-sorting']) ) ) ? get_option('foodle_settings')['foodle-roles-sorting'] : true;
$foodle_roles_sproles = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-roles-sproles']) ) ) ? get_option('foodle_settings')['foodle-roles-sproles'] : false;
$foodle_roles_email = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-roles-email']) ) ) ? get_option('foodle_settings')['foodle-roles-email'] : true;
$foodle_roles_usage = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-roles-usage']) ) ) ? get_option('foodle_settings')['foodle-roles-usage'] : true;
$foodle_roles_settings = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-roles-settings']) ) ) ? get_option('foodle_settings')['foodle-roles-settings'] : false;
$foodle_roles_tips = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-roles-tips']) ) ) ? get_option('foodle_settings')['foodle-roles-tips'] : true;
$foodle_roles_deleteun = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-roles-deleteun']) ) ) ? get_option('foodle_settings')['foodle-roles-deleteun'] : false;
$foodle_email_link_admins = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['voter-email-link-for-admins']) ) ) ? get_option('foodle_settings')['voter-email-link-for-admins'] : true;
$foodle_email_link_non_admins = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['voter-email-link-for-non-admins']) ) ) ? get_option('foodle_settings')['voter-email-link-for-non-admins'] : false;
$foodle_show_vote_date_admins = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['vote-date-for-admins']) ) ) ? get_option('foodle_settings')['vote-date-for-admins'] : true;
$foodle_show_vote_time_admins = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['vote-time-for-admins']) ) ) ? get_option('foodle_settings')['vote-time-for-admins'] : true;
$foodle_show_vote_date_specview = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['vote-date-for-specview']) ) ) ? get_option('foodle_settings')['vote-date-for-specview'] : true;
$foodle_show_vote_time_specview = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['vote-time-for-specview']) ) ) ? get_option('foodle_settings')['vote-time-for-specview'] : false;
$foodle_scroll_up_button_visible['frontend'] = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-scroll-up-button-visible']['frontend']) ) ) ? get_option('foodle_settings')['foodle-scroll-up-button-visible']['frontend'] : false;
$foodle_scroll_up_button_visible['democracy'] = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-scroll-up-button-visible']['democracy']) ) ) ? get_option('foodle_settings')['foodle-scroll-up-button-visible']['democracy'] : false;
$foodle_scroll_up_button_visible['foodle'] = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-scroll-up-button-visible']['foodle']) ) ) ? get_option('foodle_settings')['foodle-scroll-up-button-visible']['foodle'] : false;
$foodle_scroll_up_button_visible['comments'] = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-scroll-up-button-visible']['comments']) ) ) ? get_option('foodle_settings')['foodle-scroll-up-button-visible']['comments'] : false;
$foodle_scroll_up_button_visible['bar_graph'] = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-scroll-up-button-visible']['bar_graph']) ) ) ? get_option('foodle_settings')['foodle-scroll-up-button-visible']['bar_graph'] : false;
$foodle_scroll_up_button_visible['backend'] = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-scroll-up-button-visible']['backend']) ) ) ? get_option('foodle_settings')['foodle-scroll-up-button-visible']['backend'] : false;
$foodle_scroll_up_button_visible['democracy_admin'] = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-scroll-up-button-visible']['democracy_admin']) ) ) ? get_option('foodle_settings')['foodle-scroll-up-button-visible']['democracy_admin'] : true;
$foodle_scroll_up_button_visible['foodle_admin'] = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-scroll-up-button-visible']['foodle_admin']) ) ) ? get_option('foodle_settings')['foodle-scroll-up-button-visible']['foodle_admin'] : true;



// Set the global Foodle version and initialize in case
if ( ! get_option('foodle_version') ) {
    update_option('foodle_version', '0', 'no');
    $foodle_version = '0';
} else
    $foodle_version = get_option('foodle_version');



// make sure that this plugin is only activated under certain conditions...
function foodle_suppress_activation($plugin, $network_wide) {
  global $wp_version;

  // the same 4 lines as below
  $this_is_me = 'foodle-for-democracy-poll/foodle-for-democracy-poll.php';
  $this_is_my_name = 'Foodle';
  $i_need_this_one = 'democracy-poll/democracy.php';
  $this_is_its_name = 'Democracy Poll';

  $wp_version_min = '4.8';

  $is_not_ok_version = ( $wp_version < $wp_version_min ) ? '<p>WordPress version needs to be at least '.$wp_version_min.' to activate '.$this_is_my_name.'.</p>' : '';
  $is_not_ok_needing = ( ! is_plugin_active( $i_need_this_one ) ) ? '<p>\''.$this_is_its_name.'\' plugin needs to be active to activate '.$this_is_my_name.'.</p>' : '';

  if ( ( $plugin == $this_is_me ) && ( strlen($is_not_ok_version.$is_not_ok_needing) != 0 ) ) {
    error_log( 'The plugin activiation conditions for '.$this_is_my_name.' ('.$this_is_me.') are not met!' );      
    $args = var_export( func_get_args(), true );
    error_log( $args );
    wp_die( $is_not_ok_version.$is_not_ok_needing.'<p><a href="javascript:history.back()">You can press here to return</a></p>' );
  }
}
add_action( 'activate_plugin', 'foodle_suppress_activation' , 10, 2);

// ... and later, just in case: Deactivate this plugin if the plugin activation condtions are no longer met in terms of plugins needed
function foodle_check_activation_conditions() {
  // the same 4 lines as above
  $this_is_me = 'foodle-for-democracy-poll/foodle-for-democracy-poll.php';
  $this_is_my_name = 'Foodle';
  $i_need_this_one = 'democracy-poll/democracy.php';
  $this_is_its_name = 'Democracy Poll';  

  $is_not_ok_needing = '<p>\''.$this_is_its_name.'\' plugin needs to be active to activate '.$this_is_my_name.'.</p>';

  include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); // in order to avoid an 'undefined error message' for is_plugin_active() under circumstances not clear to me...
  if ( ! is_plugin_active( $i_need_this_one ) ) {
    error_log( 'The plugin activiation conditions for '.$this_is_my_name.' ('.$this_is_me.') are not met!' );      
    $args = var_export( func_get_args(), true );
    error_log( $args );
    deactivate_plugins($this_is_me, false, null);
    wp_die( $is_not_ok_needing.'<p><a href="javascript:history.back(); window.location.reload(true);">You can press here to return</a></p>' ); // additional reload(true) to see the change
  }
}
add_action( 'wp_loaded', 'foodle_check_activation_conditions' );



// Activate plugin (conditions check is already done above)
function foodle_for_democracy_poll_activate() {
  delete_option('foodle_variables'); // no longer used from 1.1.8.0 onwards: now stored in user_meta
  // generate the option array for the flag storage when foodle_change_demCollectAnsw() has been replaced in case it doesn't exist, yet
  if ( ! get_option('foodle_change_demCollectAnsw') ) update_option('foodle_change_demCollectAnsw', array(), 'yes');
  // generate the option array (see above) in case it doesn't exist, yet
  if ( ! get_option('foodle_meta_fields') ) update_option('foodle_meta_fields', array(), 'yes');
  // generate the option array (see above) in case it doesn't exist, yet
  if ( ! get_option('foodle_meta_defaults_sorting') ) update_option('foodle_meta_defaults_sorting', array(), 'yes');
  // generate the option array (see above) in case it doesn't exist, yet
  if ( ! get_option('foodle_special_functions') ) update_option('foodle_special_functions', array(), 'yes');
  // generate the option array (see above) in case it doesn't exist, yet
  if ( ! get_option('foodle_reminders') ) update_option('foodle_reminders', array(), 'yes');
  // generate the option array (see above) in case it doesn't exist, yet
  if ( ! get_option('foodle_regex_main') ) update_option('foodle_regex_main', array(), 'yes');
  // generate the option array (see above) in case it doesn't exist, yet
  if ( ! get_option('foodle_email_content') ) update_option('foodle_email_content', array(), 'yes');
  // generate the option array (see above) in case it doesn't exist, yet
  if ( ! get_option('foodle_settings') ) update_option('foodle_settings', array(), 'yes');
  // generate the option array (see above) in case it doesn't exist, yet
  if ( ! get_option('foodle_dem_categories') ) update_option('foodle_dem_categories', array(), 'yes');
  // generate the option foodle_version in case it doesn't exist, yet (since 2.1.0.0)
  if ( ! get_option('foodle_version') ) update_option('foodle_version', FOODLE_VERSION, 'no');

  // Add the Foodle capability to the Administrator, in case
    if ( ! get_role( 'administrator' )->has_cap( 'manage_foodle' ) ) wp_roles()->add_cap( 'administrator', 'manage_foodle' );

  // Add columns 'in_comments', 'in_foodles', 'roles_concerned' and 'poll_comments' to democracy_q, in case
  global $wpdb;
  $table_name = $wpdb->prefix . 'democracy_q';
  require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
  $column_name = 'in_comments';
  $create_ddl = "ALTER TABLE $table_name ADD $column_name TEXT NOT NULL DEFAULT '';";
  maybe_add_column($table_name, $column_name, $create_ddl);
  $column_name = 'in_foodles';
  $create_ddl = "ALTER TABLE $table_name ADD $column_name TEXT NOT NULL DEFAULT '';";
  maybe_add_column($table_name, $column_name, $create_ddl);
  $column_name = 'roles_concerned';
  $create_ddl = "ALTER TABLE $table_name ADD $column_name TEXT NOT NULL DEFAULT '';";
  maybe_add_column($table_name, $column_name, $create_ddl);
  $column_name = 'poll_comments';
  $create_ddl = "ALTER TABLE $table_name ADD $column_name TEXT NOT NULL DEFAULT '';";
  maybe_add_column($table_name, $column_name, $create_ddl);
}
register_activation_hook( __FILE__, 'foodle_for_democracy_poll_activate' );



// Do something if this is an update (an update will not trigger plugin activation, expecially not if an update is done through FTP)
if ( $foodle_version !== FOODLE_VERSION ) {
    // Check for administrator role capability, in case
    if ( ! get_role( 'administrator' )->has_cap( 'manage_foodle' ) ) wp_roles()->add_cap( 'administrator', 'manage_foodle' );

    // Add columns 'in_comments', 'in_foodles', 'roles_concerned' and 'poll_comments' to democracy_q, in case
    global $wpdb;
    $table_name = $wpdb->prefix . 'democracy_q';
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $column_name = 'in_comments';
    $create_ddl = "ALTER TABLE $table_name ADD $column_name TEXT NOT NULL DEFAULT '';";
    maybe_add_column($table_name, $column_name, $create_ddl);
    $column_name = 'in_foodles';
    $create_ddl = "ALTER TABLE $table_name ADD $column_name TEXT NOT NULL DEFAULT '';";
    maybe_add_column($table_name, $column_name, $create_ddl);
    $column_name = 'roles_concerned';
    $create_ddl = "ALTER TABLE $table_name ADD $column_name TEXT NOT NULL DEFAULT '';";
    maybe_add_column($table_name, $column_name, $create_ddl);
    $column_name = 'poll_comments';
    $create_ddl = "ALTER TABLE $table_name ADD $column_name TEXT NOT NULL DEFAULT '';";
    maybe_add_column($table_name, $column_name, $create_ddl);

    // Set the new Foodle_version
    update_option('foodle_version', FOODLE_VERSION, 'no');
    $foodle_version = FOODLE_VERSION;

    // Delete no longer used
    delete_option('foodle_shortcode_usage_update'); // no longer used since version 2.5.23.2
    delete_option('foodle_democracy_post_usage'); // no longer used since version 2.5.23.2
    delete_option('foodle_foodle_post_usage'); // no longer used since version 2.5.23.2
    delete_option('foodle_comments_post_usage'); // no longer used since version 2.5.23.2

    // do something
    if ( $foodle_version == '2.5.23.3' ) foodle_check_shortcode_presence();
}



// Do some stuff upon plugin deactivation
function foodle_for_democracy_poll_deactivate() {
  // Unschedule Foodle's wp_cron job, in case it is currently scheduled
  $foodle_timestamp = wp_next_scheduled( 'foodle_cron_hook' );
  wp_unschedule_event( $foodle_timestamp, 'foodle_cron_hook' );
}
register_deactivation_hook( __FILE__, 'foodle_for_democracy_poll_deactivate' );



// Clean up upon plugin uninstall
function foodle_for_democracy_poll_uninstall() {
  global $wp_roles;
  global $wpdb;
  
  // Delete all options used in the foodle-for-democracy-poll plugin
  delete_option('foodle_variables'); // no longer used from 1.1.8.0 onwards: now stored in user_meta
  delete_option('foodle_change_demCollectAnsw');
  delete_option('foodle_meta_fields');
  delete_option('foodle_meta_defaults_sorting');
  delete_option('foodle_special_functions');
  delete_option('foodle_reminders');
  delete_option('foodle_regex_main');
  delete_option("foodle_email_content");
  delete_option('foodle_settings');
  delete_option('foodle_dem_categories');
  delete_option('foodle_shortcode_usage_update'); // no longer used since version 2.5.23.2
  delete_option('foodle_democracy_post_usage'); // no longer used since version 2.5.23.2
  delete_option('foodle_foodle_post_usage'); // no longer used since version 2.5.23.2
  delete_option('foodle_comments_post_usage'); // no longer used since version 2.5.23.2
  delete_option('foodle_shortcode_usage_error_pages_posts');
  delete_option('foodle_version');

  // Remove capability 'manage_foodle' from all roles, just in case...
  foreach ( $wp_roles->role_names as $foodle_wp_role_slug=>$foodle_wp_role_name ) {
    wp_roles()->remove_cap( $foodle_wp_role_slug, 'manage_foodle' );
  }

  // Delete all foodle meta data
  $users = get_users(array(
    'orderby'  => 'meta_value',
    'meta_key' => 'last_name', // just a habit ;-)
    'order'    => 'ASC'
  ));
  foreach ( $users as $user ) {
    $foodle_user_id = $user->ID;
    $foodle_user_meta = get_user_meta($foodle_user_id);
    foreach( $foodle_user_meta as $foodle_meta_key => $foodle_meta_value ) {
      if ( strpos($foodle_meta_key, 'foodle-') === 0 ) delete_user_meta($foodle_user_id, $foodle_meta_key);
    }
  }

  // Unschedule Foodle's wp_cron job, just in case...
  $foodle_timestamp = wp_next_scheduled( 'foodle_cron_hook' );
  wp_unschedule_event( $foodle_timestamp, 'foodle_cron_hook' );

  // Remove columns 'in_comments', 'in_foodles', 'roles_concerned' and 'poll_comments' from database 'democracy_q' (if it exists)
  $table_name = $wpdb->prefix . 'democracy_q';
  require_once(ABSPATH . 'wp-admin/install-helper.php');
  $column_name = 'in_comments';
  $drop_ddl = "ALTER TABLE $table_name DROP $column_name;";
  maybe_drop_column($table_name, $column_name, $drop_ddl);
  $column_name = 'in_foodles';
  $drop_ddl = "ALTER TABLE $table_name DROP $column_name;";
  maybe_drop_column($table_name, $column_name, $drop_ddl);
  $column_name = 'roles_concerned';
  $drop_ddl = "ALTER TABLE $table_name DROP $column_name;";
  maybe_drop_column($table_name, $column_name, $drop_ddl);
  $column_name = 'poll_comments';
  $drop_ddl = "ALTER TABLE $table_name DROP $column_name;";
  maybe_drop_column($table_name, $column_name, $drop_ddl);
}
register_uninstall_hook( __FILE__, 'foodle_for_democracy_poll_uninstall' );



// Set title from option
if ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle_title']) ) && ( get_option('foodle_settings')['foodle_title'] != '' ) ) {
  $foodle_title = esc_html(get_option('foodle_settings')['foodle_title']);
} else $foodle_title = 'Foodle';



// Get admin menu color from option, store it in a global variable...
if ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle_admin_menu_color']) ) && ( get_option('foodle_settings')['foodle_admin_menu_color'] != '' ) ) {
    $foodle_admin_menu_color = get_option('foodle_settings')['foodle_admin_menu_color'];
}
else $foodle_admin_menu_color = '#8CBD5A';
// ...and use it in the admin area, marking the admin bar entry for Democracy and the submenu entires for Democracy Poll and Foodle
function modify_admin_submenu_colors() {
  global $foodle_admin_menu_color;
  
  echo '
    <script type="text/javascript" id="set_democracy_and_foodle_menu_color">
    jQuery(document).ready( function() {
        var $ = jQuery;
        foodle_color = "'.$foodle_admin_menu_color.'";
        $("li a[href$=\'?page=foodle-admin-page\']").css("color",foodle_color);                 // in submenu
        $("li a[href^=\'options-general.php?page=democracy-poll\']").css("color",foodle_color); // in submenu
        $("#wp-admin-bar-dem_settings :first").css("color",foodle_color);                       // in admin bar
        $("#wp-admin-bar-foodle-main :first").css("color",foodle_color);                        // in admin bar
        $("#toplevel_page_foodle-admin-page a").css("color",foodle_color);                      // as top level menu (just in case...)
  });
    </script>
  ';
}
add_action('admin_footer', 'modify_admin_submenu_colors',2147483647); // Let it work as late as possible in the back end to avoid being overridden by other color settings
add_action('wp_footer', 'modify_admin_submenu_colors',2147483647); // Let it work as late as possible in the front end to avoid being overridden by other color settings



function foodle_get_poll_vote_participation_icon($poll_id) {
  // determine the participation rate for the poll in order to select the correct icon color
  $foodle_participation_data = foodle_get_the_poll_participation_data($poll_id); // returns false or an array of data
  if ( $foodle_participation_data !== false ) {
    $foodle_participation_rate = $foodle_participation_data['participation_rate'];
    $number_of_users_concerned = $foodle_participation_data['number_of_users_concerned'];
    $number_of_unexpected_voters = $foodle_participation_data['number_of_unexpected_voters'];
    $foodle_poll_participation_error = ( $number_of_unexpected_voters > 0 );
  }
  if ( ( $foodle_participation_data === false ) || ( $foodle_participation_rate > 100 ) || ( $foodle_poll_participation_error ) ) { // no such poll id or something's wrong
    $foodle_participation_rate = 101; // indicate an error
    $foodle_participation_image = 'img/votes_error.png';
  } else {
    $foodle_participation_image_initial = ( $number_of_users_concerned == 0 ) ? 'img/nobody_to_vote.png' : 'img/not_voted_yet.png';
    $foodle_participation_image = ( $foodle_participation_rate == 100 ) ? 'img/votes_complete.png' : $foodle_participation_image_initial;
  }
  return $foodle_participation_image;
} // this function is initially just called from foodle_add_category_selection_to_democracy_poll() for the Democracy Poll backend poll list and edit pages!



function foodle_add_category_selection_to_democracy_poll() {
  global $wpdb;
  global $wp_roles;
  global $foodle_title;
  global $foodle_sorting;
  global $foodle_help_tooltips;
  global $foodle_no_safety_query;
  global $foodle_scroll_up_button_visible;

  if ( get_current_screen()->base != 'settings_page_democracy-poll' ) return; // Not the Democracy Poll settings page

  if ( ( isset($foodle_scroll_up_button_visible['democracy_admin']) ) && ( $foodle_scroll_up_button_visible['democracy_admin'] ) ) foodle_provide_scroll_up_button();

  $foodle_sorting_button_text = __('Sorting button text','foodle-for-democracy-poll');
  $foodle_show_refresh_button_voted = __('Show refresh button <u>after</u> voting','foodle-for-democracy-poll');
  $foodle_show_refresh_button_not_voted = __('Show refresh button <u>before</u> voting','foodle-for-democracy-poll');
  $foodle_count_marked_voters = __('Count marked voters in the answer column sum','foodle-for-democracy-poll');
  $foodle_delete_poll_IP_addresses = __('Prevent from storing voter IP addresses for this poll','foodle-for-democracy-poll');
  $foodle_send_comment_email = __('Send an email to the admin upon each new, updated or deleted comment for this poll','foodle-for-democracy-poll');
  $foodle_select_roles_concerned = __('Select the roles concerned for this Foodle (none selected = all roles)','foodle-for-democracy-poll');
  $foodle_select_roles_for_not_voted = __('Select the roles to see the bar graph tooltip about users<br>who did not vote so far (none selected = all roles)','foodle-for-democracy-poll');
  $foodle_democracy_email_reminders_users = __('Impact &rArr; Reminder email recipients','foodle-for-democracy-poll');
  $foodle_democracy_count_as_voters_users = __('Impact &rArr; Count as voters (bar graph / voting)','foodle-for-democracy-poll');
  $foodle_select_roles_admin = _x('Administrator','User role').': '.__('Roll members can be voters','foodle-for-democracy-poll');
  $foodle_select_roles_democracy = __('Impact &rArr; Democracy Poll visibility','foodle-for-democracy-poll');
  $foodle_select_roles_foodle = __('Impact &rArr; Foodle visibility','foodle-for-democracy-poll');
  $foodle_select_roles_comments = __('Impact &rArr; Comments visibility','foodle-for-democracy-poll');
  $foodle_select_roles_do_comments = __('Impact &rArr; Entering new comments','foodle-for-democracy-poll').'&nbsp;☝️';
  $foodle_select_roles_bar_graph = __('Impact &rArr; Bar graph visibility','foodle-for-democracy-poll');
  $foodle_select_event = __('Enter related event data for use by shortcode [foodle-create-ics] in case this is an event poll','foodle-for-democracy-poll');
  $foodle_select_event_use = __('This poll concerns an event','foodle-for-democracy-poll');
  $foodle_select_event_auto = __('Generate an ICS auto button','foodle-for-democracy-poll');
  $foodle_select_event_summary = __('The Event Summary/Title','foodle-for-democracy-poll');
  $foodle_select_event_start = __('The Event Start','foodle-for-democracy-poll');
  $foodle_select_event_end = __('The Event End','foodle-for-democracy-poll');
  $foodle_select_event_description = __('The Event Description','foodle-for-democracy-poll');
  $foodle_select_event_location = __('The Event Location','foodle-for-democracy-poll');
  $foodle_select_event_url = __('The Event URL','foodle-for-democracy-poll');
  $foodle_select_ics_button_text = __('The ICS Button Text','foodle-for-democracy-poll');

  // Check, whether this is invoked from saving the foodle poll settings and react accordingly
  $poll_id = -1;
  if ( isset($_GET["edit_poll"]) ) $poll_id = $_GET["edit_poll"];
  if ( ( isset($_GET["foodle_dem_edit"]) ) && ( $poll_id != -1 )  && ( ! isset($_POST["dmc_qid"]) ) ) {
    if ( $_GET["foodle_dem_edit"] == "foodle_changed")
      foodle_pwx_admin_notice__success('<p>'.__('The Foodle categories settings were properly stored for poll id','foodle-for-democracy-poll').' '.$poll_id.'.</p>');
    else
    if ( $_GET["foodle_dem_edit"] == "foodle_unchanged") 
      foodle_pwx_admin_notice__success('<p>'.__('No change in the Foodle categories settings for poll id','foodle-for-democracy-poll').' '.$poll_id.'.</p>');
    echo '<script type="text/javascript">window.history.replaceState("",window.title,window.location.href.replace("changed","nothing"));</script>'; // avoid message to re-appear upon page reload
  }
  
  $foodle_democracy_textarea_template = ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle-democracy-textarea-template']) ) ) ? get_option('foodle_settings')['foodle-democracy-textarea-template'] : "";
  $foodle_democracy_textarea_template = preg_replace( '/[\r][\r\n]/', '\n',$foodle_democracy_textarea_template);
  $foodle_democracy_textarea_template_style = ( $foodle_democracy_textarea_template !== "" ) ? 'style=\"opacity:1.0;cursor:pointer;\"' : 'style=\"opacity:0.1;cursor:not-allowed;\"';
  $foodle_democracy_textarea_clear_style = 'style=\"opacity:1.0;cursor:pointer;\"';
  $foodle_democracy_textarea_template_set = ( $foodle_democracy_textarea_template !== "" ) ? true : false;

  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['sorting_button_text'][$poll_id]) ) )
    $poll_sorting_button_text = get_option('foodle_dem_categories')['sorting_button_text'][$poll_id];
  else
    $poll_sorting_button_text = '';

  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['refresh_button_voted'][$poll_id]) ) )
    $democracy_refresh_button_voted_checked = ( get_option('foodle_dem_categories')['refresh_button_voted'][$poll_id] ) ? " checked='checked'" : "";
  else
    $democracy_refresh_button_voted_checked = '';
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['refresh_button_not_voted'][$poll_id]) ) )
    $democracy_refresh_button_not_voted_checked = ( get_option('foodle_dem_categories')['refresh_button_not_voted'][$poll_id] ) ? " checked='checked'" : "";
  else
    $democracy_refresh_button_not_voted_checked = '';
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['count_marked_voters'][$poll_id]) ) )
    $democracy_count_marked_voters_checked = ( get_option('foodle_dem_categories')['count_marked_voters'][$poll_id] ) ? " checked='checked'" : "";
  else
    $democracy_count_marked_voters_checked = '';
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['delete_poll_IP_addresses'][$poll_id]) ) )
    $democracy_delete_poll_IP_addresses_checked = ( get_option('foodle_dem_categories')['delete_poll_IP_addresses'][$poll_id] ) ? " checked='checked'" : "";
  else
    $democracy_delete_poll_IP_addresses_checked = '';
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['send_comment_email'][$poll_id]) ) )
    $democracy_send_comment_email_checked = ( get_option('foodle_dem_categories')['send_comment_email'][$poll_id] ) ? " checked='checked'" : "";
  else
    $democracy_send_comment_email_checked = '';
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['non_voters_to_admin_only'][$poll_id]) ) )
    $democracy_non_voters_to_admin_only_checked = ( get_option('foodle_dem_categories')['non_voters_to_admin_only'][$poll_id] ) ? "administrator" : ""; // for backward compatibility
  else
    $democracy_non_voters_to_admin_only_checked = "administrator"; // for backward compatibility
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['roles_for_not_voted'][$poll_id]) ) )
    $foodle_roles_for_not_voted = ( get_option('foodle_dem_categories')['roles_for_not_voted'][$poll_id] );
  else
    $foodle_roles_for_not_voted = array($democracy_non_voters_to_admin_only_checked); // for backward compatibility
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['roles_show_democracy'][$poll_id]) ) )
    $foodle_roles_show_democracy_checked = ( get_option('foodle_dem_categories')['roles_show_democracy'][$poll_id] ) ? " checked='checked'" : "";
  else
    $foodle_roles_show_democracy_checked = '';
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['roles_show_foodle'][$poll_id]) ) )
    $foodle_roles_show_foodle_checked = ( get_option('foodle_dem_categories')['roles_show_foodle'][$poll_id] ) ? " checked='checked'" : "";
  else
    $foodle_roles_show_foodle_checked = " checked='checked'";
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['roles_show_comments'][$poll_id]) ) )
    $foodle_roles_show_comments_checked = ( get_option('foodle_dem_categories')['roles_show_comments'][$poll_id] ) ? " checked='checked'" : "";
  else
    $foodle_roles_show_comments_checked = " checked='checked'";
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['roles_do_comments'][$poll_id]) ) )
    $foodle_roles_do_comments_checked = ( get_option('foodle_dem_categories')['roles_do_comments'][$poll_id] ) ? " checked='checked'" : "";
  else
    $foodle_roles_do_comments_checked = ""; // for backward compatibility
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['roles_show_bar_graph'][$poll_id]) ) )
    $foodle_roles_show_bar_graph_checked = ( get_option('foodle_dem_categories')['roles_show_bar_graph'][$poll_id] ) ? " checked='checked'" : "";
  else
    $foodle_roles_show_bar_graph_checked = '';
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['roles_show_admin'][$poll_id]) ) )
    $foodle_roles_show_admin_checked = ( get_option('foodle_dem_categories')['roles_show_admin'][$poll_id] ) ? " checked='checked'" : "";
  else
    $foodle_roles_show_admin_checked = " checked='checked'";
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['event_use'][$poll_id]) ) ) {
    $foodle_event_use_checked = ( get_option('foodle_dem_categories')['event_use'][$poll_id] ) ? " checked='checked'" : "";
    $event_disable = ( get_option('foodle_dem_categories')['event_use'][$poll_id] ) ? "" : " disabled='disabled' ";
  } else {
    $foodle_event_use_checked = "";
    $event_disable = " disabled='disabled' ";
  }
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['event_auto'][$poll_id]) ) )
    $foodle_event_auto_checked = ( get_option('foodle_dem_categories')['event_auto'][$poll_id] ) ? " checked='checked'" : "";
  else
    $foodle_event_auto_checked = "";
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['event_summary'][$poll_id]) ) )
    $foodle_event_summary = get_option('foodle_dem_categories')['event_summary'][$poll_id];
  else
    $foodle_event_summary = "";
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['event_start'][$poll_id]) ) )
    $foodle_event_start = get_option('foodle_dem_categories')['event_start'][$poll_id];
  else
    $foodle_event_start = "";
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['event_end'][$poll_id]) ) )
    $foodle_event_end = get_option('foodle_dem_categories')['event_end'][$poll_id];
  else
    $foodle_event_end = "";
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['event_description'][$poll_id]) ) )
    $foodle_event_description = get_option('foodle_dem_categories')['event_description'][$poll_id];
  else
    $foodle_event_description = "";
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['event_location'][$poll_id]) ) )
    $foodle_event_location = get_option('foodle_dem_categories')['event_location'][$poll_id];
  else
    $foodle_event_location = "";
    if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['event_url'][$poll_id]) ) )
      $foodle_event_url = get_option('foodle_dem_categories')['event_url'][$poll_id];
    else
      $foodle_event_url = "";
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['ics_button_text'][$poll_id]) ) )
    $foodle_ics_button_text = get_option('foodle_dem_categories')['ics_button_text'][$poll_id];
  else
    $foodle_ics_button_text = "";
  // check whether comments exist for this poll
  $sql = "SELECT * FROM $wpdb->democracy_q WHERE id={$poll_id}";
  $get_foodle_poll = $wpdb->get_row($sql);
  $foodle_poll_comments = maybe_unserialize($get_foodle_poll->poll_comments); // if not yet filled
  if ( ! is_array($foodle_poll_comments) ) $foodle_poll_comments = array(); // if not yet filled
  $foodle_comments_exist_here = ( $foodle_poll_comments == array() ) ? false : true;

  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['category_column'][$poll_id]) ) )
    $poll_category_column = get_option('foodle_dem_categories')['category_column'][$poll_id];
  else
    $poll_category_column = ''; // if empty, use the first category as default category column

  $category_selection = __('Category & Parameter Selection','foodle-for-democracy-poll');
  $foodle_meta_fields = (array)get_option('foodle_meta_fields');

  $foodle_category_column_help = ( $foodle_help_tooltips ) ? " foodle_tooltip='".__('Define the category (see righthand) to be used as category column.<br>Whether displayed or not is being defined in the Foodle shortcode.','foodle-for-democracy-poll')."'" : "";
  $foodle_category_display_help = ( $foodle_help_tooltips ) ? " foodle_tooltip='".__('Define which of the categories to be displayed<br>underneath the answer columns.','foodle-for-democracy-poll')."'" : "";
  $foodle_sortbutton_help = ( $foodle_help_tooltips ) ? " foodle_tooltip='".__('Define the sortbutton text<br>for the Foodle table.','foodle-for-democracy-poll')."'" : "";
  $foodle_refreshbutton_help = ( $foodle_help_tooltips ) ? " foodle_tooltip='".__('Decide whether or not to show the \"refresh\" button in the results display<br>after voting and/or before voting. When e.g. in a simultaneous voting<br>situation, this would refresh the results when pressed.','foodle-for-democracy-poll')."'" : "";
  $foodle_count_marked_voters_help = ( $foodle_help_tooltips ) ? " foodle_tooltip='".__('Decide whether or not to count marked voters<br>in the total sum of an answer column.','foodle-for-democracy-poll')."'" : "";
  $foodle_send_category_selection_help = ( $foodle_help_tooltips ) ? " foodle_tooltip='".__('Submit your Foodle category & parameter<br>selections with this button.','foodle-for-democracy-poll')."'" : "";
  $foodle_delete_poll_IP_adresses_help = ( $foodle_help_tooltips ) ? " foodle_tooltip='".__('When set, IP addresses will not be stored for this poll, preserving<br>full functionality even when voters have the same IP address.<br>Logging and IP storage of Democracy Poll must remain activated!','foodle-for-democracy-poll')."'" : "";
  $foodle_send_comment_email_help = ( $foodle_help_tooltips ) ? " foodle_tooltip='".__('When set, an email notification will be sent to the admin upon<br>each new comment, comment change or deletion for this poll.<br>This is to be set individually for each poll.','foodle-for-democracy-poll')."'" : "";
  $foodle_roles_for_not_voted_help = ( $foodle_help_tooltips ) ? " foodle_tooltip='".__('Select the roles to see the bar graph tooltip, which displays users who did not vote so far.<br>Remark: The bar graph should of course be visible for the roles selected (check above).','foodle-for-democracy-poll')."'" : "";
  $foodle_select_roles_concerned_help = ( $foodle_help_tooltips ) ? " foodle_tooltip='".__('Select the roles concerned for this Foodle.<br>The selected roles are typically used for the reminder emails and for statistics.<br>You might want to use this feature for polls, which just concern selected roles.<br>For backward compatibility, with no role selected, all roles are considered concerned.','foodle-for-democracy-poll')."'" : "";
  $foodle_log_and_ip_help = ( $foodle_help_tooltips ) ? __('<strong>This is mandatory for Foodle to work!</strong><br>In order to overcome the restrictions<br>when voting with the same IP address,<br>you can prohibit IP address storage<br>for each poll individually.','foodle-for-democracy-poll') : ""; // special format due to introduction by .attr("foodle_tooltip","...")
  $foodle_registered_only_help = ( $foodle_help_tooltips ) ? __('Whether you select this one here as a general selection,<br>do this individually in each poll admin page or alternatively<br>only provide Foodle on pages accessible<br>just for registered users:<br><strong>The Foodle shortcode only makes sense for registered<br>voters! All other features will of course work :).</strong>','foodle-for-democracy-poll') : ""; // special format due to introduction by .attr("foodle_tooltip","...")
  $foodle_registered_only_alt_help = ( $foodle_help_tooltips ) ? __('Whether you select this one here individually, do this<br>generally in the democracy settings or alternatively<br>only provide Foodle on pages accessible<br>just for registered users:<br><strong>The Foodle shortcode only makes sense for registered<br>voters! All other features will of course work :).</strong>','foodle-for-democracy-poll') : ""; // special format due to introduction by .attr("foodle_tooltip","...")
  $foodle_ip_off_help_text = __("<strong>IP storage is off for this poll.</strong><br>Votes from same WLAN<br>are fine without issues.",'foodle-for-democracy-poll');
  $foodle_ip_off_help = ( true ) ? ' foodle_tooltip_touch=\"true\" foodle_tooltip=\"'.$foodle_ip_off_help_text.'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_ip_on_help_text = __("<strong>IP storage is ON for this poll!</strong><br>Votes from same WLAN<br>can generate issues!",'foodle-for-democracy-poll');
  $foodle_ip_on_help = ( true ) ? ' foodle_tooltip_touch=\"true\" foodle_tooltip=\"'.$foodle_ip_on_help_text.'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_comments_received_help_text = __("This poll did receive comments.",'foodle-for-democracy-poll');
  $foodle_comments_received_wemail_help_text = __("This poll did receive comments.<br>Email comment notifications are switched on for his poll.",'foodle-for-democracy-poll');
  $foodle_comments_received_help = ( true ) ? ' foodle_tooltip_touch=\"true\" foodle_tooltip=\"'.$foodle_comments_received_help_text.'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_comments_received_wemail_help = ( true ) ? ' foodle_tooltip_touch=\"true\" foodle_tooltip=\"'.$foodle_comments_received_wemail_help_text.'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_no_comments_received_help_text = __("This poll did not yet receive comments.",'foodle-for-democracy-poll');
  $foodle_no_comments_received_wemail_help_text = __("This poll did not yet receive comments.<br>Email comment notifications are switched on for this poll.",'foodle-for-democracy-poll');
  $foodle_no_comments_received_help = ( true ) ? ' foodle_tooltip_touch=\"true\" foodle_tooltip=\"'.$foodle_no_comments_received_help_text.'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_no_comments_received_wemail_help = ( true ) ? ' foodle_tooltip_touch=\"true\" foodle_tooltip=\"'.$foodle_no_comments_received_wemail_help_text.'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_textarea_help = ( $foodle_help_tooltips ) ? __('The Democracy Poll textarea.<br>The text herein will be displayed under the poll.<br>Shortcodes are welcome.<br><span style=\'color:#0047b3\'>For all foodle shortcodes with poll id parameter, e.g. [foodle-comments],<br>[foodle-link-democracy-poll] or [foodle-create-ics], id=\'self\' can be used here.</span>','foodle-for-democracy-poll') : ''; // No embedding foodle_tooltip=\"\" as this help will be inserted by jQuery attr();
  $foodle_insert_before_textarea_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('Insert the template before existing text<br>in the Democracy Poll textarea.','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_copy_textarea_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('Replace the whole Democracy Poll<br>textarea with the template.','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_insert_after_textarea_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('Insert the template after existing text<br>in the Democracy Poll textarea.','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_clear_textarea_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('Clear the Democracy Poll<br>textarea content.','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_roles_email_reminders_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('The roles selection will influence the reminder email recipients.<br><strong>Remark: Additional control through Foodle\'s \'Special Roles & Users\' tab</strong>.','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_roles_count_as_voters_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('The roles selected will be considered to be part of the pool of voters for a poll (bar graph / voting).<br><strong>Remark: Additional control for administrators with the next selection below</strong>.','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_roles_show_admin_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('Decide whether administrators shall really be considered to be part of the pool of voters (bar graph / voting)<br>when they are selected (left). By this, you can e.g. control the visibility without being \'in the game\'.<br><strong>Remark: Additional control through Foodle\'s \'Special Roles & Users\' tab (reminders)</strong>.','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_roles_show_democracy_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('Decide whether the roles selection will influence the Democracy Poll visibility.','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_roles_show_foodle_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('Decide whether the roles selection will influence the Foodle visibility.<br><strong>Remark: Foodle will only be visible for logged-in users.</strong>','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_roles_show_comments_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('Decide whether the roles selection will influence the comments visibility.<br><strong>Remark: Comments will only be visible for logged-in users.</strong>','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_roles_do_comments_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('Decide whether the roles selection will influence being able to enter new comments.<br>Remark: The textarea for new comments must be visible (check above the general<br>visibility of comments).','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_roles_show_bar_graph_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('Decide whether the roles selection will influence the bar graph visibility.<br><strong>Remark: The bar graph will only be visible for logged-in users.</strong>','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_event_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('<strong>Should this be an event poll:</strong><br>Enter the related data.<br>Shortcode [foodle-create-ics] will use this data in case you determine the poll id.<br>However, shortcode definitions will overwrite the related data herein!','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_event_use_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('Check here if this poll concerns an event.','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_event_auto_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('Check here if an automatic ICS download<br>button shall be generated.','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_event_summary_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('<strong>Should this be an event poll:</strong><br>Determine the event summary/title.<br>Remember: shortcode definitions will overwrite the<br>related data herein (must not be empty at the end)!','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_event_start_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('<strong>Should this be an event poll:</strong><br>Determine the event start date/time.<br>Remember: shortcode definitions will overwrite the<br>related data herein (must not be empty at the end)!','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_event_end_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('<strong>Should this be an event poll:</strong><br>Determine the event end date/time.<br>Remember: shortcode definitions will<br>overwrite the related data herein!','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_event_description_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('<strong>Should this be an event poll:</strong><br>Determine the event description.<br>Remember: shortcode definitions will<br>overwrite the related data herein!','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_event_location_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('<strong>Should this be an event poll:</strong><br>Determine the event\'s location.<br>Remember: shortcode definitions will<br>overwrite the related data herein!','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_event_url_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('<strong>Should this be an event poll:</strong><br>Determine the event URL.<br>Remember: shortcode definitions will<br>overwrite the related data herein!','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';
  $foodle_ics_button_text_help = ( $foodle_help_tooltips ) ? ' foodle_tooltip=\"'.__('<strong>Should this be an event poll:</strong><br>You may define an individual ics button text here.<br>If empty, the standard text will be used.<br>Remember: shortcode definitions will overwrite<br>the related data herein!','foodle-for-democracy-poll').'\"' : ''; // " must be escaped here due to introduction by echo'append("...")';

  $foodle_dem_poll_form = "
  <p id='foodle_dem_poll_form' style='margin:30px; padding:0px;'></p>
    <h2>".$foodle_title." ".$category_selection."</h2>
    <form class='foodle-dem-poll-form' style='margin:0px; padding:10px 20px;' action='".admin_url( 'admin.php?page=foodle-admin-page' )."' method='post'>
    <table style='border-collapse:collapse;'><tbody><tr><th style='text-align:right; padding-right:20px;padding-bottom:8px;'".$foodle_category_column_help.">".__('Use as<br>Category Column','foodle-for-democracy-poll')."</th><th style='text-align:left; padding-left:20px; padding-bottom:8px;'".$foodle_category_display_help.">".__('Category display<br>per Answer Column','foodle-for-democracy-poll')."</th></tr>";
  $category_count = -1; // to get 0 after the first iteration
  if ( count($foodle_meta_fields) == 0 ) $foodle_dem_poll_form .= "<tr><td colspan='2'>".__('No metafields to select from for this poll, yet!','foodle-for-democracy-poll')."</td></tr>";
  foreach($foodle_meta_fields as $foodle_category => $foodle_category_data) {
    $foodle_category_data []= ''; // avoid an error as there's a new field (version 1.8.4.0)
    $category_count += 1;
    $foodle_category_id = str_replace('.', '€', str_replace(' ', '_', $foodle_category));
    $foodle_category_attr = '';
    $foodle_category_column_attr = '';
    $foodle_category_style = '';
    $foodle_category_column_style = '';
    $foodle_label_style = '';
    $external_color = 'steelblue';
    $foodle_category_column_checked = ( $poll_category_column == $foodle_category ) ? "checked='checked'" : "";
    $foodle_checked = ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')[$poll_id]) ) && ( in_array($foodle_category, (array)get_option('foodle_dem_categories')[$poll_id]) ) ) ? " checked='checked'" : "";
    $foodle_disabled_selection = false;
    if ( $foodle_category_data[2] == 'no' ) {
      if ( $foodle_checked != "" ) $foodle_disabled_selection = true;
      $foodle_category_attr = " disabled='disabled'";
      $foodle_category_style = "cursor:not-allowed;";
      $foodle_label_style = "color:darkred; cursor:default;";
      $external_color = "darkred";
    }
    if ( $foodle_category_data[3] == 'no' ) {
      if ( $foodle_category_column_checked != "" ) $foodle_disabled_selection = true;
      $foodle_category_column_attr = " disabled='disabled'";
      $foodle_category_column_style = "cursor:not-allowed;";
      $foodle_label_style = "color:darkred; cursor:default;";
      $external_color = "darkred";
    }
    $foodle_label_txt = ( $foodle_disabled_selection ) ? " (".__('Disabled selections will not be stored upon saving','foodle-for-democracy-poll').")" : "" ;
    if ( strpos($foodle_category, '••') === 0 )
        $foodle_category_display = "<span style='color:".$external_color."'>".str_replace('••', '', $foodle_category)." (".__('existing field','foodle-for-democracy-poll').")</span>";
      else
        $foodle_category_display = $foodle_category;
    $foodle_dem_poll_form .= "
      <tr>
        <td style='text-align:right;border-top:1px solid LightGrey;padding-top:auto;padding-bottom:auto;padding-left:auto;padding-right:20px;'".$foodle_category_column_help."><input type='radio' style='".$foodle_category_column_style."' name='foodle_dem_category_column' value='".$foodle_category."' ".$foodle_category_column_attr.$foodle_category_column_checked." /></td>
        <td style='text-align:left;border-top:1px solid LightGrey;padding-top:6px;padding-bottom:6px;padding-left:24px;padding-right:auto;'".$foodle_category_display_help."><label style='".$foodle_label_style."'><input type='checkbox' style='".$foodle_category_style."' id='".$foodle_category_id."' name='foodle_dem_categories[]' value='".$foodle_category."' ".$foodle_category_attr.$foodle_checked." />".$foodle_category_display.$foodle_label_txt."</label></td>
      </tr>
    ";
  }
  $foodle_dem_poll_form .= "
    </tbody></table>
    <br>
    <label".$foodle_sortbutton_help."><strong>".$foodle_sorting_button_text."</strong><br><input type='text' name='sorting_button_text' value='".$poll_sorting_button_text."' placeholder='".$foodle_sorting."'/></label>
    <br><br>
    <label".$foodle_refreshbutton_help."><input type='checkbox' name='democracy_refresh_button_voted' value='yes'".$democracy_refresh_button_voted_checked."/><strong>".$foodle_show_refresh_button_voted."</strong></label>
    <br><br>
    <label".$foodle_refreshbutton_help."><input type='checkbox' name='democracy_refresh_button_not_voted' value='yes'".$democracy_refresh_button_not_voted_checked."/><strong>".$foodle_show_refresh_button_not_voted."</strong></label>
    <br><br>
    <label".$foodle_count_marked_voters_help."><input type='checkbox' name='democracy_count_marked_voters' value='yes'".$democracy_count_marked_voters_checked."/><strong>".$foodle_count_marked_voters."</strong></label>
    <br><br>
    <label".$foodle_delete_poll_IP_adresses_help."><input type='checkbox' name='democracy_delete_poll_IP_addresses' value='yes'".$democracy_delete_poll_IP_addresses_checked."/><strong>".$foodle_delete_poll_IP_addresses."</strong></label>
    <br><br>
    <label".$foodle_send_comment_email_help."><input type='checkbox' name='democracy_send_comment_email' value='yes'".$democracy_send_comment_email_checked."/><strong>".$foodle_send_comment_email."</strong></label>
    <br><br>
    <table style='border:1px solid #e4e4e4;border-radius:4px;border-spacing:6px;border-collapse:separate;background-color:#f4f4f4;'><tbody>
    <tr><th colspan='2'><span".$foodle_select_roles_concerned_help."><strong>".$foodle_select_roles_concerned."</strong></span><br></th></tr><tr>
    <td style='border-width:0px;padding:0px;'><select".$foodle_select_roles_concerned_help." style='font-size:0.8em;' id='foodle-roles-concerned' name='foodle_roles_concerned[]' size='12' multiple>";
  $sql = "SELECT * FROM $wpdb->democracy_q WHERE id={$poll_id}";
  $current_roles_concerned = maybe_unserialize($wpdb->get_row($sql)->roles_concerned); // if not yet filled
  if ( ! is_array($current_roles_concerned) ) $current_roles_concerned = array(); // if not yet filled
  foreach ( $wp_roles->role_names as $foodle_role_key=>$foodle_role_value) {
    $foodle_role_selected = ( in_array($foodle_role_key,$current_roles_concerned) ) ? "selected='selected'" : "";
    $foodle_dem_poll_form .= "<option value='".$poll_id."|".$foodle_role_key."' ".$foodle_role_selected.">"._x($foodle_role_value,'User role')."</option>";
  }
  // Add a hidden field to identify the roles selection, even if no role was selected. A bit redundant, as no entry in the database equals an empty array entry.
  $foodle_dem_poll_form .= "
    </select></td>
    <td style='border-width:0px;padding:auto; padding-left:10px;'>
    <label".$foodle_roles_email_reminders_help."><input type='checkbox' name='no-name-no-function2' value='no' disabled='disabled' checked='checked' /><strong>".$foodle_democracy_email_reminders_users."</strong></label>
    <br><br>
    <label".$foodle_roles_count_as_voters_help."><input type='checkbox' name='no-name-no-function1' value='no' disabled='disabled' checked='checked' /><strong>".$foodle_democracy_count_as_voters_users."</strong></label>
    <br><br>
    <span style='display:inline-block;width:20px;'>&nbsp;</span><label".$foodle_roles_show_admin_help."><input type='checkbox' name='foodle_roles_show_admin' value='yes'".$foodle_roles_show_admin_checked."/><strong>".$foodle_select_roles_admin."</strong></label>
    <hr style='height:1px;border-width:0;color:#e0e0e0;background-color:#e0e0e0;margin: 10px 0px 10px 0px;width:100%;' />
    <label".$foodle_roles_show_democracy_help."><input type='checkbox' name='foodle_roles_show_democracy' value='yes'".$foodle_roles_show_democracy_checked."/><strong>".$foodle_select_roles_democracy."</strong></label>
    <br><br>
    <label".$foodle_roles_show_foodle_help."><input type='checkbox' name='foodle_roles_show_foodle' value='yes'".$foodle_roles_show_foodle_checked."/><strong>".$foodle_select_roles_foodle."</strong></label>
    <br><br>
    <label".$foodle_roles_show_comments_help."><input type='checkbox' name='foodle_roles_show_comments' id='foodle_roles_show_comments' value='yes'".$foodle_roles_show_comments_checked."/><strong>".$foodle_select_roles_comments."</strong></label>
    <br><br>
    <span style='display:inline-block;width:20px;'>&nbsp;</span><label".$foodle_roles_do_comments_help."><input type='checkbox' name='foodle_roles_do_comments' id='foodle_roles_do_comments' value='yes'".$foodle_roles_do_comments_checked."/><strong>".$foodle_select_roles_do_comments."</strong></label>
    <br><br>
    <label".$foodle_roles_show_bar_graph_help."><input type='checkbox' name='foodle_roles_show_bar_graph' id='foodle_roles_show_bar_graph' value='yes'".$foodle_roles_show_bar_graph_checked."/><strong>".$foodle_select_roles_bar_graph."</strong></label>
    </td></tr></tbody></table>
    <input type='hidden' name='foodle_roles_concerned[]' value='".$poll_id."|*'/>
    <br><br>
    <table style='border:1px solid #e4e4e4;border-radius:4px;border-spacing:6px;border-collapse:separate;background-color:#f4f4f4;'><tbody>
    <tr><th colspan='2'><span".$foodle_roles_for_not_voted_help."><strong>".$foodle_select_roles_for_not_voted."</strong></span><br></th></tr>
    <tr><td style='border-width:0px;padding:0px;'>
    <select".$foodle_roles_for_not_voted_help." style='font-size:0.8em;' id='foodle-roles-for-not-voted' name='foodle_roles_for_not_voted[]' size='12' multiple>";
  foreach ( $wp_roles->role_names as $foodle_role_key=>$foodle_role_value) {
    $foodle_role_selected = ( in_array($foodle_role_key,$foodle_roles_for_not_voted) ) ? "selected='selected'" : "";
    $foodle_dem_poll_form .= "<option value='".$poll_id."|".$foodle_role_key."' ".$foodle_role_selected.">"._x($foodle_role_value,'User role')."</option>";
  }
  // Add a potential warning and a hidden field to identify the roles selection, even if no role was selected. A bit redundant, as no entry in the option equals an empty array entry.
  $foodle_dem_poll_form .= "
    </select>
    </td><td><span id='foodle_bar_graph_roles_visibility_does_not_match' style='color:DarkGoldenrod;'>".__('<strong>Warning:</strong><br>The saved tooltip roles selection does not match<br>the saved bar graph visibility (check above)!','foodle-for-democracy-poll')."</span></td></tr>
    </tbody><table>
    <br><br>
    <table style='border:1px solid #e4e4e4;border-radius:4px;border-spacing:6px;border-collapse:separate;background-color:#f4f4f4;'><tbody>
    <tr><th colspan='2'><span".$foodle_event_help."><strong>".$foodle_select_event."</strong></span><br></th></tr>
    <tr><td style='border-width:0px;padding:0px;'>
    <br>
    <label".$foodle_event_use_help."><strong>".$foodle_select_event_use."</strong><br><input id='event_use_switch' type='checkbox' name='event_use'  value='yes'".$foodle_event_use_checked."/></label>
    <br><br>
    <label".$foodle_event_auto_help."><strong>".$foodle_select_event_auto."</strong><br><input ".$event_disable." class='event_use' type='checkbox' name='event_auto'  value='yes'".$foodle_event_auto_checked."/></label>
    <br><br>
    <label".$foodle_event_summary_help."><strong>".$foodle_select_event_summary."</strong><br><input ".$event_disable." class='event_use' type='text' size='60' name='event_summary' value='".$foodle_event_summary."' placeholder='"."'/></label>
    <br><br>
    <label".$foodle_event_start_help."><strong>".$foodle_select_event_start."</strong><br><input ".$event_disable." class='event_use' type='datetime-local' name='event_start' value='".$foodle_event_start."' placeholder='"."'/></label>
    <br><br>
    <label".$foodle_event_end_help."><strong>".$foodle_select_event_end."</strong><br><input ".$event_disable." class='event_use' type='datetime-local' name='event_end' value='".$foodle_event_end."' placeholder='"."'/></label>
    <br><br>
    <label".$foodle_event_description_help."><strong>".$foodle_select_event_description."</strong><br><input ".$event_disable." class='event_use' type='text' size='60' name='event_description' value='".$foodle_event_description."' placeholder='"."'/></label>
    <br><br>
    <label".$foodle_event_location_help."><strong>".$foodle_select_event_location."</strong><br><input ".$event_disable." class='event_use' type='text' size='60' name='event_location' value='".$foodle_event_location."' placeholder='"."'/></label>
    <br><br>
    <label".$foodle_event_url_help."><strong>".$foodle_select_event_url."</strong><br><input ".$event_disable." class='event_use' type='text' size='60' name='event_url' value='".$foodle_event_url."' placeholder='"."'/></label>
    <br><br>
    <label".$foodle_ics_button_text_help."><strong>".$foodle_select_ics_button_text."</strong><br><input ".$event_disable." class='event_use' type='text' size='60' name='ics_button_text' value='".$foodle_ics_button_text."' placeholder='"."'/></label>
    </td></tr>
    </tbody><table>
    <input type='hidden' name='foodle_roles_for_not_voted[]' value='".$poll_id."|*'/>
    <br><br><br>
    <input type='hidden' name='democracy_url' value='\" + window.location.href + \"'/>
    <input".$foodle_send_category_selection_help." type='submit' class='button-primary' name='select_poll_categories' value='".__('Submit category & parameter selection','foodle-for-democracy-poll')."...'";
    if ( ! $foodle_no_safety_query ) $foodle_dem_poll_form .= " onclick='return foodle_confirm_category_save();'";
    $foodle_dem_poll_form .= "/></form>
  ";
  $foodle_dem_poll_announce = "
  <p style='margin:40px; padding:0px;'></p>
    <h2>".$foodle_title." ".$category_selection."</h2>
    <p style='margin:0px; padding:10px 20px;'>".__('Category and parameter selection will be available, once the poll was created','foodle-for-democracy-poll')."</p>
  ";
  $foodle_icon_wlan_ok_help = " foodle_tooltip_touch='true' foodle_tooltip = '".$foodle_ip_off_help_text."'";
  $foodle_icon_wlan_no_help = " foodle_tooltip_touch='true' foodle_tooltip = '".$foodle_ip_on_help_text."'";
  $foodle_icon_comments_yes_help = " foodle_tooltip_touch='true' foodle_tooltip = '".$foodle_comments_received_help_text."'";
  $foodle_icon_comments_yes_wemail_help = " foodle_tooltip_touch='true' foodle_tooltip = '".$foodle_comments_received_wemail_help_text."'";
  $foodle_icon_comments_no_help = " foodle_tooltip_touch='true' foodle_tooltip = '".$foodle_no_comments_received_help_text."'";
  $foodle_icon_comments_no_wemail_help = " foodle_tooltip_touch='true' foodle_tooltip = '".$foodle_no_comments_received_wemail_help_text."'";
  $foodle_icon_votes_complete_help = " foodle_tooltip_touch='true' foodle_tooltip = '".__('Everyone voted already.','foodle-for-democracy-poll')."'";
  $foodle_icon_not_voted_yet_help = " foodle_tooltip_touch='true' foodle_tooltip = '".__('Not everyone voted so far.','foodle-for-democracy-poll')."'";
  $foodle_icon_nobody_to_vote_help = " foodle_tooltip_touch='true' foodle_tooltip = '".__('The number of users to vote is zero.','foodle-for-democracy-poll')."'";
  $foodle_icon_votes_error_help = " foodle_tooltip_touch='true' foodle_tooltip = '".__('An unexpected voter did vote or the<br>participation rate exceeds 100%.','foodle-for-democracy-poll')."'";
  $foodle_icon_foodle_parameters_not_fully_saved_help = " foodle_tooltip_touch='true' foodle_tooltip = '".__('NOT all (maybe the brandnew) Foodle poll parameters have been saved so far, so they are still in their programmed default state.','foodle-for-democracy-poll')."'";
  $foodle_comments_visualize_help = "&nbsp;<span foodle_tooltip_touch='true' foodle_tooltip = '".__('Received comments will be<br>visualized as a tooltip.','foodle-for-democracy-poll')."'>(&#x1F441;)</span>";
  $foodle_not_voted_visualize_help = "&nbsp;<span foodle_tooltip_touch='true' foodle_tooltip = '".__('A list of users who did not yet vote<br>will be visualized as a tooltip.','foodle-for-democracy-poll')."'>(&#x1F441;)</span>";
  echo '
    <script type="text/javascript" id="foodle-add-category-selection-to-democracy-poll">
      var $ = jQuery;

      function foodle_confirm_category_save() { return confirm("'.__('Are you sure to submit the category & parameter selection?','foodle-for-democracy-poll').'") }

      $(document).ready( function() {
        var foodle_href_check = window.location.href;
        $(".new-poll-answers").before("<p style=\'margin:0px 25px; padding:0px;\'>('.__('Use','foodle-for-democracy-poll').' •• '.__('as first two digits of an answer to identify it as \'radio\' selection inside a \'multiple answers\' poll','foodle-for-democracy-poll').')</p>");
        $("input[name=dmc_multiple]").parent().append("&nbsp;('.__('The use of •• as first two digits of an answer will make a difference if this option is active!','foodle-for-democracy-poll').')");
        $foodle_log_message="'.foodle_check_keeping_logs().'";
        if ( foodle_href_check.indexOf("&edit_poll=") != -1 ) {
          $(".button-primary").addClass("foodle-democracy-button");
        }
        if ( foodle_href_check.indexOf("&subpage=add_new") == -1 ) {
          $("textarea[name=dmc_note]").parent("label").find(".description").remove();
          $("textarea[name=dmc_note]").attr("foodle_tooltip","'.$foodle_textarea_help.'");
          $("textarea[name=dmc_note]").css({"transition":"0.15s","transition-delay":"0.15s","min-height":"3.5em","height":"3.5em","overflow":"hidden","color":"#0047b3"}).prop("placeholder","'.__('The text herein will be displayed under the poll. Shortcodes are welcome.','foodle-for-democracy-poll').'");
          $("textarea[name=dmc_note]").focusin( function() {
            setTimeout(function(){
              $("textarea[name=dmc_note]").css("height","3.5em");
              setTimeout(function(){
                $("textarea[name=dmc_note]").css("height",($("textarea[name=dmc_note]").prop("scrollHeight") + 10) + "px");
              },100);
            },100);
          });
          $("textarea[name=dmc_note]").focusout( function() {
            $(this).css("height","3.5em");
          });
          $("textarea[name=dmc_note]").on("input", function() {
            $(this).css("height","");
            $(this).css("height",($(this).prop("scrollHeight") + 10) + "px");
          });
          $("textarea[name=dmc_note]").parent("label").after("<p><img '.$foodle_democracy_textarea_template_style.' id=\"foodle-template-insert-before\"'.$foodle_insert_before_textarea_help.' src=\"'.plugin_dir_url(__FILE__).'img/insert before.png'.'\" height=\"30\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img '.$foodle_democracy_textarea_template_style.' id=\"foodle-template-copy\"'.$foodle_copy_textarea_help.' src=\"'.plugin_dir_url(__FILE__).'img/copy.png'.'\" height=\"30\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img '.$foodle_democracy_textarea_template_style.' id=\"foodle-template-insert-after\"'.$foodle_insert_after_textarea_help.' src=\"'.plugin_dir_url(__FILE__).'img/insert after.png'.'\" height=\"30\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img '.$foodle_democracy_textarea_clear_style.' id=\"foodle-textarea-clear\"'.$foodle_clear_textarea_help.' src=\"'.plugin_dir_url(__FILE__).'img/delete.png'.'\" height=\"30\"></p>");
          $(".dem-new-poll").before($foodle_log_message);
          $(".dempolls").before($foodle_log_message);
          $(".demlogs").before($foodle_log_message);
          $("input[name*=\'dmc_forusers\'").parent().attr("foodle_tooltip","'.$foodle_registered_only_alt_help.'");
          if ( foodle_href_check.indexOf("&subpage=") == -1 ) {
            $(".dempolls").before("<span class=\'foodle-icon-info\' style=\'font-size:0.85em;opacity:0.7;\'>&nbsp;'.__('Mouse-hover or touch (here and below)','foodle-for-democracy-poll').':&nbsp;&nbsp; <img'.$foodle_icon_wlan_ok_help.' src=\''.plugin_dir_url(__FILE__).'img/same_wlan_ok.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_wlan_no_help.' src=\''.plugin_dir_url(__FILE__).'img/same_wlan_no.png\' width=\'17\'> '.__('IPs storage status','foodle-for-democracy-poll').'&nbsp;&nbsp; •&nbsp;&nbsp;&nbsp;<img'.$foodle_icon_comments_yes_help.' src=\''.plugin_dir_url(__FILE__).'img/comments__yes.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_comments_yes_wemail_help.' src=\''.plugin_dir_url(__FILE__).'img/comments__yes_wemail.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_comments_no_help.' src=\''.plugin_dir_url(__FILE__).'img/comments__no.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_comments_no_wemail_help.' src=\''.plugin_dir_url(__FILE__).'img/comments__no_wemail.png\' width=\'17\'> '.__('Comments status','foodle-for-democracy-poll').$foodle_comments_visualize_help.'&nbsp;&nbsp; •&nbsp;&nbsp;&nbsp;<img'.$foodle_icon_votes_complete_help.' src=\''.plugin_dir_url(__FILE__).'img/votes_complete.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_not_voted_yet_help.' src=\''.plugin_dir_url(__FILE__).'img/not_voted_yet.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_nobody_to_vote_help.' src=\''.plugin_dir_url(__FILE__).'img/nobody_to_vote.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_votes_error_help.' src=\''.plugin_dir_url(__FILE__).'img/votes_error.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_foodle_parameters_not_fully_saved_help.' src=\''.plugin_dir_url(__FILE__).'img/foodle_parameters_not_fully_saved.png\' width=\'17\'> '.__('Poll participation/warning status','foodle-for-democracy-poll').$foodle_not_voted_visualize_help.'<br>");
            if ( $("td.column-id").length > 7 ) $(".dempolls").after("<span class=\'foodle-icon-info\' style=\'display:inline-block;margin-top:4px;font-size:0.85em;opacity:0.7;\'>&nbsp;'.__('Mouse-hover or touch (here and above)','foodle-for-democracy-poll').':&nbsp;&nbsp; <img'.$foodle_icon_wlan_ok_help.' src=\''.plugin_dir_url(__FILE__).'img/same_wlan_ok.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_wlan_no_help.' src=\''.plugin_dir_url(__FILE__).'img/same_wlan_no.png\' width=\'17\'> '.__('IPs storage status','foodle-for-democracy-poll').'&nbsp;&nbsp; •&nbsp;&nbsp;&nbsp;<img'.$foodle_icon_comments_yes_help.' src=\''.plugin_dir_url(__FILE__).'img/comments__yes.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_comments_yes_wemail_help.' src=\''.plugin_dir_url(__FILE__).'img/comments__yes_wemail.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_comments_no_help.' src=\''.plugin_dir_url(__FILE__).'img/comments__no.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_comments_no_wemail_help.' src=\''.plugin_dir_url(__FILE__).'img/comments__no_wemail.png\' width=\'17\'> '.__('Comments status','foodle-for-democracy-poll').$foodle_comments_visualize_help.'&nbsp;&nbsp; •&nbsp;&nbsp;&nbsp;<img'.$foodle_icon_votes_complete_help.' src=\''.plugin_dir_url(__FILE__).'img/votes_complete.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_not_voted_yet_help.' src=\''.plugin_dir_url(__FILE__).'img/not_voted_yet.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_nobody_to_vote_help.' src=\''.plugin_dir_url(__FILE__).'img/nobody_to_vote.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_votes_error_help.' src=\''.plugin_dir_url(__FILE__).'img/votes_error.png\' width=\'17\'>&nbsp;<img'.$foodle_icon_foodle_parameters_not_fully_saved_help.' src=\''.plugin_dir_url(__FILE__).'img/foodle_parameters_not_fully_saved.png\' width=\'17\'> '.__('Poll participation/warning status','foodle-for-democracy-poll').$foodle_not_voted_visualize_help.'<br>");
            $foodle_ID_IP_list = [];
            $foodle_comment_list = [];
            $foodle_comment_email_list = [];
            $foodle_icon_list = [];';
        if ( ! $foodle_no_safety_query ) echo '$(".button-primary").attr("onclick","return confirm(\"'.__('Are you sure to save the Democracy poll?','foodle-for-democracy-poll').'\");")';
        if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['delete_poll_IP_addresses']) ) ) {
          foreach(get_option('foodle_dem_categories')['delete_poll_IP_addresses'] as $foodle_poll_ID=>$foodle_poll_IP) {
            // Check whether IP storage is on or off and make it known to javascript
            if ( $foodle_poll_IP ) $foodle_poll_IP = 1; else $foodle_poll_IP = 0;
            echo '
            $foodle_ID_IP_list["'.$foodle_poll_ID.'"] = '.$foodle_poll_IP.';';
            // Check whether comments exist and make it known to javascript
            $sql = "SELECT * FROM $wpdb->democracy_q WHERE id={$foodle_poll_ID}";
            $get_foodle_poll = $wpdb->get_row($sql);
            $foodle_poll_comments = maybe_unserialize($get_foodle_poll->poll_comments); // if not yet filled
            if ( ! is_array($foodle_poll_comments) ) $foodle_poll_comments = array(); // if not yet filled
            if ( $foodle_poll_comments == array() ) $foodle_comments_exist = 0; else $foodle_comments_exist = 1;
            if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['send_comment_email'][$foodle_poll_ID]) ) && ( get_option('foodle_dem_categories')['send_comment_email'][$foodle_poll_ID] ) ) $foodle_comments_email = 1; else $foodle_comments_email = 0;
            $foodle_poll_vote_participation_icon = ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['roles_for_not_voted'][$foodle_poll_ID]) ) ) ? foodle_get_poll_vote_participation_icon($foodle_poll_ID) : 'img/foodle_parameters_not_fully_saved.png' ; // ALWAYS PUT HERE THE FOODLE POLL PARAMETER OF get_option('foodle_dem_categories') THAT WAS INTRODUCED LAST !!!
            echo '
              $foodle_comment_list["'.$foodle_poll_ID.'"] = '.$foodle_comments_exist.';
              $foodle_comment_email_list["'.$foodle_poll_ID.'"] = '.$foodle_comments_email.';
              $foodle_icon_list["'.$foodle_poll_ID.'"] = "'.$foodle_poll_vote_participation_icon.'";
            ';
          }
        }
        echo '
            $("td.column-id").each(function(){
              $foodle_poll_ID = $(this).html().substr(0,$(this).html().indexOf("<button"));
              if ( $foodle_ID_IP_list[$foodle_poll_ID] == 1 ) $(this).append("<br /><img align=\"right\"'.$foodle_ip_off_help.' src=\"'.plugin_dir_url(__FILE__).'img/same_wlan_ok.png'.'\">"); else $(this).append("<br /><img align=\"right\"'.$foodle_ip_on_help.' src=\"'.plugin_dir_url(__FILE__).'img/same_wlan_no.png'.'\">");
              if ( $foodle_comment_email_list[$foodle_poll_ID] == 1 )
                { if ( $foodle_comment_list[$foodle_poll_ID] == 1 ) $(this).append("<br /><img style=\"margin-top:3px;width:25px;\" align=\"right\" foodle_com_tooltip=\"" + $foodle_poll_ID + "\" src=\"'.plugin_dir_url(__FILE__).'img/comments__yes_wemail.png'.'\" />"); else $(this).append("<br /><img style=\"margin-top:3px;width:25px;\" align=\"right\"'.$foodle_no_comments_received_wemail_help.' src=\"'.plugin_dir_url(__FILE__).'img/comments__no_wemail.png'.'\" />"); }
              else
                { if ( $foodle_comment_list[$foodle_poll_ID] == 1 ) $(this).append("<br /><img style=\"margin-top:3px;width:25px;\" align=\"right\" foodle_com_tooltip=\"" + $foodle_poll_ID + "\" src=\"'.plugin_dir_url(__FILE__).'img/comments__yes.png'.'\" />"); else $(this).append("<br /><img style=\"margin-top:3px;width:25px;\" align=\"right\"'.$foodle_no_comments_received_help.' src=\"'.plugin_dir_url(__FILE__).'img/comments__no.png'.'\" />"); }
              if ( $foodle_icon_list[$foodle_poll_ID] !== undefined ) $(this).append("<br /><img style=\"margin-top:3px;width:25px;\" align=\"right\" foodle_non_voters_tooltip=\"" + $foodle_poll_ID + "\" src=\"'.plugin_dir_url(__FILE__).'" + $foodle_icon_list[$foodle_poll_ID] + "\">");
                else $(this).append("<br /><img style=\"margin-top:3px;width:25px;\" align=\"right\" foodle_non_voters_tooltip=\"" + $foodle_poll_ID + "\" src=\"'.plugin_dir_url(__FILE__).'img/foodle_parameters_not_fully_saved.png\">");
            });
          }';

          // determine the correct poll participation icon
          $foodle_poll_vote_participation_icon = ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['roles_for_not_voted'][$poll_id]) ) ) ? foodle_get_poll_vote_participation_icon($poll_id) : 'img/foodle_parameters_not_fully_saved.png' ; // ALWAYS PUT HERE THE FOODLE POLL PARAMETER OF get_option('foodle_dem_categories') THAT WAS INTRODUCED LAST !!!
          $foodle_poll_comment_email = ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['send_comment_email'][$poll_id]) ) && ( get_option('foodle_dem_categories')['send_comment_email'][$poll_id] ) ) ? '_wemail' : '' ;
          $foodle_no_comments_received_help_detail = ( $foodle_poll_comment_email == '_wemail' ) ? $foodle_no_comments_received_wemail_help : $foodle_no_comments_received_help ;
  
          if ( $democracy_delete_poll_IP_addresses_checked == '' )
            echo '$(".dem-new-poll").before("<br /><br /><img'.$foodle_ip_on_help.' src=\''.plugin_dir_url(__FILE__).'img/same_wlan_no.png\'/>");';
          else
            echo '$(".dem-new-poll").before("<br /><br /><img'.$foodle_ip_off_help.' src=\''.plugin_dir_url(__FILE__).'img/same_wlan_ok.png\'/>");';
          if ( $foodle_comments_exist_here )
            echo '$(".dem-new-poll").before("<br /><img foodle_com_tooltip=\"'.$poll_id.'\" style=\"margin-top:3px;width:25px;\" src=\''.plugin_dir_url(__FILE__).'img/comments__yes'.$foodle_poll_comment_email.'.png\' />");';
          else
            echo '$(".dem-new-poll").before("<br /><img'.$foodle_no_comments_received_help_detail.' style=\"margin-top:3px;width:25px;\" src=\''.plugin_dir_url(__FILE__).'img/comments__no'.$foodle_poll_comment_email.'.png\' />");';
          echo '$(".dem-new-poll").before("<br /><img foodle_non_voters_tooltip=\"'.$poll_id.'\" style=\"margin-top:3px;width:25px;\" src=\''.plugin_dir_url(__FILE__).$foodle_poll_vote_participation_icon.'\' /><br />");';

                echo '
                if ( foodle_href_check.indexOf("&subpage=general_settings") != -1 ) {
                    if ( $foodle_log_message.length == 0 ) {
                        $mf_color = "2px solid Green";
                        $foodle_log_mark_color = "Green";
                    }
                    else {
                        $(".dempage_settings").before($foodle_log_message);
                        $mf_color = "2px solid Red";
                        $foodle_log_mark_color = "Red";
                    }
                    $("input[name*=\'keep_logs\'").parent().append("<span class=\'foodle-log-mark\'> ☞ Foodle</span>").parent().css({"border":$mf_color,"padding":"6px 6px 0px 6px","margin-bottom":"20px"});
                    $("input[name*=\'keep_logs\'").parent().attr("foodle_tooltip","'.$foodle_log_and_ip_help.'");
                    $("input[name*=\'only_for_users\'").parent().attr("foodle_tooltip","'.$foodle_registered_only_help.'");
                    $(".foodle-log-mark").css("color",$foodle_log_mark_color);
                    $("input[name*=\'keep_logs\'").change(function() {
                        if ( $(this).prop("checked") ) {
                            $(this).parent().parent().css("border-color","Green");
                            $(".foodle-log-mark").css("color","Green");
                        }
                        else {
                            $(this).parent().parent().css("border-color","Red");
                            $(".foodle-log-mark").css("color","Red");
                        }
                    });
                }
                $(".dem-new-poll").before("<p><a class=\"button-primary foodle-smooth-scroll\" foodle_smooth_scroll_duration=\"1500\" foodle_smooth_scroll_effect=\"easeInOutCubic\" foodle_smooth_scroll_offset=\"-40\" style=\"background-color:SlateGrey;\" href=\"#foodle_dem_poll_form\">☟ '.__('Down to the Foodle settings','foodle-for-democracy-poll').'</a></p>");
                $(".dem-new-poll").after("'.preg_replace('/\s+/', ' ', $foodle_dem_poll_form).'");
            }
            else {
                $(".dem-new-poll").before($foodle_log_message);
                $(".dem-new-poll").after("'.preg_replace('/\s+/', ' ', $foodle_dem_poll_announce).'");
            }
            $(".foodle--scroll").on("click", function(event) {
                if (this.hash !== "") {
                    event.preventDefault();
                    var hash = this.hash;
                    $("html, body").animate({
                        scrollTop: $(hash).offset().top
                    }, 1500, function(){
                        window.location.hash = hash;
                    }); 
            
                } // End if
            });';
            if ( $foodle_democracy_textarea_template_set ) echo '
            $("#foodle-template-insert-before").on("click", function(event) {
              var foodle_template = "'.$foodle_democracy_textarea_template.'";
              var new_democracy_textarea = foodle_template + "\n\n" + $("textarea[name=dmc_note]").val();
              $("textarea[name=dmc_note]").focus().val(new_democracy_textarea).trigger("change").focus();
            });
            $("#foodle-template-copy").on("click", function(event) {
              var foodle_template = "'.$foodle_democracy_textarea_template.'";
              var new_democracy_textarea = foodle_template;
              $("textarea[name=dmc_note]").focus().val(new_democracy_textarea).trigger("change").focus();
            });
            $("#foodle-template-insert-after").on("click", function(event) {
              var foodle_template = "'.$foodle_democracy_textarea_template.'";
              var new_democracy_textarea = $("textarea[name=dmc_note]").val() + "\n\n" + foodle_template;
              $("textarea[name=dmc_note]").focus().val(new_democracy_textarea).trigger("change").focus();
            });
            $("#foodle-textarea-clear").on("click", function(event) {
              $("textarea[name=dmc_note]").val("").trigger("change");
            });
            ';
  // Determine whether the roles to see the bargraph tooltip are equal to or a subset of the roles who really see the bargraph
  if ( $current_roles_concerned == array() ) $current_roles_concerned = array_keys(wp_roles()->get_names());
  if ( $foodle_roles_for_not_voted == array() ) $foodle_roles_for_not_voted = array_keys(wp_roles()->get_names());
  $foodle_roles_for_not_voted_is_ok = ( count(array_intersect($foodle_roles_for_not_voted,$current_roles_concerned)) == count($foodle_roles_for_not_voted) ) ? 'true' : 'false';
  echo '
        // Enter comments visibility
        if ( ! $("#foodle_roles_show_comments").prop("checked") )
          $("#foodle_roles_do_comments").prop("disabled",true);
        $($("#foodle_roles_show_comments")).change(function(){
          if ( $(this).prop("checked") )
            $("#foodle_roles_do_comments").prop("disabled",false);
          else
            $("#foodle_roles_do_comments").prop("disabled",true);
        });
        // Enter event data ability & disability
        $($("#event_use_switch")).change(function(){
          if ( $(this).prop("checked") )
            $(".event_use").prop("disabled",false);
          else
            $(".event_use").prop("disabled",true);
        });
        // Bar graph tooltip visibility
        if ( ( ! $("#foodle_roles_show_bar_graph").prop("checked") ) || ( '.$foodle_roles_for_not_voted_is_ok.' ) )
          $("#foodle_bar_graph_roles_visibility_does_not_match").css("visibility","hidden");
        $($("#foodle_roles_show_bar_graph")).change(function(){
          if ( ( $(this).prop("checked") ) && ( ! '.$foodle_roles_for_not_voted_is_ok.' ) )
            $("#foodle_bar_graph_roles_visibility_does_not_match").css("visibility","visible");
          else
            $("#foodle_bar_graph_roles_visibility_does_not_match").css("visibility","hidden");
        });
        if ( foodle_href_check.indexOf("#dmc-note-anchor") != -1 ) {
          $("html,body").animate({scrollTop: $("textarea[name=dmc_note]").offset().top + 0},1500,"easeInOutCubic");
          $("textarea[name=dmc_note]").focus();
        }
      });
    </script>
  ';
}
add_action('admin_footer', 'foodle_add_category_selection_to_democracy_poll', 2147483647);



function foodle_watch_form_changes_without_saving_before_leave() {

    if ( ( get_current_screen()->base != 'settings_page_democracy-poll' ) && ( get_current_screen()->base != 'settings_page_foodle-admin-page' ) ) return; // Not the Democracy Poll or the Foodle settings page 

  echo '
    <script type="text/javascript" id="foodle-watch-form-changes-without-saving-before-leave">
      var $ = jQuery;
      $(document).ready( function() {
        setTimeout(function(){ // just for the first new answer handling
          var foodle_href_check = window.location.href;
          if ( ( foodle_href_check.indexOf("?page=foodle-admin-page") != -1 ) || ( foodle_href_check.indexOf("?page=democracy-poll&") != -1 ) ) {
            var $foodle_unload_trigger = true;
            $("input,textarea").addClass("unload-input-msg");
            $("select").addClass("unload-select-msg");
            $(".unload-input-msg").on("input",function(){
              $(this).css("outline","2px solid GoldenRod");
              foodle_unload_watch_on();
              $(this).parent().parent().parent().find(".auto-sortlist-button").attr("disabled",true);
              $(this).parent().parent().parent().find(".auto-sortlist-label").html("");
            });
            $(".unload-input-msg").change(function(){ // just for the template modifications buttons handling
              $(this).css("outline","2px solid GoldenRod");
              foodle_unload_watch_on();
            });
            $(".unload-select-msg").change(function(){
              $(this).css("outline","2px solid GoldenRod");
              foodle_unload_watch_on();
            });
            $("form").submit(function() {
              foodle_unload_watch_off();
            });
            function foodle_unload_watch_on() {
              if ( true === $foodle_unload_trigger ) {
                $(window).on("beforeunload", function () {
                  return "?";
                });
                $foodle_unload_trigger = false;
              }
            }
            function foodle_unload_watch_off() {
              $(window).off("beforeunload");
              $foodle_unload_trigger = true;
            }
          }
        },200); // just for the first new answer handling
      });
    </script>
  ';
}
add_action('admin_footer', 'foodle_watch_form_changes_without_saving_before_leave', 2147483647);



// Initialize the individual foodle variables prior their use upon page load in order to
// avoid the array getting bigger and bigger with the foodle private tokens above 20KB
function foodle_initialize_foodle_variables_in_user_meta() {
  $foodle_current_user_id = get_current_user_id();
  $foodle_variable_size = strlen(serialize(get_user_meta($foodle_current_user_id, 'foodle_variables', true)));
  if ( $foodle_variable_size > 20480 )
    update_user_meta($foodle_current_user_id, 'foodle_variables', array());
}
add_action('set_current_user', 'foodle_initialize_foodle_variables_in_user_meta');



// Introduce AJAX call to foodle display function after democracy poll screen change and introduce a few adaptations
function foodle_democracy_update( $html, $foodle_this ) {
  global $wpdb;
  global $foodle_scroll_up_button_visible;

  if ( ( isset($foodle_scroll_up_button_visible['democracy']) ) && ( $foodle_scroll_up_button_visible['democracy'] ) ) foodle_provide_scroll_up_button();

  $foodle_user_id = get_current_user_id();
  $foodle_id = $foodle_this->id;
  $foodle_variables = (array)get_user_meta($foodle_user_id, 'foodle_variables', true);
  $foodle_update = ""; // for use below (AJAX) or not

  if ( isset($foodle_variables[$foodle_id]) ) foreach( $foodle_variables[$foodle_id] as $foodle_private_token => $dummy ) {
    $gl_ajshow_date = $foodle_variables[$foodle_id][$foodle_private_token]["gl_ajshow_date"];
    $gl_ajshow_category = $foodle_variables[$foodle_id][$foodle_private_token]["gl_ajshow_category"];
    $gl_ajdem_categories = $foodle_variables[$foodle_id][$foodle_private_token]["gl_ajdem_categories"];
    $gl_maxlines_single_summary = $foodle_variables[$foodle_id][$foodle_private_token]["gl_maxlines_single_summary"];
    $gl_ajanswerlist = $foodle_variables[$foodle_id][$foodle_private_token]["gl_ajanswerlist"];
    $gl_ajcategorysort = $foodle_variables[$foodle_id][$foodle_private_token]["gl_ajcategorysort"];
    $gl_ajblocksort = $foodle_variables[$foodle_id][$foodle_private_token]["gl_ajblocksort"];
    $gl_ajsolo = $foodle_variables[$foodle_id][$foodle_private_token]["gl_ajsolo"];
    $gl_maxcount = $foodle_variables[$foodle_id][$foodle_private_token]["gl_maxcount"];
    $gl_ajcomments = $foodle_variables[$foodle_id][$foodle_private_token]["gl_ajcomments"];
    if ( ! get_the_ID() === false ) {
      $foodle_the_post_id = get_the_ID();
      $foodle_variables[$foodle_id][$foodle_private_token]["foodle_the_post_id"] = $foodle_the_post_id;
      update_user_meta($foodle_user_id, 'foodle_variables', $foodle_variables);
    } else
      if ( isset(get_user_meta($foodle_user_id, 'foodle_variables', true)[$foodle_id][$foodle_private_token]["foodle_the_post_id"]) ) {
        $foodle_the_post_id = get_user_meta($foodle_user_id, 'foodle_variables', true)[$foodle_id][$foodle_private_token]["foodle_the_post_id"];
    } else {
      $foodle_the_post_id = 0;
    }

    // call the AJAX function
    $not_post = array();
    if ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle_page_post_exclusion']) ) && ( get_option('foodle_settings')['foodle_page_post_exclusion'] != '' ) ) $not_post = (array)get_option('foodle_settings')['foodle_page_post_exclusion'];
    if ( !in_array( $foodle_the_post_id, $not_post ) ) {
      $foodle_update = '
        if ( $("#mf_sw_foodle_sort_content_'.$foodle_private_token.'").length > 0 ) mf_sw_foodle_sort_js('.$foodle_private_token.','.$gl_ajshow_date.','.$gl_ajshow_category.','.$gl_ajdem_categories.','.$gl_maxlines_single_summary.','.$gl_ajanswerlist.','.$gl_ajcategorysort.','.$gl_ajblocksort.','.$gl_ajsolo.','.$gl_maxcount.','.$gl_ajcomments.');';
    }
  }

  // determine the participation rate for the poll and update the related bar graph(s)
  $foodle_participation_data = foodle_get_the_poll_participation_data($foodle_id); // returns false or an array of data
  if ( $foodle_participation_data === false ) { // no such poll id or something's wrong
    $foodle_participation_rate = 101; // indicate an error
    $number_of_users_to_vote = 0; // indicate an error
    $number_of_users_voted = 0; // who could vote anyway here...
    $foodle_roles_concerned = array('foodle-foo-role'); // no existing role (hopefully)
    $foodle_remove_admin = false; // default state
  } else {
    $foodle_participation_rate = $foodle_participation_data['participation_rate'];
    $number_of_users_concerned = $foodle_participation_data['number_of_users_concerned'];
    $number_of_users_to_vote = $foodle_participation_data['number_of_users_to_vote'];
    $number_of_users_voted = $foodle_participation_data['number_of_users_voted'];
    $number_of_unexpected_voters = $foodle_participation_data['number_of_unexpected_voters'];
    $foodle_roles_concerned = $foodle_participation_data['roles_concerned'];
    $foodle_remove_admin = $foodle_participation_data['remove_admin'];
  }

  // prohibit administrators and others to vote if they are not part of the pool of voters
  $current_user_is_excluded = ( ( get_option('foodle_special_functions') ) && ( isset(get_option('foodle_special_functions')[$foodle_user_id]) ) ) ? ( in_array('no-voter',get_option('foodle_special_functions')[$foodle_user_id]) ) : false;
  $current_user_is_allowed_to_vote = ( count(array_intersect((array)wp_get_current_user()->roles, $foodle_roles_concerned)) > 0 );
  if ( ( ( $foodle_remove_admin ) && ( in_array('administrator',(array)wp_get_current_user()->roles ) ) ) || ( ! $current_user_is_allowed_to_vote ) || ( $current_user_is_excluded ) )
    $foodle_disable_to_vote = '
      $("#democracy-'.$foodle_id.'").find("[data-dem-act=\'vote\']").attr("disabled",true);
    ';
  else
    $foodle_disable_to_vote = '';

  // animate the existing related bar graphs and delay this a little bit in order to be robust
  $foodle_animate = '
    setTimeout(function(){ jQuery(".foodle-fill-'.$foodle_id.'").foodle_adjust_bar_graph('.$foodle_participation_rate.',"('.$number_of_users_voted.'/'.$number_of_users_concerned.')",'.$number_of_users_concerned.','.$number_of_unexpected_voters.'); }, 50);
  ';

  // enable to have check and radio buttons in parallel
  $foodle_radio = '
    foodle_radio();
  ';
  $html = str_replace('<form ', '<form id="mf_foodle_form" ', $html); // Mark the Democracy Poll form with a unique ID

  // Check whether to display Democracy Poll for the current user
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['roles_show_democracy'][$foodle_id]) ) )
    $roles_show_democracy = get_option('foodle_dem_categories')['roles_show_democracy'][$foodle_id];
  else
    $roles_show_democracy = false;
  if ( ( ! $roles_show_democracy ) || ( ( $roles_show_democracy ) && ( $current_user_is_allowed_to_vote ) ) )
    // show Democracy Poll
    $foodle_show_or_delete_democracy = '';
  else
    // hide Democracy Poll
    $foodle_show_or_delete_democracy = '
      $(".dem-poll-shortcode").find("#democracy-'.$foodle_id.'").parents(".dem-poll-shortcode").first().unbind().hide();
      $(".dem-archives-shortcode").find("#democracy-'.$foodle_id.'").parents(".dem-elem-wrap").first().unbind().hide();
    ';

  // Start the script
  $foodle_script_start = '
    <script type="text/javascript">
      var $ = jQuery;
    ';

  // replace the original function temporarily to support check and radio buttons in parallel
  $foodle_fnscript = '
      $("#mf_foodle_form").parent().parent().mouseenter( function () {
        ';
  if ( ! get_option('foodle_change_demCollectAnsw')) {
    $foodle_fnscript .= 'foodle_change_demCollectAnsw();'; // Replace the Democracy Poll function, adding mixed polls (checkbox and radio)
    update_option('foodle_change_demCollectAnsw', 'true', 'no');
  }
  $foodle_refresh = __('Refresh','foodle-for-democracy-poll');
  $foodle_refresh_pic = plugin_dir_url(__FILE__).'img/refresh.png';
  $foodle_fnscript .= '
      });
        $.each( $(".dem-label, .dem__radio_label"), function( i, foodle_result_label){
        var foodle_this = $(foodle_result_label);
        mf_label_html = foodle_this.html();
        mf_search = mf_label_html.search("••");
        if ( mf_search != -1 ) {
          mf_label_html = mf_label_html.replace("••", "");
          foodle_this.html(mf_label_html);
        }
      });

      $("#democracy-'.$foodle_id.' .dem-voted-this .dem-label").each(function(){
        if ( $(this).children().last().attr("class") != "democracy-your-vote" )
          $(this).append("<div class=\"democracy-your-vote\">('.__('You voted here','foodle-for-democracy-poll').')</div");
      });

      if ( $("#foodle-democracy-top-spacing-'.$foodle_id.'").length == 0 ) $("#democracy-'.$foodle_id.'").before("<p class=\'foodle-democracy-top-spacing\' id=\'foodle-democracy-top-spacing-'.$foodle_id.'\'></p>");

      $(".democracy .dem-vote").closest(".democracy").removeClass("democracy-results").addClass("democracy-voting");
      $(".democracy .dem-answers").closest(".democracy").removeClass("democracy-voting").addClass("democracy-results");
      $(".democracy").removeClass("democracy-voted").addClass("democracy-not-voted");
      $(".democracy .dem-voted-this").closest(".democracy").removeClass("democracy-not-voted").addClass("democracy-voted");';
  if ( ( $foodle_this->poll->open == 1 ) && ( isset(get_option('foodle_dem_categories')['refresh_button_voted'][$foodle_id])) && ( get_option('foodle_dem_categories')['refresh_button_voted'][$foodle_id]) ) $foodle_fnscript .= '
      $("#democracy-'.$foodle_id.'.democracy-results.democracy-voted .dem-poll-info").append("<button type=\"submit\" margin-top:5px; style=\"float:right; box-shadow:5px 5px 5px SteelBlue; font-size:0.65em;\" class=\"dem-button democracy-refresh-button\" data-dem-act=\"view\">'.$foodle_refresh.'&nbsp;&nbsp;<img src=\"'.$foodle_refresh_pic.'\" width=\"18\"></button>");';
  if ( ( $foodle_this->poll->open == 1 ) && ( isset(get_option('foodle_dem_categories')['refresh_button_not_voted'][$foodle_id])) && ( get_option('foodle_dem_categories')['refresh_button_not_voted'][$foodle_id]) ) $foodle_fnscript .= '
      $("#democracy-'.$foodle_id.'.democracy-results.democracy-not-voted .dem-poll-info").append("<button type=\"submit\" margin-top:5px; style=\"float:right; box-shadow:5px 5px 5px SteelBlue; font-size:0.65em;\" class=\"dem-button democracy-refresh-button\" data-dem-act=\"view\">'.$foodle_refresh.'&nbsp;&nbsp;<img src=\"'.$foodle_refresh_pic.'\" width=\"18\"></button>");
  '; // add foodle-democracy-top-spacing only once in case it doesn't exist, yet, and add some classes for use with CSS

  // End the script
  $foodle_script_end = '
    </script>
  ';

  // Delete the poll voters' IP addresses - if requested for this poll
  if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['delete_poll_IP_addresses'][$foodle_id]) ) )
  if ( get_option('foodle_dem_categories')['delete_poll_IP_addresses'][$foodle_id] ) {
    $wpdb->query("UPDATE {$wpdb->democracy_log} SET ip = NULL WHERE qid = {$foodle_id}");
  }
  return $html.$foodle_script_start.$foodle_show_or_delete_democracy.$foodle_fnscript.$foodle_radio.$foodle_update.$foodle_animate.$foodle_disable_to_vote.$foodle_script_end;
}
add_filter( 'dem_vote_screen', 'foodle_democracy_update', 10, 2 );
add_filter( 'dem_result_screen', 'foodle_democracy_update', 10, 2 );



// Enable a shortcode inside the democracy shortcode (purpose: to allow e.g. 'foodle-link-democracy-poll' shortcode to be used inside the Democracy text field underneath
// the voting/results) and make "From posts" (first string found between <b> and :</b> by RegEx for flexibility upon changes) in [democracy_archives] translatable
function foodle_execute_shortcode_inside_democracy($output, $tag, $attr) {

  if ( ('democracy' == $tag) || ( 'democracy_archives' == $tag ) ) {
    // replace all id="self" occurences by the correct poll id for use with shortcodes inside the Democracy Poll's textarea
    preg_match_all('/(?<=id="democracy-).*?(?=")/i',$output,$foodle_result); // find all Democracy screens (even those in an archive)
    $foodle_strings = array();
    $startpos = 0;
    foreach( $foodle_result[0] as $foodle_id ) {
      $findpos = strpos($output,'id="democracy-'.$foodle_id.'"');
      $foodle_strings[] = substr($output,$startpos,$findpos-$startpos);
      $startpos = $findpos;
    }
    $foodle_strings[] = substr($output,$startpos);
    $count = 0;
    $output = $foodle_strings[0];
    foreach( $foodle_result[0] as $foodle_id ) {
      $count += 1;

      if ( ( get_option('foodle_dem_categories') ) && ( isset(get_option('foodle_dem_categories')['event_auto'][$foodle_id]) ) && ( get_option('foodle_dem_categories')['event_auto'][$foodle_id] ) ) {
        $ics_shortcode_result = do_shortcode('[foodle-create-ics id="'.$foodle_id.'"]');
        $ics_shortcode_result = ( $ics_shortcode_result == "" ) ? "" : "<br>".$ics_shortcode_result."<br><br>";
        $output .= str_replace('<div class="dem-poll-note">',$ics_shortcode_result.'<div class="dem-poll-note">',preg_replace('/(?<=id="|\')self(?="|\')/i',$foodle_id,$foodle_strings[$count]));
      }
      else
        $output .= preg_replace('/(?<=id="|\')self(?="|\')/i',$foodle_id,$foodle_strings[$count]);
    }
  
    if ( 'democracy_archives' == $tag ) {
      $output = do_shortcode($output);
      $output = preg_replace("/(?<=<b>).*?(?=:<\/b>)/",__('Found in posts','foodle-for-democracy-poll'),$output);
    }
    else {
      $output = do_shortcode($output);
    }
    return $output;
  } else {
    return $output;
  }
}
add_filter( 'do_shortcode_tag','foodle_execute_shortcode_inside_democracy', 10, 3 );



// Schedule, unschedule and execute wp_cron jobs for Foodle
// Set a new bi-monthly interval
function foodle_bi_monthly_interval( $schedules ) { 
    $schedules['two_months'] = array(
        'interval' => 60 * 60 * 24 * 30 * 2, // 2 months in seconds
        'display'  => esc_html__('Every second month','foodle-for-democracy-poll' ),
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'foodle_bi_monthly_interval' );
// schedule the wp_cron task if not already done (to be called when needed)
function foodle_schedule_cron() {
  if ( ! wp_next_scheduled( 'foodle_cron_hook' ) ) {
      wp_schedule_event( time(), 'two_months', 'foodle_cron_hook' );
  }
}
// unschedule the wp_cron task (to be called when needed)
function foodle_unschedule_cron() {
  $foodle_timestamp = wp_next_scheduled( 'foodle_cron_hook' );
  wp_unschedule_event( $foodle_timestamp, 'foodle_cron_hook' );
  // set all democracy poll's answer expiry dates to one year from the answer date
  foodle_set_democracy_poll_answer_expiry_dates('vote_date');
}
// this is the very task done every two months
function foodle_execute_cron() {
  // set all democracy poll's answer expiry dates to one year from now
  foodle_set_democracy_poll_answer_expiry_dates('now');
}
add_action( 'foodle_cron_hook', 'foodle_execute_cron' );
// Now do the job as requested
function foodle_set_democracy_poll_answer_expiry_dates($timeframe) {
  global $wpdb;
  $database_prefix = $wpdb->prefix;
  
  if ( ( $timeframe == 'vote_date' ) || ( $timeframe == 'now' ) ) {
    if ( $timeframe == 'now' ) {
      $one_year_timestamp = date_i18n('U') + 60 * 60 * 24 * 365; // one year in seconds from today
      $sql = "UPDATE $wpdb->democracy_log SET expire={$one_year_timestamp}";
      $wpdb->query($sql); 
    } else {
      foreach($wpdb->get_results("SELECT * FROM $wpdb->democracy_log") as $poll_vote ) { // get the relevant poll data
        $poll_voted = $poll_vote->date;
        $poll_logid = $poll_vote->logid;
        $poll_vote_expire = strtotime($poll_voted) + 60 * 60 * 24 * 365;
        $sql = "UPDATE $wpdb->democracy_log SET expire={$poll_vote_expire}  where logid={$poll_logid}";
        $wpdb->query($sql);
      }
    }
  }
}



delete_option('foodle_change_demCollectAnsw'); // Mark an internal Democracy Poll function as not yet amended (used for mixed polls)



// For the time being: Remove an unwanted an not completely understood language file!
unlink(WP_LANG_DIR."/plugins/foodle-for-democracy-poll-de_DE.l10n.php");



// Load the plugin's textdomain to retrieve the translations
function foodle_translations() {
  $domain = 'foodle-for-democracy-poll';
  load_plugin_textdomain( $domain, false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' ); // load WordPress plugin translations with normal logic
 }
add_action( 'init', 'foodle_translations' );



function foodle_translate_global_strings () {
  global $foodle_undefined_error;        // translated
  global $foodle_sorting;                // translated
  global $thanks_for_using_foodle;       // translated
  global $foodle_review;                 // translated
  global $foodle_like_me_1;              // translated
  global $foodle_like_me_2;              // translated
  global $foodle_results_text_default;   // translated
  global $foodle_results_text;           // just the administrator's choice or the default
  global $foodle_bar_graph_text_default; // translated
  global $foodle_bar_graph_text;         // just the administrator's choice or the default
  global $foodle_unknown_user;           // translated  $foodle_icon_comments_yes_wemail_help = " foodle_tooltip_touch='true' foodle_tooltip = '".$foodle_comments_received_wemail_help_text."'";
  
  $foodle_sorting = __('Sorting','foodle-for-democracy-poll'); // default text e.g. for the foodle category column sorting
  $foodle_undefined_error = __('Undefined error','foodle-for-democracy-poll').'!'; // Generic error message used more than once
  $thanks_for_using_foodle = __('Thanks a lot for using Foodle','foodle-for-democracy-poll');
  $foodle_review = __('If you like this plugin, then <a target="_blank" href="https://wordpress.org/support/plugin/foodle-for-democracy-poll/reviews/#new-post">please leave a review</a> for others to see. Many thanks! ','foodle-for-democracy-poll');
  $foodle_like_me_1 = __('In such case, you could as well ','foodle-for-democracy-poll');
  $foodle_like_me_2 = __(' your appreciation...','foodle-for-democracy-poll');
  $foodle_results_text_default = __('Poll results so far','foodle-for-democracy-poll');
  $foodle_bar_graph_text_default = __('Rate of participation','foodle-for-democracy-poll');
  $foodle_unknown_user = __('Unknown User','foodle-for-democracy-poll');

  // Set table headline from option
  if ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle_results_text']) ) && ( get_option('foodle_settings')['foodle_results_text'] != '' ) ) {
    $foodle_results_text = get_option('foodle_settings')['foodle_results_text'];
  } else $foodle_results_text = $foodle_results_text_default;
  // Set bar graph text from option
  if ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle_bar_graph_text']) ) && ( get_option('foodle_settings')['foodle_bar_graph_text'] != '' ) ) {
    $foodle_bar_graph_text = get_option('foodle_settings')['foodle_bar_graph_text'];
  } else $foodle_bar_graph_text = $foodle_bar_graph_text_default;
}
add_action('init', 'foodle_translate_global_strings');



// Change Admin Footer Text for Foodle
function foodle_update_admin_footer_text($content) {
  global $thanks_for_using_foodle;
  if ( strpos(get_current_screen()->base, 'foodle-admin-page') !== false ) {
    remove_all_filters( 'admin_footer_text' );
    return $thanks_for_using_foodle.'!';
  }
  else
    return $content;
}
add_filter( 'admin_footer_text', 'foodle_update_admin_footer_text', 1, 1); // Priority 1 to make it work



// Change Admin Footer Update for Foodle
function foodle_update_admin_footer_version($content) {
  if ( strpos(get_current_screen()->base, 'foodle-admin-page') !== false ) {
    remove_all_filters( 'update_footer' );
    return 'Foodle © 2019-'.wp_date("Y").', Version '.FOODLE_VERSION;
  }
  else
    return $content;
}
add_filter( 'update_footer', 'foodle_update_admin_footer_version', 1, 1); // Priority 1 to make it work



// Enqueue back end "Touch Punch" for touchscreen use and at the same time ensure jquery-ui-sortable is active
function hook_foodle_touch_punch_script( $foodle_hook ) {
    if ( strpos($foodle_hook,'foodle-admin-page') !== false ) { // only in 'Foodle'
    $js_url = plugin_dir_url(__FILE__).'js/foodle_jquery.ui.touch-punch.js';
    wp_register_script( 'foodle-touch-punch-script', $js_url, array('jquery','jquery-ui-core','jquery-ui-sortable','jquery-ui-widget','jquery-ui-mouse'), FOODLE_VERSION, false );
    wp_enqueue_script( 'foodle-touch-punch-script' );
  }
}
add_action( 'admin_enqueue_scripts', 'hook_foodle_touch_punch_script' ); // for the admin area



// Enqueue back end plugin style-file
function add_back_end_foodle_stylesheet( $foodle_hook ) {
  if ( ( strpos($foodle_hook,'foodle-admin-page') !== false ) || ( strpos($foodle_hook,'democracy-poll') !== false ) ) { // only in 'Foodle' and 'Democracy'
    $css_url = plugin_dir_url(__FILE__).'styles/foodle-for-democracy-poll-back-end.css';
    wp_register_style( 'foodle-back-end-css', $css_url, array(), FOODLE_VERSION, 'all' );
    wp_enqueue_style( 'foodle-back-end-css' );
  }
}
add_action( 'admin_enqueue_scripts', 'add_back_end_foodle_stylesheet' ); // for the admin area



// enqueue back end and front end tooltips js
function hook_foodle_tooltips_script() {
  $js_url = plugin_dir_url(__FILE__).'js/foodle_tooltips.js';
  wp_register_script( 'foodle-tooltips-script', $js_url, array('jquery'), FOODLE_VERSION, true ); // true = 'in_footer' to reach Democracy Poll from here
  wp_enqueue_script( 'foodle-tooltips-script' );
}
add_action( 'admin_enqueue_scripts', 'hook_foodle_tooltips_script' ); // for the admin area
add_action( 'wp_enqueue_scripts', 'hook_foodle_tooltips_script' ); // for the front end as well



// enqueue back end and front end comments tooltips js
function hook_foodle_comments_tooltips_script() {
  $js_url = plugin_dir_url(__FILE__).'js/foodle_comments_tooltips.js';
  wp_register_script( 'foodle-comments-tooltips-script', $js_url, array('jquery'), FOODLE_VERSION, true ); // true = 'in_footer' to reach Democracy Poll from here
  wp_enqueue_script( 'foodle-comments-tooltips-script' );
}
add_action( 'admin_enqueue_scripts', 'hook_foodle_comments_tooltips_script' ); // for the admin area
add_action( 'wp_enqueue_scripts', 'hook_foodle_comments_tooltips_script' ); // for the front end as well



// enqueue back end and front end non-voters tooltips js
function hook_foodle_non_voters_tooltips_script() {
  $js_url = plugin_dir_url(__FILE__).'js/foodle_non_voters_tooltips.js';
  wp_register_script( 'foodle-non-voters-tooltips-script', $js_url, array('jquery'), FOODLE_VERSION, true ); // true = 'in_footer' to reach Democracy Poll from here
  wp_enqueue_script( 'foodle-non-voters-tooltips-script' );
}
add_action( 'admin_enqueue_scripts', 'hook_foodle_non_voters_tooltips_script' ); // for the admin area
add_action( 'wp_enqueue_scripts', 'hook_foodle_non_voters_tooltips_script' ); // for the front end as well



// enqueue front end jQuery table2excel script
function hook_foodle_table2excel_script() {
  $js_url = plugin_dir_url(__FILE__).'js/foodle_jquery.table2excel.js';
  wp_register_script( 'foodle-table2excel-script', $js_url, array('jquery'), FOODLE_VERSION, true ); // true = 'in_footer' to reach the Foodle table from here
  wp_enqueue_script( 'foodle-table2excel-script' );
}
//add_action( 'wp_enqueue_scripts', 'hook_foodle_table2excel_script' ); // for the front end



// enqueue back end and front end tooltips style-file including comments tooltips
function hook_foodle_tooltips_stylesheet() {
  $css_url = plugin_dir_url(__FILE__).'styles/foodle-tooltips.css';
  wp_register_style( 'foodle-tooltips-css', $css_url, array(), FOODLE_VERSION, 'all' );
  wp_enqueue_style( 'foodle-tooltips-css' );
}
add_action( 'admin_enqueue_scripts', 'hook_foodle_tooltips_stylesheet' ); // for the admin area
add_action( 'wp_enqueue_scripts', 'hook_foodle_tooltips_stylesheet' ); // for the front end as well



// Enqueue front end plugin style-file
function add_front_end_foodle_stylesheet() {
  $css_url = plugin_dir_url(__FILE__).'styles/foodle-for-democracy-poll-front-end.css';
  wp_register_style( 'foodle-front-end-css', $css_url, array(), FOODLE_VERSION, 'all' );
  wp_enqueue_style( 'foodle-front-end-css' );
}
add_action( 'wp_enqueue_scripts', 'add_front_end_foodle_stylesheet' ); // for the front end



// Enqueue front end plugin script to convert checkboxes marked with &bull; into a radio button
function foodle_hook_radioconvert_script() {
  $js_url = plugin_dir_url(__FILE__).'js/foodle_radio.js';
  wp_register_script( 'foodle_radioconvert', $js_url, array('jquery'), FOODLE_VERSION, false);
  wp_enqueue_script( 'foodle_radioconvert' );
}
add_action( 'wp_enqueue_scripts', 'foodle_hook_radioconvert_script' ); // for the front end



// enqueue back end and front end smoothscroll js
function hook_foodle_smoothscroll_script() {
  $js_url = plugin_dir_url(__FILE__).'js/foodle_smoothscroll.js';
  wp_register_script( 'foodle-smoothscroll-script', $js_url, array('jquery','jquery-ui-core','jquery-effects-core'), FOODLE_VERSION, true ); // true = 'in_footer' to reach anything from here
  wp_enqueue_script( 'foodle-smoothscroll-script' );
}
add_action( 'admin_enqueue_scripts', 'hook_foodle_smoothscroll_script' ); // for the admin area
add_action( 'wp_enqueue_scripts', 'hook_foodle_smoothscroll_script' ); // for the front end as well



// Description: AJAX-Function, generating the sortlist from the first meta field and the regular expression.
function foodle_hook_auto_generate_sortlist_script() {
  $js_url = plugin_dir_url(__FILE__).'js/foodle_auto_sortlist_ajax_file.js';
  wp_register_script( 'foodle_auto_sortlist_ajax_script', $js_url, array('jquery'), FOODLE_VERSION, false );
  wp_enqueue_script( 'foodle_auto_sortlist_ajax_script' );

  wp_localize_script( 'foodle_auto_sortlist_ajax_script', 'foodle_auto_sortlist_ajax_var', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'auto_message' => '*AUTO*'
    )
  );
}
add_action('admin_enqueue_scripts','foodle_hook_auto_generate_sortlist_script'); // just for the back end
// And now the related action
function foodle_auto_generate_sortlist_php() {
  global $foodle_undefined_error;

  $out = $foodle_undefined_error;

  if ( isset($_POST['foodle_metafield']) ) {
    $foodle_metafield = sanitize_text_field($_POST['foodle_metafield']); // The meta field
    $foodle_base_metafield = array_keys((array)get_option('foodle_meta_fields'))[0]; // The base meta field
    $foodle_regexp = get_option('foodle_regex_main')[$foodle_metafield][0];
    $foodle_regrep = ( isset(get_option('foodle_regex_main')[$foodle_metafield][1]) ) ? get_option('foodle_regex_main')[$foodle_metafield][1] : '';
    $replace_limit = ( strpos($foodle_regexp,'/g') === false ) ? 1 : -1;
    $foodle_regexp = str_replace('/g','/',$foodle_regexp);
    $foodle_sortlist_array = explode('<br>',get_option('foodle_meta_defaults_sorting')[$foodle_base_metafield]['sortlist']);
    $foodle_sortlist_array_new = array();
    foreach($foodle_sortlist_array as $foodle_sortlist_item) {
      $foodle_sortlist_item_new = ( $foodle_sortlist_item == '&nbsp;' ) ? '&nbsp;' : preg_replace($foodle_regexp,$foodle_regrep,$foodle_sortlist_item, $replace_limit);
      if ( ( $foodle_sortlist_item_new == '&nbsp;' ) || ( ! in_array($foodle_sortlist_item_new,$foodle_sortlist_array_new) ) ) $foodle_sortlist_array_new[] = $foodle_sortlist_item_new;
    }
    $out = implode('&#13;&#10;',$foodle_sortlist_array_new);
  }

  echo $out;
  die();
}
add_action('wp_ajax_nopriv_foodle_auto_generate_sortlist','foodle_auto_generate_sortlist_php');
add_action('wp_ajax_foodle_auto_generate_sortlist','foodle_auto_generate_sortlist_php');



// enqueue back end email placeholder copy js
function hook_foodle_placeholder_copy_script() {
  $js_url = plugin_dir_url(__FILE__).'js/foodle_email_placeholder_copy.js';
  wp_register_script( 'foodle-email-placeholder-copy-script', $js_url, array('jquery'), FOODLE_VERSION, true );
  wp_localize_script( 'foodle-email-placeholder-copy-script','foodle_CopyI18n',
    array(
      'foodle_defaultTooltip' => __('Click to copy', 'foodle-for-democracy-poll'),
      'foodle_copiedTooltip'  => __('Copied', 'foodle-for-democracy-poll').' 😊',
      'foodle_errorTooltip'   => __('Error!', 'foodle-for-democracy-poll'),
    )
  );
  wp_enqueue_script( 'foodle-email-placeholder-copy-script' );
}
add_action( 'admin_enqueue_scripts', 'hook_foodle_placeholder_copy_script' ); // for the admin area



// enqueue back end email placeholder copy css
function hook_foodle_email_placeholder_copy_stylesheet() {
  $css_url = plugin_dir_url(__FILE__).'styles/foodle_email_placeholder_copy.css';
  wp_register_style( 'foodle-email-placeholder-copy-css', $css_url, array(), FOODLE_VERSION, 'all' );
  wp_enqueue_style( 'foodle-email-placeholder-copy-css' );
}
add_action( 'admin_enqueue_scripts', 'hook_foodle_email_placeholder_copy_stylesheet' ); // for the admin area



// Add the submenu entry and the help tabs...
function add_foodle_admin_menu_items() {
  global $submenu;

  $location = 10;
  if ( isset($submenu['options-general.php']) ) {
    $dem_count = 0;
    $settings_menu = $submenu['options-general.php'];
    foreach($settings_menu as $menu_entry ) { // search the related submenu for Democracy and locate Foodle behind
      $dem_count += 1;
      $found = strpos($menu_entry[2],'democracy-poll'); // check the page slug
      if ( $found !== false ) {
        $location = $dem_count;
        break;
      }
    }
  }
  $foodle_admin_page = add_options_page(
                          'Foodle for Democracy Poll', // page title
                          'Foodle ➤ Democracy', // submenu title
                          'manage_foodle', // required capability (or role)
                          'foodle-admin-page', // page slug foodle-admin-page
                          'foodle_admin_page_callback', // callback function: the main plugin function
                          $location // position behind Democracy
                        );
  add_action( 'load-'.$foodle_admin_page, 'foodle_add_help' ); // Add the help tabs callback function...
}
add_action('admin_menu','add_foodle_admin_menu_items', 2147483647);



// Add the same entry in the WordPress toolbar
function add_foodle_admin_toolbar( WP_Admin_Bar $wp_admin_bar ) {
    global $foodle_roles_metafields;
    global $foodle_roles_sorting;
    global $foodle_roles_sproles;
    global $foodle_roles_email;
    global $foodle_roles_usage;
    global $foodle_roles_settings;
    global $foodle_roles_tips;

    // Capability allowed
    if ( ! current_user_can('manage_foodle') ) return;

    // Case 1: Not coming from Foodle settings
    if ( ! isset($_POST['save_foodle_settings']) ) {
        if ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['show-in-admin-menu-bar']) ) && ( ! get_option('foodle_settings')['show-in-admin-menu-bar'] ) ) return;
        if ( ( ! get_option('foodle_settings') ) || ( ( get_option('foodle_settings') ) && ( ! isset(get_option('foodle_settings')['show-in-admin-menu-bar']) ) ) ) return;
    }
    // Case 2: Coming from Foodle settings
    else {
      if ( ! isset($_POST['show-in-admin-menu-bar']) ) return;
      if ( current_user_can('manage_options') ) { // last line of defence for an administrator privilege
        $foodle_roles_tips = ( isset($_POST['foodle-roles-tips'] ) ) ? true : false;
        $foodle_roles_settings = ( isset($_POST['foodle-roles-settings'] ) ) ? true : false;
        $foodle_roles_usage = ( isset($_POST['foodle-roles-usage'] ) ) ? true : false;
        $foodle_roles_email = ( isset($_POST['foodle-roles-email'] ) ) ? true : false;
        $foodle_roles_sproles = ( isset($_POST['foodle-roles-sproles'] ) ) ? true : false;
        $foodle_roles_sorting = ( isset($_POST['foodle-roles-sorting'] ) ) ? true : false;
        $foodle_roles_metafields = ( isset($_POST['foodle-roles-metafields'] ) ) ? true : false;
      }
    }

    // check first submenu entry
    $foodle_first_admin_tab = 'foodle-admin-page&tab=define-metafields';
    if ( $foodle_roles_tips ) $foodle_first_admin_tab = 'foodle-admin-page&tab=foodle-tips';
    if ( $foodle_roles_settings ) $foodle_first_admin_tab = 'foodle-admin-page&tab=foodle-settings';
    if ( $foodle_roles_usage ) $foodle_first_admin_tab = 'foodle-admin-page&tab=foodle-usage';
    if ( $foodle_roles_email ) $foodle_first_admin_tab = 'foodle-admin-page&tab=edit-email';
    if ( $foodle_roles_sproles ) $foodle_first_admin_tab = 'foodle-admin-page&tab=special-roles-users';
    if ( $foodle_roles_sorting ) $foodle_first_admin_tab = 'foodle-admin-page&tab=metafield-default-sorting';
    if ( ( $foodle_roles_metafields ) || ( current_user_can('manage_options') ) ) $foodle_first_admin_tab = 'foodle-admin-page&tab=define-metafields';

	$wp_admin_bar->add_menu(
      array(
		'id'    => 'foodle-main',
		'parent' => null,
		'group'  => false,
		'title' => 'Foodle ➤ Democracy',
		'href'  => admin_url('options-general.php?page='.$foodle_first_admin_tab),
		'meta' => [
			'title' => 'Plugin: Foodle for Democracy Poll',
        ]
      )
    );
    if  ( ( current_user_can('manage_options') ) || ( $foodle_roles_metafields ) ) $wp_admin_bar->add_menu(
      array(
        'id'    => 'foodle-define-meta',
        'parent' => 'foodle-main',
        'title' => __('Define Metafields','foodle-for-democracy-poll'),
        'href'  => admin_url('options-general.php?page=foodle-admin-page&tab=define-metafields'),
      )
	);
	if ( ( current_user_can('manage_options') ) || ( $foodle_roles_sorting ) ) $wp_admin_bar->add_menu(
      array(
        'id'    => 'metafield-default-sorting',
        'parent' => 'foodle-main',
        'title' => __('Metafield Defaults & Sorting','foodle-for-democracy-poll'),
        'href'  => admin_url('options-general.php?page=foodle-admin-page&tab=metafield-default-sorting'),
      )
    );
    if ( ( current_user_can('manage_options') ) || ( $foodle_roles_sproles ) ) $wp_admin_bar->add_menu( // for administrators only
      array(
        'id'    => 'special-roles-users',
        'parent' => 'foodle-main',
        'title' => __('Special Roles & Users','foodle-for-democracy-poll'),
        'href'  => admin_url('options-general.php?page=foodle-admin-page&tab=special-roles-users'),
      )
    );
    if ( ( current_user_can('manage_options') ) || ( $foodle_roles_email ) ) $wp_admin_bar->add_menu(
      array(
        'id'    => 'edit-email',
        'parent' => 'foodle-main',
        'title' => __('Edit Email','foodle-for-democracy-poll'),
        'href'  => admin_url('options-general.php?page=foodle-admin-page&tab=edit-email'),
      )
    );
    if ( ( current_user_can('manage_options') ) || ( $foodle_roles_usage ) ) $wp_admin_bar->add_menu(
        array(
          'id'    => 'foodle-usage',
          'parent' => 'foodle-main',
          'title' => __('Shortcode Use','foodle-for-democracy-poll'),
          'href'  => admin_url('options-general.php?page=foodle-admin-page&tab=foodle-usage'),
        )
      );
    if ( ( current_user_can('manage_options') ) || ( $foodle_roles_settings ) ) $wp_admin_bar->add_menu( // for administrators only
      array(
        'id'    => 'foodle-settings',
        'parent' => 'foodle-main',
        'title' => __('Foodle Settings','foodle-for-democracy-poll'),
        'href'  => admin_url('options-general.php?page=foodle-admin-page&tab=foodle-settings'),
      )
    );
      if ( ( current_user_can('manage_options') ) || ( $foodle_roles_tips ) ) $wp_admin_bar->add_menu(
      array(
        'id'    => 'foodle-tips',
        'parent' => 'foodle-main',
        'title' => __('Widespread Tips','foodle-for-democracy-poll'),
        'href'  => admin_url('options-general.php?page=foodle-admin-page&tab=foodle-tips'),
      )
    );
}
add_action('admin_bar_menu', 'add_foodle_admin_toolbar', 100);



// Add the help tabs and sidebar here...
function foodle_add_help () {
  global $version;
  global $foodle_review;
  global $foodle_like_me_1;
  global $foodle_like_me_2;

  $mfem_screen = get_current_screen();
  
  // Generic explanations
  $id = 'foodle_gen_ex';
  $title = __('Information','foodle-for-democracy-poll');
  $content  = '<p>'.__('The following \'help\' tabs may be consulted for detailed explanations and hints for their related topic\'s usage.</p>
               <p>More detailed information is available in the <a href="/wp-admin/options-general.php?page=foodle-admin-page&tab=foodle-tips">Tips tab</a> or by activating \'Help-Tooltips\' in the <a href="/wp-admin/options-general.php?page=foodle-admin-page&tab=foodle-settings">Foodle Settings tab</a>.</p>
               <p>Additional information may be found in the FAQs.','foodle-for-democracy-poll').'</p>';
  $content .= '<p>&nbsp;</p>
               <p style="font-size:1.2em;">'.$foodle_review.'</p>
               <p style="font-size:1.2em;">'.$foodle_like_me_1.'<img src="'.plugin_dir_url( __FILE__ ).'img/PayPal-Logo-2019-kl.jpg" height="16" alt="PayPal">'.$foodle_like_me_2.'</p>
               <form action="https://www.paypal.com/donate" method="post" target="_top">
               <input type="hidden" name="hosted_button_id" value="W3V5CKXFJS948" />
               <input type="image" src="https://www.paypalobjects.com/en_US/DK/i/btn/btn_donateCC_LG.gif" border="0" name="submit" title="PayPal - The safer, easier way to pay online!" alt="Donate with PayPal button" />
               <img alt="" border="0" src="https://www.paypal.com/en_DE/i/scr/pixel.gif" width="1" height="1" />
               </form>';

  $mfem_screen->add_help_tab( array( 
   'id' => $id,            // unique id for the tab
   'title' => $title,      // unique visible title for the tab
   'content' => $content   // actual help text
  ) );

  // Foodle Shortcode and email option
  $id = 'foodle_short_code';
  $title = __('Foodle Shortcode and Email Option','foodle-for-democracy-poll');
  $content = '<p>'.__('The Foodle shortcode is used to display the poll results in various ways. It can be used on the same page as the democracy poll shortcode and will be have interactively (AJAX) when voting. However, it can as well be used independently on any page or post.</p>
              <p>You may consult the <a href="/wp-admin/options-general.php?page=foodle-admin-page&tab=foodle-tips">Tips tab</a> for shortcode details.</p>
              <p>For <a href="/wp-admin/options-general.php?page=foodle-admin-page&tab=special-roles-users">selectable viewers</a>, the shortcode provides an automated email reminder option for those who didn\'t vote, yet. The email text can be edited in the <a href="/wp-admin/options-general.php?page=foodle-admin-page&tab=edit-email">related tab</a>. Placeholders are available to configure the email in many ways. This includes name information of the person that will trigger the email (can be anyone of those special viewers having access).','foodle-for-democracy-poll').'</p>';
  $mfem_screen->add_help_tab( array( 
   'id' => $id,            // unique id for the tab
   'title' => $title,      // unique visible title for the tab
   'content' => $content   // actual help text
  ) );

  // Questions & Answers
  $id = 'foodle_q_a';
  $title = __('FAQs','foodle-for-democracy-poll');
  $content = '<p id="foodle-faq-p"></p><script type="text/javascript">jQuery("#foodle-faq-p").load("/wp-admin/plugin-install.php?tab=plugin-information&plugin=foodle-for-democracy-poll&section=faq #section-faq");</script>';
  if ( current_user_can('manage_options') ) $mfem_screen->add_help_tab( array( // will anyway not work for non-admins...
   'id' => $id,            // unique id for the tab
   'title' => $title,      // unique visible title for the tab
   'content' => $content   // actual help text
  ) );
  
  // The help sidebar
  $mfem_sidebar =  '<p style="font-weight:bold;">'.__('Support Hints','foodle-for-democracy-poll').'</p>';
  $mfem_sidebar .= '<p>'.__('For plugin information, please consult the','foodle-for-democracy-poll');
  $mfem_sidebar .= ' <a href="https://de.wordpress.org/plugins/foodle-for-democracy-poll/" target="_blank">';
  $mfem_sidebar .= __('WordPress&nbsp;Plugin&nbsp;Page','foodle-for-democracy-poll').'</a>.</p>';
  $mfem_sidebar .= '<p>'.__('In case of questions or issues, you may use the','foodle-for-democracy-poll');
  $mfem_sidebar .= ' <a href="https://wordpress.org/support/plugin/foodle-for-democracy-poll/" target="_blank">';
  $mfem_sidebar .= __('Plugin&nbsp;Supportpage','foodle-for-democracy-poll').'</a> ';
  $mfem_sidebar .= __('or contact the plugin author directly under','foodle-for-democracy-poll').' <a href="mailto:plugins@finkenberger.net?subject=Foodle for Democracy Poll Plugin Direct Support">';
  $mfem_sidebar .= __('Direct&nbsp;Support','foodle-for-democracy-poll').'</a>.</p>';
  $mfem_sidebar .= '<p>V'.FOODLE_VERSION.'</p>';
  $mfem_screen->set_help_sidebar( $mfem_sidebar );
}



// Adding WordPress plugin action links 
function foodle_add_plugin_action_links( $links ) {
  $foodle_color = '';
  if ( ( get_option('foodle_settings') ) && ( isset(get_option('foodle_settings')['foodle_admin_menu_color']) ) )
    $foodle_color = get_option('foodle_settings')['foodle_admin_menu_color'];
  else
    $foodle_color = '#8CBD5A'; // the default
  return array_merge(
    array(
      'settings' => '<a style="font-size:1.1em; color:'.$foodle_color.'"; href="' . get_bloginfo( 'wpurl' ) . '/wp-admin/options-general.php?page=foodle-admin-page">'.__('Foodle-Settings','foodle-for-democracy-poll').'</a>'
    ),
    $links
  );
}
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'foodle_add_plugin_action_links' );



require('foodle-extra-fields.php'); // add the requested additional fields to each user's profile

require('foodle-foodle-shortcode.php'); // the main [foodle-democracy-poll-list-log] shortcode definition and supporting functions in separate file

require('foodle-link-democracy-shortcode.php'); // the [foodle-link-democracy-poll] shortcode in separate file

require('foodle-database-check-shortcode.php'); // the [foodle-democracy-poll-database-check] shortcode and related dashboard widget in separate file

require('foodle-comments-shortcode.php'); // the [foodle-comments] shortcode in separate file

require('foodle-send-reminder.php'); // email function enqueuing and sending in separate file

require('foodle-display-on-for-roles-shortcode.php'); // the [foodle-display-on-for-roles] shortcode (with separate end tag) to limit enclosed content for specific roles

require('foodle-archive-do-not-show-shortcode.php'); // the [foodle-archive-do-not-show] shortcode (with separate end tag) to not display certain ids in an archive listing

require('foodle-poll-bar-graph-shortcode.php'); // the [foodle-poll-bar-graph] shortcode to display a bar graph for a poll, indicating the percentage of voters that voted

require('foodle-create-ics-shortcode.php'); // the [foodle-create-ics] shortcode to generate an ics file download for storing an event to a calendar

require('foodle-tips.php'); // the foodle tips and detailed explanations



// Check and record the related shortcodes' page/post use and correct/update democracy's "in_posts" entries, which are sometimes not fully correct plus fill the database's 'in_foodles' and 'in_comments' entries
function foodle_check_shortcode_presence($post_id = "", $post = "", $update = "") {
  global $wpdb;

  // delete the old errors
  delete_option('foodle_shortcode_usage_error_pages_posts');

  // Retrieve all except 'inherit' {prefix}posts database entries for all registered post_types
  $foodle_post_statuses = array_keys(get_post_statuses());
  unset($foodle_post_statuses['inherit']);
  $pages_posts_args = array(
    'numberposts' => -1,
    'post_type'   => array_keys(get_post_types()),
    'post_status' => $foodle_post_statuses,
    'orderby'     => 'date',
    'order'       => 'ASC',
  ); // 'orderby date' and 'order ASC' are important to make sure that the first shortcode use stays available for shortcode [foodle-link-democracy-poll]
  $pages_posts = get_posts($pages_posts_args);

  // Initialize variables
  $matches = array();
  $democracy_uses = array();
  $democracy_uses_serial = array();
  $foodle_uses = array();
  $foodle_uses_serial = array();
  $comments_uses = array();
  $comments_uses_serial = array();

  // Delete previous use entries in democracy_q database
  $wpdb->query("UPDATE $wpdb->democracy_q SET in_posts = '', in_foodles = '', in_comments = ''");

  // Initialize error_logs
  $erroneous_uses = array();

  // All related democracy and foodle shortcodes to be recorded at this time
  $shortcodes_search = array('democracy','foodle-democracy-poll-list-log','foodle-comments','foodle-poll-bar-graph','foodle-link-democracy-poll');
  $pattern = get_shortcode_regex($shortcodes_search);

  foreach ($pages_posts as $page_post) {

    if ( preg_match_all( '/'. $pattern .'/s', $page_post->post_content, $matches )
    && array_key_exists( 2, $matches ) ) {
      $shortcode_count  = count( $matches[2] );
      $shortcodes_array = $matches[2];
      $atts_array       = $matches[3];
      for ( $i = 0; $i < $shortcode_count; $i++ ) {
        $shortcode = $shortcodes_array[ $i ];
        $atts      = shortcode_parse_atts( $atts_array[ $i ] );
        if ( ! in_array('id',array_keys($atts)) || ( $atts['id'] == '' ) ) {
          $erroneous_uses[] = sprintf(__('Missing or erroneous poll id for [%s] in pages/posts','foodle-for-democracy-poll'),$shortcode).': <a style="color:darkgreen;" href="'.get_edit_post_link($page_post->ID).'">'.get_the_title($page_post->ID).' ('.$page_post->ID.', id: '.$shortcode_id.')</a>';
        } else {
          $poll_question = '';
          $shortcode_id = $atts['id'];
          if ( is_numeric($shortcode_id) ) {
            $sql = "SELECT * FROM $wpdb->democracy_q where id={$shortcode_id}";
            $poll_question = $wpdb->get_row($sql)->question; // Check whether id exists
          }
          if ( strlen($poll_question) == 0 ) {
            $erroneous_uses[] = sprintf(__('Not existing poll id for [%s] in pages/posts','foodle-for-democracy-poll'),$shortcode).': <a style="color:darkgreen;" href="'.get_edit_post_link($page_post->ID).'">'.get_the_title($page_post->ID).' ('.$page_post->ID.', id: '.$shortcode_id.')</a>';
          } else {
            if ( $shortcode == 'democracy' ) $democracy_uses[$shortcode_id][] = $page_post->ID;
            else if ( $shortcode == 'foodle-democracy-poll-list-log' ) $foodle_uses[$shortcode_id][] = $page_post->ID;
            else if ( $shortcode == 'foodle-comments' ) $comments_uses[$shortcode_id][] = $page_post->ID;
          }
        }
      }
    }
  }

  foreach ( $democracy_uses as $shortcode_id => $shortcode_id_uses) {
      $democracy_uses_serial[$shortcode_id] = implode(',', $shortcode_id_uses);
  }
  foreach ( $foodle_uses as $shortcode_id => $shortcode_id_uses) {
    $foodle_uses_serial[$shortcode_id] = implode(',', $shortcode_id_uses);
  }
  foreach ( $comments_uses as $shortcode_id => $shortcode_id_uses) {
    $comments_uses_serial[$shortcode_id] = implode(',', $shortcode_id_uses);
  }

  $error_database_update = __('Error while trying to update the shortcode use for [%s] in pages/posts','foodle-for-democracy-poll');

  foreach( $democracy_uses_serial as $shortcode_id => $shortcode_id_uses_serial) {
    $sql = "UPDATE $wpdb->democracy_q SET in_posts='{$shortcode_id_uses_serial}' where id={$shortcode_id}";
    $oktest = $wpdb->query($sql); // Correct/update democracy's use entries
    if ( $oktest === false ) $erroneous_uses[] = sprintf($error_database_update,'democracy')." - id: ".$shortcode_id;
  }
  foreach( $foodle_uses_serial as $shortcode_id => $shortcode_id_uses_serial) {
    $sql = "UPDATE $wpdb->democracy_q SET in_foodles='{$shortcode_id_uses_serial}' where id={$shortcode_id}";
    $oktest = $wpdb->query($sql); // Correct/update democracy's use entries
    if ( $oktest === false ) $erroneous_uses[] = sprintf($error_database_update,'foodle-democracy-poll-list-log')." - id: ".$shortcode_id;
  }
  foreach( $comments_uses_serial as $shortcode_id => $shortcode_id_uses_serial) {
    $sql = "UPDATE $wpdb->democracy_q SET in_comments='{$shortcode_id_uses_serial}' where id={$shortcode_id}";
    $oktest = $wpdb->query($sql); // Correct/update democracy's use entries
    if ( $oktest === false ) $erroneous_uses[] = sprintf($error_database_update,'foodle_comments')." - id: ".$shortcode_id;
  }

  $erroneous_uses_democracy_foodle_comments = $erroneous_uses;
  if ( count($erroneous_uses_democracy_foodle_comments) > 0 ) {
    $erroneous_uses_democracy_foodle_comments_html = '<ul style="list-style-type:disc;margin-left:20px;"><li>'.implode('</li><li>',$erroneous_uses_democracy_foodle_comments).'</li></ul>';
    update_option('foodle_shortcode_usage_error_pages_posts', $erroneous_uses_democracy_foodle_comments_html, false);
  }
}
add_action('save_post', 'foodle_check_shortcode_presence', 2147483647, 0); // Upon post save, search the Democracy and Foodle shortcode use and do this late
add_action('dem_poll_inserted', 'foodle_check_shortcode_presence', 2147483647, 0); // Upon Democracy poll save, search the Democracy and Foodle shortcode use and do this late



function foodle_provide_scroll_up_button() {
  global $foodle_help_tooltips;
  global $foodle_scroll_up_button_visible;
  // Show a dynamic scroll up button - before, prevent an unwanted scroll button in the democracy design window
  $foodle_inhibit_democracy_scroll_in_design_backend = ( ( ! $foodle_scroll_up_button_visible['democracy_admin'] ) && ( ! $foodle_scroll_up_button_visible['backend'] ) ) ? "democracy-poll&subpage=design" : "foodle_foo";
  $foodle_inhibit_democracy_scroll_in_texte_backend = ( ( ! $foodle_scroll_up_button_visible['democracy_admin'] ) && ( ! $foodle_scroll_up_button_visible['backend'] ) ) ? "democracy-poll&subpage=l10n" : "foodle_foo";
  $help_scroll_to_top = ( $foodle_help_tooltips ) ? ' foodle_tooltip="'.__('Scroll to top','foodle-for-democracy-poll').'." ' : '';
  echo "<script type='text/javascript' id='foodle_scroll_to_top'>
    var $ = jQuery;
    var foodle_href_check2 = window.location.href;
    if ( ( foodle_href_check2.indexOf('".$foodle_inhibit_democracy_scroll_in_design_backend."') == -1 ) && ( foodle_href_check2.indexOf('".$foodle_inhibit_democracy_scroll_in_texte_backend."') == -1 ) )
      if ( $('html').attr('name') != 'foodle_top' ) {
        $('html').attr('name','foodle_top');
        $('body').append('<a".$help_scroll_to_top." foodle_tooltip_dx=\"-100\" class=\"foodle-smooth-scroll scrollToTopBtn\" id=\"scrollToTopBtn\" foodle_smooth_scroll_duration=\"2000\" foodle_smooth_scroll_effect=\"easeInOutCubic\" foodle_smooth_scroll_offset=\"0\" href=\"#foodle_top\">👆</a>');
        $('head').append('<style>.scrollToTopBtn{position:fixed;bottom:35px;right:35px;z-index:999;opacity:0;transform:translateY(77px);transition: all 0.8s ease;text-align:center;text-decoration:none;background-color:#8Db8c6;border:1px solid #888888;border-radius:4px;cursor:pointer;font-size:30px;line-height:40px;height:40px;width:40px;}.showBtn{opacity:0.9;transform:translateY(0)}</style>');
        $(document).on('scroll',function(){
          var $ = jQuery;
          var scroll_position = $(document).scrollTop();
          if ( scroll_position > ( $(window).height() * 1.5 ))
            $('.scrollToTopBtn').addClass('showBtn');
          else
            $('.scrollToTopBtn').removeClass('showBtn');
        });
      }
  </script>";
}
if ( ( isset($foodle_scroll_up_button_visible['frontend']) ) && ( $foodle_scroll_up_button_visible['frontend'] ) ) add_action('wp_print_footer_scripts', 'foodle_provide_scroll_up_button', 2147483647, 0); // for front end
if ( ( isset($foodle_scroll_up_button_visible['backend']) ) && ( $foodle_scroll_up_button_visible['backend'] ) ) add_action('admin_footer', 'foodle_provide_scroll_up_button', 2147483647, 0); // for back end
//-----------------------------------------
function foodle_remove_scroll_up_button() {
  // Remove the same dynamic scroll up button - just for the Foodle settings to have immediate effect :)
  echo "<script type='text/javascript' id='foodle_scroll_to_top_remove'>
    var $ = jQuery;
    $(document).ready(function(){
      $('html').attr('name','');
      $(document).off('scroll');
      $('.scrollToTopBtn').remove();
    });
  </script>";
}



// *************************************************************************************************************************************************************************************
// **********************************************************************                                       ************************************************************************
// **********************************************************************   The main plugin callback function   ************************************************************************
// **********************************************************************       The main admin functions        ************************************************************************
// **********************************************************************                                       ************************************************************************
// *************************************************************************************************************************************************************************************

require_once('foodle_main_plugin_callback_function.php');

require_once('foodle_main_admin_functions.php');

// *************************************************************************************************************************************************************************************
// **********************************************************************                                       ************************************************************************
// **********************************************************************     The main plugin callback End      ************************************************************************
// **********************************************************************     The main admin functions End      ************************************************************************
// **********************************************************************                                       ************************************************************************
// *************************************************************************************************************************************************************************************






// The success notice as admin_notice...
function foodle_pwx_admin_notice__success($foodle_success_message) {
  ?>
  <div class="notice success notice-success is-dismissible">
    <?php
      echo '<p>&nbsp;</p>';
      echo __('OK','foodle-for-democracy-poll').': '.$foodle_success_message;
      echo '<p>&nbsp;</p>';
    ?>
  </div>
  <?php
}



// The info notice as admin_notice...
function foodle_pwx_admin_notice__info($foodle_info_message) {
    ?>
    <div class="notice info notice-info is-dismissible">
      <?php
        echo '<p>&nbsp;</p>';
        echo __('INFO','foodle-for-democracy-poll').': '.$foodle_info_message;
        echo '<p>&nbsp;</p>';
      ?>
    </div>
    <?php
  }



// The last-chance-cancel warning(s) as admin_notice...
function foodle_pwx_admin_notice__warning($foodle_warning_message) {
    ?>
    <div class="notice warning notice-warning is-dismissible">
      <?php
        echo '<p>&nbsp;</p>';
        echo __('WARNING','foodle-for-democracy-poll').': '.$foodle_warning_message;
        echo '<p>&nbsp;</p>';
      ?>
    </div>
    <?php
  }



  // The defined error notice(s) as admin_notice...
function foodle_pwx_admin_notice__defined_error($foodle_error_message) {
  ?>
  <div class="notice error notice-error is-dismissible">
    <?php
      echo '<p>&nbsp;</p>';
      echo __('ERROR','foodle-for-democracy-poll').': '.$foodle_error_message;
      echo '<p>&nbsp;</p>';
    ?>
  </div>
  <?php
}



// The undefined error notice as admin_notice...
function foodle_pwx_admin_notice__error() {
  ?>
  <div class="notice error notice-error is-dismissible">
    <?php
      echo '<h2 class="mfem-h2">'.__('ERROR: The action was most probably not properly performed!','foodle-for-democracy-poll' ).'</h2>';
    ?>
  </div>
  <?php
}



// Check whether Democracy will keep logs. Otherwise, issue a warning!
function foodle_check_keeping_logs() {
  if ( isset(get_option('democracy_options')['keep_logs']) ) {
    if (! get_option('democracy_options')['keep_logs'] )
      return "<div class='notice error notice-error is-dismissible missing-dem-logs' style='padding-top:10px;padding-bottom:10px;'>".__('<strong>ERROR!</strong><br>Foodle cannot work, as Democracy Poll will not keep voting logs in the database.<br>Please change the related Democracy Poll setting if you want to use Foodle!<br>Storage of IP addresses can be inhibited separately per poll.','foodle-for-democracy-poll')."</div>";
  }
  return "";
}


