/** 
 * Classe: Valida��o de Campos 1.2
 * Descri��o: Classe verifica tags inputs para sua valida��o
 * Desenvolvido por : Kleber Oliveira , kleber.oliveira@live.com
 * Exemplo : <input type="text" validate="true|false" vlength="numero_de_caracteres" vtype="tipo_de_verifica��o" vmensage="mensagem_de_erro" />

 * variaveis de configura��o


 * borda,cor de fundo e da fonte da caixa de dica
**/

var BordaDica 		= "#999 solid 1px";
var corFundoDica	= "#FFFFFF";
var corFonteDica	= "#000000";


// fonte e borda dos inputs quando nao validado
var classErro	= "text_input";
var classNormal = "text_input";


var vformularios,caminho,cauxi;
var isDOM = (navigator.appName.match("Microsoft Internet Explorer") || navigator.appName.match("MSIE")) ? false : true;

function procuraPosX(obj){
	var curleft = 0;
	if(obj.offsetParent){
		while(1){
		  curleft += obj.offsetLeft;
		  if(!obj.offsetParent){break;}
		  obj = obj.offsetParent;
		}
	}else if(obj.x){
		curleft += obj.x;
	}
	return curleft;
}

function procuraPosY(obj){
	var curtop = 0;
	if(obj.offsetParent){
		while(1){
		  curtop += obj.offsetTop;
		  if(!obj.offsetParent){break;}
		  obj = obj.offsetParent;
		}
	}else if(obj.y){
		curtop += obj.y;
	}
	return curtop;
}


function existeObjeto(id){
	var verificador = document.getElementById(id);
	verificador = verificador==null?false:true;	
	return verificador;
}


function adicionaDocumento(obj){
	var corpo = document.getElementsByTagName("body")[0]; 
	corpo.appendChild(obj);	
}


function removeDocumento(obj){
	var corpo = document.getElementsByTagName("body")[0]; 
	corpo.removeChild(obj);	
}


function definePosicao(dica,obj){
	with(dica.style){
		left 	= (procuraPosX(obj)+obj.offsetWidth+10)+"px";
		top	 	= (procuraPosY(obj)-10)+"px";
	}
}


function removerDica(){
	if(existeObjeto("dica")){
		var dica = document.getElementById('dica');
		removeDocumento(dica);
	}
}


function inserirDica(obj,texto){
	
	if(!existeObjeto("dica")){		
		var dica = document.createElement("div");
		dica.setAttribute("id","dica");
		dica.setAttribute("pai",obj.id);		
			with(dica.style){
				position 	= "absolute";
				border	 	= BordaDica;
				background	= corFundoDica;
				color		= corFonteDica;
				width		= "auto";
				padding		= "2px";
				marginRight = "5px";
			}
		definePosicao(dica,obj);
		var setDica = document.createElement("span");
			with(setDica.style){
				position	= "relative";
				marginLeft	= "-17px";
			}		

		var texDica = document.createElement("span");
			with(texDica.style){
				padding		= "10px";
			}
		texDica.setAttribute("id","texDica");
		setDica.innerHTML = "<img src=\""+caminho+"setdica.png\" alt=\"set\" />";
		texDica.innerHTML = texto;
		dica.appendChild(setDica);
		dica.appendChild(texDica);
	}else{
		var dica = document.getElementById("dica");
		dica.setAttribute("pai",obj.id);
		var texDica = document.getElementById("texDica");
		texDica.innerHTML = texto;
	}
	definePosicao(dica,obj);
	adicionaDocumento(dica);
}



function listaTag(tag,tipo,form,val){
	
	var	valtipo	=tipo=="todos"?false:true;
	if(form!='document'){
		var formulario = document.getElementById(form);
	}else{
		var formulario = document;
	}
	
	var tag	 =  formulario.getElementsByTagName(tag);
	var campos = new Array();
	var p = 0;
	for (i=0;i<tag.length;i++){		
		if(valtipo){
			validador = val?eval(tag[i].getAttribute('validate')):true;
			if(tag[i].type==tipo && validador){
				campos[p] = tag[i];
				p++;
			}
		}else{
			validador = val?eval(tag[i].getAttribute('validate')):true;
			if(validador){
				campos[p] = tag[i];
				p++;
			}
		}
	}
	return campos;
}


function validacaracter(obj){
	if(obj.value.length <= eval(obj.getAttribute('vlength')) || obj.value == obj.title || ( eval(obj.getAttribute('vselectlength')) == true && obj.value == "0")){
		inserirDica(obj,obj.getAttribute('vmensage'));
		obj.focus();
		obj.className = classErro;
		obj.onkeydown = obj.onblur = function(){
			obj.className = classNormal;
			removerDica();
		}
		return true;
	}else{
		obj.className = classNormal;
		return false;
	}
}


function validaemail(obj) {	
	regex=/^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;	
	var value = obj.value;
	if(value.length <= eval(obj.getAttribute('vlength')) || value == obj.title || !regex.test(value)){		
		inserirDica(obj,obj.getAttribute('vmensage'));
		obj.focus();
		obj.className = classErro;
		obj.onkeydown = obj.onblur = function(){
			obj.className = classNormal;
		}		
		return true;
	}else{
		obj.className = classNormal;
		return false;
	}
}



