

var map            = null;
var geocoder       = null;
var marcadorAtual  = null;
var icone          = null;
var routePoints    = new Array();
var routeMarkers   = new Array();
var routeOverlays  = new Array();
var junctionPoints = new Array();
var pLinePoints    = new Array();
var polylines      = new Array();
var totalDistance = 0.0;
var lineIx = 0;
var markerInicioRota = null;
var markerFimRota = null;
var tipoRota = 1;
var enderecoInicioRota = '';
var enderecoFinalRota = '';
var detalhesRota = '';
var enderecos = new Hashtable();

function initialize() 
{
   function TextualZoomControl() {
    }

    TextualZoomControl.prototype = new GControl();
    TextualZoomControl.prototype.initialize = function(map) 
    {
      var container = document.createElement("div");

      // BOTÃO DE SELECAO DE TIPO DE ROTAS
      var btnTipoRota = document.createElement("div");
      this.setButtonStyle_(btnTipoRota);
 
      var btnTipoRotaPonto = document.createElement("div");
      btnTipoRotaPonto.className = "AlinhamentoDireito";
      btnTipoRotaPonto.innerHTML = "<input type ='radio' id='btnSelTipoRotaPonto' style='height:10px;' name='TipoRota' checked='true'>Ponto a ponto</input>";
      GEvent.addDomListener(btnTipoRotaPonto, "click", function() 
      {
        alterarTipoRota();
      });    
      btnTipoRota.appendChild(btnTipoRotaPonto);

      var btnTipoRotaRua = document.createElement("div");
      btnTipoRotaRua.className = "AlinhamentoDireito";
      btnTipoRotaRua.innerHTML = "<input type ='radio' id='btnSelTipoRotaRua' style='height:10px;' name='TipoRota'>Ruas</input>";
      GEvent.addDomListener(btnTipoRotaRua, "click", function() 
      {
        alterarTipoRota();
      });    
      btnTipoRota.appendChild(btnTipoRotaRua);
      container.appendChild(btnTipoRota);
      
      // BOTÃO PARA INICIAR A ROTA    
      var btnRota = document.createElement("div");
      btnRota.id = "btnRota";
      this.setButtonStyle_(btnRota);
      container.appendChild(btnRota);
      btnRota.innerHTML = "<B>Iniciar rota</B>";
      GEvent.addDomListener(btnRota, "click", function() 
      {
         iniciarRota(btnRota);
      });

      // BOTÃO PARA DESFAZER UMA ROTA
//      var btnDesfazerRota = document.createElement("div");
//      this.setButtonStyle_(btnDesfazerRota);
//      container.appendChild(btnDesfazerRota);
//      btnDesfazerRota.innerHTML = "Desfazer";
//      GEvent.addDomListener(btnDesfazerRota, "click", function() 
//      {
//        undoPoint();                
//      });      

      // BOTÃO PARA LIMPAR TODAS AS ROTAS
      var btnLimparRota = document.createElement("div");
      this.setButtonStyle_(btnLimparRota);
      container.appendChild(btnLimparRota);
      btnLimparRota.innerHTML = "Limpar";
      GEvent.addDomListener(btnLimparRota, "click", function() 
      {
        clearAll();
      });      
      
      // BOTÃO EXIBIR KM DA ROTA          
      var divDistancia = document.createElement("div");
      divDistancia.id = "dist";
      this.setButtonStyleKM_(divDistancia);
      container.appendChild(divDistancia);
      divDistancia.innerHTML = "0.000 km";


      map.getContainer().appendChild(container);
      return container;

   }

   TextualZoomControl.prototype.getDefaultPosition = function() 
   {
      return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(7, 7));
   }

   TextualZoomControl.prototype.setButtonStyle_ = function(button) 
   {
      button.style.textDecoration = "none";
      button.style.color = "#0000cc";
      button.style.backgroundColor = "white";
	  button.style.font = "11px Arial";
      button.style.border = "1px solid black";
      button.style.padding = "2px";
      button.style.paddingTop = "5px";
      button.style.marginRight = "3px";
      button.style.textAlign = "center";
      button.style.width = "1px";
      button.style.cursor = "pointer";
      button.style.color = "black";
      button.style.height = "25px";
      button.className = "AlinhamentoDireito";      
      button.style.paddingRight = "5px";
      button.style.paddingLeft = "5px";
   }
   
   TextualZoomControl.prototype.setButtonStyleKM_ = function(button) 
   {
      button.style.textDecoration = "none";
      button.style.color = "#0000cc";
      button.style.backgroundColor = "#F6F9BD";
	  button.style.font = "11px Arial";
      button.style.border = "1px solid black";
      button.style.padding = "2px";
      button.style.paddingTop = "5px";      
      button.style.marginRight = "3px";
      button.style.textAlign = "center";
      button.style.width = "1px";
      button.style.color = "black";
      button.style.height = "25px";      
      button.className = "AlinhamentoDireito";
      button.style.paddingRight = "5px";
      button.style.paddingLeft = "5px";      
   }
   
   if (GBrowserIsCompatible()) 
   {
     map      = new GMap2(document.getElementById("map"));
     geocoder = new GClientGeocoder();       
     icone    = new GIcon();

     map.addControl(new GMapTypeControl());
     map.addControl(new GLargeMapControl(),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 70)));
     map.addControl(new GOverviewMapControl());
     map.addMapType(G_PHYSICAL_MAP);     
     map.enableDoubleClickZoom();
     map.enableContinuousZoom();     
     centralizarMapa();
     //map.addControl(new TextualZoomControl());     
     //adicionarControleEstados();  

	 GEvent.addListener(map, "moveend", getMapcenter);
	
     return;
     var pl = new GPolyline.fromEncoded(
     {
      color: "#0000ff",
      weight: 4,
      opacity: 0.8,
      points: "_gkxEr}|vNcBwBoAoA{Jg@cBcBoA{@S?uBoA}@wBS_DbBwhATg@c[sDiT}\\g@i@{@S{@{@ScBRSnAg@SoAS{Eg@kCkClH?nAoF`LQRU{E~CgJ?g@jCqNrNcGz@?zJyBf@y@~CmC{@zJ?f@mAnA?f@x@z@bBR~HsIRe@jClKRz@`Dh@`Bd@vBRnF_DRSg@S?wBpFcGd@SScBwBvB{@T_D~Cg@?oA`B{@R{E~CqD{EUgJwB{@nAoA?kChJrIdJaBz@i@f@_DdBf@dEgEnFcGoP_N{@SeTvBqKoA{J_SsDoF?_Df@{@vB_XoAoPbLoZrDcBy@{EmC_D{ToAy@g@?_DlAgEgEcLg@g@qDnAqAkR_DyJy@i@mC?g@{@}CqNi@i@_ISoK_g@g@{@{EiCiCd@g@z@yGfOwBnAoARyJ_DuDRoAg@_D_IoKyEcGk\\gOx@cGy@{@}@sI_DcGgEwLbBuBRmCe@{JgOS}Jy@{@kHcBy[_]gEmPnA}Ef@g@vGwBgEa[rDqP|h@w[hMoFzJ{J~HwL{@_DoAkCcGwBuBgJyBoA_SfJiCz@{Jz@yBg@oU{OkCkCf@cLbBsIy@iCyGeB}H{@mCnFoAvB}ReEyGaIpFsSx@iHoAmCkHkCQ{JmM{TS_DvBuG?qFR{@vBoA~Hg@bBoAlCuL}@cG_IcGyEi@?sNUy@{@}@wLvBuB?aIcGgTgOSwLS_DoFoFwQTsDUg^kW}Hwe@U_DrI_l@|@_Dx@g@fTbBjC?j\\sD|OgEdJcGnAwBaB{EuDoAaLcB}J{JqDjCee@wGsD{JoAwB_X?cB{@g@g@kCqSkf@ye@gJkWoi@_]{JgESkHcBkHco@u[{Od@{@e@sIa]{@gJk\\kMkHoF_NgJcG?oAaBoAyGcBoAgESgYvG{@?wB_NcBgO~HoFrI_I~a@_]rNcVzJoAnU_q@nA{@rIsDrDsIwG_Ng@}CjMa]bBcGz@g@nF|@z@i@sDa[vGiYvBoAfJ_Dz@_DgEoKoA_NdBuL`VkWvLmH_Ie@kH?wB|Ce^|TyBx@cL?f@{T{@yEcQyBoFfEoKtDeJPmCoFg@{@gO}Huj@oA}OgOaBeBwQf@}@?mFsIyB_DyE_DaXrDcGrDbBkCvBgE{JsSoKsIqDSuDkHR{@xB?lAbBcBR",
      levels: "P?CFDEADGDHBGIBDCEADCFDECFADFBFGCFCEEBDBCDGBEBFHDEABDFBCCDEBFCEFEDCFFECFGEFFCGEHEDCJFGDEDFGHDFBEGECFCIBEGCEDFFGHEFCGEKFECGEHDEFGCEIFDEFGHGHIFDEFGDFGEFJDFEDGEFDGHFEGEFIDEFBDGDFEFGHBDFDGLEFEGDHGDIDCFGHFGDEDFGDHEFGDBFJFHEFEIFCGKGEHEDFDEGCIEFGHFGICFEGDHJCECFGDHDFEGIFEFDGDHFDGEFGICFHFDGCJDEGEDEMFDGBDEP",
      zoomFactor: 2,
      numLevels: 18
     });
     map.addOverlay(pl);     
  }
  svgOn();
}

