
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
var is_ie6 = $.browser.msie && ($.browser.version.slice(0, 1) == "6");
var is_ie7 = $.browser.msie && ($.browser.version.slice(0, 1) == "7");

var preload = new Image();
preload.src = '/images/main/popup-head-bg.gif';

function iload(){
	
	if(is_ie6){
		$(window).resize(function(){
			var w = $(window).width();
			if(w < 1000)
				$('body').width('1000px');
			else
				$('body').width('100%');	
			
			$('#popular').css('zoom','1');
		});
		window.onload = function(){
			var w = $(window).width();
			if(w < 1000)
				$('body').width('1000px');
			else
				$('body').width('100%');	
		};
	}
	
//	var startTime = new Date();
//	var curTime = new Date();
//	console.log("start: ", new Date() - curTime, " ms");
	
	load_auth_popup();
//	console.log("load_auth_popup time: ", new Date() - curTime, " ms");
//	curTime = new Date();
	
	load_top_menu();
//	console.log("load_top_menu time: ", new Date() - curTime, " ms");
//	curTime = new Date();	
	
	
	load_city_select();
//	console.log("load_city_select time: ", new Date() - curTime, " ms");
//	curTime = new Date();		
	
	load_tabs();
//	console.log("load_tabs time: ", new Date() - curTime, " ms");
//	curTime = new Date();		
	
	load_catalog_menu();
//	console.log("load_catalog_menu time: ", new Date() - curTime, " ms");
//	curTime = new Date();
	
	load_search();	
//	console.log("load_search time: ", new Date() - curTime, " ms");
//	curTime = new Date();
	
	load_register();	
//	console.log("load_register time: ", new Date() - curTime, " ms");
//	curTime = new Date();
	
	load_cash();
//	console.log("load_cash time: ", new Date() - curTime, " ms");
//	curTime = new Date();
	
	load_orderauth();
//	console.log("load_orderauth time: ", new Date() - curTime, " ms");
//	curTime = new Date();
	
	load_path();	
//	console.log("load_path time: ", new Date() - curTime, " ms");
//	console.log("total time: ", new Date() - startTime, " ms");
	load_resize_handler();
}

function load_resize_handler() {
	window.onresize = function(){
		if ($('#delivery-popup').css("display") == 'block') {	
			shop_delivery_cost();
		}
	};
}

function load_auth_popup(){
	//auth popup

	$('#auth a.close').click(function(){
		$('#overlay,#auth').hide();
		return false;
	});
	
	$('#test-login').click(function(){
		$('#overlay,#auth').show();
		if(is_ie6)
			$('#overlay').height($('body').outerHeight());
		return false;
	});
	$('#overlay').click(function(){
		$('#overlay,#auth').hide();
		return false;
	});		
}

function getInternetExplorerVersion() {
	var rv = -1; // Return value assumes failure.
	if (navigator.appName == 'Microsoft Internet Explorer')	{
		var ua = navigator.userAgent;
	 	var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
	 	if (re.exec(ua) != null)
		 rv = parseFloat( RegExp.$1 );
	}
	return rv;
}


function shop_delivery_cost(){
	var h=w=0;
	if (navigator.appName != 'Microsoft Internet Explorer') {
		if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
			h = Math.round(window.innerHeight * 99/100)-295;
			w = Math.round(window.innerWidth * 99/100)-367;
		} else {
			h = Math.round(window.innerHeight * 99/100)-274;
			w = Math.round(window.innerWidth * 99/100)-366;
		}
		
		$('#delivery-popup').css("left",w);
		$('#delivery-popup').css("top",h);
	} else if (navigator.appName == 'Microsoft Internet Explorer' && getInternetExplorerVersion() > 7) {
		h = document.documentElement.clientHeight-300;
		w = document.documentElement.clientWidth-360;
		
		$('#delivery-popup').css("left",w);
		$('#delivery-popup').css("top",h);
	}
	$('#delivery-popup').show();
	$('.aclose').click(function(){
		$('#delivery-popup').hide();
		return false;
	});
	return false;
}

function load_top_menu(){	
	//top menu
	if(is_ie6)
		return ;
		
	var menu = $('#top-menu');
	var cashLi = menu.children();	
	if(!cashLi.length)
		return ;
		
	if (is_ie6) {
		menu.find('.rounded-bg').each(function(){
			var t = $(this);
			var w = t.parent().width();
			t.width(w + 20);
			t.find('i').width(w + 15);
		});
	}
	var someTimer = null;
	
	$('#top-menu>li>a , #top-menu>li>div').hover(function(){
		cashLi.removeClass('open');
		var p = $(this).parent();		
		p.addClass('open');
		if(!p.hasClass('loaded')){
			if(is_ie6){
				p.find('.mega-select').width(243);
			} else {
				p.find('.mega-select').width(p.find('.middle').width()+4);	
			}
			
			p.addClass('loaded');
		}
		clearTimeout(someTimer);
	},function(){
		var p = $(this).parent();
		someTimer=setTimeout(function(){
			p.removeClass('open');	
		}, 300);		
	});
}

function load_city_select(){	
	// city select
	var s = $('#change-city');
	var popup = $('#select-city');
	
	s.click(function(){
		popup.show();
		if(!popup.hasClass('loaded')){
			if(is_ie6){
				popup.width(243);
			} else {
				var w = s.width() + 4;
				var nw = popup.find('ul').width()+4; 
				if (nw > w) {
					w = nw;
				}
				popup.width(w);	
			}
			popup.addClass('loaded');
		}
		popup.css(s.offset());
		return false;
	});
	popup.find('a.selected').click(function(){
		popup.hide();
		return false;
	});
	
	var timerCity = null;
	popup.mouseout(function(){
		timerCity = setTimeout(function(){
			popup.hide();	
		},500);
	}).mouseover(function(){
		clearTimeout(timerCity);
	});
}

function load_tabs(){	
	// tabs

	$('a.need-tab').click(function(){
		var t = $(this);
		if (t.parent().parent().parent().hasClass('js-tabs')) {
			
			var show = t.parent().parent();
			var hide = show.parent().find('li.selected');
			
			hide.removeClass('selected');
			$('.'+hide.attr('_tab')).hide();
			
			show.addClass('selected');
			$('.'+show.attr('_tab')).show();
			
			return false;
		}
	});
	
}


