/*
 * Really easy field validation with Prototype
 * http://tetlaw.id.au/view/blog/really-easy-field-validation-with-prototype
 * Andrew Tetlaw
 * Version 1.5.3 (2006-07-15)
 * 
 * Copyright (c) 2006 Andrew Tetlaw
 * http://www.opensource.org/licenses/mit-license.php
 */
Validator = Class.create();

Validator.prototype = {
	initialize : function(className, error, test, options) {
		this.options = Object.extend({}, options || {});
		this._test = test ? test : function(v,elm){ return true };
		this.error = error ? error : 'Validation failed.';
		this.className = className;
	},
	test : function(v, elm) {
		return this._test(v,elm);
	}
}

function isRut(strRut, fieldRut){
	var c = 0;
	var rut_array = strRut.split("-");

	if(strRut.length < 6 || rut_array[0].length < 5 )
		return false;
		
	//condicion ? con guión : sin guión;
	var rut = (rut_array[0].length == strRut.length)?rut_array[0].substring(0,strRut.length-1):rut_array[0];
	var dv = (rut_array[0].length == strRut.length)?rut_array[0].substring(strRut.length-1,strRut.length):rut_array[1];
								
	var digVerif = Get_dv(rut);
	//alert("digito:" + digVerif + "| dig ing:"+dv+"|");
	if(digVerif != dv.toUpperCase())
		return false;

	fieldRut.value = formatRut(rut, dv);
	return true;
}
function formatRut(rut, dv){
	//concatena en la variable Numero sólo los dígitos de la primera parte del rut, obviando cualquie rotro caracter.
	var Numero = "";
	var sLength = rut.length;
	for(i=0;i<sLength;i++) {
		Carac = parseInt(rut.charAt(i),10);
		if(Carac >=0 && Carac <=9) {
			Numero+=rut.charAt(i);
		}
	}
	//concatena en la variable rutfinal sólo los dígitos de la primera parte del rut más "." cada 3 caracteres
	var rutfinal = ""
	var count = 0;
	rut = Numero;
	sLength = rut.length;
	while(sLength > -1) {
		count ++;
		rutfinal = (count==4 || count ==7)?"." + rut.charAt(sLength) + rutfinal:rut.charAt(sLength) + rutfinal;
		sLength--;
	}
	rutfinal = rutfinal+"-"+dv.toUpperCase();
	return (rutfinal);
	
}
// Retorna el Digito verificador de un RUT.
function Get_dv(strRut) {

    var Largo, LargoN, i, Total;
    var Numero="", Verif, Carac, CaracVal;
    var tmpRut,intTmp;

    tmpRut = trim(strRut);
    Largo = tmpRut.length;
    LargoN = 0;
    
    for(i=0;i<Largo;i++) {
        Carac = parseInt(tmpRut.charAt(i),10);
        if(Carac >=0 && Carac <=9) {
			Numero+=tmpRut.charAt(i);
          LargoN++;
	 	}
    }

	Total=0;
    for(i=LargoN-1;i>=0;i--) {
		if((LargoN - i) < 7) 
		   intTmp=LargoN - i + 1;
		else
		   intTmp=LargoN - i - 5;
        Total+= parseInt(Numero.charAt(i),10) * intTmp;
    }
    
    CaracVal = 11 - (Total % 11);
    
    if(CaracVal==10) 
       return('K');
	
	if(CaracVal >=0 && CaracVal <=9) 
       return(CaracVal);
	
	if(CaracVal==11) 
	   return(0);
}


var Validation = Class.create();

Validation.prototype = {
	initialize : function(form, options){
		this.options = Object.extend({
			onSubmit : true,
			stopOnFirst : false,
			immediate : false,
			focusOnError : true,
			useTitles : false,
			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);
	},
	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();
		if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
			if(!elm[prop]) {
				var advice = Validation.getAdvice(name, elm);
				if(typeof advice == 'undefined') {
					var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
					advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'
					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 = $('advice-' + name + '-' + Validation.getElmID(elm));
				}
				if(typeof Effect == 'undefined') {
					advice.style.display = 'block';
				} 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(typeof advice != 'undefined') advice.hide();
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			elm.addClassName('validation-passed');
			return true;
		}
	},
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = elm.parentNode;
		}
		return true;
	},
	getAdvice : function(name, elm) {
		return Try.these(
			function(){ return $('advice-' + name + '-' + Validation.getElmID(elm)) },
			function(){ return $('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] : new Validator();
	},
	methods : {}
});

Validation.add('IsEmpty', '', function(v) {
				return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
			});

Validation.addAllThese([
	['required', 'Este es un Campo Requerido.', function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['validate-number', 'Por favor ingrese un número válido en este campo.', function(v) {
				//return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
				return Validation.get('IsEmpty').test(v) || !isNaN(v);
			}],
	['validate-digits', 'Por favor use números solamente en este campo. Evitar por favor los espacios u otros caracteres tales como puntos o comas.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-rut', 'Por favor ingrese un Rut válido en este campo.', function(v, elm) {
				return Validation.get('IsEmpty').test(v) ||  isRut(v,elm);
			}],
	['validate-alpha', 'Por favor use letras solamente (a-z) en este campo. Otros caracteres no son permitidos.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z ]+$/.test(v)
			}],
	['validate-alphanum', 'Por favor use solamente letras (a-z) o números (0-9) en este campo. Otros caracteres no son permitidos.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W /.test(v)
			}],
	['validate-alpha-only', 'Por favor use letras solamente (a-z) en este campo. Espacios y otros caracteres no son permitidos.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
			}],
	['validate-alphanum-only', 'Por favor use solamente letras (a-z) o números (0-9) en este campo. Espacios y otros caracteres no son permitidos.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
			}],
	['validate-date', 'Por favor ingrese una fecha válida.', function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
			}],
	['validate-email', 'Por favor ingrese una dirección de correo válida. Por ejemplo juan@dominio.com', function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){0,2}[.][\w\-]{2,4}$/.test(v)
			}],
	['validate-url', 'Por favor ingrese una URL válida.', 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', 'Por favor utilice este formato: dd/mm/yyyy.<br/ >Por ejemplo 17/03/2006 para 17 de Marzo de 2006.', function(v) {
				if(Validation.get('IsEmpty').test(v)) return true;
				var regex = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
				//alert(v);
				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-currency-dollar', 'Please enter a valid $ amount. For example $100.00 .', function(v) {
				// [$]1[##][,###]+[.##]
				// [$]1###+[.##]
				// [$]0.##
				// [$].##
				return Validation.get('IsEmpty').test(v) ||  /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
			}],
	['validate-phone', 'Por favor ingrese un teléfono válido. Debe ingresar tanto código de área como el número de teléfono.', function (v,elm) {
				var p = elm.parentNode;
				var phone = new Array;
				var options = p.childNodes;
				$A(options).any(function(elm) {
					if(elm.type)
						phone.push($F(elm));
				});
				if(isNaN(phone[1]))
					return false;
				if((phone[0]!="" && phone[1]=="") || (phone[0]=="" && phone[1]!="") || (phone[1]!="" && phone[1].length < 6) || ((phone[0] == "02" || phone[0] == "098" || phone[0] == "099") && (phone[1].length < 7 || phone[1].length > 7)) )
					return false;
				return true;
			}],
	['validate-one-required', 'Por favor seleccione 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);
				});
			}]
]);