<!--

function trim(string) 
{ 
	return string.replace(/(^\s*)|(\s*$)/g,''); 
} 

function disable (composant, racineimage)
{
	eval("document." + composant + "_palette").src = racineimage+'/themes/artic/images/boutons/palette0.gif';
	if (eval("document." + composant + "_glossaire"))
		eval("document." + composant + "_glossaire").src = racineimage+'/themes/artic/images/boutons/glossaire0.jpg';
	eval("document." + composant + "_gomme").src = racineimage+'/themes/artic/images/boutons/gomme0.gif';
	eval("document." + composant + "_gras").src = racineimage+'/themes/artic/images/boutons/gras0.gif';
	eval("document." + composant + "_italique").src = racineimage+'/themes/artic/images/boutons/italique0.gif';
	eval("document." + composant + "_souligne").src = racineimage+'/themes/artic/images/boutons/souligne0.gif';
	eval("document." + composant + "_gauche").src = racineimage+'/themes/artic/images/boutons/gauche0.gif';
	eval("document." + composant + "_centre").src = racineimage+'/themes/artic/images/boutons/centre0.gif';
	eval("document." + composant + "_droite").src = racineimage+'/themes/artic/images/boutons/droite0.gif';
	eval("document." + composant + "_justifie").src = racineimage+'/themes/artic/images/boutons/justifie0.gif';
	eval("document." + composant + "_tabplus").src = racineimage+'/themes/artic/images/boutons/tabplus0.gif';
	eval("document." + composant + "_tabmoins").src = racineimage+'/themes/artic/images/boutons/tabmoins0.gif';
	eval("document." + composant + "_liste").src = racineimage+'/themes/artic/images/boutons/liste0.gif';
	eval("document." + composant + "_listenum").src = racineimage+'/themes/artic/images/boutons/listenum0.gif';
	eval("document." + composant + "_polplus").src = racineimage+'/themes/artic/images/boutons/polplus0.gif';
	eval("document." + composant + "_polmoins").src = racineimage+'/themes/artic/images/boutons/polmoins0.gif';
	eval("document." + composant + "_polnormal").src = racineimage+'/themes/artic/images/boutons/polnormal0.gif';
	eval("document." + composant + "_lien").src = racineimage+'/themes/artic/images/boutons/lien0.gif';
	eval("document." + composant + "_image").src = racineimage+'/themes/artic/images/boutons/image0.gif';
	eval("document." + composant + "_lunette").src = racineimage+'/themes/artic/images/boutons/lunette0.gif';
	eval("document." + composant + "_tableau").src = racineimage+'/themes/artic/images/boutons/tableau0.gif';
	
	if (typeof (eval("document." + composant + "_document")) != "undefined")
		eval("document." + composant + "_document").src = racineimage+'/themes/artic/images/boutons/document0.gif';
	if (typeof (eval("document." + composant + "_document2")) != "undefined")
		eval("document." + composant + "_document2").src = racineimage+'/themes/artic/images/boutons/classement0.jpg';
		
	var MenuDeroulantStyle = eval("formulaire." + composant +"_slStyleWysiwyg");
	if (typeof (MenuDeroulantStyle) !="undefined"){
		MenuDeroulantStyle.disabled ="disabled";
	}
	
	var MenuDeroulantHn = eval("formulaire." + composant +"_slHn");
	if (typeof (MenuDeroulantHn) !="undefined"){
		MenuDeroulantHn.disabled ="disabled";
	}
}

function enable (composant, racineimage)
{
	eval("document." + composant + "_palette").src = racineimage+'/themes/artic/images/boutons/palette.gif';
	if (eval("document." + composant + "_glossaire"))
		eval("document." + composant + "_glossaire").src = racineimage+'/themes/artic/images/boutons/glossaire.jpg';
	eval("document." + composant + "_gomme").src = racineimage+'/themes/artic/images/boutons/gomme.gif';
	eval("document." + composant + "_gras").src = racineimage+'/themes/artic/images/boutons/gras.gif';
	eval("document." + composant + "_italique").src = racineimage+'/themes/artic/images/boutons/italique.gif';
	eval("document." + composant + "_souligne").src = racineimage+'/themes/artic/images/boutons/souligne.gif';
	eval("document." + composant + "_gauche").src = racineimage+'/themes/artic/images/boutons/gauche.gif';
	eval("document." + composant + "_centre").src = racineimage+'/themes/artic/images/boutons/centre.gif';
	eval("document." + composant + "_justifie").src = racineimage+'/themes/artic/images/boutons/justifie.gif';
	eval("document." + composant + "_droite").src = racineimage+'/themes/artic/images/boutons/droite.gif';
	eval("document." + composant + "_tabplus").src = racineimage+'/themes/artic/images/boutons/tabplus.gif';
	eval("document." + composant + "_tabmoins").src = racineimage+'/themes/artic/images/boutons/tabmoins.gif';
	eval("document." + composant + "_liste").src = racineimage+'/themes/artic/images/boutons/liste.gif';
	eval("document." + composant + "_listenum").src = racineimage+'/themes/artic/images/boutons/listenum.gif';
	eval("document." + composant + "_polplus").src = racineimage+'/themes/artic/images/boutons/polplus.gif';
	eval("document." + composant + "_polmoins").src = racineimage+'/themes/artic/images/boutons/polmoins.gif';
	eval("document." + composant + "_polnormal").src = racineimage+'/themes/artic/images/boutons/polnormal.gif';
	eval("document." + composant + "_lien").src = racineimage+'/themes/artic/images/boutons/lien.gif';
	eval("document." + composant + "_image").src = racineimage+'/themes/artic/images/boutons/image.gif';
	eval("document." + composant + "_tableau").src = racineimage+'/themes/artic/images/boutons/tableau.gif';
	if (typeof (eval("document." + composant + "_document")) != "undefined")
		eval("document." + composant + "_document").src = racineimage+'/themes/artic/images/boutons/document.gif';
	if (typeof (eval("document." + composant + "_document2")) != "undefined")
		eval("document." + composant + "_document2").src = racineimage+'/themes/artic/images/boutons/classement.jpg';
	eval("document." + composant + "_lunette").src = racineimage+'/themes/artic/images/boutons/lunette.gif';
	
	var MenuDeroulantStyle = eval("formulaire." + composant +"_slStyleWysiwyg");
	if (typeof (MenuDeroulantStyle) !="undefined"){
		MenuDeroulantStyle.disabled = false;
	}
	
	var MenuDeroulantHn = eval("formulaire." + composant +"_slHn");
	if (typeof (MenuDeroulantHn) !="undefined"){
		MenuDeroulantHn.disabled = false;
	}
}

function changeaffichage (composant, racineimage)
{
	if (eval(composant + "_mode"))
	{
		eval("document." + composant + "_code").src = racineimage+'/themes/artic/images/boutons/code_enf.gif';
		disable (composant, racineimage);
		// on rajoute des doubles quotes autour des valeurs attributs qui n'en n'ont pas
		// ! si une valeur contient un espace, cela ne marche pas correctement
		eval(composant + "_iframe").document.body.innerText = eval(composant + "_iframe").document.body.innerHTML;
		// ! alternative pour tester AjouteAttQuotes() (normalement pas de régression)
		//eval(composant + "_iframe").document.body.innerText = AjouteAttQuotes(eval(composant + "_iframe").document.body.innerHTML);
	}
	else
	{
		eval("document." + composant + "_code").src = racineimage+'/themes/artic/images/boutons/code2.gif';

		enable (composant, racineimage);

		eval(composant + "_iframe").document.body.innerHTML = eval(composant + "_iframe").document.body.innerText;
	}
}
function ConvertitEnAccessible(composant, texteOk){
	if (!window.NettoieHTML)
		return;
	eval(composant + "_iframe").document.body.innerHTML = NettoieHTML(eval(composant + "_iframe").document.body.innerHTML);
	alert(texteOk);
}

function colorPicker (thefield, texteaucunmot, urlwysiwygcss, modeEdition)
{
	var strErreurImbrication = "";
	if ( colorPicker.arguments[5] != undefined){
		strErreurImbrication = colorPicker.arguments[5]
	}
	
	// Champs wyiswyg n'est pas en mode edition
	if (!modeEdition) 
		return;
	var result = window.showModalDialog('colorpicker.php?act=display','palette','resizable:no;help:no;status:no;dialogHeight:400px;dialogWidth:400px;');
		
	if (result != null)
	{
		AddStyleComplet(thefield, result, modeEdition, strErreurImbrication, texteaucunmot);
	}
}

function sansword (texte)
{
	// Ces 2 lignes qui marchaient ne marche plus bizaremment
	texte = texte.replace (/\\n/ig, "");
	texte = texte.replace (/\\r/ig, "");

	texte = texte.replace (/\n/ig, "");
	texte = texte.replace (/\r/ig, "");
	texte = texte.replace (/<\/?div[^>]*>/gi, "");
	texte = texte.replace (/<\/?dir[^>]*>/gi, "");
	texte = texte.replace (/<\/?v[^>]*>/gi, "");
	texte = texte.replace (/<\/?o:[^>]*>/gi, "");
	texte = texte.replace (/ style=\"[^"]*\"/gi, "");
	texte = texte.replace (/<\?xml[^>]*>/gi, "");
	texte = texte.replace (/<\/?o:p>/gi, "");
	texte = texte.replace (/’/gi, "'");
	
	// Convertit en code accessible
	if(window.NettoieHTML){
		texte = NettoieHTML(texte);
	}
	
	// Supprime le dernier <p>&nbsp;</p>
	var ArrTextASupprimer = new Array("<p>&nbsp;</p>", "<p></p>");
	var StrTexteASupprimer = "";
	for (var i=0;i<ArrTextASupprimer.length;i++){
		StrTexteASupprimer = ArrTextASupprimer[i];
//	alert('StrTexteASupprimer : '+StrTexteASupprimer + '\n texte.length   : '+texte.length +'\nStrTexteASupprimer.length : '+StrTexteASupprimer.length+'\n texte : '+texte +'\n texte.toLowerCase().lastIndexOf(StrTexteASupprimer.toLowerCase()) : '+texte.toLowerCase().lastIndexOf(StrTexteASupprimer.toLowerCase()) )
		while (texte.toLowerCase().lastIndexOf(StrTexteASupprimer.toLowerCase()) == texte.length - StrTexteASupprimer.length){
			texte = texte.substring(0, texte.length - StrTexteASupprimer.length);
		}
	}
	return texte;
}

