function removeNode(node) {
	if (typeof node === "string") {
		node = $(node);
	}
	if (node && node.parentNode) {
		node.parentNode.removeChild(node);
	}
}

function setNodeVisible(id, visible) {
	if (el = $(id)) {
		el.style.display = visible ? "" : "none";
	}
}

function hideElement(id) {
	setNodeVisible(id, false);
}

function alertThanx() {
	alert('Aciu už pranešimą.');
}

function showLameBrowserWarning() {
	var userAgent = navigator.userAgent;
	if (userAgent.indexOf("MSIE") !== -1 && userAgent.indexOf("MSIE 8.") === -1 && (el = $("container"))) {
		var node = el.parentNode.insertBefore(document.createElement("DIV"), el);
		node.innerHTML = "! Jūs naudojate nesaugią, atsilikusią ir <a href=\"http://www.bajeriai.lt/\">bajeriai.lt</a> nepritaikytą naršyklę - Internet Explorer. " + 
			"Naudokite: <a href=\"http://www.firefox.com/\" target=\"_blank\">Firefox</a>, <a href=\"http://www.opera.com/\" target=\"_blank\">Opera</a>, <a href=\"http://www.google.lt/chrome\" target=\"_blank\">Chrome</a>, ...";
		node.className = "lame_browser";
	}
}

function firefoxEscapeWorkaround() {
	var nodes = document.getElementsByTagName("SPAN");
	for (var i = 0; i < nodes.length; i++) {
		try {
			var node = nodes[i];
			if (node.getAttribute("unescape") != 1) {
				continue;
			}
			node.parentNode.insertBefore(document.createElement("TEXT"), node)
				.innerHTML = node.firstChild.data ? node.firstChild.data : node.innerText;
			node.parentNode.removeChild(node);
			i--;			
		} catch (e) {}
	}
}

function sendAJAX(url, data, listener) {
	new Ajax.Request(
		url, {
			onSuccess: listener ? listener.onSuccess.bind(listener) : null, method : "POST", 
			parameters : data
		}
	);
}

function setCookie(name, value, days) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 3600000));
		expires = "; expires=" + date.toGMTString();
	}
	document.cookie = name + "=" + value+expires + "; path=/";
}
 
function getCookie(name) {
	var nameEQ = name + "=";
	var parts = document.cookie.split(';');
	var l = parts.length;
	for (var i = 0; i < l; i++) {
		var part = parts[i];
		while (part.charAt(0)==' ') {
			part = part.substring(1, part.length);
		}
		if (part.indexOf(nameEQ) == 0) {
			return part.substring(nameEQ.length, part.length);
		}
	}
	return null;
}
 
function removeCookie(name) {
	setCookie(name, "", -1);
}

function onJokeTypeChanged() {
	var form = Form.get(1);
	var type = Number(form.getFieldValue("type"));
		
	form.setFieldVisible("file_image", type == 2);
	form.setFieldVisible("url_remote_video", type == 3);
	form.setFieldVisible("url_remote_audio", type == 4);	
	form.setFieldVisible("file", type == 5);
	form.setFieldVisible("url_remote_interactive", type == 5);
	
	form.setFieldRequired("text", type == 1);	
}

function rejectJoke(path, element_id){
	sendAJAX(path, true);
	hideElement(element_id);	
}

var BajeriaiVoteListener = function(joke) {
	
	this.joke = joke;
	
	this.onSuccess = function(request) {
		var root = request.responseXML.documentElement;
		var joke = root.getElementsByTagName("joke")[0];
		var rating = joke.getElementsByTagName("rating")[0].firstChild.nodeValue;			
		var id = this.joke;
		var id_prefix = '__joke_' + id;
		var el_rating = $(id_prefix + '_rating');
		el_rating.innerHTML = (rating > 0 ? '+': '') + rating;
		if ($(id_prefix + '_plus')) {
			el_rating.style.display = "";
		}
		removeNode(id_prefix + '_vplus');
		removeNode(id_prefix + '_vminus');
		removeNode(id_prefix + '_plus');
		removeNode(id_prefix + '_minus');
	}
	
}

