//coding:utf-8 
// Por daniel tygel em 2007, 2008 e um monte em 2009
var map = null;
var markerCluster = false;
var geoXml = [];
var Icone = new Object();
var icones = [];
var marcadores=[];
var marcadoresAbrangencia=[];
var points=[];
var numpts = 0;

/*Inicializa um icone genérico:*/
function inicializa_icone(tipo) {
	var d=def_icone[tipo];
	var icon = new GIcon();
	if (d[0].search(/http/)>-1)
		icon.shadow = d[0];
		else icon.shadow = imgurl+d[0];
	icon.iconSize = new GSize(d[1],d[2]);
	icon.shadowSize = new GSize(d[3],d[4]);
	icon.iconAnchor = new GPoint(d[5],d[6]);
	icon.infoWindowAnchor = new GPoint(d[7],d[8]);
	return icon;
}


/* Função que gera um círculo:
	center: latlng do centro;
	radius: raio (em km)
	nodes: número de pontos (precisão)
	liColor: cor da linha
	liWidth: espessura da linha
	liOpa: opacidade da linha
	fillColor: cor do preenchimento do círculo
	fillOpa: opacidade do preenchimento
*/
function drawCircle(center, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa) {
	// Esa 2006
	//calculating km/degree
	var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
	var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;
	//Loop 
	var ptsborda = [];
	var step = parseInt(360/nodes)||10;
	for(var i=0; i<=360; i+=step) {
		var tmp = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() + (radius/lngConv * Math.sin(i * Math.PI/180)));
		ptsborda.push(tmp);
	}
	if (liColor=='Azul')
		liColor="#0055ff";
		else if(liColor=='Amarelo')
			liColor="yellow";
	fillColor = fillColor||liColor||"#0055ff";
	liWidth = liWidth||2;
	var poly = new GPolygon(ptsborda,liColor,liWidth,liOpa,fillColor,fillOpa);
	map.addOverlay(poly);
}



function faz_area(center, ptspoly, raio, nodes, liColor, liWidth, liOpa, fillColor, fillOpa) {
	// Esa 2006
	//calculating km/degree
	var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
	var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;
	//Loop 
	var ptsborda = [];
	var step = parseInt(360/nodes)||10;
	for(var i=0; i<=360; i+=step) {
		var tmp = new GLatLng(center.lat() + (raio/(latConv*1000) * Math.cos(i * Math.PI/180)), center.lng() 
			+ ( raio/(lngConv*1000) * Math.sin(i * Math.PI/180) ) );
		var min=raio;
		var jmin=0;
		for (var j=0; j<ptspoly.length; j++) {
			if ( tmp.distanceFrom(ptspoly[j])<min ) {
				jmin=j;
				min=tmp.distanceFrom(ptspoly[j]);
			}
		}
		ptsborda.push(ptspoly[jmin]);
	}
	if (liColor=='Azul')
		liColor="#0055ff";
		else if(liColor=='Amarelo')
			liColor="yellow";
	fillColor = fillColor||liColor||"#0055ff";
	liWidth = liWidth||2;
	var poly = new GPolygon(ptsborda,liColor,liWidth,liOpa,fillColor,fillOpa);
	return poly;
}

function trim(txt){return txt.replace(/^\s+|\s+$/g,"");}

/*
Função que gera o HTML da mensagem
*/
function faz_msg(texto, config, thumb) {
	var pre1="<p class='mensagem_balao";
	var pre2="'>";
	var pos="</p>";
	var valores=texto.split("|");
	if (thumb && thumb!="undefined")
		var ret='<img src="'+thumb.image+'" style="float:left">';
		else var ret="";
	var tmp="";
	for (var i=0;i<config.campos.length;i++) {
		if (valores[i]!='') {
			if (config.campos[i].indexOf("{dado}")==-1)
				tmp=config.campos[i]+valores[i];
			else
				tmp=config.campos[i].replace(/{dado}/g,valores[i]);
			ret+=pre1+config.estilos[i]+pre2+tmp+pos;
		}
	}	
	return ret;
}


