//Verifica qual o browser do visitante e armazena na variável púbica browser,
 //Caso Internet Explorer(IE) outros (Other)
 if (navigator.appName.indexOf('Microsoft') != -1){
 	browser = "IE";
 }else{
 	browser = "Other";
 }

//##################################################################################################################

//funcao para abrir popups no centro da tela
function abrir_popup(url, nome, w, h, scroll) {
    var winl = (screen.width - w) / 2;
    var wint = (screen.height - h) / 2;
    //var winl = (794 - w) / 2;
    //var wint = (660 - h) / 2;
    propriedades = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable=yes,status=yes';
    win = window.open(url, nome, propriedades);

    if (parseInt(navigator.appVersion) >= 4){
        win.window.focus();
    }
}


//##################################################################################################################
//FUNCAO QUE MASCARA OS CAMPOS TEXTO
function mascara(event,formatacao){
    var tecla;    //variavel q recebera a tecla digitada
    var codigo_tecla;  //variavel q receberá o codigo ASCII da tecla
    
	if(browser == "IE" )
		codigo_tecla=event.keyCode;  //recebe o codigo ASCII da tecla digitada
	else
		codigo_tecla=event.charCode;  //recebe o codigo ASCII da tecla digitada
		
		
    tecla = String.fromCharCode(codigo_tecla);  //recebe a tecla

    return valida_caractere(tecla,event,formatacao); //chama a funcao valida_tecla, que
                                      //retorna true se a tecla for válida e false se não for
}

//FUNCAO QUE VALIDA TECLA (É CHAMADA PELA FUNCAO MASCARA)
function valida_caractere(caractere,event,formatacao){
    //conjunto de caracteres válidos//
    var caracteres_validos;
	
	if(browser == "IE" )
		codigo_tecla=event.keyCode;  //recebe o codigo ASCII da tecla digitada
	else
		codigo_tecla=event.charCode;  //recebe o codigo ASCII da tecla digitada

   
   
   switch(formatacao){
        case "NUMEROS" :

            caracteres_validos = "0123456789";
            break;

        case "CONSULTA" :

            caracteres_validos = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%";
            break;

        case "ABCDE" :

            caracteres_validos = "ABCDEabcde";
            break;
		 
		 case "ABCDEX" :

            caracteres_validos = "ABCDEXabcdex";
            break;
        case "0|1|2" :

            caracteres_validos = "012";
            break;

        case "4|5" :

            caracteres_validos = "45";
            break;

        case "EDITAL" :

            caracteres_validos = "01234567/89";
            break;

        case "MAIUSCULAS" :

            caracteres_validos = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\ÁáÂâÃãÉéÊêÍíÓóÔôÕõÚúÇç()°";
            break;
			
        case "ALFANUM" :

            caracteres_validos = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-ÁáÂâÃãÉéÊêÍíÓóÔôÕõÚú/\Çç()°";
            break;
		case "REAL" :

            caracteres_validos = "0123456789,.";
            break;


        default :
            caracteres_validos = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123\456789/-°()";
    }
    
	
	if( caracteres_validos.indexOf(caractere) != -1 || codigo_tecla < 31){
		return true ;
	}else{
		return false;
	}
   
}//fim da funcao valida_caractere

//#########################################################################################################################

//funcao para tornar o valor de um campo em maiusculas
function upperCase(campo){
	campo.value = campo.value.toUpperCase();
}

//#########################################################################################################################
//FUNCAO PARA FORMATAR CAMPOS DE DATA,HORA,ETC...

