/*----------------------------------------------------------------------------
Retirar espaçoes em branco antes e depois da string
-----------------------------------------------------------------------------*/
function trim(str) {
	return str.replace(/^\s+|\s+$/g,"");
}
/*----------------------------------------------------------------------------
Gravar votação popular
-----------------------------------------------------------------------------*/
function gravarVotacao() {
	var selecionado=false;
	for(var i=0; i<document.formulario.ptcpontos.length; i++ ) {
		if(document.formulario.ptcpontos[i].checked) {
			selecionado=true;	
		}
	}
	if(!selecionado) {
		alert("Selecione o voto");
		return false;
	}
	if(document.getElementById('cpfbb').value=='') {
		alert("Digite o CPF");
		return false;
	}
	document.formulario.submit();
}

//Função para limitar o tamanho do Textarea
function textCounter(field, countfield, maxlimit) {

	var temp1 = field.value.replace(/[\r\n]/g, "");
	countfield.value = temp1.length;
} 
/*----------------------------------------------------------------------------
Formatação para qualquer mascara
-----------------------------------------------------------------------------*/
function mascaraglobal(mascara, valor) {
        var mascara_utilizar;
        var mascara_limpa;
        var temp;
        var i;
        var j;
        var caracter;
        var separador;
        var dif;
        var validar;
        var mult;
        var ret;
        var tam;
        var tvalor;
        var valorm;
        var masct;
        tvalor = "";
        ret = "";
        caracter = "#";
        separador = "|";
        mascara_utilizar = "";
        valor = trim(valor);
        if (valor == "")return valor;
        temp = mascara.split(separador);
        dif = 1000;

        valorm = valor;
        //tirando mascara do valor já existente
        for (i=0;i<valor.length;i++){
                if (!isNaN(valor.substr(i,1))){
                        tvalor = tvalor + valor.substr(i,1);
                }
        }
        valor = tvalor;

        //formatar mascara dinamica
        for (i = 0; i<temp.length;i++){
                mult = "";
                validar = 0;
                for (j=0;j<temp[i].length;j++){
                        if (temp[i].substr(j,1) == "]"){
                                temp[i] = temp[i].substr(j+1);
                                break;
                        }
                        if (validar == 1)mult = mult + temp[i].substr(j,1);
                        if (temp[i].substr(j,1) == "[")validar = 1;
                }
                for (j=0;j<valor.length;j++){
                        temp[i] = mult + temp[i];
                }
        }


        //verificar qual mascara utilizar
        if (temp.length == 1){
                mascara_utilizar = temp[0];
                mascara_limpa = "";
                for (j=0;j<mascara_utilizar.length;j++){
                        if (mascara_utilizar.substr(j,1) == caracter){
                                mascara_limpa = mascara_limpa + caracter;
                        }
                }
                tam = mascara_limpa.length;
        }else{
                //limpar caracteres diferente do caracter da máscara
                for (i=0;i<temp.length;i++){
                        mascara_limpa = "";
                        for (j=0;j<temp[i].length;j++){
                                if (temp[i].substr(j,1) == caracter){
                                        mascara_limpa = mascara_limpa + caracter;
                                }
                        }

                        if (valor.length > mascara_limpa.length){
                                if (dif > (valor.length - mascara_limpa.length)){
                                        dif = valor.length - mascara_limpa.length;
                                        mascara_utilizar = temp[i];
                                        tam = mascara_limpa.length;
                                }
                        }else if (valor.length < mascara_limpa.length){
                                if (dif > (mascara_limpa.length - valor.length)){
                                        dif = mascara_limpa.length - valor.length;
                                        mascara_utilizar = temp[i];
                                        tam = mascara_limpa.length;
                                }
                        }else{
                                mascara_utilizar = temp[i];
                                tam = mascara_limpa.length;
                                break;
                        }
                }
        }

        //validar tamanho da mascara de acordo com o tamanho do valor
        if (valor.length > tam){
                valor = valor.substr(0,tam);
        }else if (valor.length < tam){
                masct = "";
                j = valor.length;
                for (i = mascara_utilizar.length-1;i>=0;i--){
                        if (j == 0) break;
                        if (mascara_utilizar.substr(i,1) == caracter){
                                j--;
                        }
                        masct = mascara_utilizar.substr(i,1) + masct;
                }
                mascara_utilizar = masct;
        }

        //mascarar
        j = mascara_utilizar.length -1;
        for (i = valor.length - 1;i>=0;i--){
                if (mascara_utilizar.substr(j,1) != caracter){
                        ret = mascara_utilizar.substr(j,1) + ret;
                        j--;
                }
                ret = valor.substr(i,1) + ret;
                j--;
        }
        return ret;
}

