var ie = (navigator.appName == "Microsoft Internet Explorer");
function verificar(formulario)
{
	for (i=0; i<formulario.length; i++)
	{
		tipo = document.forms[0].item(i).type;
		verifica = document.forms[0].item(i).verificar;
		if (tipo != "submit"&&"reset"&&"button"&&"image"&&"hidden" && formulario.item(i).disabled == false && verifica == "true")
		{
			tipo_dado = formulario.item(i).dado;
			mensagem = formulario.item(i).mensagem;
			check_null = formulario.item(i).checknull;
			if (typeof(check_null) == "undefined")
				check_null = true;
			
			if (verificar_campo(formulario.item(i), check_null, tipo_dado, mensagem) == false)
			{
				return false;
				break;
			}
		}
	}
}

function verificar_campo(campo, verificar_nulo, tipo_dado, nome_campo)
{
	if (typeof(campo) == "object")		//verifica se o campo que foi passado é um objeto
	{
		if (verificar_nulo == true)		//se é para verificar se o campo está vazio, verifica
		{
			if (campo.value == "")
			{
				alert("Por favor, preencha o campo " + nome_campo);
				campo.focus();
				return false;
			}
		}
		else
		{
			if (campo.value == "")
			{
				return true;
			}
		}
		if (tipo_dado == "texto"||"numero"||"data"||"cpf"||"combo"||"email"||"cep"||"imagem")		//se o tipo de dado está entre os especificados, verifica se o dado está correto
		{
			if (verificar_dado(campo, tipo_dado, nome_campo) == false)
			{
				return false;
			}
		}
		else
		{
			alert("Erro de programação: \nO tipo de dado especificado não foi encontrado");
			return false;
		}
	}
	else
	{
		alert("Erro de programação: \nObjeto não encontrado");
		return false;
	}
}

function verificar_dado(campo, tipo_dado, nome_campo)
{
	switch (tipo_dado)
	{
		case "texto":
		return true;
		
		case "numero":
		campo.value = campo.value.replace(" ","");
		if (isNaN(campo.value) == true)
		{
			alert("Utilize somente números neste campo.");
			campo.focus();
			return false;
		}
		else
		{
			return true;
		}

		case "combo":
		if (ie)
		{
			nome_campo = campo.value;
		}else{
			nome_campo = campo.options[campo.selectedIndex].value;
		}
		
			if (nome_campo == 0)
			{
				alert("Por favor, preencha o campo corretamente.");
				campo.focus();
				return false;
			}else{
				return true;
			}

		case "data":
		if (valida_data(campo.value) == false)
		{
			alert("Data inválida. Utilize a data no formato dd/mm/aaaa.");
			campo.focus();
			return false;
		}
		else
		{
			return true;
		}
		
		case "email":
		if (campo.value == "")
		{
			alert("Email inválido.");
			campo.focus();
			return false;
		}
		else
		{
			mail = campo.value;
			if (emailCheck(mail) == false) 
			{
				alert("Email inválido.");
				campo.focus();
				return false;
			}
			else
			{
				return true;
			}		
		}

		case "cep":
		if (campo.value.length != 9)
		{
			alert("Utilize o CEP no formato 00000-000");
			campo.focus();
			return false;
		}
		else
		{
			if (isNaN(campo.value.substring(0,5)) == true)
			{
				alert("CEP inválido.");
				campo.focus();
				return false;
			}
			else
			{
				if (isNaN(campo.value.substring(6,9)) == true)
				{
					alert("b=" + campo.value.substring(6,9))
					alert("CEP inválido.");
					campo.focus();
					return false;
				}
				else
				{
					return true;
				}
			}
		}

		case "cpf":
		if (Valida_CPF(campo) == false){
			return false;
		}
		else
		{
			return true;
		}

		case "imagem":
		pos = campo.value.indexOf (".");
		if (pos == -1)
		{
			alert ("É necessário colocar a extensão do arquivo.");
			campo.focus();
			return false;
		}
		else
		{
			extensao = campo.value.substring(pos+1, pos+4);
			if (extensao != "gif"&&"jpg"&&"GIF"&&"JPG")
			{
				if (extensao == "")
					alert("É necessário colocar a extensão do arquivo.");
				else
					alert("O arquivo deve ser do tipo gif ou jpg");
				campo.focus();
				return false;
			}
			else
			{
				return true;
			}
		}
	}
}

