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)
},
notEqualToField : 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 : false,
focusOnError : true,
useTitles : false,
onFormValidate : function(result, form) {},
onElementValidate : function(result, elm) {}
}, options || {});
this.form = $(form);
this.form.validator = this;
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
});
});
Event.observe(input, 'keypress', function(ev) {
if ((ev.keyCode ? ev.keyCode : ev.which) == 13) {
Validation.validate(Event.element(ev),{
useTitle : useTitles,
onElementValidate : callback
});
}
});
Event.observe(input, 'focus', function() {
$(input).removeClassName('validation-failed');
if ($('advice-' + $(input).id))
$('advice-' + $(input).id).hide();
});
});
}
},
onSubmit :  function(ev){
if(!this.validate()) {
Event.stop(ev); return false;
}
return true;
},
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] || v.response*/ true) { //true para for�ar redesenhar
var advice = Validation.getAdvice(name, elm);
if (advice) {
advice.remove();
advice = Validation.getAdvice(name, elm);
}
if(true /*advice == null || v.response*/) { //true para for�ar redesenhar
var errorMsg = v.response || useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
if (v.response)
errorMsg = v.response;
//advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'
advice = '<span class="validation-advice" id="advice-' + Validation.getElmID(elm) +'" style="display:none" onclick="$(this).hide()">' + errorMsg + '<span class="hint-pointer"></span></span>'
var nextElem = elm;
while (!!nextElem.next())
nextElem = nextElem.next();
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(nextElem, advice);
}
advice = Validation.getAdvice(name, elm);
}
if(typeof Effect == 'undefined') {
advice.style.display = 'block';
} else {
advice.setStyle({
marginRight:(-advice.getWidth())+"px"
})
new Effect.Appear(advice, {
duration : 0.3
});
}

}
elm[prop] = true;
elm.removeClassName('validation-passed');
elm.addClassName('validation-failed');
return false;
} else {
var advice = Validation.getAdvice(name, elm);
if(advice != null) Effect.Fade(advice, {
duration: 0.3
});
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.addAllThese([
['requerido', 'Este campo &eacute; obrigat&oacute;rio.', function(v) {
return !Validation.get('IsEmpty').test(v);
}],
['porcentagem', 'Por favor, entre com um n�mero v�lido.', function(v) {
return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
}],
['real', 'Por favor, entre com um n�mero v�lido.', function(v) {
return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
}],
['monetario', 'Por favor, entre com um n�mero v�lido. Use ponto no lugar da v�rgula', function(v) {
return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
}],
['numeros', 'Por favor, use somente n�meros. Tente evitar espa�os ou outros caracteres como pontos ou v�rgulas.', function(v) {
return Validation.get('IsEmpty').test(v) ||  /[\d]/.test(v);
}],
['positivo', 'Por favor, use somente n�meros positivos.', function(v) {
return Validation.get('IsEmpty').test(v) ||  ( /[\d]/.test(v) && parseFloat(v) >= 0 );
}],
['inteiro', 'Por favor, use somente n�meros. Tente evitar espa�os ou outros caracteres como pontos ou v�rgulas.', function(v) {
return Validation.get('IsEmpty').test(v) ||  /[\d]/.test(v);
}],
['alpha', 'Por favor, use somente letras de (a-z).', function (v) {
return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
}],
['alphanum', 'Por favor, use somente letras (a-z) ou n�meros (0-9). Espa�os ou outros caracteres n�o s�o permitidos.', function(v) {
return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
}],
['date', 'Por favor, entre com uma data v�lida.', function(v) {
var test = new Date(v);
return Validation.get('IsEmpty').test(v) || !isNaN(test);
}],
['email', 'Por favor, entre com um e-mail v&aacute;lido. Por exemplo fred@domain.com .', function (v) {
return Validation.get('IsEmpty').test(v) || /^(([A-Za-z0-9]+[_\.\+\-]+)*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})?$/.test(v)
}],
['url', 'Por favor, entre com uma 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)
}],
['data', 'Por favor, entre com uma data no formato: dd/mm/yyyy. Por exemplo 17 de Mar�o de 2006 para 17/03/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() );
}],
['data_hora', 'Por favor, entre com uma data no formato: dd/mm/yyyy HH:MM:SS. Por exemplo 17/03/2006 13:30:25.', function(v) {
if(Validation.get('IsEmpty').test(v)) return true;
var regex = /^(\d{2})\/(\d{2})\/(\d{4})\s(\d{2})\:(\d{2})\:(\d{2})$/;
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', 'Por favor, entre com um valor monet�rio v�lido. Por exemplo $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)
}],
['selecao_requerida', 'Por favor, fa�a uma sele��o.', function(v,elm){
return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
}],
['um_requerido', 'Por favor, selecione uma das op��es.', function (v,elm) {
var p = elm.parentNode;
//alert(p.tagName == 'LABEL');
if (p.tagName =='LABEL') {
p = p.parentNode;
}
var options = p.getElementsByTagName('INPUT');
return $A(options).any(function(elm) {
return $F(elm) != null;
});
}],
['cpf_cnpj', null, function(v) {
if ($('ignoraCnpjCpf') && $('ignoraCnpjCpf').checked)
return true;
this.response = responseAjax("/application/validaCPFCNPJ", {
cpf_cnpj: v
} );
return this.response.gsub(/\s/,"") == "";
}],
['tem_escolhido', "Escolha pelo menos um", function(v) {
return $$('input.escolhido').length > 0 || v.length > 0;
}],
['fone', 'Por favor, entre com um telefone v&aacute;lido.', function (v) {
return Validation.get('IsEmpty').test(v) || /^(((\(\d{2}\))( ))\d{3,4}(-)\d{4})?$/.test(v)
}],
['hora', 'Por favor, entre com uma hora v&aacute;lido.', function (v) {
return Validation.get('IsEmpty').test(v) || /^([0-1][0-9]|2[0-3]):[0-5][0-9]$/.test(v)
}]
]);

responseAjax = function(url, params) {
var response = "";
var x = new Ajax.Request ( url , {
method: 'post' ,
parameters: params ,
onComplete: function(w){
response = w.responseText;
},
asynchronous: false,
timeout: 0
});
return response;
};

formCallback = function(result, form) {
window.status = "valiation callback for form '" + form.id + "': result = " + result;
};
var valid = false;
applyEasyValidation = function(elem){
elem = $(elem) || $$(elem)[0] || elem || $$('form.validation')[0];
if (!!elem && !(elem.hasClassName("validation") || elem.up('form.validation'))) {
elem = elem.select('form.validation')[0];
}
if (!!elem && (elem.hasClassName("validation") || elem.up('form.validation'))) {
try {
valid = new Validation(elem, {
immediate: true,
onFormValidate: formCallback
});
}
catch (err) {}
}
};
Event.observe(window, 'load', function() {
applyEasyValidation();
});
