var keyEvent = $browser.ie || $browser.webkit ? "onKeyDown" : "onKeyPress";
var L4F = {
	lite: true,
	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 () {
					$(obj, '<:1').addClass('marked');
					var votes = $("#r" + id);
					votes.innerHTML = eval(votes.innerHTML + act + "1");
				};
			} else {
				$extend(_data, { type: {"b": 1, "s": 2}[act], how: 0 });
				onSuccess = function () {};
			}
			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: "add to Sleds", del: "del from sleds"}
			},
			fav: {
				action: 'star',
				label: { add: "Add to Favorites", del: "in Favorites"}
			}
		},
		mark: function (id, act, obj, marker) {
			if (!L4F.user.loged) {
				//L4F.UI.alert('You need to be registered.');
				//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, '<:1').toggleClass('marked');
					obj.innerHTML = 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) {
			return false;
		}
	},
	comment: {
		vote: function (id, act) {
			var _data = { comment_id: id, how_vote: act + "1", action: "vote_comment" };
			L4F.AjaxQuick({
				data: _data,
				onSuccess: function () { 
					var votes = $("#comment" + id + " ul.actions li.rating span.votes");
					votes.innerHTML = eval(votes.innerHTML + act + "1");
					$$("#comment" + id + " ul.actions li.rating a.vote").each( function (a) { a.removeElement(); });
				},
				from: "COMMENT_VOTE"
			});
			return false;
		},
		replyCurAuthor: '',
		replyCurAuthorCatched: false,
		replyCurId: 0,
		replyCurLvl: 0,
		reply: function (id, author) {
			var com = $("#comment" + id), form = $("#addcomment"), 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);
				form.removeClass("lvl" + (this.replyCurLvl + 1));
				var lvl = parseInt(com.className.match(/lvl(\d+)/)[1]);
				form.addClass("lvl" + (lvl + 1));
				this.replyCurLvl = 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);
				form.removeClass("lvl" + (this.replyCurLvl + 1));
				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 ? "in Friends" : "Add to Friends";
					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 ? "Ignored" : "Ignore User";
					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) {
				return false;
				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 + '">best from ' + user.name + '</a>',
						'<a href="' + links.jokes + '">all from ' + user.name + '</a>',
						'-',
						'<a href="' + links.big_profile + '">adv profile</a>',
						'-'
					];
					if (info.is_my) {
						menu.push(
							'<a href="' + L4F.siteUrl + '/blacklist">My Ignore List</a>',
							'<a href="' + user.link + '/friend_of">My Friends</a>'
						);
					} else {
						menu.push(
							'<a class="button" href="' + L4F.siteUrl + '/sendpm/' + user.name + '">send pm</a>',
							'<a class="button" href="#" onclick="return L4F.user.friend(\'' + user.name + '\', ' + (info.is_friend ? 'false' : 'true' ) + ', this);">' + (info.is_friend ? 'Del friend' : 'add friend') + '</a>',
							'<a class="button" href="#" onclick="return L4F.user.ignor(\'' + user.name + '\', ' + (info.is_ban ? 'false' : 'true' ) + ', this);">' + (info.is_ban ? 'UnIgnore' : 'Ignore') + '</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('Delete message?', 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: {
		imagesCountMax: 51,
		init: function(name) {
			if ($("#" + name + "Gallery")) {
				if ($browser.flashVer >= 8) {
					L4F.addJoke.stdUp = $("#" + name + "Gallery div.file:0");
					L4F.addJoke.flUp = $("#" + name + "flashUploaderFile");
					if (!L4F.addJoke.flUp) {
						L4F.addJoke.flUp = $c("div", {className: "file flashUploaderFile", id: name + "flashUploaderFile"}, [
							$c("span", { id: name + "flashButton" }),
							$c("a", { href: "#", className: 'button useStandart', onclick: function () {
								L4F.addJoke.stdUp.show();
								L4F.addJoke.flUp.hide();
								return false;
							} }, "Use Standart Image Uploader")
						]);
						$("#" + name + "Gallery").insertSiblingPrevious(L4F.addJoke.flUp);
					}
					L4F.addJoke.stdUp.hide();
					L4F.addJoke.flUp.show();
					Uploader.init(L4F.addJoke.uploaderListener(name), $("#" + name + "flashButton"));
				}
			}
		},
		addImage: function (obj) {
			if ($$("#addFormGallery div.file").length > this.imagesCountMax) {
				return false;
			}
			var file = $c("div", { className: "file" },
'<input type="file" class="file" name="files[]" style="vertical-align: middle;" />\
<input type="hidden" name="images[]" value="files" />\
<div class="buttons"><a href="#" class="button" onclick="return L4F.addJoke.addImage(this)"><img src="/styles/btn-plus.gif" alt="+" /></a>\
 <a href="#" onclick="return L4F.addJoke.delImage(this);"><img src="/styles/btn-x.gif" alt="x" /></a>\
 <a href="#" onclick="return L4F.addJoke.upImage(true, this);"><img src="/styles/btn-up.gif" alt="&uarr;" /></a>\
 <a href="#" onclick="return L4F.addJoke.upImage(false, this);"><img src="/styles/btn-down.gif" alt="&darr;" /></a></div>');
			if (obj == undefined) {
				$("#addFormGallery").insertChildFirst(file);
			} else {
				$(obj, "<div.file").insertSiblingNext(file);
			}
			return false;
		},
		delImage: function (obj) {
			$(obj, "<:2").removeElement();
			return false;
		},
		upImage: function (up, obj) {
			var obj = $(obj, "<:2");
			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("MAXIMUM " + this.tagsCountMax + " TAGS");
					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: function(form_name) {
			return {
				onInit: function () {
				},
				onOpen: function (id, name) {
					if ($$("#" + form_name + "Gallery div.file").length > L4F.addJoke.imagesCountMax) {
						this.stop();
						return;
					}
					$("#" + form_name + "Gallery").appendChild($c(
						"div",
						{ id: form_name + "flUpImg" + id, className: "file", fileInfo: { name: name } },
						'Uploading <span class="fileName">' + name + '</span>...'
					));
				},
				onProgress: function (id, loaded, total) {
					var str = 'Uploading <span class="fileName">' + $("#" + form_name + "flUpImg" + id).fileInfo.name + '</span>... '
					if (loaded < total) {
						str += '<span class="fileProgress">' + Math.round(100 * loaded / total) + '%</span>';
					} else {
						str += 'is done! <span class="fileProgress">Processing, please wait...</span>';
					}
					$("#" + form_name + "flUpImg" + id).innerHTML = str;
				},
				onError: function (id, error) {
					this.stop();
					L4F.UI.alert("Internal error. Sorry =)");
					L4F.UI.alert(error);
					//AjaxQuick({ url: '/js_error.php', data: { TYPE: 'ajax', ENTRY: error, FROM: "UPLOADER" } });
					$("#" + form_name + "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") {
							$("#" + form_name + "flUpImg" + id).innerHTML = 'Picture <span class="fileName">' + $("#" + form_name + "flUpImg" + id).fileInfo.name + '</span> almost was<div class="buttons"><a href="#" onclick="return L4F.addJoke.delImage(this);"><img src="/styles/btn-x.gif" alt="x" /></div>';
						} else if (code.errorType == "good") {
							L4F.UI.alert(code.errorText);
							$("#" + form_name + "flUpImg" + id).removeElement();
							this.stop();
						} else {
							this.onError(id, "SERVER: (" + code.errorType + ") " + code.errorText);
						}
						return;
					}
					$("#" + form_name + "flUpImg" + id).innerHTML =
	'<img src="' + code.preview.src + '" /><input type="hidden" name="images[]" value="' + code.name + '" />\
	<div class="buttons"><a href="#" onclick="return L4F.addJoke.delImage(this);"><img src="/styles/btn-x.gif" alt="x" /></a>\
	 <a href="#" onclick="return L4F.addJoke.upImage(true, this);"><img src="/styles/btn-up.gif" alt="&uarr;" /></a>\
	 <a href="#" onclick="return L4F.addJoke.upImage(false, this);"><img src="/styles/btn-down.gif" alt="&darr;" /></a></div>';
				}
			}
		}
	},
	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("Type number of page (from 1 to " + 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("No such a page");
				}
			}
		});
		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: "Yes", click: function() {
						func();
						w.close();
					}, focus: true },
					{ title: "No", 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: "Close", 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: "Ok", click: function () {
						value = pr.value;
						w.close();
					}, key: "enter"},
					{title: "Cancel", 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("Need to be signed in");
			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("Internal error. Please resign in", "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("Internal error. Please resign in.", "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("Internal error. Please resign in.", "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(); });

		//if (!L4F.lite) {
		/*$(window).addEvent("onLoad", function () {
			if (_this.list.scrollWidth <= _this.list.clientWidth) {
				_this.list.style.height = "140px";
			}
		});*/
			
		var btnPrev = $(big, "span.btn-prev"), btnNext = $(big, "span.btn-next");
		
		var babs = big.absPos();
		var vclw = big.clientWidth / 2;
		big.addEvent("onMouseMove", function (e) {
			if (e.page.x - babs.x - vclw < 0) {
				btnPrev.addClass("btn-active");
				btnNext.removeClass("btn-active");
			} else {
				btnPrev.removeClass("btn-active");
				btnNext.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, "p").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, "p").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);
		this.list.scrollLeft = 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.loading = true;
			this.loadSpan = $c('span', {className: 'loading'});
			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;
var 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);
}

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 + '/styles/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 };
		}
	}
}

