// --------------------------------------------------------------------------------------------------------------------------------
//
//		TO DO : 
//			- boir pb titre realisation
//			- ajouter cw-popup
//			- ajouter espace avant nom erreur
//			- attention taille fenˆtre et d‚calage button sur IE6
//			- rajouter image de fond sur mail envoy‚
//			-mettre une restriction sur l'accŠs du rep formulaire_devis
//			-interdire l'accŠs au robots
//	
// --------------------------------------------------------------------------------------------------------------------------------



// creation de l'objet cwPopup en indiquant son parent
DevisPopup = new cwPopup("bloc_general");


var MyFormValidator = null;
// on pourrait aussi le mettre ds MyFormValidator
var Xmlhttp = getHTTPObject();


function getHTTPObject() {
	
	var red=null;
	
	if (window.XMLHttpRequest)
		{
 			req = new XMLHttpRequest();
			if (req.overrideMimeType) 
			{
				req.overrideMimeType('text/xml');
			}
		} 
	else if (window.ActiveXObject) 
	{
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e)
		{
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {alert(e)}
		}
        }
        
        return req;

}



//-----------------------------------------------------------------------------------------------------------------------------------
//-				Classe FieldValidator (associ‚e … chaque champ … v‚rifier)
//-				idobj : id du champ … v‚rifier
//-				ErrorLabel : chaine indiquant l'erreur de siaise renvoy‚e
//-				IdInner : id de l'objet ou l'on doit afficher l'erreur
//-				checkrule : type de rŠgle de validation … appliquer au champ
//-----------------------------------------------------------------------------------------------------------------------------------
function FieldValidator(idobj, idinner,checkrule) {
	
	this.IdObj=idobj;
	this.ErrorLabel="OK";
	this.IdInner=idinner;
	this.CheckRule=checkrule;
	this.ErrCurr="";
	
	
	// s'il s'agit d'un radio on met sa valeur … checked			
	if(document.getElementById(this.IdObj).type=='radio')
		this.value=document.getElementById(this.IdObj).checked;
	else
		this.value=document.getElementById(this.IdObj).value;
				
	
     	this.getElement = function()
	{
		return document.getElementById(this.IdObj);
	}
	
	this.getValue = function()
	{
		return this.getElement().value;
	}
	
	
	this.showError = function()
	{	
		if(this.IdInner)
		{
			var str=this.ErrorLabel;
			
			if(this.ErrorLabel=='OK') // si le champ est valid‚ on affiche rien
				str="";
			
			document.getElementById(this.IdInner).innerHTML=unescape(str);
		}
	}
	
	this.validate = function()
	{		
		// on part du principe que si l'objet existe il ya une rŠgle qui est au minimun de ne pas ˆtre vide
		// donc c'est pas la peine d'envoyer le test de la rŠgle avec AJAX !
		if(this.CheckRule)
		{
			
			if(!this.getValue())
			{
				this.ErrorLabel="Saisie obligatoire";
			}
			else
				SendRequest(this);
		}	
		
		return (this.ErrorLabel=='OK');
	}
}

