<?
if (!defined('SITE')) die();
//echo "<PRE>"; print_r ($_GET); echo "</PRE>";

function show_page_list_admin ($page, $num, $count_on_page, $id_cat)
{
	echo "<table align=center><tr><td>";
	if (!isset($page) && intval($page) == 0) $page = 1;
	$count_pages = intval($num / $count_on_page); //количество страниц = количество строчек в базе : кол-во элементов на странице
	$ostatok = $num % $count_on_page;// проверяем, нет ли остатка от деления
	if($ostatok > 0) $count_pages++;//если остаток есть, то прибавляем к числу страниц единичку
	if ($page>1) echo " <a href = \"".$h."/admin/catalog/category/$id_cat/page/".($page - 1)."/\" title = \"Предыдущая страница\"> <strong class=\"sm gray\"><<</strong> </a> ";
	$diapazon = 7;
	$page_from = $page - $diapazon; 
	if($page_from < 1) $page_from = 1;
	$page_to = $page + $diapazon; 
	if($page_to > $count_pages) $page_to = $count_pages;

	for ($i = $page_from; $i <= $page_to; $i++) // в цикле увеличиваем $i, пока не будет <= общему числу страниц
	{
		if ($count_pages != 1)
		{
			if ($i == $page) echo " <strong class=gray>[$i]</strong> ";
			else echo "<a href =\"http://".$_SERVER['HTTP_HOST'].$GLOBALS['p']."/admin/catalog/category/$id_cat/page/$i/\" title=\"$i страница\"> <strong class=gray>[$i]</strong> </a>";
		}
	}

	if ($page<$count_pages) echo " <a href = \"http://".$_SERVER['HTTP_HOST'].$GLOBALS['p']."/admin/catalog/category/$id_cat/page/".($page + 1)."/\" title=\"Следующая страница\"> <strong class=\"sm gray\">>></strong> </a> ";
	echo "</td></tr></table>";
}
function list2subcategory($id, $sub)
{
	$categories = mysql_query("SELECT * FROM jshop_categories WHERE root_category = $id");
	while($category = mysql_fetch_array($categories)) 
	{	
		$count = 0;
		$count = mysql_numrows(mysql_query("SELECT * FROM jshop_cat WHERE category = ".$category['id']));
		$query = mysql_query("SELECT * FROM jshop_categories WHERE root_category = ". $category['id']);
		if(@mysql_numrows($query) > 0) $root = 1;
		echo "<tr bgcolor=#FFFFFF><td><div>";
		for($i = 0; $i < $sub; $i++) echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		echo "<a href=\"http://".$_SERVER['HTTP_HOST'].$GLOBALS['p']."/admin/catalog/category/".$category['id']."/\">".$category['category_name']."</a> ";
		if(@$root != 1) echo " [$count] ";
		echo "</div></td><td align=center><div><a href=\"http://".$_SERVER['HTTP_HOST'].$GLOBALS['p']."/admin/catalog/category/".$category['id']."/edit/\"><img border=0 src=\"http://".$_SERVER['HTTP_HOST'].$GLOBALS['p']."/img/edit.gif\"></a></div></td><td align=center><div><a href=\"http://".$_SERVER['HTTP_HOST'].$GLOBALS['p']."/admin/catalog/category/".$category['id']."/drop/\" onClick='return ConformDelete(this);'><img border=0 src=\"http://".$_SERVER['HTTP_HOST'].$GLOBALS['p']."/img/drop.gif\"></a></div></td></tr>";
		$root = 0;
		list2subcategory($category['id'], $sub+1);
	}
}


