var date_unix = new Date().getTime();

jQuery(function() {
        var boxen = [];
        //find all links w/ rel="lightbox[gallery_name]" or just rel="lightbox" it works both ways
        jQuery('a.lightbox').each(function() {
        //push only unique lightbox[gallery_name] into boxen array
        if (jQuery.inArray(jQuery(this).attr('rel'),boxen)) boxen.push(jQuery(this).attr('rel'));
    });
    //for each unique lightbox group, apply the lightBox
    jQuery(boxen).each(function(i,val) {jQuery('a[rel='+val+']').lightBox();});
    });

jQuery(document).ready(function($) 
{       
    if($('h1').height() > 40) $('h1').css('background','none');
	
	$('h2').each(function(){
		if($(this).height() > 40) $(this).css('background-position','0 -900px');
		else $(this).css('background-position','0 9px');
	});
	
	$('.show_more').click(function(){
		$('.more_info').show();
		$(this).hide();
	});
	
	$('.blight_td input,.blight_td textarea,.tmp_td input,.tmp_td textarea').live('keyup', function(){
		if($(this).val()) $(this).parents('.blight_td').attr('class','tmp_td');
		else $(this).parents('.tmp_td').attr('class','blight_td');
	});
	
	$('.page_link').hover(function(){
		if($(this).width()>20) $(this).css('margin','0 -4px');
	}, function(){
		$(this).attr('style','');
	});

	if($('.sect_list').length>0) {
	  var maxHeight = 0;
	  $('.sect_list div').each(function(){
		if(maxHeight < $(this).height()){
			maxHeight = $(this).height();
		}
	  });
	  $('.sect_list div').css('height',maxHeight+'px');
	}
	
	event();
        
    if($('.zoom_img').length > 0) 
	{
	  $('.zoom_img').jqzoom({  
		position:'left',
		zoomWidth: '305',
		zoomHeight: '340'
      });
      //alert('!');
	}
	
	if($('.history').html()=='' || $('.history').html()==null) $('.area').hide();     
	
	
	
	$('.text_inp').focus(function()
	{
		if($(this).val()=="0"){$(this).attr('value',"");}
	});
	
	$('.text_inp').blur(function()
	{
		if($(this).val()<1){$(this).attr('value',"0");}
	});	
	
	$('.text_inp').keyup(function()
	{
		if(parseInt($(this).val())>30)
		{
			$(this).parent().parent().find('.added').html('Мы сообщим вам о наличии необходимого количества товаров на складе.');
		}
		
		if(parseInt($(this).val())>$(this).parent().find('a:first').attr('max') && $(this).parent().find('a:first').attr('max')!="0")
		{
			$(this).attr('value',$(this).parents().find('a:first').attr('max'));
		}
	});	
	
	skype();
	/*$('.cart a').hover(function(){
	  $('.cart').css('background-position','-1000px -1000px');
	  $('.cart_ins').fadeIn(100);
	}, function(){
	  $('.cart').css('background-position','-284px 13px');
	  $('.cart_ins').fadeOut(100);
	});*/
        
        /*$('.cart a:first').mouseover(function(){
            $('.cart a:first').animate({'color':'#fff'},500);
            $('.cart_ins').fadeIn(500); 
        }).mouseout(function(){
            $('.cart a:first').animate({'color':'#B1BAC5'},500);
            $('.cart_ins').fadeOut(500); 
        });   */
        $(".cart a:first").hoverIntent({
            over: cartMakeTall,
            timeout: 100,
            out: cartMakeShort
        });
	
	$('.big_banner div a').eq(0).hide();
	
	$(".big_banner div a").show();
	if($('.big_banner').length) {
		var appear = 450;
		var delay = 3500;
		var click = false;
		var bCount = $('.switch a').length;
	
		if (!jQuery.browser.safari)  {
			  $(".big_banner div a").each(function(){
				if($(this).attr('class')!='ban_act') $(this).fadeOut(5);
			  });
		} else {
			  $(".big_banner div a").each(function(){
				if($(this).attr('class')!='ban_act') $(this).hide(5);
			  });
		}
		
		function sw(btn){
			$('.ban_act').fadeOut(appear).removeClass('ban_act');
			$('#ban'+$(btn).attr('rel')).fadeIn(appear).addClass('ban_act');
			$('.switch .act').removeClass('act');
			$(btn).addClass('act');
		}
		
	  $('.switch a').click(function(){
	    if($(this).attr('class')!='act')
		{
			sw($(this));
			click = true;
		}
	  });
	  
	  function change(){
		if(!click) {
		  var curr = $('.switch .act').attr('rel');
		  var next = (curr)%bCount + 1;

		  sw($('.switch a[rel='+next+']'));
		  setTimeout(function() {change();}, delay);
		}
	  };
	  
	  setTimeout(function() {change();}, delay);
	}
	
	var isAct = false;
	var openedFilt;
	$('.filter .color .change,.material .change,.filter .price_filt .change').click(function()
	{
		if($(this).parent().find('.list').css('display')=='none') 
		{
		  $('.list').each(function(){$(this).hide()});
		  $(this).parent().find('.list').show();
		  isAct = ($(this).attr('class')=='change') ? false : true;
		  $(this).addClass('change_act');
		  openedFilt = $(this);
		} else {
		  $('.list').each(function(){$(this).hide()});
		  if(!isAct) $(this).removeClass('change_act');
		}
	});
	
	$('.filter .color span,.material span').click(function(){
	  if($(this).attr('class')!='act'){
	    $('input[name='+$(this).parent().parent().attr('class')+']').val($(this).attr('rel'));
		savefilt();$('.items_form').submit();
	  } else {
		$('.list').hide();
	  }
	});
	
	$('.changecity,.citys a[class!=selected]').click(function()
	{
		self.location.href="where_to_buy.php?city="+$(this).attr('value');
	});
	
	$('.price_filt span').click(function(){
	  if($(this).attr('class')!='act'){ 
	    $('input[name=price1]').val($(this).attr('pr1'));
		$('input[name=price2]').val($(this).attr('pr2')); 
		savefilt();$('.items_form').submit();
	  } else {
		$('.list').hide();
	  }
	});
	
	$('.change span,.save_filt div').click(function()
	{
	  if($(this).parent().find('input').is(':checked')) 
	  {
	    $(this).parent().find('input').removeAttr('checked');
		$('.items_form input[name='+$(this).parent().find('input').attr('name')+']').val('');
		if ($(this).parent().find('input').attr('name')=="save")
		{
			$('.items_form input[name=news],.items_form input[name=discount],.items_form input[name=color],.items_form input[name=material],.items_form input[name=price1]').attr('value',"");
			$('.items_form input[name=price2]').attr('value',"9999999");
		}
	  } 
	  else 
	  { 
	    $(this).parent().find('input').attr('checked','checked');
		$('.items_form input[name='+$(this).parent().find('input').attr('name')+']').val('on');
		
		if($(this).parent().find('input').attr('name')=="news")
		{
			$('.change input[name=discount]').removeAttr('checked');
			$('.items_form input[name=discount]').attr('value',"");
		}
		else if ($(this).parent().find('input').attr('name')=="discount")
		{
			$('.change input[name=news]').removeAttr('checked');
			$('.items_form input[name=news]').attr('value',"");
		}
	  }
	  savefilt();$('.items_form').submit();
	});
	
	
	$('.change input').change(function()
	{
		if($(this).is(':checked')) 
		{
			$('.items_form input[name='+$(this).attr('name')+']').val('on');
			
			if($(this).parent().find('input').attr('name')=="news")
			{
				$('.change input[name=discount]').removeAttr('checked');
				$('.items_form input[name=discount]').attr('value',"");
			}
			else
			{
				$('.change input[name=news]').removeAttr('checked');
				$('.items_form input[name=news]').attr('value',"");
			}
		}
		else
		{ 
			$('.items_form input[name='+$(this).attr('name')+']').val('');
		}
		savefilt();$('.items_form').submit();
	});
	
	
	$('.order_form_sort .curr').click(function(){
	  if($(this).parent().find('.order_form_in').css('display')=='none') 
		{
		  $('.order_form_in').hide();
		  $('.slide_wrap').css('height',($('.slide_wrap').height()+$(this).parent().find('.order_form_in').height())+'px');
		  $(this).parent().find('.order_form_in').show();
		  $(this).addClass('curr_act');
		} else {
		  $('.order_form_in').hide();
		  $('.slide_wrap').css('height',($('.slide_wrap').height()-$(this).parent().find('.order_form_in').height())+'px');
		  $(this).removeClass('curr_act');
		}
	});
	
	$('.order_form_in a').click(function(){
      if($(this).attr('class')!='active'){ 
	    if($(this).parents('.order_form_sort').attr('id') == 'sort')
	      $('.sort_inp').val($(this).attr('name'));
		else 
		  $('.items_form input[name="onpage"]').val($(this).attr('name'));
	    savefilt();
		$('.items_form').submit();
	  }
	});
	
	
	$('#sort').change(function()
	{
		$(this).parent().submit();
	});
        
	$('.choose_items span').mouseover(function(){
            var color = $(this).next().attr('color');
            $(this).parents('.choose_items').find('span.act_color').removeClass('act_color');
            $(this).addClass('act_color');
            $('.more_photos').find('a.act_img').removeClass('act_img');
            $('.more_photos a[color='+color+']').addClass('act_img');
			
			if(!$(this).parent().parent().hasClass("choose_items2"))
			{
				$('.cnt').html($(this).find('a').attr('cnt'));
			}
        });
        
        
    $('.colors,.choose_items2').find('a').mouseenter(function()
	{
		
		var img=$(this).parents('tr').find('.basket_img');
		var img2=$(this).parents('.item').find('img');
		$(this).parents('tr').find('.cnt').html($(this).attr('cnt'));

		var src = ($(this).attr('ref')) ? $(this).attr('ref') : "/bitrix/templates/main/img/pict/item.gif";
		$(img).attr('src',src);
		$(img2).attr('src',src);
		
		$(img).parent().attr('href',$(this).attr('href'));
		if($(this).attr('color')!=null)
		{
			$(this).parents('tr').find('.add_to_cart').attr('ref',$(this).attr('color'));
		}
		$(this).parent().parent().find('.act_color').removeClass('act_color');
		$(this).parent().addClass('act_color');		
		
                $('.more_photos a[color]').removeClass('act_img');
		$('.more_photos a[color='+$(this).attr('color')+']').addClass('act_img')/*.trigger('mouseover')*/;
                var big = $('.more_photos a.act_img img').attr('big');
                var sourse = $('.more_photos a.act_img img').attr('sourse');
                $('.zoomPad img').removeAttr('src');
                 
	}
	);
            
        
	
	if($('.comp_count').html()=='Выбран 1 товар') $('.compare_link').addClass('compare_link_nact');
	else $('.compare_link').removeClass('compare_link_nact');
	
        $('.comparisons_del').click(function(){
            $.ajax({
			url: '/ajaxer.php',          
			type : "POST",
			cache: false,
			data: ({mode: 'comparisons',type:'del',id:'1',action:'1'}),
			success: function (data, textStatus) 
			{
                            //alert(data);
                            //<p><font class="notetext">Список сравниваемых элементов пуст.</font></p>
                            $('.catalog-compare-result').html('<p>Список сравниваемых элементов пуст.<br />Вы можете добавить товары к сравнению, используя соответствующую ссылку в каталоге или на странице товара.</p>');
                        }
		
            });
        });
        
   $('.fastorder').live('click',function()
	{
		var td=this;
		$.ajax({
			url: '/ajaxer.php',          
			type : "POST",
			cache: false,
			data: ({mode: 'fastorder'}),
			success: function (data, textStatus) 
			{
				var tmp=data.split("_");
				if(tmp[0]="ok"){alert(tmp[1]);location.href='/';}
				else{alert(tmp[1]);}
				//$(td).append(data);
			}			
		}); 
	});
		
    $('.comparisons').live('click',function()
	{
		var td=this;
                var flag = false;
		$.ajax({
			url: '/ajaxer.php',          
			type : "POST",
			cache: false,
			data: ({mode: 'comparisons',type:$(this).attr('mode'),id:$(this).attr('rel')}),
			success: function (data, textStatus) 
			{
			//	alert(data);
				if($(td).attr('mode')=='del')
				{
					if($('.comparisons_list').find('.item2').length==1){$('.comparisons_list').html('');}
				    if($(td).attr('class')!='comparisons') {
					    $('.comparisons_list .item2[rel='+ $(td).attr('rel') +']').remove();
						$(td).removeClass('compare_act').attr('mode','add');
						$(td).find('span').html('Добавить к сравнению');
					} else {
						if ($(td).parent().attr('class')!='item2') $(td).parent().parent().remove();
						else $(td).parent().remove();
						$('.compare_act[rel='+ $(td).attr('rel') +']').removeClass('compare_act').attr('mode','add');
					}
					//$('.comp_link').html('');
				}
				else
				{
					/*if($('.comparisons_list').parent().parent().find('.item2').length==0)
					{
					  $('.comparisons_list').html('Выбрано для сравнения:  <a class="compare_link" href="/card/comparisons.php">Сравнить</a>');
					  $('.comparisons_list').append("<div class='compare_inner'><div class='sortable'></div><span class='toright'></span><span class='toleft'></span></div>");  
					}
					$('.sortable').append(data);*/
					$(td).addClass('compare_act').attr('mode','del');
					$(td).find('span').html('Добавлено к сравнению');
					flag = true
					//$('.comp_link').html('Перейти к сравнению');
				}
				if(data) 
				{
					$('.comp_block').html(data);
					if($('.comp_count').html()=='Выбран 1 товар') $('.compare_link').addClass('compare_link_nact');
					else $('.compare_link').removeClass('compare_link_nact');
					$('.comp_wrap').show();
                    if(flag){comparisonsFly(td);};
				}
				else $('.comp_wrap').hide();
				items_count();
			}
		});	
	

	});
	
	function savefilt()
	{
		$('.items_form input').each(function()
		{
			setCookie($(this).attr('name'), $(this).attr('value'), "Mon, 01-Jan-2199 00:00:00 GMT", "/");
		});
		
	}
	
	function items_count(){
	var ind = 1;
	$('.item2').each(function(){
	  $(this).css('left',(25*ind) + '%').css('margin-left','-25%').css('zoom','1');
	  ind ++;
	});
	$('.toleft').hide();
	$('.toright').show();
	if(ind<6) $('.toright').hide();
	}
	
	items_count();
	
  var clicks = 0;
  var marg = 0;
  $('.toright').live('click', function(){
	$('.toleft').show();
    $('.item2').each(function() { 
	  marg = parseInt($(this).css('marginLeft').replace('px','').replace('%',''));
	  $(this).animate({'marginLeft':(marg-100)+'%'},700);
	});
	clicks++;
	if(!(clicks+1<$('.item2').length/4)) $('.toright').hide();
  });
  
  $('.toleft').live('click', function(){
    $('.toright').show();
    $('.item2').each(function() { 
	  marg = parseInt($(this).css('marginLeft').replace('px','').replace('%',''));
	  $(this).animate({'marginLeft':(marg+100)+'%'},700);
	});
	clicks--;
	if(clicks==0) $('.toleft').hide();
  });
	
  $('#collection_show').click(function(){
    $('#section').hide();
    $('#collection').show();
	setCookie("menu", "collection", "Mon, 01-Jan-2199 00:00:00 GMT", "/");
  });
  
  $('#section_show').click(function(){
    $('#section').show();
    $('#collection').hide();
	setCookie("menu", "section", "Mon, 01-Jan-2199 00:00:00 GMT", "/");
  });     

  $('.collection_show').click(function(){
	$('#collection_show').trigger('click');
  });
  
  $('.section_show').click(function(){	
	$('#section_show').trigger('click');		
  });
  
   function update_suff(v) {
		var ends = new Array('ие','ия','ий');
		var end;
		var vlast = v.substr(-1);
		var vv = v.substr(-2);
		if ((vv>10)&&(vv<20)) $end = 2;
		else end = (vlast==1)?0:(((vlast>1)&&(vlast<5))?1:2);
		return(ends[end]);
	}
		 
	$('.add_to_cart,.addorder').live('click',
        function(){
   
		{
                        if($('.comparisons_list').size()>0){
                            $(this).html('Обработка');
                        }else{
                            $(this).html('Обработка...');
                        }
			var td=this;
			
			var count=$(td).parent().find('input[name=text_inp]').val();
			var cnt=0;
			var cc="";
			if($(this).parents('tr').html()!=null){var div=$(this).parents('tr');}else{var div=$('.choose_items');}
			$(div).find('input[type=buy]').each(function()
			{
				if($(this).val()>0)
				{
					cc=cc+$(this).attr('color')+"="+$(this).val()+"&";
					cnt=cnt+parseInt($(this).val());
				}
			});
			if(cnt>count){count=cnt;}
			
			$.ajax({
				url: '/ajaxer.php',            
				type : "POST",
				data: ({id: $(td).attr('ref'),count: count,mode: 'buyitem',color:$(this).attr('color'),cc:cc}),
				success: function (data, textStatus) 
				{
					//alert(data);
				
					//Жесть
					var i=1;
					var check=true;
					if($(td).attr('mode')=="change")
					{
						$('.price').each(function()
						{
							if($(this).attr('real')!=null && $(this).attr('art')!=null)
							{
								var td2=this;
								$.ajax({
										url: '/ajaxer.php',            
										type : "POST",
										data: ({art:$(td2).attr('art'),mode: 'check_rate',check:check}),
										success: function (data2, textStatus) 
										{
											//alert(data2);
											
											var price=new String(Math.round(parseFloat($(td2).attr('real'))*parseFloat(data2)*100)/100);
											price=price.split('.');
											if(price[1]==null){price[1]="00";}
											else if(price[1].lenght<2){price[1]=price[1]+"0";}
											
											$(td2).html(price[0]+"."+price[1]);
																	
											if($('.price').length==i)
											{
												$('.add_to_cart,.addorder').unbind('click');
												$('.cart_items').removeClass('inactive').html(data);//alert(data);
												if($('.cart').find('.rub').html()=='' || $('.cart').find('.rub').html()==null) $('.cart').append("<span class='rub'>Р</span>, <a href='/personal/order.php'>оформить заказ</a>");
												if(count>0)
												{
													$(td).next().html('Добавлено '+count+' наименован'+update_suff($(td).parent().find('input[name=text_inp]').val())+'<br/><a href="/personal/order.php">Перейти к оформлению заказа</a>');
												}
												flyToCart(td);
											}
											i++;
										}
									});	
								check=false;
							}
						});
					}
					else
					{
						$('.add_to_cart,.addorder').unbind('click');
						$('.cart_items').removeClass('inactive').html(data);//alert(data);
						if($('.cart').find('.rub').html()=='' || $('.cart').find('.rub').html()==null) $('.cart').append("<span class='rub'>Р</span>, <a href='/personal/order.php'>оформить заказ</a>");
						$(td).parent().find('div').html('Товар добавлен к заказу<br/><a href="/personal/order.php">Перейти к оформлению</a>');

						flyToCart(td);					
					}
					
				}
			});
           // date_unix = new Date().getTime();
        }
		/*else{
                        //alert('oops');
        }  */ 
	});
	
	function skype()
	{
		$.ajax({
			url: '/ajaxer.php',          
			type : "POST",
			cache: false,
			data: ({mode: 'skype'}),
			success: function (data, textStatus) {
				$('.skype').html(data);
			}
		});	
	}
function showprice(num)
{
	num=Math.ceil(num);
	num=num.toString();
	var count=0;
	
	if(num.length>3)
	{
		var lng=num.length%3;
		for(var i=lng;i<num.length-2;i+=3)
		{
			if(i!=0)
			{
				num=num.substr(0,i+count)+" "+num.substr(i+count,num.length);
				count++;
			}
		}
	}

	return num;
}	
	function shadWidth(){
	  if($(window).width()<1420 && $(window).width()>1000) {
	    w = ($(window).width() - $('#root').width())/2;
		mw = -w;
	    $('.shad_right').css({paddingRight: w + 'px', right: mw + 'px'});
	  } else {
	    if($(window).width()<1001) $('.shad_right').css({paddingRight:'15px', right:'-15px'});
	    else $('.shad_right').css({paddingRight:'99px', right:'-99px'});
	  }
    }
	
	var firstTime = true;
	function margChange(){
	  if($(window).width()<1070) {
	    $('.item').each(function(){
		  if($(this).attr('class')=='item') $(this).css('margin-right','2%');
		})
	  } else {
        $('.item').each(function(){
		  if($(this).attr('class')=='item') $(this).css('margin-right','4%');
		})
      }	 
	  
	   	if($('.slide_wrap').html()!='' && $('.slide_wrap').html()!=null) 
		{
			var h = $('.slide_in').height() + 32;
			if(firstTime) 
				$('.slide_wrap').animate({'height': h + 'px'}, h, function(){});
			else $('.slide_wrap').css('height',h+'px');
			$('.slide_wrap').css('height',($('.slide_wrap').height()+$('.curr_act').parent().find('.order_form_in').height())+'px');
		}
	  
	   firstTime = false;	  
	}
	
	shadWidth();
	margChange();
	$(window).resize(function(){
		shadWidth();margChange();compareHeight();
		$('h2').each(function(){
			if($(this).height() > 40) $(this).css('background-position','0 -900px');
			else $(this).css('background-position','0 9px');
		});
	});

  	if($(document).height()<700) $('#to_top').hide();
	$('#to_top').bind('click',function(){
	   var time = $(this).offset().top/5;
	   if ($.browser.opera)	$('html').animate({scrollTop: 0}, time);
	   else $('html,body').animate({scrollTop: 0}, time);
	});
	
	$('.left_menu .dash').live('click',function(){
	  $(this).removeClass('dash'); 
	  if($(this).attr('class')=='types') {
	    $('#colls').hide();
		$('.colls').addClass('dash');
	  } else {
	    $('#types').hide();
		$('.types').addClass('dash');
	  }
	  $('#' + $(this).attr('class')).show();
	});
	
	$('.history .dash').click(function(){
		var posX = $(this).offset().left + $(this).width()/2;
	    var posY = $(this).offset().top + 20;
		$('.hint').css({left: posX + 'px', top: posY + 'px', display: 'block'});
	});
	
	$(document).click(function(e){ 
		if ($(e.target).parents().filter('.hint:visible').length != 1 && $(e.target).attr('rel')!='hint_show') {
			$('.hint').hide();
		}
		if ($(e.target).parents().filter('#login-form-window:visible').length != 1 && $(e.target).attr('rel')!='auth_show') {
			$('#login-form-window').hide();
		}
		if ($(e.target).parents().filter('#fastsearch:visible').length != 1 && $(e.target).attr('id')!='q') {	
			$('#fastsearch').hide();
		}
		if ($(e.target).parents().filter('.order_form_in:visible').length != 1 && !$(e.target).parents('.order_form_sort').length) {	
			$('.order_form_in').hide();
			if($('.curr_act').length) $('.slide_wrap').css('height',($('.slide_wrap').height()-$('.order_form_in').height())+'px');
			$('.curr_act').removeClass('curr_act');
		}
		if ($(e.target).parents().filter('.list:visible').length != 1 && !$(e.target).parents('.filter td').length) {	
			$('.list').hide(); 
			if(!isAct) $(openedFilt).removeClass('change_act');
		}
		if ($(e.target).parents().filter('.citys:visible').length != 1 && !$(e.target).parents('.city_wrap').length) {	
			$('.citys').hide(); 
		}
	});
	
	/*$('body').click(function(){
	  $('#login-form-window').hide();
	  $('.hint').hide();
      $('.city_wrap_current').removeClass('active');
      $('.citys').hide();
	});*/
	
	if ($.browser.safari) {
	  if(!($.browser.safari && /chrome/.test(navigator.userAgent.toLowerCase()))) {
	    $('.history .rub').each(function(){
		  if($('.wholesale').html()!=null && $('.wholesale').html()!='')
		    $(this).css('background-position','-162px -18px');
		  else
		    $(this).css('background-position','-162px -4px');
		});
		//$('.item .price .rub,.sale_order_full_table .rub').each(function(){$(this).css('background-position','-174px 10px');});
		$('.item .old_price .rub').each(function(){$(this).css('background-position','-177px -8px');});
		$('.comp_wrap').css('line-height','15px');
		$('.props td').css('background-position','0 13px');
		$('.shop_data .prop_val img, .store .prop_val img').css('top','-4px');
	  }
	}
	
	$('.search .dash').click(function(){
	  $('#q').val($(this).html());
	});
	
	if($('#login-form-window').find('.errortext').length)
	{
		if($.browser.opera)
		{
			$('html').animate({scrollTop: ($('.auth_show').offset().top - 22)}, 500, function()
			{
				$('.auth_show').trigger('click');
			});
		} else {
			$('body').animate({scrollTop: ($('.auth_show').offset().top - 22)}, 500, function()
			{
				$('.auth_show').trigger('click');
			});
		}
	}
	
	$('.auth_show').live('click', function(){ 
	  if($('#login-form-window').css('display')=='none') {
		  var posX = $(this).offset().left + $(this).width()/2;
		  var posY = $(this).offset().top + 22;
		  $('#login-form-window').css({left: posX + 'px', top: posY + 'px', display: 'block'});
	  } else {
	      $('#login-form-window').hide();
	  }
	});

	        
        $('.shop_more_images a').mouseover(function(){
            var href = $(this).attr('href');            
        });
	
	compareHeight();
	
	$('.city_wrap_current').click(function(){
		  if(!$('.citys').length) $('body').append($('.citys'));
		  var posX = $(this).position().left + $(this).width()/2;
		  var posY = $(this).position().top + 20;
		  if($('.citys').css('display')=='none') {  
			  $('.citys').css({left: posX + 'px', top: posY + 'px', display: 'block'});
		  } else {
			  $('.citys').hide();
		  }
	});
	
});