function sanslfcr (texte)
{
	// A utiliser pour champs wysiwyg3 (code source, one ne retire que les sauts pour éviter les erreurs javascript au moment du chargement de la textarea)
	// Ces 2 lignes qui marchaient ne marche plus bizaremment
	texte = texte.replace (/\\n/ig, "");
	texte = texte.replace (/\\r/ig, "");

	texte = texte.replace (/\n/ig, "");
	texte = texte.replace (/\r/ig, "");
	
	return texte;
}

function cleanAllTags (theselection, IFrameChoisie)
{	
	IFrameChoisie.document.execCommand('removeformat');
	IFrameChoisie.document.execCommand('unlink');
	
	// Selection du textArea qui va etre utilise si on seletionne un paragraphe.
	var textAreaRange    = IFrameChoisie.document.body.createTextRange();
	var rangeSelectionne = theselection.createRange();
	
	// Texte HTML avant la selection
	var arrResultatAvant = new Array();
	getAvantTexteRangeSelectionne(textAreaRange, rangeSelectionne, arrResultatAvant);
	var StrHtmlDebut     = arrResultatAvant["chaine"];
	//alert('StrHtmlDebut : '+StrHtmlDebut)
	var NbDebutSpan      = arrResultatAvant["nbDebutSpan"];
	var intNbDeplacement = arrResultatAvant["NbDeplacement"];
	
	var arrResultatApres = new Array();
	getApresTexteRangeSelectionne(textAreaRange, rangeSelectionne, arrResultatApres);
	var StrHtmlApres     = arrResultatApres["chaine"];
	var NbFinSpan        = arrResultatApres["nbFinSpan"];
	

	// Texte HTML Selectionne
	var StrHtmlSelectionne = getTexteRangeSelectionne(NettoieRange(textAreaRange.htmlText), StrHtmlDebut, StrHtmlApres)
	
	var ArrStyleOuvert = CreeTableauStyleOuvert(NettoieRange(textAreaRange.htmlText), StrHtmlSelectionne, StrHtmlDebut.length -1, "SPAN");
	
	//alert('__Selection__\n StrHtmlDebut : '+StrHtmlDebut +'\n StrHtmlApres : ' + StrHtmlApres + '\n StrHtmlSelectionne : '+StrHtmlSelectionne+'\n s \n Tout : '+NettoieRange(textAreaRange.htmlText)+ '\n NbFinSpan :' + NbFinSpan + '\n NbDebutSpan :' +NbDebutSpan + '\n ArrStyleOuvert.length : '+ArrStyleOuvert.length);
	
	
	//A ce moment du traitement, on a reconstitue la chaine du textarea
	if (StrHtmlSelectionne == ""){
		arrNouvellesChaines = new Array();
		SelectionneParagraphe(StrHtmlDebut, StrHtmlSelectionne, StrHtmlApres, arrNouvellesChaines);
		StrHtmlDebut        = arrNouvellesChaines["debut"];
		StrHtmlSelectionne  = arrNouvellesChaines["milieu"];
		StrHtmlApres        = arrNouvellesChaines["fin"];
	}
	
 	// Expression reguliere de nettoyage... 
 	nbFinSpanDansSelection = CompteNombreOccurence(StrHtmlSelectionne, "</SPAN>");
 	// On commence par supprimer tous les elements dont le nom de tag est 2 ou plus ex : <H1..., <SPAN...
 	StrHtmlSelectionne = StrHtmlSelectionne.replace (/<h[1-6]>/gi,"<p>");
 	
 	// On laisse certaines balises. Pour cela, on renomme les tags afin qu'elles soit exclues de l'expression régulière de nettoyage
 	StrHtmlSelectionne = StrHtmlSelectionne.replace (/<br>/gi,"<_br_>");
 	StrHtmlSelectionne = StrHtmlSelectionne.replace (/<img/gi,"<_img");
 	StrHtmlSelectionne = StrHtmlSelectionne.replace (/<br\/>/gi,"<_br_/>");
 	StrHtmlSelectionne = StrHtmlSelectionne.replace (/<\/?h[1-6]>/gi,"</p>");
 	
	StrHtmlSelectionne = StrHtmlSelectionne.replace (/(<\s*(\/)?[a-z1-9]{2,}(\s+[^>]*)?>)/ig,"");
	// Nous avons des elements de la forme <a href="" class="">. On supprime tous ceux dont le tag n'est pas P
	StrHtmlSelectionne = StrHtmlSelectionne.replace (/(<\s*(\/)?[^p](\s+[^>]*)?>)/ig,"");
	
	// On remet les bones expressions
	StrHtmlSelectionne = StrHtmlSelectionne.replace (/<_br_>/gi,"<br>");
 	StrHtmlSelectionne = StrHtmlSelectionne.replace (/<_br_\/>/gi,"<br/>");
 	StrHtmlSelectionne = StrHtmlSelectionne.replace (/<_img/gi,"<img");
	// Pour finir, nous avons : <P class="">. Nous supprimons tous les attributs des tags P
	StrHtmlSelectionne = StrHtmlSelectionne.replace (/(<\s*p(\s+[^>]*)?>)/ig, "<P>");
	
	// Perte des styles ouverts
	var ArrStyleOuvert = CreeTableauStyleOuvert(NettoieRange(textAreaRange.htmlText), StrHtmlSelectionne, StrHtmlDebut.length -1, "SPAN");
	boolSpanClassOuvert = false;
	
	if (ArrStyleOuvert.length>0 && StrHtmlDebut != ""){
		for(var i = 0 ; i<ArrStyleOuvert.length  ; i++){
			StrHtmlSelectionne = "</SPAN>"+ StrHtmlSelectionne;
			// Reouverture des span que si ils ne sont pas fermes dans la selection (cf i >=nbFinSpanDansSelection) ou en fin de selection (ou en debut de champs suivant i >= NbFinSpan)...
			if (i >= NbFinSpan && StrHtmlApres.length>0 && i >=nbFinSpanDansSelection)
				StrHtmlSelectionne = StrHtmlSelectionne + trim(ArrStyleOuvert[i]);
		}
	}
	
 	//alert('__final__\n StrHtmlDebut : |'+StrHtmlDebut +'|\n StrHtmlSelectionne : |'+StrHtmlSelectionne + '|\n StrHtmlApres :  |'+StrHtmlApres+'|');
	var StrFinal = StrHtmlDebut + StrHtmlSelectionne + StrHtmlApres;
		// Il est possible que l'on ait des <span class="quelquechose"></span>. On nettoie donc!
	StrFinal = RetireSpanVide(StrFinal);

	IFrameChoisie.document.execCommand("SelectAll");
	IFrameChoisie.document.execCommand("delete");
	IFrameChoisie.document.clear();
	textAreaRange.pasteHTML(StrFinal);

	textAreaRange = IFrameChoisie.document.body.createTextRange();
	workRange     = textAreaRange.duplicate();
 	workRange.setEndPoint("StartToStart", textAreaRange);
	workRange.setEndPoint("EndToStart", textAreaRange);
	var NbAvance = 0;	
	// Aggrandissement du workRange jusqu'a ce qu'il arrive a RangeSelectionne
	while(NbAvance < intNbDeplacement){
		workRange.moveEnd("character", 1);
		NbAvance++;
	}
	workRange.collapse(false);
	workRange.select();
}

function InsereImage (nomchamp, typechamp, racineabsolue, racineuploadimages) 
{
	var result = showModalDialog(racineabsolue+"/commun/dialoggenerique.php?page=4", "", "dialogWidth:800px;dialogHeight:590px;resizable:yes");
   // window.open(racineabsolue+"/commun/dialoggenerique.php?page=4");
	if (result != null)
	{
		if (typechamp == 'image1')
		{
			var correspondances = result.match (/src="([^'"]*)"/i);
			var src_image = correspondances[1];
			correspondances = result.match (/alt="([^"]*)"/i);
			var alt_image = correspondances[1];

			eval ("document.all." + nomchamp).value = "<IMG src=\"" + src_image + "\" border=\"0\" alt=\"" + alt_image + "\" title=\"" + alt_image + "\" usemap=\"#"+nomchamp+"_map\">";
			eval ("document." + nomchamp + "image").src = src_image;
		}
		else if (typechamp == 'wysiwyg')
		{
			eval(nomchamp + "_iframe").focus ();

			var objSelection = eval(nomchamp + "_iframe").document.selection.createRange();

			objSelection.pasteHTML(result);
		}
	}
}

function InsereDocument (nomchamp, typechamp, racineabsolue, strcallby) 
{
	if (typechamp == 'document2' || typechamp == 'flash' || typechamp == 'real')
	{
		var result = showModalDialog(racineabsolue+"/commun/dialoggenerique.php?callby="+strcallby+"&page=3&typechamp="+typechamp, "", "resizable:yes");
	}
	else if ((typechamp == 'wysiwyg') || (typechamp == 'document1'))
	{
		var result = showModalDialog(racineabsolue+"/commun/dialoggenerique.php?callby="+strcallby+"&page=2&typechamp="+typechamp, "", "resizable:yes;dialogHeight:400px;dialogWidth:700px");
	}

	if (result != null)
	{
		if ((typechamp == 'document1') || (typechamp == 'document2') || (typechamp == 'flash') || (typechamp == 'real'))
		{
			eval ("document.all." + nomchamp).value = result;
		}
		else if (typechamp == 'wysiwyg')
		{
			eval(nomchamp + "_iframe").focus (); 

			var objSelection = eval(nomchamp + "_iframe").document.selection.createRange();
			objSelection.pasteHTML(result);
		}
	}
}

