//*******************************************************************************************
//	Script :		Client_Library.js
//	Progiciel :		Profils.net
//	Version :		2.7
//	MAJ par :		LRL
//	MAJ le :		22/01/03
//	Description :	Fonctions de script clients
//*******************************************************************************************

//*******************************************************************************************
// inclusion des bibliothèques de fonctions et de constantes
//
// -->IsStringOK (Compare le contenu d'une chaine (stringTape) avec le contenu d'une chaine de référence (StringOk).
//
// -->IsStringNotOK (Vérifie si un caractère interdit se trouve dans une chaine de caractères)
//
// -->CountOccurrences (Compte le nombre d'occurrences d'un élément donné dans une chaine de caractères.)
//
// -->IsFirstLastStringOK (Teste la validité du premier et du dernier caractère d'une chaine)
//
// -->ContainOnlySpaces (Détecte si la chaîne ne contient que des espaces)
//
// -->SelectAll (Selectionne toutes les options d'un select multiple)
//
// -->AddItem (Ajoute la sélection d'un combo obj_HTMLListdans un combo obj_HTMLListAdd en tenant compte
//				le cas échéant du choix d'une option de précision dans le combo obj_HTMLListPrecision)	
//
// -->AddItemNew (Ajoute la sélection d'un combo obj_HTMLListdans un combo obj_HTMLListAdd en tenant compte
//				le cas échéant du choix d'une option de précision dans le combo obj_HTMLListPrecision
//
// -->RemoveItem (Supprime les options sélectionées d'un objet select)
//
// -->MoveItem (Déplace une option dans un objet select vers le haut ou le bas suivant str_direction)
//
// -->FillDepCombo (Fonction appelant la page DepCombosM.asp dans un IFrame pour la mise à jours des éléments dans les combos dépendants (combos multiples)		
//
// -->VerifMotCle(Vérifie les mots clés ne pouvant être remplacés dans un texte)
//
// -->ValidMessMotCle(Message de récapitulation des mots clés dans un texte)
//
//*******************************************************************************************



function IsStringOK(str_tape, str_ok)
//*******************************************************************************************
//  Auteur : Lagrange Virginie
//  Date maj : 14/08/01
//
//	Fonction :	IsStringOK
//
//	Objet :		Compare le contenu d'une chaine (stringTape)
//	            avec le contenu d'une chaine de référence (StringOk).
//
//	Entrées :	- str_tape : Chaine de caractères saisie.
//				- str_ok : Chaine de caractères de référence.
//
//	Sortie :	si non conforme : - False
//									  - affichage d'un message d'erreur avec explications
//									  - focus sur l'élément
//					True sinon
//*******************************************************************************************
{
	var int_i, int_j;
		// parcours de la chaine de caractères
    	for (int_i = 0; int_i < str_tape.length; int_i++)
	 	{	
	   		var str_Ch = str_tape.charAt(int_i);
	   		for (int_j = 0; int_j < str_ok.length; int_j++)
	     		if (str_Ch == str_ok.charAt(int_j))
					break;
	   			if (int_j == str_ok.length)
				return(false);
	  	}
	 	return (true);
}


function IsStringNotOK(str_tape, str_NotOK)
//*******************************************************************************************
//  Auteur		: CGY
//  Date maj	: 04/09/2002
//	Fonction	: IsStringNotOK
//
//	Objet		: Vérifie si un caractère interdit se trouve dans une chaine de caractères
//
//	Entrées		:- str_tape : Chaine de caractères saisie.
//				 - str_NotOK : Chaine de caractères de référence.
//
//	Sortie		:- False (si un caractère interdit est détecté) :
//				 - True (si aucun caractère interdit n'est détecté)
//*******************************************************************************************
{
	var int_i, int_j;
		// parcours de la chaine de caractères non autorisés
    	for (int_i = 0; int_i < str_NotOK.length; int_i++)
	 	{	
	   		//Sélection du premier caractères de la chaine de caractères non autorisés
	   		var str_Ch = str_NotOK.charAt(int_i);
	   		
	   		// parcours de la chaine de caractères à vérifier
	   		for (int_j = 0; int_j < str_tape.length; int_j++)
	   		{
	   			//comparaison du caractère interdit avec le caractère parcouru
	     		if (str_Ch == str_tape.charAt(int_j))
	     		{
					return(false);
				}
			}
	   			
	  	}
	 	return (true);
}