// catalog menu
function load_catalog_menu(){
	
	var select=$('#city_id');
	var timer=null;
	var catMenu = $('#catalog-menu'); 
	
	var cashOuter = catMenu.children();
	var cashSubLevel2 = new Array();
	var cashSubLevel3 = new Array();
	var cashSubLevel4 = new Array();
	
	catMenu.show();
	
	var tl = 0;
	cashOuter.each(function(){
		tl+=$(this).outerWidth();
	});
	
	catMenu.width(tl);

	if (!is_ie6) {
	
		cashOuter.find('a.title').each(function(){
			
			var t = $(this);
			t.width(t.width());
			
			if ($.browser.opera || is_chrome || $.browser.safari) {
				var te = t.html();
				
				te = te.substr(te.indexOf('<! [endif]-->') + '<! [endif]-->'.length);
				te = te.substr(0, te.indexOf('<'));
				te = te.replace(/(^\s+)|(\s+$)/g, "");
				if (te.length < 6) {
					t.css('height', '26px');
					t.css('padding-top', '6px');
				}
				t.css('display', 'block');
			}
		});
	}
	
	if (is_ie6) {
		cashOuter.filter('.active').find('.rounded-bg').each(function(){
			var t = $(this);
			var w = t.parent().outerWidth() - 10;
			
			t.width(w + 10);
			t.find('i').width(w + 5);
		});
		
	}
	
	if(!catMenu.hasClass('show'))
		catMenu.hide();


	//catalog menu 1 level
	
	cashOuter.hover(function(){

		clearTimeout(timer);
		if(is_ie6 && this.timer)
			clearTimeout(this.timer);
		var t = $(this);
		if(t.hasClass('open'))
			return;

		cashOuter.removeClass('open nohide');
		
		if (!is_ie6) {
			for (var i = 2; i <= 4; i++) {
				jQuery.each(eval("cashSubLevel" + i), function(){
					this.hide();
				});
				
				eval("cashSubLevel" + i + "= new Array()");
			}
		}

		if(t.hasClass('active')){
			t.removeClass('active');
			t.addClass('activeopen');
		}
		t.addClass('open');
		if(!t.hasClass('loaded')){
			t.find('.mega-select').each(function(){
				var ti = $(this);
				if (is_ie6) {
					ti.width(243);
				}
				else if($.browser.msie) {
					//ti.width(ti.find('.middle').width() + 2);
					ti.width(243);
				}
			});
			
			if ($.browser.msie && !t.hasClass('activeopen')) {
				t.find('.rounded-bg').each(function(){
					var ti = $(this);
					var w = t.outerWidth();
					
					ti.width(w + 10);
					ti.find('i').width(w + 5);
				});
			}
			t.addClass('loaded');
		}
		
		if(is_ie6)
			select.css('visibility','hidden');
				
	},function(){
		var t = $(this);
		/*if(is_ie6){
			if(this.timer)
				clearTimeout(this.timer);
			
			this.timer = setTimeout(function(){
				if (!t.hasClass('nohide')) {
			
					if(t.hasClass('activeopen')){
						t.removeClass('activeopen');
						t.addClass('active');
					}
					t.removeClass('open');
					//select.css('visibility','visible');
				}
				
			},300)	
			return;
		}*/
		
		if (!t.hasClass('nohide')) {
			
			if(t.hasClass('activeopen')){
				t.removeClass('activeopen');
				t.addClass('active');
			}
			t.removeClass('open');
			if(is_ie6)
				select.css('visibility','visible');
		}
		
	});
	
	if (!is_ie6) {
		$('#catalog-menu .mega-select a').each(function(){
		
			var t = $(this);
			t.addClass('hasover');
			
			var parent = t.parent().parent().parent().parent();
			var cashParent = parent.find('a');
			parent.cashParent = cashParent;
			
			if (t.hasClass('next')) {
				t.mouseover(function(){
				
					var p = t.attr('megaselect'); //popup
					if (p) {
						p = $('#' + p);
					}
					else {
						return;
					}
					
					t.parent().parent().parent().parent().parent().addClass('nohide');
					
					cashParent.removeClass('nexthover').removeClass('hover');
					t.addClass('nexthover');
					
					for (var i = 2; i <= 4; i++) {
						jQuery.each(eval("cashSubLevel" + i), function(){
							this.hide();
						});
						
						eval("cashSubLevel" + i + "= new Array()");
					}
					
					
					p.show();
					if (p.cashParent) 
						p.cashParent.removeClass('nexthover').removeClass('hover');
					cashSubLevel2.push(p);
					
					if (!p.hasClass('loaded')) {
						p.width(p.find('.middle').width() + 4);
						p.addClass('loaded');
					}
					
					var left = t.offset().left + t.width() + 40;
					if (left + p.width() > $('html').width()) {
						left = t.offset().left - 1 - p.width();
					}
					p.css({
						'top': t.offset().top,
						'left': left
					});
				});
			}
			else {
				t.mouseover(function(){
				
					cashParent.removeClass('nexthover').removeClass('hover');
					t.addClass('hover');
					
					jQuery.each(cashSubLevel2, function(){
						this.hide();
					});
					
					cashSubLevel2 = new Array();
				});
			}
		});

		$('body>.mega-select a').each(function(){
			var t = $(this);
			if (t.hasClass('hasover')) 
				return true;
			
			var parent = t.parent().parent().parent().parent();
			if (parent.parent().parent().hasClass('menu')) 
				return true;
			var cashParent = parent.find('a');
			
			if (t.hasClass('next')) {
			
				t.mouseover(function(){
				
					var p = t.attr('megaselect'); //popup
					if (p) {
						p = $('#' + p);
					}
					else {
						return true;
					}
					
					cashParent.removeClass('nexthover').removeClass('hover');
					t.addClass('nexthover');
					
					var level = parseInt(parent.attr('level')) + 1;
					for (var i = level; i <= 4; i++) {
						jQuery.each(eval("cashSubLevel" + i), function(){
							this.hide();
						});
						
						eval("cashSubLevel" + i + "= new Array()");
					}
					
					
					p.show();
					if (p.cashParent) 
						p.cashParent.removeClass('nexthover').removeClass('hover');
					eval("cashSubLevel" + level + ".push(p);");
					
					if (!p.hasClass('loaded')) {
						p.width(p.find('.middle').width() + 4);
						p.addClass('loaded');
					}
					
					var left = t.offset().left + t.width() + 40;
					if (left + p.width() > $('html').width()) {
						left = t.offset().left - 1 - p.width();
					}
					p.css({
						'top': t.offset().top,
						'left': left
					});
					
				});
			}
			else {
				t.mouseover(function(){
					cashParent.removeClass('nexthover').removeClass('hover');
					t.addClass('hover');
					
					var level = parseInt(parent.attr('level')) + 1;
					for (var i = level; i <= 4; i++) {
						jQuery.each(eval("cashSubLevel" + i), function(){
							this.hide();
						});
						
						eval("cashSubLevel" + i + "= new Array()");
					}
				});
			}
		});
		
		
		$('.mega-select').hover(function(){
			var t = $(this);
			if(t.hasClass('no-level'))
				return ;
	
			clearTimeout(timer);
		},function(){
			var t = $(this);
			if(t.hasClass('no-level'))
				return ;
	
			timer=setTimeout(function(){
				cashOuter.removeClass('open nohide');
				var p = t.parent();
				if(p.hasClass('activeopen')){
					p.removeClass('activeopen');
					p.addClass('active');
				}	
				for (var i = 2; i <= 4; i++) {
					jQuery.each(eval("cashSubLevel"+i),function(){
						this.hide();
					});				
					
					eval("cashSubLevel"+i +"= new Array()");
				}	
			},300);
		});
	
	}	
	
}

