/******************************************************************/
/* Fonctions globales à l'application                             */
/******************************************************************/

function checkFocusDateElement( anElement ) {
	
	var errorString = null;
	
	if ( ( anElement.value == "" ) || ( anElement.value == null ) ) {
		return "";
	}
	
	var dateTab = stringTokenizer( "/" , anElement.value );
	if ( dateTab.length < 3 ) {
		anElement.value = numberFromString(anElement.value);
		var newString = formatDateString(anElement.value,"2/2/4","/");
		dateTab = stringTokenizer("/",newString);
		if ( dateTab.length < 3 ) {
			errorString = "La date doit être saisie sous le format jj/mm/aaaa.";
		}
	    else {
			anElement.value = newString;
        }
	}
	
	if ( errorString == null ) {
		errorString = dateValide( dateTab );
	}
	
	if ( errorString != null ) {
		alert( errorString );
		anElement.focus();
    	return false;
	}

	return true;
}

function checkDateElement(anElement) {
	if (anElement.value=="" || anElement.value==null) {
		return "";
	}
	var dateTab=stringTokenizer("/",anElement.value);
	if (dateTab.length<3) {
		anElement.value=numberFromString(anElement.value);
		var newString=formatDateString(anElement.value,"2/2/4","/");
		dateTab=stringTokenizer("/",newString);
		if (dateTab.length<3) {
			anElement.value="";
			alert("La date doit être saisie sous le format jj/mm/aaaa.");
			return anElement.value;
		}
		else {
			anElement.value=newString;
		}
	}
	var errorString=dateValide (dateTab);
	if (!errorString)
		return anElement.value;
	else {
		alert(errorString);
		anElement.focus();
		return errocheckString="";
	}
	return anElement.value;
}

function checkDate(checkString){
	if (checkString=="" || checkString==null)
		return "";
	var dateTab=stringTokenizer("/",checkString);
	if (dateTab.length<3) {
		checkString=numberFromString(checkString);
		var newString=formatDateString(checkString,"2/2/4","/");
		dateTab=stringTokenizer("/",newString);
		if (dateTab.length<3) {
			checkString="";
			return checkString;
		}
		else {
			checkString=newString;
		}
	}
	var errorString=dateValide (dateTab);
	if (!errorString)
		return checkString;
	else {
		alert(errorString);
		return errocheckString="";
	}
	return checkString;
}

function dateValide(dateTab){
	var annee,jour,mois;
	var returnString=null;
	if (dateTab.length>=3) {
	    jour=dateTab[0];
	    mois=dateTab[1];
	    annee=dateTab[2];
	    if (annee==0)
		    returnString="L'annee n'a pas ete saisie";
	    if ((jour.length != 2) || (mois.length != 2) || (annee.length != 4)) {
		    returnString="La date doit être saisie sous le format jj/mm/aaaa.";
	    }
	    if (jour<1 || jour>31)
		    returnString="Le numéro de jour est incohérent (doit être compris entre 1 et 31)...";
	    if (!returnString && (mois<1 || mois>12) )
		    returnString="Le numéro du mois est incohérent (doit être compris entre 1 et 12)...";
	    if (!returnString && (jour==31 && (mois==2 || mois==4 || mois==6 || mois==9  || mois==11))) 
		    returnString="Il n'y a pas 31 jours dans ce mois...";
	    if (!returnString && (jour==30 && mois==2))
		    returnString="Cette date n'existe pas (maximum 29 jours en Fevrier)...";
	    if (annee>2100)
		returnString="La date doit être antérieure au 01/01/2100";
	    if (!returnString && (jour==29 && mois==2 && (annee % 400) !=0 &&
		    ((annee % 4) !=0 || (annee % 100)==0)))
		    returnString="Cette date n'existe pas,ce n'est pas une annee bissextile...";
	    }
	    return returnString;
}

function stringTokenizer(separator,checkString){
	var result=new Array();
	var index=checkString.indexOf(separator);
	var tmpString=checkString ;
	var cuttedString,lastIndex=0;
	var tabIndex=0;
	while( index>0) {
		cuttedString=tmpString.substring(lastIndex,index);
		if (cuttedString.length>0) {
			result[tabIndex++]=cuttedString;
		}
		tmpString=tmpString.substring(index+1,tmpString.length);
		index=tmpString.indexOf(separator);
	}
	if (tmpString.length>0) {
		result[tabIndex++]=tmpString;
	}
	return result;
}

