
/**************************************************************

	Script		: Validate
	Version		: 2.2
	Authors		: Samuel Birch
	Desc		: Form validation
	Licence		: Open Source MIT Licence

**************************************************************/

var rut_mod = "";

function revisarDigito(dvr) {
	dv = dvr + "";
	if ( dv != '0' && dv != '1' && dv != '2' && dv != '3' && dv != '4' && dv != '5' && dv != '6' && dv != '7' && dv != '8' && dv != '9' && dv != 'k'  && dv != 'K') {
		return false;	
	}
return true;
}

function revisarDigito2(crut) {
	largo = crut.length;
	if ( largo < 2 ) {
		return false;	
	}
	if ( largo > 2 ) {
		rut = crut.substring(0, largo - 1);
	} else {
		rut = crut.charAt(0);
	}
	dv = crut.charAt(largo-1);
	revisarDigito(dv);

	if ( rut == null || dv == null ) {
		return false;
	}

	var dvr = '0';
	suma = 0;
	mul  = 2;

	for (i= rut.length -1 ; i >= 0; i--) {
		suma = suma + rut.charAt(i) * mul;
		if (mul == 7) {
			mul = 2;
		} else {
			mul++;
		}
	}

	res = suma % 11;
	if (res==1) {
		dvr = 'k';
	} else if (res == 0) {
		dvr = '0';
	} else {
		dvi = 11-res;
		dvr = dvi + "";
	}

	if ( dvr != dv.toLowerCase() ) {
		return false	
	}

return true
}

function Rut(texto) {
	var tmpstr = "";
	for ( i=0; i < texto.length ; i++ ) {
		if ( texto.charAt(i) != ' ' && texto.charAt(i) != '.' && texto.charAt(i) != '-' ) {
			tmpstr = tmpstr + texto.charAt(i);
		}
	}
	texto = tmpstr;
	largo = texto.length;

	if ( largo < 2 ) {
		return false;
	}	

	for (i=0; i < largo ; i++ ) {
		if ( texto.charAt(i) !="0" && texto.charAt(i) != "1" && texto.charAt(i) !="2" && texto.charAt(i) != "3" && texto.charAt(i) != "4" && texto.charAt(i) !="5" && texto.charAt(i) != "6" && texto.charAt(i) != "7" && texto.charAt(i) !="8" && texto.charAt(i) != "9" && texto.charAt(i) !="k" && texto.charAt(i) != "K" ) {
			return false;
		}
	}

	var invertido = "";
	for ( i=(largo-1),j=0; i>=0; i--,j++ ) {
		invertido = invertido + texto.charAt(i);
	}
	var dtexto = "";	
	dtexto = dtexto + invertido.charAt(0);
	dtexto = dtexto + '-';
	cnt = 0;

	for ( i=1,j=2; i<largo; i++,j++ ) {
		//alert("i=[" + i + "] j=[" + j +"]" );		
		if ( cnt == 3 ) {
			dtexto = dtexto + '.';
			j++;
			dtexto = dtexto + invertido.charAt(i);
			cnt = 1;
		} else {
			dtexto = dtexto + invertido.charAt(i);
			cnt++;
		}
	}

	invertido = "";
	for ( i=(dtexto.length-1),j=0; i>=0; i--,j++ ) {
		invertido = invertido + dtexto.charAt(i);
	}

	rut_mod = invertido.toUpperCase();

	if ( revisarDigito2(texto) ) {
		return true;
	}

return false;
}