$('.retail_stores .store .title').unbind().live('click',function(){
    var el = $(this);
    if($(this).attr('rel') == 'active'){
       //$(this).next().animate({'height':'0px'});
       $(this).next().slideUp();
       $(this).attr({'rel':''}).removeClass('active');
    }else{
        //$(this).next().animate({'height':'200px'});
        $(this).next().slideDown();
        $(this).attr('rel','active').addClass('active');;
        $('.retail_stores .store .data').each(function(){
            if($(this).text() !== el.next().text()){
                //$(this).animate({'height':'0px'});
                $(this).slideUp();
                $(this).prev().attr('rel','').removeClass('active');;
            }
        })
    }
})

$('.item_desc_more').live('click',function(){
    $(this).parent().html($(this).find('.more').html());
});

        
/*function buttonActive()
 {
var subButton=document.getElementById('subm');
var checkme=document.getElementById('agree');
(checkme.checked)?subButton.disabled=false:subButton.disabled=true;
 }*/

function compareHeight()
{
	var maxHeight = 0;
	if($('.comparisons_list').size()>0){           
		$('.item2_top').each(function(){
			if(maxHeight < $(this).height()){
				maxHeight = $(this).height();
			}
		});
		
		$('.item2_top').css('height', maxHeight+'px');
		$dif = 24;
		$('.p_material').css('top', ($('.last_prop').eq(0).position().top - $dif) + 'px').show();
		$('.p_price').css('top', ($('.last_prop').eq(1).position().top - $dif) + 'px').show();
		$('.p_size').css('top', ($('.last_prop').eq(2).position().top - $dif) + 'px').show();
		$('.p_color').css('top', ($('.prop_color_wrap').position().top - $dif) + 'px').show();
	}
}
 
