/*
* Really easy field validation with Prototype
* http://tetlaw.id.au/view/javascript/really-easy-field-validation
* Andrew Tetlaw
* Version 1.5.4.1 (2007-01-05)
* 
* Copyright (c) 2007 Andrew Tetlaw
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* 
*/

//la funcion "IsUnsignedInteger(YourNumber)" chequea si "YourNumber" es un numero entero sin signo valido
//La variable "YourNumber" es una cadena de caracteres
function IsUnsignedInteger(YourNumber)
{
	var Template = /^d+$/ //Formato de numero entero sin signo
	return (Template.test(YourNumber)) ? 1 : 0 //Compara "YourNumber" con el formato "Template" y si coincidevuelve verdadero si no devuelve falso
}

//la funcion "IsChar(YourChar)" chequea si "YourChar" es una letra valida
//La variable "YourChar" es una cadena de caracteres
function IsChar(YourChar)
{
	var Template = /^[a-z]$/i //Formato de letra
	return (Template.test(YourChar)) ? 1 : 0 //Compara "YourChar" con el formato "Template" y si coincidevuelve verdadero si no devuelve falso
}

//la funcion "IsAlphaNumeric(YourAlphaNumeric)" chequea si "YourAlphaNumeric" es una letra valida
//La variable "YourAlphaNumeric" es una cadena de caracteres
function IsAlphaNumeric(YourAlphaNumeric)
{
	var Template = /^[a-z0-9]+$/i //Formato de alfanumerico
	return (Template.test(YourAlphaNumeric)) ? 1 : 0 //Compara "YourAlphaNumeric" con el formato "Template" y si coincidevuelve verdadero si no devuelve falso
}

//la funcion "IsMail(YourMail)" chequea si "YourMail" es una direccion de correo electronico valida
//La variable "YourMail" es una cadena de caracteres
function IsMail(YourMail)
{
	var Template = /^[a-z][a-z-_0-9.]+@[a-z-_=>0-9.]+.[a-z]{2,3}$/i //Formato de direccion de correo electronico
	return (Template.test(YourMail)) ? 1 : 0 //Compara "YourMail" con el formato "Template" y si coincidevuelve verdadero si no devuelve falso
}

function IsNIF(YourNIF)
{
		//alert(IsChar(YourNIF.substring(8, 9)))
	/*if (YourNIF.length != 9) return 0 //Si la longitud de "YourNIF" es menor que 9 devuelve falso
	else if (!IsUnsignedInteger(YourNIF.substring(0, 8))) return 0 //Si los ocho primeros digitos no forman un numero entero sin signo valido devuelve falso
	else if (!IsChar(YourNIF.substring(8, 9))) return 0 //Si el ultimo digito no es una letra valida devuelve falso
	else
	{*/
		var ControlValue = 0 //Control de calculos segun el criterio de correccion
		var NIFCharIndex = 0 //Almacenara la posicion de la letra correpondiente a la parte numerica del DNI con respecto al array "NIFChars"
		//El siguiente array "NIFChars" contiene las letras de DNI ordenadas segun el criterio de correccion
		var MaxLen = YourNIF.length
		var NIFChars = new Array('T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E')
		var FirstDigit = YourNIF.substring(0,1)//Almacenamos el primer digito para ver si es NIF o NIE
		FirstDigit = FirstDigit.toUpperCase() //Pasamos la letra del NIE a mayusculas por si acaso estaba en minusculas
		if(FirstDigit=='X'){
			var NIFNumber = '0'+(YourNIF.substring(1, MaxLen-1)) //Almacenanos la parte numerica del NIE en "NIFNumber"
		}
		else{
			var NIFNumber = YourNIF.substring(0, MaxLen-1) //Almacenanos la parte numerica del DNI en "NIFNumber"
		}
		var NIFChar = YourNIF.substring(MaxLen-1, MaxLen) //Almacenamos la letra del DNI en "NIFChar"
		NIFChar = NIFChar.toUpperCase() //Pasamos la letra del DNI a mayusculas por si acaso estaba en minusculas
		//Los siguientes 4 calculos sirven para calcular la posicion de la letra correspondiente al la parte numerica del DNI "NIFNumber" en en array "NIFChars"
		ControlValue = NIFNumber / NIFChars.length
		ControlValue = Math.floor(ControlValue);
		ControlValue = ControlValue * NIFChars.length
		NIFCharIndex = NIFNumber - ControlValue
		return (NIFChar == NIFChars[NIFCharIndex]) ? 1 : 0 //Si la letra coincide con la letra dada devuelve verdadero si no devuelve falso
	//}
}

