/* ======================================================================================*/
/*				 FONCTIONS GÉNÉRIQUES DE VALIDATION DE FORMULAIRE 						 */
/* ======================================================================================*/

//---------------------------------------------
// Empeche la saisie d'un caractere onKeypress
//----------------------------------------------
function empechechar()
{
	if( event.keyCode < 48 || event.keyCode > 57 )
 	{ 
 		alert(get_trad_champ("numeric") );
   		event.returnValue = false;
   	}
}

//-------------------------------------
// Permet la saisie d un chiffre
//-------------------------------------
function onlyNumber(evt)
{
 var charCode = (evt.which) ? evt.which : event.keyCode
 if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;

 return true;
}

//-------------------------------------
// Verifie la validite d'un email
//-------------------------------------
function isValidEmail ( _fieldId ) {
	
	var email = document.getElementById(_fieldId);		
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	if ( !filter.test(email.value) ) 
	{		
		return false;
	}
	else 
	{
		return true;
	}
}


//-------------------------------------
// Verifie la validite d'une date
//-------------------------------------
function isValidDate ( _fieldId )
{
    if ( _fieldId == "" )
        return true;

    // Récupération de la valeur
    var totalDate    = document.getElementById( _fieldId ).value;
    if ( totalDate == "" )
        return false;
   
    // Découpage de la date récupérée
    var aDate = totalDate.split( "/" );
    if ( aDate.length != 3 )
        return false;

    // Création d'un objet date
    var generatedDate = new Date ( aDate[ 2 ], aDate[ 1 ] - 1, aDate[ 0 ] );
   
    // Test
    if (     generatedDate.getFullYear() == aDate[ 2 ]
        &&    generatedDate.getMonth() + 1 == aDate[ 1 ]
        &&    generatedDate.getDate() == aDate[ 0 ] )
        return true;
   
    return false;
}


/* ======================================================================================*/
/*							 FONCTIONS GÉNÉRIQUES										 */
/* ======================================================================================*/

//--------------------------------------------------
// Verifie les champs obligatoire d'un formulaire
//--------------------------------------------------
valider_formulaire_generique = function () {

	var tab = valider_formulaire_generique.arguments;

	taille = tab.length;

	if ( taille > 0 ) {
		var nameForm = tab[0];
		
		for ( i = 1; i < taille; i++ ) {
			
			if ( tab[i] == "email" ) {				
				if ( !isValidEmail( tab[i] ) ) {
					inlineMsg ( tab[i], get_trad_champ( tab[i] ) );		
					return false; 
				}
			}
			else {			
				var field = document.forms[nameForm].elements[tab[i]];
				
				if ( ( field.value.trim() == ""	|| field.value.trim() == field.defaultValue ) ) {				
					inlineMsg ( tab[i], get_trad_champ( tab[i] ) );				
					field.select();
					return false; 
				}
			}
		
		}
		return true;
	}
	else {
		return false;
	}
}

String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g,"");
}


/* ======================================================================================*/
/*				 FONCTIONS D APPELS LIES AU PROJET				 						 */
/* ======================================================================================*/

// Création objet AJAX pour le rechargement des options
var xhr = null; 
	 
function getXhr(){

	if(window.XMLHttpRequest) // Firefox et autres
		xhr = new XMLHttpRequest(); 
	else if(window.ActiveXObject){ // Internet Explorer 
		try {
                	xhr = new ActiveXObject("Msxml2.XMLHTTP");
            	} catch (E) {
                	xhr = new ActiveXObject("Microsoft.XMLHTTP");
            	}
	}
	else { // XMLHttpRequest non supporté par le navigateur 
		//alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
	   	xhr = false; 
	} 
}


/**
 * Fonction de changement de devise
 */
function changeDevise()
{	
	xhr = null; 
	getXhr(); // cree un objet xhr si possible

	if(xhr != null)
	{
		// On defini ce qu'on va faire quand on aura la reponse
		xhr.onreadystatechange = function(){
			
			// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
			if(xhr.readyState == 4 && xhr.status == 200)
			{
				var reponseAjax = xhr.responseText;
				
				var reg=new RegExp("[|]+", "g");
				var tab_reponseAjax = reponseAjax.split(reg);
				if(tab_reponseAjax.length == 5)
				{
					$('span.'+tab_reponseAjax[1]+'').show();
					$('span.'+tab_reponseAjax[2]+'').hide();
					
					$('div.'+tab_reponseAjax[1]+'').show();
					$('div.'+tab_reponseAjax[2]+'').hide();
					
					
					if(document.getElementById(tab_reponseAjax[3]))
					{
						document.getElementById(tab_reponseAjax[3]).style.display = 'none';
					}
					
					if(document.getElementById(tab_reponseAjax[4]))
					{
						document.getElementById(tab_reponseAjax[4]).style.display = 'inline';
					}
				}
			}
		}
		xhr.open("POST","ajax/changeDevise.ajax.php",true);
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');		
		xhr.send();
	}
}

