var maxTextAreaLength = 50;
var maxLogSize = 40;

function httpRequest(url, postData, callback) {
	this.url = url;
	this.callback = callback;
	if (window.XMLHttpRequest)     // Object of the current windows
	{
		this.xhr = new XMLHttpRequest();     // Firefox, Safari, ...
	} else if (window.ActiveXObject)   // ActiveX version
	{
		this.xhr = new ActiveXObject("Microsoft.XMLHTTP");  // Internet Explorer
	}
	var xhr = this.xhr;
	this.xhr.onreadystatechange = function()
		{
			if(xhr.readyState == 4) {
				callback(xhr.responseText);
			}
		};
	this.xhr.open("POST", url, true);
	this.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	this.xhr.send(postData);
}

function getChildElementsByClass(object, className)
{
	var found = new Array();
	for(i in object.childNodes)
	{
		if(object.childNodes[i].className == className) {
			found.push(object.childNodes[i]);
		}
	}
	if(found.length == 0) {
		return false;
	}
	return found;
}

function logger(text)
{
	var lg = document.getElementById("logger");
	if(!lg) {
		return;
	}
	if(lg.childNodes.length > maxLogSize) {
		lg.removeChild(lg.firstChild);
	}
	lg.appendChild(document.createTextNode(text + "\r\n"));
}

function TextArea(taName, maxLength, previewUrl, bbCodes) {
	this.maxLength = maxLength;
	this.previewUrl = previewUrl;
	this.ta = document.getElementsByName(taName)[0];
	this.container = document.getElementById(taName + "_container");
	this.bbCodes = bbCodes;
	this.ta.object = this;
	this.ta.parentNode.object = this;
	// detect selection capabilities
	if(typeof document.selection != 'undefined') {
		this.selectionMode = 'msie';
	} else if (typeof this.ta.selectionStart != 'undefined') {
		this.selectionMode = 'gecko';
	} else {
		this.selectionMode = 'none';
	}
	logger(this.selectionMode);
	this.addButtons();
	this.update();
};
TextArea.prototype.addButtons = function()
{
	var code = '';
	for(tag in this.bbCodes)
	{
		code += '<button onclick="this.parentNode.parentNode.object.insertBBCode(this.innerHTML)" type="button"';
		code += ' title="' + (this.bbCodes[tag]['help'] ? this.bbCodes[tag]['help'] : this.bbCodes[tag]['name']) + '">'
		code += this.bbCodes[tag]['name'] + "</button> ";
	}
	getChildElementsByClass(this.container, "textareabuttons")[0].innerHTML = code;
}
TextArea.prototype.attributeId = function(tagName, attributeName)
{
	return this.ta.name + '_bb_' + tagName + '_' + attributeName;
}
TextArea.prototype.doBBCodeInsert = function()
{
	var tag = this.tagToBeInserted;
	if(!tag) {
		return;
	}
	tagInfos = this.bbCodes[tag];
	var bTag = '[' + tag;
	for (a in tagInfos['attributes'])
	{
		var aID = this.attributeId(tag, a);
		var aInput = document.getElementById(aID);
		if(aInput && aInput.value != '') {
			bTag += ' ' + a + '=' + aInput.value;
		}
	}
	bTag += ']';
	if(this.bbCodes[tag]['text'] != '') {
		bTag += document.getElementById(this.attributeId(tag, 'text')).value;
	}
	eTag = '[/' + tag + ']';
	this.selectionInsertBBCode(bTag, eTag);
	this.removePopup();
};
TextArea.prototype.insertBBCode = function(name)
{
	// Find BBCode tag
	var tag = '';
	for(tagName in this.bbCodes)
	{
		if(this.bbCodes[tagName]['name'] == name) {
			tag = tagName;
		}
	}
	if(tag == '') {
		return;
	}

	logger(tag);
	attributes = this.bbCodes[tag]['attributes']

	var showPopup = false;
	var count = 0;
	for(a in attributes)
	{
		if(attributes[a]['name'] != '') {
			showPopup = true;
			++count;
			logger("showPopup: "  + attributes[a]['name']);
		}
	}
// 	if(count == 0 && this.bbCodes[tag]['text'] != '' && this.selectionText() == '') {
// 		showPopup = true;
// 	}

	if(showPopup && !this.popup)
	{
		this.popup = new Popup(this.container);
		this.setButtonsEnabled(false);
		var code = '<div>';
		code += '<h1>Formatierung einf&uuml;gen</h1>';
		code += (this.bbCodes[tag]['help'] ? this.bbCodes[tag]['help'] : this.bbCodes[tag]['name']) + '<br /><br />';

		this.tagToBeInserted = tag;

		var focusField = false;
		if(this.bbCodes[tag]['text'] != '') {
			a = 'text';
			fieldId = this.ta.name + '_bb_' + tag + '_' + a;
			code += '<label for="' + fieldId + '" />' + this.bbCodes[tag]['text'] + '</label>';
			code += '<input type="text" id="' + fieldId + '" /><br />';
			focusField = fieldId;
		}

		for(a in attributes)
		{
			logger("log: " + a);
			fieldId = this.attributeId(tag, a);
			code += '<label for="' + fieldId + '" />' + attributes[a]['name'] + '</label>';
			code += '<input type="text" id="' + fieldId + '" /><br />';
			if(!focusField) {
				focusField = fieldId;
			}
		}

		code += '<button type="button" value="Abbrechen" onclick="var ta = document.getElementsByName(\''+ this.ta.name + '\')[0].object;ta.setButtonsEnabled(true);ta.removePopup()">Abbrechen</button>';
		code += '<button type="button" onclick="var ta = document.getElementsByName(\''+ this.ta.name + '\')[0].object; ta.setButtonsEnabled(true);ta.doBBCodeInsert();" >OK</button>';
		code += '<br style="clear:both;" />';
		code += "</div>";
		this.popup.setHTML(code);
		if(focusField) {
			document.getElementById(focusField).focus();
		}
	} else {
		this.selectionInsertBBCode('[' + tag + ']', '[/' + tag + ']');
	}
}