// Cette ouvre une popup afin de permettre d'uploader un document via un formulaire simple
// puis l'insère dans un champ wysiwyg
function InsereDocumentSimple (nomchamp, racineabsolue, strcallby) 
{
//	window.open(racineabsolue+ "/commun/dialoggenerique.php?callby=" + strcallby +"&page=1");
	var result = showModalDialog(racineabsolue+ "/commun/dialoggenerique.php?callby=" + strcallby +"&page=1", "", "resizable:yes;dialogHeight:200px;dialogWidth:700px");

	if (result != null)
	{
		eval(nomchamp + "_iframe").focus (); 

		var objSelection = eval(nomchamp + "_iframe").document.selection.createRange();
		objSelection.pasteHTML(result);
	}
}
/*
function glossaire (theselection, texteaucunmot, modeEdition)
{
	// Mode d'edition refuse
	if (!modeEdition)
		return;

	therange = theselection.createRange();
	texte = therange.text;
	if(texte=="")
	{
		alert (texteaucunmot);
		return false;
	}
	else
	{
		textehtml = therange.htmlText;
		textehtml = "<SPAN class=glossaire>" + texte + "</SPAN> ";
		therange.execCommand("Delete");
		therange.pasteHTML(textehtml);
	}
}
*/
function RetireSpanVide(strChaineATraiter){
	// On remplace les <span class="quelqueChose"></span> qui aurait ete laisses par l'application
	var exp = /<SPAN([^>]*)>\s*<\/SPAN>/gi;
	while (exp.test(strChaineATraiter)){
		strChaineATraiter = strChaineATraiter.replace(exp, "");
//		alert('strChaineATraiter : '+ strChaineATraiter + '\n exp.test(strChaineATraiter)' + exp.test(strChaineATraiter)) ;
	}
	strChaineATraiter = strChaineATraiter.replace(/<SPAN([^>]+)><\/P>/gi, "</P>");
	return strChaineATraiter;
}
// Rajout d'un style CSS a l'element selectionne de l'iframe passe en parametre
	// strErreurImbrication contient le message en cas d'imbrication de styles complexes
function AddStyleComplet(IFrameChoisie, nameOfStyle, modeEdition, strErreurImbrication, strErreurAucunMot){
	// Tableau de reference
	var ArrBaliseParagraphe = new Array("P", "H");
	
	// Blindage de fonction
	if(nameOfStyle =="" || !modeEdition) 
		return;
	// focus est obligatoire car sinon il est possible que tout la page appelante soit utilisee
	IFrameChoisie.focus();

	// on vérifie que l'on est pas dans un tableau dans ce cas on n'applique pas le style car celui-ci buggerait
	if (HasAncestorNode(IFrameChoisie, "TABLE"))
	{
		return;
	}
	
	// Definition de constantes qui seront utilisees pour determiner le type de traitement a faire
	var MotCleAlignement      = 'Alignement';
	var MotCleListeNumerique  = 'ListeNumerique';
	var MotCleListeNormal     = 'ListeNormale';
	
	// Selection du range du textArea 
	textAreaRange = IFrameChoisie.document.body.createTextRange();
	
	// Selection du texte normal et HTML
	var theselection     = IFrameChoisie.document.selection;
	rangeSelectionne     = theselection.createRange();
	var texte            = rangeSelectionne.text;
	
	// Initilisation des balises
	var BaliseDebut = "SPAN";
	var BaliseFin   = "SPAN";

	// Definition du cas a traiter
	var AlignementATraiter = nameOfStyle.lastIndexOf(MotCleAlignement)>=0;
	var OlATraiter         = nameOfStyle.lastIndexOf(MotCleListeNumerique)>=0;
	var UlATraiter         = nameOfStyle.lastIndexOf(MotCleListeNormal)>=0;
	var HnATraiter         = (nameOfStyle.lastIndexOf("H")>=0 && nameOfStyle.length == 2);
	
	// Variable pour forcer l'imbrication
	var EstStyleSimple = false;
	if (nameOfStyle.toUpperCase().indexOf("GRAS")>0 || nameOfStyle.toUpperCase().indexOf("ITALI")>0 || nameOfStyle.toUpperCase().indexOf("SOULIGNE")>0 || nameOfStyle.toUpperCase().indexOf("UNDER")>0) {
		EstStyleSimple = true;
	}
	
	// Mot cle contenant le "pattern" a selectionner. IE ne gerant pas les paragraphes, ce cas sera traiter a part.
	var MotifASelectioner  = "";
	
	// Prefixe et suffixe a rajouter avant le colle du code HTML. Utilise lorsque l'utilisateur a selecttionne tout un paragraphe
	var strPrefixeTextHtml = "";
	var strSuffixeTextHtml = "";
	
	if (texte == "" && !(OlATraiter || UlATraiter || AlignementATraiter || HnATraiter)){
		alert(strErreurAucunMot)
		return;
	}
			
	// Definition d'un booleen forcant le coller
	ToutPaster = false;

	// Traitement particulier suivant le style envoye
	if (UlATraiter || OlATraiter || AlignementATraiter || HnATraiter){
		MotifASelectioner = 'paragraphe';
	}
	if (AlignementATraiter){
		BaliseDebut        = "P";
		BaliseFin          = "P";
		strPrefixeTextHtml = "";
		strSuffixeTextHtml = "";
	}
	else if (HnATraiter){
		BaliseDebut = nameOfStyle;
		BaliseFin   = nameOfStyle;
		strPrefixeTextHtml = nameOfStyle;
		strSuffixeTextHtml = nameOfStyle;
	}
	else if (OlATraiter){
		BaliseDebut        = "<LI>";
		BaliseFin          = "</LI>";
		strPrefixeTextHtml = "OL";
		strSuffixeTextHtml = "OL";
	}
	else if (UlATraiter){
		BaliseDebut        = "<LI>";
		BaliseFin          = "</LI>";
		strPrefixeTextHtml = "UL";
		strSuffixeTextHtml = "UL";
	}
	
	// Selection de tout le MotifASelectioner si c'est necessaire. Dans le cas du paragraphe => traitement sur les chaines de caractere (cf plus loin)
	if (MotifASelectioner!="" && MotifASelectioner != 'paragraphe'){
		rangeSelectionne.expand(MotifASelectioner);
	}
		
	// Recuperation de la partie avant la selection
	var arrResultatAvant = new Array();
	getAvantTexteRangeSelectionne(textAreaRange, rangeSelectionne, arrResultatAvant);
	var StrHtmlDebut     = arrResultatAvant["chaine"];
	var intNbDeplacement = arrResultatAvant["NbDeplacement"];

	// Recuperation de la partie apres la selection
	var arrResultatApres = new Array();
	getApresTexteRangeSelectionne(textAreaRange, rangeSelectionne, arrResultatApres);
	var StrHtmlApres     = arrResultatApres["chaine"];
	// !! Un peu de rapiecage... dans le cas la balise de fermeture n'est pas complete ie le champs est de la forme : /P>
	var nbOccurenceOuvertureInf  = CompteNombreOccurence(StrHtmlApres, "<");
	var nbOccurenceFermertureSup = CompteNombreOccurence(StrHtmlApres, ">");
	
	if (nbOccurenceFermertureSup ==  nbOccurenceOuvertureInf  + 1){
		StrHtmlApres =  "<" + StrHtmlApres;
	}
	var NbFinSpan        = arrResultatApres["nbFinSpan"];
	
	// Recuperation du texte selectionne
	StrHtmlSelectionne = getTexteRangeSelectionne(NettoieRange(textAreaRange.htmlText), StrHtmlDebut, StrHtmlApres);
	// !! Un peu de rapiecage... 
	var intPosInf = StrHtmlApres.indexOf("<");
	if (intPosInf <0){
		intPosInf = StrHtmlApres.length - 1;
	}
	var intPosSup = StrHtmlApres.indexOf(">");
	// Si le paragraphe commence par une balise de P non ouverte(cas ou le carret est en fin d'un paragraphe)
	if (StrHtmlApres.toUpperCase().indexOf("P") == 0 && intPosInf > intPosSup ){
		StrHtmlApres =  "<"+ StrHtmlApres;
	}
	intDebutTagP = StrHtmlSelectionne.toUpperCase().indexOf("<P");
	
	if (CompteNombreOccurence(StrHtmlSelectionne, "</OL>")>0 && CompteNombreOccurence(StrHtmlSelectionne, "</UL>")>0){
		alert('Vous ne pouvez pas appliquer ce style car vous avez sélectionné la fin d\'une liste. Veuillez sélectionner moins.');
		return;
	}

	if (VerifieImbrication(NettoieRange(textAreaRange.htmlText), StrHtmlSelectionne, StrHtmlDebut.length -1, strErreurImbrication, nameOfStyle)== false){
		return;
	}
	//alert('__avant para__\n StrHtmlSelectionne : ||'+StrHtmlSelectionne + '||\nStrHtmlDebut  : ||' +StrHtmlDebut + '||\n StrHtmlApres :||'+StrHtmlApres+'||')
	// Selection de tout le paragraphe
	if (MotifASelectioner == 'paragraphe'){
		arrNouvellesChaines = new Array();
		if (NettoieRange(textAreaRange.htmlText.toUpperCase()).indexOf("<P") <0 && NettoieRange(textAreaRange.htmlText.toUpperCase()).indexOf("<H") <0){
			StrHtmlDebut = "<P>" + StrHtmlDebut;
			StrHtmlApres = StrHtmlApres + "</P>";
		}
		SelectionneParagraphe(StrHtmlDebut, StrHtmlSelectionne, StrHtmlApres, arrNouvellesChaines);
		StrHtmlDebut        = arrNouvellesChaines["debut"];
		StrHtmlSelectionne  = arrNouvellesChaines["milieu"];
		StrHtmlApres        = arrNouvellesChaines["fin"];
		ToutPaster = true;
	}
	
//	alert('__APRES para__\n StrHtmlSelectionne : ||'+StrHtmlSelectionne + '||\nStrHtmlDebut  : ||' +StrHtmlDebut + '||\n StrHtmlApres :||'+StrHtmlApres+'||')
	//if (trim(StrHtmlDebut) == "" && trim(StrHtmlApres) =="" && StrHtmlSelectionne.toUpperCase().indexOf("<P") != 0){
	//	StrHtmlSelectionne = "<P>" + StrHtmlSelectionne + "</P>";
	//}
	
	// Determination des tableaux de span ouverts
	var ArrStyleOuvert = CreeTableauStyleOuvert(NettoieRange(textAreaRange.htmlText), StrHtmlSelectionne, StrHtmlDebut.length -1, "SPAN");
	
	if (VerifieImbrication(NettoieRange(textAreaRange.htmlText), StrHtmlSelectionne, StrHtmlDebut.length -1, strErreurImbrication, nameOfStyle)== false){
		return;
	}

	
	//A ce moment du traitement, on a reconstitue la chaine du textarea
	//alert('__Selection__\n StrHtmlDebut : ||'+StrHtmlDebut +'||\n StrHtmlApres : ||' + StrHtmlApres + '||\n StrHtmlSelectionne : ||'+StrHtmlSelectionne+'||\n s \n Tout : '+NettoieRange(textAreaRange.htmlText)+ '\n NbFinSpan :' + NbFinSpan);
	
	// ... On commence par modifier toutes les balises de debut et de fin de paragraphe par la valeur de la nouvelle balise
	ArrBaliseParagrapheOuverture = new Array();
	ArrBaliseParagrapheFermerture = new Array();
		
	for(var i=0; i<ArrBaliseParagraphe.length;i++){
		ArrBaliseParagrapheOuverture[i]  = "<"+ArrBaliseParagraphe[i];
		ArrBaliseParagrapheFermerture[i] = "</"+ArrBaliseParagraphe[i];
	}
			
	// .... Puis Dans le cas d'un paragraphe...
	if (MotifASelectioner == 'paragraphe'){
		if (CompteNombreOccurence(StrHtmlSelectionne, "<LI>")>0){
			alert("Vous ne pouvez pas imposer ce style car vous avez sélectionné une liste.")
			return;
		}
		if (HnATraiter){
			//StrHtmlSelectionne = SupprimeBaliseOuvertureEtFermertureParagraphe(StrHtmlSelectionne, new Array());
			StrHtmlSelectionne = RemplaceParagraphe(StrHtmlSelectionne, ArrBaliseParagrapheOuverture, "<"+BaliseDebut+">", false);
	//		alert('vt : '+StrHtmlSelectionne)
			StrHtmlSelectionne = RemplaceParagraphe(StrHtmlSelectionne, ArrBaliseParagrapheFermerture, "</"+BaliseFin+">", true);
	//		alert('ap : '+StrHtmlSelectionne)
			//textehtml = '<'+BaliseDebut+'>' + StrHtmlSelectionne + '</'+BaliseFin+'>';
			textehtml = StrHtmlSelectionne;
		}
		else if (OlATraiter || UlATraiter){
			StrHtmlSelectionne = RemplaceParagraphe(StrHtmlSelectionne, ArrBaliseParagrapheOuverture, BaliseDebut, false);
			StrHtmlSelectionne = RemplaceParagraphe(StrHtmlSelectionne, ArrBaliseParagrapheFermerture, BaliseFin, true);
			textehtml = '<'+strPrefixeTextHtml+ ' class="' + nameOfStyle + '">' + StrHtmlSelectionne + '</'+strSuffixeTextHtml+'>';
		}
		else if(AlignementATraiter){
	//		StrHtmlSelectionne = '<'+BaliseDebut+ ' class="' + nameOfStyle + '">' + StrHtmlSelectionne + "</"+BaliseFin+">";
			StrHtmlSelectionne = RemplaceParagraphe(StrHtmlSelectionne, ArrBaliseParagrapheOuverture, '<'+BaliseDebut+ ' class="' + nameOfStyle + '">', false);
			StrHtmlSelectionne = RemplaceParagraphe(StrHtmlSelectionne, ArrBaliseParagrapheFermerture, "</"+BaliseFin+">", true);
			textehtml = StrHtmlSelectionne;
		}
	}
	else{
		var RajoutSpan         = (BaliseDebut.toUpperCase().indexOf("SPAN") >=0 );
		// ... Ou dans le cas d'un span...
		if (RajoutSpan){
			// Cas ou tout le texte est selectionne
			if (StrHtmlDebut == "" && StrHtmlApres =="") {
				// Il est possible qu'un replace fasse l'affaire?
				alert("Vous ne pouvez pas sélectionner tout le texte");
				return;
			}
			// Protection contre l'application d'un style sur plusieurs paragraphes
			var nbOccurenceOuverture = 0;
			var nbOccurenceFermeture = 0;
			var posBaliseOuvrante    = -1;
			var posBaliseFermante    = -1;
			var boolSurPlusieursParagraphes = false;
			for(var i=0;i<ArrBaliseParagraphe.length;i++){
				// Il est possible qu'un replace fasse l'affaire?
				nbOccurenceOuverture = CompteNombreOccurence(StrHtmlSelectionne, "<"+ArrBaliseParagraphe[i]);
				nbOccurenceFermeture = CompteNombreOccurence(StrHtmlSelectionne, "</"+ArrBaliseParagraphe[i]+">");
				posBaliseFermante = StrHtmlSelectionne.indexOf("</"+ArrBaliseParagraphe[i]+">");
				posBaliseOuvrante = StrHtmlSelectionne.indexOf("<"+ArrBaliseParagraphe[i]);
				if (nbOccurenceFermeture == nbOccurenceOuverture && posBaliseFermante < posBaliseOuvrante){
					boolSurPlusieursParagraphes = true;
				}
				if (nbOccurenceOuverture == nbOccurenceFermeture && (nbOccurenceFermeture >1 ) ){
					boolSurPlusieursParagraphes = true;
				}
				if (nbOccurenceOuverture != nbOccurenceFermeture && (nbOccurenceFermeture > 1 || nbOccurenceOuverture > 1)){
					boolSurPlusieursParagraphes = true;
				}
				if (boolSurPlusieursParagraphes){
					alert("Vous ne pouvez pas appliquer un style sur plusieurs paragraphes.")
					return;
				}
			}
		
			var ArrBalisesParagrapheCourant = new Array();
			//alert('avant sup bliase : '+StrHtmlSelectionne);
			while(StrHtmlSelectionne.toUpperCase().indexOf("</SPAN>")==0){
				var intPosFermerture = 7;
				StrHtmlDebut = StrHtmlDebut + StrHtmlSelectionne.substring(0, intPosFermerture);
				StrHtmlSelectionne = StrHtmlSelectionne.substring(intPosFermerture, StrHtmlSelectionne.length);
			}
			StrHtmlSelectionne = SupprimeBaliseOuvertureEtFermertureParagraphe(StrHtmlSelectionne, ArrBalisesParagrapheCourant);
			//alert('avant : '+ArrBalisesParagrapheCourant["baliseOuvrante"] + '\n apres : '+ArrBalisesParagrapheCourant["baliseFermante"] + '\nStrHtmlSelectionne'+StrHtmlSelectionne);
			StrHtmlSelectionne = AppliqueStyle(nameOfStyle, StrHtmlSelectionne, NettoieRange(textAreaRange.htmlText), StrHtmlDebut);
			StrHtmlSelectionne = ArrBalisesParagrapheCourant["baliseOuvrante"] + StrHtmlSelectionne + ArrBalisesParagrapheCourant["baliseFermante"];
		//			alert('StrHtmlSelectionne (apres application style ): '+StrHtmlSelectionne)
		}
		textehtml = StrHtmlSelectionne;
	}
	textehtml = StrHtmlDebut + textehtml+ StrHtmlApres;
//	alert('avant paste : '+textehtml)
	textehtml = RetireSpanVide(textehtml);
	
	IFrameChoisie.document.execCommand("SelectAll");
	IFrameChoisie.document.execCommand("delete");
	IFrameChoisie.document.clear();
	textAreaRange.pasteHTML(textehtml);


	textAreaRange = IFrameChoisie.document.body.createTextRange();
	workRange     = textAreaRange.duplicate();
 	workRange.setEndPoint("StartToStart", textAreaRange);
	workRange.setEndPoint("EndToStart", textAreaRange);
	var NbAvance = 0;	
	// Aggrandissement du workRange jusqu'a ce qu'il arrive a RangeSelectionne
	while(NbAvance < intNbDeplacement){
		workRange.moveEnd("character", 1);
		NbAvance++;
	}
	workRange.collapse(false);
	workRange.select();

//	alert('__Fin__\n StrHtmlDebut : '+StrHtmlDebut +'\n StrHtmlApres : ' + StrHtmlApres + '\n StrHtmlSelectionne : '+StrHtmlSelectionne+'\n s \n Tout : '+NettoieRange(textAreaRange.htmlText)+ '\n NbFinSpan :' + NbFinSpan +'\n textehtml : '+ textehtml);


}

