// ----------------------------------------------------------------------------------------------
//
//	global/jscript/str_fnc.js
//
//	Fonctions de gestion de chaines
//
//--------------------------------------  PREREQUIS  --------------------------------------------
//
//
//-------------------------------------- HISTORIQUE ---------------------------------------------
//
//      Cr?ation
//      --------
//
//	Modifications
//	-------------
//	12/2003		LTS		V131 NEGPLUS
//	- ajout fonction de conversion de poids fichier KO en cha?ne de caract?res KO/MO
//	- ajout fonction de conversion de nb secondes en cha?ne de caract?res temps
//
// ----------------------------------------------------------------------------------------------

// ---------------------------------------------------------------------------------------------- //
//                INITIALISATIONS GLOBALES AU MODULE
// ---------------------------------------------------------------------------------------------- //

var sepDEC		= ",";			// s?parateur de d?cimales
//
var strKO		= "Ko";			// kilo octets
var strMO		= "Mo";			// mega octets
//
var strHOU		= "h";			// heures
var strMIN		= "m";			// minutes
var strSEC		= "s";			// secondes
//
var isSelected = false;


// ---------------------------------------------------------------------------------------------- //
//                FONCTIONS TRAITEMENT DE CHAINES DE CARACTERES
// ---------------------------------------------------------------------------------------------- //

//
// Fonction de remplacement d'un caract?res par une chaine
//
//      strIn           la chaine initiale ? traiter
//      chrWhat         le caract?re ? chercher/remplacer
//      strBy           la chaine de remplacement
//
function strReplaceChar (strIn, chrWhat, strBy)
{
        // D?clarations
        //
        var strOut, intStrInLen, intPos, c;

        // Initialisation de variables
        //
        intStrInLen = strIn.length;
        strOut = "";

        // Boucle de remplacement des caract?res
        //
        for (i=0 ; (i < intStrInLen) ; i++)
        {
                c = strIn.charAt(i);
                if (c == chrWhat)
                        strOut = strOut + strBy
                else    strOut = strOut + c;
        }

        // Retour de la chaine r?sultat
        //
        return strOut;
}

// ---------------------------------------------------------------------------------------------- //

// MODIF LTS 12/2003 V131 NEGPLUS: ajout de la fonction suivante

//
// Fonction de conversion de poids fichier en cha?ne de caract?res
//
//	a_koweight	le poids en ko
//
function weight2String (a_koweig)
{
	// Initialisations
        //
        var l_wstr = "";
        var l_moweig = Math.floor (a_koweig/1024);

        // Traitement
        //
        if (l_moweig >= 1)
        {
        	// Affichage en Mo
                //	- avec 1 chiffre apr?s la virgule si < 10 Mo
                //
                var l_korest = "";
                //
        	l_koweig = Math.floor (a_koweig - (l_moweig*1024));			// le reste en Ko

                if (l_moweig < 10  &&  l_koweig > 0)
                {
			l_korest = l_koweig.toString();
// 01/2006 correction			l_korest = sepDEC + l_korest.substr(1,1);
			l_korest = sepDEC + l_korest.substr(0,1);
                }
		l_wstr = l_moweig + l_korest + " " + strMO;
        }
        else	l_wstr = a_koweig + " " + strKO;

        // Retour traitement
        //
        return (l_wstr);
}

// ---------------------------------------------------------------------------------------------- //

//
// Fonction de conversion nb de secondes en cha?ne de caract?res temps
//
//	a_nbseconds	le nb de secondes
//
function seconds2String (a_nbseconds)
{
	// Initialisations
        //
        var l_tstr = "";

        // Traitement
        //
        var l_hourate = Math.floor (a_nbseconds/3600);		      		// nb d'heures compl?tes
        var l_minrate = Math.floor ((a_nbseconds - (l_hourate*3600))/60);	// nb de minutes restantes
        var l_secrate = a_nbseconds - (l_hourate*3600) - (l_minrate*60);		// nb de secondes restantes
        //
        if (l_hourate > 0)	        	l_tstr = l_tstr + l_hourate+strHOU+" ";
	if (l_hourate > 0  ||  l_minrate > 0)	l_tstr = l_tstr + l_minrate+strMIN+" ";
        l_tstr = l_tstr + l_secrate+strSEC;

        // Retour traitement
        //
        return (l_tstr);
}

// FIN MODIF LTS 12/2003 V131 NEGPLUS


// ---------------------------------------------------------------------------------------------- //
//                FONCTIONS DE VERIFICATION DE STRUCTURE
// ---------------------------------------------------------------------------------------------- //

