/* Função para exibição de Flash no IE */
function ExibeFlash(w,h,wmode,movie) {
	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+w+'" height="'+h+'">');
	document.write('<param name="wmode" value="'+wmode+'"/>');
	document.write('<param name="quality" value="high"/>');
	document.write('<param name="movie" value="'+movie+'"/>');
	document.write('<embed src="'+movie+'" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" wmode="'+wmode+'" width="'+w+'" height="'+h+'"></embed>');
	document.write('</object>');
}

/* Setar Texto */
function setTexto(Txt,ID) {
	document.getElementById(ID).innerHTML = Txt;
}

/* Função Show/Hide */
function ExibirOcultar(id,aLink) {
	elemento = document.getElementById(id);

	elemento.className = elemento.className == "on" ? "off" : "on";
	aLink.className = aLink.className == "ocultar" ? "exibir" : "ocultar";
}


function SH(ID,Total) {
	var Itens = Total;
	var Item = ID;

	for(var i=1; i<=Itens; i++){
		if (i != Item) {
			document.getElementById('Item'+i).style.display = 'none'
		} else {
			if (document.getElementById('Item'+i).style.display == 'none') {
				document.getElementById('Item'+i).style.display = '';
			} else {
				document.getElementById('Item'+i).style.display = '';	};
		}
	}

}
function CatSH(ID,Total) {
	var Itens = Total;
	var Item = ID;

	for(var i=0; i<=Itens; i++){
		var Categoria = 'Cat' +i;
		var Link = 'CatLink' +i;
		if (i != Item) {
			document.getElementById(Categoria).style.display = 'none';
			document.getElementById(Link).className = 'C';
		} else {
			if (document.getElementById(Categoria).style.display == 'none') {
				document.getElementById(Categoria).style.display = '';
				document.getElementById(Link).className = 'C-on';
			} else {
				document.getElementById(Categoria).style.display = '';
				document.getElementById(Link).className = 'C-on';
			}
		}
	}
}
	function SHListaCat(list,cat) {
		lista = document.getElementById(list);
		categoria = cat;

		lista.style.display = lista.style.display == "none" ? "" : "none";
		categoria.className = categoria.className == "" ? "ativo" : "";
	}
function SHLayer(ID) {
	var Layer = document.getElementById(ID);
	var Visivel = Layer.style.visibility == 'visible' ? true : false;
	
	if(Visivel) {
		Layer.style.visibility = 'hidden';
		Layer.style.display = 'none';
	} else {
		Layer.style.visibility = 'visible';
		Layer.style.display = '';
	}

}
function Multas(ID) {
	
	Detalhes = ID + 'D';

	if (document.getElementById(Detalhes).className == "off") {
		document.getElementById(Detalhes).className = "on";
		document.getElementById(ID).className = "mON";
	} else {
		document.getElementById(Detalhes).className = "off";
		document.getElementById(ID).className = "mOFF";
	}

}

/* Função do Menu */
function Menu(SubMenu) {

	if (document.getElementById(SubMenu).className == "Container S-off") {
		document.getElementById(SubMenu).className = "Container S-on";
	} else {
		document.getElementById(SubMenu).className = "Container S-off";
	}
}
function FMenu() {
	document.getElementById('TransitoERodovias').className = "Container S-off";
	document.getElementById('Obras').className = "Container S-off";
	document.getElementById('Gerais').className = "Container S-off";
}

function FormularioAviso(deAviso,campo) {
	alert(deAviso);
	document.getElementById(campo).focus();
	return false;
}