// Fonction cherchant les tags ouverts NomTag et non fermes de textAreaTexteHtml qui precedent  texteHtmlSelectionne a partir de posHtmlSelectionne
function CreeTableauStyleOuvert(textAreaTexteHtml, texteHtmlSelectionne, posHtmlSelectionne, NomTag){
	// Cas aux limites
	if (texteHtmlSelectionne==textAreaTexteHtml)
		return new Array();
	if (trim(texteHtmlSelectionne) == "" || trim(textAreaTexteHtml)=="")
		return new Array();
	
	// Gestion de la surcharge de la fonction
	var estSurchargee = false;
	var ArrRetour;
	var Style = "";
	if ( CreeTableauStyleOuvert.arguments[4] != undefined){
		ArrRetour     = new Array();
		ArrRetour     = CreeTableauStyleOuvert.arguments[4];
		estSurchargee = true;
		Style = ArrRetour["SpanASupprimer"];
	}
		
		
	// Texte selectionne sans SPAN (utilise dans la surcharge de la fonction)
	var StrTexteSansSpan = "";
	
	// Tableau dans lequel sera pushe/pop les tag trouves et qui sera renvoye
	var arrTagOuvert = new Array();
	
	// Constantes
	var DebutTag = "<SPAN";
	var FinTag   = "</SPAN";
	if (NomTag != ""){
		DebutTag = "<"+NomTag ;
		FinTag   = "</"+NomTag;
	}

	
	// Quelques variables
	texteHtmlSelectionne       = texteHtmlSelectionne.toUpperCase();
	var posTraitement          = 0; // Variable temporaire qui prendre la position de l'element courant
	var posDebutEltARechercher = posHtmlSelectionne;
	var texteTmp               = NettoieRange(textAreaTexteHtml);// Texte temporaire qui prendra la chaine de caractere a traiter
	var texteTag              = "";

	while(posTraitement<posDebutEltARechercher)
	{
		
		// Determination de l'ouverture ou de la fermeture du tag qui arrive
  		posDebutTag = texteTmp.toUpperCase().indexOf(DebutTag.toUpperCase(), 0);	// Position de la balise d'ouverture de style
  		posFinTag   = texteTmp.toUpperCase().indexOf(FinTag.toUpperCase(), 0);	// Position de la balise de fermeture de style
  		
  		
  		// Determination du min entre ces 2 valeurs
  		posMinTag   = posDebutTag;
  		if (posDebutTag > posFinTag || posMinTag<0 ){
  			posMinTag = posFinTag;
  		}
  		
  		// Cas final : la prochaine balise de style est apres le debut du texte a rechercher
  		if( posMinTag>0 && (posMinTag +  posTraitement >posDebutEltARechercher)){
  			posTraitement = posDebutEltARechercher;
  		}
  		else{
  			// Rajout du style dans le tableau de retour
  			if ((posDebutTag < posFinTag && posDebutTag>=0) || (posFinTag <=0 && posDebutTag>0)){
  				// Recuperation du tag
  				texteTag = texteTmp.substring(posDebutTag, texteTmp.indexOf(">", posDebutTag + 1) +1);
  				texteTag = NettoieRange(texteTag);
  				// Push dans le tableau
  				arrTagOuvert.push(texteTag);
  				// Calcul de la nouvelle position
	  			nouveauPosTraitement = posTraitement + texteTag.length + posDebutTag;
				if (estSurchargee && texteTag.indexOf(Style)>0){
  					StrTexteSansSpan = StrTexteSansSpan + texteTmp.substring(posTraitement, posDebutTag);
  				}
  				// Affectation pour le prochain tour
	  			posTraitement = nouveauPosTraitement;
  			}
  			// Suppression du style dans le tableau de retour
  			else if (posFinTag>=0){
  				 // Calcul de la nouvelle position
  				nouveauPosTraitement = posTraitement + posFinTag + FinTag.length + 1;
  				if (arrTagOuvert.length>0) {
  					if (estSurchargee && arrTagOuvert[arrTagOuvert.length - 1].indexOf(Style)>0){
	  					StrTexteSansSpan = StrTexteSansSpan + texteTmp.substring(posTraitement, nouveauPosTraitement +1);
	  				}
	  			}
  				// Suppression de la derniere valeur du tableau
  				arrTagOuvert.pop();
  				// Affectation pour le prochain tour
	  			posTraitement = nouveauPosTraitement;
  			}
  			else{
  				if (estSurchargee){
	  				StrTexteSansSpan = StrTexteSansSpan + texteTmp;
	  			}
  				// Cas final : Il n'y a plus de balise de style Tag
  				posTraitement = posDebutEltARechercher;
  			}
  			// Mise a jour de la variable de traitement
  			
  			texteTmp = textAreaTexteHtml.substring(posTraitement, textAreaTexteHtml.length);
  		}
 	}
 	
 	// Renvoie le texte sans SPAN si la fonction est surcharge
 	if (estSurchargee){
 		var expOuvertureSpan = new RegExp("<span class=[\"']?"+Style+"[\"']?","gi");
		StrTexteSansSpan = StrTexteSansSpan.replace(expOuvertureSpan, "");
 		ArrRetour["strSansSpanFermerture"] = StrTexteSansSpan;
 	}
 		
 	return arrTagOuvert;
}