function showLocation(endereco, outroEndereco, codigoLoja, nomeLoja, imagem, IDopcao, exibeMensagem, imagemMarcador, valorProducao, codigoCidade, qtdPopulacao, qtdSrvDireto, qtdSrvIndireto, enderecoNaoEncontrado, codigoUPag, nomeUPag, ministerioUPag, percentualCrescUPag) 
{  
  var valorEndereco = enderecoNaoEncontrado == null ? endereco : outroEndereco;
  geocoder.getLatLng(   
     valorEndereco,    
     function(point) {      
                        if (!point) 
                        {      
                            if (enderecoNaoEncontrado == null)
                            {
                               showLocation(endereco, outroEndereco, codigoLoja, nomeLoja, imagem, IDopcao, exibeMensagem, imagemMarcador, valorProducao, codigoCidade, qtdPopulacao, qtdSrvDireto, qtdSrvIndireto, true, codigoUPag, nomeUPag, ministerioUPag, percentualCrescUPag);
                               return false;
                            }
    
                            if (IDopcao)
                               document.getElementById(IDopcao).checked = false;
                                
                            if (exibeMensagem)    
                               ExibirMensagemScript('Endereço não foi localizado.');
                                
                               document.getElementById('txtEndereco').select();
                        } 
                        else 
                        {   
                            _producao = '';
                            _dadosCidade = '';
                            _dadosUPag = '';
                            _editarDadosCidade = '';
                            _divFotografia = '';    

                            if (codigoCidade != null && codigoCidade != '')
                            {
                               _dadosCidade += '<br/><br/><span class="fontePadrao"><b>População:&nbsp;&nbsp;</b>' + qtdPopulacao + '</span>'; 
                               _dadosCidade += '<br/><span class="fontePadrao"><b>Servidores&nbsp;&nbsp;&nbsp;&nbsp;Direto:&nbsp;&nbsp;</b>' + qtdSrvDireto + '</span>'; 
                               _dadosCidade += '&nbsp;&nbsp;&nbsp;&nbsp;<span class="fontePadrao"><b>&nbsp;&nbsp;Indireto:&nbsp;&nbsp;</b>' + qtdSrvIndireto + '</span>'; 
                               _editarDadosCidade = '<a href="javascript:ExibirDadosCidade(' + codigoCidade + ');" style="padding-right:10px" class="fontePadrao">Dados da prefeitura</a>';
                            }
                            if (codigoUPag != null && codigoUPag != '')
                            {
                               _dadosUPag += '<br/><br/><span class="fontePadrao"><b>Servidor Federal - Total:&nbsp;&nbsp;</b>' + qtdSrvDireto + '</span>'; 
                               _dadosUPag += '<br/><span class="fontePadrao"><b>Empréstimos BMG:&nbsp;&nbsp;</b>' + qtdSrvIndireto + '</span>'; 
                               _dadosUPag += '<br/><span class="fontePadrao"><b>Potencial de crescimento:</b>&nbsp;&nbsp;' + percentualCrescUPag + '%</span>'; 
                            }
                                                        
                            icone.iconSize = new GSize(21, 20);
                            icone.shadowSize = new GSize(33, 20);
                            icone.iconAnchor = new GPoint(10, 20);
                            icone.infoWindowAnchor = new GPoint(5, 1);
                            if (imagemMarcador != null && imagemMarcador != '')
                            {
                               icone.image = imagemMarcador;
                            }
                            else
                            {    
                               icone.image = "img/imgMarcadorBMGMapsPadrao.png"
                               icone.shadow = "img/imgSombraMarcadorBMGMapsPadrao.png";
                            }   
                            
                            if (codigoUPag)
                            {
                                imagem = '<img src="' + imagem + '" style="margin-bottom:10px;width:45px;height:45px;">';
                                nomeUPag = '<b>' + codigoUPag + '</b> - ' + nomeUPag;
                            }
                            else if (imagem!= null && imagem != '')                                                               
                                imagem = '<img src="img/' + imagem + '" style="margin-bottom:10px;width:110px;height:81px;">';
                            else
                                imagem = '<img src="img/imgLogotipo.gif" style="margin-bottom:10px;">';
                                
                            // Caso tenha o código da loja concatena com o nome.
                            if (codigoLoja)
                                nomeLoja = codigoLoja + ' - ' + nomeLoja;
                               
                            if (nomeLoja) 
                            {
                                var html = imagem + '<br/><span class="fontePadrao"><b>' + nomeLoja + '</b><br>' + endereco + '</span>' + _dadosCidade + _producao + '<br><br><div style="vertical-align:bottom;float:left">' +_editarDadosCidade + '<a href="javascript:RemoverMarcadorAtual(' + codigoLoja + ');" style="padding-right:10px;"  class="fontePadrao">Excluir marcador</a></div>' + _divFotografia;                               
                            }
                            else if (codigoCidade != null && codigoCidade != '') 
                            {
                                var html = imagem + '<br/><span class="fontePadrao">' + outroEndereco + '</span>' + _dadosCidade + _producao + '<br><br><div style="vertical-align:bottom;float:left">' + _editarDadosCidade + '<a href="javascript:RemoverMarcadorAtual();" style="padding-right:10px;" class="fontePadrao" >Excluir marcador</a></div>' + _divFotografia;
                            }    
                            else if (codigoUPag != null && codigoUPag != '')
                            {
                                var html = imagem + '<br/><span class="fontePadrao">' + nomeUPag + '<br>' + ministerioUPag + '<br><br>' + outroEndereco + '</span>' + _dadosUPag + '<br><br><div style="vertical-align:bottom;float:left"><a href="javascript:RemoverMarcadorAtual();" style="padding-right:10px;" class="fontePadrao" >Excluir marcador</a></div>' + _divFotografia;
                            }
                            else
                            {
                                var html = imagem + '<br/><span class="fontePadrao">' + endereco + '</span>' + _dadosCidade + _producao + '<br><br><div style="vertical-align:bottom;float:left">' + _editarDadosCidade + '<a href="javascript:RemoverMarcadorAtual();" style="padding-right:10px;" class="fontePadrao" >Excluir marcador</a></div>' + _divFotografia;
                            }

                            // Escrevendo o div final
                            html = '<div style="background-color:white; width:300px; height:100%;">' +  html + '</div>';

                            var marker = new GMarker(point, {icon:icone, draggable:true, title:'P:' + point.x + ';' + point.y});
                                
                            // Armazenando os enderecos na hashTable
                            enderecos.put(marker.getTitle(),valorEndereco);
                            
                            GEvent.addListener(marker, "dragstart", function() { map.closeInfoWindow();           });
                            GEvent.addListener(marker, "dragend", function()   { marker.openInfoWindowHtml(html); });
                            
                            map.addOverlay(marker);
                            
                            map.setCenter(point, 14);
                            marker.openInfoWindowHtml(html);
                            
                            if (codigoLoja != null && document.getElementById('grdResultadoPF_linhaResultado' + codigoLoja) != null)
                                document.getElementById('grdResultadoPF_linhaResultado' + codigoLoja).style.backgroundColor = '#ffffcc';

                            marcadorAtual = marker;
                            GEvent.addListener(marker, "click", function() 
                                        { 
                                            if (getStatusRota()) 
                                            {
                                                map.closeInfoWindow();  
	                                            addRoutePoint(point, marker);                                            
	                                        }
	                                        else
	                                        {      
                                                marcadorAtual = this; marker.openInfoWindowHtml(html);  
                                                if (codigoLoja != null && document.getElementById('grdResultadoPF_linhaResultado' + codigoLoja) != null)
                                                    document.getElementById('grdResultadoPF_linhaResultado' + codigoLoja).style.backgroundColor = '#ffffcc';
                                            }
                                            
                                        });
                         }    
                      }  
                );
 }
             
