/* Fonctions JavaScript pour les formulaires */


//Active/désactive l'affichage automatique des erreurs
var bool_disp=true;

//Effectue l'affichage adéquat en fonction du champ
function display_verif(img, mess, img_alt, zindex)
{
	//Message d'erreur, alors affichage de la croix + bulle d'aide
	if(mess.length>0)
	{
		img.style.display='block';
		if(!zindex)
			img.onmouseover=function () { show(mess); } 
		else
			img.onmouseover=function () { show(mess,zindex); } 
		img.onmouseout=function () { hide(); }
		img.src="img/form_no.gif";
		
		//Bulle d'erreur statique affichée pendant 2 secondes
		if(bool_disp)
		{
			if(!zindex)
				show_static(mess,pos_x(img)+img.clientWidth+1,pos_y(img)+img.clientHeight+1);
			else
				show_static(mess,pos_x(img)+img.clientWidth+1,pos_y(img)+img.clientHeight+1,null,zindex);
		}

		return false;
	}
	else if(img_alt)
	{
		if(!zindex)
			img.onmouseover=function () { show('<img src="'+img_alt+'"/>'); } 
		else
			img.onmouseover=function () { show('<img src="'+img_alt+'"/>',zindex); } 
		img.style.display='block';
		//img.onmouseover=function () { show('<img src="'+img_alt+'"/>'); } 
		img.onmouseout=function () { hide(); }
		img.style.cursor="default";
		img.src=img_alt;
		return false;
	}
	
	//Pas d'erreur
	img.style.display='none';
	img.onmouseover=function () {}
	img.onmouseout=function () {}
	//img.src="img/form_ok.gif";
	img.style.cursor="default";
	return true;
}

//Vérifcation d'un formulaire de connexion
function verif_form_login()
{
	var bool=true;
	
	if(!verif_vide(get_id('pass')))
		bool=false;
	if(!verif_vide(get_id('login')))
		bool=false;
	
	return bool;
}

//Vérification d'un champ vide
function verif_vide(chp)
{
	var val=rem_spec(chp.value);
	chp.value=val;
	
	var re=/^ +$/gi;
	if(val.length<1 || val.match(re))
		return display_verif(get_id('img_'+chp.name),'Champ non renseigné.');
	else
		return display_verif(get_id('img_'+chp.name), '');
}
//Vérification d'un champ vide avec div d'auto-completion
function verif_vide_ac(chp, ac)
{
	if(ac.style.display=='block')
		return;
		
	var val=rem_spec(chp.value);
	chp.value=val;
	
	var re=/^ +$/gi;
	if(val.length<1 || val.match(re))
		return display_verif(get_id('img_'+chp.name),'Champ non renseigné.');
	else
		return display_verif(get_id('img_'+chp.name), '');
}
//Vérification d'un text area
function verif_textarea(chp)
{
	var val=chp.value;
	
	if(val.length<1)
		return display_verif(get_id('img_'+chp.name),'Champ non renseigné.');
	else
		return display_verif(get_id('img_'+chp.name), '');
}
//Vérification d'un Rich Text Editor
function verif_RTE(val,chp)
{
	if(val.length<1 || val=="<br>")
		return display_verif(get_id('img_'+chp),'Champ non renseigné.');
	else
		return display_verif(get_id('img_'+chp), '');
}
//Vérification d'un champ vide (formu RTE)
function verif_vide_rte(chp)
{
	var val=rem_spec(chp.value);
	chp.value=val;
	
	var re=/^ +$/gi;
	if(val.length<1 || val.match(re))
		return display_verif(get_id('img_'+chp.name),'Champ non renseigné.', null, 9999);
	else
		return display_verif(get_id('img_'+chp.name), '');
}
//Vérifie la validité d'une date
function verif_date(chp)
{
	verif_champ("blur",'date',chp);
	var date=chp.value;
	
	var re = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;

	if(date.length==0)
		return display_verif(get_id('img_'+chp.name), 'Champ non renseigné.');
	else if(date.length < 10)
		return display_verif(get_id('img_'+chp.name), 'Date incomplète.');
	else if(!date.match(re))
		return display_verif(get_id('img_'+chp.name), 'Date incorrecte.');
	else
		return display_verif(get_id('img_'+chp.name), '');
}
//Vérifie la validité d'une heure
function verif_heure(chp, chp2, tape)
{
	var ret=true;
	verif_champ("blur",'heure',chp);
	if(chp2)
		verif_champ("blur",'heure',chp2);
		
	if(chp.value.length>0 || !tape)
	{
		var heure=chp.value;
		
		var re = /(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23)[:](0|1|2|3|4|5)\d{1}/;
	
		if(heure.length==0)
			ret=display_verif(get_id('img_'+chp.name), 'Champ non renseigné.');
		else if(heure.length < 5)
			ret=display_verif(get_id('img_'+chp.name), 'Heure incomplète.');
		else if(!heure.match(re))
			ret=display_verif(get_id('img_'+chp.name), 'Heure incorrecte.');
		else
			display_verif(get_id('img_'+chp.name), '');
	}
		
	if(chp2 && (chp2.value.length>0 || !tape))
	{
		heure=chp2.value;
		if(heure.length==0)
			ret=display_verif(get_id('img_'+chp2.name), 'Champ non renseigné.');
		else if(heure.length < 5)
			ret=display_verif(get_id('img_'+chp2.name), 'Heure incomplète.');
		else if(!heure.match(re))
			ret=display_verif(get_id('img_'+chp2.name), 'Heure incorrecte.');
		else if(parseInt(chp.value.replace(/[^0-9]/g,''))>=parseInt(chp2.value.replace(/[^0-9]/g,'')))
			ret=display_verif(get_id('img_'+chp2.name), 'Heure de fin antérieure à heure de début.');
		else
			display_verif(get_id('img_'+chp2.name), '');
	}
	
	return ret;
}