function fastsearch()
{
  if(!($.browser.msie && $.browser.version=="6")){
	var q=$('#q').attr('value');
	if(q!="Поиск по сайту")
	{
		$.ajax({
				url: '/ajaxer.php',            
				type : "POST",
				data: ({data: q,mode: 'fastsearch'}),
				success: function (data, textStatus) 
				{
					//alert(data);
					$('#fastsearch').html(data).show();
					
					//event();
				}
			});
	}
  }
}

function event()
{
  if(!($.browser.msie && $.browser.version=="6"))
  {
	var timerID;
	$('#q').keyup(function(eventObject)
	{
		//alert('2');
	
		if(eventObject.which==38)
		{
                    _gaq.push(['_trackEvent', 'Поиск', 'Использование клавиатуры в выпадающих результатах поиска', 'Клавиша «Вверх»']);
			var mass=$('.fastsearch_in a');
			if($('.bag_act').html()==null)
			{
				 var cur=0;
			}else{
				var cur=parseInt($('.bag_act').attr('ref'))-1;
			}
			//alert(cur);
			if(cur>0)
			{
				//alert(cur);
				$('.bag_act').removeClass("bag_act");
				$(mass[cur-1]).addClass("bag_act");
			}
		}
		if(eventObject.which==40)
		{
                    _gaq.push(['_trackEvent', 'Поиск', 'Использование клавиатуры в выпадающих результатах поиска', 'Клавиша «Вниз»']);
			var mass=$('.fastsearch_in a');
			if($('.bag_act').html()==null)
			{
				 var cur=0;
			}else{
				var cur=parseInt($('.bag_act').attr('ref'));
			}
			if(cur<mass.length)
			{
				$('.bag_act').removeClass("bag_act");
				$(mass[cur]).addClass("bag_act");
			}
		}
		if(eventObject.which==13)
		{
                    _gaq.push(['_trackEvent', 'Поиск', 'Использование клавиатуры в выпадающих результатах поиска', 'Клавиша «Enter»']);
			if(parseInt($('.bag_act').attr('ref'))>0 && $('.bag_act').attr('type')!='all')
			{
				window.location.href=$('.bag_act').attr('href');
			}
			else
			{
				$(this).submit();
			}
		}	
		
		if(eventObject.which!=38 && eventObject.which!=40 && eventObject.which!=13)
		{
			//alert('123');
			clearTimeout(timerID);
			timerID=setTimeout('fastsearch()','1000');
		}
	});	
  }
}