function LimparMarcacoes() 
{  
    clearAll();
    map.clearOverlays();  
    map.setCenter(new GLatLng(-15, -55), 4);
    document.getElementById('txtEndereco').value = '';
    document.getElementById('txtEndereco').focus();
    enderecos.clear();
}

function RemoverMarcadorAtual(codigoLoja) 
{  
    if (marcadorAtual)
    {
        map.closeInfoWindow();
        
        // Removendo o endereco na HashTable
        enderecos.remove(marcadorAtual.getTitle());
         
        map.removeOverlay(marcadorAtual);  
        marcadorAtual = null;
        
        if (codigoLoja != null && document.getElementById('grdResultadoPF_linhaResultado' + codigoLoja) != null)
         document.getElementById('grdResultadoPF_linhaResultado' + codigoLoja).style.backgroundColor = document.getElementById('grdResultadoPF_linhaResultado' + codigoLoja).title;
    }
}

function centralizarMapa()
{
   map.setCenter(new GLatLng(-15, -55), 4);
}


function AjustarFiltro(acao)
{
   if (acao == 1)
   { 
          document.getElementById('ladofiltro').style.width = 0;
          document.getElementById('filtro').style.width = 0;
          document.getElementById('map').style.width = document.getElementById('tabFiltros').offsetWidth;
          map.checkResize();
   }
   else
   {
          document.getElementById('ladofiltro').style.width = '100%';
          document.getElementById('filtro').style.width = '100%';
          document.getElementById('map').style.width = '650px';
          map.checkResize();
   }
}

