<?php
/**
 * Система управления сайтом HostCMS v. 5.xx
 * Copyright © 2005-2010 ООО "Хостмэйк" (Hostmake LLC), http://www.hostcms.ru
 *
 * Ajax загрузчик формы списка содержимого определенного магазина.
 *
 * Файл: /admin/shop/action/load_data.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);

	$shop_shops_id = to_int($_REQUEST['shop_shops_id']);
	$shop_groups_parent_id = to_int($_REQUEST['shop_groups_parent_id']);

	$DataBase = & singleton('DataBase');
	$shop = & singleton('shop');

	$row = $shop->GetShop($shop_shops_id);

	// Строим хлебные крошки
	$path_array = $shop->GetShopPathArray($shop_groups_parent_id, true);

	// Преобразуем идентификаторы групп в ссылки на группы.
	$new_path_array = array();
	$new_path_array[0]['name'] = $GLOBALS['MSG_shops']['header_admin__list_forms'];
	$new_path_array[0]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '', 54, 'load_data');
	$new_path_array[0]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '', 54, 'load_data');

	$new_path_array[1]['name'] = $row['shop_shops_name'];
	$new_path_array[1]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=0&shop_shops_id=$shop_shops_id", 65, 'load_data');
	$new_path_array[1]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=0&shop_shops_id=$shop_shops_id", 65, 'load_data');

	if ($path_array)
	{
		foreach ($path_array as $key => $value)
		{
			$new_path_array[] = array (
			'link' =>  $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=$key&shop_shops_id=$shop_shops_id", 65, 'load_data'),
			'onclick' =>  $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=$key&shop_shops_id=$shop_shops_id", 65, 'load_data'),
			'name' => $value);
		}
	}

	$param['path_array'] = $new_path_array;

	// Запрос для выборки каталогов магазина
	$param['data'][] = "SELECT *, shop_groups_id AS keyfield, shop_groups_name AS name,
		shop_groups_indexation AS indexing, 
		shop_groups_activity AS activity,
		shop_groups_parent_id AS current_group,
		shop_groups_order AS orderr
		FROM `shop_groups_table`
		WHERE `shop_groups_parent_id` = '$shop_groups_parent_id'
		AND `shop_shops_id` = '$shop_shops_id'
		{FILTER_STRING} {ORDER_STRING} {LIMIT}";

	// Количество групп
	$count_groups = "SELECT count(shop_groups_id) as count
	FROM `shop_groups_table`
	WHERE `shop_shops_id`= '$shop_shops_id'
	AND `shop_groups_parent_id` = '$shop_groups_parent_id'
	{FILTER_STRING}";	

	/*
	 , SUM(`shop_warehouse_items_count`) AS ostatok
	 LEFT JOIN `shop_warehouse_items_table` USING (`shop_items_catalog_item_id`)
	 GROUP BY `shop_items_catalog_item_id` 
	HAVING 1 {FILTER_STRING}
	 */
	
	// Запрос для выборки элементов магазина
	$param['data'][] = "SELECT *, shop_items_catalog_item_id AS keyfield,
	shop_items_catalog_name AS name, shop_items_catalog_marking AS articul,
	shop_items_catalog_weight AS ves,
	shop_items_catalog_order AS orderr, shop_items_catalog_price AS price,
	shop_items_catalog_yandex_market_bid AS price_ym_bid,
	shop_items_catalog_yandex_market_allow AS ym_allow,
	shop_items_catalog_is_active AS activity,
	shop_items_catalog_indexation AS indexing,
	shop_items_catalog_item_id AS addons,
	shop_items_catalog_date_time AS data,
	shop_groups_id AS current_group,
	shop_items_catalog_type
	FROM `shop_items_catalog_table`
	WHERE `shop_groups_id` = '$shop_groups_parent_id'
	AND `shop_shops_id` = '$shop_shops_id'
	AND `shop_items_catalog_modification_id` = 0
	{FILTER_STRING}
	{ORDER_STRING} {LIMIT}";

	$count = "SELECT count(*) AS count
	FROM `shop_items_catalog_table`
	WHERE `shop_groups_id` = '$shop_groups_parent_id'
	AND `shop_shops_id` = '$shop_shops_id'
	AND `shop_items_catalog_modification_id`=0
	{FILTER_STRING} 
	";

	/*$count = "SELECT count(shop_items_catalog_item_id) AS count, shop_items_catalog_item_id AS keyfield,
	shop_items_catalog_name AS name, shop_items_catalog_price AS price,
	SUM(`shop_warehouse_items_count`) AS ostatok
	FROM `shop_items_catalog_table`
	LEFT JOIN `shop_warehouse_items_table` USING (`shop_items_catalog_item_id`)
	WHERE `shop_groups_id` = '$shop_groups_parent_id'
	AND `shop_shops_id` = '$shop_shops_id'
	AND `shop_items_catalog_modification_id`=0
	GROUP BY `shop_items_catalog_item_id` 
	HAVING 1 {FILTER_STRING} 
	";*/

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

	$menu[$k]['name'] = $GLOBALS['MSG_shops']['links_items'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$p = 0;
	$sub_menu = array();
	$sub_menu[$p]['name'] = $GLOBALS['MSG_shops']['add_group_link1'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_item', 'check_1_0', 65, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_item', 'check_1_0', 65, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/page_add.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['items_catalog_add_form_comment_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&all_comments_this_shop=1", 66, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&all_comments_this_shop=1", 66, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/comments.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['shops_add_form_link_properties'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_properties_items_dir_id=0", 67, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id&shop_properties_items_dir_id=0", 67, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/page_gear.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['properties_item_for_groups_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_id=$shop_groups_parent_id&shop_groups_parent_id=0", 71, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_id=$shop_groups_parent_id&shop_groups_parent_id=0", 71, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/folder_page_gear.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['change_prices_for_shop_group'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&action=change_prices&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 0, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&action=change_prices&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 0, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/service.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['import_price_list_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&action=import_price_list&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 0, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&action=import_price_list&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 0, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/import.gif';

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['export_shop'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&action=export&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 0, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&action=export&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 0, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/export.gif';

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

	//	$menu = array();
	$menu[++$k]['name'] = $GLOBALS['MSG_shops']['links_groups'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	//	$p = 0;
	$sub_menu = array();
	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['add_group_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallTrigerSingleAction('edit_item', 'check_0_0', 65, 0, 0);
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallTrigerSingleAction('edit_item', 'check_0_0', 65, 0, 0);
	$sub_menu[$p]['icon'] = '/admin/images/folder_add.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['shops_add_form_link_properties_for_group'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&action=add_external_property_group&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 135, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&action=add_external_property_group&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 135, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/folder_gear.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;


	$menu[++$k]['name'] = $GLOBALS['MSG_shops']['shops_link_orders'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$sub_menu = array();
	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['shops_add_form_link_orders'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id", 75, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id", 75, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/order.gif';

	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;
	$menu[++$k]['name'] = $GLOBALS['MSG_shops']['show_delivery_on'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$sub_menu = array();
	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['show_type_of_delivery_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 77, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 77, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/type_of_delivery.gif';

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

	// Формируем заголовок меню
	$menu[++$k]['name'] = $GLOBALS['MSG_shops']['show_sds_link'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	// Формируем новый массив элементов подменю
	$sub_menu = array();
	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['show_prices_title'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 68, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 68, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/prices.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	// Платежные системы
	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['system_of_pays'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', '', 57, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', '', 57, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/payment.gif';

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

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['show_producers_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 69, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 69, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/company.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['show_sellers_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 70, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 70, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/company.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	// склады
	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['main_menu_warehouses_list'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 181, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 181, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/company.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;


	// Меню "Отчеты"
	$menu[++$k]['name'] = $GLOBALS['MSG_shops']['show_reports_title'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	// Подменю "Отчеты о продажах"
	$sub_menu = array();
	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['show_sales_order_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&action=show_sales_order&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 0, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&action=show_sales_order&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 0, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/report.gif';

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

	// Формируем заголовок меню
	$menu[++$k]['name'] = $GLOBALS['MSG_shops']['shop_menu_title'];
	$menu[$k]['link'] = '';
	$menu[$k]['icon'] = '';

	$sub_menu = array();

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['show_discount_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 72, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 72, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/money.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['order_discount_show_title'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 73, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 73, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/money.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['coupon_group_link'];
	$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 74, 'load_data');
	$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_shops_id=$shop_shops_id&shop_groups_parent_id=$shop_groups_parent_id", 74, 'load_data');
	$sub_menu[$p]['icon'] = '/admin/images/money.gif';
	// Добавляем подэлементы.
	$menu[$k]['sub_items'] = $sub_menu;

	if (class_exists('SiteUsers'))
	{
		// Формируем заголовок меню
		$menu[++$k]['name'] = $GLOBALS['MSG_shops']['affiliate_menu_title'];
		$menu[$k]['link'] = '';
		$menu[$k]['icon'] = '';

		$sub_menu = array();
		$sub_menu[++$p]['name'] = $GLOBALS['MSG_shops']['affiliate_menu_title'];
		$sub_menu[$p]['link'] = $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "", 166, 'load_data');
		$sub_menu[$p]['onclick'] = $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "", 166, 'load_data');
		$sub_menu[$p]['icon'] = '/admin/images/money.gif';
		// Добавляем подэлементы.
		$menu[$k]['sub_items'] = $sub_menu;
	}
	// Формируем массив меню.
	$menu_array = array();
	$menu_array[] = $menu;

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

	$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');

		$shop = & singleton('shop');
		
		$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['activity'] == 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['activity'] == 1)
		{
			// Получаем данные о магазине
			$shop_row = $shop->GetShop($row['shop_shops_id']);
			
			if ($shop_row)
			{
				$Structure = & singleton('Structure');
				
				$site = & singleton('site');
				$current_alias = $site->GetCurrentAlias($shop_row['site_id']);
				
				// Получаем путь к магазину
				$shop_path = $Structure->GetStructurePath($shop_row['structure_id'], 0);
		
				if ($shop_path != '/')
				{
					$shop_path = '/'.$shop_path;
				}
				?>&nbsp;<a href="<?php echo 'http://' . $current_alias . $shop_path . $shop->GetPathGroup($row['shop_groups_id'], '')?>" 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)
	{
		$shop = & singleton('shop');
		
		// Элемент является ярлыком
		if ($row['shop_items_catalog_shortcut_id'] != 0)
		{
			//Получаем информацию о информационном элементе, на который ссылается ярлык
			$item_row = $shop->GetItem($row['shop_items_catalog_shortcut_id'], array('cache_off' => true));
			$row['name'] = $item_row['shop_items_catalog_name'];
			$row['shop_items_catalog_putend_date'] = $item_row['shop_items_catalog_putend_date'];
			$row['activity'] = $item_row['shop_items_catalog_is_active'];
		}

		if ($row['shop_items_catalog_putend_date'] != "0000-00-00 00:00:00"
		&& $row['shop_items_catalog_putend_date'] < date("Y-m-d H:i:s")
		|| $row['activity'] == 0)
		{
			?><div style="text-decoration: line-through"><?php echo htmlspecialchars($row['name'])?></div><?php
		}
		else
		{
			// Получаем данные о магазине
			$shop_row = $shop->GetShop($row['shop_shops_id']);
			
			if ($shop_row)
			{
				$Structure = & singleton('Structure');
				
				$site = & singleton('site');
				$current_alias = $site->GetCurrentAlias($shop_row['site_id']);
				
				// Получаем путь к магазину
				$shop_path = $Structure->GetStructurePath($shop_row['structure_id'], 0);
		
				if ($shop_path != '/')
				{
					$shop_path = '/'.$shop_path;
				}
			
				echo htmlspecialchars($row['name']);
				?>&nbsp;<a href="<?php echo 'http://' . $current_alias . $shop_path . $shop->GetPathItem($row['shop_items_catalog_item_id']).rawurlencode($row['shop_items_catalog_path']).'/'?>" target="_blank"><img src="/admin/images/new_window.gif" class="img_line" /></a><?php
			}
		}
	}

	// В поле с картинкой отображаем значек папки.
	$param['field_params'][0]['shop_items_catalog_shortcut_id']['admin_forms_field_image'] = "=/admin/images/folder.gif";

	// Меняем тип столбца "Количество" для групп товаров
	$param['field_params'][0]['ostatok']['admin_forms_field_type'] = 0;

	// Остаток
	$param['field_params'][0]['ostatok']['admin_forms_field_type'] = 0;
	$param['field_params'][1]['ostatok']['callback_function'] = 'callback_function_shop_items_catalog_ostatok';

	// Формируем функцию обратного вызова
	function callback_function_shop_items_catalog_ostatok($field_value, $value, $row)
	{
		$shop = & singleton('shop');
		$warehouse = & singleton('warehouse');
	
		// Ярлык
		if ($row['shop_items_catalog_shortcut_id'] != 0)
		{
			$item_row = $shop->GetItem($row['shop_items_catalog_shortcut_id'], array('cache_off' => true));

			// Теперь остаток считается по всем складам
			$value = $warehouse->GetItemCountForAllWarehouses($item_row['shop_items_catalog_item_id']);
		}
		else 
		{
			$value = $warehouse->GetItemCountForAllWarehouses($row['shop_items_catalog_item_id']);
		}

		// Если склад только 1
		if (count($warehouse->GetAllWarehousesForShop($row['shop_shops_id'])) == 1)
		{
			$onAction = "DoModification('id_check_1_{$row['shop_items_catalog_item_id']}')";
			$name = "check_1_{$row['shop_items_catalog_item_id']}_fv_243";
			?><input id="id_<?php echo $name?>" name="<?php echo $name?>" onchange="<?php echo $onAction?>" onkeydown="<?php echo $onAction?>" type="text" style="<?php echo $field_value['admin_forms_field_style'];?>" value="<?php echo $shop->Round($value)?>" /><?php
		}
		else
		{
			echo $shop->Round($value);
		}
	}

	// Цена
	$param['field_params'][0]['price']['admin_forms_field_type'] = 0;
	$param['field_params'][1]['price']['callback_function'] = 'callback_function_shop_items_catalog_price';

	// Формируем функцию обратного вызова
	function callback_function_shop_items_catalog_price($field_value, $value, $row)
	{
		$shop = & singleton('shop');

		// Ярлык
		if ($row['shop_items_catalog_shortcut_id'] != 0)
		{
			$item_row = $shop->GetItem($row['shop_items_catalog_shortcut_id'], array('cache_off' => true));
			$row['shop_currency_id'] = $item_row['shop_currency_id'];
			//$row['shop_items_catalog_item_id'] = $item_row['shop_items_catalog_item_id'];
			$value = $item_row['shop_items_catalog_price'];
		}

		$row_currency_item = $shop->GetCurrency($row['shop_currency_id']);

		?><nobr> <input type="text" style="<?php echo $field_value['admin_forms_field_style'];?>" name="check_1_<?php echo $row['shop_items_catalog_item_id'];?>_fv_<?php echo $field_value['admin_forms_field_id'];?>" value="<?php echo $value;?>" id="id_check_1_<?php echo $row['shop_items_catalog_item_id'];?>_fv_<?php echo $field_value['admin_forms_field_id'];?>"  onkeydown="DoModification('id_check_1_<?php echo $row['shop_items_catalog_item_id'];?>');" onchange="DoModification('id_check_1_<?php echo $row['shop_items_catalog_item_id'];?>');" />
&nbsp; <?php echo $row_currency_item['shop_currency_name'];?></nobr><?php
	}

	// Яндекс.Маркет - основная расценка
	/*$param['field_params'][0]['price_ym_bid']['admin_forms_field_type'] = 0;
	$param['field_params'][1]['price_ym_bid']['callback_function'] = 'callback_function_shop_items_catalog_price_ym_bid';

	// Формируем функцию обратного вызова
	function callback_function_shop_items_catalog_price_ym_bid($field_value, $value, $row)
	{
		?><input type="text" style="<?php echo $field_value['admin_forms_field_style'];?>" name="check_1_<?php echo $row['shop_items_catalog_item_id'];?>_fv_<?php echo $field_value['admin_forms_field_id'];?>" value="<?php echo $value;?>" id="id_check_1_<?php echo $row['shop_items_catalog_item_id'];?>_fv_<?php echo $field_value['admin_forms_field_id'];?>"  onkeydown="DoModification('id_check_1_<?php echo $row['shop_items_catalog_item_id'];?>');" onchange="DoModification('id_check_1_<?php echo $row['shop_items_catalog_item_id'];?>');" /><?php
	}*/

	// Активность
	$param['field_params'][0]['activity']['admin_forms_field_alt'] = "0=" . $GLOBALS['MSG_shops']['group_is_active']
	. "\n1=" . $GLOBALS['MSG_shops']['group_is_active'];
	$param['field_params'][0]['activity']['admin_forms_field_title'] = "0=" . $GLOBALS['MSG_shops']['group_is_active']
	. "\n1=" . $GLOBALS['MSG_shops']['group_is_active'];

	$param['field_params'][1]['activity']['admin_forms_field_alt'] = "0=".$GLOBALS['MSG_shops']['catalog_is_active']
	. "\n1=".$GLOBALS['MSG_shops']['catalog_is_active'];
	$param['field_params'][1]['activity']['admin_forms_field_title'] = "0=".$GLOBALS['MSG_shops']['catalog_is_active']
	. "\n1=".$GLOBALS['MSG_shops']['catalog_is_active'];

	// Сопутствующие товары
	$param['field_params'][0]['addonses']['callback_function'] = 'callback_function_item_addonses';
	$param['field_params'][1]['addonses']['callback_function'] = 'callback_function_item_addonses';

	function callback_function_item_addonses ($field_value, $value, $row)
	{
		// Отображаем товар/ярлык на товар
		if (isset($row['shop_items_catalog_item_id']))
		{
			// Товар
			if ($row['shop_items_catalog_shortcut_id'] == 0)
			{
				$item_id = $row['shop_items_catalog_item_id'];
				$shop_groups_id = $row['shop_groups_id'];

			}
			else // Ярлык
			{
				$shop = & singleton('shop');

				$item_row = $shop->GetItem($row['shop_items_catalog_shortcut_id'], array('cache_off' => true));

				$item_id = $row['shop_items_catalog_shortcut_id'];
				$shop_groups_id = $item_row['shop_groups_id'];
			}
			?><a href="/admin/shop/shop.php?admin_forms_id=79&operation=load_data&limit=0&shop_shops_id=<?php echo $row['shop_shops_id']; ?>&shop_groups_parent_id=<?php echo $shop_groups_id;?>&shop_items_catalog_item_id=<?php echo $item_id ?>" onclick="DoLoadAjax('/admin/shop/shop.php', '&shop_shops_id=<?php echo $row['shop_shops_id']; ?>&shop_groups_parent_id=<?php echo $shop_groups_id;?>&shop_items_catalog_item_id=<?php echo $item_id?>', 79, 'load_data', '', '', '', ''); return false;"><img src="/admin/images/tying_products.gif" border="0" alt="<?php echo $GLOBALS['MSG_shops']['show_tying_products_menu'];?>" title="<?php echo $GLOBALS['MSG_shops']['show_tying_products_menu'];?>" /></a><?php
		}
	}

	// Скидки
	$param['field_params'][0]['easy']['callback_function'] = 'callback_function_item_easy';
	$param['field_params'][1]['easy']['callback_function'] = 'callback_function_item_easy';

	function callback_function_item_easy($field_value, $value, $row)
	{
		// Отображаем товар/ярлык на товар
		if (isset($row['shop_items_catalog_item_id']))
		{
			// Товар
			if ($row['shop_items_catalog_shortcut_id'] == 0)
			{
				$item_id = $row['shop_items_catalog_item_id'];
				$shop_groups_id = $row['shop_groups_id'];
			}
			else // Ярлык
			{
				$shop = & singleton('shop');

				$item_row = $shop->GetItem($row['shop_items_catalog_shortcut_id'], array('cache_off' => true));

				$item_id = $row['shop_items_catalog_shortcut_id'];
				$shop_groups_id = $item_row['shop_groups_id'];
			}
			?><a href="/admin/shop/shop.php?admin_forms_id=72&operation=load_data&limit=0&shop_shops_id=<?php echo $row['shop_shops_id']; ?>&shop_groups_parent_id=<?php echo $shop_groups_id;?>&shop_items_catalog_item_id=<?php echo $item_id ?>" onclick="DoLoadAjax('/admin/shop/shop.php', '&shop_shops_id=<?php echo $row['shop_shops_id']; ?>&shop_groups_parent_id=<?php echo $shop_groups_id;?>&shop_items_catalog_item_id=<?php echo $item_id?>', 72, 'load_data', '', '', '', ''); return false;"><img src="/admin/images/money.gif" border="0" alt="<?php echo $GLOBALS['MSG_shops']['show_groups_discount'];?>" title="<?php echo $GLOBALS['MSG_shops']['show_groups_discount'];?>" /></a><?php
		}
	}

	// Отзывы
	$param['field_params'][0]['voices']['callback_function'] = 'callback_function_item_voices';
	$param['field_params'][1]['voices']['callback_function'] = 'callback_function_item_voices';

	function callback_function_item_voices($field_value, $value, $row)
	{
		// Отображаем товар/ярлык на товар
		if (isset($row['shop_items_catalog_item_id']))
		{
			// Товар
			if ($row['shop_items_catalog_shortcut_id'] == 0)
			{
				$item_id = $row['shop_items_catalog_item_id'];
				$shop_groups_id = $row['shop_groups_id'];

			}
			else // Ярлык
			{
				$shop = & singleton('shop');

				$item_row = $shop->GetItem($row['shop_items_catalog_shortcut_id'], array('cache_off' => true));

				$item_id = $row['shop_items_catalog_shortcut_id'];
				$shop_groups_id = $item_row['shop_groups_id'];
			}
			?><a href="/admin/shop/shop.php?admin_forms_id=66&operation=load_data&limit=0&shop_shops_id=<?php echo $row['shop_shops_id']; ?>&shop_groups_parent_id=<?php echo $shop_groups_id;?>&sort_catalog_item_id=<?php echo $item_id ?>" onclick="DoLoadAjax('/admin/shop/shop.php', '&shop_shops_id=<?php echo $row['shop_shops_id']; ?>&shop_groups_parent_id=<?php echo $shop_groups_id;?>&sort_catalog_item_id=<?php echo $item_id?>', 66, 'load_data', '', '', '', ''); return false;"><img src="/admin/images/comments.gif" border="0" alt="<?php echo $GLOBALS['MSG_shops']['show_groups_comment'];?>" title="<?php echo $GLOBALS['MSG_shops']['show_groups_comment'];?>" /></a><?php
		}
	}

	// Модификации
	$param['field_params'][0]['mods']['callback_function'] = 'callback_function_item_mods';
	$param['field_params'][1]['mods']['callback_function'] = 'callback_function_item_mods';

	function callback_function_item_mods($field_value, $value, $row)
	{
		// Отображаем товар/ярлык на товар
		if (isset($row['shop_items_catalog_item_id']))
		{
			// Товар
			if ($row['shop_items_catalog_shortcut_id'] == 0)
			{
				$item_id = $row['shop_items_catalog_item_id'];
				$shop_groups_id = $row['shop_groups_id'];

			}
			else // Ярлык
			{
				$shop = & singleton('shop');

				$item_row = $shop->GetItem($row['shop_items_catalog_shortcut_id'], array('cache_off' => true));

				$item_id = $row['shop_items_catalog_shortcut_id'];
				$shop_groups_id = $item_row['shop_groups_id'];
			}
			?><a href="/admin/shop/shop.php?admin_forms_id=81&operation=load_data&limit=0&shop_shops_id=<?php echo $row['shop_shops_id']; ?>&shop_groups_parent_id=<?php echo $shop_groups_id;?>&shop_items_catalog_modification_id=<?php echo $item_id ?>" onclick="DoLoadAjax('/admin/shop/shop.php', '&shop_shops_id=<?php echo $row['shop_shops_id']; ?>&shop_groups_parent_id=<?php echo $shop_groups_id;?>&shop_items_catalog_modification_id=<?php echo $item_id?>', 81, 'load_data', '', '', '', ''); return false;"><img src="/admin/images/modifications.gif" border="0" alt="<?php echo $GLOBALS['MSG_shops']['modifications'];?>" title="<?php echo $GLOBALS['MSG_shops']['modifications'];?>" /></a><?php
		}
	}

	// Формируем функцию обратного вызова
	$param['field_params'][0]['shop_items_catalog_type']['admin_forms_field_type'] = 0;
	$param['field_params'][1]['shop_items_catalog_type']['callback_function'] = 'callback_function_shop_items_catalog_type';

	function callback_function_shop_items_catalog_type($field_value, $value, $row)
	{
		// Получаем данные для передачи в новую форму
		$shop_shops_id = to_int($_REQUEST['shop_shops_id']);

		// Товар
		if ($row['shop_items_catalog_shortcut_id'] == 0)
		{
			$item_id = $row['shop_items_catalog_item_id'];
			//$shop_groups_id = $row['shop_groups_id'];

			// Текущий каталог товаров
			$shop_groups_parent_id = to_int($_REQUEST['shop_groups_parent_id']);
			$item_name = to_str($row['name']);
			$shop_items_catalog_type = $value;
		}
		else // Ярлык
		{
			$shop = & singleton('shop');
			$item_row = $shop->GetItem($row['shop_items_catalog_shortcut_id'], array('cache_off' => true));
			$item_id = $row['shop_items_catalog_shortcut_id'];
			$shop_groups_parent_id = $item_row['shop_groups_id'];
			$item_name = $item_row['shop_items_catalog_name'];
			$shop_items_catalog_type = $item_row['shop_items_catalog_type'];
		}

		$admin_forms = & singleton('admin_forms');

		if ($shop_items_catalog_type == 1)
		{
			?>
<a
	href="<?php echo $admin_forms->GetHtmlCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=$shop_groups_parent_id&shop_shops_id=$shop_shops_id&item_id=$item_id", 132, 'load_data')?>"
	onclick="<?php echo $admin_forms->GetOnClickCallDoLoadAjax('/admin/shop/shop.php', "&shop_groups_parent_id=$shop_groups_parent_id&shop_shops_id=$shop_shops_id&item_id=$item_id", 132, 'load_data')?>"><img
	alt="<?php echo $GLOBALS['MSG_shops']['shop_eitems_menu_title'] . " '" . $item_name . "'"?>"
	title="<?php echo $GLOBALS['MSG_shops']['shop_eitems_menu_title'] . " '" . $item_name . "'"?>"
	src="/admin/images/table.gif" /></a>
			<?php
		}
		else
		{
			?>&mdash;<?php
		}
	}

	$param['field_params'][0]['ym_allow']['admin_forms_field_type'] = 0;

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

	$param['title'] = $row['shop_shops_name'];

	return $param;
}

/**
 * Необязательная функция для определения реального имени столбца по псевдониму.
 *
 * @param string $field_name
 * @param integer $dataset_id
 * @return boolean
 */
function ResolveFieldName(&$field_name, $dataset_id)
{
	switch ($dataset_id)
	{
		case 0: // Список каталогов документов.
			{
				switch ($field_name)
				{
					case 'keyfield':
						{
							$field_name = 'shop_groups_id';
							break;
						}
					case 'shop_groups_id':
						{
							$field_name = 'shop_groups_parent_id';
							break;
						}
					case 'name':
						{
							$field_name = 'shop_groups_name';
							break;
						}
					case 'indexing':
						{
							$field_name = 'shop_groups_indexation';
							break;
						}
					case 'orderr':
						{
							$field_name = 'shop_groups_order';
							break;
						}
					case 'articul':
						{
							/*чтобы в результаты фильтрации товаров не попадали группы, т.к. поле Артикул у них вообще отсутсвует*/
							$field_name = 'shop_groups_name';
							break;
						}
					case 'ves':
						{
							$field_name = '';
							break;
						}
					case 'ostatok':
						{
							$field_name = 'shop_groups_name';
							break;
						}
					case 'price':
						{
							$field_name = '';
							break;
						}
					case 'price_ym_bid':
						{
							$field_name = '';
							break;
						}
					case 'ym_allow':
						{
							$field_name = '';
							break;
						}
					case 'data':
						{
							$field_name = '';
							break;
						}
					default:
						{
							$field_name = '';
							break;
						}
				}
				break;
			}
		case 1: // Список документов.
			{
				switch ($field_name)
				{
					case 'keyfield':
						{
							$field_name = 'shop_items_catalog_item_id';
							break;
						}
					case 'name':
						{
							$field_name = 'shop_items_catalog_name';
							break;
						}
					case 'articul':
						{
							$field_name = 'shop_items_catalog_marking';
							break;
						}
					case 'ves':
						{
							$field_name = 'shop_items_catalog_weight';
							break;
						}
					case 'ostatok':
						{
							$field_name = 'ostatok';
							break;
						}
					case 'orderr':
						{
							$field_name = 'shop_items_catalog_order';
							break;
						}
					case 'price':
						{
							$field_name = 'shop_items_catalog_price';
							break;
						}
					case 'price_ym_bid':
						{
							$field_name = 'shop_items_catalog_yandex_market_bid';
							break;
						}
					case 'ym_allow':
						{
							$field_name = 'shop_items_catalog_yandex_market_allow';
							break;
						}
					case 'activity':
						{
							$field_name = 'shop_items_catalog_is_active';
							break;
						}
					case 'indexing':
						{
							$field_name = 'shop_items_catalog_indexation';
							break;
						}
					case 'addons':
						{
							$field_name = 'shop_items_catalog_item_id';
							break;
						}
					case 'data':
						{
							$field_name = 'shop_items_catalog_date_time';
							break;
						}
					default:
						{
							$field_name = '';
							break;
						}
				}
				break;
			}
	}
	return true;
}

// Создание ярлыка товара
function add_item_shortcut(&$param)
{
	ob_start();

	$shop_shops_id = to_int($_REQUEST['shop_shops_id']);
	$shop_groups_parent_id = to_int($_REQUEST['shop_groups_parent_id']);

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

	if (isset($param['data']))
	{
		ob_start();

		$form_name = 'shop_itemshortcut_' . time();
		$form_params = array();
		$form_params['form_attribs']['method'] = 'post';
		$form_params['form_attribs']['action'] = '/admin/shop/shop.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_shops']['tab']);

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

				// Определяем информацию об объекте
				$object_row = $shop->GetItem($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))
				{
					$shop_item_id = intval($key);

					// Создаем ярлык из ярлыка
					if ($object_row['shop_items_catalog_shortcut_id'] != 0)
					{
						$shop_item_id = $object_row['shop_items_catalog_shortcut_id'];
						
						$shop_item_row = $shop->GetItem($shop_item_id, array('cache_off' => true));
						
						$shop_item_name = $shop_item_row['shop_items_catalog_name'];
					}
					else
					{
						$shop_item_name = $object_row['shop_items_catalog_name']; 
					}

					$form_params = array();
					$form_params['tab_id'] = $tab_id;
					$form_params['name'] = 'shop_item_id';
					$form_params['type'] = 4; // Скрытое поле.
					$form_params['value'] = $shop_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['tab_id'] = $tab_id;
		$form_params['name'] = 'shop_group_id';
		$form_params['caption'] = $GLOBALS['MSG_shops']['move_items_groups_shop_groups_id'];
		$form_params['type'] = 2; // Выпадающий список.
		$form_params['value'] = 0;

		// Массив, содержащий полное дерево групп
		$mas = $shop->GetDelimitedGroups(0, $shop_shops_id, "&nbsp;&nbsp;");
		//$mas = GetDelimitedGroups(0, $shop_shops_id, "&nbsp;&nbsp;");
		$shop->mas_groups = array ();
		$shop->MasGroup = array ();
		$shop->CacheGoupsIdTree = array ();
		
		$items = array();
		$items[0] = '..';
		
		if (is_array($mas) && count($mas) > 0)
		{
			foreach ($mas as $key_mas => $value_mas)
			{
				//$items[$mas[$key_mas]['shop_groups_id']] = $mas[$key_mas]['separator'] . $mas[$key_mas]['shop_groups_name'];
				// Получаем полный путь к группе товаров
				//$group_path_array = GetShopPathArray($value_mas['shop_groups_id']);
				$group_path_array = $shop->GetShopPathArray($mas[$key_mas]['shop_groups_id'], true);

				$items[$value_mas['shop_groups_id']] = implode(' / ', $group_path_array);
			}
		}

		unset($mas);

		$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'] = 'shop_id';
		$form_params['type'] = 4; // Скрытое поле.
		$form_params['value'] = $shop_shops_id;
		$admin_forms_fields->AddField($form_params);

		// Добавляем скрытое поле с идентификатором текущей группы
		$form_params = array();
		$form_params['tab_id'] = $tab_id;
		$form_params['name'] = 'shop_groups_parent_id';
		$form_params['type'] = 4; // Скрытое поле.
		$form_params['value'] = $shop_groups_parent_id;
		$admin_forms_fields->AddField($form_params);

		// Добавляем специальное скрытое поле с именем кнопки
		$form_params = array();
		$form_params['tab_id'] = $tab_id;
		$form_params['name'] = 'add_shop_item_shortcut';
		$form_params['type'] = 4; // Скрытое поле.
		$form_params['value'] = '';
		$admin_forms_fields->AddField($form_params);

		$form_params = array();
		$form_params['name'] = 'add_shop_item_shortcut';
		$form_params['caption'] = $GLOBALS['MSG_shops']['save'];
		$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=65&shop_shops_id={$shop_shops_id}&shop_groups_parent_id={$shop_groups_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 sprintf($GLOBALS['MSG_shops']['add_shop_item_shortcut_title'], to_str($shop_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();

	$shop_shops_id = to_int($_REQUEST['shop_shops_id']);
	$shop_groups_parent_id = to_int($_REQUEST['shop_groups_parent_id']);

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

	if (isset($param['data']))
	{		
		ob_start();
				
		$form_name = 'move_items_gorups_' . time();
		$form_params = array();
		$form_params['form_attribs']['method'] = 'post';
		$form_params['form_attribs']['action'] = '/admin/shop/shop.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_shops']['tab']);

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

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

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

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

					$form_params = array();
					$form_params['tab_id'] = $tab_id;
					$form_params['name'] = 'move_group_' . $shop_group_id;
					$form_params['type'] = 4; // Скрытое поле.
					$form_params['value'] = $shop_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 = $shop->GetItem($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))
				{
					$shop_item_id = intval($key);

					$form_params = array();
					$form_params['tab_id'] = $tab_id;
					$form_params['name'] = 'move_item_' . $shop_item_id;
					$form_params['type'] = 4; // Скрытое поле.
					$form_params['value'] = $shop_item_id;
					$admin_forms_fields->AddField($form_params);
				}
			}
		}
			
		// Список групп
		$form_params = array();
		$form_params['tab_id'] = $tab_id;
		$form_params['name'] = 'shop_group_id';
		$form_params['caption'] = $GLOBALS['MSG_shops']['move_items_groups_shop_groups_id'];
		$form_params['type'] = 2; // Выпадающий список.
		$form_params['value'] = 0;

		// Массив, содержащий полное дерево групп

		$mas = $shop->GetDelimitedGroups(0, $shop_shops_id, "&nbsp;&nbsp;");

		// Массив идентификаторов переносимых групп
		$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];
			}
		}

		if (is_array($mas) && count($mas) > 0)
		{
			// Удаляем из массива с деревом групп переносимые группы и их дочерние подгруппы
			foreach($mas as $key_group_tree => $value_group_tree)
			{
				// Цикл по переносимым группам
				foreach($mas_move_groups as $key_move_groups => $value_move_groups)
				{
					// Текущая группа в дереве групп является переносимой группой
					// или родительской по отношению к переносимой
					if ($value_group_tree['shop_groups_id'] == $value_move_groups
					|| $value_group_tree['shop_groups_parent_id'] == $value_move_groups)
					{
						if ($value_group_tree['shop_groups_parent_id'] == $value_move_groups)
						{
							//$mas_move_groups[$key_move_groups] = $value_group_tree['shop_groups_id'];

							$mas_move_groups[] = $value_group_tree['shop_groups_id'];
						}

						unset($mas[$key_group_tree]);
					}
				}
			}
		}

		$items = array();
		$items[0] = '..';

		if (is_array($mas) && count($mas) > 0)
		{
			foreach ($mas as $key_mas => $value_mas)
			{
				//$items[$mas[$key_mas]['shop_groups_id']] = $mas[$key_mas]['separator'] . $mas[$key_mas]['shop_groups_name'];
								
				// Получаем полный путь к группе товаров
				$group_path_array = $shop->GetShopPathArray($mas[$key_mas]['shop_groups_id'], true);
							
				$items[$mas[$key_mas]['shop_groups_id']] = implode(' / ', $group_path_array);
			}
		}

		$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'] = 'shop_shops_id';
		$form_params['type'] = 4; // Скрытое поле.
		$form_params['value'] = $shop_shops_id;
		$admin_forms_fields->AddField($form_params);

		// Добавляем скрытое поле с идентификатором текущей группы
		$form_params = array();
		$form_params['tab_id'] = $tab_id;
		$form_params['name'] = 'shop_groups_parent_id';
		$form_params['type'] = 4; // Скрытое поле.
		$form_params['value'] = $shop_groups_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_shops']['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=65&shop_shops_id={$shop_shops_id}&shop_groups_parent_id={$shop_groups_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_shops']['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;
}

/**
 * функция для удаления элемента
 *
 * @param array $param
 */
function delete_item(&$param)
{
	ob_start();

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

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

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

		$shop = & singleton('shop');

		$count = 0;

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

				$shop = & singleton('shop');

				// Определяем информацию об объекте
				$object_row = $shop->GetItem($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 (!$shop->DeleteItem($key))
					{
						$flag_success = false;
					}
					else
					{
						$count++;

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

					$flag_success = false;
				}

			}

			if ($flag_success)
			{
				if ($count == 1)
				{
					show_message($GLOBALS['MSG_shops']['items_catalog_success_delete']);
				}
				else
				{
					show_message($GLOBALS['MSG_shops']['items_catalogs_success_delete']);
				}
			}
		}
		// Удаление каталога элементов
		if (isset($param['data'][0]))
		{
			foreach ($param['data'][0] as $key => $value)
			{
				// Определяем режим доступа пользователя и принадлежит ли объект пользователю
				$user_access = new user_access();

				$shop = & singleton('shop');

				// Определяем информацию об объекте
				$object_row = $shop->GetGroup($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 (!$shop->DeleteGroup($key))
					{
						$flag_success = false;
					}
					else
					{
						$count++;

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

					$flag_success = false;
				}

			}

			if ($flag_success)
			{
				if ($count == 1)
				{
					show_message($GLOBALS['MSG_shops']['groups_success_delete']);
				}
				else
				{
					show_message($GLOBALS['MSG_shops']['groups_success_deletes']);
				}
			}
		}
	}

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

/**
 * Добавление/редактирование элементов/каталогов магазина
 *
 * @param array $param
 * @return boolean
 */
function edit_item(&$param)
{
	ob_start();

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

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

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

				$shop = & singleton('shop');

				// Определяем информацию об объекте
				$object_row = $shop->GetGroup($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))
				{
					$id = $key;

					include(CMS_FOLDER.'admin/shop/action/form_edit_add_groups.php');
					// Устанавливаем <title> для страницы
					$param['title'] = ($id == 0)
					? $GLOBALS['MSG_shops']['groups_add_form_title']
					: $GLOBALS['MSG_shops']['groups_edit_form_title'];
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}

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

				$shop = & singleton('shop');

				// Определяем информацию об объекте
				$object_row = $shop->GetItem($id, 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 ($object_row['shop_items_catalog_shortcut_id'] != 0)
					{
						$id = $object_row['shop_items_catalog_shortcut_id'];
					}
					else
					{
						$id = intval($id);
					}

					include(CMS_FOLDER.'admin/shop/action/form_edit_add_items_catalog.php');

					// Устанавливаем <title> для страницы
					$param['title'] = ($id == 0)
					? $GLOBALS['MSG_shops']['items_catalog_add_form_title']
					: $GLOBALS['MSG_shops']['items_catalog_edit_form_title'];
				}
				else
				{
					$user_access->MessageOnlyOwn();
					$param['error'] = ob_get_clean();
					return ;
				}
			}
		}
	}

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

/**
 * Применить изменения
 *
 * @param array $param
 */
function apply_changes(&$param)
{
	ob_start();
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');
		$kernel->ReadMode();
	}
	else
	{
		$shop_groups_parent_id = to_int($_REQUEST['shop_groups_parent_id']);
		$shop_shops_id = to_int($_REQUEST['shop_shops_id']);

		$params = array();
		$shop = & singleton('shop');
		$DataBase = & singleton('DataBase');

		if (isset($param['data']))
		{
			// редактирование директории
			foreach ($param['data'] AS $key => $val)
			{
				foreach ($val AS $id => $value)
				{
					$id = intval($id);

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

						$shop = & singleton('shop');

						// Определяем информацию об объекте
						$object_row = $shop->GetItem($id, array('cache_off' => true));
						
						// Ярлык
						if ($object_row['shop_items_catalog_shortcut_id'] != 0)
						{
							// Сохраняем идентификатор товара/ярлыка товара
							$original_shortcut_id = $id;
								
							$id = $object_row['shop_items_catalog_shortcut_id'];

							//echo $object_row['shop_items_catalog_shortcut_id'];
							// Получаем информацию о товаре, на который ссылается ярлык
							$object_row = $shop->GetItem($object_row['shop_items_catalog_shortcut_id'], 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 (isset($value['ostatok']))
							{
								$warehouse = & singleton('warehouse');
								$aWarehouseDefaultRow = $warehouse->GetDefaultWarehouse($object_row['shop_shops_id']);
								if ($aWarehouseDefaultRow)
								{
									$warehouse->InsertWarehouseItems(array(
										'shop_warehouse_id' => $aWarehouseDefaultRow['shop_warehouse_id'],
										'shop_items_catalog_item_id' => $id,
										'shop_warehouse_items_count' => $value['ostatok']
									));
								}
							}
							
							// Есть поле расценки yandex маркет
							if (isset($value['price_ym_bid']))
							{
								$price_ym_bid = intval($value['price_ym_bid']);
								$query_price_ym_bid = ",`shop_items_catalog_yandex_market_bid` = {$price_ym_bid}";
							}
							else
							{
								$query_price_ym_bid = '';
							}

							if (isset($value['ym_allow']))
							{
								$ym_allow = intval($value['ym_allow']);
								$query_ym_allow = ", `shop_items_catalog_yandex_market_allow` = {$ym_allow}";
							}
							else
							{
								$query_ym_allow = '';
							}

							$order = to_int($value['orderr']);

							$price = $shop->ConvertPrice(to_str($value['price']));

							// Товар
							if (!isset($original_shortcut_id))
							{
								$query = "UPDATE `shop_items_catalog_table` SET `shop_items_catalog_order` = '$order',`shop_items_catalog_price` ='$price' 
										$query_price_ym_bid $query_ym_allow
										WHERE `shop_items_catalog_item_id` = '$id'";
										$DataBase->query($query);
							}
							else // Ярлык товара
							{
								$query = "UPDATE `shop_items_catalog_table` SET 
								`shop_items_catalog_price` ='$price' $query_price_ym_bid $query_ym_allow
								WHERE `shop_items_catalog_item_id` = '$id'";

								$DataBase->query($query);

								// Для ярлыка "свой" порядок сортировки
								$query = "UPDATE `shop_items_catalog_table` SET `shop_items_catalog_order` = '$order'
								WHERE `shop_items_catalog_item_id` = '$original_shortcut_id'";

								$DataBase->query($query);
							}
						}
						else
						{
							$user_access->MessageOnlyOwn();
							$param['error'] = ob_get_clean();
							return ;
						}
					}
					
					// Группа
					if (isset($param['data'][0]))
					{
						// Определяем режим доступа пользователя и принадлежит ли объект пользователю
						$user_access = new user_access();

						$shop = & singleton('shop');

						// Определяем информацию об объекте
						$object_row = $shop->GetGroup($id);
						
						if ($object_row)
						{
							$object_user_id = $object_row['users_id'];
						}
						else
						{
							$object_user_id = 0;
						}

						if ($user_access->IssetUserAccessForObject($object_user_id))
						{
							$order = to_int($value['orderr']);
							$query = "UPDATE `shop_groups_table` SET `shop_groups_order` = '$order' WHERE `shop_groups_id` = '$id'";
							$DataBase->query($query);
						}
						else
						{
							$user_access->MessageOnlyOwn();
							$param['error'] = ob_get_clean();
							return ;
						}
					}
				}
			}
		}
	}
	$error = ob_get_clean();

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

// Копирование товара
function copy_item(&$param)
{
	ob_start();
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

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

		$count_copys = 0;

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

					$shop = & singleton('shop');

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

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						if ($shop->CopyItem($key))
						{
							$count_copys++;

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

				// Сообщения на странице
				// Копирование завершено успешно
				if ($flag_success_copy)
				{
					if ($count_copys == 1)
					{
						show_message($GLOBALS['MSG_shops']['copy_one_item_success']);
					}
					else
					{
						show_message($GLOBALS['MSG_shops']['copy_many_items_success']);
					}
				}
				// Ошибка копирования
				else
				{
					show_error_message($GLOBALS['MSG_shops']['copy_item_error']);
				}
			}
		}
	}
	$error = ob_get_clean();

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

/**
 * Изменение статуса активности
 *
 * @param array $param
 */
function active(&$param)
{
	ob_start();

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

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

		if (isset($param['data']))
		{
			$user_access = & singleton('user_access');
			$shop = & singleton('shop');

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

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

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

					if ($user_access->IssetUserAccessForObject($object_user_id))
					{
						$object_row = $shop->GetGroup($key);

						$shop->InsertGroup(array('group_id' => $key,
						'shop_shops_id' => $object_row['shop_shops_id'],
						'shop_groups_indexation' => $object_row['shop_groups_indexation'],
						'shop_groups_activity' => 1 - $object_row['shop_groups_activity']));
						/*$key = intval($key);
						 $query = "UPDATE `shop_groups_table` SET `shop_groups_activity` = 1 - `shop_groups_activity` WHERE `shop_groups_id` = '$key'";
						 $ret = $DataBase->query($query);*/
					}
					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();

					$shop = & singleton('shop');

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

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

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

						// Если указан текущий статус - используем его,
						// необходимо в случае, если указывается прямая ссылка
						// и инвертирование недопустимо.
						if (isset($_REQUEST['current_status']))
						{
							if ($_REQUEST['current_status'] == 0)
							{
								$current_status = 0;
							}
							else
							{
								$current_status = 1;
							}

							$shop->InsertItem(array('item_id' => $key,
							'shops_id' => $object_row['shop_shops_id'],
							'is_active' => 1 - $current_status));

							/*$query = "UPDATE `shop_items_catalog_table`
							 SET `shop_items_catalog_is_active` = 1 - {$current_status}
							 WHERE `shop_items_catalog_item_id` = '$key'";*/
						}
						else
						{
							$shop->InsertItem(array('item_id' => $key,
							'shops_id' => $object_row['shop_shops_id'],
							'is_active' => 1 - $object_row['shop_items_catalog_is_active']));

							/*$query = "UPDATE `shop_items_catalog_table`
							 SET `shop_items_catalog_is_active` = 1 - `shop_items_catalog_is_active`
							 WHERE `shop_items_catalog_item_id` = '$key'";*/
						}

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

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

/**
 * Изменение статуса индексации
 *
 * @param array $param
 */
function index(&$param)
{
	ob_start();
	if (defined('READ_ONLY') && READ_ONLY)
	{
		$kernel = & singleton('kernel');

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

					$shop = & singleton('shop');

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

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

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

						$query = "UPDATE `shop_items_catalog_table` SET `shop_items_catalog_indexation` = 1 - `shop_items_catalog_indexation` WHERE `shop_items_catalog_item_id` = '$key'";

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

					$shop = & singleton('shop');

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

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

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

						$query = "UPDATE `shop_groups_table` SET `shop_groups_indexation` = 1 - `shop_groups_indexation` WHERE `shop_groups_id` = '$key'";

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

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