Event.observe(window,'load',demarrage,false);

String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

var GObjet ="";
var GTaille=0;

function fenetre()
{
			var viewportwidth;
			 var viewportheight;
			 
			 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
			 
			 if (typeof window.innerWidth != 'undefined')
			 {
				  viewportwidth = window.innerWidth,
				  viewportheight = window.innerHeight
			 }
			 
			// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
			
			 else if (typeof document.documentElement != 'undefined'
				 && typeof document.documentElement.clientWidth !=
				 'undefined' && document.documentElement.clientWidth != 0)
			 {
				   viewportwidth = document.documentElement.clientWidth,
				   viewportheight = document.documentElement.clientHeight
			 }
			 
			 // older versions of IE
			 
			 else
			 {
				   viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
				   viewportheight = document.getElementsByTagName('body')[0].clientHeight
			 }
			 
			 this.height = viewportheight
			 this.width =  viewportwidth 
}

function Exception(fonction,message)
{
	alert('Exception levée dans la fonction ' + fonction +'\n raison :' +message);
}
function demarrage()
{
	
	//chargement de la fenetre d'upload
	loadcvbox();
	loadattach();
	//au départ la boite de CV est masquée...
	resumeAfterCv();
	resumeAfterAttach();
	
	$$('.controle5').each(						  	function(p){Event.observe(p.id,'change',coherence,false); }						  );

	$$('.action').each(
							function(p)
							{
								element = p.id.gsub('titre_','')
								Event.observe(p.id,'click',switcher.bindAsEventListener(p,element));
								if($('contenu_'+element))	$('contenu_'+element).toggle();
							}
					  );
	

	//paramétrage et positionnement de la fenêtre d'upload
	var fen = new fenetre();
	if ($('cv_box') )
	{
		$('cv_box').setStyle(  { width:fen.width.toString() +'px',
									height:(fen.height*2).toString()+'px',
									opacity:1});
							 
		
	}
	if ($('form_cv') )
	{
		$('form_cv').setStyle(  {top:(fen.height/2-80).toString() +'px'});
							 
		
	}
	
	if ($('typed')) Event.observe($('typed'),'change',laureat, false);
	if($('cvacces')) Event.observe($('cvacces'),'click',allowToAddCv.bindAsEventListener(),false);
	//if($('form_cv')) Event.observe($('form_cv'),'submit',resumeAfterCv.bindAsEventListener(), false );
	if($('annulercv')) Event.observe($('annulercv'),'click',resumeAfterCv.bindAsEventListener(), false );
	if($('form_cv')) Event.observe($('form_cv'),'submit',verifavtcv,false);
	if ($('form_insc') )Event.observe( $('form_insc'),'submit',verifavtinsc,false );
	
	if ($('attach_box') )
	{
		$('attach_box').setStyle(  { width:fen.width.toString() +'px',
									height:(fen.height*2).toString()+'px',
									opacity:1});
							 
		
	}
	if ($('form_attach') )	{		$('form_attach').setStyle(  {top:(fen.height/2-80).toString() +'px'});}
	if($('attachacces')) Event.observe($('attachacces'),'click',allowToAddAttach.bindAsEventListener(),false);
	//if($('form_cv')) Event.observe($('form_cv'),'submit',resumeAfterCv.bindAsEventListener(), false );
	if($('annulerattach')) Event.observe($('annulerattach'),'click',resumeAfterAttach.bindAsEventListener(), false );
	if($('form_attach')) Event.observe($('form_attach'),'submit',verifavtattach,false);
	Element.scrollTo($('form_insc'));
	
	
}

