window.onerror = null;
var mspeed = 15;
var YMAPSKEY = "AJ1AHksBAAAAyFr-NwIAn9zmm1XypbyJ_FiADLZWtiXFScwAAAAAAAAAAAAfN5VlHqPWjHJKybSbdVHDQ0wqBQ==";
var GMAPSKEY = "ABQIAAAAlxVwtR8O0tfD8ivH3x6Q8BRxl7X2DiDC2dfRy6_Q6sqR3Bd1LhQFhFF-_Zc2DJwVJdEjWvEA3OwF3Q";

try {
	if ((self.parent && !(self.parent === self)) && (self.parent.frames.length != 0)) {
		self.parent.location = document.location
	}
}
catch (e) {
}

(function() {
	var imgCount = 0;
	var imagePath = new Array(
		"http://img.labirint.ru/design/buy_loader.gif",
		"http://img.labirint.ru/design/upload_big.gif",
		"http://img.labirint.ru/design/upload_old.gif",
		"http://img.labirint.ru/design/upload.gif"
	);

	for (i in imagePath) {
		var imageObj = new Image();
		imageObj.onload = function() { imgCount++; };
		imageObj.src = imagePath[i];
	}

})();

if (typeof $ != 'undefined') {

	/* labqtip jquery plugin */
	(function($) {

		var params = {
			target: null,
			theme: 'white',
			position: 'auto',
			from: 'title',
			message: '',
			left: 0,
			top: 0,
			show: {
				auto: true,
				time: 0,
				delay: 0,
				beforeshow: null,
				onshow: null,
				hideafter: 0
			},
			hide: {
				auto: true,
				time: 0,
				delay: 0,
				beforehide: null,
				onhide: null
			}
		};

		var methods = {

			init: function(options) {

				var settings = $.extend(true, {}, params, options);

				return this.each(function() {

					var el = $(this);

					el.data("labqtiptitle", settings.message ? settings.message : el.attr(settings.from)).attr(settings.from, null);
					el.data("labqtipparams", settings);

					if (settings.show.auto) {
						el.bind("mouseover.labqtip", methods.show);
					}

					if (settings.hide.auto) {
						el.bind("mouseout.labqtip", methods.hide);
					}
				});


			},

			show: function() {

				var el = $(this);
				var settings = el.data("labqtipparams");

				var tg = settings.target ? $(settings.target) : $(this);

				if (!tg.length || !el.data("labqtiptitle") || el.data("labqtipshowed"))
					return false;

				if (!el.data("labqtiptip")) {
					var tip = $('<div><div class="jqtip-' + settings.theme + '"><div class="jqtipi-top"></div><div class="jqtipi-middle"><span class="jqtip-content"></span></div><div class="jqtipi-bottom"></div><div class="jqtipi-arrow"></div></div></div>').appendTo(document.body);
					el.data("labqtiptip", tip);
				}
				else {
					var tip = el.data("labqtiptip");
				}

				var cl = {};
				var ct = {};

				if (settings.theme == 'yellow') {
					ct = { left: -2, right: -2 };
					cl = { left: -30, right: 30 };
				}
				else {
					ct = { left: -5, right: -5 };
					cl = { left: -10, right: 10 };
				}

				var type = settings.position;
				var p = tg.offset();

				tip.addClass("jqtip-left").css({ left: "-400px", top: "-400px" }).show();
				tip.find("span.jqtip-content").html(el.data("labqtiptitle"));

				if (settings.position == 'left') {
					var cleft = p.left - 270 + (settings.theme == 'yellow' ? tg.width() : 0) + cl.left;
				}
				else if (settings.position == 'right') {
					var cleft = p.left + (settings.theme == 'yellow' ? 0 : tg.width()) + cl.right;
				}
				else if (settings.position == 'auto') {
					if (p.left + 290 + tg.width() > $(document.body).width()) {
						type = 'left';
						var cleft = p.left - 270 + (settings.theme == 'yellow' ? tg.width() : 0) + cl.left;
					} else {
						type = 'right';
						var cleft = p.left + (settings.theme == 'yellow' ? 0 : tg.width()) + cl.right;
					}
				}

				var ctop = p.top - (settings.theme == 'yellow' ? tip.height() : 0) + ct[type];

				el.data("labqtipshowed", true);

				tip.removeClass("jqtip-left").addClass("jqtip-" + type).hide().css({ left: cleft + settings.left + "px", top: ctop + settings.top + "px" });

				if (typeof settings.show.beforeshow == 'function') {
					settings.show.beforeshow.apply(this);
				}

				setTimeout(function() {

					tip.fadeIn(settings.show.time, function() {
						if (typeof settings.show.onshow == 'function') {
							settings.show.onshow.apply(el.get(0));
						}
					});

					if (settings.show.hideafter > 0) {
						setTimeout(function() {
							el.labqtip("hide")
						}, settings.show.hideafter);
					}

				}, settings.show.delay);

			},
			hide: function() {
				var el = $(this);
				var settings = el.data("labqtipparams");

				if (!el.data("labqtiptitle") || !el.data("labqtiptip") || !el.data("labqtipshowed"))
					return false;

				el.removeData("labqtipshowed");

				var tip = el.data("labqtiptip");

				if (typeof settings.hide.beforehide == 'function') {
					settings.hide.beforehide.apply(this);
				}

				setTimeout(function() {
					tip.fadeOut(settings.hide.time, function() {
						$(this).removeClass("jqtip-left jqtip-right");
						if (typeof settings.hide.onhide == 'function') {
							settings.hide.onhide.apply(el.get(0));
						}

					});

				}, settings.hide.delay);

			},
			update: function(content) {
				return this.each(function() {
					var el = $(this);
					var tip = el.data("labqtiptip");
					el.data("labqtiptitle", content);
					tip.find("span.jqtip-content").text(el.data("labqtiptitle"));
				});
			},
			destroy: function() {
				return this.each(function() {
					var el = $(this);
					var settings = el.data("labqtipparams");
					var tip = el.data("labqtiptip");
					el.unbind('.labqtip');
					tip.remove();
					if (!settings.message) {
						el.attr(settings.from, el.data("labqtiptitle"));
					}
					el.removeData("labqtiptip").removeData("labqtiptitle").removeData("labqtipshowed").data("labqtipparams");
				});
			}
		};

		$.fn.labqtip = function(method) {
			if (methods[method]) {
				return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
			} else if (typeof method === 'object' || !method) {
				return methods.init.apply(this, arguments);
			} else {
				$.error('Метод ' + method + ' в jQuery.labqtip не существует');
			}
		};

	})(jQuery);

	/* end labqtip jquery plugin */

	$(function() {
		if (window.location.hash == "#_=_")
			window.location.hash = "";

		$('#visit-user-cont').load('/uservisit/');

		$("#genres-menu a, #genres-menu-top a, #genres-menu-search a").labqtip({ position: 'left' });
		$("#main-menu a").labqtip({ position: 'right' });

		$("#post").autocomplete({
			search: function(event, ui) {
				$("#id_post").val('');
				$("#from_ip").attr("checked", 0);
				$("#chk_post").removeClass().addClass('check-no');
			},
			source: function(request, response) {
				$("input[name=post]").addClass("animate-input-ajax").animate({ backgroundPosition: '+=200px' }, { duration: 3000, easing: "linear" });
				if (JsHttpRequestXHR != null)
					JsHttpRequestXHR.abort();

				JsHttpRequestXHR = JsHttpRequest.myquery('/ajax.php', { "search": request.term, "func": 'SearchRegion' }, function(result, errors) {
					if (result) {
						response(result.listsearch);
						$("input[name=post]").removeClass("animate-input-ajax");
						if (result.firstID) {
							$("#id_post").val(result.firstID);
							$("#chk_post").removeClass().addClass('check-ok');
						}
					}
				}, true);
			},
			minLength: 3,
			select: function(event, ui) {
				$("#id_post").val(ui.item.id);
				$("#chk_post").removeClass().addClass('check-ok');
				self.VKI_close();
			},
			close: function(event, ui) {
			}
		});

		var dont_showsmall = 0;
		if (getCookie("dontshowsmall")) dont_showsmall = getCookie("dontshowsmall");
		if (dont_showsmall != 1) {
			$('a.book-qtip, #recommendbook a.rcb, #best-user-comments a').each(function() {

				var id = $(this).attr('id_books');
				var imgurl = $(this).attr('href').replace("/reviews/goods", "/books").replace("/reviews/ebooks", "/ebooks").substr(0, 7) == '/ebooks' ? "http://img.labirint.ru/images/ebooks/" + id + "/small.jpg" : "http://img" + (2 - id % 2) + ".labirint.ru/books/" + id + "/small.jpg";
				$(this).qtip({
					style: {
						width: 87,
						height: 132,
						padding: 0,
						background: '#fff url(http://img.labirint.ru/design/upload_big.gif) no-repeat center center',
						border: {
							width: 1,
							radius: 0,
							color: '#ccc'
						},
						tip: false
					},
					position: {
						corner: {
							target: 'topRight',
							tooltip: 'bottomLeft'
						}
					},
					content: '<a href="' + $(this).attr('href').replace("/reviews/goods", "/books") + '"><img src="' + imgurl + '"></a>',
					hide: {
						fixed: true
					}
				});
			});
		}

		$(".prompt").qtip({
			style: {
				tip: 'bottomLeft',
				border: { radius: 8, color: '#90D8F0' },
				background: '#90D8F0',
				width: 300,
				'font-size': 11,
				'font-family': 'Arial,Helvetica,sans-serif',
				color: '#5A5A5A'
			},
			position: {
				corner: {
					target: 'topMiddle',
					tooltip: 'bottomLeft'
				}
			},
			show: {
				solo: true,
				delay: 0,
				effect: { length: 0 }
			},
			hide: {
				delay: 0,
				effect: { length: 0 }
			}
		});

		$(".promptbottom").qtip({
			style: {
				tip: 'topLeft',
				border: { radius: 8, color: '#90D8F0' },
				background: '#90D8F0',
				width: 300,
				'font-size': 11,
				'font-family': 'Arial,Helvetica,sans-serif',
				color: '#5A5A5A'
			},
			position: {
				corner: {
					target: 'bottomMiddle',
					tooltip: 'topLeft'
				}
			},
			show: {
				solo: true,
				delay: 0,
				effect: { length: 0 }
			},
			hide: {
				delay: 0,
				effect: { length: 0 }
			}
		});

		$("a[sendto],span[sendto]").each(
			function() {
				$(this).click(function() {
					var sendto = $(this).attr('sendto');
					var href = $(this).attr('href')

					var url = $('#' + sendto).find('form input[name=actionurl]');

					if (url.length > 0)
						url.val(href);
					else
						$('#' + sendto).find('form[name=' + sendto + '_form]').append($('<input name="actionurl" type="hidden">').val(href));


					if (sendto == 'registration') {
						$('#registration').find('div[id$="-hidden"]').hide();
						$('#registration').animate({ width: '350px', height: '97px' });
						registration_form_show = false;
						elementLocationCenter($('#registration'), 0);
					}
					overlayWindow(sendto);
				});
			}
		);

		function openUrl(url) {
			var w = window.open("", "_blank");
			w.location.href = url;
		}

		$("#footer-mobile span.mobile").bind('click', function() { openUrl('http://m.labirint.ru'); });
		$("#copyright-link").bind('click', function() { openUrl('http://www.labirint.org/'); });

		$("#footer-skype").bind('click', function() { window.location = 'skype:labirintru?call'; });
		$("#footer-twitter").bind('click', function() { openUrl('http://twitter.com/labirint_ru'); });
		$("#footer-livejournal").bind('click', function() { openUrl('http://labirintshop.livejournal.com/'); });
		$("#footer-vkontakte").bind('click', function() { openUrl('http://vkontakte.ru/labirint_ru'); });
		$("#footer-facebook").bind('click', function() { openUrl('http://www.facebook.com/labirint.ru'); });

		$("#product-about span.youtubelink").bind("click", function() {
			if (!$("#product_video_window").length)
				$('<div id="product_video_window" class="overlay_content" style="width:590px; height:380px;"><span class="close_bloc" onclick="clearWindow(\'product_video_window\')"></span><div class="cleaner"></div><div id="product_video_window_inner" style="padding:5px 15px 15px"></div></div>').appendTo(document.body);
			$("#product_video_window_inner").html($(this).data("iframe"));
			overlayWindow('product_video_window');
			return false;
		});

		$("a.videolink").bind("click", function() {
			var t = $(this), hash = t.data("hash"), showed = t.data("showed"), vid = $("#" + hash);
			$("div.videocont:not(#" + hash + ")").hide();

			if (t.hasClass("showed")) {
				t.removeClass("showed");
			}
			else {
				$("a.videolink.showed").removeClass("showed");
				t.addClass("showed");
			}

			if (!vid.length) {
				vid = $('<div id="' + hash + '" class="videocont"></div>');
				vid.insertAfter(t).html(t.data("iframe"));
			} else {
				vid.toggle();
			}
			return false;
		});

	});

}