function CountOccurrences(str_characters, var_char)
//*******************************************************************************************
//  Auteur : Lagrange Virginie
//  Date maj : 14/08/01
//
//	Fonction :	CountOccurrences
//
//	Objet :		Compte le nombre d'occurrences d'un élément donné dans une chaine de caractères.
//
//	Entrées :	- str_characters : Chaine de caractères saisie.
//				- var_char : Caractère recherché.
//
//	Sortie :	- int_nbOccur : Nombre d'occurrences.
//*******************************************************************************************
{
	var int_length; //Nombre de caractères
	var int_nbOccur; //Nombre d'occurrences

	int_length = str_characters.length;
	int_nbOccur = 0;
	
	//parcours de la chaine de caractères
	for (int_i = 0; int_i <= int_length; int_i++)
	{
		//si le caractère courant correspond au caractère recherché
		//on incrémente le compteur d'occurrences
		if((str_characters.substr(int_i, 1) == var_char))
		{
			int_nbOccur = int_nbOccur + 1;
		}
	}

	return int_nbOccur;  //on retourne le nombre d'occurrences
}


function IsFirstLastStringOK(str_mailCharacters)
//*******************************************************************************************
//  Auteur : Lagrange Virginie
//  Date maj : 14/08/01
//
//	Fonction :	IsFirstLastStringOK
//
//	Objet :		Teste la validité du premier et du dernier caractère d'une chaine
//
//	Entrées :	- str_mailCharacters : Chaine de caractères saisie.
//
//	Sortie :	si non conforme : - False
//									  - affichage d'un message d'erreur avec explications
//									  - focus sur l'élément
//					True sinon
//*******************************************************************************************
{
	var str_FirstCharacter = str_mailCharacters.slice(0,1);
	var str_LastCharacter = str_mailCharacters.slice(str_mailCharacters.length - 1);
	var str_CharactMailOk = "0123456789azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN";
			
	//Test si les deux caractères (premier et dernier) sont des caractères autorisés
	//par rapport à la chaine de référence str_CharactMailOk.			
	if (!(IsStringOK(str_FirstCharacter, str_CharactMailOk) && IsStringOK(str_LastCharacter, str_CharactMailOk)))
	{
		return false;
	}
	return true;										
}


function ContainOnlySpaces(str_string)
//*******************************************************************************************
//	Auteur :  Frédéric Mayot
// 	Date maj : 04/09/01
//	Fonction :	ContainOnlySpaces()
//
//	Objet :		Détecte si la chaîne ne contient que des espaces
//
//	Entrées :	- str_string (type string): chaine de caractères à vérifier
//
//	Sortie :	True si ne contient que des espaces sinon false
//
//*******************************************************************************************
{
	// on récupère le nombre d'espaces dans la chaine
	var int_nbEspace = CountOccurrences(str_string,' ');

	// on calcule la longueur de la chaine
	var int_longueur = str_string.length;

	// si les deux sont identiques, c'est que l'on a que des espaces.
	if (int_nbEspace == int_longueur)
	{
		return true;
	}
	
	// sinon tout roule
	return false;
}


//*******************************************************************************************
//	Auteur : BREAU Julien
// 	Date maj : 17/08/01
//
//	Fonction :		SelectAll(obj_HTMLElement)
//
//	Objet :			Selectionne toutes les options d'un select multiple
//
//	Appliquée à :	- select multiple
//
//	Entrées :		- obj_HTMLElement (type objet) : objet HTML à vérifier
//
//	Sortie :		si non conforme : - false
//									  - affichage d'un message d'erreur (debug)
//					true sinon
//******************************************************************************************