//Vérification du mail
function verif_mail(chp, chp2)
{
	var ret=true;
	var mail = chp.value;
	
	if(mail.length<1)
		ret=display_verif(get_id('img_'+chp.name),'Champ non renseigné.');
	else if(!verif_syntaxe(mail))
		ret=display_verif(get_id('img_'+chp.name),'Format d\'email non valide ou contenant des caractères illégaux ( ex : [ ] ; # & ! * \' " < > % ( ) { } ? \\ ).');
	else if(verif_domaine(mail)!="")
		ret=display_verif(get_id('img_'+chp.name),'Nom de domaine '+verif_domaine(mail));
	else
		ret=display_verif(get_id('img_'+chp.name),'');
		
	if(chp2 && ret==true)
	{
		val=chp2.value;
		if(val.length<1)
			ret=display_verif(get_id('img_'+chp2.name),'Champ non renseigné.');
		else if(val!=chp.value)
			ret=display_verif(get_id('img_'+chp2.name), 'Les mails ne correspondent pas.');
		else
			ret=display_verif(get_id('img_'+chp2.name), '');
	}
	
	return ret;
}
function verif_mail2(chp)
{
	var ret=true;
	var mail = chp.value;
	
	if(mail.length<1)
		ret=display_verif(get_id('img_'+chp.name),'');
	else if(!verif_syntaxe(mail))
		ret=display_verif(get_id('img_'+chp.name),'Format d\'email non valide ou contenant des caractères illégaux ( ex : [ ] ; # & ! * \' " < > % ( ) { } ? \\ ).');
	else if(verif_domaine(mail)!="")
		ret=display_verif(get_id('img_'+chp.name),'Nom de domaine '+verif_domaine(mail));
	else
		ret=display_verif(get_id('img_'+chp.name),'');
		
	return ret;
}
//Vérification de la syntaxe générale de l'email
function verif_syntaxe(mail)
{
	var re=/^[a-z\d]+((\.|-|_)[a-z\d]+)*@((?![-\d])[a-z\d-]{0,62}[a-z\d]\.){1,4}.{1,}$/gi;
	return (mail.match(re)==mail);
} 
//Vérification du nom de domaine	 
function verif_domaine(mail)
{
	var re=/[a-z].*/gi;
	if(!mail.substr(mail.lastIndexOf(".") + 1).match(re))
		return 'contenant des caractères non autorisés.';
		
	re=/^(ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw|aero|arpa|biz|com|coop|edu|eu|gov|info|int|mil|museum|name|net|org|pro|jobs|travel)$/gi;
	if( (mail.substr(mail.lastIndexOf(".") + 1).match(re)!=null) == false)
	{
		if(mail.substr(mail.lastIndexOf(".") + 1).length<7)
			return '"'+mail.substr(mail.lastIndexOf(".") + 1)+'" inexistant.';
		else
			return 'trop long (max. 6 caractères).';
	}
	else return "";
}

