var keyEvent = $browser.ie || $browser.webkit ? "onKeyDown" : "onKeyPress";
var L4F = {
	lite: false,
	siteUrl: "",
	Ajax: Class(Ajax, {
		init: function (_config) {
			_config = _config || {};
			_config.url = _config.url || '/l';
			Ajax.prototype.init.call(this, _config);
			this.createEvent(["onGoodError"])
			this.onSuccess = function(data) {
				var code = data.parseJSON();
				if (!code) {
					this.onError("PARSE: " + data);
					return;
				}
				if (code.error) {
					if (code.errorType == "good") {
						if (!this.config.silent) {
							L4F.UI.alert(code.errorText);
						}
						this.onGoodError(code.errorText);
					} else {
						this.onError("SERVER: (" + code.errorType + ") " + code.errorText);
					}
					return;
				}
				this.fireEvent("onSuccess", [code]);
			}
			this.onError = function(err) {
				var data = "";
				if (typeof this.config.data == "object") {
					for (var i in this.config.data) {
						data += i + " -> " + this.config.data[i] + "\n";
					}
					if (data == "") {
						data = "{NONE}";
					}
				} else {
					data = "{NULL}";
				}
				AjaxQuick({ url: '/js_error.php', data: { TYPE: 'ajax', FROM: this.config.from || "AJAX", DATA: data, ENTRY: err } });
				this.fireEvent("onError", [err]);
			};
		}
	}),
	AjaxQuick: function (_config) {
		var res = new L4F.Ajax(_config);
		res.send();
		return res;
	},
	post: function (_url, _data) {
		if (typeof _url != "string") {
			_data = _url;
			_url = window.location.href;
		}
		_data = _data || {};
		PostQuick({url: _url, data: _data});
		return false;
	},
	pajax: function (_data, obj) {
		var done = function () { obj.innerHTML += " [v]"; }
		L4F.AjaxQuick({data: _data,
			onSuccess: done,
			onError: done,
			onGoodError: done
		});
		return false;
	},
	joke: {
		vote: function (id, act, obj) {
			var _data = { joke_id: id, action: "rating" };
			var onSuccess = Function.empty;
			if ({"+": 1, "-": 1}[act]) {
				$extend(_data, { type: 0, how: act + "1"});
				onSuccess = function () {
					var votes = $("#joke" + id + " span.votes");
					votes.innerHTML = eval(votes.innerHTML + act + "1");
					$("#joke" + id + " div.rating").className += " rating-novote";
				};
			} else {
				$extend(_data, { type: {"b": 1, "s": 2}[act], how: 0 });
				onSuccess = function () {
					var btns = [$("#joke" + id + " a.bred <:1"), $("#joke" + id + " a.spam <:1")];
					btns[0].insertSiblingPrevious($c("li", {}, "<span>" + obj.innerHTML + "</span>"));
					btns.invoke("removeElement");
					$("#joke" + id).className += " post-menued";
				};
			}
			L4F.AjaxQuick({ data: _data, onSuccess: onSuccess, from: "JOKE_VOTE" });
			return false;
		},
		sled: function (id, act, obj) { return this.mark(id, act, obj, 'sled'); },
		fav: function (id, act, obj) { return this.mark(id, act, obj, 'fav'); },
		markers: {
			sled: {
				action: 'step',
				label: { add: "добавить в следы", del: "удалить из следов"}
			},
			fav: {
				action: 'star',
				label: { add: "добавить в избранное", del: "удалить из избранного"}
			}
		},
		mark: function (id, act, obj, marker) {
			if (!L4F.user.loged) {
				L4F.UI.alert('Необходимо зарегистрироваться');
				return false;
			}
			var _data = { post_id: id, action: L4F.joke.markers[marker].action, type: { add: 0, del: -1}[act] };
			obj = $(obj);
			act = act == "add" ? "del" : "add";
			L4F.AjaxQuick({
				data: _data,
				onSuccess: function () {
					obj.removeClass(marker + "-new");
					obj.toggleClass(marker + "-selected");
					obj.title = L4F.joke.markers[marker].label[act];
					obj.onclick = function () { return L4F.joke.mark(id, act, this, marker); };
				},
				from: "JOKE_MARK"
			});
			return false;
		},
		define: function (id) {
			var joke = $("#joke" + id);
			var rating = $(joke, "div.rating");
			var ratingHeight = rating.clientHeight + 27;
			if (!L4F.lite) {
				window.onscroll = window.onresize = function () {
					var jokeHeight = joke.clientHeight - ratingHeight, jokePos = joke.absPos(), winSize = getWindowSize();
					jokePos.y -= 10;
					jokePos.x -= winSize.scrollLeft;
					if (winSize.scrollTop < jokePos.y) {
						rating.removeClass("fixed"); rating.addClass("nofixed");
						rating.applyStyle({ top: "0", left: "-130px" });
					} else if (winSize.scrollTop > jokePos.y + jokeHeight) {
						rating.removeClass("fixed"); rating.addClass("nofixed");
						rating.applyStyle({ top: jokeHeight + "px", left: "-130px" });
					} else {
						rating.addClass("fixed"); rating.removeClass("nofixed");
						rating.applyStyle({ top: "10px", left: (jokePos.x - 130) + "px" });
					}
				}
			}
			var np = [$("#nextLink"), $("#prevLink")];
			if (np[0]) {
				hotKey("up_c", function () { window.location.href = np[0].href; return false; });
			}
			if (np[1]) {
				hotKey("down_c", function () { window.location.href = np[1].href; return false; });
			}
		},
		openMenuZIndex: 11,
		openMenu: function(obj) {
			obj = $(obj);
			if (obj.hasClass("alert-empty")) {
				return;
			}
			if ($browser.ie) { $(obj, "<:3").style.zIndex = L4F.joke.openMenuZIndex++; }
			if (obj.closing) {
				clearTimeout(obj.closing);
				obj.closing = false;
				return;
			}
			obj.addClass("alert-open");
			obj.addEvent("onMouseOut", function (e) { 
				if (!obj.closing) {
					obj.closing = (function () { obj.removeClass("alert-open"); obj.closing = false; }).toTimeout(1000);
				}
			});
		},
		sendToFriend: function (id, type, link, img, text) {
			var bb, html, ta, t1;
			text = text.replace(/<q>/g, "'").replace(/<dq>/g, '"');
			ta = text.split(/<nl>/g);
			t1 = ta.shift() || '';
			if (img != "") {
				bb = type + ' на [URL=' + L4F.siteUrl + ']Live4Fun[/URL]:' + "\n" + '[URL=' + link + '][IMG]' + img + '[/IMG][/URL]' + "\n" + '[URL=' + link + ']' + t1 + '[/URL]' + "\n" + ta.join("\n");
				html = type + ' на <a href="' + L4F.siteUrl + '">Live4Fun</a>:<br />' + '<a href="' + link + '"> <img src="' + img + '" /><br />' + t1 + '</a><br />' + ta.join("<br />");
			} else {
				bb = type + ' на [URL=' + L4F.siteUrl + ']Live4Fun[/URL]:' + "\n" + '[URL=' + link + ']' + t1 + '[/URL]' + "\n" + ta.join("\n");
				html = type + ' на <a href="' + L4F.siteUrl + '">Live4Fun</a>:<br />' + '<a href="' + link + '">' + t1 + '</a><br />' + ta.join("<br />");
			}
			var res = 'Ссылка:<br /><input type="text" class="text" value="' + link + '" onclick="this.select();" style="width: 300px;" /><br />' +
			'Код для форума (BBCode):<br /><textarea style="width: 300px; height: 50px; font-size: 11px;" onclick="this.select();">' + bb + '</textarea><br />' +
			'Код для блога (HTML):<br /><textarea style="width: 300px; height: 50px; font-size: 11px;" onclick="this.select();">' + html + '</textarea><br /><br />' +
			'Отправить другу по e-mail:<form action="' + window.location.href + '" method="post"><input type="text" class="text" name="email" value="" style="width: 300px;" /><br /><input type="hidden" name="action" value="email_send" /><input type="hidden" name="post_id" value="' + id + '" /><input type="submit" class="button" value="Отправить" /></form>';
			(new L4F.UI.Window("Live4Fun", "helpTip", res, [
				{ title: "Закрыть", click: "close", key: "esc" }
			], {
				onInit: function () {
					this.element.applyStyle({
						width: "400px",
						height: "400px"
					});
					$(this.element, "div.info").applyStyle({
						height: "306px"
					});
				}
			})).open();
			return false;
		}
	},
	comment: {
		vote: function (id, act, obj) {
			var _data = { comment_id: id, how_vote: act + "1", action: "vote_comment" };
			L4F.AjaxQuick({
				data: _data,
				onSuccess: function () { 
					var votes = $(obj, "<:1 span.votes");
					votes.innerHTML = eval(votes.innerHTML + act + "1");
					$(obj, "<:1").className += " rating-novote";
				},
				from: "COMMENT_VOTE"
			});
			return false;
		},
		replyCurAuthor: '',
		replyCurAuthorCatched: false,
		replyCurId: 0,
		reply: function (id, author, obj) {
			var com = $(obj, "<:2"), form = $("#replyComment"), text = $("#replyCommentText"), parent = $("#replyCommentParent");
			if (!this.replyCurAuthorCatched) {
				var authorCatch = text.value.match(/([a-zA-Z0-9_]+),/);
				if (authorCatch ? authorCatch.length > 0 : false) {
					var authors = $$("div.comment div.author a.user").collect(function (e) { return e.innerHTML; } );
					if (authors.search(authorCatch[1]) >= 0) {
						this.replyCurAuthor = authorCatch[1];
					}
				}
				this.replyCurAuthorCatched = true;
			}
			if (id != this.replyCurId) {
				parent.value = id;
				$(form, "h3").hide();
				form.removeElement();
				com.insertSiblingNext(form);
				var lvl = parseInt(com.className.match(/lvl(\d+)/)[1]);
				form.className = "lvl" + lvl;
				if (this.replyCurAuthor != '' ? text.value.substring(0, this.replyCurAuthor.length + 1) == this.replyCurAuthor + "," : false) {
					text.value = author + text.value.substring(this.replyCurAuthor.length);
				} else {
					text.value = author + ", " + text.value;
				}
				this.replyCurAuthor = author;
				this.replyCurId = id;
				if (text.setSelectionRange) {
					text.focus();
					text.setSelectionRange(text.value.length, text.value.length);
				} else if (text.createTextRange) {
					var range = text.createTextRange();
					range.moveStart('character', text.value.length);
					range.moveEnd('character', text.value.length);
					range.collapse(false);
					range.select();
				}
			} else {
				parent.value = 0;
				if (this.replyCurAuthor != '' ? text.value.substring(0, this.replyCurAuthor.length + 1) == this.replyCurAuthor + "," : false) {
					text.value = text.value.substring(this.replyCurAuthor.length + 1).trim(true);
				}
				$(form, "h3").show();
				form.removeElement();
				$(com, "<:1").insertSiblingNext(form);
				this.replyCurAuthor = '';
				this.replyCurId = 0;
			}
			return false;
		}
	},
	user: {
		name: '',
		loged: false,
		logIn: function (user) {
			if (user != '') {
				this.name = user;
				this.loged = true;
			}
		},
		friend: function (name, add, obj) {
			L4F.AjaxQuick({
				data: { action: "friends", nick_name: name, friends_action: add ? "add" : "del" },
				onSuccess: function () {
					obj.innerHTML = add ? "Удалить из друзей" : "Добавить в друзья";
					obj.onclick = function () { return L4F.user.friend(name, !add, obj); }
				},
				from: "USER_FRIEND"
			});
			return false;
		},
		ignor: function (name, add, obj) {
			L4F.AjaxQuick({
				data: { action: "ban_user", nick_name: name, ban_action: add ? "add" : "del" },
				onSuccess: function () {
					obj.innerHTML = add ? "Отменить игнор" : "Добавить в игнор";
					obj.onclick = function () { return L4F.user.ignor(name, !add, obj); }
				},
				from: "USER_IGNORE"
			});
			return false;
		},
		open: function (e, user, obj) {
			if (L4F.lite) { return; }
			if (!L4F.user.loged) { return; }
			e = new _Event(e);
			obj = this == L4F.user ? obj : this;
			obj.panel = obj.panel || new L4F.user.panel({ user: user, parent: obj });
			obj.panel.open(e.page.x + 12, e.page.y + 12);
		},
		panel: Class({
			init: function (config) {
				var _this = this;
				$(this.parent).addEvent("onMouseOut", function () { _this.close() });
				$extend(this, {
					period: 1000,
					to: false
				});
				$extend(this, config);
				this.element = $c("div", { className: "userPanel" });
				this.element.addEventListener({
					onMouseOver: function () { _this.open(); },
					onMouseOut: function () { _this.close(); }
				});
			},
			status: 0,
			open: function (x, y) {
				if ((this.status == 0) && (x != undefined)) {
					this.status = 1;
					this.element.applyStyle({ left: x + "px", top: y + "px" });
					this.element.startLoad();
					$("body").appendChild(this.element);
					var _this = this;
					this.to = setTimeout(function () {
						_this.to = false;
						_this.aStartTime = $uts();
						_this.ajax = L4F.AjaxQuick({
							url: "/uinfo",
							method: "get",
							silent: true,
							data: { nick_name: _this.user },
							onSuccess: function(data) {
								_this.ajax = false;
								_this.data = data;
								var period = _this.period / 2 - $uts() + _this.aStartTime;
								if (period >= 0) {
									_this.to = setTimeout(function () { _this.open('timer'); }, period);
								} else {
									_this.open('timer');
								}
							},
							onGoodError: function () {
								_this.ajax = false;
								_this.close();
							},
							onError: function() {
								_this.ajax = false;
								_this.close();
							},
							from: "USER_PANEL"
						});
					}, this.period / 2);
				} else if ((this.status == 1) && (x == 'timer')) {
					this.status = 2;
					this.element.stopLoad();
					this.element.addClass("userPanel-open");
					var user = this.data.user;
					var links = this.data.links;
					var info = this.data.info;
					var userHTML = '<span class="avatar"><img src="' + user.avatar + '" /></span><div class="user"><a href="' + user.link + '">' + user.name + '</a> ' + user.status_image + '<div class="status">' + user.status_message + '</div></div><div class="clear"></div>';
					userHTML += '<ul class="menu">'
					var menu = [
						'<a href="' + links.bestjokes + '">Лучшие шутки от ' + user.name + '</a>',
						'<a href="' + links.jokes + '">Все шутки от ' + user.name + '</a>',
						'-',
						'<a href="' + links.big_profile + '">Расширенный профиль</a>',
						'-'
					];
					if (info.is_my) {
						menu.push(
							'<a href="' + L4F.siteUrl + '/blacklist">Мой игнор лист</a>',
							'<a href="' + user.link + '/friend_of">Кто меня добавил в друзья?</a>'
						);
					} else {
						menu.push(
							'<a class="button" href="' + L4F.siteUrl + '/sendpm/' + user.name + '">Написать личное сообщение</a>',
							'<a class="button" href="#" onclick="return L4F.user.friend(\'' + user.name + '\', ' + (info.is_friend ? 'false' : 'true' ) + ', this);">' + (info.is_friend ? 'Удалить из друзей' : 'Добавить в друзья') + '</a>',
							'<a class="button" href="#" onclick="return L4F.user.ignor(\'' + user.name + '\', ' + (info.is_ban ? 'false' : 'true' ) + ', this);">' + (info.is_ban ? 'Отменить игнор' : 'Добавить в игнор') + '</a>'
						);
					}
					for (var i = 0; i < menu.length; i++) {
						if (menu[i] == "-") {
							userHTML += '<li class="hr"></li>';
						} else {
							userHTML += "<li>" + menu[i] + "</li>";
						}
					}
					userHTML += "</ul>";
					this.element.innerHTML = userHTML;
				} else if (this.status == 3) {
					this.status = 2;
					if (this.to) { clearTimeout(this.to); this.to = false; }
				}
			},
			close: function (key) {
				if (this.status == 1) {
					this.status = 0;
					this.element.stopLoad();
					if (this.ajax) { this.ajax.abort(); }
					if (this.to) { clearTimeout(this.to); this.to = false; }
					this.element.removeElement();
				} else if (this.status == 2) {
					this.status = 3;
					var _this = this;
					this.to = setTimeout(function () { _this.close("timer") }, this.period);
				} else if ((this.status == 3) && (key == "timer")) {
					this.status = 0;
					this.element.innerHTML = "";
					this.element.removeClass("userPanel-open");
					this.element.removeElement();
				}
			},
			current: false
		})
	},
	pm: {
		checkAll: function (checked) {
			$$("input.mail").each( function (obj) { obj.checked = checked; } );
		},
		check: function () {
			var checked = true;
			$$("input.mail").each( function (obj) { checked = obj.checked && checked; } );
			$("#mailAll").checked = checked;
		},
		reply: function (id, obj) {
			obj = $(obj, "<:3");
			var subj = $(obj, "h3 a").innerHTML, form = $("#sendMail");
			form.removeElement();
			var re = subj.match(/(Re(\((\d+)\))?:)?(.*)/);
			subj = re[1] ? (re[3] ? "Re(" + (parseInt(re[3]) + 1) + "):" + re[4] : "Re(2):" + re[4]) : "Re: " + subj;
			obj.insertSiblingNext(form)
			form.show();
			$("#sendMailSubject").value = subj;
			return false;
		},
		again: function (id, obj) {
			this.reply(id, obj);
			$("#sendMailSubject").value = $(obj, "<:3 h3 a").innerHTML
			return false;
		},
		del: function (id, obj) {
			L4F.UI.ask('Удалить сообщение?', function () { L4F.AjaxQuick({
				data: { action: 'pm_delete_act', delete_pm_id: id },
				onSuccess: function(data) { $(obj, "<:3").removeElement(); },
				from: "PM_DELETE"
			}); });
			return false;
		},
		toFriend: function (obj) {
			$("#sendMailRecepient").value = obj.options[obj.selectedIndex].value;
		}
	},
	addJoke: {
		tagsCountMax: 4,
		imagesCountMax: 50,
		init: function() {
			$("#addFormType").onchange = function () {
				$("#addForm").className = "type" + this.options[this.selectedIndex].value;
			}
			var tagsToToggle = $("#addFormTags").value.trim().split(/\s*,\s*/g);
			$("#addFormTags").readOnly = true;
			this.tagsCount = 0;
			$$("#addFormTagsList a").each( function (tag) { if (tagsToToggle.has(tag.innerHTML)) { tag.toggleClass("selected"); L4F.addJoke.tagsCount++ } } );
			$("#addFormType").onchange();
			if ($browser.flashVer >= 8) {
				L4F.addJoke.stdUp = $("#addFormGallery div.file:0");
				L4F.addJoke.flUp = $("#flashUploaderFile");
				if (!L4F.addJoke.flUp) {
					L4F.addJoke.flUp = $c("div", {className: "file", id: "flashUploaderFile"}, [
						$c("span", { id: "flashButton" }),
						$c("a", { href: "#", onclick: function () {
							L4F.addJoke.stdUp.show();
							L4F.addJoke.flUp.hide();
							return false;
						} }, "Вернуть обычный загрузчик картинок")
					]);
					$("#addFormGallery").insertChildFirst(L4F.addJoke.flUp);
				}
				L4F.addJoke.stdUp.hide();
				L4F.addJoke.flUp.show();
				Uploader.init(L4F.addJoke.uploaderListener, $("#flashButton"));
			}
		},
		addImage: function (obj) {
			if ($$("#addFormGallery div.file").length > this.imagesCountMax) {
				return false;
			}
			var file = $c("div", { className: "file" },
'<label>Картинка</label> <input type="file" class="file" name="files[]" style="vertical-align: middle;" />\
 <input type="hidden" name="images[]" value="files" />\
 <a href="#" class="button" onclick="return L4F.addJoke.addImage(this)">+</a>\
 <a href="#" class="button" onclick="return L4F.addJoke.delImage(this);">&#215;</a>\
 <a href="#" class="button" onclick="return L4F.addJoke.upImage(true, this);">&uarr;</a>\
 <a href="#" class="button" onclick="return L4F.addJoke.upImage(false, this);">&darr;</a>');
			if (obj == undefined) {
				$("#addFormGallery").insertChildFirst(file);
			} else {
				$(obj, "<div.file").insertSiblingNext(file);
			}
			return false;
		},
		delImage: function (obj) {
			$(obj, "<:1").removeElement();
			return false;
		},
		upImage: function (up, obj) {
			var obj = $(obj, "<:1");
			if (up) {
				var sibl = $(obj, "+ -1");
				if (sibl) {
					obj.removeElement();
					sibl.insertSiblingPrevious(obj);
				}
			} else {
				var sibl = $(obj, "+ 1");
				if (sibl) {
					obj.removeElement();
					sibl.insertSiblingNext(obj);
				}
			}
			return false;
		},
		toggleTag: function (obj) {
			var value = [];
			if (obj.toggleClass("selected")) {
				if (++this.tagsCount > this.tagsCountMax) {
					obj.removeClass("selected");
					this.tagsCount--;
					L4F.UI.alert("Максимум " + this.tagsCountMax + " тега");
					return false;
				} 
			} else {
				this.tagsCount--;
			}
			$$("#addFormTagsList a").each(function (tag) { if (tag.hasClass("selected")) { value.push(tag.innerHTML); } } );
			$("#addFormTags").value = value.join(", ");
			return false;
		},
		editTags: function (obj) {
			$("#addFormTagsList").toggle();
			return false;
		},
		uploaderListener: {
			onInit: function () {
			},
			onOpen: function (id, name) {
				if ($$("#addFormGallery div.file").length > L4F.addJoke.imagesCountMax) {
					this.stop();
					return;
				}
				$("#addFormGallery").appendChild($c(
					"div",
					{ id: "flUpImg" + id, className: "file", fileInfo: { name: name } },
					'Загружается <span class="fileName">' + name + '</span>...'
				));
			},
			onProgress: function (id, loaded, total) {
				var str = 'Загружается <span class="fileName">' + $("#flUpImg" + id).fileInfo.name + '</span>... '
				if (loaded < total) {
					str += '<span class="fileProgress">' + Math.round(100 * loaded / total) + '%</span>';
				} else {
					str += '<span class="fileProgress">Обработка. Пожалуйста, подождите...</span>';
				}
				$("#flUpImg" + id).innerHTML = str;
			},
			onError: function (id, error) {
				this.stop();
				L4F.UI.alert("Произошла внутренняя ошибка. Извините. Постараемся все исправить.");
				AjaxQuick({ url: '/js_error.php', data: { TYPE: 'ajax', ENTRY: error, FROM: "UPLOADER" } });
				$("#flUpImg" + id).removeElement();
			},
			onSuccess: function (id, data) {
				var code = data.parseJSON();
				if (code === null) {
					this.onError(id, "PARSE: " + data);
					return;
				}
				if (code.error) {
					if (code.errorType == "boyan") {
						$("#flUpImg" + id).innerHTML = 'Картинка <span class="fileName">' + $("#flUpImg" + id).fileInfo.name + '</span> уже была';
					} else if (code.errorType == "good") {
						L4F.UI.alert(code.errorText);
						$("#flUpImg" + id).removeElement();
						this.stop();
					} else {
						this.onError(id, "SERVER: (" + code.errorType + ") " + code.errorText);
					}
					return;
				}
				$("#flUpImg" + id).innerHTML =
'<img src="' + code.preview.src + '" /><input type="hidden" name="images[]" value="' + code.name + '" />\
 <a href="#" class="button" onclick="return L4F.addJoke.delImage(this);">&#215;</a>\
 <a href="#" class="button" onclick="return L4F.addJoke.upImage(true, this);">&uarr;</a>\
 <a href="#" class="button" onclick="return L4F.addJoke.upImage(false, this);">&darr;</a>';
			}
		}
	},
	hasPages: false,
	pages: function (cur, max, link_pre, link_post) {
		this.hasPages = true;
		this.curPage = cur;
		this.maxPage = max;
		this.pageLinkPre = link_pre;
		this.pageLinkPost = link_post;
		hotKey("left_c", function () { if (cur - 1 >= 1) { window.location.href = link_pre + (cur - 1) + link_post; return false; } });
		hotKey("right_c", function () { if (cur + 1 <= max) { window.location.href = link_pre + (cur + 1) + link_post; return false; } });
	},
	pagesGoTo: function () {
		if (!this.hasPages) {
			return false;
		}
		L4F.UI.prompt("Введите номер страницы (от 1 до " + L4F.maxPage + "):", function (p) {
			if (p != undefined) {
				p = parseInt(p);
				if (p ? ((p > 0) && (p <= L4F.maxPage)) : false) {
					window.location.href = L4F.pageLinkPre + p + L4F.pageLinkPost;
				} else {
					L4F.UI.alert("Такой страницы не существует");
				}
			}
		});
		return false;
	},
	UI: {
		ask: function (q, func) {
			if (typeof func == "string") {
				func = Function(func);
			} else if (typeof func != "function") {
				func = Function.empty;
			}
			if (L4F.lite) {
				if (confirm(q)) {
					func();
				}
			} else {
				var w;
				(w = new this.Window("Live4Fun", "helpTip", q, [
					{ title: "Да", click: function() {
						func();
						w.close();
					}, focus: true },
					{ title: "Нет", click: "close", key: "esc" }
				])).open();
			}
			return false;
		},
		alert: function (str, type) {
			if (L4F.lite) {
				alert(str);
			} else {
				(new this.Window("Live4Fun", type || "warning", str, [{title: "Закрыть", click: "close", time: 3, key: "esc", focus: true}])).open();
			}
			return false;
		},
		prompt: function (q, func) {
			var value;
			if (typeof func == "string") {
				func = Function(func);
			} else if (typeof func != "function") {
				func = Function.empty;
			}
			if (L4F.lite) {
				value = prompt(q, "");
				func(value);
			} else {
				var w, pr;
				(w = new this.Window("Live4Fun", "helpTip", q, [
					{title: "Ок", click: function () {
						value = pr.value;
						w.close();
					}, key: "enter"},
					{title: "Отмена", click: "close", key: "esc" }
				], {
					onInit: function () {
						$(this.element, "div.info").appendChild($c("br"));
						$(this.element, "div.info").appendChild(pr = $c("input", { type: "text", className: "text"}));
					},
					onOpen: function () {
						pr.focus();
					},
					onClose: function () {
						func(value);
					}
				})).open();
			}
			return false;
		},
		Window: Class({
			init: function (title, type, text, buttons, config) {
				config = config || {};
				$_eventListener(this);
				var _this = this;
				this.createEvents(["onInit", "onOpen", "onClose"]);
				var buttons_objs = [];
				function createButton (btn, win) {
					var btnEl = $c("input", {
						type: "button",
						className: "button",
						value: btn.title
					});
					if (btn.click) {
						var clickEvnt;
						if (btn.click == "close") {
							btn.click = function () { win.close() };
						}
						win.addEvent("onOpen", function () {
							clickEvnt = btnEl.addEvent("onClick", btn.click);
						});
						win.addEvent("onClose", function () {
							btnEl.removeEvent(clickEvnt);
						});
					}
					if (btn.focus) {
						win.addEvent("onOpen", function () {
							btnEl.focus();
						});
					}
					if (btn.time) {
						btnEl.value = btn.title + " (" + btn.time + ")";
						win.addEvent("onOpen", function () { (new Effect({
							duration: btn.time * 1000,
							tick: 1000,
							proc: function (t) { btnEl.value = btn.title + " (" + Math.round((1 - t) * btn.time) + ")"; },
							onStop: function () { btnEl.click(); }
						})).start() });
					}
					if (btn.key) {
						btn.keys = [btn.key];
					}
					if (btn.keys) {
						var key_e = $(document).addEvent(keyEvent, function (e) {
							if (btn.keys.has(e.key)) {
								btnEl.click();
							}
						});
						win.addEvent("onClose", function () {
							document.removeEvent(key_e);
						});
					}
					return btnEl;
				}
				for (var i = 0; i < buttons.length; i++) {
					buttons_objs.push(createButton(buttons[i], this));
				}
				this.element = $c("div", { className: "window fixed", style: { zIndex: 901 } }, [
					$c("div", { className: "title" }, [
						$c("span", {}, title + " "),
						$c("a", { href: "#", onclick: function () { _this.close(); return false; }, className: "button" }, "&#215;") 
					]),
					$c("div", { className: "info " + type }, text ),
					$c("div", { className: "buttons" }, buttons_objs)
				]);
				this.opened = false;
				this.config = {};
				$extend(this.config, config);
				this.addEventListener(config);
				this.onInit();
			},
			open: function () {
				var _this = this;
				if (this.current[0] === false) {
					this.current[0] = this;
					var winSize = getWindowSize();
					this.element.setOpacity(0);
					var chain = [
						function () {
							$("body").appendChild(_this.element);
							_this.element.style.top = (winSize.height - _this.element.clientHeight) / 2 + "px";
							_this.element.style.left = (winSize.width - _this.element.clientWidth) / 2 + "px";
						},
						L4F.lite ?
						function () { _this.element.setOpacity(1) } :
						function (t) { _this.element.setOpacity(t) }.toEffect(300),
						function () { _this.opened = true; _this.onOpen(); }
					];
					if (!this.covered[0]) {
						chain.unshift(
							function () {
								_this.covered[0] = true;
								_this.cover.setOpacity(0);
								$("body").appendChild(_this.cover);
								_this.cover.style.height = winSize.height + "px";
							},
							L4F.lite ? 
							function () { _this.cover.setOpacity(0.3); } :
							function (t) { _this.cover.setOpacity(t * 0.3) }.toEffect(300)
						);
					}
					chain.toChain().start();
				} else {
					this.queue.push(this);
				}
			},
			close: function () { if (this.opened) {
				var _this = this;
				this.opened = false;
				this.onClose();
				[
					L4F.lite ? 
					function () { _this.element.setOpacity(0) } :
					function (t) { _this.element.setOpacity(1 - t) }.toEffect(300),
					function () {
						_this.element.removeElement();
						_this.current[0] = false;
						if (_this.queue.length > 0) {
							_this.queue.shift().open();
						} else {
							[
								L4F.lite ?
								function () { _this.cover.setOpacity(0); } :
								function (t) { _this.cover.setOpacity((1 - t) * 0.3); }.toEffect(300),
								function () { _this.cover.removeElement(); _this.covered[0] = false; }
							].toChain().start();
						}
					}
				].toChain().start();
			} },
			queue: [],
			current: [false],
			covered: [false],
			cover: $c("div", { className: "fixed", style: { top: 0, left: 0, width: "100%", background: "#000", zIndex: 900 } })
		})
	}
};