function SelectAll(obj_HTMLElement, bln_defaultoption)
{
	if(obj_HTMLElement.type == "select-multiple") 
	{
		//Condition, si aucune sélection n'a été faite, pour ajouter une option vide de valeur vide, afin que le selectmultiple soit posté page suivante.
		if ((obj_HTMLElement.length == 0)&&(bln_defaultoption))
		{
			var obj_newoption = new Option('','');
			obj_HTMLElement.options[0] = obj_newoption;
			obj_HTMLElement.options[0].selected = true;			
		}
		for(var i = 0; i < obj_HTMLElement.length; i++)
		{
			obj_HTMLElement.options[i].selected = true;
		}
		return true;
	}
	else
	{
		alert(err_Object);
		return false;
	}
}


function AddItem (obj_HTMLList, obj_HTMLListAdd, int_AddMax, arr_Options, obj_HTMLListPrecision)
//*******************************************************************************************
//  Auteur :	Laurent Rigal
//  Date maj :	15/01/02
//
//	Fonction :	AddItem
//
//	Objet :		Ajoute la sélection d'un combo obj_HTMLList
//				dans un combo obj_HTMLListAdd en tenant compte le cas échéant
//				du choix d'une option de précision dans le combo obj_HTMLListPrecision		
//
//	Entrées :	- obj_HTMLList (type objet select) : liste de choix des options
//          	- obj_HTMLListAdd (type objet select) : liste des options sélectionnées
//        		- obj_HTMLListPrecision (type objet select) : liste des options de précision
//
//	Sortie :	aucune
//*******************************************************************************************
{
	var int_selindex = obj_HTMLList.selectedIndex;
	var int_NbOption = obj_HTMLListAdd.length;
	var arr_index = new Array(int_NbOption);

	// Initialisation des variables s'il existe une option sélectionnée
	// ds le combo obj_HTMLList
	// Sinon return
	if (int_selindex>=0)
	{
		var selvalue = obj_HTMLList.options[int_selindex].value;
		var seltext = obj_HTMLList.options[int_selindex].text;
	}
	else
	{
		return;
	}
	
	// Teste si le nombre maximum d'option sélectionné a été atteint
	if (int_AddMax != 0)
	if (int_NbOption>=int_AddMax)
	{
		alert(err_Limit + int_AddMax + err_Selection + err_Dot);
		obj_HTMLListAdd.focus()
		return;
	}

	// Teste si la valeur n'a pas déja été sélectionnée puis
	// Génère un tableau avec la position initiale de l'option
	var i = 0;
	while (i<int_NbOption)
	{
		var arr_value = obj_HTMLListAdd.options[i].value.split("_");
		// Si la valeur a déja été sélectionnée return
		if (arr_value[0].value == selvalue)
		{
			return;
		}
		
		// Tableau listant les positions initiales des options sélectionnées
		var j=0;
		while(j<arr_Options.length)
		{
			if (arr_Options[j] == obj_HTMLListAdd.options[i].value)
			{
				arr_index[i] = j;
				break;
			}
			j++;
		}		
		i++;
	}
	
	// Position initiale de l'élément à insérer
	i=0;
	while (i<arr_Options.length)
	{
		if (arr_Options[i] == selvalue)
		{
			break;
		}
		i++;
	}
	int_position = i;
	
	// Détermine la position ou insérer la nouvelle option
	i=0;
	while (i<arr_index.length)
	{
		if (int_position<arr_index[i])
		{
			break;
		}
		i++;
	}
	var int_insertpos = i;

	
	// Si sélection d'une option précision (combo obj_HTMLListPrecision),
	// génère la valeur et le texte pour l'option à ajouter
	if (obj_HTMLListPrecision)
	{
		if (obj_HTMLListPrecision.selectedIndex != "")
		{
			var i = 0;
			
			do
				i++;
			while (obj_HTMLListPrecision.value != obj_HTMLListPrecision.options[i].value);
			
			if (obj_HTMLListPrecision.options[i].value != "")
			{
				while(obj_option.text.length < 50)
				{
					obj_option.text += ' ';
				}			
				
				seltext += '|  ' + obj_HTMLListPrecision.options[i].text;
				selvalue += '_' + obj_HTMLListPrecision.value;
				obj_HTMLListPrecision.selectedIndex = 0;
			}
		}
		else
		{
			obj_HTMLListPrecision.focus();
			return;
		}
	}
	

	// Ajoute l'option sélectionnée au combo obj_HTMLListAdd
	if (int_NbOption==int_insertpos)
	{
		var obj_option = new Option (seltext, selvalue);
		obj_HTMLListAdd.options[int_NbOption] = obj_option;
	}
	else
	{
		var obj_option = new Option (obj_HTMLListAdd.options[int_NbOption-1].text,obj_HTMLListAdd.options[int_NbOption-1].value)
		obj_HTMLListAdd.options[int_NbOption] = obj_option;
		
		i = int_NbOption-1;
		// Décale les options pour laisser la position de sélection libre
		while (i>int_insertpos)
		{
			obj_HTMLListAdd.options[i].value = obj_HTMLListAdd.options[i-1].value;
			obj_HTMLListAdd.options[i].text = obj_HTMLListAdd.options[i-1].text;
			i--;
		}
		
		// Insère l'option sélectionnée
		obj_HTMLListAdd.options[i].value = selvalue;
		obj_HTMLListAdd.options[i].text = seltext;
		
	}
	
	// Supprime l'option du combo obj_HTMLList
	obj_HTMLList.options[int_selindex] = null;
	
	// Désactive la sélection du combo obj_HTMLList
	obj_HTMLList.selectedIndex=-1;
	obj_HTMLList.focus();
}