// Renvoie dans outArray la chaine de caractere et le nombre de SPAN non ferme avant le rangeselectionne du textAreaRange (supprime les caracteres rajoutes par .htmltext)
function getAvantTexteRangeSelectionne(textAreaRange, RangeSelectionne, outArray){

	// Initialisation du range de travail au debut du textArea passe en parametre
	workRange = textAreaRange.duplicate();
 	workRange.setEndPoint("StartToStart", textAreaRange);
	workRange.setEndPoint("EndToStart", textAreaRange);
	var NbRecul = 0;	
	// Aggrandissement du workRange jusqu'a ce qu'il arrive a RangeSelectionne
	while(workRange.compareEndPoints("EndToStart", RangeSelectionne) < 0){
		workRange.moveEnd("character", 1);
		NbRecul++;
	}
	if (NbRecul ==0){
		outArray["chaine"]     = "";
 		outArray["nbDebutSpan"] = 0;
		return outArray;
	}
 	
 	// Recul d'un element pour recuperer la balise fermante pour les paragraphes. Ce deplacement peut entrainer la perte d'un caractere. On le rajoutera plus tard si ce n'est pas un paragraphe.
 	workRange.moveEnd("character", -1);
 	
 	nbDebutStyleSpan = NombreDebutDeStyle(workRange, "<SPAN");
 	
 	// Recuperation et nettoyage des textes
 	var RangeTexteHtml   = NettoieRange(workRange.htmlText);
 	var TextAreaTextHtml = NettoieRange(textAreaRange.htmlText);
 //	alert('RangeTexteHtml AVT : '+RangeTexteHtml +'\n RangeSelectionne : ' +RangeSelectionne.htmlText + '\nTextAreaTextHtml : '+TextAreaTextHtml)
 	var boolIdentique    = true;
 	var strDebut         = "";
 	
 	// Avant de commencer, nous verifions que le debut des deux range est identique : dans certains cas, il manque la balise <P>
 	if (TextAreaTextHtml.toUpperCase().indexOf("<P", 0) == 0 && RangeTexteHtml.indexOf("<P", 0)!=0 && RangeTexteHtml!=""){
 		var StrBaliseP = TextAreaTextHtml.substring(0, TextAreaTextHtml.indexOf(">") + 1);
// 		alert('Ajout <p>' + StrBaliseP);
 		RangeTexteHtml = StrBaliseP + RangeTexteHtml;
 	}
 	// La recuperation du code HTML a entraine le rajout d'element en plus... En comparant le texte html nettoye des deux ranges, nous reconstruisions le texte
 	var FinPos = 0;
	for(var j=0; j<RangeTexteHtml.length && boolIdentique;j++){
 		if (RangeTexteHtml.charAt(j)== TextAreaTextHtml.charAt(j)) {
 			strDebut = strDebut + TextAreaTextHtml.charAt(j);
// 			alert('tex : '+strDebut)
 	 	}
 		else{
 		 	boolIdentique = false;
 		}
 		 FinPos = j;
 	}
 	// Dans le cas ou on est sorti de la boucle en atteignant la fin de la chaine de comparaison, il faut avancer d'un cran car FinPos est encore dans cette chaine de debut
 	if (boolIdentique){
 		FinPos++;
 	}
 	if(strDebut.charAt(strDebut.length -1 ) == "<"){
 		strDebut = strDebut.substring(0, strDebut.length -1);
 		FinPos  = RangeTexteHtml.length  +1;
 	}
 	

 	// Si l'utilisateur n'a pas selectionne un paragraphe entier => le debut du range a un caractere en trop
 	//if (strDebut.charAt(strDebut.length - 1) != ">" && FinPos <= RangeTexteHtml.length && FinPos >0){
 	if (FinPos <= RangeTexteHtml.length && FinPos >0){
 		if (TextAreaTextHtml.charAt(FinPos) != "<"){
 			strDebut = strDebut + TextAreaTextHtml.charAt(FinPos);
 		}
 	}
 	outArray["NbDeplacement"] = NbRecul;
 	outArray["chaine"]        = strDebut;
 	outArray["nbDebutSpan"]   = nbDebutStyleSpan;
	return outArray;
}

// Fonction permettant de recuperer le text situe entre TextDebut et TextFin de la chaine textGlobal 
function getTexteRangeSelectionne(textGlobal, TextDebut, TextFin){
	posFin   = textGlobal.length - TextFin.length;
	
	if (posFin <= 0 && trim(TextFin.toUpperCase()) == "</P>"){
		posFin = textGlobal.length;
	}
	posDebut = textGlobal.indexOf(TextDebut) + TextDebut.length;
	
	//alert('__ Sel milieu__\n textGlobal : '+ textGlobal +'\n TextDebut :'+TextDebut + '\n TextFin :' +TextFin + ' \n posFin : '+ posFin + '\n posDebut : '+posDebut + '\n retourn : '+textGlobal.substring(posDebut, posFin))
	var strResultat = textGlobal.substring(posDebut, posFin);
	// !! rapiecage
	if (strResultat.charAt(strResultat.length -1) == "<"){
		strResultat = strResultat.substring(0, strResultat.length - 1);
	}
	return strResultat;
}



// Idem getAvantTexteRangeSelectionne pour apres
function getApresTexteRangeSelectionne(textAreaRange, RangeSelectionne, outArray){

	// Initialisation du range de travail a la fin du textArea passe en parametre
	workRange = textAreaRange.duplicate();
	workRange.setEndPoint("StartToEnd", textAreaRange);
	workRange.setEndPoint("EndToEnd", textAreaRange);
	
	// Deplacement du debut du  workRange jusqu'a ce qu'il arrive a RangeSelectionne
	while(workRange.compareEndPoints("StartToEnd", RangeSelectionne) > 0){
  		workRange.moveStart("character", -1);
 	}
 	
 	// Recuperation et nettoyage des textes
 	var WorkRangeText     = workRange.text;
 	var TextAreaTextHtml  = NettoieRange(textAreaRange.htmlText);
 	var nbFinStyleSpan = 0;
 	
 	// Le workrange selectionne fini par retour a la ligne => c'est une fin de paragraphe
 	if (NettoieRange(WorkRangeText.charAt(0))== "") {
 		// Deplacement de 1 pour prendre le debut du paragraphe
 		workRange.moveStart("character", 1);
 	}
 	
	nbFinStyleSpan = NombreFinDeStyle(workRange, "</SPAN>");

 	var WorkRangeTextHtml = NettoieRange(workRange.htmlText);

 	var boolIdentique     = true;
 	var strFin            = "";
 	// A certain moment, le workrange ne possede pas la derniere balise (de fermeture). Nous allons le rajouter
 	
 	var intPosSup  = TextAreaTextHtml.lastIndexOf('>');
 	var intPosInf  = TextAreaTextHtml.lastIndexOf("<");
 	var intPosInf2 = WorkRangeTextHtml.lastIndexOf("<");
 	if (intPosSup == (TextAreaTextHtml.length - 1) && WorkRangeTextHtml != "" && (TextAreaTextHtml.substring(intPosInf, TextAreaTextHtml.length) !=  WorkRangeTextHtml.substring(intPosInf2, WorkRangeTextHtml.length))){
 		var strDebutFinBalise = TextAreaTextHtml.substring(0, intPosInf);
 		var strDerniereBalise = TextAreaTextHtml.substring(intPosInf, intPosSup + 1);
 		WorkRangeTextHtml     = WorkRangeTextHtml + strDerniereBalise;
 	}
 	
	// La recuperation du code HTML a entraine le rajout d'element en plus... En comparant le texte html nettoye des deux ranges, nous reconstruisions le texte 	
	var FinPos = 0;
 	for (var k=0; k<WorkRangeTextHtml.length && boolIdentique; k++){
	 	if (WorkRangeTextHtml.charAt(WorkRangeTextHtml.length - k) == TextAreaTextHtml.charAt(TextAreaTextHtml.length - k)) {
 			strFin = WorkRangeTextHtml.charAt(WorkRangeTextHtml.length - k) + strFin ;
 		}
 		else{
	 	 	boolIdentique = false;
 		}
 		FinPos = k;
 	}
	// Dans le cas ou on est sorti de la boucle en atteignant la fin de la chaine de comparaison, il faut avancer d'un cran car il manque le dernier caractere
 	if (boolIdentique){
 		TextAreaTextHtml.length - FinPos;
 		strFin = TextAreaTextHtml.charAt(TextAreaTextHtml.length - FinPos - 1) + strFin ;
 	}
 		
 	
 	// Nettoyage de la dernire balise (ex le range de travail peut avoir : </P> et celui selectionne </SPAN>)
 	if (strFin.indexOf(">",0) == 0){
 		strFin = strFin.substring(1, strFin.length);
 	}
 	//strFin = strFin + WorkRangeTextHtml.CharAt(WorkRangeTextHtml.length - FinPos);
 	
 	outArray["chaine"]    = strFin;
 	outArray["nbFinSpan"] = nbFinStyleSpan;
}