function getWindowSize() {
	var res = {
		width: window.innerWidth,
		height: window.innerHeight,
		scrollTop: window.pageYOffset,
		scrollLeft: window.pageXOffset
	};
	if ($browser.ie) {
		res = {
			width: document.documentElement.clientWidth,
			height: document.documentElement.clientHeight,
			scrollTop: document.documentElement.scrollTop,
			scrollLeft: document.documentElement.scrollLeft
		};
	}
	res.clientWidth = document.body.clientWidth;
	res.clientHeight = document.body.clientHeight;
	res.scrollWidth = res.clientWidth - res.width;
	res.scrollHeight = res.clientHeight - res.height;
	return res;
}

var Uploader = {
	flashSrc: L4F.siteUrl + "/jscripts/nfu.swf",
	flashID: "flashUploader",
	link: "/add_img",
	initialized: false,
	init: function (listener, obj) {
		$extend(this, listener);
		obj.innerHTML = '\
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="' + this.flashID + '" width="170" height="22" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" style="margin: 0 -1px -1px 0;">\
	<param name="src" value="' + this.flashSrc + '" />\
	<param name="allowScriptAccess" value="always" />\
	<param name="wmode" value="transparent" />\
	<embed src="' + this.flashSrc + '" name="' + this.flashID + '" width="170" height="22" allowScriptAccess="always" wmode="transparent" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>\
</object>';
	},
	_onInit: function () {
	    if ($browser.ie) {
	        this.engine = window[this.flashID];
	    } else {
	        this.engine = document[this.flashID];
	    }
		this.initialized = true;
		if (this.onInit) {
			this.onInit();
		}
	},
	_onOpen: function (id, name) {
		if (this.onOpen) {
			this.onOpen(id, name);
		}
	},
	_onProgress: function (id, loaded, total) {
		if (this.onProgress) {
			this.onProgress(id, loaded, total);
		}
	},
	_onError: function (id, error) {
		if (this.onError) {
			this.onError(id, error);
		}
	},
	_onSuccess: function (id, data) {
		if (this.onSuccess) {
			this.onSuccess(id, data);
		}
	},
	browse: function() {
		if (this.initialized) {
			this.engine.openUploader();
		}
	},
	stop: function() {
		if (this.initialized) {
			this.engine.stopUploader();
		}
	},
	_getSession: function() {
		return document.cookie.split(';').join('&');
	},
	_getLink: function() {
		return this.link;
	}
}