function FillDepCombo(FilterComboId, DepComboId, SelMult, str_AutresParam)
//*******************************************************************************************
//  Auteur :	Laurent Rigal
//  Date maj :	09/12/02
//
//	Fonction :	FillDepCombo
//
//	Objet :		Fonction appelant la page DepCombos.asp dans un IFrame
//				pour la mise à jours des éléments dans les combos dépendants (combos multiples)		
//
//	Entrées :	- FilterComboId (type string) : identifie les controles "parent" (ListeId + Id)
//          	- DepComboId (type string ou array) : identifie les controles dépendants (enfants)
//				- SelMult	: 0= le combo enfant n'est pas multiple; 1= le combo enfant est multiple
//				- str_AutresParam : string pour l'héritage du style du combo parent vers les combo enfants
//
//	Sortie :	aucune
//*******************************************************************************************
{
	var obj_filter = eval('document.forms[0].' + FilterComboId);
	var obj_select;
	var objDiv;
	var arr_seloption = new Array();
	var arr_DepComboId; // tableau
	var int_j;
	
	//alert('Paramètres d\'entrée de FillDepCombo\nFilterComboId = ' + FilterComboId + '\nDepComboId = ' + DepComboId + '\nSelMult = ' + SelMult  + '\nstr_AutresParam = ' + str_AutresParam);
	
	//Test sur le paramètre DepComboId pour créer un tableau qui contiendra le nom du combo dépendant
	if (typeof(DepComboId)=='string')
		{
		arr_DepComboId = new Array(DepComboId);
		}
	else
		{
		arr_DepComboId = DepComboId;
		}
		
	//Cas Combo multiples
	if (obj_filter.type=='select-multiple')
	{
		var str_filter = '';
		//Boucle sur le nombre d'options du combo Parent des options sélectionnées
		for(i=0; i<obj_filter.options.length; i++)
		{
			if (str_filter.length > 0)
				str_filter += ',' + obj_filter.options[i].value;
			else
				str_filter = obj_filter.options[i].value;
		}	
		
		//Boucle sur le nombre de combo enfant (un ou plusieurs)
		for(var i=0; i<arr_DepComboId.length; i++)
		{
			//Désignation du combo enfant
			obj_select = eval('document.forms[0].' + arr_DepComboId[i]); 
			if (obj_select=='[object]')
			{
				//Boucle sur le nombre d'options du combo enfant qui contient les options déjà sélectionnées
				if (obj_select.options.length>0)
					for(j=0; j<obj_select.options.length; j++)
					{
						//alert('arr_seloption.length = ' + arr_seloption.length);
						if (arr_seloption.length > 0)
						{
							arr_seloption[i] += ',' + obj_select.options[j].value;
						//	alert('arr_seloption[i] = ' + arr_seloption[i]);
						}
						else
						{
							arr_seloption[i] = obj_select.options[j].value;
						}
					}
				else
					arr_seloption[i] = '';
			}
			else
				arr_seloption[i] = '';
		}
	}
	else
	{
		if (obj_filter.type=="select-one")
		{
			str_filter= obj_filter.options[obj_filter.selectedIndex].value;
			
			for(var i=0; i<arr_DepComboId.length; i++)
				arr_seloption[i] = '';
		}
	}
	

	//S'il y a eu une sélection dans comboparent ou pour un select-one Si La première ligne contient du texte = > on recharge l'Iframe
	//alert("obj_filter.options[obj_filter.selectedIndex].text='" + obj_filter.options[obj_filter.selectedIndex].text + "'");
	if (!(str_filter =='') || ((obj_filter.type=="select-one")&&(obj_filter.options[obj_filter.selectedIndex].text!='')))
	{
		
		for(var i=0; i<arr_DepComboId.length; i++)
		{
                        var objName = "self.window.frames['IFrame" + arr_DepComboId[i] + "']";

                        var objIFrame = eval(objName);

			//var objIFrame = eval('document.frames("Iframe'+ arr_DepComboId[i] +'")');

			//alert("../iframe/DepCombo.asp?DepId=" + arr_DepComboId[i] + "&Filt=" + str_filter + "&Sel=" + arr_seloption[i] + "&SelMult=" + SelMult + "&Param=" + str_AutresParam);

			objIFrame.location.href = '../iframe/DepCombo.asp?DepId=' + arr_DepComboId[i] + '&Filt=' + str_filter + '&Sel=' + arr_seloption[i] + '&SelMult='+ SelMult + '&Param=' + str_AutresParam;
		}
	}
	// on efface les combos enfants
	else
	{
		for(i=0; i<arr_DepComboId.length; i++)
		{
			//Cas specifique des compétences
			if (arr_DepComboId[i]=='CompCand')
			{
				//Faire tant que le div suivant existe
				int_j = 1;
				objDiv = eval('document.all.div' + arr_DepComboId[i]+ int_j);
				do
				{
					if (typeof(objDiv) == 'object')
					{
						objDiv.innerHTML = '';
							
						objDiv = eval('document.all.divLib' + arr_DepComboId[i]+ int_j);
						objDiv.innerHTML = '';
					}
					int_j+= 1;
					objDiv = eval('document.all.div' + arr_DepComboId[i]+ int_j);
				}
				while (typeof(objDiv) == 'object');
			}
			else
			{
				objDiv = eval('document.all.divLib' + arr_DepComboId[i]);
				if (typeof(objDiv) == 'object')
					objDiv.innerHTML = '';
						
				objDiv = eval('document.all.div' + arr_DepComboId[i]);
				if (typeof(objDiv) == 'object')
					objDiv.innerHTML = '';
			
				// Pages Statistiques (tableaux)
				objDiv = eval('document.all.divOption1' + arr_DepComboId[i]);
				if (typeof(objDiv) == 'object')
					objDiv.innerHTML = '';
				
				objDiv = eval('document.all.divOption2' + arr_DepComboId[i]);
				if (typeof(objDiv) == 'object')
					objDiv.innerHTML = '';
			}
		}
	}
}