//search
function load_search(){

	$('#searchB').click(function() {
		$('.search #keyword').val($(this).html());
		return false;
	}).hover(function(){
		$(this).addClass('hover');
	},function(){
		$(this).removeClass('hover');
	});
	
	// ПОИСК
	
	
	$("#searchA").click(function() {
		var keyword = $('.search #keyword').val();
		if (keyword == '') {
			alert('Введите текст для поиска');
			$('.search #keyword').select();
			return false;
		}
		
		$('#search_form').get(0).submit();
	});
		
}


//register
function load_register(){

	var auth = $('#auth');
	
	auth.find('a.js-register').click(function(){
		$('#auth-enter, #auth-register, #auth-forgot').hide();
		$('#auth-register').show();
		return false;
	});
	
	auth.find('a.js-enter').click(function(){
		$('#auth-enter, #auth-register, #auth-forgot').hide();
		$('#auth-enter').show();
		return false;
	});
	
	auth.find('a.js-forgot').click(function(){
		$('#auth-enter, #auth-register, #auth-forgot').hide();
		$('#auth-forgot').show();
		return false;
	});
	
	auth.find('#mail, #sf_guard_user_username').keyup(function(){//, #mail2

		var value = $(this).val();
		
		try {
			if ($(this).attr('id') != 'mail') {
				var oForm = ZForms.getFormById('zf-enter'), oCopyWidget = oForm.getWidgetById('mail');
				oCopyWidget.setValue(oCopyWidget.createValue(value));
			}
			
/*			if ($(this).attr('id') != 'mail2') {
				var oForm = ZForms.getFormById('zf-forgot'), oCopyWidget = oForm.getWidgetById('mail2');
				oCopyWidget.setValue(oCopyWidget.createValue(value));
			}*/
			
			if ($(this).attr('id') != 'sf_guard_user_username') {
				var oForm = ZForms.getFormById('zf-register'), oCopyWidget = oForm.getWidgetById('sf_guard_user_username');
				oCopyWidget.setValue(oCopyWidget.createValue(value));
			}
		}
		catch(e){}
	});
	
}

function add_spaces(summ){

	summ = ' ' + summ;
	summ = summ.substr(1);
	var textsumm;
	if(summ.length < 4)
		textsumm = summ;
	else if(summ.length < 7){
		textsumm = ' ' + summ.substr(summ.length-3,3);
		var temp = summ.substr(0,summ.length - 3);
		textsumm = ' ' + temp + textsumm;
	}		
	else if (summ.length < 10) {
		textsumm = ' ' + summ.substr(summ.length-3, 3);
		var temp = summ.substr(0, summ.length - 3);
		textsumm = ' ' + summ.substr(temp.length-3, 3) + textsumm;
		var temp = temp.substr(0, temp.length - 3);
		textsumm = ' ' + temp + textsumm;
	}
	else 
		textsumm = summ;
	return textsumm; 
}

function recount(){
	var summ = 0;
	$('#cash .price').each(function(){
		var v = parseInt($(this).html().replace(/ /ig,''));
		
		if(!v)
			v = 0;
		summ+=v;
	});

	summ = add_spaces(summ);
	 
	$('#all-cash').html(summ + ' p.');
	
	var count = 0;
	$('#cash .count input').each(function(){
		var v = $(this).val()*1;
		if(!v)
			v=0;
		count+=v;
	});
	if (count == 0) {
		$('.cash').hide();
		$('.cash-0').addClass('zf-disabled').attr('click','false');
	}
	else {
		$('.cash-0').removeClass('zf-disabled').attr('click','tuu');
		$('.cash').show();
		var txt = '';
        if(count%10 == 1 && count != 11 || (count > 20 && count%10 == 1))
        	txt = count + ' товар на ' + summ + ' р.';
        else if(count < 20 && count > 4)
        	txt = count + ' товаров на ' + summ + ' p.';
        else if(count<5 ||( count%10 < 5 && count%10 != 0))
        	txt = count + ' товара на ' + summ + ' р.';
        else
        	txt = count + ' товаров на ' + summ + ' р.';

		$('.cash .repeat .items').html(txt);
	}
}

function load_cash(){

	var korzina = $('#cash');
	if(!korzina.length)
		return ;
		
	$('.cash-0').attr('click','tuu')
		.click(function(){
			if($(this).attr('click') == 'tuu')
				return true;
			else 
				return false;
		});
	
	
	korzina.find('.count input').each(function(){
		var t=$(this);
		var p=t.parent().parent();
		var v=p.find('.price');
		var ic = p.find('div b');
		var id = p.find('.itemid').html();
		t.keydown(function(e){
			if(e.keyCode > 95 && e.keyCode< 106)
				return true;
			if(e.keyCode > 58)
				return false;
		});
		t.keyup(function(){
			if (!parseInt(t.val())) {
				p.addClass('del');
			}
			else 
				p.removeClass('del');
			var value = t.val();
			if(!value)
				value = 0;
			Set_Cookie('cart['+id+']',value, 30, '/');
			Set_Cookie('cart_changed','yes', null, '/'); 
			var summ = value*parseInt(ic.html().replace(/ /ig,'')); 
			summ = add_spaces(summ);
			v.html( summ + ' p.');
			recount();
		});
	});
	korzina.find('.actions a.close').each(function(){
		var t = $(this);
		var p = t.parent().parent();
		var i = p.find('input');
		var v=p.find('.price');
		var ic = p.find('div b');
		var id = p.find('.itemid').html();
		t.click(function(){
			p.addClass('del');
			i.val('0');
			v.html('0 p.');
			Set_Cookie('cart['+id+']',0, -100, '/');
			Set_Cookie('cart_changed','yes', null, '/'); 
			recount();
			return false;
		});
	});
	
	korzina.find('.actions a.back').each(function(){
		var t = $(this);
		var p = t.parent().parent();
		var i = p.find('input');
		var v = p.find('.price');
		var ic = p.find('div b');
		var id = p.find('.itemid').html();
		t.click(function(){
			p.removeClass('del');
			i.val('1');
			var summ = parseInt(i.val())*parseInt(ic.html().replace(/ /ig,''));
			summ = add_spaces(summ);
			v.html(summ + ' p.');
			Set_Cookie('cart['+id+']',1, 30, '/');
			Set_Cookie('cart_changed','yes', null, '/'); 
			recount();
			return false;
		});
	});
}

function load_orderauth(){
	var test = $('#orderauth');
	if(!test.length)
		return ;
		 
	test.find('label').hover(function(){
		$(this).addClass('hover');
	},function(){
		$(this).removeClass('hover');
	});
}