var Chat = Class({
	init: function (config) {
		if (!L4F.user.loged) {
			L4F.UI.alert("Вы не авторизованы. Пожалуйста, авторизуйтесь.");
			return false;
		}
		$_eventListener(this);
		this.createEvents(["onMessage", "onInit", "onSend"]);
		$extend(this, {
			users: [],
			messages: [],
			elements: {},
			period: {
				messages: L4F.lite ? 6000 : 3000,
				users: L4F.lite ? 30000 : 15000
			},
			to: {
				messages: false,
				users: false
			},
			lastMessage: 0,
			colors: {},
			recipient: ""
		});
		$extend(this, config);
		if (this.elements.color) {
			for(var i = 0; i < this.elements.color.options.length; i++) {
				this.colors[this.elements.color.options[i].value] = this.elements.color.options[i].style.color;
			}
		}
		this.onInit(config);
		var _this = this;
		this.update();
	},
	send: function() {
		if (this.to.messages !== false) {
			clearTimeout(this.to.messages);
			this.to.messages = false;
		}
		var text = this.elements.input.value;
		if (text.trim() == "") {
			return false;
		}
		var _this = this;
		var tof = function () {
			_this.updateMessages.call(_this);
		}
		var data = {
			action: "chat_add_message",
			send_message: text,
			color: this.elements.color.options[this.elements.color.selectedIndex].value,
			send_to: this.recipient,
			time_last: this.lastMessage
		};
		this.elements.input.value = '';
		this.recipient = '';
		L4F.AjaxQuick({
			data: data,
			silent: true,
			from: "CHAT",
			onError: function () {
				_this.printError("Возникла внутренняя ошибка. Попробуйте перезайти в чат. При повторе ошибки, обратитесь к администрации.", "error");
			},
			onGoodError: function (err) {
				_this.printError(err);
				_this.to.messages = setTimeout(tof, _this.period.messages);
			},
			onSuccess: function (data) {
				_this.printMessages(data.messages);
				_this.to.messages = setTimeout(tof, _this.period.messages);
			}
		});
		return false;
	},
	sendTo: function (nr) {
		if (this.recipient == "") {
			this.recipient = nr;
			this.elements.input.value = nr + ", " + this.elements.input.value;
		} else if (this.recipient == nr) {
			this.recipient = "";
			if (this.elements.input.value.substr(0, nr.length + 1) == nr + ",") {
				this.elements.input.value = this.elements.input.value.substr(nr.length + 1).trim(true);
			}
		} else {
			if (this.elements.input.value.substr(0, this.recipient.length + 1) == this.recipient + ",") {
				this.elements.input.value = nr + this.elements.input.value.substr(this.recipient.length);
			} else {
				this.elements.input.value = nr + ", " + this.elements.input.value;
			}
			this.recipient = nr;
		}
		if (this.elements.input.setSelectionRange) {
			this.elements.input.focus();
			this.elements.input.setSelectionRange(this.elements.input.value.length, this.elements.input.value.length);
		} else if (this.elements.input.createTextRange) {
			var range = this.elements.input.createTextRange();
			range.moveStart('character', this.elements.input.value.length);
			range.moveEnd('character', this.elements.input.value.length);
			range.collapse(false);
			range.select();
		}
	},
	updateMessages: function() {
		if (this.to.messages !== false) {
			clearTimeout(this.to.messages);
			this.to.messages = false;
		}
		var _this = this;
		var tof = function () {
			_this.updateMessages.call(_this);
		}
		L4F.AjaxQuick({
			url: "/chat_messages",
			method: "get",
			data: { time_last: this.lastMessage },
			silent: true,
			from: "CHAT",
			onError: function () {
				_this.printError("Возникла внутренняя ошибка. Попробуйте перезайти в чат. При повторе ошибки, обратитесь к администрации.", "error");
				_this.to.messages = setTimeout(tof, _this.period.messages);
			},
			onGoodError: function (err) {
				_this.printError(err);
				_this.to.messages = setTimeout(tof, _this.period.messages);
			},
			onSuccess: function (data) {
				_this.printMessages(data.messages);
				_this.to.messages = setTimeout(tof, _this.period.messages);
			}
		});
	},
	updateUsers: function() {
		if (this.to.users !== false) {
			clearTimeout(this.to.users);
			this.to.users = false;
		}
		var _this = this;
		var tof = function () {
			_this.updateUsers.call(_this);
		}
		L4F.AjaxQuick({
			url: "/chat_users",
			method: "get",
			silent: true,
			from: "CHAT",
			onError: function () {
				_this.printError("Возникла внутренняя ошибка. Попробуйте перезайти в чат. При повторе ошибки, обратитесь к администрации.", "error");
			},
			onGoodError: function (err) {
				_this.printError(err);
				_this.to.users = setTimeout(tof, _this.period.users);
			},
			onSuccess: function (data) {
				_this.printUsers(data.users);
				_this.to.users = setTimeout(tof, _this.period.users);
			}
		});
	},
	update: function () {
		this.updateMessages()
		this.updateUsers();
	},
	printError: function(err, type) {
		var scroll = (this.elements.messages.scrollTop > this.elements.messages.scrollHeight - 10 - this.elements.messages.clientHeight);
		this.elements.messages.appendChild($c("div", { className: type || "warning" }, err));
		if (scroll) {
			this.elements.messages.scrollTop = this.elements.messages.scrollHeight;
		}
	},
	printMessages: function (msgs) {
		var msg;
		while (msg = msgs.pop()) {
			this.printMessage(msg.id, msg.nick, msg.my, msg.time, this.colors[msg.color] == undefined ? this.colors[0] : this.colors[msg.color], msg.message);
		}
	},
	printMessage: function (id, from, tome, time, color, text) {
		if (id <= this.lastMessage) {
			return false;
		}
		var scroll = (this.elements.messages.scrollTop > this.elements.messages.scrollHeight - 10 - this.elements.messages.clientHeight);
		this.lastMessage = id;
		var itm;
		this.elements.messages.appendChild(itm = $c("div", { className: "cm" + (tome ? " cm-tome" : "") }, '<span class="time">' + time + '</span> ' + from + ' &raquo; <span class="text" style="color: ' + color + ';">' + text + '</span>'));
		if (this.elements.messages.scrollWidth > this.elements.messages.clientWidth) {
			$(itm, "span.text").innerHTML = text.wbr();
		}
		var _this = this;
		$(itm, "a").addEvent("onClick", function () {
			_this.sendTo(this.innerHTML);
			return false;
		});
		if (scroll) {
			this.elements.messages.scrollTop = this.elements.messages.scrollHeight;
		}
	},
	printUsers: function (usrs) {
		this.elements.users.innerHTML = '';
		for (var i = 0; i < usrs.length; i++) {
			this.printUser(usrs[i]);
		}
	},
	printUser: function (name) {
		var itm;
		this.elements.users.appendChild(itm = $c("li", {}, name));
		var _this = this;
		$(itm, "a").addEvent("onClick", function () {
			_this.sendTo(this.innerHTML);
			return false;
		});
	},
	exit: function () {
		L4F.AjaxQuick({
			silent: true,
			from: "CHAT",
			data: { action: "chat_logout" }
		});
		window.location.href = L4F.siteUrl + '/';
	},
	clear: function () {
		this.elements.messages.innerHTML = '';
	}
});