var Validate = new Class({
	
	getOptions: function(){
		return {
			validateOnBlur: true,
			errorClass: 'error',
			errorMsgClass: 'errorMessage',
			dateFormat: 'yyyy-MM-dd',
// 			_onFail: $empty,
// 			_onSuccess: false,
			showErrorsInline: true,
			label: 'Espere...'
		};
	},

	initialize: function(form, options){
		this.setOptions(this.getOptions(), options);
		
// 		Agregado por Seba Salazar
		this.options.onFail = options.onFail || $empty;
		this.options.onSuccess = options.onSuccess || false;
		
		this.form = $(form);
		this.elements = this.form.getElements('.required');
		
		this.list = [];
		
		this.elements.each(function(el,i){
			if(this.options.validateOnBlur){
				el.addEvent('blur', this.validate.bind(this, el));
			}
		}.bind(this));
		
		this.form.addEvent('submit', function(e){
			var event = new Event(e);
			var doSubmit = true;
			this.elements.each(function(el,i){
				if(! this.validate(el)){
					event.stop();
					doSubmit = false
					this.list.include(el);
				}else{
					this.list.erase(el);
				}
			}.bind(this));
			
			if(doSubmit){
				if(this.options.onSuccess){
					event.stop();
					this.options.onSuccess(this.form);
				}else{
					this.form.getElement('input[type=submit]').setProperty('value',this.options.label);
				}
			}else{
				this.options.onFail(this.getList());
			}
			
// 			return false;
			
		}.bind(this));
		
	},
	
	getList: function(){
		var list = new Element('ul');
		this.list.each(function(el,i){
			if(el.title != ''){
			var li = new Element('li').inject(list);
			new Element('label').set({
				'for': el.id,
				'text': el.title
			}).inject(li);
			}
		});
		return list;
	},
	
	validate: function(el){
		var valid = true;
		this.clearMsg(el);
		
		switch(el.type){
			case 'text':
			case 'textarea':
			case 'select-one':
				if(el.value != ''){
					if(el.hasClass('email')){
						var regEmail = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
						if(el.value.toUpperCase().match(regEmail)){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el, 'Ingrese un correo electrónico válido.');
						}
					}
					
					if(el.hasClass('number')){
						var regNum = /[-+]?[0-9]*\.?[0-9]+/;
						if(el.value.match(regNum)){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el, 'Ingrese un número válido.');
						}
					}
					
					if(el.hasClass('postcode')){
						var regPC = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/
						if(el.value.match(regPC)){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el, 'Ingrese un código postal válido');
						}
					}
					
					if(el.hasClass('date')){
						var d = Date.parseExact(el.value, this.options.dateFormat);
						if(d != null){
							valid = true;
						}else{
							valid = false;
							this.setMsg(el, 'Ingrese la fecha en este formato: '+this.options.dateFormat.toLowerCase());
						}
					}
					
					if (el.hasClass('rut')) {
						var r = Rut(el.value);
						el.value = rut_mod;
						if (r != false) {
							valid = true;
						} else {
							valid = false;
							this.setMsg(el, 'Ingrese un rut válido');
						}
					}
				}else{
					valid = false;
					this.setMsg(el);
				}
				break;
				
			case 'checkbox':
				if(!el.checked){
					valid = false;
					this.setMsg(el);
				}else{
					valid = true;
				}
				break;
				
			case 'radio':
				var rad = $A(this.form[el.name]);
				var ok = false;
				rad.each(function(e,i){
					if(e.checked){
						ok = true;
					}
				});
				if(!ok){
					valid = false;
					this.setMsg(rad.getLast(), 'Escoja una opción');
				}else{
					valid = true;
					this.clearMsg(rad.getLast());
				}
				break;
				
		}
		return valid;
	},
	
	setMsg: function(el, msg){
		if(msg == undefined){
			msg = el.title;
		}
		if(this.options.showErrorsInline){
			if(el.error == undefined){
				el.error = new Element('span').addClass(this.options.errorMsgClass).set('text', msg).inject(el, 'after');
			}else{
				el.error.set('text', msg);
			}
			el.addClass(this.options.errorClass);
		}
	},
	
	clearMsg: function(el){
		el.removeClass(this.options.errorClass);
		if(el.error != undefined){
			el.error.destroy();
			el.error = undefined;
		}
	}
	
});

Validate.implement(new Options);
Validate.implement(new Events);


/*************************************************************/

