<?php
////////////////////////////////////////////////////////////////////////////////

require_once 'lib/abstract_preloaded_regular_screen.php';

////////////////////////////////////////////////////////////////////////////////

class SettingsDialogsDefs
{
	const	quick_config		= 'quick_config';
	const	provider_opts		= 'provider_opts';
	const	plugin_opts			= 'plugin_opts';
	const	customs_ctrl		= 'customs_ctrl';
	const	parental_ctrl		= 'parental_ctrl';
	const	about_plugin		= 'about_plugin';
	const	reset_settings		= 'reset_settings';
	const	history_vers		= 'history_vers';
	const	whats_new			= 'whats_new';
}

////////////////////////////////////////////////////////////////////////////////

class SettingsScreen extends AbstractPreloadedRegularScreen implements UserInputHandler
{
	const ID = 'tv_settings';
	const PLUGIN_VERS_HISTORY_URL = 'http://brigadir.mydune.ru/home_tv/history350%s.txt';
	const FILE_TREEVIEW_MAX_LINES = 6;
	const CUSTOM_OPTS_DIALOG_WIDTH = 1400;

	private	$plugin;
	private	$out_action;
	private	$macro_locations_list = array();
	private	$macro_locations_list_idx;
	private	$sub_locations_list = array();
	private	$sub_locations_list_idx;
	private	$qfilter;
	private	$favorites_enable;
	private	$sdp_root_urls_list;
	private	$sdp_root_urls_list_idx;
	private	$custom_sdp_root_url;
	private	$plugin_cookies_epg;
	private	$plugin_cookies_location;
	private	$plugin_cookies_parental;
	private	$plugin_cookies_tv_archives;
	private	$plugin_cookies_app_version;
	private	$plugin_cookies_playback_dvb;
	private	$plugin_cookies_playback_udp;
	private	$plugin_cookies_playback_http;
	private	$plugin_cookies_playlist_export;
	private	$plugin_cookies_customs_control;
	private	$m3u_fname;
	private	$m3u_file_list;
	private	$m3u_file_list_idx;
	private	$channels_search_delay;
	private	$storages_list;
	private $system_settings;
	private $epg_providers;

	///////////////////////////////////////////////////////////////////////

	private static $show_widget;

	private static $settings_dialog_captions =
		array
		(
			SettingsDialogsDefs::quick_config		=> 'Пошаговый конфигуратор',
			SettingsDialogsDefs::provider_opts		=> 'Выбор локации',
			SettingsDialogsDefs::plugin_opts			=> 'Опции плагина',
			SettingsDialogsDefs::customs_ctrl		=> 'Управление надстройками',
			SettingsDialogsDefs::parental_ctrl		=> 'Родительский контроль',
			SettingsDialogsDefs::about_plugin		=> 'О плагине и авторах',
			SettingsDialogsDefs::reset_settings		=> 'Сброс настроек',
			SettingsDialogsDefs::history_vers		=> 'История версий',
			SettingsDialogsDefs::whats_new			=> 'Что нового',
		);

	private static $tv_archives_stream_type_ops =
		array
		(
			TvArchivePlaybackDefs::auto		=> 'Автовыбор (TSTV+NPVR)',
			TvArchivePlaybackDefs::tstv		=> 'TSTV (Time Shifted TV)',
			TvArchivePlaybackDefs::npvr		=> 'NPVR (Network Personal Video Recorder)',
		);

	private static $plugin_ctrls_hints = //93
		array
		(
			'location_combo'				=> 'Выбор региона (край, область, республика)',
			'sub_location_combo'			=> 'Выбор населенного пункта (весь регион, город, поселок)',
			'sdp_root_url_combo'			=> 'Выбор регионального сервера данных',
			'time_zones_combo'				=> 'Выбор часового пояса (выбранное время должно совпадать |с временем на виджете)',
			'custom_sdp_root_url_field'		=> 'Введите IP-адрес сервера данных. Для доступа к серверу |из приватной сети - требуется настройка маршрутизации в |роутере по IP назначения в локальную сеть провайдера (см. |руководство и примеры на https://forum.mydune.ru)',
			'favorites_enable_btn'			=> 'Включение списка избранных в браузере каналов',
			'tv_archives_btn'				=> 'Включение и выбор параметров воспроизведения архива |телепередач',
			'qfilter_combo'					=> 'Выбор качества подбираемых из множества потоков',
			'channels_search_delay_combo'	=> 'Период автообновления списка каналов (для синхронизации |внутреннего плейлиста с данными провайдера)',
			'epg_enable_btn'				=> 'Включение и настройка электронного телегида (EPG) в |браузере каналов',
			'autoplay_enable_btn'			=> 'Автостарт воспроизведения при запуске плагина',
			'auto_resume_enable_btn'		=> 'Возобновлять воспроизведение после включения плеера. |Воспроизведение запустится только если плеер был выключен|во время воспроизведения (т.е. не останавливая и не выходя|из плагина нажали кнопку питания)',
			'playback_dvb_btn'				=> 'Активация подбора DVB потоков для воспроизведения (выборка |в рамках имеющегося списка). DVB потоки имеет наивысший |приоритет над остальными типами потоков (UDP, HTTP, HLS)',
			'playback_udp_btn'				=> 'Активация подбора и выбор параметров воспроизведения |потоков UDP Multicast. Если у вас не работает прямой эфир |рекомендуется выключить эту опцию',
			'playback_http_btn'				=> 'Здесь можно отрегулировать параметры плеера для режима |воспроизведения',
			'export_m3u_btn'				=> 'Включение экспорта плейлиста плагина в M3U формате. |Экспорт выполняется по завершении процедуры поиска |каналов',
			'check_skin_palette_btn'		=> 'Некоторые темы оформления (скины) могут искажать цвет |текстовых лэйблов, рекомендуется включить опцию для |правильного отображения текста в диалоговых окнах',
			'custom_epg_key'				=> 'Выберите кнопку для показа телегида с полной информацией |о телепередачах, или "Деактивировать управление" чтобы |вернуть стандартные функции кнопкам пульта управления',
			'custom_clock_key'				=> 'Выберите кнопку для показа OSD блока с часами, или |"Деактивировать управление" чтобы вернуть стандартные |функции кнопкам пульта управления',
			'custom_clock_pos'				=> 'Выберите позицию OSD блока с часами на экране телевизора',
			'custom_repeat_key'				=> 'Выберите кнопку возврата к предыдущему каналу. Действие |опции аналогично стандартной функции по кнопке %s, |и расширяет последнюю. Таким образом возврат будет |работать также из кастомного телегида',
			'save_btn'						=> '',
			'close'							=> '',
		);

	private static $on_off_ops =
		array
		(
			ControlSwitchDefs::switch_on	=> 'Включено',
			ControlSwitchDefs::switch_off	=> 'Выключено',
		);

	private static $qfilter_ops =
		array
		(
			QualityDefs::lowest 			=> 'Низкое (только SD)',
			QualityDefs::middle 			=> 'Среднее (SD+HDLQ)',
			QualityDefs::highest 			=> 'Высокое (SD+HDHQ+UHD)',
		);

	private static $epg_font_size_ops =
		array
		(
			PLUGIN_FONT_NORMAL				=> 'Обычный',
			PLUGIN_FONT_SMALL				=> 'Уменьшенный',
		);

	private static $ctrl_keys_ops =
		array
		(
			'' 								=> 'Деактивировать управление',
			GUI_EVENT_KEY_INFO				=> 'Кнопка INFO',
			GUI_EVENT_KEY_SELECT			=> 'Кнопка SELECT',
			GUI_EVENT_KEY_TOP_MENU			=> 'Кнопка TOP MENU',
			GUI_EVENT_KEY_POPUP_MENU		=> 'Кнопка POPUP MENU',
			GUI_EVENT_KEY_DUNE				=> 'Кнопка DUNE',
			GUI_EVENT_KEY_A_RED				=> 'Кнопка A-RED',
			GUI_EVENT_KEY_B_GREEN			=> 'Кнопка B-GREEN',
			GUI_EVENT_KEY_C_YELLOW			=> 'Кнопка C-YELLOW',
			GUI_EVENT_KEY_D_BLUE			=> 'Кнопка D-BLUE',
			GUI_EVENT_KEY_CLEAR				=> 'Кнопка CLEAR',
			GUI_EVENT_KEY_SETUP				=> 'Кнопка SETUP',
			GUI_EVENT_KEY_EJECT				=> 'Кнопка EJECT',
			GUI_EVENT_KEY_URL				=> 'Кнопка URL',
			GUI_EVENT_KEY_SEARCH			=> 'Кнопка SEARCH',
		);

	private static $http_stream_type_ops =
		array
		(
			HttpStreamsDefs::hls_abs		=> 'HLS c адаптивным битрейтом (ABS)',
			HttpStreamsDefs::hls_cbr		=> 'HLS c постоянным битрейтом (CBR)',
			HttpStreamsDefs::mpd_abs		=> 'MpegDASH c адаптивным битрейтом (ABS)',
		);

	private static $clock_pos_ops =
		array
		(
			'120,80'	=> 'Левый верхний угол',
			'1550,80'	=> 'Правый верхний угол',
			'120,920'	=> 'Левый нижний угол',
			'1550,920'	=> 'Правый нижний угол',
		);

	private static $time_zones_ops =
		array
		(
			'43200' 	=> 'GMT -12:00 (%s)',
			'39600' 	=> 'GMT -11:00 (%s)',
			'36000' 	=> 'GMT -10:00 (%s)',
			'32400' 	=> 'GMT -09:00 (%s)',
			'28800' 	=> 'GMT -08:00 (%s)',
			'25200' 	=> 'GMT -07:00 (%s)',
			'21600' 	=> 'GMT -06:00 (%s)',
			'18000' 	=> 'GMT -05:00 (%s)',
			'14400' 	=> 'GMT -04:00 (%s)',
			'12600' 	=> 'GMT -03:30 (%s)',
			'10800' 	=> 'GMT -03:00 (%s)',
			'7200' 		=> 'GMT -02:00 (%s)',
			'3600' 		=> 'GMT -01:00 (%s)',
			'0' 		=> 'GMT 00:00 (%s)',
			'-3600' 	=> 'GMT +01:00 (%s)',
			'-7200' 	=> 'GMT +02:00 (%s)',
			'-10800' 	=> 'GMT +03:00 (%s)',
			'-12600' 	=> 'GMT +03:30 (%s)',
			'-14400' 	=> 'GMT +04:00 (%s)',
			'-16200' 	=> 'GMT +04:30 (%s)',
			'-18000' 	=> 'GMT +05:00 (%s)',
			'-19800' 	=> 'GMT +05:30 (%s)',
			'-20700' 	=> 'GMT +05:45 (%s)',
			'-21600' 	=> 'GMT +06:00 (%s)',
			'-23400' 	=> 'GMT +06:30 (%s)',
			'-25200' 	=> 'GMT +07:00 (%s)',
			'-28800' 	=> 'GMT +08:00 (%s)',
			'-32400' 	=> 'GMT +09:00 (%s)',
			'-34200' 	=> 'GMT +09:30 (%s)',
			'-36000' 	=> 'GMT +10:00 (%s)',
			'-39600' 	=> 'GMT +11:00 (%s)',
			'-43200' 	=> 'GMT +12:00 (%s)',
			'-46800' 	=> 'GMT +13:00 (%s)',
		);

	private static $http_buff_size_ms_ops =
		array
		(
			'300' 		=> '300 мс',
			'500' 		=> '500 мс',
			'700' 		=> '700 мс',
			'1000' 		=> '1000 мс',
			'1500' 		=> '1500 мс',
			'2000' 		=> '2000 мс',
			'3000' 		=> '3000 мс',
			'5000' 		=> '5000 мс (по умолчанию)',
			'7000'		=> '7000 мс',
			'10000'		=> '10000 мс',
		);

	private static $udpxy_buff_size_ops =
		array
		(
			'300' 		=> '300 мс',
			'500' 		=> '500 мс',
			'700' 		=> '700 мс',
			'1000' 		=> '1000 мс (по умолчанию)',
			'1500' 		=> '1500 мс',
			'2000' 		=> '2000 мс',
			'3000' 		=> '3000 мс',
			'5000'		=> '5000 мс',
		);

	private static $channels_search_delay_ops =
		array
		(
			'0' 		=> 'Никогда',
			'86400' 	=> '1 день',
			'259200' 	=> '3 дня',
			'604800' 	=> '1 неделя',
			'1209600'	=> '2 недели',
			'2419200'	=> '4 недели',
		);

	private static $step_by_step_wizard_answer_ops =
		array
		(
			3 =>	array
					(
						'adsl' 			=> 'До 8 Мбит/с (ADSL)',
						'adsl2' 		=> 'До 20 Мбит/с (ADSL2/2+)',
						'fttx' 			=> 'Свыше 20 Мбит/с (FTTx/ETTH)',
					),
		);

	private static $reset_settings_ops =
		array
		(
			'clear_epg_cache'						=> 'Очистить кэш телепрограммы',
			'clear_data_cache'						=> 'Очистить кэш данных',
			'reset_settings'						=> 'Сбросить настройки',
			'reset_settings_and_clear_data_cache'	=> 'Полный сброс (настройки и кэш данных)',
		);

	///////////////////////////////////////////////////////////////////////

	private static function cmp_locations($a, $b)
	{
		return
			strnatcmp(
				preg_match('/(.*)\s+\((.*)\)/u', $a, $matches)? $matches[2] . ' ' . $matches[1] : $a,
				preg_match('/(.*)\s+\((.*)\)/u', $b, $matches)? $matches[2] . ' ' . $matches[1] : $b);
	}

	private static function GET_TV_PLUGIN_SETTINGS_FOLDER_VIEW($rows, $ver_info = PHP_EOL, $show_widget = false)
	{
		$content_box_y = ($rows > 6)? 65 : 100;
		$content_box_height = ($rows > 6)? 860 : 755;

		return
			array
			(
				array
				(
					PluginRegularFolderView::async_icon_loading => false,
					PluginRegularFolderView::view_params =>
						array
						(
							FolderViewParams::num_cols => 1,
							FolderViewParams::num_rows => $rows,
							FolderViewParams::paint_icon_selection_box=> true,
							FolderViewParams::paint_path_box => false,
							FolderViewParams::paint_widget => $show_widget,
							FolderViewParams::paint_scrollbar => false,
							FolderViewParams::paint_help_line => true,
							FolderViewParams::paint_details => false,
							FolderViewParams::paint_content_box_background => false,
							FolderViewParams::content_box_x => 460,
							FolderViewParams::content_box_y => $content_box_y,
							FolderViewParams::content_box_width => 930,
							FolderViewParams::content_box_height => $content_box_height,
							FolderViewParams::icon_badge_box_height => 105,
							FolderViewParams::paint_icon_badge_box => true,
							FolderViewParams::hidden_badge_box => false,
							FolderViewParams::background_path=> 'plugin_file://img/bg/main_screen_plugin_settings.png',
							FolderViewParams::background_order => 0,
							FolderViewParams::optimize_full_screen_background => true,
							FolderViewParams::icon_selection_box_height => 105,
							FolderViewParams::extra_content_objects => 'label{x=-308}{y=' . (($rows > 6)? 913 : 878) . '}{color=' . DEF_LABEL_TEXT_COLOR_DARKGRAY2 . '}{text=Версия: '.$ver_info.'}label{x=-310}{y=' . (($rows > 6)? 911 : 876) . '}{color=' . DEF_LABEL_TEXT_COLOR_GOLD . '}{text=Версия: '.$ver_info.'}',
						),
					PluginRegularFolderView::base_view_item_params =>
						array
						(
							FolderViewItemParams::item_paint_icon => true,
							FolderViewItemParams::item_layout => HALIGN_LEFT,
							FolderViewItemParams::icon_valign => VALIGN_CENTER,
							FolderViewItemParams::icon_margin_right => 1000,
							FolderViewItemParams::item_override_default_badge => true,
							FolderViewItemParams::item_badge_icon_path => 'plugin_file://img/button_blue.png',
							FolderViewItemParams::item_caption_font_size => FONT_SIZE_NORMAL,
							FolderViewItemParams::item_caption_dx => 230,
						),
					PluginRegularFolderView::not_loaded_view_item_params => array()
				),
			);
	}