//
// V?rification de la structure d'un mail
//
//        mail                le champ qui contien l'email
//
function CheckEmail (mail)
{
	// Valeur de retour
        var ret = true;
        // Calcul longueur chaine
        var ilgmail = mail.value.length - 1;
        // Lecture des posiions des diff?rents @
        var fidxaro = mail.value.indexOf ("@");                // position premier @
        var lidxaro = mail.value.lastIndexOf ("@");                // postion dernier @

        // Lecture des posiions des diff?rents .
        var fidxpoi = mail.value.indexOf (".");                // position premier .
        var lidxpoi = mail.value.lastIndexOf (".");                // postion dernier .

        // Test qu'aucun espace dans le mail
        if (mail.value.indexOf (" ") >= 0)
                ret = false;
        // Test qu'un et un seul @ et position > 0 et position <> lg
        else if (fidxaro <= 0  ||  (lidxaro > 0  &&  fidxaro != lidxaro)  ||  fidxaro == ilgmail  ||  lidxaro == ilgmail)
                ret = false;
        // Test qu'au moins 1 . et dernier (autre que premier, si existant) apr?s @
        else if (fidxpoi <= 0  ||  (lidxpoi > 0  &&  lidxpoi < fidxaro)  ||  fidxpoi == ilgmail  ||  lidxpoi == ilgmail)
                ret = false;


        // Valeur de retour
        return (ret);
}

// RBT v351 tools
// vérification de structure d'une liste de mails séparés par ";"
// en cas d'erreur, retourne le mail erroné et no pas false (différent de fonction CheckMail ci dessus)
function CheckMails (listemails)
{
	// séparation des différents mails;
	var modele = /;/;
	var ret='';
	
	liste = listemails.value.split(modele);

	if (liste[0].length>0)
	{
		for (i=0; i<liste.length; i++)
		{
			mail = liste[i];
			// on nettoie les espaces avant le mail
			while (mail.indexOf(" ")==0)
			{
				mail = mail.substr(1,mail.length);
			}
			
			// Calcul longueur chaine
			var ilgmail = mail.length - 1;
			
			
			// on nettoie les espaces avant et après le mail
			if (mail.indexOf(" ")>0)
			{
				//alert('index espace = '+mail.indexOf(" ")+', longueur mail = '+mail.length+', pos dernier = '+ilgmail);
				while (mail.substr(ilgmail,1)==" ")
				{
					mail = mail.substr(0,ilgmail);
					ilgmail--;
				}
			}
			
			// Calcul longueur chaine
			//var ilgmail = mail.length - 1;
			
			// Lecture des posiions des diff?rents @
			var fidxaro = mail.indexOf ("@");                // position premier @
			var lidxaro = mail.lastIndexOf ("@");            // postion dernier @
		
			// Lecture des posiions des diff?rents .
			var fidxpoi = mail.indexOf (".");                // position premier .
			var lidxpoi = mail.lastIndexOf (".");            // postion dernier .
		
			// Test qu'aucun espace dans le mail
			if (mail.indexOf (" ") >= 0)
				ret = mail;
			// Test qu'un et un seul @ et position > 0 et position <> lg
			else if (fidxaro <= 0  ||  (lidxaro > 0  &&  fidxaro != lidxaro)  ||  fidxaro == ilgmail  ||  lidxaro == ilgmail)
				ret = mail;
			// Test qu'au moins 1 . et dernier (autre que premier, si existant) apr?s @
			else if (fidxpoi <= 0  ||  (lidxpoi > 0  &&  lidxpoi < fidxaro)  ||  fidxpoi == ilgmail  ||  lidxpoi == ilgmail)
				ret = mail;
			
			//alert(mail+' '+ (ret));
			if (ret) break;
	
		}
	}
	else ret=' ';

	return(ret);
	
}



// retourne la valeur d'un champs email, ne retourne rien si vuide (et non pas null ou undefined)
function getEmail(email)
{
	
	var ret='';
	if (email.value.length>0)
	{
		return(email.value);
	}
	else return (ret);
	
	
}

// ---------------------------------------------------------------------------------------------- //
//                FONCTIONS DE COMPTAGE DE MOTS/CARACTERES
// ---------------------------------------------------------------------------------------------- //

function countWords(form, inptxt)
{
        txt = eval("document." + form + "." + inptxt);
        // la chaine ? compter
        var fullStr = txt.value;

	//
	return (strCountWords(fullStr));
}


