// Module de validation Javascript par PM.

//<script type="text/javascript">omv.type = 'spans';< /script> 
//ŕ placer sur le form :: onsubmit="return omv.send(this,'<%=textes("erroui")%>');"
//sinon sur la func qui submit :: 	var toto = omv.send(TheForm,'Il y a des erreurs sur la page');if (toto) TheForm.submit();
//exemple :: accept="omv.Empty('<%=textes("errnom")%>',3,-1);"
//pour un dropdown, forcer item autre que le 1er :: lang="omv.selIndex('<%=textes("errpay")%>');"
var DEFAULT_ID = "omv";

function omValidator(){
	
	this.id = (arguments.length==1) ? arguments[0] : DEFAULT_ID;
	this.caller = DEFAULT_ID;
	this.type = "alert";
	this.tags = new Array("INPUT","SELECT","TEXTAREA");
	this.errType = null;
	this.mainErr = null;
	
	this.useLoader = false;
	this.loaderId = "";
	this.hasModal = false;
	
	this.useAjax = false;
	this.ajaxFunction = "";
	this.ajaxRunning = false;
	this.ajaxSender = "omv";
	this.ajaxUrl = "";
	
	this.loaderContent = "Chargement en cours ...";
	this.inp = null; //Input en cours de traitement ...
	
	this.oldAction = null;
	
	this.isDefined = function(obj){
		//fonction probablement inutile ...
		if (typeof(obj) == "undefined") return false;
		return true;
	};
	
	//RegEx preetablies :
	this.rules = new Object();
	this.rules.email = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9_]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z.]*[a-zA-Z]$/;
	this.rules.url = /^https?\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}(\/\S*)?$/;
	this.rules.phone = /^((\d{3}|\(\d{3}\))([ -]?))?(\d{3})([ -]?)(\d{4})$/;
	this.rules.number = /[0-9]/;
