function initMenu()
{
 //инициализируем внешний вид каталога
 var catHolder = document.getElementById('catalog_holder');
 if(catHolder)
 {
	var lists = catHolder.getElementsByTagName('UL');
	//сворачиваем все списки кроме первого
	lists[0].className="";
	//for(i = 1; i<lists.length;i++)
	//{
		//сворачиваем все списки кроме первого
		//lists[i].className="invisible";
	//}
	//var items = catHolder.getElementsByTagName('LI');
	//for(j = 0;j<items.length;j++)
	//{
		//if(items[j].className!="clicked")
			//items[j].className="unclicked";
		
		//вешаем функцию обработчик клика на каждый LI
		
	//}

	//alert(lists.length);
 }
}
//меняем статус для пункта меню
function setStatus(item_number)
{
	var item  =document.getElementById('menu_item_'+item_number);
	//alert(item.id+' '+item.className);
	//устанавливаем статус в сессии
	 var myAjax = new Ajax.Request('/ajax/setstatus', 
                                   {method: 'post', parameters: {iditem: item_number,status: item.className} ,asynchronous:false}
                                   );
	
}

function clickMenu(sender)
{
		var parent = sender.parentNode;
		if(parent.className=="clicked")
		{
			parent.className="unclicked";
		}
		else
		{
			parent.className="clicked";
		}
}

function ajaxProducts(id) 
{
	
	
	
	//создаем аякс запрос
    var myAjax = new Ajax.Request('/ajax/getproducts', 
                                   {method: 'post', parameters: {idcategory: id}, 
                                   onComplete: handleResponse});
	$('loading').className="";
}
//отобразить полное описание одного продукта
function ajaxFull(id,id_sender) 
{
	
	//создаем аякс запрос

    var myAjax = new Ajax.Request('/ajax/getproduct', 
                                   {method: 'post', parameters: {idproduct: id}, 
                                   onComplete: handleResponse});
	$('loading').className="";
}
//добавить продукт в корзину
function addToCart(id,name,price) 
{
	
	//window.pathname="bebebee";
	//alert('call');
	//создаем аякс запрос
   // var myAjax = new Ajax.Request('/ajax/addtocart', 
    //                               {method: 'post', parameters: {idproduct: id, nameproduct: name, priceproduct: price}, 
     //                              onComplete: handleCart});
								   
	$.post("/ajax/addtocart",  { idproduct: id, nameproduct: name, priceproduct: price},
					function handleCart(transport)
{
 //принимаем асинхронный ответ 

	//var json = transport.responseText.evalJSON();
	
	var id = transport.id;
	var total = transport.total;
	var quantity=transport.quantity;
	var buyAnchor = document.getElementById('buy_anchor_'+id);
	if(buyAnchor)
	{
		buyAnchor.innerHTML=""; 
	}
	
	var removeAnchor = document.getElementById('remove_'+id);
	if(removeAnchor)
	{
		removeAnchor.innerHTML="<a style='color:blue;text-decoration:none;' href='JavaScript:removeFromCart("+id+");'><center><img style='border:none;' src='/design/img/del.gif'/></center><br/>Убрать из корзины</a>";
	}
	//меняем визуальное представление корзины
	var quantLabel = document.getElementById('cart_quantity');
	if(quantLabel)
	{
	   quantLabel.innerHTML=quantity;
	}
	var totalLabel = document.getElementById('cart_total');
	if(totalLabel)
	{
	   totalLabel.innerHTML=total+' грн';
	}
	
}, "json");

	var buyAnchor = document.getElementById('buy_anchor_'+id);
	if(buyAnchor)
	{
		buyAnchor.innerHTML="<img src='/design/img/round.gif' alt='Загрузка' width='40' height='40'/>";
	 
	}
	
}
//функция удаления продукта из корзины
function removeFromCart(id)
{
  //var myAjax = new Ajax.Request('/ajax/removefromcart', 
   //                                {method: 'post', parameters: {idproduct: id}, 
    //                               onComplete: handleCartRemove});
	$.post("/ajax/removefromcart",  { idproduct: id},
					function handleCartRemove(transport)
{
 //принимаем асинхронный ответ 
	
	
	
	
	var name=transport.name;
	var price =transport.price;
	var id = transport.id;
	var total = transport.total;
	var quantity=transport.quantity;
  
	var buyAnchor = document.getElementById('buy_anchor_'+id);
	if(buyAnchor)
	{
		buyAnchor.innerHTML="<a style='color:blue;text-decoration:none;' href='JavaScript:addToCart("+id+",\""+name+"\","+price+");'><center><img style='border:none;' src='/design/img/cart.jpg'/><br/></center>Добавить в корзину</a>";
	}
	
	var removeAnchor = document.getElementById('remove_'+id);
	if(removeAnchor)
	{
		removeAnchor.innerHTML="";
	}
	//меняем визуальное представление корзины
	var quantLabel = document.getElementById('cart_quantity');
	if(quantLabel)
	{
	   quantLabel.innerHTML=quantity;
	}
	var totalLabel = document.getElementById('cart_total');
	if(totalLabel)
	{
	   totalLabel.innerHTML=total+' грн';
	}
	
}, "json");
	
	
	
	var removeAnchor = document.getElementById('remove_'+id);
	if(removeAnchor)
	{
		removeAnchor.innerHTML="<img src='/design/img/round.gif' alt='Загрузка' width='40' height='40' style='margin-top:-10px;'/>";
	 
	}
	
}