function verifavtinsc(e)
{
	Event.stop(e);
	var regleDate = new RegExp("^[0-9]{2}\/[01]?[0-9]\/[0-9]{4}$");
	var regleCP   = new RegExp("^[0-9]{5,5}$");
	var regleMail = new RegExp("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]{2,}[.][a-zA-Z]{2,4}$");
	//var regleTel  = new RegExp('^[0-9]{3}([ -/]|[./])[0-9]{3}\1[0-9]{3}$');//("^[0-9]{10,10}$");
	var regleTel  = new RegExp('^([0-9]{2}((\-)|(\s)|(\.))){4}[0-9]{2}(\s)*$') ;
	source = Event.element(e);
	
	
	if ( $F('nom')==""){new Insertion.Bottom('nomprenom','<br/><span class="missing">Attention le champ nom est mal rempli.</span><br/>');Element.scrollTo($('nomprenom'));return false;}
	
	if ( $F('prenom')==""){new Insertion.Bottom('nomprenom','<span class="missing">Attention le champ pr&eacute;nom est mal rempli.</span><br/>');Element.scrollTo($('nomprenom'));return false;}
	
//	if(!regleDate.test($F('daten') )) {new Insertion.Bottom('inf_naissance','<br/><span class="missing">Saisissez la date au format jj/mm/aaaa.</span><br/>');Element.scrollTo($('inf_naissance'));return false;}
	if (!chkdate2($('daten'))){new Insertion.Bottom('inf_naissance','<br/><span class="missing">Saisissez la date au format jj/mm/aaaa.</span><br/>');Element.scrollTo($('inf_naissance'));return false;}
	if($F('adresse')==""){new Insertion.Bottom('inf_adresse','<br/><span class="missing">Veuillez indiquer une adresse o&ugrave; vous contacter.</span><br/>');Element.scrollTo($('inf_adresse'));return false;}
	if(!regleCP.test($F('cp') )) {new Insertion.Bottom('inf_cp','<br/><span class="missing">Votre code postal est incorrect.</span><br/>');Element.scrollTo($('inf_cp'));return false;}
	if($F('ville')==""){new Insertion.Bottom('inf_ville','<br/><span class="missing">Veuillez indiquer votre ville.</span><br/>');Element.scrollTo($('inf_ville'));return false;}
	
	if(!regleMail.test($F('mail') )){new Insertion.Bottom('inf_mail','<br/><span class="missing">Veuillez indiquer un courriel valide.</span><br/>');Element.scrollTo($('mail'));return false;}
	//alert(regleTel.test( $F('tel1')));
	if (!regleTel.test( $F('tel1').trim()) ) {new Insertion.Bottom('inf_tel','<br/><span class="missing">Veuillez indiquer un num&eacute;ro de t&eacute;l&eacute;phone fixe valide.</span><br/>');Element.scrollTo($('inf_tel'));return false;}
	if( ($F('tel2')!="")&&(!regleTel.test( $F('tel2').trim() )) ){new Insertion.Bottom('inf_tel','<br/><span class="missing">Veuillez indiquer un num&eacute;ro de t&eacute;l&eacute;phone mobile valide.</span><br/>');Element.scrollTo($('inf_tel'));return false;}
	if( ($F('tel3')!="")&&(!regleTel.test( $F('tel3').trim() )) ){new Insertion.Bottom('inf_tel_pro','<br/><span class="missing">Veuillez indiquer un num&eacute;ro de t&eacute;l&eacute;phone professionnel valide.</span><br/>');Element.scrollTo($('inf_tel3'));return false;}
	
	
	if ( $F('typed')=="%"){new Insertion.Bottom('demandeur','<br/><span class="missing">Attention vous devez choisr un type de demandeur.</span><br/>');Element.scrollTo($('demandeur'));return false;}
	
	if ( $('typelaureat')&& $F('typelaureat')=="%"){new Insertion.Bottom('inf_typelaureat','<br/><span class="missing">Attention vous devez choisr un type de Laur&eacute;at.</span><br/>');Element.scrollTo($('demandeur'));return false;}
	
	
	if ( $F('secteur')=="%"){new Insertion.Bottom('inf_secteur','<br/><span class="missing">Attention vous devez choisr un secteur d\'activit&eacute;.</span><br/>');Element.scrollTo($('secteur'));return false;}
	
	if ( ( ( $F('typed')!='DET' ) && ($F('cadreemploi')=='%') ) ) {new Insertion.Bottom('inf_cadreemploi','<br/><span class="missing">Attention vous devez choisir un cadre d\'emploi.</span><br/>');Element.scrollTo($('cadreemploi'));return false;}
	
	if ( $F('niveau')=="%"){new Insertion.Bottom('inf_niveau','<br/><span class="missing">Attention vous devez choisr un niveau d\'&eacute;tudes .</span><br/>');Element.scrollTo($('niveau'));return false;}
	
	if ( $F('pre_valid')!="oui"){new Insertion.Bottom('averto','<br/><span class="missing">Attention vous devez cocher la case ci dessus pour valider votre inscription.</span><br/>');Element.scrollTo($('averto'));return false;}	
//	if ( $F('localisation')=="%"){new Insertion.Bottom('inf_localisation','<br/><span class="missing">Attention vous devez choisr une localisation.</span><br/>');Element.scrollTo($('localisation'));return false;}
	if ( ($('typed')!='LAU')&&($F('cadreemploi')=='%')  ) {new Insertion.Bottom('inf_cadreemploi','<br/><span class="missing">Attention vous devez choisir un cadre d\'emploi.</span><br/>');Element.scrollTo($('localisation'));return false;}
	
	
	//if( ($F('date_dispo')!="")&&(!regleDate.test( $F('date_dispo'))) ){new Insertion.Bottom('inf_dispo','<br/><span class="missing">Veuillez saisir la date de disponibilit&ea au bon format.</span><br/>');Element.scrollTo($('inf_dispo'));return false;}
	
	var typeL="";
	var tel3="";
	if ($('typelaureat')) typeL=$F('typelaureat');
	if ($('tel3')) tel3=$F('tel3');
	var data=$H({'nom':$F('nom').toUpperCase(),'prenom':$F('prenom').capitalize(),'daten':$F('daten'),'adresse':$F('adresse'),'cp':$F('cp'),'ville':$F('ville'),'mail':$F('mail'),'tel1':$F('tel1'),'tel2':$F('tel2'),'date_dispo':$F('date_dispo'),'souhaits':$F('souhaits'),'formation':$F('formation'),'cv_name':$F('cv_name'),'contrat':$F('contrat'),'nominatif':$F('nominatif'),'tpscomplet':$F('tpscomplet'),'experience':$F('experience'),'typed':$F('typed'),'secteur':$F('secteur'),'niveau':$F('niveau'),'localisation':$F('localisation'),'detexperience':$F('detexperience'),'objet':'validation','pj':$F('attach_name'),'categorie':$F('categorie'),'filiere':$F('filiere'),'cadreemploi':$F('cadreemploi'),'typelaureat':typeL,'rapprochement':$F('rapprochement'),'tel3':tel3}).toQueryString()
//	alert(data)
	//alert(data);
	//alert('on va transmettre')
	new Ajax.Updater('insc',
					 '/Traitements/validinsc.asp',
					 {
						 postBody:data,
						 insertion:Insertion.Bottom,
						 evalScripts:true
					 }
					 );
	
	//alert('on a transmis')
}
function verifavtcv(e)
{
	//LA page inscdemval.asp met à jour la variable cachée cv_name transmise lors de la validation du formulaire.
	source = Event.element(e);
	if (source.id =="form_cv")
	{
		Event.stop(e);
		//alert("pour le moment on va en rester là!!");
		if (checkextensions('cv') )
		{
			new Insertion.Bottom('recap_cv','<span id="wait_cv">Cv en cours de r&eacute;cup&eacute;ration...</span>');
			 GObjet="Cv"
			$('form_cv').submit();
			$('cv_box').addClassName('invisible');
			$A(document.getElementsByTagName('select')).each( function(p){$(p.id).removeClassName('invisible');});
			Element.scrollTo($('cvacces'));
		}
		else 
		{
			
			if( $('msgcv')) Element.remove( $('msgcv'));
			new Insertion.Before('validcv',"<div id='msgcv'>Votre document ne correspond pas aux crit&egrave;res.</div>");
			
		}
	}
	
}
function allowToAddCv()
{
	$A(document.getElementsByTagName('select')).each( function(p){$(p.id).addClassName('invisible');})
	$('cv_box').removeClassName('invisible');
	
	Element.scrollTo($('cv_box'));
}
function resumeAfterCv()
{
	$A(document.getElementsByTagName('select')).each( function(p){$(p.id).removeClassName('invisible');})
	if ($('cv_acces')) Element.scrollTo($('cvacces'));
	if ($('cv_box'))	$('cv_box').addClassName('invisible');
	
}