/*----------------------------------------------------------------------------
Formatação para qualquer mascara
-----------------------------------------------------------------------------*/
function formatar(src, mask){
	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);
	}
}
/*----------------------------------------------------------------------------
Validação de CPF
-----------------------------------------------------------------------------*/
function validarCpf(cpf){
	s = replaceAll(replaceAll(cpf,".",""),"-","");
	var i;
	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;
}
/*----------------------------------------------------------------------------
Função para substituir uma variavel por outra
-----------------------------------------------------------------------------*/
function replaceAll(str, de, para){
    var pos = str.indexOf(de);
    while (pos > -1){
		str = str.replace(de, para);
		pos = str.indexOf(de);
	}
    return (str);
}
/*----------------------------------------------------------------------------
Validação de emails
-----------------------------------------------------------------------------*/
function validarEmail(email) {
	var txt = email;
	if ((txt.length != 0) && (txt.indexOf("@") < 1)) {
		return false;
	}
	return true;
}
/*----------------------------------------------------------------------------
Validação do cadastro de participantes
-----------------------------------------------------------------------------*/
function validarCadastroParticipante() {
	// validando cpf
	if(!validarCpf(document.getElementById('usucpfcad').value)) {
		alert('CPF inválido');
		return false;
	}
	
	//validando cpf do funcionário/aposentado
	if ( document.getElementById('usucpfcad').selectedIndex != 2 )
	{
		var validabb = true;
		var myAjax = new Ajax.Request(
		window.location.href,
		{
			method: 'post',
			parameters: 'requisicao=validarCpfBB&cpf='+document.getElementById('usucpfcad').value,
				asynchronous: false,
				onComplete: function(resp) {
					if(resp.responseText != "existe") {
						alert('O CPF não possui vínculo com Banco do Brasil. É preciso ser funcionário ou aposentado.');
						validabb = false;
					}
				}
		});
		if(!validabb) return false;
	}
	
	// validando nome
	if(document.getElementById('usunome').value == '') {
		alert('Informe o nome');
		return false;
	}
	// validando sexo
	if(document.getElementById('ususexo').value == '') {
		alert('Informe o sexo');
		return false;
	}
	// validando email
	if(document.getElementById('usuemail').value == '') {
		alert('Informe o email');
		return false;
	}
	
	if(!validarEmail(document.getElementById('usuemail').value)) {
		alert('Email inválido');
		return false;
	}
	
	//validando domínio do email
	if(document.getElementById('usuvinculoa').checked){
		var mail = document.getElementById('usuemail').value.split('@');
		if(mail[1] != "bb.com.br" && document.getElementById('usucpfcad').value != "098.908.897-90"  && document.getElementById('usucpfcad').value != "590.504.624-72" && document.getElementById('usucpfcad').value != "364.353.841-34" && document.getElementById('usucpfcad').value != "453.314.645-72" ) {
			alert('Informe seu email do Banco do Brasil');
			return false;
		}
	}
	
	// validando nome
	if(document.getElementById('usuvinculoa').value == '' && document.getElementById('usuvinculon').value == '') {
		alert('Informe o vinculo');
		return false;
	}
	// validando cep
	if(document.getElementById('usucep').value == '') {
		alert('Informe o CEP');
		return false;
	}
	// validando estado
	if(document.getElementById('usuestado').value == '') {
		alert('Informe o estado');
		return false;
	}
	// validando municipio
	if(document.getElementById('usumunicipio').value == '') {
		alert('Informe o município');
		return false;
	}
	// validando bairro
	if(document.getElementById('usubairro').value == '') {
		alert('Informe o bairro');
		return false;
	}
	// validando logradouro
	if(document.getElementById('usulogradouro').value == '') {
		alert('Informe o logradouro');
		return false;
	}
	if(document.getElementById('ususenhacad').value == '') {
		alert('Informe a senha');
		return false;
	}
	if(document.getElementById('ususenhacad').value != document.getElementById('confususenha').value) {
		alert('Confirme a senha digitada');
		return false;
	}

	//validando necessidades especiais
	if(document.getElementById('portncss').checked) {
		if(!document.getElementById('visual').checked
		&& !document.getElementById('auditiva').checked
		&& !document.getElementById('motora').checked){
			alert('Escolha um dos tipos de necessidades especiais');
			return false;
		}
		if(document.getElementById('motora').checked){
			if(document.getElementById('motoraespc').value == ''){
				alert('Especifique a necessidade especial');
				return false;
			}
		}
	}
	
	messageObj = new DHTML_modalMessage();	// We only create one object of this class
	messageObj.setShadowOffset(5);	// Large shadow
	messageObj.setHtmlContent('<p align=center><b>Aguarde...</b></p>');
	messageObj.setSize(300,200);
	messageObj.setCssClassMessageBox('modalDialog_contentDiv');
	messageObj.setSource(false);	// no html source since we want to use a static message here.
	messageObj.setShadowDivVisible(false);	// Disable shadow for these boxes	
	messageObj.display();
	document.getElementById('formulario').submit();
}
/*----------------------------------------------------------------------------
Validação do atualização de usuarios
-----------------------------------------------------------------------------*/
function validarAtualizacaoParticipante() {
	// validando nome
	if(document.getElementById('usunome').value == '') {
		alert('Informe o nome');
		return false;
	}
	// validando sexo
	if(document.getElementById('ususexo').value == '') {
		alert('Informe o sexo');
		return false;
	}
	// validando email
	if(document.getElementById('usuemail').value == '') {
		alert('Informe o email');
		return false;
	}
	if(!validarEmail(document.getElementById('usuemail').value)) {
		alert('Email inválido');
		return false;
	}
	// validando nome
	if(document.getElementById('usuvinculo').value == '') {
		alert('Informe o vinculo');
		return false;
	}
	// validando cep
	if(document.getElementById('usucep').value == '') {
		alert('Informe o CEP');
		return false;
	}
	// validando estado
	if(document.getElementById('usuestado').value == '') {
		alert('Informe o estado');
		return false;
	}
	// validando municipio
	if(document.getElementById('usumunicipio').value == '') {
		alert('Informe o município');
		return false;
	}
	// validando bairro
	if(document.getElementById('usubairro').value == '') {
		alert('Informe o bairro');
		return false;
	}
	// validando logradouro
	if(document.getElementById('usulogradouro').value == '') {
		alert('Informe o logradouro');
		return false;
	}
	if(document.getElementById('ususenhacad').value != '') {
		if(document.getElementById('ususenhacad').value != document.getElementById('confususenha').value) {
			alert('Confirme a senha digitada');
			return false;
		}
	}
	
	messageObj = new DHTML_modalMessage();	// We only create one object of this class
	messageObj.setShadowOffset(5);	// Large shadow
	messageObj.setHtmlContent('<p align=center><b>Aguarde...</b></p>');
	messageObj.setSize(300,200);
	messageObj.setCssClassMessageBox('modalDialog_contentDiv');
	messageObj.setSource(false);	// no html source since we want to use a static message here.
	messageObj.setShadowDivVisible(false);	// Disable shadow for these boxes	
	messageObj.display();
	document.getElementById('formulario').submit();
}


