var is_gecko = /gecko/i.test(navigator.userAgent);
var is_ie    = /MSIE/.test(navigator.userAgent);

function addBBCode(code_pre, code_post, elementId)
{
	editor = document.getElementById(elementId);
	theSelection = false;
	if (document.selection && editor.storedRange)
		theSelection = editor.storedRange.text;
		//theSelection = document.selection.createRange().text;

	if (!theSelection)
	{
		if (editor.selectionStart >= 0)
		{
			editor.value = editor.value.substring(0, editor.selectionStart) + code_pre + editor.value.substring(editor.selectionStart, editor.selectionEnd) + code_post + editor.value.substring(editor.selectionEnd);
			
			if (!editor.newlines)
				removeNewlines(elementId);
				
			if (editor.validchars != false)
				removeInvalidChars(elementId);
		
			if (editor.maxchars > 0)
				charsLeft(elementId, editor.maxchars);
			
			return;
		}
			
		if (document.selection && editor.storedRange)
		{			    
	    caretPos = getCaretPos(elementId);
			editor.value = editor.value.substring(0, caretPos) + code_pre + code_post + editor.value.substring(caretPos);
		}
		else
		{
			editor.value = editor.value + code_pre + code_post;
		}
	}
	else
	{
		if (editor.storedRange == null)
		{
			editor.value = editor.value + code_pre + code_post;
		}
		else
		{
			if (editor.storedRange.parentElement().id != elementId)
			//if (document.selection.createRange().parentElement().id != elementId)
				return;
	
			editor.storedRange.text = code_pre + theSelection + code_post;
			//document.selection.createRange().text = code_pre + theSelection + code_post;
		}
	}
	
	if (!editor.newlines)
		removeNewlines(elementId);
		
	if (editor.validchars != false)
		removeInvalidChars(elementId);
				
	if (editor.maxchars > 0)
		charsLeft(elementId, editor.maxchars);
	
} // addBBCode

function getCaretPos(elementId)
{
	var caretPos = -1;
	editor = document.getElementById(elementId);
	if (editor.selectionStart >= 0)
	{
		caretPos = editor.selectionStart;
	}
	else
	{
		if (document.selection && editor.storedRange)
		{			    
	    var bookmark = "~#";
	    var orig = editor.value;
	    var range = editor.storedRange;
	    range.text = bookmark;
	    caretPos = editor.value.search(bookmark);
	    editor.value = orig;
	  }
	}
	
	return caretPos;
} // getCaretPos

function setCaretPos(caretPos, elementId)
{
	editor = document.getElementById(elementId);
	editor.focus();
	
	if (is_gecko) {
		editor.setSelectionRange(caretPos, caretPos);
	} else {
		// assumed IE
		var range = editor.createTextRange();
		range.collapse(true);
		range.moveStart("character", caretPos);
		range.moveEnd("character", 0);
		range.select();
		editor.storedRange = document.selection.createRange();
	}
} // setCaretPos

function containsSelection(elementId)
{
	editor = document.getElementById(elementId);
	theSelection = false;
	if (document.selection)
		theSelection = document.selection.createRange().text;
		
	if (!theSelection)
	{
		return (editor.selectionStart < editor.selectionEnd);
	}
	else
	{
		return (document.selection.createRange().parentElement().id == elementId);
	}
} // containsSelection

function addBBSmileyCode(code, elementId)
{
	if (code == null || code == '')
		return;
		
	addBBCode('', code, elementId);
	closePopWindows(elementId);
} // addBBSmileyCode

function addBBColor(color, elementId)
{
	addBBCode('[color='+color+']', '[/color]', elementId);
	document.getElementById(elementId+'ColorWin').style.display = "none";
} // addBBColor


function showPreview(elementId, color)
{
	editor = document.getElementById(elementId);
	//previewForm = document.getElementById(elementId+'PreviewForm');
	previewFormObject = document.getElementById('previewForm');
	previewFormObject.bbcode.value = editor.value;
	previewFormObject.color.value = color;
	
	var dialogheight = 600;
	var dialogwidth = 680;
	dialog = window.open('', "previewWindow", "scrollbars=yes,height="+ dialogheight +",width="+ dialogwidth+",resize=0,left="+ (screen.width-dialogwidth)/2 +",top="+ (screen.height-dialogheight)/2);
	
	previewFormObject.submit();
} // showPreview