var Zabor = Class({
	init: function (nick, obj, id) {
		//if (L4F.lite) { return; }
		$extend(this, {
			element: obj,
			user: nick,
			lastId: id,
			timeout: false,
			period: 5000
		});
		this.update();
	},
	update: function () {
		if (this.timeout !== false) {
			clearTimeout(this.timeout);
			this.timeout = false;
		}
		var _this = this;
		var fto = function () {
			_this.update();
		}
		L4F.AjaxQuick({
			url: "/nzabor",
			method: "get",
			data: { nick_name: this.user, id: this.lastId },
			onSuccess: function (data) {
				if (data.messages ? data.messages.length > 0 : false) {
					_this.printMessages(data.messages);
				}
				_this.timeout = setTimeout(fto, _this.period);
			},
			silent: true,
			from: "ZABOR"
		});
	},
	printMessages: function (msgs) {
		for (var i = msgs.length - 1; i >= 0; i--) {
			this.printMessage(msgs[i].id, msgs[i].author, msgs[i].date, msgs[i].text, msgs[i].image);
		}
	},
	printMessage: function (id, user, date, text, image) {
		if (id <= this.lastId) {
			return false;
		}
		this.lastId = id;
		image = image == "" ? "" : '<div class="image"><img src="' + image + '" /></div>';
		this.element.insertChildFirst($c("div", { className: "message message-new", id: "message" + id }, '<div class="author">' + user + ' (' + date + ').</div><div class="entry">' + text + image + '</div>'));
	}
});

