function escapeHTML(s) {
	var replace_tab = {
		'&lt;': /</g,
		'&gt;': />/g,
		'&#039;': /'/g,
		'&quot;': /"/g
	};

	for (var to in replace_tab) {
		s = s.replace(replace_tab[to], to);
	}

	return s;
}

function checkTagsInField(container, inputid) {
	var tags = $(container).childNodes;
	var input = inputid.value.replace(/\s+$/, '');
	if (input != '') {
		var inputarray = input.split(' ');
	} else {
		if (tags) {
			for (var i = 0; i < tags.length; i++) {
				if (tags[i].nodeName == 'A') {
					tags[i].style.border = 'none';
				}
			}
		}
		return;
	}
	if (tags && (inputarray.length > 0)) {
		var tagsa = new Array();
		for (var h = 0; h < tags.length; h++) {
			if (tags[h].nodeName == 'A') {
				tagsa.push(tags[h]);
			}
		}
		for (var i = 0; i < tagsa.length; i++) {
			for (var j = 0; j < inputarray.length; j++) {
				if (tagsa[i].innerHTML == inputarray[j]) {
					tagsa[i].style.border = '1px solid green';
					break;
				} else {
					if (j == (inputarray.length - 1)) {
						tagsa[i].style.border = 'none';
					}
				}
			}
		}
	}
}

function addTextToList(c, d, e, type, config) {
	// used in templates/edit_group.tpl
	var word = c.value;
	var allWords = $(d);
	var wordList = $(e);
	var errorDiv = $('jserror');
	var result = ajax('/api.php?m=validatelogin&p=' + encodeURIComponent(word));
	//if (ajax('/api.php?m=validatelogin&p=' + encodeURIComponent(word)) === true) {
	if (result.result == 0) {
		var errorDiv = $('jserror');
		errorDiv.innerHTML = result.message;
		errorDiv.style.marginLeft = '1em';
	} else {
		if (allWords.innerHTML == '') {
			if (type == 'hiddeninput') {
				allWords.innerHTML = addHtmlHiddenFormInput(word, c.form.id, d);
			} else {
				allWords.innerHTML = word;
			}
		} else {
			if (type == 'hiddeninput') {
				allWords.innerHTML += addHtmlHiddenFormInput(word, c.form.id, d);
			} else {
				allWords.innerHTML += ' ' + word;
			}
		}
		wordList.innerHTML += addHtmlForHiddenFormInput(word, d, config);
		errorDiv.innerHTML = '';
		errorDiv.style.marginLeft = '0px';
		return 1;
	}
}

function addTextToInput(word, d, e) {
	// d.form.id erteke a form id
	// d.id erteke az input id

	var allWords = d;
	var errorDiv = $('jserror');
	if (e) {
		var wordList = $(e);
	}
	if (allWords.value == '') {
		allWords.value = word;
	} else {
		allWords.value += ' ' + word;
	}
	if (wordList) {
		wordList.innerHTML += addHtmlFormInput(word, d.form.id, d.id);
	}
	errorDiv.innerHTML = '';
	errorDiv.style.marginLeft = '0px';
	return 1;
}

function removeText(c, d, e) {
	var textSpan = $(c);
	var allWords = $(d);
	var removable = textSpan.innerHTML;
	var regexes = new Array(
		Array(RegExp('^' + removable + '$'), ""),
		Array(RegExp('^' + removable + ' +'), ""),
		Array(RegExp(' ' + removable + ' '), " "),
		Array(RegExp(' ' + removable + '$'), "")
	);
	for (var i = 0; regexes[i]; i++) {
		allWords.innerHTML = allWords.innerHTML.replace(regexes[i][0], regexes[i][1]);
	}
	if (e) {
		var parentSpan = $(e);
		var textSpanContainer = $('js-lec-' + c);
		parentSpan.removeChild(textSpanContainer);
	}
}