function EnviaSolicitacao(formulario) {
	
	
	var hrInicioEvento = document.getElementById("hrInicioEvento");
	var hrFimEvento = document.getElementById("hrFimEvento");
	
	if(!document.getElementById("nmEntidadeEvento").value) {
		return FormularioAviso("O nome do Órgão/Entidade deve ser informado.", "nmEntidadeEvento");
	} else if(!document.getElementById("nmSolicitante").value) {
		return FormularioAviso("O Nome do Solicitante deve ser informado.", "nmSolicitante");
	} else if(!document.getElementById("deEmail").value) {
		return FormularioAviso("Você deve informar o e-mail para contato.", "deEmail");
	} else if(!VEmail(document.getElementById("deEmail").value)) {
		return FormularioAviso("O e-mail informado não é válido.", "deEmail");
	} else if(!document.getElementById("nuFone").value) {
		return FormularioAviso("Você deve informar o telefone para contato.", "nuFone");
	} else if(document.getElementById("nuFone").value.length < 14) {
		return FormularioAviso("O telefone informado não é válido.", "nuFone");
	} else if(!document.getElementById("sgRodovia").value) {
		return FormularioAviso("A Rodovia onde o evento será realizado deve ser informada.", "sgRodovia");
	} else if(!document.getElementById("dePontoRefEvento").value) {
		return FormularioAviso("Você deve informar um Ponto de Referência.", "dePontoRefEvento");
	} else if(!document.getElementById("nmCidade").value) {
		return FormularioAviso("O nome do Município deve ser informado.", "nmCidade");
	} else if(!document.getElementById("dtInicioEvento").value) {
		return FormularioAviso("Você deve informar a data de início do Evento.", "dtInicioEvento");
	} else if(!document.getElementById("dtFimEvento").value) {
		return FormularioAviso("Você deve informar a data de enceramento do Evento.", "dtFimEvento");
	} else if(!hrInicioEvento.value) {
		return FormularioAviso("Você deve informar o horário de início do Evento.", "hrInicioEvento");
	} else if(hrInicioEvento.value.length < 5) {
		return FormularioAviso("O formato do horário de início do Evento deve ser \"00:00\".", "hrInicioEvento");
	} else if(hrInicioEvento.value.length == 5) {
		var hrInicioStr = hrInicioEvento.value;
		if(hrInicioStr.substr(0,2) > 23 || hrInicioStr.substr(3,5) > 59) {
			return FormularioAviso("O horário de início do Evento deve variar entre 00:00 e 23:59.", "hrInicioEvento");
		}
	}
	if(!hrFimEvento.value) {
		return FormularioAviso("Você deve informar o horário previsto para enceramento do Evento.", "hrFimEvento");
	} else if(hrFimEvento.value.length < 5) {
		return FormularioAviso("O formato do horário previsto para encerramento do Evento deve ser \"00:00\".", "hrFimEvento");
	} else if(hrFimEvento.value.length == 5) {
		var hrFimStr = hrFimEvento.value;
		if(hrFimStr.substr(0,2) > 23 || hrFimStr.substr(3,5) > 59) {
			return FormularioAviso("O horário previsto para encerramento do Evento deve variar entre 00:00 e 23:59.", "hrFimEvento");
		}
	}
	if(!document.getElementById("nmResponsavelEvento").value) {
		return FormularioAviso("Você deve informar o Nome do Responsável pelo Evento.", "nmResponsavelEvento");
	} else if(!document.getElementById("deMensagem").value) {
		return FormularioAviso("Você deve informar uma breve descrição do Evento.", "deMensagem");
	} else {
		return true;
	}
}


function VEmail( strEmail ) {
     var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
     return (filter.test(strEmail));
}
function VContato() {
  if (!document.form1.nome.value) { alert("Por favor, informe seu nome."); document.form1.nome.focus(); return false; };
  if (!VEmail( document.form1.email.value)) { alert("O seu e-mail não é válido!\nVerifique-o novamente."); document.form1.email.focus(); return false; };
  if (!document.form1.assunto.value) { alert("Por favor, informe o assunto da mensagem."); document.form1.assunto.focus(); return false; };
  if (!document.form1.mensagem.value) { alert("Você deve escrever a mensagem."); document.form1.mensagem.focus(); return false; };
  return true;
}


/* Funções do Formulário */
function Ativar(Campo) {

	if (document.getElementById(Campo).className == "Inativo") {
		document.getElementById(Campo).className = "Ativo";
	}
	else if (document.getElementById(Campo).className == "Ativo") {
		document.getElementById(Campo).className = "Inativo";
	}
	else if (document.getElementById(Campo).className == "Inativo Obrigatorio") {
		document.getElementById(Campo).className = "Ativo Obrigatorio";
	}
	else if (document.getElementById(Campo).className == "Ativo Obrigatorio") {
		document.getElementById(Campo).className = "Inativo Obrigatorio";
	} else {
		document.getElementById(Campo).className = "Inativo";
	}
}

