/*
 * Valide une adresse email
 */
function validEmail(adr){
	var reg = new RegExp("^(([a-z0-9\-_]+)((\.[a-z0-9\-_]+)*)@([a-z0-9\-_]+)((\.[a-z0-9\-_]+)+))$","i");
	return reg.test(adr);
}

function validhttpaddress(a){
	// Retourne vrai si a est une adresse http valide (http://...)
	var reg = new RegExp( "^((http|ftp)://([a-z0-9\-\./]+))$", "i" );
	return reg.test(a);
}

/*
 * Supprime les caractères espace, retour chariot et newline
 * en début et fin de chaîne.
 */
function trim(str){
	str = str.replace( /^([\s]+)/g, '' ); // Supprime les caractères non-imprimables de début de chaîne
	str = str.replace( /([\s]+)$/g, '' ); // Supprime les caractères non-imprimables de fin de chaîne
	return str;
}

/*
 *	Complète une chaîne à gauche avec le caractère de complétion.
 *	Si aucun caractère de complétion n'est précisé, complète avec des espaces
 */
function lpad(str,padlength,padstr){
	var l = str.length;
	if( l<padlength ){
		pad = padstr=='undefined' ? ' ' : padstr;
		for( var i=0; i<padlength-l; i++ )
			str = pad + str;
	}
	return str;
}

/*
 *	Complète une chaîne à droite avec le caractère de complétion.
 *	Si aucun caractère de complétion n'est précisé, complète avec des espaces
 */
function rpad(str,padlength,padstr){
	var l = str.length;
	if( l<padlength ){
		pad = padstr=='undefined' ? ' ' : padstr;
		for( var i=0; i<padlength-l; i++ )
			str += pad;
	}
	return str;
}

/*
 *	Vérifie qu'une chaîne décrit un nombre a virgule flottante valide
 * 	les séparateurs de décimale sont la virgule et le point
 */
function validfloat(ch){
	var reg = new RegExp("^([0-9]+((\.|,)[0-9]+)?)$");
	return reg.test(ch);
}

/*
 *	Vérifie qu'une chaîne contient un nombre entier valide
 * 	les séparateurs de décimale sont la virgule et le point
 */
function validint(ch){
	var reg = new RegExp("^(([\+\-]?)([0-9]+))$");
	return reg.test(ch);
}

/*
 *	Vérifie qu'une chaîne contient un nombre entier valide
 * 	les séparateurs de décimale sont la virgule et le point
 */
function validunsignedint(ch){
	var reg = new RegExp("^(([0-9]+))$");
	return reg.test(ch);
}


/*
 *	Vérifie qu'une chaîne contient une date au format
 *	jj/mm/aaaa ou jj-mm-aaaa
 */
function validdate(ch){
	var reg = new RegExp("^([0-3][0-9](-|/)[0-1][0-9](-|/)([0-9]{4}))$");
	var valid = reg.test(ch);
	if( valid ){
		var day = parseInt(ch.substr(0,2));
		var month = ch.substr(3,1)=='0' ? parseInt(ch.substr(4,1)) : parseInt(ch.substr(3,2));
		if( month<=7 )
			valid = month%2==1 ? day<=31 : day<=30;
		else
			valid = month%2==0 ? day<=31 : day<=30;
		if( valid && month==2 ){
			var year = parseInt(ch.substr(6,4));
			valid = year%4==0 ? day<=29 : day<=28;
		}
	}
	return valid;
}

/*
 *	Vérifie qu'une chaîne contient une heure
 *	au format 24:00
 */
function validheure(ch){
	var reg = new RegExp("^([0-2][0-9]:[0-6][0-9](:[0-6][0-9])?)$");
	return reg.test(ch);
}

/*
 *	Vérifie qu'une chaîne contient un code postal
 */
function validcodepostal(ch){
	var reg = new RegExp("^((2A|2B|([0-9]{2}))([0-9]{3}))$","i");
	return reg.test(ch);
}

/*
 *	Vérifie qu'une chaîne contient un numéro siret valide
 */
function validsiret(ch){
	var reg = new RegExp("^([0-9]{14})$");
	return reg.test(ch);
}

/*
 *	Vérifie qu'une chaîne contient un numéro ape-naf valide
 */
function validape(ch){
	var reg = new RegExp("^(([0-9]{3})[a-z])$","i");
	return reg.test(ch);
}

/*
 *	Vérifie qu'une chaîne contient un sigle valide (propre au tourisme)
 */
function validsigle(ch){
	var reg = new RegExp("^(([0-9a-z])+)$","i");
	return reg.test(ch);
}

/*
 *	Vérifie qu'une chaîne contient un nombre hexadécimal
 */
function validhexa(ch){
	var reg = new RegExp("^([0-9A-F]+)$","i");
	return reg.test(ch);
}

/*
 *	Vérifie qu'une chaîne contient une couleur au format hexadécimal
 */
function validhexacolor(ch){
	var reg = new RegExp("^([0-9A-F]{6})$","i");
	return reg.test(ch);
}

/*
 *	Vérifie qu'une chaîne ne contient que des lettres et des chiffres
 */
function validalphanum(ch){
	var reg = new RegExp("^([a-z0-9]+)$","i");
	return reg.test(ch);
}

/*
 * Vérifie qu'une chaîne ne contient que des lettres
 */
function validalpha(ch){
	var reg = new RegExp("^([a-z]+)$","i");
	return reg.test(ch);
}

/*
 * Vérifie qu'une chaîne représente une heure valide
 */