function removeTextFromInput(c, d, e) {
	if (typeof(c) == 'object') {
		var textSpan = $(c);
		var removable = textSpan.innerHTML;
	} else {
		removable = c;
	}
	var allWords = d
	var regexes = new Array(
		Array(RegExp('^' + removable + '$'), ""),
		Array(RegExp('^' + removable + ' +'), ""),
		Array(RegExp(' ' + removable + ' '), " "),
		Array(RegExp(' ' + removable + '$'), "")
	);
	for (var i = 0; regexes[i]; i++) {
		allWords.value = allWords.value.replace(regexes[i][0], regexes[i][1]);
	}
	if (e) {
		var parentSpan = $(e);
		var textSpanContainer = $('js-lec-' + c);
		parentSpan.removeChild(textSpanContainer);
	}
}

function removeTextFromHiddenInput(c, d, e) {
	var parentSpan = $(e);
	var textSpanContainer = $('js-lec-' + c);
	parentSpan.removeChild(textSpanContainer);
	var parentSpan2 = $(d);
	var textSpanContainer2 = $('js-hic-' + c);
	parentSpan2.removeChild(textSpanContainer2);
}

function changeTextInInput(word, d) {
	allWords = d;
	var re = new RegExp('(^| )' + word + '( |$)');
	if (re.test(allWords.value)) {
		removeTextFromInput(word, allWords, '');
		var wordSpan = $(word);
		wordSpan.style.border = 'none';
	} else {
		addTextToInput(word, allWords, '');
		var wordSpan = $(word);
		wordSpan.style.border = '1px solid green';
	}
}

function postEditEntry(s, h, api, title, url, notes, notesz, tags, configid, configuser, rewrite) {
	if (url) {
		var params = 'm=editentry&p[id]=' + encodeURIComponent(configid) + '&edit[title]=' + encodeURIComponent(title) + '&edit[url]=' + encodeURIComponent(url) + '&edit[notes]=' + encodeURIComponent(notes) + '&edit[tags]=' + encodeURIComponent(tags);
	} else if (notesz) {
		var params = 'm=editentry&p[id]=' + encodeURIComponent(configid) + '&edit[title]=' + encodeURIComponent(title) + '&edit[notesz]=' + encodeURIComponent(notesz) + '&edit[notes]=' + encodeURIComponent(notes) + '&edit[tags]=' + encodeURIComponent(tags);
	}

	var entrydata = ajax(api, params);
	if (entrydata.message) {
		errorDiv = $('jserror' + configid);
		errorDiv.innerHTML = entrydata.message;
		errorDiv.style.marginLeft = '1em';
	}
	//if (entrydata !== false) {
	if (entrydata.result != 0) {
		edit_config['entries'][configid]['title'] = title;
		edit_config['entries'][configid]['url'] = url;
		edit_config['entries'][configid]['notes'] = notes;
		edit_config['entries'][configid]['notesz'] = notesz;
		// title & url
		var entryTitle = $('entry-title' + configid);
		if ($('edit_form_url_' + configid)) {
			entryTitle.innerHTML = '<a href="' + $('edit_form_url_' + configid).value + '">' + entrydata['data']['title'] + '</a>';
		} else {
			entryTitle.innerHTML = entrydata['data']['title'];
		}
		// notesz
		if ($('edit_form_notesz_' + configid)) {
			$('entry-notesz' + configid).innerHTML = entrydata['data']['notesz'];
		}
		// notes
		$('entry-notes' + configid).innerHTML = entrydata['data']['notes'];
		// tags & groups
		var entryTags = $('entry-tags' + configid);
		entryTags.innerHTML = "";
		var tagsarray = $('edit_form_tags_' + configid).value.split(" ");
		var gre = /^group:/;
		var tag_counter = 0;
		for (var i = 0; i < tagsarray.length; i++) {
			if (gre.test(tagsarray[i])) {
				var groupElementsArray = tagsarray[i].split(":");
				if (rewrite === true) {
					entryTags.innerHTML += '<a href="/group/' + groupElementsArray[1] + ':' + groupElementsArray[2] + '" class="group">' + tagsarray[i] + '</a> ';
				} else {
					entryTags.innerHTML += '<a href="/entries.php?g=' + groupElementsArray[1] + ':' + groupElementsArray[2] + '" class="group">' + tagsarray[i] + '</a> ';
				}
			} else if (tagsarray[i] == 'visibility:private') {
				entryTags.innerHTML += '<span class="private">' + tagsarray[i] + '</span> ';
			} else if (tagsarray[i] != '') {
				tag_counter++;
				if (rewrite === true) {
					entryTags.innerHTML += '<a href="/user/' + configuser + '/' + tagsarray[i] + '">' + tagsarray[i] + '</a> ';
				} else {
					entryTags.innerHTML += '<a href="/entries.php?u=' + configuser + '&t=' + tagsarray[i] + '">' + tagsarray[i] + '</a> ';
				} 
			}
		}
		if (tag_counter == 0) {
			if (rewrite === true) {
				untagged_link = '<a href="/user/' + configuser + '/system:untagged">system:untagged</a>';
			} else {
				untagged_link = '<a href="/entries.php?u=' + configuser + '&t=system:untagged">system:untagged</a>';
			}
			entryTags.innerHTML = untagged_link + entryTags.innerHTML;
		}
		// h2 title
		var h2title = $('h2title');
		if (h2title) {
			//h2title.innerHTML = document.forms['edit' + configid].title.value;
			h2title.innerHTML = $('edit_form_title_' + configid).value;
		}
		viewSpan(s);
		hideSpan(h);
	}
}