function ExibirDadosCidade(codigoCidade)
{
    var x = (screen.width - 650)/2;
    var y = (screen.height - 400)/2 - 100; 
    _janela = window.open('BNMapExibirDadosLoja.aspx?ID=' + codigoCidade,'','width=650,toolbar=no,resizable=no,location=no, status=no, scrollbars=no, height=400, top=' + y + ',left = ' + x);
}


function adicionarControleEstados()
{
     var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, 'Estados');
     var copyrights = new GCopyrightCollection('Banco BMG - Mapa dos estados');
     copyrights.addCopyright(copyright);
     var tilelayer = new GTileLayer(copyrights, 0, 17);
     tilelayer.getTileUrl = function(tile, zoom) { 
        return 'http://maps.forum.nu/cgi-bin/getTiles.pl?t=counties&x='+tile.x+'&y='+tile.y+'&z='+zoom;
     };
     var CUSTOM_MAP = new GMapType( [tilelayer], new GMercatorProjection(20), "Estados" );
     map.addMapType(CUSTOM_MAP);
}

function iniciarRota(btnRota)
{
    if (btnRota.innerHTML == "<B>Iniciar rota</B>")
    {
       btnRota.innerHTML = "<B>Finalizar</B>";   
       inicializarDadosRota();
     }
     else
     {
        addClosing();
        btnRota.innerHTML =  "<B>Iniciar rota</B>";           
     }
}