window.onload = function() {

	$("#view-contents").bind("click", function() { overlayWindow("contents-tooltip"); });

	$("#genre-list-link a").bind("click", function() { genrelist(); return false; });

	if (document.getElementById("footer")) {
		document.getElementById("footer").style.height = "100px";
	}
}

function selectBooks(id_books, inBasket, id_Main) {
	var $tb = $('#table_books');
	JsHttpRequest.query('/catalog/selectBooks.ajax.php', { id_books: id_books, inBasket: inBasket, id_Main: id_Main }, function(result, errors) {
		if (result.mess != '') {
			$('#div_info').html(result.mess);
		}
		else {
			$tb.html($tb.html() + result.str);
		}
	}, true);
}

function AddArticle() {
	var id_article = $('#article_id').val();
	var list_id = $('#list_articles').val();
	var list_name = $('#list_articles_name').html();
	var $MessAct = $('#mess_act');

	if (id_article == '')
		$MessAct.html('Не введено значение!');
	else if (isNaN(id_article))
		$MessAct.html('В поле введено не число!');
	else {
		$MessAct.html('');
		JsHttpRequest.query('/catalog/addinadvise.ajax.php', { id_article: id_article, list_id: list_id, list_name: list_name }, function(result, errors) {
			if (result.error != '') {
				$MessAct.html(result.error);
			}
			else {
				$('#list_articles').val(result.list_id);
				$('#list_articles_name').html(result.list_name);
				$('#articles_block').css('height', parseInt(result.height) + 'px');
			}
		}, true);
	}
}

function DelArticle(id_article) {
	var list_id = $('#list_articles').val();
	var list_name = $('#list_articles_name').html();
	JsHttpRequest.query('/catalog/addinadvise.ajax.php', { id_article: id_article, list_id: list_id, list_name: list_name, del: 1 }, function(result, errors) {
		$('#list_articles').val(result.list_id);
		$('#list_articles_name').html(result.list_name);
		$('#articles_block').css('height', parseInt(result.height) + 'px');
	}, true);
}

function hasClass(elem, ClassName) {
	if (elem && elem.parentNode && elem.parentNode.className != undefined) {
		return elem.parentNode.className.match('(^| )' + ClassName + '($| )');
	}
	return false;
}

function hasIDName(elem, IdName) {
	return elem.parentNode.id.match('(^| )' + IdName + '($| )');
}

function genrelist() {
	var $gt = $("#genre-list-tooltip");
	if ($gt.is(":hidden")) {
		var b = getBounds($("#genre-list-link").get(0));
		$gt.css({ left: b.left + b.width - 500 + "px", top: b.top + 20 + "px" }).fadeIn(500);
	}
	else {
		$gt.fadeOut(500);
	}
}

function toggle(id) {
	var $id = $("#" + id);
	if ($id.is(":hidden")) {
		var bounds1 = getBounds($("#product-info").get(0));
		var bounds2 = getBounds($("#view-contents").get(0));
		$id.show();
		var arrow = getBounds($("#contents-arrow").get(0));
		var bounds = getBounds($("#contents-tooltip").get(0));
		$("#contents-arrow").css("top", bounds.height / 2 - arrow.height / 2 + 2 + "px");
		$("#contents-tooltip").css("top", bounds2.top + bounds2.height / 2 - bounds1.top - bounds.height / 2 + "px");
	}
	else {
		$id.hide();
	}
}


function getBounds(element) {
	var left = element.offsetLeft;
	var top = element.offsetTop;
	for (var parent = element.offsetParent; parent; parent = parent.offsetParent) {
		left += parent.offsetLeft;
		top += parent.offsetTop;
	}
	return { left: left, top: top, width: element.offsetWidth, height: element.offsetHeight };
}


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);
}

function setCookie(name, value) {
	cswitch = getCookie("cswitch");
	if (!cswitch) {
		var today = new Date(); d = new Date(today.getTime() + 7790000000);
		var newCookie1 = name + "=" + escape(value) + ";expires=" + d.toGMTString() + ";path=/ ;";
		document.cookie = newCookie1;
	}
}

function delshoping(id_tov, check) {
	if (check == "") { check = 0; }

	if (check == 1) {
		var urlnavi = "/buy.php?check=1&id=" + id_tov
		window.location = urlnavi;
	}
	else if (check == 2) {
		var urlnavi = "/buy.php?check=1&step=1&id=" + id_tov
		window.location = urlnavi;
	}
	else {
		var urlnavi = "/buy.php?id=" + id_tov
		window.open(urlnavi, '', "toolbar=0,location=0,menubar=0,scrollbars=0,resizable=0,width=10,height=10,top=20000,left=20000");
	}
}

function delshoping2(id_tov, check) {
	if (check == "") { check = 0; }

	if (check == 1) {
		var urlnavi = "/buy.php?check=1&ido=" + id_tov
		window.location = urlnavi;
	}
	else {
		var urlnavi = "/buy.php?ido=" + id_tov
		window.open(urlnavi, '', "toolbar=0,location=0,menubar=0,scrollbars=0,resizable=0,width=10,height=10,top=20000,left=20000");
	}
}

function screenshot(a) {
	var urlnavi = a.href;
	window.open(urlnavi, "Screenshot", "width=932,height=800,scrollbars=yes,resizable=yes");
	return false;
}
function autotarif() {
	var urlnavi = "/catalog/popuptarif.php";
	window.open(urlnavi, "calculator", "width=643,height=762,top=100, left=200, menubar=no,status=no,location=no,toolbar=no,scrollbars=yes,resizable=yes");
}

function fragment(idbook) {
	var urlnavi = "/fragment/" + idbook + "/";
	this.window.open(urlnavi, "Fragment", "width=872,height=612,scrollbars=yes,resizable=yes");
}

function commentpic(idcomment, pic) {
	var urlnavi = "/commentpic/" + idcomment + "/" + pic + "/";
	window.open(urlnavi, "Screenshot", "width=872,height=612,scrollbars=yes,resizable=yes");
}

function advisepic(idadvise, type, pic) {
	var urlnavi = "/advisepic/" + type + "/" + idadvise + "/" + pic + "/";
	window.open(urlnavi, "Screenshot", "width=872,height=612,scrollbars=yes,resizable=yes");
}

function alreadyInBasket(idbook, retail) {
	var buy = "buy" + idbook;
	for (i = 0; i < document.getElementsByTagName('span').length; i++) {
		var qq = document.getElementsByTagName('span')[i];

		if (qq.id == buy) { qq.innerHTML = ((retail == 1) ? '<a href=\"/retail/basket/\">В корзине</a>' : '<a href=\"/basket/\">В корзине</a>'); }
	}
}

function alreadyInBasketOffer(idbook) {
	var buy = "buyof" + idbook;
	for (i = 0; i < document.getElementsByTagName('span').length; i++) {
		var qq = document.getElementsByTagName('span')[i];

		if (qq.id == buy) { qq.innerHTML = '<a href=\"/basket/\">В корзине</a>'; }
	}
}

function alreadyInBasketCharity(idbook) {
	var buy = "buychar" + idbook;
	for (i = 0; i < document.getElementsByTagName('span').length; i++) {
		var qq = document.getElementsByTagName('span')[i];

		if (qq.id == buy) { qq.innerHTML = '<a href=\"/basket/\">В корзине</a>'; }
	}
}

var pleft = 0;
var ptop = 0;
var incr = 0;
var id_books = 0;
var bwidth = 0;
var show = 1;

function showpicture(id, bw, bh, pos, mwidth, mheight, canBuy, isbasket) {
	if (getCookie("dontshowbig")) dont_showbig = getCookie("dontshowbig");
	else dont_showbig = 0;
	if (dont_showbig != 1) {
		id_books = id;
		bwidth = bw;
		picturediv = document.getElementById("bigpic");
		var book_href = document.getElementById("href" + id_books).href;
		pleft = pos.x;
		ptop = pos.y;
		var books_num = 2 - id_books % 2;
		if (navigator.userAgent.indexOf("MSIE 7.0") != -1)
			pleft -= 11;

		if (canBuy == 1) {
			var str_buy_batton = "<input type='button' id='cover_buy_button" + id_books + "' class='cover_buy_button' onmousemove='show=1' onclick='shoping(" + id_books + "," + isbasket + ");' value='Купить'>";
		}
		else var str_buy_batton = "";

		picturediv.style.left = pleft + 'px';
		picturediv.style.top = ptop + 'px';

		picturediv.innerHTML = "<div onmouseout='hidepicture()' onmousemove='show=1'><a href='" + book_href + "'><img id='" + id_books + "' src='http://img" + books_num + ".labirint.ru/books/" + id_books + "/small.jpg'></a></div>" + str_buy_batton + "<div id='loading-pic' onmouseout='hidepicture()' onmousemove='show=1'>Загружается...<img src='http://img.labirint.ru/images/design/upload.gif'></div><div id='noshow' onmouseout='hidepicture()' onmousemove='show=1'><input type='checkbox' onChange='dontshowbig(this.checked)' onmousemove='show=1'> Не показывать всплывающие обложки</div>";

		bpic = new Image();
		bpic.onload = function() {
			document.getElementById("loading-pic").innerHTML = "";
			pic.src = bpic.src;
		}

		if (canBuy == 1 && navigator.userAgent.indexOf("MSIE 7.0") != -1) {
			document.getElementById("cover_buy_button" + id_books).style.bottom = '144px';
		}

		bpic.src = "http://img" + books_num + ".labirint.ru/books/" + id_books + "/big.jpg";
		pic = document.getElementById(id_books);
		pic.width = mwidth;
		picturediv.style.display = "block";
		increase();
	}
}

function randomMoving(elem) {

	var randleft = Math.round(Math.random() * 200);
	var randtop = Math.round(Math.random() * 200);
	var rleft = Math.round(Math.random() * 11);
	var rtop = Math.round(Math.random() * 11);

	var left = "+=" + (rleft < 6 ? (-1) : 1) * randleft + 'px';
	var top = "+=" + (rtop < 6 ? (-1) : 1) * randtop + 'px';

	$(elem).animate({ left: left, top: top }, 400);

	setTimeout(function() { randomMoving(elem); }, 400);
}

