// JavaScript Document

function somenteNumero(e) {
	/**
	* onKeyPress="return somenteNumero(event);"
	*/
	var tecla = (window.event)?event.keyCode:e.which;
	if ((tecla>47 && tecla<58) || tecla==8 || tecla==9 || tecla==0) {
		return true;
	} else {
		if (tecla!=44) {
			return false;
		} else { 
			return true;
		}
	}
}

function somenteNumeroPonto(e, valor) {
	/**
	* onKeyPress="return somenteNumeroPonto(event, this.value);"
	*/
	var tecla = (window.event)?event.keyCode:e.which;
	var controle = valor.split(".");
	
	if ((tecla>47 && tecla<58) || tecla==8 || tecla==9 || tecla==0) {
		if (controle[1].length<2) {
			return true;
		} else {
			return false;
		}
	} else {
		if (tecla!=46) {
			return false;
		} else {
			return true;
		}
	}
}

function mascaraCep(e, cep) {
	/**
	* maxlength="10" onkeypress="return mascaraCep(event, this);" onBlur="validaCEP(event, this);"
	*/
	if (mascaraInteiro(e)==false) {
		return false;
	}
	return formataCampo(cep, '00.000-000', e);
}

function mascaraData(e, data) {
	/**
	* maxlength="10" onkeypress="return mascaraData(event, this);" onBlur="validaData(this);"
	*/
	if (mascaraInteiro(e)==false) {
		return false;
	}
	return formataCampo(data, '00/00/0000', e);
}

function mascaraTelefone(e, tel) {
	/**
	* maxlength="11" onkeypress="return mascaraTelefone(event, this);" onBlur="validaTelefone(this);"
	*/

	if (mascaraInteiro(e)==false) {
		return false;
	}
	return formataCampo(tel, '00 00000000', e);
}

function mascaraCPF(e, cpf) {
	/**
	* maxlength="14" onkeypress="return mascaraCPF(event, this);" onBlur="validaCPF(this);"
	*/
	if (mascaraInteiro(e)==false) {
		return false;
	}
	return formataCampo(cpf, '000.000.000-00', e);
}

function mascaraInteiro(e) {
	var tecla = (window.event)?event.keyCode:e.which;

	if (tecla!=8 && tecla!=9 && tecla!=0 && (tecla<48 || tecla>57)) {
		return false;
	}
	else return true;
}

function formataCampo(campo, Mascara, evento) {
	var boleanoMascara;
	var Digitato = (window.event)?evento.keyCode:evento.which;
	exp = /\-|\.|\/|\(|\)| /g
	campoSoNumeros = campo.value.toString().replace( exp, "" );
	var posicaoCampo = 0;
	var NovoValorCampo = "";
	var TamanhoMascara = campoSoNumeros.length;
	
	if (Digitato!=8) { 
		// backspace
	
		for(i=0; i<=TamanhoMascara; i++) {
			boleanoMascara = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".") || (Mascara.charAt(i) == "/"));
			boleanoMascara = boleanoMascara || ((Mascara.charAt(i) == "(") || (Mascara.charAt(i) == ")") || (Mascara.charAt(i)==" "));
			if (boleanoMascara) {
				NovoValorCampo += Mascara.charAt(i);
				TamanhoMascara++;
			}
			else {
				NovoValorCampo += campoSoNumeros.charAt(posicaoCampo); 
				posicaoCampo++;
			}
		}
		campo.value = NovoValorCampo;
		return true;
	}
	else {
		return true;
	}
}

//valida telefone
function validaTelefone(tel) {
	/**
	* onBlur="validaTelefone(this);"
	*/
	exp = /\d{2}\ \d{8}/
	if (tel.value!="") {
		if (!exp.test(tel.value)) {
			alert('Numero de telefone inválido!');
			tel.focus();
		}
	}
}

//valida CEP
function validaCEP(cep) {
	/**
	* onBlur="validaCEP(this);"
	*/
	exp = /\d{8}/
	if (cep.value!="") {
		if (!exp.test(cep.value)) {
			alert('Número de CEP inválido!');
			cep.focus();
		}
	}
}

//valida data
function validaData(data) {
	/**
	* onBlur="validaData(this);"
	*/
	exp = /\d{2}\/\d{2}\/\d{4}/
	if (data.value!="") {
		if (!exp.test(data.value)) {
			alert('Data inválida!');
			data.focus();
		}
	}
}

function validaCPF(Objcpf) {
	/**
	* onBlur="validaCPF(this);"
	*/
	var cpf = Objcpf.value;
	exp = /\.|\-/g
	cpf = cpf.toString().replace( exp, "" );
	var digitoDigitado = eval(cpf.charAt(9)+cpf.charAt(10));
	var soma1 = 0, soma2 = 0;
	var vlr = 11;
	
	for (i=0; i<9; i++) {
		soma1 += eval(cpf.charAt(i)*(vlr-1));
		vlr--;
	}
	
	if (soma1%11<2) {
		digito1 = 0;
	} else {
		digito1 = 11-(soma1%11);
	}
	
	vlr = 11;
	
	for (i=0; i<9; i++) {
		soma2 += eval(cpf.charAt(i)*(vlr));
		vlr--;
	}
	
	if ((soma2+(digito1*2))%11<2) {
		digito2=0;
	} else {
		digito2=11-((soma2+(digito1*2))%11);	
	}

	if (Objcpf.value!="") {
		if (digito1!=cpf.charAt(9) || digito2!=cpf.charAt(10)) {
			alert('CPF Invalido!');
			Objcpf.value = "";
			Objcpf.focus();
		}
	}
}