function VerifMotCle(str_TextATraiter,arr_MotCleVerifVal,arr_MotCleVerif)
//*******************************************************************************************
//  Auteur		:	XMN
//  Date maj	:	06/03/03
//
//	Fonction	:	VerifMotCle
//
//	Objet		:	Vérifie les mots clés ne pouvant être remplacés dans un texte
//
//	Entrées		:	- str_TextATraiter		: texte envoyé à vérifier
//					- arr_MotCleVerif		: Valeur en fonction de la langue du mot réservé : RefDoss
//					- arr_MotCleVerifVal	: Référence du dossier
//
//	Sortie		:	aucune
//*******************************************************************************************
{
	for (i = 0; i < arr_MotCleVerif.length; i++)
	{
		var arr_TraitText = str_TextATraiter.split("[" + arr_MotCleVerif[i] + "]");
		//	err_StrMotCle1 = Le mot réservé
		//	err_StrMotCle2 = est vide,\n veuillez remplir directement sa valeur
		if ((arr_TraitText.length != 1) && (arr_MotCleVerifVal[i] == ""))
		{
			alert(err_StrMotCle1 + "[" + arr_MotCleVerif[i] + "]" + err_StrMotCle2 + err_Dot);
			return(false);
		}
	}
	return true;
}

function ValidMessMotCle(str_TextATraiter,arr_MotCleVal,arr_MotCle,str_TypeOrigText)
//*******************************************************************************************
//  Auteur		:	XMN
//  Date maj	:	06/03/03
//
//	Fonction	:	ValidMessMotCle
//
//	Objet		:	Message de récapitulation des mots clés dans un texte
//
//	Entrées		:	- str_TextATraiter		: texte envoyé à vérifier
//					- arr_MotCle			: tableau contenant les mots clé dans ordre défini par la base
//					- arr_MotCleVal			: tableau contenant les valeurs qui remplaceront les mots clé dans ordre défini par la base
//					- str_TypeOrigText		: Nom du champ dans lequel se passe la vérification
//
//	Sortie		:	aucune
//*******************************************************************************************
{
	var j;
	var int_NbMotCle = 0;
	var str_TextRetour = '';

	// initialisation du message : 
	// err_StrMotCle3 = voici les informations contenues dans
	// err_StrMotCle4 = de valeur
	// err_StrMotcle5 = pas de mot clé dans
	// alert('int_lengthArr' + arr_MotCle.length);
	// alert('int_lengthArr' + arr_MotCleVal.length);
	for (i = 0; i < arr_MotCle.length; i++)
	{
		var arr_TraitText = str_TextATraiter.split("[" + arr_MotCle[i] + "]");
		var int_lengthArr = arr_MotCleVal.length;

		if (arr_TraitText.length != 1 && i < int_lengthArr)
		{
			int_NbMotCle = arr_TraitText.length - 1
			str_TextRetour = str_TextRetour + int_NbMotCle + " [" + arr_MotCle[i] + "]";

			if (arr_MotCleVal[i].length != 0)
			{
				str_TextRetour = str_TextRetour + err_StrMotCle4 + ': ' + arr_MotCleVal[i] + '\n';
			}
			else
			{
				str_TextRetour = str_TextRetour + "\n";
			}
		}
	}

	// gestion si Mots réservés dans le texte ou non
	if (str_TextRetour.length == 0)
	{
		str_TextRetour = err_StrMotCle5 + "\'" + str_TypeOrigText + "\'" + err_Dot
	}
	else
	{
		str_TextRetour = err_StrMotCle3 + "\'" + str_TypeOrigText + "\' :\n" + str_TextRetour;
	}
	return(str_TextRetour);
}