//Vérification d'un mot de passe
function verif_mdp(chp, chp2)
{
	var ret=true;
	
	var val=chp.value;
	
	if(val.length<1)
		ret=display_verif(get_id('img_'+chp.name),'Champ non renseigné.');
	else if(val.length<4)
		ret=display_verif(get_id('img_'+chp.name),'Mot de passe trop court (au moins 4 caractères).');
	else
		ret=display_verif(get_id('img_'+chp.name), '');
		
	if(chp2 && ret==true)
	{
		val=chp2.value;
		if(val.length<1)
			ret=display_verif(get_id('img_'+chp2.name),'Champ non renseigné.');
		else if(val!=chp.value)
			ret=display_verif(get_id('img_'+chp2.name), 'Les mots de passe ne correspondent pas.');
		else
			display_verif(get_id('img_'+chp2.name), '');
	}
	
	return ret;
}

//Vérification d'un code postal
function verif_cp(chp)
{
	var cp=chp.value;
	
	if(cp.length<1 || cp.length==5)
		return display_verif(get_id('img_'+chp.name),'');
	else if(cp.length<5)
		return display_verif(get_id('img_'+chp.name),'Champ incomplet (5 chiffres).');
}

//Vérification d'un téléphone
function verif_tel(chp)
{
	verif_champ("blur",'tel',chp);
	var tel=chp.value;
	
	var re = /^(01|02|03|04|05|06|07|08|09)(([\-])?[0-9][0-9]){4}/;

	if(tel.length==0)
		return display_verif(get_id('img_'+chp.name), 'Champ non renseigné.');
	else if(tel.length < 14)
		return display_verif(get_id('img_'+chp.name), 'Téléphone incomplet.');
	else if(!tel.match(re))
		return display_verif(get_id('img_'+chp.name), 'Numéro de téléphone incorrect.');
	else
		return display_verif(get_id('img_'+chp.name), '');
}

//Vérification d'un âge
function verif_age(chp)
{
	var val=chp.value;
	
	if(val.length<1)
		return display_verif(get_id('img_'+chp.name),'Champ non renseigné.');
	else if(val<1)
		return display_verif(get_id('img_'+chp.name),'Veuillez entrer un âge correct.');
	else
		return display_verif(get_id('img_'+chp.name),'');
}

//Vérifiaction d'un doublon
function verif_doublon(val, table, champ)
{
	//Utilisation d'AJAX pour se connecter à la BDD
    var xhr_object = null;   
        
    if(window.XMLHttpRequest) // Firefox   
       xhr_object = new XMLHttpRequest();   
    else if(window.ActiveXObject) // Internet Explorer   
       xhr_object = new ActiveXObject("Microsoft.XMLHTTP");   
    else  // XMLHttpRequest non supporté par le navigateur   
       alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest.\nCertaines vérifications automatiques ne seront pas effectuées.");  
	   
	//Connection au fichier comportant la requete
	var adresse="js/requete_ajax_tableau.php";
	param="type=recup&table="+table+"&chp="+champ+"&where="+champ+"&like="+val+"&aleat="+Number(new Date());
		
    xhr_object.open("POST", adresse, false); 
    xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
	xhr_object.setRequestHeader("Content-length", param.length);
	//Transmet le mail entré par l'utilisateur
    xhr_object.send(param); 
		
	if(xhr_object.readyState==4)
	{
		if(xhr_object.status == 200) 
		{
			var ajax=xhr_object.responseXML;
			if(!ajax || ajax.length<1)
				return false;
			
			var tableau=new Array();
			var items = ajax.getElementsByTagName("xml_enrg");
			
			if(items.length>0)
				return true;
		}
		else
			alert("Erreur: "+xhr_object.status); 
	}
}