var flag_comparisons = true;


function comparisonsFly(link){
    
    var size_img = [0,0];
    
    if($('.wholesale').size() > 0){ // опт
        if($('.zoom_img').size() > 0){
            var image = $('.zoom_img img.big_img'); 
       }else{
            var image = $(link).parents('tr').find('td:first').find('img.basket_img')/*.css('padding','0px')*/; 
       }
    }else{ // розница
        
        if($('.zoom_img_wrap').size() > 0){
            var image = $('.zoom_img img.big_img'); 
       }else{
           size_img = ['182px','182px'];
           var image = $(link).parents('.item').find('a > img.pic'); 
       } 
       //alert(image);
    }  
    
    var btPos = getPosition(image);
    
    var cartPos = $('.comp_count').offset();
    var width_count = $('.comp_count').width();
    var height_count = $('.comp_count').height();
    //alert('top '+cartPos.top)
    //alert(image);
      var tmp = $(image).clone(true)
              .appendTo('body')
              .css({'top':btPos.y+'px','position':'absolute','left':btPos.x+'px','opacity':0.75,'z-index':120});
              
              if(size_img[0] != 0 && size_img[1] != 0) $(tmp).css({'width':size_img[0],'height':size_img[1]});
              
              $(tmp).animate({
                   top: (cartPos.top + height_count/2 + 5)+'px',
                   left: (cartPos.left + width_count/2)+'px',//cartPos.x
                   padding : '0px',
                   width: '0px',
                   height: '0px'
              },700).fadeOut(500,function(){
              $(this).remove();
              });
              
}