function cancelEditEntry(s, h) {
	var toHide = $(h);
	toHide.innerHTML = '';
	viewSpan(s);
}

function showEditForm(s, h, config, configid, configuser, tagsList, urlornotesz, isowner) {
	var toShow = $(s);
	hideSpan(h);
	var text = addHtmlEditForm(config, configid, configuser, urlornotesz, isowner);
	toShow.innerHTML = text;
	if (toShow.style.display == 'none') {
		toShow.style.display = '';
		toShow.style.visibility = 'visible';
	}
	// script.aculo.us
	new Autocompleter.Local('edit_form_tags_' + configid, 'autocomplete' + configid, tagsList, { tokens: ' ', partialSearch: true, fullSearch: true });
	return false;
}

function hideSpan(c) {
	var Span = $(c);
	Span.style.display = 'none';
	Span.style.visibility = 'hidden';
}

function viewSpan(c) {
	var Span = $(c);
	Span.style.display = '';
	Span.style.visibility = 'visible';
}

function addHtml(c, formname, divname) {
	var text = '<span id="js-lec-' + c + '"><span id="js-lenc-' + c + '">' + c + '</span> <a href="javascript:void(0)" onClick="javascript:removeText(\'' + c + '\', \'document.' + formname + '.' + divname + '\', \'list\');">x</a><br /></span>'
	return text;
}

function addHtmlFormInput(c, formname, inputname) {
	var text = '<span id="js-lec-' + c + '"><span id="js-lenc-' + c + '">' + c + '</span> <a href="javascript:void(0)" onClick="javascript:removeTextFromInput(\'' + c + '\', document.' + formname + '.' + inputname + ', \'list\');">x</a><br /></span>'
	return text;
}

function addHtmlForHiddenFormInput(c, inputname, config) {
	var text = '<span id="js-lec-' + c + '"><span id="js-lenc-' + c + '"><a href="' + config['url'] + c + '">' + c + '</a></span> (<a href="javascript:void(0)" onClick="javascript:removeTextFromHiddenInput(\'' + c + '\', \'' + inputname + '\', \'memberslist\');">' + config['remove'] + '</a>)<br /></span>'
	return text;
}

function addHtmlHiddenFormInput(c, formname, divname) {
	var text = '<span id="js-hic-' + c + '"><input type="hidden" name="' + formname + '[' + divname + '][]" value="' + c + '" /></span>';
	return text;
}