var Validator = Class.create();

Validator.prototype = {
	initialize : function(className, error, test, options) {
		if(typeof test == 'function'){
			this.options = $H(options);
			this._test = test;
		} else {
			this.options = $H(test);
			this._test = function(){return true};
		}
		this.error = error || 'Validation failed.';
		this.className = className;
	},
	test : function(v, elm) {
		return (this._test(v,elm) && this.options.all(function(p){
			return Validator.methods[p.key] ? Validator.methods[p.key](v,elm,p.value) : true;
		}));
	}
}
Validator.methods = {
	pattern : function(v,elm,opt) {return Validation.get('IsEmpty').test(v) || opt.test(v)},
	minLength : function(v,elm,opt) {return v.length >= opt},
	maxLength : function(v,elm,opt) {return v.length <= opt},
	min : function(v,elm,opt) {return v >= parseFloat(opt)}, 
	max : function(v,elm,opt) {return v <= parseFloat(opt)},
	notOneOf : function(v,elm,opt) {return $A(opt).all(function(value) {
		return v != value;
	})},
	oneOf : function(v,elm,opt) {return $A(opt).any(function(value) {
		return v == value;
	})},
	is : function(v,elm,opt) {return v == opt},
	isNot : function(v,elm,opt) {return v != opt},
	equalToField : function(v,elm,opt) {return v == $F(opt)},
	equalToPhone : function(v,elm,opt) {return (v != "" || $F(opt)!="")},	
	notEqualToField : function(v,elm,opt) {return v != $F(opt)},
	notEmptyToField : function(v,elm,opt) {
		return (v != "" || $F(opt)!="")
		},
	include : function(v,elm,opt) {return $A(opt).all(function(value) {
		return Validation.get(value).test(v,elm);
	})}
}

var Validation = Class.create();

Validation.prototype = {
	initialize : function(form, options){
		this.options = Object.extend({
			onSubmit : true,
			stopOnFirst : false,
			immediate : true,
			focusOnError : false,
			useTitles : true,
			onFormValidate : function(result, form) {},
			onElementValidate : function(result, elm) {}
		}, options || {});
		this.form = $(form);
		if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
		if(this.options.immediate) {
			var useTitles = this.options.useTitles;
			var callback = this.options.onElementValidate;
			Form.getElements(this.form).each(function(input) { // Thanks Mike!
				Event.observe(input, 'blur', function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, onElementValidate : callback}); });
			});
		}
	},
	onSubmit :  function(ev){
		if(!this.validate()){
			Event.stop(ev);
	//	document.getElementById("mssgerror").style.display="block"	
		} 
		

			
	},
	validate : function() {
		var result = false;
		var useTitles = this.options.useTitles;
		var callback = this.options.onElementValidate;
		if(this.options.stopOnFirst) {
			result = Form.getElements(this.form).all(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); });
		} else {
			result = Form.getElements(this.form).collect(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); }).all();
		}
		if(!result && this.options.focusOnError) {
			Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
		}
		this.options.onFormValidate(result, this.form);
		return result;
	},
	reset : function() {
		Form.getElements(this.form).each(Validation.reset);
	}
}