function validadata(obj) {	
  var expReg = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/(19|20)?\d{2}$/;
  
  var aRet = false;  
  if ((obj) && (obj.value.match(expReg)) && (obj.value != '')) {
	var dia = obj.value.substring(0,2);
    var mes = obj.value.substring(3,5);
    var ano = obj.value.substring(6,10);
	if ((mes == 4 || mes == 6 || mes == 9 || mes == 11 ) && dia > 30){
      aRet = true;
	}else{
      if ((ano % 4) != 0 && mes == 2 && dia > 28){
        aRet = true;
	  }else{
        if ((ano%4) == 0 && mes == 2 && dia > 29){
          aRet = true;
		}
	  }
	}
  }else{
    aRet = true;  
  }
  
  if(aRet){
	inserirDica(obj,obj.getAttribute('vmensage'));
	obj.focus();
	obj.className = classErro;
	obj.onkeydown = obj.onblur = function(){
		obj.className = classNormal;
	}
  
  }else{
	obj.className = classNormal;
  }
  
  return aRet;
}

function verificaCampos(formulario){

	validado = false;	
	
	var inputHTML = listaTag("input",'todos',formulario,true);	
	var textAreaHTML = listaTag("textarea",'todos',formulario,true);
	var selectHTML = listaTag("select",'todos',formulario,true);
	
	var inputVal = inputHTML.concat(textAreaHTML.concat(selectHTML));
	
	for(i=0;i<inputVal.length;i++){
		var vtype = inputVal[i].getAttribute('vtype');
		
		if(eval('valida'+vtype+'(inputVal[i]);')){
			validado = false;
			break;		
		}else{
			removerDica();
			validado = true;
		}
	}
	return validado;
}



function adicionaValidacaoMascara(formulario){
	
	//validac�o
	var inputs 	= listaTag("input",'text',formulario,true);
	for(m=0;m<inputs.length;m++){
		if(inputs[m].title == inputs[m].value){			
			inputs[m].onfocus = function(){
				this.value = "";
			}
			inputs[m].onblur = function(){
				if(this.value == ""){
					this.value = this.title;
				}
			}
		}
	}
	
	//mascara
	var inputs 	= listaTag("input",'text',formulario,false);
	for(m=0;m<inputs.length;m++){
		var vmask = inputs[m].getAttribute('vmask');
		switch(vmask){
			case "date":
				inputs[m].onkeypress =	function(){
					this.maxLength = "10";
					mascara(this,data);
				};
				break;
				
			case "num":
				inputs[m].onkeypress =	function(){
					this.maxLength = "10";
					mascara(this,numeros);
				};
				break;

			case "cpf":
				inputs[m].onkeypress =	function(){
					this.maxLength = "14";
					mascara(this,cpf);
				};
				break;

			case "tel":
				inputs[m].onkeypress =	function(){
					this.maxLength = "14";
					mascara(this,telefone);
				};
				break;
				
			case "cep":
				inputs[m].onkeypress =	function(){
					this.maxLength = "9";
					mascara(this,cep);
				};
				break;

                        case "reg":
				inputs[m].onkeypress =	function(){
					this.maxLength = "13";
					mascara(this,reg);
				};
				break;
				
			case "value":
				addEvento(inputs[m] ,"keypress", function(e){ return valor(this, "", ",", e)});
				break;	
				
			case "weight":
				addEvento(inputs[m] ,"keypress", function(e){ return peso(this, "", ",", e)});
				break;
				
			case "cm":
				addEvento(inputs[m] ,"keypress", function(e){ return tamanho(this, "", ",", e)});
				break;

                        case "uf":
				inputs[m].onkeypress =	function(){
					this.maxLength = "2";
					mascara(this,uf);
				};
				break;
			
		}
	}	
}

function verificaFormulario(){
	
	if(cauxi == undefined){cauxi=""}
	caminho 	 	= cauxi+"modulos/scripts/";	
	var valform = vformularios!=undefined?true:false;

        

	if(valform){
		for(j=0;j<vformularios.length;j++){			
			var button 	= listaTag('input','submit',vformularios[j],false);
			adicionaValidacaoMascara(vformularios[j]);
			button[0].setAttribute('formPai',vformularios[j]);
			button[0].onclick = function(){
                               return verificaCampos(this.getAttribute('formPai'));
			}
		}

	}else{
		var button 	= listaTag('input','submit','document',false);
		adicionaValidacaoMascara('document');

                button[0].onclick = function(){
                       return verificaCampos('document');
		}
	}
}




function seguePai(){
	if(existeObjeto("dica")){
		var dica = document.getElementById("dica");
		var obj  = document.getElementById(dica.getAttribute("pai"));
		definePosicao(dica,obj);
	}
}