function validaEmail(email) {
	/**
	* onBlur="validaEmail(this);"
	*/
	exp = /[a-z-\._0-9]{3,}@[a-z]{2,}\.[a-z]{3,}(\.[a-z]{2,})?$/
	if (email.value!="") {
		if (!exp.test(email.value)) {
			alert('E-mail inválido!');
			email.focus();
		}
	}
}

function MM_findObj(n, d) {
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function camposObrigatorios() {
	/**
	* onSubmit="return camposObrigatorios('formulario','campo1','#q','0','mensagem',...);return document.MM_returnValue"
	*'obrigatorio','#q','0','c obrigatorio'
	*'numeros','0_9','1','c numero entre 0 e 9'
	*'email','S','2','c email'
	*'data','^\([0-9][0-9]\)\/\([0-9][0-9]\)\/\([0-9]{4}\)$#1#2#3','3','c data'	
	*'data obrigatória','#^\([0-9][0-9]\)\/\([0-9][0-9]\)\/\([0-9]{4}\)$#1#2#3','3','Digite seu nascimento.'
	*combobox - 'combonome','#q','1','c obrigatorio'
	*'foto','#q','PDF,JPG','Insira sua foto.'
	*/
  var a=camposObrigatorios.arguments,oo=true,v='',s='',err=false,r,o,at,o1,t,i,j,ma,rx,cd,cm,cy,dte,at;
  for (i=1; i<a.length;i=i+4){
    if (a[i+1].charAt(0)=='#'){r=true; a[i+1]=a[i+1].substring(1);}else{r=false}
    o=MM_findObj(a[i].replace(/\[\d+\]/ig,""));
    o1=MM_findObj(a[i+1].replace(/\[\d+\]/ig,""));
    v=o.value;t=a[i+2];
    if (o.type=='text'||o.type=='password'||o.type=='hidden'){
      if (r&&v.length==0){err=true}
      if (v.length>0)
      if (t==1){ //fromto
        ma=a[i+1].split('_');if(isNaN(v)||v<ma[0]/1||v > ma[1]/1){err=true}
      } else if (t==2){
        rx=new RegExp("^[\\w\.=-]+@[\\w\\.-]+\\.[a-zA-Z]{2,4}$");if(!rx.test(v))err=true;
      } else if (t==3){ // date
        ma=a[i+1].split("#");at=v.match(ma[0]);
        if(at){
          cd=(at[ma[1]])?at[ma[1]]:1;cm=at[ma[2]]-1;cy=at[ma[3]];
          dte=new Date(cy,cm,cd);
          if(dte.getFullYear()!=cy||dte.getDate()!=cd||dte.getMonth()!=cm){err=true};
        }else{err=true}
      } else if (t==4){ // time
        ma=a[i+1].split("#");at=v.match(ma[0]);if(!at){err=true}
      } else if (t==5){ // check this 2
            if(o1.length)o1=o1[a[i+1].replace(/(.*\[)|(\].*)/ig,"")];
            if(!o1.checked){err=true}
      } else if (t==6){ // the same
            if(v!=MM_findObj(a[i+1]).value){err=true}
      }
    } else
    if (!o.type&&o.length>0&&o[0].type=='radio'){
          at = a[i].match(/(.*)\[(\d+)\].*/i);
          o2=(o.length>1)?o[at[2]]:o;
      if (t==1&&o2&&o2.checked&&o1&&o1.value.length/1==0){err=true}
      if (t==2){
        oo=false;
        for(j=0;j<o.length;j++){oo=oo||o[j].checked}
        if(!oo){s+='* '+a[i+3]+'\n'}
      }
    } else if (o.type=='checkbox'){
      if((t==1&&o.checked==false)||(t==2&&o.checked&&o1&&o1.value.length/1==0)){err=true}
    } else if (o.type=='select-one'||o.type=='select-multiple'){
      if(t==1&&o.selectedIndex/1==0){err=true}
    }else if (o.type=='textarea'){
      if(v.length<a[i+1]){err=true}
    } else if (o.type=='file'){
		if(a[i+1]=="q") {
		  if(o.value==""){
			s+='* '+a[i+3]+'\n';
		  }
		}
		if(a[i+2]!="") {
			vExt=0;
			extensoes = a[i+2].split(",");
			qtd = extensoes.length;
			extensao = o.value.substr(o.value.length-3).toUpperCase();
			for(x=0; x<qtd; x++) {
				if(extensao==extensoes[x]) {
					vExt=1;
				}
			}
			if(vExt==0) {
				s+='* O arquivo deve conter a(s) extensão: '+a[i+2]+'\n';
			}
		}
    } 
    if (err){s+='* '+a[i+3]+'\n'; err=false}
  }
  if (s!=''){
	alert('As informações necessárias estão incompletas ou apresentam erro:\t\t\t\t\t\n\n'+s)
  	return false;
  }
  else if (s=='') {
  	//document.getElementById(a[0]).submit();
		return true;
  }
}
