if (typeof FORUM_LOGIN_CHECK != "undefined" && document.cookie.match(/(?:^|;)\s*remembermel=/))
	location = "/autologin";

String.prototype.trim = function () {
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

String.prototype.htmlizeSpaces = function() {
	return this.replace(/[\n\r\s]+/g, " ");
}

String.prototype.nl2br = function() {
	return this.replace(/\n/g, "<br>");
}

var TRANSLIT_TBL = {'а':'a','б':'b','в':'v','г':'g','д':'d','е':'e','ё':'e','ж':'j','з':'z','и':'i','і':'i','ї':'yi','й':'y','к':'k','л':'l','м':'m','н':'n','о':'o','п':'p','р':'r','с':'s','т':'t','у':'u','ф':'f','х':'h','ц':'c','ч':'ch','ш':'sh','щ':'shch','ъ':'','ы':'y','ь':'','э':'e','є':'ye','ю':'yu','я':'ya',
		    'А':'A','Б':'B','В':'V','Г':'G','Д':'D','Е':'E','Ё':'E','Ж':'J','З':'Z','И':'I','І':'I','Ї':'Yi','Й':'Y','К':'K','Л':'L','М':'M','Н':'N','О':'O','П':'P','Р':'R','С':'S','Т':'T','У':'U','Ф':'F','Х':'H','Ц':'C','Ч':'Ch','Ш':'Sh','Щ':'Shch','Ъ':'','Ы':'Y','Ь':'','Э':'E','Є':'Ye','Ю':'Yu','Я':'Ya'};
var TRANSLIT_MAX_LEN = 40;
String.prototype.translit = function () {
	var data = this.trim();
	var result = "";
	for (var i = 0, j = this.length; i != j; i++) {
		var ch = this.charAt(i);
		result += typeof TRANSLIT_TBL[ch] == "undefined" ? ch : TRANSLIT_TBL[ch];
	}
	result = result.replace(/[\s\n\r]+/g, "_").replace(/[^\w\.\-]/g, "");
	if (result.length > TRANSLIT_MAX_LEN) {
		if ("_.-".indexOf(result.charAt(TRANSLIT_MAX_LEN)) >= 0)
			return result.substring(0, TRANSLIT_MAX_LEN);
		return result.substring(0, TRANSLIT_MAX_LEN).replace(/[_\.\-][^_\.\-]*$/, "");
	}
	return result;
}

// Safari 2.0.4, and suppose below crash on ajaxed login
buddySafariRe = new RegExp("Safari/([\\d\\.]+)$");
buggySafariMatch = buddySafariRe.exec(navigator.userAgent);
buggySafariVer = buggySafariMatch == null ? 0 : parseFloat(buggySafariMatch[1]);
buggySafari = buggySafariMatch != null && !isNaN(buggySafariVer) && buggySafariVer <= 419.3;

UI_AUTOROTATE_TABS_PERIOD = 5000;
UI_AUTOROTATE = null;

var LOGIN_FORM_HIGHER = false;

var HASH_CHUNKS = location.hash.toString();
var SEARCH_STRING = null;
var SEARCH_START = 0;
if (location.pathname == "/search") {
	if (HASH_CHUNKS.charAt(0) != '#') location = "/";
	SEARCH_STRING = HASH_CHUNKS.substring(1);
	var matches = SEARCH_STRING.match(/^start=(\d+),(.*)$/);
	if (matches == null) location = "/";
	SEARCH_START = matches[1];
	SEARCH_STRING = decodeURI(matches[2].trim());
	if (SEARCH_STRING == "") location = "/";
	HASH_CHUNKS = null;
} else if (HASH_CHUNKS.charAt(0) == '#')
	HASH_CHUNKS = HASH_CHUNKS.substring(1).split(",");
else
	HASH_CHUNKS = null;

var LOGIN_OPTIONS = {
	url: '/login/',
	success: function(responseText) {
		if ('redirect' == responseText['status']) {
			if (responseText['text'])
				location = responseText['text'];
			else {
				var form = $("#loginForm");
				var redirect = form.attr("redirect");
				if (redirect == null) {
					var hash = location.hash;
					if (hash == "#loginme")
						location = location.protocol + "//" + location.host + location.pathname + location.search;
					else
						location.reload();
				} else if (redirect.substring(0, 11) == "javascript:") {
					eval(redirect.substring(11));
					return false;
				} else {
					if (form.attr("redirectProfile")) redirect = "/user/" + responseText["id"] + redirect;
					location = redirect;
				}
			}
		}
		if ('error' == responseText['status']) $("#loginForm div.error").show().fadeOut(7000, function() { $("#loginForm input[type='submit']").attr('disabled', '') }).html(responseText['text']);
		$("#loginIndicator").hide();
		return false;
	},
	beforeSubmit: function(formArray, jqForm) { $("#loginIndicator").show() },
	dataType: 'json'
};

$(function($) {
	adjustHeader();
	bindGlobal();
	$().ajaxStop(function(){bindGlobal()});
	$(".block .tabs.interactive td,.block .tabs.interactive li").click(function() {
		var td = $(this);
		if (td.hasClass("garbage")) return false;
		uiInteractiveTabsClick(td);
		var table = td.get(0).tagName.toLowerCase() == "td" ? td.parent().parent().parent() : td.parent();
		if (table.hasClass("autorotate") || table.hasClass("customAutorotate")) {
			table.removeClass("autorotate");
			table.removeClass("customAutorotate");
			UI_AUTOROTATE = $(".block .tabs.interactive.autorotate");
		}
		return false;
	});

	UI_AUTOROTATE = $(".block .tabs.interactive.autorotate");
	if (UI_AUTOROTATE.length > 0)
		setTimeout(uiAutorotateTabs, UI_AUTOROTATE_TABS_PERIOD);

	$("#lostpass").click(function(){ tb_show('', this.href+'?height=200&width=240', false); return false });

	$("img.autoResize").each(function () { uiImgAutosize($(this)) });

	$(".dots3").each(function () {
		var it = $(this);
		it.ThreeDots({ max_rows : it.attr("rows") });
	});

	$(".imgPosition").each(function () {
		var it = $(this);
		var dst = $(it.attr("imgPositionDst"));
		var dstObj = dst.get(0);
		dstObj.onload = function () {
			var pos = dst.position();
			var width = pos.left + dst.width();
			var height = pos.top + dst.height();
			it.css({ left : eval(it.attr("imgPositionX")) + "px", top : eval(it.attr("imgPositionY")) + "px" }).show();
		};
		if (dstObj.complete) dstObj.onload();
	});

	themeInit();
	editorToolsInit();
	randomGalleriesInit("");
	randomGalleriesInit("Contest");
	randomGalleriesInit("Main");
	randomGalleriesInit("MainCards");
	pollInit();
	gamesRotatorInit();
	faqRotatorInit();
	childrenSpeakRotatorInit();
	banktestRotatorInit();
	creativeRotatorInit();
	newItemsRotatorInit();
	forumRotatorInit();
	rateInit();

	$("div.hdrSearch input").val(SEARCH_STRING == null ? "поиск по сайту" : SEARCH_STRING).attr("nonempty", SEARCH_STRING == null ? "" : 1).focus(function () {
		var me = $(this);
		if (me.attr("nonempty") != 1) me.val("");
	}).blur(function () {
		var me = $(this);
		if (me.val().trim() == "") me.val("поиск по сайту").attr("nonempty", "");
		else me.attr("nonempty", 1);
	}).keyup(function (e) {
		var me = $(this);
		if (e.keyCode == 13 && me.val().trim() != "") {
			me.attr("nonempty", 1);
			search_search();
		}
	});
	$("div.hdrSearch a").attr({ "href" : "#", "title" : "Искать!"}).click(search_search);
	if (SEARCH_STRING != null) search_execute(SEARCH_STRING, SEARCH_START);

	if (HASH_CHUNKS != null)
		for (var i = 0; i != HASH_CHUNKS.length; i++)
			if (HASH_CHUNKS[i] == "loginme") {
				if (i + 1 < HASH_CHUNKS.length && HASH_CHUNKS[i + 1].substring(0, 8) == "confirm=") {
					var code = HASH_CHUNKS[i + 1].substring(8);
					$(code == "10" ? "#loginFormRegReconfirm" : "#loginFormRegConfirm").show();
					HASH_CHUNKS.splice(i, 2);
					location = location.search + "#" + HASH_CHUNKS.join(",");
					LOGIN_FORM_HIGHER = true;
				} else {
					HASH_CHUNKS.splice(i, 1);
					location = location.search + "#" + HASH_CHUNKS.join(",");
					if (!$("#login").length)
						break;
				}
				loginClick();
				break;
			} else if (HASH_CHUNKS[i].substring(0, 10) == "highlight=") {
				highlightTerms(HASH_CHUNKS[i].substring(10));
				break;
			}
});

function adjustHeader() {
	var div = $(".leftfoot");
	div.css("padding-left", (445 - div.width()) + "px");
	div = $(".menu");
	var a = $(".menu a:last");
	var xh = a.position().top + a.outerHeight();
	var h = div.height();
	if (xh > h) {
		xh -= h;
		div.css("margin-top", (parseInt(div.css("margin-top")) - xh) + "px");
		var le = $(".menu .left.ear");
		le.height(le.height() + xh);
	}
}

function loginClick() {
	var it = this == window ? null : $(this);
	var form = $("#loginForm");
	if (it != null) form.attr("redirect", it.attr("redirect"));
	if (it != null && it.attr("redirectProfile")) form.attr("redirectProfile", true);
	else form.removeAttr("redirectProfile");
	form.submit(function(e) { $(this).ajaxSubmit(LOGIN_OPTIONS); return false });
	form.find("div.error").hide();
	var hgt = 260;
	if (LOGIN_FORM_HIGHER) {
		hgt = 330;
		LOGIN_FORM_HIGHER = false;
	} else
		$("#loginFormRegReconfirm,#loginFormRegConfirm").hide();
	tb_show("", { width : 260, height : hgt, data: form }, false);
	return false;
}

function bindGlobal() {
	if (!buggySafari) {
		$(".loginHref").unbind('click').click(loginClick);
		$(".logoutHref").unbind('click').click(function() {
			var options = {
				url: "/logout/",
				dataType: "json",
				success: function(response, status) {
					location.reload();
				}
			};
			$.ajax(options);
			return false;
		});
	}

	if ($("#photoInfo").length == 0) $("body").append("<div id=photoInfo usedId=0><div class=photoInfoTitle></div><div class=photoInfoCreated>Загружена: <span></span></div><div class=photoInfoRate>Рейтинг: <span></span></div><div class=photoInfoComments>Комментариев: <span></span></div></div>");
	$(".photoInfo").unbind("mouseenter mouseleave").hover(photoInfo_hover, photoInfo_unhover);
}

function search_search() {
	var input = $("div.hdrSearch input");
	if (input.attr("nonempty") != 1) {
		input.focus();
		return false;
	}
	var token = input.val().trim();
	input.val(token);
	location = "/search#start=0," + token;
	if (location.pathname == "/search") search_execute(SEARCH_STRING = token, 0);
	return false;
}

function highlightTerms(terms) {
	terms = terms.trim().split(/[\s\n\r]+/);
	var neTerms = [];
	for (var i = 0; i != terms.length; i++)
		if (terms[i].length != 0) neTerms[neTerms.length] = terms[i].replace(/([\\\|\[\]\*\.\?\(\)])/g, "\\$1");
	terms = new RegExp(terms.join("|"), "gi");
	var firstMatch = null;
	var replacer = function (element) {
		var childNodes = element.childNodes;
		var len = childNodes.length;
		while (len--) {
			var node = childNodes[len];
			var name = node.nodeName.toLowerCase();
			if (name == "html" || name == "head" || name == "style" || name == "title" || name == "link" || name == "meta" || name == "script" || name == "object" || name == "embed" || name == "iframe") continue;
			if (node.nodeType === 1 && element.childNodes.length != 0)
				replacer(node);
			if (node.nodeType !== 3 || !terms.test(node.data)) continue;
			var pos = -1;
			var chunks = [];
			var data = node.data;
			var localFirstMatch = null;
			var match;
			var lastIndex = 0;
			terms.lastIndex = 0;
			while ((match = terms.exec(data)) != null) {
				if (match["index"] > lastIndex) chunks[chunks.length] = document.createTextNode(data.substring(lastIndex, match["index"]));
				var innerText = document.createTextNode(match[0]);
				var span = document.createElement("span");
				span.className = "highlight";
				span.appendChild(innerText);
				chunks[chunks.length] = span;
				if (localFirstMatch == null) localFirstMatch = span;
				lastIndex = terms.lastIndex;
			}
			firstMatch = localFirstMatch;
			if (lastIndex != 0 && lastIndex != data.length) chunks[chunks.length] = document.createTextNode(data.substring(lastIndex));
			for (var i = 0; i != chunks.length; i++)
				element.insertBefore(chunks[i], node);
			element.removeChild(node);
		}
	};
	replacer(document.body);
	if (firstMatch !== null) $.scrollTo(firstMatch);
}

function uiImgAutosize(jq) {
	var img = new Image();
	var boxWidth = jq.attr("bwidth");
	var boxHeight = jq.attr("bheight");
	var afterSized = jq.attr("afterSized");
	img.onload = function () {
		var box = imgGetBox(this.width, this.height, boxWidth, boxHeight);
		jq.attr({ "width" : box["w"], "height" : box["h"] }).show();
		if (afterSized != null && afterSized != "") eval(afterSized);
	};
	var parent = jq.parent("div.img");
	if (parent.length > 0)
		img.onerror = img.onabort = function () {
			parent.hide();
			if (afterSized != null && afterSized != "") eval(afterSized);
		};
	img.src = jq.attr("src");
}

function uiInteractiveTabsClick(td) {
	if (td.hasClass("active")) {
		var a = td.find("a");
		if (a.length) {
			a = a.attr("href");
			if (a != "" && a != "#")
				location = a;
		}
		return;
	}
	var container = td.get(0).tagName.toLowerCase() == "td" ? td.parent().parent().parent() : td.parent();
	container = container.next();
	var c5 = container.find('.c5');
	if (td.prev().length == 0)
		c5.addClass('nobg');
	else
		c5.removeClass('nobg');
	td.siblings().removeClass('active');
	td.addClass('active');
	var data = container.find(".data");
	var id = td.attr("id");
	data.each(function (index) {
		if ($(this).attr("data") == id) $(this).addClass("show"); else $(this).removeClass("show");
	});
}

function uiAutorotateTabs() {
	if (UI_AUTOROTATE.length == 0) return;
	UI_AUTOROTATE.each(function (index) {
		var active = $(this).find("td.active");
		var next = active.next();
		if (next.length == 0) next = active.prevAll().first();
		uiInteractiveTabsClick(next);
	});
	setTimeout(uiAutorotateTabs, UI_AUTOROTATE_TABS_PERIOD);
}

function photoInfo_hover(event) {
	var it = $(this);
	var id = it.attr("id").substring(9);
	var checkId = it.attr("checkId") == 1;
	var photoInfo = $("#photoInfo");
	if (checkId || photoInfo.attr("usedId") != id) {
		var ref = it.attr("dataRef");
		var elemA = ref == null || ref == "" ? $("#imgBox" + id + " a").eq(0) : (ref == "me" ? it : $(ref).eq(0));
		if (!checkId || elemA.attr("checkId") != id) {
			var title = elemA.attr("title");
			if (title == null || title == "") title = elemA.attr("xtitle");
			if (title == null) title = "";
			$("#photoInfo .photoInfoTitle").text(title);
			var created = elemA.attr("created");
			if (created != null && created != "")
				$("#photoInfo .photoInfoCreated span").text(new Date(elemA.attr("created") * 1000).format("shortDate")).show();
			else
				$("#photoInfo .photoInfoCreated").hide();
			$("#photoInfo .photoInfoComments span").text(elemA.attr("comments"));
			$("#photoInfo .photoInfoRate span").text(elemA.attr("rating") / (elemA.attr("contestratemode") == "1" ? 5 : 100));
			var w = photoInfo.width();
			var left = event.pageX + 12;
			if (left + w > $(document).width())
				left -= (w + 30);
			photoInfo.css({ "left" : left + "px", "top" : (event.pageY + 6) + "px" }).attr("usedId", id);
		}
	}
	if (photoInfo.attr("shown") != 1)
		photoInfo.attr("shown", 1).fadeIn(600);
}

function photoInfo_unhover() {
	$("#photoInfo").attr("shown", "").fadeOut(600);
}

// Gallery random image
var RANDOM_GALLERIES_IMAGES = { "" : 1, "Contest" : 1, "Main" : 3, "MainVideo" : 3, "MainCards" : 1 };
var RANDOM_GALLERIES_ROTATE_PERIOD = { "" : 10000, "Contest" : 10000, "Main" : 10000, "MainVideo" : 10000, "MainCards" : 10000 };
var RANDOM_GALLERIES_BOX_WIDTH = { "" : 198, "Contest" : 110, "Main" : 60, "MainVideo" : 60, "MainCards" : 60 };
var RANDOM_GALLERIES_BOX_HEIGHT = { "" : 198, "Contest" : 110, "Main" : 90, "MainVideo" : 90, "MainCards" : 90 };
var RANDOM_GALLERIES_IMGPREFIX = { "" : "", "Contest" : "", "Main" : "", "MainVideo" : "/upload/", "MainCards" : "/cards/" };
var RANDOM_GALLERIES_HORIZONTAL = { "" : false, "Contest" : false, "Main" : true, "MainVideo" : true, "MainCards" : true };
var RANDOM_GALLERIES_URL = { "" : "", "Contest" : "", "Main" : "", "MainVideo" : "/videos/%s.html", "MainCards" : "/cards/edit/?id=%s" };
var RANDOM_GALLERIES_CACHE = 15;

var RANDOM_GALLERIES_LASTQUERIED = { "" : 0, "Contest" : 0, "Main" : 0, "MainVideo" : 0, "MainCards" : 0 };
var RANDOM_GALLERIES_DATA = { "" : [], "Contest" : [], "Main" : [], "MainVideo" : [], "MainCards" : [] };
var RANDOM_GALLERIES_SLOTS = { "" : 0, "Contest" : 0, "Main" : 0, "MainVideo" : 0, "MainCards" : 0 };
var RANDOM_GALLERIES_POS = { "" : 0, "Contest" : 0, "Main" : 0, "MainVideo" : 0, "MainCards" : 0 };
var RANDOM_GALLERIES_SUBTITLE = { "" : true, "Contest" : false, "Main" : true, "MainVideo" : true, "MainCards" : false };
var RANDOM_GALLERIES_SUBTITLE_POPUP = { "" : true, "Contest" : false, "Main" : false, "MainVideo" : false, "MainCards" : false };
var RANDOM_GALLERIES_SUBTITLE_FIXED = { "" : false, "Contest" : false, "Main" : true, "MainVideo" : true, "MainCards" : false };
var RANDOM_GALLERIES_MAIN_VIDEO_INITED = false;

function RANDOM_GALLERIES_ROTATOR_MAIN_CB() {
	$("#photoVideoImg1").css("visibility", "hidden");
	$("#photoVideoImg3").css("visibility", "visible");
	uiInteractiveTabsClick($("#photoVideoVideo"));
}

function RANDOM_GALLERIES_ROTATOR_MAINVIDEO_CB() {
	$("#photoVideoImg3").css("visibility", "hidden");
	$("#photoVideoImg1").css("visibility", "visible");
	uiInteractiveTabsClick($("#photoVideoPhoto"));
}

var RANDOM_GALLERIES_ROTATOR = { "Main" : function () {
	if (RANDOM_GALLERIES_MAIN_VIDEO_INITED) randomGalleriesRotate("MainVideo", RANDOM_GALLERIES_ROTATOR_MAIN_CB);
	else {
		randomGalleriesInit("MainVideo");
		RANDOM_GALLERIES_MAIN_VIDEO_INITED = true;
		RANDOM_GALLERIES_ROTATOR_MAIN_CB();
	}
}, "MainVideo" : function () {
	randomGalleriesRotate("Main", RANDOM_GALLERIES_ROTATOR_MAINVIDEO_CB);
} };
var RANDOM_GALLERIES_ONCHANGE = { "MainCards" : function (data) {
	$("#birthdayCard").attr("href", "/cards/edit/?id=" + data["id"]);
} };
var RANDOM_GALLERIES_OPTIONS = {
	"" : {
		url: "/gallery/getrandom",
		data: { "cnt" : RANDOM_GALLERIES_CACHE * RANDOM_GALLERIES_IMAGES[""] },
		dataType: "json",
		success: function(response, status) {
			randomGalleriesResponseOk(response, "");
		},
		error: function(request, status, err) {
			randomGalleriesResponseErr("");
			return false;
		}
	},
	"Contest": {
		url: "/gallery/getrandomcontest",
		data: { "cnt" : RANDOM_GALLERIES_CACHE * RANDOM_GALLERIES_IMAGES["Contest"] },
		dataType: "json",
		success: function(response, status) {
			randomGalleriesResponseOk(response, "Contest");
		},
		error: function(request, status, err) {
			randomGalleriesResponseErr("Contest");
			return false;
		}
	},
	"Main" : {
		url: "/gallery/getrandom",
		data: { "cnt" : RANDOM_GALLERIES_CACHE * RANDOM_GALLERIES_IMAGES["Main"] },
		dataType: "json",
		success: function(response, status) {
			randomGalleriesResponseOk(response, "Main");
		},
		error: function(request, status, err) {
			randomGalleriesResponseErr("Main");
			return false;
		}
	},
	"MainVideo" : {
		url: "/videos/getrandom",
		data: { "cnt" : RANDOM_GALLERIES_CACHE * RANDOM_GALLERIES_IMAGES["MainVideo"] },
		dataType: "json",
		success: function(response, status) {
			randomGalleriesResponseOk(response, "MainVideo");
		},
		error: function(request, status, err) {
			randomGalleriesResponseErr("MainVideo");
			return false;
		}
	},
	"MainCards" : {
		url: "/cards/getrandom",
		data: { "cnt" : RANDOM_GALLERIES_CACHE * RANDOM_GALLERIES_IMAGES["MainCards"] },
		dataType: "json",
		success: function(response, status) {
			randomGalleriesResponseOk(response, "MainCards");
		},
		error: function(request, status, err) {
			randomGalleriesResponseErr("MainCards");
			return false;
		}
	}
};

function imgGetBox(w, h, bw, bh) {
	if (w > bw || h > bh) {
		var coef1 = bh / h, coef2 = bw / w;
		if (coef1 > coef2) coef1 = coef2;
		h = Math.round(h * coef1);
		w = Math.round(w * coef1);
	}
	return {"w" : w, "h" : h};
}

function randomGalleriesResponseOk(response, profile) {
	if (response.length > 0) {
		RANDOM_GALLERIES_DATA[profile] = response;
		RANDOM_GALLERIES_LASTQUERIED[profile] = RANDOM_GALLERIES_DATA[profile].length;
		RANDOM_GALLERIES_LASTQUERIED[profile] = RANDOM_GALLERIES_DATA[profile].length;
		$("#galleryRandom" + profile + "NoPhoto").hide();
		randomGalleriesRotate(profile);
	} else
		randomGalleriesResponseErr(profile);
}

function randomGalleriesResponseErr(profile) {
	$("#galleryRandom" + profile + "Loading").hide();
	$("#galleryRandom" + profile + "Photos").hide();
	$("#galleryRandom" + profile + "NoPhoto").show();
}

function randomGalleriesInit(profile) {
	if ($("#galleryRandom" + profile + "Loading").length == 0) return;
	$.ajax(RANDOM_GALLERIES_OPTIONS[profile]);
}

function randomGalleriesEnsureSlots(slots, profile) {
	if (RANDOM_GALLERIES_SLOTS[profile] == slots) return;
	var width = slots ? Math.round(100 / slots) : 0;
	if (RANDOM_GALLERIES_SLOTS[profile] > slots) {
		for (var i = slots; i != RANDOM_GALLERIES_SLOTS[profile]; i++)
			$("#galleryRandom" + profile + "Photo" + i).remove();
	} else {
		for (var i = RANDOM_GALLERIES_SLOTS[profile]; i != slots; i++) {
			var container, prefix, suffix;
			if (RANDOM_GALLERIES_HORIZONTAL[profile]) {
				container = $("#galleryRandom" + profile + "Photos table.images > tbody > tr");
				prefix = '<th id=galleryRandom' + profile + 'Photo' + i + ' style="display:none;width:' + width + '%">';
				suffix = '</th>';
			} else {
				container = $("#galleryRandom" + profile + "Photos table.images");
				prefix = '<tr id=galleryRandom' + profile + 'Photo' + i + ' style="display:none"><th style="width:' + (RANDOM_GALLERIES_BOX_WIDTH[profile] + 42) + 'px">';
				suffix = '</th></tr>';
			}
			container.append(prefix + '<center><div class=imgBoxLarge id=imgBoxRG' + profile + i + '><center><table cellspacing=0 cellpadding=0><tr class=image><th colspan=2><div class=imgBoxUpper><div><table cellspacing=0 cellpadding=0><tr><th><a href="#" id=galleryRandom' + profile + 'PhotoA' + i + '><img id=galleryRandom' + profile + 'PhotoImg' + i + '></a></th></tr></table></div></div></th></tr>' + (RANDOM_GALLERIES_SUBTITLE[profile] ? '<tr class=subtitle><th></th>' + (RANDOM_GALLERIES_SUBTITLE_POPUP[profile] ? '<td><img src=/img/front/gallery/i.png align=absmiddle class=photoInfo checkId=1 id=photoInfoRG' + profile + i + '></td>' : '') + '</tr>' : '') + '</table></center></div></center>' + suffix);
			if (RANDOM_GALLERIES_SUBTITLE[profile] && RANDOM_GALLERIES_SUBTITLE_POPUP[profile]) $("#galleryRandom" + profile + "Photo" + i + " .photoInfo").hover(photoInfo_hover, photoInfo_unhover);
			$("#galleryRandom" + profile + "Photo" + i).fadeIn(600);
		}
			
	}
	for (var i = 0, j = Math.min(slots, RANDOM_GALLERIES_SLOTS[profile]); i != j; i++)
		$('#galleryRandom' + profile + 'Photo' + i).css("width", width + "%");
	RANDOM_GALLERIES_SLOTS[profile] = slots;
}

function randomGalleriesRotate(profile, onloadCb) {
	randomGalleriesIterate({"i" : 0, "limit" : Math.min(RANDOM_GALLERIES_IMAGES[profile], RANDOM_GALLERIES_LASTQUERIED[profile]), "images" : []}, profile, onloadCb);
}

function randomGalleriesIterate(state, profile, onloadCb) {
	var image = new Image();
	var pos = (RANDOM_GALLERIES_POS[profile] + state["i"]) % RANDOM_GALLERIES_DATA[profile].length;
	var data = RANDOM_GALLERIES_DATA[profile][pos];
	var last = (state["i"] + 1 == state["limit"]);
	image.onload = function() {
		image.onload = image.onerror = image.onabort = null;
		state["images"][state["images"].length] = { "image" : image, "data" : data };
		if (last) {
			RANDOM_GALLERIES_POS[profile] = (RANDOM_GALLERIES_POS[profile] + state["limit"]) % RANDOM_GALLERIES_DATA[profile].length;
			randomGalleriesShow(state["images"], profile, onloadCb);
		} else {
			state["i"]++;
			randomGalleriesIterate(state, profile, onloadCb);
		}
	};
	image.onerror = image.onabort = function() {
		image.onload = image.onerror = image.onabort = null;
		if (RANDOM_GALLERIES_DATA[profile].length == state["limit"])
			$.ajax(RANDOM_GALLERIES_OPTIONS[profile]);
		else {
			for (var i = pos + 1; i < RANDOM_GALLERIES_DATA[profile].length; i++)
				RANDOM_GALLERIES_DATA[profile][i - 1] = RANDOM_GALLERIES_DATA[profile][i];
			RANDOM_GALLERIES_DATA[profile].length = RANDOM_GALLERIES_DATA[profile].length - 1;
			randomGalleriesIterate(state, profile);
		}
	};
	image.src = (RANDOM_GALLERIES_IMGPREFIX[profile] != "" ? RANDOM_GALLERIES_IMGPREFIX[profile] : "/img/gallery/") + data["image_small"];
}

function randomGalleriesShowImage(i, imageData, profile) {
	var image = imageData.image;
	var data = imageData.data;
	var oldSrc = $("#galleryRandom" + profile + "PhotoImg" + i).attr("src");
	var box = imgGetBox(data["width"], data["height"], RANDOM_GALLERIES_BOX_WIDTH[profile], RANDOM_GALLERIES_BOX_HEIGHT[profile]);
	var href = RANDOM_GALLERIES_URL[profile] != "" ? RANDOM_GALLERIES_URL[profile].replace(/%s/, data["url"]) : "/gallery/" + data["parent_url"] + "#photo" + data["url"];
	if (oldSrc) {
		if (oldSrc == image.src) return;
		$("#galleryRandom" + profile + "Photo" + i).fadeTo(600, 0.05, function() {
				$("#galleryRandom" + profile + "PhotoImg" + i).css({"width" : box["w"] + "px", "height" : box["h"] + "px"}).attr({"src": image.src, "title" : data["title"]});
				$("#galleryRandom" + profile + "PhotoA" + i).attr({"href" : href, "title" : data["title"], "created" : data["created_ts"], "comments" : data["comments_cnt"], "rating" : data["compound_rating"], "checkId" : data["id"]});
				$(this).fadeTo(600, 1);
		});
	} else {
		$("#galleryRandom" + profile + "PhotoImg" + i).css({"width" : box["w"] + "px", "height" : box["h"] + "px"}).attr({"src": image.src, "title" : data["title"]});
		$("#galleryRandom" + profile + "PhotoA" + i).attr({"href" : href, "created" : data["created_ts"], "comments" : data["comments_cnt"], "rating" : data["compound_rating"], "checkId" : data["id"]});
	}
	var hdr = $("#galleryRandom" + profile + "Photos h1 a");
	if (hdr.length)
		hdr.text(data["parent_title"]).attr("href", "/gallery/" + data["parent_url"] + "/contest");
	if (RANDOM_GALLERIES_SUBTITLE[profile]) {
		$("#imgBoxRG" + profile + i + ",#photoInfoRG" + i).attr("binding", data["id"]);
		var ownerIcon = data["favourite_owner"] ? '<img class=icon src=/img/front/gallery/small-heart.png style="background:url(/img/front/gallery/user.png)" align=absmiddle>' : '<img class=icon src=/img/front/gallery/user.png align=absmiddle>';
		$("#imgBoxRG" + profile + i + " tr.subtitle th").html((RANDOM_GALLERIES_SUBTITLE_FIXED[profile] ? "<div style='height:10px;width:" + (box["w"] + 12) + "px;overflow:visible'>" : "") +
							    (data["owner"] ?
								'<a href="/user/' + data["owner"] + '/profile">' + ownerIcon + ' <u></u></a>&nbsp;' :
								ownerIcon + ' <span style="font-weight:normal">Мамина умничка&nbsp;</span>') +
							    (RANDOM_GALLERIES_SUBTITLE_FIXED[profile] ? "</div>" : ""));
		if (data["owner"]) {
			var name = data["owner_name"];
			var dots = false;
			var maxLen = Math.round(box["w"] / 9);
			if (name.length > maxLen) {
				name = name.substring(0, maxLen - 1);
				dots = true;
			}
			var nameContainer = $("#imgBoxRG" + profile + i + " tr.subtitle th u");
			nameContainer.text(name);
			if (dots) nameContainer.append("&hellip;").attr("title", data["owner_name"]);
		}
	}
	if (typeof RANDOM_GALLERIES_ONCHANGE[profile] == "function")
		RANDOM_GALLERIES_ONCHANGE[profile](data);
}

function randomGalleriesShow(images, profile, onloadCb) {
	$("#galleryRandom" + profile + "Loading").hide();
	$("#galleryRandom" + profile + "Photos").show();
	randomGalleriesEnsureSlots(images.length, profile);
	for (var i = 0; i != images.length; i++)
		randomGalleriesShowImage(i, images[i], profile);
	if (typeof onloadCb == "function") onloadCb();
	setTimeout(typeof RANDOM_GALLERIES_ROTATOR[profile] == "function" ?
			RANDOM_GALLERIES_ROTATOR[profile] :
			function() { randomGalleriesRotate(profile) },
		   RANDOM_GALLERIES_ROTATE_PERIOD[profile]);
}

var POLL_OPTIONS = {
	dataType: "json",
	success: function(response, status) {
		if (response["options"] == null || response["options"].length == 0) return false;
		$("#pollTitle").text(response["title"]);
		var votable = response["votable"] && response["votable"] != 0 && response["votable"] != "";
		for (var key in response['options']) {
			var option = response['options'][key];
			$("#pollsResults").append("<tr><td><span id=pollResTitle" + option.id + "></span><br><div class=pollbar id=pollsStatus" + option.id + ">&nbsp;</div><div class=pollval id=pollsValue" + option.id + "></div></td></tr>");
			$("#pollResTitle" + option.id).text(option.title);
			if (!votable) {
				$("#pollsStatus" + option.id).width(response['total'] ? Math.round(option.value * 150 / response['total']) : 0);
				$("#pollsValue" + option.id).text(option.value);
			}
		}
		if (votable) {
			for (var key in response['options']) {
				var option = response['options'][key];
				$("#formPolls table").append("<tr><td><input type=radio value=" + option.id + " name=option id=polloption" + option.id + "></td><td><label for=polloption" + option.id + ">&nbsp;<span id=pollLabel" + option.id + "></span></label></td></tr>");
				$("#pollLabel" + option.id).text(option.title);
			}
			$("#pollId").val(response.id);
			$("#formPolls").show();
		} else {
			if (response["require_registration"] && response["require_registration"] != 0 && response["require_registration"] != "")
				$("#pollRequireReg").show();
			$("#pollsResults").show();
		}
		$("#pollBlock").show();
	},
	error: function(request, status, err) {
		return false;
	}
};

var POLL_VOTE_OPTIONS = {
	url: '/polls/vote',
	dataType: "json",
	type : "POST",
	success: function(response) {
		if ('error' == response['status']) {
			$("#pollsErrorDiv").show().fadeOut(7000).html(response['text']);
			$("#indicatorPolls").hide();
		} else {
			$("#pollsThanksDiv").show();
			$("#indicatorPolls").hide();
			$("#formPolls").hide();
			if (response['options']) {
				$("#pollsThanksDiv").fadeOut(7000);
				for (var option in response['options']) {
					var val = response['options'][option]['value'];
					$("#pollsStatus" + option).width(val * 150 / response['total']);
					$("#pollsValue" + option).text(val);
				}
				$("#pollsResults").show();
			}
			return false;
		}
	},
	beforeSubmit: function(formArray, jqForm) {
		$("#indicatorPolls").show();
	}
};

function pollInit() {
	if (typeof POLL_PLACE_ID == "undefined") return;
	POLL_OPTIONS["url"] = "/polls/" + POLL_PLACE_ID;
	$('#formPolls').submit(function() {
		if ($('#formPolls input[type=radio]:checked').length == 0) return false;
		$(this).ajaxSubmit(POLL_VOTE_OPTIONS);
		return false;
	});
	$.ajax(POLL_OPTIONS);
}

GAMES_ROTATOR_PERIOD = 3000;

function gamesRotatorInit() {
	if ($("#gamesRotator").length)
		setTimeout(gamesRotatorRotate, GAMES_ROTATOR_PERIOD);
}

function gamesRotatorRotate() {
	var active = $("#gamesRotator tr.active");
	var next = active.next();
	if (next.length == 0) next = active.parent().children().first();
	active.removeClass("active");
	next.addClass("active");
	setTimeout(gamesRotatorRotate, GAMES_ROTATOR_PERIOD);
}

FAQ_ROTATOR_PERIOD = 5000;
FAQ_ROTATOR_POS = 0;
FAQ_QUESTION_3D = null;
FAQ_ANSWER_3D = null;

function faqRotatorInit() {
	if ($("#faqQuestionWrapper").length != 0) $("#faqQuestionWrapper").ThreeDots({ max_rows : 3 });
	if ($("#faqAnswerWrapper").length != 0) $("#faqAnswerWrapper").ThreeDots({ max_rows : 4 });
	if (typeof FAQ_QUESTIONS == "undefined" || FAQ_QUESTIONS.length < 2) return;
	setTimeout(faqRotatorRotate, FAQ_ROTATOR_PERIOD);
}

function faqRotatorRotate() {
	if (++FAQ_ROTATOR_POS >= FAQ_QUESTIONS.length) FAQ_ROTATOR_POS = 0;
	var q = FAQ_QUESTIONS[FAQ_ROTATOR_POS];
	$("#faqQuestion").text(q["question"]);
	$("#faqQuestionWrapper").attr("threedots", q["question"]).ThreeDots({ max_rows : 3 });
	$("#faqAnswer").text(q["answer"]);
	$("#faqAnswerWrapper").attr("threedots", q["answer"]).ThreeDots({ max_rows : 4 });
	if (q["consultant_name"] != null && q["consultant_type"] != null)
		$("#faqConsultant").text(q["consultant_type"] + " " + q["consultant_name"]);
	else
		$("#faqConsultant").text("");
	setTimeout(faqRotatorRotate, FAQ_ROTATOR_PERIOD);
}

CHILDREN_SPEAK_PERIOD = 5000;
CHILDREN_SPEAK_POS = 0;

function childrenSpeakRotatorInit() {
	if ($("#childrenSpeakHead").length != 0) {
		$("#childrenSpeakHead").ThreeDots({ max_rows : 1 });
		$("#childrenSpeak").ThreeDots({ max_rows : 7 });
	}
	if (typeof CHILDREN_SPEAK_ITEMS == "undefined" || CHILDREN_SPEAK_ITEMS.length < 2) return;
	setTimeout(childrenSpeakRotatorRotate, CHILDREN_SPEAK_PERIOD);
}

function childrenSpeakRotatorRotate() {
	if (++CHILDREN_SPEAK_POS >= CHILDREN_SPEAK_ITEMS.length) CHILDREN_SPEAK_POS = 0;
	var q = CHILDREN_SPEAK_ITEMS[CHILDREN_SPEAK_POS];
	$("#childrenSpeak span").text(q["text"]);
	$("#childrenSpeak").attr("threedots", q["text"]).ThreeDots({ max_rows : 7 });
	if (q["title"] != null && q["title"] != "") {
		$("#childrenSpeakHead span").text(q["title"]);
		$("#childrenSpeakHead").attr("threedots", q["title"]).ThreeDots({ max_rows : 1 });
		$("#childrenSpeakHead").show();
	} else
		$("#childrenSpeakHead").hide();
	setTimeout(childrenSpeakRotatorRotate, CHILDREN_SPEAK_PERIOD);
}

BANKTEST_PAGE_PERIOD = 7000;
BANKTEST_ITEM_PERIOD = 2000;
BANKTEST_POS = 0;
BANKTEST_IMAGE_POS = 0;
BANKTEST_IMAGE_TIMER = null;

function banktestRotatorInit() {
	if (typeof BANKTEST_ITEMS == "undefined" || BANKTEST_ITEMS.length == 0) return;
	if (BANKTEST_ITEMS[BANKTEST_POS].images.length > 1)
		BANKTEST_IMAGE_TIMER = setTimeout(banktestRotatorRotateImage, BANKTEST_ITEM_PERIOD);
	if (BANKTEST_ITEMS.length > 1)
		setTimeout(banktestRotatorRotate, BANKTEST_PAGE_PERIOD);
}

function banktestRotatorRotate() {
	BANKTEST_IMAGE_POS = 0;
	if (++BANKTEST_POS >= BANKTEST_ITEMS.length) BANKTEST_POS = 0;
	var cell = BANKTEST_ITEMS[BANKTEST_POS];
	if (cell.images.length == 0) {
		if (cell["has_image"] != 1)
			$("#banktestNewTable img").hide();
		else
			$("#banktestNewTable img").attr("src", "/img/banktest/cells/thumbs/" + cell.id + ".jpg").show();
	} else
		$("#banktestNewTable img").attr("src", "/img/banktest/units/thumbs/" + cell.images[0] + ".jpg").show();
	if (cell.images.length >= 2 && BANKTEST_IMAGE_TIMER == null)
		BANKTEST_IMAGE_TIMER = setTimeout(banktestRotatorRotateImage, BANKTEST_ITEM_PERIOD);
	uiImgAutosize($("#banktestNewCell img").attr("src", "/img/banktest/cells/" + cell.image));
	$("#banktestNewCell a").attr("href", "/banktest/cell/?id=" + cell.url).text(cell.title);
	$("#banktestNewUnits").empty();
	for (var i = 0; i != cell.units.length; i++) {
		var li = document.createElement("li");
		var a = document.createElement("a");
		$(a).attr("href", "/banktest/cell/" + cell.url + "/unit/" + cell.units[i].url + "/").text(cell.units[i].title);
		$(li).append(a);
		$("#banktestNewUnits").append(li);
	}
	setTimeout(banktestRotatorRotate, BANKTEST_PAGE_PERIOD);
}

function banktestRotatorRotateImage() {
	var images = BANKTEST_ITEMS[BANKTEST_POS].images;
	if (images.length < 2) {
		BANKTEST_IMAGE_TIMER = null;
		return;
	}
	if (++BANKTEST_IMAGE_POS >= images.length) BANKTEST_IMAGE_POS = 0;
	$("#banktestNewTable img").attr("src", "/img/banktest/units/thumbs/" + images[BANKTEST_IMAGE_POS] + ".jpg");
	BANKTEST_IMAGE_TIMER = setTimeout(banktestRotatorRotateImage, BANKTEST_ITEM_PERIOD);
}

FORUM_POS = 0;
FORUM_OFFS = 0;
FORUM_PERIOD = 3000;
FORUM_MOVE = true;
FORUM_SLOTS = null;

function forumRotatorInit() {
	if (typeof FORUM_ITEMS == "undefined" || FORUM_ITEMS.length < 2) return;
	FORUM_SLOTS = $("#forumBlockList li");
	setTimeout(FORUM_ITEMS.length <= FORUM_SLOTS.length ? forumRotatorRotateSmall : forumRotatorRotate, FORUM_PERIOD);
}

function forumRotatorRotateSmall() {
	var current = FORUM_SLOTS.filter(".active");
	var next = current.next();
	if (next.length == 0) next = FORUM_SLOTS.eq(0);
	current.removeClass("active");
	next.addClass("active");
	setTimeout(forumRotatorRotateSmall, FORUM_PERIOD);
}

function forumRotatorRotate() {
	if (FORUM_MOVE && FORUM_OFFS < (FORUM_SLOTS.length >> 1)) {
		var current = FORUM_SLOTS.filter(".active");
		var next = current.next();
		current.removeClass("active");
		next.addClass("active");
		++FORUM_OFFS;
	} else {
		FORUM_MOVE = false;
		if (++FORUM_POS == FORUM_ITEMS.length) FORUM_POS = 0;
		for (var i = 0; i != FORUM_SLOTS.length; i++) {
			var item = FORUM_ITEMS[(FORUM_POS + i) % FORUM_ITEMS.length];
			var slot = FORUM_SLOTS.eq(i);
			slot.find("span.text").text(item.title);
			slot.find("span.username").text(item.username);
			slot.find("a").attr("href", item.url);
		}
	}
	setTimeout(forumRotatorRotate, FORUM_PERIOD);
}

CREATIVE_POS = 0;
CREATIVE_PERIOD = 3000;
CREATIVE_CLICKED = false;
CREATIVE_SLOTS = null;

function creativeRotatorInit() {
	if (typeof CREATIVE_ITEMS == "undefined" || CREATIVE_ITEMS.length == 0) {
		$("#indexCreativeContainer").hide();
		return;
	}
	if (CREATIVE_ITEMS.length <= 3) {
		$("#indexCreativePrev,#indexCreativeNext").hide();
		return;
	}
	CREATIVE_SLOTS = $("#indexCreativeContainer th.item");
	CREATIVE_SLOTS.each(function (index) {
		$(this).find("div").ThreeDots({ max_rows : 3 });
	});
	$("#indexCreativePrev,#indexCreativeNext").attr("href", "#").click(function () {
		CREATIVE_CLICKED = true;
		creativeRotatorRotate($(this).attr("id") == "indexCreativeNext");
		return false;
	});
	setTimeout(creativeRotatorAutorotate, CREATIVE_PERIOD);
}

function creativeRotatorAutorotate() {
	if (CREATIVE_CLICKED) return;
	creativeRotatorRotate(true);
	setTimeout(creativeRotatorAutorotate, CREATIVE_PERIOD);
}

function creativeRotatorRotate(fwd) {
	var item = 0;
	var img = null;
	if (fwd) {
		CREATIVE_POS++;
		img = CREATIVE_SLOTS.eq(0).find("img").attr("src");
		for (var i = 0, j = CREATIVE_SLOTS.length - 1; i != j; i++)
			creativeIteratorCopy(CREATIVE_SLOTS.eq(i + 1), CREATIVE_SLOTS.eq(i));
		item = CREATIVE_SLOTS.length - 1;
	} else {
		CREATIVE_POS--;
		img = CREATIVE_SLOTS.eq(CREATIVE_SLOTS.length - 1).find("img").attr("src");
		for (var i = CREATIVE_SLOTS.length - 1; i > 0; i--)
			creativeIteratorCopy(CREATIVE_SLOTS.eq(i - 1), CREATIVE_SLOTS.eq(i));
	}
	if (CREATIVE_POS < 0) CREATIVE_POS = CREATIVE_ITEMS.length - 1;
	else if (CREATIVE_POS == CREATIVE_ITEMS.length) CREATIVE_POS = 0;
	var data = CREATIVE_ITEMS[(CREATIVE_POS + item) % CREATIVE_ITEMS.length];
	var dst = CREATIVE_SLOTS.eq(item);
	dst.find("img").attr("src", img);
	dst.find("a").attr("href", data["url"]);
	dst.find("li > a").text(data["title"]);
	var div = dst.find("div");
	var a = div.children("a");
	a.text(data["text"]);
	div.attr("threedots", data["text"]).ThreeDots({ max_rows : 3 });
}

function creativeIteratorCopy(src, dst) {
	dst.find("img").attr("src", src.find("img").attr("src"));
	var url = src.attr("href");
	dst.find("a").attr("href", url);
	dst.find("li > a").text(src.find("li > a").text());
	var div = dst.find("div");
	var a = div.children("a");
	var txt = src.find("div").attr("threedots");
	a.text(txt);
	div.attr("threedots", txt).ThreeDots({ max_rows : 3 });
}

NEW_ITEMS_PERIOD = 5000;
NEW_ITEMS_TAB_RE = new RegExp("^(\\S+)\\s+(.*)$");

function newItemsRotatorInit() {
	if ($(".newItemsContainer").length == 0) return;
	setTimeout(newItemsRotatorRotate, NEW_ITEMS_PERIOD);
}

function newItemsRotatorRotate() {
	var hasRotators = false;
	$(".newItemsContainer").each(function (index) {
		var tabs = $(this).find("ul.tabs");
		if (!tabs.hasClass("customAutorotate")) return;
		var data = $(this).find("div.data.show");
		var li = data.find("li.highlight");
		var next = li.next();
		if (next.length == 0) {
			var active = tabs.find("li.active");
			var a = active.find("a");
			var prefix = NEW_ITEMS_TAB_RE.exec(a.text());
			a.text(prefix[2]);
			next = active.next();
			if (next.length == 0) next = active.parent().children().first();
			a = next.find("a");
			a.text(prefix[1] + " " + a.text());
			uiInteractiveTabsClick(next);
			data = $(this).find("div.data.show");
			li = data.find("li");
			next = li.first();
		}
		li.removeClass("highlight");
		next.addClass("highlight");
		var img = next.attr("image");
		var imgBox = data.find("img.newItemsImage");
		if (img == "") imgBox.hide();
		else imgBox.attr("src", img).show();
		hasRotators = true;
	});
	if (hasRotators) setTimeout(newItemsRotatorRotate, NEW_ITEMS_PERIOD);
}

function themeInit() {
	if (THEME_TOP_IMAGES[0]) $("div.left_col").prepend("<img class=themeColTop src='/img/themes/" + THEME_ID + "/2.jpg'>").css("margin-top", 0);
	if ($("div.center_col > div.big_content_block").length) {
		if (THEME_TOP_IMAGES[3]) $("div.center_col").prepend("<img class=themeColTop src='/img/themes/" + THEME_ID + "/5.jpg'>").css("margin-top", 0);
	} else {
		if (THEME_TOP_IMAGES[1]) $("div.center_col").prepend("<img class=themeColTop src='/img/themes/" + THEME_ID + "/3.jpg'>").css("margin-top", 0);
		if (THEME_TOP_IMAGES[2]) $("div.right_col").prepend("<img class=themeColTop src='/img/themes/" + THEME_ID + "/4.jpg'>").css("margin-top", 0);
	}
}

function themeFix9() {
	var img = $(".footer .bany img");
	var obj = img.get(0);
	if (obj.height > 150) img.css("top", (150 - obj.height) + "px");
}

function editorToolsInit() {
	if (typeof editor_tools_construct == "function" && $("#xCommentsList,#commentsList").length) {
		editor_tools_lang = {
			'help' : 'помощь',
			'b' : 'жирный',
			'i' : 'наклонный',
			'u' : 'подчеркнутый',
			's' : 'перечеркнутый',
			'sub' : 'нижний индекс',
			'sup' : 'верхний индекс',
			'color' : 'цвет текста',
			'size' : 'размер текста',
			'center' : 'центрировать текст',
			'url' : 'вставить ссылку',
			'email' : 'вставить email',
			'img' : 'вставить ссылку на картинку',
			'hr' : 'вставить горизонтальныйй разделитель',
			'code' : 'программный код',
			'quote' : 'вставить цитату',
			'list' : 'вставить список',
			'quote_title' : 'цитата',
			'enter url' : 'Пожалуйста, введите интернет-адрес, на который должна указывать ссылка.',
			'enter email' : 'Пожалуйста, введите email.',
			'enter subject' : 'Пожалуйста, укажите заголовок письма, которое будет предложено отправить при нажатии на ссылку.',
			'enter url description' : 'Пожалуйста, введите текст, который будет отображаться в ссылке.',
			'invalid url' : 'Интернет-адрес имеет неверный формат. Он должен начинаться с http://, https://, ftp:// или mailto:',
			'enter image url' : 'Пожалуйста, введите интернет-адрес картинки, которую хотите вставить.',
			'invalid image url' : 'Интернет-адрес картинки неверен. Он должен начинаться с http://, https:// или ftp://',
			'enter who you quote' : 'Пожалуйста, введите имя пользователя, которого вы цитируете. Можете оставить это поле пустым, если хотите.',
			'enter new list item' : 'Пожалуйста, введите текст для последующего элемента списка. Как только вы введете все элементы, оставте поле пустым и нажмите \"ОК\".',
			'x-large' : 'Очень большой шрифт',
			'large' : 'Большой шрифт',
			'medium' : 'Средний шрифт',
			'small' : 'Мелкий шрифт',
			'x-small' : 'Очень мелкий шрифт',
			'list type b' : 'Маркеры',
			'list type 1' : 'Номера',
			'list type a' : 'Буквы',
			'list type A' : 'Заглавные буквы',
			'list type i' : 'Маленькие римские числа',
			'list type I' : 'Большие римские числа',
			'bbcode help' : 'Помощь по BBcode-форматированию',
			'disable' : 'Не использовать BBcode-форматирование для этого сообщения'
		};
		editor_tools_default_iconheight = 20;
		editor_tools_help_chapters = [['помощь по BBcode-форматированию', '/forum/addon.php?3,module=bbcode,action=help'],
					      ['помощь по смайликам', '/forum/addon.php?3,module=smileys,action=help']];
		editor_tools = [['b', 'жирный', '/forum/mods/bbcode/icons/b.gif', 'editor_tools_handle_b()', 21, 20, 'body'],
				['i', 'наклонный', '/forum/mods/bbcode/icons/i.gif', 'editor_tools_handle_i()', 21, 20, 'body'],
				['u', 'подчеркнутый', '/forum/mods/bbcode/icons/u.gif', 'editor_tools_handle_u()', 21, 20, 'body'],
				['color', 'цвет текста', '/forum/mods/bbcode/icons/color.gif', 'editor_tools_handle_color()', 21, 20, 'body'],
				['size', 'размер текста', '/forum/mods/bbcode/icons/size.gif', 'editor_tools_handle_size()', 21, 20, 'body'],
				['url', 'вставить ссылку', '/forum/mods/bbcode/icons/url.gif', 'editor_tools_handle_url()', 21, 20, 'body'],
				['hr', 'вставить горизонтальныйй разделитель', '/forum/mods/bbcode/icons/hr.gif', 'editor_tools_handle_hr()', 21, 20, 'body'],
				['list', 'вставить список', '/forum/mods/bbcode/icons/list.gif', 'editor_tools_handle_list()', 21, 20, 'body'],
				['center', 'центрировать текст', '/forum/mods/bbcode/icons/center.gif', 'editor_tools_handle_center()', 21, 20, 'body'],
				['smiley', 'вставить смайлик', '/forum/mods/smileys/icon.gif', 'editor_tools_handle_smiley()', 21, 20, 'body']];
		editor_tools_textarea_ids.push("xCommentsBody");
		editor_tools_construct();
	}
}

function comment_format(comment) {
	var element = "<div id=commentData" + comment.id + " style='margin-left:0px;display:none'><p class=commentSubtitle><span class=authorName>[<a class=authorName></a>]</span> <span class=commentDate></span></p><div class=commentData></div></div>";
	$("#xCommentsList").prepend(element);
	var commentData = $("#commentData" + comment.id + " .commentData");
	commentData.html(comment.comment.nl2br());
	var author = $("#commentData" + comment.id + " a.authorName");
	if (typeof COMMENTS_ME == "undefined")
		author.text("Гость").addClass("guest");
	else
		author.text(COMMENTS_ME[1]);
	if (typeof COMMENTS_ME != "undefined") $("#commentData" + comment.id + " a.authorName").attr("href", "/user/" + COMMENTS_ME[0] + "/profile");
	$("#commentData" + comment.id + " span.commentDate").text(new Date(comment.created_ts * 1000).format("shortDate"));
	var result = $("#commentData" + comment.id);
	result.fadeIn(600);
	return result;
}

function comment_add() {
	var result = $("#xCommentsBody").val().trim();
	if (!result.length) {
		$("#xCommentsBody").focus();
		return;
	}
	if (typeof checkCaptcha == "function" && !checkCaptcha()) return;
	var captchaInput = $("#captchaInput");
	captchaInput = captchaInput.length ? captchaInput.val() : null;
	var options = {
		url: "/comment/" + COMMENTS_TAG + "/add",
		data: { "id" : COMMENTS_ID_ITEM, "comment" : result, "captcha" : captchaInput },
		dataType: "json",
		type: "POST",
		success: function(response, status) {
			var captchaOk = typeof checkCaptchaResponse == "undefined" || checkCaptchaResponse(response);
			if (response["ok"]) {
				var comment = {
					id: response["id"],
					created_ts: response["created_ts"],
					comment: response["comment"]
				};
				$("#xCommentsBlock").show();
				$("#xCommentsBody").val("");
				comment_format(comment);
				$.scrollTo($("#xCommentsHeaderDiv"));
			} else {
				if (typeof response.text != "undefined") {
					var msg = "";
					for (var i in response.text)
						msg += response.text[i] + "\n";
					alert(msg);
				} else
					alert("Внутренняя ошибка при добавлении комментария");
				if (captchaOk) $("#xCommentsBody").focus();
			}
			return false;
		},
		error: function(request, status, err) {
			alert("Внутренняя ошибка при добавлении комментария");
			$("#xCommentsBody").focus();
			return false;
		}
	};
	$.ajax(options);
}

function formCheckRequiredFields(flds) {
	var ok = [];
	var firstKey = null;
	for (var key in flds) {
		var q = $(key);
		var radios = q.length != 1;
		var empty = radios ? q.filter(":checked").length == 0 : q.val().trim().length == 0;
		if (empty) {
			if (firstKey == null) firstKey = key;
			ok.push("\n - " + flds[key]);
			if (!radios) $(key).val("");
		}
	}
	if (firstKey != null) {
		alert("Следующие поля являются обязательными для заполнения, но Вами заполнены не были:" + ok.join(""));
		$(firstKey).eq(0).focus();
		return false;
	}
	return true;
}

FORM_CHECK_EMAIL = new RegExp("^.+@.+\..{2,}$");

function formCheckEmail(fld) {
	fld = $(fld);
	if (!FORM_CHECK_EMAIL.test(fld.val())) {
		alert("Неверный формат email-адреса. Пожалуйста, введите корректный email");
		fld.focus();
		return false;
	}
	return true;
}

function formCheckPassword(fld1, fld2) {
	fld1 = $(fld1);
	fld2 = $(fld2);
	if (fld1.val() != fld2.val()) {
		alert("Пароль не совпадает с повтором. Пожалуйста, перевведите пароль");
		fld1.val("");
		fld2.val("");
		fld1.focus();
		return false;
	}
	return true;
}

function rateInit() {
	$(".rateRateDiv").each(function (index) {
		var me = $(this);
		var rate = me.next();
		if (rate.length != 0 && rate.hasClass("rateVoteDiv"))
			me.mouseenter(rate_vote_init);
	});
	$(".rateVoteDiv a").hover(function() {
		var me = $(this);
		me.parent().prevAll().find("a").add(me).addClass("activeRate");
	}, function() {
		var me = $(this);
		me.parent().prevAll().find("a").add(me).removeClass("activeRate");
	});
}

function rate_vote_init() {
	var rate = $(this);
	rate.hide();
	rate.next().show().hover(null, rate_vote_cancel);
	return false;
}

function rate_vote_cancel() {
	var vote = $(this);
	vote.hide().unbind("mouseenter mouseleave");
	vote.prev().show();
	return false;
}

function rate_rate(obj, title, tag, id, val) {
	obj = $(obj).parents(".rateVoteDiv");
	var options = {
		url: "/rate/" + tag,
		data: { "id" : id, "rate" : val },
		dataType: "json",
		success: function(response, status) {
			if (response != null && response["rate"]) {
				var pos = $("#galRateContainer").offset();
				obj.hide().unbind("mouseenter mouseleave");
				var rateDiv = obj.prev();
				rateDiv.css("cursor", "default").attr("title", "Вы уже проголосовали за " + title).unbind("click mouseenter mouseleave");
				var parent = rateDiv.parents(".rateContainer");
				if (response["rate"] > 0) {
					var result = Math.round(response["rate"] * 35);
					rateDiv.removeClass("norate");
					parent.find(".rateNumbers th").each(function (index) {
						if (response["rate"] < index + 0.5)
							$(this).addClass("norate");
						else
							$(this).removeClass("norate");
					});
					rateDiv.children(".rateRate").width(result);
					parent.find(".rateNone,.rateHeader").hide();
					parent.find(".rateCurrentNumber").text(Math.round(response["rate"] * 10) / 10);
					parent.find(".rateCurrent").show();
				} else {
					rateDiv.addClass("norate");
					parent.find(".rateNumbers th").removeClass("norate");
					rateDiv.children(".rateRate").width(175);
					parent.find(".rateCurrent").hide();
					parent.find(".rateNone,.rateHeader").show();
				}
				var succ = parent.find(".rateSuccVoteDiv");
				succ.show();
				setTimeout(function() { succ.fadeOut("slow", function() { rateDiv.show() }) }, 5000);
			} else {
				obj.hide().unbind("mouseenter mouseleave");
				obj.prev().show();
			}
			return false;
		},
		error: function(request, status, err) {
			obj.hide().unbind("mouseenter mouseleave");
			obj.prev().show();
			return false;
		}
	};
	$.ajax(options);
}