	public static function get_media_url_str($show_widget = false)
	{
		self::$show_widget = $show_widget;
		return self::ID;
	}

	public static function get_dialog_caption($dialog_type)
	{
		return
			self::$settings_dialog_captions[$dialog_type];
	}

	///////////////////////////////////////////////////////////////////////

	private function get_plugin_settings_folder_views($show_widget, &$plugin_cookies)
	{
		return
			self::GET_TV_PLUGIN_SETTINGS_FOLDER_VIEW(7, $this->plugin->app_version, $show_widget);
	}

	private function get_locations_list()
	{
		$list = array();

		foreach ($this->sub_locations_list as $value)
			$list += $value;

		uasort($list, 'self::cmp_locations');

		return $list;
	}

	private function get_time_zones_list()
	{
		$local_ts = time();

		foreach (self::$time_zones_ops as $key => $value)
			$list[$key] = sprintf($value, strftime('%H:%M', $local_ts - $key));

		return $list;
	}

	private function get_reset_settings_dialog_controls_defs(&$add_params)
	{
		ControlFactory::add_vgap($defs, 20);

		if ($add_params['settings_was_reset'] || $add_params['data_cache_was_clear'] || $add_params['epg_cache_was_clear'])
		{
			if ($add_params['settings_was_reset'])
			{
				ControlFactory::add_smart_label($defs, null, '<gap width=40/><text>Настройки плагина сброшены к значениям</text>');
				ControlFactory::add_vgap($defs, -24);
				ControlFactory::add_smart_label($defs, null, '<gap width=300/><text>по умолчанию.</text>');
			}

			if ($add_params['data_cache_was_clear'])
				ControlFactory::add_smart_label($defs, null, '<gap width=140/><text>Кэш данных полностью очищен.</text>');

			if ($add_params['epg_cache_was_clear'])
				if ($add_params['epg_cache_clear_error'])
				{
					ControlFactory::add_smart_label($defs, null, '<gap width=8/><text color=' . DEF_LABEL_TEXT_COLOR_CORAL . '>Процедура очистки памяти прервана ошибкой!</text>');
					ControlFactory::add_vgap($defs, -24);
					ControlFactory::add_smart_label($defs, null, '<gap width=8/><text color=' . DEF_LABEL_TEXT_COLOR_CORAL . '>Файлов всего: ' . $add_params['epg_cache_files_count'] . ' (' . str_replace('.', ',', ($add_params['epg_cache_used_bytes'] > 999999)? round($add_params['epg_cache_used_bytes'] / 1000000, 1) . ' МБ' : (($add_params['epg_cache_used_bytes'] > 999)? round($add_params['epg_cache_used_bytes'] / 1000, 1) . ' КБ' : $add_params['epg_cache_used_bytes'] . ' Байт')) . ').</text>');
				}
				else
				{
					ControlFactory::add_smart_label($defs, null, '<gap width=20/><text>Кэш телепрограммы полностью очищен.</text>');
					if ($add_params['epg_cache_files_count'] > 0)
					{
						ControlFactory::add_vgap($defs, -24);
						ControlFactory::add_smart_label($defs, null, '<gap width=20/><text>Удалено файлов: ' . $add_params['epg_cache_files_count'] . ' (' . str_replace('.', ',', ($add_params['epg_cache_used_bytes'] > 999999)? round($add_params['epg_cache_used_bytes'] / 1000000, 1) . ' МБ' : (($add_params['epg_cache_used_bytes'] > 999)? round($add_params['epg_cache_used_bytes'] / 1000, 1) . ' КБ' : $add_params['epg_cache_used_bytes'] . ' Байт')) . ').</text>');
					}
					else
						ControlFactory::add_vgap($defs, 45);
				}

			if ($add_params['settings_was_reset'])
			{
				ControlFactory::add_vgap($defs, 20);
				ControlFactory::add_smart_label($defs, null, '<gap width=130/><text color=' . DEF_LABEL_TEXT_COLOR_YELLOW . '>Медиаплеер будет перезагружен!</text>');
			}
			else if ($add_params['data_cache_was_clear'])
			{
				ControlFactory::add_vgap($defs, 20);
				ControlFactory::add_smart_label($defs, null, '<gap width=100/><text color=' . DEF_LABEL_TEXT_COLOR_YELLOW . '>Системная оболочка медиаплеера</text>');
				ControlFactory::add_vgap($defs, -24);
				ControlFactory::add_smart_label($defs, null, '<gap width=240/><text color=' . DEF_LABEL_TEXT_COLOR_YELLOW . '>будет перезагружена!</text>');
			}
			else
				ControlFactory::add_vgap($defs, 44);

			ControlFactory::add_vgap($defs, 40);
			ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'reset_settings_apply_btn', 'ОК', 350);
		}
		else
		{
			ControlFactory::add_combobox($defs, $this, null, 'ops_selector_combo', null, $add_params['ops_selector_combo'], self::$reset_settings_ops, 900, true);
			ControlFactory::add_vgap($defs, 60);
			ControlFactory::add_button($button_defs, $this, null, 'reset_settings_apply_btn', null, 'Применить', 350);
			ControlFactoryExt::add_button_centered($defs, $button_defs, 900);
			ControlFactory::add_close_dialog_button($button_defs, 'Отмена', 350);
		}

		ControlFactoryExt::add_button_centered($defs, $button_defs, 900);
		ControlFactory::add_vgap($defs, 10);