function formatDateString(string,format,formatSeparator){
	var ch="",index=0,index2=0,annee="";
	var formatTab=stringTokenizer(formatSeparator,format);
	for (i=0; i<formatTab.length; i++){
		index2=index2 + parseInt(formatTab[i],10);
		ch+=string.substring(index,index2);
		if (i<formatTab.length-1)
			ch+=formatSeparator;	
		index=index + parseInt(formatTab[i],10);
	}
	return ch;
}

function numberFromString(theString){
	newString=""; 
	count=0;         
	for (i=0; i<theString.length; i++) {
		ch=theString.substring(i,i+1);
		if (ch>="0" && ch<="9") {
			newString +=ch;
		}
	}
	return newString;
}

function stringFromString(theString){
	newString=""; 
	count=0;         
	for (i=0; i<theString.length; i++) {
		ch=theString.substring(i,i+1);
		if (ch>="a" && ch<="z") {
			newString +=ch;
		}
	}
	return newString;
}

function computeAgeFromString(string){
	var today=new Date();
	var dateTab=stringTokenizer("/",string);
	if (dateTab.length<2)
		return "";
	else {
		var tmpDate=dateWithString(dateTab[0]+"/"+dateTab[1]+"/"+yearForDate(today));
		var todayYear=yearForDate(today);

		if (dateEarlierThanToday(dateDescription (tmpDate))==true)
			return (todayYear-parseInt(dateTab[2],10));
		else 
			return (todayYear-(parseInt(dateTab[2],10)))-1;
	}
	return "";
}

function computeDnaFromAge(age){
	var today=new Date();
	var annee=(yearForDate(today)-age);
	return "01/01/"+annee;
}

function dateEarlierThanToday(dateString){
	var dateTab=stringTokenizer("/",dateString);
	if (dateTab.length<2)
		return null;
	else {
		var today=new Date();
		var todayStr=dateDescription (today);

		return  dateEarlierThan(dateString,todayStr);
	}
}

function dateEarlierThan(date1,date2){
	var dateObj1=dateWithString(date1);
	var dateObj2=dateWithString(date2);
	if (dateObj1==null || dateObj2==null)
		return null;
	else {
		var year1=yearForDate(dateObj1);
		var year2=yearForDate(dateObj2);

		if ((year2-year1)<0)
			return false;
		if ((year2-year1)>0)
			return true;
		if ((year2-year1)==0) {
			if ((parseInt(dateObj1.getMonth(),10)-parseInt(dateObj2.getMonth(),10))<0)
				return true;				
			if ((parseInt(dateObj1.getMonth(),10)-parseInt(dateObj2.getMonth(),10))>0)
				return false;				
			if ((parseInt(dateObj1.getMonth(),10)-parseInt(dateObj2.getMonth(),10))==0){
				if ((parseInt(dateObj1.getDate(),10)-parseInt(dateObj2.getDate(),10))<0)
					return true;						
				if ((parseInt(dateObj1.getDate(),10)-parseInt(dateObj2.getDate(),10))>0)
					return false;				
				if ((parseInt(dateObj1.getDate(),10)-parseInt(dateObj2.getDate(),10))==0)
					return null;
			}
		}
	return true;
	}
}

function dateDescription(aDate){
	var todayYear = yearForDate(aDate);
        var jour = aDate.getDate();
        var mois = parseInt(aDate.getMonth(),10) + 1;

	if ( jour < 10 ) {
	  jour = "0" + jour.toString(); 
	} else {
	  jour = jour.toString(); 
	}

	if ( mois < 10 ) {
	  mois = "0" + mois.toString(); 
	} else {
	  mois = mois.toString(); 
	}

	return jour + "/" + mois + "/" + todayYear;
	//return ( aDate.getDate()+"/"+(parseInt(aDate.getMonth(),10) + 1)+"/"+todayYear);
}

function timeDescription(aDate){
        var heure = aDate.getHours();
        var minute = aDate.getMinutes();

	if ( heure < 10 ) {
	  heure = "0" + heure.toString(); 
	} else {
	  heure = heure.toString(); 
	}

	if ( minute < 10 ) {
	  minute = "0" + minute.toString(); 
	} else {
	  minute = minute.toString(); 
	}

	return heure + ":" + minute;
}

