// valida numero inteiros ou não
function valida_numero(numero,inteiro) {
	numero = new String(numero);
	
	if(numero.length==0)
		return false;
		
	var exp = /^\$|\./g ;

	// retira $ e .
	numero = numero.replace(exp, "");
	
	exp = /,/g ;
	
	// troca , por .
	numero = numero.replace(exp,".");

	numero = parseFloat(numero);
	
	if(isNaN(numero))
		return false;
		
	if(numero==0.00)
		return false;

	if(inteiro && numero!=Math.round(numero))
		return false;
		
	return true;

}


function numeros_validos(numero)
{
	var reDigits = /^\d+$/;
	
	if (reDigits.test(numero)) {
		return true;
	} else {
		return false;
	}
}

// verifica se um ano é bissexto
function ano_bi(ano) {
	if (ano % 100 == 0) {
		if (ano % 400 == 0) 
			return true; 
	}
	else 
		if ((ano % 4) == 0) 
			return true; 
	return false;
}


// Valida uma data
function valida_data(data) {
	var datePat = /^(\d{1,2})(\/|-|.)(\d{1,2})\2(\d{4})$/;

	var datadiv = data.match(datePat);

   	if (datadiv==null)
		return false;
	
	var dia = datadiv[1];
	var mes = datadiv[3];
	var ano = datadiv[4];

	if(dia<1 || dia>31 || mes<1 || mes>12)
		return false;

	if ((mes==4 || mes==6 || mes==9 || mes==11) && dia>30) 
		return false;
	
	if(mes==2)
		if(dia>29)
			return false;
		else
			if(dia==29 && !ano_bi(ano))
				return false;
	if(ano<1800)
		return false;

	return true;

}

function valida_hora(hora){ 
              
	var horaPat = /^(\d{1,2})(\/|-:|.)(\d{1,2})$/;

        var horadiv = hora.match(horaPat);

        if (horadiv==null)
                return false;

        var hrs = horadiv[1];
        var min = horadiv[3];
 
              // verifica data e hora 
              if ((hrs < 00 ) || (hrs > 23) || ( min < 00) ||( min > 59))
                  return false; 
               
	return true;
}

// valida CEP
function valida_cep(cep) {
	if(cep.length>9 || (cep.indexOf("-")==-1 && cep.length>8))
		return false;
	
	var pat = /((\d{5})(-)(\d{3}))|(\d{8})/;
	
	var cepdiv = cep.match(pat);
	
	if(cepdiv==null)
		return false;
	return true;
}


// Calculo do CNPJ 
function valida_cnpj(cnpj) {
	var erro = true; 
	var aux_cnpj = "";	
	var cnpj1=0,cnpj2=0;
	for(j=0;j<cnpj.length;j++)
		if(cnpj.substr(j,1)>="0" && cnpj.substr(j,1)<="9")
			aux_cnpj += cnpj.substr(j,1);
	if(aux_cnpj.length!=14)
		erro = false;
	else {
		cnpj1 = aux_cnpj.substr(0,12);
		cnpj2 = aux_cnpj.substr(aux_cnpj.length-2,2);
		fator = "543298765432";
		controle = "";
		for(j=0;j<2;j++) {
			soma = 0;
			for(i=0;i<12;i++) 
				soma += cnpj1.substr(i,1) * fator.substr(i,1);
			if(j==1) soma += digito * 2;
			digito = (soma * 10) % 11;
			if(digito==10) digito = 0;
			controle += digito;
			fator = "654329876543";
		} 
		if(controle!=cnpj2)
			erro = false;
	} 
	return erro;
}

// Validação do CPF
function valida_cpf(cpf) {
	var cpf = new String(cpf);
    var aux_cpf = "";
	var exp = /^\$|\.|\-/g ;
	        // retira $ e .
        cpf = cpf.replace(exp, "");

        exp = /,/g ;
	
	if(cpf.length!=11)
		return false;
				 		
	if ((cpf == '00000000000')|| (cpf == '11111111111') || (cpf == '2222222222')
		|| (cpf == '33333333333') || (cpf == '44444444444') || (cpf == '55555555555')
		|| (cpf == '66666666666') || (cpf == '77777777777') || (cpf == '88888888888')
		|| (cpf == '99999999999')) return false;
		
    for(j=0;j<cpf.length;j++)
  		if(cpf.substr(j,1)>="0" && cpf.substr(j,1)<="9")
   			aux_cpf += cpf.substr(j,1);
	if(aux_cpf.length!=11)
		return false;
    else {
    	var cpf1 = String(aux_cpf);
    	var cpf2 = cpf.substr(cpf.length-2,2);
      	var controle = "";
      	var start = 2;
      	var end = 10;
      	for(var i=1;i<=2;i++) {
      		var soma = 0;
      		for(j=start;j<=end;j++)
      			soma += cpf1.substr((j-i-1),1)*(end+1+i-j);
        	if(i==2)
          		soma += digito * 2;
        	digito = (soma * 10) % 11;
        	if(digito==10)
          		digito = 0;
        	controle += digito;
        	start = 3;
        	end = 11;
      	}
      	if(controle!=cpf2)
        	return false;
    }
	
	return true;
}