function load_path(){
	var outer = $('#pathway');
	if(!outer.length)
		return ;
	
	//Хак, для кеширования
	if($('#pathway b.lastsect').hasClass('last'))
		$('#pathway b.lastsect').prev('b.last').removeClass('last hidebg');
	
	// mega link
	outer.find('a').each(function()
	{
		var t = $(this);
		if(t.hasClass('home'))
			return ;
			
		var i = $(this).next();
		var s = i.next();
		var p = t.parent();
		
		t.hover(function(){
			if (!p.hasClass('last')) {
				p.addClass('link hidebg');
				p.prev().addClass('hidebg');
			}
		},function(){
			if (!p.hasClass('last')) {
				p.removeClass('link hidebg');
				p.prev().removeClass('hidebg');
			}
		});
		
		i.hover
		(	function()
			{
				if (!p.hasClass('last')) {
					p.addClass('link hidebg');
					p.prev().addClass('hidebg');
				}
			},
			function()
			{
				if (!p.hasClass('last')) {
					p.removeClass('link hidebg');
					p.prev().removeClass('hidebg');
				}
			}
		);
		
		s.hover(function(){
			//if (!p.hasClass('last')) {
				p.addClass('select hidebg');
				p.prev().addClass('hidebg');
			//}
		},function(){
			//if (!p.hasClass('last')) {
				p.removeClass('select hidebg');
				p.prev().removeClass('hidebg');
			//}
		});
		
		if (s.attr('megaselect')) 
		{
			var popup = $('#' + s.attr('megaselect'));
			$('body').append(popup);
			s.click(function(){
				popup.show().css(t.offset());
				if(!popup.hasClass('loaded')){
					if(is_ie6)
						popup.width(243);
					else{
						popup.width(popup.find('ul').width()+4);
					}
					popup.addClass('loaded');
				}
				return false;
			});
			popup.find('.selected').click(function(){
				popup.hide();
				return false;
			});
			popup.mouseover(function(){
				if(this.timer)
					clearTimeout(this.timer);
			}).mouseout(function(){
				if(this.timer)
					clearTimeout(this.timer);
				var t = $(this);
				this.timer = setTimeout(function(){
					t.hide();	
				},600);
			})	;
		}
	});
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function compare_add(gid, sid, gname, gurl, compare_url, e) {
	if (e.preventDefault)
		e.preventDefault();
	else
		e.returnValue = false;

	var gc_arr = [];
	var goods_compare = $.cookie('goods_compare['+sid+']');
	if (goods_compare) {
		gc_arr = goods_compare.split(',');
		var has_goods = false;
		for (var i = 0; i < gc_arr.length; i++) {
			if (gc_arr[i] == gid) {
				has_goods = true;
				break;
			}
		}
		if (!has_goods)
			gc_arr[gc_arr.length] = gid;
	} else {
		gc_arr = [ gid ];
	}
	// сохраняем в куки
	var cgc = "";
	for (i = 0; i < gc_arr.length; i++) {
		if (i > 0)
			cgc += ',';
		cgc += gc_arr[i];
	}
	
	$.cookie('goods_compare['+sid+']', cgc, { path: '/' });
	// обновляем блок, если он на экране
	if ($('#compare-block').length > 0) {
		$('#compare-block').css('display', '');
		// добавляем контент
		var html = '<a id="g'+gid+'" href="'+gurl+'">'+gname+'</a><a id="gc'+gid+'" class="close" href="#" onclick="compare_remove('+gid+', '+sid+', event)"></a><br id="gb'+gid+'" />';
		$('#compare-block #goods-compare').html($('#compare-block #goods-compare').html() + html);
	}
	
	// проверяем кол-во ссылок
	var cnt_links = compare_link_check();
	
	// Обновляем подпись на уже в сравнении
	$('span.compare[gid='+gid+']').html('уже в '+ (cnt_links > 1 ? '<a href="'+compare_url+'">сравнении</a>' : 'сравнении'));
	$('span.compare[gid='+gid+']').addClass('compared');
}

function compare_remove(gid, sid, e) {
	//e.preventDefault();
	if (confirm("Вы действительно хотите убрать товар из сравнения ?")) {
		var goods_compare = $.cookie('goods_compare['+sid+']');
		if (goods_compare) {
			var gc_arr = goods_compare;
			gc_arr = gc_arr.split(',');
			// сохраняем в куки
			var cgc = "";
			for (i = 0; i < gc_arr.length; i++) {
				if (gc_arr[i] != gid) 
					cgc += gc_arr[i] + ',';
			}
			if (cgc.length > 0) {
				cgc = cgc.substr(0, cgc.length - 1);
			}
			goods_compare = cgc;
			
			if (goods_compare.length > 0) {
				$.cookie('goods_compare['+sid+']', goods_compare, {
					path: '/'
				});
			} else { // удаляем
				$.cookie('goods_compare['+sid+']', null, { path: '/' });
			}
		}
		
		// удаляем строку в блоке
		$('#goods-compare a#g'+gid).remove();
		$('#goods-compare a#gc'+gid).remove();
		$('#goods-compare a#gb'+gid).remove();
		
		// меняем статус у товара, если есть
		$('#comp'+gid).html('добавить к <a href="#" class="out" onclick="'
							+$('#comp'+gid).attr('xonclick')				
							+'">сравнению</a>'
							);
		
		compare_link_check();
		return true;
	}
	return false;
}

function compare_link_check() {
	var cnt_links = 0;
	/*
	alert($('#compare-block #compare-link').length);
	alert($('#compare-block #goods-compare a').length);
	*/
	cnt_links = $('#compare-block #goods-compare a[class!="close"]').length;
	$('#compare-block #compare-link').css('display', cnt_links > 1 ? 'inline' : 'none');
	$('#compare-block').css('display', cnt_links > 0 ? 'block' : 'none');
	
	return cnt_links;
}

function compare_clear(sid) {
	$.cookie('goods_compare['+sid+']', null, { path: '/' });
	
	// обновляем блок, если он на экране
	if ($('#compare-block').length > 0) {
		// удаляем контент
		$('#compare-block #goods-compare').html('');
	}
}

function restore_pass_init(form_id, email_id, pass_id) 
{
	var rp_pass_field = $('#'+form_id+' #'+pass_id);
	var rp_pass_help = rp_pass_field.next('div.help');
	var rp_restore_link = rp_pass_help.children('a.restore_link');
	var rp_pass_result = rp_pass_help.children('span.result');
		
	var rp_email_field = $('#'+form_id+' #'+email_id);
	var rp_email_help = rp_email_field.next('div.help');
	var rp_email_result = rp_email_help.children('span.result');	
	
	ZForms.attachObserver
	(
		ZForms.EVENT_TYPE_ON_INIT,
		function() {
			
			if (!rp_email_field.parents('DL').hasClass('zf-invalid-ok'))
				rp_restore_link.addClass('js-disabled');

			ZForms.attachObserver
			(
				ZForms.EVENT_TYPE_ON_CHANGE,
				function(sEventType, oWidget) 
				{
					if (!rp_email_field.parents('DL').hasClass('zf-invalid-ok')) 
						rp_restore_link.addClass('js-disabled');
					else 
						rp_restore_link.removeClass('js-disabled');
				},
				ZForms.getFormById(form_id).getWidgetById(email_id)
			);
		}
	);	
	
	rp_restore_link.click(function()
	{
		//alert(rp_email_field.val());
		//return false;
		
		if (!rp_email_field.parents('DL').hasClass('zf-invalid-ok')) 
		{
			alert('Введите правильный e-mail');
			rp_email_field.focus();
			return false;
		}

		$.ajax({
			type: "GET",
			dataType : "html", 
			cache: "false",
			data: {email:rp_email_field.val()},
			beforeSend: function(){
				rp_restore_link.text('Восстановление пароля...');
				rp_restore_link.toggleClass('js-loading');
			},
			success: function(data, textStatus){
				rp_restore_link.hide();
				rp_email_help.removeClass('show');
				rp_pass_result.text(" — "+data+".");
				rp_pass_field.focus();
			},
			error: function(data, textStatus){
				rp_restore_link.text('Восстановить пароль');
				
				if(data.responseText.length<250)
				{
					rp_email_help.addClass('show');
					rp_email_result.text(" — "+data.responseText+".");
					rp_email_result.addClass('js-error');
				} else {
					rp_pass_result.text(" — к сожалению, сервис восстановления пароля сейчас не доступен. Вы можете воспользоваться телефоном справочной службы.");
					rp_pass_result.addClass('js-error');
				}
				
				rp_restore_link.toggleClass('js-loading');
				rp_email_field.focus();
			},
			//complete: function(){
				//.TODO 11.08.09 xit костыль жуткий ниже идет...
				//if(rp_form_id=='zf-enter')
					//$('#'+rp_form_id+' DL.checkbox').animate({ top: "+=1" }, "fast");
			//},
			url: rp_pass_result.next('INPUT.restore_url').val()
		});

		return false;
	});
	
}

function setStepAction(href) {
	var formName = $(".zf.zf-inited").attr("name");
	if($("#order").find("dl").hasClass("zf-changed")) {
		if(confirm("Сохранить изменения?")) {
			$("#hd").val(href);
			document.forms[formName].submit();
			return false;
		} else {
			return true;
		}
	} else {
		return true;
	};
}

function setAccessoryFilter(id) {
	$('#'+id).parent().children('a').removeClass('selected').addClass('jsgray');
	$('#'+id).addClass('selected');
	$('.content').children('span.item').each(function(){
		if(!$(this).hasClass(id)) {
			$(this).hide();
		} else {
			$(this).show();
		}
		if(id == 'section_id_0') {
			$(this).show();
		}
	});
	$('.content').children('div.search-sub-category').each(function(){
		if(!$(this).hasClass(id)) {
			$(this).hide();
		} else {
			$(this).show();
		}
		if(id == 'section_id_0') {
			$(this).show();
		}
	});
}

function getOffsetRect(elem) {
   
	 if (elem.getBoundingClientRect) {
			var box = elem.getBoundingClientRect();
		    var body = document.body;
		    var docElem = document.documentElement;
		    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
		    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
		    var clientTop = docElem.clientTop || body.clientTop || 0;
		    var clientLeft = docElem.clientLeft || body.clientLeft || 0;
		    var top  = box.top +  scrollTop - clientTop;
		    var bottom  = box.bottom +  scrollTop - clientTop;
		    var left = box.left + scrollLeft - clientLeft;
		    return { top: Math.round(top), left: Math.round(left), bottom: Math.round(bottom) };
	    
	 } else {
	        var top=0, left=0;
	        while(elem) 
	        {
	            top = top + parseInt(elem.offsetTop);
	            left = left + parseInt(elem.offsetLeft);
	            elem = elem.offsetParent;     
	        }
	     
	        return {top: top, left: left};
	 }

}

//Инициализация помошника по выбору товаров
function init_goods_helper(){

	$(document).ready(function(){
		$('#goods_helper_link').click(function(){
	
			$('#goods_helper').toggle();
			$('.recipe span.arrowdown').toggle();
			
			if(!$('#goods_helper_link span').hasClass('choosed'))
				if($('#goods_helper').css('display')=='block')
					$('#goods_helper_link span').text(':');
				else
					$('#goods_helper_link span').text('...');
				
			return false;
		});
	
		var ontip=false;
		var showing=false;
		var hideTimer = null;
		var showingTimer = null;
		var prevel = null;
	
		$('#goods_helper a.jsspan').click(function(){
			return false;
		});
		
		$('#goods_helper a.variant').hover(function(){
			if (hideTimer) clearTimeout(hideTimer);
			if (showingTimer) clearTimeout(showingTimer);
	
			var curel = this;
			showing = true;
			
			if(prevel != curel)
				$('#popup-tip').animate({opacity:'hide'},100);
			
			showingTimer = setTimeout(function(){
				
				tip = $(curel).next('.tip');
				
				if(tip.hasClass('narrow'))
					$('#popup-tip').addClass('narrow');
				else
					if($('#popup-tip').hasClass('narrow'))
						$('#popup-tip').removeClass('narrow');
				
				$('#popup-tip .middle').html(tip.html());
		
				//x = $(curel).position().left-( $('#popup-tip').width()/2 - $(curel).width()/2 );
				//y = $(curel).parent().position().top-$('#popup-tip').height()+36;
				//br = getOffsetRect(curel);
				x = $(curel).offset().left-( $('#popup-tip').width()/2 - $(curel).width()/2 );
				y = $(curel).offset().top+$(curel).height()-$('#popup-tip').height()-125;
				//alert($(curel).offset().top);
				
				$('#popup-tip').css('left',x+'px');
				$('#popup-tip').css('top',y+'px');
			
				$('#popup-tip').animate({opacity:'show'},200);
	
				setTimeout(function(){
					prevel = curel;
					showing=false;
				},200);
					
			},100);
			
		},function(){
			
			if (hideTimer) clearTimeout(hideTimer);
			if (showingTimer) clearTimeout(showingTimer);
			
			hideTimer = setTimeout(function(){
				if(!ontip && !showing)// 
					$('#popup-tip').animate({opacity:'hide'},200);
			},200)
					
		});
	
		$('#popup-tip').hover(function(){
			ontip = true;
		},function(){
			ontip = false;
			if (hideTimer) clearTimeout(hideTimer);
			
			hideTimer = setTimeout(function(){
				if(!ontip && !showing)// 
					$('#popup-tip').animate({opacity:'hide'},200);
			},200)
		});
		
	});
}

function showOrderDetail(val) {
	if($(val).next("tr.order_detail").css("display") == "none") 
	{
		$(val).children("td:first").children("a.js").html("&ndash;");
		$(val).next("tr.order_detail").fadeIn("medium");
	} 
	else 
	{
		$(val).children("td:first").children("a.js").html("+");
		$(val).next("tr.order_detail").fadeOut("fast");
	}
	return false;
}

function init_order_detail()
{
	$(document).ready(function()
	{
		$('.profile_orders TR.head, .profile_orders a.js').click(function(e){
			e.preventDefault();
			showOrderDetail(this);
		});
	});
}

function init_goods_filter() //блок подбора по хар-м
{
	$(document).ready(function()
	{
		/* показ\сокрытие всего блока подбора по хар-м */
		$('#goods-filters #param_link').click(function()
		{
			//загружаем первый раз
			if(!$('#goods-filters #params_content').hasClass('loaded'))
			{
				$('#params_content').addClass('loading');
				
				$.ajax({
					type: "GET",
					dataType : "html", 
					cache: "false",
					data: {}, //email:email_field.val()
					beforeSend: function(){
					},
					success: function(data, textStatus){
						//впихиваем полученое на страницу:
						$('#params_content .other').html(data);
						
						//Инициализируем zforms
						$('#params').addClass('zf');
						ZForms.buildForm(document.getElementById('params'));
						
						//отображаем
						$('#params_content .brands').show();
						$('#params_content .other').show();
						$('#params .buttons').show();
						$('#params_content').removeClass('loading');
						$('#params_content').addClass('loaded');
						
						add_tip_to_links('#params_content .param .name a.question');
						
						/* Активность\неактивность фильтра характеристики */
						$('#params_content .param .values select').click(function()	
						{
							if(!$(this).parents('.param').hasClass('checked'))
							{
								$(this).parents('.param').addClass('checked');
								$(this).parents('.param').find('.name input:checkbox').attr('checked',true);
							}
						});
						
						/* Проставляем класс checked */
						$('#params_content .param .name input:checkbox').click(function(){
					
							if($(this).is(':checked'))
							{
								$(this).parent().parent().addClass('checked');
							}
							else
							{
								if($(this).parent().parent().hasClass('multiple'))
								{
									$(this).parent().parent().find('.values select option').each(function(){
										$(this).attr('selected',false);
									});							
								}								
								
								$(this).parent().parent().removeClass('checked');
							}
						});
						
						setTimeout(function(){ //Почему-то событие стало возникать сразу после загрузки
							//При изменение слайдера цены ставим галочку.
							ZForms.attachObserver 
							(
								ZForms.EVENT_TYPE_ON_CHANGE,
								function(sEventType, oWidget) 
								{
									if(!$('#price_filter').hasClass('checked'))
									{
										$('#price_filter').addClass('checked');
										$('#price_filter').children('.name').children('input:checkbox').attr('checked',true);
									}
								},
								ZForms.getFormById('params').getWidgetById('price_filter_widget')
							);	
						}, 500);
						
					},
					error: function(data, textStatus){
						if(data.responseText.length<250)
						{
						} else {
							//pass_result.text(" — к сожалению, сервис восстановления пароля сейчас не доступен. Вы можете воспользоваться телефоном справочной службы.");
							//pass_result.addClass('js-error');
						}
					},
					url: $('#params_content').attr('_ajax_url')
				});
			}
			
			prm = $('#goods-filters #params');
			prm.toggle();
			$('#goods-filters .producers').toggle();
			$('#goods-filters .status').toggle();
			$('#goods-filters #param_link a').toggleClass('up');
			
			if(prm.css('display')=='block')
				$('#goods-filters #param_link a b').text('Скрыть');
			else
				$('#goods-filters #param_link a b').text('Подбор по параметрам');

			return false;
		});
	});
}

function init_property_list() //страница всех хар-к
{
	$(document).ready(function()
	{
		$('#property_list .param .name input').click(function(e){
			param = $(this).parent().parent();
			//if(param.attr('id') == 'price_filter') return true;
			
			if(!$(this).is(':checked'))
			{
				param_uncheck(param);
			}
		});
		
		$('#property_list .param .name label').click(function(e){
			param = $(this).parent().parent();
			//if(param.attr('id') == 'price_filter') return true;
			
			e.preventDefault();
			
			if(!param.hasClass('checked'))
			{
				param.addClass('checked');
				$(this).prev('input').show();
				$(this).prev('input').attr('checked', true);
				param.children('.values').show();
			}
			else
			{
				param_uncheck(param);
			}

		});
		
		$('#property_list A#clear_all').click(function(e){
			e.preventDefault();
			$('#property_list .param').each(function(){
				if($(this).hasClass('checked'))
					param_uncheck($(this));
			});
		});
		
		//$('FORM#params').submit(function(){
		//});
		
		add_tip_to_links('#property_list .param .name a.question');
		
		pl_update_submit_position();		
		$(window).scroll(pl_update_submit_position);
		$(window).resize(pl_update_submit_position);
	
		ZForms.attachObserver
		(
			ZForms.EVENT_TYPE_ON_INIT,	function() 
			{
				ZForms.attachObserver 
				(
					ZForms.EVENT_TYPE_ON_CHANGE,
					function(sEventType, oWidget) 
					{
						if(!$('#price_filter').hasClass('checked'))
						{
							$('#price_filter').addClass('checked');
							$('#price_filter').children('.name').children('input:checkbox').attr('checked',true);
						}
					},
					ZForms.getFormById('params').getWidgetById('price_filter_widget')
				);
			}
		);
		
		
	});
}

var posTimer=false;
function pl_update_submit_position()
{
	clearTimeout(posTimer);
	
	posTimer = setTimeout(function(){
		var top = $(window).height()+$(window).scrollTop()-$('#popup_submit').height()-20;
		$('#popup_submit').animate({ top: top+"px" }, 300);
	},600);
}

function param_uncheck(param)
{
	param.removeClass('checked');
	param.find('.name input').attr('checked', false);
	
	if(param.attr('id') == 'price_filter') return true;
	
	param.find('.name input').hide();
	param.children('.values').hide();
	
	param.find('.values select option').each(function(){
		$(this).attr('selected',false);
	});
	
	param.find('.values input:checkbox').each(function(){
		$(this).attr('checked',false);
	});			
}

/*function getCityName(c_name)
{
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) { 
			c_start=c_start + c_name.length+1 ;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
}*/

function calcFirstImgHeight()
{
	gv_maxViewHeight = $('div#div-img').height();
	$('div#div-img').height(gv_maxViewHeight);
	gv_diffView = gv_maxViewHeight - $('img#big-img').height();
	//console.log(gv_maxViewHeight);
	//console.log(gv_diffView);
}

function calcNewImgHeight()
{
	if(gv_heightCalculated) return false;

	//Сохраняем самую большую высоту для блока
	var newHeight = $('img#big-img').height() + gv_diffView;
	//console.log(newHeight);
	
	if( newHeight >= gv_maxViewHeight )
	{
		gv_maxViewHeight = newHeight;
		$('div#div-img').height(gv_maxViewHeight);
	} 
	else
	{
		$('div#div-img').height(gv_maxViewHeight);
	}

	$('img#big-img').animate({ opacity: "show", marginLeft: "0px"}, 100);

	if($.browser.opera)
		setTimeout(function(){// для старой оперы - обновляем рендеринг (замечено в 9.27)
			$('img#big-img').hide();
			$('img#big-img').show();
		}, 115);
	
	gv_heightCalculated = true;
}			

//gv_ means Goods View page
var gv_diffView = gv_maxViewHeight = 0;
var gv_heightCalculated = false;

//gv_ means Goods Property
var gp_prev_pid = null;
var gp_posTimer = false;
function gp_update_position(now)
{
	if(now == true)
	{
		var top = $(window).height()+$(window).scrollTop()-$('#tip-popup').height()-20;
		$('#tip-popup').css('top', top+"px");
		return;
	}
		
	clearTimeout(gp_posTimer);
	
	gp_posTimer = setTimeout(function(){
		var top = $(window).height()+$(window).scrollTop()-$('#tip-popup').height()-20;
		$('#tip-popup').animate({ top: top+"px" }, 300);
	},600);
}

//подсказки к хар-м
function add_tip_to_links(links)
{
	$(links).each(function(){
		$(this).attr('title', 'Показать описание характеристики');
	});
	
	$(links).click(function(e){
		e.preventDefault();
		var prop_id = $(this).attr('id').slice(4);
		
		if($('#tip-popup').css('display')=='block' && prop_id==gp_prev_pid)
			return false;

		if(is_ie6 || is_ie7)
		{
			if(gp_prev_pid==null) //первый запуск
			{
				gp_update_position(true);
				$(window).scroll(gp_update_position);
				$(window).resize(gp_update_position);
			}
			$('#tip-popup').show();
		}
		else 
			if(is_chrome)
				$('#tip-popup').show();
			else
				$('#tip-popup').slideDown();
			
		
		$('#tip-popup #desc').addClass('loading');
		if(!$.browser.msie){
			$('#tip-popup #desc').fadeTo("fast", 0.1, function(){
				$('#tip-popup #desc').html('');
				$('#tip-popup #desc').css("opacity", 1);				
			});
		} 
		else
		{
			$('#tip-popup #desc').html('');
		}
		
		$.get(gp_tip_url+'?pid='+prop_id+"&sid="+gp_sid, function(msg){ 
			if (msg == 'empty') return false;
			
			$('#tip-popup #desc').html(msg);
			
			$('#tip-popup #desc').removeClass('loading');
			
			gp_prev_pid = prop_id;
		});
		
	});
	
	$('#tip-popup .aclose').click(function(){
		$('#tip-popup').fadeOut();
		return false;
	});
}

function init_goods_view()
{
	$(document).ready(function() {

		//подсказки к хар-м
		add_tip_to_links('#pDetail a.js-help, #pGeneral a.js-help');

		// переключалка изображений
		if(is_chrome){
			$('img#big-img').load(calcFirstImgHeight); //это у всех кроме хрома не срабатывает, если картинка загрузилась не из кеша
		}else{//setTimeout(calcFirstImgHeight, 200);
			$('img#big-img').each(function(){
				if (this.complete || this.readyState == 'complete'){  
					calcFirstImgHeight();
				}else{
					$(this).bind('load readystatechange', function(e){
						if (this.complete || (this.readyState == 'complete' && e.type == 'readystatechange')){
							$(this).unbind('load readystatechange');
							calcFirstImgHeight();							
						}
					});
				}
			});
		}
		
		$('.images a').bind('click', function(e) 
		{
			e.preventDefault();

			if($(this).hasClass('open'))
				return false;

			gv_heightCalculated = false;
			

			$('img#big-img').animate({ opacity: "hide", marginLeft: "50px" }, 100);
			
			if($(this).hasClass('it3d'))
			{
				//alert('blya');
				if(!$('.beonoGlobus').hasClass('inited'))
				{
					$('.beonoGlobus').beonoGlobus();
					$('.beonoGlobus').addClass('inited')
				}
				$('.beonoGlobus').show();
			}
			else
			{
				if($('.images a.open').hasClass('it3d'))
					$('.beonoGlobus').hide();
				
				var srcBig = $('img', this).attr('big');
				
				setTimeout(function()	//После hide()
				{
					$('img#big-img').css('margin-left', '-50px');
					//$('img#big-img').load(calcNewImgHeight);	
					//setTimeout(calcNewImgHeight, 200); //еще раз если у кого-то load не сработал
					$('img#big-img').each(function(){						
						$(this).bind('load readystatechange', function(e){
							if (this.complete || (this.readyState == 'complete' && e.type == 'readystatechange')){
								$(this).unbind('load readystatechange');
								calcNewImgHeight();
							}
						});
						$(this).attr('src', srcBig);
					});
				},115);
			}
			
			$('.images a').removeClass('open');
			$(this).addClass('open');
		});

		// переключалка характеристик
		$('.info .title a').bind("click", function(e) {
			e.preventDefault();
			
			$('.info .title a').removeClass('selected');
			$(this).addClass('selected');
			
			// отображаем нужный див
			$(".info div.text").css('display', 'none');
			var div_id = 'p' + this.id.substr(1);
			$(".info div#"+div_id).css('display', '');
		});
		
		//следить за ценой
		$('A#spy_price').click(function(e){
			if($(this).hasClass('disabled')) return false;
			e.preventDefault();
			
			$('#spy_price_popup').fadeIn();
			$('#spy_email').focus();

			$('#spy_price_popup form.zf').submit(function(){
				$('#spy_price_popup .loading').show();
				
				email = $('#spy_email').val();
				$.post(gv_spy_price_url, { goods_id: gv_goods_id, email: email}, function(data){ //city_id: gv_city_id,
					msg = 'Произошла ошибка';
					if(data == 'ok')
						msg = 'Вы подписаны на уведомление.';
					else if(data == 'already')
						msg = 'Данный e-mail уже был подписан.';
					
					$('#spy_price_popup div.middle form.zf').html(msg);
					$('#spy_price_popup form.zf').addClass('only-message');
					
					$('#spy_price_popup .loading').hide();
					
					$('A#spy_price b').html('Вы следите за ценой товара');
					$('A#spy_price').addClass('disabled');
					setTimeout(function(){
						$('#spy_price_popup').fadeOut();
					},2000); 
				});

				return false;
			});
			
			$('#spy_price_popup .aclose').click(function(){
				$('#spy_price_popup').fadeOut();
				return false;
			});

		});
		
		
	});
}

var hp_goods_url = '';
function init_home_page(goods_url)
{
	hp_goods_url=goods_url;

	$(document).ready(function() {
		$('.special .need-tab').click(function() {
			var t = $(this).parent().parent().attr("_tab");
			url = getUrlByTab(t);
			
			$(".special a.all").attr('href', url);
		});
		
		// начальная вкладка
		var sel_tab = $(".special li.selected");
		if (sel_tab.length == 0)
			sel_tab = $(".special li:first").addClass('selected');
		
		$(".special a.all").attr('href', getUrlByTab(sel_tab.attr('_tab')));
		$(".special .content div").removeClass('show');
		$(".special .content div."+sel_tab.attr('_tab')).addClass('show');
	});
}

function getUrlByTab(t) 
{
	if (t == 'price-spec')
		hp_goods_url += '/-bestprice';
	else if (t == 'search-spec')
		hp_goods_url += '/-theone';
	else if (t == 'new-spec')
		hp_goods_url += '/-new';
		
	return hp_goods_url;
}


function ratePhoto(object_type, object_id, value, slug){
	$('#rate-'+object_id).toggleClass('loading');
	$('#rate-'+object_id+'-lb').toggleClass('loading');
	$.ajax({
		url: '../../ajax/news/RateObject?object_type='+object_type+'&object_id='+object_id+'&rate='+value+'&slug='+slug,
		success: function(response) {
			$('#rate-'+object_id+' a').each(function(){
				$(this).toggleClass('vi-h');
			});
			$('#rate-'+object_id+' a-lb').each(function(){
				$(this).toggleClass('vi-h');
			});
			$('#rate-'+object_id).toggleClass('loading');
			$('#rate-'+object_id+'-lb').toggleClass('loading');
		}		
	});	
}


function isChildOf(el, filter_string){
	var parents = el.parents().get();         
	for (var i=0;i<parents.length;i++){
		if($(parents[i]).is(filter_string))	return true;		
	}
	return false;
}

$(function(){
	var onp = {h : 'Интернет цена', b: 'Цена действует при заказе через Интернет.'};
	var ofp = {h : 'Розничная цена', b: 'Цена действует при покупке в розничном магазине.'};
	var spp = {h : 'Спецпредложение', b: 'Цена действует при покупке в розничном магазине, цена окончательная'};
	$('div.price a').data('ct0', ofp);
	$('tr.spc div.price a').data('ct0', spp);	
	$('table.dp div.price a').data('ct0', onp);
	$('table.dps div.price a').data('ct0', ofp);
	$('tr.spc table.dps div.price a').data('ct0', spp);
	$('div.price a').click(function(e){		
			var ontip = false;
			var showing = false;
			var hideTimer = null;
			var showingTimer = null;
			var prevel = null;	
			if (hideTimer) clearTimeout(hideTimer);
			if (showingTimer) clearTimeout(showingTimer);	
			var curel = this;
			showing = true;
			var txt = '<h3>'+$(this).data('ct0').h+'</h3>'
						+$(this).data('ct0').b;
			if(prevel != curel) $('#popup-tip-price').animate({opacity:'hide'},100);			
			$('body').click(function(e){				
				if (!isChildOf($(e.target),'#popup-tip-price')){
					if (hideTimer) clearTimeout(hideTimer);
					if (showingTimer) clearTimeout(showingTimer);
					hideTimer = setTimeout(function(){
						if(!ontip && !showing) $('#popup-tip-price').animate({opacity:'hide'},200);
					},200);
				}
			});			
			$('#popup-tip-price a.x-close').click(function(e){
				if (hideTimer) clearTimeout(hideTimer);
				if (showingTimer) clearTimeout(showingTimer);
				hideTimer = setTimeout(function(){
					if(!ontip && !showing) $('#popup-tip-price').animate({opacity:'hide'},200);
				},200);
				return false;
			});
			showingTimer = setTimeout(function(){
				$('#popup-tip-price .middle').html(txt);
				x = $(curel).offset().left-( $('#popup-tip-price').width()/2 - $(curel).width()/2 );
				y = $(curel).offset().top+$(curel).height()-$('#popup-tip-price').height() - 25;				
				$('#popup-tip-price').css('left',x+'px');
				$('#popup-tip-price').css('top',y+'px');			
				$('#popup-tip-price').animate({opacity:'show'},200);	
				setTimeout(function(){
					prevel = curel;
					showing=false;
				},200);					
			},100);	
		return false;
	});	
	
	var jQBanners = {arr: []};
	$('.bannerJq').each(function(){
		jQBanners[$(this).attr('bId')] = $(this).attr('id');
		jQBanners.arr.push($(this).attr('bId'));
	});
	$.getJSON('/ajax/home/loadBanners?ihsection='+$('#ihsection').val()+'&load='+$.toJSON(jQBanners.arr), function(ret) {
		  $.each(ret,function(k,v){
					if(v){
						var ie6Fix = $('div.ie6BannerFix',$(v[0].html));
						if(ie6Fix.length>0){
							var params = $.evalJSON(ie6Fix.text());
								$('#'+jQBanners[k]).html();
								$('#'+jQBanners[k]).flash({
									swf: params[0],
									width: params[1],
									height: params[2],
									wmode: 'opaque',
									allowScriptAccess: 'never'
								});						
						}else{
							$('#'+jQBanners[k]).html(v[0].html);
							$('#'+jQBanners[k]).show();
						}
					}else{
						if($('#'+jQBanners[k]).parent().hasClass('uberfooter-banners')){
							$('.uberfooter-banners').css('margin-left', (parseInt($('.uberfooter-banners').css('margin-left').replace(/px/,'')) + 115) + 'px');						
						}
						$('#'+jQBanners[k]).remove();					
					}
				});
	});

	/*$.ajax({
		url: '/ajax/home/loadBanners',
		type: 'GET',
		data: 'ihsection='+$('#ihsection').val()+'&load='+$.toJSON(jQBanners.arr),
		success: function(r){
			//var ret = $.evalJSON(r);
			eval('var ret ='+r);
			$.each(ret,function(k,v){
				if(v){
					var ie6Fix = $('div.ie6BannerFix',$(v[0].html));
					if(ie6Fix.length>0){
						var params = $.evalJSON(ie6Fix.text());
							$('#'+jQBanners[k]).html();
							$('#'+jQBanners[k]).flash({
								swf: params[0],
								width: params[1],
								height: params[2],
								wmode: 'opaque',
								allowScriptAccess: 'never'
							});						
					}else{
						$('#'+jQBanners[k]).html(v[0].html);
						$('#'+jQBanners[k]).show();
					}
				}else{
					if($('#'+jQBanners[k]).parent().hasClass('uberfooter-banners')){
						$('.uberfooter-banners').css('margin-left', (parseInt($('.uberfooter-banners').css('margin-left').replace(/px/,'')) + 115) + 'px');						
					}
					$('#'+jQBanners[k]).remove();					
				}
			});
		}
	});*/
	
});