/* Funcoes de Mascara */
//-----------------------------------------
function valor(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){	

	
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;    
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc    
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8))
    	return true;
    key = String.fromCharCode(whichCode); // Valor para o c�digo da Chave
 
 
	if (strCheck.indexOf(key) == -1) 
		return false; // Chave inv�lida
		
	len = objTextBox.value.length;
	
		for(i = 0; i < len; i++)
			if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) 
				break;
		
		aux = '';
		for(; i < len; i++)
			if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) 
				aux += objTextBox.value.charAt(i);
				
		aux += key;
		len = aux.length;
		if (len == 0) 
			objTextBox.value = '';
		if (len == 1) 
			objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
		if (len == 2) 
			objTextBox.value = '0'+ SeparadorDecimal + aux;
		if (len > 2) {
			aux2 = '';
			for (j = 0, i = len - 3; i >= 0; i--) {
				if (j == 3) {
					aux2 += SeparadorMilesimo;
					j = 0;
				}
				aux2 += aux.charAt(i);
				j++;
			}
			objTextBox.value = '';
			len2 = aux2.length;
			for (i = len2 - 1; i >= 0; i--)
				objTextBox.value += aux2.charAt(i);
			objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
		}
	
	    return false;
}
//-----------------------------------------
function peso(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){	

	
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;    
	
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc    
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8))
    	return true;
    key = String.fromCharCode(whichCode); // Valor para o c�digo da Chave
 
 
	if (strCheck.indexOf(key) == -1) 
		return false; // Chave inv�lida
		
	len = objTextBox.value.length;
	
		for(i = 0; i < len; i++)
			if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) 
				break;
		
		aux = '';
		for(; i < len; i++)
			if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) 
				aux += objTextBox.value.charAt(i);
				
		aux += key;
		len = aux.length;
		if (len == 0) 
			objTextBox.value = '';
		if (len == 1) 
			objTextBox.value = '0'+ SeparadorDecimal + '00' + aux;
		if (len == 2) 
			objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
		if (len == 3) 
			objTextBox.value = '0'+ SeparadorDecimal + aux;			
		if (len > 3) {
			aux2 = '';
			
			for (j = 0, i = len - 4; i >= 0; i--) {
				if (j == 4) {
					aux2 += SeparadorMilesimo;
					j = 0;
				}
				aux2 += aux.charAt(i);
				j++;
			}
			
			objTextBox.value = '';
			
			len2 = aux2.length;
			
			for (i = len2-1 ; i >= 0; i--){
				objTextBox.value += aux2.charAt(i);
			}
			objTextBox.value += SeparadorDecimal + aux.substr(len - 3, len);
		}
	
	    return false;
}

//-----------------------------------------
function tamanho(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){	

	
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;    
	
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc    
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8))
    	return true;
    key = String.fromCharCode(whichCode); // Valor para o c�digo da Chave
 
 
	if (strCheck.indexOf(key) == -1) 
		return false; // Chave inv�lida
		
	len = objTextBox.value.length;
	
		for(i = 0; i < len; i++)
			if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) 
				break;
		
		aux = '';
		for(; i < len; i++)
			if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) 
				aux += objTextBox.value.charAt(i);
				
		aux += key;
		len = aux.length;
		if (len == 0) 
			objTextBox.value = '';
		if (len == 1) 
			objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
		if (len == 2) 
			objTextBox.value = '0'+ SeparadorDecimal +  aux;
		if (len > 2) {
			aux2 = '';
			
			for (j = 0, i = len - 3; i >= 0; i--) {
				if (j == 3) {
					aux2 += SeparadorMilesimo;
					j = 0;
				}
				aux2 += aux.charAt(i);
				j++;
			}
			
			objTextBox.value = '';
			
			len2 = aux2.length;
			
			for (i = len2-1 ; i >= 0; i--){
				objTextBox.value += aux2.charAt(i);
			}
			objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
		}
	
	    return false;
}
//-----------------------------------------

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value);
}

function numeros(v){
	return v.replace(/\D/g,"")    
}

function cep(v){
    v=v.replace(/D/g,"")               
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") 
    return v
}

function data(v){
    v=v.replace(/\D/g,"")                    
    v=v.replace(/(\d{2})(\d)/,"$1\/$2")   
    v=v.replace(/(\d{2})(\d)/,"$1\/$2")      
    	                                     
	return v
}

function cpf(v){
    v=v.replace(/\D/g,"")                    
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       
    	                                     
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") 
    return v
}

function reg(v){
    v=v.replace(/\D/g,"")
    v=v.replace(/(\d{3})(\d)/,"$1.$2")
    v=v.replace(/(\d{3})(\d)/,"$1.$2")
    v=v.replace(/(\d{3})(\d)/,"$1-$2")
    v=v.replace(/(\d{1})$/,"$1")
    return v
}

function telefone(v){
    v=v.replace(/\D/g,"")                 
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2")
    v=v.replace(/(\d{4})(\d)/,"$1-$2")   
    return v
}

function cnpj(v){
    v=v.replace(/\D/g,"")                         
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")            
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") 
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              
    return v
}

function uf(v){
    v=v.replace(/[^A-Z]/,"")
    //v=v.replace(//,"$1.$2")
    return v
}


/* Fim Funcoes de Mascara */

addEvento(window,"load",verificaFormulario);
addEvento(window,"resize",seguePai);