// Fonction applicant le style a la selection passee en parametre
function AppliqueStyle(StrNameOfStyle, StrSelection, StrTotal, StrDebut){
	// Suppression des styles ouverts en debut de paragraphe
	while(StrSelection.indexOf("</SPAN>")==0){
		var intPosFermerture = StrSelection.indexOf("</SPAN>") + 1;
		//PosDebut = PosDebut + intPosFermerture;
		StrSelection = StrSelection.substring(intPosFermerture, StrHtmlSelectionne.length);
		StrDebut = StrDebut + "</SPAN>";
	}
	// Definitions des chaines de caractere qui vont gerer le style de la selection
	var StrAAppliquerApres = "";
	var StrAAppliquerAvant = "";
	// Resultat de la fonction
	var StrResultat = "";
	// Tableau des styles ouverts (et non fermes) avant le debut de la selection
	var ArrSpanOuvertAvantDebutSelection = CreeTableauStyleOuvert(StrTotal, StrDebut, StrDebut.length - 1 , "SPAN");
	var ClePosSpanOuvertAvantSelection   = 0;
	// Tableau des styles ouverts (et non fermes) avant la fin de la selection. la difference des 2 tableaux va nous permettre de connaitre les styles ovuerts _dans_ la selection
	var ArrSpanOuvertFinSelection        = CreeTableauStyleOuvert(StrTotal, StrDebut + StrSelection, StrDebut.length - 1 + StrSelection.length - 1, "SPAN");
	// Tableau des styles ouverts (et non fermes) dans la selection 
	var ArrSpanOuvertDansSelection       = CreeTableauStyleOuvert(StrSelection, "a", StrSelection.length, "SPAN");
	
	
	// On determine si StrNameOfStyle est ouvert avant le debut de la selection
	var StyleEstPresentAvantSelection = false;
	for(var i=0; i<ArrSpanOuvertAvantDebutSelection.length && !StyleEstPresentAvantSelection; i++){
		if (ArrSpanOuvertAvantDebutSelection[i].indexOf(StrNameOfStyle)>0){
			StyleEstPresentAvantSelection = true;
			ClePosSpanOuvertAvantSelection  = i;
		}
	}
	
	// On determine si StrNameOfStyle est ouvert dans la selection
	var StyleEstPresentDansSelection = false;
	for(var o=0; o<ArrSpanOuvertDansSelection.length && !StyleEstPresentDansSelection; o++){
		if (ArrSpanOuvertDansSelection[o].indexOf(StrNameOfStyle)>0){
			StyleEstPresentDansSelection = true;
		}
	}
	
	// Traitement particulier : la selection ouvre une balse avec le style a ajouter => dans ce cas on supprime toute presence du style
	if (StyleEstPresentDansSelection){
		var arrResultat = new Array();
		arrResultat["SpanASupprimer"] = StrNameOfStyle;
		CreeTableauStyleOuvert(StrSelection, "a", StrSelection.length, "SPAN", arrResultat);
		strResultat = arrResultat["strSansSpanFermerture"];
		return strResultat;
	}
	
	// Determination des balises a mettre avant et apres le style.
	if(StyleEstPresentAvantSelection){
	 	// Dans ce cas, le style doit etre supprime
	 	StrAAppliquerApres = "<SPAN class='" +StrNameOfStyle+ "'>";
	 	StrAAppliquerAvant = "</SPAN>";
	 	if (ClePosSpanOuvertAvantSelection >=0  && ArrSpanOuvertAvantDebutSelection.length > ClePosSpanOuvertAvantSelection + 1){
	 		for(var m = ClePosSpanOuvertAvantSelection + 1; m<ArrSpanOuvertAvantDebutSelection.length;m++){
	 			 StrAAppliquerAvant = " </SPAN> " + StrAAppliquerAvant + ArrSpanOuvertAvantDebutSelection[m]+" ";
	 			 StrAAppliquerApres = " </SPAN> " + StrAAppliquerApres + ArrSpanOuvertAvantDebutSelection[m]+" ";;
	 		}
		}
	}
	else{
		// Dans ce cas, le style doit etre rajouter
		StrAAppliquerAvant = "<SPAN class='" +StrNameOfStyle+ "'>";
	 	StrAAppliquerApres = "</SPAN>";
	
		// Gestion de l'imbrication
		var IntDeltaSpanOuvert = ArrSpanOuvertAvantDebutSelection.length - ArrSpanOuvertFinSelection.length;
			// 1er cas : la selection ouvre des styles sans les refermer. exemple : exemple : <b> toto [ti<i>ti] tutu </i>aze </b> [] indique l'element selectionne ==> il faut tous les refermer!
		if (ArrSpanOuvertDansSelection.length>0){
			for (var k = 0; k < ArrSpanOuvertDansSelection.length; k++){
				StrAAppliquerApres = "</SPAN>" + StrAAppliquerApres + ArrSpanOuvertDansSelection[k];
			}
		}
			// 2eme cas : il y a plus de styles (ie de SPAN) ouvert DANS la selection qu'AVANT. exemple : <b> toto [ti<i>ti] tutu </i>aze </b> [] indique l'element selectionne
				// probablement obsolete!
		else if (IntDeltaSpanOuvert < 0){
			// Note : l'ordre croissant ne pose pas de probleme car la fin du style est identique quelque soit le style
			for (var k = ArrSpanOuvertAvantDebutSelection.length; k < ArrSpanOuvertFinSelection.length; k++){
				StrAAppliquerApres = "</SPAN>" + StrAAppliquerApres + ArrSpanOuvertFinSelection[k];
			}
		}
			// 3eme  cas : il y a plus de styles (ie de SPAN) ouvert AVANT le debut de la selection que DANS. Certains styles sont donc fermes dans la selection! exemple : <b> toto [t</b>i<i>ti] tutu <i>aze
		else if (IntDeltaSpanOuvert >0 ){
			for (var k = ArrSpanOuvertFinSelection.length; k < ArrSpanOuvertAvantDebutSelection.length; k++){
			 	// Cas particulier : le style peut etre ferme dans la selection... On ne le rouvre pas apres pas!
				if (StyleEstPresentAvantSelection && ArrSpanOuvertAvantDebutSelection[k].indexOf(StrNameOfStyle)>0){
					StrAAppliquerApres = "";
				}
				StrAAppliquerAvant = "</SPAN>" + StrAAppliquerAvant + ArrSpanOuvertAvantDebutSelection[k];
			}
		}
	}

	StrResultat = StrAAppliquerAvant + StrSelection + StrAAppliquerApres;
//	alert('StrNameOfStyle : '+StrNameOfStyle+'\n StrDebut :'+StrDebut+'\n  StrSelection : '+StrSelection+'\nStrTotal : '+StrTotal+' \nIntDeltaSpanOuvert :'+IntDeltaSpanOuvert+'\n ArrSpanOuvertFinSelection.len : '+ArrSpanOuvertFinSelection.length+'\n ArrSpanOuvertAvantDebutSelection.length : '+ArrSpanOuvertAvantDebutSelection.length+'\nArrSpanOuvertDansSelection.length :'+ArrSpanOuvertDansSelection.length+' \n _ \n StrResutlat : '+StrResultat);
	return StrResultat;
}


// Fonction retirant des caracteres rajoutes par l'interface IE
function NettoieRange(texte){
	return texte.replace(/[\n\r]*/gi, "");
}

// Fonction comptant le nombre de fois ou StrARechercher apparait dans StrChaine
function CompteNombreOccurence(StrChaine, StrARechercher){
	// Mise en minuscule pour eviter le probleme de la sensibilite a la casse
	StrChaine      = StrChaine.toLowerCase();
	StrARechercher = StrARechercher.toLowerCase();
	// Initialisation des variables
	var i = 0;
	var nbOccurence = 0;
	
	// Traitement
	while (i != -1) {
		i = StrChaine.indexOf(StrARechercher, i);
		if (i>=0) {
			nbOccurence ++;
			i += StrARechercher.length;
		}
	}
	return nbOccurence;
}

// Fonction comptant combien de fois nomBalise apparait dans range
function NombreFinDeStyle(range, nomBalise){
	localWorkRange = range.duplicate();
	
	// Initialisation de workRange a la fin du textarea
	localWorkRange.setEndPoint("StartToStart", range);
	localWorkRange.setEndPoint("EndToStart", range);
	
	// Recule d'un caractere
	nbAvancement = 0;
 	localWorkRange.moveStart("character", -1);
 	nbAvancement++;
 	
 	// Deux cas au limite
 	if (NettoieRange(localWorkRange.htmlText) == ""){
 		nbAvancement++;
 		localWorkRange.moveStart("character", -1);
 	}
 	if (NettoieRange(localWorkRange.htmlText) == ""){
 		localWorkRange.moveStart("character", nbAvancement);
 		return 0;
 	}
 	var ChaineHtmlRange = NettoieRange(localWorkRange.htmlText)
 	localWorkRange.moveStart("character", nbAvancement);
	return CompteNombreOccurence(ChaineHtmlRange, nomBalise);
}


// Meme chose mais pour le debut
function NombreDebutDeStyle(range, nomBalise){
	localWorkRange = range.duplicate();
	
	// Initialisation de workRange a la fin du textarea
	localWorkRange.setEndPoint("StartToStart", range);
	localWorkRange.setEndPoint("EndToStart", range);
	
	// Recule d'un caractere
	nbAvancement = 0;
 	localWorkRange.moveEnd("character", 1);
 	nbAvancement++;
 	
 	if (NettoieRange(localWorkRange.htmlText) == ""){
 			nbAvancement++;
 			localWorkRange.moveEnd("character", 1);
 	}
 	if (NettoieRange(localWorkRange.htmlText) == ""){
 		localWorkRange.moveStart("character", - nbAvancement);
 		return 0;
 	}
 	var ChaineHtmlRange = NettoieRange(localWorkRange.htmlText)
 	localWorkRange.moveStart("character", - nbAvancement);
	return CompteNombreOccurence(ChaineHtmlRange, nomBalise);
}




