/********************************
* Linnea user-editor validation *
********************************/
// Verify that required fields in userform are filled
function ValidateUserEditor(userform) {
	if (userform.nimi.value == '' || userform.tunnus.value == '' || userform.salasana.value == '') {
		alert("Täytä tähdellä merkityt kentät!");
		return false;
	}
	return true;
}




/**************************
* Linnea TEXTAREAEDITABLE *
**************************/
// If there is text selected, enclose it with tags Tagopen and Tagclose.
// If text has not been selected, add both tags at current cursor position.
// Mozilla and IE like the also select the trailing space when user selects a word by double
// clicking - not incorrect but still ugly so that space is moved to after the closing tag.
function AddTags(textareaid, tagopen, tagclose) {
	var textarea = document.getElementById(textareaid);
	
	// Mozilla and Opera codepath:
	if (textarea.setSelectionRange) {
		// Workaround for Mozilla scroll-to-top bug
		var scrollpos = textarea.scrollTop;

		// Get selection properties
		var selstart = textarea.selectionStart;
		var selend   = textarea.selectionEnd;
		var sellen   = selend - selstart;
		var seltext  = textarea.value.substr(selstart, sellen);

		// Reduce selection range if last char is space
		if (seltext.charAt(seltext.length - 1) == ' ') {
			selend--;
			sellen--;
			seltext  = textarea.value.substr(selstart, sellen);
		}

		// Enclose selected text with tags
		var leadingtext = textarea.value.substr(0, selstart);
		var trailingtext = textarea.value.substr(selend);
		textarea.value = leadingtext + tagopen + seltext + tagclose + trailingtext;

		// Set new position for cursor
		if (sellen == 0) {
			// Move text cursor to right after the opening tag
			var caretpos = selend + tagopen.length;
			textarea.setSelectionRange(caretpos, caretpos);
		}
		else {
			// Move text cursor to right after the closing tag
			var caretpos = selend + tagopen.length + tagclose.length;
			textarea.setSelectionRange(caretpos, caretpos);
		}

		// Workaround for Mozilla scroll-to-top bug
		textarea.scrollTop = scrollpos;
	}

	// IE codepath (works in Opera too but the Mozilla codepath has smart cursor placement):
	else if (textarea.createTextRange) {
		var seltext = textarea.caretPos.text
		// Selection exists - enclose with tags
		if (seltext) {
			// Move trailing space in selection after the added tag pair
			if (seltext.charAt(seltext.length - 1) == ' ') {
				seltext = seltext.substring(0, seltext.length - 1);
				textarea.caretPos.text = tagopen + seltext + tagclose + " ";    
			}
			else {
				textarea.caretPos.text = tagopen + seltext + tagclose;    
			}
		}
		// No selection made - add tags with nothing between them
		else {
			textarea.focus();
			var sel = document.selection.createRange();
			sel.text = tagopen + tagclose;
		}
	}
	
	textarea.focus();
}

// Some IE hack to keep cursor position
function StoreCaret(textarea) {
	if (textarea.createTextRange)
		textarea.caretPos = document.selection.createRange().duplicate();
}

// Create hyperlink 
function CreateLink(textareaid, url, opensNewWindow) {
	var tagopen = "";
	var tagclose = "[/a]";
	if ((url.indexOf('\@') != -1) && (url.indexOf('mailto:') == -1))
		url = 'mailto:' + url;
	if (opensNewWindow == 1) {
		tagopen = "[a href='" + url + "' target='_blank']";
	}
	else {
		tagopen = "[a href='" + url + "']";
	}
	AddTags(textareaid, tagopen,tagclose);
}



/********************************
* Linnea page-editor validation *
********************************/
// Verify that input field CONTENT:TITLE in page edit form is not empty.
// Not the easiest job because of the ':' in the field name.
function ValidatePageEditor(pageform){
	return; // Olkoon ilman otsikkoa jos halutaan
	for (var i=0; i<=pageform.elements.length; i++){
		var fieldname = pageform.elements[i].name;
		if (fieldname.match('CONTENT:TITLE')){
			var fieldvalue = pageform.elements[i].value;
			if (fieldvalue.match(/\S/)) {
				return true;
			}
			else {
				alert('Sivun otsikko puuttuu!');
				pageform.elements[i].value='Kirjoita otsikko tähän...';
				pageform.elements[i].focus();
				pageform.elements[i].select();
				return false;
			}
		}
	}
	return true;
}



/******************************************
* Special fun for venajanverkosto[venaja] *
******************************************/
function ClearIngress(pageform){
	for (var i=0; i <= pageform.elements.length ; i++){
		var fieldname = pageform.elements[i].name;
		if (fieldname.match('CONTENT:INGRESS')){
			pageform.elements[i].value = '[!-- --]';
		}
	}
}