Object.extend(Validation, {
	validate : function(elm, options){
		options = Object.extend({
			useTitle : false,
			onElementValidate : function(result, elm) {}
		}, options || {});
		elm = $(elm);
		var cn = elm.classNames();
		return result = cn.all(function(value) {
			var test = Validation.test(value,elm,options.useTitle);
			options.onElementValidate(test, elm);
			return test;
		});
	},
	test : function(name, elm, useTitle) {
		var v = Validation.get(name);
		var prop = '__advice'+name.camelize();
		try {
		if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
			if(!elm[prop]) {
				var advice = Validation.getAdvice(name, elm);
				if(advice == null) {
					var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
					var valfunction = "muestraAyuda(event, '" + errorMsg + "')"
					var valfunction2 = "ocultaAyuda()"
					
					//advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none" ><a href="javascript:void(0)" style="cursor:pointer !important;" onmouseout="javascript:ocultaAyuda()" onmouseover="'+valfunction+'"><img src="img/base/btn_error.gif" border=0></a></div>'
				
				
					advice = '<span  class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none" ><img style="vertical-align:bottom;"src="img/registro/alert.gif" border=0>'+ errorMsg + '</span>'
				 
					switch (elm.type.toLowerCase()) {
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;
							if(p) {
								new Insertion.Bottom(p, advice);
							} else {
								new Insertion.After(elm, advice);
							}
							break;
						default:
							new Insertion.After(elm, advice);
				    }
					advice = Validation.getAdvice(name, elm);
				}
				if(typeof Effect == 'undefined') {
					//advice.style.display = 'block';
					advice.style.display = 'inline';
				} else {
					new Effect.Appear(advice, {duration : 1 });
				}
			}
			elm[prop] = true;
			elm.removeClassName('validation-passed');
			elm.addClassName('validation-failed');
			return false;
		} else {
			var advice = Validation.getAdvice(name, elm);
			if(advice != null) advice.hide();
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			elm.addClassName('validation-passed');
			return true;
		}
		} catch(e) {
			throw(e)
		}
	},
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = elm.parentNode;
		}
		return true;
	},
	getAdvice : function(name, elm) {
		return $('advice-' + name + '-' + Validation.getElmID(elm)) || $('advice-' + Validation.getElmID(elm));
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	},
	reset : function(elm) {
		elm = $(elm);
		var cn = elm.classNames();
		cn.each(function(value) {
			var prop = '__advice'+value.camelize();
			if(elm[prop]) {
				var advice = Validation.getAdvice(value, elm);
				advice.hide();
				elm[prop] = '';
			}
			elm.removeClassName('validation-failed');
			elm.removeClassName('validation-passed');
		});
	},
	add : function(className, error, test, options) {
		var nv = {};
		nv[className] = new Validator(className, error, test, options);
		Object.extend(Validation.methods, nv);
	},
	addAllThese : function(validators) {
		var nv = {};
		$A(validators).each(function(value) {
				nv[value[0]] = new Validator(value[0], value[1], value[2], (value.length > 3 ? value[3] : {}));
			});
		Object.extend(Validation.methods, nv);
	},
	get : function(name) {
		return  Validation.methods[name] ? Validation.methods[name] : Validation.methods['_LikeNoIDIEverSaw_'];
	},
	methods : {
		'_LikeNoIDIEverSaw_' : new Validator('_LikeNoIDIEverSaw_','',{})
	}
});

Validation.add('IsEmpty', '', function(v) {
			return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
			});
			
			Validation.add('isFecha', '', function(v) {
				
				var fechas = v.split("/");		
				
				if(fechas[0]>=12 && fechas[0]<=21){
					if(fechas[1]==6){
						if(fechas[2]==2008){
							return true
						}else{
							return false	
						}
					}else{
						return false
					}
				}else
				{
					return false
				} // || /^\s+$/.test(v));
			});

Validation.addAllThese([
	['phone-one-required', 'Este campo es obligatorio.', function(v) {
			return !Validation.get('IsEmpty').test(v) && !Validation.get('IsEmpty').test(v);
			}],	
	['required_option', ' Campo obligatorio', function(v) {
			return !Validation.get('IsEmpty').test(v);
			}],	
	['required-num', 'El numero de digitos no es correcto.', function(v) {
			return !Validation.get('IsEmpty').test(v);
		}],
	['required-fecha', 'El formato de la fecha no es correcto', function(v) {
				return Validation.get('isFecha').test(v);
		}],
	['required', '<-- Este campo es obligatorio.', function(v) {
			return !Validation.get('IsEmpty').test(v);
		}],
	['validate-number', '<-- Por favor, introduzca solo dígitos.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));

			}],
	['validate-digits', 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-alpha', '<-- Por favor use únicamente caracteres.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
			}],
	['validate-alphanum', 'Por favor use únicamente caracteres alfanuméricos.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
			}],
	['validate-name', 'Por favor use únicamente caracteres y espacios, 3 caracteres mínimo.', function(v) {
				return Validation.get('IsEmpty').test(v) || /^[A-Za-zŔ-ÖŘ-öř-˙ \.]{3,30}$/.test(v)
			}],
		
	['validate-date', 'Please enter a valid date.', function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
			}],
	['validate-email', 'Por favor introduzca un email correcto.', function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v) 
			}],
	['validate-dni', '<-- Por favor introduzca un DNI correcto.', function (v) {
				//alert(IsNIF(v));
				return IsNIF(v)
			}],	
	['isPhone', '<-- El teléfono ha de empezar por 9 y tener 9 dígitos.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(9)\d{8}/.test(v)
			}],	
	['isMobile', '<-- El m&oacute;vil ha de empezar por 6 y tener 9 d&iacute;gitos.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(6)\d{8}/.test(v)
			}],	
	['isZipCode', '<-- El codigo postal introducido es incorrecto.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^([1-9]{2}|[0-9][1-9]|[0-9][0-9])([1-9][1-9][1-9]|[1-9][1-9][0-9]|[1-9][0-9][1-9]|[0-9][1-9][1-9]|[1-9][0-9][0-9]|[0-9][0-9][1-9]|[0-9][1-9][0-9])$/.test(v) && v<=52006
			}],	
	['validate-provincia', 'La provincia no coincide con el codigo postal.', function(v) {
				//alert($F('CodigoPostal')+""+v);
				return v == $F('CodigoPostal').substring(0,2)
			}],	
	['validate-url', 'Please enter a valid URL.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
			}],
	['validate-date-au', 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.', function(v) {
				if(Validation.get('IsEmpty').test(v)) return true;
				var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
				if(!regex.test(v)) return false;
				var d = new Date(v.replace(regex, '$2/$1/$3'));
				return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) && 
							(parseInt(RegExp.$1, 10) == d.getDate()) && 
							(parseInt(RegExp.$3, 10) == d.getFullYear() );
			}],
	['validate-selection', '<-- Por favor. Escoja una opci&oacute;n', function(v,elm){
				return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
			}],
	['validate-one-required', '<-- Por favor escoja una de las opciones.', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}]
]);