function allowToAddAttach(){	$A(document.getElementsByTagName('select')).each( function(p){$(p.id).addClassName('invisible');});$('attach_box').removeClassName('invisible');	Element.scrollTo($('attach_box'));}
function resumeAfterAttach(){	$A(document.getElementsByTagName('select')).each( function(p){$(p.id).removeClassName('invisible');});if ($('attach_box'))	$('attach_box').addClassName('invisible'); if ($('attachacces'))Element.scrollTo($('attachacces'));}

function verifavtattach(e)
{
	//LA page inscdemval.asp met à jour la variable cachée cv_name transmise lors de la validation du formulaire.
	source = Event.element(e);
	if (source.id =="form_attach")
	{
		Event.stop(e);
		//alert("pour le moment on va en rester là!!");
		if (checkextensions('attach') )
		{
			new Insertion.Bottom('recap_attach','<span id="wait_attach">Pi&egrave;ce jointe en cours de r&eacute;cup&eacute;ration...</span>');
			 GObjet="Attach"
			$('form_attach').submit();
			$('attach_box').addClassName('invisible');
			$A(document.getElementsByTagName('select')).each( function(p){$(p.id).removeClassName('invisible');});
			Element.scrollTo($('attachacces'));
		}
		else 
		{
			
			if( $('msgattach')) Element.remove( $('msgattach'));
			new Insertion.Before('validattach',"<div id='msgattach'>Votre document ne correspond pas aux crit&egrave;res.</div>");
			
		}
	}
	
}