function getStatusRota()
{
   return document.getElementById('btnRota').innerHTML != "<B>Iniciar rota</B>";   
}

function addRoutePoint(point, marker) 
{

    if (marker != null)
    {
        if(tipoRota == 1)
        {
    	    var dist = 0;

    	    if (!routePoints[lineIx]) 
    	    {
    		    routePoints[lineIx] = Array();
    		    routeMarkers[lineIx] = Array();
    	    }

    	    routePoints[lineIx].push(marker.getPoint());
    	    if (routePoints[lineIx].length > 1)
            {
                plotRoute();
                markerFimRota = marker;    	
    		    dist = routePoints[lineIx][routePoints[lineIx].length-2].distanceFrom(point) / 1000;
    		    totalDistance += dist;
    		    document.getElementById("dist").innerHTML =  totalDistance.toFixed(3) + ' km';
    	    }
    	    else 
    	    {
    		    routeMarkers[lineIx][routePoints[lineIx].length-1] = marker;
    		    inicializarMarcadorRota(marker);
    		    markerInicioRota = marker;
    	    }
        }
        else
        {
            if (enderecoInicioRota == '')
            {
    		    inicializarMarcadorRota(marker);
    		    markerInicioRota = marker;
    		    enderecoInicioRota = enderecos.get(marker.getTitle()); 
            }
            else
            {
                markerFimRota = marker;    	
                enderecoFinalRota = enderecos.get(marker.getTitle()); 
                getRoute();
            }
        
        }
    }
}

function getMapcenter() 
{
	var center = map.getCenter();
	var z = map.getZoom();
}

function plotRoute() 
{
    if(routeOverlays[lineIx])
	    map.removeOverlay(routeOverlays[lineIx]);
	routeOverlays[lineIx] = new GPolyline(routePoints[lineIx],'#C602C8',3,1);
	map.addOverlay(routeOverlays[lineIx]);
}

function clearAll()
 {
    if (routePoints[lineIx] != null)
    { 
        if (routePoints[lineIx].length > 1)	
	        lineIx++;

        while (lineIx > 0) 
	        resetRoute();
    }

	for (var n = 0 ; n < polylines.length ; n++ )
	    map.removeOverlay(polylines[n]);
    
    enderecoInicioRota = '';
    enderecoFinalRota = ''; 
    detalhesRota = '';        
    	
    totalDistance = 0;
    document.getElementById("dist").innerHTML = '0.000 km';
    btnRota.innerHTML =  "<B>Iniciar rota</B>";           
    finalizarMarcadoresRota();
    
    routePoints   = new Array();
    routeMarkers  = new Array();
    routeOverlays = new Array();
    lineIx = 0;
}


function resetRoute()
 {
	if (!routePoints[lineIx] || routePoints[lineIx].length == 0)
		lineIx--;
	
	routePoints[lineIx] = null;
	map.removeOverlay(routeOverlays[lineIx]);

	routeMarkers[lineIx] = null;
	
}

function undoPoint() 
{

    if (tipoRota == 1)
    {
        if ( routePoints[lineIx] != null)
        {
            if (!routePoints[lineIx] || routePoints[lineIx].length == 0) 
	            lineIx--;

            if (routePoints[lineIx].length > 1)	{

	            var dist = routePoints[lineIx][routePoints[lineIx].length-2].distanceFrom(routePoints[lineIx][routePoints[lineIx].length-1]) / 1000;
	            totalDistance -= dist;
	            if (totalDistance < 0) 
	                document.getElementById("dist").innerHTML = '0 km';
	            else
	                document.getElementById("dist").innerHTML =  totalDistance.toFixed(3) + ' km';

	            routePoints[lineIx].pop();
	            plotRoute();
            }
            else 
            {
	            resetRoute();	
                finalizarMarcadoresRota();
            }
      }
   }
   else
    ExibirMensagemScript('Opção habilitada somente para o tipo "Ponto a ponto".');
}

function addClosing()
 {
    if (((tipoRota ==1 && routePoints[lineIx] != null && routePoints.length > 0 && routePoints[lineIx].length > 1) || (tipoRota == 2)) && document.getElementById("btnRota").innerHTML == "<B>Finalizar</B>" )	
    {
        finalizarMarcadorRota(markerFimRota);
        
        if (tipoRota == 2)
            ExibirDetalhesRota();
    }
}

