// JavaScript Document
// Limpa o texto do campo quando este recebe o foco
function limpaTextoCampo(campo) {
	if (campo.value==campo.defaultValue) {
		campo.value = "";
	}
}

// Restaura o texto original caso não tenha sido digitado nada
function restauraTextoCampo(campo) {
	if (campo.value=="") {
		campo.value = campo.defaultValue;
	}
}

function limpaPassword( campo ){
 	txt_campo = campo.value
 	if( txt_campo == "Senha" ){
  		campo.value = "";
  		return;
 	}
 
 	if( txt_campo == "" ){
   		campo.value = "Senha";
 	}
}

function limpaLogin( campo ){
 	txt_campo = campo.value
 	if( txt_campo == "Login" ){
  		campo.value = "";
  		return;
 	}
 
 	if( txt_campo == "" ){
   		campo.value = "Login";
 	}
}

function valida_email(emailParam){
	
	var email = document.getElementById(emailParam);
	if (email.value.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) == -1) {
		alert("O e-mail deve ser um endereço de e-mail válido.");
		email.value = '';
		email.focus();
		return false;
	}
	return true;
}

//Exibe ou esconde pelo Id
function mostraDados( pri ) {
  var element = document.getElementById(pri);

  if (element.style.display == 'none') {
    element.style.display = '';
  }
  else {
    element.style.display = 'none'
  }
}


function validaBranco( campo, nome ){
	campo = document.getElementById( campo );

	if(  campo.value  == "" ) {
		if( nome != null )
			alert( "O campo " + nome.toUpperCase() + " dever ser preenchido." );
		else
			alert( "O campo " + campo.name.toUpperCase() + " deve ser preenchido." );
		
		campo.focus();
		return false;
	}
	return true;
}



function validaBranco2( campoParam ){
	var campo = document.getElementById(campoParam);
	
	if( campo.value == "" ){
		return false;
	}
	return true;
}

//Limita a quantidade de caracteres no text area

function ismaxlength(obj){  
 var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""  ;
 	if (obj.getAttribute && obj.value.length>mlength)  {
        obj.value=obj.value.substring(0,mlength) ;
 } 
}

// Valida um URL
function validaURL( campo, mensagem ){
	campo = document.getElementById( campo );

	if( campo.value.substr(0, 7) != "http://" || campo.value.length <= 12 ){
		alert( "O campo " + mensagem.toUpperCase() + " não contém uma URL válida." );
		campo.focus();
		return false;
	}
	return true;
}

function CarregaCidadesLista(idEstado, idCidade){
	var q = "http://www.sbotologia.com.br/ajax_CidadesEstados.asp?q=" + document.getElementById(idEstado).options[document.getElementById(idEstado).selectedIndex].value;
	var objDest = "Local" + idCidade;
	var a = new AjaxClass(q, objDest);
	document.getElementById(objDest).innerHTML = "Carregando cidades para o estado, por favor aguarde...";
	document.getElementById(idCidade).disabled = true;
	a.objAjax.onreadystatechange = function(){	
		if (a.objAjax.readyState==4) {
			if (a.objAjax.status==200) {
				document.getElementById(objDest).innerHTML = "*";
				document.getElementById(idCidade).options.length = 0;
				incluiItemLista("Selecione uma cidade","",idCidade);
				for(i=0;i<a.objAjax.responseXML.childNodes[0].childNodes.length;i++){
					t = a.objAjax.responseXML.childNodes[0].childNodes[i].childNodes[0].nodeValue;
					incluiItemLista(t,t,idCidade);
				}
				document.getElementById(idCidade).disabled = false;
			} else {
				document.getElementById(objDest).innerHTML = "Erro ao checar os dados.";
			}
		}
	}
	a.ajaxManual();
}

function incluiItemLista(novoText, novoValue, local){
	var newOpt = document.createElement('option');
	newOpt.text = novoText;
	newOpt.value = novoValue;
	var LocalItemDest = local;
	if(window.navigator.appName == "Microsoft Internet Explorer") {
		document.getElementById(LocalItemDest).add(newOpt); // IE only
	} else {
		document.getElementById(LocalItemDest).options[document.getElementById(LocalItemDest).length] = new Option(novoText, novoValue);
	}
}