/*****************
* Linnea foorumi *
*****************/
// Change visible post in viewpost threaded mode
function bbs_show_post(id) {
	if (bbs_open_post_id) { // global var set by bbs.pm
		document.getElementById('bbs_post_' + bbs_open_post_id).style.display = 'none';
		document.getElementById('bbs_post_link_' + bbs_open_post_id).className = 'bbs_postlist_ptitle';
	}
	document.getElementById('bbs_post_' + id).style.display = 'block';
	document.getElementById('bbs_post_link_' + id).className = 'bbs_postlist_ptitle_active';
	bbs_open_post_id = id;
	location.hash = 'bbspost' + id;
	return false;
}

// Change visible page in viewpost flat mode
function bbs_view_page(page_id) {
	for (var i=0; i<100; i++) {
		if (document.getElementById('bbs_page_' + i) != null) {
			document.getElementById('bbs_page_' + i).style.display = 'none';
			document.getElementById('bbs_navitop_' + i).style.textDecoration = 'underline';
			document.getElementById('bbs_navibtm_' + i).style.textDecoration = 'underline';
		}
	}
	document.getElementById('bbs_page_' + page_id).style.display = 'block';
	document.getElementById('bbs_navitop_' + page_id).style.textDecoration = 'none';
	document.getElementById('bbs_navibtm_' + page_id).style.textDecoration = 'none';
	location.hash = 'bbs_post_anchor';
	return false;
}


// Validate posting form
function bbs_compose_validate(form) {
	for (var i=0; i<form.length; i++) {
		if (form.elements[i].value.match(/^\s*$/)) {
			var err = null;
			if (form.elements[i].name == 'bbsthreadtitle')
				err = "Kirjoita viestiketjun aihe";
			if (form.elements[i].name == 'bbsposttitle')
				err = "Kirjoita viestin otsikko";
			if (form.elements[i].name == 'bbsnick')
				err = "Kirjoita nimimerkki";
			if (form.elements[i].name == 'bbsbody')
				err = "Kirjoita viestin teksti";

			if (err != null) {
				alert(err);
				form.elements[i].focus();
				return false;
			}
		}
	}
	return true;
}

// Quote existing post (flatview forums)
function bbs_quote_post(id) {
	// Find the text-body div (different childNodes[] index in IE & ffx)
	var postdiv = document.getElementById('bbs_post_' + id);
	var bodydiv = null;
	for (var i=0; i<postdiv.childNodes.length; i++)
		if (postdiv.childNodes[i].nodeName == "DIV")
			bodydiv = postdiv.childNodes[i];

	// Fetch post content (also strips html)
	var postbody = "";
	for (var i=0; i<bodydiv.childNodes.length; i++) {
		if (bodydiv.childNodes[i].nodeName == "#text")
			postbody = postbody + bodydiv.childNodes[i].nodeValue;
		if (bodydiv.childNodes[i].nodeName == "BR")
			postbody = postbody + "\n";
		if (bodydiv.childNodes[i].nodeName == "A")
			postbody = postbody + bodydiv.childNodes[i].childNodes[0].nodeValue;
	}


	// Insert text to textarea
	var tarea = document.getElementById('bbsquote');
	tarea.value = tarea.value + postbody;

	// Scroll to form
	location.hash = "bbs_compose_form";

	// Make quote field visible. IE hack..
	/*@cc_on
	document.getElementById('bbs_compose_quote').style.display = "block";
	if (0)
	@*/
	document.getElementById('bbs_compose_quote').style.display = "table-row";
}



// Email obfuscator. Weird order of params is intentional.
function sposti(dmain, aelem, nimiR13) {
	nimiR13 = nimiR13.replace(/A/g, '.');
	dmain = dmain.replace(/B/g, '.');
	aelem.href = "mail" + 'to:' + rot13(nimiR13) + "@" + dmain;
}
function rot13 (string) {
	var aCode = 'a'.charCodeAt();
	var zCode = 'z'.charCodeAt();
	var ACode = 'A'.charCodeAt();
	var ZCode = 'Z'.charCodeAt();
	var result = '';
	for (var c = 0; c < string.length; c++) {
		var charCode = string.charCodeAt(c);
		if (charCode >= aCode && charCode <= zCode)
			charCode = aCode + (charCode - aCode + 13) % 26;
		else if (charCode >= ACode && charCode <= ZCode)
			charCode = ACode + (charCode - ACode + 13) % 26;
		result += String.fromCharCode(charCode);
	}
	return result;
}





/*********************************************
* Statsview table row expander (uses jquery) *
*********************************************/
function ExpandTable(table_id) {
	$("tr", document.getElementById(table_id) ).css("display", "table-row");
}

