var reLetra 		=/^[^\d*?]+$/;
var caracters 	= "!@#$%¨&*()-=+_[]{}\/|<>,.;:?";
var reDigitos 	=/^\d+$/;
var reDDMMAAAA	= /^(([0][1-9])|([1,2]\d)|([3][0,1]))\W?(([0][1-9])|([1][0-2]))\W?([1-9][0-9]{3})$/
var fsDDMMAAAA	= "$1/$5/$8"
var reDDMMAA		= /^(([0][1-9])|([1,2]\d)|([3][0,1]))\W?(([0][1-9])|([1][0-2]))\W?([0-9][0-9]{1})$/
var fsDDMMAA		= "$1/$5/$8"

var reCPF				= /^(\d{3})\W?(\d{3})\W?(\d{3})\W?(\d{2})$/ 
var fsCPF				= "$1.$2.$3-$4"
var feCPF				= "$1$2$3$4"
//var reCGCMF				= /^(\d{8})\W?(\d{4})\W?(\d{2})$/
var reCGCMF				=   /^(\d{2})\W?(\d{3})\W?(\d{3})\W?(\d{4})\W?(\d{2})$/;
//var fsCGCMF				= "$1-$2/$3"
var fsCGCMF				= "$1.$2.$3/$4-$5"
//var feCGCMF				= "$1$2$3"
var feCGCMF				= "$1$2$3$4$5"

function tornarOpaco(cur,which){
  strength=(which==0)?1:0.3;
  if (cur.style.MozOpacity)
    cur.style.MozOpacity=strength
  else if (cur.filters)
    cur.filters.alpha.opacity=strength*100;
}

function CentralizarJanela(Largura,Altura) {
Esquerda = (screen.availWidth/2) - (Largura/2);
Topo = (screen.availHeight/2) - (Altura/2);
novajanela.moveTo(Esquerda-10,Topo-10);
}

function AbreAjuda(arquivo) {
novajanela=window.open(arquivo,'novajanela','location=0,status=0,resizable=1,scrollbars=1,width=760,height=400');
CentralizarJanela(740,400);
}


/**************************************************************************************************
***************************************************************************************************/
// REPLACE ALL INSTANCES OF find WITH replace
// inString: the string you want to convert
// find:     the value to search for
// replace:  the value to substitute
//
// usage:    jsReplace(inString, find, replace);
// example:  jsReplace("To be or not to be", "be", "ski");
//           result: "To ski or not to ski"
//
function jsReplace(inString, find, replace) {
    if (!inString) {
        return "";
    }
    // REPLACE ALL INSTANCES OF find WITH replace
    if (inString.indexOf(find) != -1) {
        // SEPARATE THE STRING INTO AN ARRAY OF STRINGS USING THE VALUE IN find
        t = inString.split(find);

        // JOIN ALL ELEMENTS OF THE ARRAY, SEPARATED BY THE VALUE IN replace
        return (t.join(replace));
    }
    else {
        return inString;
    }
}

/**************************************************************************************************
***************************************************************************************************/

function IsTeclaEspecial(tecla){
	var bValido = false;

	if(	(tecla == 8)  ||	//backspace
			(tecla == 39) ||	//right
			(tecla == 37) ||	//left
			(tecla == 36) ||	//home
			(tecla == 46) ||	//delete
			(tecla == 9)  ||	//tab
			(tecla == 35)){ 	//end
			bValido = true;
		}

	return bValido;
}

/**************************************************************************************************
***************************************************************************************************/
function IsNumber(tecla,event){
	var bValido = false;

	if(!event.shiftKey){//verifica se a tecla shift não está pressionada
		if((tecla >= 47 && tecla <= 58) || //numeros de 0 a 9 no teclado acima das letras
			(tecla >= 96 && tecla <= 105)){  //numeros de 0 a 9 no teclado numerico	
			bValido = true
		}
	}

	return bValido;
}

/**************************************************************************************************
***************************************************************************************************/
function IsLetter(tecla){
	var bValido = false;
	var c;
	if((tecla >= 65 && tecla <= 90) || tecla == 32){  //letras de 'a' a 'z'	e espaço em branco
		bValido = true
	}
	
	return bValido;
}
/**************************************************************************************************
***************************************************************************************************/

function valDigitos(campo) {
	if (!reDigitos.test(campo)) {
		return false;
	}
	return true;
}

