<?php
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2010 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Ajax загрузчик формы списка информационных групп и элементов.
 *
 * Файл: /admin/InformationSystems/action/load_information_groups.php
 *
 * @author Hostmake LLC
 * @version 5.x
 */
function LoadAjaxData(&$admin_forms)
{
	$on_page = $admin_forms->GetOnPageCount();
	$page = to_int($_REQUEST['limit']);
	$begin = ($page == 0) ? 0 : ($page - 1) * $on_page;

	$param = array();

	$param['limit']['all'] = array('begin' => $begin, 'count' => $on_page);

	$information_system_id = to_int($_REQUEST['information_system_id']);
	$information_groups_parent_id = to_int($_REQUEST['information_groups_parent_id']);

	$InformationSystem = & singleton('InformationSystem');
		
	// Строим "хлебные крошки"
	$path_array = $InformationSystem->GetInformationGroupsPathArray($information_groups_parent_id, $information_system_id);
		
	$new_path_array = array();

	$new_path_array[] = array(
	'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', ' ', 11, 'load_data'),
	'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', ' ', 11, 'load_data'),
	'name' => $GLOBALS['MSG_information_systems']['show_information_systems_title']);

	// Путь по группам инфосистем
	$information_systems_dir_parent_id = to_int($_REQUEST['information_systems_dir_parent_id']);
	
	if ($information_systems_dir_parent_id)
	{
		$information_systems_dir_path_array = $InformationSystem->GetInformationSystemsDirPathArray($information_systems_dir_parent_id);
		
		// Меняем порядок следования элементов в массиве на обратный
		$information_systems_dir_path_array = array_reverse($information_systems_dir_path_array, true);
		
		foreach ($information_systems_dir_path_array as $key => $value)
		{
			$new_path_array[] = array (
			'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_systems_dir_parent_id={$key}", 11, 'load_data'),
			'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&information_systems_dir_parent_id={$key}", 11, 'load_data'),
			'name' => $value['information_systems_dir_name']);
		}
	}	
	
	// Меняем порядок следования элементов в массиве на обратный
	$path_array = array_reverse($path_array, true);

	// Преобразуем идентификаторы групп в ссылки на группы.
	if ($path_array)
	{
		foreach ($path_array as $information_groups_parent_id => $value)
		{
			$new_path_array[] = array (
			'link' => $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_groups&information_groups_parent_id={$information_groups_parent_id}&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 12, 'load_data'),
			'onclick' => $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_groups&information_groups_parent_id={$information_groups_parent_id}&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 12, 'load_data'),
			'name' => $value['information_groups_name']);
		}
	}

	$param['path_array'] = $new_path_array;

	// Запрос для выборки информационных групп инфосистемы.
	$param['data'][] = "SELECT information_groups_id AS key_field, information_groups_name AS name,
	information_groups_allow_indexation AS indexation_field,
	information_systems_id AS information_systems_id,	
	information_groups_parent_id,
	information_groups_name AS date,
	information_groups_activity AS status_field,
	information_groups_order AS order_field
	FROM `information_groups_table`
	WHERE `information_systems_id`= '$information_system_id'
	AND `information_groups_parent_id` = '$information_groups_parent_id' 
	{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Количество информационных групп
	$count_groups = "SELECT count(information_groups_id) as count
	FROM `information_groups_table`
	WHERE `information_systems_id`= '$information_system_id'
	AND `information_groups_parent_id` = '$information_groups_parent_id'
	{FILTER_STRING}";	

	// Запрос для выборки информационных элементов.
	$param['data'][] = "SELECT information_items_table.*,
	information_items_table.information_systems_id AS information_systems_id,
	information_items_table.information_items_id AS key_field,
	information_items_table.information_groups_id AS information_groups_parent_id, 
	information_items_table.information_items_name AS name, 
	information_items_table.information_items_status AS status_field, 
	information_items_table.information_items_allow_indexation AS indexation_field, 
	count( comment_table.comment_id ) AS comment_field,
	information_items_date AS date,
	information_items_table.information_items_putend_date AS date_end,
	information_items_order AS order_field	
	FROM `information_items_table` LEFT JOIN `comment_table` 
	ON information_items_table.information_items_id = comment_table.information_items_id
	WHERE information_items_table.information_systems_id = $information_system_id
	AND `information_groups_id` = $information_groups_parent_id  {FILTER_STRING} 
	GROUP BY information_items_table.information_items_id {ORDER_STRING} {LIMIT}";

	// Посчитаем общее число информационных элементов.
	$count = "SELECT count(information_items_id) as count
	FROM `information_items_table`
	WHERE `information_systems_id`= '$information_system_id'
	AND `information_groups_id` = '$information_groups_parent_id'
	{FILTER_STRING}";

	// Формируем верхнее меню.
	$k = 0;

	$menu = array();
	$menu[$k]['name'] = $GLOBALS['MSG_information_systems']['information_system_top_menu_items'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$sub_menu = array();
	$sub_menu[$p = 0]['name'] = $GLOBALS['MSG_information_systems']['show_information_groups_link2'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_group_item', 'check_1_0', 12, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_group_item', 'check_1_0', 12, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/page_add.gif';

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_information_systems']['show_information_groups_link3'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_propertys_items&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 50, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_propertys_items&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 50, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/page_gear.gif';

	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	$menu[++$k]['name'] = $GLOBALS['MSG_information_systems']['information_system_top_menu_groups'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$p = 0;

	// Добавление группы
	$sub_menu = array();

	$sub_menu[$p]['name'] = $GLOBALS['MSG_information_systems']['show_information_groups_link1'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_group_item', 'check_0_0', 12, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_group_item', 'check_0_0', 12, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/folder_add.gif';

	// Свойства групп
	$sub_menu[++$p]['name'] = $GLOBALS['MSG_information_systems']['show_information_groups_link4'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_propertys_groups&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 51, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_information_propertys_groups&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 51, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/folder_gear.gif';

	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	$p = 0;

	$menu[++$k]['name'] = $GLOBALS['MSG_information_systems']['show_all_comments_top_menu'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$sub_menu = array();

	$sub_menu[$p]['name'] = $GLOBALS['MSG_information_systems']['show_comments_link_show_all_comments'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_comments&all_comments_system=1&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 52, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/InformationSystems/InformationSystems.php', "&action=show_comments&all_comments_system=1&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 52, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/comments.gif';

	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	// Формируем массив меню.
	$menu_array = array();
	$menu_array[] = $menu;

	// Для первого набора данных общее количство не указываем, т.к. передаем все элементы,
	// для второго набора данных указываем в виде запроса.
	$param['total_count'][0] = $count_groups;
	$param['total_count'][1] = $count;

	// В поле с картинкой отображаем значек папки. Т.к. изображение для поля задается в
	// формате <Значение поля>=<Путь к изображению> и поле не имеет значения, поэтому
	// присваиваемое значение имеет данный вид
	$param['field_params'][0][46]['admin_forms_field_image'] = "=/admin/images/folder.gif";

	if (class_exists('Sns') && class_exists('SiteUsers'))
	{
		$Sns = & singleton('Sns');

		// Информационная система, в которую входит группа, связана с блогом
		if ($sns_info = $Sns->GetSnsAssociatedInformationSystem($information_system_id))
		{			
			// корневая группа
			if ($information_groups_parent_id == 0)
			{
				$param['field_params'][0][49]['admin_forms_field_image'] = "=/admin/images/users_group.gif";
				$param['field_params'][0][49]['admin_forms_field_alt'] = "=" . $GLOBALS['MSG_information_systems']['information_group_site_users_groups']
				. "\n1=".$GLOBALS['MSG_information_systems']['information_group_site_users_groups'];
				$param['field_params'][0][49]['admin_forms_field_title'] = "=" . $GLOBALS['MSG_information_systems']['information_group_site_users_groups']
				. "\n1=" . $GLOBALS['MSG_information_systems']['information_group_site_users_groups'];

				$param['field_params'][0][49]['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallDoLoadAjax($admin_forms->AAction, "&information_groups_parent_id={$information_groups_parent_id}&information_group_id={key_field}&information_item_id=0&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 174, 'load_data');
				$param['field_params'][0][49]['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax($admin_forms->AAction, "&information_groups_parent_id={$information_groups_parent_id}&information_group_id={key_field}&information_item_id=0&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 174, 'load_data');

				$param['field_params'][0][49]['admin_forms_field_name'] = '';
			}

			$param['field_params'][1][49]['admin_forms_field_image'] = "=/admin/images/users_group.gif";
			$param['field_params'][1][49]['admin_forms_field_alt'] = "=" . $GLOBALS['MSG_information_systems']['information_group_site_users_groups']
			. "\n1=".$GLOBALS['MSG_information_systems']['information_group_site_users_groups'];
			$param['field_params'][1][49]['admin_forms_field_title'] = "=" . $GLOBALS['MSG_information_systems']['information_group_site_users_groups']
			. "\n1=" . $GLOBALS['MSG_information_systems']['information_group_site_users_groups'];

			$param['field_params'][1][49]['admin_forms_field_onclick'] = $admin_forms->GetOnClickCallDoLoadAjax($admin_forms->AAction, "&information_groups_parent_id={$information_groups_parent_id}&information_group_id=0&information_item_id={key_field}&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 174, 'load_data');
			$param['field_params'][1][49]['admin_forms_field_link'] = $admin_forms->GetHtmlCallDoLoadAjax($admin_forms->AAction, "&information_groups_parent_id={$information_groups_parent_id}&information_group_id=0&information_item_id={key_field}&information_systems_dir_parent_id={$information_systems_dir_parent_id}&information_system_id={$information_system_id}", 174, 'load_data');

			$param['field_params'][1][49]['admin_forms_field_name'] = '';
		}
	}

	if (!isset($sns_info) || $information_groups_parent_id != 0)
	{
		// В поле Активность для информационных групп не отображаем индикатор активности
		$param['field_params'][0][49]['admin_forms_field_alt'] = "0=" . $GLOBALS['MSG_information_systems']['information_group_is_active']
		. "\n1=" . $GLOBALS['MSG_information_systems']['information_group_is_active'];
		$param['field_params'][0][49]['admin_forms_field_title'] = "0=" . $GLOBALS['MSG_information_systems']['information_group_is_active']
		. "\n1=" . $GLOBALS['MSG_information_systems']['information_group_is_active'];

		$param['field_params'][1][49]['admin_forms_field_alt'] = "0=".$GLOBALS['MSG_information_systems']['information_item_is_active']
		. "\n1=".$GLOBALS['MSG_information_systems']['information_item_is_active'];
		$param['field_params'][1][49]['admin_forms_field_title'] = "0=".$GLOBALS['MSG_information_systems']['information_item_is_active']
		. "\n1=".$GLOBALS['MSG_information_systems']['information_item_is_active'];
	}

	$param['field_params'][0][50]['admin_forms_field_alt'] = "0=".$GLOBALS['MSG_information_systems']['information_group_is_indexation']
	. "\n1=".$GLOBALS['MSG_information_systems']['information_group_is_indexation'];
	$param['field_params'][0][50]['admin_forms_field_title'] = "0=".$GLOBALS['MSG_information_systems']['information_group_is_indexation']
	. "\n1=".$GLOBALS['MSG_information_systems']['information_group_is_indexation'];

	$param['field_params'][1][50]['admin_forms_field_alt'] = "0=".$GLOBALS['MSG_information_systems']['information_item_is_indexation']
	. "\n1=".$GLOBALS['MSG_information_systems']['information_item_is_indexation'];
	$param['field_params'][1][50]['admin_forms_field_title'] = "0=".$GLOBALS['MSG_information_systems']['information_item_is_indexation']
	. "\n1=".$GLOBALS['MSG_information_systems']['information_item_is_indexation'];


	$param['current_page'] = $page;
	$param['on_page'] = $on_page;
	$param['menus'] = $menu_array;

	$row_information_system = $InformationSystem->GetInformationSystem($information_system_id);

	// Заголовок формы
	$param['title'] = sprintf($GLOBALS['MSG_information_systems']['show_information_groups_title'], $row_information_system['information_systems_name']);

	$param['field_params'][0]['name']['admin_forms_field_type'] = 10;// вычисляемое поле
	$param['field_params'][0]['name']['callback_function'] = 'callback_function_group_name';

	// Функция обратного вызова для названия группы
	function callback_function_group_name($field_value, $value, $row)
	{
		$admin_forms = & singleton('admin_forms');

		$InformationSystem = & singleton('InformationSystem');
				
		$row['information_systems_dir_parent_id'] = to_int($_REQUEST['information_systems_dir_parent_id']);
		
		$link = $field_value['admin_forms_field_link'];
		$onclick = to_str($field_value['admin_forms_field_onclick']);
								
		$link = $admin_forms->DoReplaces(false, $row, $link);						
		$onclick = $admin_forms->DoReplaces(false, $row, $onclick);
		
		if ($row['status_field'] == 0)
		{
			$prefix = '<div style="text-decoration: line-through">';
			$suffix = '</div>';
		}
		else
		{
			$prefix = '';
			$suffix = '';
		}
		?><?php echo $prefix?><a href="<?php echo $link?>" onclick="<?php echo $onclick?>"><?php echo $value?></a><?php echo $suffix?><?php
		
		// Группа активна - выводим ссылку на клиентский раздел
		if ($row['status_field'] == 1)
		{
			// Получаем данные об ИС
			$infsys_row = $InformationSystem->GetInformationSystem($row['information_systems_id']);
			
			if ($infsys_row)
			{
				$site = & singleton('site');
				$current_alias = $site->GetCurrentAlias($infsys_row['site_id']);
				
				$Structure = & singleton('Structure');
				
				// Информацию о пути к инфосистеме получаем по идентификатору узла структуры, с которым связана инфосистема
				$url = $Structure->GetStructurePath($infsys_row['structure_id'], 0);
	
				if ($url != '/')
				{
					$url = '/' . $url;
				}
			
				?>&nbsp;<a href="<?php echo 'http://' . $current_alias . $url . $InformationSystem->GetPathGroup($row['key_field'], '')?>" target="_blank"><img src="/admin/images/new_window.gif" class="img_line" /></a><?php
			}
		}
	}

	$param['field_params'][1]['name']['admin_forms_field_type'] = 10;// вычисляемое поле
	$param['field_params'][1]['name']['callback_function'] = 'callback_function_item_name';

	// Функция обратного вызова для названия элемента
	function callback_function_item_name($field_value, $value, $row)
	{
		$InformationSystem = & singleton('InformationSystem');
		
		// Элемент является ярлыком
		if ($row['information_items_shortcut_id'] != 0)
		{
			//Получаем информацию о информационном элементе, на который ссылается ярлык
			$item_row = $InformationSystem->GetInformationSystemItem($row['information_items_shortcut_id']);
			
			$row['name'] = $item_row['information_items_name'];
			$row['date_end'] = $item_row['information_items_putend_date'];
			// Нельзя, т.к. ярлык может сам по себе быть выключен 
			//$row['information_items_status'] = $item_row['information_items_status'];
		}

		if ($row['date_end'] != "0000-00-00 00:00:00" && $row['date_end'] < date("Y-m-d H:i:s")
		|| $row['information_items_status'] == 0
		// Ярлык может быть отдельно выключен
		|| isset($item_row['information_items_status']) && $item_row['information_items_status']  == 0)
		{
			?><div style="text-decoration: line-through"><?php echo htmlspecialchars($row['name'])?></div><?php
		}
		else
		{
			// Получаем данные об ИС
			$infsys_row = $InformationSystem->GetInformationSystem($row['information_systems_id']);
			
			if ($infsys_row)
			{
				$site = & singleton('site');
				$current_alias = $site->GetCurrentAlias($infsys_row['site_id']);
			
				$Structure = & singleton('Structure');
				
				// Информацию о пути к инфосистеме получаем по идентификатору узла структуры, с которым связана инфосистема
				$url = $Structure->GetStructurePath($infsys_row['structure_id'], 0);
	
				if ($url != '/')
				{
					$url = '/' . $url;
				}
			
				echo htmlspecialchars($row['name']);
				?>&nbsp;<a href="<?php echo 'http://' . $current_alias . $url . $InformationSystem->GetPathItem($row['information_items_id'], '')?>" target="_blank"><img src="/admin/images/new_window.gif" class="img_line" /></a><?php
			}
		}
	}

	$param['field_params'][0]['comment_field']['callback_function'] = 'callback_function_item_comments';
	$param['field_params'][1]['comment_field']['callback_function'] = 'callback_function_item_comments';

	// Функция обратного вызова для отображения комментариев элемента
	function callback_function_item_comments($field_value, $value, $row)
	{
		//var_dump($row);

		// Отображаем элемент/ярлык
		if (isset($row['information_items_id']))
		{
			// Элемент
			if ($row['information_items_shortcut_id'] == 0)
			{
				?><a href="/admin/InformationSystems/InformationSystems.php?admin_forms_id=52&operation=load_data&action=show_comments&information_systems_dir_parent_id=<?php echo $_REQUEST['information_systems_dir_parent_id']?>&information_system_id=<?php echo $row['information_systems_id']; ?>&information_groups_parent_id=<?php echo $row['information_groups_id'];?>&information_item_id=<?php echo $row['information_items_id']?>"
					onclick="DoLoadAjax('/admin/InformationSystems/InformationSystems.php', '&action=show_comments&information_systems_dir_parent_id=<?php echo $_REQUEST['information_systems_dir_parent_id'];?>&information_system_id=<?php echo $row['information_systems_id']; ?>&information_groups_parent_id=<?php echo $row['information_groups_id'];?>&information_item_id=<?php echo $row['information_items_id']?>', 52, 'load_data', '', '', '', ''); return false;"><?php echo $row['comment_field']; ?></a>
				<?php
			}
			else // Ярлык
			{				
				$DataBase = & singleton('DataBase');
				$InformationSystem = & singleton('InformationSystem');

				$query = "SELECT information_items_table.*, COUNT(comment_id) AS count_comments
					FROM `information_items_table` LEFT JOIN `comment_table` 
					ON information_items_table.information_items_id = comment_table.information_items_id 
					WHERE information_items_table.information_items_id = " . intval($row['information_items_shortcut_id']);

				$item_comment_resource = $DataBase->select($query);

				$item_comment_row = mysql_fetch_assoc($item_comment_resource);
				
				// Полчаем данные о информационной системе
				$information_system_row = $InformationSystem->GetInformationSystem($item_comment_row['information_systems_id']);
				
				?>
				<a href="/admin/InformationSystems/InformationSystems.php?admin_forms_id=52&operation=load_data&action=show_comments&information_systems_dir_parent_id=<?php echo $information_system_row['information_systems_dir_id']?>&information_system_id=<?php echo $item_comment_row['information_systems_id']; ?>&information_groups_parent_id=<?php echo $item_comment_row['information_groups_id'];?>&information_item_id=<?php echo $item_comment_row['information_items_id']?>"
					onclick="DoLoadAjax('/admin/InformationSystems/InformationSystems.php', '&action=show_comments&information_systems_dir_parent_id=<?php echo $information_system_row['information_systems_dir_id']?>&information_system_id=<?php echo $item_comment_row['information_systems_id']; ?>&information_groups_parent_id=<?php echo $item_comment_row['information_groups_id'];?>&information_item_id=<?php echo $item_comment_row['information_items_id']?>', 52, 'load_data', '', '', '', ''); return false;"><?php echo $item_comment_row['count_comments']; ?></a>
				<?php
			}
		}		
	}

	// Доп. параметры
	$admin_forms->external_replaces['{information_systems_dir_parent_id}']= $information_systems_dir_parent_id;
	
	return $param;
}

// Необязательная функция для определения реального имени столбца по псевдониму.
function ResolveFieldName(&$field_name, $dataset_id)
{
	switch ($dataset_id)
	{
		case 0: // Список информационных групп.
			{
				if ($field_name == 'name')
				{
					$field_name = 'information_groups_name';
				}
				elseif ($field_name == 'key_field')
				{
					$field_name = 'information_groups_id';
				}
				elseif ($field_name == 'indexation_field')
				{
					$field_name = 'information_groups_allow_indexation';
				}
				elseif ($field_name == 'date')
				{
					$field_name = 'information_groups_name';
				}
				elseif ($field_name == 'comment_field')
				{
					$field_name = 'information_groups_name';
				}
				elseif ($field_name == 'status_field')
				{
					$field_name = 'information_groups_activity';
				}
				elseif ($field_name == 'order_field')
				{
					$field_name = 'information_groups_order';
				}

				break;
			}
		case 1: // Список информационных элементов.
			{
				if ($field_name == 'name')
				{
					$field_name = 'information_items_name';
				}
				elseif ($field_name == 'key_field')
				{
					$field_name = 'information_items_table.information_items_id';
				}
				elseif ($field_name == 'status')
				{
					$field_name = 'information_items_status';
				}
				elseif ($field_name == 'indexation_field')
				{
					$field_name = 'information_items_allow_indexation';
				}
				elseif ($field_name == 'date')
				{
					$field_name = 'information_items_date';
				}
				elseif ($field_name == 'date_end')
				{
					$field_name = 'information_items_table.information_items_putend_date';
				}
				elseif ($field_name == 'order_field')
				{
					$field_name = 'information_items_order';
				}
				break;
			}
	}
	return true;
}

// Обработчик события "Редактировать" информационную группы или элемента.
function edit_group_item(&$param)
{
	ob_start();

	$information_system_id=to_int($_REQUEST['information_system_id']);
	$information_group_parent_id = to_int($_REQUEST['information_groups_parent_id']);

	$InformationSystem = & singleton('InformationSystem');

	if (isset($param['data']))
	{
		// Редактирование информационной группы.
		if (isset($param['data'][0]))
		{
			foreach ($param['data'][0] as $information_group_id => $value)
			{
				// Определяем режим доступа пользователя и принадлежит ли объект пользователю
				$user_access = new user_access();

				// Определяем информацию об объекте
				$object_res = $InformationSystem->SelectInformationGroups($information_group_id);

				if ($object_res)
				{
					$object_row = mysql_fetch_assoc($object_res);
				}

				if ($object_row)
				{
					$object_user_id = $object_row['users_id'];
				}
				else
				{
					$object_user_id = 0;
				}

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					include(CMS_FOLDER . 'admin/InformationSystems/action/form_edit_add_information_groups.php');

					$param['title'] = ($information_group_id == 0) ? $GLOBALS['MSG_information_systems']['information_groups_add_form_title'] : $GLOBALS['MSG_information_systems']['information_groups_edit_form_title'];
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}
		}

		// Редактирование информационного элемента.
		if (isset($param['data'][1]))
		{
			foreach ($param['data'][1] as $key => $value)
			{
				// Определяем режим доступа пользователя и принадлежит ли объект пользователю
				$user_access = new user_access();

				// Определяем информацию об объекте
				$object_row = $InformationSystem->GetInformationSystemItem($key);

				if ($object_row)
				{
					$object_user_id = $object_row['users_id'];
				}
				else
				{
					$object_user_id = 0;
				}

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					// Редактируем ярлык
					if ($object_row['information_items_shortcut_id'] != 0)
					{
						$information_item_id = $object_row['information_items_shortcut_id'];
					}
					else
					{
						$information_item_id = intval($key);
					}

					include(CMS_FOLDER . 'admin/InformationSystems/action/form_edit_add_information_items.php');

					$param['title'] =  $information_item_id == 0 ? $GLOBALS['MSG_information_systems']['information_items_add_form_title'] : $GLOBALS['MSG_information_systems']['information_items_edit_form_title'];

				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}
		}
	}

	$param['result'] = ob_get_clean();
	return true;
}

// Создание ярлыка информационного элемента
function add_item_shortcut(&$param)
{
	ob_start();
	
	$information_system_id = to_int($_REQUEST['information_system_id']);
	$information_group_parent_id = to_int($_REQUEST['information_groups_parent_id']);

	$InformationSystem = & singleton('InformationSystem');
	$admin_forms_fields = & singleton('admin_forms_fields');

	if (isset($param['data']))
	{
		ob_start();
		
		$form_name = 'itemshortcut_' . time();
		
		$form_params = array();
		$form_params['form_attribs']['method'] = 'post';
		$form_params['form_attribs']['action'] = '/admin/InformationSystems/InformationSystems.php';
		$form_params['form_attribs']['id'] = 'form_'. $form_name;
		$form_params['form_attribs']['ENCTYPE'] = 'multipart/form-data';

		$admin_forms_fields->admin_forms_fields($form_params);

		$tab_id = $admin_forms_fields->AddTab($GLOBALS['MSG_information_systems']['information_groups_form_tab_1']);
		
		// Редактирование информационного элемента
		if (isset($param['data'][1]))
		{
			foreach ($param['data'][1] as $key => $value)
			{
				// Определяем режим доступа пользователя и принадлежит ли объект пользователю
				$user_access = new user_access();

				// Определяем информацию об объекте
				$object_row = $InformationSystem->GetInformationSystemItem($key);

				if ($object_row)
				{
					$object_user_id = $object_row['users_id'];
				}
				else
				{
					$object_user_id = 0;
				}

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					$information_item_id = intval($key);
										
					// Создаем ярлык из ярлыка
					if ($object_row['information_items_shortcut_id'] != 0)
					{
						$information_item_id = $object_row['information_items_shortcut_id'];
						
						// Получаем информацию о информационном элементе, на который ссылается ярлык 
						$item_row = $InformationSystem->GetInformationSystemItem($information_item_id);
						
						$item_name = $item_row['information_items_name']; 
					}
					else
					{
						$item_name = $object_row['information_items_name'];
					}					
					
					$form_params = array();
					$form_params['tab_id'] = $tab_id;
					$form_params['name'] = 'information_item_id';
					$form_params['type'] = 4; // Скрытое поле.
					$form_params['value'] = $information_item_id;
					$admin_forms_fields->AddField($form_params);
						
					break;					
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					$param['form_html'] = '';
					return ;
				}
			}
		}
		
		$form_params = array();
		$form_params['form_attribs']['method'] = 'post';
		$form_params['form_attribs']['action'] = '/admin/InformationSystems/InformationSystems.php';
		$form_params['form_attribs']['id'] = 'formItemShortcut_' . $information_item_id;
		$form_params['form_attribs']['ENCTYPE'] = 'multipart/form-data';

		$admin_forms_fields->admin_forms_fields($form_params);
		
		// Список групп
		$param = array();
		$param['tab_id'] = $tab_id;
		$param['name'] = 'information_group_id';
		$param['caption'] = $GLOBALS['MSG_information_systems']['add_item_shortcut_information_groups_id'];
		$param['type'] = 2; // Выпадающий список.
		$param['value'] = to_int($object_row['information_groups_id']);

		$mas_groups = $InformationSystem->GetAllInformationGroups(array(
			'information_system_id' => $information_system_id,
			'select_fields' => array('information_groups_id',
			/* 'information_systems_id', */
			'information_groups_parent_id', 'information_groups_name'),
		));
		
		$aGroupsTree = array();
		foreach ($mas_groups as $key => $row)
		{
			$aGroupsTree[$row['information_groups_parent_id']][] = $row;
		}

		$param['items'] = array ('..') + GetDelimitedGroups(0, $aGroupsTree, '', FALSE);

		$param['div_attributes']['style'] = '';
		$param['attributes']['style'] = 'width: 320px; float: left;';
		$param['apply_filter'] = true;

		$admin_forms_fields->AddField($param);
								
		// Добавляем скрытое поле с идентификатором группы (раздела) информационных систем
		$param = array();
		$param['tab_id'] = $tab_id;
		$param['name'] = 'information_systems_dir_parent_id';
		$param['type'] = 4; // Скрытое поле.
		$param['value'] = to_int($_REQUEST['information_systems_dir_parent_id']);
		$admin_forms_fields->AddField($param);
								
		// Добавляем скрытое поле с идентификатором информационной системы
		$param = array();
		$param['tab_id'] = $tab_id;
		$param['name'] = 'information_system_id';
		$param['type'] = 4; // Скрытое поле.
		$param['value'] = to_int($object_row['information_systems_id']);
		$admin_forms_fields->AddField($param);
				
		// Добавляем скрытое поле с идентификатором текущей группы
		$param = array();
		$param['tab_id'] = $tab_id;
		$param['name'] = 'information_groups_parent_id';
		$param['type'] = 4; // Скрытое поле.
		$param['value'] = $object_row['information_groups_id'];
		$admin_forms_fields->AddField($param);
		
		// Добавляем скрытое поле с именем кнопки
		// из-за того, что на странице может быть много форм созания ярлыков,
		// при этом скрытый input уже есть, но у другой формы, поэтому
		// для этой формы он не создастся
		$param = array();
		$param['tab_id'] = $tab_id;
		$param['name'] = 'add_information_item_shortcut';
		$param['type'] = 4; // Скрытое поле.
		$param['value'] = '';
		$admin_forms_fields->AddField($param);
				
		$param = array();
		$param['name'] = 'add_information_item_shortcut';
		$param['caption'] = $GLOBALS['MSG_information_systems']['information_groups_save_form_button_name'];
		$param['image'] = '/admin/images/add.gif';
		$param['attributes']['onclick'] = "SendForm('{$admin_forms_fields->GetWindowId()}', '{$admin_forms_fields->AAction}', '&action=load_data&admin_forms_id=12&information_system_id={$object_row['information_systems_id']}&information_groups_parent_id={$object_row['information_groups_id']}', this, ".to_int($_REQUEST['admin_forms_id']).", 'load_data', " . to_int($admin_forms_fields->form_params['current_page']) . ", " . to_int($admin_forms_fields->form_params['on_page']) . " ); SlideWindow('$form_name'); return false;";
		$param['attributes']['type'] = 'button';
		$admin_forms_fields->AddButton($param);
		
		// Для правильной работы фильтрации списка
		$admin_forms_fields->window_id = $form_name;
		
		// Отображение формы
		$admin_forms_fields->ShowForm();

		$form_content = ob_get_clean();

		?>
		<script>
		var oWindowId = '<?php echo $form_name?>';
		
		if (document.getElementById(oWindowId) == undefined)
		{
			// Создаем окно
			CreateWindow(oWindowId, '<?php echo sprintf($GLOBALS['MSG_information_systems']['add_information_item_shortcut_title'], to_str($item_name));?>', '750px', '140px', 1);

			var oWindow = $("#"+oWindowId);

			var ElementDiv = $('<div>').attr('id', "subdiv_small");
			$("#"+oWindowId).append(ElementDiv);
			
			var content = '<?php echo str_replace("script>", "sc' + 'ript>", str_replace("\r\n", '', str_replace("'", "\'", $form_content)))?>';
			insertContent(ElementDiv, content);
		}
		SlideWindow(oWindowId);
		</script>
		<?php
	}

	$param['error'] = ob_get_clean();
	return true;
}

// Групповой перенос информационных элементов и групп
function move_items_groups(&$param)
{
	ob_start();
	
	$information_system_id = to_int($_REQUEST['information_system_id']);
	$information_group_parent_id = to_int($_REQUEST['information_groups_parent_id']);

	$InformationSystem = & singleton('InformationSystem');
	$admin_forms_fields = & singleton('admin_forms_fields');
	
	if (isset($param['data']))
	{		
		ob_start();
		
		$form_name = 'move_items_groups_' . time();
		$form_params = array();
		$form_params['form_attribs']['method'] = 'post';
		$form_params['form_attribs']['action'] = '/admin/InformationSystems/InformationSystems.php';
		$form_params['form_attribs']['id'] = 'form_'.$form_name;
		$form_params['form_attribs']['ENCTYPE'] = 'multipart/form-data';

		$admin_forms_fields->admin_forms_fields($form_params);

		$tab_id = $admin_forms_fields->AddTab($GLOBALS['MSG_information_systems']['information_groups_form_tab_1']);
						
		if (isset($param['data'][0]))
		{
			foreach ($param['data'][0] as $key => $value)
			{
				// Определяем режим доступа пользователя и принадлежит ли объект пользователю
				$user_access = & singleton('user_access');

				// Определяем информацию об объекте
				$object_row = $InformationSystem->GetInformationSystemItem($key);

				if ($object_row)
				{
					$object_user_id = $object_row['users_id'];
				}
				else
				{
					$object_user_id = 0;
				}

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					$information_group_id = intval($key);
										
					$form_params = array();
					$form_params['tab_id'] = $tab_id;
					$form_params['name'] = 'move_group_' . $information_group_id;
					$form_params['type'] = 4; // Скрытое поле.
					$form_params['value'] = $information_group_id;
					$admin_forms_fields->AddField($form_params);
				}				
			}
		}
		
		if (isset($param['data'][1]))
		{
			foreach ($param['data'][1] as $key => $value)
			{
				// Определяем режим доступа пользователя и принадлежит ли объект пользователю
				$user_access = & singleton('user_access');

				// Определяем информацию об объекте
				$object_row = $InformationSystem->GetInformationSystemItem($key);

				if ($object_row)
				{
					$object_user_id = $object_row['users_id'];
				}
				else
				{
					$object_user_id = 0;
				}

				if ($user_access->IssetUserAccessForObject($object_user_id))
				{
					$information_item_id = intval($key);
															
					$form_params = array();
					$form_params['tab_id'] = $tab_id;
					$form_params['name'] = 'move_item_' . $information_item_id;
					$form_params['type'] = 4; // Скрытое поле.
					$form_params['value'] = $information_item_id;
					$admin_forms_fields->AddField($form_params);
				}				
			}
		}
							
		// Список групп
		$form_params = array();
		$form_params['tab_id'] = $tab_id;
		$form_params['name'] = 'information_group_id';
		$form_params['caption'] = $GLOBALS['MSG_information_systems']['move_items_groups_information_groups_id'];
		$form_params['type'] = 2; // Выпадающий список.
		$form_params['value'] = 0;
				
		// Массив идентификаторов переносимых групп
		$mas_move_groups = array();
		
		foreach($_REQUEST as $request_key => $request_value)
		{
			if (ereg("^check_0_([0-9]*)$", $request_key, $regs))
			{
				$mas_move_groups[] = $regs[1];
			}
		}

		$mas_groups = $InformationSystem->GetAllInformationGroups(array(
			'information_system_id' => $information_system_id,
			'select_fields' => array('information_groups_id',
			/* 'information_systems_id', */
			'information_groups_parent_id', 'information_groups_name'),
		));
		
		$aGroupsTree = array();
		foreach ($mas_groups as $key => $row)
		{
			$aGroupsTree[$row['information_groups_parent_id']][] = $row;
		}

		$items = array('..') + GetDelimitedGroups(0, $aGroupsTree, '', $mas_move_groups);
		
		$form_params['items'] = $items;
		$form_params['div_attributes']['style'] = '';
		$form_params['attributes']['style'] = 'width: 320px; float: left;';
		$form_params['apply_filter'] = true;

		$admin_forms_fields->AddField($form_params);
								
		// Добавляем скрытое поле с идентификатором информационной системы
		$form_params = array();
		$form_params['tab_id'] = $tab_id;
		$form_params['name'] = 'information_system_id';
		$form_params['type'] = 4; // Скрытое поле.
		$form_params['value'] = $information_system_id;
		$admin_forms_fields->AddField($form_params);
				
		// Добавляем скрытое поле с идентификатором текущей группы
		$form_params = array();
		$form_params['tab_id'] = $tab_id;
		$form_params['name'] = 'information_groups_parent_id';
		$form_params['type'] = 4; // Скрытое поле.
		$form_params['value'] = $information_group_parent_id;
		$admin_forms_fields->AddField($form_params);
		
		// Добавляем специальное скрытое поле с именем кнопки		
		$form_params = array();
		$form_params['tab_id'] = $tab_id;
		$form_params['name'] = 'move_items_groups';
		$form_params['type'] = 4; // Скрытое поле.
		$form_params['value'] = '';
		$admin_forms_fields->AddField($form_params);
				
		$form_params = array();
		$form_params['name'] = 'move_items_groups';
		$form_params['caption'] = $GLOBALS['MSG_information_systems']['move_items_groups_form_button_name'];
		$form_params['image'] = '/admin/images/add.gif';
		
		$form_params['attributes']['onclick'] = "SendForm('{$admin_forms_fields->GetWindowId()}', '{$admin_forms_fields->AAction}', '&action=load_data&admin_forms_id=12&information_system_id={$information_system_id}&information_groups_parent_id={$information_group_parent_id}', this, " . to_int($_REQUEST['admin_forms_id']) . ", 'load_data', " . to_int($admin_forms_fields->form_params['current_page']) . ", " . to_int($admin_forms_fields->form_params['on_page']) . " ); SlideWindow('$form_name'); return false;";
		$form_params['attributes']['type'] = 'button';
		$admin_forms_fields->AddButton($form_params); 
					
		// Для правильной работы фильтрации списка
		$admin_forms_fields->window_id = $form_name;

		// Отображение формы
		$admin_forms_fields->ShowForm();

		$form_content = ob_get_clean();
		?>
		<script>
		var oWindowId = '<?php echo $form_name?>';
		
		if (document.getElementById(oWindowId) == undefined)
		{
			// Создаем окно
			CreateWindow(oWindowId, '<?php echo $GLOBALS['MSG_information_systems']['move_items_groups_title']; ?>', '750px', '140px', 1);

			var oWindow = $("#"+oWindowId);

			var ElementDiv = $('<div>').attr('id', "subdiv_small");
			$("#"+oWindowId).append(ElementDiv);
			
			var content = '<?php echo str_replace("script>", "sc' + 'ript>", str_replace("\r\n", '', str_replace("'", "\'", $form_content)))?>';
			insertContent(ElementDiv, content);
		}
		SlideWindow(oWindowId);
		</script>
		<?php
	}

	$param['error'] = ob_get_clean();
	return true;
}

// Обработчик события "Копировать" информационного элемента
function copy_item(&$param)
{
	ob_start();

	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		$InformationSystem = & singleton('InformationSystem');

		if (isset($param['data']))
		{
			if (isset($param['data'][1]))
			{
				foreach ($param['data'][1] as $key => $value)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					// Определяем информацию об объекте
					$object_row = $InformationSystem->GetInformationSystemItem($key);

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$InformationSystem->CopyInformationItem($key);
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}
	$param['error'] = ob_get_clean();
}

// Изменение статуса активности информационного элемента
function change_item_active(&$param)
{
	ob_start();

	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');
		$kernel->ReadMode();
	}
	else
	{
		$InformationSystem = & singleton('InformationSystem');

		if (isset($param['data']) && is_array($param['data']))
		{
			$user_access = new user_access();

			if (isset($param['data'][0]))
			{
				foreach ($param['data'][0] as $key => $row)
				{
					// Определяем информацию об объекте
					$object_row = $InformationSystem->GetInformationGroup($key, array('cache_off' => TRUE));

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$param_group = array();
						$param_group['information_groups_id'] = $key;
						$param_group['information_groups_activity'] = 1 - $object_row['information_groups_activity'];

						// Чтобы произошла событийная индексация
						$param_group['information_groups_allow_indexation'] = $object_row['information_groups_allow_indexation'];

						$InformationSystem->InsertInformationGroup($param_group);
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
			if (isset($param['data'][1]))
			{
				foreach ($param['data'][1] as $key => $row)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю

					// Определяем информацию об объекте
					$object_row = $InformationSystem->GetInformationSystemItem($key, array('cache_off' => TRUE));

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$param_item = array();
						$param_item['information_items_id'] = $key;
						$param_item['information_items_status'] = 1 - $object_row['information_items_status'];

						// Чтобы произошла событийная индексация
						$param_item['information_items_allow_indexation'] = $object_row['information_items_allow_indexation'];

						$InformationSystem->InsertInformationItem($param_item);
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}
	$error = ob_get_clean();

	$param['error'] = $error;
}

// Изменение статуса индексированности информационного элемента
function change_item_indexation(&$param)
{
	ob_start();

	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		$InformationSystem = & singleton('InformationSystem');

		if (isset($param['data']) && is_array($param['data']))
		{
			if (isset($param['data'][0]))
			{
				foreach ($param['data'][0] as $key => $row)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					// Определяем информацию об объекте
					$object_res = $InformationSystem->SelectInformationGroups($key);

					if ($object_res)
					{
						$object_row = mysql_fetch_assoc($object_res);
					}

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$information_group_id = intval($key);

						// Выбираем данные об инфоэлементе
						$res = $InformationSystem->GetInformationGroup($information_group_id);

						$InformationSystem->InsertInformationGroup(array(
						'information_groups_id' => $information_group_id,
						// Чтобы произошла событийная индексация
						'information_groups_activity' => $res['information_groups_activity'],
						'information_groups_allow_indexation' => 1 - $res['information_groups_allow_indexation']));
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}

			if (isset($param['data'][1]))
			{
				foreach ($param['data'][1] as $key => $row)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					// Определяем информацию об объекте
					$object_row = $InformationSystem->GetInformationSystemItem($key, array('cache_off' => true));

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						// Выбираем данные об инфоэлементе
						$res = $InformationSystem->GetInformationSystemItem($key);

						$param_item = array();
						$param_item['information_items_id'] = $key;
						$param_item['information_items_allow_indexation'] = 1 - $res['information_items_allow_indexation'];

						// Чтобы произошла событийная индексация
						$param_item['information_items_status'] = $res['information_items_status'];

						$InformationSystem->InsertInformationItem($param_item);
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}
	$error = ob_get_clean();

	$param['error'] = $error;
}

// Изменение порядка сортировки информационного элемента
function apply_changes(&$param)
{
	ob_start();

	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		$InformationSystem = & singleton('InformationSystem');

		if (isset($param['data']) && is_array($param['data']))
		{
			if (isset($param['data'][0]))
			{
				foreach ($param['data'][0] as $key => $row)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					// Определяем информацию об объекте
					$object_res = $InformationSystem->SelectInformationGroups($key);

					if ($object_res)
					{
						$object_row = mysql_fetch_assoc($object_res);
					}

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						// Выбираем данные об инфоэлементе
						$res = $InformationSystem->GetInformationGroup(intval($key));

						$InformationSystem_id = $res['information_systems_id'];
						$information_group_id = intval($key);
						$information_group_parent_id = $res['information_groups_parent_id'];
						$information_group_name = $res['information_groups_name'];
						$information_group_description = $res["information_groups_description"];
						$information_group_order = $row['order_field'];
						$information_group_path = $res['information_groups_path'];
						$information_group_small_image = $res['information_groups_small_image'];
						$information_group_allow_indexation = $res['information_groups_allow_indexation'];
						$information_group_seo_title = $res['information_groups_seo_title'];
						$information_group_seo_description = $res['information_groups_seo_description'];
						$information_group_seo_keywords = $res['information_groups_seo_keywords'];
						$information_group_access = $res['information_groups_access'];
						$user_id = $res['users_id'];

						$InformationSystem->InsertInformationGroups(1, $information_group_id, $InformationSystem_id, $information_group_parent_id, $information_group_name, $information_group_description, $information_group_order, $information_group_path, '', $information_group_allow_indexation, $information_group_seo_title, $information_group_seo_description, $information_group_seo_keywords, $information_group_access, $user_id);
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}

			if (isset($param['data'][1]))
			{
				foreach ($param['data'][1] as $key => $row)
				{

					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					// Определяем информацию об объекте
					$object_row = $InformationSystem->GetInformationSystemItem($key, array('cache_off' => true));

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						// Выбираем данные об инфоэлементе
						$res = $InformationSystem->GetInformationSystemItem($key);

						$param_item = array();
						$param_item['information_items_id'] = $key;
						$param_item['information_items_order'] = $row['order_field'];

						$InformationSystem->InsertInformationItem($param_item);
					}
					else
					{
						$user_access->MessageOnlyOwn();
						$param['error'] = ob_get_clean();
						return ;
					}
				}
			}
		}
	}
	$error = ob_get_clean();

	$param['error'] = $error;
}

// Удаление информационной группы и элемента.
function delete_group_item(&$param)
{
	ob_start();

	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		$information_system = & singleton('InformationSystem');

		$information_system_id = to_int($_REQUEST['information_system_id']);

		$count_deleted_items = 0;

		$count_deleted_groups = 0;

		if (isset($param['data']))
		{
			if (isset($param['data'][0]))
			{
				foreach ($param['data'][0] as $key => $value)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					// Определяем информацию об объекте
					$object_res = $information_system->SelectInformationGroups($key);

					if ($object_res)
					{
						$object_row = mysql_fetch_assoc($object_res);
					}

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						if (!$information_system->del_information_groups($key, $information_system_id))
						{
							$flag_success_delete_group = false;
						}
						else
						{
							++$count_deleted_groups;

							$flag_success_delete_group = true;
						}
					}
					else
					{
						$user_access->MessageOnlyOwn();

						$flag_success_delete_group = false;
					}
				}

				if ($flag_success_delete_group)
				{
					if ($count_deleted_groups == 1)
					{
						show_message($GLOBALS['MSG_information_systems']['delete_information_group_success']);
					}
					else
					{
						show_message($GLOBALS['MSG_information_systems']['delete_information_groups_success']);
					}
				}
				/*else
				 {
				 show_error_message($GLOBALS['MSG_information_systems']['delete_information_group_error']);
				 }*/
			}

			if (isset($param['data'][1]))
			{
				foreach ($param['data'][1] as $key => $value)
				{
					// Определяем режим доступа пользователя и принадлежит ли объект пользователю
					$user_access = new user_access();

					// Определяем информацию об объекте
					$object_row = $information_system->GetInformationSystemItem($key, array('cache_off' => true));

					if ($object_row)
					{
						$object_user_id = $object_row['users_id'];
					}
					else
					{
						$object_user_id = 0;
					}

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						if (!$information_system->del_information_items($key))
						{
							$flag_success_delete_item = false;
						}
						else
						{
							++$count_deleted_items;

							$flag_success_delete_item = true;
						}
					}
					else
					{
						$user_access->MessageOnlyOwn();

						$flag_success_delete_item = false;
					}
				}
				if ($flag_success_delete_item)
				{
					if ($count_deleted_items == 1)
					{
						show_message($GLOBALS['MSG_information_systems']['delete_information_item_success']);
					}
					else
					{
						show_message($GLOBALS['MSG_information_systems']['delete_information_items_success']);
					}
				}
				/*else
				 {
				 show_error_message($GLOBALS['MSG_information_systems']['delete_information_items_error']);
				 }*/
			}
		}
	}
	$param['error'] = ob_get_clean();
}

// Удаление файла большого изображения информационного элемента.
function delete_big_image_item(&$param)
{
	ob_start();

	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

		$kernel->ReadMode();
	}
	else
	{
		$information_system = & singleton('InformationSystem');

		$information_system_id = to_int($_REQUEST['information_system_id']);

		if (isset($param['data']))
		{
			if (isset($param['data'][1]))
			{
				$DataBase = & singleton(DataBase);

				foreach ($param['data'][1] as $key => $value)
				{
					$information_item_id = intval($key);

					$row = $information_system->GetInformationSystemItem($information_item_id);

					if ($row)
					{
						if (is_dir(CMS_FOLDER.UPLOADDIR))
						{
							$fname = CMS_FOLDER.UPLOADDIR.$row['information_items_image'];#путь к большой картинке
							$field_name = "`information_items_image`";

							if (is_file($fname))
							{
								// удаляем файл
								if (@unlink($fname))
								{
									// Удаляем файл из таблицы
									$query = "UPDATE `information_items_table` SET  $field_name = ''  WHERE information_items_id=$information_item_id";
									$DataBase->query($query);
								}
							}
						}
						else
						{
							show_error_message($GLOBALS['MSG_information_systems']['error_information_dir'].CMS_FOLDER.UPLOADDIR);
						}
					}
				}
			}
		}
	}

	$param['error'] = ob_get_clean();
}

?>