var Gallery = Class({
	init: function (big, list) {
		var _this = this;
		$extend(this, {
			current: 0,
			list: list,
			image: big,
			images: $$(list, "a"),
			scrollEffect: L4F.lite ? {} : new Effect({
				duration: 1000,
				proc: function (t, a) {
					_this.list.scrollLeft = (a[0] - this.fromV) * t + this.fromV;
				},
				onStart: function() {
					this.fromV = _this.list.scrollLeft;
				}
			})
		});

		hotKey("left_c", function () { _this.openPrev(); });
		hotKey("right_c", function () { _this.openNext(); });

		var babs = big.absPos();
		var vclw = big.clientWidth / 2;

		if (!L4F.lite) {
			
			var btnLeft = $(big, "span.btn-left"), btnRight = $(big, "span.btn-right");
		
			$(window).addEvent("onLoad", function () {
				if (_this.list.scrollWidth <= _this.list.clientWidth) {
					_this.list.style.height = "140px";
				}
			});

			big.addEvent("onMouseMove", function (e) {
				if (e.page.x - babs.x - vclw < 0) {
					btnLeft.addClass("btn-active");
					btnRight.removeClass("btn-active");
				} else {
					btnLeft.removeClass("btn-active");
					btnRight.addClass("btn-active");
				}
			});
		
		}
		
		big.addEvent("onClick", function (e) {
			if (e.page.x - babs.x - vclw < 0) {
				_this.openPrev();
			} else {
				_this.openNext();
			}
		});
		
		this.loaded[0] = $(big, "img")
	},
	open: function (id, obj) {
		//if (id == this.current) return false;
		if (obj) {
			if (this.current == this.images.length - 1) { this.image.removeClass("galleryImage-last"); }
			if (this.current == 0) { this.image.removeClass("galleryImage-first"); }
			if (id == this.images.length - 1) { this.image.addClass("galleryImage-last"); }
			if (id == 0) { this.image.addClass("galleryImage-first"); }
			this.images[this.current].removeClass("selected");
			this.current = id;
			this.images[id].addClass("selected");
			$(this.image, "img").removeElement();
			$(this.image).appendChild(obj);
			this.image.stopLoad();
		} else {
			if (this.loaded[id]) {
				if (this.loaded[id] == '{loading}') {
					if (this.current == this.images.length - 1) { this.image.removeClass("galleryImage-last"); }
					if (this.current == 0) { this.image.removeClass("galleryImage-first"); }
					if (id == this.images.length - 1) { this.image.addClass("galleryImage-last"); }
					if (id == 0) { this.image.addClass("galleryImage-first"); }
					this.images[this.current].removeClass("selected");
					this.current = id;
					this.images[id].addClass("selected");
					this.loaded[id] = '{loading}';
					this.image.startLoad();
				} else {
					return this.open(id, this.loaded[id]);
				}
			} else {
				if (this.current == this.images.length - 1) { this.image.removeClass("galleryImage-last"); }
				if (this.current == 0) { this.image.removeClass("galleryImage-first"); }
				if (id == this.images.length - 1) { this.image.addClass("galleryImage-last"); }
				if (id == 0) { this.image.addClass("galleryImage-first"); }
				this.images[this.current].removeClass("selected");
				this.current = id;
				this.images[id].addClass("selected");
				this.loaded[id] = '{loading}';
				var _this = this, _image;
				var _onload = function () {
					_this.loaded[id] = _image;
					if (id == _this.current) {
						$(_this.image, "img").removeElement();
						$(_this.image).appendChild(_image);
						_this.image.stopLoad();
					}
				}
				this.image.startLoad();
				_image = $c('img', { src: this.images[id].href });
				_image.onload = _onload;
				if (_image.complete) {
					_onload();
				} else {
					(function () { if (_this.loaded[id] == '{loading}') {
						_onload();
					} }).toTimeout(3000);
				}
			}
		}
		return false;
	},
	openNext: function () {
		if (this.current + 1 < this.images.length) {
			this.open(this.current + 1);
			this.scrollTo(this.current);
		}
	},
	openPrev: function () {
		if (this.current - 1 >= 0) {
			this.open(this.current - 1);
			this.scrollTo(this.current);
		}
	},
	scrollTo: function(id) {
		var tovalue = this.images[id].offsetLeft - this.images[0].offsetLeft + ($(this.images[id], "img").clientWidth / 2) - (this.list.clientWidth / 2);
		if (L4F.lite) {
			this.list.scrollLeft = tovalue;
		} else {
			this.scrollEffect.start(tovalue);
		}
	},
	loaded: {}
});

