/*
**** LICENCE AGREEMENT **** 
This code is the property of www.pcinfo-web.com, and under Creative Common (Non Commercial, Paternity, Share Alike) Licence.
You can free distribte and modify this code but you can't :
* Use it for commercial purpose without the express permission of the author ( http://www.pcinfo-web.com/contact.php )

You also must : 
* Quote the author and the origin of the code, by keeping this licence at the top of the code
* Distribute the code and you modifications under the same licence

If you don't respect these conditions, you also make an illegal utilisationn of this work and you expose yourself to law-suit.

You can view a copy of this licence at this page : http://creativecommons.org/licenses/by-nc-sa/2.0/fr/deed.en_GB
****************************

function badtags()
This function checks if the BBcode tags of a string are correctly opened and closed.
If not, the function rectifies.

@param str : form element (if @param replace on true) or string to check
@param disp : write the result of the function
@param verbose : debug option : write the path of the script and the result

Warning : if @param replace on true be careful that str be a form element and not a string.

*/

// start of to copy : 

if(typeof(replacez) != "function") {
	function replacez(str1,str2,strz)
	{
		var i=0
				while (i!=-1)
		{
			i=strz.indexOf(String(str1),i);
			if (i>=0)
			{
				strz=strz.substring(0,i)+str2+strz.substring(i+str1.length);
				i+=str2.length;
			}
		}
		return strz;
	}
}

	var ptag = String.fromCharCode(5,6,7);

if(typeof(nl2khol) != "function") {

	function nl2khol(t) {
	textarea= new String(t);
	textarea = textarea.replace(/\r\n/g,ptag);
	textarea = textarea.replace(/\n/g,ptag);
	return textarea;
	}
}

if(typeof(unkhol) != "function") {
	function unkhol(t) {
		textarea=new String(t);
		return textarea.replace(new RegExp(ptag,'g'),'\n');
	}
}
	function noCode_badtags(string) {
		var arr = string.match(/\[nocode\](.*?)\[\/nocode\]/gi);
		var arr_ = new Array();
		if(typeof(arr) != 'undefined' && arr != null && arr.length >= 1) {
			if(typeof(arr[1]) != 'undefined') {
				for(var i=0;i<arr.length;i++) {
					//window.alert(arr[i]);
					arr_[i] = remplace_tag(/\[nocode\](.*?)\[\/nocode\]/gi,'$1', arr[i]);
					arr_[i] = remplace_tag(/\[/g,'&#91;', arr_[i]);
					arr_[i] = remplace_tag(/\]/g,'&#93;', arr_[i]);
					arr_[i] = "[nocode]"+arr_[i]+"[/nocode]";
					//window.alert(arr_[i]);
					string = replacez(arr[i],arr_[i],string);
				}
			}
			else {
				arr_[0] = remplace_tag(/\[nocode\](.*?)\[\/nocode\]/gi,'$1', arr[0]);
				arr_[0] = remplace_tag(/\[/g,'&#91;', arr_[0]);
				arr_[0] = remplace_tag(/\]/g,'&#93;', arr_[0]);
				arr_[0] = "[nocode]"+arr_[0]+"[/nocode]";
				string = replacez(arr[0],arr_[0],string);
			}
		}
		return string;
	}

	function sCode_badtags(string) {
		//alert("Khol : "+string.match(ptag));
		var arr = string.match(/\[code\](.*?)\[\/code\]/gi);//alert("Arr :"+arr);
		var arr_ = new Array();
		if(typeof(arr) != 'undefined' && arr != null && arr.length >= 1) {
			if(typeof(arr[1]) != 'undefined') {
				for(var i=0;i<arr.length;i++) {
					//window.alert(arr[i]);
					arr_[i] = remplace_tag(/\[code\](.*?)\[\/code\]/gi,'$1', arr[i]);
					arr_[i] = remplace_tag(/\[/g,'&#91;', arr_[i]);
					arr_[i] = remplace_tag(/\]/g,'&#93;', arr_[i]);
					arr_[i] = '[code]'+arr_[i]+'[/code]';
					//window.alert(arr_[i]);
					string = replacez(arr[i],arr_[i],string);
				}
				
			}
			else {
				//alert(string.match(/\n/ig));
				arr_[0] = remplace_tag(/\[code\](.*?)\[\/code\]/gi,'$1', arr[0]);
				arr_[0] = remplace_tag(/\[/g,'&#91;', arr_[0]);
				arr_[0] = remplace_tag(/\]/g,'&#93;', arr_[0]);
				arr_[0] = '[code]'+arr_[0]+'[/code]';
				string = replacez(arr[0],arr_[0],string);
			}
		}
		return string;
	}

if(typeof(remplace_tag) != "function") {
	function remplace_tag(reg,rep,t) {
		textarea=new String(t);
		return textarea.replace(reg,rep);
	}
}

function Wiki_Paf(string) {
	return string.replace(/\[\[(.*?)\]\]/ig, "&#91;&#91;$1&#93;&#93;");
}