//Ouverture d'un programme dans le resultat d'un acces rapide
function openProgram(lotId)
{
	if(document.getElementById(lotId))
	{
		document.getElementById(lotId).style.display = 'block';
	}
}

//Fermeture d'un programme dans le resultat d'un acces rapide
function closeProgram(lotId)
{
	if(document.getElementById(lotId))
	{
		document.getElementById(lotId).style.display = 'none';
	}
}

function pagineResultatBudget(page)
{
	if(document.getElementById('page') && document.getElementById("pagination"))
	{
		document.getElementById('page').value	= page;
		document.getElementById("pagination").submit();
	}
}

function pagineResultatLivraison(page)
{
	if(document.getElementById('page') && document.getElementById("pagination"))
	{
		document.getElementById('page').value	= page;
		document.getElementById("pagination").submit();
	}
}

function pagineResultatAppartement(page)
{
	if(document.getElementById('page') && document.getElementById("pagination"))
	{
		document.getElementById('page').value	= page;
		document.getElementById("pagination").submit();
	}
}

/** Formulaire de contact RDV **/
function validCaptchaFormRDV(){	
	$.ajax({
		type: "POST",
		data: "captcha="+document.getElementById('strcode').value,
		async: true,
		url:  "ajax/ajax_verif_captcha.php",		
		
		success: function(data){

			var tab = data.split("|");	
			var err = 0;
			
			if(tab[1] == "OK"){								
				validFormRDV();
			}else{
				inlineMsg( 'strcode', get_trad_champ('bad_captcha'));		
				document.forms['formRDV'].elements['strcode'].select();		
				return false;
			}
		} });
	
}

function validFormRDV() {	
	if ( valider_formulaire_generique('formRDV', 'email', 'prenom',	'nom', 'date', 'telephone' ) ) {
		document.forms['formRDV'].submit();		
	}																		
	else {
		return false;
	}
}

/** Formulaire de contact RAPPEL **/
function validCaptchaFormContact(){	
	$.ajax({
		type: "POST",
		data: "captcha="+document.getElementById('strcode').value,
		async: true,
		url:  "ajax/ajax_verif_captcha.php",		
		
		success: function(data){

			var tab = data.split("|");	
			var err = 0;
			
			if(tab[1] == "OK"){								
				validFormContact();
			}else{
				inlineMsg( 'strcode', get_trad_champ('bad_captcha'));		
				document.forms['formContact'].elements['strcode'].select();		
				return false;
			}
		} });
	
}

function validFormContact() {	
	if ( valider_formulaire_generique('formContact', 'email', 'prenom',	'nom', 'telephone' ) ) {
		document.forms['formContact'].submit();		
	}																		
	else {
		return false;
	}
}

function validCaptchaFormInfos(){	
	$.ajax({
		type: "POST",
		data: "captcha="+document.getElementById('strcode').value,
		async: true,
		url:  "ajax/ajax_verif_captcha.php",		
		
		success: function(data){

			var tab = data.split("|");	
			var err = 0;
			
			if(tab[1] == "OK"){								
				validFormInfos();
			}else{
				inlineMsg( 'strcode', get_trad_champ('bad_captcha'));		
				document.forms['formInfos'].elements['strcode'].select();		
				return false;
			}
		} });
	
}

/** Formulaire de contact INFOS **/
function validFormInfos() {
	if ( valider_formulaire_generique('formInfos', 'email', 'prenom', 'nom', 'adresse', 'cp', 'ville', 'telephone' ) ) {
		document.forms['formInfos'].submit();		
	}																		
	else {
		return false;
	}
}

function changeFormAction(formId, actionUrl)
{
	if(document.getElementById(formId))
	{
		document.getElementById(formId).action = actionUrl;
	}	
}