function emailCheck (emailStr) 
{
    //remove espaços antes da verificação  
    var emailStr = emailStr;
	// Critica de e-mail 
	var emailPat = /^(.+)@(.+)$/
	var specialChars = "\\(\\)<>@çáéíóúãõâêîôûàèìòù`'^~*!,;:?\\\\\\\"\\.\\[\\]";
	var validChars = "\[^\\s" + specialChars + "\]";
	var quotedUser = "(\"[^\"]*\")";
	var atom = validChars + '+';
	var word = "(" + atom + "|" + quotedUser + ")";
	var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat = new RegExp("^" + atom + "(\\." + atom +")*$");

	// Verifica @ ou .
	var matchArray = emailStr.match(emailPat);
	if (matchArray == null) 
	{
		return false;
	}
	
	//Verifica Nome de usuário
	var user = matchArray[1];
	var domain = matchArray[2];
	if (user.match(userPat) == null) 
	{
		return false;
	}
	
	// Verifica Nome do domínio 
	var domainArray = domain.match(domainPat);
	var domainPonto = domainArray[0].indexOf(".");
	var dominio = domainArray[0].substring(0,domainPonto);
	if (dominio.length < 2)
	{
		return false;
	}
	if (domainArray==null) 
	{
		return false;
	}

	// Verifica Domínio de 3 letras ou 2 letras
	var atomPat = new RegExp(atom,"g");
	var domArr = domain.match(atomPat);
	var len = domArr.length;
	if (domArr[domArr.length-1].length < 2 || domArr[domArr.length-1].length > 3) 
	{
		return false;
	}
}

function valida_data(data)
{
	var data_teste = new Date(data);
	if (isNaN(data_teste))
	{
		return false;
	}
	pos = data.indexOf("/");
	dia = data.substring(0,pos);
	pos_anterior = pos;
	pos = data.indexOf("/",pos+1);
	mes = data.substring(pos_anterior+1,pos);
	pos_anterior = pos;
	ano = data.substring(pos+1,data.length);
	if (dia.indexOf(0)==0)
	{
		dia = dia.substring(1,2);
	}
	if (mes.indexOf(0)==0)
	{
		mes = mes.substring(1,2);
	}
	data = mes + "/" + dia + "/" + ano;
	data = new Date(data);
	if (data.getDate() != dia)
	{
		return false;
	}
	if (data.getMonth()+1 != mes)
	{
		return false;
	}
	if (data.getFullYear() != ano)
	{
		return false;
	}
	return true;
}

function verificadatainiciomaior(d1,d2)
{
	var2 = d1;
	pos = var2.indexOf("/");
	dia = var2.substring(0,pos);
	pos_anterior = pos;
	
	pos = var2.indexOf("/",pos+1);
	mes = var2.substring(pos_anterior+1,pos);
	pos_anterior = pos;
	ano = var2.substring(pos+1,var2.length);
	if (dia.indexOf(0)==0)
	{
		dia = dia.substring(1,2);
	}
	if (mes.indexOf(0)==0)
	{
	mes = mes.substring(1,2);
	}
	var2 = dia + "/" + mes + "/" + ano;
	var DataVar1 = new Date(mes + "/" + dia + "/" + ano);
	
	var3 = d2;
	pos = var3.indexOf("/");
	dia = var3.substring(0,pos);
	pos_anterior = pos;
	
	pos = var3.indexOf("/",pos+1);
	mes = var3.substring(pos_anterior+1,pos);
	pos_anterior = pos;
	ano = var3.substring(pos+1,var3.length);
	if (dia.indexOf(0)==0)
	{
		dia = dia.substring(1,2);
	}
	if (mes.indexOf(0)==0)
	{
		mes = mes.substring(1,2);
	}
	var3 = dia + "/" + mes + "/" + ano;
	var DataVar2 = new Date(mes + "/" + dia + "/" + ano);
	if (DataVar1<=DataVar2)
	{
		return(true);
	}
	else
	{
		return(false);
	}
}

