/************************************************************************
  			BBCodes.js - Copyright Jonathan Adami
**************************************************************************/

/**
 * This class is able to manage BBCodes
 */
TextArea = function (name) {
    this._init(name);
}

/**
 * TextArea's constructor
 */
TextArea.prototype._init = function (name) {
	this.name = name;
	this.textarea = document.getElementById(this.name);
}

/**
 * The effective tag operation
 */
TextArea.prototype.tag = function (bStart,bEnd) {
	this.textarea.focus();
	if (typeof(document.selection) != 'undefined') {
		return this.tagIE(bStart,bEnd);
	} else {
		return this.tagGecko(bStart,bEnd);
	}
}

TextArea.prototype.tagIE = function (bStart,bEnd) {
	var range = document.selection.createRange();
	var insText = range.text;
	range.text = bStart + insText + bEnd;
	range = document.selection.createRange();
	if (insText.length == 0) {
		range.move('character', -(bEnd.length));
	} else {
		range.moveStart('character', bStart.length + insText.length + bEnd.length);
	}
	range.select();
}

TextArea.prototype.tagGecko = function (bStart,bEnd) {
	var start = this.textarea.selectionStart;
	var end = this.textarea.selectionEnd;
	var insText = this.textarea.value.substring(start, end);
	this.textarea.value = this.textarea.value.substr(0, start) + bStart + insText + bEnd + this.textarea.value.substr(end);
	var pos = insText.length ? start + bStart.length + insText.length + bEnd.length : start + bStart.length;
	this.textarea.selectionStart = pos;
	this.textarea.selectionEnd = pos;
}

/**
 * Automatically tag start and end by using a simple open/close tag
 */
TextArea.prototype.simpleTag = function (tag) {
	this.tag('['+tag+']','[/'+tag+']');
}

/**
 * Automatically tag start and end by using an open/close tag with a param asked to user
 * by a prompt
 */
TextArea.prototype.promptTag = function (tag,message) {
	rep = prompt(message);
	if (rep && rep.length)	this.tag('['+tag+'='+rep+']','[/'+tag+']');
}