function addHtmlEditForm(config, configid, configuser, urlornotesz, isowner) {
	errorDiv = $('jserror' + configid);
	errorDiv.innerHTML = '';
	errorDiv.style.marginLeft = '0px';
	var config2 = new Array();

	config2['title'] = config['entries'][configid]['title'];
	config2['notes'] = config['entries'][configid]['notes'];
	// url
	var entryTitle = $('entry-title' + configid);
	if (urlornotesz == 'url') {
		config2['url'] = entryTitle.childNodes[0].href;
	}

	// notesz
	if (urlornotesz == 'notesz') {
		config2['notesz'] = config['entries'][configid]['notesz'];
	} else {
		config2['notesz'] = '';
	}
	// tags & groups
	config2['tags'] = '';
	var entryTags = $('entry-tags' + configid);
	if (entryTags.childNodes) {
		for (var i = 0; i < entryTags.childNodes.length; i++) {
			if (entryTags.childNodes[i].nodeName == 'A' || entryTags.childNodes[i].nodeName == 'SPAN') {
				config2['tags'] += entryTags.childNodes[i].innerHTML + ' ';
			}
		}
	}

	// escape form values
	for (var field in config2) {
		if (typeof config2[field] == 'string') {
			config2[field] = escapeHTML(config2[field]);
		}
	}

	var text = '<form name="edit' + configid + '" method="post" id="edit' + configid + '">';
	text += '<input type="hidden" name="a" value="submit" id="a" />';
	text += '<input type="hidden" name="id" value="' + configid + '" id="id" />';
	text += '<table>';
	text += '<tr><td><label for="edit_form_title_' + configid + '">' + config['texts']['title'] + '</label></td>';
	text += '<td><input class="wide" type="text" id="edit_form_title_' + configid + '" name="edit[title]" value="' + config2['title'] + '" /></td></tr>';
	if (urlornotesz == 'url') {
		text += '<tr><td><label for="edit_form_url_' + configid + '">' + config['texts']['url'] + '</label></td>';
		text += '<td><input class="wide" type="text" id="edit_form_url_' + configid + '" name="edit[url]" value="' + config2['url'] + '" /></td></tr>';
	}
	if (urlornotesz == 'notesz') {
		text += '<tr><td><label for="edit_form_notesz_' + configid +'">' + config['texts']['notesz'] + '</label></td><td>';
		if (isowner === true) {
			text += '<textarea name="edit[notesz]" id="edit_form_notesz_' + configid + '">' + config2['notesz'] + '</textarea>';
		} else {
			text += config2['notesz'];
		}
		text += '</td></tr>';
	}
	text += '<tr><td><label for="edit_form_notes_' + configid + '">' + config['texts']['notes'] + '</label></td>';
	text += '<td><input class="wide" type="text" name="edit[notes]" id="edit_form_notes_' + configid + '" value="' + config2['notes'] + '" /></td></tr>';
	text += '<tr><td><label for="edit_form_tags_' + configid + '">' + config['texts']['tags'] + '</label></td>';
	text += '<td><input class="wide" type="text" id="edit_form_tags_' + configid + '" name="edit[tags]" value="' + config2['tags'] + '" autocomplete="off" />';
	text += '<div id="autocomplete' + configid + '" class="autocomplete" style="display:none;"></div>';
	text += '</td></tr>';
	text += '<tr><td><span id="editnewpage' + configid + '"><a href="' + config['texts']['newpageurl'] + configid + '">' + config['texts']['newpage'] + '</a></span></td>';
	if (urlornotesz == 'url') {
		text += '</td><td class="submit"><input type="button" value="' + config['texts']['edit'] + '" ';
		text += 'onClick="postEditEntry(\'entry' + configid + '\', \'editentry' + configid + '\', \'/api.php\', ';
		text += '$(edit_form_title_' + configid + ').value, ';
		text += '$(edit_form_url_' + configid + ').value, ';
		text += '$(edit_form_notes_' + configid + ').value, ';
		text += '\'\', ';
		text += '$(edit_form_tags_' + configid + ').value, ';
		text += '\'' + configid + '\', \'' + configuser + '\', ' + config['rewrite'] + ');" />';
	}
	if (urlornotesz == 'notesz') {
		text += '</td><td class="submit"><input type="button" value="' + config['texts']['edit'] + '" ';
		text += 'onClick="postEditEntry(\'entry' + configid + '\', \'editentry' + configid + '\', \'/api.php\', ';
		text += '$(edit_form_title_' + configid + ').value, ';
		text += '\'\', ';
		text += '$(edit_form_notes_' + configid + ').value, ';
		text += '$(edit_form_notesz_' + configid + ').value, ';
		text += '$(edit_form_tags_' + configid + ').value, ';
		text += '\'' + configid + '\', \'' + configuser + '\', ' + config['rewrite'] + ');" />';
	}
	text += ' <input type="button" value="' + config['texts']['cancel'] + '" onClick="cancelEditEntry(\'entry' + configid + '\', \'editentry' + configid + '\');" />';
	text += '</td></tr>';
	text += '</table>';
	text += '</form>';

	return text;
}