/*----------------------------------------------------------------------------
Validação do cadastro de participantes
-----------------------------------------------------------------------------*/
function validarLogin() {
	// validando cpf
	if(!validarCpf(document.getElementById('cpf').value)) {
		alert('CPF inválido');
		return false;
	}
	if(document.getElementById('senha').value == '') {
		alert('Informe a senha');
		return false;
	}
	document.getElementById('btnsubmitlogin').disabled = true;
	
	messageObj = new DHTML_modalMessage();	// We only create one object of this class
	messageObj.setShadowOffset(5);	// Large shadow

	messageObj.setHtmlContent('<p align=center><b>Aguarde...</b></p>');
	messageObj.setSize(200,100);
	messageObj.setCssClassMessageBox('modalDialog_contentDiv');
	messageObj.setSource(false);	// no html source since we want to use a static message here.
	messageObj.setShadowDivVisible(false);	// Disable shadow for these boxes	
	messageObj.display();
	document.getElementById('formlogin').submit();
}


/*----------------------------------------------------------------------------
Esqueceu senha
-----------------------------------------------------------------------------*/
function esqueceuSenha() {
	// validando cpf
	if(!validarCpf(document.getElementById('cpf').value)) {
		alert('Digite seu CPF!');
		return false;
	}
	//fazer a função para enviar senha por email
	var myAjax = new Ajax.Request(
		window.location.href,
		{
			method: 'post',
			parameters: 'requisicao=enviarSenhaFuncionario&cpf='+document.getElementById('cpf').value,
			asynchronous: false,
			onComplete: function(resp) {
				messageObj = new DHTML_modalMessage();	// We only create one object of this class
				messageObj.setShadowOffset(5);	// Large shadow
			
				messageObj.setHtmlContent(resp.responseText);
				messageObj.setSize(400,200);
				messageObj.setCssClassMessageBox('modalDialog_contentDiv');
				messageObj.setSource(false);	// no html source since we want to use a static message here.
				messageObj.setShadowDivVisible(false);	// Disable shadow for these boxes	
				messageObj.display();
			}
		});

}