function loaded() {
	var fobj = $("flasth_object");
	var path = "_f/img/jokes/paveiksleliai/";
	var l = __image_jokes.length;
	for (var i = 0; i < l; i++) {
		fobj.addImage(path + __image_jokes[i][0], path + __image_jokes[i][1]);
	}
}

function initializeImagesView() {
	$("jokes_list").style.display = getCookie("images_list_view") === "gallery" ? "" : "none";
	showJokesImagesGallery();
}

function showJokesImagesGallery() {
	var gallery = $("jokes_list").style.display !== "none";
	$("jokes_list").style.display = gallery ? "none" : "";
	$("flash_gallery").style.display = gallery ? "" : "none";
	if (!$("flasth_object")) {
		flash = new SWFObject("_f/flash/eGallery.swf", "flasth_object", "805", "685", "10", "#BABABA");
		flash.write("flash_gallery");
	}
	setCookie("images_list_view", gallery ? "gallery" : "");
	$("link_as_gallery").style.display = gallery ? "none" : "";
	$("link_as_list").style.display = gallery ? "" : "none";
}
function unmarkJoke(uri) {
	var listener = {};
	listener.onSuccess = function(request) {
		var node_joke = request.responseXML.documentElement.getElementsByTagName("joke")[0];
		var joke_id = node_joke.getElementsByTagName("id")[0].firstChild.nodeValue;
		removeMarkedJoke(joke_id);
	}
	sendAJAX(uri, null, listener);
}
function markJoke(node_star, uri, uri_unmark) {
	var listener = {node : node_star, uri_unmark : uri_unmark};
	listener.onSuccess = function(request) {
		var node_joke = request.responseXML.documentElement.getElementsByTagName("joke")[0];
		var nodes_thumb = node_joke.getElementsByTagName("filename_thumb");
		var thumb = null;
		var type = node_joke.getElementsByTagName("id_jokes_types")[0].firstChild.nodeValue;
		if (nodes_thumb && nodes_thumb[0]) {
			thumb = nodes_thumb[0].firstChild.nodeValue;
			thumb = '_f/img/jokes/' + __joke_types[type].name + "/" + thumb;
		}
		var tags = new Array();
		var nodes_tags = node_joke.getElementsByTagName("tags");
		if (nodes_tags && nodes_tags[0]) {
			var nodes_tag = nodes_tags[0].childNodes;
			var l = nodes_tag.length;
			for (var i = 0; i < l; i++) {
				tags.push(nodes_tag[i].firstChild.nodeValue);
			}
		}
		var description = "";
		try {
			description = node_joke.getElementsByTagName("text")[0].firstChild.nodeValue;
		} catch (e) {}
		addMarkedJoke(
			{
				type : type, 
				id : node_joke.getElementsByTagName("id")[0].firstChild.nodeValue, 
				description : description,
				thumb : thumb,
				tags : tags
			},
			uri_unmark
		);		
	}
	sendAJAX(uri, null, listener);
}
function showHideMarkedJokes() {
	var el = $('marked');
	var show = el.style.display == "none";
	el.style.display = show ? "" : "none";
	updateMarkedExpandButton();
}
function updateMarkedExpandButton() {
	var el = $('marked');
	$("marked_button").innerHTML = (el.style.display != "none" ? "Suskleisti" : "Išskleisti") + " (" + el.childNodes.length + ")";
}
function removeMarkedJoke(id) {
	if (el = $("__marked_joke_" + id)) {
		removeNode(el)
	}
	setJokeStarClass(id, "star_off");
	updateMarkedExpandButton();
	el = $('marked');
	if (el.childNodes.length < 1) {
		removeNode($("marked_container"));
	}
}
function setJokeStarClass(joke_id, class_name) {
	if (el_list = $("jokes_list")) {
		var l = el_list.childNodes.length;
		for (var i = 0; i < l; i++) {
			var el_li = el_list.childNodes[i];
			var el_star = $(el_li.id + "_star");
			if (el_star && el_star.getAttribute("joke_id") == joke_id) {
				el_star.className = class_name;
			}
		}
	}	
}
function addMarkedJoke(data, uri_unmark) {
	var el = $('marked');
	if (!el) {
		var el_container = $('container');
		var el_marked = el_container.insertBefore(document.createElement("DIV"), el_container.firstChild);
		el_marked.className = "marked_jokes";
		el_marked.id = "marked_container";
		el = el_marked.appendChild(document.createElement("UL"));
		el.id = "marked";
		el.style.display = "none";
		var el_button = el_marked.appendChild(document.createElement("A"));
		el_button.setAttribute("href", "javascript:showHideMarkedJokes();void(null)");
		el_button.id = "marked_button";
		el_button.className = "expand";
		el_button.innerHTML = "Išskleisti (0)";
		
		el_button = el_marked.appendChild(document.createElement("A"));
		el_button.setAttribute("href", "rinkiniai/sukurti_pagal_pazymetus");
		el_button.id = "marked_button";
		el_button.innerHTML = "Versti į rinkinį";
	}
	if ($("__marked_joke_" + data.id)) {
		return false;
	}
	var el_li = el.appendChild(document.createElement("LI"));
	el_li.id = "__marked_joke_" + data.id;
	
	var description_short = data.description;
	if (description_short.length < 1 && data.tags) {
		description_short = "";
		var l = data.tags.length;
		if (l > 0) {
			description_short = new Array();
			for (var i = 0; i < l; i++) {
				description_short.push(data.tags[i]);
			}
			description_short = description_short.join(" ");
		}
	}
	if (description_short.length > 60) {
		var parts = description_short.substr(0, 60).split(" ");
		description_short = parts.slice(0, parts.length - 1).join(" ");
		if (description_short.length > 0) {
			description_short += "...";
		}
	}
	var type = __joke_types[data.type];
	el_a = el_li.appendChild(document.createElement("A"));
	el_a.href = type.name + "/id/" + data.id;
	if (data.thumb) {
		var el_img = el_a.appendChild(document.createElement("IMG"));
		el_img.setAttribute("src", data.thumb);
	}
	if (!data.thumb) {
		el_a.appendChild(document.createElement("B")).appendChild(document.createTextNode(type.title_5));
		el_a.appendChild(document.createTextNode(": "));
	}
	el_a.appendChild(document.createTextNode(description_short));
	var node_delete = el_li.appendChild(document.createElement("A"));
	node_delete.className = "delete";
	node_delete.href = "javascript:unmarkJoke('" + uri_unmark + "?xml')";
	node_delete.innerHTML = "X";
	
	updateMarkedExpandButton();
	setJokeStarClass(data.id, "star_on");	
}
function sendJokeBad(uri) {
	sendAJAX(uri);
	alertThanx();
	return void(0);
}
function renderJokeControls(id, position, voted, rating) {
	voted = voted == 1;
	var el = $("__joke_" + position)
	el.innerHTML = 
		"<div class=\"jokes_rating\" title=\"Bajerio reitingas\" id=\"__joke_" + position + "_rating\" " + 
		(voted ? "" : " style=\"display:none\"") + ">" + (rating > 0 ? "+" : "") + rating + "</div>" +
		(
				voted ? "" :
				"<a id=\"__joke_" + position + "_minus\" title=\"Balsuoti kad bajeris nevertas dėmesio\" class=\"minus_off\" href=\"javascript:sendAJAX('bajeris/balsuoti/" + id + "/-?xml', true, new BajeriaiVoteListener('" + position + "'));\"><br /></a>" +				
				"<a id=\"__joke_" + position + "_plus\" title=\"Balsuoti kad geras bajeris\" class=\"plus_off\" href=\"javascript:sendAJAX('bajeris/balsuoti/" + id + "/+?xml', true, new BajeriaiVoteListener('" + position + "'));\"><br /></a>"
		) +
		"<a id=\"__joke_" + position + "_star\" joke_id=\"" + id + "\" " +
		"title=\"Pažymėti / atžymėti bajerį\" " +
		"href=\"javascript:markJoke($('__joke_" + position + "_star'), 'bajeris/pazymeti/" + id + "?xml'," +
		"'bajeris/atzymeti/" + id + "')\" class=\"star_off\"><br /></a>"
		+ el.innerHTML;
}
function renderSortBar(by, path) {
	var fields = {"time" : "laiką", "rating" : "reitingą", "views" : "populiarumą"};
	var content = ["Rūšiuojama pagal: "];	
	for (var field in fields) {
		content.push(
			"<a " + (by == field ? "class=\"active\"" : "href=\"" + path + "sort/" + field + "\"")+ ">" + 
			fields[field] + "</a>"
		);
	}
	$("container_sortbar").innerHTML = content.join("");
}
function renderPaging(offset, total, limit, url) {
	limit = Number(limit);
	var el = $("__paging__");
	var pages = Math.ceil(total / limit);
	if (pages <= 1) {
		return false;
	}
	
	var pageActive = Math.floor(offset / limit);
	var pagesOnOneSide = 8;
	var pagesAround = pagesOnOneSide > pageActive ? (pagesOnOneSide * 2) - pageActive : pagesOnOneSide;
	var content = ["<ul class=\"paging\">"];
	
	var pageCurrent = Math.max(pageActive - 1, 0);
	var offsetActive = pageCurrent * limit;
	content.push(
		"<li><a href=\"" + url + (pageActive != 1 ? offsetActive : "") + "\" class=\"next_previous arrow_left\" " + 
		"title=\"Ankstesnis puslapis[" + (offsetActive + 1) + " - " + ((pageCurrent + 1) * limit) + "]\"><br /></a></li>"
	);
	
	pageCurrent = Math.min(pageActive + 1, pages - 1);
	offsetActive = pageCurrent * limit;
	content.push(
		"<li><a href=\"" + url + offsetActive + "\" class=\"next_previous arrow_right\" " + 
		"title=\"Sekantis puslapis[" + (offsetActive + 1) + " - " + (pages > pageCurrent + 1 ? (pageCurrent + 1) * limit : total) + "]\"><br /></a></li>"
	);
	for (var i = Math.max(pageActive - pagesAround, 0); i < Math.min(pageActive + pagesAround + 1, pages); i++) {
		offsetActive = i * limit;
		content.push(
			"<li><a href=\"" + url + offsetActive + "\" " + (i == pageActive ? "class=\"active\"" : "") + " " + 
			"title=\"" + (i + 1) + " puslapis[" + (offsetActive + 1) + " - " + Math.min(offsetActive + limit, total) + "]\">" + (i + 1) + "</a></li>"
		);		
	}
	content.push("</ul>");
	el.innerHTML = content.join("");
	el.id = "";
}
function renderTopBar(activeType, basehref) {
	var content = [
	  "<li style=\"float: right\"><a href=\"bajeris/atsiusti/daug\" title=\"Atsiųsti daug anekdotų iškarto\">DA</a></li>",
	  "<li style=\"float: right\"><a href=\"bajeris/atsiusti/" + (activeType ? "0/" + activeType + "/" : "") + "\">ATSIŲSTI BAJERĮ</a></li>",
	  "<li style=\"float: right\"><form method=\"post\" action=\"paieska\" class=\"search\">" +
	  	"<input type=\"text\" id=\"search\" name=\"search\" onfocus=\"this.select()\" />" +
	  	"<select name=\"type\" id=\"search_type\"><option>[Visi tipai]</option></select>" +
	  	"<input type=\"submit\" value=\"Ieškoti\" />" +
	  "</form></li>"		
  ];

	var el = $("bar_top");
	el.innerHTML = "<li class=\"bajeriai\"><a href=\"" + basehref + 
		"\" title=\"bajeriai.lt\" class=\"active\">bajeriai.lt</a></li>" + el.innerHTML + 
		content.join("");
}