/*
//Esta funcao chama qualquer tipo de icones! Eles podem ser chamados depois pelo PHP, com o nome correto. Atencao para as cores existentes! :
// BANDEIRINHAS: 
//		BandeiraAzul, BandeiraVerde, BandeiraCinza, BandeiraLaranja, BandeiraRosa,
//		BandeiraPurpura, BandeiraVermelha, BandeiraAmarela

// ÍCONES PEQUENOS: 
//		PeqAzul, PeqVerde, PeqCinza, PeqLaranja, PeqPreto, PeqMarrom,
//		PeqPurpura, PeqAmarelo, PeqVermelho, PeqBranco

// ÍCONES CONVENCIONAIS:
//		Padrao, Azul, Verde, Laranja, Amarelo, Vermelho

// ÍCONES ESPECIAIS:
//		AgroredeAmarelo, AgroredeVerde

// PONTOS:
//		PontoAmarelo, PontoAzul
*/
function faz_icone(dados) {
	var cor = dados.cor;
	var tipo = dados.tipo;
	if ((typeof(cor)=="undefined") || (cor==null) || !cor)
    	cor = "";
	if ((typeof(tipo)=="undefined") || (tipo==null) || !tipo)
    	tipo = "";
	if (!icones[tipo+cor]) {
		if (!Icone[tipo] || Icone[tipo]=='undefined')
			Icone[tipo]=inicializa_icone(tipo);
		icones[tipo+cor] = new GIcon(Icone[tipo]);
		icones[tipo+cor].image=imgurl+tipo+cor+'.png';
	}
	return icones[tipo+cor];
};

function coloca_marcador(ponto, dados, i) {
    var marcador = new GMarker(ponto,dados.ictmp);
    marcador.cat=dados.cat;
    marcador.htmlmsg=dados.htmlmsg;
    marcador.idMae=dados.idMae;
    marcador.nomeFrm=dados.nomeFrm;
    marcador.idPt=dados.idPt;
    marcador.nome=dados.nome;
    GEvent.addListener(marcador, "mouseover", function() {
    	if (marcador.nome)
	    	overlib(txt['mapa_clique_para_detalhes'], CAPTION, marcador.nome, ABOVE, LEFT, WIDTH, 300, AUTOSTATUSCAP);
   		for (i=0;i<marcadoresAbrangencia.length;i++)
   			if (marcadoresAbrangencia[i].idMae==marcador.idPt)
				marcadoresAbrangencia[i].show();
	});
	GEvent.addListener(marcador, "mouseout", function() {
		if (marcador.nome)
			nd();
   		for (i=0;i<marcadoresAbrangencia.length;i++)
   			if (marcadoresAbrangencia[i].idMae==marcador.idPt)
				marcadoresAbrangencia[i].hide();
	});
	GEvent.addListener(marcador, "click", function() {
              pega_infos(dados);
	});
	return marcador;
}
//Esta função serve para fazer request ajax simples:
function ajaxRequest(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])
   }
   catch(e){
    //suppress error
   }
  }
 }
 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  return new XMLHttpRequest()
 else
  return false
}
//Esta função apaga ou mostra uma determinada camada:
function camadas(el,url,i,camadaVariavel) {
	if (typeof geoXml[i] =='undefined') {
		if (camadaVariavel==1) {
			var limites = map.getBounds();
			var SO = limites.getSouthWest();
			var NE = limites.getNorthEast();
			var minlat = SO.lat();
			var minlng = SO.lng();
			var maxlat = NE.lat();
			var maxlng = NE.lng();
			var params='?minlat='+minlat+'&minlng='+minlng+'&maxlat='+maxlat+'&maxlng='+maxlng;
			url += params;
			var mygetrequest=new ajaxRequest();
			mygetrequest.onreadystatechange=function(){
				if (mygetrequest.readyState==4){
					if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
						var msg = eval("("+mygetrequest.responseText+")");
						if (msg=='ok') {
							geoXml[i] = new GGeoXml(url);
							document.getElementById('carregando_mapa').style.visibility='visible';
							GEvent.addListener(geoXml[i],
"load", function() { document.getElementById('carregando_mapa').style.visibility='hidden' });
							map.addOverlay(geoXml[i]);
						} else {
							alert(msg);
							el.checked=false;
						}
					}
					else{alert("O carregamento de dados de camadas deu errado. Por favor, tente mais tarde ou contate o administrador do sistema.");
						el.checked=false;}
				}
			}
			mygetrequest.open("GET", url+'&verifica=1', true);
			mygetrequest.send(null);
		} else {
			geoXml[i] = new GGeoXml(url);
			document.getElementById('carregando_mapa').style.visibility='visible';
			GEvent.addListener(geoXml[i],
"load", function() { document.getElementById('carregando_mapa').style.visibility='hidden' });
			map.addOverlay(geoXml[i]);
		}
	} else if (el.checked)
		geoXml[i].show();
		else {
			geoXml[i].hide();
			if (camadaVariavel)
				delete geoXml[i];
		}
}