function validaNome(oCampo){
	var i;
	var bNomeValido = true;
	var texto = oCampo.value;
	
	if(!texto){//se não estiver preenchido, retorna true. Não testa obrigatoriedade
		return true;
	}
	if(!reLetra.test(texto)){
		bNomeValido = false;
	}
	else{
		for(i=0; i < texto.length; i++){
			if(caracters.indexOf(texto.charAt(i)) >= 0){
				bNomeValido = false;
				break;
			}
		}
	}
	
	return bNomeValido;
}

/**************************************************************************************************
-- Valida se tem apenas numeros e letras
***************************************************************************************************/
function validaAlfaNumerico(oCampo){
	var i;
	var bValido = true;
	var texto = oCampo.value;
	
	if(!texto){//se não estiver preenchido, retorna true. Não testa obrigatoriedade
		return true;
	}
	for(i=0; i < texto.length; i++){
		if(caracters.indexOf(texto.charAt(i)) >= 0){
			bValido = false;
			break;
		}
	}
	
	return bValido;
}
/**************************************************************************************************
***************************************************************************************************/
function validaNumero(oCampo){
	var bNumeroValido = true;

	if(!oCampo.value){//se não estiver preenchido, retorna true. Não testa obrigatoriedade
		return true;
	}
	if (!reDigitos.test(oCampo.value)) {
		bNumeroValido = false;
	}
	
	return bNumeroValido;
}
/**************************************************************************************************
***************************************************************************************************/
function validaCep(oCampo) {
	var bCepValido,cep;
	
	if(!oCampo.value){//se não estiver preenchido, retorna true. Não testa obrigatoriedade
		return true;
	}
	bCepValido = true;
	cep = jsReplace(oCampo.value,"-","");
  if(cep.length != 8){
		bCepValido = false;
	}	
	else{
		if(!reDigitos.test(cep)){ //verifica se eh so numero
			bCepValido = false;
		}
	}
	
	//Formata o campo
	if(bCepValido){
		oCampo.value = cep.substring(0,5) + "-" + cep.substring(5);
	}
	
	return bCepValido;
}
/**************************************************************************************************
***************************************************************************************************/
//Substitui todas as ocorrencias de uma string expressão regular por outra
//Eh usado pelo validaData
function impFormat(instr, reBusca, sTroca,umavez,ignorecase) {
	var x= String(typeof reBusca); // Se vier string - converte em espressão regular para aplicar 'g'=global
    if (x.toUpperCase().indexOf('STRING')>=0){
	  	reBusca = new RegExp(reBusca,((ignorecase)?"i":"")+((umavez)?"":"g"))
	}
    return instr.replace(reBusca,sTroca);
}

/**************************************************************************************************
Parametros
field = o campo para ser validado
bmsg = passar true se quiser que a funcao retorne um 'alert'
itipo= 	passar 1 se o formato da data for DDMMAA
				passar 2 se o formato da data for DDMMAAAA 
***************************************************************************************************/
function validaData(field,bmsg,itipo) {
	var atipo=["data","dd/mm/aa","dd/mm/aaaa"];
	var bDDMMAA		= false;
	var bDDMMAAAA	= false;
 	var dia0,mes0,ano0;
 	var auxData;
 	var dData="";

	if (field.value==""){
		return true;
	}
  itipo = (itipo) ? itipo : 0 //0=qualquer, 1=dmaa,2=dmaaaa
	if (itipo == 0 || itipo == 1){
		bDDMMAA = reDDMMAA.test(field.value);
	}
	if (itipo == 0 || itipo == 2){
		bDDMMAAAA = reDDMMAAAA.test(field.value);
	}
	if ((!bDDMMAA) && (!bDDMMAAAA)){// formato não reconhecido
		if(bmsg) alert ("Conteúdo informado não reconhecido como sendo " + atipo[itipo] + "\nVerifique sua digitação");
		return false;
	}
	if (bDDMMAAAA) 
		dData = impFormat(field.value,reDDMMAAAA,fsDDMMAAAA);
 	else 
		dData = impFormat(field.value,reDDMMAA,fsDDMMAA);
  dma=dData.split("/");
		
	if (bDDMMAA){
		dma[2] = (dma[2]<20) ? parseInt(dma[2])+2000 : parseInt(dma[2])+1900} // janelamento de data
  	dData=dma.join("/");
		var obj = new Date(dma[2], dma[1]-1, dma[0]);//cria data no browser
  	dia0 = "00" + obj.getDate();
  	mes0 = "00" + (obj.getMonth()+1);
  	ano0 = "0000" + obj.getFullYear();
  	dia0 = dia0.substring(dia0.length-2);
  	mes0 = mes0.substring(mes0.length-2);
  	ano0 = ano0.substring(ano0.length-4);
  	auxData = dia0 + "/"+  mes0 + "/"+ ano0;
		if (auxData != dData) {
			if (bmsg) alert("Data incorreta\nVerifique sua Digitação");
			return false
		}
  	else {  
			field.value = dia0 + "/" + mes0 + "/" + ((itipo==1)?ano0.substring(ano0,2):ano0);
			return true
		}
  }