//Intercepte les caractères non autorisés dans le champ désigné
function scan_touche(evt,type) 
{
	var re_spec = /[\x00\x08\x0D]/;
	if(type=='date')
		var re_car = /[\d\-]/;
	else if(type=='heure')
		var re_car = /[\d\:]/;
	else if(type=='int')
		var re_car = /[\d]/;

	var key_pressed=code_touche(evt);
	var car = String.fromCharCode(key_pressed);
	var test = re_car.test(car) || re_spec.test(car);
	
	return test;
} 

//Vérifie les caractères tapés - apres le process_keypress
function verif_champ(evt,type,val)
{
	if(evt!="blur")
	{
		var key_pressed=code_touche(evt);
		//evite de perdre la position du focus sur les touches backspace, prec, suiv, suppr
		if(key_pressed == 8 || key_pressed == 37 || key_pressed == 39  || key_pressed == 46) 
			return;
	}
		
	var str=val.value;
	
	if(type=='prix')
	{
		str=str.replace(',','.');
		
		var tmp;
		var decim='';
		if(str.indexOf('.')!=-1)
		{
			tmp=str.substr(str.indexOf('.')+1);
			tmp=tmp.replace(/[^0-9]/g,'');
			if(tmp.length>2)
			{
				decim=tmp.charAt(2);
				tmp=tmp.substr(0,2);
			}
			if(str.indexOf('.')==0)
				str='0'+str;
			str=str.replace(/[^0-9\.]/g,'');
			str=parseFloat(str.substring(0,str.indexOf('.')))+'.'+tmp;
		}
		else if(str.length!=1)
			str=str.replace(/^0*/,'');
		
		str=str.replace(/[^0-9\.]/g,'');
		
		//Arrondi si plus de 2 décimales
		if(decim!='')
			str=Math.round(parseFloat(str+decim)*100)/100;
	}
	else if(type=='date')
	{
		if(str.match(RegExp("^[0-9]-$")))
			str='0'+str;
		else if(str.match(RegExp("[0-9]{2}-[0-9]-$")))
			str=str.substr(0,3)+'0'+str.substr(3);
		str=str.replace(/[^0-9]/g,'');
		
		var i=0;
		var tmp='';
        while(i < str.length) 
		{
			tmp+=str.charAt(i);
			if(i==1)
			{
				if(parseFloat(tmp)<1)
					tmp="01";
				else if(parseFloat(tmp)>31)
					tmp="31";
				tmp+='-';
			}
			else if(i==3)
			{
				if(parseFloat(tmp.substr(3))<1)
					tmp=tmp.substr(0,3)+"01";
				else if(parseFloat(tmp.substr(3))>12)
					tmp=tmp.substr(0,3)+"12";
				tmp+='-';
			}
			i++;	
		}	
		str=tmp.substr(0,10);
	}
	else if(type=="tel")
	{
		str=str.replace(/[^0-9]/g,'');
		
		var i=0;
		var tmp='';
        while(i < str.length) 
		{
			tmp+=str.charAt(i);
			if(i==1 || i==3 || i==5 || i==7 || i==9)
				tmp+='-';
			i++;	
		}	
		str=tmp.substr(0,14);
	}
	else if(type=="heure")
	{
		if(str.match(RegExp("^[3-9]$")))
			str='0'+str;
		else if(str.match(RegExp("^[0-9]:$")))
			str='0'+str;
		else if(str.match(RegExp("[0-9]{2}:[6-9]$")))
			str=str.substr(0,3)+'0'+str.substr(3);
		else if(evt=="blur" && str.match(RegExp("[0-9]{2}:[0-9]$")))
			str=str.substr(0,3)+'0'+str.substr(3);
		str=str.replace(/[^0-9]/g,'');
		
		var i=0;
		var tmp='';
        while(i < str.length) 
		{
			tmp+=str.charAt(i);
			if(i==1)
			{
				if(parseFloat(tmp)<0)
					tmp="00";
				else if(parseFloat(tmp)>23)
					tmp="23";
				tmp+=':';
			}
			else if(i==3)
			{
				if(parseFloat(tmp.substr(3))<0)
					tmp=tmp.substr(0,3)+"00";
				else if(parseFloat(tmp.substr(3))>59)
					tmp=tmp.substr(0,3)+"59";
				tmp+=':';
			}
			i++;	
		}	
		str=tmp.substr(0,5);
	}
	
	val.value=str;
}