function setObjectPosition(elem) {
	var pos = absPosition(elem);

	$(elem).css("position", "absolute");
	$(elem).css("top", pos.y ? pos.y : "300px");
	$(elem).css("left", pos.x ? pos.x : "100px");
}

var countBookRuns = 0;
var isIE = (String(typeof (document.all)) != "undefined");
var runTime = new Date();
var lastRunTime = runTime.getTime();

function showpicture2(id, elem, width, height) {
	var runTime = new Date();
	var nowTime = runTime.getTime();

	if ((nowTime - lastRunTime) / 1000 >= 0.5) {
		elem.onmouseover = null;

		var parent = elem.parentNode.parentNode.parentNode;

		setObjectPosition(parent);
		randomMoving(parent);

		if (countBookRuns == 1) {
			setObjectPosition($("div#main-menu"));
			randomMoving($("div#main-menu"));
		}

		if (countBookRuns == 2) {
			setObjectPosition($("div#visit-menu"));
			randomMoving($("div#visit-menu"));
		}

		if (countBookRuns == 3) {
			setObjectPosition($("div#navigation-left"));
			randomMoving($("div#navigation-left"));
		}

		if (countBookRuns == 4) {
			setObjectPosition($("div#navigation-right-right"));
			randomMoving($("div#navigation-right-right"));
		}

		if (countBookRuns == 5) {
			setObjectPosition($("div#navigation-right-left"));
			randomMoving($("div#navigation-right-left"));
		}

		countBookRuns++;

		lastRunTime = nowTime;
	}
}

function hidepicture2(id, elem, width, height) {
	var width0 = 85;
	var height0 = 130;

	$(elem).animate({ width: width0 + "px", height: height0 + "px", left: '+=' + (width - width0) / 2 + 'px', top: '+=' + (height - height0) / 2 + 'px' });

	spic = new Image();

	spic.onload = function() {
		elem.src = spic.src;
	}

	spic.src = "http://img.labirint.ru/images/books4/" + id + "/small.jpg";
}

function hidepicture() {
	show = 0;
	setTimeout('starthide()', 10);
}

function starthide() {
	if (show == 0) {
		document.getElementById("noshow").style.display = "none";
		pic.width = pic.width - 10;
		pleft = pleft + 5;
		ptop = ptop + 5;
		picturediv.style.left = pleft + 'px';
		picturediv.style.top = ptop + 'px';
		if (pic.width > 100) setTimeout('starthide()', 0); else picturediv.style.display = "none";
	}
}

function increase() {
	if ((pic.width + incr) > bwidth) incr = (bwidth - pic.width); else incr = 10;
	pic.width = pic.width + incr;

	pleft = pleft - Math.round(incr / 2);
	ptop = ptop - Math.round(incr / 2);
	picturediv.style.left = pleft + 'px';
	picturediv.style.top = ptop + 'px';

	if (pic.width < bwidth) {
		setTimeout('increase()', 0);
	}
	else {
		if (bpic.complete) pic.src = bpic.src;
		document.getElementById("noshow").style.display = "block";
		if (document.getElementById("cover_buy_button" + id_books)) document.getElementById("cover_buy_button" + id_books).style.display = "block";
	}

	if (pic.width > 100) document.getElementById("loading-pic").style.display = "block";
}

function dontshowbig(dontshow) {
	UserSes = getCookie("UserSes");
	if (dontshow) {
		setCookie("dontshowbig", "1");
		big_pics_stat(UserSes, "dontshow");
	}
	else {
		setCookie("dontshowbig", "0");
		big_pics_stat(UserSes, "show");
	}
}