// Fonction renvoyant le paragraphe complet (delimite par <p> et <p/>)
function SelectionneParagraphe(strDebut, strMilieu, strFin, outArray){

	var ArrBaliseParagraphe = new Array("P", "H");
	// Si strMilieu ne correspond pas a un paragraphe (ie commence par <p ou <hn) alors on recherche des tags de paragraphe dans debut et fin
	var intTmpPosBaliseDansStrMilieu = -1;
	var nomPremiereBaliseOuvrante = "";
	var nomDerniereBaliseFermante = "";
	var intPosBaliseOuvranteDansStrMilieu = strMilieu.length;
	var boolSansSelection = false;
	if (intPosBaliseOuvranteDansStrMilieu ==0){// Cas sans selection
		intPosBaliseOuvranteDansStrMilieu = -1;
		boolSansSelection = true;
	}
	var intPosBaliseFermanteDansStrMilieu = -1;
	
	if (!boolSansSelection){
		for(var i=0; i< ArrBaliseParagraphe.length;i++){
			// Determination de la valeur minimale des balises ouvrantes de paragraphe
			intTmpPosBaliseDansStrMilieu = strMilieu.toUpperCase().indexOf("<"+ArrBaliseParagraphe[i].toUpperCase());
			if (intTmpPosBaliseDansStrMilieu >= 0 && intTmpPosBaliseDansStrMilieu < intPosBaliseOuvranteDansStrMilieu){
				nomPremiereBaliseOuvrante         = ArrBaliseParagraphe[i];
				intPosBaliseOuvranteDansStrMilieu = intTmpPosBaliseDansStrMilieu;
			}
			// Determination de la valeur maximale dess balises fermantes de paragraphe
			intTmpPosBaliseDansStrMilieu = strMilieu.toUpperCase().lastIndexOf("</"+ArrBaliseParagraphe[i].toUpperCase()+">");
			if (intTmpPosBaliseDansStrMilieu >= 0 && intTmpPosBaliseDansStrMilieu > intPosBaliseFermanteDansStrMilieu){
				nomDerniereBaliseFermante         = ArrBaliseParagraphe[i];
				intPosBaliseFermanteDansStrMilieu = intTmpPosBaliseDansStrMilieu;
			}
		}
	}
	var StrMilieuFinal = strMilieu;
	
	// Cas ou strMilieu ne commence pas par un tag de debut de paragraphe
	var intPosDebutParagraphe    = -1;
	var intPosMaxDebutParagraphe = -1;
	var boolPasDeModifDebut      = false;
	if (intPosBaliseOuvranteDansStrMilieu != 0 || boolSansSelection){
		// Recherche de la derniere balise liee a un paragraphe dans strDebut
		for(var i=0; i< ArrBaliseParagraphe.length;i++){
			intPosDebutParagraphe = strDebut.toUpperCase().lastIndexOf("<"+ArrBaliseParagraphe[i].toUpperCase());
			if (intPosDebutParagraphe>=0 && intPosDebutParagraphe>intPosMaxDebutParagraphe){
				intPosMaxDebutParagraphe = intPosDebutParagraphe;
			}
		}
		StrMilieuFinal = strDebut.substring(intPosMaxDebutParagraphe , strDebut.length) + StrMilieuFinal;
//		alert('DEB StrMilieuFinal : '+StrMilieuFinal+'\nstrDebut : '+strDebut+ '\nintPosMaxDebutParagraphe : '+intPosMaxDebutParagraphe)
	}
	else{
		boolPasDeModifDebut = true;
	}
//	alert('MIL StrMilieuFinal :'+StrMilieuFinal)
	
	// Cas ou strMilieu ne finit pas par un tag de fin de paragraphe
	var intPosFinParagraphe    = -1;
	var intPosMinFinParagraphe = strFin.length;
	var boolPasDeModifFin      = false;
	
	if (intPosBaliseFermanteDansStrMilieu != strMilieu.length - ("</"+nomDerniereBaliseFermante+">").length){
		// Recherche de la premiere balise liee a un paragraphe dans strFin
		for(var i=0; i< ArrBaliseParagraphe.length;i++){
			intPosFinParagraphe = strFin.toUpperCase().indexOf("</"+ArrBaliseParagraphe[i].toUpperCase()+">");
			if (intPosFinParagraphe >=0 && intPosFinParagraphe<intPosMinFinParagraphe){
				intPosMinFinParagraphe = intPosFinParagraphe;
			}
		}
		StrMilieuFinal = StrMilieuFinal + strFin.substring(0, intPosMinFinParagraphe + nomDerniereBaliseFermante.length+4);
		//alert('FIN StrMilieuFinal : '+StrMilieuFinal+'\nstrDebut : '+strDebut+ '\nstrFin.substring(0, intPosMinFinParagraphe + nomDerniereBaliseFermante.length+1) : '+strFin.substring(0, intPosMinFinParagraphe + nomDerniereBaliseFermante.length+1))
	}
	else{
		boolPasDeModifFin = true;
	}
	
	var strDebutFinal = strDebut;
	if (!boolPasDeModifDebut){
		strDebutFinal = strDebut.substring(0, intPosMaxDebutParagraphe);
	}
	var strFinFinal   = strFin;
	
	if (!boolPasDeModifFin){
//		strFinFinal   = strFin.substring(strFin.toUpperCase().indexOf("<"+nomDerniereBaliseFermante) + (strFin.toUpperCase().indexOf(">", strFin.toUpperCase().indexOf("<"+nomDerniereBaliseFermante)) - strFin.toUpperCase().indexOf("<"+nomDerniereBaliseFermante)) + 1, strFin.length);
		strFinFinal   = strFin.substring(intPosMinFinParagraphe + nomDerniereBaliseFermante.length+4, strFinFinal.length);
	}
	else if (trim(nomDerniereBaliseFermante)==""){
		strFinFinal = "";
	}
	var strBaliseP    = strDebut.substring(intPosMaxDebutParagraphe, intPosMaxDebutParagraphe + nomDerniereBaliseFermante.length);
	
	outArray["debut"]    = strDebutFinal;
	outArray["milieu"]   = StrMilieuFinal;
	outArray["fin"]      = strFinFinal;
	
	outArray["baliseP"]  = strBaliseP;
}

// Fonction verifant l'imbrication des styles.
function VerifieImbrication(StrTexte, StrHtmlSelectionne, PosDebut, strErreurImbrication, StrStyle){
	// Verification de la presence de le fonction JS avec les styles a exclure (cree dynamiquement en PHP)
	if (!window.CreeTableauElementInterdit){
		return true;
	}
	var ArrEltAProteger = CreeTableauElementInterdit();
	
	// Definition des attributs a tester
	var NomAttributATester = new Array("div", "p");
	
	// Dans certains cas, on ne teste pas les span
	var MotCleAlignement   = 'Alignement';
	var HnATraiter         = StrStyle.toUpperCase().lastIndexOf("H")>=0 && StrStyle.length == 2;
	var AlignementATraiter = StrStyle.lastIndexOf(MotCleAlignement)>=0;
	// Dans le cas ou on n'ajoute pas de Hn => test de l'attribut SPAN
	if (!HnATraiter && !AlignementATraiter){
		NomAttributATester.push("span");
	}
	for(var i=0;i<ArrEltAProteger.length;i++){
		if (ArrEltAProteger[i].toUpperCase().indexOf("H")>=0 && trim(ArrEltAProteger[i].toUpperCase()).length == 2){
			NomAttributATester.push(ArrEltAProteger[i]);
		}
	}
	
	// Suppression des styles ouverts en debut de paragraphe
	StrHtmlSelectionne = trim(StrHtmlSelectionne);
	while(StrHtmlSelectionne.indexOf("<")==0){
		var intPosFermerture = StrHtmlSelectionne.indexOf(">") + 1;
		PosDebut = PosDebut + intPosFermerture;
		StrHtmlSelectionne = StrHtmlSelectionne.substring(intPosFermerture, StrHtmlSelectionne.length);
	}
	// Creation dynamique du tableau avec les elements
	var TableauElementHtml = new Array();
	var ElementImbrique    = false;
	var j = 0;
	
	// Pour tous les attributs a tester...
	for(var i=0; i< NomAttributATester.length && !ElementImbrique;i++){
		// Creation d'une colonne
		TableauElementHtml[NomAttributATester[i]] = new Array();
		// Creation du tableau avec l'element html courant selectionne
		TableauElementHtml[NomAttributATester[i]] = CreeTableauStyleOuvert(StrTexte, StrHtmlSelectionne, PosDebut, NomAttributATester[i]);
	// ... Pour tous les tag ouverts ...
		for(j=0; j< TableauElementHtml[NomAttributATester[i]].length && !ElementImbrique ;j++){
	// ... Pour toutes les chaines a interdire...
			for(k=0; k< ArrEltAProteger.length &&!ElementImbrique ; k++){
	// ... Verifier si le tag ne possede pas cet element.
				if(TableauElementHtml[NomAttributATester[i]][j].indexOf(ArrEltAProteger[k], 0)>0){
					ElementImbrique = true;
				}				
			}

		}
	}
	
	if (ElementImbrique) {
		//alert('Vous ne pouvez imbriquer des styles complexes.');
		alert(strErreurImbrication);
	}
	
	return !ElementImbrique;
}

// Fonction rajoutant les liens
function AjouteLien(IFrameChoisie, racineabsolue, strcallby){
	// Appel de la pop-up IE
	var theselection = IFrameChoisie.document.selection;
	objRange         = theselection.createRange();

	// la source est passée à un parseur XML dans PHP=> les quotes autour des paramètres sont requises
	StrSource = AjouteAttQuotes(objRange.htmlText);

//	window.open(racineabsolue+ "/commun/dialoggenerique.php?callby=" + strcallby +"&page=5&textehtml="+escape(StrSource));
	var result = showModalDialog(racineabsolue+ "/commun/dialoggenerique.php?callby=" + strcallby +"&page=5&textehtml="+escape(StrSource), "", "resizable:no;dialogHeight:160px;dialogWidth:500px");
		
	if (result != null)
	{
		IFrameChoisie.focus ();
		objRange.pasteHTML(result);
	}
}