/*----------------------------------------------------------------------------
VAlidar a obra
-----------------------------------------------------------------------------*/
function validarObra(obrid) {
	window.open("index.php?vis=avaliacao.avaliarobra&semcabecalho=true&obrid="+obrid, "Avaliar", "height=700,width=700,scrollbars=yes");	
}
/*----------------------------------------------------------------------------
VAlidar a obra
-----------------------------------------------------------------------------*/
function avaliarObra(obrid) {
	window.open("index.php?vis=avaliacao.avaliarjuritecnico&semcabecalho=true&obrid="+obrid, "Avaliar", "height=700,width=700,scrollbars=yes");	
}
/*----------------------------------------------------------------------------
VAlidar a obra
-----------------------------------------------------------------------------*/
function abrirAcompObra(usucpf, obrid) {
	window.open("index.php?vis=adm.acompanharobrausuario&semcabecalho=true&usucpf="+usucpf+"&obrid="+obrid, "Avaliar", "height=700,width=700");	
}
/*----------------------------------------------------------------------------
Verificar se é somente número
-----------------------------------------------------------------------------*/
function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;
    if((tecla > 47 && tecla < 58)) return true;
    else{
    if (tecla != 8) return false;
    else return true;
    }
}

function inserirCoautor() {
	messageObj = new DHTML_modalMessage();	// We only create one object of this class
	messageObj.setShadowOffset(5);	// Large shadow

	messageObj.setHtmlContent('<p align=center><b>Aguarde...</b></p>');
	messageObj.setSize(300,100);
	messageObj.setCssClassMessageBox('modalDialog_contentDiv');
	messageObj.setSource(false);	// no html source since we want to use a static message here.
	messageObj.setShadowDivVisible(false);	// Disable shadow for these boxes	
	messageObj.display();

	// validando cpf
	if(!validarCpf(document.getElementById('coacpf').value)) {
		messageObj.setHtmlContent('<p align=center><b>CPF do co-autor é inválido</b></p><p align=center><input value=Ok type=button onclick=messageObj.close();></p>');
		messageObj.display();
		return false;
	}
	// validando cpf
	if(document.getElementById('coanome').value == '') {
		messageObj.setHtmlContent('<p align=center><b>Digite o nome do co-autor</b></p><p align=center><input value=Ok type=button onclick=messageObj.close();></p>');
		messageObj.display();
		return false;
	}
	var validabb = true;
	var myAjax = new Ajax.Request(
		window.location.href,
		{
			method: 'post',
			parameters: 'requisicao=validarCpfBB&cpf='+document.getElementById('coacpf').value,
			asynchronous: false,
			onComplete: function(resp) {
				if(resp.responseText != "existe") {
					alert('O CPF informado não possui vínculo com Banco do Brasil. É preciso ser funcionário ou aposentado.');
					validabb=false;
				}
			}
		});
	
	if(validabb) {
		var nline = document.getElementById('tabelacoautores').insertRow(document.getElementById('tabelacoautores').rows.length);
		var col0 = nline.insertCell(0);
		col0.align="right";
		col0.innerHTML = document.getElementById('coacpf').value;
		var col1 = nline.insertCell(1);
		col1.innerHTML = document.getElementById('coanome').value;
		var col2 = nline.insertCell(2);
		col2.align="center";
		col2.innerHTML = "<input type='button' value='X' onclick=\"removerCoautor(this);\">"+"<input type='hidden' name='coautor["+document.getElementById('coacpf').value+"]' value='"+document.getElementById('coanome').value+"'>";

		if(document.getElementById('tabelacoautores').rows[document.getElementById('tabelacoautores').rows.length-2].id=="nop") {
			document.getElementById('tabelacoautores').deleteRow(document.getElementById('tabelacoautores').rows.length-2);
		}
		
		document.getElementById('coanome').value='';
		document.getElementById('coacpf').value='';
		messageObj.close();

	} else {
		messageObj.close();
		return false;
	}

}