//Esta função mostra ou esconde os marcadores de uma determinada categoria:
function aparencia(categoria,acao) {
	// == check ou uncheck o checkbox ==
	document.getElementById(categoria).checked = (acao=='mostrar');
	map.closeInfoWindow();
	var temoutra=false;
	for (var i=0; i<marcadores.length; i++) {
		if (marcadores[i].cat.search(categoria)>-1) {
			if (acao=='mostrar')
				marcadores[i].show();
			else {
				for (var j=0;j<categorias.length;j++)
					if (document.getElementById(categorias[j][0]))
						if (document.getElementById(categorias[j][0]).checked==true && marcadores[i].cat.search(categorias[j][0])>-1)
							temoutra=true;
				if (temoutra==false)
					marcadores[i].hide();
				else temoutra=false;
			}
		}
	}
}

//Esta função faz a alternância dos marcadores quando há click num checkbox (veja no HTML!):
function boxclick(box,categoria) {
        if (box.checked) aparencia(categoria,'mostrar');
        else aparencia(categoria,'esconder');
        // == rebuild the side bar
        makeSidebar();
}

//Este aqui peguei da página do googlecode: Pamela.
function createSidebarEntry(i,marker, mensagemhtml) {
      var div = document.createElement('div');
      var html = mensagemhtml;
      div.id='indice'+i;
      div.innerHTML = html;
      div.style.cursor = 'hand';
      div.style.marginBottom = '0';
      /*div.style.display = 'inline';*/
      GEvent.addDomListener(div, 'click', function() {
        GEvent.trigger(marker, 'click');
      });
      GEvent.addDomListener(div, 'mouseover', function() {
        div.style.backgroundColor = '#ccf';
      });
      GEvent.addDomListener(div, 'mouseout', function() {
        div.style.backgroundColor = '#fff';
      });
      return div;
}

//Esta função (re)faz o painel lateral:
function makeSidebar() {
	var sidebar=document.getElementById(sidebarId);
	if (sidebar) {
		sidebar.innerHTML = cabecalho_sidebar;
			var html = "";
			for (var i=0; i<marcadores.length; i++) {
				if (!marcadores[i].isHidden()) {
				var sidebarEntry = createSidebarEntry(i,marcadores[i], marcadores[i].htmlmsg+'<hr>');
	    sidebar.appendChild(sidebarEntry);
				}
			}
			document.getElementById(sidebarId).innerHTML = html;
	}
}