$compareflag = true;
function flyToCart(lnk){
    //alert($(lnk).attr('class'));
    var size_img = [0,0];
    if($('.sortable_tems').size() > 0){
        var img = $(lnk).parents('.item2').find('a:first img');
        //alert(img);
        size_img = ['110px','110px'];
    }else{
       var img = ($(lnk).attr('class')=='addorder') ? $('.big_img') : $(lnk).parent().parent().find('.basket_img');
       var img2 = ($('.act_big').size() > 0) ? $('.act_big') : $('.img0'); 
    }
    
        
       var image = (img.size() > 0) ? img : img2; 
        //var image = $('.big_img');
        //alert($(image).attr('src'));
        
        if($(image).size()>0){
              var cart = $('.cart');
              var btPos = getPosition(image);
              //var cartPos = getCenterPos(image,cart);
              var cartPos = $('.cart').offset();
              //alert(cartPos.y);
              
              $('.cart').animate({'color':'#fff'},500).animate({'color':'#B1BAC5'},500);
              $('.cart_ins').fadeIn(500).fadeOut(500);
              var tmp = $(image)
              .clone(true)
              .appendTo('body')
              .css({'top':btPos.y+'px','position':'absolute','left':btPos.x+'px','opacity':0.75,'z-index':120});
              
              // для страницы сравнения
              if(size_img[0] != 0 && size_img[1] != 0) $(tmp).css({'width':size_img[0],'height':size_img[1]});
              
              $(tmp)
              .animate({
                   top: '15px',
                   left: (cartPos.left + 8)+'px',//cartPos.x
                   width: '0px',
                   height: '0px'
              },700).fadeOut(500,function(){
                $(this).remove();
              });
      }
      if($(lnk).parents('.comparisons_list').size()>0){
          $(lnk).html('В корзину');
          if($(lnk).next().attr('class') == 'add'){
              $(lnk).next().remove();
          }
		  $(lnk).parents('.item2_top').append("<div class=\"add\" style=\"float: none;\"><div>Товар добавлен<br><a class=\"comparisons_list_a_my\" style=\"color: #A41727;text-decoration:underline;\" href=\"/personal/order.php\">Перейти к&nbsp;оформлению</a></div></div>");
		  if($compareflag) $(lnk).parents('.item2_top').css('height',$(lnk).parents('.item2_top').height() + 42 +'px');
		  compareHeight();
		  $compareflag = false;
      }else{
          $(lnk).html('Добавить в корзину');
      }
      
}