function OnOFF(obj) {
	var nmStyle = new String(obj.className);
	obj.className = nmStyle.substr(0, nmStyle.length - 4) + "-on";
}


function OFFOn(obj) {
	var nmStyle = new String(obj.className);
	obj.className = nmStyle.substr(0, nmStyle.length - 3) + "-off";
}

function MaisMenos(obj) {
	var obj = obj;
	var img = obj.childNodes[0].src;
	var src = img.substr(img.length - 12, img.length);
	
	if(src == "bot-mais.gif") {
		obj.innerHTML = '<img src="/imagens/bot-menos.gif" title="Ocultar Informações" />';
	} else {
		obj.innerHTML = '<img src="/imagens/bot-mais.gif" title="Exibir Informações" />';
	}

}



/* Funções do PopUp */
function Open(mypage,myname,w,h,scroll){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	
	/* Hack - Bug de CSS no IE - position:fixed
	if (scroll=='Sim' && navigator.appName.indexOf('Internet Explorer')>0) {
		scroll = 'no';
	} else {
		scroll = 'yes';
	}*/
	scrolls = 'no';
	
	settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scrolls+',noresizable,status=yes'
	win = window.open(mypage,myname,settings)
}

function Mascara(objeto, evt, mask) {
		
	var LetrasU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var LetrasL = 'abcdefghijklmnopqrstuvwxyz';
	var Letras 	= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
	var Numeros = '0123456789';
	var Fixos 	= '().-:/ '; 
	var Charset = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_/`abcdefghijklmnopqrstuvwxyz{|}~";
	
	evt = (evt) ? evt : (window.event) ? window.event : "";
	var value = objeto.value;
	if (evt) {
		var ntecla = (evt.which) ? evt.which : evt.keyCode;
		tecla = Charset.substr(ntecla - 32, 1);
		if (ntecla < 32) return true;

		var tamanho = value.length;
		if (tamanho >= mask.length) return false;

		var pos = mask.substr(tamanho,1); 
		while (Fixos.indexOf(pos) != -1) {
			value += pos;
			tamanho = value.length;
			if (tamanho >= mask.length) return false;
			pos = mask.substr(tamanho,1);
		}

		switch (pos) {
				case '#' : if (Numeros.indexOf(tecla) == -1) return false; break;
				case 'A' : if (LetrasU.indexOf(tecla) == -1) return false; break;
				case 'a' : if (LetrasL.indexOf(tecla) == -1) return false; break;
				case 'Z' : if (Letras.indexOf(tecla) == -1) return false; break;
				case '*' : objeto.value = value; return true; break;
				default : return false; break;
		}
	}
	objeto.value = value; 
	return true;
}


// Deixa a string apenas com os numeros, eliminando o restante.
function trimToDigits(string) {
	s = "";
	var Numeros = /\d/;
	for (i = 0; i <= string.length; i++) 
		if (Numeros.test(string.substr(i,1))) s += string.substr(i,1);
	return s;	
}

function MaskTelefone(objeto, evt) { 
	return Mascara(objeto, evt, '(##) ####-####');
}
function DecHex(dec2) {  
    var hex_chars = "0123456789ABCDEF";  

    var n1 = hex_chars.charAt(Math.floor(dec2 / 16));  
    var n2 = hex_chars.charAt(dec2 % 16);  

    return n1 + n2;  
}  
// Ajax
function ajaxInit() {
	var req;
	
	try {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	} catch(e) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(ex) {
			try {
				req = new XMLHttpRequest();
			} catch(exc) {
				alert("Esse browser não tem recursos para uso do Ajax");
				req = null;
			}
		}
	}
	return req;
}

// hoHOHO
function Ajax(f,ID) {
	F = document.getElementById(f);
    var acao = F.action;  
    var metodo = F.method.toLowerCase();
    
	//if (!document.getElementById('nmSolicitante').value) { alert("O campo Nome é obrigatório."); document.getElementById('nmSolicitante').focus(); return false; };
	//if (!VEmail( document.getElementById('deEmail').value)) { alert("Este E-mail não é válido."); document.getElementById('deEmail').focus(); return false; };
	//if (!document.getElementById('nmCidade').value) { alert("O campo Cidade é obrigatório."); document.getElementById('nmCidade').focus(); return false; };
	//if (!document.getElementById('sgUnidadefederal').value) { alert("Você deve informar a Unidade Federativa."); document.getElementById('sgUnidadefederal').focus(); return false; };

	if(!acao) {  
        alert("Erro: O valor action do formulario não foi definido.");  
    }  
      
    var send = new Array();  
    var elementos = F.elements;  
      
    for(var i = 0; i < elementos.length; i++) {  
        var e = elementos[i];  
        if(!e.name)  
            continue;  
          
        var nVal = "";  
          
        for(var x = 0; x < e.value.length; x++) {  
            codeA = e.value.charCodeAt(x);  
            codeA = DecHex(codeA);  
            nVal += "%" + codeA;  
        }  
          
        var tipo = e.type.toLowerCase();  
          
        if(tipo != "checkbox" && tipo != "radio") {  
            send[send.length] = e.name + "=" + nVal;  
        } else {  
            if(e.checked) {  
                send[send.length] = e.name + "=" + nVal;  
            }  
        }  
    }  
      
    send = send.join("&");
    var ajax = ajaxInit();  
      
    if(ajax) {
        if(metodo == "post") {  
            ajax.open("POST", acao, true); 
			//ajax.setRequestHeader("Content-type", "multipart/form-data");
			ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			ajax.setRequestHeader("Content-length", send.length);
			ajax.setRequestHeader("Connection", "close");
        } else {  
            ajax.open("GET", acao + "?" + send, true);  
        }  
          
        ajax.onreadystatechange = function() {  
			if (ajax.readyState == 4) {
				//alert( ajax.status );
				//alert(ajax.responseText);
				if (ajax.status == 418) {
					var URL = "/enquete/ok.jsp?height=100&width=250";
					tb_show("BPMRv - Enquete", URL, false);
				}
				else if (ajax.status == 419) {
					var URL = "/enquete/erro.jsp?id=1&height=100&width=250";
					tb_show("BPMRv - Enquete", URL, false);
				}
				else if (ajax.status == 200) {
					alert( ajax.responseText );
					//document.getElementById(ID).innerHTML = ajax.responseText;
				};
				
			}
		}  
          
        if(metodo == "post") {  
            ajax.send(send);  
        } else {  
            ajax.send(null);  
        }  
    }  
}

/* Exibir Dados de Paginação */
function exibeDadosPaginacao(url,ID) {
	var ajax = ajaxInit();  
    if(ajax) {
		ajax.open("GET", url, true);  
        ajax.onreadystatechange = function() {  
			if (ajax.readyState == 4) {
				if (ajax.status == 200) {
					// 200 = quando carregou os dados no browser
					document.getElementById(ID).innerHTML = ajax.responseText;
				}
			}
		}
	}  
	ajax.send(null);
} 
	

/* Verifica Enquete */
function VerificaEnquete(F,id) {
	AjaxF = F;
	AjaxID = id;
	//alert(AjaxF);
	var selecionado = -1;
	Item = document.enqueteForm.cdItem;
	//alert(Item);
	for (i=0; i<Item.length; i++) {
		if (Item[i].checked) {
			selecionado = i;
		}
	}
	if (selecionado == -1) {
		var URL = "/enquete/erro.jsp?id=2&height=100&width=250";
		tb_show("BPMRv - Enquete", URL, false);
	} else {
		//return Ajax(AjaxF,AjaxID);
		Ajax(AjaxF,AjaxID);
	}	
}
function ocorrenciasRelatorio() {
	var formulario = document.getElementById("ocorrenciasRelatorioPDF");
	formulario.submit();
}