function addSWF(URL, WIDTH, HEIGHT, TRANSPARENT) {
	document.write (' <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ');
	document.write (' codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" ');
	document.write (' width="'+ WIDTH +'" height="'+ HEIGHT +'" id="'+URL+'" align="middle">');
	document.write (' <param name="allowScriptAccess" value="sameDomain" />');
	document.write (' <param name="movie" value="'+ URL +'.swf" />');
	document.write (' <param name="quality" value="high" />');
	document.write (' <param name="menu" value="false" />');
	document.write (' <param name="bgcolor" value="#ffffff" />');
	
	if ( TRANSPARENT ) {
	  document.write (' <param name="Wmode" value="Transparent" />');
	} 
	
	document.write (' <embed src="'+ URL +'.swf" quality="high" name="'+URL+'" allowScriptAccess="sameDomain" bgcolor="#ffffff" align="middle" ');
	
	if ( TRANSPARENT ) {
	document.write (' Wmode = "transparent" ');
	}
	
	document.write (' pluginspage="http://www.macromedia.com/go/getflashplayer" ');
	document.write (' type="application/x-shockwave-flash" width="'+ WIDTH +'" height="'+ HEIGHT +'"></embed> ');
	document.write (' </object>');
}

function Banner(){
	document.location.href = "http://www.aborlccf.org.br/39cbo";
	//MM_openBrWindow("http://www.aborlccf.org.br/39cbo","39CBO","width=800,height=600,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes");
}

function otoweb(){
	document.location.href = "otoweb-red.asp";//otoweb.asp
}

function abreOtorrino(local){
	if(document.getElementById(local).style.display == "none") document.getElementById(local).style.display = "block";
	else document.getElementById(local).style.display = "none"
}

function janela(local){
	//alert(local);
	window.open("../Includes/bannerBudecort/" + local,"Budecort","scrollbars=yes,resizable=yes,width=850,height=550");
}

