/*
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ---- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
   Validación de formularios
   version:  d08-m06-a06
//  -- -- -- -- -- -- -- -- --
//  Mauricio F. Tolezano (www.acuataller.com)
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ---- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
// 
//
*/


es.aquataller.utiles.ValidarFormulario = function( rv, ef ) 
{
	this.reglasValidacion	= rv;
	this.errorEnvio			= ef;
	
	this._asignarEventos();
}


es.aquataller.utiles.ValidarFormulario.prototype._asignarEventos = function() 
{
	var eventoSubmit = false;
	for (var idCampo in this.reglasValidacion) 
	{
		var campo = document.getElementById( idCampo ); 
		if(campo)
		{
			this._asignarEvento(campo, 'blur', this._validarCampo, false); 
			if(!eventoSubmit){
				var formulario = campo.form;
				this._asignarEvento(formulario, 'submit', this._validarCampos, false);
				// PARCHE para recuoerar el Scope de esta clase
				campo.form.vf = this;
				eventoSubmit = true;
			}
		}
	}	
}


es.aquataller.utiles.ValidarFormulario.prototype._validarCampo = function( e, c ) 
{
	var campo = (c)? c : window.event ? window.event.srcElement : e ? e.target : null;   
	if (!campo) return;
	// PARCHE
	var vf 	= campo.form.vf; // PARCHE Scope, recuperando el scope de esta clase.
				
	var campoObligatorio = vf._comprobarCampoObligatorio(campo);	
	if(!campoObligatorio){
		vf._errorCampoObligatorio(campo);				
		return false;
	}else{
		var campoValido = vf._comprobarValorCampo(campo);
		if(!campoValido){
			vf._errorCampoInvalido(campo);
		}else{
			vf._borrarError(campo);
		}
		return campoValido;	
	}
}



es.aquataller.utiles.ValidarFormulario.prototype._comprobarCampoObligatorio = function( campo ) 
{
	var idCampo = campo.id;
	var reglaCampo = this.reglasValidacion[idCampo];

	if(reglaCampo && reglaCampo['obligatorio'] ) {
		 return !this._comprobarCampoVacio(campo.value);
	}
	return true;
}

es.aquataller.utiles.ValidarFormulario.prototype._comprobarCampoVacio = function( dato ) 
{
	// No permite estar vacio o contener solo carcteres de espacios en blanco.
	return dato.match( /^\d*$|^\s+$/ ) != null;	
}

es.aquataller.utiles.ValidarFormulario.prototype._comprobarValorCampo = function( campo ) 
{
	var idCampo = campo.id;
	var reglaCampo = this.reglasValidacion[idCampo];

	if(reglaCampo && reglaCampo['regla'])
	{						
		if( 
		   		reglaCampo['obligatorio']	// Campo obligatorio											
				||
				(
					!reglaCampo['obligatorio'] 	&& 			// Campo opcional. 	
					!this._comprobarCampoVacio(campo.value)	// Se valida solo si contiene datos.
				)
			)			
		{			
			return campo.value.match(reglaCampo['regla']) != null;	
		}else{
			// Campo opcional vacio.
			return true;			
		}
	}else{
		// No existe regla de validacióm para el campo y se pasa por alto.
		return true;		
	}	
}


es.aquataller.utiles.ValidarFormulario.prototype._errorCampoObligatorio = function( campo ) 
{
	var idCampo 				= campo.id;
	var reglaCampo 				= this.reglasValidacion[idCampo];

	if(reglaCampo && reglaCampo['obligatorio']){
		this._mostrarMensaje(campo,reglaCampo['obligatorio']);	
	}
}


es.aquataller.utiles.ValidarFormulario.prototype._errorCampoInvalido = function( campo ) 
{
	var idCampo 				= campo.id;
	var reglaCampo 				= this.reglasValidacion[idCampo];

	if(reglaCampo && reglaCampo['error']){
		this._mostrarMensaje(campo,reglaCampo['error']);	
	}
}


es.aquataller.utiles.ValidarFormulario.prototype._mostrarMensaje = function( campo, mensaje ) 
{
	var idCampo 			 = campo.id;
	var idMensajeError 		 = this._idMensajeError(idCampo);
	var elementoMensajeError =  document.getElementById( idMensajeError );

	if(!elementoMensajeError) 
	{		
		elementoMensajeError = this._createElement('span');
		elementoMensajeError.id = idMensajeError;
		elementoMensajeError.className = 'mensaje';	
		var limpieza = document.createTextNode(mensaje);
		elementoMensajeError.appendChild( document.createTextNode(mensaje) );
		
		// Elemento HTML label asociado al campo .
		var etiquetaCampo = this._etiquetaCampo(campo);
		this._asignarEstilo(etiquetaCampo, 'error');
		etiquetaCampo.appendChild(elementoMensajeError);		
	}
	else if( mensaje != elementoMensajeError.firstChild.nodeValue)
	{			
		elementoMensajeError.replaceChild(document.createTextNode(mensaje),elementoMensajeError.firstChild);
	}	
}