function dateWithString(dateStr){
	var dateTab=stringTokenizer("/",dateStr);
	if (dateTab.length<2)
		return null;
	var returnValue=new Date(parseInt(dateTab[2],10),(parseInt(dateTab[1],10)-1),parseInt(dateTab[0],10),10);
	return returnValue;
}

function yearForDate(date){

	var versionNavigateur = parseFloat(navigator.appVersion.substr(0,3));

	if ( versionNavigateur >= 4.5 ) {
		 return date.getFullYear();
	}
	else{
		var year=parseInt(date.getYear(),10);
		if (year<100)
			year=year + 1900;	
		return year;
	}

}

/*
Fonction qui ajoute a checkDate le test de la date butoire aujourd hui
*/
function checkDateBeforeToday(checkString)
{
//java.lang.System.out.println( "CheckDate checkDateBeforeToday  .");
	var newString = checkDate(checkString);
	if(newString !="") {
		var test = dateEarlierThanToday(newString);
		if ( test != false )
			return newString;		
		else {
			alert("Date de résultat postérieure à aujourd'hui !");
			newString = "";
		}
	}
	return newString;		
}

function checkDateNaissance(checkString)
{
	var newString = checkDate(checkString);
	if(newString !="") {
		var test = dateEarlierThanToday(newString);
		if ( test != false )
			return newString;		
		else {
			alert("Date de naissance postérieure à aujourd'hui !");
			newString = "";
		}
	}
	return newString;		
}

function checkDateAfterToday(checkString)
{
//java.lang.System.out.println( "CheckDate checkDateAfterToday  .");
	var newString = checkDate(checkString);
	if (newString !="") {
		if (dateEarlierThanToday(newString) != true)
			return newString;		
		else {
			alert("Cette date ne peut être antérieure à aujourd'hui !");
			newString = dateDescription( new Date() );
		}
	}
	return newString;	
}

function checkTimeElement(anElement)
{
	var newString = numberFromString(anElement.value);
	if ( newString.length == 0 ) return "";
	if ( newString.length == 1 ) newString = "0" + newString + "00";
	if ( newString.length == 2 ) newString = newString + "00";
	if ( newString.length == 3 ) var newString = "0" + newString;
	if ( newString.length > 4  ) return "";

	if (parseInt(newString.substring(0, 2),10) > 23) {
		alert("L'heure est un nombre compris entre 0 et 23");
		anElement.focus();
		return "";
	}
	if (parseInt(newString.substring(2, 4),10) > 59) {
		alert("Pour indiquer des minutes utiliser un nombre compris entre 0 et 59");
		anElement.focus();
		return "";
	}

	return formatDateString(newString,"2:2",":");		
}

function checkTime(checkString)
{
//java.lang.System.out.println( "CheckDate checkTime  .");
	var newString = numberFromString(checkString);
	if ( newString.length == 0 ) return "";
	if ( newString.length == 1 ) newString = "0" + newString + "00";
	if ( newString.length == 2 ) newString = newString + "00";
	if ( newString.length == 3 ) var newString = "0" + newString;
	if ( newString.length > 4  ) return "";

	if (parseInt(newString.substring(0, 2),10) > 23) {
		alert("L'heure est un nombre compris entre 0 et 23");
		return "";
	}
	if (parseInt(newString.substring(2, 4),10) > 59) {
		alert("Pour indiquer des minutes utiliser un nombre compris entre 0 et 59");
		return "";
	}

	return formatDateString(newString,"2:2",":");		
}


/******************************************************************/
/* Fonctions utilisées dans le sous projet Personnes              */
/******************************************************************/

/* Fonction qui enleve les characteres dans une chaines de nombre */
function checkCP( checkString )
{
	newString = ""; 
	count = 0;         
	for (i = 0; i < checkString.length; i++) {
		ch = checkString.substring(i, i+1);
		if (ch >= "0" && ch <= "9") {
			newString += ch;
		}
	}

	return newString;
}

function checkCPElement( anElement )
{
	return checkCPDepartementElement( anElement , 5 );
}

function checkDepartementElement( anElement )
{
	return checkCPDepartementElement( anElement , 2 );
}