function getPosition(elem){
  var el = $(elem).get(0);
	var p = {x: el.offsetLeft, y: el.offsetTop}
	while (el.offsetParent){
		el = el.offsetParent;
		p.x += el.offsetLeft;
		p.y += el.offsetTop;
		if (el != document.body && el != document.documentElement){
			p.x -= el.scrollLeft;
			p.y -= el.scrollTop;
		}
	}
	return p;
}

function cartMakeTall(){
    $('.cart a:first').animate({'color':'#fff'},500);
    $('.cart_ins').fadeIn(500); 
}

function cartMakeShort(){
    $('.cart a:first').animate({'color':'#B1BAC5'},500);
     $('.cart_ins').fadeOut(500); 
}

/*$('.cart a:first').mouseover(function(){
            $('.cart a:first').animate({'color':'#fff'},500);
            $('.cart_ins').fadeIn(500); 
        }).mouseout(function(){
            $('.cart a:first').animate({'color':'#B1BAC5'},500);
            $('.cart_ins').fadeOut(500); 
        });   */
function getCenterPos(elA,elB,Awidth,Aheight){
  if(typeof(Awidth)=='undefined') Awidth = $(elA).outerWidth();
  if(typeof(Aheight)=='undefined') Aheight = $(elA).outerHeight();
  posB = new Object();
  cntPos = new Object();
  posB = getPosition(elB);
  var correct;
  cntPos.x = Math.round(($(elB).outerWidth()-Awidth)/2)+posB.x;
  cntPos.y = Math.round(($(elB).outerHeight()-Aheight)/2)+posB.y;
  if(cntPos.x+Awidth>$(window).width()){
    cntPos.x = Math.round($(window).width()-$(elA).outerWidth())-2;
  }
  if(cntPos.x<0){
    cntPos.x = 2;
  }
  return cntPos;
}

function SetHistory(id)
{
	setCookie('history',"2;", "Mon, 01-Jan-2199 00:00:00 GMT", "/");
	alert(getCookie('history'));
}

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) 
{
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

common = {vars: {loaded:false}};

common.offsets = function (object) {
	var offsets = {w: object.offsetWidth, h: object.offsetHeight, x: 0, y: 0};

	for ( ; object; object = object.offsetParent) {
		offsets.y += object.offsetTop;
		offsets.x += object.offsetLeft;
	}

	return offsets;
};




