﻿/** @file Validate.js
    @author Nilson Pontello de Freitas <nilson@hostminas.com>
    @date 13/11/2007 05:13:57
 */
/* *** INFORMAÇÕES DE LICENCIAMENTO (LICENSE INFORMATION)  ***
   Version: HostMinas License 1.0

   O conteúdo desse arquivo está sujeito às regras da Licença de Software
   HostMinas, versão 1.0. Está proibido o uso dos códigos contidos neste arquivo
   por terceiros, bem sua cópia, no todo ou em parte, sem expressa autorização
   dos detententores da propriedade intelectual e dos direitos comerciais. Uma
   cópia da licença pode ser obtida em http://www.hostminas.com/license. A
   propriedade intelectual e comercial deste código pertence à HostMinas
   Internet Services Ltda.

   Copyright (c) 2007. Todos os direitos reservados.

   ----

   This paragraph is a free translation from Brazilian-Portuguese to
   American-English of the license information above, for better understanding
   purposes. Any intepretation of it must consider the original document. The
   contents of this file are subject to the HostMinas Software License, version
   1.0. It is forbidden the use of the codes included on this file, even
   partially, for third parties, such as its copy, without express
   authorization of the intelectual property and commercial rights owners. A
   copy of the license may be obtained at http://www.hostminas.com/license.
   The intelectual property and comercial rights of this file and codes belong
   to HostMinas Internet Services Ltd.

   Copyright (c) 2007. All rights reserved.

   *** FIM DAS INFORMAÇÕES DE LICENCIAMENTO (END OF LICENSE INFORMATION) ***
 */
 
	var PASSWORD_SECURITY_LEVEL = 1;

	var PICTURE_EXTENSION_REGEXP = /^.gif|.jpg|.png|jpeg$/;
	var ZIP_REGEXP = /^[0-9]{8}$/;
	var EMAIL_REGEXP= /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	var LOWERCASE = /[a-z]/;
	var UPPERCASE = /[A-Z]/;
	var NUMBER = /\d/;
	var NONALPHA =  /\W/; 
 
 
	var Validate={	
		firstError : null,
		
		isEmpty : function(field)
		{
			return field.value=="";	
		},
		
		isRequired : function(field)
		{
			return field.getAttribute('required') == 'yes';
		},
		
		text : function(field)
		{			
			if(Validate.isRequired(field) || !Validate.isEmpty(field)) 
			{
				var regexp = field.getAttribute('regexp');
				if(regexp != null && regexp != "")
					return Validate.regexp(field.value, regexp); 
					
				// verifica tomando como base o nome do input
				switch (field.name) 
				{
					case 'zip':
					case 'cep':
						return Validate.cep(field);
						
					case 'cpf':
						return Validate.cpf(field);
						
					case 'cnpj':
						return Validate.cnpj(field);
					
					case 'email':
					case 'mail' :
						return Validate.email(field);
						
					default:
						return !Validate.isEmpty(field);
				}	
			}
			
			return true;
		},

		file : function(field)
		{			
			if(Validate.isRequired(field) || !Validate.isEmpty(field)) 
			{
				var regexp = field.getAttribute('regexp');
				if(regexp != null && regexp != "")
					return Validate.regexp(field.value, regexp); 
					
				// verifica tomando como base o nome do input
				switch (field.name) 
				{
					case 'photo':
					case 'picture':
					case 'image':
						return Validate.image(field);
					break;
						
					default:
						return !Validate.isEmpty(field);
				}	
			}
			
			return true;
		},

		select : function(field)
		{			
			if(Validate.isRequired(field)) 
			{
				return !Validate.isEmpty(field);
			}
			
			return true;
		},
		
		textarea : function(field)
		{		
			if(Validate.isRequired(field)) 
			{
				return !Validate.isEmpty(field);
			}
			
			return true;
		},
		
		executeStrategy : function(field)
		{			
			switch(field.nodeName)
			{
				case 'SELECT':				
					if(!Validate.select(field)){
						Validate.makeErrorMessage(field);
						return false;
					}
					else{
						Validate.resetErrorMessage(field);
						return true;
					}
				break;		
				
				
				case 'TEXTAREA':
					if(!Validate.textarea(field)){
						Validate.makeErrorMessage(field);
						return false;
					}
					else{
						Validate.resetErrorMessage(field);
						return true;
					}

				break;
				case 'INPUT':
						switch(field.type)
						{
							case 'text':
							case 'password':
								if(!Validate.text(field)){
									Validate.makeErrorMessage(field);
									return false;
								}
								else{
									Validate.resetErrorMessage(field);
									return true;
								}
							break;
							case 'file':
								if(!Validate.file(field)){
									Validate.makeErrorMessage(field);
									return false;
								}
								else{
									Validate.resetErrorMessage(field);
									return true;
								}				
							default:
								return true;
						}					
				break;
			}
		},
		
		form : function(form)
		{ 
			Validate.firstError = null;
			
			for(var x in form)
			{
				if(form[x] != null)
				{
					Validate.executeStrategy(form[x])
				}
			}
			
			if(Validate.firstError != null)
			{
				Validate.firstError.focus();
				return false;
			}
			return true;		
		},
		
		makeErrorMessage : function(field)
		{
			
			if(field.getAttribute('errorType') == 'single')
			{
				field.setAttribute('class'    , 'inputError');
				field.setAttribute('className', 'inputError');
			}
			else
			{
			
				var parent = field.parentNode;
				while(parent.className == 'errorbox')
				{
					var tmp = parent;
					parent  = parent.parentNode;
					parent.removeChild(tmp);
				}
				field.parentNode.removeChild(field);
				var DIV = document.createElement('DIV');
					DIV.setAttribute('class',     'errorbox');
					DIV.setAttribute('className', 'errorbox');
					DIV.appendChild(field);
					
					DIV.appendChild(document.createElement('BR'));
					
					if(Validate.isEmpty(field))
					{
						switch(field.nodeName)
						{
							case 'SELECT':
							case 'RADIO':
								DIV.appendChild(document.createTextNode("Você deve selecionar uma opção"));
							break;
							default:
								DIV.appendChild(document.createTextNode("O campo obrigatório não pode ficar em branco"));
							break;	
						}
						
					}
					else
					{
						if(field.getAttribute('errormessage')!= null && field.getAttribute('errormessage') !=="")
							DIV.appendChild(document.createTextNode(field.getAttribute('errormessage')));
						
						else
							DIV.appendChild(document.createTextNode("Este campo não foi preenchido corretamente"));
					
						if(field.getAttribute('example')!= null)
						{
							DIV.appendChild(document.createElement('BR'));
							DIV.appendChild(document.createTextNode("Ex: "+field.getAttribute('example')));
						}
					}
	
				parent.appendChild(DIV);
			}
			
			if(Validate.firstError==null)
			{
				Validate.firstError = field;
			}
		},
		
		resetErrorMessage : function(field)
		{	
			if(field.getAttribute('errorType') == 'single')
			{
				field.setAttribute('class'    , '');
				field.setAttribute('className', '');
				return;	
			}
			
			
			var parent = field.parentNode;
				
			if(parent.nodeName == 'TD') return;
			
			while(parent.nodeName != 'TD')
			{
				var tmp = parent;
				parent  = parent.parentNode;
				parent.removeChild(tmp);
			}
			parent.appendChild(field);
		},
		
		cpf : function(field)
		{
			var cpf = field.value.replace(/[.-]/g,"");
	
			var numbers, digits, add, i, result, same_digits;
			same_digits = 1;
			
			if (cpf.length < 11) return false;
			
			for (i = 0; i < cpf.length - 1; i++)
			{
				if (cpf.charAt(i) != cpf.charAt(i + 1))
				{
					  same_digits = 0;
					  break;
				}
			}
			
			if (!same_digits)
			{
				numbers = cpf.substring(0,9);
				digits = cpf.substring(9);
				add = 0;
			
				for (i = 10; i > 1; i--)  add += numbers.charAt(10 - i) * i;
				
				result = add % 11 < 2 ? 0 : 11 - add % 11;
				
				if (result != digits.charAt(0)) return false;
				
				numbers = cpf.substring(0,10);
				add = 0;
				
				for (i = 11; i > 1; i--) add += numbers.charAt(11 - i) * i;
				
				
				result = add % 11 < 2 ? 0 : 11 - add % 11;
				
				if (result != digits.charAt(1)) return false;
				
				return true;
			}
				else return false;
		 },
		 
		cnpj : function(field)
		{
			cnpj = field.value.replace(/[-.\/]/g,"");
	
			var numbers, digits, add, i, result, pos, size, same_digits;
			same_digits = 1;
			
			if (cnpj.length < 14 && cnpj.length < 15) return false;
	
			for (i = 0; i < cnpj.length - 1; i++)
			{
				if (cnpj.charAt(i) != cnpj.charAt(i + 1))
				{
					same_digits = 0;
					break;
				}
			}
			
			if (!same_digits)
			{
				size = cnpj.length - 2
				numbers = cnpj.substring(0,size);
				digits = cnpj.substring(size);
				add = 0;
				pos = size - 7;
				for (i = size; i >= 1; i--)
				{
					  add += numbers.charAt(size - i) * pos--;
					  if (pos < 2)
							pos = 9;
				}
					  
				result = add % 11 < 2 ? 0 : 11 - add % 11;
	
				if (result != digits.charAt(0)) return false;
				
				size = size + 1;
				numbers = cnpj.substring(0,size);
				add = 0;
				pos = size - 7;
				
				for (i = size; i >= 1; i--)
				{
					  add += numbers.charAt(size - i) * pos--;
					  if (pos < 2) pos = 9;
				}
				
				result = add % 11 < 2 ? 0 : 11 - add % 11;
				
				if (result != digits.charAt(1)) return false;
				
				return true;
			}
			
			else return false;
		},
		cep : function(field)
		{
			var cep = field.value.replace(/[-]/,"");
			return 	cep.match(ZIP_REGEXP);
		},
		
		image : function(field)
		{
			var extension = field.value.substr(field.value.length-4, field.value.length);			
			return (extension.match(PICTURE_EXTENSION_REGEXP) != null);
		},	
		
		email : function(field)
		{
			return 	field.value.match(EMAIL_REGEXP);
		},	
		
		password : function(field)
		{
			var security = LOWERCASE.test(field.value) + UPPERCASE.test(field.value) + NUMBER.test(field.value) + NONALPHA.test(field.value); 
			return (security >= PASSWORD_SECURITY_LEVEL);
		},
		
		regexp : function(value, REGEXP)
		{
			return 	value.match(REGEXP)!=null;
		}
	}