//функция отрисовывает корзину 
function showCart(id,in_cart,name,price)
{
	//id - идентификатор товара
	//in_cart - товар в корзине, {"false","true"}
	var output="";
	if(in_cart=="true")
	{
		//товар уже в корзине
		  output+="<tr align='center' valign='bottom'><td width='50%' height='100'><div id='buy_anchor_"+id+"'><a  href='/cart'><img src='/design/img/knopka2.gif' alt='Корзина' width='40' height='40'>";
		  output+="<br/>Корзина</a></div></td><td><div id ='remove_"+id+"'><a href='JavaScript:removeFromCart("+id+");'>";
		  output+="<img src='/design/img/knopka3.gif' alt='Убрать из корзины' width='40' height='40'><br/>Убрать</a></div></td></tr>"
	}
	else
	{
		//товар еще не ы корзине
		output+="<tr align='center' valign='bottom'><td height='100' width='50%'><div id='buy_anchor_"+id;
		output+="'><a href='JavaScript:addToCart("+id+",\""+name+"\","+price+");'>";
		output+="<img height='40' width='40' alt='Купить' src='/design/img/knopka.gif'/><br/>Купить</a></div></td><td><div id='remove_"+id+"'/></td></tr>";
	}
	
	return output;
		
}
//функция выводит галлерею фоток в товаре
function ShowGallery(num_photo,product)
{
	var output="";
	if(num_photo>0)
	{
			output+="<div class='descr_gall'>";
         for(j=0;j<num_photo;j++)
			{
				output+="<div class='gall_item'><a rel='lightbox' href='/design/img/product/"+product.id+"/pictures/";
				output+=product.photo[j]+"'><img width='100' height='100' src='/design/img/product/"+product.id+"/thumbs/"+product.photo[j]+"'></a></div>";
			}					  
         output+="</div>";
	}
	
	return output;
}

//формирует html для отображения товара. mode - полное или сокращенное отображение
function outputProduct(product,mode)
{
	//разобрали поля
	var id = product.id;
	var name= product.name;
	var link = product.link;
	var short_text = product.short_text;
	var long_text = product.long_text;
	var quantity = product.quantity;
	var unit = product.unit;
	var brand_code = product.brand_code;
	var price_whole = product.price_wholesale_uah;
	var price_retail = product.price_retail_uah;
	var in_cart = product.in_cart;
	var showcart = product.showcart;
	if(mode=="full")
	{
		var num_photo = product.num_photo;
	
	}
	//вывод главного блока
	var output = "<div class='descr_without_clear' ><div class='descr_small'><div class='descr_img'>";
	output+="<img width='100' src='"+link+"' alt=''></div><div class='descr_text'>";
	output+="<span class='nazv_text'>"+name+"</span><br/><br/><span class='bold_text'>Краткое описание:</span>"+short_text+"<br/>";
   output+="<span class='bold_text'>Единица измерения:</span>"+unit+"<br/>";
	output+="<span class='bold_text'>Наличие:</span>"+quantity+"<br/><span class='bold_text'>ID номер:</span>"+brand_code+"<br/>";
                                       
   if(mode!='full') 
		output+="<a href='JavaScript:ajaxFull("+id+")'>Подробнее...</a>";
   
	output+="</div>";
	
	//вывод корзины и цен

	output+="<div class='descr_buy'><span class='bold_text'><center>Цена</center></span><table width='90%'><tr bgcolor='#eaffd4' align='center'>";
	output+="<td width='80' style='border-right:3px solid #fff'>розн</td><td width='80'>опт</td></tr><tr align='center'><td width='50%'>"
	output+=price_retail+"</td><td>"+price_whole+"</td></tr>";
	
	if(showcart=="true")
	{
		//вывод корзины
		output+=showCart(id,in_cart,name,price_retail);
	}
	output+="</table></div>";
	
	output+="<div style='clear:both'>&nbsp;</div>";
	
	if(mode=="full")
	{
		//отображение полной информации
		output+="<div class='descr_full'><div style='border-bottom:1px solid #eee;'><span class='bold_text'>Полное описание:</span><br/></div>";
		output+=long_text+"<br/></div>";
		//отображение галереи
		output+=ShowGallery(num_photo,product);			
	}
                             
	output+="</div></div>";
	return output;
}
function handleResponse(transport)
{
 //принимаем асинхронный ответ 

	var json = transport.responseText.evalJSON();
	
	var output ="";
	if(json.error)
	{
		//были ошибки
		output=json.error;
	}
	else
	{
		for(i=0;i<json.length;i++)
		{
			//выводим товары
			var product = json[i];
			//разбираем объект
			var htmlproduct = outputProduct(product,product.mode);
			output+=htmlproduct;
		}
	}
   $('dynamic_content').innerHTML =output;// transport.responseText;
	$('loading').className="invisible";
	
	//подключаем лайтбокс
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	if(anchors)
	{
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];

		if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox")){
			anchor.onclick = function () {showLightbox(this); return false;}
		}
	}
	}

}
//ответ сервера про добавление продукта