// Esta é uma função simples para validar emails
function valida_email(email) {
	var chars = "@#$&[]()/\\\{}!^:'\"";
	var pat=/^(.+)@(.+)$/;
	
	var emaildiv = email.match(pat);
	
	if(emaildiv==null)
		return false;
		
	var login = emaildiv[1];
	var dominio = emaildiv[2];
	
	for(var i=0;i<chars.length;i++) {
		if(login.indexOf(chars.substr(i,1))!=-1)
			return false;
	}
	
	for(var i=0;i<chars.length;i++) {
		if(dominio.indexOf(chars.substr(i,1))!=-1)
			return false;
	}
	
	return true;
}

// Valida uma string em particular (tipo login ou senha)
function valida_string(string) {
	str = new String(string);
	if(str.length<5)
		return false;
	if(str.indexOf(" ")!=-1)
		return false;

	var chars = "@#$&[]()/\\\{}!^:'\"";

	for(var i=0;i<chars.length;i++) {
		if(str.indexOf(chars.substr(i,1))!=-1) {
			return false;
		}
	}
		
	return true;

}

// Valida o numero do Cartão de crédito
function valida_cartao(numero) {
	var str = new String(numero);

	if(str.length==0)
		return false;

	var peso = (str.length%2==0) ? 2 : 1;
	var soma = 0;
	
	for(var i=0;i<str.length;i++) {
		num = str.substr(i,1);
		vlr = num*peso;
		soma+= (vlr>9) ? vlr-9 : vlr;
		peso = (peso==2) ? 1 : 2;
	}

	return (soma%10==0 && soma!=0);
}

// Valida a Data de validade do cartão (mm/aa)
function valida_dtvalidade(data) {
	var datePat = /^(\d{1,2})(\/|-|.)(\d{1,2})$/;
	var dtdiv = data.match(datePat);
	
	if(dtdiv==null)
		return false;
	
	var dia = 31;
	var mes = parseInt(dtdiv[1]);
	var ano = parseInt(dtdiv[3]);
	
	if(mes<1 || mes>12 || ano<01)
		return false;
	
	var data = new Date();
	var mes_at = data.getMonth();
	var ano_at = data.getYear();
	mes_at++;
	ano+=2000; 
	
	var anomes = ano*100+mes;
	var anomes_at = ano_at*100+mes_at;
	
	if(anomes<anomes_at)
		return false;
	
	return true;		
}

function retira_car(numero) {

	var exp = /^\$|\./g ;


	numero = numero.replace(exp, "");
	
	return numero;

}

function retira_caract(numero) {

	if(numero.length=="0")
                return false;

        var exp = /^\0|\.|\-/g ;

        numero = numero.replace(exp, "");

        return numero;

}