function switcher(objet,element)
{
	try
	{
		id= 'contenu_'+element;
		
		if ($(id))
		{
			 $(id).toggle();
			// new Effect.Scale($(id),100,{duration:0.5,scaleFromCenter:true});
		}
		 else alert('la description associ&eacute;e à cette information n\'existe pas');
	}
	catch(e)
	{
		Exception('switcher',e.message )
	}	
	
}

function postupload( fichier )
{
		if ($('recap_cv'))
		{
			if($('det_cv')) Element.remove( $('det_cv'));
			if($('wait_cv')) Element.remove($('wait_cv'));
	 		new Insertion.Bottom('recap_cv','<span id="det_cv">'+fichier+'</span>');
		}
	//	alert(GTaille);
		//var motif = new RegExp("(é,è,ê,&eacute;,Ã©)","g")
		$('cv_name').value=fichier;//.replace(motif,"davidddd");
		//alert($F('cv_name'))
}

function postuploadAttach( fichier )
{
		if ($('recap_attach'))
		{
			//if($('det_cv')) Element.remove( $('det_cv'));
			if($('wait_attach')) Element.remove($('wait_attach'));
	 		new Insertion.Bottom('recap_attach','<span class="pj">'+fichier+'</span><br />');
		}
		$('attach_name').value= ($F('attach_name')=="") ? fichier : $F('attach_name')+'|'+fichier;
		//$('attach_name').value=$F('attach_name')+'|'+fichier;
		
}



function checkextensions( objet)
{
		var fichier = (objet=='cv') ? $F('cv'):$F('attach');
//		var fichier = $F('cv');
		
		//alert(fichier);
		regle= new RegExp("[.]+","g");
		var tab = fichier.split(regle);
		var indice = tab.length-1;
		if (indice>=0)
		{
			if( tab[indice]=='doc' || tab[indice]=='xls' || tab[indice]=='pdf' || tab[indice]=='odt' || tab[indice]=='docx' || tab[indice]=='txt' || tab[indice]=='rtf' ) return true;
			else return false;
		}
		return false;
}



function loadcvbox()
{
	var boite =	'<div id="cv_box"> <form name="cvUpload" method="post"  action="./inscdemval.asp" enctype="multipart/form-data" target="UpCv" class="form_cv" id="form_cv">			<p>             S&eacute;lectionnez votre curriculum vitae. Merci de bien nous transmettre votre document dans l\'un des formats suivant : <strong>Word</strong> (extensions .doc, .docx), <strong>PDF</strong> (.pdf), <strong>Open Office </strong> (.odt)            </p>            <p>           	<label for="cv" id="lbl_cv">cv :</label> <input type="file" name="cv" id="cv" height="34" class="file" />                        <iframe name="UpCv" id="UpCv" ></iframe>            <input type="hidden" name="loadcv" value="ready"  />           </p>                       <input type="submit" value="Ajouter CV" class="valid" id="validcv"  />           <input type="reset" value="Annuler"  id="annulercv"/>               </form></div>';
	
	new Insertion.After('form_insc',boite);
	
}

function loadattach()
{
	var boite =	'<div id="attach_box"> <form name="attachUpload" method="post"  action="./inscdemval.asp" enctype="multipart/form-data" target="UpAttach" class="form_attach" id="form_attach">			<p>             S&eacute;lectionnez la piece suppl&eacute;lementaire &agrave; joindre &agrave; votre inscription . Merci de bien nous transmettre votre document dans l\'un des formats suivant : <strong>Word</strong> (extensions .doc, .docx), <strong>PDF</strong> (.pdf), <strong>Open Office </strong> (.odt)            </p>            <p>           	<label for="attach" id="lbl_attach">Pi&egrave;ce suppl&eacute;mentaire :</label> <input type="file" name="attach" id="attach" height="34" class="file" value="" />                        <iframe name="UpAttach" id="UpAttach" ></iframe>            <input type="hidden" name="loadattach" id="loadattach" value="ready"  />           </p>                       <input type="submit" value="Ajouter" class="valid" id="validattach"  />           <input type="reset" value="Annuler"  id="annulerattach"/>               </form></div>';
	
	new Insertion.After('form_insc',boite);
	
}