function badtags(str, replace, disp, verbose) {
	//alert("Reconnaissance ptag : "+ptag.match(/./ig));
	//var varr = ("[code][i]"+ptag+"[/code]").match(/\[code\](.*?)\[\/code\]/gi); alert(varr);
	var pile = [];
	var out = "";
	// Si "replace" vaut true alors on doit aller chercher la valeur dans l'élément :
	if(replace) { 
		var string = str.value;
	}
	else {
		var string = str;
	}
	
	// Traîtement de la string pour ne pas intépréter les balises contenue dans [nocode] et [code] :
	//alert(string);
	//alert(string.match(/\r\n/ig));
	string=nl2khol(string);//alert(string.match(/\n/ig));
	//alert(string);
	string = noCode_badtags(string);
	string = sCode_badtags(string);
	string = Wiki_Paf(string);//alert(string.match(/\n/ig));
	string=unkhol(string);

	var tableau = string.split(/(\[\/?[^\]\[]+\])/i);

	for(var i=0;i<tableau.length;i++) {
		out += "<br />Itération n°"+i+" :<br />"+tableau[i]+"<br />";
		var m = tableau[i].match(/(\[\/?(img|nocode|list|url|color|quote|code|flash|center|size|float|justify|right|left|poll|strike|titre|stitre|style|anchor|b|u|i)(( |=)[^\]]+)?\])+/i);
		// Note : les balises u i b sont à la fin car img = balise i + "mg" plus loin => détecté en balise i
		if(typeof(m) != "undefined" && m != null) { // Si on a bien à faire à une balise
			out += "Balise détectée<br />";			
			var n = m[0].match(/\[\/(img|nocode|list|url|color|quote|code|flash|center|size|float|justify|right|left|poll|strike|titre|stitre|style|anchor|b|u|i)\]/i);
			if(n != null) { // Si c'est bien une balise fermante
				out += "Balise fermante détectée<br />";
				if(pile.length >= 1) { // A condition qu'on ait déjà qqchose dans la pile
					out += "<br />Longueur de la pile : "+pile.length+"<br />";
					var num = Math.abs(pile.length - 1); // Utilisation de l'objet Math pour obtenir int
//					var previous_tag = pile[num].match(/[(b|u|i|img|nocode|list|url|color|quote|code|flash|center|size|float|justify|right|left|poll|strike|titre|stitre|style|anchor)([^\]])*\]/i);
					var previous_tag = pile[num].replace(/\[(img|nocode|list|url|color|quote|code|flash|center|size|float|justify|right|left|poll|strike|titre|stitre|style|anchor|b|u|i)(( |=)[^\]]+)?\]/i, "[$1]")
					if(previous_tag != null && previous_tag == n[0].replace(/\[\//, "[")) { // Si le tag précédent est le même que celui qu'on ferme actuellement
						out += "Balise fermante correspondante : dépilage <br />";
						// Alors on dépile :
						pile.length = num;
					}
					else { // Si les tags sont différents, il y a une erreur, donc on la corrige :
						out += "Balise fermante non correspondante : <br />Tag ouvrant : "+previous_tag+"<br />Tag fermant : "+n[0].replace(/\[\//, "[")+" <br />correction puis dépilage<br />";
						tableau[i] = tableau[i].replace(m[0], previous_tag.replace(/\[/, "[/"));
						pile.length = num; //num vaut pile.length-1, donc suppression du dernier array
					}
				 }
				else { // Sinon si la pile est vide, c'est que la première balise trouvée est fermante, impossibe, on supprime :
					out += "Erreur ! String commençant par une balise fermante, suppression de la balise.<br />";
					tableau[i] = "";
				}
			}
			else { // Sinon, si n est null, alors on a pas à faire à une balise fermante, on empile :
				out += "La balise est une balise ouvrante, empilage.<br />";
				pile[pile.length] = tableau[i];
			}
		}
	}
	// A la fin du tableau, le dépilage doit être complet, la pile doit donc être vide, sinon on ferme les balises restées [ouvertes] dans la pile :
	if(pile.length > 0) {
		for(var i=0; i<pile.length; i++) {
			out += "<br />Balise restée ouverte : "+pile[i]+"<br />Fermeture de la balise";
			var close_tag = pile[i].replace(/\[(img|nocode|list|url|color|quote|code|flash|center|size|float|justify|right|left|poll|strike|titre|stitre|style|anchor|b|u|i)(( |=)[^\]]+)?\]/i, "[/$1]")
			//On rajoute la balise :
			tableau[tableau.length] = close_tag;
		}
	}
		// Note :  les deux .replace() remettent les crochets transformés en entités pour ne pas être interprétés à l'état de crochets.
	var finale = tableau.join("").replace(/&#91;/gi, "[").replace(/&#93;/gi, "]");
	if(verbose) document.write(out+"<br /><br />"+finale);
	else if(disp) document.write(finale);
	
	if(replace) {
		str.value = finale;
	}
}

function badtags_form(f, elems, replace, disp, verbose) {
	if(typeof(f) ==  "undefined" || !f) alert("Erreur, f est vide");
	//alert("Execution started");
	for(var i = 0;i<f.elements.length;i++) {
		var e = f.elements[i];
		for(var j = 0;j<elems.length;j++) {
			if(e.name == elems[j]) {
				badtags(e, replace, disp, verbose);
				break;
			}
		}
	}
	//alert("Execution finished");
}