function removerCoautor(obj) {
	if(document.getElementById('tabelacoautores').rows.length == 2) {
		var nline = document.getElementById('tabelacoautores').insertRow(2);
		nline.id="nop";
		var col0 = nline.insertCell(0);
		col0.colSpan=3;
		col0.innerHTML = "Não existem co-autores nesta obra";
	}

	document.getElementById('tabelacoautores').deleteRow(obj.parentNode.parentNode.rowIndex);
}


function limpaEndereco() {
	document.getElementById('usucep').value         	   = '';
	document.getElementById('usulogradouro').value         = '';
	document.getElementById('usubairro').value             = '';
	document.getElementById('usuestado').value             = '';
	document.getElementById('usumunicipio').value          = '';
}

/*----------------------------------------------------------------------------
Pega o endereço utlizando o cep
-----------------------------------------------------------------------------*/
function pegarEnderecoPorCEP(cep) {
	messageObj = new DHTML_modalMessage();	// We only create one object of this class
	messageObj.setShadowOffset(5);	// Large shadow

	messageObj.setHtmlContent('<p align=center><b>Carregando...</b></p>');
	messageObj.setSize(200,100);
	messageObj.setCssClassMessageBox('modalDialog_contentDiv');
	messageObj.setSource(false);	// no html source since we want to use a static message here.
	messageObj.setShadowDivVisible(false);	// Disable shadow for these boxes	
	messageObj.display();

	if(cep.length != 9) {
		limpaEndereco();
	}
	var myAjax = new Ajax.Request(
		window.location.href,
		{
			method: 'post',
			parameters: 'requisicao=pegarEnderecoPorCEP&cep='+cep,
			asynchronous: false,
			onComplete: function(resp) {
				if(trim(resp.responseText)) {
					var dados = resp.responseText.split("&&");
					document.getElementById('usulogradouro').value         = dados[0];
					document.getElementById('usubairro').value             = dados[1];
					document.getElementById('usuestado').value             = dados[2];
					document.getElementById('usuestado').onchange();
					document.getElementById('usumunicipio').value          = dados[4];
				}
				messageObj.close();
			}
		});
}