function RemplaceParagraphe(strChaineATraiter, arrElementARemplacer, strChaineDeRemplacement, boolTagEstComplet){
	var strOutChaine = strChaineATraiter;
	for(var i=0;i<arrElementARemplacer.length;i++){
		if (!boolTagEstComplet){
			var expReg = new RegExp ('('+arrElementARemplacer[i]+'[1-6]{0,1}(\\s+[^>]*)?>)', "gi");
		}
		else{
			var expReg = new RegExp (arrElementARemplacer[i]+'[1-6]{0,1}>', "gi");
		}
//		alert('expReg : '+expReg+'\n strChaineDeRemplacement : '+strChaineDeRemplacement+'\nstrOutChaine : '+strOutChaine)
		strOutChaine = strOutChaine.replace(expReg, strChaineDeRemplacement);
//		alert('strOutChaine apr : '+strOutChaine);
	}
	
	return strOutChaine;
}
function SupprimeBaliseOuvertureEtFermertureParagraphe(StrHtmlSelectionne, ArrRetour){
	// Tableau avec les tags definissant les paragraphes
	var ArrBaliseParagraphe = new Array("P", "H");
	var strOutChaine       = StrHtmlSelectionne;
	
	// Recherche de la premiere balise de paragraphe ouvrante
	var intTmpPosBaliseDebutDansStrHtmlSelectionne = -1;
	var intTmpPosBaliseFinDansStrHtmlSelectionne   = -1
	var nomPremiereBaliseOuvrante    = "";
	var nomDerniereBaliseFermante    = "";
	var intPosBaliseOuvrante = StrHtmlSelectionne.length;
	if (intPosBaliseOuvrante ==0){// Cas sans selection
		intPosBaliseOuvrante = -1;
	}
	var intPosBaliseFermante = -1;
	
	// Determination de la valeur minimale des balises ouvrantes de paragraphe
	for(var i=0; i< ArrBaliseParagraphe.length;i++){
		intTmpPosBaliseDebutDansStrHtmlSelectionne = StrHtmlSelectionne.toUpperCase().indexOf("<"+ArrBaliseParagraphe[i].toUpperCase());
		intTmpPosBaliseFinDansStrHtmlSelectionne   = StrHtmlSelectionne.toUpperCase().lastIndexOf("</"+ArrBaliseParagraphe[i].toUpperCase());
		if (intTmpPosBaliseDebutDansStrHtmlSelectionne >= 0 && intTmpPosBaliseDebutDansStrHtmlSelectionne < intPosBaliseOuvrante){
			nomPremiereBaliseOuvrante = ArrBaliseParagraphe[i].toUpperCase();
			intPosBaliseOuvrante      = intTmpPosBaliseDebutDansStrHtmlSelectionne;
		}
		if (intTmpPosBaliseFinDansStrHtmlSelectionne >= 0 && intTmpPosBaliseFinDansStrHtmlSelectionne > intPosBaliseFermante){
			nomDerniereBaliseFermante = ArrBaliseParagraphe[i].toUpperCase();
			intPosBaliseFermante      = intTmpPosBaliseFinDansStrHtmlSelectionne;
		}
	}
	// Determination des positions des balises ouvrantes
	var intPosDebutBaliseOuvrante = 0;
	var boolExisteBaliseOuvrante  = true;
	if (nomPremiereBaliseOuvrante!=""){
		intPosDebutBaliseOuvrante = strOutChaine.toUpperCase().indexOf("<"+nomPremiereBaliseOuvrante.toUpperCase());
		boolExisteBaliseOuvrante = true;
	}
	else{
		boolExisteBaliseOuvrante = false;
	}
	if (intPosDebutBaliseOuvrante <0 || nomPremiereBaliseOuvrante ==""){
		intPosDebutBaliseOuvrante = 0;
	}
	var intPosFinBaliseOuvrante   = strOutChaine.toUpperCase().indexOf(">", intPosDebutBaliseOuvrante);
	
	// Recuperation des balises de debut de paragraphe
	if (intPosDebutBaliseOuvrante<intPosFinBaliseOuvrante && boolExisteBaliseOuvrante){
		ArrRetour["baliseOuvrante"] = strOutChaine.substring(intPosDebutBaliseOuvrante, intPosFinBaliseOuvrante + 1);
	}
	else{
		ArrRetour["baliseOuvrante"] = "";
	}
	
	// Recuperation des balises de fin  de paragraphe
	var intFinBaliseFermante      = strOutChaine.indexOf(">", intPosBaliseFermante);
	if (intPosBaliseFermante<0){
		intPosBaliseFermante = strOutChaine.length;
	}
	if (nomDerniereBaliseFermante!="" && intFinBaliseFermante == strOutChaine.length - 1){
		ArrRetour["baliseFermante"] = strOutChaine.substring(intPosBaliseFermante, intFinBaliseFermante +1);
	}
	else{
		ArrRetour["baliseFermante"] = "";
	}
	// Gestion des cas au limite
	if (intPosFinBaliseOuvrante>0){
		intPosFinBaliseOuvrante++;
	}
	else{
		intPosFinBaliseOuvrante = 0;
	}
	if (intPosBaliseFermante<=0){
		intPosBaliseFermante = strOutChaine.length;
	}
	// Remise a 0 de intPosFinBaliseOuvrante s'il est superieur a intPosBaliseFermante car 
	if (intPosFinBaliseOuvrante >= intPosBaliseFermante){
		intPosFinBaliseOuvrante = 0;
	}
//	alert('intPosBaliseFermante  '+ intPosBaliseFermante + '\n'+intPosFinBaliseOuvrante + '\nstrOutChaine : '+strOutChaine + '\n strOutChaine.substring(intPosFinBaliseOuvrante, intPosBaliseFermante); ' + strOutChaine.substring(intPosFinBaliseOuvrante, intPosBaliseFermante)+'\nArrRetour["baliseFermante"] : '+ArrRetour["baliseFermante"]+'\n ArrRetour["baliseOuvrante"] : '+ArrRetour["baliseOuvrante"])
	
	strOutChaine = strOutChaine.substring(intPosFinBaliseOuvrante, intPosBaliseFermante);
	return strOutChaine;
}
// -->

// modifie du code non XHTML (retourné par InnerHTML) afin de rajouter des quotes aux attributs qui n'en n'ont pas
function AjouteAttQuotes(StrInput)
{
	BoolDansBalise = false;
	BoolDansValeurParam = false;
	StrTypeParam = "";
	StrOutput = "";

	for (i=0; i<StrInput.length; i++)
	{
		StrChar = StrInput.charAt(i);
		
		switch (StrChar)
		{
			case "<":
				if (!BoolDansValeurParam)
				{
					BoolDansBalise = true;
				}
				StrOutput += StrChar;
			break;
			case ">":
				if (!BoolDansValeurParam)
				{
					BoolDansBalise = false;
				}
				else
				{
					if (StrTypeParam == "nue")
					{
						StrOutput += "\"";
						BoolDansValeurParam = false;
						BoolDansBalise = false;
					}
				}
				StrOutput += StrChar;
			break;
			case "=":
				StrOutput += StrChar;
				if (BoolDansBalise && !BoolDansValeurParam)
				{
					BoolDansValeurParam = true;

					StrCharSuivant = StrInput.charAt(i+1);	// existe car innerHTML ferme tjrs les balises
					if (StrCharSuivant == "\"")
					{
						StrTypeParam = "quote";
						StrOutput += StrCharSuivant;
						i++;
					}
					else
					{
						StrTypeParam = "nue";
						StrOutput += "\"";
					}
				}
			break;
			case "\"":
				if (BoolDansValeurParam)
				{
					BoolDansValeurParam = false;
				}
				StrOutput += StrChar;
			break;
			case " ":
				if (BoolDansValeurParam && StrTypeParam == "nue")
				{
					BoolDansValeurParam = false;
					StrOutput += "\"";
				}
				StrOutput += StrChar;
			break;
			default:
				StrOutput += StrChar;
			break;
		}
	}
	return StrOutput;
}

// Cette ouvre une popup permettant de choisir les caractérisitques du tableau
function InsereTableau (nomchamp, racineabsolue, strcallby) 
{
	var result = showModalDialog(racineabsolue+ "/commun/dialoggenerique.php?callby=" + strcallby +"&page=6", "", "resizable:no;srollbar:no;dialogHeight:225px;dialogWidth:610px");
	if (result != null)
	{
		eval(nomchamp + "_iframe").focus ();
		var objSelection = eval(nomchamp + "_iframe").document.selection.createRange();
		objSelection.pasteHTML(result);
	}
}

// Rajout d'un style CSS au tableau
// strAlertAucunTD contient le message dans le cas ou on n'as pas de TD
function AddStyleTD(IFrameChoisie, nameOfStyle, modeEdition, strAlertAucunTD)
{
	// focus sinon l'utilisateur ne peut plus éditer le contenu du tableau
	IFrameChoisie.focus();
	
	if (HasAncestorNode(IFrameChoisie, "TD"))
	{
		objTD = MoveToAncestorNode(IFrameChoisie, "TD");
		objTD.className = nameOfStyle;
	}
	else if(HasAncestorNode(IFrameChoisie, "TH"))
	{
		objTH = MoveToAncestorNode(IFrameChoisie, "TH");
		objTH.className = nameOfStyle;
	}
	else
	{
		alert(strAlertAucunTD);
	}
}

// retourne un tag de type 'nodeTagName' s'il correspond à celui sélectionné ou un parent
// The "nodeTagName" parameter must be UPPER CASE.
function HasAncestorNode (nomchamp, nodeTagName)
{
	var objSelection = eval(nomchamp).document.selection;
	var oRange = objSelection.createRange() ;

	var oContainer ;

	if ( objSelection.type == "Control" )
	{
		if ( oRange && oRange.item )
			oContainer = oRange.item(0) ;
	}
	else
	{
		oContainer = oRange.parentElement() ;
	}

	while ( oContainer )
	{
		if ( oContainer.tagName == nodeTagName ) return true ;
		oContainer = oContainer.parentNode ;
	}

	return false ;
}

// The "nodeTagName" parameter must be UPPER CASE.
function MoveToAncestorNode (nomchamp, nodeTagName)
{
	var objSelection = eval(nomchamp).document.selection;
	var oNode ;

	if ( objSelection.type == "Control" )
	{
		var oRange = objSelection.createRange() ;
		for ( i = 0 ; i < oRange.length ; i++ )
		{
			if (oRange(i).parentNode)
			{
				oNode = oRange(i).parentNode ;
				break ;
			}
		}
	}
	else
	{
		var oRange  = objSelection.createRange() ;
		oNode = oRange.parentElement() ;
	}

	while ( oNode && oNode.nodeName != nodeTagName )
		oNode = oNode.parentNode ;

	return oNode ;
}