if (@$_GET['op'] == "category" && !@$_GET['item'])
{
	if (@$_GET['go'] == "new")
	{
		if(@$_POST['name'] != "")
		{
			$_POST['name'] = strip_tags($_POST['name']);
			$_POST['root'] = intval ($_POST['root']);
			if (!get_magic_quotes_gpc()) $_POST['name'] = mysql_escape_string($_POST['name']);
			else $_POST['name'] = str_replace("'","`", $_POST['name']);
			if (mysql_query("INSERT INTO jshop_categories SET category_name = '".$_POST['name']."', root_category = '".$_POST['root']."'"))
			{
				if(@$_FILES["logo"]["name"] != "" and $_FILES['logo']['size'] > "0")
				{
					$valid_types=array("gif","jpg","jpeg","png");
					$fotoname = $_FILES['logo']['name'];
					$fotosize=$_FILES['logo']['size'];
					$ext = strtolower(substr($fotoname, 1 + strrpos($fotoname, ".")));
					if (!in_array($ext, $valid_types)) die ("Ошибка при загрузке изображения");
					$path = @$PATH_TRANSLATED;
					$path = str_replace('sadmin.php','', $path);
					preg_match("/(.*?)\.(.*?)/", $fotoname, $result);
					$ras = str_replace($result[1].".", "", $fotoname);
					$file_id = mysql_insert_id();
					$size= GetImageSize($_FILES["logo"]["tmp_name"]);
					$w = $size[0]; $hs = $size[1];
					$filename = $file_id.".".$ras;
					$path_for_icons = "upload_category/";
					$small_height = $hs * $category_width_ico / $w;
					if(!@img_resize($_FILES["logo"]["tmp_name"], $path.$path_for_icons.$filename, $category_width_ico, $small_height)) die ("Ошибка при загрузке изображения");
					$update = mysql_query ("UPDATE jshop_categories SET logo = '".$filename."' WHERE id = '".$file_id."'"); 
				}
				echo "Категория добавлена";
			}
		}
		else
		{
			echo "<form enctype=\"multipart/form-data\" method=post action=\"".$h."/admin/catalog/category/new/\">";
			echo "<table align=center cellpadding=0 cellspacing=0><tr><td bgcolor=#E5E5E5><table width=100% cellpadding=1 cellspacing=1>";
			echo "<tr bgcolor=#F8F8F8><td colspan=10 align=center><div><b>Добавить категорию</b></div></td></tr>";
			echo "<tr bgcolor=#FFFFFF><td><div>Название</div></td><td align=center><div><input type=text name=name></div></td></tr>";
			echo "<tr bgcolor=#FFFFFF><td><div>Подкатегория</div></td><td align=center><div>"; 
			echo "<select name=root>";
			echo "<option value=\"0\">Корневая директория</option>";
		
			function subcategory($id, $sub)
			{
				$categories = mysql_query("SELECT * FROM jshop_categories WHERE root_category = $id");
				while($category = mysql_fetch_array($categories)) 
				{	
					echo "<option value=\"".$category['id']."\">"; 
					for($i = 0; $i < $sub; $i++) echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
					echo $category['category_name'];
					subcategory($category['id'], $sub+1);
				}
			}
			$categories = mysql_query("SELECT * FROM jshop_categories WHERE root_category = 0");
			while($category = mysql_fetch_array($categories)) 
			{
				$sub = 1;
				echo "<option value=\"".$category['id']."\">".$category['category_name'];
				subcategory($category['id'], $sub);
			}					
			echo "</select>";
			echo "</div></td></tr>
			
			<tr bgcolor=#FFFFFF><td><div>Картинка</div></td><td align=center><div>
			
			<input type=file name=logo><br /><br />			
			</div></td></tr>
			</table></td></tr></table><br><br><center><input type=submit value=Добавить></center></form>";
		}	
	}
	else if (@$_GET['go'] == "edit")
	{
		if (@$_GET['img'] == "drop_img")
		{
			
			$category = mysql_query("SELECT * FROM jshop_categories WHERE id = ".intval($_GET['id']));
			if(mysql_num_rows($category)) $chcategory = mysql_fetch_assoc($category);
			$path = str_replace("sadmin.php","", @$PATH_TRANSLATED);
			if (file_exists($path."upload_category/".$chcategory['logo']))
			{
				if ($del_photo = unlink($path."upload_category/".$chcategory['logo']))
				{
					$icon_update = mysql_query ("UPDATE jshop_categories set logo = '' WHERE id = '".$chcategory['id']."' LIMIT 1");
				}
			}
		}
		if(@$_POST['name'] != "")
		{
			if ($_POST['root'] == $_GET['id']) die("Категория не может одновременно быть и своим родителем!");
			$_POST['name'] = strip_tags($_POST['name']);
			$_POST['root'] = intval ($_POST['root']);
			if (!get_magic_quotes_gpc()) $_POST['name'] = mysql_escape_string($_POST['name']);
			else $_POST['name'] = str_replace("'","`", $_POST['name']);
			
			if (mysql_query("UPDATE jshop_categories SET category_name = '".$_POST['name']."', root_category = '".$_POST['root']."' WHERE id = '".intval($_GET['id'])."'"))
			{
				if(@$_FILES["logo"]["name"] != "" and $_FILES['logo']['size'] > "0")
				{
					$valid_types=array("gif","jpg","jpeg","png");
					$fotoname = $_FILES['logo']['name'];
					$fotosize=$_FILES['logo']['size'];
					$ext = strtolower(substr($fotoname, 1 + strrpos($fotoname, ".")));
					if (!in_array($ext, $valid_types)) die ("Ошибка при загрузке изображения");
					$path = @$PATH_TRANSLATED;
					$path = str_replace('sadmin.php','', $path);
					preg_match("/(.*?)\.(.*?)/", $fotoname, $result);
					$ras = str_replace($result[1].".", "", $fotoname);
					$file_id = intval($_GET['id']);
					$size= GetImageSize($_FILES["logo"]["tmp_name"]);
					$w = $size[0]; $hs = $size[1];
					$filename = $file_id.".".$ras;
					$path_for_icons = "upload_category/";
					$small_height = $hs * $category_width_ico / $w;
					if(!@img_resize($_FILES["logo"]["tmp_name"], $path.$path_for_icons.$filename, $category_width_ico, $small_height)) die ("Ошибка при загрузке изображения");
					$update = mysql_query ("UPDATE jshop_categories SET logo = '".$filename."' WHERE id = '".$file_id."'"); 
				}
				echo "Данные изменены!<br />";
			}
		}
		else
		{
			$category = mysql_query("SELECT * FROM jshop_categories WHERE id = ".intval($_GET['id']));
			if(mysql_numrows($category) == 1)
			{
				$chcategory = mysql_fetch_array($category);
				
				$chcategory['category_name'] = str_replace('"', "&quot;", $chcategory['category_name']);
				echo "<form enctype=\"multipart/form-data\" method=post action=\"".$h."/admin/catalog/category/".$chcategory['id']."/edit/\">";
				echo "<table align=center cellpadding=0 cellspacing=0><tr><td bgcolor=#E5E5E5><table width=100% cellpadding=1 cellspacing=1>";
				echo "<tr bgcolor=#F8F8F8><td colspan=10 align=center><div><b>Редактировать категорию</b></div></td></tr>";
				echo "<tr bgcolor=#FFFFFF><td><div>Название</div></td><td align=center><div><input type=text name=name value=\"".$chcategory['category_name']."\"></div></td></tr>";
				
				echo "<tr bgcolor=#FFFFFF><td><div>Подкатегория</div></td><td align=center><div>"; 
				echo "<select name=root>";
				echo "<option value=\"0\""; if($chcategory['root_category'] == 0) echo " selected"; echo "> Корневая директория </option>";
	
				
				function subcategory($id, $sub)
				{
					global $chcategory;
					$categories = mysql_query("SELECT * FROM jshop_categories WHERE root_category = $id");
					while($category = mysql_fetch_array($categories)) 
					{	
						echo "<option value=\"".$category['id']."\""; if($chcategory['root_category'] == $category['id']) echo " selected"; echo ">"; 
						for($i = 0; $i < $sub; $i++) echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
						echo $category['category_name'];
						subcategory($category['id'], $sub+1);
					}
				}
				$categories = mysql_query("SELECT * FROM jshop_categories WHERE root_category = 0");
				while($category = mysql_fetch_array($categories)) 
				{
					$sub = 1;
					echo "<option value=\"".$category['id']."\""; if($chcategory['root_category'] == $category['id']) echo " selected"; echo ">".$category['category_name'];
					subcategory($category['id'], $sub);
				}					
				echo "</select></div></td></tr>";
				
				echo "<tr bgcolor=#FFFFFF><td><div>Картинка</div></td><td align=center><div>";
				
				if ($chcategory['logo']) echo "<img src=\"".$h."/upload_category/".$chcategory['logo']."\"><br /><a href=\"".$h."/admin/catalog/category/".$chcategory['id']."/edit/drop_img/\">Удалить картинку</a>";
				else echo "<input type=file name=logo>";
				echo "</div></td></tr></table></td></tr></table><br><br><center><input type=submit value=Редактировать></center></form>";
			}	
		}
	}
	else if (@$_GET['go'] == "drop")
	{
		if (mysql_num_rows (mysql_query ("SELECT * FROM jshop_categories WHERE root_category = '".$_GET['id']."'"))) die ("Вам не удастся удалить категорию, имеющую дочерние подкатегории. Сначала удалите их.");
		else
		{
			$tovary = mysql_query ("SELECT * FROM jshop_cat WHERE category = '".intval($_GET['id'])."'");
			if (mysql_num_rows ($tovary))
			{
				while ($tovar = mysql_fetch_assoc ($tovary))
				{
					if ($tovar['image'])
					{
						$path = str_replace("sadmin.php","", @$PATH_TRANSLATED);
						
						if (file_exists($path."upload_cat/big/".$tovar['image'])) unlink($path."upload_cat/big/".$tovar['image']);
						if (file_exists($path."upload_cat/normal/".$tovar['image'])) unlink($path."upload_cat/normal/".$tovar['image']);
						if (file_exists($path."upload_cat/small/".$tovar['image'])) unlink($path."upload_cat/small/".$tovar['image']);
					}
					mysql_query ("DELETE FROM jshop_cat WHERE id = '".$tovar['id']."'");
				}
				echo "Все товары данной категории удалены<br>";
			}
		}
		
		$category = mysql_query("SELECT * FROM jshop_categories WHERE id = ".intval($_GET['id']));
		if(mysql_num_rows($category)) $chcategory = mysql_fetch_assoc($category);
		if ($chcategory['logo'])
		{
			$path = str_replace("sadmin.php","", @$PATH_TRANSLATED);
			if (file_exists($path."upload_category/".$chcategory['logo'])) unlink($path."upload_category/".$chcategory['logo']);
		}
		if (mysql_query("DELETE FROM jshop_categories WHERE id = ".$chcategory['id'])) echo "Категория удалена!<br />";
	}
	else if (@$_GET['go'] == "show")
	{
		$num = mysql_num_rows(mysql_query("SELECT * FROM jshop_cat WHERE category = '".$_GET['id']."'"));
		@$start = page_list ($_GET['page'], $num, $COUNT_SHOW_ITEMS);
		echo "<div><a href=\"".$h."/admin/catalog/category/".intval($_GET['id'])."/item/new/\">Добавить наименование</a></div><br>";

		if(@$_GET['item'] == "" || $_GET['item'] == "drop")
		{
			if(@$_GET['item'] == "drop") mysql_query("DELETE FROM jshop_cat WHERE id = ". $_GET['item_id']);
			echo "<table align=center width=98% cellpadding=0 cellspacing=0><tr><td bgcolor=#E5E5E5><table width=100% cellpadding=1 cellspacing=1>";
			echo "<tr bgcolor=#F8F8F8><td colspan=7 align=center><div><b>Товары</b></div></td></tr>";
			echo "<tr bgcolor=#FFFFFF>
			<td align=center width=$small_width_new><div></div></td>
			<td align=center><div><strong>Наименование товара</strong></div></td>
			
			<td align=center><div><strong>Цена товара, руб.</strong></div></td>
			<td align=center><div><strong>Редактировать</strong></div></td>
			<td align=center><div><strong><br />Удалить<br /><br /></strong></div></td></tr>";

			$items = mysql_query ("SELECT * FROM jshop_cat WHERE category = '".$_GET['id']."' LIMIT $start,$COUNT_SHOW_ITEMS"); // запрос с LIMITом
			while($item = mysql_fetch_array($items))
			{
				echo "<tr bgcolor=#FFFFFF><td align=center width=$small_width_new><div>";
				if($item['image'] != "") echo "<table cellpadding=0 cellspacing=0><tr><td bgcolor=#E5E5E5 width=$small_width_new><table cellpadding=1 cellspacing=1><tr><td bgcolor=#FFFFFF><img src=\"".$h."/upload_cat/small/".$item['image']."\"></td></tr></table></td></tr></table>";
				else echo "<table cellpadding=0 cellspacing=0><tr><td bgcolor=#E5E5E5 width=$small_width_new height=$small_width_new><table cellpadding=1 cellspacing=1><tr><td bgcolor=#FFFFFF align=center width=$small_width_new height=$small_width_new><div>нет изображения</div></td></tr></table></td></tr></table>";
				echo "</div></td>
				<td align=center><div>".$item['name']."</div><br />".$item['short_review']."</td>
				
				<td align=center><div>".$item['price']."</div></td>
				<td align=center><div><a href=\"".$h."/admin/catalog/category/".$item['category']."/item/".$item['id']."/edit/\"><img border=0 src=\"".$im."/edit.gif\"></a></div></td>
				<td align=center><div><a href=\"".$h."/admin/catalog/category/".$item['category']."/item/".$item['id']."/drop/\" onClick='return ConformDelete(this);'><img border=0 src=\"".$im."/drop.gif\"></a></div></td></tr>";
			}
			echo "<tr bgcolor=#F8F8F8><td colspan=7><div>&nbsp;</div></td></tr>";
			echo "<tr bgcolor=#FFFFFF><td colspan=7 align=right><div><a href=\"".$h."/admin/catalog/category/".intval($_GET['id'])."/item/new/\">Добавить наименование</a></div></td></tr>";
			echo "</table></tr></td></table><br><br>";
			
			@show_page_list_admin($_GET['page'], $num, $COUNT_SHOW_ITEMS, $_GET['id']);
		}
	}
}
else if (@$_GET['item'] == "new")
{
	if(@$_POST['name'])
	{
		if($_POST['name'] == "") die ("Заполните поле \"Название\"");
		if($_POST['short_review'] == "") die ("Заполните поле \"Краткое описание\"");
		if($_POST['full_review'] == "") die ("Заполните поле \"Полное описание\"");
		if(!isset($_POST['recommend'])) $_POST['recommend'] = 0; 

		if (!get_magic_quotes_gpc())
		{
			$_POST['name'] = mysql_escape_string($_POST['name']);
			$_POST['short_review'] = mysql_escape_string($_POST['short_review']);
			$_POST['full_review'] = mysql_escape_string($_POST['full_review']);
			$_POST['info1'] = mysql_escape_string($_POST['info1']);
			$_POST['info2'] = mysql_escape_string($_POST['info2']);
		}
		else
		{
			$_POST['name'] = str_replace("'","`", $_POST['name']);
			$_POST['short_review'] = str_replace("'","`", $_POST['short_review']);
			$_POST['full_review'] = str_replace("'","`", $_POST['full_review']);
			$_POST['info1'] = str_replace("'","`", $_POST['info1']);
			$_POST['info2'] = str_replace("'","`", $_POST['info2']);
		}
		$query = mysql_query("INSERT INTO jshop_cat SET name = '".$_POST['name']."', category = '".$_POST['category']."', short_review = '".$_POST['short_review']."', full_review = '".$_POST['full_review']."', price = '".$_POST['price']."', date = NOW(), info1 = '".$_POST['info1']."', info2 = '".$_POST['info2']."', recommend = '".$_POST['recommend']."'");
		if($query) 
		{
			if($_FILES["banner"]["name"] != "")
			{
				$path = @$PATH_TRANSLATED;
				$path = str_replace("sadmin.php","", $path);
				preg_match("/(.*?)\.(.*?)/", $_FILES["banner"]["name"], $result);
				$ras = str_replace($result[1].".", "", $_FILES["banner"]["name"]);
				$file_id = mysql_insert_id();	
				$size= GetImageSize($_FILES["banner"]["tmp_name"]);
				$w = $size[0];	$hs = $size[1];
				$small_height = $hs * $small_width_new / $w;
				if(@img_resize($_FILES["banner"]["tmp_name"], $path.$small_path.$file_id.".".$ras, $small_width_new, $small_height)) {} else $errors = 1;
				$big_height = $hs * $big_width_new / $w;
				if(@img_resize($_FILES["banner"]["tmp_name"], $path.$big_path.$file_id.".".$ras, $big_width_new, $big_height)){} else $errors = 1;
				$normal_height = $hs * $normal_width_new / $w;
				if(@img_resize($_FILES["banner"]["tmp_name"], $path.$normal_path.$file_id.".".$ras, $normal_width_new, $normal_height)){} else $errors = 1;
				mysql_query("UPDATE `jshop_cat` SET image = '$file_id.$ras' WHERE id = $file_id");
			}
			echo "<br /><br /><center>Товар добавлен!</center><br><br>";
		}
		else echo "<center>Ошибка при добавлении товара_1!</center><br><br>";
	}
	
	if(isset($_POST['name'])) $_POST['name'] = str_replace('"', "&quot;", $_POST['name']);
	if(isset($_POST['price'])) $_POST['price'] = str_replace('"', "&quot;", $_POST['price']);
	if(isset($_POST['info1'])) $_POST['info1'] = str_replace('"', "&quot;", $_POST['info1']);
	if(isset($_POST['info2'])) $_POST['info2'] = str_replace('"', "&quot;", $_POST['info2']);
	if(isset($_POST['short_review'])) $_POST['short_review'] = str_replace('"', "&quot;", $_POST['short_review']);
	if(isset($_POST['full_review'])) $_POST['full_review'] = str_replace('"', "&quot;", $_POST['full_review']);


	if (@$_GET['id']) $g_id = $_GET['id']; else $g_id = 1;
	echo "<form enctype=\"multipart/form-data\" method=post action=\"".$h."/admin/catalog/category/".$_GET['id']."/item/new/\">";
	echo "<input type=hidden name=add value=1>";
	echo "<table align=center width=98% cellpadding=0 cellspacing=0><tr><td bgcolor=#E5E5E5><table width=100% cellpadding=1 cellspacing=1>";
	echo "<tr bgcolor=#F8F8F8><td colspan=10 align=center><div><b>Добавить наименование</b></div></td></tr>";
	echo "<tr bgcolor=#FFFFFF><td><div>Название</div></td><td><div><input type=text name=name size=98 value=\"".htmlspecialchars(@$_POST['name'])."\"></div></td></tr>";
	echo "<tr bgcolor=#FFFFFF><td><div>Категория</div></td><td><div>"; 
	echo "<select name=category>";
	function subcategory($id, $sub)
	{
		$categories = mysql_query("SELECT * FROM jshop_categories WHERE root_category = $id");
		while($category = mysql_fetch_array($categories)) 
		{	
			echo "<option value=\"".$category['id']."\""; if($_GET['id'] == $category['id']) echo " selected"; echo ">"; 
			for($i = 0; $i < $sub; $i++) echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
			echo $category['category_name'];
			subcategory($category['id'], $sub+1);
		}
	}
	$categories = mysql_query("SELECT * FROM jshop_categories WHERE root_category = 0");
	while($category = mysql_fetch_array($categories)) 
	{
		$sub = 1;
		echo "<option value=\"".$category['id']."\""; if($_GET['id'] == $category['id']) echo " selected"; echo ">".$category['category_name'];
		subcategory($category['id'], $sub);
	}					
	echo "</select></div></td></tr>";
	echo "<tr bgcolor=#FFFFFF><td><div>Цена, руб.</div></td><td><div><input type=text name=price size=98 value=\"".htmlspecialchars(@$_POST['price'])."\"></div></td></tr>";
	echo '<tr bgcolor=#FFFFFF><td><div>Путь к изображению</div></td><td><div><input size=50 type="file" name="banner" value="'; if(isset($_FILES["banner"]["tmp_name"])) echo $_FILES["banner"]["tmp_name"]; echo '"></div></td></tr>';
	echo "<tr bgcolor=#FFFFFF><td><div>Дополнительная информация 1</div></td><td><div><input type=text name=info1 size=98 value=\"".htmlspecialchars(@$_POST['info1'])."\"></div></td></tr>";
	echo "<tr bgcolor=#FFFFFF><td><div>Дополнительная информация 2</div></td><td><div><input type=text name=info2 size=98 value=\"".htmlspecialchars(@$_POST['info2'])."\"></div></td></tr>";
	echo "<tr bgcolor=#FFFFFF><td><div>Краткое описание</div></td><td><div><input type=text name=\"short_review\"  size=98 value=\"".htmlspecialchars(@$_POST['short_review'])."\"></div></td></tr>";
	echo "<tr bgcolor=#FFFFFF><td><div>Полное описание</div></td><td><div>";  
	include ('editor/spaw.inc.php'); $text = @$_POST['full_review']; $spaw2 = new SPAW_Wysiwyg("full_review", $text); $spaw2->show();
	echo "</div></td></tr>";
	echo "<tr bgcolor=#FFFFFF><td><div>Рекомендовать товар</div></td><td><div><input type=checkbox name=recommend value=1"; if(@$_POST['recommend'] == 1) echo " checked"; echo "></div></td></tr>";
	echo "</table></td></tr></table><br><br><center><input type=submit value=Добавить></center></form>";	
}