function coherence(e, obj)
{	var decl = (e) ? Event.element(e).id: obj


		if( decl == "categorie")data = $H({'objet':'categorie','categorie':$F('categorie'),'origine':'coherence'}).toQueryString();
		if( decl == "filiere")data = $H({'objet':'filiere','filiere':$F('filiere'),'categorie':$F('categorie'),'origine':'coherence'}).toQueryString();
		if( decl == "cadreemploi")data = $H({'objet':'cadreemploi','cadreemploi':$F('cadreemploi'),'filiere':$F('filiere'),'categorie':$F('categorie'),'origine':'coherence'}).toQueryString();
		
		//alert(data);
		new Ajax.Updater('insc',
						 '/Traitements/validinsc.asp',
						 {
							 postBody:data,
							 insertion:Insertion.Bottom,
							 evalScripts:true
						 }
						 );
	
	
}
function laureat()
{
	if($F('typed')=="LAU")		new Insertion.After('demandeur','<p class="element" id="inf_typelaureat">        <label for="typelaureat" class="obligatoire" id="lbl_typelaureat">Type de laur&eacute;at</label><select id="typelaureat" class="controle" name="typelaureat"><option value="%"> --------------- </option><option value="LAUCDG69">Laur&eacute;at CDG69</option><option value="LAUAUTCDG">Laur&eacute;at autre CDG</option></select>        </p>');
	else
		if($('inf_typelaureat')) Element.remove($('inf_typelaureat'));
		
}
 function Verifier_Numero_Telephone(num_tel)
 {
 // Definition du motif a matcher
 var regex = new RegExp(/^(01|02|03|04|05|06|08)[0-9]{8}/gi);

 // Definition de la variable booleene match
 var match = false;

 // Test sur le motif
 if(regex.test(num_tel))
 {
 match = true;
 }
 else
 {
 match = false;
 }

 // On renvoie match
 return match;
 }
function chkdate2(objName) {
//var strDatestyle = "US"; //United States date style
var strDatestyle = "EU";  //European date style
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
var err = 0;
var strMonthArray = new Array(12);
strMonthArray[0] = "01";//"Jan";
strMonthArray[1] = "02"//;"Jan";
strMonthArray[2] = "03";//"Mar";
strMonthArray[3] = "04";//"Avr";
strMonthArray[4] = "05";//"Mai";
strMonthArray[5] = "06";//"Juin";
strMonthArray[6] = "07";//"Juil";
strMonthArray[7] = "08";//"Aout";
strMonthArray[8] = "09";//"Sept";
strMonthArray[9] = "10";//"Oct";
strMonthArray[10] = "11";//"Nov";
strMonthArray[11] = "12";//"Dec";
strDate = datefield.value;
if (strDate.length < 1) {
return true;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
strDateArray = strDate.split(strSeparatorArray[intElementNr]);
if (strDateArray.length != 3) {
err = 1;
return false;
}
else {
strDay = strDateArray[0];
strMonth = strDateArray[1];
strYear = strDateArray[2];
}
booFound = true;
   }
}
if (booFound == false) {
if (strDate.length>5) {
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(2, 2);
strYear = strDate.substr(4);
   }
}
if (strYear.length == 2) {
strYear = '20' + strYear;
}
// US style
if (strDatestyle == "US") {
strTemp = strDay;
strDay = strMonth;
strMonth = strTemp;
}
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
for (i = 0;i<12;i++) {
if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
intMonth = i+1;
strMonth = strMonthArray[i];
i = 12;
   }
}
if (isNaN(intMonth)) {
err = 3;
return false;
   }
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
err = 4;
return false;
}
if (intMonth>12 || intMonth<1) {
err = 5;
return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
err = 6;
return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
err = 7;
return false;
}
if (intMonth == 2) {
if (intday < 1) {
err = 8;
return false;
}
if (LeapYear(intYear) == true) {
if (intday > 29) {
err = 9;
return false;
}
}
else {
if (intday > 28) {
err = 10;
return false;
}
}
}
if (strDatestyle == "US") {
datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
}
else {
datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
//datefield.value = intday + "/" + intMonth + "/" + strYear;
}
return true;
}
function LeapYear(intYear) {
if (intYear % 100 == 0) {
if (intYear % 400 == 0) { return true; }
}
else {
if ((intYear % 4) == 0) { return true; }
}
return false;
}