//-----------------------------------------------------------------------------------------------------------------------------------
//-				Classe FormValidator (gŠre la validation du formulaire avec l'objet Validator)
//-				rules : CHECKMAIL, CHECKPHONE, CHECKFILLED, CHECKNBCARAC (doit apparaŒtre dans class)
//-				
//-				
//-----------------------------------------------------------------------------------------------------------------------------------
function FormValidator(idform,phpCheckFile) {

	this.Form=document.getElementById(idform);
	this.Rules=['CHECKMAIL','CHECKPHONE','CHECKFILLED','CHECKNBCARAC'];
	this.Validated=true;
	this.phpCheckFile=phpCheckFile;
	
	// construction des objets FieldValidator par rapport au formulaire
	this.FV_array=new Array();
	
	
	this.IsRule = function(rule)
	{
		for(var i=0;i<this.Rules.length;i++)
		{
			if (rule==this.Rules[i])
				return i;
		}	
		
		return -1;
	}
	
	
	// parcours de tous les input et text area et cr‚ation d'objet si des rules existent
	this.BuildFielValidators = function(object_type)
	{
		var objInput = document.getElementsByTagName(object_type);
		for (var iCounter=0; iCounter<objInput.length; iCounter++)
		{				
			// r‚cup‚ration de la rŠgle … appliquer
			var params=objInput[iCounter].className.split(" ");
			
			if(objInput[iCounter].type!="submit") //on stocke tout sauf les button!!
			{	
				if(params[0] && params[1])
				{
					var indexrule = this.IsRule(params[0]);
					if (indexrule!=-1)
					{	
						//alert(indexrule);
						this.FV_array.push(new FieldValidator(objInput[iCounter].id,params[1],this.Rules[indexrule]));
					}
					else
					{
						//alert("iCounter : "+iCounter+"-"+objInput[iCounter].id);
						this.FV_array.push(new FieldValidator(objInput[iCounter].id,"",""));
					}
				
				}
				else
				{
					//alert("iCounter : "+iCounter+"-"+objInput[iCounter].id);
					this.FV_array.push(new FieldValidator(objInput[iCounter].id,"",""));
				}
			}
		}
	}
	
	this.BuildFielValidators('input');
	this.BuildFielValidators('textarea');
			
	this.Validate = function()
	{
		var index=0;
		for(index=0;index<this.FV_array.length;index++)
		{
			if(!this.FV_array[index].validate())				
			{
				//alert(this.FV_array[index].ErrorLabel);
				this.Validated=false;
			}

		}
		
	}
	
	this.showErrors = function()
	{
		var index=0;
		for(index=0;index<this.FV_array.length;index++)
		{
			this.FV_array[index].showError();
		}
	}
	
	this.getMailData = function()
	{
		var maildata="";
		
		for(index=0;index<this.FV_array.length;index++)
		{
			var news="&"+this.FV_array[index].IdObj+"="+this.FV_array[index].value;
			maildata+=news;
			
		}
		
		return maildata;
	}

}


function SendRequest(FieldValidatorObj) {
		
	Xmlhttp.open('POST', MyFormValidator.phpCheckFile, false);
	Xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		
	// ici on passe la rŠgle en plus qui permettra de choisir la fonction ds resultat
	var data = "FieldValue="+ FieldValidatorObj.getValue()+"&Rule="+FieldValidatorObj.CheckRule;
	Xmlhttp.send(data); 
	// en local : %0D%0A
	FieldValidatorObj.ErrorLabel=escape(Xmlhttp.responseText).split("%0A")[0];

}


function CheckForm()
{
	MyFormValidator=new FormValidator('formdevis','formulaire_devis/checkrules.php');

	
	var pageToShow='formulaire_devis/email_sent.php';
	MyFormValidator.Validate();
	
	if(!MyFormValidator.Validated)
	{			
		alert("Il y a des erreurs dans la saisie de votre formulaire");
		MyFormValidator.showErrors();
		return false;
				
	}
	else
	{
		ShowDevisForm(pageToShow);
		return false; // on retourne tjs false car il faut montrer le resultat et pas fermer la popup
	
	}
}



function ShowDevisForm(pageToShow)
{ 

	var req = null; 

	if (window.XMLHttpRequest)
	{
		req = new XMLHttpRequest();
		if (req.overrideMimeType) 
		{
			req.overrideMimeType("text/html");
		}
	} 
	else if (window.ActiveXObject) 
	{
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		}
		 catch (e)
		{
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) {}
		}
        }

	function waitResponse()
	{ 
		
		if(req.readyState == 4)
		{
			if(req.status == 200)
			{
				DevisPopup.Show(req.responseText);
			}	
			else	
			{
				DevisPopup.Show("Error: returned status code " + req.status + " " + req.statusText);
			}	
		} 
	}
	
	// en synchrone la fonction onreadystatechange, ne sert … rien il faut continuer le script aprŠs le send
	if (pageToShow=='formulaire_devis/email_sent.php')
	{
		var tt=MyFormValidator.getMailData();
	
		req.open('POST', pageToShow, false);
		req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

		req.send(MyFormValidator.getMailData());
		DevisPopup.Show(req.responseText); 
	}
	else // en asynchrone on utilise une fonction callback onreadystatechange
	{	
		req.open("GET", pageToShow, true); 
		req.onreadystatechange = waitResponse;				
		req.send(null); 
	}
	
} 