String.prototype.noText = { "<" : ">", "&" : ";" };
String.prototype.whiteSpace = [" ", "\t", "\n"];
String.prototype.wbr = function (each) {
	var wbr = $browser.opera ? "&shy;" : "<wbr />"
	each = each || 5;
	var res = "", c = "", stts = "", j = 0;
	for (var i = 0; i < this.length; i++) {
		c = this.charAt(i);
		res += c;
		if (stts == "") {
			if (this.noText[c]) {
				stts = c;
			} else if (this.whiteSpace.has(c)) {
				j = 0;
			} else {
				j++;
			}
		} else {
			if (c == this.noText[stts]) {
				stts = "";
			}
		}
		if (j >= each) {
			j = 0;
			res += wbr;
		}
	}
	return res;
};

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

$extend(ElementMethods, {
	startLoad: function () {
		if (!this.loading) {
			this.loadSpan = $c('span', {className: 'loading'});
			this.loading = true;
			this.appendChild(this.loadSpan);
		}
	},
	stopLoad: function () {
		if (this.loading) {
			this.loading = false;
			this.removeChild(this.loadSpan);
		}
	}
});

function addSubmitEventOnCEnter(input, form, submit) {
	if (submit) {
		$(submit).insertSiblingNext($c("span", {}, "&nbsp;(ctrl + enter)"));
	}
	$(input).addEvent(keyEvent, function (e) {
		if (e.key == "enter" && e.control) {
			$(form).submit();
		}
	});
}

