<?

if ($_REQUEST['op']=="saveprices") {
	
$prices = $_REQUEST['price'];		
$prices2 = $_REQUEST['price2'];
$count = $_REQUEST['kolvo'];
$titles = $_REQUEST['title'];
				
if (is_array($prices)){
		
			foreach($prices as $itemid=>$price){
				$price = str_replace(',', '.', $price);
				$price = number_format($price, 2, '.', '');
				
				$inDB->query("UPDATE cms_uc_items SET price='$price' WHERE id = '$itemid'");
				
	
			}
			
		}
	if (is_array($prices2)){	
			foreach($prices2 as $itemid=>$price2){
				$price2 = str_replace(',', '.', $price2);
				$price2 = number_format($price2, 2, '.', '');
				
				$inDB->query("UPDATE cms_uc_items SET price2='$price2' WHERE id = '$itemid'");
				
	
			}
				}
if (is_array($count)){	
			foreach($count as $itemid=>$kolvo){
		$inDB->query("UPDATE cms_uc_items SET kolvo='$kolvo' WHERE id = '$itemid'");
				
	
			}
				}
if (is_array($titles)){	
			foreach($titles as $itemid=>$title){
		$inDB->query("UPDATE cms_uc_items SET title='$title' WHERE id = '$itemid'");
				
	
			}
				}
		header('location:'.$_SERVER['HTTP_REFERER']);
	}
	
	