var cconfig_len = 10;
function cconfig (place, value) {
	var cc = new Array(cconfig_len);
	var _cc = getCookie("cc");
	if (_cc == null) {
		for (var i = 0; i < cconfig_len; i++) {
			cc[i] = '0';
		}
	} else {
		_cc = _cc.split('', cconfig_len);
		_cc.unshift(0, _cc.length);
		cc.splice.apply(cc, _cc);
	}
	if (typeof value == "undefuned") {
		return cc[place];
	} else {
		if (typeof value == "boolean") {
			value = value ? "1" : "0"
		}
		cc[place] = value;
		setCookie("cc", cc.join(''), 7);
	}
}

function getCookie(sName) {
	var aCookie = document.cookie.split(";");
	for (var i = 0; i < aCookie.length; i++) {
		var aCrumb = (aCookie[i].trim()).split("=");
		if (sName == aCrumb[0]) 
			return unescape(aCrumb[1]);
	}
	return null;
}
function setCookie(c_name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	var domain = location.hostname.split('.');
	if (domain.length > 1) {
		domain = '.' + domain[domain.length - 2] + '.' + domain[domain.length - 1]
	} else {
		domain = domain[1];
	}
	document.cookie=c_name+ "=" +escape(value)+ ";domain=" + domain + ";path=/" + ((expiredays == null) ? "" : ";expires="+exdate.toGMTString());
}

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