function FormataCampo(Campo,teclapres,mascara){
    
	//escolhe a funcao de acordo com o navegador
	if(browser == "IE")
		tecla = teclapres.keyCode;
	else
		tecla = teclapres.charCode;
		
	//pegando o tamanho do texto da caixa de texto com delay de -1 no event
    //ou seja o caractere que foi digitado não será contado.
	//teclapres = window.event;
	strtext = Campo.value
    tamtext = strtext.length
    //pegando o tamanho da mascara
    tammask = mascara.length
    //criando um array para guardar cada caractere da máscara
    arrmask = new Array(tammask)
    //jogando os caracteres para o vetor
    for (var i = 0 ; i < tammask; i++){
        arrmask[i] = mascara.slice(i,i+1)
    }
    //alert (tecla)
    //começando o trabalho sujo
    if (((((arrmask[tamtext] == "#") || (arrmask[tamtext] == "9"))) || (((arrmask[tamtext+1] != "#") || (arrmask[tamtext+1] != "9"))))){
        if ((tecla >= 37 && tecla <= 40)||(tecla >= 48 && tecla <= 57)||(tecla >= 96 && tecla <= 105)||(tecla == 8)||(tecla == 9) ||(tecla == 46) ||(tecla == 13)){
            Organiza_Casa(Campo,arrmask[tamtext],tecla,strtext)
        }
        else{
            Detona_Event(Campo,strtext)
        }
    }
    else{//Aqui funcionaria a mascara para números mas eu ainda não implementei
        if ((arrmask[tamtext] == "A"))    {
            charupper = event.valueOf()
            //charupper = charupper.toUpperCase()
            Detona_Event(Campo,strtext)
            masktext = strtext + charupper
            Campo.value = masktext
        }
    }
}
function Organiza_Casa(Campo,arrpos,teclapres_key,strtext){
    if (((arrpos == "/") || (arrpos == ".") || (arrpos == ",") || (arrpos == ":") || (arrpos == " ") || (arrpos == "-")) && !(teclapres_key == 8)){
        separador = arrpos
        masktext = strtext + separador
        Campo.value = masktext
    }
}
function Detona_Event(Campo,strtext){
    
    if (strtext != "") {
        Campo.value = strtext
    }
	return false;
}


function Bloqueia_Caracteres(evnt){
 //Função permite digitação de números
 	if (browser == "IE"){
 		if (evnt.keyCode < 48 || evnt.keyCode > 57){
 			return false
 		}
 	}else{
 		if (( (evnt.charCode > 31 && evnt.charCode < 48 ) || evnt.charCode > 57) && evnt.charCode == 0){
 			return false
 		}
 	}
 }
 
 //#################################################################################################################
 

//funcao que verifica se as datas foram digitadas corretamente

function Verifica_Data(data, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
  //var data = document.getElementById(data);
 	var strdata = data.value;
 	if((obrigatorio == 1) || (obrigatorio == 0 && strdata != "")){
 		//Verifica a quantidade de digitos informada esta correta.
 		if (strdata.length != 10){
 			alert("Formato da data não é válido.Formato correto: dd/mm/aaaa.");
 			data.focus();
 			return false
 		}
 		//Verifica máscara da data
 		if ("/" != strdata.substr(2,1) || "/" != strdata.substr(5,1)){
 			alert("Formato da data não é válido. Formato correto: dd/mm/aaaa.");
 			data.focus();
 			return false
 		}
 		dia = strdata.substr(0,2)
 		mes = strdata.substr(3,2);
 		ano = strdata.substr(6,4);
 		//Verifica o dia
 		if (isNaN(dia) || dia > 31 || dia < 1){
 			alert("Formato do dia não é válido.");
 			data.focus();
 			return false
 		}
 		if (mes == 4 || mes == 6 || mes == 9 || mes == 11){
 			if (dia == "31"){
 				alert("O mês informado não possui 31 dias.");
 				data.focus();
 				return false
 			}
 		}
 		if (mes == "02"){
 			bissexto = ano % 4;
 			if (bissexto == 0){
 				if (dia > 29){
 					alert("O mês informado possui somente 29 dias.");
 					data.focus();
 					return false
 				}
 			}else{
 				if (dia > 28){
 					alert("O mês informado possui somente 28 dias.");
 					data.focus();
 					return false
 				}
 			}
 		}
 	//Verifica o mês
 		if (isNaN(mes) || mes > 12 || mes < 1){
 			alert("Formato do mês não é válido.");
 			data.focus();
 			return false
 		}
 		//Verifica o ano
 		if (isNaN(ano)){
 			alert("Formato do ano não é válido.");
 			data.focus();
 			return false
 		}
 	}
 }
 
//######################################################################################################################

//funcao que verifica se as horas foram digitadas corretamente
function Verifica_Hora(hora, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
 	//var hora = document.getElementById(hora);
 	if((obrigatorio == 1) || (obrigatorio == 0 && hora.value != "")){
 		if(hora.value.length < 5){
 			alert("Formato da hora inválido.Por favor, informe a hora no formato correto: hh:mm");
 			hora.focus();
 			return false
 		}
 		if(hora.value.substr(0,2) > 23 || isNaN(hora.value.substr(0,2))){
 			alert("Formato da hora inválido.");
 			hora.focus();
 			return false
 		}
 		if(hora.value.substr(3,2) > 59 || isNaN(hora.value.substr(3,2))){
 			alert("Formato do minuto inválido.");
 			hora.focus();
 			return false
 		}
 	}
 }

//#######################################################################################################