function DEC2DMS(dec) {

	var deg = Math.floor(Math.abs(dec));
	var min = Math.floor((Math.abs(dec)-deg)*60);
	var sec = (Math.round((((Math.abs(dec) - deg) - (min/60)) * 60 * 60) * 100) / 100 ) ;

	deg = dec < 0 ? deg * -1 : deg;

	var dms  = deg + '&deg ' + min + '\' ' + sec + '"';
	return dms;
}


function encodePolyline() {
	var encodedPoints = '';
	var	encodedLevels = '';

	var plat = 0;
	var plng = 0;

	for (var n = 0 ; n < routePoints[lineIx].length ; n++ ) {
		var lat = routePoints[lineIx][n].y.toFixed(8);
		var lng = routePoints[lineIx][n].x.toFixed(8);

		var level = (n == 0 || n == routePoints[lineIx].length-1) ? 3 : 1;
		var level = 0;

		var late5 = Math.floor(lat * 1e5);
		var lnge5 = Math.floor(lng * 1e5);

		dlat = late5 - plat;
		dlng = lnge5 - plng;

		plat = late5;
		plng = lnge5;

		encodedPoints += encodeSignedNumber(dlat) + encodeSignedNumber(dlng);
		encodedLevels += encodeNumber(level);
	}

	var html = '';
	html += 'new GPolyline.fromEncoded({\n';
	html += '  color: "#0000ff",\n';
	html += '  weight: 4,\n';
	html += '  opacity: 0.8,\n';
	html += '  points: "'+encodedPoints+'",\n';
	html += '  levels: "'+encodedLevels+'",\n';
	html += '  zoomFactor: 16,\n';
	html += '  numLevels: 4\n';
	html += '});\n';

	return html;
}

function encodeSignedNumber(num) {
	var sgn_num = num << 1;

	if (num < 0) {
		sgn_num = ~(sgn_num);
	}

	return(encodeNumber(sgn_num));
}

function encodeNumber(num) {
	var encodeString = "";

	while (num >= 0x20) {
		encodeString += (String.fromCharCode((0x20 | (num & 0x1f)) + 63));
		num >>= 5;
	}

	encodeString += (String.fromCharCode(num + 63));
	return encodeString;
}

function inicializarMarcadorRota(marker)
{
    if (marker != null)   
    {
        if(marker.getIcon().image == 'img/imgMarcadorBMGMaps.gif')
        {
	        marker.setImage('img/imgMarcadorBMGMapsStart.gif');
    		marker.getIcon().image = 'img/imgMarcadorBMGMapsStart.gif';
        }
    	else if (marker.getIcon().image == 'img/imgMarcadorBMGMapsPadrao.png')
    	{
	        marker.setImage('img/imgMarcadorBMGMapsPadraoStart.png');
    		marker.getIcon().image = 'img/imgMarcadorBMGMapsPadraoStart.png';  	
    	}
	}	   
}

function finalizarMarcadorRota(marker)
{
    if (marker)   
    {
        if(marker.getIcon().image == 'img/imgMarcadorBMGMaps.gif' || marker.getIcon().image == 'img/imgMarcadorBMGMapsStart.gif')
        {
	        marker.setImage('img/imgMarcadorBMGMapsEnd.gif');
    		marker.getIcon().image = 'img/imgMarcadorBMGMapsEnd.gif';
        }
    	else if (marker.getIcon().image == 'img/imgMarcadorBMGMapsPadrao.png' || marker.getIcon().image == 'img/imgMarcadorBMGMapsPadraoStart.png')
    	{
	        marker.setImage('img/imgMarcadorBMGMapsPadraoEnd.png');
    		marker.getIcon().image = 'img/imgMarcadorBMGMapsPadraoEnd.png';  	
    	}
	}	   
}

function finalizarMarcadoresRota()
{
    if (markerInicioRota)   
    {
        if(markerInicioRota.getIcon().image == 'img/imgMarcadorBMGMapsStart.gif' || markerInicioRota.getIcon().image == 'img/imgMarcadorBMGMapsEnd.gif')
        {
	        markerInicioRota.setImage('img/imgMarcadorBMGMaps.gif');
    		markerInicioRota.getIcon().image = 'img/imgMarcadorBMGMaps.gif';
    		
    		if(markerFimRota)
    		{
    		    markerFimRota.setImage('img/imgMarcadorBMGMaps.gif');
    		    markerFimRota.getIcon().image = 'img/imgMarcadorBMGMaps.gif';
    		}
	    }
	    else if(markerInicioRota.getIcon().image == 'img/imgMarcadorBMGMapsPadraoStart.png' || markerInicioRota.getIcon().image == 'img/imgMarcadorBMGMapsPadraoEnd.png')
        {
	        markerInicioRota.setImage('img/imgMarcadorBMGMapsPadrao.png');
    		markerInicioRota.getIcon().image = 'img/imgMarcadorBMGMapsPadrao.png';
    		
    		if (markerFimRota)
    		{
    		    markerFimRota.setImage('img/imgMarcadorBMGMapsPadrao.png');
    		    markerFimRota.getIcon().image = 'img/imgMarcadorBMGMapsPadrao.png';        
    		}
        }
	}	   
}

