/*
* 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.
* 
*/
var Validator = Class.create();
var a_validator_cep_uf = ['SP;','SP;','RJ;ES;',
		               'MG;','BA;SE;','AL;PB;PE;RN;',
		               'MA;AC;AM;AP;CE;PA;PI;RR;','DF;GO;MS;MT;RO;TO;','PR;SC;',
		               'RS;'];

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 || 'Erro na validação.';
		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;},
	minValue : function(v,elm,opt) {return Validation.get('IsEmpty').test(v) || fg_unformat_valor(v) >= parseFloat(opt);},
	maxValue : function(v,elm,opt) {return Validation.get('IsEmpty').test(v) || fg_unformat_valor(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);},
	isValidCep: function(v,elm,opt) {
      var v_uf = a_validator_cep_uf[parseInt(v.charAt(0))];
      return Validation.get('IsEmpty').test($F(opt)) || (v_uf.indexOf($F(opt))!=-1);
   },
	notEqualToField : function(v,elm,opt) {return v != $F(opt);},
	requiredIfField : function(v,elm,opt) {
	  if(!Validation.get('IsEmpty').test($F(opt)))
	  {
	     return !Validation.get('IsEmpty').test(v);
     }
     else
     {
        return true;    
     }
   },
   lessEqualToDate: function(v,elm,opt) {
      if(Validation.get('IsEmpty').test(v))
      {
         return true;
      }
      return !(Validation.dateToUnixdate(v) < Validation.dateToUnixdate($F(opt)));
   },
	fileTypeOf : function(v,elm,opt) {
      if(Validation.get('IsEmpty').test(v))
      {
         return true;
      }
      var a_v = v.split(".");
      v = a_v[a_v.length-1];
      return $A(opt).any(function(value) {return v == value;});
   },
	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);
		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();
		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;
					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) {
								p.insert({'bottom':advice});
							} else {
								elm.insert({'after':advice});
							}
							break;
						default:
						   if(elm.hasClassName('insertion_before')) {
						   		elm.insert({'before':advice});
                     }
						   else {
   							elm.insert({'after':advice});
                     }
				    }
					advice = Validation.getAdvice(name, 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(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())
         {
            if((elm.id.indexOf('hid_sel_')>=0)&&(elm.tagName == 'INPUT'))
            {
      			elm = elm.parentNode;
      			continue;
            }
   		   if((elm.tagName != 'TEXTAREA')||
               ((elm.tagName == 'TEXTAREA')&&(!$(elm).hasClassName("use_tinymce"))))
            {
               return false;
            }
         }
			elm = elm.parentNode;
		}
		return true;
	},
	dateToUnixdate: function(date) {
      if(date == '')
      { return ''; }
      a_date = date.split('/');
      return a_date[2]+a_date[1]+a_date[0];
   },
	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([
	['required', 'Este é um campo obrigatório.', function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['required-trimspace', 'Este é um campo obrigatório.', function(v) {
            return !Validation.get('IsEmpty').test(v.replace(/^\s\s*/, '').replace(/\s\s*$/, ''));
			}],
	['validate-no-pad-space', 'Espaços no início ou no final não são permitidos.', function(v) {
            return Validation.get('IsEmpty').test(v) ||  (!/^\s\s*/.test(v) &&  !/\s\s*$/.test(v));
			}],
	['validate-number', 'Informe um número válido neste campo.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
			}],
	['validate-digits', 'Informe apenas números neste campo. Evite espaços e outros caracteres tipo pontos e virgulas.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-phonedigits', 'Informe apenas números e traço (-) neste campo. Evite espaços e outros caracteres tipo pontos e virgulas.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  /^[0-9\-]+$/.test(v);
			}],
	['validate-alpha', 'Use apenas letras (a-z) neste campo.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v);
			}],
	['validate-alphanum', 'Use apenas letras (a-z) ou números (0-9) neste campo. Espaços ou outros caracteres não são permitidos.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v);
			}],
	['validate-date', 'Informe uma data válida.', function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
			}],
	['validate-login', 'Informe um login válido. Espaços e caracteres acentuados não são permitidos.', function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}$/.test(v);
			}],
	['validate-image', 'Informe um arquivo de imagem válido.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^.+\.((jpg)|(gif)|(jpeg)|(png))$/i.test(v);
			}],
	['validate-email', 'Informe um e-mail válido.', function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v);
			}],
	['validate-multi-email', 'Há um ou mais e-mails inválidos.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$/.test(v);
			}],
	['validate-cep', 'Informe um CEP válido.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^[0-9]{5}[\-]{1}[0-9]{3}$/.test(v);
			}],
	['validate-cpf', 'Informe um CPF válido.', function (v) {
				if(Validation.get('IsEmpty').test(v)) {return true;}
				var regex_digitos = /^\d{3}\.\d{3}\.\d{3}-\d{2}$/;
				if(!regex_digitos.test(v)) {return false;}
            if((v = v.replace(/[^\d]/g,"").split("")).length != 11) {return false;}
            for(var s = 10, n = 0, i = 0; s >= 2; n += v[i++] * s--){}
            if(v[9] != (((n %= 11) < 2) ? 0 : 11 - n)) {return false;}
            for(var s = 11, n = 0, i = 0; s >= 2; n += v[i++] * s--){}
            return (v[10] == (((n %= 11) < 2) ? 0 : 11 - n));
			}],
	['validate-url', 'Informe uma URL válida. Uma url deve iniciar com \'http\', \'https\' ou \'ftp\'.', 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', 'Informe uma data no formato: dd/mm/aaaa. Por exemplo 17/03/2006 para 17 de março de 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-hour', 'Informe uma hora no formato: hh:mm. Por exemplo 23:05 para 23 horas e 5 minutos.', function(v) {
				if(Validation.get('IsEmpty').test(v)) {return true;}
				var regex = /^(\d{2})\:(\d{2})$/;
				if(!regex.test(v)) {return false;}
    			return (parseInt(RegExp.$1, 10) >=0) &&
                   (parseInt(RegExp.$1, 10) <=23) &&
						 (parseInt(RegExp.$2, 10) >= 0)&&
						 (parseInt(RegExp.$2, 10) <= 59 );
			}],
	['validate-currency-dollar', 'Informe uma quantia válida em R$. Por exemplo R$ 1.100,00 .', function(v) {
				// [$]1[##][,###]+[.##]
				// [$]1###+[.##]
				// [$]0.##
				// [$].##
				return Validation.get('IsEmpty').test(v) ||  /^[R]\$?\s?\-?([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-money', 'Informe uma quantia válida no formato monetário. Por exemplo 1.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-selection', 'Selecione um item', function(v,elm){
				return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
			}],
	['validate-one-required', 'Selecione uma das opções acima.', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}]
]);

// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download.
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

//-------------------------------------------------------------------
// getSingleInputValue(input_object,use_default)
//   Utility function used by others
//-------------------------------------------------------------------
function getSingleInputValue(obj,use_default) {
	switch(obj.type){
		case 'radio': case 'checkbox': return(((use_default)?obj.defaultChecked:obj.checked)?obj.value:null);
		case 'text': case 'hidden': return(use_default)?obj.defaultValue:obj.value;
      case 'textarea': return(use_default)?obj.defaultValue.replace(/(&nbsp;|\u00A0|\u2028|\u2029)/g,' ').replace(/(&quot;|\u0022)/g,'"'):obj.value.replace(/(&nbsp;|\u00A0|\u2028|\u2029)/g,' ').replace(/(&quot;|\u0022)/g,'"');
		case 'password': return((use_default)?null:obj.value);
		case 'select-one':
			if (obj.options==null) { return null; }
			if(use_default){
				var o=obj.options;
				for(var i=0;i<o.length;i++){if(o[i].defaultSelected){return o[i].value;}}
				return o[0].value;
				}
			if (obj.selectedIndex<0){return null;}
			return(obj.options.length>0)?obj.options[obj.selectedIndex].value:null;
		case 'select-multiple':
			if (obj.options==null) { return null; }
			var values=new Array();
			for(var i=0;i<obj.options.length;i++) {
				if((use_default&&obj.options[i].defaultSelected)||(!use_default&&obj.options[i].selected)) {
					values[values.length]=obj.options[i].value;
					}
				}
			return (values.length==0)?null:values.join(',');
		}
	alert("FATAL ERROR: Field type "+obj.type+" is not supported for this function");
	return null;
	}

//-------------------------------------------------------------------
// getInputValue(input_object)
//   Get the value of any form input field
//   Multiple-select fields are returned as comma-separated values
//   (Doesn't support input types: button,file,reset,submit)
//-------------------------------------------------------------------
function getInputValue(obj) {
	var use_default=(arguments.length>1)?arguments[1]:false;
	if (Object.isArray(obj) && (typeof(obj.type)=="undefined")) {
		var values=new Array();
		for(var i=0;i<obj.length;i++){
			var v=getSingleInputValue(obj[i],use_default);
			if(v!=null){values[values.length]=v;}
			}
		return values.join(',');
		}
	return getSingleInputValue(obj,use_default);
	}

//-------------------------------------------------------------------
// getInputDefaultValue(input_object)
//   Get the default value of any form input field when it was created
//   Multiple-select fields are returned as comma-separated values
//   (Doesn't support input types: button,file,password,reset,submit)
//-------------------------------------------------------------------
function getInputDefaultValue(obj){return getInputValue(obj,true);}

//-------------------------------------------------------------------
// isChanged(input_object)
//   Returns true if input object's value has changed since it was
//   created.
//-------------------------------------------------------------------
function isChanged(obj){return(getInputValue(obj) != getInputDefaultValue(obj));}

