/* Insère les balises BBcode dans la zone de texte */
function insertTag(startTag, endTag, textareaId) {
    var field = document.getElementById(textareaId);
    field.focus();
    
    //Si IE
    if (window.ActiveXObject) {
        var textRange = document.selection.createRange();
        var currentSelection = textRange.text;
        
        textRange.text = startTag + currentSelection + endTag;
        textRange.moveStart("character", -endTag.length - currentSelection.length);
        textRange.moveEnd("character", -endTag.length);
        textRange.select();
    }
    //Si autre navigateur
    else {
        var startSelection   = field.value.substring(0, field.selectionStart);
        var currentSelection = field.value.substring(field.selectionStart, field.selectionEnd);
        var endSelection     = field.value.substring(field.selectionEnd);
        
        field.value = startSelection + startTag + currentSelection + endTag + endSelection;
        field.focus();
        field.setSelectionRange(startSelection.length + startTag.length, startSelection.length + startTag.length + currentSelection.length);
    }
}

/* Construit un objet XMLHttpRequest */
function getXMLHttpRequest() {
	var xhr = null;
	
	if (window.XMLHttpRequest || window.ActiveXObject) {
		if (window.ActiveXObject) {
			try {
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e){
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		else
			xhr = new XMLHttpRequest();
	}

	return xhr;
}

/* Génère l'apercu du texte avec BBcode */
function apercu(textareaId, viewDiv) {
	var content = encodeURIComponent(document.getElementById(textareaId).value);
	var xhr = getXMLHttpRequest();
	
	if (xhr && xhr.readyState != 0) {
		xhr.abort();
		delete xhr;
	}
	
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4 && xhr.status == 200)
			document.getElementById(viewDiv).innerHTML = xhr.responseText;
		else if (xhr.readyState == 3)
			document.getElementById(viewDiv).innerHTML = "<div style=\"text-align: center;\"><p><b>Aper&ccedil;u :</b></p><p>Chargement en cours...</p></div>";
	}
	
	xhr.open("POST", "scripts/bbcode.php", true);
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xhr.send("texte=" + content);
}