//********************************************************************************************
// Valida horas
// true = ok
// false = com erro
// 0 = vazio
//********************************************************************************************
function validaHora(oCampo) {
	var bHoraValida = true
	var vHora;
	var vMinuto;

	if(!oCampo.value){//se não estiver preenchido, retorna true. Não testa obrigatoriedade
		return true;
	}

	horario = oCampo.value
	horario = jsReplace(horario,":","");
	
	if(horario.length != 4)
		bHoraValida = false;
	else{
		vHora = horario.substring(0,2);
		vMinuto = horario.substring(2);
		if (vHora > 23 || vMinuto > 59){
			bHoraValida = false;
		}
		else {
			oCampo.value = vHora + ":" + vMinuto;
		}
	}
	
	return bHoraValida
}
/**************************************************************************************************
***************************************************************************************************/
function validaDataHora(oCampo){
	var bDataHoraValida = true;
	var hora, pos, auxCampo;

	if(!oCampo.value){//se não estiver preenchido, retorna true. Não testa obrigatoriedade
		return true;
	}
	//separa a hora
	auxCampo = oCampo.value;
	oCampo.value = jsReplace(oCampo.value,"/","");
	oCampo.value = jsReplace(oCampo.value,":","");
	oCampo.value = jsReplace(oCampo.value,"-","");
	
	hora = oCampo.value.substring(oCampo.value.length - 4);
	oCampo.value = oCampo.value.substring(0,8);//deixa no campo apenas a data
	if(!validaData(oCampo,false,2)){
		bDataHoraValida = false;
		oCampo.value = auxCampo;
	}
	else if(!validaHora(hora, oCampo)){
		bDataHoraValida = false;
		oCampo.value = auxCampo;
	}
		
	return bDataHoraValida;
}
/**************************************************************************************************
***************************************************************************************************/
function validaTelefone(oCampo){
	var bFoneValido,fone;

	if(!oCampo.value){//se não estiver preenchido, retorna true. Não testa obrigatoriedade
		return true;
	}
	
	bFoneValido = true;
	fone = jsReplace(oCampo.value,"-","");
	fone = jsReplace(fone," ","");
	if(fone.length < 9){
		bFoneValido = false;
	}	
	else{
		if(!reDigitos.test(fone)){ //verifica se eh so numero
			bFoneValido = false;
		}
	}
	
	//Formata o campo
	if(bFoneValido){
		if(fone.length == 9)//prefixo com tres digitos
			oCampo.value = fone.substring(0,2) + " " + fone.substring(2,5) + "-" + fone.substring(5);
		else if(fone.length == 10)//prefixo com quatro digitos
			oCampo.value = fone.substring(0,2) + " " + fone.substring(2,6) + "-" + fone.substring(6);
	}

	return bFoneValido;	
}
/**************************************************************************************************
***************************************************************************************************/
function valFormat(instr, reBusca, sTroca, umavez, ignorecase) {
	var x = String(typeof reBusca);
	if (x.toUpperCase().indexOf('STRING')>=0)
		reBusca = new RegExp(reBusca,((ignorecase)?"i":"")+((umavez)?"":"g"))
	return instr.replace(reBusca,sTroca);
}
/**************************************************************************************************
***************************************************************************************************/
function impCalcDig11(numero) {
	var pesos=[2,3,4,5,6,7,8,9,2,3,4,5,6,7,8,9]
	var calc= 0 , x=''
	var numero=String(numero).split("")
	var limite=numero.length -1
	var result = 0
	var pso=0
	for (var i=limite; i>=0; i--) {
		x+="\npso:"+pesos[pso]+" * "+ numero[i] + " = " + (pesos[pso] * parseInt(numero[i]))
		calc += (pesos[pso++] * parseInt(numero[i]))
	} 
	result = 11 - ((calc)%11)
	if (result == 11) {result = 0}
	return result	 
}
/**************************************************************************************************
***************************************************************************************************/
function validaCpfCgc(oCampo,itipo){ 
	var atipo=["CPF/CNPJ","CPF","CNPJ"]
	var cpf='', cgc='', digito='',dg='', dgc='', digitoc='', k=0, i=0, j=0, soma=0, mt=0;
	var cpfcgc = oCampo.value;
	var bcpf=false;
	var bcgc=false;

	if (oCampo.value==""){
		return true;
	}
	
	itipo=(itipo)?itipo:0 // 0=qualquer, 1=cpf,2=cgc   
	if (itipo==0||itipo==1) bcpf= reCPF.test(cpfcgc);	// valida tamanho e formato do CPF
	if (itipo==0||itipo==2) bcgc= reCGCMF.test(cpfcgc);	// valida tamanho e formato do CCG
	if ((!bcpf)&&(!bcgc)) {// formato não reconhecido
		return false ;
	}
	// tirar separadores
	if (bcpf)
		cpfcgc=cpfcgc.replace(reCPF,feCPF);
	else
		cpfcgc=cpfcgc.replace(reCGCMF,feCGCMF) ;
	// valida entradas fáceis
	var cpferr = 	"0000000000011111111111222222222223333333333344444444444"+
					 			"5555555555566666666666777777777778888888888899999999999"
	if (cpferr.indexOf(cpfcgc) >= 0) { // informado campo de facil entrada
		return false;
	}
	// tabela de pesos para colunas
	mult = [2,3,4,5,6,7,8,9,2,3,4,5,6,7,8,9];
	if (bcgc){
		cgc = cpfcgc.substring(0,12);
		digito = cpfcgc.substring(12,14);
		for (j = 1; j <= 2; j++) {
			digitoc = impCalcDig11(cgc)
			if (digitoc == 10) digitoc = 0
			dgc +=digitoc;
			cgc+=digitoc;
		}
	}
	else{
		cpf = cpfcgc.substring(0,9);
		digito = cpfcgc.substring(9,11);
		for (j = 1; j <= 2; j++) {
			soma = 0;
			mt = 2;
			for (i = 8 + j; i >= 1; i--) {
				soma += parseInt(cpf.charAt(i-1),10) * mt;
				mt++;
			}
			dg = 11 - (soma % 11);
			if (dg > 9) {dg = 0};
			cpf += dg;
			dgc+=dg
		}
	} 
	// digito inválido	
	if (dgc != digito) {
		return false;
	}
	else {
		oCampo.value = valFormat(oCampo.value,((bcgc)?reCGCMF:reCPF),((bcgc)?fsCGCMF:fsCPF));
		return true;
	}
}