//funcoes que mascaram os campos de moeda colocando automaticamente os pontos e as virgulas

documentall = document.all;
/*
* função para formatação de valores monetários retirada de
* http://jonasgalvez.com/br/blog/2003-08/egocentrismo
*/

function formatamoney(c) {
    var t = this; if(c == undefined) c = 2;		
    var p, d = (t=t.split("."))[1].substr(0, c);
    for(p = (t=t[0]).length; (p-=3) >= 1;) {
	        t = t.substr(0,p) + "." + t.substr(p);
    }
    return t+","+d+Array(c+1-d.length).join(0);
}

String.prototype.formatCurrency=formatamoney

function demaskvalue(valor, currency){
/*
* Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as 
* casas decimais
*/
var val2 = '';
var strCheck = '0123456789';
var len = valor.length;
	if (len== 0){
		return 0.00;
	}

	if (currency ==true){	
		/* Elimina os zeros à esquerda 
		* a variável  <i> passa a ser a localização do primeiro caractere após os zeros e 
		* val2 contém os caracteres (descontando os zeros à esquerda)
		*/
		
		for(var i = 0; i < len; i++)
			if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;
		
		for(; i < len; i++){
			if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);
		}

		if(val2.length==0) return "0.00";
		if (val2.length==1)return "0.0" + val2;
		if (val2.length==2)return "0." + val2;
		
		var parte1 = val2.substring(0,val2.length-2);
		var parte2 = val2.substring(val2.length-2);
		var returnvalue = parte1 + "." + parte2;
		return returnvalue;
		
	}
	else{
			/* currency é false: retornamos os valores COM os zeros à esquerda, 
			* sem considerar os últimos 2 algarismos como casas decimais 
			*/
			val3 ="";
			for(var k=0; k < len; k++){
				if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);
			}			
	return val3;
	}
}

function reais(obj,event){

var whichCode = (window.Event) ? event.which : event.keyCode;
/*
Executa a formatação após o backspace nos navegadores !document.all
*/
if (whichCode == 8 && !documentall) {	
/*
Previne a ação padrão nos navegadores
*/
	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	obj.value= demaskvalue(x,true).formatCurrency();
	return false;
}
/*
Executa o Formata Reais e faz o format currency novamente após o backspace
*/
FormataReais(obj,'.',',',event);
} // end reais


function backspace(obj,event){
/*
Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.
O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.
*/

var whichCode = (window.Event) ? event.which : event.keyCode;
if (whichCode == 8 && documentall) {	
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	var y = demaskvalue(x,true).formatCurrency();

	obj.value =""; //necessário para o opera
	obj.value += y;
	
	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	return false;

	}// end if		
}// end backspace

function FormataReais(fld, milSep, decSep, 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;

//if (whichCode == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown
if (whichCode == 0 ) return true;
if (whichCode == 9 ) return true; //tecla tab
if (whichCode == 13) return true; //tecla enter
if (whichCode == 16) return true; //shift internet explorer
if (whichCode == 17) return true; //control no internet explorer
if (whichCode == 27 ) return true; //tecla esc
if (whichCode == 34 ) return true; //tecla end
if (whichCode == 35 ) return true;//tecla end
if (whichCode == 36 ) return true; //tecla home

/*
O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script
*/

if (e.preventDefault){ //standart browsers
		e.preventDefault()
	}else{ // internet explorer
		e.returnValue = false
}

var key = String.fromCharCode(whichCode);  // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false;  // Chave inválida

/*
Concatenamos ao value o keycode de key, se esse for um número
*/
fld.value += key;

var len = fld.value.length;
var bodeaux = demaskvalue(fld.value,true).formatCurrency();
fld.value=bodeaux;

/*
Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror.
*/
  if (fld.createTextRange) {
    var range = fld.createTextRange();
    range.collapse(false);
    range.select();
  }
  else if (fld.setSelectionRange) {
    fld.focus();
    var length = fld.value.length;
    fld.setSelectionRange(length, length);
  }
  return false;

}
//###################################################################################################

//funcao que verifica se os emails foram digitados corretamente
function Verifica_Email(email, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
 	//var email = document.getElementById(email);
 	if (((obrigatorio == 1) || (obrigatorio == 0 && email.value != "")) || (strpos (",",email) ) ){
 		if(!email.value.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+.[a-zA-Z0-9._-]+)/gi)){
 			alert("Informe um e-mail válido");
 			email.focus();
 			return false
 		}
 	}
 }
 
//###################################################################################################