function checkCPDepartementElement( anElement , minLength )
{
	newString = ""
	checkString = anElement.value;
	isValid = true;
	count = 0;         
	for (i = 0; i < checkString.length; i++) {
		ch = checkString.substring(i, i+1);
		if (ch >= "0" && ch <= "9") {
			newString += ch;
		}
		else {
			isValid = false;
			break;
		}
	}

	if ( ( isValid == false ) || ( newString.length < minLength ) )
	{
		alert("ERREUR : Le code postal n'est pas valide.\nVeuillez ressaisir la valeur");
		anElement.value = '';
	}

	return newString;
}


/* Fonction qui formatte le numéro de telephone 00 00 00 00 00*/
function formatPhoneNumber(checkString)
{
	newString = ""; 
	count = 0;         
	for (i = 0; i < checkString.length; i++) {
		ch = checkString.substring(i, i+1);

		newString += ch;
		count++;
		if (count==2 && i < checkString.length-1) {
			count=0;
			newString += " "	
		}
	}
	return newString;
}

/* Fonction qui en plus de reformatter le numéro, supprime les caracteres indesirables */
function checkPhone(checkString)
{
	newString = ""; 
	count = 0;
	
	for ( i = 0; i < checkString.length; i++ ) {
		
		ch = checkString.substring(i, i+1);

		if ( ch >= "0" && ch <= "9" ) {
			newString += ch;
			count++;
		}
		if ( count==2 && i < checkString.length-1 ) {
			count=0;
			newString += " "	
		}
	}
	return newString;
}

function checkPhoneElementWithFormat(anElement) {

    //alert("checkPhoneElementWithFormat : " + anElement.value );

	newString = checkPhoneElement(anElement);

    //alert("checkPhoneElementWithFormat : " + newString );

    anElement.value = formatPhoneNumber( newString );		

	return newString;
}

function checkPhoneElement( anElement ) {

	newString = "";
	checkString = anElement.value;
	isValid = true;
	count = 0;

    //alert("checkPhoneElement : " + checkString );
	
    checkString = removeAllSpace( checkString );

	for (i = 0; i < checkString.length; i++) {

		ch = checkString.substring(i, i+1);

		if ( ( ch >= "0" ) &&( ch <= "9" ) ) {
			newString += ch;
			count++;
		}
		else {
			isValid = false;
			break;
		}
	}
	
    //alert("isValid : " + isValid + " : newString.length : " + newString.length );

	//10 minimum si pas de format
	if ( ( isValid == false ) || ( newString.length < 10 ) )
	{
		alert("ERREUR : Le numéro de téléphone n'est pas valide.\nVeuillez ressaisir la valeur");
		newString = '';
	}
	else 
	{
		newString = checkString.substring( 0 , 14 );
	}

	anElement.value = newString;		

	return newString;
}

function checkMobilPhoneElement(anElement) {

	newString = checkPhone(anElement.value);
	deuxPremierChiffre = newString.substring(0, 2);

	if ( deuxPremierChiffre != '06' )
	{
		alert("ERREUR : Le numero de portable ne commence pas par 06.\nVeuillez ressaisir la valeur");
		anElement.value = '';
		newString = '';

		return newString;
	}

	if ( newString.length < 14 )
	{
		alert("ERREUR : Le numéro de portable n'est pas valide.\nVeuillez ressaisir la valeur");
		anElement.value = '';
		newString = '';
	}
	else {
		anElement.value = newString;		
	}

	return newString;
}

/* Fonction qui verife l'integriter de l age  et met a jour le champ dna*/
function checkAgeAndUpdateDna(ageStr,page)
{
	var dnaElement = page.forms[0].elements["dna"];
	var ageNumber = parseInt(ageStr);
	if(ageNumber < 130 && ageNumber > 0){
		dnaElement.value = computeDnaFromAge(ageStr);
		}
	else {
		dnaElement.value = "";
		ageStr = "";
	}
	return ageStr;		
}
/* Fonction qui verifie l'integriter de la dna  et met a jour le champ age */
function checkDateAndUpdateAge(checkString,page)
{
	var newString = checkDate(checkString);

	var ageElement = page.forms[0].elements["age"];
	var today = new Date();

	if(newString !="") {
		if (dateEarlierThanToday(newString) != false) {
			var startDate = new Date((yearForDate(today) - 130), today.getMonth(), today.getDate());
			if (dateEarlierThan(newString, dateDescription (startDate)) != false) {
				var alertString = "La date définie dans cette rubrique est antérieure au minimum autorisé:"+ dateDescription(startDate);
			alert(alertString);
			newString = "";
			ageElement.value = "";
			}
			else {
				var age = computeAgeFromString(newString);
				if (age >=0)
					ageElement.value = age;
				else 
					ageElement.value = 0;
			}
		}
		else {
			var alertString = "La date définie dans cette rubrique est postérieure au maximum autorisé:"+ dateDescription(today);
			alert(alertString);
			newString = "";
			ageElement.value = "";
		}
	}
	else {
		ageElement.value = "";
	}
	return newString;		
}
/* Fonction qui ajoute a checkDate le test de la date butoire aujourd hui */
function checkDateLocal(checkString)
{

	var newString = checkDate(checkString);

	if(newString !="") {
		if (dateEarlierThanToday(newString) != true){
			alert("Date postérieure à aujourd'hui !");
			newString = "";
		}
	}
	return newString;		
}