Validation.add('class-password-length', 'El password tiene que tener entre 4 y 10 caracteres', {
     minLength : 4, // value must be at least 4 characters
     maxLength : 10, // value must be no longer than 13 characters
     notEqualToField : 'Email' // value is not equal to the form element with this ID
});



Validation.add('class-password-validar', '<-- Los passwords no coinciden', {
     equalToField : 'Contrasenya', // value is equal to the form element with this ID
     include : ['validate-alphanum'] // also tests each validator included in this array of validator keys (there are no sanity checks so beware infinite loops!)
});


Validation.add('class-email-validar', 'Los e-mails no coinciden', {
     equalToField : 'Email' // value is equal to the form element with this ID
});

Validation.add('class-email-validar-padre', 'Los e-mails no coinciden', {
     equalToField : 'Email_padre' // value is equal to the form element with this ID
});

Validation.add('class-email-hijo', 'El email del padre no puede ser igual que el del hijo', {
     notEqualToField : 'Email' // value is equal to the form element with this ID
});

Validation.add('class-phone-validar', 'Los telefonos no coinciden', {
     notEmptyToField : 'client_fijo' // value is equal to the form element with this ID
});

Validation.add('class-mobile-validar', 'Los telefonos no coinciden', {
     notEmptyToField : 'client_movil' // value is equal to the form element with this ID
});

Validation.add('codigo-de-barras', 'Los codigos deben ser diferentes', {
      notEqualToField : 'codigoBarras_1' // value is equal to the form element with this ID
	
});

// Mensajes de ayuda
if(navigator.userAgent.indexOf("MSIE")>=0) navegador=0;
else navegador=1;

function colocaAyuda(event)
{
	if(navegador==0)
	{
		var corX=window.event.clientX+document.documentElement.scrollLeft-205;
		var corY=window.event.clientY+document.documentElement.scrollTop-127;
	}
	else
	{
		var corX=event.clientX+window.scrollX-205;
		var corY=event.clientY+window.scrollY-127;
	}
	document.getElementById("ayudaTexto").style.top=corY+100+"px";
	document.getElementById("ayudaTexto").style.left=corX-80+"px";
}

function ocultaAyuda()
{
document.getElementById("ayudaTexto").style.display="none";
	if(navegador==0) 
	{
		document.detachEvent("onmousemove", colocaAyuda);
		document.detachEvent("onmouseout", ocultaAyuda);
	}
	else 
	{
		document.removeEventListener("mousemove", colocaAyuda, true);
		document.removeEventListener("mouseout", ocultaAyuda, true);
	}
}

function muestraAyuda(event, campo)
{
	colocaAyuda(event);
	
	if(navegador==0) 
	{ 
		document.attachEvent("onmousemove", colocaAyuda); 
		document.attachEvent("onmouseout", ocultaAyuda); 
	}
	else 
	{
		document.addEventListener("mousemove", colocaAyuda, true);
		document.addEventListener("mouseout", ocultaAyuda, true);
	}
	document.getElementById("ayudaTexto").style.display="block";
	document.getElementById("ayudaTexto").innerHTML=campo;
	document.getElementById("ayudaTexto").style.background="#FFFFFF";
//	document.getElementById("mensajesAyuda").style.display="block";
}