else if (@$_GET['item'] == "edit")
{
	if(@$_GET['photodel'] == 1)
	{
		$photodel = mysql_query ("SELECT image FROM jshop_cat WHERE id = '".intval($_GET['item_id'])."'");
		if (mysql_num_rows ($photodel)) $fotodel = mysql_fetch_assoc ($photodel);
		
		$path = str_replace("sadmin.php","", @$PATH_TRANSLATED);
		if (file_exists($path."upload_cat/small/".$fotodel['image'])) unlink($path."upload_cat/small/".$fotodel['image']);
		if (file_exists($path."upload_cat/big/".$fotodel['image'])) unlink($path."upload_cat/big/".$fotodel['image']);
		if (file_exists($path."upload_cat/normal/".$fotodel['image'])) unlink($path."upload_cat/normal/".$fotodel['image']);
		mysql_query("UPDATE jshop_cat SET image = '' WHERE id = ". $_GET['item_id']);
	}
	
	if(@$_POST['name'])
	{
		if($_POST['name'] == "") die ("Заполните поле \"Название\"");
		if($_POST['short_review'] == "") die ("Заполните поле \"Краткое описание\"");
		if($_POST['full_review'] == "") die ("Заполните поле \"Полное описание\"");
		if(!isset($_POST['recommend'])) $_POST['recommend'] = 0; else  $_POST['recommend'] = "1";

		if (!get_magic_quotes_gpc())
		{
			$_POST['name'] = mysql_escape_string($_POST['name']);
			$_POST['short_review'] = mysql_escape_string($_POST['short_review']);
			$_POST['full_review'] = mysql_escape_string($_POST['full_review']);
			$_POST['info1'] = mysql_escape_string($_POST['info1']);
			$_POST['info2'] = mysql_escape_string($_POST['info2']);
		}
		else
		{
			$_POST['name'] = str_replace("'","`", $_POST['name']);
			$_POST['short_review'] = str_replace("'","`", $_POST['short_review']);
			$_POST['full_review'] = str_replace("'","`", $_POST['full_review']);
			$_POST['info1'] = str_replace("'","`", $_POST['info1']);
			$_POST['info2'] = str_replace("'","`", $_POST['info2']);
		}
		$query = "UPDATE jshop_cat SET name = '".$_POST['name']."', category = '".$_POST['category']."', short_review = '".$_POST['short_review']."', full_review = '".$_POST['full_review']."', price = ".$_POST['price'].", info1 = '".$_POST['info1']."', info2 = '".$_POST['info2']."', recommend = ".$_POST['recommend']." WHERE id = ". $_GET['item_id'];

		if(mysql_query($query)) 
		{
			if(@$_FILES["banner"]["name"] != "")
			{
				$path = @$PATH_TRANSLATED;
				$path = str_replace("sadmin.php","", $path);
				preg_match("/(.*?)\.(.*?)/", $_FILES["banner"]["name"], $result);
				$ras = str_replace($result[1].".", "", $_FILES["banner"]["name"]);
				$file_id = $_GET['item_id'];	
				$size= GetImageSize($_FILES["banner"]["tmp_name"]);
				$w = $size[0];	$hs = $size[1];
				$small_height = $hs * $small_width_new / $w;
				if(@img_resize($_FILES["banner"]["tmp_name"], $path.$small_path.$file_id.".".$ras, $small_width_new, $small_height)) {} else $errors = 1;
				$big_height = $hs * $big_width_new / $w;
				if(@img_resize($_FILES["banner"]["tmp_name"], $path.$big_path.$file_id.".".$ras, $big_width_new, $big_height)){} else $errors = 1;
				$normal_height = $hs * $normal_width_new / $w;
				if(@img_resize($_FILES["banner"]["tmp_name"], $path.$normal_path.$file_id.".".$ras, $normal_width_new, $normal_height)){} else $errors = 1;
				mysql_query("UPDATE `jshop_cat` SET image = '$file_id.$ras' WHERE id = $file_id");
			}
			echo "<br><br><center>Товар успешно изменен!</center><br><br>";
		}
		else echo "<br><br><center>Ошибка при изменении товара!</center><br><br>";
	}

	else
	{
		$queryitem = mysql_query("SELECT * FROM jshop_cat WHERE id = ".intval($_GET['item_id']));
		if(mysql_num_rows($queryitem))
		{
			$item = mysql_fetch_assoc($queryitem);
			echo "<form enctype=\"multipart/form-data\" method=post action=\"".$h."/admin/catalog/category/".$item['category']."/item/".$item['id']."/edit/\">";
			echo "<table align=center width=98% cellpadding=0 cellspacing=0><tr><td bgcolor=#E5E5E5><table width=100% cellpadding=1 cellspacing=1>";
			echo "<tr bgcolor=#F8F8F8><td colspan=10 align=center><div><b>Редактировать наименование</b></div></td></tr>";
			echo "<tr bgcolor=#FFFFFF><td><div>Название</div></td><td><div><input type=text name=name size=98 value=\"".htmlspecialchars($item['name'])."\"></div></td></tr>";
			echo "<tr bgcolor=#FFFFFF><td><div>Категория</div></td><td><div>"; 
			echo "<select name=category>";
			function subcategory($id, $sub)
			{
				global $item;
				$categories = mysql_query("SELECT * FROM jshop_categories WHERE root_category = $id");
				while($category = mysql_fetch_array($categories)) 
				{	
					echo "<option value=\"".$category['id']."\""; if($item['category'] == $category['id']) echo " selected"; echo ">"; 
					for($i = 0; $i < $sub; $i++) echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
					echo $category['category_name'];
					subcategory($category['id'], $sub+1);
				}
			}
		
			$categories = mysql_query("SELECT * FROM jshop_categories WHERE root_category = 0");
			while($category = mysql_fetch_array($categories)) 
			{
				$sub = 1;
				echo "<option value=\"".$category['id']."\""; if($item['category'] == $category['id']) echo " selected"; echo ">".$category['category_name'];
				subcategory($category['id'], $sub);
			}					
			echo "</select></div></td></tr>";
			echo "<tr bgcolor=#FFFFFF><td><div>Цена, руб.</div></td>
			<td><div><input type=text name=price size=98 value=\"".htmlspecialchars($item['price'])."\"></div></td></tr>";
			echo "<tr bgcolor=#FFFFFF><td><div>Изображение</div></td><td><div>";
			if($item['image']) echo "<img src=\"".$h."/upload_cat/small/".$item['image']."\"> <br /><a href=\"".$h."/admin/catalog/category/".$item['category']."/item/".$_GET['item_id']."/edit/delete_photo/\">удалить изображение</a>";
			else echo "<input size=50 type=\"file\" name=\"banner\">";
			echo "</div></td></tr>";
			echo "<tr bgcolor=#FFFFFF><td><div>Дополнительная информация 1</div></td><td><div><input type=text name=info1 size=98 value=\"".htmlspecialchars($item['info1'])."\"></div></td></tr>";
			echo "<tr bgcolor=#FFFFFF><td><div>Дополнительная информация 2</div></td><td><div><input type=text name=info2 size=98 value=\"".htmlspecialchars($item['info2'])."\"></div></td></tr>";
			echo "<tr bgcolor=#FFFFFF><td><div>Краткое описание</div></td><td><div><input type=text name=\"short_review\"  size=98 value=\"".htmlspecialchars(@$item['short_review'])."\"></div></td></tr>";
			echo "<tr bgcolor=#FFFFFF><td><div>Полное описание</div></td><td><div>";
			include ('editor/spaw.inc.php');
			$text = @$item['full_review'];
			$spaw2 = new SPAW_Wysiwyg("full_review", $text);
			$spaw2->show();
			echo "</div></td></tr>";
			echo "<tr bgcolor=#FFFFFF><td><div>Рекомендовать товар</div></td><td><div><input type=checkbox name=recommend "; if(isset($_POST['full_review'])) { if($_POST['recommend'] == 1) echo " checked"; } else { if($item['recommend'] == 1) echo " checked"; } echo "></div></td></tr>";
			echo "</table></td></tr></table><br><br><center><input type=submit value=Редактировать></center></form>";	
		}
	}
}
else if (@$_GET['item'] == "drop")
{
	$tovary = mysql_query ("SELECT * FROM jshop_cat WHERE id = '".intval($_GET['item_id'])."'");
	if (mysql_num_rows ($tovary))
	{
		$tovar = mysql_fetch_assoc ($tovary);
		if ($tovar['image'])
		{
			$path = str_replace("sadmin.php","", @$PATH_TRANSLATED);
			if (file_exists($path."upload_cat/big/".$tovar['image'])) unlink($path."upload_cat/big/".$tovar['image']);
			if (file_exists($path."upload_cat/normal/".$tovar['image'])) unlink($path."upload_cat/normal/".$tovar['image']);
			if (file_exists($path."upload_cat/small/".$tovar['image'])) unlink($path."upload_cat/small/".$tovar['image']);
		}
		if (mysql_query ("DELETE FROM jshop_cat WHERE id = '".$tovar['id']."'")) echo "Товары удалён!<br>";
	}
}
else
{
	echo "<table align=center width=98% cellpadding=0 cellspacing=0><tr><td bgcolor=#E5E5E5><table width=100% cellpadding=1 cellspacing=1>";
	echo "<tr bgcolor=#FFFFFF><td colspan=3 align=center><a href=\"".$h."/admin/catalog/category/new/\">Добавить категорию</a> | <a href=\"".$h."/admin/catalog/category/1/item/new/\">Добавить наименование</a></td></tr>";
	echo "<tr bgcolor=#F8F8F8><td colspan=3 align=center><div><b>Категории</b></div></td></tr>";
	$categories = mysql_query("SELECT * FROM jshop_categories WHERE root_category = 0 ORDER by category_name ASC");
	while($category = mysql_fetch_array($categories)) 
	{
		$sub = 1;
		$count = 0;
		$count = mysql_numrows(mysql_query("SELECT * FROM jshop_cat WHERE category = ".$category['id']));
		$query = mysql_query("SELECT * FROM jshop_categories WHERE root_category = ". $category['id']);
		if(@mysql_numrows($query) > 0) $root = 1;
		echo "<tr bgcolor=#FFFFFF><td><div><a href=\"".$h."/admin/catalog/category/".$category['id']."/\">".$category['category_name']."</a> "; echo " [$count] "; echo "</div></td><td align=center><div><a href=\"".$h."/admin/catalog/category/".$category['id']."/edit/\"><img border=0 src=\"".$im."/edit.gif\"></a></div></td><td align=center><div><a href=\"".$h."/admin/catalog/category/".$category['id']."/drop/\" onClick='return ConformDelete(this);'><img border=0 src=\"".$im."/drop.gif\"></a></div></td></tr>";
		$root = 0;
		list2subcategory($category['id'], $sub);
	}
	echo "<tr bgcolor=#F8F8F8><td colspan=3><div>&nbsp;</div></td></tr>";
	echo "<tr bgcolor=#FFFFFF><td colspan=3 align=center><a href=\"".$h."/admin/catalog/category/new/\">Добавить категорию</a> | <a href=\"".$h."/admin/catalog/category/1/item/new/\">Добавить наименование</a></td></tr>";
	echo "</table></tr></td></table><br><br>";
}
?>