function verifierLongueurTexte(chaine,maximum)
{
  if ( chaine.length > maximum ) {
    var resultat=chaine.substring(0,maximum);
    alert("Le texte a du être tronqué : "+ maximum +" caractères au maximum");
    return resultat;
  }
  else {
    return chaine;
  }
}

function testLongueurTexte(chaine,maximum)
{
  if ( chaine.length > maximum ) {
    var resultat=chaine.substring(0,maximum);
    alert("Votre texte contient " + chaine.length + "caractères. " + maximum + " caractères maximum sont autorisés.");
    return false;
  }
  else {
    return true;
  }
}

function checkEmail(anElement) {

	if ( (anElement.value !="") && (anElement.value.indexOf("@") !="-1") && (anElement.value.indexOf(".") !="-1"))
	{
		return anElement.value;
	}
	else
	{
		alert("L'adresse éléctronique est non valide.\nVeuillez ressaisir sa valeur");
		anElement.focus();
		return "";
	} 
}

function replaceFirstInstanceOfString(s,s1,s2)
{
        var i = 0;
        var sBuffer;

        if (s != null )
        {
            i = s.indexOf(s1);
            if ( i != -1 )
            {
               sBuffer = s.substring(0, i);

                if( s2 != null )
                {
                    sBuffer = sBuffer + s2;
                }

                sBuffer = sBuffer + s.substring( i + s1.length, s.length );
            }
            if (sBuffer == null) {
                return s;
            }
            else {
                return sBuffer;
            }
        }
        else {
            return s;
        }
}

function removeAllSpace( s )
{

  while( s.indexOf( " " ) != -1  ) {
    s = replaceFirstInstanceOfString( s , " " , "" )
  }

  return s;
}

// vérifie que le nombre maxi n'a pas été atteint pendant que l'utilisateur reste appuyé sur la touche
function verif_press(textarea,max,count) 
{
  if ( textarea.value.length > max - 1 ) { //s'il dépasse la taille requise, on sort
    alert('Vous ne pouvez rentrer que '+ max +' caractères maximum pour la zone : '+ textarea.name + ' .');
    //textarea.value = textarea.value.substring( 0 , max );
    //show_nb_car(textarea,max,count);
    return false;
  }
  else { // sinon
    count.value = max - textarea.value.length; // on met à jour le champs de contrôle.
    return true;
  }
}

// textarea est la référence du TEXTAREA à contrôler, max en est la valeur maximal, pour cette fonction count n'est pas inclu
// car lorsqu'elle est appellée, le nombre de caractère a déja été inscrit lors de l'évenement "onkeyup"
// vérifie que le nombre maxi n'a pas été atteint lorsque l'utilisateur sort du champs
function verif_change(textarea,max) 
{
  if ( textarea.value.length > max ) { // s'il dépasse la taille requise, on prévient et on sort
    alert('Vous ne pouvez rentrer que '+ max +' caractères maximum pour la zone : '+ textarea.name + ' .');
    //textarea.value = textarea.value.substring( 0 , max );
    return false;
  }
  else {
    return true; // sinon, on continu
  }
}

// textarea est la référence du TEXTAREA à contrôler, count est la référence
// du champs texte de contrôle où s'affichera le nombre de caractère en cour. Cette fonction est appelée lors de l'évenement "onkeyup"
function show_nb_car(textarea,max,count)
{
  count.value = max - textarea.value.length;
  return true;
}