function inicializarDadosRota()
{
   totalDistance = 0.0;
   markerInicioRota = null;
   markerFimRota = null;
}

function alterarTipoRota()
{
    enderecoInicioRota = '';
    enderecoFinalRota = '';   
    detalhesRota = '';      
    totalDistance = 0;
    finalizarMarcadoresRota();
   
    inicializarDadosRota();
    btnRota.innerHTML = "<B>Iniciar rota</B>";        
    tipoRota = document.getElementById('btnSelTipoRotaPonto').checked ? 1 : 2;
    document.getElementById("dist").innerHTML = "0.000 km";
}

function getRoute() 
{
    if (enderecoInicioRota != '' && enderecoFinalRota != '' && enderecoInicioRota != enderecoFinalRota)
	{   
	    indicarCarregando();
	    
	    var URL = 'BNTunel.aspx?' + 'http://maps.google.com.br/maps?saddr=' + encodeURI(enderecoInicioRota) + '&daddr=' + encodeURI(enderecoFinalRota) + '&output=kml';
	    	  
	    GDownloadUrl(URL, loadKML);
	}
}

function loadKML(doc) 
{

	var xmlDoc = GXml.parse(doc);
    if (GXml.value(xmlDoc) != '')
    {
	    var bounds =  new GLatLngBounds();
	    var pointCount = 0;
	    var pointCountU = 0;
    	
	    var placemarks = xmlDoc.documentElement.getElementsByTagName("Placemark");
	    var routeName = GXml.value(xmlDoc.documentElement.getElementsByTagName("name")[0]);
	    var desc = GXml.value(placemarks[placemarks.length-1].getElementsByTagName("description")[0]);
	    desc = desc.replace(/Map data.+/,"");
	    desc = desc.replace(/\(.+/,"");

        var html = detalhesRota == null || detalhesRota == '' ? '<div id="divDetalheRota" >' : '<br /><div >';
        html += '<input type="hidden" id="hdNomeRota" value="' + routeName + '" />';
	    html += '<div style="display:block;">';
	    html += '<table width="100%" cellspacing="1" cellpadding="1" class="FontePadrao" style="background-color:#999999">';

        // DETALHES DA ROTA
	    for (var i = 0; i < placemarks.length-1; i++) 
	    {
		    var name = GXml.value(placemarks[i].getElementsByTagName("name")[0]);
		    var desc = GXml.value(placemarks[i].getElementsByTagName("description")[0]);
		    var coords = GXml.value(placemarks[i].getElementsByTagName("coordinates")[0]);
		    var path = coords.split(" ");
		    var bits = path[0].split(",");
		    var point =  new GLatLng(parseFloat(bits[1]), parseFloat(bits[0]));
		    bounds.extend(point);
		    junctionPoints.push(point);
		    html += '<tr style="background-color:whitesmoke; height:20px;"><td style="font-weight:bold; text-align:center ">' + (i + 1) + '</td><td style="padding-left:10px">' + name + '</td><td style="text-align:center;width:100px ">' + desc + '</td></tr>';
 	    }
    	
	    html += '</table></div></div>';
        
        detalhesRota += html;
        
	    var GeometryCollection = xmlDoc.documentElement.getElementsByTagName("GeometryCollection")[0];
	    var LineStrings = GeometryCollection.getElementsByTagName("LineString");
	    pLinePoints[pLinePoints.length] = Array();
	    var lastlatlon = new GLatLng(0,0);
	    for (var l = 0; l < LineStrings.length; l++) 
	    {
		    var coords = GXml.value(LineStrings[l].getElementsByTagName("coordinates")[0]);
		    var path = coords.split(" ");
		    for (var p = 0; p < path.length - 1; p++) 
		    {
			    var bits = path[p].split(',');
			    var latlon = new GLatLng(bits[1],bits[0]);

			    var dist = 0;
			    if ( p > 0 ) 
			        dist = latlon.distanceFrom(lastlatlon) / 1000;
			    
		        pLinePoints[pLinePoints.length - 1].push(latlon);
		        lastlatlon = latlon;
		        pointCountU++;
			    pointCount++;
			
    		    totalDistance += dist;
		    }
	    }

        document.getElementById("dist").innerHTML =  totalDistance.toFixed(3) + ' km';
	    window.setTimeout("drawPolylines()",1000);	
	    enderecoInicioRota = enderecoFinalRota;
	}
	else
	   ExibirMensagemScript('Não foi possível encontrar a rota!\n\nVerifique se o endereço de origem ou destino estão inválidos.') 

	loading = false;		
}

function drawPolylines() 
{
	if (pLinePoints.length) 
	{
		var points = pLinePoints.shift();
		polylines.push(new GPolyline(points,  '#ff0000',  4,  0.8));
		map.addOverlay(polylines[polylines.length-1]);
		window.setTimeout("drawPolylines()",10);
	}
}

function indicarCarregando() 
{
	loading = true;
	document.getElementById('divCarregando').style.left = ((document.getElementById('map').offsetWidth / 2) -  120) + (document.getElementById('tabFiltros').offsetWidth - document.getElementById('map').offsetWidth) + 'px';
	mostrarMensagemCarregando();
}

function mostrarMensagemCarregando()
{
	var oLMsg = document.getElementById('divCarregando');
	oLMsg.style.display = '';
	oLMsg.style.filter="alpha(opacity=70)";

	if (loading){
		var to = window.setTimeout('mostrarMensagemCarregando()',100);
	}
	else {
		oLMsg.style.display = 'none';
	}
}

function svgOn() 
{
  if(document.implementation.hasFeature(
   "http://www.w3.org/TR/SVG11/feature#SVG","1.1"))
   { 
     _mSvgEnabled = true;
     _mSvgForced  = true;
   }
}

function ExibirFotografia(url)
{   
  document.getElementById('iframeGaleriaFotos').src = url;
  document.getElementById('iframeGaleriaFotos').style.display = 'block';
  CentralizarJanelaFotografia();  
}

function CentralizarJanelaFotografia()
{
   document.getElementById('iframeGaleriaFotos').style.left = (document.getElementById('tabFiltros').offsetWidth / 2)  - (document.getElementById('iframeGaleriaFotos').offsetWidth /2) + 'px';
   document.getElementById('iframeGaleriaFotos').style.top = (window.screen.height / 2)  - (document.getElementById('iframeGaleriaFotos').offsetHeight /2) - 45 + 'px';   
}

function FecharFotografia()
{ 
  document.getElementById('iframeGaleriaFotos').src = '';
  document.getElementById('iframeGaleriaFotos').style.display = 'none';
}

function ExibirDetalhesRota()
{   
  var hd = document.getElementById('divInfoDetalhesRota');
  if(hd)
  {
      if (detalhesRota != '') 
        document.getElementById('divInfoDetalhesRota').innerHTML = detalhesRota;
      else
        document.getElementById('divInfoDetalhesRota').innerHTML = 'Nenhuma rota criada até o momento.';
  }
}

function CalcularFinalBarraLayout(qtdeAbas)
{
    var total = 0;
    for (var cont = 1; cont <= qtdeAbas; cont+=1)
    {
        if (document.getElementById('aba' + cont) != null ) 
                total += document.getElementById('aba' + cont).offsetWidth;
    }  
    return total;     
}

function ExibirJanelaEnvioEmailRota()
{
    window.showModalDialog('BNMapEnviarRotaEmail.aspx',self,'scroll:no;center:yes;help:no;resizable:no;dialogHeight:370px;dialogWidth:500px;status:no'); 
}

function carregarDescricaoRotasEmail()
{
    var descricaoRota = '';
    if (window.dialogArguments) 
        window.opener = window.dialogArguments;

    for (var cont = 0; cont <= window.opener.document.getElementById('divInfoDetalhesRota').childNodes.length - 1; cont += 1)
    {
        if (window.opener.document.getElementById('divInfoDetalhesRota').childNodes[cont].innerHTML != '')
        {
            descricaoRota = window.opener.document.getElementById('divInfoDetalhesRota').childNodes[cont].childNodes[0].value;
            document.getElementById('divNomeRotas').innerHTML += '<input type="checkbox" class="fontePadrao" id="chk_' + cont + '" checked />&nbsp;' + descricaoRota + '<br />';
        }
    }  
}

function AtualizarRotasSelecionadasEmail()
{
  var flag = false;
  
  document.getElementById('hdValorHtml').value = '';
  if (window.dialogArguments) 
      window.opener = window.dialogArguments;
    
  for (var cont = 0; cont <= window.opener.document.getElementById('divInfoDetalhesRota').childNodes.length - 1; cont += 1)
    {
        if(document.getElementById('chk_' + cont) && document.getElementById('chk_' + cont).checked)
        {
            document.getElementById('hdValorHtml').value += window.opener.document.getElementById('divInfoDetalhesRota').childNodes[cont].childNodes[1].innerHTML + window.opener.document.getElementById('divInfoDetalhesRota').childNodes[cont].childNodes[2].innerHTML + ' <br /> ';
            flag = true;
        }
    }  
  document.getElementById('hdValorHtml').value = document.getElementById('hdValorHtml').value.replace(/</g,'#%');
  document.getElementById('hdValorHtml').value = document.getElementById('hdValorHtml').value.replace(/>/g,'%#');
  return flag;
}

function ExibirCatalogoEnderecosBMGMaps()
{
   var enderecos = window.showModalDialog('BNMapCatalogoEnderecos.aspx',self,'scroll:no;center:yes;help:no;resizable:no;dialogHeight:400px;dialogWidth:700px;status:no'); 
   document.getElementById('txtDestinatarios').value += enderecos;
   document.getElementById('txtAssunto').focus();   
}