var hasHotKeys = false, hotKeys = {};

$(document).addEvent(keyEvent, function (e) {
	if (hasHotKeys) {
		var i = e.key + (e.control ? '_c' : '')
		if (hotKeys[i]) {
			for (var j = 0; j < hotKeys[i].length; j++) {
				if (!hotKeys[i][j](e)) { return false; }
			}
		}
	}
});

function hotKey (i, func) {
	hasHotKeys = true;
	hotKeys[i] = hotKeys[i] || [];
	hotKeys[i].push(func);
}

function openMessage(e, obj) {
	var _e = new _Event(e);
	obj = $(obj);
	if ($(obj, "div.entry div").clientHeight > 42) {
		obj.fullView = $(obj.cloneNode(true));
		obj.fullView.className += " bigBoardMessage";
		if ($browser.opera) { obj.fullView.applyStyle({ marginTop: '-1px' }); }
		var _opnmsg = function() {
			if (!obj.msgOpen) {
				obj.msgOpen = true;
				var pos = obj.absPos();
				obj.fullView.applyStyle({
					left: pos.x + 'px',
					top: pos.y + 'px'
				});
				$('body').appendChild(obj.fullView);
			}
		}
		var _clsmsg = function(_e) {
			var e = new _Event(_e);
			if (obj.msgOpen) {
				var rel = e.related;
				while (rel) {
					if ((rel == obj) || (rel == obj.fullView)) {
						return;
					}
					rel = rel.parentNode;
				}
				obj.fullView.removeElement();
				obj.msgOpen = false;
			}
		}
		obj.onmouseout = obj.fullView.onmouseout = _clsmsg;
		obj.onmouseover = obj.fullView.onmouseover = _opnmsg;
		_opnmsg(_e);
	} else {
		obj.onmouseover = Function.empty;
	}
}