function validtime(ch){
	var reg = /^([0-9]{1,2}):([0-9]{2})$/g;
	var res = reg.exec(ch);
	if( !res ) return false;
	
	return parseInt(res[1])<=24 && parseInt(res[2])<60;
}

/*
 * Utilitaires Divers
 */

function insertSorted(select,opt){
	// Insère une option dans une zone de liste de manière triée (sur le libellé)
  
	// Recherche le point d'insertion
	var found = false;
	var i = 0;
	while( i<select.options.length && !found ){
		if( strComp(select.options[i].text,opt.text)==1 )
			found = true;
		else
			i++;
	}
  
	if( found ){
		// Décale les éléments de la liste pour laisser la place au nouveau
		var j;
		for( j=select.options.length-1; j>=i; j-- ){
			select.options[j+1] = new Option( select.options[j].text, select.options[j].value );
		}
	}
  
	// Insère l'élément
	select.options[i] = opt;
	return i; // Retourne le point d'insertion
}

function strComp(str1,str2){
	var res = 0;
	
  // Fonction de comparaison de chaîne optimisée, comportement semblable à strcomp en C
  
	// Recherche la première différence entre les deux chaines
	i = 0;
	while( i<str1.length && i<str2.length && res==0 ){
		if( str1.charCodeAt(i) < str2.charCodeAt(i) )
			res = -1;
		else
			if( str1.charCodeAt(i) > str2.charCodeAt(i) )
				res = 1;
			else
				i = i + 1;
	}
  
	if( res!=0 )
		return res;
	else
		if( str1.length==str2.length )
			return 0;
		else
			if( str1.length<str2.length )
				return -1;
			else
				return 1;
}

//
//	Formate une heure
// 

function format_time(val){
	val = val.replace( / |\xA0/g, '' );
	var reg = /^([0-9]{1,2})(:[0-9]{2})?(:[0-9]{2})?$/g;
	var res = reg.exec( val );
	if( !res ) return val;
	
	if( res[3] )
		return lpad(res[1],2,'0') + res[2] + res[3];
	else if( res[2] )
		return lpad(res[1],2,'0') + res[2];
	else
		return lpad(res[1],2,'0') + ':00';
}

//
// Formate un nombre. decimals spécifie le nombre de décimales, thousands_sep est
// une chaîne contenant le séparateur de milliers
//
function format_number(nbr,decimals,thousands_sep){

	var formated = new String( nbr );

	if( nbr!='' ){
		formated = formated.replace( / |\xA0/g, '' );
		formated = formated.replace( ',',  '.' );
		if( !isNumeric(formated) )
			return 'Erreur';
		var origin = formated;
		
		if( decimals && decimals<0 ) decimals = 0;
			origin = formated = round_decimal( formated, decimals ).toString();
		
		if( formated!='' ){
			var entier = parseInt( formated );
			if( !isNaN(entier) ){
				if( thousands_sep && thousands_sep!='' ){
					// Insertion du séparateur de milliers
					var strInt = new String( entier );
					var strTemp = '';
					var l = strInt.length;
					var p = 1;
					for( var i=l-1; i>=0; i-- && p++ )
						if( p%3==0 && p!=l )
							strTemp = thousands_sep + strInt.substr( i, 1 ) + strTemp;
						else
							strTemp = strInt.substr( i, 1 ) + strTemp; 
					formated = strTemp;
				}
				if( decimals>0 ){
					var p = origin.indexOf( '.' );
					if( p==-1 ) p = origin.indexOf( ',' );
					var strFloat = '';
					if( p!=-1 ) {
						strFloat = origin.slice( p+1 );
						if( strFloat.length>decimals )
							strFloat = strFloat.substr(0,decimals);
					}
					strFloat = rpad( strFloat, decimals, '0' );
					formated += ',' + strFloat;
				}
			}
		}	
	}
	
	return formated;
}

// Retourne vrai si une chaîne représente un nombre entier.
function isInteger(str){
	return str.match(/^[0123456789]*$/);
}

// Retourne vrai si une chaîne contient un nombre
function isNumeric(str){
	return str.match( /^-?[0-9]*(\.[0-9]*)?$/ );
}

//	Formate une date au format jj/mm
function format_date_short(sDate){
	var formated = '';
	sDate = trim(sDate);
	if( sDate!='' ){
		var comp = sDate.split( '/' );
		
		// Vérifie que chacun des éléments est numérique
		for( var i=0; i<comp.length; i++ ){
			if( !isInteger( comp[i] ) )
				return 'Erreur';
		}
		
		var day = '';
		var month = '';
		if( comp.length==1 ){
			// La chaîne ne contient pas de séparateur
			if( sDate.length==3 ){
				day = lpad( sDate.substr(0,1), 2, '0' );
				month = sDate.substr(1,2);
			}else if( sDate.length==4 ){
				day = sDate.substr(0,2);
				month = sDate.substr(2,2);
			}else{
				formated = 'Erreur';
			}
		}else if( comp.length==2 ){
			day = lpad( comp[0], 2, '0' );
			month = lpad( comp[1], 2, '0' );
		}
		if( !day.match( /^01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31$/ ) )
			formated = 'Erreur';
		else if( !month.match( /^01|02|03|04|05|06|07|08|09|10|11|12$/ ) )
			formated = 'Erreur';
		else
			formated = day + '/' + month;
	}
	return formated;
}

function createPassword(length){
	if( !length )
		length = 6;
	// Crée un mot de passe aléatoire
	var chars = 'abcdefghijklmnopqrstuvwxyz1234567890';
	var pwd = '';
	for( var i=0; i<length; i++ )
		pwd += chars.substr( Math.round( chars.length * Math.random() ), 1 );
	return pwd;
}