function Separata(){
	window.open("separata.asp","separata","scrollbars=yes,resizable=yes,width=850,height=550");
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function selecionaLogin(local){
	if(local.value == "CPF")
		local.value = "";
}

function tiraSelecaoLogin(local){
	if(!local.value)
		local.value = "CPF";
}

function selecionaSenha(){
	getElement("senha").style.display = "inline";
	getElement("senhaVisual").style.display = "none";
	getElement("senha").focus();
}

function tiraSelecaoSenha(){
	if(!getElement("senha").value){
		getElement("senha").style.display = "none";
		getElement("senhaVisual").style.display = "inline";
	}
}

function init(){	
	var w = window.screen.width;
	if(w < 820) {
		getElement("Pagina").style.left = "0px";
		getElement("Pagina").style.marginLeft = "0px";
	}
}

function getElement(id){
	return document.getElementById(id);
}

function TopoLinks(local) {
	var destino = "default.asp";
	switch (local) {
		case 1:
			destino = "noticias.asp?s=49";
			break;
		case 2:
			destino = "eventos.asp";
			break;
		case 3:
			destino = "secao.asp?s=17";
			break;
		case 4:
			destino = "noticias.asp?s=51";
			break;
		case 5:
			destino = "secao.asp?s=9";
			break;
		case 6:
			destino = "../sga/";
			//destino = "anuidade2007.asp";
			break;		
	}
	document.location.href = destino;
}


function resultado(codEnq){
	var a = new AjaxClass("ajax_Enquete.asp","ConteudoEnquete", "post", "codEnquete=" + codEnq);
	a.ajax();
	getElement("ConteudoEnquete").innerHTML = "O resultado será exibido, aguarde...";
	getElement("btn_Votar").style.display = "none";
	getElement("btn_Resultados").style.display = "none";
}

function votar(total, codEnq){
	//validar voto
	var validaVoto = -1;
	for(i=0;i<total;i++){
		if(getElement("OptEnq" + i).checked) validaVoto = getElement("OptEnq" + i).value;
	}
	if(validaVoto >= 0){
		var a = new AjaxClass("ajax_Enquete.asp","ConteudoEnquete", "post", "codEnquete=" + codEnq + "&codVoto=" + validaVoto);
		a.ajax();
		getElement("ConteudoEnquete").innerHTML = "Seu voto está sendo contabilizado, por favor aguarde o resultado...";
		getElement("btn_Votar").style.display = "none";
		getElement("btn_Resultados").style.display = "none";
	} else {
		alert("Selecione uma das opções antes de votar.");
	}
}

function checkInput(){
	var idObj = this.id;
	if(document.getElementById(idObj).value){
		document.getElementById(idObj).style.backgroundColor = "#FFFFFF";
	} else document.getElementById(idObj).style.backgroundColor = "#FFFFFF";
}

function checkSelect(){
	var idObj = this.id;
	if(document.getElementById(idObj).selectedIndex != 0){
		document.getElementById(idObj).style.backgroundColor = "#FFFFFF";
	} else document.getElementById(idObj).style.backgroundColor = "#FFFFFF";
}

function faleConosco(){
	var erro = "";	
	if(!getElement("Nome").value) {
		erro += "<br /> - O Nome Completo deverá ser informado.";
		getElement("Nome").style.backgroundColor = "#F2FBF8";
		getElement("Nome").onchange = checkInput;
	}
		if(!getElement("Telefone").value) {
		erro += "<br /> - O n.° de telefone deverá ser informado.";
		getElement("Telefone").style.backgroundColor = "#F2FBF8";
		getElement("Telefone").onchange = checkInput;
	}	
	if(!getElement("Email").value) {
		erro += "<br /> - O email deverá ser informado.";
		getElement("Email").style.backgroundColor = "#F2FBF8";
		getElement("Email").onchange = checkInput;
	}
	if(!getElement("Cidade").value) {
		erro += "<br /> - A cidade deverá ser informada.";
		getElement("Cidade").style.backgroundColor = "#F2FBF8";
		getElement("Cidade").onchange = checkInput;
	}
	if(getElement("UF").selectedIndex == 0) { 
		erro += "<br /> - O estado deverá ser selecionado.";
		getElement("UF").style.backgroundColor = "#F2FBF8";
		getElement("UF").onchange = checkSelect;
	}
	if(!getElement("Mensagem").value) {
		erro += "<br /> - A mensagem deverá ser informada.";
		getElement("Mensagem").style.backgroundColor = "#F2FBF8";
		getElement("Mensagem").onchange = checkInput;
	}
	if(erro) {
		document.location.href = "#MsgErro";
		getElement("MsgErro").style.display = "block";
		getElement("MsgErro").innerHTML = "Não foi possível avançar devido as pendências abaixo:<br />" + erro;
		alert("Não foi possível prosseguir preencha os campos obrigatórios.");
		return false;
	} else {
		return true;
	}
}


//Limita a quantidade de caracteres no text area

function ismaxlength(obj){  
 var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""  ;
 	if (obj.getAttribute && obj.value.length>mlength)  {
        obj.value=obj.value.substring(0,mlength) ;
 } 
}

function valida_email(campoform)
{
	var MensIdioma = "O e-mail deve ser um endereço de e-mail válido.";
	var email = campoform.value;
    if (email) {
		p=email.indexOf('@');
		pont=email.indexOf('.');
		if (p<1 || p==(email.length-1) || pont<1 || pont==(email.length-1))
		{
			alert (MensIdioma);
			campoform.value = '';
			campoform.focus();
			return false;
		} else return true;
	} else {
		alert (MensIdioma);
		campoform.value = '';
		campoform.focus();
		return false;
	}
}

function valida_tel(campo) {
   var valor='';
   var digito = false;
   a = campo.value;
   if (a) {
   num = a.length;
   for (f=0;f<num;f++)
     {
     if (parseInt(a.substr(f,1)) || a.substr(f,1)=='0') 
        if ((a.substr(f,1) != '0') || digito) valor = valor + '' + a.substr(f,1);
        if (parseInt(a.substr(f,1)) && a.substr(f,1) != '0') digito = true;
     };
   num = valor.length;
   if (num < 9 || num > 10)
      {
      alert ('- Número de telefone inválido. \nEntre com o DDD e o número do telefone.\nExemplo: (11) 1234-5678');
      campo.value = '';
      campo.focus();
      }
	  else
	  {
	  if (num == 9) valor = '(' + valor.substr(0, 2) + ') ' + valor.substr(num-7, 3) + '-' + valor.substr(num-4, 4);
	  if (num == 10) valor = '(' + valor.substr(0, 2) + ') ' + valor.substr(num-8, 4) + '-' + valor.substr(num-4, 4);
	  campo.value = valor;
	  }
   }
}

function valida_cep(campo) {
   var valor='';
   a = campo.value;
   if (a) {
   num = a.length;
   for (f=0;f<num;f++)
     {
     if (parseInt(a.substr(f,1)) || a.substr(f,1)=='0') 
        valor = valor + '' + a.substr(f,1);
     };
   num = valor.length;
   if (num != 5 && num != 8)
	  {
      alert ('- CEP inválido. \nEntre com o CEP correto.\nExemplo: 12345678');
      campo.value = '';
      campo.focus();
	  }
      else
	  {	
      /*if (num == 5) valor = valor.substr(0, 2) + '.' + valor.substr(num-3, 3) + '-000';
      if (num == 8) valor = valor.substr(0, 2) + '.' + valor.substr(num-6, 3) + '-' + valor.substr(num-3, 3);
      campo.value = valor;*/
	  }
   }
}

function valida_cpf(campoform) {
	num_cpf = '';
	campo = campoform.value;
	if (campo == "00000000000" || campo == "11111111111" || campo == "22222222222" || campo == "33333333333" || campo == "44444444444" || campo == "55555555555" || campo == "66666666666" || campo == "77777777777"  || campo == "88888888888"  || campo == "99999999999"){
		alert ('- CPF inválido. \nEntre com o CPF correto.');
    	campoform.value = '';
    	campoform.focus();
		return false;
	}
	if (campo == "000.000.000-00" || campo == "111.111.111-11" || campo == "222.222.222-22" || campo == "333.333.333-33" || campo == "444.444.444-44" || campo == "555.555.555-55" || campo == "666.666.666-66" || campo == "777.777.777-77"  || campo == "888.888.888-88"  || campo == "999.999.999-99"){
		alert ('- CPF inválido. \nEntre com o CPF correto.');
    	campoform.value = '';
    	campoform.focus();
		return false;
	}
	if (!campo) return true;
	for (i=0;i<campo.length;i++) {
		resposta=campo.charAt(i) ;
		num = parseFloat(resposta);
		if (resposta==''+num) num_cpf=num_cpf+resposta; 
	}
	if (num_cpf.length == 11) {
		soma = 0;
		for (i=0; i < 9; i ++) soma += parseInt(num_cpf.charAt(i)) * (10 - i);
		resto = 11 - (soma % 11);
		if (resto == 10 || resto == 11)	resto = 0;
		soma = 0;
		for (i = 0; i < 10; i ++) soma += parseInt(num_cpf.charAt(i)) * (11 - i);
		resto2 = 11 - (soma % 11);
		if (resto2 == 10 || resto2 == 11) resto2 = 0;
		if ((resto != parseInt(num_cpf.charAt(9))) || (resto2 != parseInt(num_cpf.charAt(10))))	{
			alert ('- CPF inválido. \nEntre com o CPF correto.');
    		campoform.value = '';
    		campoform.focus();
			return false;
		} else {
			campoform.value= num_cpf.substring(0,3) + '.' + num_cpf.substring(3,6) + '.'
			+ num_cpf.substring(6,9) + '-' + num_cpf.substring(9,11);
			return true;
		}
	} else {
		alert ('- CPF inválido. \nEntre com o CPF correto.');
		campoform.value = '';
		campoform.focus();
		return false;
	}
}

function convertCPF(num_cpf){
	if(num_cpf.length < 12 && isNumber(num_cpf)) {
		while(num_cpf.length < 11) {
			num_cpf = "0" + num_cpf;
			//alert(11-num_cpf.length + " - " + num_cpf);
		}
		num_cpf = num_cpf.substring(0,3) + '.' + num_cpf.substring(3,6) + '.' + num_cpf.substring(6,9) + '-' + num_cpf.substring(9,11);
	}
	return num_cpf;
}

function convertData(a){
	var valor = a.value;
	if(valor.indexOf("/") == -1){
		if(valor.length > 2 && valor.length < 5) 
			a.value = valor.substr(0,2) + "/" + valor.substr(2,1);
	} 
	if(valor.lastIndexOf("/") < 5){
		if(valor.length > 5) 
			a.value = valor.substr(0,5) + "/" + valor.substr(5,1);
	}
	if(valor.length > 10)
		a.value = valor.substr(0,10);	
}

function isNumber(x){
	var anum=/(^\d+$)|(^\d+\.\d+$)/;
	if (anum.test(x)) testresult=true;
	else testresult=false; 
	return (testresult);
}


function validaData(objData){
	var data = objData.value.toString();
	var dia = data.substr(0,2);
	var mes = data.substr(3,2);
	var ano = data.substr(6,4);
	var erro = "";
	if(isNumber(dia) && isNumber(mes) && isNumber(ano) && data.length == 10) {
		try {
			dia = parseInt(dia);
			mes = parseInt(mes);
			ano = parseInt(ano);
			dataAtual = new Date();
			anoAtual = dataAtual.getFullYear();
			if(dia > 31) erro += "\n- Foi digitado um número maior que 31 para dia.";
			if(mes > 12) erro += "\n- Foi colocado um número maior que 12 para mês.";
			if(ano > (anoAtual+50) || ano < (anoAtual-120)) erro += "\n- O ano foi digitado incorretamente";
			if(dia == 29 && mes == 2 && !anoBissesto(ano)) erro += "\n- O ano digitado não é bissesto para ter 29 dias";
			if(dia > 29 && mes == 2) erro += "\n- O mês de fevereiro não tem mais de 29 dias.";
			if((dia > 30 && mes == 4) || (dia > 30 && mes == 6) || (dia > 30 && mes == 4) || (dia > 30 && mes == 6) || (dia > 30 && mes == 9) || (dia > 30 && mes == 11)) erro += "\n- O mês de digitado possui no máximo 30 dias.";
			if((dia > 31 && mes == 1) || (dia > 31 && mes == 3) || (dia > 31 && mes == 5) || (dia > 31 && mes == 7) || (dia > 31 && mes == 8) || (dia > 31 && mes == 10) || (dia > 31 && mes == 12)) erro += "\n- O mês de digitado possui no máximo 31 dias.";
		} catch(e){
			erro += "\n- Foi digitado um caracter não-numérico na data.";
		}
	} else {
		erro += "\n- Foi digitado um caracter não-numérico na data.";
	}
	if(erro) {
		alert("Data Inválida:\n" + erro);
		objData.value = "";
		objData.focus();
	}

}

function anoBissesto(ano){
	if((((ano % 4) == 0 && (ano % 100)!=0) || (ano % 400)==0))
		return true;
	else
		return false;
}

function LembraSenha(){
/*	var e = getElement("txtLembraSenha").value;
	if(isNumber(e)) e = convertCPF(e);
	//alert(e);
	var a = new AjaxClass("ajax_LembraSenha.asp?Login=" + e, "LembraSenha");
	getElement("LembraSenha").innerHTML = "Validando, aguarde...";
	a.ajax();
*/	
	var e = getElement("txtLembraSenha").value;
	
	if(isNumber(e)) e = convertCPF(e);

	if (e != ""){
		var a = new AjaxClass("../ajax_LembraSenha.asp?Login=" + e, "LembraSenha");
		getElement("LembraSenha").innerHTML = "Validando, aguarde...";
		a.ajax();
	}
}

/*****************************************
* Autor: Daniel Marcoto
* Data: 13/10/2006
* Objetivo: Cria o objeto ajax
*****************************************/

function AjaxClass(url, local, metodo, params)
{
	this.url = url;
	this.local = local;
	this.metodo = metodo;
	this.params = params;
	this.objAjax = this.contruct();
}

AjaxClass.prototype.contruct = function(){
	var xml;
	if (window.XMLHttpRequest)  {
		xml = new XMLHttpRequest();
	} else {
		xml = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return xml;
}

AjaxClass.prototype.formStandard = function(b){
	do {
		b = b.replace(/ /,"|!|");
	} while(b.search(/ /) > 0);
	return b;
}

AjaxClass.prototype.ajaxManual = function(){
	var local = this.local;
	var obj = this.objAjax;
	if(!this.params) this.params = null;
	if(!this.metodo) this.metodo = "GET";
	this.metodo = this.metodo.toUpperCase();	
	
	this.objAjax.open(this.metodo,this.url, true);	
	
	if(this.metodo == "POST" && this.params){
		this.objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		this.objAjax.setRequestHeader("Cache-Control","no-store, no-cache, must-revalidate");
		this.objAjax.setRequestHeader("Cache-Control","post-check=0, pre-check=0");
		this.objAjax.setRequestHeader("Pragma", "no-cache");
	}
	
	this.objAjax.send(this.params);
}

AjaxClass.prototype.ajax = function(){
	var local = this.local;
	var obj = this.objAjax;
	if(!this.params) this.params = null;
	if(!this.metodo) this.metodo = "GET";
	this.metodo = this.metodo.toUpperCase();
		
	this.objAjax.open(this.metodo,this.url, true);	
	
	if(this.metodo == "POST" && this.params){
		this.objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		this.objAjax.setRequestHeader("Cache-Control","no-store, no-cache, must-revalidate");
		this.objAjax.setRequestHeader("Cache-Control","post-check=0, pre-check=0");
		this.objAjax.setRequestHeader("Pragma", "no-cache");
	}
	
	this.objAjax.onreadystatechange = function(){	
		if (obj.readyState==4) {
			if (obj.status==200) {
				document.getElementById(local).innerHTML = obj.responseText;
			} else {
				document.getElementById(local).innerHTML = "Ocorreu um erro no momento de carregar a página.<br> Descrição do erro: " + obj.statusText;
			}
		}
	}
	this.objAjax.send(this.params);
}
// Adiciona a tag span para ajudar na formatação
$(document).ready(function() {
    $('#conteudo h2').wrapInner('<span class="helper" />');
});