var htc = {
	hover: function (element) {
		element.attachEvent("onmouseover", function () { htc.IEHoverOn.call(element); });
		element.attachEvent("onmouseout", function () { htc.IEHoverOff.call(element); });
		element.htcHover = {};
		return 1;
	},
	focus: function (element) {
		element.attachEvent("onfocus", function () { htc.IEFocusOn.call(element); });
		element.attachEvent("onblur", function () { htc.IEFocusOff.call(element); });
		element.htcFocus = {};
		return 1;
	},
	trgif: L4F.siteUrl + '/images/tr.gif',
	png: function (img) {
		img.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + img.src + '", sizingMethod="crop")';
		img.src = htc.trgif;
		img.htcPNG = {}
		return 1;
	},
	IEHoverGetClass: function (element) {
		if (element.className == "") {
			return " hover";
		} else {
			return " " + element.className.split(/\s/g)[0] + "-hover hover";
		}
	},
	IEHoverOn: function () {
		if (this.IE_HOVER) {
			if (!this.IE_HOVER.hover) {
				this.className += this.IE_HOVER.className;
				this.IE_HOVER.hover = true;
			}
		} else {
			this.IE_HOVER = { className: htc.IEHoverGetClass(this), hover: true };
			this.className += this.IE_HOVER.className;
		}
	},
	IEHoverOff: function () {
		if (this.IE_HOVER) {
			if (this.IE_HOVER.hover) {
				var obj = window.event.toElement;
				while (obj) {
					if (obj == this) {
						return;
					}
					obj = obj.parentNode;
				}
				var pos = this.className.indexOf(this.IE_HOVER.className);
				this.className = this.className.substr(0, pos) + this.className.substr(pos + this.IE_HOVER.className.length);
				this.IE_HOVER.hover = false;
			}
		} else {
			this.IE_HOVER = { className: htc.IEHoverGetClass(this), hover: false };
		}
	},
	IEFocusGetClass: function(element) {
		if (element.className == "") {
			return " focus";
		} else {
			return " " + element.className.split(/\s/g)[0] + "-focus focus";
		}
	},
	IEFocusOn: function() {
		if (this.IE_FOCUS) {
			if (!this.IE_FOCUS.focus) {
				this.className += this.IE_FOCUS.className;
				this.IE_FOCUS.focus = true;
			}
		} else {
			this.IE_FOCUS = { className: htc.IEFocusGetClass(this), focus: true };
			this.className += this.IE_FOCUS.className;
		}
	},
	IEFocusOff: function() {
		if (this.IE_FOCUS) {
			if (this.IE_FOCUS.focus) {
				var pos = this.className.indexOf(this.IE_FOCUS.className);
				this.className = this.className.substr(0, pos) + this.className.substr(pos + this.IE_FOCUS.className.length);
				this.IE_FOCUS.focus = false;
			}
		} else {
			this.IE_FOCUS = { className: htc.IEFocusGetClass(this), focus: false };
		}
	}
}

window.curTab = false;
function openTab(name) {
	if (curTab != name) {
		if (curTab) {
			$('#' + curTab + 'Tab').hide();
			$('#' + curTab + 'Btn').removeClass('selected');
		}
		curTab = name;
		$('#' + name + 'Tab').show();
		$('#' + name + 'Btn').addClass('selected')
	}
	return false;
}