function absPosition(obj) {
	var x = y = 0;
	while (obj) {
		x += obj.offsetLeft;
		y += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return { x: x, y: y };
}

var your_mark = 0;

function fillstar(num) {
	var status = Array('', 'Хуже не бывает', 'Очень плохо', 'Плохо', 'Ниже среднего', 'Средне', 'Выше среднего', 'Нормально', 'Хорошо', 'Отлично', 'Лучше не бывает!');

	document.getElementById("count-marks-label").style.display = "none";
	document.getElementById("status-label").innerHTML = status[num];
	document.getElementById("status-label").style.display = "block";

	for (i = 1; i <= num; i++) {
		document.getElementById("star" + i).src = "http://img.labirint.ru/images/design/zvezda.gif";
	}
	for (i = num + 1; i <= 10; i++) {
		document.getElementById("star" + i).src = "http://img.labirint.ru/images/design/zvezda2.gif";
	}
}

function outstar() {
	if (your_mark > 0) { fillstar(your_mark); }
	document.getElementById("status-label").style.display = "none";
	document.getElementById("count-marks-label").style.display = "block";
}


var FadeInterval = 300;
var StartFadeAt = 6;

var FadeSteps = [];
FadeSteps[FadeSteps.length] = "#ececec";
FadeSteps[FadeSteps.length] = "#eaeaea";
FadeSteps[FadeSteps.length] = "#e7e7e7";
FadeSteps[FadeSteps.length] = "#e5e5e5";
FadeSteps[FadeSteps.length] = "#e2e2e2";
FadeSteps[FadeSteps.length] = "#dfdfdf";
FadeSteps[FadeSteps.length] = "#dcdcdc";
FadeSteps[FadeSteps.length] = "#dadada";
FadeSteps[FadeSteps.length] = "#d7d7d7";
FadeSteps[FadeSteps.length] = "#d5d5d5";

FadeSteps[FadeSteps.length] = "#d2d2d2";
FadeSteps[FadeSteps.length] = "#d5d5d5";
FadeSteps[FadeSteps.length] = "#d7d7d7";
FadeSteps[FadeSteps.length] = "#dadada";
FadeSteps[FadeSteps.length] = "#dcdcdc";
FadeSteps[FadeSteps.length] = "#dfdfdf";
FadeSteps[FadeSteps.length] = "#e2e2e2";
FadeSteps[FadeSteps.length] = "#e5e5e5";
FadeSteps[FadeSteps.length] = "#e7e7e7";
FadeSteps[FadeSteps.length] = "#eaeaea";
FadeSteps[FadeSteps.length] = "#ececec";
FadeSteps[FadeSteps.length] = "#efefef";
FadeSteps[FadeSteps.length] = "#f2f2f2";
FadeSteps[FadeSteps.length] = "#f5f5f5";
FadeSteps[FadeSteps.length] = "#f7f7f7";
FadeSteps[FadeSteps.length] = "#fafafa";
FadeSteps[FadeSteps.length] = "#fcfcfc";
FadeSteps[FadeSteps.length] = "#ffffff";

function DoFade(colorId, targetId) {
	if (colorId >= 0) {
		document.getElementById(targetId).style.backgroundColor = FadeSteps[colorId];
		if (colorId == 0) {
			document.getElementById(targetId).style.backgroundColor = "#efefef";
		}
		colorId--;
		setTimeout("DoFade(" + colorId + ",'" + targetId + "')", FadeInterval);
	}
}


function checkAuthorize(elem) {
	document.getElementById('authorize').style.display = 'block';
	document.getElementById('authorize').style.top = '800px';
	document.getElementById('authorize').style.top = (getElementPosition(elem) - 50) + 'px';
}

function getElementPosition(elem) {
	var offsetTrail = elem;
	var offsetTop = 0;
	while (offsetTrail) {
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	return offsetTop;
}

function authorizeClose() {
	document.getElementById('authorize').style.display = 'none';
}

function onScroll_center() {
	var height = clientHeight();
	var element = document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement : document.body;
	if (document.getElementById('authorize')) document.getElementById('authorize').style.top = element.scrollTop + 250 + "px";
	if (document.getElementById('change_region')) document.getElementById('change_region').style.top = element.scrollTop + 250 + "px";

}

function clientHeight() {
	return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientHeight : document.body.clientHeight;
}

function show_tag_add(label) {
	var cont = document.getElementById("tags-add-cont");
	if (cont.style.display == "block") {
		cont.style.display = "none";
		label.className = "closed";
	}
	else {
		cont.style.display = "block";
		label.className = "opened";
	}
}

function show_win(id) {
	var cont = document.getElementById(id);
	if (cont.style.display == "block") {
		cont.style.display = "none";
	}
	else {
		cont.style.display = "block";
	}
}

document.onclick = function(e) {
	if (typeof dont_close_my_tags == "undefined") {
		var isIE = (String(typeof (document.all)) != "undefined");
		var target = isIE ? event.srcElement : e.target;
		var book_tags = document.getElementById('tags_book_tags');
		var your_tags = document.getElementById('tags_your_tags');

		if (book_tags && book_tags.style.display == "block" && target.parentNode.id != "tags_book_tags_cont") {
			book_tags.style.display = "none";
		}
		if (your_tags && your_tags.style.display == "block" && target.parentNode.id != "tags_your_tags_cont") {
			your_tags.style.display = "none";
		}
	}
}

function copy_tag(tag) {
	var form = document.forms.add_tag_form;
	form.tag.value = tag.replace(/%27|%22|%26/g, decodeURIComponent);
	form.tag.focus();
}

function showallprops(obj) {
	for (var prop in obj) {
		displayLine = obj.name + "." + prop + "=" + obj[prop];
		document.write(displayLine + "<BR>");
	}
}
function confirmDel() {
	if (confirm('Удалить?'))
		return true;
	else
		return false;
}

function showGiftPack(body, head) {
	if ($("#gift_packing_body").css("display") == "none") {
		$("#gift_packing_body").slideDown(600);
		$("#head_label").addClass("disabled");
		document.forms.asd.giftpack.value = "1";
	}
	else {
		$("#gift_packing_body").slideUp(600);
		$("#head_label").attr("class", "");
		document.forms.asd.giftpack.value = "";
	}
}

function showGiftPackType(type) {
	if ($("#box_radio").attr("checked")) {
		$("#gift_box_body").slideDown(600);
		$("#gift_box_head > label").addClass("disabled");
		$("#gift_paper_body").slideUp(600);
		$("#gift_paper_head > label").attr("class", "");
	}
	else if ($("#paper_radio").attr("checked")) {
		$("#gift_paper_body").slideDown(600);
		$("#gift_paper_head > label").addClass("disabled");
		$("#gift_box_body").slideUp(600);
		$("#gift_box_head > label").attr("class", "");
	}
}

function giftImgHl(img) {
	$(img).attr("class", "sel_label_active");
}

function giftImgUnhl(img) {
	$(img).attr("class", "sel_label");
}

function selectGiftBox(select) {
	$("#box_price_label").text(box_prices[select.value] != undefined ? box_prices[select.value] + " ." : "");
	var sumfield = $("td.price:last span", select.parentNode.parentNode.parentNode);
	sumfield.text(200 + (document.forms.asd.hasBowBox.checked ? 50 : 0) + (box_prices[select.value] != undefined ? box_prices[select.value] : 0));
}

function addGiftBow(checkbox) {
	var sumfield = $("td.price:last span", checkbox.parentNode.parentNode.parentNode);

	if (checkbox.checked) {
		$("td.price", checkbox.parentNode.parentNode).text("50 .");
		sumfield.text(sumfield.text() * 1 + 50);
	}
	else {
		$("td.price", checkbox.parentNode.parentNode).text("");
		sumfield.text(sumfield.text() * 1 - 50);
	}
}

function showGiftPaperBig(target, e) {
	var isIE = (String(typeof (document.all)) != "undefined");
	var left = (isIE ? event.clientX : e.clientX);
	var top = (isIE ? event.clientY : e.clientY);

	var img = $("img.sel_label", target.parentNode);
	$("#gift_paper_big").css("display", "none");

	$("#gift_paper_big").empty();
	var name = target.id.substring(5);

	if (target.id.substring(0, 5) == "paper") {
		var newimage = $("<img />")
			.attr("src", "http://img.labirint.ru/images/gift_paper/" + name + ".jpg")
			.attr("width", 300)
			.attr("height", 300)
			.appendTo($("#gift_paper_big"));
	}
	else {
		var newimage = $("<img />")
			.attr("src", "http://img.labirint.ru/images/books/" + name + "/big.jpg")
			.attr("width", 220)
			.attr("height", 340)
			.appendTo($("#gift_paper_big"));
	}

	setInScreen($("#gift_paper_big"), left, top);
	$("#gift_paper_big").fadeIn(300);
}

function setInScreen(obj, x, y) {
	var body_width = $("body").width() - document.body.parentNode.scrollLeft - 20;
	var body_height = $("body").height() - document.body.parentNode.scrollTop - 20;
	var width = obj.width();
	var height = obj.height();

	if ((x + width) > body_width) {
		var x = x - width - 10;
	}
	if ((y + height) > body_height) {
		var y = y - height - 10;
	}

	$(obj).css("left", document.body.parentNode.scrollLeft + x - 10);
	$(obj).css("top", document.body.parentNode.scrollTop + y - 10);
}

function selectGiftPaper(label) {
	var cont = $(label.parentNode.parentNode.parentNode);
	$("div:first", cont).remove();
	var paper_item_copy = $(label.parentNode)
		.clone()
		.css("float", "right")
		.prependTo($(cont));
	$("img:first", paper_item_copy).attr("class", "sel_label");
	$("img:first", paper_item_copy).attr("onclick", "");
	var fname = $(cont).attr("id");
	$("input[name=" + fname + "]").attr("value", label.id);
}

function selectPostcard(label) {
	selectGiftPaper(label);
	var tr = $(label.parentNode.parentNode.parentNode.parentNode);
	//$("td.price", tr).text($("span.comment", label.parentNode).text());
	$("textarea", tr).attr("class", "postcard_comment");
}

function itemAddToList(label, id) {
	if ($("#selected_items_head").css("display") == "none") {
		$("#selected_items_head").css("display", "block");
	}
	b = false;
	$("input:checkbox", "#selected_items").each(
			function() {
				if ($(this).attr("value") == id) b = true;
			}
	);
	//alert('ghdtn');
	if (b == true) {
		if (confirm('Уже в списке! Вы точно хотите добавить запись?') == false) return;
	}
	var chbx = $("<input type=\"checkbox\">")
		.attr("name", "items[]")
		.attr("value", id)
		.appendTo($("#selected_items"))
		.attr("checked", 1);

	$("#selected_items").append($(label.parentNode).children("span").text() + "<br />");
	$(label.parentNode).empty().css("display", "none");
}

function fullCommentShow(elem) {

	var parent = elem.parentNode.parentNode;
	var childs = parent.childNodes;

	for (var n in childs) {
		if (childs[n].id != 'undefined' && childs[n].style) {
			childs[n].style.display = 'block';
		}
	}

	elem.parentNode.style.display = 'none';
}

function AdviceSearch() {
	var el = document.getElementById('advises-search-opened');
	var but = document.getElementById('search_advise');

	if (el.style.display == 'block') {
		but.className = 'search_advise_cl';
		el.style.display = 'none';
	}
	else {
		but.className = 'search_advise_op';
		el.style.display = 'block';
	}
}

function callback_open() {
	window.open("/callback/", "callback", "width=872,height=750,scrollbars=yes,resizable=yes");
}
function helpcard_open_scr(idcard, nm_scr) {
	window.open("/screenshelp/" + idcard + "/" + nm_scr + "/", "screenshelp" + idcard + nm_scr, "width=872,height=612,scrollbars=yes,resizable=yes");
}
function helpcard_open(idcard) {
	window.open("/helpcard/" + idcard + "/", "helpcard" + idcard, "width=800,height=540,scrollbars=yes,resizable=yes");
}

function helpcard_open_isadmin(idcard) {
	window.open("/helpcard/" + idcard + "/isadmin/", "helpcard" + idcard, "width=800,height=540,scrollbars=yes,resizable=yes");
}

function check_other_subject(select) {
	document.getElementById("other_subject").style.display = (select.value == 5 ? "block" : "none");
}

function changeCallDay(val) {
	document.getElementById("time").style.display = (val > 0 ? "block" : "none");
}

var currentContenPage = 1;

function contenPage(page) {
	$("#contents_page" + currentContenPage).hide();
	$("#contents_page" + page).show();

	var link = $("<a></a>").attr("href", "javascript: contenPage(" + currentContenPage + ");").html(currentContenPage);
	$("#contents_page_num" + currentContenPage).html(link);

	$("#contents_page_num" + page).html(page);

	currentContenPage = page;
}

function dhmyoncm() {
	var dhaf = document.getElementById('dhcena');
	var dhbf = document.getElementById('dhmassa');
	var dha = document.getElementById('dhcena').value;
	var dhb = document.getElementById('dhmassa').value;
	if (dha == '') {
		alert('Не заполнено поле "Цена"!');
		dhaf.focus();
		return false;
	}
	else {
		if (dhb == '') {
			alert('Не заполнено поле "Вес"!');
			dhbf.focus();
			return false;
		}
		else {
			if (isNaN(dha)) {
				alert('В поле "Цена" введено не число!');
				dhaf.focus();
				return false;
			}
			else {
				if (isNaN(dhb)) {
					alert('В поле "Вес" введено не число!');
					dhbf.focus();
					return false;
				}
				else return true;
			}
		}
	}
}

var dhshowautohelp = true;
function autohelp_timeout(e, dhp) {
	if (dhshowautohelp) {
		var text_k = e;

		if (text_k != 16 && text_k != 17 && text_k != 18 && text_k != 13 && text_k != 20 && text_k != 192 && text_k != 37 && text_k != 38 && text_k != 39 && text_k != 40 && text_k != 116) {
			autohelp_change(dhp);
		}

		if (text_k == 38 || text_k == 40) {
			if (dhp == 7 || dhp == 8 || dhp == 9) { var auhr = 'autohelp_rows_list'; var txt = document.forms.list_search.lit; }
			if (dhp == 6) { var auhr = 'autohelp_rows_genre'; var txt = document.forms.genre_search.txt; }
			if (dhp == 4) { var auhr = 'autohelp_rows_big'; var txt = document.forms.searchformadvanced.helptxt; }
			if (dhp == 3) { var auhr = 'autohelp_rows_big'; var txt = document.getElementById('txtwordsadv'); }
			if (dhp == 2) { var auhr = 'autohelp_rows_width'; var txt = document.getElementById('txtwords'); }
			if (dhp == 1) { var auhr = 'autohelp_rows'; var txt = document.getElementById('search-field'); }

			if (document.getElementById(auhr).style.display == 'block' || document.getElementById(auhr).style.display == '') {
				var test = document.getElementById('dhlistul' + dhp);
				var dhsch = 11;

				for (var i in test.childNodes) { if (test.childNodes[i].value == 2) dhsch = i; }
				var dhi = test.childNodes.length - 2;

				if (text_k == 40) {
					if (dhsch == 11) {
						test.childNodes[0].style.backgroundColor = "#CCFFCC";
						test.childNodes[0].value = 2;
						txt.value = document.getElementById('dha' + 0 + dhp).innerHTML;
					}
					else {
						if (dhsch == dhi) {
							test.childNodes[dhsch].value = 1;
							test.childNodes[dhsch].style.backgroundColor = "#ffffff";
							txt.value = document.getElementById('dha' + 0 + dhp).innerHTML;
							test.childNodes[0].style.backgroundColor = "#CCFFCC";
							test.childNodes[0].value = 2;
						}
						else {
							if (text_k == 13) alert(test.childNodes[dhsch].value);
							test.childNodes[dhsch].value = 1;
							test.childNodes[dhsch].style.backgroundColor = "#ffffff";
							dhsch++;
							txt.value = document.getElementById('dha' + dhsch + dhp).innerHTML;
							test.childNodes[dhsch].style.backgroundColor = "#CCFFCC";
							test.childNodes[dhsch].value = 2;
						}
					}
				}
				if (text_k == 38) {
					if (dhsch == 11) {
						test.childNodes[dhi].style.backgroundColor = "#CCFFCC";
						test.childNodes[dhi].value = 2;
						txt.value = document.getElementById('dha' + dhi + dhp).innerHTML;
					}
					else {
						if (dhsch == 0) {
							test.childNodes[dhsch].value = 1;
							test.childNodes[dhsch].style.backgroundColor = "#ffffff";
							txt.value = document.getElementById('dha' + dhi + dhp).innerHTML;
							test.childNodes[dhi].style.backgroundColor = "#CCFFCC";
							test.childNodes[dhi].value = 2;
						}
						else {
							test.childNodes[dhsch].value = 1;
							test.childNodes[dhsch].style.backgroundColor = "#ffffff";
							dhsch--;
							txt.value = document.getElementById('dha' + dhsch + dhp).innerHTML;
							test.childNodes[dhsch].style.backgroundColor = "#CCFFCC";
							test.childNodes[dhsch].value = 2;
						}
					}
				}
			}
		}
	}
}

function autohelp_change(dhp) {
	if (dhshowautohelp) {
		if (dhp == 7 || dhp == 8 || dhp == 9) {
			var txt = document.forms.list_search.lit.value;
			var auhr = 'autohelp_rows_list';
			var file_name = "/catalog/autohelp.ajax.php";
		}
		if (dhp == 6) {
			var txt = document.forms.genre_search.txt.value;
			var auhr = 'autohelp_rows_genre';
			var file_name = "/catalog/autohelp.ajax.php";
		}
		if (dhp == 4) {
			var txt = document.forms.searchformadvanced.helptxt.value;
			var auhr = 'autohelp_rows_big';
			var file_name = "/catalog/autohelp.ajax.php";
		}
		if (dhp == 3) {
			var txt = document.getElementById('txtwordsadv').value;
			var auhr = 'autohelp_rows_big';
			var file_name = "/catalog/autohelp.ajax.php";
		}
		if (dhp == 2) {
			var txt = document.getElementById('txtwords').value;
			var auhr = 'autohelp_rows_width';
			var file_name = "/catalog/autohelp.ajax.php";
		}
		if (dhp == 1) {
			var txt = document.getElementById('search-field').value;
			var auhr = 'autohelp_rows';
			var file_name = "/catalog/autohelp.ajax.php";
		}
		if (txt.length > 1 && txt != ' ') {
			var list = document.getElementById(auhr);
			if (JsHttpRequestXHR != null)
				JsHttpRequestXHR.abort();

			JsHttpRequestXHR = JsHttpRequest.myquery(file_name, { "txt": txt, "dhp": dhp }, function(result, errors) {
				if (result) {
					list = document.getElementById(auhr);
					if (result.err == 'no') {
						if (result.html) {
							list.innerHTML = '';
							list.innerHTML = result.html;
							list.style.display = 'block';
						}
						else list.style.display = 'none';

					}
					else {
						list.innerHTML = result.log;
					}
				}
			}, true);
		}
		else document.getElementById(auhr).style.display = 'none';
	}
}

function open_helpercard(id, search) {

	var file_name = "/catalog/helpercard.ajax.php";
	var list = document.getElementById('CardHelp' + id);
	list.innerHTML = '<div style="width:100%; text-align: center;"><img src="http://img.labirint.ru/images/design/loadingnew.gif"></div>';
	JsHttpRequest.query(file_name, { "id": id, "search": search }, function(result, errors) {
		if (result.err == 'no') {
			if (result.html) {
				list.innerHTML = '';
				list.innerHTML = result.html;
				eval(result.js);

				var childs = $('div', document.getElementById('CardHelp' + id));
				for (var i in childs) {
					if (childs[i] != undefined && childs[i].id != undefined && childs[i].id.substr(0, 7) == 'YMapsID') {
						var id_map = childs[i].id.substr(7, childs[i].id.length - 1);
						loadMiniMap(id_map);
					}
				}
			}
		}
		else {
			list.innerHTML = result.log;
		}
	}, true);
}

function dhdisplaynone(dhp) {
	if (dhshowautohelp) {
		if (dhp == 3 || dhp == 4) {
			var auhr = 'autohelp_rows_big';
		}
		if (dhp == 2) {
			var auhr = 'autohelp_rows_width';
		}
		if (dhp == 1) {
			var auhr = 'autohelp_rows';
		}
		if (dhp == 5) var auhr = 'postlist';
		if (dhp == 6) var auhr = 'autohelp_rows_genre';
		if (dhp == 7 || dhp == 8 || dhp == 9) var auhr = 'autohelp_rows_list';

		document.getElementById(auhr).style.display = 'none';
	}
}

function dhautohelpclose() {
	dhshowautohelp = false;
	if (document.getElementById('autohelp_rows_big')) document.getElementById('autohelp_rows_big').style.display = 'none';
	if (document.getElementById('autohelp_rows_width')) document.getElementById('autohelp_rows_width').style.display = 'none';
	if (document.getElementById('autohelp_rows')) document.getElementById('autohelp_rows').style.display = 'none';
	if (document.getElementById('autohelp_rows_genre')) document.getElementById('autohelp_rows_genre').style.display = 'none';
	if (document.getElementById('autohelp_rows_list')) document.getElementById('autohelp_rows_list').style.display = 'none';
}

function alreadyInCompList(idbook, sgenre, retail) {
	var comp = "comp" + idbook;
	for (i = 0; i < document.getElementsByTagName('span').length; i++) {
		qq = document.getElementsByTagName('span')[i];
		if (qq.id == comp) {
			var gnres = Array();
			tit = "Перейти к списку сравнения";
			gnres[-1] = "books/"; gnres[-2] = "video/"; gnres[-3] = "audio/"; gnres[-4] = "software/"; gnres[-5] = "games/"; gnres[-6] = "office/"; gnres[-7] = "other/"; gnres[-10] = "ebooks/";
			qq.innerHTML = (retail == 1 ? '<a href=\"/retail/compare/' + gnres[sgenre] + '\" class=\"addedincomp\" title=\"' + tit + '\"><nobr>Перейти к сравнению</nobr></a>' : '<a href=\"/compare/' + gnres[sgenre] + '\" class=\"addedincomp\" title=\"' + tit + '\"><nobr>Перейти к сравнению</nobr></a>');
		}
	}
}

function compareShowContent(style, type) {
	var divs = document.getElementsByTagName('div');
	var spans = document.getElementsByTagName('span');
	for (i = 0; i < divs.length; i++) {
		var id = divs[i].id + '';
		if (id.substring(0, 6) == (type + 'txt')) divs[i].style.display = style;
	}
	for (i = 0; i < spans.length; i++) {
		var id = spans[i].id + '';
		if (style == 'block') {
			if (id.substring(0, 5) == (type + 'vs')) spans[i].style.display = 'none';
			if (id.substring(0, 5) == (type + 'vh')) spans[i].style.display = 'inline';
		}
		else {
			if (id.substring(0, 5) == (type + 'vs')) spans[i].style.display = 'inline';
			if (id.substring(0, 5) == (type + 'vh')) spans[i].style.display = 'none';
		}
	}
}

function selectSelfDelivery(id_deliv) {
	id_deliv = id_deliv.replace('place', '');
	showDelivery(id_deliv);
	document.forms.ShablonForm.NextStep.onclick = function() { writeHiddenSelfdelivery(id_deliv) }
	document.getElementById("delivery_maps").style.visibility = "hidden";
}

function getRegionPhones(regions) {
	var region = regions.value;

	$(regions).addClass("upload");
	$(regions).attr("disabled", "disabled");

	$("#region_phone1_code").html("");
	$("#region_phone1_phone").html("");
	$("#region_phone2_code").html("");
	$("#region_phone2_phone").html("");

	JsHttpRequest.query("/ajax.php", { "func": "getRegionPhones", "region": region }, function(result, errors) {
		if (!result.err) {
			$("#region_phone1_code").html(result.phones.phone1.code);
			$("#region_phone1_phone").html(result.phones.phone1.number);
			$("#region_phone2_code").html(result.phones.phone2.code);
			$("#region_phone2_phone").html(result.phones.phone2.number);
		}
		else {

		}

		$(regions).removeClass("upload");
		$(regions).attr("disabled", "");
	}, true);
}

var overlay_id = null;
if (typeof jQuery != 'undefined') {
	var is_ie6 = '\v' == 'v' && jQuery.browser.version == '6.0';
}

function overlayWindow(param) {
	switch (typeof param) {
		case 'string':
			var id = param;
			var func = '';
			break;
		case 'object':
			var id = param.id;
			var func = param.func;
			break;
		case 'default':
			return;
			break;
	}

	var div = $("#overlay");

	if (div.length > 0) {
		div.show();
	}
	else {
		var div = $("<div></div>").attr({ "id": "overlay" }).appendTo("body");
	}


	div.click(function() { clearWindow(id); });

	if (is_ie6) {
		resizeElement(div, $("body").width(), $("body").height());
		div.append("<iframe></iframe>");
	}
	else {
		resizeElement(div, $(window).width(), $(window).height());
		$(window).resize(function() {
			resizeElement(div, $(window).width(), $(window).height());

			if (id != '')
				elementLocationCenter($("#" + id));
		});
	}

	if (id != '') {
		overlay_id = id;
		var cheight = $("#" + id).height();
		var cwidth = $("#" + id).width();

		if ($("body>#" + id).length > 0) {
			var inner = $("#" + id).show();

			resizeElement(inner, cwidth, cheight);
			elementLocationCenter(inner);

			if (typeof func == 'function')
				func();
		}
		else {
			var content = $("#" + id).html();
			var classname = $("#" + id).attr("class");

			$("#" + id).remove();

			var inner = $("<div></div>")
				.attr({ "class": classname, "id": id })
				.appendTo("body");

			resizeElement(inner, cwidth, cheight);
			elementLocationCenter(inner);

			inner.addClass("content_upload").show(100);

			if (typeof func == 'function') {
				setTimeout(function() {
					inner.append(content);
					func();
					inner.removeClass("content_upload");
				}, 300);
			}
			else {
				setTimeout(function() {
					inner.append(content);
					inner.removeClass("content_upload");
				}, 300);
			}
		}
	}
}

function resizeElement(elem, width, height) {
	$(elem).css({ "width": width + "px", "height": height + "px" });
}

function elementLocationCenter(elem) {
	var cheight = $(elem).height();
	var cwidth = $(elem).width();

	if (is_ie6) {
		var top = (document.documentElement.clientHeight - cheight) / 2;
		var left = (document.documentElement.clientWidth - cwidth) / 2;
		top += document.documentElement.scrollTop;

		top = (top > 0 ? top : 0);
		left = (left > 0 ? left : 0);

		$(elem).css({ "top": top + "px", "left": left + "px", "height": cheight + "px", "width": cwidth + "px" });
	}
	else {
		var marginLeft = -cwidth / 2 + 'px';
		var marginTop = -cheight / 2 + 'px';

		$(elem).css({ 'margin-left': marginLeft, 'margin-top': marginTop, "height": cheight + "px", "width": cwidth + "px" });
	}
}

function clearWindow(id) {
	if (id != '') {
		$("#" + id).hide();
	}

	$("#overlay").hide();
	$(window).resize(function() { return false; });
}

function ieScroll() {
	var top = 200;

	if (overlay_id) {
		var cheight = $("#" + overlay_id).height();
		var top = (document.documentElement.clientHeight - cheight) / 2 - 20;

		top = (top > 0 ? top : 0);
	}

	$("div.overlay_content").css("top", document.documentElement.scrollTop + top + "px");
}

function keytext(event) {
	if (navigator.appName == 'Netscape') { if ((event.charCode > 0 && event.charCode < 48) || event.charCode > 57) { return false; } }
	else { if (event.keyCode < 48 || event.keyCode > 57) { event.returnValue = false; } }
}

function isEmpty(obj) {
	for (var key in obj) return false;
	return true;
}

function showDiv(id, show, scroll, p) {
	var div = $('#' + id);
	$(div).css('display', show ? 'block' : 'none');
	if (show) {
		var html = typeof document.documentElement != 'undefined' ? document.documentElement : document.body;
		if (typeof p != 'undefined' && p.id && $(p.id)) {
			var h = $(p.id).height();
			if (h) {
				$(div).css({ height: h + "px" });
			}
		}
		if (scroll == 1) $(div).css({ left: 0, top: 250 + html.scrollTop });
		else if (scroll > 0) window.scrollTo(0, scroll);
	}
}

var execTimeout = (function() {
	var exec_called = 0;

	function execCaller(f, a, n) {
		if (n == exec_called)
			f.apply(null, a);
	}

	return function(f) {
		var timeout = 250;

		if (typeof f == 'object') {
			if (typeof f.func != 'function')
				return false;

			if (f.timeout != undefined)
				timeout = f.timeout;

			f = f.func;
		}

		if (typeof f == 'function') {
			exec_called++;
			args = Array.prototype.slice.call(arguments);
			args = args.slice(1);
			var callback = function(f, a, n) {
				return function() { execCaller(f, a, n); }
			} (f, args, exec_called);

			setTimeout(callback, timeout);
		}
	}
} ());

function sendID_Post(id_post) {
	document.forms.select_post.id_post.value = id_post;
	document.forms.select_post.submit();
}

function showPostList(id) {
	if (document.getElementById(id).innerHTML.length > 1) $("#" + id).show();
}

function getGTRuleAgain() {
	JsHttpRequest.query("/ajax.php", { "func": 'getGTRuleAgain' }, function(result, errors) {
		$("input[name=post]").val(result.gt_rule_name);
	}, true);
}

function showIPQuestion(p, flag) {
	$(typeof p == 'string' ? '#' + p : p).css('display', flag ? 'block' : 'none');
}

function dontshowsmall(dontshow) {
	setCookie("dontshowsmall", dontshow ? 1 : 0);
}

// ширина сикриншотов
var scrnwidth = 146;
function scrnMoveRight() {
	var sw = parseInt($("#small_images").css("width"));
	var w = parseInt($("#smi_list").css("width"));
	if (w < sw) return false;
	var m = parseInt($("#smi_list").css("margin-left"));
	var k = Math.floor(sw / scrnwidth);
	m = Math.floor(m / scrnwidth) * scrnwidth;
	m = m - scrnwidth * k;
	if (m < -(w - sw)) m = sw - w;
	$("#smi_list").animate({ marginLeft: m }, 350);
}

function scrnMoveLeft() {
	var sw = parseInt($("#small_images").css("width"));
	var m = parseInt($("#smi_list").css("margin-left"));
	if (m > 0) return false;
	var k = Math.floor(sw / scrnwidth);
	m = Math.floor(m / scrnwidth) * scrnwidth;
	m = m + scrnwidth * k;
	if (m > 0) m = 0;
	$("#smi_list").animate({ marginLeft: m }, 350);
}


function ltrim(str) {
	return str.replace(/^\s+/, '');
}

function rtrim(str) {
	return str.replace(/\s+$/, '');
}

function trim(str) {
	return rtrim(ltrim(str));
}

function htmlspecialchars(html) {
	return html.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}

var glavskazlimit = 0;
function chekGlavskazkaBonus() {
	var gscount = 0;
	for (var i = 1; i < 7; i++) {
		if ($("#glavskazka" + i).attr("checked")) gscount++;
	}

	if (gscount >= glavskazlimit) {
		for (var i = 1; i < 7; i++) {
			if (!$("#glavskazka" + i).attr("checked"))
				$("#glavskazka" + i).attr("disabled", true);
			else
				$("#glavskazka" + i).attr("disabled", false);
		}
	}
	else
		$("#glavskazkabonus input").attr("disabled", false);

}

function writesearchform(path, name, hiddenobj) {
	var hidden = '';
	if (typeof hiddenobj == 'object') {
		for (id in hiddenobj) {
			hidden += '<input type="hidden" name="' + id + '" value="' + hiddenobj[id] + '" />';
		}
	}
	document.write('<div id="sale-search" style="margin: 0px 20px 0px 0px; z-index: 1000;"><div id="search"><div id="searchadvvip"><div class="searchadv-top"><div class="searchadv-left"><div class="searchadv-right"><div class="searchadv-bottom"><div class="searchadv-topleft"><div class="searchadv-bottomleft"><div class="searchadv-topright"><div class="searchadv-bottomright"><div class="more">Поиск по каталогу:</div><form name="salesearch" action="' + path + '" method="get">' + hidden + '<div id="list-hidden" style="width: 0px; float: left;"></div><div class="searchadvleft"><input autocomplete="off" type="text" id="txtwordsadv" value="" class="input-width keyboardInput adv" name="' + name + '" /><br /></div><div class="searchadvright"><input type="submit" class="red-button-adv" value="Найти" /></div></form></div></div></div></div></div></div></div></div></div></div></div><div class="cleaner"></div>');
}

function showepicture(id_books, bw, pos, mwidth, canBuy, isbasket) {
	if (!getCookie("dontshowbig")) {
		bwidth = bw;
		picturediv = document.getElementById("bigpic");
		var book_href = document.getElementById("href" + id_books).href;
		pleft = pos.x;
		ptop = pos.y;
		if (navigator.userAgent.indexOf("MSIE 7.0") != -1) { pleft -= 11; }
		if (canBuy == 1) {
			str_buy_batton = "<div id='cover_buy_button" + id_books + "' class='cover_buy_button' onmouseout='hidepicture()' onmousemove='show=1' onclick=' shoping(" + id_books + "," + isbasket + "); hidepicture();'><img src='http://img.labirint.ru/images/design/kupit.gif'></div>";
		}
		else str_buy_batton = "";

		picturediv.style.left = pleft + 'px';
		picturediv.style.top = ptop + 'px';

		picturediv.innerHTML = "<div onmouseout='hidepicture()' onmousemove='show=1'><a href='" + book_href + "'><img id='" + id_books + "' src='http://img.labirint.ru/images/ebooks/" + id_books + "/small.jpg'></a></div>" + str_buy_batton + "<div id='loading-pic' onmouseout='hidepicture()' onmousemove='show=1'>Загружается...<img src='http://img.labirint.ru/images/design/upload.gif'></div><div id='noshow' onmouseout='hidepicture()' onmousemove='show=1'><input type='checkbox' onChange='dontshowbig(this.checked)' onmousemove='show=1'> Не показывать всплывающие обложки</div>";

		bpic = new Image();
		bpic.onload = function() {
			document.getElementById("loading-pic").innerHTML = "";
			pic.src = bpic.src;
		}

		if (canBuy == 1 && navigator.userAgent.indexOf("MSIE 7.0") != -1) {
			document.getElementById("cover_buy_button" + id_books).style.bottom = '144px';
		}

		bpic.src = "http://img.labirint.ru/images/ebooks/" + id_books + "/big.jpg";
		pic = document.getElementById(id_books);
		pic.width = mwidth;
		picturediv.style.display = "block";
		increase();
	}
}

function captchaRefresh(id_container) {
	var cont = $("#" + id_container);
	var kcaptcha_img = $('<img>').css('vertical-align', 'middle');
	var src = cont.find('img').attr('src');
	src = src.replace(/&r=[0-9\.]+/, '');
	kcaptcha_img.load(function() {
		cont.html(kcaptcha_img);
	})
	kcaptcha_img.attr('src', src + '&r=' + Math.random());
}

function close_openapi() {
	clearWindow('auth_openapi');
	$('#openap_list').show();
	$('#add-socsrv').show();
	$('#check-havecode').hide();
	$('#checkcode_error').hide();
}

/* getfunctions.js */
function getPubhouse(id_pubhouse) {
	var txt = document.forms.filter.txt.value;
	var pubhouses = document.getElementById("select-pubhouse");
	document.forms.diagram.txt.value = txt;
	pubhouses.innerHTML = "<center>Загрузка... <img src='http://img.labirint.ru/design/upload.gif'></center>";
	JsHttpRequest.query("/obmb/diagram/getpubhouse.php", { "txt": txt }, function(result, errors) {
		pubhouses = document.getElementById("select-pubhouse");
		if (result.err == 'no') {
			pubhouses.innerHTML = result.html;
			document.forms.filter.id_pubhouse.value = id_pubhouse;
			document.getElementById('id_p').focus();
			var a = document.forms.filter.id_pubhouse.value;
			if (a > 0) {
				document.getElementById('but').disabled = false;
			}
			else {
				document.getElementById('but').disabled = true;
			}
		}
		else {
			pubhouses.innerHTML = result.log;
		}
	}, true);
}

function shoping(id_tov, check, retail) {
	if (check == "") { check = 0; }
	var imho = 0
	if (check > 1) { var imho = check }
	if (retail > 1000) var charity = retail;
	else var charity = 0;

	if (check == 1) {
		var urlnavi = "/buy.php?check=1&s=1&id=" + id_tov + "&charity=" + charity;
		window.location = urlnavi;
		if (charity == 0) {
			if (document.getElementById('basket-in-cart-a')) {
				var bcount = parseInt(document.getElementById('basket-in-cart-a').innerHTML)
				document.getElementById('basket-in-cart-a').innerHTML = bcount + 1;
			}
			var buy = "buy" + id_tov;
			for (i = 0; i < document.getElementsByTagName('span').length; i++) {
				qq = document.getElementsByTagName('span')[i];
				if (qq.id == buy) { qq.innerHTML = ((retail == 1) ? '<a href=\"/retail/basket/\">В корзине</a>' : '<a href=\"/basket/\">В корзине</a>'); }
			}
		}
	}
	else {
		$("#buy" + id_tov).html("&nbsp;").addClass("buyload");
		JsHttpRequest.query("/buy.php", { "id": id_tov, "imho": imho, "s": 1, "charity": charity }, function(result, errors) {
			$("#buy" + id_tov).removeClass("buyload");
			if (result.err == 'no') {
				if (result.books_limit == 0) {
					if (document.getElementById('basket-in-cart-a')) {
						var bcount = parseInt(document.getElementById('basket-in-cart-a').innerHTML)

						document.getElementById('basket-in-cart-a').innerHTML = bcount + 1;
					}

					if (document.getElementById('basket-in-dreambox-a') && result.put_book == 1) {
						var bcount = parseInt(document.getElementById('basket-in-dreambox-a').innerHTML)
						document.getElementById('basket-in-dreambox-a').innerHTML = bcount + 1;
					}

					if (document.getElementById('fullsumprice') && document.getElementById('discsumprice').innerHTML && result.fullsumcena && result.sumcena) {
						document.getElementById('fullsumprice').innerHTML = result.fullsumcena;
						document.getElementById('discsumprice').innerHTML = result.sumcena;
					}

					var buy = "buy" + id_tov;
					var buychar = "buychar" + id_tov + charity;
					for (i = 0; i < document.getElementsByTagName('span').length; i++) {
						qq = document.getElementsByTagName('span')[i];
						if (qq.id == buy) {
							if (check == 20) qq.innerHTML = ((retail == 1) ? '<a href=\"/retail/basket/\">В корзине</a>' : '<a target=\"_blank\" href=\"/basket/\">В корзине</a>');
							else qq.innerHTML = ((retail == 1) ? '<a href=\"/retail/basket/\">В корзине</a>' : '<a href=\"/basket/\">В корзине</a>');
						}
						if (qq.id == buychar) {
							if (check == 20) qq.innerHTML = ((retail == 1) ? '<a href=\"/retail/basket/\">В корзине</a>' : '<a target=\"_blank\" href=\"/basket/\">В корзине</a>');
							else qq.innerHTML = ((retail == 1) ? '<a href=\"/retail/basket/\">В корзине</a>' : '<a href=\"/basket/\">В корзине</a>');
						}
					}
				}
				else
					alert("В корзину нельзя положить более 500 товаров!");
			}
			else {
				var buy = "buy" + id_tov;
				for (i = 0; i < document.getElementsByTagName('span').length; i++) {
					qq = document.getElementsByTagName('span')[i];
					if (qq.id == buy) { qq.innerHTML = '<a href=\"/helpgopage/support/\">Купить</a>'; }
				}
			}
		}, true);
	}
}

function shoping2(id_tov) {
	JsHttpRequest.query("/buy.php", { "ido": id_tov, "s": 1 }, function(result, errors) {
		if (result.err == 'no') {
			if (result.books_limit == 0) {
				if (document.getElementById('basket-in-cart-a')) {
					var bcount = parseInt(document.getElementById('basket-in-cart-a').innerHTML)
					document.getElementById('basket-in-cart-a').innerHTML = bcount + 1;
				}

				var buy = "buyof" + id_tov;
				document.getElementById(buy).innerHTML = "<a href=\"/basket/\">В корзине</a>";
			}
			else
				alert("В корзину нельзя положить более 500 товаров!");
		}
	}, true);
}

function shoping3(id_tov) {
	JsHttpRequest.query("/buy.php", { "ido": id_tov, "s": 1 }, function(result, errors) {
		if (result.err == 'no') {
			if (result.books_limit == 0) {
				$("#basket-in-cart-a").html(parseInt($("#basket-in-cart-a").html()) + 1);
				$(".clbuyof" + id_tov).html('<a href="/basket/">В корзине</a>');
			}
			else
				alert("В корзину нельзя положить более 500 товаров!");
		}
	}, true);
}

function getSubGenres(more_genre) {
	if (document.getElementById('gl' + more_genre).innerHTML.length > 0) {
		document.images['gi' + more_genre].src = 'http://img.labirint.ru/design/plus.gif';
		document.getElementById('gl' + more_genre).innerHTML = '';
		document.getElementById('gl' + more_genre).style.display = 'none';
	}
	else {
		document.images['gi' + more_genre].style.visibility = "hidden";

		JsHttpRequest.query("/catalog/genretree.php", { "more_genre": more_genre }, function(result, errors) {
			if (result.err == 'no') {
				document.getElementById('gl' + more_genre).style.display = 'block';
				document.images['gi' + more_genre].style.visibility = "visible";
				document.images['gi' + more_genre].src = 'http://img.labirint.ru/design/minus.gif';
				document.getElementById('gl' + more_genre).innerHTML = result.html;
			}
		}, true);
	}
}

// Запись в базу статистики по отказавшимся от больших обложек
function big_pics_stat(UserSes, dontshow) {
	JsHttpRequest.query("/catalog/big_pics_stat.php", { "UserSes": UserSes, "dontshow": dontshow }, function(result, errors) { }, true);
}

// Голосование - оценка книги
function sendvote(id_books, votemark) {
	JsHttpRequest.query("/catalog/vote.ajax.php", { "book": id_books, "votemark": votemark }, function(result, errors) {
		if (result.err == 'no') {
			document.getElementById("rate").innerHTML = result.rate;
			document.getElementById("count-marks-label").innerHTML = "Ваша оценка: " + result.your_mark + " (оценило: " + result.countmarks + ")";
			your_mark = result.your_mark * 1;
			outstar();
		}
	}, true);
}

function send_mailticket(id_order) {
	JsHttpRequest.query("/cabinet/send_mailticket.php", { "id_order": id_order }, function(result, errors) { }, true);
}

var is_typing = 0;
var is_sended = 0;
function list_timeout(path, e, adm) {
	is_typing++;
	var txt = document.forms.list_search.lit.value;
	var text_k = e.keyCode;
	if (text_k != 16 && text_k != 17 && text_k != 18 && text_k != 13 && text_k != 20 && text_k != 192 && text_k != 37 && text_k != 38 && text_k != 39 && text_k != 40 && text_k != 116) {
		setTimeout("waaait('" + path + "', " + is_typing + ", '" + adm + "')", 500);
	}
}

function waaait(path, n, adm) {
	if (is_typing == n) { list_change(path, adm); }
}

function list_change(path, adm) {
	var txt = document.forms.list_search.lit.value;
	if (txt.length > 2) {
		var text = document.getElementById("list_text");
		var list = document.getElementById("list_rows");
		list.innerHTML = "<br><br><center style=\"font: 12px Arial, Helvetica, sans-serif;\"><img src='http://img.labirint.ru/design/upload_big.gif'></center>";

		JsHttpRequest.query("/catalog/list_change.php", { "txt": txt, "path": path, "adm": adm }, function(result, errors) {
			var list = document.getElementById("list_rows");
			if (result.err == 'no') {
				list.innerHTML = '';
				list.innerHTML = result.html;
			}
			else
				pubhouses.innerHTML = result.log;
		}, true);
	}
}

function commentVote(id_comment, voting, best, thanks) {
	var user_mark = document.getElementById("user_mark" + id_comment) ?
		document.getElementById("user_mark" + id_comment) :
		document.getElementById("user_mark");

	var voting_div = document.getElementById("comment_vote" + id_comment);
	var comm_mark = document.getElementById("comment_mark" + id_comment);

	if (best == 1)
		var best_table = document.getElementById("best");

	voting_div.innerHTML = "<center style=\"font: 12px Arial, Helvetica, sans-serif;\"> Загрузка...&nbsp; <img style=\"float: none; border: 0px solid #cccccc; margin:0;\" src='http://img.labirint.ru/design/upload_old.gif'></center>";

	JsHttpRequest.query("/catalog/commentVote.ajax.php", { "id_comment": id_comment, "voting": voting, "best": best }, function(result, errors) {
		if (result.err == 'no') {
			voting_div.innerHTML = '';
			voting_div.innerHTML = result.html;

			comm_mark.innerHTML = result.comment_thanks;
			comm_mark.style.color = result.comment_thanks_color;
			comm_mark.style.weight = 'bold';

			if (best == 1) {
				best_table.innerHTML = result.best;
			}

		}
		else {
			voting_div.innerHTML = result.log;
		}
	}, true);
}

function deleteCommentPic(id_comment, id_pic) {
	var commentPic = document.getElementById("commentPic" + id_pic);
	var commentPics = document.getElementById("commentPics");
	commentPic.innerHTML = "<div style=\"font: 12px Arial, Helvetica, sans-serif;\"> Удаление...&nbsp; <img style=\"float: none; border: 0px solid #cccccc; margin:0;\" src='http://img.labirint.ru/design/upload.gif'></div>";

	JsHttpRequest.query("/catalog/commentDelPic.ajax.php", { "id_comment": id_comment, "id_pic": id_pic }, function(result, errors) {
		if (result.err == 'no') {
			commentPic.innerHTML = '';
			commentPic.innerHTML = result.html;
			commentPics.style.border = result.border;
		}
		else {
			commentPic.innerHTML = result.log;
		}
	}, true);
}

function be_Paid(id_order, param) {
	JsHttpRequest.query("/cabinet/be_paid.php", { "id_order": id_order }, function(result, errors) {
		if (result.err == 'no') {
			if (param == 1) document.forms.form1.submit();
		}
	}, true);
}

function CabinetMess(id_order, mess) {
	document.getElementById('MessForm').style.visibility = 'hidden';
	document.getElementById('MessForm').style.position = 'absolute';
	document.getElementById('MessTXT').innerHTML = "<center><img src='http://img.labirint.ru/design/upload.gif'></center>";
	JsHttpRequest.query("/cabinet/cabinet_mess.php", { "id_order": id_order, "mess": mess }, function(result, errors) {
		if (result.err == 'no') {
			document.forms.newMessForm.mess.value = '';
			document.getElementById('MessTXT').innerHTML = "Сообщение отправлено.<br/>Окно автоматически закроется через 3 секунды<br/><br/><input type='button' value=\"Закрыть\" class='red-button' onClick='$(\"#newMess\").css(\"display\",\"none\");'/>";
			setTimeout("document.getElementById('newMess').style.visibility='hidden'; document.getElementById('MessTXT').innerHTML='';", 3000);
		}
		else {
			document.forms.newMessForm.mess.value = '';
			document.getElementById('MessTXT').innerHTML = "Не верный номер заказа.<br/><br/><input type='button' value=\"Закрыть\" class='red-button' onClick='$(\"#newMess\").css(\"display\",\"none\"); document.getElementById(\"MessForm\").style.visibility=\"visible\";'/>";
		}
	}, true);
}

function typeTimeOut(f, e) {
	is_typing++;
	var text_k = e.keyCode;
	if (text_k != 16 && text_k != 17 && text_k != 18 && text_k != 20 && text_k != 192 && text_k != 37 && text_k != 38 && text_k != 39 && text_k != 40 && text_k != 116) {
		setTimeout("type_waaait(" + is_typing + ", " + f + ")", 500);
	}
}

function type_waaait(n, f) {
	if (is_typing == n)
		f();
}

/* корзина sms*/
function chkSmsNumer() {
	var phone = '7' + $('#smsphone_code').val() + $('#smsphone_end').val();

	phone = !isNaN(phone) && phone.length == 11 && phone.substr(0, 2) == '79' ? phone : null;

	if (phone) {
		$("#phonesdiv").attr("class", "phoneg");
		$("#phonestat").html("верный формат");
	}
	else {
		$("#phonesdiv").attr("class", "phoneb");
		$("#phonestat").html("не соответствует формату");
	}

	return phone;
}

function changeSmsNumber(e) {
	var text_k = e.keyCode;
	if (text_k != 16 && text_k != 18 && text_k != 13 && text_k != 20 && text_k != 192 && text_k != 37 && text_k != 38 && text_k != 39 && text_k != 40 && text_k != 116) {
		chkSmsNumer();
	}
}

function saveNumber() {
	var phone = chkSmsNumer();
	if (!phone) {
		alert('Неверный формат телефона!');
		return false;
	}
	$("#sendSMS").addClass("content_upload");
	JsHttpRequest.query("/basket/chekPhone4SMS.php", { "phone": phone, "save": 1 }, function(result, errors) {
		if (result.err != 'no') {
			if (result.err) alert(result.err);
		}
		else {
			clearWindow("sendSMS");
			$('#smscbx').attr('checked', 1);
		}
		$("#sendSMS").removeClass("content_upload");
	}, true);
}

function smsChange() {
	if ($('#smscbx').attr("checked")) {
		var phone = chkSmsNumer();
		if (!phone) {
			$('#smscbx').attr("checked", "");
			overlayWindow("sendSMS");
		}
		else saveNumber();
	}
}
/* конец корзина sms*/

function dont_puBooks(dontshow) {
	dont_put = dontshow ? 1 : 0;
	JsHttpRequest.query("/cabinet/dont_putBooks.php", { "dont_put": dont_put }, function(result, errors) { }, true);
}

function geoTargetingTimeOut(type, e) {
	is_typing++;
	var text_k = e.keyCode;

	if (text_k != 16 && text_k != 17 && text_k != 18 && text_k != 13 && text_k != 20 && text_k != 192 && text_k != 37 && text_k != 38 && text_k != 39 && text_k != 40 && text_k != 116) {
		setTimeout("geoTargeting_waaait('" + type + "'," + is_typing + ")", 500);
	}
}

function geoTargeting_waaait(type, n) {
	if (is_typing == n) { geoTargetingSearch(type, 0); }
}

function geoTargetingSearch(type, id_rule) {
	var txt = document.getElementById(type).value;
	var id_rule = id_rule > 0 ? id_rule : null;

	if (txt.length) {

		var text = document.getElementById('result_' + type);

		text.innerHTML = "<center style=\"font: 12px Arial, Helvetica, sans-serif;\"><img src='http://img.labirint.ru/design/upload.gif'></center>";
		JsHttpRequest.query("geoTargeting.ajax.php", { "txt": txt, "type": type, "id_rule": id_rule }, function(result, errors) {
			if (result.err == 'no') {
				if (id_rule) {
					document.getElementById(type).value = '';
				}
				text.innerHTML = '';
				text.innerHTML = result.html;
			}
			else {
				text.innerHTML = result.log;
			}
		}, true);
	}
}

function add_user_tag(form, id_books) {
	var tag = form.tag.value;
	var path = id_books > 10000000 ? "ebooks" : "books";

	JsHttpRequest.query("/catalog/userTags.ajax.php", { "func": "addTag", "id_books": id_books, "tag": tag }, function(result, errors) {
		id_books = id_books > 10000000 ? id_books - 10000000 : id_books;
		if (result.err == undefined) {
			var cont = document.getElementById("tags-add-cont");
			var user_tags_main = document.getElementById("user-tags-main");

			if (document.getElementById("tags-added") == undefined) {
				var tags_added = document.createElement("div");
				tags_added.setAttribute("id", "tags-added");
				cont.insertBefore(tags_added, cont.firstChild);

				var tags_added_head = document.createElement("span");
				tags_added_head.setAttribute("id", "tags-added-head");
				tags_added.appendChild(tags_added_head);
				tags_added_head.innerHTML = "Добавлены: ";

				if (document.getElementById("all-tags") == undefined) {
					user_tags_main.className = "";

					var user_tags_bottom = document.getElementById("user-tags-bottom");
					var all_tags = document.createElement("div");
					all_tags.setAttribute("class", "right");
					user_tags_bottom.appendChild(all_tags);
					var all_tags_link = document.createElement("a");
					all_tags_link.setAttribute("href", "/tags/" + path + "/" + id_books + "/");
					all_tags_link.innerHTML = "Все метки...";
					all_tags.appendChild(all_tags_link);
				}
				else {
					var tn1 = document.createTextNode(", ");
					user_tags_main.appendChild(tn1);
				}

				var tag_added = document.createTextNode(result.tag3);
				tags_added.appendChild(tag_added);
			}
			else {
				var tags_added = document.getElementById("tags-added");
				if (tags_added.lastChild.nodeValue != undefined) {
					tags_added.lastChild.nodeValue = ", " + result.tag3 + " ";
				}
				else {
					var tag_added = document.createTextNode(", " + result.tag3 + " ");
					tags_added.appendChild(tag_added);
				}

				var tn1 = document.createTextNode(", ");
				user_tags_main.appendChild(tn1);
			}

			var added_delimg = document.createElement("img");
			added_delimg.setAttribute("src", "http://img.labirint.ru/design/user_tags_minus.gif");
			added_delimg.setAttribute("title", "Удалить метку");
			added_delimg.className = "imgbutton";
			tags_added.appendChild(added_delimg);
			var id = result.id;
			added_delimg.onclick = function() { del_user_tag(added_delimg, id); }

			var added_tag_link = document.createElement("a");
			added_tag_link.setAttribute("href", "/usertags/" + result.tagurl + "/");
			added_tag_link.innerHTML = result.tag2;
			user_tags_main.appendChild(added_tag_link);

			form.tag.value = "";
		}
		else {
			alert(result.err);
		}
	}, true);
}

function del_user_tag(delimg, id) {
	JsHttpRequest.query("/catalog/userTags.ajax.php", { "func": "delTag", "id": id }, function(result, errors) {
		if (result.err == undefined) {
			var tags_added = document.getElementById("tags-added");
			if (delimg && delimg.previousSibling != undefined) {
				var txt = delimg.previousSibling;

				if (txt.previousSibling != undefined && txt.previousSibling.id == "tags-added-head" && delimg.nextSibling != undefined) {
					delimg.nextSibling.nodeValue = delimg.nextSibling.nodeValue.substring(2);
				}

				tags_added.removeChild(delimg);
				tags_added.removeChild(txt);
			}
		}
		else {
			alert(result.err);
		}
	}, true);
}

function sendInquirer(id, result) {
	var inquirer = document.getElementById('inquirer-questions');
	var anons = document.getElementById('inquirer-anons');
	var arr = Array();
	var arr2 = Array();
	var name0;
	var i = 1;

	$("input[name^=que]:checked").each(
		function() {
			var name = $(this).attr("name");
			name = name.replace('que', '');
			if (name == name0) {
				arr[name][i] = $(this).attr("value");
				i++;
			}
			else {
				arr[name] = Array();
				arr[name][0] = $(this).attr("value");
			}

			name0 = name;
		}
	);

	$("textarea[name^=que]").each(
		function() {
			if ($(this).attr("value")) {
				var name = $(this).attr("name");
				name = name.replace('que', '')
				arr[name] = Array();
				arr[name][0] = $(this).attr("value");
			}
		}
	);

	if (arr.length > 0) {
		inquirer.style.height = "500px";
		inquirer.innerHTML = "<center style=\"font: 12px Arial, Helvetica, sans-serif; vertical-align: middle;\"><img style='vertical-align: middle; margin-top: 200px;' src='http://img.labirint.ru/design/upload_big.gif'></center>";

		JsHttpRequest.query("/catalog/inquirer.ajax.php", { "func": "delTag", "id": id, "que": arr, "result": result }, function(result, errors) {
			if (result.err == 'no') {
				inquirer.innerHTML = '';
				inquirer.innerHTML = result.html;
				inquirer.style.height = "auto";
			}
			else {
				inquirer.innerHTML = result.log;
			}
		}, true);
	}
	else
		alert('Ничего не выбрано');
}

function put_book(id_tov) {
	JsHttpRequest.query("/buy.php", { "id": id_tov, "put_book": 1 }, function(result, errors) {
		if (result.err == 'no') {
			if (document.getElementById('basket-in-dreambox-a') && result.put_book == 1) {
				var bcount = parseInt(document.getElementById('basket-in-dreambox-a').innerHTML)
				document.getElementById('basket-in-dreambox-a').innerHTML = bcount + 1;
			}

			var put = "put" + id_tov;
			for (i = 0; i < document.getElementsByTagName('span').length; i++) {
				var qq = document.getElementsByTagName('span')[i];
				if (qq.id == put) { qq.innerHTML = '&nbsp;<a href=\"/cabinet/putorder/\" title=\"Перейти в Отложенные\">Отложено</a>'; }
			}
		}
		else {
			var put = "put" + id_tov;
			for (i = 0; i < document.getElementsByTagName('span').length; i++) {
				var qq = document.getElementsByTagName('span')[i];
				if (qq.id == put) { qq.innerHTML = '<a href=\"/helpgopage/support/\">Отложить</a>'; }
			}
		}
	}, true);
}

function adviseVote(id) {
	var voting_div = document.getElementById("advise_vote" + id);
	var rating = document.getElementById("rating" + id);

	voting_div.innerHTML = "<center style=\"font: 12px Arial, Helvetica, sans-serif;\"> Загрузка...&nbsp; <img style=\"float: none; border: 0px solid #cccccc; margin:0;\" src='http://img.labirint.ru/design/upload_old.gif'></center>";

	JsHttpRequest.query("/catalog/commentVote.ajax.php", { "id_comment": id, "type": "advise" }, function(result, errors) {
		if (result.err == 'no') {
			voting_div.innerHTML = result.html;
			voting_div.style.color = '#8C8C8C';

			rating.innerHTML = result.rating;
			rating.style.color = result.color;
			rating.style.weight = 'bold';
		}
		else {
			voting_div.innerHTML = result.log;
		}
	}, true);
}

function dont_sendmail(id_contact, mailingType) {
	JsHttpRequest.query("/cabinet/dont_sendmail.php", { "id_contact": id_contact, "mailingType": mailingType }, function(result, errors) { }, true);
}

function comparing(id_tov, sgenre, retail) {
	JsHttpRequest.query("/compare.php", { "id": id_tov, "sgenre": sgenre }, function(result, errors) {
		var comp = "comp" + id_tov;
		for (i = 0; i < document.getElementsByTagName('span').length; i++) {
			qq = document.getElementsByTagName('span')[i];
			if (qq.id == comp) {
				var gnres = Array();
				tit = "Перейти к списку сравнения";
				gnres[-1] = "books/"; gnres[-2] = "video/"; gnres[-3] = "audio/"; gnres[-4] = "software/"; gnres[-5] = "games/"; gnres[-6] = "office/"; gnres[-7] = "other/"; gnres[-10] = "ebooks/";
				qq.innerHTML = (retail == 1 ? '<a href=\"/retail/compare/' + gnres[sgenre] + '\" class=\"addedincomp\" title=\"' + tit + '\"><nobr>Перейти к сравнению</nobr></a>' : '<a href=\"/compare/' + gnres[sgenre] + '\" class=\"addedincomp\" title=\"' + tit + '\"><nobr>Перейти к сравнению</nobr></a>');
			}
		}
		if (result.err != 'no') alert(result.err);
	}, true);
}

function getQIWIBill(id_order, mobile_pay) {
	var qiwi_newpay = 'qiwi_' + id_order;
	JsHttpRequest.query("/pay/qiwi/index.php", { "id_order": id_order, "mobile_pay": mobile_pay }, function(result, errors) {
		if (result.err == 'no' && document.getElementById('qiwi_pay')) {
			if (result.status) document.getElementById('qiwi_pay').innerHTML = 'Счет на оплату не создан, создать счет можно через <a href="/cabinet/hist/">Личное пространство</a>';
			else if (mobile_pay == 9) document.getElementById('qiwi_pay').innerHTML = 'Создан счет для оплаты в системе QIWI';
			else document.getElementById('qiwi_pay').innerHTML = 'Создан счет на оплату с баланса телефона';

			document.getElementById('qiwi_pay').style.display = 'block';
		}
		else if (result.err == 'no' && document.getElementById(qiwi_newpay)) {
			if (result.status) document.getElementById(qiwi_newpay).innerHTML = 'Попробуйте позже';
			else document.getElementById(qiwi_newpay).innerHTML = 'Создан счет';
		}
	}, true);
}

function addWish(wish) {
	if (document.getElementById('participate_contest_warning')) {
		document.getElementById('participate_contest_warning').innerHTML = '';
		document.getElementById('participate_contest_warning').style.display = 'none';
	}

	var subscription = '';
	if (wish.subscription1.checked) subscription += wish.subscription1.value;
	if (wish.subscription2.checked) subscription += ',' + wish.subscription2.value;
	if (wish.subscription3.checked) subscription += ',' + wish.subscription3.value;
	if (wish.subscription4.checked) subscription += ',' + wish.subscription4.value;
	if (wish.subscription5.checked) subscription += ',' + wish.subscription5.value;
	if (wish.subscription6.checked) subscription += ',' + wish.subscription6.value;
	if (wish.subscription7.checked) subscription += ',' + wish.subscription7.value;
	if (wish.subscription8.checked) subscription += ',' + wish.subscription8.value;

	JsHttpRequest.query("/basket/addWish.php", {
		"id_order": wish.id_order.value,
		"subscription": subscription,
		"wish_txt": wish.wish_txt.value,
		"pindex": wish.pindex.value,
		"country": wish.country.value,
		"pstate": wish.pstate.value,
		"city": wish.city.value,
		"street": wish.street.value,
		"building": wish.building.value,
		"building_p": wish.building_p.value,
		"fflat": wish.fflat.value,
		"lastName": wish.lastName.value,
		"firstName": wish.firstName.value,
		"middleName": wish.middleName.value
	}, function(result, errors) {
		if (result.err == 'no' && document.getElementById('participate_contest')) {

			if (result.rez_mess) {
				document.getElementById('participate_contest').innerHTML = result.rez_mess;
				if (document.getElementById('dopinfo')) document.getElementById('dopinfo').style.display = 'block';
				window.scrollTo(0, 0);
			}
			if (result.warning_mess) {
				$('#participate_contest_warning').html(result.warning_mess).css("display", "block");
			}
		}
	}, true);
}

function dontsavesort() {
	JsHttpRequest.query("/ajax.php", { "func": 'ajaxdontsavesort' }, function(result, errors) { }, true);
}

function buyecert() {
	var ecert_value = $("input[name=ecert_value]").val();
	if (!(ecert_value >= 100 && ecert_value <= 5000))
		alert('Не верное значение номинала!');
	else {
		JsHttpRequest.query("/buy.php", { "ecert_value": ecert_value }, function(result, errors) {
			if (result.err == 'no') {
				if (result.books_limit == 0) {
					if (document.getElementById('basket-in-cart-a')) {
						var bcount = parseInt(document.getElementById('basket-in-cart-a').innerHTML)
						document.getElementById('basket-in-cart-a').innerHTML = bcount + 1;
					}

					if (document.getElementById('basket-in-dreambox-a') && result.put_book == 1) {
						var bcount = parseInt(document.getElementById('basket-in-dreambox-a').innerHTML)
						document.getElementById('basket-in-dreambox-a').innerHTML = bcount + 1;
					}

					if (document.getElementById('fullsumprice') && document.getElementById('discsumprice').innerHTML && result.fullsumcena && result.sumcena) {
						document.getElementById('fullsumprice').innerHTML = result.fullsumcena;
						document.getElementById('discsumprice').innerHTML = result.sumcena;
					}

					$("input[name=ecert_value]").val('');
					$("#ecert_rez").html('Добавлен сертификат номинал ' + ecert_value + ' р., перейти в <a href="/basket/">корзину</a>');
				}
				else
					alert("В корзину нельзя положить более 100 электронных сертификатов!");
			}
			else
				$("#ecert_rez").html(result.error_message);
		}, true);
	}
}