TextArea.prototype.preview = function ()
{
	ta = this.ta;
	try {
		document.getElementById(this.taName + '_preview');
	} catch(e) {
		return;
	}
	var url = this.previewUrl;
// 	var postData = this.ta.name + '=' + encodeURIComponent(ta.value);
	var postData = 'bbcode=' + encodeURIComponent(ta.value);
	var callback = function(response) { document.getElementById(ta.name + '_preview').innerHTML = response; document.getElementById(ta.name + '_preview').style.display = 'block'; };
	request = new httpRequest(url, postData, callback)
};

TextArea.prototype.removePopup = function()
{
	if(this.popup) {
		this.popup.remove();
		this.popup = false;
	}
}
TextArea.prototype.selectionInsertBBCode = function(bTag, eTag)
{
// 	bTag = '[' + tag + ']';
// 	eTag = '[/' + tag + ']';
	this.ta.focus();
	if(this.selectionMode == 'msie') {
		var range = document.selection.createRange();
		var selectionText = range.text;
		range.text = bTag + selectionText + eTag;
		range = document.selection.createRange();
		if (selectionText.length == 0) {
			range.move('character', (-eTag.length));
		} else {
			range.moveStart('character', bTag.length + selectionText.length + eTag.length);
		}
//     	return ;
	} else if(this.selectionMode == 'gecko') {
		var start = this.ta.selectionStart;
		var end = this.ta.selectionEnd;
		var selectionText = this.ta.value.substring(start, end);
		this.ta.value = this.ta.value.substr(0, start) + bTag + selectionText + eTag + this.ta.value.substr(end);
		var cursorPos;
		if (selectionText.length == 0) {
			pos = start + bTag.length;
		} else {
			pos = start + bTag.length + selectionText.length + eTag.length;
		}
		this.ta.selectionStart = pos;
		this.ta.selectionEnd = pos;
// 		return this.ta.value.substring(start, end);
	} else {
		this.ta.value += bTag + eTag;
	}
// 	return '';
}
TextArea.prototype.selectionText = function()
{
	this.ta.focus();
	if(this.selectionMode == 'msie') {
		var range = document.selection.createRange();
		logger('iee' + range.text);
    	return range.text;
	} else if(this.selectionMode == 'gecko') {
		var start = this.ta.selectionStart;
		var end = this.ta.selectionEnd;
		logger('geeecko' + this.ta.value.substring(start, end));
		return this.ta.value.substring(start, end);
	}
	return '';
}
TextArea.prototype.setButtonsEnabled = function(enabled)
{
	var buttonDiv = getChildElementsByClass(this.container, "textareabuttons")[0];
	var button;
	logger("setButtonsEnabled: " + enabled + buttonDiv.childNodes);
	for(i in buttonDiv.childNodes)
	{
		button = buttonDiv.childNodes[i];
		logger("Button: " + button.nodeName);
		if(button.nodeName && button.nodeName.toLowerCase() == "button")
		{
			if(enabled) {
				if(button.getAttribute("disabled")) {
					button.removeAttribute("disabled");
				}
			} else {
				if(!button.getAttribute("disabled")) {
					button.setAttribute("disabled", true);
				}
			}
		}
	}
}
TextArea.prototype.update = function ()
{
	if(this.ta.value.length > this.maxLength) {
		this.ta.value = this.ta.value.substr(0, this.maxLength);
	}
	document.getElementById(this.ta.name + '_chars').firstChild.nodeValue = this.ta.value.length;
};
function Popup (parentElement)
{
	this.div=getChildElementsByClass(parentElement, "popup")[0];
	logger(this.div.style);
	this.div.style.display="block";
}
Popup.prototype.setHTML = function(html)
{
	this.div.innerHTML = html;
}
Popup.prototype.remove = function(html)
{
	this.div.style.display="none";
}
