
var target = null;

function putTag(type, text, id)
{
 	target = document.getElementById(id);
	
	if (target !== null)
	{
		if (typeof target.cursorPos != 'undefined')
		{
			var cursorPos = target.cursorPos;
			if (type != 'plain') {text = cursorPos.text;}
			cursorPos.text = det_replace(type, text);
		}
		else if (typeof target.selectionStart != 'undefined')
		{
			// remember scrollposition
			var scrollTop = target.scrollTop;

			var sStart = target.selectionStart;
			var sEnd = target.selectionEnd;
			if (type != 'plain') {text = target.value.substring(sStart, sEnd);}
			text = det_replace(type, text);
			target.value = target.value.substr(0, sStart) + text + target.value.substr(sEnd);
			var nStart = sStart == sEnd ? sStart + text.length : sStart;
			var nEnd = sStart + text.length;
			target.setSelectionRange(nStart, nEnd);

			// reset scrollposition
			target.scrollTop = scrollTop;
		}
		else
		{
			if (type != 'plain') {
				text = '';
			}
			
			target.value += det_replace(type, text);
		}

		target.focus();
		if (typeof target.cursorPos != 'undefined') {target.onselect();}
	}
}

function det_replace(type, text)
{
	var val = '';
	switch (type)
	{
		case 'plain':
			break;
		case 'bold':
			text = '<b>'+text+'</b>';
			break;
		case 'italic':
			text = '<i>'+text+'</i>';
			break;
		case 'underline':
			text = '<u>'+text+'</u>';
			break;
		case 'strike':
			text = '<s>'+text+'</s>';
			break;
		case 'sub':
			text = '[sub]'+text+'[/sub]';
			break;
		case 'sup':
			text = '[sup]'+text+'[/sup]';
			break;
		case 'spoiler':
			text = '[spoiler]'+text+'[/spoiler]';
			break;
		case 'code':
			text = '[code]'+text+'[/code]';
			break;
		case 'php':
			text = '[php]'+text+'[/php]';
			break;
		case 'spoiler':
			text = '[spoiler]'+text+'[/spoiler]';
			break;
		case 'quote':
			text = '[quote]'+text+'[/quote]';
			break;
		case 'listbullet':
			text = '\r\n[*]'+(text.split(/\r?\n/).join('\r\n[*]'))+'\r\n';
			break;
		case 'url':
			if (/^(http:\/\/|www\.)/i.test(text))
			{
				val = prompt('Voer omschrijving in:', text);
				if (val !== null && val !== '') {text = '[url name="'+val+'"]'+text+'[/url]';}
			}
			else
			{
				val = prompt('Voer de URL in:','http:\/\/');
				if (val !== null && val != 'http:\/\/')
				{
					if (text === '') {text = '[url]'+val+'[/url]';}
					else {text = '[url name="'+text+'"]'+val+'[/url]';}
				}
			}
			break;
		case 'img':
			if (text === '')
			{
				val = prompt('Voer de URL in:','http:\/\/');
				if (val !== null && val	 != 'http:\/\/') {text = '[img]'+val+'[/img]';}
			}
			else
			{
				text = '[img]'+text+'[/img]';
			}
			break;
		case 'imgnolink':
			if (text === '')
			{
				val = prompt('Voer de URL in:','http:\/\/');
				if (val !== null && val	 != 'http:\/\/') {text = '[img nolink]'+val+'[/img]';}
			}
			else
			{
				text = '[img nolink]'+text+'[/img]';
			}
			break;
	}
	return text;
}