function valida_form(form,campos,nomes,tipos,status) {
	/*
	form = posição do formulário (0,1,...)
	campos = campos a verificar (0,1,2,...)
	tipos = tipo de cada campo:
			 	1-inteiro
				2-decimal
				3-data
				4-email
				5-cpf
				6-cnpj
				7-cep
				8-string MAIUSC
				9-login/senha
				10-confirmação de senha 
				11-Cartão de Crédito
				12-Validade do Cartão (mes/ano)
				13-Campo quantidade
				14-hora
				15-String Normal
	status = 0 - não obrigatório, 1 - obrigatório

	select = 0 - não;  //válido somente para campo to tipo input text;
		     1 - sim;
	*/

	var mensagem = "Preencha corretamente o campo:\n\n";
	var erro = false;
	var foco = -1;
	var seleciona_campo = 0;
	
	form++;
	
		for(var i=0;i<campos.length;i++) {
			resultado=true;
			valor = document.forms[form].elements[campos[i]].value;
			switch(tipos[i]) {
			case 1:
//				resultado = valida_numero(valor,true);
				resultado = numeros_validos(valor);
				if(valor==0 && status[i]==1)
					resultado=false;
				document.forms[form].elements[campos[i]].value = retira_car(valor);
				break;
			case 2:
				resultado = valida_numero(valor,false);
				document.forms[form].elements[campos[i]].value = retira_car(valor);			
				break;
			case 3:
				resultado = valida_data(valor);
				break;
			case 4:
				resultado = valida_email(valor);
				document.forms[form].elements[campos[i]].value = valor.toLowerCase();
				break;
			case 5:
				resultado = valida_cpf(valor);
				break;
			case 6:
				resultado = valida_cnpj(valor);
				break;
			case 7:
				resultado = valida_cep(valor);
				break;
			case 8:
				resultado = (valor.length==0) ? false : true;
				document.forms[form].elements[campos[i]].value = valor.toUpperCase();			
				break;
			case 9:
				resultado = valida_string(valor);
				break;
			case 10:
				resultado = valida_string(valor);
				if(resultado)
					resultado = (valor==document.forms[form].elements[campos[i-1]].value);
				break;
			case 11:
				resultado = valida_cartao(valor);
				break;
			case 12:
				resultado = valida_dtvalidade(valor);
				break;
			case 13:
				resultado = valida_numero(valor,true);
							if(valor==0 && status[i]==1)
									resultado=false;
							document.forms[form].elements[campos[i]].value = retira_caract(valor);
							break;
			case 14:
							resultado = valida_hora(valor);
							break;
			case 15:
				resultado = (valor.length==0) ? false : true;
				break;							
			}
			
			if(!resultado && (status[i]==1 || (status[i]==0 && valor.length!=0))) {
				erro = true;
				if (foco==-1) {
					mensagem+= "- " + nomes[i] + "\n";				
					foco = campos[i];
					tipo_campo = tipos[i];
					seleciona_campo = selecionar[i];
				}
			}
			
		}
	
		if(erro){
			alert(mensagem);
			document.forms[form].elements[foco].focus();
			if (seleciona_campo == 1)
			document.forms[form].elements[foco].select();
		}
		return !erro;
}

/*MOVER A BARRA DE ROLAGEM DO BROWSER*/
function scrollbody() {
	if( document.body && document.body.clientHeight ) {
		window.innerHeight = document.body.clientHeight
	}
	window.scrollTo( 0, (window.innerHeight/2) );
}

function checkArea() {
	if(fcurriculo.areaInteresse.value == 8) {
		fcurriculo.outroInteresse.disabled = false;
		fcurriculo.outroInteresse.focus();
	} else {
		fcurriculo.outroInteresse.disabled = true;
	}
}

function valida_OutraArea() {
	if ((fcurriculo.areaInteresse.value == 8)&&(fcurriculo.outroInteresse.disabled==false)&&(fcurriculo.outroInteresse.value=='')) {
		fcurriculo.outroInteresse.focus();
		alert("Preencha corretamente o campo:\n\n- OUTRA ÁREA");		
	}
}

function formataData(Campo, teclapres){
                                var tecla = teclapres.keyCode;

                                var vr = new String(Campo.value);
                                vr = vr.replace("/", "");

                                tam = vr.length + 1;

                                if (tecla != 9 && tecla != 8 && tecla != 46){
                                        if (tam > 2 && tam < 4)
                                                Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, tam);
                                        if (tam >= 5 && tam <7)
                                                Campo.value = vr.substr(0,2) + '/' + vr.substr(2,2) + '/' + vr.substr(7,tam);

                        	}
                      	}
						
function popup_produto(img){
	var janela
	var lado = (screen.width - 400) / 2;
	var topo = (screen.height - 300) / 2;	
	janela = window.open("","janela1",'height=300, width=400, top='+topo+',left='+lado+'');
	janela.document.open();
	janela.document.write("<html><title> StoreAge - Telas </title>");
    janela.document.write("<body leftmargin=0 topmargin=0 marginwidth=0 marginheight=0 bgcolor='#000000'>");	
	janela.document.write('<div align="center" style="position:relative; font-family:Arial, Helvetica, sans-serif; font-size:10px; background-color:#FFFFFF;">Clique na imagem para fechar.</div>');
	janela.document.write('<div align="center" style="cursor:pointer;"><img src="' + img +'"alt="Clique para Fechar" width="400" height="300" onclick="window.close();"/></div>');
	janela.document.write("</body></html>");	
	janela.document.close();
}						