function showPopWindow(e, winType, elementId)
{
	var smileyWin1 = document.getElementById(elementId + 'SmileyWin1');
	smileyWin1.style.display = "none";
	var smileyWin2 = document.getElementById(elementId + 'SmileyWin2');
	smileyWin2.style.display = "none";
	var colorWin = document.getElementById(elementId + 'ColorWin');
	colorWin.style.display = "none";
		
	var editorBtn = e.target || e.srcElement;
	
	if (winType == 'color')
	{
	  colorWin.style.left = 0;
	  colorWin.style.top = 0;
	  colorWin.style.display = (colorWin.style.display=="block")?"none":"block";
	}
	else if (winType == 'smiley1')
	{
	  smileyWin1.style.left = 0;
	  smileyWin1.style.top = 0;
	  smileyWin1.style.display = (smileyWin1.style.display=="block")?"none":"block";
	}
	else if (winType == 'smiley2')
	{
	  smileyWin2.style.left = 0;
	  smileyWin2.style.top = 0;
	  smileyWin2.style.display = (smileyWin2.style.display=="block")?"none":"block";
	}
} // showPopWindow

function closePopWindows(elementId)
{
	var colorWin = document.getElementById(elementId + 'ColorWin');
	colorWin.style.display = "none";
	var smileyWin1 = document.getElementById(elementId + 'SmileyWin1');
	smileyWin1.style.display = "none";
	var smileyWin2 = document.getElementById(elementId + 'SmileyWin2');
	smileyWin2.style.display = "none";
} // closePopWindows

function getPosX(obj) 
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
} // getPosX

function getPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
} // getPosY

function charsLeft(elementId, maxchars)
{
	editor = document.getElementById(elementId);
	charsleft = maxchars - editor.value.length;
	
	if (editor.value.indexOf("\r") == -1)
	{
		// FireFox counts 1 newline as 1 char, it should be 2
		// IE newlines are /r/n, FireFox uses /n, but after submit
		// there /n become /r/n as well.
		// subtract 1 from charsleft for each newline
		newLinePos = 0;
		newLines = 0;
		while (newLinePos > -1)
		{
			newLinePos = editor.value.indexOf("\n", newLinePos);
			if (newLinePos > -1)
			{
				newLinePos++;
				newLines++;
			}
				
		}
		charsleft -= newLines;
	}
	
	if (charsleft < 0)
	{
		charsleft = 0;
		if (editor.value.indexOf("\r") == -1)
		{
			// FireFox count 1 newline as 1 char. So substring does not
			// work as wanted.
			// fetch first maxchars characters from the editor, while counting
			// newlines double
			i=0;
			newValue = "";
			fetchedChars = 0;
			while(fetchedChars < maxchars)
			{
				c = editor.value.charAt(i);
				i++;
				if (c == "\n")
				{
					fetchedChars += 2;
					if (fetchedChars > maxchars)
						break;
				}
				else
					fetchedChars += 1;
					
				newValue += c;
			}
			editor.value = newValue;
		}
		else
			editor.value = editor.value.substring(0, maxchars);
	}
	
	_setContent(elementId + 'CharsLeft', charsleft);
} // charsLeft

function removeNewlines(elementId)
{
	editor = document.getElementById(elementId);
	if (editor.value.indexOf('\n') != -1)
	{
		editor.value = editor.value.replace(/\n/g,"");
		editor.value = editor.value.replace(/\r\n/g,"");
	}
} // removeNewlines

function removeInvalidChars(elementId)
{
	editor = document.getElementById(elementId);
	newValue = editor.value.replace(editor.validchars, '');
	//newValue = editor.value.replace(/[^A-Za-z0-9@£$¥èéùìòÇØøÅå_Ææß!#¤%&\'()*+,-.\/ :;<=>?¡ÄÖÑÜ§¿äöñüà"]{1,1}/g, '');
	if (newValue != editor.value)
		editor.value = newValue;
} // removeInvalidChars

function _setContent(elementId, content)
{
	if (document.layers)
	{
		var lyr = document.layers[elementId].document;
		lyr.open();
		lyr.write(content);
		lyr.close();
	}
	else if (document.getElementById && document.getElementById(elementId))
		document.getElementById(elementId).innerHTML = content;
	else
		document.all[elementId].innerHTML = content;
} // _setContent

document.write(
	'<form method="post" name="previewForm" id="previewForm" action="editor/preview.php" target="previewWindow">'+
	'<input type="hidden" name="bbcode" value="" />'+
	'<input type="hidden" name="color" value="#ffffff" />'+
	'</form>'
	);