function valide_ranges(min,max,idmin,idmax,spanerror)
{	
	if(document.getElementById(idmin) && document.getElementById(idmax) && document.getElementById(spanerror))
	{
		var realMin = document.getElementById(idmin).value;	
		var realMax = document.getElementById(idmax).value;	
		
		var minDif = realMin - min;
		var maxDif = max - realMax;
		var realDif = realMax - realMin;

		if(minDif < 0 || maxDif < 0 || realDif < 0)
		{
			document.getElementById(spanerror).style.display = 'block';		
			return false;
		}
		return true;	
	}
	return false;	
}

function valide_appartement(form,spanerror)
{
	if(document.getElementById(form) && document.getElementById(spanerror))
	{
		var form = document.getElementById(form);
		var inputs = form.getElementsByTagName('input');
		
		for(var index = 0; index < inputs.length; index++)
		{
			if(inputs[index].type == 'radio' && inputs[index].checked)
			{
				return true;
			}	
		}
		
		document.getElementById(spanerror).style.display = 'block';
	}
	return false;	
}

function valide_livraison(form,spanerror)
{
	if(document.getElementById(form) && document.getElementById(spanerror))
	{
		var form = document.getElementById(form);
		var inputs = form.getElementsByTagName('input');
		
		for(var index = 0; index < inputs.length; index++)
		{
			if(inputs[index].type == 'radio' && inputs[index].checked)
			{
				return true;
			}	
		}
		document.getElementById(spanerror).style.display = 'block';
	}
	return false;	
}

function submitsearch(link)
{
	if(document.getElementById('pagination'))
	{
		document.getElementById('pagination').action=link.href;
		document.getElementById('pagination').submit();	
	}
}

function alertFlash ( codex, codey ) {
	alert ( 'X : ' + codex + ', Y : ' + codey );
}

// *** Formulaire de newsletter *** //
function validCaptchaNewsletter(){	
	$.ajax({
		type: "POST",
		data: "captcha="+document.getElementById('strcode').value,
		async: true,
		url:  "ajax/ajax_verif_captcha.php",		
		
		success: function(data){

			var tab = data.split("|");	
			var err = 0;
			
			if(tab[1] == "OK"){								
				validFormNewsletter();
			}else{
				inlineMsg( 'strcode', get_trad_champ('bad_captcha'));		
				document.forms['formNewsletter'].elements['strcode'].select();		
				return false;
			}
		} });
	
}

function validFormNewsletter() {
	
	if ( valider_formulaire_generique('formNewsletter', 'nom', 'prenom', 'email' ) ) {					
		document.forms['formNewsletter'].submit();		
	}																		
	else {
		return false;
	}
}

// *** Formulaire de desinscription newsletter *** //
function validCaptchaDesNewsletter(){	
	$.ajax({
		type: "POST",
		data: "captcha="+document.getElementById('strcode').value,
		async: true,
		url:  "ajax/ajax_verif_captcha.php",		
		
		success: function(data){

			var tab = data.split("|");	
			var err = 0;
			
			if(tab[1] == "OK"){								
				validFormDesNewsletter();
			}else{
				inlineMsg( 'strcode', get_trad_champ('bad_captcha'));		
				document.forms['formDesNewsletter'].elements['strcode'].select();		
				return false;
			}
		} });
	
}

function validFormDesNewsletter() {
	
	if ( valider_formulaire_generique('formDesNewsletter', 'email' ) ) {					
		document.forms['formDesNewsletter'].submit();		
	}																		
	else {
		return false;
	}
}

// *** Formulaire de prescripteur *** //
function validCaptchaPrescripteur(){	
	$.ajax({
		type: "POST",
		data: "captcha="+document.getElementById('strcode').value,
		async: true,
		url:  "ajax/ajax_verif_captcha.php",		
		
		success: function(data){

			var tab = data.split("|");	
			var err = 0;
			
			if(tab[1] == "OK"){								
				validFormPrescripteur();
			}else{
				inlineMsg( 'strcode', get_trad_champ('bad_captcha'));		
				document.forms['formPrescripteur'].elements['strcode'].select();		
				return false;
			}
		} });
	
}

function validFormPrescripteur() {
	
	if ( valider_formulaire_generique('formPrescripteur', 'nom', 'prenom', 'telephone', 'email', 'message' ) ) {					
		document.forms['formPrescripteur'].submit();		
	}																		
	else {
		return false;
	}
}

function filtreAccesRapide(action)
{
	//On remet la pagination au debut
	if(document.getElementById('page'))
	{
		document.getElementById('page').value = '';
	}
	//On valide la formulaire
	if(document.getElementById('pagination'))
	{
		if(action != '' && action != undefined)
		{
			document.getElementById('pagination').action = action;
		}
		document.getElementById('pagination').submit();
	}
}