// Funcao que faz auto-zoom de acordo com os pontos gerados
function fitMap( map, points, tipo_mapa ) {
  var bounds = new GLatLngBounds();
  if (points.length>1) {
	  for (var i=0; i< points.length; i++)
    	 bounds.extend(points[i]);
	  map.setZoom(map.getBoundsZoomLevel(bounds));
	  map.setCenter(bounds.getCenter());
  } else {
  	map.setZoom(10);
	map.setCenter(points[0]);
  }
  //alert ("map.setCenter("+bounds.getCenter()+","+map.getBoundsZoomLevel(bounds)+","+tipo_mapa+")");
}

function pega_infos(dados) {
	var nomeFrm = dados.nomeFrm;
	var idPt = dados.idPt;
	var existe=false;
	for (var i=0;i<marcadores.length;i++) {
		if (marcadores[i].idPt==idPt) {
			if (marcadores[i].htmlmsg) {
				faz_msg2(marcadores[i].htmlmsg,i);
				/*marcadores[i].openInfoWindowHtml(marcadores[i].htmlmsg);*/
				existe=true;
			} else 
				marcadores[i].openInfoWindowHtml('<div class="info_carregando_dados"></div>');
			var indice = i;
			break;
		}
	}
	if (!existe) {
		var url = urls[0] + '?c=1&f=infos&nomeFrm='+nomeFrm+'&idPt='+idPt;
		GDownloadUrl(url, function(data) {
			var xml = GXml.parse(data);
			var res = xml.documentElement.getElementsByTagName("info");
			var msg = res[0].getAttribute("msg");
			faz_msg2(msg,indice);
		});
	}
}
function faz_msg2(htmlmsg,indice) {
	if (marcadores[indice].htmlmsg=='' || !marcadores[indice].htmlmsg)
		marcadores[indice].htmlmsg = htmlmsg;
	marcadores[indice].openInfoWindowHtml('<div class="balaoContainerGeral">'+htmlmsg+'</div>');
}
// Funcao que faz o loop de pingar os dados nas varias fontes de dados:
function pega_dados(parametrosUrl, k, idAlvo, contagem, idLegenda) {
	if (!contagem)
		document.getElementById('carregando_mapa').style.visibility='visible';
	var sidebar = document.getElementById(sidebarId);
	if (!k)
		k = 0;
	var url = urls[k]+parametrosUrl[k];
	GDownloadUrl(url, function(data) {
		var xml = GXml.parse(data);
		if (points.length>0 && !contagem) {
			if (markerCluster!=false)
				markerCluster.clearMarkers();
			if (geoXml.length>0) {
				for (var i=0; i<marcadores.length; i++)
					map.removeOverlay(marcadores[i]);
			} else
				map.clearOverlays();
			
			marcadores.length=0;
			marcadoresAbrangencia.length=0;
			points.length=0;
		}
		numpts=0;
		var markers = xml.documentElement.getElementsByTagName("pt");
		if (markers.length == 0) {
			/*if (sidebar)
				sidebar.innerHTML = 'erro, dados nao encontrados...';*/
			if (!contagem)
				document.getElementById('carregando_mapa').style.visibility='hidden';
			else if (idAlvo)
				document.getElementById(idAlvo).style.display="visible";
			if (typeof idLegenda !== 'undefined') {
				document.getElementById('span_'+idLegenda).innerHTML=0;
			}
			return;
		} else if (markers[0].getAttribute("num")) {
			numpts += parseInt(markers[0].getAttribute("num"));
		} else {
			var tmp = xml.documentElement.getElementsByTagName("config");
			var config= new Object;
			if (tmp[0].getAttribute("campos"))
				config.campos = tmp[0].getAttribute("campos").split("|");
			if (tmp[0].getAttribute("estilos"))
				config.estilos = tmp[0].getAttribute("estilos").split("|");
			if (tmp[0].getAttribute("tipo"))
				var tipo_global = tmp[0].getAttribute("tipo");
			if (tmp[0].getAttribute("cor"))
				var cor_global = tmp[0].getAttribute("cor");
			if (tmp[0].getAttribute("cat"))
				var cat = tmp[0].getAttribute("cat");
			if (tmp[0].getAttribute("cats")) {
				tmp = tmp[0].getAttribute("cats").split("||");
				for (var i=0;i<tmp.length;i++) 
					categorias[i]=tmp[i].split("|");
			}
			var conjunto = new Object;
			for (var i = 0; i < markers.length; i++) {
				var dados = new Object;
				if (markers[i].getAttribute("tipo"))
					dados.tipo = markers[i].getAttribute("tipo");
					else dados.tipo=tipo_global;
				if (markers[i].getAttribute("cor"))
					dados.cor = markers[i].getAttribute("cor");
					else dados.cor=cor_global;
				if (markers[i].getAttribute("cat"))
					dados.cat = markers[i].getAttribute("cat");
				if (markers[i].getAttribute("id"))
					dados.idPt = markers[i].getAttribute("id");
				if (markers[i].getAttribute("nome"))
					dados.nome = markers[i].getAttribute("nome");
				dados.idMae = (markers[i].getAttribute("id_mae"))
					? markers[i].getAttribute("id_mae")
					: '';
				if (markers[i].getAttribute("nomefrm"))
					dados.nomeFrm = markers[i].getAttribute("nomefrm");
				dados.ictmp = faz_icone(dados);
				if (markers[i].getAttribute("msg"))
					dados.msghtml = faz_msg(markers[i].getAttribute("msg"));
					else dados.msghtml='';
				conjunto.lat = markers[i].getAttribute("lat").split(",");
				conjunto.lng = markers[i].getAttribute("lng").split(",");
				if (conjunto.lat.length==1)
					var point = new GLatLng(parseFloat(conjunto.lat[0]), parseFloat(conjunto.lng[0]));
					else {
					// Aqui é o caso de um conjunto de pontos, e portanto devemos fazer um círculo embaixo do seu centro, demarcando a região dos pontos:
						var bounds = new GLatLngBounds();
						var ptspoly=new Array();
						for (var l=0; l<conjunto.lat.length; l++) {
							var tt= new GLatLng(parseFloat(conjunto.lat[l]), parseFloat(conjunto.lng[l]));
							bounds.extend(tt);
							ptspoly.push(tt);
						}
						var point = bounds.getCenter();
						//drawCircle(point, point.distanceFrom(bounds.getSouthWest())/1000, 10, 'Azul');
						var poly = faz_area(point, ptspoly, point.distanceFrom(bounds.getSouthWest()), 6, 'Azul');
						poly.cat = cat;
						map.addOverlay(poly);
						if (dados.idMae=='')
							marcadores.push(poly);
						else {
							poly.hide();
							marcadoresAbrangencia.push(poly);
						}
					}
				var marcador = coloca_marcador(point, dados, i);
				if (markerCluster==false)
					map.addOverlay(marcador);
				points.push(point);
				if (dados.idMae=='') {
					marcadores.push(marcador);
					numpts++;
				} else {
					marcador.hide();
					marcadoresAbrangencia.push(marcador);
				}
				/*if (sidebar) {
					var sidebarEntry = createSidebarEntry(i,marcador, mensagemhtml+'<hr>');
					sidebar.appendChild(sidebarEntry);
				}*/
			}
			if (markerCluster!=false)
				markerCluster.addMarkers(marcadores);
		}
		if (urls[k+1])
			pega_dados(parametrosUrl, k+1, idAlvo, contagem, idLegenda);
			else {
				if (!contagem) {
					setTimeout("document.getElementById('carregando_mapa').style.visibility='hidden'",2000);
					if (sidebar)
						setTimeout("document.getElementById(sidebarId).style.visibility='visible'",2000);
					fitMap( map, points );
				}
				if (idAlvo) {
					document.getElementById('span_'+idAlvo).innerHTML = numpts;
					document.getElementById(idAlvo).style.display="block";
				}
				if (typeof idLegenda !== 'undefined') {
					document.getElementById('span_'+idLegenda).innerHTML=numpts;
				}
			}
	});
}