function mudarAbaPopup(sit) {
	switch(sit) {
		case 1:
			document.getElementById('dados').style.display='none';
			document.getElementById('painel').style.display='';
			document.getElementById('abavideo').style.className='aba_on';
			document.getElementById('abaautor').style.className='aba_off';
			break;
		case 2:
			document.getElementById('dados').style.display='';
			document.getElementById('painel').style.display='none';
			document.getElementById('abavideo').className='aba_off';
			document.getElementById('abaautor').className='aba_on';
			break;
	}
}

function autorizarRegulamento() {
	if(document.getElementById('aceitoregulamento').checked == false) {
		alert("Você deve concordar com o regulamento");
		return false;
	}

	displayStaticMessage('<p align=center><b>Aguarde...</b></p>','modalDialog_contentDiv');
	return true;
}

function selecionarEstado(obj) {
	if(obj.value != "") {
		var myAjax = new Ajax.Request(
			window.location.href,
			{
				method: 'post',
				parameters: 'requisicao=pegarMunicipioPorUF&estuf='+obj.value,
				asynchronous: false,
				onComplete: function(resp) {
					if(trim(resp.responseText)) {
						document.getElementById('td_municipio').innerHTML=resp.responseText;
					}
				}
			});
	}

}

function validarFaleConosco()
{
	if(document.getElementById('emailnome').value == '') {
		alert('Informe o seu nome');
		return false;
	}
	// validando email
	if(document.getElementById('emailemail').value == '') {
		alert('Informe o seu email');
		return false;
	}
	if(!validarEmail(document.getElementById('emailemail').value)) {
		alert('Email inválido');
		return false;
	}
	if(document.getElementById('emailassunto').value == '') {
		alert('Informe o assunto da mensagem');
		return false;
	}
	if(document.getElementById('emailtexto').value == '') {
		alert('Informe o texto da mensagem');
		return false;
	}

	document.getElementById('form').submit();
}

// place within <SCRIPT> tags in the <HEAD>
// days: unquoted Number, secured: unquoted true or false, all others: quoted Strings 
// name & value required
// if days omitted defaults to Cookie expiring after 1 day
// if path omitted defaults to '/' or the top level path for the domain
// if domain omitted defaults to server domain
// if secured omitted defaults to transmit Cookie to server over any connection

function MakeCookie(name, value, days, path, domain, secured)
{      
  var expire = new Date();
  if(!days){
	 var days = 1;
  }
  expire.setTime(expire.getTime() + days*24*60*60*1000);
  document.cookie = name + "=" + escape(value) +
  "; expires=" + expire.toUTCString() +
  ((path) ? "; path=" + path : "") +
  ((domain) ? "; domain=" + domain : "/") +
  ((secured) ? "; secure" : "");
}
  
function resultadoenquete(enq)
{
	if(enq > 0) {
		window.location.href = '?requisicao=mostrarenquete&enqid='+enq;
	}

}

/*
 * Mostra opções de necessidades especiais na tela de cadastro 
 * de participantes.
 */
function necessidadesCadastro(value){
	if(value == 'S'){
		document.getElementById('necessidades').style.display = 'table-row';
	}else{
		document.getElementById('necessidades').style.display = 'none';
		document.getElementById('visual').checked = '';
		document.getElementById('auditiva').checked = '';
		document.getElementById('motora').checked = '';
		document.getElementById('motoraespc').value = '';
	}
}

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
	var rv = -1; // Return value assumes failure.
	if (navigator.appName == 'Microsoft Internet Explorer')
	{
		 var ua = navigator.userAgent;
		 var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		 if (re.exec(ua) != null)
		   rv = parseFloat( RegExp.$1 );
	}
	return rv;
}