function jokePreviewScroll(obj) {
	obj.onmouseover = Function.empty;
	obj = $(obj);
	var entry = $(obj, "> span");
	var objh = 113;
	var enth = entry.clientHeight;
	var speed = 0.03;
	if (objh < enth) {
		var pos = 0;
		var move = 0;
		var maxpos = enth - objh;
		var time = $uts();
		(function  () {
			var delta = $uts() - time;
			time = $uts();
			if (move != 0 && (delta > 0)) {
				pos += move * speed * delta;
				time = $uts();
				if (pos > maxpos) {
					pos = maxpos;
					move = 0;
				}
				if (pos < 0) {
					pos = 0;
					move = 0;
				}
				obj.scrollTop = Math.round(pos);
				//entry.applyStyle({marginTop: -Math.round(pos) + 'px'});
			}
			//$('input.text').value = pos;
		}).toInterval(10);
		move = 1;
		//(function  () { $('input.text').value = omo++; }).toInterval(10);
		obj.addEventListener({
			onMouseOver: function () {
				move = 1;
			},
			onMouseOut: function () {
				move = -1;
			}
		});
	}
}


var tags = {};


function tagsEdit (inp) {

//	alert('lol');
	var tagsBlock = $c('span');
	var newInp = $c('textarea', {
		rows: 1,
		cols: 20,
		style: {
		}
	});
	var tagsInput = $c('div', { className: 'tagsEdit'}, [tagsBlock, $c('span', {}, '<wbr />&nbsp;'), newInp]);
	
	
	//inp.type = 'hidden';
	inp = $(inp);
	inp.style.display = 'none';
	newInp.id = inp.id;
	inp.id = '';
	
	//var selection = new Selection(newInp);
	
	var curTags = inp.value.trim().toLowerCase().split(/\s*,\s*/);
	if (curTags[0] == '') {
		curTags.shift();
	}
	
	function removeTag(tag, obj) {
		$(obj, '<:3').removeElement();
		curTags.remove(tag);
		inp.value = curTags.join(',');
		return false;
	}
	
	var curTag;
	
	function createTag (name) { 
		return $c('span', {}, [
			$c('span', {}, '<wbr />&nbsp;'),
			$c('a', {
				href: "#",
				className: "tag",
				onclick: Function._false
			}, $c('span', {}, [
				$t(name),
				$c('span', { className: 'sp sp-del', onclick: function () { return removeTag(name, this); } }, '&nbsp;')
			]) ),
			$c('span', { style: { display: 'none' } }, ',' )
		]);
	}
	
	for (var i = 0; i < curTags.length; i++) {
		curTag = curTags[i].trim();
		if (curTag != '') {
			tagsBlock.appendChild(createTag(curTag));
		}
	}
	
	inp.insertSiblingNext(tagsInput);
	
	function editTag(e, blur) {
		var val = newInp.value;
		if ((val.indexOf(',') != -1) || (blur == true)) {
			val = val.trim().toLowerCase().split(/\s*,\s*/);
			for (var i = 0; i < val.length; i++) {
				if ((val[i] != '') ? (curTags.search(val[i]) == -1) : false) {
					tagsBlock.appendChild(createTag(val[i]));
					curTags.push(val[i]);
				}
			}
			curval = '';
			newInp.value = '';
			inp.value = curTags.join(',');
		}

		if (blur) {
			autoInput.hide();
		} else {
			editAutoInput();
		}
	}
	
	function editTagEnter(e) {
		if (e.key == 'enter') {
			if (variants_cur != -1) {
				newInp.value = $(autoInput, 'li', variants_cur, 'span').innerHTML;
			}
			editTag(e, true);
			return false;
		}
		if ((e.key == 'backspace') && (getSelectionStart(newInp) == 0) && (curTags.length > 0)) {
			$$(tagsBlock, 'a <:1').pop().removeElement();
			newInp.value = curTags.pop() + newInp.value;
			return false;
		}
		if (((e.key == 'down') || (e.key == 'up')) && (variants_cnt > 0)) {
			if (variants_cur == -1) {
				variants_cur = e.key == 'down' ? 0 : variants_cnt - 1;
			} else {
				$(autoInput, 'li', variants_cur).removeClass('selected');
				variants_cur += e.key == 'down' ? 1 : -1;
				if (variants_cur == -1) {
					variants_cur = variants_cnt - 1;
				}
				if (variants_cur == variants_cnt) {
					variants_cur = 0;
				}
			}
			$(autoInput, 'li', variants_cur).addClass('selected');
			return;
		}
		if ((e.key == 'esc') && (variants_cur != -1)) {
			$(autoInput, 'li', variants_cur).removeClass('selected');
			variants_cur = -1;
			return false;
		}
	}
	
	function editTagQuick(e) {
	}

	var autoInput = $c('ul', { className: 'tags-auto' } );
	autoInput.hide();
	//autoInput.addEvent("onClick", function() { alert(-4); });
	$(window).addEvent("onLoad", function () {$('body').appendChild(autoInput); });
	
	var variants_cnt = 0;
	var variants_cur = -1;
	var curval = '';
	
	function editAutoInput() {
		var val = newInp.value.trim().toLowerCase();
		if (curval != val) {
			curval = val;
			autoInput.innerHTML = '';
			variants_cnt = 0;
			variants_cur = -1;
			var apos = newInp.absPos()
			autoInput.applyStyle({ top: (apos.y + newInp.clientHeight) + 'px', left: apos.x + 'px' })
			autoInput.hide();
			if (val != '') {
				var got = true;
				for (var i in tags) {
					if ((i.substr(0, val.length).toLowerCase() == val) && !curTags.has(i.toLowerCase())) {
						autoInput.appendChild($c('li', {}, createTagAutoInput(i)));
						variants_cnt++;
						if (got) {
							got = false;
							autoInput.show();
						}
					}
				}
			}
		}
	}
	
	function createTagAutoInput (name) {
		return $c( 'a', {
			className: 'tag',
			href: '#',
			onmousedown: function (e) {
				//alert(2);
				return false;
			},
			onclick: function (_e) {
				//alert(-3);
				newInp.value = name;
				editTag(new _Event(_e), true);
				newInp.focus();
				return false;
			}
		}, '<span>' + name + '</span>')
	}
		
	function editTagBlur(e) {
		//alert(1);
		autoInput.hide();
		editTag(e, true);
	}
	
	newInp.addEventListener({
		onKeyUp: editTag,
		onBlur: editTagBlur
	});
	
	newInp.addEvent(keyEvent, editTagEnter);
	
	tagsInput.addEvent('onClick', function (e) {
		newInp.focus();
	});
}

function getSelectionStart(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveEnd('character', o.value.length)
		if (r.text == '') return o.value.length
		return o.value.lastIndexOf(r.text)
	} else return o.selectionStart
}

function _dttm(uts) {
	var date = new Date(uts * 1000);
	var hour = date.getHours(), ap = 'AM';
	if (hour   > 11) { ap = "PM"; }
	if (hour   > 12) { hour = hour - 12; }
	if (hour   == 0) { hour = 12; }
	var minute = date.getMinutes();
	if (minute < 10) { minute = "0" + minute; }
	var _dtm = ["January","February","March","April","May","June","July","August","September","October","November","December"];
	document.write(_dtm[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear() + ' ' + hour + ':' + minute + ' ' + ap);
}

function _dt(uts) {
	var date = new Date(uts * 1000);
	var _dtm = ["January","February","March","April","May","June","July","August","September","October","November","December"];
	document.write(_dtm[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear());
}

function _dttz() {
	setCookie('timezone_offset', (new Date()).getTimezoneOffset() * 60, 7);
}