//	this.rules.price = 
	
	this.form = null;
	this.formErrMess = null;
	
	//Ŕ mettre en attribut accept ou onblur ...
	//est-ce que le champ est vide?
	this.Empty = function(errMsg,nmin,nmax){
		if(this.inp.value=="" || !this.vChars(this.inp,nmin,nmax)) return this.msg(errMsg);
		return true;
	};
	
	this.dblEmpty = function(errMsg,nmin,nmax,oID,nmin2,nmax2){
		var inp2 = document.getElementById(oID);
		if((this.inp.value=="" || !this.vChars(this.inp,nmin,nmax)) || (inp2.value=="" || !this.vChars(inp2,nmin2,nmax2))){
			if(inp2.className.indexOf("omInvalid")==-1) inp2.className += " omInvalid";
			return this.msg(errMsg);
		}
		return true;
	};
	
	this.EmptyGhost = function(errMsg,nmin,nmax){
		if(this.inp.style.display!="none") return this.Empty(errMsg,nmin,nmax);
		return true;
	};
		this.showGhost = function(formel){
			if(formel.selectedIndex == formel.length-1){
				document.getElementById(formel.id+'_gh').style.display="";
				document.getElementById(formel.id+'_ghostinp').style.display="";
			}else{
				document.getElementById(formel.id+'_gh').style.display="none";
				document.getElementById(formel.id+'_ghostinp').style.display="none";
			}
		}
	
	this.Same = function(errMsg,id){
		if(this.inp.value!=document.getElementById(id).value) return this.msg(errMsg);
		return true;
	};
	
	//est-ce que c'est un chiffre?
	this.No = function(errMsg,obg,nmin,nmax){
		//alert(isNaN(this.inp.value));
		if(this.inp.value==""&&!obg) return true;
		if(isNaN(this.inp.value) || !this.vChars(this.inp,nmin,nmax)) return this.msg(errMsg);
		if(obg&&this.inp.value=="") return this.msg(errMsg);
		return true;
	};
	
	//est-ce que c'est un nombre entre nmin et nmax?
	this.Nbr = function(errMsg,obg,nmin,nmax){
		if(this.inp.value==""&&!obg) return true;
		if(isNaN(parseFloat(this.inp.value)) || !(parseFloat(this.inp.value)>=nmin && parseFloat(this.inp.value)<=nmax)) return this.msg(errMsg);
		return true;
	};
	
	//est-ce que l'element match la RegEx?
	this.Reg = function(errMsg,obg,rule){
		if(this.inp.value==""&&!obg) return true;
		var check = this.rules[rule];
		if(!check) check = rule;
		var look = new RegExp(check);
		if(!look.test(this.inp.value)) return this.msg(errMsg);
		return true;
	};
	
	//est-ce que l'index est différent de 0?
	this.selIndex = function(errMsg){
		if(this.inp.selectedIndex == 0) return this.msg(errMsg);
		return true;
	};
	
	//est-ce que le checkbox est checké?
	this.checkBool = function(errMsg){
		if(!this.inp.checked) return this.msg(errMsg);
		return true;
	};
	
	//est-ce que le champs est dépendant d'un autre ...
	this.checkDependance = function(errMsg,inp2ID){
		inp2 = document.getElementById(inp2ID);
		doValidation = false;
		switch(this.inp.tagName){
			case "INPUT" : 	switch(this.inp.type){
								case "radio" : 	
								case "checkbox" : 	if(this.inp.checked) doValidation = true;
													break;
							}
							break;
		}
		this.inp = inp2;
		if(doValidation){
			if(this.inp.value=="") return this.msg(errMsg);
		}
		return true;
	};
	
	//le calcCha
	this.calcCha = function(errMsg,calc){
		if(this.Empty(errMsg,-1,-1)){
			var isEqual = checkCalc(this.inp.value,calc);
			if(!isEqual) return this.msg(errMsg);
			return true;
		}
	};
	
	//valide le nombre de characteres
	this.vChars = function(inpobj,nmin,nmax){
		if(nmin==-1 && nmax==-1) return true;
		if(nmin==-1 || nmax==-1){
			if(nmin==-1) if(inpobj.value.length<=nmax) return true;
			if(nmax==-1) if(inpobj.value.length>=nmin) return true;
		}
		if(inpobj.value.length>=nmin && inpobj.value.length<=nmax) return true;
		return false;
	};
	
	//trouve le span d'erreur et l'efface
	this.delSpan = function(){
		if(this.inp.className.indexOf("omInvalid")>-1) this.inp.className = this.inp.className.replace("omInvalid","");
		var childs = this.inp.parentNode.childNodes;
		for(c=0;c<childs.length;c++){
			if(childs[c].tagName=="SPAN") if(childs[c].className=="omError") this.inp.parentNode.removeChild(childs[c]);
		}
	};
	
	//fonction d'affichage de l'erreur
	this.msg = function(errMsg){
		returnIt = false;
		if(this.type=="alert"){
			if(this.useLoader && window[this.caller].hasModal!=false) window[this.caller].loadpage(window[this.caller].hasModal);
			alert(errMsg);
			try { this.inp.focus(); } catch (e) { } //pourquoi c'était inp.select() ?
			if(this.inp.className.indexOf("omInvalid")==-1) this.inp.className += " omInvalid";
			//if(this.useLoader) this.showElements();
			returnIt = true;
		}else if(this.type=="spans"){
			if(this.errType!="mainErrOnly"){
				var mess = document.createElement('span');
				mess.className = "omError";
				mess.innerHTML = errMsg;
				this.delSpan();
				this.inp.parentNode.appendChild(mess);
			}
			if(this.inp.className.indexOf("omInvalid")==-1) this.inp.className += " omInvalid";
		}
		if(this.useLoader) this.unloadpage("");
		if(returnIt) return false;
	};
	
	//fonction qui simule le click d'un input "submit" encapsule dans un lien
	//devra disparaitre ...
	this.sim = function(sender){
		sender.childNodes[0].click();
	}
	//fonction qui simule un href pour IE
	this.ie = function(sender){
		if(document.all) sender.href='javascript:;';
	}
	
	this.pushUrl = function(url){
		this.oldAction = this.form.action;
		this.form.action = url;
		if(this.send(this.form, this.formErrMess)) this.form.submit();
		this.form.action = this.oldAction;
	}
	
	this.initiate = function(form,errMsg){
		//surtout utilisé pour permettre pushUrl
		this.form = form;
		this.formErrMess = errMsg;
	}
	
	this.checkGhost = function(id){
		ghost = document.getElementById("ghost"+id);
		ghost.value = (ghost.value=="1") ? "0" : "1";
	}
	
	this.loadpage = function(childID){
		this.loaderId = childID;
		if(!(typeof(Lightbox) == "undefined")){ //Vérifie la présence de Lightbox qui est nécéssaire au script.
			childBoxContent = this.loaderContent;
			if(childID==""){
				childID="loaderChild";
				loaderID="loaderDiv";
			}else{
				this.hasModal = childID;
				if(document.getElementById(childID+'Ghost')){
					childBoxContent = document.getElementById(childID+'Ghost').innerHTML;
				}
				loaderID="loaderModal";
			}
			
			var omBody = document.getElementsByTagName("body").item(0);
			var loadingHandler = document.getElementById('loadingHandler');
			
			/*if(!loadingHandler){
				loadingHandler = document.createElement("div");
				loadingHandler.setAttribute('id','loadingHandler');
				omBody.appendChild(loadingHandler);
			}*/
			
			
			if(!document.getElementById(loaderID)){
				var omLoader = document.createElement("div");
				omLoader.setAttribute('id',loaderID);
				omLoader.style.display = 'none';
				//p-e pas de onclick ... omLoader.onclick = function() { myLightbox.end(); }
				//loadingHandler.appendChild(omLoader);
				omBody.appendChild(omLoader);
			}
			if(!document.getElementById(childID)){	
				var omChild = document.createElement("div");
				omChild.setAttribute('id',childID);
				omChild.setAttribute('class','modalHolder');
				omChild.style.display = 'none';
				//p-e onclik voir dansLightbox ...
				//loadingHandler.appendChild(omChild);
				omBody.appendChild(omChild);
				
				if(childID=="loaderChild"){
					var omChildBox = document.createElement("div");
					omChildBox.setAttribute('id',childID+'Box');
					omChildBox.innerHTML = childBoxContent;
					omChild.appendChild(omChildBox);
				}else{
					var omForm = document.createElement("form");
					omForm.setAttribute('id',childID+'Form');
					omForm.setAttribute('name',childID+'Form');
					omForm.setAttribute('method','POST');
					omForm.setAttribute('action',document.getElementById(childID+'Action').value);
					omChild.appendChild(omForm);
					omForm.onsubmit = function(omForm){
						return window[document.getElementById(childID+'OnSubmit').value].send(document.getElementById(childID+'Form'),'Test');
					}
					
					var omInpOnsubmit = document.createElement("input");
					omInpOnsubmit.setAttribute('id',childID+'OnSubmit');
					omInpOnsubmit.setAttribute('type','hidden');
					omInpOnsubmit.setAttribute('value',document.getElementById(childID+'OnSubmit').value);
					omForm.appendChild(omInpOnsubmit);
					
					document.getElementById(childID+'Ghost').innerHTML = "";
					
					var omChildBox = document.createElement("div");
					omChildBox.setAttribute('id',childID+'Box');
					omChildBox.setAttribute('class','modalBox');
					omChildBox.innerHTML = childBoxContent;
					omForm.appendChild(omChildBox);
				}
			}
			
			omChildBox = document.getElementById(childID+'Box');
			
			hideSelectBoxes(); //dans LightBox
			hideFlash(); //dans LightBox
			
			var omPageSize = getPageSize(); //dans Lightbox
			Element.setHeight(loaderID, omPageSize[1]); //dans LightBox
			new Effect.Appear(loaderID, { duration: 0, from: 0.0, to: 0.8 }); //dans LightBox
			Element.show(childID);
			
			// calcul la position du top de la boite de l'enfant
			var omPageScroll = getPageScroll(); //dans LightBox
			var childTop = omPageScroll[1] + (omPageSize[3] / 2) - (omChildBox.offsetHeight/2); //dans LightBox
			Element.setTop(childID, childTop); //dans LightBox
			
			var omSelects = omChildBox.getElementsByTagName("select");
			for (i = 0; i != omSelects.length; i++) {
				omSelects[i].style.visibility = "visible";
			}
		}else{
			alert('Vous devez inclure les scripts du LightBox pour utiliser le loader :\n   - prototype.js\n   - scriptaculous.js\n   - effects.js\n   - lightbox.js');
		}
	}
	this.unloadpage = function(childID){
		var forceReshow = (arguments.length==2 && arguments[1]!="") ? true : false;
		this.loaderId = childID;
		
		if(!(typeof(Lightbox) == "undefined")){ //Vérifie la présence de Lightbox qui est nécéssaire au script.
			loaderID="loaderModal";
			reShowHidden=true;
			if(childID==""){
				childID="loaderChild";
				loaderID="loaderDiv";
				reShowHidden=false;
			}else{
				this.hasModal = false;
			}
			
			Element.hide(childID); //dans LightBox
			new Effect.Fade(loaderID, { duration: 0}); //dans LightBox
			
			if(reShowHidden || forceReshow){
				showSelectBoxes(this.loaderId); //dans LightBox
				if(!this.hasModal) showSelectBoxes();
				showFlash(); //dans LightBox
			}
		}
	}
	
	//fonction generale de validation et d'envoi du formulaire :
	//doit etre place dans le onsubmit du form ainsi : onsubmit="return omv.send(this,'Erreur X');"
	this.send = function(form,errMsg){
		if(this.useLoader) this.loadpage("");
		this.form = form;
		this.formErrMess = errMsg;
		
		var err = false;
		var attributes = new Array("accept","lang","lang");
		var toEval = null;

		for(i=0;i<this.tags.length;i++){
			var inputs = this.form.getElementsByTagName(this.tags[i]);
			/*for(j=0;j<inputs.length;j++){}*/
			for(j=0;j<inputs.length;j++){
				this.inp = inputs[j];
				
				//le try s'assure que la fonction existe, si elle n'existe pas
				//il n'y aura simplement pas de validation
				toEval = this.inp.getAttribute(attributes[i]);
				if(toEval!=null){
					if(toEval.indexOf(this.id)!=-1){
				
						try{iEval = eval(toEval);}catch(err){iEval = true;}
						
						if(this.type=="alert"){
							if(toEval) if(!iEval) return false;
							if(this.inp.className.indexOf("omInvalid")>-1) this.inp.className = this.inp.className.replace("omInvalid","");
						}else if(this.type=="spans"){
							if(toEval) if(!iEval){err=true;}else{this.delSpan();}
						}
					}
				}
			}
		}
		if(err){
			
			switch(this.errType){
				case "mainErrOnly" :
				case "noalert" : 		this.mainErr.style.display="";
										break;
									
				default : 	alert(this.formErrMess);
							break;
			}
			
			if(this.useLoader) this.showElements(this.loaderId);
			return false;
		}
	
		if(!this.useAjax){
			return true;
		}else{
			window[this.ajaxFunction]();
			return false;
		}
	};
	
	this.showElements = function(loaderId){
		
		if(!(typeof(Lightbox) == "undefined")){ //Vérifie la présence de Lightbox qui est nécéssaire au script.
			showSelectBoxes(loaderId); //dans LightBox
			showFlash(); //dans LightBox
		}
	};
	
	this.ajaxStart = function(){
		this.ajaxRunning = true;
		window[this.ajaxSender].loadpage('');
	
	}
	this.ajaxEnd = function(reloadID){
		this.ajaxRunning = false;
		window[this.ajaxSender].unloadpage('');
		window[this.ajaxSender].loadpage(reloadID);
	}
	
	this.BuildAjaxURL = function(modalID,dstroy){
		var fieldHolder = document.getElementById(modalID);
		var aUrl = (this.ajaxUrl.indexOf("?")==-1) ? this.ajaxUrl + '?' : this.ajaxUrl + '&';
		
		var aFields = (document.getElementById('champs')) ? document.getElementById('champs').value : "";
		for(ai=0;ai<this.tags.length;ai++){
			var ajaxInps = fieldHolder.getElementsByTagName(this.tags[ai]);
			for(ak=0;ak<ajaxInps.length;ak++){
				if(ajaxInps[ak].id.indexOf("field"+modalID)!=-1){
					fieldName = ajaxInps[ak].name;
					fieldValue = ajaxInps[ak].value;
					
					if(ajaxInps[ak].tagName=="INPUT" && ajaxInps[ak].type=="checkbox"){
						fieldValue = (ajaxInps[ak].checked) ? "1" : "0";
					}
					
					aUrl +=  fieldName + "=" + fieldValue + "&";
					
					if(dstroy){
						switch(ajaxInps[ak].tagName){
							case "INPUT" :	switch(ajaxInps[ak].type){
												case "checkbox" :   ajaxInps[ak].checked=false;
																	break;
												case "hidden" :   ajaxInps[ak].value=ajaxInps[ak].value;
																	break;
												default : 	ajaxInps[ak].value = "";
															break;
											}
											break;
											
							case "SELECT" : ajaxInps[ak].selectedIndex = 0;
											break;
											
							case "TEXTAREA" : 	ajaxInps[ak].value = "";
												break;
						}
					}
				}
			}
		}
		aUrl = aUrl.substr(0,aUrl.length-1);
		if (aFields!="") aUrl = aUrl + '&champs=' + aFields;
		return aUrl;
	}
}
var is_equal;
function checkCalc(r,qs){
	XmlRequestSetup.IsAsync = false;
	XmlRequestSetup.url = "/ajax/ajax.calcCha.asp?qs="+qs+"&r="+r;
	XmlRequestSetup.ReturnFunction = rCalcCha;
	XmlRequestSetup.MAXIMUM_WAITING_TIME = 1000;
	XmlRequest();
	eq = (is_equal==0) ? false : true;
	return eq;
};
function rCalcCha(xmlResponse){
	is_equal = xmlResponse;
}
var omv = new omValidator();