//funcao que verifica se os ceps foram digitados corretamente
 function Verifica_Cep(cep, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
 	//var cep    = document.getElementById(cep);
 	var strcep = cep.value;
 	if((obrigatorio == 1) || (obrigatorio == 0 && strcep != "")){
 		if (strcep.length != 9){
 			alert("CEP informado inválido.");
 			cep.focus();
 			return false
 		}else{
 			if (strcep.indexOf("-") != 5){
 				alert("Formato de CEP informado inválido.");
 				cep.focus();
 				return false
 			}else{
 				if (isNaN(strcep.replace("-","0"))){
 					alert("CEP informado inválido.");
 					cep.focus();
 					return false
 				}
 			}
 		}
 	}	  
 }
 
 
//##############################################################################################################

//funcao que mascara os campos de cep colocando o '-'
function Ajusta_Cep(input, evnt){
 //Ajusta máscara de CEP e só permite digitação de números
 	if (input.value.length == 5){
 		if(browser == "IE"){
 			input.value += "-";
 		}else{
 			if(evnt.keyCode == 0){
 				input.value += "-";
 			}
 		}
 	}
 //Chama a função Bloqueia_Caracteres para só permitir a digitação de números
 	return Bloqueia_Caracteres(evnt);
 }
 
//#####################################################################################################


 function valida_cpf_cnpj(form) {
	var invalid, s;
	invalid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;

	var s;

// inicio de verificacao de cnpj ou cpf
	
	s = form.value;
	
	
	// CHECA SE EH CPF	
	if (s.length == 11) {
		if (valida_cpf(form.value) == false ){
			alert("O CPF  "+form.value+"  não é válido !\n        Tente novamente !");
		   document.form_candidato.cpf.focus();
            return false;	
            }
     }

     //CHECA SE EH CNPJ
	else if (s.length == 14) {
		if (valida_cnpj(form.value) == false ) {
			alert("O CNPJ  "+form.value+"  não é válido !\n       Tente novamente !");
			document.form_candidato.cpf.focus();
            return false;
        }
	}else{
			alert("O CPF  "+ form.value+"  não é válido !\n     Tente novamente !");
			document.form_candidato.cpf.focus();
			return false;
    }
		
     return true;
}
// FIM DA FUNCAO VALIDA_CPF_CNPJ(), FUNCAO PRINCIPAL


function limpa_string(S){
	// Deixa so' os digitos no numero
	var Digitos = "0123456789";
	var temp = "";
	var digito = "";

	for (var i=0; i<S.length; i++)	{
		digito = S.charAt(i);
		if (Digitos.indexOf(digito)>=0)	{
			temp=temp+digito	}
	} //for

	return temp
}
//FIM DA FUNCAO LIMPA_STRING()


////funcao que valida só o CPF
function valida_cpf(s)	{
	var i;
	s = limpa_string(s);
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	for (i = 0; i < 9; i++)
	{
		d1 += c.charAt(i)*(10-i);
	}
        if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1)
	{
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 9; i++)
	{
		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1)
	{
		return false;
	}
        return true;
}
////fim funcao valida_CPF

///funcao que valida só o CNPJ
function valida_cnpj(s)
{
	var i;
	s = limpa_string(s);
	var c = s.substr(0,12);
	var dv = s.substr(12,2);
	var d1 = 0;
	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+(i % 8));
	}
        if (d1 == 0) return false;
        d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1)
	{
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1)
	{
		return false;
	}
	return true;
}
////FIM DO BLOCO DE FUNCOES PARA VALIDACAO DO CPF/CNPJ////

//##############################################################################################################

//funcao que mascara os campos de cep colocando o '-'
function validaEdital(input, evnt){
 
 	if(input.value != ''){
			inicio = input.value.indexOf('/');
			fim = input.value.length - 1;
			str = input.value.substr(inicio , fim) ;
			
			if(str.length != 5 || inicio == -1){
				alert("Digite um Número de Edital na Forma n°edital/Ano");
				//input.focus();
			}
	}else{
		alert("Digite um Número de Edital/Ano");
		//input.focus();
	}
	
 	
 	
 	
 }
 
//#####################################################################################################

function Ajusta_Hora(input, evnt){
 //Ajusta máscara de Hora e só permite digitação de números
 	if (input.value.length == 2){
 		if(browser == "IE"){
 			input.value += ":";
 		}else{
 			if(evnt.keyCode == 0){
 				input.value += ":";
 			}
 		}
 	}
 //Chama a função Bloqueia_Caracteres para só permitir a digitação de números
 	return Bloqueia_Caracteres(evnt);
 }