//
// Compte le nombre de mots d'un champ input
//
function strCountWords(a_fullstr)
{
	var fullStr = a_fullstr;

        // les caract?res de ponctuation
        var rExp = /[,;:?.!]/gi;
        // on remplace les caract?res de ponctuations par des espaces (ils induient 1 nouveau mot)
        var cleanedStr = fullStr.replace(rExp, " ");
        cleanedStr = cleanedStr.replace("\n", " ");

        //
        // on supprime tous les doubles espaces
        do
        {
                var old_str = cleanedStr;
                cleanedStr = cleanedStr.replace("  ", " ");
        }
        while(old_str != cleanedStr);

        //
        // on supprime les espaces de d?but de cha?ne
        do
        {
                old_str = cleanedStr;
                longueur = cleanedStr.length;
                if (cleanedStr.charAt(0) == " ")
                { cleanedStr = cleanedStr.substring(1,longueur);  }
        }
        while(old_str != cleanedStr);


        //
        // on cr?e un tableau avec tout les mots, le s?parateur ?tant l'espace
        var splitString = cleanedStr.split(" ");

        //
        wordCount = 0;
        // si la chaine nettoy?e est vide le tableau retournera 1, mais il y a 0 mot!
        if (cleanedStr.length < 1)
                {wordCount=0;}
        // le dernier mot en cours de frappe n'est pas compt?
        else
//                {wordCount=splitString.length - 1; }
                {wordCount=splitString.length; }
        //
        //

        return wordCount;
}


// ---------------------------------------------------------------------------------------------- //

//
// Compte le nombre de mots d'un champ input et efface ceux qui d?passent le nombre max
//
function delLastWords(form, inptxt, maxwords)
{
        txt = eval("document." + form + "." + inptxt);
        // la chaine ? compter
        var fullStr = txt.value;

	//
        txt.value = strDelLastWords(fullStr, maxwords);
}


function strDelLastWords(a_fullstr, maxwords)
{
        // la chaine ? compter
        var fullStr = stripHTML(a_fullstr);
        // les caract?res de ponctuation
        var rExp = /[,;:?.!]/gi;
        // on remplace les caract?res de ponctuations par des espaces (ils induient 1 nouveau mot)
        var cleanedStr = fullStr.replace(rExp, " ");
        //
        // on supprime tous les doubles espaces
        do
        {
                var old_str = cleanedStr;
                cleanedStr = cleanedStr.replace("  ", " ");
        }
        while(old_str != cleanedStr);

        //
        // on supprime les espaces de d?but de cha?ne
        do
        {
                old_str = cleanedStr;
                longueur = cleanedStr.length;
                if (cleanedStr.charAt(0) == " ")
                { cleanedStr = cleanedStr.substring(1,longueur);  }
        }
        while(old_str != cleanedStr);



        //
        // on cr?e un tableau avec tout les mots, le s?parateur ?tant l'espace
        var splitString = cleanedStr.split(" ");

        var toDelete = splitString[maxwords];
//        alert (toDelete+"#"+ txt.value.lastIndexOf(toDelete));
        return(a_fullstr.substring(0, a_fullstr.lastIndexOf(toDelete)));

}

// ---------------------------------------------------------------------------------------------- //

//
// Compte le nombre de mots d'un champ input et efface ceux qui d?passent le nombre max
//
function addtext(form, inptxt, toadd)
{

        txt = eval("document." + form + "." + inptxt);
        // la chaine ? compter
        txt.value = txt.value + toadd;
        txt.focus();
}




// ---------------------------------------------------------------------------------------------- //

function markSelection ( txtObj )
{
	if ( txtObj.createTextRange )
        {
		txtObj.caretPos = document.selection.createRange().duplicate();
//alert (txtObj.caretPos.text)
		isSelected = true;
	}
}


// ---------------------------------------------------------------------------------------------- //