$id = $inUser->id;										
$usr['id']	 = $inUser->id;						
	$sql = "SELECT A.*, B.* FROM cms_users as A, cms_user_profiles as B WHERE A.id = $id AND B.user_id = $id";
	$result = $inDB->query($sql);
	
	if ($inDB->num_rows($result)>0){
		$usr = $inDB->fetch_assoc($result);
		$inPage->addPathway($usr['nickname'], cmsUser::getProfileURL($usr['login']));
		$inPage->addPathway($_LANG['tovari']);
        $inPage->setTitle($_LANG['tovari'].' - '.$usr['nickname']);

		
$usr['avatar'] = usrLink(usrImageNOdb($usr['id'], 'small', $usr['imageurl'], $usr['is_deleted']), $usr['login'], $menuid);
$usr['nickname'] = cmsUser::getProfileLink($usr['login'], $usr['nickname']);

$usr['tovari_count'] = $inDB->rows_count('cms_uc_items', "user_id={$usr['id']}");

$usr['karma'] = strip_tags( cmsUser::getKarmaFormat($usr['id'], false), '<table><tr><td><img><a>' );

							  
echo '<div class="o" style="margin-bottom:15px;background:#e3ecf6;padding:5px 10px">';
echo '<table width="100%" height="" cellspacing="" cellpadding="0"><tr>';

echo '<div class="con_heading" style="margin-bottom:7px;font-size:18px"><a href="'.cmsUser::getProfileURL($usr['login']).'">'.$usr['nickname'].'</a> &rarr; Товары <sup style="font-size:13px;color:#5485b7">'.$usr['tovari_count'].'</sup>
&nbsp;&nbsp;<img style="margin-right:3px" src="/templates/_default_/images/icons/add.png" align=absmiddle><span style="font-size:18px"><a href="/torg/add.html">Добавить товар</a> в </span>';

  echo '<form method="post" action="" enctype="multipart/form-data" style="display:inline" name=cats>';
    $sql0 = "SELECT * FROM cms_uc_cats WHERE parent_id>0 AND NSLevel=1";
$result0 = $inDB->query($sql0);
  echo '<select style="width:250px" name="cat_id" id="cat_id">';
while($cats = $inDB->fetch_assoc($result0)){	
echo '<option style="background:#e2eff4;text-align:center;font-weight:bold">--- '.$cats['title'].' ---</option>';
$cat_id=$cats['id'];
$sql2 = "SELECT * FROM cms_uc_cats WHERE parent_id='$cat_id'";
$result2 = $inDB->query($sql2);


while($sub_cats = $inDB->fetch_assoc($result2)) {
  echo '<option value="'.$sub_cats['id'].'" onclick=location.href="/torg/"+this.value+"/add.html">'.$sub_cats['title'].'</option>';
}
 }
echo '</select></form> <span style="color:#555;font-size:12px">&larr; Выберите подкатегорию</span>';

echo '</div>';
echo '<div class="o" style="background:#fff;padding:5px 10px;font-size:14px">';

if ($_REQUEST['op']=="import_xls") {
echo '<a href="/torg/u'.$id.'/tovari">В наличие</a>&nbsp;&nbsp;|&nbsp;&nbsp<a href="/torg/u'.$id.'/tovari-cart">В корзине</a> <span style="color:#555;font-size:12px">- (временное хранилище)</span>&nbsp;&nbsp;|&nbsp&nbsp<b>Импорт товаров из MS Excel</b>';
}
else if ($_REQUEST['op']=="tovari-cart") {
echo '<a href="/torg/u'.$id.'/tovari">В наличие</a>&nbsp;&nbsp;|&nbsp&nbsp;<b>В корзине</b> <span style="color:#555;font-size:12px">- (временное хранилище)</span>&nbsp;&nbsp;|&nbsp&nbsp<a href="/torg/u'.$id.'/tovari/import.html">Импорт товаров из MS Excel</a>';
}
else if ($_REQUEST['op']==!"tovari-cart") {
echo '<b>В наличие</b>&nbsp;&nbsp;|&nbsp;&nbsp<a href="/torg/u'.$id.'/tovari-cart">В корзине</a> <span style="color:#555;font-size:12px">- (временное хранилище)</span>&nbsp;&nbsp|&nbsp;&nbsp<a href="/torg/u'.$id.'/tovari/import.html">Импорт товаров из MS Excel</a>';
} else
 {
 echo '<a href="/torg/u'.$id.'/tovari">В наличие</a>&nbsp;&nbsp;|&nbsp;&nbsp<a href="/torg/u'.$id.'/tovari-cart">В корзине</a> <span style="color:#555;font-size:12px">- (временное хранилище)</span>&nbsp;&nbsp;&nbsp<a href="/torg/u'.$id.'/tovari/import.html">Импорт товаров из MS Excel</a>;';
}
echo '</div></td>';
echo '</tr></table></div>';



 


if ($_REQUEST['op']=="go_import_xls") {
		//get variables
		$cat_id = $inCore->request('cat_id', 'int');
		//$titles = $inCore->request('title', 'str');
		//$art = $inCore->request('art', 'str');
		//	$kolvo= $inCore->request('kolvo', 'int');
		$cat_title = $inCore->request('cat_title', 'str');
        $rows   = $inCore->request('xlsrows', 'int');
        $sheet   = $inCore->request('xlslist', 'int', 1);
        $cells  = $_REQUEST['cells'];
        $charset = $inCore->request('charset', 'str', 'cp1251');
        //get items config
        $published      = $inCore->request('published', 'int', 0);
        $imgfile        = '';
        $is_comments    = $inCore->request('is_comments', 'int', 0);
        $tags           = $inCore->request('tags', 'str', '');
        $meta_desc      = '';
        $meta_keys      = $tags;
        $canmany        = $inCore->request('canmany', 'int', 0);
        $price          = 0;
		 $price2          = 0;
		  $kolvo          = 0;
		  
		  


        //upload image
        if (isset($_FILES["imgfile"]["name"]) && @$_FILES["imgfile"]["name"]!=''){
            require($_SERVER['DOCUMENT_ROOT'].'/includes/graphic.inc.php');
			//generate image file
			$tmp_name = $_FILES["imgfile"]["tmp_name"];
			$imgfile = $_FILES["imgfile"]["name"];
			$path_parts = pathinfo($imgfile);
			$ext = $path_parts['extension'];
			$imgfile = md5($imgfile.time()).'.'.$ext;
			//upload image and insert record in db
			if (@move_uploaded_file($tmp_name, $_SERVER['DOCUMENT_ROOT']."/images/torg/$imgfile")){
				@img_resize($_SERVER['DOCUMENT_ROOT']."/images/torg/$imgfile", $_SERVER['DOCUMENT_ROOT']."/images/torg/small/$imgfile.jpg", 100, 100);
				@img_resize($_SERVER['DOCUMENT_ROOT']."/images/torg/$imgfile", $_SERVER['DOCUMENT_ROOT']."/images/torg/medium/$imgfile.jpg", 250, 250);
			} else { $msg .= 'Ошибка загрузки изображения!'; }
		} else { $imgfile = ''; }

        //process import
		if (isset($_FILES["xlsfile"]["name"]) && @$_FILES["xlsfile"]["name"]!=''){
			//upload xls file
			$tmp_name = $_FILES["xlsfile"]["tmp_name"];
			$file = $_FILES["xlsfile"]["name"];
			$file = $_SERVER['DOCUMENT_ROOT']."/upload/". md5($file . time()). '.xls';
			if (@move_uploaded_file($tmp_name, $file)){
                $inCore->includeFile('includes/excel/excel_reader2.php');
                $data = new Spreadsheet_Excel_Reader($file, true, $charset);
                //read rows in xls
                for($r=0; $r<$rows; $r++){
                    $fields = array();
                    $title = '';
                    $price = '';
					    $price2 = '';
						    $kolvo = '';

                    //get each cell in row by user coordinates
                    foreach($cells as $cell_id=>$pos){                        
                        if (isset($pos['ignore'])){
                            $celldata = $pos['other'];
                        } else {
                            $celldata = $data->val($r+$pos['row'],$pos['col'],$sheet-1);
                        }

                        if ($cell_id === 'title'){
                            $title = $celldata;
                        } elseif ($cell_id === 'price'){
                            $price = $celldata;
                        } elseif ($cell_id === 'price2'){
                            $price2 = $celldata;
                        } elseif ($cell_id === 'art'){
                            $art = $celldata;
                        }elseif ($cell_id === 'kolvo'){
                            $kolvo = $celldata;
                        }else {
                            $fields[] = $celldata;
                        }
                    }                    

                    $fields = serialize($fields);

if ($title && $fields){


$title=htmlspecialchars($title);

$sql = "INSERT INTO cms_uc_items (category_id, cat_title, art, title, pubdate, published, imageurl, is_comments, tags, rating, meta_desc, meta_keys, price,price2, canmany,user_id,kolvo)
VALUES ($cat_id, '$cat_title',  '$art', '$title', NOW(), '$published', '$imgfile', $is_comments, '$tags', 0, '$meta_desc', '$meta_keys', '$price', '$price2', $canmany, '$id', '$kolvo')";
            
$inDB->query($sql) or die('Ошибка импорта. Проверьте правильность настроек. <a href="javascript:window.history.go(-2)">Назад</a>');           

					
                        if ($tags){
                            $lastid = dbLastId('cms_uc_items');
                            cmsInsertTags($tags, 'torg', $lastid);
                        }
                    }
                }

                if ($file) @unlink($file);

			} else { $msg .= 'Ошибка загрузки файла Excel!'; }
		} else { $file = ''; }

		header('location:/torg/u'.$id.'/tovari');
	}
//=================================================================================================//
//=================================================================================================//
elseif ($_REQUEST['op']=="import_xls") {

       // cpAddPathway('Импорт из MS Excel', $_SERVER['REQUEST_URI']);
        echo '<h3>Импорт из MS Excel</h3>';

        if ($inCore->inRequest('cat_id')){
            //load category fields structure
            $cat = dbGetFields('cms_uc_cats', 'id='.$_REQUEST['cat_id'], 'title, fieldsstruct, view_type');
            $fstruct = unserialize($cat['fieldsstruct']);

	
            ?>
	<style>
	.proptable {
	font-size: 12px;
	    overflow:hidden;
    border-radius:8px;
    -moz-border-radius:8px;
    clear:both;
	border: 1px dotted silver;
	margin-top: 3px;
	margin-bottom: 3px;
	padding:8px
	
}
.proptable strong{
	color:#0099CC;
    font-size:12px;
}

.proptable div{
    margin-bottom:6px;
}
.hinttext {
	color: #999999;
}

	</style>
					
            <form action="/torg/u<?  echo $_REQUEST['id'];  ?>/tovari/goimport.html" method="POST" enctype="multipart/form-data" name="addform">
            <div class="o" style="background:#fafafa;float:left;padding:8px"><strong>Рубрика:</strong> <a href="/torg/u<?  echo $_REQUEST['id'];  ?>/tovari/import.html"><?php echo $cat['title']; ?></a></div>
			
            <div style="padding:10px;"><br/><br/>Выберите файл Excel, в котором находится таблица с характеристиками записей</div>
            <div class="proptable"><table width="650" border="0" cellspacing="5">
                <tr>
                    <td width="300">
                        <strong>Файл таблицы Excel:</strong><br/>
                        <span class="hinttext">В формате *.XLS</span>
                    </td>
                    <td><input type="file" name="xlsfile" /></td>
                </tr>
                <tr>
                    <td width="300">
                        <strong>Кодировка файла:</strong><br/>
                        <span class="hinttext">Зависит от пакета, в котором создавалась таблица</span>
                    </td>
                    <td>
                        <select name="charset" style="width:300px">
                            <option value="cp1251" selected>windows-1251 (MS Office)</option>
                            <option value="UTF-8">utf-8 (OpenOffice)</option>
                        </select>
                    </td>
                </tr>
                      <tr>
                    <td>
                        <strong>Количество записей (строк) для импорта:</strong><br/>
                        <span class="hinttext">Большие файлы рекомендуется импортировать по частям. <span style="color:red">Не оставляйте это поле пустым!</span></span>
                    </td>
                    <td><input type="text" name="xlsrows" style="width:40px" onkeyup="lookup(this.value);" onblur="if(this.value=='') this.value='10'" onfocus="if(this.value=='10') this.value='' " /> шт.</td>
                </tr>
                <tr>
                    <td><strong>Номер листа с таблицей в файле:</strong></td>
                    <td><input type="text" name="xlslist" style="width:40px" value="1" /></td>
                </tr>
            </table></div>
            <div style="padding:10px">
                Укажите числовые координаты первых ячеек с данными для каждого столбца.<br/>
                Если какую-либо характеристику нужно брать не из таблицы Excel, а сделать одинаковой для всех записей,<br/>
                то отметьте для нее галочку "Текст" и введите значение вручную.
            </div>
          <div class="proptable">  <table width="650" border="0" cellspacing="5">
		  <tr id="row_title">
                    <td width=""><strong>Артикуль\Номер:</strong></td>
                    <td>Столбец:</td>
                    <td><input type="text" onkeyup="xlsEditCol()" id="art_col" name="cells[art][col]" style="width:40px" /></td>
                    <td>Строка:</td>
                    <td><input type="text" onkeyup="xlsEditRow()" id="art_row" name="cells[art][row]" style="width:40px" /></td>
                    <td width="90"><input type="checkbox" id="ignore_art" name="cells[art][ignore]" onclick="ignoreRow('art')" value="1"/> Текст:</td>
                    <td><input type="text" class="other" name="cells[art][other]" style="width:200px" disabled /></td>
                </tr>
                <tr id="row_title">
                    <td width=""><strong>Название:</strong></td>
                    <td>Столбец:</td>
                    <td><input type="text" onkeyup="xlsEditCol()" id="title_col" name="cells[title][col]" style="width:40px" /></td>
                    <td>Строка:</td>
                    <td><input type="text" onkeyup="xlsEditRow()" id="title_row" name="cells[title][row]" style="width:40px" /></td>
                    <td width="90"><input type="checkbox" id="ignore_title" name="cells[title][ignore]" onclick="ignoreRow('title')" value="1"/> Текст:</td>
                    <td><input type="text" class="other" name="cells[title][other]" style="width:200px" disabled /></td>
                </tr>
				
			             <tr id="row_kolvo">
                    <td width=""><strong>Кол-во:</strong></td>
                    <td>Столбец:</td>
                    <td><input type="text" onkeyup="xlsEditCol()" id="kolvo_col" name="cells[kolvo][col]" style="width:40px" /></td>
                    <td>Строка:</td>
                    <td><input type="text" onkeyup="xlsEditRow()" id="kolvo_row" name="cells[kolvo][row]" style="width:40px" /></td>
                    <td width="90"><input type="checkbox" id="ignore_kolvo" name="cells[kolvo][ignore]" onclick="ignoreRow('kolvo')" value="1"/> Текст:</td>
                    <td><input type="text" class="other" name="cells[kolvo][other]" style="width:200px" disabled /></td>
                </tr>
         <tr id="row_price2">
                        <td width="250"><strong>Опт. Цена:</strong></td>
                        <td>Столбец:</td>
                        <td><input type="text" class="col" name="cells[price2][col]" style="width:40px" /></td>
                        <td>Строка:</td>
                        <td><input type="text" class="row" name="cells[price2][row]" style="width:40px" /></td>
                        <td><input type="checkbox" id="ignore_price2" name="cells[price2][ignore]" onclick="ignoreRow('price2')" value="1"/> Текст: </td>
                        <td><input type="text" class="other" name="cells[price2][other]" style="width:200px" disabled /></td>
                    </tr>		
                    <tr id="row_price">
                        <td width="250"><strong>Цена:</strong></td>
                        <td>Столбец:</td>
                        <td><input type="text" class="col" name="cells[price][col]" style="width:40px" /></td>
                        <td>Строка:</td>
                        <td><input type="text" class="row" name="cells[price][row]" style="width:40px" /></td>
                        <td><input type="checkbox" id="ignore_price" name="cells[price][ignore]" onclick="ignoreRow('price')" value="1"/> Текст: </td>
                        <td><input type="text" class="other" name="cells[price][other]" style="width:200px" disabled /></td>
                    </tr>
					
			
                  

            </table></div>

                   <div style="padding:10px">Задайте остальные параметры записей:</div>
        <div class="proptable">    <table width="650" border="0" cellspacing="5">
                <tr>
                    <td width="300">
                        <strong>Публиковать записи:</strong><br/>
                        <span class="hinttext">Если включено, записи сразу появятся на сайте</span>
                    </td>
                    <td>
                        <input name="published" type="radio" value="1" checked="checked" /> Да
                        <input name="published" type="radio" value="0" /> Нет
                    </td>
                </tr>
                <tr>
                    <td><strong>Разрешить комментарии:</strong></td>
                    <td>
                        <input name="is_comments" type="radio" value="1" checked="checked" /> Да
                        <input name="is_comments" type="radio" value="0" /> Нет
                    </td>
                </tr>
                <?php if ($cat['view_type']=='shop'){ ?>
                <tr>
                    <td>
                        <strong>Разрешить выбор количества:</strong><br/>
                        <span class="hinttext">При заказе товара</span>
                    </td>
                    <td>
                        <input name="canmany" type="radio" value="1" checked="checked" /> Да
                        <input name="canmany" type="radio" value="0" /> Нет
                    </td>
                </tr>
                <?php } ?>
                <tr>
                    <td>
                        <strong>Тэги записей:</strong><br/>
                        <span class="hinttext">Не обязательно</span>
                    </td>
                    <td>
                        <input type="text" name="tags" style="width:300px" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <strong>Изображение:</strong><br/>
                        <span class="hinttext">Не обязательно</span>
                    </td>
                    <td>
                        <input type="file" name="imgfile" />
                    </td>
                </tr>                
            </table></div>

            <p><br/>
                <input name="cat_id" type="hidden" id="cat_id" value="<?php echo (int)$_REQUEST['cat_id']; ?>" />
				    <input name="cat_title" type="hidden" id="cat_title" value="<?php echo $cat['title']; ?>" />
                 <input name="opt" type="hidden" id="opt" value="go_import_xls" />
                 <input name="save" type="submit" id="save" value="Импортировать" />
                 <input name="back" type="button" id="back" value="Отмена" onclick="window.history.go(-1);"/>
            </p>

            </form>
			
			
			
			
			
			<?php

        } else {


            echo '<h4>Выберите рубрику для импорта записей:</h4>';

            $sql = "SELECT id, title, NSLeft, NSLevel, parent_id
                    FROM cms_uc_cats
                    WHERE parent_id > 0
                    ORDER BY NSLeft";
       
			$result = $inDB->query($sql);

            if (mysql_num_rows($result)>0){
                echo '<div style="padding:10px">';
                    while ($cat = mysql_fetch_assoc($result)){
                        echo '<div style="padding:2px;padding-left:18px;margin-left:'.(($cat['NSLevel']-1)*15).'px;background:url(/admin/images/icons/hmenu/cats.png) no-repeat">
                                  <a href="/torg/u'.$id.'/tovari/import'.$cat['id'].'.html">'.$cat['title'].'</a>
                              </div>';
                    }
                echo '</div>';
            }




        }

    }


if ($_REQUEST['op']=="import_xls"){} else {




echo '<div class="o" style="border:1px solid #eee;padding:8px;">';
if (isset($_REQUEST['cat_id'])) $sql_cat_id="AND category_id='".$_REQUEST['cat_id']."'"; else $sql_cat_id=""; 
if ($_REQUEST['op']=="tovari-cart")  $arctype="1"; else $arctype="0";

		$sql = "SELECT *
				FROM cms_uc_items
				WHERE user_id = $id $sql_cat_id AND archive=$arctype AND prodano !=1
				ORDER BY pubdate DESC
				"; 
		
		$perpage = 20;
		if (isset($_REQUEST['page'])) { $page = abs((int)$_REQUEST['page']); } else { $page = 1; }
		$sql .= "LIMIT ".($page-1)*$perpage.", $perpage";

		$result = $inDB->query($sql);

		if ($inDB->num_rows($result)){		







// рубрикатор	

if (isset($_REQUEST['cat_id'])) $vid_cat_id='/c'.$_REQUEST['cat_id'].'.html'; else $vid_cat_id=""; 

$sq_cat = "SELECT category_id, cat_title FROM cms_uc_items
				WHERE user_id = $id
				GROUP BY category_id
				";
															
$result_cat = $inDB->query($sq_cat);


if ($inDB->num_rows($result_cat)){	

 
echo '<div class="o" style="padding:10px 5px 10px 5px; background:#fafafa;margin:0 0 8px 0;text-align:left">';
while($item_cat = $inDB->fetch_assoc($result_cat)) {
	
if ($_REQUEST['cat_id']==$item_cat['category_id']) $this_cat='style="text-decoration:none;color:#000"'; else $this_cat=""; 
$item_cat['torg_count'] = $inDB->rows_count('cms_uc_items', "user_id={$usr['id']} AND category_id={$item_cat['category_id']}");
 
echo '<div class="cat_links2" style="float:left;border:0;"><a href="/torg/u'.$id.'/tovari/'.$vid_cat.'c'.$item_cat['category_id'].'.html" '.$this_cat.'><b>'.$item_cat['cat_title'].'</b> <sup style="font-size:11px;color:#5485b7">'.$item_cat['torg_count'].'</sup></a></div>'; 

}
if ($_REQUEST['cat_id']) echo '<div style="padding:8px 5px 7px 10px;float:left"><a href="/torg/u'.$id.'/tovari">Все категории</a></div>';
echo '</div>';
} // рубрикатор	



echo '<form method="post" action="" target="_self" name="tovari_form" onsubmit="return check_fields_tovari();">';
//echo '<form name="selform" action="/torg/u'.$id.'/tovari-saveprice.html" method="post">';
echo '<table  cellpadding="2" cellspacing="0" border="0" width="100%">';
echo '<tr style="font-weight:bold;">';
echo '<td valign="middle" width="330px"></td>';
echo '<td valign="middle" style="border:1px dashed #226dd2;border-width:1px 1px 0 1px;">';
echo '<div style="text-align:center"><a style="display:block;padding-top:10px;text-decoration:none" href=javascript:sendForm("/torg/u'.$id.'/tovari-saveprice.html");>Сохранить внесённые изменения</a></div>';
echo '</td>';
echo '<td valign="middle" width="90px"></td>';
echo '</tr>';
echo '</table>';

echo '<table width="100%"  cellpadding="2" cellspacing="0" border="0">';
echo '<tr style="font-weight:bold;font-size:11px">';
echo '<td valign="middle" width="60px" style="font:normal 9px Verdana">'.$_LANG['DATE'].'</td>';
if (!isset($_REQUEST['cat_id'])) echo '<td width=100px>Категория</td>';
echo '<td valign="middle" width="80px" style="font:normal 9px Verdana">Действия</td>';
echo '<td width="10px"><input type="checkbox" onclick="checkall(this)" /></td>';
echo '<td width="50px">Номер</td>';
echo '<td width=30px></td>';
echo '<td>'.$_LANG['tovar'].'</td>';
echo '<td valign="middle" width="70px">Опт. '.$_LANG['PRICE'].'</td>';
echo '<td valign="middle" width="70px">';
echo ''.$_LANG['PRICE'].'</td>';
echo '<td valign="middle" width="30px">Кол-во</td>';
echo '<td valign="middle" width="15px" style="font:normal 9px Verdana">Сделок</td>';
echo '<td valign="middle" width="15px" style="font:normal 9px Verdana">Заказов</td>';
echo '</tr>';

$count = 1;
while($item = $inDB->fetch_assoc($result)){	
$itemid=$item['id'];


 $TrColor = ($count % 2 == 0) ? "" : "background:#f8f8f8";
 
//if ($item['prodano']==2) {$prodano="<td><b style='font-size:11px;color:#000'>В резерве</b></td>"; $prodano_style="style='color:#888'";}  else {$prodano="";$prodano_style="";}
//$item['pubdate']  = cmsCore::dateformat($item['pubdate']);

echo '<tr style="'.$TrColor.'">';
echo '<td valign="middle" width=60px '.$prodano_style.'>';	
echo '<div style="font:normal 8px Verdana">'.$item['pubdate'].'</div>';
echo '</td>';
if (!isset($_REQUEST['cat_id'])) echo '<td width=100px><a style="font-size:11px;text-decoration:none;" href="/torg/u'.$id.'/tovari/c'.$item['category_id'].'.html">'.$item['cat_title'].'</a></td>';

echo '<td valign="middle" width="80px">
<a href="/torg/u'.$id.'/tovari-del'.$item['id'].'.html" title="Удалить товар"><img src="/templates/_default_/images/icons/delete.png"></a>&nbsp;
<a href="/torg/'.$item['category_id'].'/edit'.$item['id'].'.html" title="Полное редактирование товара"><img src="/templates/_default_/images/icons/edit.png"></a>';


if ($item['prodano']==2) echo '&nbsp;<a href="/torg/u'.$id.'/tovari-norezerv'.$item['id'].'.html" title="Снять товар с резерва"><img src="/templates/_default_/images/icons/actions/no_friend.png"></a>';
else echo '&nbsp;<a href="/torg/u'.$id.'/tovari-torezerv'.$item['id'].'.html" title="Зарезирвировать товар"><img src="/templates/_default_/images/icons/actions/add_friend.png"></a>';


echo '</td>';
echo '<td width="10px"><input type="checkbox" value="'.$item['id'].'" name="board_check[]" /></td>';
echo '<td width="50px" style="font:normal 9px Verdana">'.$item['art'].'</td>';
echo '<td width=30px>';
echo '<a style="text-decoration:none;display:block;float:left;width:15px" class="itemlink"><img align=absmiddle src="/templates/_default_/images/icons/w/photography.png"></a><div class="imghint"><img src="/images/torg/small/'.$item['imageurl'].'.jpg" /></div>';	
echo '<a style="text-decoration:none;display:block;float:left;width:15px" title="На страницу товара" href="/torg/item'.$item['id'].'.html"><img align=absmiddle src="/templates/_default_/images/icons/eye.png"></a>';							
echo '</td>';
echo '<td valign="middle" '.$prodano_style.'>';		
echo cpTitleInput($itemid);	
echo '</td>';
echo '<td valign="middle" width="70px" '.$prodano_style.'>';
echo cpPrice2Input($itemid);	
echo '</td>';
echo '<td valign="middle" width="70px" '.$prodano_style.'>';
echo cpPriceInput($itemid);	
echo '</td>';
echo '<td valign="middle" width="30px" align=center>';
echo cpKolvoInput($itemid);	
echo '</td>';
$sdelki = $inDB->rows_count('cms_user_zakazi', "to_id=$id AND item_id={$item['id']} AND provesti=1");
if ($sdelki == 0) $sdelki="";
echo '<td valign="middle" width="15px" align=center style="font:normal 9px Verdana">'.$sdelki.'</td>';
$zakazi = $inDB->rows_count('cms_user_zakazi', "to_id=$id AND item_id={$item['id']}");
if ($zakazi == 0) $zakazi="";
echo '<td valign="middle" width="15px" align=center style="font:normal 9px Verdana">'.$zakazi.'</td>';
//echo $prodano;
echo '</tr>';
	 $count ++;
				}
			
echo '<tr style="font-weight:bold;font-size:11px">';
echo '<td valign="middle" width="60px" style="font:normal 9px Verdana">'.$_LANG['DATE'].'</td>';
if (!isset($_REQUEST['cat_id'])) echo '<td width=100px>Категория</td>';
echo '<td valign="middle" width="80px" style="font:normal 9px Verdana">Действия</td>';
echo '<td width="10px"><input type="checkbox" onclick="checkall(this)" /></td>';
echo '<td width="50px">Номер</td>';
echo '<td width=30px></td>';
echo '<td>'.$_LANG['tovar'].'</td>';
echo '<td valign="middle" width="70px">Опт. '.$_LANG['PRICE'].'</td>';
echo '<td valign="middle" width="70px">'.$_LANG['PRICE'].'</td>';
echo '<td valign="middle" width="30px">Кол-во</td>';
echo '<td valign="middle" width="15px" style="font:normal 9px Verdana">Сделок</td>';
echo '<td valign="middle" width="15px" style="font:normal 9px Verdana">Заказов</td>';
echo '</tr>';

echo '</table>';

echo '<table  cellpadding="2" cellspacing="0" border="0" width="100%">';
echo '<tr style="font-weight:bold;">';
echo '<td valign="middle" width="330px"></td>';
echo '<td valign="middle" style="border:1px dashed #226dd2;border-width:0 1px 1px 1px;">';
echo '<div style="text-align:center"><a style="display:block;padding-bottom:10px;text-decoration:none" href=javascript:sendForm("/torg/u'.$id.'/tovari-saveprice.html");>Сохранить внесённые изменения</a></div>';
echo '</td>';
echo '<td valign="middle" width="90px"></td>';
echo '</tr>';
echo '</table>';

echo '<div class="o" style="padding:5px 0 5px 0;margin-top:15px;background:#fafafa">';
echo '<table  cellpadding="5" cellspacing="0" border="0"><tr>';
echo '<td valign=middle width="202px" align=center><b>Что делать c<br/>отмеченными?</b></td>'; 
echo '<td valign=top><input type="submit" onclick=this.form.action="/torg/u'.$id.'/tovari_torezerv"; this.form.target="_blank"; value="Зарезирвировать" />
<br/><input style="margin-top:5px" type="submit" onclick=this.form.action="/torg/u'.$id.'/tovari_norezerv"; this.form.target="_blank"; value="Снять с резерва" />
</td>'; 
echo '<td valign=top>'; 
if ($_REQUEST['op']=="tovari-cart") {
echo '<input type="submit" onclick=this.form.action="/torg/u'.$id.'/tovari_to"; this.form.target="_blank"; value="Вернуть из корзины" /> <span style="color:#555">- (вернуть к общиму списку товаров)</span>';
} else echo '<input type="submit" onclick=this.form.action="/torg/u'.$id.'/tovari_tocart"; this.form.target="_blank"; value="В корзину" /> <span style="color:#555">- (поместить во временное хранилище)</span>';
echo '</td><td>';
echo '<input style="margin-top:5px" type="submit" onclick=this.form.action="/torg/u'.$id.'/tovari-del"; this.form.target="_blank"; value="Удалить" />';
echo '</td>'; 

echo '</tr></table>';
echo '</div></form>';



				echo pageBartorg($id, $page, $perpage);	
		} else { 
				 echo '<div class="o" style="border:1px solid #eaf1f6;padding:20px">'.$_LANG['notovars'].'</div>';
				}		

}




	echo '</div>';
	



				
?>