es.aquataller.utiles.ValidarFormulario.prototype._borrarError = function( campo ) 
{
	var idCampo 			 = campo.id;
	var idMensajeError 		 = this._idMensajeError(idCampo);	
	var elementoMensajeError =  document.getElementById( idMensajeError );
	
	if(elementoMensajeError) {
		var etiquetaCampo = this._etiquetaCampo(campo);	
		etiquetaCampo.removeChild(elementoMensajeError);
		this._eliminarEstilo(etiquetaCampo, 'error');			
	}
}


es.aquataller.utiles.ValidarFormulario.prototype._idMensajeError = function( idCampo ) 
{
	return 'vf_error_'+idCampo;
}


es.aquataller.utiles.ValidarFormulario.prototype._etiquetaCampo = function(campo) 
{
	var etiquetaCampo = false;	
	var idCampo = campo.id;	
	var formulario = campo.form;	
	var etiquetas = formulario.getElementsByTagName('label');
	
	// Buscando etiqueta asociada al campo mediante "for".
	for (var i=0; i<etiquetas.length; i++) {
		if(etiquetas[i].htmlFor == idCampo){
			return etiquetas[i];
			break;			
		}		
	}	
	// Buscando etiqueta alrededor del campo.
	var elemntoHTML = campo;
	while(elemntoHTML.parentNode) {
		elemntoHTML = elemntoHTML.parentNode;	
		if(elemntoHTML.tagName.toLowerCase() == 'label'){
			return elemntoHTML;
			break;
		}
	}	
}



es.aquataller.utiles.ValidarFormulario.prototype._validarCampos = function(e) 
{
	var formulario = window.event ? window.event.srcElement : e ? e.target : null;   
	if (!formulario) return;
	// PARCHE
	var vf 	= formulario.vf; // Scope, recuperando esta clase.	
	
	var r = true;
	var etiquetas = formulario.getElementsByTagName('label');	
	for (var idCampo in vf.reglasValidacion) 
	{
		var campo = document.getElementById( idCampo ); 
		if(campo){
			if(r) r = vf._validarCampo(false, campo);
		}
	}		

	if(!r){
		alert(vf.errorEnvio);		
		if (e && e.stopPropagation && e.preventDefault) {
			e.stopPropagation();
			e.preventDefault();
		}
		if (window.event) {
			window.event.cancelBubble = true;
			window.event.returnValue = false;
			return false;
		}
	}
	return r;
}

es.aquataller.utiles.ValidarFormulario.prototype._createElement = function (element) {
  if (typeof document.createElementNS != 'undefined') {
    return document.createElementNS('http://www.w3.org/1999/xhtml', element);
  }
  if (typeof document.createElement != 'undefined') {
    return document.createElement(element);
  }
  return false;
}


es.aquataller.utiles.ValidarFormulario.prototype._asignarEstilo = function(target, classValue) 
{	
	var pattern = new RegExp("(^| )" + classValue + "( |$)");	
	if (!pattern.test(target.className)) {
		if (target.className == ""){
		  target.className = classValue;
		}else{
		  target.className += " " + classValue;
		}
	}	
	return true;
}


es.aquataller.utiles.ValidarFormulario.prototype._eliminarEstilo = function(target, classValue) 
{
	var removedClass = target.className;
	var pattern = new RegExp("(^| )" + classValue + "( |$)");
	
	removedClass = removedClass.replace(pattern, "$1");
	removedClass = removedClass.replace(/ $/, "");
	
	target.className = removedClass;
	
	return true;
}	


es.aquataller.utiles.ValidarFormulario.prototype._asignarEvento = function(target, eventType, functionRef, capture) 
{
	if (typeof target.addEventListener != "undefined") {
		target.addEventListener(eventType, functionRef, capture);
	} else if (typeof target.attachEvent != "undefined") {
		target.attachEvent("on" + eventType, functionRef);
	}else{
		eventType = "on" + eventType;
	
		if (typeof target[eventType] == "function") {
			var oldListener = target[eventType];
		
			target[eventType] = function() {
				oldListener();				
				return  functionRef();
			}
		}else{
		  target[eventType] = functionRef;
		}
	}  
}




