
var preambluleAlertesFormulaires = 'Veuillez saisir les informations suivantes :\n' ;
var preambluleAlertesFormulaires2 = 'Veuillez déposer les documents suivants :\n';

var reEmail = /^.+\@.+\..+$/ ;

var compteurPopups = 0;

	
var XmlHttp = false;
if(window.XMLHttpRequest) {
	try {
		XmlHttp = new XMLHttpRequest();
  } catch(e) {
		XmlHttp = false;
  }			
} else if(window.ActiveXObject) {
 	try {
  	XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch(e) {
  	try {
    		XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  	} catch(e) {
    		XmlHttp = false;
  	}
	}
}



function LaunchVerif(query) {
	
	if (!XmlHttp) {
		alert("requete non effectuée");
	}
	
	
	XmlHttp.open("GET",query,false);
	XmlHttp.send(null);
	
	if (XmlHttp.readyState == 4) {
		var xml_response = XmlHttp.responseXML;
		if (xml_response) {
			var erreur = xml_response.getElementsByTagName("erreur").item(0).firstChild.data;
			if (erreur == "0") {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	return false;
}	


function isEmail( aString ) {

	return reEmail.test(aString);

}

function checkLogin(formulaire) {

	var f = document.forms[0];
	var alerts = [];

	if (formulaire==0) {
		var chpsLogin="login";
		var chpsPassword="password";
	} else {
		var chpsLogin="d_login";
		var chpsPassword="d_password";
		f.typeForm.value = 1;
	}

	if(eval("f."+chpsLogin+".value.length")<1)
		alerts.push('- votre identifiant');
	if(eval("f."+chpsPassword+".value.length")<1)
		alerts.push('- votre mot de passe');

	if(alerts.length>0) {
		window.alert(preambluleAlertesFormulaires+alerts.join("\n") );
	} else {
		f.action = sitePath+'actions/login.php';
		f.submit();

	}

}


function checkClient() {
	var f = document.forms[0];
	var alerts = [];
	
	if (isNaN(f.capital.value))
		alerts.push('- le capital doit être un nombre');
		
	if(f.pass.value!=f.confirmPass.value)
		alerts.push('- les champs "Mot de passe" et "Confirmation" doivent être identiques');
	
	
	if(f.nom.value.length<1)
		alerts.push('- la raison sociale du siège social');
	if(f.adresse.value.length<1)
		alerts.push('- l\'adresse du siège social');
	if(f.codePostal.value.length<1)
		alerts.push('- le code postal du siège social');
	if(f.ville.value.length<1)
		alerts.push('- la ville du siège social');
	if(f.pass.value.length<1)
		alerts.push('- le mot de passe');
	if(f.confirmPass.value.length<1)
		alerts.push('- la confirmation du mot de passe');
	if(f.nomContactPrincipal.value.length<1)
		alerts.push('- le nom du contact principal');
	if(f.prenomContactPrincipal.value.length<1)
		alerts.push('- le prénom du contact principal');
	if(f.fonctionContactPrincipal.value.length<1)
		alerts.push('- la fonction du contact principal');
	if(f.telephoneContactPrincipal.value.length<1)
		alerts.push('- le téléphone du contact principal');
	if( ! isEmail(f.emailContactPrincipal.value) )
		alerts.push('- l\'email du contact principal');
	if (!LaunchVerif(sitePath+'actions/gestionClientVerifMailXML.php?id='+escape(f.id.value)+'&email='+escape(f.emailContactPrincipal.value))) 
		alerts.push('- l\'email du contact principal existe déjà');
	if (!LaunchVerif(sitePath+'actions/gestionClientVerifMailXML.php?id='+escape(f.id.value)+'&email='+escape(f.emailContactJuridique.value))) 
		alerts.push('- l\'email du contact juridique existe déjà');
		
	
	if(alerts.length>0) {
		window.alert(preambluleAlertesFormulaires+alerts.join("\n") );
	} else {	
		f.action = sitePath+'actions/gestionClient.php';
		f.submit();
	}
}


function checkReglement() {
	var f = document.forms[0];
	var alerts = [];
	var alerts2 = [];
	var alerts3 = [];
	var txt_alert = "";
	
	
	if(f.nom.value.length<1)
		alerts.push('- le nom du jeu');
		
	if(f.dateDebut.value.length<1)
		alerts.push('- la date de début du jeu');
			
	if(f.dateFin.value.length<1)
		alerts.push('- la date de fin du jeu');
		
	if(f.reglementTitre.value.length<1)
		alerts.push('- le titre du règlement');
		
	if((f.destinDuReglementFichier==undefined || f.destinDuReglementFichier[1].checked) && f.reglementFichier.value.length<7)
		alerts2.push('- le règlement du jeu');
	
	
//	if (f.dateDebut.value>=f.dateFin.value && f.dateDebut.value!="" && f.dateFin.value!="")
//		alerts3.push('La date de fin du jeu doit être postérieure à la date de début du jeu');

	var timestampDateDebut;
	var timestampDateFin;
			
	timestampDateDebut = getTimestampDate(f.dateDebut.value, '-');
	timestampDateFin = getTimestampDate(f.dateFin.value, '-');
	
	if(timestampDateDebut==-1) {
		alerts3.push('La date de début du jeu n\'est pas valide');
	}
	if(timestampDateFin==-1) {
		alerts3.push('La date de fin du jeu n\'est pas valide');
	}	
	if(alerts3.length==0 && timestampDateDebut>=timestampDateFin) {
		alerts3.push('La date de début du jeu doit être antérieure à celle de fin du jeu');
	}		
	
	
	if( typeof(f.destinDuReglementFichier)=='undefined' || ! f.destinDuReglementFichier[0].checked ) {
	
		var extensionReglementFichier = f.reglementFichier.value.substring(f.reglementFichier.value.lastIndexOf('.')+1, f.reglementFichier.value.length).toLowerCase();
		
		if (extensionReglementFichier!='pdf' && extensionReglementFichier!='doc')
			alerts3.push('Le règlement du jeu doit être au format doc ou pdf');
			
	}
		
	
	if (f.tirage[0].checked==true) {
		for (i=1; i<=f.nbRangs.options[f.nbRangs.selectedIndex].value; i++) {
			eval("valeurRang = f.rang"+i+".value;");
			if (valeurRang=="")
				alerts.push('- le champ rang '+i);
		}
				
	
		if (f.dateTirage.value=="")
			alerts.push('- la date du tirage au sort');
			
//		if (f.dateTirage.value<=f.dateFin.value && f.dateTirage.value!="" && f.dateDebut.value!="" && f.dateFin.value!="")
//			alerts3.push('La date du tirage au sort doit être postérieure à la date de fin du jeu');

	}
		
	
	if(alerts.length>0 || alerts2.length>0 || alerts3.length>0) {
		if (alerts.length>0)
			txt_alert += preambluleAlertesFormulaires+alerts.join("\n")+"\n\n";
		
		if (alerts2.length>0) 
			txt_alert += preambluleAlertesFormulaires2+alerts2.join("\n")+"\n\n";
		
		if (alerts3.length>0)
			txt_alert += alerts3.join("\n");
			
		window.alert(txt_alert);
	} else {
		f.action = sitePath+'pages/confirmation.php';
		f.submit();
	}
}

function checkTirage() {
	var f = document.forms[0];
	var alerts = [];
	var alerts2 = [];
	var alerts3 = [];
	var txt_alert = "";
	
	if (f.jeuExistant.options[f.jeuExistant.selectedIndex].value=="") {
		if(f.nom.value.length<1)
			alerts.push('- le nom du jeu');
			
		if(f.dateDebut.value.length<1)
			alerts.push('- la date de début du jeu');
			
		if(f.dateFin.value.length<1)
			alerts.push('- la date de fin du jeu');
			
		var timestampDateDebut;
		var timestampDateFin;
				
		timestampDateDebut = getTimestampDate(f.dateDebut.value, '-');
		timestampDateFin = getTimestampDate(f.dateFin.value, '-');
		
		if(timestampDateDebut==-1) {
			alerts3.push('La date de début du jeu n\'est pas valide');
		}
		if(timestampDateFin==-1) {
			alerts3.push('La date de fin du jeu n\'est pas valide');
		}	
		if(alerts3.length==0 && timestampDateDebut>=timestampDateFin) {
			alerts3.push('La date de début du jeu doit être antérieure à celle de fin du jeu');
		}				
			
//		if (f.dateDebut.value>=f.dateFin.value && f.dateDebut.value!="" && f.dateFin.value!="")
//			alerts3.push('La date de fin du jeu doit être postérieure à la date de début du jeu');
		
//		if (f.dateTirage.value<=f.dateFin.value && f.dateTirage.value!="" && f.dateDebut.value!="" && f.dateFin.value!="")
//			alerts3.push('La date du tirage au sort doit être postérieure à la date de fin du jeu');
	}
	
	for (i=1; i<=f.nbRangs.options[f.nbRangs.selectedIndex].value; i++) {
		eval("valeurRang = f.rang"+i+".value;");
		if (valeurRang=="")
			alerts.push('- le champ rang '+i);
	}
	
	if (f.dateTirage.value=="")
			alerts.push('- la date du tirage au sort');

	if((f.destinDuTirageFichier==undefined || f.destinDuTirageFichier[1].checked) && f.tirageFichier.value.length<7)
		alerts2.push('- la liste des participants');

	if( typeof(f.destinDuTirageFichier)=='undefined' || ! f.destinDuTirageFichier[0].checked ) {
		
		var extensionTirageFichier = f.tirageFichier.value.substring(f.tirageFichier.value.lastIndexOf('.')+1, f.tirageFichier.value.length).toLowerCase();
		
		if (extensionTirageFichier!='' && extensionTirageFichier!='xls')
			alerts3.push('La liste des participants doit être au format xls');
		
	}
		
	if(alerts.length>0 || alerts2.length>0 || alerts3.length>0) {
		if (alerts.length>0)
			txt_alert += preambluleAlertesFormulaires+alerts.join("\n")+"\n\n";
		
		if (alerts2.length>0) 
			txt_alert += preambluleAlertesFormulaires2+alerts2.join("\n")+"\n\n";
			
		if (alerts3.length>0) 
			txt_alert += alerts3.join("\n");
			
		window.alert(txt_alert);
	} else {
		f.action = sitePath+'pages/confirmation.php';
		f.submit();
	}
}

/*
function checkDateDebut() {
	var f=document.forms[0];
	
	var jour = new Date();
	var today = complete(jour.getDate())+'-'+complete(jour.getMonth()+1)+'-'+annee(jour.getYear());


	if (f.dateDebut.value!="" && f.dateDebut.value<today)
		if (window.confirm('la date du début de votre jeu est antérieure à la date du jour ('+today+'), Souhaitez-vous continuer ?')!=1)
			f.dateDebut.value="";
}

// corrige l'annee pour Netscape 4.06 et versions superieures
function annee(an) {
  if ((navigator.appName == "Netscape") && (parseFloat(navigator.appVersion) >= 4.06))
     an = eval(an + 1900);
  return an;
}

// met un "0" devant un nombre si inferieur a 10
function complete(nombre) {
  return ((nombre <= 9) ? "0" : "") + nombre;
}
*/

function checkConditions(url) {
	var f = document.forms[0];

if (f.conditions.checked==true)
	document.location=url;
else
	alert("Vous devez accepter les conditions générales de vente");
}


function switchReglement(etape) {
	var f = document.forms[0];
	
	if (etape=="init") {
		Element.hide('etape2');
		Element.hide('hlp2');
		
		displayTirage();
	} else if (etape=="etape2") {
		$('sousTitre').innerHTML = "<h2>Etape 2/2</h2>";
		
		Element.hide('reglement');
		Element.hide('hlp1');
		Element.show('etape2');
		Element.show('hlp2');
		Element.show('choixTirage');
		
		displayTirageType();
	} else {
		$('sousTitre').innerHTML = "<h2>Etape 1/2</h2>";
		
		Element.show('reglement');
		Element.hide('etape2');
		
		Element.show('hlp1');
		Element.hide('hlp2');
	}
}

function displayTirage() {
	var f = document.forms[0];
	
	if (f.tirage[1].checked==true)
		Element.hide('tiragediv');
	else
		Element.show('tiragediv');		
}





function giveMeMyPositionPlize(largeurPopup, hauteurPopup) {

	var x, y;

	x = (screen.availWidth/2) - (largeurPopup/2);
	y = (screen.availHeight/2) - (hauteurPopup/2);

	return 'left='+x+',top='+y+',';

}


function openPopup(URL, largeur, hauteur, nomPopup, scroll) {
	codeXY = giveMeMyPositionPlize(largeur, hauteur);
	
	pPopup = window.open( sitePath+URL, nomPopup+compteurPopups, codeXY+'location=0,status=0,menubar=no,scrollbars='+scroll+',width='+largeur+',height='+hauteur+',dependant=1');
	
	compteurPopups++;
}


function checkPasswordOublieForm() {

	var f = document.forms[0];
	var alerts = [];

	if( ! isEmail(f.email.value) || f.email.value<6 ) 
		alerts.push('- votre adresse email');

	if(alerts.length>0) {
		window.alert(preambluleAlertesFormulaires+alerts.join("\n") );
	} else {
		
		f.submit();
		
	}

}

function checkTelechargementReglementForm() {

	var f = document.forms[0];
	var alerts = [];

	if( ! isEmail(f.email.value) || f.email.value<6 ) 
		alerts.push('- votre adresse email');

	if(alerts.length>0) {
		window.alert(preambluleAlertesFormulaires+alerts.join("\n") );
	} else {
		
		f.submit();
		
	}

}

function checkPublication() {
	var f = document.forms[0];
	var alerts = [];
	
	if (f.publication.options[f.publication.selectedIndex].value==1 && f.datePublication.value=="")
		alerts.push('- La date de publication (obligatoire pour une publication en différé)');
	
	if(alerts.length>0) {
		window.alert(preambluleAlertesFormulaires+alerts.join("\n") );
	} else {
		f.action = sitePath+'actions/gestionReglement.php';	
		f.submit();
	}
}

function checkRecapTirage() {
	var f = document.forms[0];
	var alerts = [];

	if((f.destinDuTirageFichier==undefined || f.destinDuTirageFichier[1].checked) && f.tirageFichier.value.length<7)
		alerts.push('- Veuillez attacher la liste des participants');

	var extensionTirageFichier = f.tirageFichier.value.substring(f.tirageFichier.value.indexOf('.')+1, f.tirageFichier.value.length);
	
	if (extensionTirageFichier!='' && extensionTirageFichier!='xls')
		alerts.push('- La liste des participants doit être au format xls');
		
	if(alerts.length>0) {
		window.alert(alerts.join("\n") );
	} else {
		f.action = sitePath+'actions/gestionTirage.php';
		f.submit();
	}
}


/*
function checkDate (str_date, nom_chp) {
	var f = document.forms[0];

	if (str_date!="") {
		var arr_date = str_date.split('-');
	
		if (arr_date.length != 3) {
			eval('f.'+nom_chp+'.value = "";');
			return cal_error ("Format de date invalide : '" + str_date + "'.\nLe format accepté est dd-mm-yyyy.");			
		}
		if (!arr_date[0]) {
			eval('f.'+nom_chp+'.value = "";');
			return cal_error ("Format de date invalide : '" + str_date + "'.\nJour introuvable.");
		}
		if (!RE_NUM.exec(arr_date[0])) {
			eval('f.'+nom_chp+'.value = "";');
			return cal_error ("Jour invalide : '" + arr_date[0] + "'.\nSeuls les chiffres sont acceptés.");
		}
		if (!arr_date[1]) {
			eval('f.'+nom_chp+'.value = "";');
			return cal_error ("Format de date invalide : '" + str_date + "'.\nMois introuvable.");
		}
		if (!RE_NUM.exec(arr_date[1])) {
			eval('f.'+nom_chp+'.value = "";');
			return cal_error ("Mois invalide : '" + arr_date[1] + "'.\nSeuls les chiffres sont acceptés.");
		}
		if (!arr_date[2]) {
			eval('f.'+nom_chp+'.value = "";');
			return cal_error ("Format de date invalide : '" + str_date + "'.\nAnnée introuvable.");
		}
		if (!RE_NUM.exec(arr_date[2])) {
			eval('f.'+nom_chp+'.value = "";');
			return cal_error ("Année invalide : '" + arr_date[2] + "'.\nSeuls les chiffres sont acceptés.");
		}

		var dt_date = new Date();
		dt_date.setDate(1);

		if (arr_date[1] < 1 || arr_date[1] > 12) {
			eval('f.'+nom_chp+'.value = "";');
			return cal_error ("Mois invalide : '" + arr_date[1] + "'.\nFourchette autorisée : 01-12.");
		}
		dt_date.setMonth(arr_date[1]-1);

		if (arr_date[2].length<4) {
			eval('f.'+nom_chp+'.value = "";');
			return cal_error ("Année invalide : longueur obligatoire de 4 chiffres.");
		}
		
		var dt_numdays = new Date(arr_date[2], arr_date[1], 0);
		dt_date.setDate(arr_date[0]);
		if (dt_date.getMonth() != (arr_date[1]-1)) {
			eval('f.'+nom_chp+'.value = "";');
			return cal_error ("Jour invalide : '" + arr_date[0] + "'.\nFourchette autorisée : 01-"+dt_numdays.getDate()+".");
		}

		return true;
	}
}

function testDateValide(saisie) {
	alert(saisie);
	if (saisie == "") return false;
	saisie = (saisie).split("/");

	if ((saisie.length != 3) || isNaN(parseInt(saisie[0])) || isNaN(parseInt(saisie[1])) || isNaN(parseInt(saisie[2])))
		return false;
	
	var laDate = new Date(eval(saisie[2]),eval(saisie[1])-1,eval(saisie[0]));
	var annee = laDate.getYear();
	
	if ((Math.abs(annee)+"").length < 4)
		annee = annee + 1900;
	
	return ((laDate.getDate() == eval(saisie[0])) && (laDate.getMonth() == eval(saisie[1])-1) && (annee == eval(saisie[2])));
}

*/

/**
 * Renvoie le timestamp de la date, ou un nombre negatif si la date n'est pas valide
 * -1 : format DDMMYYYY non respecte
 * -2 : jour non compris entre 1 et 31
 * -3 : mois non compris entre 1 et 12
 * -4 : annee non comprise entre 1970 et 2010
 * -5 : annee non valide suite aux ajustements de date
 * -6 : mois non valide suite aux ajustements de date
 * -7 : jour  non valide suite aux ajustements de date
 */
function getTimestampDate( aDDMMYYYYDate, aSeparator ) {

	var dateRegexp;
	var day, month, year;
	var dateCheck;
	
	dateRegexp = new RegExp('^([0-3]?[0-9])'+aSeparator+'([01]?[0-9])'+aSeparator+'([12][0-9]{3})$', 'g');
	
	// 1er test : format de la chaine de caracteres
		if( ! dateRegexp.test(aDDMMYYYYDate) )
			return -1;
	
	dateRegexp.exec(aDDMMYYYYDate)	;
	day = RegExp.$1;
	month = RegExp.$2;
	year = RegExp.$3;
	
	// 2eme test : 31 jours, 12 mois, tout ca...
		if( day<1 || day>31 )
			return -2;
		if( month<1 || month>12 )
			return -3;
		if(year<1970 || year>2010 )
			return -4;
	
	// 3eme test, impitoyable celui-ci qui va detecter les 29 fevrier illegaux et tout le reste
		dateCheck = new Date(year, month-1, day);
		if(year!=dateCheck.getFullYear())
			return -5;
		if(month!=(dateCheck.getMonth()+1))
			return -6;
		 if(day!=dateCheck.getDate())
		 	return -7;
	 
	 // C'est tout bon : on retourne le timestamp
	 	return dateCheck.getTime();
	

}