function Valida_CPF(VALOR) {
var ie = (navigator.appName == "Microsoft Internet Explorer");
 
VALOR1 = VALOR
VALOR = VALOR.value
if (ie){
total = VALOR.length
	for (i=0;i<total;i++){
		VALOR = VALOR.replace(String.fromCharCode(46),"")
		VALOR = VALOR.replace(",","")
		VALOR = VALOR.replace("-","")
		VALOR = VALOR.replace("/","")
		VALOR = VALOR.replace(" ","")
	}
}
	if (VALOR == "") 
	    { 
	  	  alert("Favor preencher o CPF corretamente.")
		  //VALOR1.focus()
	      return (false); 
	    } 
	if (((VALOR.length == 11) && (VALOR == 11111111111) || (VALOR == 22222222222) || (VALOR == 33333333333) || (VALOR == 44444444444) || (VALOR == 55555555555) || (VALOR == 66666666666) || (VALOR == 77777777777) || (VALOR == 88888888888) || (VALOR == 99999999999) || (VALOR == 00000000000))) 
	    { 
	  	  alert("Favor preencher o CPF corretamente.")
		  //VALOR1.focus()
	      return (false); 
	    } 

	if (!((VALOR.length == 11) || (VALOR.length == 14))) 
	    { 
	  	  alert("Favor preencher o CPF corretamente.")
		  //VALOR1.focus()	    
	      return (false); 
	    } 

	var checkOK = "0123456789"; 
	var checkStr = VALOR; 
	var allValid = true; 
	var allNum = ""; 
	for (i = 0;  i < checkStr.length;  i++) 
	  { 
	    ch = checkStr.charAt(i); 
	    for (j = 0;  j < checkOK.length;  j++) 
	      if (ch == checkOK.charAt(j)) 
	        break; 
	    if (j == checkOK.length) 
	    { 
	      allValid = false; 
	      break; 
	    } 
	    allNum += ch; 
	  } 
	  if (!allValid) 
	  { 
	  	  alert("Favor preencher o CPF corretamente.")
		  //VALOR1.focus()	  
	    return (false); 
	  } 

	  var chkVal = allNum; 
	  var prsVal = parseFloat(allNum); 
	  if (chkVal != "" && !(prsVal > "0")) 
	  { 
	  	  alert("Favor preencher o CPF corretamente.")
		  //VALOR1.focus()	  
	    return (false); 
	  } 

	if (VALOR.length == 11) 
	{ 
	  var tot = 0; 

	  for (i = 2;  i <= 10;  i++) 
	    tot += i * parseInt(checkStr.charAt(10 - i)); 

	  if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(9))) 
	  { 
	  	  alert("Favor preencher o CPF corretamente.")
		  //VALOR1.focus()	  
	    return (false); 
	  } 
	  
	  tot = 0; 
	  
	  for (i = 2;  i <= 11;  i++) 
	    tot += i * parseInt(checkStr.charAt(11 - i)); 

	  if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(10))) 
	  { 
	  	  alert("Favor preencher o CPF corretamente.")
		  //VALOR1.focus()	  
	    return (false); 
	  } 
	} 
	else 
	{ 
	  var tot  = 0; 
	  var peso = 2; 
	  
	  for (i = 0;  i <= 11;  i++) 
	  { 
	    tot += peso * parseInt(checkStr.charAt(11 - i)); 
	    peso++; 
	    if (peso == 10) 
	    { 
	        peso = 2; 
	    } 
	  } 

	  if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(12))) 
	  { 
	  	  alert("Favor preencher o CPF corretamente.")
		  //VALOR1.focus()	  
	    return (false); 
	  } 
	  
	  tot  = 0; 
	  peso = 2; 
	  
	  for (i = 0;  i <= 12;  i++) 
	  { 
	    tot += peso * parseInt(checkStr.charAt(12 - i)); 
	    peso++; 
	    if (peso == 10) 
	    { 
	        peso = 2; 
	    } 
	  } 

	  if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(13))) 
	  { 
	  	  alert("Favor preencher o CPF corretamente.")
		  //VALOR1.focus()	  
	    return (false); 
	  } 
	} 
	  VALOR1.value = VALOR
	  return(true);
}

function MM_formtCep(e,src,mask) 
{
    if(window.event) 
        _TXT = e.keyCode; 
    else if(e.which) 
        _TXT = e.which; 
    
    if(_TXT > 47 && _TXT < 58) 
    {
        var i = src.value.length; var saida = mask.substring(0,1); var texto = mask.substring(i)
        if (texto.substring(0,1) != saida) 
            src.value += texto.substring(0,1); 

        return true; 
    } 
    else 
    { 
        if (_TXT != 8) 
            return false; 
        else 
            return true; 
    }
}

//************************************************************************************* 
//máscara para Aceitar só números no campo.
//onkeypress="SomenteNumeros(this)"
function SomenteNumeros(e)
{
    var tecla = window.event ? event.keyCode : e.which;
    if (tecla > 47 && tecla < 58) // numeros de 0 a 9
        return true;
    else
        if (tecla != 8) // backspace
            event.keyCode = 0;//return false;
        else
            return true;
}
//************************************************************************************* 
