var 
	CAT_TYPE_ITEM=0,
	CAT_TYPE_DIR=1;
$(function(){
	if (!isAdmin()){
		var sw=$('<ul class="catlist-switcher cleared"><li><div><span>подробно</span></div></li><li class="active"><div><span>кратко</span></div></li></ul>')
			.insertBefore('ul.catlist')
			.click(function(e){
				var el=$(e.target);
				if (!el.is('span')){
					return;
					}
				el
					.parent().parent().siblings().removeClass('active')
					.end().addClass('active')
					.parent().next('.catlist').eq(0).toggleClass('catlist-short',el.text()=='кратко');
				$.cookie('catview',el.text()=='подробно'?'full':'',{expires:60,path:'/'});
				return false;
				});
		$.cookie('catview')=='full' && sw.find('span:contains("подробно")').click();
		
		/* Order form */
		$("#orderform").validate({
			rules:{
				email:{
					callback:function(val,field){
						var phone=$('#orderform-phone').val();
						if (FormValidator.rules.phone.mask.test(phone)){
							field.__skipValidation=true;
							return true;
							}
						else{
							return FormValidator.rules.mail.mask.test(val);
							}
						}				
					}
				},
			onsubmit:function(data){
				var 
					$this=this,
					item=window['ITEM']||{};
				$.request({
					type:'POST',
					url:item.fullUri,
					data:$.extend({},data,{
						action:'order'
						}),
					success:function(res){
						$('#orderform-core').html(''
							+'<h3 id="orderform-title">Вопрос принят</h3>'
							+'<div id="orderform-result" class="success>'
								+'<p>Мы свяжемся с&nbsp;вами в&nbsp;ближайшее время</p>'
							+'</div>'
							);
						},
					error:function(){
						container.html(''
							+'<h3 id="orderform-title">Произошла ошибка</h3>'
							+'<div id="orderform-result" class="success>'
								+'<p>В&nbsp;процессе отправки заявки произошла техническая ошибка. Пожалуйста, повторите попытку позже.</p>'
							+'</div>'
							);
						}
					});
				
				
				
				return false;
				}
			});
		
		}
	
	$('.pic-preview').click(function(){
		var 
			a=$(this),
			li=a.closest('li'),
			container=$('#pic-view'),
			picId=searchInClass($(this).find('img'),'picid-'),
			src=catPicSrc(picId,3);
			
			
		if (!container.length){
			container=
				$('<div id="pic-view"></div>')
				.appendTo(document.body)
				.click(function(e){
					var target=$(e.target);
					if (target.is('.step')){
						var pli;
						if (target.hasClass('step-prev')){
							pli=li.prev('li:not(.more)');
							if (!pli.length){
								pli=li.siblings('li:not(.more):last')
								}
							}
						else{
							pli=li.next('li:not(.more)');
							if (!pli.length){
								pli=li.siblings('li:not(.more):first')
								}
							}
						if (pli.length){
							li=pli;
							a=li.find('.pic-preview').click();
							}
						return false;
						}
					container.hide();
					unblockScreen();
					return false;
					})
				.css({
					position:'absolute',
					zIndex:10001,
					cursor:'pointer',
					textAlign:'center'
					});			
			}
		blockScreen(function(){
			unblockScreen();
			container.hide();
			});
		container.empty().show();
		var caption=$('strong',$(this).parent()).html();
		$.status.progress('Загрузка изображения');
		
		getImgSize(src,function(img){
			$.status().hide();
			container.html(''
				+img.html
				+(caption?'<strong style="width:'+(img.width+(BROWSER.isIE6?20:0))+'px">'+caption+'</strong>':'')
				+'<span class="step step-prev" title="Перейти к предыдущей картинке"></span><span class="step step-next" title="Перейти к следующей картинке"></span>'
				);			
			putInScreenCenter(container[0],true);
//			var offset=container.offset();
//			container.find('.prev').top=container.height()
			
			});
		return false;
		});
	
	(function(){
		var 
			gal=$('#main-gallery'),
			galCore=$('#main-gallery-list',gal),
			moreLink=$('#main-gallery-more');
		if (!gal.size()){
			return;
			}
		var actualize=function(){
			moreLink.toggle(gal.hasClass('gallery-collapsed') && (galCore.height()-gal.height()>50));
			};
		$(window).resize(function(){
			actualize();
			})
		.load(function(){
			actualize();
			});		
		})();
	
		
	$('#main-gallery .more a').click(function(){
		var gal=$(this).closest('.gallery');
		if (gal.hasClass('gallery-collapsed')){
			gal.removeClass('gallery-light').removeClass('gallery-collapsed').find('.adv').fadeIn();
			}		
		$(this).parent().hide();
		return false;
		});
	$('#catitem-orderlink a').click(function(){
		var item=window['ITEM']||{};
		var fields=_prop(window,'ORDER_FORM.fields')||{};	
		
		var container=$('<div/>')
			.appendTo(document.body)
			.attr('id','order-form')
			.addClass('ipopup')
			.html(''
				+'<span class="action-cancel close-bullet"></span>'
				+'<div class="ipopup-header">'
					+'<h2>Заказ оборудования</h2>'
					+'<p>Пожалуйста, заполните предлагаемую форму, после чего наш сотрудник свяжется с вами в кратчайшие сроки.</p>'
				+'</div>'
				+'<div class="ipopup-body">'
					+'<div class="order-caption">'
						+(item.mainpic_id?'<img src="'+catPicSrc(item.mainpic_id,2)+'" alt="" class="preview" />':'')
						+'<h3>'
							+'<strong>'+item.caption+'</strong>'
							+item.producer.caption+(item.producer.country_caption?', <em>'+item.producer.country_caption+(item.producer.country_use_pic?'<img src="'+PATH_COUNTRIES+item.producer.country_id+'.gif" alt="" />':'')+'</em>':'')
						+'</h3>'
					+'</div>'
					+'<form method="post" action="">'
						+'<dl>'
							+'<dd>'
								+'<label for="order-count">'+fields.count+':</label>'
								+'<input type="text" name="count" id="order-count" class="field-quantity input-text input-text-small" maxlength="3" value="1" />'
							+'</dd>'
							+'<dd>'
								+'<label for="order-delivery-period">'+fields['delivery-period']+':</label>'
								+'<select type="text" name="delivery-period" id="order-delivery-period" class="select-small">'
									+'<option value="после оплаты">после оплаты</option>'
									+'<option value="3 месяца">3 месяца</option>'
									+'<option value="6 месяцев">6 месяцев</option>'
									+'<option value="12 месяцев">12 месяцев</option>'								
								+'</select>'
							+'</dd>'
							+'<dd>'
								+'<label for="order-givenname">'+fields.givenname+':</label>'
								+'<input type="text" name="givenname" id="order-givenname" class="field-givenname input-text" />'
							+'</dd>'
							+'<dd>'
								+'<label for="order-company">'+fields.company+':</label>'
								+'<input type="text" name="company" id="order-company" class="input-text" />'
							+'</dd>'
							+'<dd>'
								+'<label for="order-email">'+fields.email+':</label>'
								+'<input type="text" name="email" id="order-email" class="field-mail input-text" />'
							+'</dd>'
							+'<dd>'
								+'<label for="order-phone">'+fields.phone+':</label>'
								+'<input type="text" name="phone" id="order-phone" class="field-phone input-text" />'
							+'</dd>'
							+'<dd>'
								+'<label for="order-comment">'+fields.comment+':</label>'
								+'<textarea type="text" name="comment" id="order-comment" cols="40" rows="7"></textarea>'
							+'</dd>'
							+'<dd class="submit">'
								+'<button type="submit">Отправить</button>'
								+'<a href="javascript:;" class="action-cancel">Закрыть</a>'
							+'</dd>'
						+'</dl>'
					+'</form>'
				+'</div>'
				);
		var close=function(){
			unblockScreen();
			container.remove();
			}
		var init=function(){
			container.find('.action-cancel').css('cursor','pointer').click(close);
			putInScreenCenter(container);
			blockScreen();			
			container.find('input').eq(0).focus();
			}
		container.find('form').validate({
			onsubmit:function(res){
				$.request({
					type:'POST',
					quite:true,
					url:item.fullUri,
					data:$.extend({},res,{
						action:'order'
						}),
					success:function(res){
						container.html(''
							+'<span class="action-cancel close-bullet"></span>'
							+'<div class="ipopup-header">'
								+'<h2>Заявка принята</h2>'
								+'<p>Мы свяжемся с вами в ближайшее время</p>'
							+'</div>'					
							+'<div class="ipopup-body">' 
								+'<div class="distant">'
									+'<button class="action-cancel">Закрыть</button>'
								+'</div>'
							+'</div>');
						init();
						},
					error:function(){
						container.html(''
							+'<span class="action-cancel close-bullet"></span>'
							+'<div class="ipopup-header">'
								+'<h2>Произошла ошибка</h2>'
								+'<p>В процессе отправки заявки произошла техническая ошибка. Пожалуйста, повторите попытку позже.</p>'
							+'</div>'					
							+'<div class="ipopup-body">' 
								+'<div class="distant">'
									+'<button class="action-cancel">Закрыть</button>'
								+'</div>'
							+'</div>'
							);
						init();
						}
					});
				
				return false;
				}
			})
		init();		
		return false;
		});
	});

var 
	PATH_CAT_DATA=PATH_DATA+'cat/',
	PATH_CAT_PIX=PATH_CAT_DATA;
function catPicSrc(p,size,ext,noRnd){
	var picId,picType='jpg';
	if (is_object(p)){
		picId=p.id;
		picType=p.type;
		}
	else{
		picId=String(p);
		}
	if (size==3 && picType && !ext){
		ext=picType;
		}
	var 
		d1=picId.substr(0,1);
		d2=picId.length>=2?picId.substr(1,1):'0';
	return PATH_CAT_DATA+d1+'/'+d2+'/'+picId+'_'+(size||2)+'.'+(ext||'jpg')+(noRnd?'':'?rnd='+Math.round(Math.random()*1000));
	}
	