//
// Fonction d'ajout automatique d'un caract?re dans une zone texte
//
//      txtName         la zone texte ? affecter
//      tag             le texte ? ajouter
//
function insertTag (txtName, tag, nomForm)
{
        // Initialisations
        //
        var closeTag = tag;
        CSAg = window.navigator.useragent;

        // Traitement diff?rent suivant IE ou NS
        //      - sur NS, on ne peut qu'ajouter en fin de champ
        //      - sur IE, on peut ajouter l? o? se trouve le curseur
        //
        if (IsIE()  &&  !IsMac())
        {
                // Traitement sp?cial pour Internet Explorer sous Windows
                //
                if (isSelected)
                {
                        var txtObj = eval ( "document." + nomForm + "." + txtName );
			//alert(txtObj);
                        if (txtObj.createTextRange && txtObj.caretPos)
                        {
                                var caretPos = txtObj.caretPos;
                                caretPos.text = tag+caretPos.text;
                                markSelection (txtObj);
                                if (txtObj.caretPos.text == '')
                                {
                                        isSelected = false;
                                        txtObj.focus();
                                }
                        }
                }
                else if (IsIE())
                        alert ("Placez le curseur ? l'endroit o? ins?rer le caract?re ...");
        }
        else
        {
                // Traitement pour les autres cas
                //
                var forme = eval ("document." + nomForm);
                addtext(nomForm, txtName, tag);
        }
}



// Fonction d'ajout automatique de tags html autour d'un texte
//
//      txtName			la zone texte ? affecter
//      tag1			le tag ouvrant
//      tag2			le tag fermant
//
function encadreTag (txtName, tag1, tag2, nomForm)
{



 	// Initialisations
        //
        //var closeTag =
        CSAg = window.navigator.useragent;

        // Traitement diff?rent suivant IE ou NS
        //      - sur NS, on ne peut qu'ajouter en fin de champ
        //      - sur IE, on peut ajouter l? o? se trouve le curseur
        //
        if (IsIE()  &&  !IsMac())
        {
                // Traitement sp?cial pour Internet Explorer sous Windows
                //
                if (isSelected)
                {
                        var txtObj = eval ( "document." + nomForm + "." + txtName );
                        if (txtObj.createTextRange && txtObj.caretPos)
                        {
                                var caretPos = txtObj.caretPos;
                                if (txtObj.caretPos.text == '')
                                {
					alert ("Selectionnez la partie du texte sur lequel vous voulez appliquer le style ...");
                                        isSelected = false;
                                        txtObj.focus();
                                }
				else
				{
                                caretPos.text = tag1+caretPos.text+tag2;
                                markSelection (txtObj);
				}
                        }
                }
                else if (IsIE())
                        alert ("Selectionnez la partie du texte sur lequel vous voulez appliquer le style ...");
        }
        else
        {

                var ta = eval ("document." + nomForm + "." + txtName);


		if (ta.selectionStart | ta.selectionStart == 0)
		     {
			if (ta.selectionEnd > ta.value.length) { ta.selectionEnd = ta.value.length; }

			var firstPos = ta.selectionStart;
			var secondPos = ta.selectionEnd + tag1.length;

			ta.value=ta.value.slice(0,firstPos)+tag1+ta.value.slice(firstPos);
			ta.value=ta.value.slice(0,secondPos)+tag2+ta.value.slice(secondPos);

			ta.selectionStart = firstPos+tag1.length;
			ta.selectionEnd = secondPos;
			ta.focus();
		     }

        }
}


function stripTags(oldString) 
{
	var newString = "";
	newString = oldString.replace(/<\S[^><]*>/g, " ");

	return (newString);

}

function convertHTML(oldString)
{
	//
	newString = oldString.replace (/&ccedil;/g, "ç");
	newString = newString.replace (/&agrave;/g, "à");
	newString = newString.replace (/&acirc;/g, "â");
	newString = newString.replace (/&eacute;/g, "é");
	newString = newString.replace (/&egrave;/g, "è");
	newString = newString.replace (/&ecirc;/g, "ê");
	newString = newString.replace (/&euml;/g, "ë");
	newString = newString.replace (/&icirc;/g, "î");
	newString = newString.replace (/&iuml;/g, "ï");
	newString = newString.replace (/&ocirc;/g, "ô");
	newString = newString.replace (/&ouml;/g, "ö");
	newString = newString.replace (/&ugrave;/g, "ù");
	newString = newString.replace (/&ucirc;/g, "û");
	newString = newString.replace (/&uuml;/g, "ü");

	newString = newString.replace (/&atilde;/g, "ã");
	newString = newString.replace (/&etilde;/g, "ë");
	newString = newString.replace (/&otilde;/g, "õ");
	newString = newString.replace (/&oacute;/g, "ó");
	newString = newString.replace (/&ntilde;/g, "ñ");
	newString = newString.replace (/&quot;/g, "\"");
	
	return (newString);
}


function stripHTML(oldString)
{
	newString = stripTags(oldString);
	newString = convertHTML(newString);
	
	return (newString);
}


function StrTrim (myString)	{
	return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
} 