		return $defs;
	}

	private function check_network_source($url)
	{
		return true;

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_USERAGENT, HTTP_USER_AGENT);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
		curl_setopt($ch, CURLOPT_VERBOSE, false);
		curl_setopt($ch, CURLOPT_TIMEOUT, 6);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSLVERSION, 3);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_NOBODY, true);

		hd_print("HTTP fetching '$url'...");

		curl_exec($ch);

		$err = curl_error($ch);

		if (!empty($err))
		{
			hd_print('HTTP request failed, CURL errno: ' . curl_errno($ch) . ' (' . curl_error($ch) . ')');
			curl_close($ch);
			return false;
		}

		$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);

		return
			in_array($http_code, array(200, 406));
	}

	private function refresh_list_files($path = '')
	{
		$_path = trim((strpos($path, '/..') !== false)? dirname(dirname($path)) : $path, '/');;
		$is_dir_selected = is_dir(DUNE_MOUNTED_STORAGES_PATH . $_path);

		if ($is_dir_selected)
		{
			$_path .= '/';
			$this->m3u_file_list_idx = $_path;
		}
		else
		{
			$this->m3u_file_list_idx = $_path;
			$_path = dirname($_path) . '/';
		}

		$this->m3u_file_list = array();

		if (($_path == '/') || ($_path == './'))
		{
			if ($this->m3u_file_list_idx <> '_create_new_file_')
				$this->m3u_file_list_idx = '';

			$this->m3u_file_list = $this->storages_list['list'];
			return;
		}
		else
			$this->m3u_file_list[$_path . '../'] = '..';

		$this->m3u_file_list['_create_new_file_'] = '<Новый файл>';
		$dir_list = scandir(DUNE_MOUNTED_STORAGES_PATH . $_path);

		if ($dir_list !== false)
		{
			foreach ($dir_list as $i => $dir)
			{
				if (($dir == '.') || ($dir == '..'))
				{
					unset($dir_list[$i]);
					continue;
				}

				if (is_dir(DUNE_MOUNTED_STORAGES_PATH . $_path . $dir))
				{
					$this->m3u_file_list[$_path . $dir] = $dir . '/';
					if ($is_dir_selected) {
						$is_dir_selected = false;
					}
					unset($dir_list[$i]);
				}
			}

			foreach ($dir_list as $file)
			{
				$this->m3u_file_list[$_path . $file] = $file;

				if ($is_dir_selected)
					$is_dir_selected = false;
			}
		}
	}

	private function get_epg_providers_arr()
	{
		if (is_array($this->epg_providers))
		{
			$parsers_names = $this->plugin->epg->get_parsers_names();
			$excluded = $epg_providers = array();

			foreach($this->epg_providers as $idx => $provider_idx)
			{
				if (isset($parsers_names[$provider_idx]))
				{
					$arr[$idx]['priority_service_idx'] = $provider_idx;
					$arr[$idx]['services_list'][$provider_idx] = isset($parsers_names[$provider_idx])? $parsers_names[$provider_idx] . " ($provider_idx)" : $provider_idx;
					$epg_providers[] = $provider_idx;
					$excluded[$provider_idx] = $idx;

					foreach($this->epg_providers as $epg_provider_id)
						if (!isset($excluded[$epg_provider_id]) && isset($parsers_names[$epg_provider_id]))
							$arr[$idx]['services_list'][$epg_provider_id] = isset($parsers_names[$epg_provider_id])? $parsers_names[$epg_provider_id] . " ($epg_provider_id)" : $epg_provider_id;
				}
			}

			$this->epg_providers = $epg_providers;
		}

		return
			isset($arr)? $arr : array();
	}

	private function get_epg_dialog_controls_defs(&$add_params)
	{
		ControlFactory::add_vgap($defs, 10);
		ControlFactory::add_button($defs, $this, null, 'ext_epg_enable_btn', 'Расширенный телегид:', self::$on_off_ops[$add_params['ext_epg_enable']], self::CUSTOM_OPTS_DIALOG_WIDTH, false);
		ControlFactory::add_vgap($defs, -65);
		ControlFactory::add_smart_label($defs, null,  '<gap width=1154/><icon>' . PLUGIN_IMG_PATH . '/' . $add_params['ext_epg_enable'] . '.png</icon>');
		ControlFactory::add_button($defs, $this, null, 'epg_fill_enable_btn', 'Заполнять всегда:', self::$on_off_ops[$add_params['epg_fill_enable']], self::CUSTOM_OPTS_DIALOG_WIDTH, false);
		ControlFactory::add_vgap($defs, -65);
		ControlFactory::add_smart_label($defs, null,  '<gap width=1154/><icon>' . PLUGIN_IMG_PATH . '/' . $add_params['epg_fill_enable'] . '.png</icon>');
		ControlFactory::add_combobox($defs, $this, null, 'epg_font_size_combo', 'Текст в браузере:', $add_params['epg_font_size'], self::$epg_font_size_ops, self::CUSTOM_OPTS_DIALOG_WIDTH, true);
		ControlFactory::add_vgap($defs, 30);

		$epg_providers = $this->get_epg_providers_arr();

		foreach($epg_providers as $idx => $data)
		{
			ControlFactory::add_combobox($defs1, $this, null, "epg_service_{$idx}_combo", '', $data['priority_service_idx'], $data['services_list'], self::CUSTOM_OPTS_DIALOG_WIDTH - 660, true);
			ControlFactory::add_vgap($defs1, -69);
			ControlFactory::add_smart_label($defs1, null,  '<text color=' . DEF_LABEL_TEXT_COLOR_SILVER . ">  Приоритет $idx" . (empty($idx)? ' (высший)' : (($idx < (count($epg_providers) - 1))? '' : ' (низший)')) . '</text>');
		}

		if (count($epg_providers))
		{
			ControlFactory::add_vgap($defs1, 20);
			ControlFactoryExt::add_group_box($defs, $defs1, 'Приоритет источников при автовыборе', self::CUSTOM_OPTS_DIALOG_WIDTH - 150);
			ControlFactory::add_vgap($defs, 20);
		}

		ControlFactory::add_vgap($defs, 20);
		ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'epg_dialog_on_btn', ($add_params['epg_enabled'] == ControlSwitchDefs::switch_on)? 'Применить' : 'Включить', 400);
		ControlFactoryExt::add_button_centered($defs, $button_defs, 1320);
		ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'epg_dialog_off_btn', ($add_params['epg_enabled'] == ControlSwitchDefs::switch_on)? 'Выключить' : 'Отмена', 400);
		ControlFactoryExt::add_button_centered($defs, $button_defs, 1320);
		ControlFactory::add_vgap($defs, 10);

		return $defs;
	}

	private function get_tv_archives_dialog_controls_defs(&$add_params)
	{
		ControlFactory::add_vgap($defs, 15);
		ControlFactory::add_combobox($defs, $this, null, 'tv_archives_stream_type_combo', 'Воспроизводить потоки:', $add_params['tv_archives_playback_stream_type'], self::$tv_archives_stream_type_ops, self::CUSTOM_OPTS_DIALOG_WIDTH, true);
		ControlFactory::add_smart_label($defs, null,  '<text color=' . DEF_LABEL_TEXT_COLOR_SILVER . '>Перегружать поток</text>');
		ControlFactory::add_vgap($defs, -24);
		ControlFactory::add_smart_label($defs, null,  '<text color=' . DEF_LABEL_TEXT_COLOR_SILVER . '>при возобновлении</text>');
		ControlFactory::add_vgap($defs, -24);
		ControlFactory::add_button($defs, $this, null, 'tv_archives_reload_when_resume_btn', 'воспроизведения:', self::$on_off_ops[$add_params['tv_archives_reload_when_resume']], self::CUSTOM_OPTS_DIALOG_WIDTH, false);
		ControlFactory::add_vgap($defs, -65);
		ControlFactory::add_smart_label($defs, null,  '<gap width=1224/><icon>' . PLUGIN_IMG_PATH . '/' . $add_params['tv_archives_reload_when_resume'] . '.png</icon>');
		ControlFactory::add_vgap($defs, 40);
		ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'tv_archives_on_btn', ($add_params['tv_archives_enabled'] == ControlSwitchDefs::switch_on)? 'Применить' : 'Включить', 400);
		ControlFactoryExt::add_button_centered($defs, $button_defs, 1320);
		ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'tv_archives_off_btn', ($add_params['tv_archives_enabled'] == ControlSwitchDefs::switch_on)? 'Выключить' : 'Отмена', 400);
		ControlFactoryExt::add_button_centered($defs, $button_defs, 1320);
		ControlFactory::add_vgap($defs, 10);

		return $defs;
	}

	private function get_playback_hls_dialog_controls_defs(&$add_params)
	{
		ControlFactory::add_vgap($defs, 5);
		//ControlFactory::add_combobox($defs, $this, null, 'http_stream_type_combo', 'Предпочитать потоки', $this->plugin_cookies_playback_http->hls_bs_prefer, self::$http_stream_type_ops, self::CUSTOM_OPTS_DIALOG_WIDTH, true);
		ControlFactory::add_combobox($defs, $this, null, 'http_buff_size_ms_combo', 'Размер буфера', $this->plugin_cookies_playback_http->buff_size_ms, self::$http_buff_size_ms_ops, self::CUSTOM_OPTS_DIALOG_WIDTH, true);
		ControlFactory::add_button($defs, $this, null, 'http_secury_btn', 'Запрет HTTP Secury', self::$on_off_ops[$this->plugin_cookies_playback_http->secury_disable], self::CUSTOM_OPTS_DIALOG_WIDTH, false);
		ControlFactory::add_vgap($defs, -65);
		ControlFactory::add_smart_label($defs, null, '<gap width=' . (self::CUSTOM_OPTS_DIALOG_WIDTH - 245) . '/><icon>' . PLUGIN_IMG_PATH . "/{$this->plugin_cookies_playback_http->secury_disable}.png</icon>");
		ControlFactory::add_vgap($defs, 50);
		ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'playback_hls_enabled_on_btn', 'Применить', 400);
		ControlFactoryExt::add_button_centered($defs, $button_defs, 1250);
		ControlFactory::add_close_dialog_button($button_defs, 'Отмена', 400);
		//ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'playback_hls_enabled_off_btn', ($add_params['playback_http_enabled'] == ControlSwitchDefs::switch_on)? 'Выключить' : 'Отмена', 400);
		ControlFactoryExt::add_button_centered($defs, $button_defs, 1250);

		ControlFactory::add_vgap($defs, 10);

		return $defs;
	}

	private function get_export_m3u_dialog_controls_defs(&$add_params)
	{
		$btn_cancel = true;
		ControlFactory::add_vgap($defs, 5);

		if (empty($this->m3u_file_list))
		{
			ControlFactory::add_vgap($defs, 10);
			ControlFactory::add_multiline_label($defs, null, "Не найдено ни одного локального хранилища!\n\nПожалуйста, подключите локальный накопитель к медиаплееру и повторите попытку.", 5);
			ControlFactory::add_vgap($defs, 50);
		}
		else
		{
			if ($this->m3u_file_list_idx == '_create_new_file_')
			{
				ControlFactory::add_label($defs, null, 'Имя нового файла:');
				ControlFactory::add_text_field($defs, $this, null, 'm3u_fname_field', null, $this->m3u_fname, false, false, false, true, 1390, true, false);
			}
			else
			{
				ControlFactory::add_label($defs, null, 'Выбор файла для сохранения плейлиста:');
				ControlFactory::add_combobox($defs, $this, null, 'm3u_dir_list', null, $this->m3u_file_list_idx, $this->m3u_file_list, 1390, true);
			}

			if ($add_params['path_not_to_file'])
			{
				ControlFactory::add_vgap($defs, 110);
				ControlFactory::add_smart_label($defs, null, '<gap width=305/><text color=' . DEF_LABEL_TEXT_COLOR_YELLOW . '>Невозможно применить настройки!</text>');

				if ($this->m3u_file_list_idx == '_create_new_file_')
					ControlFactory::add_multiline_label($defs, null, "Файл еще не создан. Пожалуйста, нажмите ENTER по завершении ввода имени файла.", 5);
				else
					ControlFactory::add_multiline_label($defs, null, "Вы должны указать файл, в который будет записан плейлист. Пожалуйста, выберите cуществующий файл или создайте новый.", 5);

				ControlFactory::add_vgap($defs, 122);
			}
			else
			{
				ControlFactory::add_smart_label($defs, null, '<icon>' . PLUGIN_IMG_PATH . '/treeview.png</icon>');
				ControlFactory::add_vgap($defs, -59);
				$path = trim(str_replace('../', '', $this->m3u_file_list_idx), '/');

				if ($path == '_create_new_file_')
					$path = trim(str_replace('../', '', $this->plugin_cookies_playlist_export->path_m3u), '/');

				$path_arr = explode('/', $path);
				$s = self::FILE_TREEVIEW_MAX_LINES;
				$c = count($path_arr);
				$path = '';
				$n = 0;

				foreach ($path_arr as $i => $dir)
				{
					if (empty($dir))
						continue;

					if (empty($path))
					{
						$drive = '';

						foreach ($this->storages_list['names'] as $k => $v)
						{
							if ($v == $dir)
							{
								$drive = $this->storages_list['aliases'][$k] . ((empty($this->storages_list['labels'][$k]))? '' : ' (' . $this->storages_list['labels'][$k] . ')');
								break;
							}
						}

						ControlFactory::add_smart_label($defs, null, '<gap width=20/><icon>' . PLUGIN_IMG_PATH . '/drive.png</icon><text size=small> ' . $drive . '</text>');
						$btn_cancel = true;
					}
					else
					{
						if ((($c - $i + intval(!empty($n))) > self::FILE_TREEVIEW_MAX_LINES))
						{
							if (empty($n))
							{
								ControlFactory::add_smart_label($defs, null, '<gap width=50/><icon>' . PLUGIN_IMG_PATH . '/pass.png</icon><text size=small> </text>');
								ControlFactory::add_vgap($defs, -34);
							}
							$n++;
							$path .= '/' . $dir;
							continue;
						}

						$btn_cancel = is_dir(DUNE_MOUNTED_STORAGES_PATH . "$path/$dir");
						ControlFactory::add_smart_label($defs, null, '<gap width=' . (20 + 35*($i - $n + intval(!empty($n)))) . '/><icon>' . PLUGIN_IMG_PATH . ($btn_cancel? '/folder.png' : '/file.png') . '</icon><text size=small>' . $dir . '</text>');
					}

					ControlFactory::add_vgap($defs, -34);
					$path .= '/' . $dir;
					$s--;
				}

				ControlFactory::add_vgap($defs, 35*$s + 50 + (empty($n)? 35 : 0));
				ControlFactory::add_vgap($defs, 40);
				ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'export_to_m3u_on_btn', 'Включить', 400);
				ControlFactoryExt::add_button_centered($defs, $button_defs, 1250);
			}
		}

		ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'export_to_m3u_off_btn', (empty($this->m3u_file_list_idx) || empty($this->m3u_file_list) || $add_params['path_not_to_file'])? 'Отмена' : ((!$add_params['path_not_to_file'] && !$btn_cancel)? 'Выключить' : 'Отмена'), 400);
		ControlFactoryExt::add_button_centered($defs, $button_defs, 1250);
		ControlFactory::add_vgap($defs, 10);

		return $defs;
	}

	private function get_parental_pin_dialog_controls_defs(&$add_params)
	{
		$msg_reboot = ($add_params['dialog_event'] == EventDefs::on_success)? 'Программная оболочка медиаплеера будет перезагружена!' : null;
		ControlFactory::add_vgap($defs, 5);

		if ($this->plugin_cookies_parental->enabled == ControlSwitchDefs::switch_off)
		{
			if ($add_params['dialog_event'] == EventDefs::on_show)
			{
				$title = 'Введите новый пин-код.';
				ControlFactory::add_multiline_label($defs, null, 'В дальнейшем, для доступа к защищенному контенту, необходимо будет вводить этот пин-код.', 3);
			}
			else if ($add_params['dialog_event'] == EventDefs::on_success)
				$title = 'Родительский контроль выключен!';
			else if ($add_params['dialog_event'] == EventDefs::on_error)
				$title = 'Ошибка! Поле с пин-кодом пусто.';

			if (!empty($msg_reboot))
				ControlFactory::add_smart_label($defs, null, '<text color=' . DEF_LABEL_TEXT_COLOR_RED . '>' . $msg_reboot . '</text>');

			if ($add_params['dialog_event'] == EventDefs::on_show)
			{
				ControlFactory::add_vgap($defs, 30);
				ControlFactory::add_text_field($defs, $this, null, 'parental_pin_field', '                      ПИН:', $add_params['parental_pin'], true, true, false, true, 400, true);
				ControlFactory::add_vgap($defs, -69);
				ControlFactory::add_smart_label($defs, null, '<text color=' . DEF_LABEL_TEXT_COLOR_GRAY . '>                      ПИН:</text>');
				ControlFactory::add_vgap($defs, 40);
				ControlFactory::add_button($defs, $this, null, 'set_pin_btn', '', 'Включить', 390);
				ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, '', 'Отмена', 390);
				ControlFactoryExt::add_button_centered($defs, $button_defs, 1120);
			}
			else
			{
				ControlFactory::add_vgap($defs, 40);
				ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, ($add_params['dialog_event'] == EventDefs::on_success)? 'refresh_entry_points' : 'refresh', 'OK', 300);
				ControlFactoryExt::add_button_centered($defs, $button_defs, 1120);
			}
		}
		else
		{
			if ($add_params['dialog_event'] == EventDefs::on_show)
				$title = 'Для отключения родительского контроля введите пин-код.';
			else if ($add_params['dialog_event'] == EventDefs::on_success)
				$title = 'Родительский контроль включен!';
			else if ($add_params['dialog_event'] == EventDefs::on_error)
				$title = 'Ошибка! Введен неверный пин-код.';

			if (!empty($msg_reboot))
				ControlFactory::add_smart_label($defs, null, '<text color=' . DEF_LABEL_TEXT_COLOR_RED . '>' . $msg_reboot . '</text>');

			if ($add_params['dialog_event'] == EventDefs::on_show)
			{
				ControlFactory::add_vgap($defs, 30);
				ControlFactory::add_text_field($defs, $this, null, 'parental_pin_field', '                      ПИН:', $add_params['parental_pin'], true, true, false, true, 400, true);
				ControlFactory::add_vgap($defs, -69);
				ControlFactory::add_smart_label($defs, null, '<text color=' . DEF_LABEL_TEXT_COLOR_GRAY . '>                      ПИН:</text>');
				ControlFactory::add_vgap($defs, 40);
				ControlFactory::add_button($defs, $this, null, 'set_pin_btn', '', 'Выключить', 390);
				ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, null, 'Отмена', 390);
				ControlFactoryExt::add_button_centered($defs, $button_defs, 1120);
			}
			else
			{
				ControlFactory::add_vgap($defs, 40);
				ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, ($add_params['dialog_event'] == EventDefs::on_success)? 'refresh_entry_points' : 'refresh', 'OK', 300);
				ControlFactoryExt::add_button_centered($defs, $button_defs, 1120);
			}
		}

		ControlFactory::add_vgap($defs, 10);

		return
			(object) array('title' => isset($title)? $title : null, 'defs' => $defs);
	}

	private function get_warning_vmx_not_support_dialog_controls_defs(&$add_params)
	{
		ControlFactory::add_vgap($defs, 5);

		if ($add_params['control_id'] == 'step_by_step_wizard_next_btn')
			$txt_insert = 'потоков "Интерактивного ТВ". Рекомендуется на данном этапе выбрать пункт о подключенной услуге "Интерактивное ТВ 2.0", даже если это не соответствует действительности.';
		else if ($add_params['control_id'] == 'playback_udp_enabled_on_btn')
			$txt_insert = 'UDP (multicast) потоков. Рекомендуется эту опцию оставить выключенной, а для опции "Воспроизводить HLS потоки" выбрать значение "с адаптивным битрейтом (ABS)".';
		else
			$txt_insert = 'HLS потоков с постоянным битрейтом. Рекомендуется выбрать значение "c адаптивным битрейтом (ABS)", а также выключить воспроизведение UDP потоков.';

		ControlFactory::add_multiline_label($defs, null, "Ваш медиаплеер на текущей прошивке (" . DUNE_FIRMWARE_STR . ") не поддерживает воспроизведение кодированных $txt_insert\n\nПодробнее о совместимости и прошивках смотрите в теме плагина на forum.mydune.ru\n\nУстановить рекомендуемые значения для указанных опций?", 10);
		ControlFactory::add_vgap($defs, 40);
		ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'warning_vmx_not_support_dialog_apply_btn', 'Да', 400);
		ControlFactoryExt::add_button_centered($defs, $button_defs, 1300);
		ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'warning_vmx_not_support_dialog_cancel_btn', 'Нет', 400);
		ControlFactoryExt::add_button_centered($defs, $button_defs, 1300);
		ControlFactory::add_vgap($defs, 10);

		return $defs;
	}

	private function get_private_server_warning_dialog_action(&$add_params)
	{
		ControlFactory::add_multiline_label($defs, null, "Нет доступа к ресурсам по указанному адресу.\n\nПожалуйста, уточните адрес сервера, настройки роутера, или " . (($add_params['dialog_type'] == SettingsDialogsDefs::quick_config)? "откажитесь от подключения к приватной сети провайдера на предыдущем шаге.\n\n\n" : "выберите значение по умолчанию (\"Открытый источник\")\n\n\n"), 10);
		ControlFactory::add_close_dialog_button($button_defs, 'OK', 350);
		ControlFactoryExt::add_button_centered($defs, $button_defs, 1100);
		ControlFactory::add_vgap($defs, 10);

		return
			ActionFactorySafe::show_dialog(
				'Предупреждение!',
				$defs,
				false,
				1100,
				array('dialog_params' => array('frame_style' => isset($add_params['dialog_frame_style'])? $add_params['dialog_frame_style'] : DIALOG_FRAME_STYLE_DEFAULT)));
	}

	private function get_settings_dialog_controls_defs(&$add_params)
	{
		static	$history_txt;

		$defs = array();
		$show_whats_new = false;
		ControlFactory::add_vgap($defs, 10);

		switch ($add_params['dialog_type'])
		{
			case SettingsDialogsDefs::quick_config:
				switch ($add_params['step_by_step_wizard_stage'])
				{
					case 0:
						ControlFactory::add_smart_label($defs, null, '<text>Уважаемый пользователь!</text><gap width=800/><icon>' . PLUGIN_IMG_PATH . '/avatars/micha86.png</icon>');
						ControlFactory::add_vgap($defs, -69);
						ControlFactory::add_smart_label($defs, null, '<gap width=1260/><icon>' . PLUGIN_IMG_PATH . '/avatars/ddaaff.png</icon>');
						ControlFactory::add_vgap($defs, -69);
						ControlFactory::add_smart_label($defs, null, '<gap width=1220/><icon>' . PLUGIN_IMG_PATH . '/avatars/trippycat.png</icon>');
						ControlFactory::add_vgap($defs, -69);
						ControlFactory::add_smart_label($defs, null, '<gap width=1180/><icon>' . PLUGIN_IMG_PATH . '/avatars/andy555.png</icon>');
						ControlFactory::add_vgap($defs, -69);
						ControlFactory::add_smart_label($defs, null, '<gap width=1140/><icon>' . PLUGIN_IMG_PATH . '/avatars/user.png</icon>');
						ControlFactory::add_vgap($defs, -69);
						ControlFactory::add_smart_label($defs, null, '<gap width=1100/><icon>' . PLUGIN_IMG_PATH . '/avatars/excepte.png</icon>');
						ControlFactory::add_vgap($defs, -74);
						ControlFactory::add_smart_label($defs, null, '<gap width=1050/><icon>' . PLUGIN_IMG_PATH . '/avatars/brigadir.png</icon>');
						ControlFactory::add_multiline_label($defs, null, "Вас приветствует команда разработчиков плагина \"Домашнее ТВ\"!\nБлагодарим за выбор и использование нашего программного\nпродукта.\n\nПеред началом просмотра требуется настроить плагин, пошаговый конфигуратор поможет вам в этом.\n\nНажмите \"Далее\" чтобы начать.", 15);
						break;
					case 1:
						$sub_locations_list = $this->get_locations_list();
						ControlFactory::add_multiline_label($defs, null, "Шаг {$add_params['step_by_step_wizard_stage_number']}.\nПожалуйста, выберите из списка свой регион (или город):               \n", 8);
						ControlFactory::add_combobox($defs, $this, null, 'sub_location_combo', null, $this->sub_locations_list_idx, $sub_locations_list, self::CUSTOM_OPTS_DIALOG_WIDTH-40, true);
						ControlFactory::add_vgap($defs, 190);
						ControlFactory::add_label($defs, null, "Нажмите \"Далее\" чтобы продолжить.");
						break;
					case 2:
						ControlFactory::add_multiline_label($defs, null, "Шаг {$add_params['step_by_step_wizard_stage_number']}.\nВыберите часовой пояс (выбранное время должно совпадать с временем \nна виджете):                            \n", 8);
						ControlFactory::add_combobox($defs, $this, null, 'time_zones_combo', null, $this->plugin_cookies_location->tz_offset, $this->get_time_zones_list(), self::CUSTOM_OPTS_DIALOG_WIDTH-40, true);
						ControlFactory::add_vgap($defs, 146);
						ControlFactory::add_label($defs, null, "Нажмите \"Далее\" чтобы продолжить.");
						ControlFactory::add_vgap($defs, 50);
						ControlFactory::add_button($defs, $this, null, 'step_by_step_wizard_prev_btn', null, '< Назад', 400);
						ControlFactory::add_vgap($defs, -119);
						break;
					case 3:
						$add_params['step_by_step_wizard_stage'] = 3;
						ControlFactory::add_multiline_label($defs, null, "Шаг {$add_params['step_by_step_wizard_stage_number']}.\nУкажите скорость вашего Интернет-соединения (по тарифному плану):     \n", 8);
						ControlFactory::add_combobox($defs, $this, null, 'net_speed_combo', null, $add_params['net_speed'], self::$step_by_step_wizard_answer_ops[$add_params['step_by_step_wizard_stage']], self::CUSTOM_OPTS_DIALOG_WIDTH-40, true);
						ControlFactory::add_vgap($defs, 190);
						ControlFactory::add_label($defs, null, "Нажмите \"Далее\" чтобы продолжить.");
						ControlFactory::add_vgap($defs, 50);
						ControlFactory::add_button($defs, $this, null, 'step_by_step_wizard_prev_btn', null, '< Назад', 400);
						ControlFactory::add_vgap($defs, -119);
						break;
					case 4:
						ControlFactory::add_multiline_label($defs, null, "Готово!\n\nНастройки успешно сохранены!                                                                                        ", 8);
						ControlFactory::add_vgap($defs, 214);
						ControlFactory::add_label($defs, null, 'Нажмите "Далее", чтобы перейти к процедуре поиска каналов');
						ControlFactory::add_smart_label($defs, null, '<gap width=0/><icon>' . PLUGIN_IMG_PATH . '/separator.png</icon>');
						ControlFactory::add_vgap($defs, -20);
						ControlFactory::add_button($defs, $this, null, 'do_show_scan_opts', ControlFactoryExt::get_left_margin_str(69), 'Далее >', 400);
						ControlFactory::add_vgap($defs, 10);
						return $defs;
				}

				ControlFactory::add_smart_label($defs, null, '<gap width=0/><icon>' . PLUGIN_IMG_PATH . '/separator.png</icon>');
				ControlFactory::add_vgap($defs, -20);
				ControlFactory::add_button($defs, $this, null, 'step_by_step_wizard_next_btn', ControlFactoryExt::get_left_margin_str(69), 'Далее >', 400);
				ControlFactory::add_vgap($defs, 10);
				return $defs;

			case SettingsDialogsDefs::provider_opts:
				ControlFactory::add_combobox($defs, $this, null, 'location_combo', 'Край, область       ', $this->macro_locations_list_idx, $this->macro_locations_list, self::CUSTOM_OPTS_DIALOG_WIDTH, true);
				ControlFactory::add_combobox($defs, $this, null, 'sub_location_combo', 'Нас. пункт', $this->sub_locations_list_idx, $this->sub_locations_list[$this->macro_locations_list_idx], self::CUSTOM_OPTS_DIALOG_WIDTH, true);
				ControlFactory::add_combobox($defs, $this, null, 'time_zones_combo', 'Часовой пояс', $this->plugin_cookies_location->tz_offset, $this->get_time_zones_list(), self::CUSTOM_OPTS_DIALOG_WIDTH, true);

//				if ($this->sdp_root_urls_list_idx == 'custom')
//					ControlFactory::add_text_field($defs, $this, null, 'custom_sdp_root_url_field', 'Сервер данных    ', $this->custom_sdp_root_url, false, false, false, true, self::CUSTOM_OPTS_DIALOG_WIDTH, true, false);
//				else
//					ControlFactory::add_combobox($defs, $this, null, 'sdp_root_url_combo', 'Сервер данных    ', $this->sdp_root_urls_list_idx, $this->sdp_root_urls_list, self::CUSTOM_OPTS_DIALOG_WIDTH, true);
				break;

			case SettingsDialogsDefs::plugin_opts:
				ControlFactory::add_vgap($defs, -9);
				ControlFactory::add_combobox($defs, $this, null, 'channels_search_delay_combo', 'Период автопоиска каналов   ', $this->channels_search_delay, self::$channels_search_delay_ops, self::CUSTOM_OPTS_DIALOG_WIDTH, true);
				ControlFactory::add_vgap($defs, -9);
				ControlFactory::add_combobox($defs, $this, null, 'qfilter_combo', 'Фильтр качества потоков', $this->qfilter, self::$qfilter_ops, self::CUSTOM_OPTS_DIALOG_WIDTH, true);
				ControlFactory::add_vgap($defs, -9);
				ControlFactory::add_button($defs, $this, null, 'auto_resume_enable_btn', 'Возобновлять воспроизведение', self::$on_off_ops[$this->auto_resume_enable], self::CUSTOM_OPTS_DIALOG_WIDTH, false);
				ControlFactory::add_vgap($defs, -65);
				ControlFactory::add_smart_label($defs, null,  '<gap width=' . (self::CUSTOM_OPTS_DIALOG_WIDTH - 95) . '/><icon>' . PLUGIN_IMG_PATH . '/' . $this->auto_resume_enable . '.png</icon>');
				ControlFactory::add_vgap($defs, -9);
				ControlFactory::add_button($defs, $this, null, 'autoplay_enable_btn', 'Автостарт воспроизведения', self::$on_off_ops[$this->autoplay_enable], self::CUSTOM_OPTS_DIALOG_WIDTH, false);
				ControlFactory::add_vgap($defs, -65);
				ControlFactory::add_smart_label($defs, null,  '<gap width=' . (self::CUSTOM_OPTS_DIALOG_WIDTH - 95) . '/><icon>' . PLUGIN_IMG_PATH . '/' . $this->autoplay_enable . '.png</icon>');
				ControlFactory::add_vgap($defs, -9);

				if (DVB_PLAYBACK_AVAILABLE && file_exists(HomeTv::dvb_channels_playlist_url))
				{
					ControlFactory::add_button($defs, $this, null, 'playback_dvb_btn', 'Воспроизводить DVB потоки', self::$on_off_ops[$this->plugin_cookies_playback_dvb->enabled], self::CUSTOM_OPTS_DIALOG_WIDTH, false);
					ControlFactory::add_vgap($defs, -65);
					ControlFactory::add_smart_label($defs, null,  '<gap width=' . (self::CUSTOM_OPTS_DIALOG_WIDTH - 95) . '/><icon>' . PLUGIN_IMG_PATH . '/' . $this->plugin_cookies_playback_dvb->enabled . '.png</icon>');
					ControlFactory::add_vgap($defs, -9);
				}

//				ControlFactory::add_button($defs, $this, null, 'playback_udp_btn', 'Воспроизводить потоки UDP', self::$on_off_ops[$this->plugin_cookies_playback_udp->enabled] . ((($this->plugin_cookies_playback_udp->enabled == ControlSwitchDefs::switch_on) && ($this->plugin_cookies_playback_udp->udpxy->enabled == ControlSwitchDefs::switch_on))? ' (через UDPXY)' : ''), self::CUSTOM_OPTS_DIALOG_WIDTH, false);
//				ControlFactory::add_vgap($defs, -65);
//				ControlFactory::add_smart_label($defs, null,  '<gap width=' . (self::CUSTOM_OPTS_DIALOG_WIDTH - 95) . '/><icon>' . PLUGIN_IMG_PATH . '/' . $this->plugin_cookies_playback_udp->enabled . '_.png</icon>');
//				ControlFactory::add_vgap($defs, -9);
//				ControlFactory::add_button($defs, $this, null, 'playback_http_btn', 'Параметры воспроизведения', /*self::$on_off_ops[$this->plugin_cookies_playback_http->enabled] . */'Изменить' . (($this->plugin_cookies_playback_http->enabled == ControlSwitchDefs::switch_on)? ' (' . $this->plugin_cookies_playback_http->buff_size_ms . 'ms/' . (($this->plugin_cookies_playback_http->secury_disable == ControlSwitchDefs::switch_on)? 'HTTPS OFF' : 'HTTPS ON') . ')' : ''), self::CUSTOM_OPTS_DIALOG_WIDTH, false);
//				ControlFactory::add_vgap($defs, -65);
//				ControlFactory::add_smart_label($defs, null,  '<gap width=' . (self::CUSTOM_OPTS_DIALOG_WIDTH - 95) . '/><icon>' . PLUGIN_IMG_PATH . '/' . $this->plugin_cookies_playback_http->enabled . '_.png</icon>');
//				ControlFactory::add_vgap($defs, -9);
				ControlFactory::add_button($defs, $this, null, 'epg_enable_btn', 'Программа телепередач', self::$on_off_ops[$this->plugin_cookies_epg->enabled] . (($this->plugin_cookies_epg->enabled == ControlSwitchDefs::switch_on)? ' (' . (($this->plugin_cookies_epg->ext_enable == ControlSwitchDefs::switch_on)? 'ExtEPG/' : '') . (($this->plugin_cookies_epg->font_size == PLUGIN_FONT_SMALL)? 'Small-Font' : 'Normal-Font') . (($this->plugin_cookies_epg->fill_enable == ControlSwitchDefs::switch_on)? '/Fill' : '') . ')' : ''), self::CUSTOM_OPTS_DIALOG_WIDTH, false);
				ControlFactory::add_vgap($defs, -65);
				ControlFactory::add_smart_label($defs, null,  '<gap width=' . (self::CUSTOM_OPTS_DIALOG_WIDTH - 95) . '/><icon>' . PLUGIN_IMG_PATH . '/' . $this->plugin_cookies_epg->enabled . '_.png</icon>');
				ControlFactory::add_vgap($defs, -9);
				ControlFactory::add_button($defs, $this, null, 'tv_archives_btn', 'Архив телепередач', self::$on_off_ops[$this->plugin_cookies_tv_archives->enabled] . (($this->plugin_cookies_tv_archives->enabled == ControlSwitchDefs::switch_on)? (($this->plugin_cookies_tv_archives->playback_stream_type == TvArchivePlaybackDefs::tstv)? ' (TSTV)' : (($this->plugin_cookies_tv_archives->playback_stream_type == TvArchivePlaybackDefs::npvr)? ' (NPVR)' : ' (TSTV+NPVR)')) : ''), self::CUSTOM_OPTS_DIALOG_WIDTH, false);
				ControlFactory::add_vgap($defs, -65);
				ControlFactory::add_smart_label($defs, null,  '<gap width=' . (self::CUSTOM_OPTS_DIALOG_WIDTH - 95) . '/><icon>' . PLUGIN_IMG_PATH . '/' . $this->plugin_cookies_tv_archives->enabled . '_.png</icon>');
				ControlFactory::add_vgap($defs, -9);
				ControlFactory::add_button($defs, $this, null, 'favorites_enable_btn', 'Группа избранных каналов', self::$on_off_ops[$this->favorites_enable], self::CUSTOM_OPTS_DIALOG_WIDTH, false);
				ControlFactory::add_vgap($defs, -65);
				ControlFactory::add_smart_label($defs, null,  '<gap width=' . (self::CUSTOM_OPTS_DIALOG_WIDTH - 95) . '/><icon>' . PLUGIN_IMG_PATH . '/' . $this->favorites_enable . '.png</icon>');
				ControlFactory::add_vgap($defs, -9);
				ControlFactory::add_button($defs, $this, null, 'export_m3u_btn', 'Экспортировать плейлист', self::$on_off_ops[$this->plugin_cookies_playlist_export->enabled], self::CUSTOM_OPTS_DIALOG_WIDTH, false);
				ControlFactory::add_vgap($defs, -65);
				ControlFactory::add_smart_label($defs, null,  '<gap width=' . (self::CUSTOM_OPTS_DIALOG_WIDTH - 95) . '/><icon>' . PLUGIN_IMG_PATH . '/' . $this->plugin_cookies_playlist_export->enabled . '_.png</icon>');
				ControlFactory::add_vgap($defs, -9);
				ControlFactory::add_button($defs, $this, null, 'playback_http_btn', 'Параметры воспроизведения', /*self::$on_off_ops[$this->plugin_cookies_playback_http->enabled] . */'Изменить' . (($this->plugin_cookies_playback_http->enabled == ControlSwitchDefs::switch_on)? ' (' . $this->plugin_cookies_playback_http->buff_size_ms . 'ms/' . (($this->plugin_cookies_playback_http->secury_disable == ControlSwitchDefs::switch_on)? 'HTTPS OFF' : 'HTTPS ON') . ')' : ''), self::CUSTOM_OPTS_DIALOG_WIDTH, false);
				ControlFactory::add_vgap($defs, -12);
				break;

			case SettingsDialogsDefs::parental_ctrl:
				ControlFactory::add_multiline_label($defs, null, 'Родительский контроль ограничивает доступ к защищенному контенту и действиям пользователя. Действие опции распространяется на каналы для взрослых и содержимое корзины.', 4);
				$parental_enable = ($this->plugin_cookies_parental->enabled == ControlSwitchDefs::switch_on);
				ControlFactory::add_label($defs, null, 'Родительский контроль сейчас ' . ($parental_enable? 'включен' : 'выключен') . '. Хотите ' . ($parental_enable? 'выключить' : 'включить') . ' опцию?');
				break;

			case SettingsDialogsDefs::customs_ctrl:
				ControlFactory::add_vgap($defs1, -10);
				$left_margin = ControlFactoryExt::get_left_margin_str(50);
				ControlFactory::add_button($defs1, $this, null, 'check_skin_palette_btn', $left_margin, self::$on_off_ops[$this->plugin_cookies_customs_control->check_skin_palette], self::CUSTOM_OPTS_DIALOG_WIDTH - 732, false);
				ControlFactory::add_vgap($defs1, -69);
				ControlFactory::add_smart_label($defs1, null,  '<text color=' . DEF_LABEL_TEXT_COLOR_SILVER . '>  Проверять и патчить</text>');
				ControlFactory::add_vgap($defs1, -65);
				ControlFactory::add_smart_label($defs1, $left_margin,  '<gap width=' . (self::CUSTOM_OPTS_DIALOG_WIDTH - 732 - 94) . '/><icon>' . PLUGIN_IMG_PATH . '/' . $this->plugin_cookies_customs_control->check_skin_palette . '.png</icon>');
				ControlFactory::add_vgap($defs1, -4);
				ControlFactoryExt::add_group_box($defs, $defs1, 'Палитра скина', self::CUSTOM_OPTS_DIALOG_WIDTH);
				ControlFactory::add_vgap($defs, 20);
				ControlFactory::add_vgap($defs2, -10);

				if (DUNE_FIRMWARE_BN > 8)
				{
					if ($this->plugin_cookies_epg->enabled == ControlSwitchDefs::switch_on)
					{
						$list = self::$ctrl_keys_ops;

						if (get_platform_kind() == 'android')
						{
							if (DUNE_FIRMWARE_BN == 12)
								unset($list[GUI_EVENT_KEY_TOP_MENU]);

							unset($list[GUI_EVENT_KEY_EJECT], $list[GUI_EVENT_KEY_URL], $list[GUI_EVENT_KEY_DUNE]);
						}

						if (!empty($this->plugin_cookies_customs_control->clock_key) && isset($list[$this->plugin_cookies_customs_control->clock_key]))
							unset($list[$this->plugin_cookies_customs_control->clock_key]);

						if (!empty($this->plugin_cookies_customs_control->repeat_key) && isset($list[$this->plugin_cookies_customs_control->repeat_key]))
							unset($list[$this->plugin_cookies_customs_control->repeat_key]);

						if (isset($list[GUI_EVENT_KEY_INFO]))
							$list[GUI_EVENT_KEY_INFO] = 'Кнопка INFO (по умолчанию)';

						ControlFactory::add_combobox($defs2, $this, null, 'custom_epg_key', '  Показать/скрыть', $this->plugin_cookies_customs_control->epg_key, $list, self::CUSTOM_OPTS_DIALOG_WIDTH - 732, true);
					}
					else
					{
						ControlFactory::add_smart_label($defs2, '  Показать/скрыть', '<text color=' . DEF_LABEL_TEXT_COLOR_CORAL . ' size=' . PLUGIN_FONT_SMALL . '>Запрещено! Пожалуйста, активируйте</text>');
						ControlFactory::add_vgap($defs2, -34);
						ControlFactory::add_smart_label($defs2, '', '<text color=' . DEF_LABEL_TEXT_COLOR_CORAL . ' size=' . PLUGIN_FONT_SMALL . '>программу телепередач в опциях плагина</text>');
						ControlFactory::add_vgap($defs2, -20);
					}
				}
				else
					ControlFactory::add_smart_label($defs2, '  Показать/скрыть', '<text color=' . DEF_LABEL_TEXT_COLOR_CORAL . '>Недоступно на текущей прошивке</text>');

				ControlFactoryExt::add_group_box($defs, $defs2, 'Кастомный ТЕЛЕГИД (в режиме воспроизведения)', self::CUSTOM_OPTS_DIALOG_WIDTH);
				ControlFactory::add_vgap($defs, 20);
				ControlFactory::add_vgap($defs3, -10);

				if (DUNE_FIRMWARE_BN >= 10)
				{
					$list = self::$ctrl_keys_ops;

					if (get_platform_kind() == 'android')
						unset($list[GUI_EVENT_KEY_TOP_MENU], $list[GUI_EVENT_KEY_EJECT], $list[GUI_EVENT_KEY_URL], $list[GUI_EVENT_KEY_DUNE]);

					if (!empty($this->plugin_cookies_customs_control->epg_key) && isset($list[$this->plugin_cookies_customs_control->epg_key]))
						unset($list[$this->plugin_cookies_customs_control->epg_key]);

					if (!empty($this->plugin_cookies_customs_control->repeat_key) && isset($list[$this->plugin_cookies_customs_control->repeat_key]))
						unset($list[$this->plugin_cookies_customs_control->repeat_key]);

					if (isset($list[GUI_EVENT_KEY_SELECT]))
						$list[GUI_EVENT_KEY_SELECT] = 'Кнопка SELECT (по умолчанию)';

					ControlFactory::add_combobox($defs3, $this, null, 'custom_clock_key', '  Показать/скрыть', $this->plugin_cookies_customs_control->clock_key, $list, self::CUSTOM_OPTS_DIALOG_WIDTH - 732, true);
					ControlFactory::add_combobox($defs3, $this, null, 'custom_clock_pos', '  Положение на экране', $this->plugin_cookies_customs_control->clock_pos, self::$clock_pos_ops, self::CUSTOM_OPTS_DIALOG_WIDTH - 732, true);
				}
				else
					ControlFactory::add_smart_label($defs3, '  Показать/скрыть', '<text color=' . DEF_LABEL_TEXT_COLOR_CORAL . '>Недоступно на текущей прошивке</text>');

				ControlFactoryExt::add_group_box($defs, $defs3, 'ЧАСЫ (в режиме воспроизведения)', self::CUSTOM_OPTS_DIALOG_WIDTH);
				ControlFactory::add_vgap($defs, 20);
				ControlFactory::add_vgap($defs4, -10);

				if (DUNE_FIRMWARE_BN >= 9)
				{
					$list = self::$ctrl_keys_ops;

					if (get_platform_kind() == 'android')
						unset($list[GUI_EVENT_KEY_TOP_MENU], $list[GUI_EVENT_KEY_EJECT], $list[GUI_EVENT_KEY_URL], $list[GUI_EVENT_KEY_DUNE]);

					if (!empty($this->plugin_cookies_customs_control->epg_key) && isset($list[$this->plugin_cookies_customs_control->epg_key]))
						unset($list[$this->plugin_cookies_customs_control->epg_key]);

					if (!empty($this->plugin_cookies_customs_control->clock_key) && isset($list[$this->plugin_cookies_customs_control->clock_key]))
						unset($list[$this->plugin_cookies_customs_control->clock_key]);

					if (isset($list[GUI_EVENT_KEY_CLEAR]))
						$list[GUI_EVENT_KEY_CLEAR] = 'Кнопка CLEAR (по умолчанию)';

					ControlFactory::add_combobox($defs4, $this, null, 'custom_repeat_key', '  Переключение', $this->plugin_cookies_customs_control->repeat_key, $list, self::CUSTOM_OPTS_DIALOG_WIDTH - 732, true);
				}
				else
					ControlFactory::add_smart_label($defs4, '  Переключение', '<text color=' . DEF_LABEL_TEXT_COLOR_CORAL . '>Недоступно на текущей прошивке</text>');

				ControlFactoryExt::add_group_box($defs, $defs4, 'Возврат к пред. каналу (в режиме воспроизведения)', self::CUSTOM_OPTS_DIALOG_WIDTH);
				break;

			case SettingsDialogsDefs::about_plugin:
				ControlFactory::add_vgap($defs, -18);
				ControlFactory::add_multiline_label($defs, '', 'Плагин для просмотра IPTV от провайдера Ростелеком на территории Российской Федерации.', 4);
				ControlFactory::add_vgap($defs, -10);
				ControlFactory::add_smart_label($defs, '', '<text>Автор:   </text><icon>' . PLUGIN_IMG_PATH . '/avatars/brigadir.png</icon><gap width=20/><text>Brigadir (forum.mydune.ru)</text>');
				ControlFactory::add_label($defs, '', 'Мои благодарности:');
				ControlFactory::add_vgap($defs, -10);
				ControlFactory::add_smart_label($defs, '', '<icon>' . PLUGIN_IMG_PATH . '/avatars/ddaaff.png</icon><gap width=20/><text>ddaaff (forum.mydune.ru) - за толковые идеи и активную помощь</text>');
				ControlFactory::add_vgap($defs, -12);
				ControlFactory::add_smart_label($defs, '', '<icon>' . PLUGIN_IMG_PATH . '/avatars/excepte.png</icon><gap width=20/><text>excepte (forum.mydune.ru) - за толковые идеи и неоценимую помощь</text>');
				ControlFactory::add_vgap($defs, -12);
				ControlFactory::add_smart_label($defs, '', '<icon>' . PLUGIN_IMG_PATH . '/avatars/user.png</icon><gap width=20/><text>Bagauser (forum.mydune.ru) - за неоценимую помощь в разработке</text>');
				ControlFactory::add_vgap($defs, -12);
				ControlFactory::add_smart_label($defs, '', '<icon>' . PLUGIN_IMG_PATH . '/avatars/andy555.png</icon><gap width=20/><text>andy555 (forum.hdtv.ru) - за скрипт ретранслятора</text>');
				ControlFactory::add_vgap($defs, -12);
				ControlFactory::add_smart_label($defs, '', '<icon>' . PLUGIN_IMG_PATH . '/avatars/trippycat.png</icon><gap width=20/><text>TrippyCat (forum.hdtv.ru) - за правки парсера vsetv.com</text>');
				ControlFactory::add_vgap($defs, -12);
				ControlFactory::add_smart_label($defs, '', '<icon>' . PLUGIN_IMG_PATH . '/avatars/micha86.png</icon><gap width=20/><text>micha86 (forum.mydune.ru) - за адаптацию под платформу 87xx</text>');
				ControlFactory::add_vgap($defs, -12);
				ControlFactory::add_smart_label($defs, '', '<icon>' . PLUGIN_IMG_PATH . '/avatars/mityagin_spb_ru.png</icon><gap width=20/><text>Mityagin.Spb.Ru (forum.mydune.ru) - за толковые идеи</text>');
				break;

			case SettingsDialogsDefs::whats_new:
				$show_whats_new = true;

			case SettingsDialogsDefs::history_vers:
				if (empty($history_txt))
				{
					$history_txt = @file_get_contents(sprintf(self::PLUGIN_VERS_HISTORY_URL, preg_match('/_test|b/', $this->plugin->app_version)? '_test' : ''));

					if ($history_txt === false)
					{
						ControlFactory::add_vgap($defs, 50);
						ControlFactory::add_smart_label($defs, null, '<gap width=' . ((self::CUSTOM_OPTS_DIALOG_WIDTH - 380)/2) . '/><text>Данные недоступны.</text>');
						ControlFactory::add_vgap($defs, -20);
						ControlFactory::add_smart_label($defs, null, '<gap width=' . ((self::CUSTOM_OPTS_DIALOG_WIDTH - 700)/2) . '/><text>Возможно временный сбой на сервере,</text>');
						ControlFactory::add_vgap($defs, -20);
						ControlFactory::add_smart_label($defs, null, '<gap width=' . ((self::CUSTOM_OPTS_DIALOG_WIDTH - 700)/2) . '/><text>попробуйте повторить попытку позже.</text>');
						ControlFactory::add_vgap($defs, 100);
					}
					else if ($show_whats_new)
					{
						$history_txt_arr = explode("\n", $history_txt);
						$history_txt = '';
						$app_version = (preg_match('/(\d+)\s*\((\d\d)(\d\d)(\d\d\d\d)\)/i', $app_version_str = str_replace('.', '', $this->plugin_cookies_app_version), $matches) && isset($matches[4]))? floatval($matches[4] . $matches[3] . $matches[2] . $matches[1]) : $app_version_str; //str_replace('.', '', $this->plugin_cookies_app_version);

						foreach($history_txt_arr as $str)
						{
							if (preg_match('/v(\d+)\s*\((\d\d)(\d\d)(\d\d\d\d)\)/i', str_replace('.', '', $str), $matches))
							{
								if ($continue = !isset($matches[4]))
									continue;

								if (floatval($matches[4] . $matches[3] . $matches[2] . $matches[1]) < $app_version)
									break;
							}

							if (empty($continue))
								$history_txt .= "$str\n";
						}
					}
				}

				if (!empty($history_txt))
				{
					if ($show_whats_new)
						ControlFactory::add_multiline_label($defs, null, preg_replace('/\n$/U', '', $history_txt), 13);
					else
					{
						ControlFactory::add_multiline_label($defs, null, $history_txt, 14);
						ControlFactory::add_vgap($defs, 20);
					}

					ControlFactory::add_smart_label($defs, null, '<gap width=' . (self::CUSTOM_OPTS_DIALOG_WIDTH - 420) . '/><icon>' . PLUGIN_IMG_PATH . '/page_plus_btn.png</icon><gap width=10/><icon>' . PLUGIN_IMG_PATH . '/page_minus_btn.png</icon><text color=' . DEF_LABEL_TEXT_COLOR_SILVER . ' size=small>  Прокрутка страниц</text>');
					ControlFactory::add_vgap($defs, 14);
				}

				ControlFactory::add_vgap($defs, $show_whats_new? 0 : -48);
		}

		ControlFactory::add_vgap($defs, 20);

		if (($add_params['dialog_type'] == SettingsDialogsDefs::provider_opts) ||
			($add_params['dialog_type'] == SettingsDialogsDefs::plugin_opts) ||
			($add_params['dialog_type'] == SettingsDialogsDefs::customs_ctrl))
		{
			$hint_lines = explode('|', sprintf(self::$plugin_ctrls_hints[$add_params['selected_ctrl']], (DUNE_FIRMWARE_BN >= 11)? strtoupper(preg_replace('/_.*/', '', $this->system_settings['return_to_prev_tv_channel'])) : 'RETURN'));
			ControlFactory::add_smart_label($defs, null,  (empty($hint_lines[0])? '<gap width=440/>' : ('<gap width=370/><icon>' . PLUGIN_IMG_PATH . '/info.png</icon><gap width=30/>')) . '<text size=small color=' . DEF_LABEL_TEXT_COLOR_SILVER . '>' . (empty($hint_lines[0])? '' : $hint_lines[0]) . '</text>');
			ControlFactory::add_vgap($defs, -36);
			ControlFactory::add_smart_label($defs, null, '<gap width=440/><text size=small color=' . DEF_LABEL_TEXT_COLOR_SILVER . '>' . (empty($hint_lines[1])? '' : $hint_lines[1]) . '</text>');
			ControlFactory::add_vgap($defs, -36);
			ControlFactory::add_smart_label($defs, null, '<gap width=440/><text size=small color=' . DEF_LABEL_TEXT_COLOR_SILVER . '>' . (empty($hint_lines[2])? '' : $hint_lines[2]) . '</text>');
			ControlFactory::add_vgap($defs, -36);
			ControlFactory::add_smart_label($defs, null, '<gap width=440/><text size=small color=' . DEF_LABEL_TEXT_COLOR_SILVER . '>' . (empty($hint_lines[3])? '' : $hint_lines[3]) . '</text>');
			ControlFactory::add_vgap($defs, -159);
			ControlFactory::add_close_dialog_and_apply_button($defs, $this, null, 'save_btn', 'Сохранить', 300);
			ControlFactory::add_close_dialog_button($defs, 'Отмена', 300);
		}
		else if (($add_params['dialog_type'] == SettingsDialogsDefs::about_plugin) || ($add_params['dialog_type'] == SettingsDialogsDefs::history_vers))
			ControlFactory::add_custom_close_dialog_and_apply_button($defs, null, 'ОK', 400, $this->out_action);
		else if ($add_params['dialog_type'] == SettingsDialogsDefs::whats_new)
		{
			ControlFactory::add_custom_close_dialog_and_apply_button($button_defs, null, 'ОK', 400, $this->out_action);
			ControlFactoryExt::add_button_centered($defs, $button_defs, 1400);
		}
		else if ($add_params['dialog_type'] == SettingsDialogsDefs::parental_ctrl)
		{
			ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'parental_btn', $parental_enable? 'Выключить' : 'Включить', 400);
			ControlFactoryExt::add_button_centered($defs, $button_defs, 1400);
			ControlFactory::add_close_dialog_button($button_defs, 'Отмена', 400);
			ControlFactoryExt::add_button_centered($defs, $button_defs, 1400);
		}
		else
		{
			ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'customs_control_dialog_save_btn', 'Сохранить', 400);
			ControlFactoryExt::add_button_centered($defs, $button_defs, 1400);
			ControlFactory::add_close_dialog_button($button_defs, 'Отмена', 400);
			ControlFactoryExt::add_button_centered($defs, $button_defs, 1400);
		}

		if ($add_params['dialog_type'] == SettingsDialogsDefs::about_plugin)
			ControlFactory::add_button($defs, $this, null, 'history_btn', null, 'История версий', 400);

		ControlFactory::add_vgap($defs, 10);

		return $defs;
	}

	private function dialog_handle_user_input(&$user_input, &$plugin_cookies)
	{
		static $selected_idx;
		static $add_params;
		static $most_idx;
		static $old_tz_offset;
		static $old_auto_resume_enable;
		static $old_sdp_root_urls_list_idx;

		$control_id = isset($user_input->control_id)? $user_input->control_id : '';

		if (!isset($user_input->action_type))
		{
			switch ($control_id)
			{
				case 'show_dialog':
					clearstatcache();
					$selected_idx = 0;
					$most_idx = ($user_input->dialog_type == SettingsDialogsDefs::provider_opts)? 4 : (($user_input->dialog_type == SettingsDialogsDefs::plugin_opts)? ((DVB_PLAYBACK_AVAILABLE && file_exists(HomeTv::dvb_channels_playlist_url))? 11 : 10) : (($user_input->dialog_type == SettingsDialogsDefs::customs_ctrl)? ((DUNE_FIRMWARE_BN <=9)? ((DUNE_FIRMWARE_BN == 9)? 3 : 2) : 6) : (($user_input->dialog_type == SettingsDialogsDefs::quick_config)? 3 : 1)));
					$add_params = array('dialog_frame_style' => isset($user_input->dialog_frame_style)? $user_input->dialog_frame_style : DIALOG_FRAME_STYLE_DEFAULT,
										'selected_ctrl' => ($user_input->dialog_type == SettingsDialogsDefs::provider_opts)? 'location_combo' : (($user_input->dialog_type == SettingsDialogsDefs::customs_ctrl)? 'check_skin_palette_btn' : 'channels_search_delay_combo'),
										'dialog_type' => $user_input->dialog_type,
										'whats_new' => ($user_input->dialog_type == SettingsDialogsDefs::whats_new),
										'warning_vmx_not_support_was_shown' => false);
					$actions = array(
								GUI_EVENT_KEY_UP => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_UP),
								GUI_EVENT_KEY_DOWN => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_DOWN),
								GUI_EVENT_KEY_LEFT => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_LEFT),
								GUI_EVENT_KEY_RIGHT => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_RIGHT));

					if ($user_input->dialog_type == SettingsDialogsDefs::quick_config)
					{
						$add_params += array(
							'step_by_step_wizard_stage' => 0,
							'step_by_step_wizard_stage_number' => 0);
						$key_return_action = UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_RETURN);

						if (DUNE_FIRMWARE_BN >= 9)
							$actions[GUI_EVENT_KEY_STOP] = $key_return_action;

						$actions[GUI_EVENT_KEY_RETURN] = $key_return_action;
					}

					if ($user_input->dialog_type == SettingsDialogsDefs::provider_opts)
						$actions[GUI_EVENT_KEY_RETURN] = UserInputHandlerRegistry::create_action($this, 'do_close_and_update');

					$this->initialize($add_params, $plugin_cookies);
					$old_tz_offset = $this->plugin_cookies_location->tz_offset;
					$old_auto_resume_enable = $this->auto_resume_enable;
					$old_sdp_root_urls_list_idx = $this->sdp_root_urls_list_idx;

					return
						ActionFactorySafe::show_dialog(
							$this->plugin->app_caption . ': ' . self::$settings_dialog_captions[$user_input->dialog_type],
							$this->get_settings_dialog_controls_defs($add_params),
							($user_input->dialog_type <> SettingsDialogsDefs::whats_new) && ($user_input->dialog_type <> SettingsDialogsDefs::provider_opts),
							($user_input->dialog_type == SettingsDialogsDefs::quick_config)? 1350 : (($user_input->dialog_type == SettingsDialogsDefs::customs_ctrl)? 1400 : self::CUSTOM_OPTS_DIALOG_WIDTH),
							array
							(
								'dialog_params' => array('frame_style' => isset($user_input->dialog_frame_style)? $user_input->dialog_frame_style : DIALOG_FRAME_STYLE_DEFAULT),
								'actions' => $actions,
								'initial_sel_ndx' => $selected_idx,
							));

				case GUI_EVENT_KEY_UP:
					if ($add_params['dialog_type'] == SettingsDialogsDefs::quick_config)
					{
						if (($most_idx > 3) && ($selected_idx < ($most_idx - 2)))
							$selected_idx -= 1;
						else
							$selected_idx = 0;
					}
					else
						$selected_idx -= 1;

					if ($selected_idx < 0)
						$selected_idx = 0;

					break;

				case GUI_EVENT_KEY_DOWN:
					if ($add_params['dialog_type'] == SettingsDialogsDefs::quick_config)
					{
						if ($selected_idx == ($most_idx - 3))
							$selected_idx = $most_idx - 1;
						else if ($most_idx <= 2)
							$selected_idx += 1;
						else if ($selected_idx < ($most_idx - 2))
							$selected_idx += 1;
					}
					else
						$selected_idx += 1;

					if ($selected_idx > $most_idx)
						$selected_idx = $most_idx;

					break;

				case GUI_EVENT_KEY_LEFT:
					$selected_idx = ($add_params['dialog_type'] == SettingsDialogsDefs::quick_config)? $most_idx - 2 : 0;
					break;

				case GUI_EVENT_KEY_RIGHT:
					$selected_idx = ($add_params['dialog_type'] == SettingsDialogsDefs::quick_config)? $most_idx : $most_idx - ((strpos('save_btn_apply_btn_cancel_btn_history_btn', substr($add_params['selected_ctrl'], 0, 7)) === false)? 1 : 0);
					break;

				case GUI_EVENT_KEY_RETURN:
					if (($add_params['step_by_step_wizard_stage'] == 0) || ($add_params['step_by_step_wizard_stage'] > 3))
						return
							ActionFactorySafe::reset_controls($this->get_settings_dialog_controls_defs($add_params));

					ControlFactory::add_vgap($defs, 40);
					ControlFactory::add_close_dialog_and_apply_button($button_defs, $this, null, 'close_dialog_and_quit', 'Да', 400);
					ControlFactoryExt::add_button_centered($defs, $button_defs, 760);
					ControlFactory::add_close_dialog_button($button_defs, 'Нет', 400);
					ControlFactoryExt::add_button_centered($defs, $button_defs, 760);
					ControlFactory::add_vgap($defs, 10);

					return
						ActionFactorySafe::show_dialog(
							"Прервать работу конфигуратора?",
							$defs,
							false,
							760,
							array('dialog_params' => array('darkens_screen' => false, 'frame_style' => DIALOG_FRAME_STYLE_DEFAULT)));

				case 'do_close_and_update':
					return
						ActionFactorySafe::close_dialog_and_run(ActionFactorySafe::invalidate_folders(array(SettingsScreen::get_media_url_str(false))));

				case 'refresh':
					$post_action = null;

					if ($add_params['dialog_type'] == SettingsDialogsDefs::quick_config)
					{
						switch ($add_params['step_by_step_wizard_stage'])
						{
							case 0: $most_idx = 1; break;
							case 1: $most_idx = 2; $post_action = SplashScreen::refresh(false); break;
							case 2: $most_idx = 3; $post_action = SplashScreen::refresh(true); break;
							case 3: $most_idx = 3; $post_action = SplashScreen::refresh(false); break;
							case 4: $most_idx = 2; break;
						}
					}
					else
						$add_params['selected_ctrl'] = $user_input->selected_control_id;

					if ($add_params['dialog_type'] == SettingsDialogsDefs::provider_opts)
						$post_action = ActionFactorySafe::invalidate_folders(array(SettingsScreen::get_media_url_str($add_params['selected_ctrl'] == 'time_zones_combo')));

					$add_params['warning_vmx_not_support_was_shown'] = false;

					return
						ActionFactorySafe::reset_controls($this->get_settings_dialog_controls_defs($add_params), $post_action);

				case 'clear_epg_cache':
					$this->plugin->epg->clear_cache();

				case 'close_and_exit':
					Wink()->set_location($this->sub_locations_list_idx);

					return $this->out_action;
			}
		}
		else if ($user_input->action_type == 'confirm')
		{
			$new_value = $user_input->{$control_id};

			switch ($control_id)
			{
				case 'epg_font_size_combo':
					$add_params['epg_font_size'] = $new_value;

					return
						ActionFactory::reset_controls($this->get_epg_dialog_controls_defs($add_params));

				case 'tv_archives_stream_type_combo':
					$add_params['tv_archives_playback_stream_type'] = $new_value;

					return
						ActionFactorySafe::reset_controls($this->get_tv_archives_dialog_controls_defs($add_params));

				case 'parental_pin_field':
					$add_params['parental_pin'] = $new_value;
					$controls = $this->get_parental_pin_dialog_controls_defs($add_params);

					return
						ActionFactorySafe::close_dialog_and_run(ActionFactorySafe::show_dialog($controls->title, $controls->defs, false, 1120, array('initial_sel_ndx' => 1)));

				case 'location_combo':
					if ($this->macro_locations_list_idx <> $new_value)
					{
						$this->macro_locations_list_idx = $new_value;
						$this->sub_locations_list_idx = key($this->sub_locations_list[$new_value]);
					}

					break;

				case 'sub_location_combo':
					$this->sub_locations_list_idx = $new_value;

					if ($add_params['dialog_type'] == SettingsDialogsDefs::quick_config)
					{
						foreach ($this->sub_locations_list as $location => $sub_locations)
							if (array_search($new_value, array_flip($sub_locations)) !== false)
							{
								$this->macro_locations_list_idx = $location;
								break;
							}

						$this->sdp_root_urls_list_idx = key($this->sdp_root_urls_list);
					}
					break;

				case 'time_zones_combo':
					$this->plugin_cookies_location->tz_offset = $new_value;
					break;

				case 'sdp_root_url_combo':
					if (!empty($new_value) && ($new_value <> 'custom') && !$this->check_network_source('http://' . $new_value . ':8080/' . sprintf(FE_NETWORK_PATH, 1000)))
						return
							$this->get_private_server_warning_dialog_action($add_params);

					$this->sdp_root_urls_list_idx = $new_value;
					break;

				case 'custom_sdp_root_url_field':
					$new_value = trim($new_value);

					if (!empty($new_value))
					{
						if (is_numeric(str_replace(array('.', ':'), '', $new_value)))
						{
							$ip = explode('.', $new_value);
							$valid = (count($ip) == 4);
							$ip[0] = (isset($ip[0]) && is_numeric($ip[0]) && ($ip[0] >= 1) && ($ip[0] < 224))? $ip[0] : '';
							$ip[1] = (isset($ip[1]) && is_numeric($ip[1]) && ($ip[1] >= 0) && ($ip[1] < 256))? $ip[1] : '';
							$ip[2] = (isset($ip[2]) && is_numeric($ip[2]) && ($ip[2] >= 0) && ($ip[2] < 256))? $ip[2] : '';
							$ip3 = isset($ip[3])? explode(':', $ip[3]) : array();
							$ip[3] = (isset($ip3[0]) && is_numeric($ip3[0]))? $ip3[0] : '';

							if (!$valid || ($ip[0] == '') || ($ip[1] == '') || ($ip[2] == '') || ($ip[3] == ''))
								ControlFactory::add_multiline_label($defs, null, "Введите правильное значение домена или IP-адреса, например:\nserver-domain\nserver-domain:P\nA.B.C.D\nA.B.C.D:P\n- где\nA - число в диапазоне 1-223\nB-C - число в диапазоне 0-255\nD - число в диапазоне 1-254\nP - число в диапазоне 0-65535 (порт TCP/IP)", 12);
							else
							{
								if (empty($ip[3]))
									ControlFactory::add_multiline_label($defs, null, "Введенный IP-адрес является адресом сети. Введите правильное значение в 4-м октете (число в диапазоне 1-254).", 5);
								else if ($ip[3] == 255)
									ControlFactory::add_multiline_label($defs, null, "Введенный IP-адрес является широковещательным. Введите правильное значение в 4-м октете (число в диапазоне 1-254).", 5);
								else if (empty($ip[0]) || ($ip[0] > 255) || ($ip[1] > 255) || ($ip[2] > 255) || ($ip[3] > 255))
									ControlFactory::add_multiline_label($defs, null, "Введенный IP-адрес некорректен. Значение в 1-м октете должно лежать в диапазоне 1-254, во 2-4 октетах - в диапазоне 0-254.", 5);

								if (isset($ip3[1]) && (!is_numeric($ip3[1]) || ($ip3[1] < 0) || ($ip3[1] > 65535)))
									ControlFactory::add_multiline_label($defs, null, "Указано некорректное значение порта TCP/IP. Правильное число лежит в диапазоне 0-65535.", 5);
							}
						}
						else
						{
							$p = explode(':', $new_value);

							if (isset($p[1]) && (!is_numeric($p[1]) || ($p[1] < 0) || ($p[1] > 65535)))
								ControlFactory::add_multiline_label($defs, null, "Указано некорректное значение порта TCP/IP. Правильное число лежит в диапазоне 0-65535.", 5);
						}

						if (isset($defs))
						{
							ControlFactory::add_vgap($defs, 40);
							ControlFactory::add_close_dialog_button($button_defs, 'OK', 350);
							ControlFactoryExt::add_button_centered($defs, $button_defs, 1200);
							ControlFactory::add_vgap($defs, 10);

							return
								ActionFactorySafe::show_dialog(
									'Внимание!',
									$defs,
									false,
									1200,
									array(
										'dialog_params' => array('frame_style' => ($user_input->parent_media_url <> SettingsScreen::ID)? DIALOG_FRAME_STYLE_GLASS : DIALOG_FRAME_STYLE_DEFAULT),
									));
						}

						if (($new_value <> 'custom') && !$this->check_network_source('http://' . $new_value . ':8080/' . sprintf(FE_NETWORK_PATH, 1000)))
							return
								$this->get_private_server_warning_dialog_action($add_params);
					}

					$this->sdp_root_urls_list_idx = empty($new_value)? $old_sdp_root_urls_list_idx : $new_value;
					$this->custom_sdp_root_url = $new_value;
					break;

				case 'http_stream_type_combo':
					$this->plugin_cookies_playback_http->hls_bs_prefer = $new_value;

					return
						ActionFactorySafe::reset_controls($this->get_playback_hls_dialog_controls_defs($add_params), null, 0);

				case 'http_buff_size_ms_combo':
					$this->plugin_cookies_playback_http->buff_size_ms = $new_value;

					return
						ActionFactorySafe::reset_controls($this->get_playback_hls_dialog_controls_defs($add_params), null, 0);

				case 'm3u_dir_list':
					$this->plugin_cookies_playlist_export->path_m3u = $this->m3u_file_list_idx;
					$this->m3u_file_list_idx = $new_value;
					$this->refresh_list_files($new_value);
					$add_params['path_not_to_file'] = false;

					return
						ActionFactorySafe::reset_controls($this->get_export_m3u_dialog_controls_defs($add_params), null, 0);

				case 'm3u_fname_field':
					$sel_control_idx = 0;
					$add_params['path_not_to_file'] = false;

					if (!empty($new_value) && !preg_match('/(\\\|\/)|(^\.*$)/', $new_value))
					{
						$this->m3u_fname == $new_value;
						$path = trim((is_dir(DUNE_MOUNTED_STORAGES_PATH . $this->plugin_cookies_playlist_export->path_m3u)? $this->plugin_cookies_playlist_export->path_m3u : str_replace(basename($this->plugin_cookies_playlist_export->path_m3u), '', $this->plugin_cookies_playlist_export->path_m3u)), '/');

						if (!file_exists(DUNE_MOUNTED_STORAGES_PATH . $path . '/' . $new_value))
							file_put_contents(DUNE_MOUNTED_STORAGES_PATH . $path . '/' . $new_value, '');

						$this->m3u_file_list_idx = $path . '/' . $new_value;
						$this->refresh_list_files($this->m3u_file_list_idx);
						$sel_control_idx = 1;
					}
					else
						$this->m3u_fname = 'playlist_' . $this->sub_locations_list_idx . '.m3u';

					return
						ActionFactorySafe::reset_controls($this->get_export_m3u_dialog_controls_defs($add_params), null, $sel_control_idx);

				case 'custom_epg_key':
					$this->plugin_cookies_customs_control->epg_key = $new_value;
					break;

				case 'custom_clock_key':
					$this->plugin_cookies_customs_control->clock_key = $new_value;
					break;

				case 'custom_clock_pos':
					$this->plugin_cookies_customs_control->clock_pos = $new_value;
					break;

				case 'custom_repeat_key':
					$this->plugin_cookies_customs_control->repeat_key = $new_value;
					break;

				default:
					if (preg_match('/epg_service_(\d*)_combo/', $control_id, $matches))
					{
						$epg_providers = $this->epg_providers;
						$epg_providers[$matches[1]] = $new_value;
						$this->epg_providers = array_values(array_unique(array_merge($epg_providers, $this->epg_providers)));

						return
							ActionFactory::reset_controls($this->get_epg_dialog_controls_defs($add_params));
					}

					$this->{str_replace(array('_combo', '_field'), '', $control_id)} = $new_value;
					$add_params[str_replace(array('_combo', '_field'), '', $control_id)] = $new_value;
					$most_idx = ($add_params['dialog_type'] == SettingsDialogsDefs::provider_opts)? 5 : (($add_params['dialog_type'] == SettingsDialogsDefs::plugin_opts)? ((DVB_PLAYBACK_AVAILABLE && file_exists(HomeTv::dvb_channels_playlist_url))? 11 : 10) : (($add_params['dialog_type'] == SettingsDialogsDefs::customs_ctrl)? ((DUNE_FIRMWARE_BN <= 9)? ((DUNE_FIRMWARE_BN == 9)? 3 : 2) : 6) : 1));
			}
		}
		else if ($user_input->action_type == 'apply')
		{
			switch ($control_id)
			{
				case 'ext_epg_enable_btn':
					$add_params['ext_epg_enable'] = ($add_params['ext_epg_enable'] == ControlSwitchDefs::switch_on)? ControlSwitchDefs::switch_off : ControlSwitchDefs::switch_on;

					return
						ActionFactory::reset_controls($this->get_epg_dialog_controls_defs($add_params));

				case 'epg_fill_enable_btn':
					$add_params['epg_fill_enable'] = ($add_params['epg_fill_enable'] == ControlSwitchDefs::switch_on)? ControlSwitchDefs::switch_off : ControlSwitchDefs::switch_on;

					return
						ActionFactory::reset_controls($this->get_epg_dialog_controls_defs($add_params));

				case 'epg_enable_btn':
					$add_params['ext_epg_enable'] = $this->plugin_cookies_epg->ext_enable;
					$add_params['epg_font_size'] = $this->plugin_cookies_epg->font_size;
					$add_params['epg_fill_enable'] = $this->plugin_cookies_epg->fill_enable;
					$add_params['epg_enabled'] = $this->plugin_cookies_epg->enabled;

					return
						ActionFactorySafe::show_dialog('Программа телепередач', $this->get_epg_dialog_controls_defs($add_params), true, self::CUSTOM_OPTS_DIALOG_WIDTH - 150, array('initial_sel_ndx' => (($this->plugin_cookies_epg->enabled == ControlSwitchDefs::switch_on)? 4 : 3) + count($this->epg_providers)));

				case 'epg_dialog_on_btn':
					$this->plugin_cookies_epg->providers = $this->epg_providers;

				case 'epg_dialog_off_btn':
					$this->plugin_cookies_epg->enabled = ($control_id == 'epg_dialog_on_btn')? ControlSwitchDefs::switch_on : ControlSwitchDefs::switch_off;
					$this->plugin_cookies_epg->ext_enable = $add_params['ext_epg_enable'];
					$this->plugin_cookies_epg->font_size = $add_params['epg_font_size'];
					$this->plugin_cookies_epg->fill_enable = $add_params['epg_fill_enable'];
					break;

				case 'http_secury_btn':
					$this->plugin_cookies_playback_http->secury_disable = ($this->plugin_cookies_playback_http->secury_disable == ControlSwitchDefs::switch_on)? ControlSwitchDefs::switch_off : ControlSwitchDefs::switch_on;

					return
						ActionFactory::reset_controls($this->get_playback_hls_dialog_controls_defs($add_params), null, 1);

				case 'do_show_scan_opts':
					$dialog_frame_style = $add_params['dialog_frame_style'];
					$add_params = null;

					return
						ActionFactorySafe::close_dialog_and_run(UserInputHandlerRegistry::create_action($this->plugin->tv, 'do_show_scan_opts', array('dialog_frame_style' => $dialog_frame_style, 'close_by_return' => false)));

				case 'step_by_step_wizard_prev_btn':
					$selected_idx = 0;
					$add_params['step_by_step_wizard_stage_number'] -= 1;
					$add_params['step_by_step_wizard_stage'] = array_pop($add_params['step_by_step_wizard_prev_step']);
					break;

				case 'step_by_step_wizard_next_btn':
					$selected_idx = 0;
					$prev_step = $add_params['step_by_step_wizard_stage'];

					switch ($add_params['step_by_step_wizard_stage'])
					{
						case 1:
							$add_params['my_provider'] = '';
							$add_params['interactive_tv'] = '';
							$add_params['udp_enable'] = '';
							$add_params['sdp_source'] = '';
							$add_params['net_speed'] = '';
							$add_params['step_by_step_wizard_stage'] += 1;
							break;

						case 2:
							$add_params['interactive_tv'] = '';
							$add_params['udp_enable'] = '';
							$add_params['sdp_source'] = '';
							$add_params['net_speed'] = '';
							$add_params['my_provider'] = '';
							$add_params['step_by_step_wizard_stage'] += 1;
							break;

						case 3:
							$add_params['warning_vmx_not_support_was_shown'] = false;
							$add_params['net_speed'] = empty($add_params['net_speed'])? 'adsl' : $add_params['net_speed'];
							$this->plugin_cookies_location->id = $this->sub_locations_list_idx;
							$plugin_cookies->location = json_encode($this->plugin_cookies_location);
							$this->plugin_cookies_playback_udp->udpxy->enabled = ($add_params['udp_enable'] == 'udpxy')? ControlSwitchDefs::switch_on : ControlSwitchDefs::switch_off;
							$this->plugin_cookies_playback_udp->enabled = ($add_params['my_provider'] == 'rt') && ($add_params['interactive_tv'] == 'itv') && in_array($add_params['udp_enable'], array('udp', 'udpxy'))? ControlSwitchDefs::switch_on : ControlSwitchDefs::switch_off;
							$plugin_cookies->playback_udp = json_encode($this->plugin_cookies_playback_udp);
							$this->plugin_cookies_playback_http->enabled = ControlSwitchDefs::switch_on;
							$this->plugin_cookies_playback_http->hls_bs_prefer = ((get_platform_kind() <> 'android') && ((DUNE_FIRMWARE_BN == 8) || (DUNE_FIRMWARE_BN > 9)))? HttpStreamsDefs::hls_cbr : HttpStreamsDefs::hls_abs;
							$plugin_cookies->playback_http = json_encode($this->plugin_cookies_playback_http);
							$plugin_cookies->qfilter = ($add_params['net_speed'] == 'adsl')? QualityDefs::lowest : (($add_params['net_speed'] == 'adsl2')? QualityDefs::middle : QualityDefs::highest);
							$this->plugin->tv->load_dvb_channels($plugin_cookies);
							$this->plugin->tv->load_channels($plugin_cookies);

						default:
							$add_params['step_by_step_wizard_stage'] += 1;
					}

					$add_params['step_by_step_wizard_stage_number'] += 1;

					if ($add_params['step_by_step_wizard_stage'] > $prev_step)
						$add_params['step_by_step_wizard_prev_step'][] = $prev_step;

					break;

				case 'refresh_entry_points':
				case 'soft_reset':
					return
						ActionFactorySafe::show_main_screen(ActionFactorySafe::stb_shell_reboot());

				case 'close_dialog':
					return
						ActionFactorySafe::close_dialog();

				case 'close_dialog_and_quit':
					return
						ActionFactorySafe::close_dialog_and_run(SplashScreen::close_and_run());

				case 'parental_btn':
					$add_params['parental_pin'] = '';
					$add_params['dialog_event'] = EventDefs::on_show;
					$controls = $this->get_parental_pin_dialog_controls_defs($add_params);

					return
						ActionFactorySafe::show_dialog($controls->title, $controls->defs, false, 1120);

				case 'auto_resume_enable_btn':
					$this->auto_resume_enable = ($this->auto_resume_enable == ControlSwitchDefs::switch_off)? ControlSwitchDefs::switch_on : ControlSwitchDefs::switch_off;
					break;

				case 'autoplay_enable_btn':
					$this->autoplay_enable = ($this->autoplay_enable == ControlSwitchDefs::switch_off)? ControlSwitchDefs::switch_on : ControlSwitchDefs::switch_off;
					break;

				case 'playback_dvb_btn':
					$this->plugin_cookies_playback_dvb->enabled = ($this->plugin_cookies_playback_dvb->enabled == ControlSwitchDefs::switch_off)? ControlSwitchDefs::switch_on : ControlSwitchDefs::switch_off;
					break;

				case 'playback_udp_enabled_on_btn':
				case 'playback_udp_enabled_off_btn':
					$this->plugin_cookies_playback_udp->enabled = ($control_id == 'playback_udp_enabled_on_btn')? ControlSwitchDefs::switch_on : ControlSwitchDefs::switch_off;

					if (($control_id == 'playback_udp_enabled_on_btn') && !$add_params['warning_vmx_not_support_was_shown'])
						if ((get_platform_kind() == 'android') || !file_exists('/firmware/lib/libvmclient.so'))
						{
							$add_params['warning_vmx_not_support_was_shown'] = true;
							$add_params['control_id'] = 'playback_udp_enabled_on_btn';
							return
								ActionFactorySafe::show_dialog(
									'ПРЕДУПРЕЖДЕНИЕ!',
									$this->get_warning_vmx_not_support_dialog_controls_defs($add_params),
									false,
									1300,
									array(
										'dialog_params' => array('frame_style' => $add_params['dialog_frame_style']),
									));
						}

					break;

				case 'playback_http_btn':
					$add_params['playback_http_enabled'] = $this->plugin_cookies_playback_http->enabled;

					return
						ActionFactorySafe::show_dialog('Параметры воспроизведения', $this->get_playback_hls_dialog_controls_defs($add_params), true, self::CUSTOM_OPTS_DIALOG_WIDTH - 150, array('initial_sel_ndx' => ($this->plugin_cookies_playback_http->enabled == ControlSwitchDefs::switch_on)? 4 : 3));

				case 'playback_hls_enabled_on_btn':
				case 'playback_hls_enabled_off_btn':
					$this->plugin_cookies_playback_http->enabled = ($control_id == 'playback_hls_enabled_on_btn')? ControlSwitchDefs::switch_on : ControlSwitchDefs::switch_off;

					if (($control_id == 'playback_hls_enabled_on_btn') && !$add_params['warning_vmx_not_support_was_shown'] && ($this->plugin_cookies_playback_http->hls_bs_prefer == HttpStreamsDefs::hls_cbr))
						if ((get_platform_kind() == 'android') || !file_exists('/firmware/lib/libvmclient.so'))
						{
							$add_params['warning_vmx_not_support_was_shown'] = true;
							$add_params['control_id'] = 'http_stream_type_combo';
							return ActionFactorySafe::show_dialog(
								'ПРЕДУПРЕЖДЕНИЕ!',
								$this->get_warning_vmx_not_support_dialog_controls_defs($add_params),
								false,
								1300,
								array(
									'dialog_params' => array('frame_style' => $add_params['dialog_frame_style']),
								));
						}

					break;

				case 'export_m3u_btn':
					$this->storages_list = get_local_storages_list();
					$this->m3u_file_list_idx = str_replace($this->storages_list['aliases'], $this->storages_list['names'], $this->plugin_cookies_playlist_export->path_m3u);
					$this->refresh_list_files($this->m3u_file_list_idx);
					$add_params['path_not_to_file'] = false;

					return
						ActionFactorySafe::show_dialog('Экспорт плейлиста в M3U', $this->get_export_m3u_dialog_controls_defs($add_params), true, 1250, array('initial_sel_ndx' => empty($this->m3u_file_list_idx)? 0 : (($this->plugin_cookies_playlist_export->enabled == ControlSwitchDefs::switch_on)? 2 : 1)));

				case 'export_to_m3u_on_btn':
					if (is_dir(DUNE_MOUNTED_STORAGES_PATH . $this->m3u_file_list_idx))
					{
						$add_params['path_not_to_file'] = true;

						return
							ActionFactorySafe::show_dialog('Экспорт плейлиста в M3U', $this->get_export_m3u_dialog_controls_defs($add_params), true, 1250);
					}

					if (file_exists(DUNE_MOUNTED_STORAGES_PATH . $this->m3u_file_list_idx))
					{
						$this->plugin_cookies_playlist_export->path_m3u = str_replace($this->storages_list['names'], $this->storages_list['aliases'], $this->m3u_file_list_idx);
						$this->plugin_cookies_playlist_export->enabled = ControlSwitchDefs::switch_on;
					}
					else
					{
						$add_params['path_not_to_file'] = true;

						return
							ActionFactorySafe::show_dialog('Экспорт плейлиста в M3U', $this->get_export_m3u_dialog_controls_defs($add_params), true, 1250);
					}

					break;

				case 'export_to_m3u_off_btn':
					$this->plugin_cookies_playlist_export->enabled = ControlSwitchDefs::switch_off;
					break;

				case 'set_pin_btn':
					if ($this->plugin_cookies_parental->enabled == ControlSwitchDefs::switch_off)
					{
						if ($add_params['parental_pin'] <> '')
						{
							$add_params['dialog_event'] = EventDefs::on_success;
							$this->plugin_cookies_parental->enabled = ControlSwitchDefs::switch_on;
							$this->plugin_cookies_parental->pin = md5(DuneSystem::$properties['plugin_name'] . $add_params['parental_pin']);
						}
						else
							$add_params['dialog_event'] = EventDefs::on_error;
					}
					else
					{
						if (md5(DuneSystem::$properties['plugin_name'] . $add_params['parental_pin']) === $this->plugin_cookies_parental->pin)
						{
							$add_params['dialog_event'] = EventDefs::on_success;
							$this->plugin_cookies_parental->enabled = ControlSwitchDefs::switch_off;
							$this->plugin_cookies_parental->pin = '';
						}
						else
							$add_params['dialog_event'] = EventDefs::on_error;
					}

					if ($add_params['dialog_event'] == EventDefs::on_success)
					{
						$plugin_cookies->parental = json_encode($this->plugin_cookies_parental);
						@file_put_contents(
							dirname(__FILE__) . '/dune_plugin.xml',
							str_replace(
								array('{name}', '{version}', '{version_index}', '{caption}', '{label}', '{auto_resume}', 'http://127.0.0.1/cgi-bin/plugins/home_tv/'),
								array($this->plugin->app_name, $this->plugin->app_version, $this->plugin->app_version_idx, $this->plugin->app_caption, $this->plugin->app_label, ($plugin_cookies->auto_resume_enable == ControlSwitchDefs::switch_on)? 'yes' : 'no', DuneSystem::$properties['plugin_cgi_url']),
								$this->plugin->tv->get_plugin_manifest_template($this->plugin_cookies_parental->enabled == ControlSwitchDefs::switch_on)));
					}

					$controls = $this->get_parental_pin_dialog_controls_defs($add_params);

					return
						ActionFactorySafe::close_dialog_and_run(ActionFactorySafe::show_dialog($controls->title, $controls->defs, false, 1120, array('initial_sel_ndx' => 1)));

				case 'history_btn':
					$add_params['dialog_frame_style'] = DIALOG_FRAME_STYLE_DEFAULT;

					return
						ActionFactorySafe::close_dialog_and_run(UserInputHandlerRegistry::create_action($this, 'show_dialog', array('dialog_type' => SettingsDialogsDefs::history_vers)));

				case 'favorites_enable_btn':
					$this->favorites_enable = ($this->favorites_enable == ControlSwitchDefs::switch_on)? ControlSwitchDefs::switch_off : ControlSwitchDefs::switch_on;
					break;

				case 'check_skin_palette_btn':
					$this->plugin_cookies_customs_control->check_skin_palette = ($this->plugin_cookies_customs_control->check_skin_palette == ControlSwitchDefs::switch_on)? ControlSwitchDefs::switch_off : ControlSwitchDefs::switch_on;
					break;

				case 'tv_archives_reload_when_resume_btn':
					$add_params['tv_archives_reload_when_resume'] = ($add_params['tv_archives_reload_when_resume'] == ControlSwitchDefs::switch_on)? ControlSwitchDefs::switch_off : ControlSwitchDefs::switch_on;

					return
						ActionFactorySafe::reset_controls($this->get_tv_archives_dialog_controls_defs($add_params), null, 1);

				case 'tv_archives_btn':
					$add_params['tv_archives_playback_stream_type'] = $this->plugin_cookies_tv_archives->playback_stream_type;
					$add_params['tv_archives_reload_when_resume'] = $this->plugin_cookies_tv_archives->reload_when_resume;
					$add_params['tv_archives_enabled'] = $this->plugin_cookies_tv_archives->enabled;

					return
						ActionFactorySafe::show_dialog('Параметры воспроизведения архивов', $this->get_tv_archives_dialog_controls_defs($add_params), true, 1320, array('initial_sel_ndx' => ($this->plugin_cookies_tv_archives->enabled == ControlSwitchDefs::switch_on)? 3 : 2));

				case 'tv_archives_on_btn':
				case 'tv_archives_off_btn':
					$this->plugin_cookies_tv_archives->enabled = ($control_id == 'tv_archives_on_btn')? ControlSwitchDefs::switch_on : ControlSwitchDefs::switch_off;
					$this->plugin_cookies_tv_archives->playback_stream_type = $add_params['tv_archives_playback_stream_type'];
					$this->plugin_cookies_tv_archives->reload_when_resume = $add_params['tv_archives_reload_when_resume'];
					break;

				case 'warning_vmx_not_support_dialog_apply_btn':
					$selected_idx = $most_idx - 1;

					if ($add_params['control_id'] == 'step_by_step_wizard_next_btn')
					{
						$add_params['interactive_tv'] == 'itv2';
						$prev_step = $add_params['step_by_step_wizard_stage'];
						$add_params['step_by_step_wizard_stage_number'] += 1;
						$add_params['step_by_step_wizard_stage'] = 9;

						if ($add_params['step_by_step_wizard_stage'] > $prev_step)
							$add_params['step_by_step_wizard_prev_step'][] = $prev_step;

					}
					else
					{
						$this->sdp_root_urls_list_idx = '';
						$this->plugin_cookies_playback_http->enabled = ControlSwitchDefs::switch_on;
						$this->plugin_cookies_playback_http->hls_bs_prefer = HttpStreamsDefs::hls_abs;
						$this->plugin_cookies_playback_udp->enabled = ControlSwitchDefs::switch_off;
					}

					break;

				case 'warning_vmx_not_support_dialog_cancel_btn':
					break;

				case 'save_btn':
					$this->plugin_cookies_location->id = $this->sub_locations_list_idx;
					$plugin_cookies->location = json_encode($this->plugin_cookies_location);
					$plugin_cookies->qfilter = $this->qfilter;
					$plugin_cookies->tv_archives = json_encode($this->plugin_cookies_tv_archives);
					$plugin_cookies->favorites_enable = $this->favorites_enable;
					$plugin_cookies->epg = json_encode($this->plugin_cookies_epg);
					$plugin_cookies->channels_search_delay = $this->channels_search_delay;
					$plugin_cookies->auto_resume_enable = $this->auto_resume_enable;
					$plugin_cookies->autoplay_enable = $this->autoplay_enable;
					$plugin_cookies->playback_dvb = json_encode($this->plugin_cookies_playback_dvb);
					$plugin_cookies->playback_udp= json_encode($this->plugin_cookies_playback_udp);
					$plugin_cookies->playback_http = json_encode($this->plugin_cookies_playback_http);
					$plugin_cookies->playlist_export = json_encode($this->plugin_cookies_playlist_export);
					$plugin_cookies->customs_control = json_encode($this->plugin_cookies_customs_control);
					$this->plugin->tv->load_dvb_channels($plugin_cookies);
					$this->plugin->tv->load_channels($plugin_cookies);
					$add_params = null;

					if ($this->auto_resume_enable <> $old_auto_resume_enable)
						@file_put_contents(
							dirname(__FILE__) . '/dune_plugin.xml',
							str_replace(
								array('{name}', '{version}', '{version_index}', '{caption}', '{label}', '{auto_resume}', 'http://127.0.0.1/cgi-bin/plugins/home_tv/'),
								array($this->plugin->app_name, $this->plugin->app_version, $this->plugin->app_version_idx, $this->plugin->app_caption, $this->plugin->app_label, ($plugin_cookies->auto_resume_enable == ControlSwitchDefs::switch_on)? 'yes' : 'no', DuneSystem::$properties['plugin_cgi_url']),
								$this->plugin->tv->get_plugin_manifest_template($this->plugin_cookies_parental->enabled == ControlSwitchDefs::switch_on)));

					Wink()->set_location($this->sub_locations_list_idx);

					if (NEWGUI_FEAUTURES_AVAILABLE)
					{
						EpfsHandler::refresh_tv_epfs($plugin_cookies);

						return
							EpfsHandler::invalidate_folders(null, $this->out_action);
					}

					return $this->out_action;
			}
		}

		return
			ActionFactorySafe::reset_controls($this->get_settings_dialog_controls_defs($add_params), UserInputHandlerRegistry::create_action($this, 'refresh'), $selected_idx);
	}

	///////////////////////////////////////////////////////////////////////////

	protected function ensure_folder_views(&$plugin_cookies)
	{
		$this->folder_views = $this->do_get_folder_views($plugin_cookies);

		if (is_null($this->folder_views))
			throw new Exception(get_class($this).': Failed to get folder views');
	}

	protected function do_get_folder_views(&$plugin_cookies)
	{
		return
			$this->get_plugin_settings_folder_views(self::$show_widget, $plugin_cookies);
	}

	///////////////////////////////////////////////////////////////////////////

	public function __construct(&$plugin)
	{
		$this->plugin = $plugin;
		parent::__construct(self::ID);
		UserInputHandlerRegistry::get_instance()->register_handler($this);
		DefaultDunePlugin::create_screen($this);
	}

	public function get_action_map(MediaURL $media_url, &$plugin_cookies)
	{
		$actions =
			array
			(
				GUI_EVENT_KEY_SETUP => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_SETUP),
				GUI_EVENT_KEY_ENTER => UserInputHandlerRegistry::create_action($this, GUI_EVENT_KEY_ENTER),
			);

		return $actions;
	}

	public function get_handler_id()
	{
		return self::ID . '_handler';
	}

	public function initialize(&$add_params, &$plugin_cookies)
	{
		$this->qfilter = $plugin_cookies->qfilter;
		$this->favorites_enable = $plugin_cookies->favorites_enable;
		$this->channels_search_delay = $plugin_cookies->channels_search_delay;
		$this->auto_resume_enable = $plugin_cookies->auto_resume_enable;
		$this->autoplay_enable = $plugin_cookies->autoplay_enable;
		$this->epg_providers = $this->plugin->tv->get_epg_providers($plugin_cookies);
		$this->plugin_cookies_epg = json_decode($plugin_cookies->epg);
		$this->plugin_cookies_tv_archives = json_decode($plugin_cookies->tv_archives);
		$this->plugin_cookies_parental = json_decode($plugin_cookies->parental);
		$this->plugin_cookies_playback_dvb = json_decode($plugin_cookies->playback_dvb);
		$this->plugin_cookies_playback_udp = json_decode($plugin_cookies->playback_udp);
		$this->plugin_cookies_playback_http = json_decode($plugin_cookies->playback_http);
		$this->plugin_cookies_playlist_export = json_decode($plugin_cookies->playlist_export);
		$this->plugin_cookies_customs_control = json_decode($plugin_cookies->customs_control);
		$this->plugin_cookies_location = json_decode($plugin_cookies->location);
		$location_info = Wink()->get_location_info($this->plugin_cookies_location->id);
		$this->sub_locations_list_idx = $location_info->sub_location_id;
		$this->plugin_cookies_app_version = $plugin_cookies->app_version;
		$this->system_settings = get_shell_settings();
		$this->m3u_fname = $this->plugin->app_name . '_playlist.m3u';
		$this->m3u_file_list = array();
		$this->m3u_file_list_idx = '';

		foreach (Wink()->get_locations_list() as $id => $name)
		{
			$this->macro_locations_list[$id] = $name;

			foreach (Wink()->get_locations_list($id) as $sub_id => $sub_name)
				$this->sub_locations_list[$id][strval($sub_id)] = $sub_name;
		}

		if (!isset($this->macro_locations_list[$this->sub_locations_list_idx]))
		{
			foreach ($this->sub_locations_list as $id => $data)
				foreach ($data as $sub_id => $sub_data)
					if ($sub_id == $this->sub_locations_list_idx)
					{
						$this->macro_locations_list_idx = $id;
						break 2;
					}
		}
		else
			$this->macro_locations_list_idx = $this->sub_locations_list_idx;
	}

	public function handle_user_input(&$user_input, &$plugin_cookies)
	{
		static $add_params;

		$control_id = $user_input->control_id;

		switch ($control_id)
		{
			case 'reset_settings_dialog_return_key':
				if ($add_params['settings_was_reset'] || $add_params['data_cache_was_clear'])
					return null;

				return
					ActionFactorySafe::close_dialog();

			case 'ops_selector_combo':
				$add_params['ops_selector_combo'] = $user_input->{$control_id};

				return
					ActionFactorySafe::reset_controls($this->get_reset_settings_dialog_controls_defs($add_params));

			case 'reset_settings_apply_btn':
				if ($add_params['ops_selector_combo'] == 'clear_epg_cache')
				{
					$add_params['epg_cache_files_count'] = 0;
					$add_params['epg_cache_used_bytes'] = 0;
					$cache_paths = array();

					foreach($this->plugin->epg->get_disk_cache_info() as $cache_info)
					{
						$apps_empty = true;
						$app_found = false;
						$cache_paths[] = $cache_info['base_dir'];

						foreach($cache_info['apps'] as $app)
							if ($app['name'] == DuneSystem::$properties['plugin_name'])
								$app_found = true;
							else
								$apps_empty = false;

						if ($app_found || $apps_empty)
						{
							$add_params['epg_cache_files_count'] += $cache_info['files_count'];
							$add_params['epg_cache_used_bytes'] += $cache_info['used_bytes'];
						}
					}

					$this->plugin->epg->clear_cache();
					$add_params['epg_cache_was_clear'] = true;
					$add_params['epg_cache_clear_error'] = false;
					clearstatcache();

					foreach($cache_paths as $path)
						if (file_exists($path))
						{
							$add_params['epg_cache_clear_error'] = true;
							break;
						}

					return
						ActionFactorySafe::reset_controls($this->get_reset_settings_dialog_controls_defs($add_params));
				}

				$this->plugin->tv->parental = json_decode($plugin_cookies->parental);

				if (($this->plugin->tv->parental->enabled == ControlSwitchDefs::switch_on) && !$this->plugin->tv->parental_passed)
					return
						$this->plugin->tv->get_input_pin_dialog_action($this);

				if ($add_params['settings_was_reset'])
					return
						ActionFactorySafe::stb_reboot();

				if ($add_params['data_cache_was_clear'])
					return
						ActionFactorySafe::show_main_screen(ActionFactorySafe::stb_shell_reboot());

				if (($add_params['ops_selector_combo'] == 'reset_settings_and_clear_data_cache') ||
					($add_params['ops_selector_combo'] == 'reset_settings'))
				{
					if (file_exists('/config/libViewRightWebClient.so'))
						unlink('/config/libViewRightWebClient.so');

					@file_put_contents('/tmp/home_tv_parental_str', $plugin_cookies->parental);
					$this->plugin->launcher->reset_plugin_settings($plugin_cookies);
					$add_params['settings_was_reset'] = true;
				}

				if (($add_params['ops_selector_combo'] == 'reset_settings_and_clear_data_cache') ||
					($add_params['ops_selector_combo'] == 'clear_data_cache')) {
					shell_exec('rm -rf ' . TEMPORARY_CACHE_PATH . '/*');
					shell_exec('rm -rf ' . LOCAL_CACHE_PATH . '/*');
					shell_exec('rm -rf ' . CUSTOM_EPG_SCREEN_BG_PATH . '/*');
					$add_params['data_cache_was_clear'] = true;
				}

				if (isset($plugin_cookies->tv_reminders))
					$plugin_cookies->tv_reminders = 'a:0:{}';

				@file_put_contents('/tmp/home_tv_was_installed_mark', '');

				return
					ActionFactorySafe::reset_controls($this->get_reset_settings_dialog_controls_defs($add_params));

			case 'show_reset_settings_dialog':
				$add_params['ops_selector_combo'] = 'clear_epg_cache';
				$add_params['settings_was_reset'] = false;
				$add_params['data_cache_was_clear'] = false;
				$add_params['epg_cache_was_clear'] = false;

				return
					ActionFactorySafe::show_dialog(
						$this->plugin->app_caption . ': ' . self::get_dialog_caption(SettingsDialogsDefs::reset_settings),
						$this->get_reset_settings_dialog_controls_defs($add_params),
						false,
						900,
						array
						(
							'actions' =>
								array
								(
									GUI_EVENT_KEY_RETURN => UserInputHandlerRegistry::create_action($this, 'reset_settings_dialog_return_key'),
								)
						));

			case 'soft_reset':
				return ActionFactorySafe::stb_shell_reboot();

			case 'pin_field':
				if ($this->plugin->tv->parental_passed = (md5(DuneSystem::$properties['plugin_name'] . $user_input->pin_field) === $this->plugin->tv->parental->pin))
					return
						ActionFactorySafe::close_dialog_and_run(UserInputHandlerRegistry::create_action($this, 'reset_settings_apply_btn'));

				return
					ActionFactorySafe::close_dialog();

			case 'input_pin_dialog_press_key_return':
				return ActionFactorySafe::close_dialog();

			case GUI_EVENT_KEY_ENTER:
				if (!isset($user_input->selected_media_url))
					return null;

				if ($user_input->selected_media_url == TvGroupsScreen::ID)
					return
						ActionFactorySafe::open_folder(TvGroupsScreen::get_media_url_str(TvBrowseModeDefs::full));//FoldersManager::open_folder(TvGroupsScreen::get_media_url_str(TvBrowseModeDefs::full));
				else if ($user_input->selected_media_url == 'reset_settings')
					return
						UserInputHandlerRegistry::create_action($this, 'show_reset_settings_dialog');

				$post_action =
					ActionFactorySafe::invalidate_folders(
						array
						(
							empty($this->plugin->tv->parent_media_url_str)? '' : $this->plugin->tv->parent_media_url_str,
							TvGroupsScreen::get_media_url_str(),
							TvChannelsScreen::get_active_media_url_str(),
							TvFavoritesScreen::get_active_media_url_str(),
						)
					);

				return
					$this->show_dialog($user_input->selected_media_url, DIALOG_FRAME_STYLE_DEFAULT, $post_action);
		}

		return
			$this->dialog_handle_user_input($user_input, $plugin_cookies);
	}

	public function show_dialog($dialog_type, $dialog_frame_style, $post_action = null)
	{
		$this->out_action = $post_action;
		$action = UserInputHandlerRegistry::create_action(
			$this,
			'show_dialog',
			array(
				'dialog_type' => $dialog_type,
				'dialog_frame_style' => $dialog_frame_style,
			)
		);

		return $action;
	}

	public function get_all_folder_items(MediaURL $media_url, &$plugin_cookies)
	{
		return
			array(
				array(
					PluginRegularFolderItem::media_url => SettingsDialogsDefs::provider_opts,
					PluginRegularFolderItem::caption => self::get_dialog_caption(SettingsDialogsDefs::provider_opts),
					PluginRegularFolderItem::view_item_params => array(
						ViewItemParams::icon_path => 'plugin_file://img/location_opts.png'),
					PluginRegularFolderItem::starred => false),
				array(
					PluginRegularFolderItem::media_url => SettingsDialogsDefs::plugin_opts,
					PluginRegularFolderItem::caption => self::get_dialog_caption(SettingsDialogsDefs::plugin_opts),
					PluginRegularFolderItem::view_item_params => array(
						ViewItemParams::icon_path => 'plugin_file://img/opt_plugin.png'),
					PluginRegularFolderItem::starred => false),
				array(
					PluginRegularFolderItem::media_url => SettingsDialogsDefs::parental_ctrl,
					PluginRegularFolderItem::caption => self::get_dialog_caption(SettingsDialogsDefs::parental_ctrl),
					PluginRegularFolderItem::view_item_params => array(
						ViewItemParams::icon_path => 'plugin_file://img/parental_control.png'),
					PluginRegularFolderItem::starred => false),
				array(
					PluginRegularFolderItem::media_url => SettingsDialogsDefs::customs_ctrl,
					PluginRegularFolderItem::caption => self::get_dialog_caption(SettingsDialogsDefs::customs_ctrl),
					PluginRegularFolderItem::view_item_params => array(
						ViewItemParams::icon_path => 'plugin_file://img/custom_controls.png'),
					PluginRegularFolderItem::starred => false),
				array(
					PluginRegularFolderItem::media_url => TvGroupsScreen::ID,
					PluginRegularFolderItem::caption => 'Список каналов',
					PluginRegularFolderItem::view_item_params => array(
						ViewItemParams::icon_path => 'plugin_file://img/tv_channels.png'),
					PluginRegularFolderItem::starred => false),
				array(
					PluginRegularFolderItem::media_url => SettingsDialogsDefs::about_plugin,
					PluginRegularFolderItem::caption => self::get_dialog_caption(SettingsDialogsDefs::about_plugin),
					PluginRegularFolderItem::view_item_params => array(
						ViewItemParams::icon_path => 'plugin_file://img/about.png'),
					PluginRegularFolderItem::starred => false),
				array(
					PluginRegularFolderItem::media_url => SettingsDialogsDefs::reset_settings,
					PluginRegularFolderItem::caption => self::get_dialog_caption(SettingsDialogsDefs::reset_settings),
					PluginRegularFolderItem::view_item_params => array(
						ViewItemParams::icon_path => 'plugin_file://img/reset_settings.png',
						ViewItemParams::item_badge_icon_path => 'plugin_file://img/button_yellow.png'),
					PluginRegularFolderItem::starred => false));
	}
}

///////////////////////////////////////////////////////////////////////////
?>