function cancelComment(container) {
	var toHide = $(container);
	toHide.innerHTML = '';
}

function showCommentPreview(textareaid, divid, prev) {
	original = $(textareaid).value;
	if (original != '') {
		var result = ajax('/api.php', 'm=typographic&p=' + encodeURIComponent(original));
		//if (ajax('/api.php', 'm=typographic&p=' + encodeURIComponent(original), false, divid, prev + ':') === true) {
		if (result.result != 0) {
			prevDiv = $(divid);
			if (prev) {
				prevDiv.innerHTML = '<div class="previewtitle">' + prev + ':</div>' + result.message;
			} else {
				prevDiv.innerHTML = result.message;
			}
			prevDiv.style.padding = '0.5em';
			prevDiv.style.backgroundColor = '#eeeeee';
			/*var title = document.createElement('DIV');
			title.setAttribute('class', 'previewtitle');
			var title_content = document.createTextNode(prev + ':');
			title.appendChild(title_content);
			prevDiv = $(divid);
			prevDiv.style.padding = '0.5em';
			var parentDiv = prevDiv.parentNode;
			parentDiv.insertBefore(title, prevDiv);*/
		}
	}
}

function addCommentForm(threadid, parentid, config, container) {
	var toShow = $(container);
	text = '<div class="commentpreview" id="commentpreview' + parentid + '"></div>';
	text += '<form method="POST" action="' + config['actionurl'] + '">';
	text += '<input type="hidden" name="comment[comments_uri]" value="' + config['commentsuri'] + '" />';
	text += '<input type="hidden" name="comment[thread_id]" value="' + threadid + '" />';
	text += '<input type="hidden" name="comment[parent_comment_id]" value="' + parentid + '" />';
	text += '<table>';
	text += '<tr><td>';
	text += config['texts']['message'];
	text += '</td></tr>';
	text += '<tr><td><textarea name="comment[message]" class="commentbox" id="commentbox' + parentid + '"></textarea>';
	text += '</td></tr>';
	text += '<tr><td class="right">';
	text += '<input type="submit" value="' + config['texts']['post'] + '" />';
	text += ' <input type="button" value="' + config['texts']['preview'] + '" onClick="showCommentPreview(\'commentbox' + parentid + '\', \'commentpreview' + parentid + '\', \'' + config['texts']['preview'] + '\');" />';
	text += ' <input type="button" value="' + config['texts']['cancel'] + '" onClick="cancelComment(\'' + container + '\');" />';
	text += '</td></tr>';
	text += '</table>';
	text += '</form>';

	toShow.innerHTML = text;
}

function countChildren(startdiv, first) {
	if (typeof countChildren.count == 'undefined' || first === true) {
		countChildren.count = 0;
	}
	var toCount = $(startdiv).childNodes;
	if (toCount) {
		for (var i = 0; i < toCount.length; i++) {
			/*if (toCount[i].nodeName == 'DIV' && toCount[i].className == 'comment') {
				countChildren(toCount[i].id, false);
			}*/
			if (toCount[i].nodeName == 'DIV' && toCount[i].className == 'asd') {
				countChildren.count++;
				countChildren(toCount[i].id, false);
			}
		}
	}
	return countChildren.count;
}

function displayCount(a, b, text, toView) {
	var c = countChildren(a, true);
	var d = $(b);
	text = text.replace(/number/, c);
	text = ' | <a href="javascript:void(0);" onClick="viewSpan(\'' + toView + '\'); hideSpan(\'' + b + '\');">' + text + '</a>';
	d.innerHTML = text;
	viewSpan(b);
}