//Assume que as datas são válidas
function validaPeriodo(dataIni,dataFim,nomePeriodo) {
	
	//Valida período de decisão
	if (dataIni.value == "" && dataFim.value == "") {
		return true;
	}
	
	if ( dataIni.value == "" ) {
		alert('Informe a data inicial do '+nomePeriodo+'.');
		return false;
	}

	if ( !validaData(dataIni,false,2) ) {
		alert('Data inicial do '+nomePeriodo+' inválida.');
		return false;
	}
	
	if ( dataFim.value == "" ) {
		alert('Informe a data final do '+nomePeriodo+'.');
		return false;
	}

	if ( !validaData(dataFim,false,2) ) {
		alert('Data final do '+nomePeriodo+' inválida.');
		return false;
	}
	
	var sDataIni = new String(dataIni.value);
	var sDataFim = new String(dataFim.value);
	
	var dDataIni = new Date(sDataIni.substr(6,4),(sDataIni.substr(3,2)-1),sDataIni.substr(0,2));
	var dDataFim = new Date(sDataFim.substr(6,4),(sDataFim.substr(3,2)-1),sDataFim.substr(0,2));

	//alert(dDataIni.toString()+"#"+dDataFim.toString());
	
	if ( dDataIni.getTime() > dDataFim.getTime() ) {
		alert(nomePeriodo+' inválido.');
		return false
	}
	return true;
}




