
function setDirections(fromAddress, toAddress) {
    map.closeInfoWindow();
    rotax = null ;
    showSumario = null;
    gdir.load("from: " + fromAddress + " to: " + toAddress,   { "locale": "pt" , "getSteps": true});
 }

//-----------------------------------------------------------------------------------------
//  
//----------------------------------------------------------------------------------------               
    
 function setDirectionsPontos(xOrigem, yOrigem, xDestino, yDestino) {
     
      var vPointDestino = yDestino + ', ' +  xDestino ;
      setDirections(yOrigem + "," + xOrigem , yDestino + "," + xDestino);
    }
//-----------------------------------------------------------------------------------------
//  handleErrors()
//----------------------------------------------------------------------------------------               
    
    function handleErrors(){
        alert("Problemas de comunica誽o (" + gdir.getStatus().code + ").");
	}

//-----------------------------------------------------------------------------------------
//  
//----------------------------------------------------------------------------------------               
    
	function onAddOverlayRota(){ 
          rotax = gdir.getRoute(0);
          var vTot = rotax.getNumSteps();
          
          var  vCab = '<table ';
			vCab +=      'style="margin-top: 10px; margin-right: 0px; margin-bottom: 10px; margin-left: 0px; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: silver; border-right-color: silver; border-bottom-color: silver; border-left-color: silver; background-color: rgb(238, 238, 238); border-collapse: collapse; color: rgb(0, 0, 0); width: 100%;">';
						
			vCab += 	 '<tr>';
			vCab +=			'<td style="vertical-align: middle;width:20px;padding: 4px 15px 0px 5px">';
			vCab +=		        '<img src="' +  iurl('icones/') + 'dd-start.png">';				
			vCab +=			'</td>';
			vCab +=			'<td style="vertical-align: middle;width: 100%">';
		    vCab +=			vParEndOrigem	;			
			vCab +=		'</td>';
			vCab +=	'</tr>';
			vCab +=  '</table>';
          
          var vAux = vCab;
          vAux  += '<table 	style="border-collapse: collapse; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; width: 100%;">';
          var pos = 0;
          for ( i = 0; i < vTot ; i = i + 1 ) {
            var step = rotax.getStep(i);
            pos = i;
            vAux = vAux + '<tr> <td style="vertical-align:top;border-top: 1px solid #cdcdcd;padding:0.3em 3px 0.3em 3px;margin: 0px;text-align:right;"> ' +  pos + '</td> <td style="vertical-align:top;border-top: 1px solid #cdcdcd;padding:0.3em 3px 0.3em 3px;margin: 0px;width:100%;"> ' +  step.getDescriptionHtml() + '</td> <td> ' + step.getDistance().html +  '</td> </tr>' ;
          
          }
           vAux = vAux + '</table>' ;
            vCab = '<table '
			vCab +=      'style="margin-top: 10px; margin-right: 0px; margin-bottom: 10px; margin-left: 0px; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: silver; border-right-color: silver; border-bottom-color: silver; border-left-color: silver; background-color: rgb(238, 238, 238); border-collapse: collapse; color: rgb(0, 0, 0); width: 100%;">';
						
			vCab += 	 '<tr>';
			vCab +=			'<td style="vertical-align: middle;width:20px;padding: 4px 15px 0px 5px">';
			vCab +=		       '<img src="' +  iurl('icones/') + 'dd-end.png ">';		
			vCab +=			'</td>';
			vCab +=			'<td style="vertical-align: middle;width: 100%">';
		    vCab +=			vParEndDestino	;			
			vCab +=		'</td>';
			vCab +=	'</tr>';
			vCab +=  '</table>';
		    vAux = vAux + vCab; 
        
        var xHtml = getElementHTML('directions');
       
        setElementHTML('directions', vAux);
        $('directions').style.display = '';
     	}


//-----------------------------------------------------------------------------------------
//  tirarAcentos(texto)
//----------------------------------------------------------------------------------------               
    
function tirarAcentos(texto) {
    String.prototype.replaceAll=function(s1, s2) {return this.split(s1).join(s2)}
	var aLetraComAcento = new Array("\xc1", "\xcd", "\xd3", "\xda", "\xc9", "\xc4", "\xcf", "\xd6", "\xdc", "\xcb", "\xc0", "\xcc", "\xd2", "\xd9", "\xc8", "\xc3", "\xd5", "\xc2", "\xce", "\xd4", "\xdb", "\xca", "\xe1", "\xed", "\xf3", "\xfa", "\xe9", "\xe4", "\xef", "\xf6", "\xfc", "\xeb", "\xe0", "\xec", "\xf2", "\xf9", "\xe8", "\xe3", "\xf5", "\xe2", "\xee", "\xf4", "\xfb", "\xea", "\xc7", "\xe7");
	var aLetraSemAcento = new Array("A", "I", "O", "U", "E", "A", "I", "O", "U", "E", "A", "I", "O", "U", "E", "A", "O", "A", "I", "O", "U", "E", "a", "i", "o", "u", "e", "a", "i", "o", "u", "e", "a", "i", "o", "u", "e", "a", "o", "a", "i", "o", "u", "e", "C", "c");
	var sResultado;
	 sResultado = texto
	for (var i = 0; i < aLetraComAcento.length; i = i + 1) {
	  sResultado =  sResultado.split(aLetraComAcento[i]).join(aLetraSemAcento[i]);
	}         
	return sResultado;
}    
               
//-----------------------------------------------------------------------------------------
//  limpaResultados()
//-----------------------------------------------------------------------------------------
function limpaResultados() {
    resultsPage = 0;
 	setElementHTML("div_resultados", "");
	setElementHTML("total_locais", "");
	setElementHTML("lista_paginas", "");
}
             
//-----------------------------------------------------------------------------------------
//  limpaComboCategorias()
//-----------------------------------------------------------------------------------------
function limpaComboCategorias() {
	limpaResultados();
	var selectCategorias = $("combo_categorias");
	selectCategorias.options.length = 0;
	selectCategorias.options[0] = new Option(" Aguarde... ", "-1");
	categoriaAtual = -1;
}   
//-----------------------------------------------------------------------------------------
// limpaComboCanais()
//-----------------------------------------------------------------------------------------
function limpaComboCanais() {
	limpaResultados();
	var sel = $("combo_canal");
	sel.options.length = 0;
	sel.options[0] = new Option(" Aguarde... ", "-1");
	canalAtual = -1;
}
//-----------------------------------------------------------------------------------------
// montaComboCanais(vDados)
//-----------------------------------------------------------------------------------------
function montaComboCanais(vDados) {
	var selectCanais = $("combo_canal");
	selectCanais.options.length = 0;
	selectCanais.options[0] = new Option("-- Selecione --", "-1");  
                // alert('montaComboCanais ' + vDados.length );
	if (vDados.length > 0) {
		for (i = 0; i < vDados.length; i++) {
			selectCanais.options[i + 1] = new Option(vDados[i].nome, vDados[i].id);
		}//for
	} //if  
}     
//-----------------------------------------------------------------------------------------
// doExecCompoPesquisa()
//-----------------------------------------------------------------------------------------
function doExecCompoPesquisa(){
  var selectPesquisa = $("comboPesquisa");
  vIndicePesquisa = selectPesquisa.options[selectPesquisa.selectedIndex].value;
}

//-----------------------------------------------------------------------------------------
// showDialogEnd(id, vHtml)
//-----------------------------------------------------------------------------------------
 function showDialogEnd(vHtml) { 
  	Dialog.alert(vHtml, {className: "alphacube",  width:400, cancelLabel:"Cancelar",  okLabel: "ok", ok: closeAllModalWindows})
  } 
//-----------------------------------------------------------------------------------------
// closeAllModalWindows() 
//-----------------------------------------------------------------------------------------
   function closeAllModalWindows() {
      var pt  = vDadosPesquisa[vIndicePesquisa];   
      pontoUsuario = criaMarcaUsuario(pt);
      gravaPtUsuarioCookie(pt);
	  map.addOverlay(pontoUsuario);
	  center = new GLatLng(parseFloat(vDadosPesquisa[vIndicePesquisa].latitude), parseFloat(vDadosPesquisa[vIndicePesquisa].longitude));
	  map.setCenter(center, 15);	 
      Windows.closeAllModalWindows();
    return true;
  }    
     
//-----------------------------------------------------------------------------------------
//  execAjaxRota()
//-----------------------------------------------------------------------------------------
function execAjaxRota(){
     startLoadingAnimation(); 
	if ( pontoPesquisaRota !== null){     
      var selectTipo = $("sel_rota_tipo");
      var vOpcao  = selectTipo.options[selectTipo.selectedIndex].value;     
      xDestino =  vRotaPontoDestino.x;
      yDestino = vRotaPontoDestino.y;
      xOrigem =  pontoPesquisaRota.x;
      yOrigem =  pontoPesquisaRota.y;
      vParEndOrigem = vEndOrigem;
      vParEndDestino = vEndDestino;
      if ( vOpcao == 2 ){
          xDestino =  pontoPesquisaRota.x
         yDestino =   pontoPesquisaRota.y;
         xOrigem =  vRotaPontoDestino.x;
         yOrigem =  vRotaPontoDestino.y; 
         vParEndOrigem = vEndDestino ;
         vParEndDestino = vEndOrigem;
      }
     setElementHTML('directions','');
	 setDirectionsPontos(xOrigem, yOrigem, xDestino,  yDestino);
   }
}


//-----------------------------------------------------------------------------------------
// showDialogRota(id, vHtml)
//-----------------------------------------------------------------------------------------
 function showDialogRota(vHtml) {
  	Dialog.alert(vHtml, {className: "alphacube",  width:400, cancelLabel:"Cancelar",  okLabel: "ok", ok: closeWindowRota});
  } 
//-----------------------------------------------------------------------------------------
// closeAllModalWindows() 
//-----------------------------------------------------------------------------------------
   function closeWindowRota() {
     pontoPesquisaRota = new GPoint( parseFloat(vDadosPesquisa[vIndicePesquisa].longitude), parseFloat(vDadosPesquisa[vIndicePesquisa].latitude));	  
     vEndOrigem =  vDadosPesquisa[vIndicePesquisa].rua + ', ' +  vDadosPesquisa[vIndicePesquisa].bairro;
     Windows.closeAllModalWindows();   
     execAjaxRota();
     return true;
  }        
//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------
function achaEnderecoRota(response) {
      stopLoadingAnimation();
      if (!response || response.Status.code != 200) {
        pontoPesquisaRota = null;
       var vInputOrigem = document.getElementById('fname');
  	    var vEnd =  vInputOrigem.value;
        alert("Endere蔞 : " + vEnd + ', n緌 encontrado !');
        pontoPesquisaRota = null;
		handleMapChange();
      } else {
  	    vIndicePesquisa = 0;
	    vDadosPesquisa = montaVetDadosPesquisa(response.Placemark);
	     var vTotal = vDadosPesquisa.length;
	    if (vTotal > 1){
	      var vHtml = '<table><tr><td>Foram encontrados mais de um resultado.<br>Selecione um dos itens abaixo:</td></tr><tr><td valign="middle"><select  id="comboPesquisa" onchange="doExecCompoPesquisa(); return false;">';
	      for (i = 0; i < vTotal; i = i + 1){
	        vHtml = vHtml + '<option value='+ i + '>' + vDadosPesquisa[i].rua + ', '  +  vDadosPesquisa[i].bairro +', ' + vDadosPesquisa[i].cidade + '</option>';    
	      }
	      vHtml = vHtml +'</select><tr><td></table>';
          showDialogRota( vHtml);  
        }else{
  		 pontoPesquisaRota = point = new GPoint( parseFloat(vDadosPesquisa[0].longitude), parseFloat(vDadosPesquisa[0].latitude));
 		 vEndOrigem =  vDadosPesquisa[0].rua + ', ' +  vDadosPesquisa[0].bairro;
  		 execAjaxRota();
	    }
      }   
}

//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------
function doBuscaRota() {  
    startLoadingAnimation();
    var vInputOrigem = $('fname');
  	var vEnd =  vInputOrigem.value;
	vEnd = tirarAcentos(vEnd);
	if (geocoder) {
       vEnd =  vEnd + ", " +  vCidPesquisa;
        geocoder.getLocations(vEnd, achaEnderecoRota);
    }
}      
//-----------------------------------------------------------------------------------------
// mostraPontoUsuario()
//-----------------------------------------------------------------------------------------
function mostraPontoUsuario() {	
}               
               
//-----------------------------------------------------------------------------------------
// handleEnderecoErro(req) 
//-----------------------------------------------------------------------------------------
function handleEnderecoErro(req) {
    stopLoadingAnimation();
	alert("Erro de Comuni\xe7\xe3o de rede, Tente novamente");
                  //displayLocateMsg('Estamos sem condi覺es momentaneamente de realizar buscas.', true);
}

//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------
function getObjectResultPesuisa(place){
  
    var pt = new Object();
        pt.longitude =  place.Point.coordinates[0];
        pt.latitude = place.Point.coordinates[1];
        pt.nome = place.address;
        pt.nome = pt.nome.replace(', Brazil', '');
        var temp = place.address.split(',');
        pt.rua = temp[0];
        pt.bairro = temp[1];
        pt.cidade = temp[2];
        pt.estado = temp[3];
    return  pt;
}
//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------
function montaVetDadosPesquisa(vetIn){ 
  var vRet = new Array();
  for ( i = 0 ; i < vetIn.length; i++) {
    vRet[i] = getObjectResultPesuisa(vetIn[i]);
  }
  return vRet;
}
//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------
function addAddressToMap(response) {
      stopLoadingAnimation();
      if (!response || response.Status.code != 200) {
        var vInput = $("campo_endereco");
	    var vEnd = vInput.value;
        alert("Endere蔞 : " + vEnd + ', n緌 encontrado !');
        pontoUsuario = null;
		handleMapChange();
      } else {
  	    vIndicePesquisa = 0; 
	    vDadosPesquisa = montaVetDadosPesquisa(response.Placemark);
	     var vTotal = vDadosPesquisa.length;
	    if (vTotal > 1){
	      var vHtml = '<table><tr><td>Foram encontrados mais de um resultado.<br>Selecione um dos itens abaixo:</td></tr><tr><td valign="middle"><select  id="comboPesquisa" onchange="doExecCompoPesquisa(); return false;">';
	      for (i = 0; i < vTotal; i = i + 1){
	       // alert('vDadosPesquisa[i].rua = '+ vDadosPesquisa[i].nome);
	        vHtml = vHtml + '<option value='+ i + '>' + vDadosPesquisa[i].rua + ', '  +  vDadosPesquisa[i].bairro +', ' + vDadosPesquisa[i].cidade + '</option>';    
	      }
	      vHtml = vHtml +'</select><tr><td></table>';
          showDialogEnd( vHtml);
        }else{
  		  var pt  = vDadosPesquisa[0];
  		  pontoUsuario = criaMarcaUsuario(pt);
	      map.addOverlay(pontoUsuario);
  		  gravaPtUsuarioCookie(pt);
  		  
		  center = new GLatLng(parseFloat(pt.latitude), parseFloat(pt.longitude));
	      map.setCenter(center, 15);
	    }
      }   
}

//-----------------------------------------------------------------------------------------
// doBuscaCanais()()
// 
//-----------------------------------------------------------------------------------------
function showAddress(address) {  
      if (geocoder) {
        address =  address + ", " +  vCidPesquisa;
        geocoder.getLocations(address, addAddressToMap);
      }
    }
//-----------------------------------------------------------------------------------------
// doBuscaCanais()
// 
//-----------------------------------------------------------------------------------------
function doBuscaPesquisa(pEndInicial) {  
    startLoadingAnimation();
    limparRota();
   if (pontoUsuario !== null) { 
      map.removeOverlay(pontoUsuario);
      pontoUsuario = null;   
    }
    if ( pEndInicial == null ){
	  var vInput = $("campo_endereco");
	  var vEnd = vInput.value;
	}else{
	   var vEnd = pEndInicial;
	}
	vEnd = tirarAcentos(vEnd);	
	showAddress(vEnd);	
}
               
//-----------------------------------------------------------------------------------------
// doExecPesquisa()
//
//-----------------------------------------------------------------------------------------
function doExecPesquisa() {
	doBuscaPesquisa();
}
    
//-----------------------------------------------------------------------------------------
// handleCanaisResponse(results)
//-----------------------------------------------------------------------------------------
function handleCanaisResponse(results) {
    stopLoadingAnimation();
	results = JSON.parse(results.responseText);
	var selectCanais = $("combo_canal");
	selectCanais.options.length = 0;
	selectCanais.options[0] = new Option("-- Selecione --", "-1");
	var selectCategorias = $("combo_categorias");
	selectCategorias.options.length = 0;
	selectCategorias.options[0] = new Option("-- Selecione --", "-1");
	if (!results["success"]) {
		return;
	}
	canalAtual = -1;
	vAgenciasVW = results["vw"];
	vCidPesquisa = results["normalized_location"];
	var center = new GLatLng(parseFloat(results["latitude"]), parseFloat(results["longitude"]));
	if (results["zoom"] == map.getZoom()) {
		map.panTo(center);
	} else {
		map.setCenter(center, results["zoom"]);
	}
	var vDados = results["result"]["canais"];
	montaComboCanais(vDados);
}              
//-----------------------------------------------------------------------------------------
// handleCanaisErro(req)
//-----------------------------------------------------------------------------------------
function handleCanaisErro(req) {
    stopLoadingAnimation();
	var sel = $("combo_canal");
	sel.options.length = 0;
	sel.options[0] = new Option("-- Selecione --", "");
	var selecCategorias = $("combo_categorias");
	selectCategorias.options.length = 0;
	selectCategorias.options[0] = new Option("-- Selecione --", "-1");
	alert("Erro de Comuni\xe7\xe3o de rede, Tente novamente");
                  //displayLocateMsg('Estamos sem condi覺es momentaneamente de realizar buscas.', true);
}

//-----------------------------------------------------------------------------------------
// doBuscaCanais()()
// Faz um request para mudar de Cidade (localidae)
//-----------------------------------------------------------------------------------------
function doBuscaCanais(id) {  
	if ((id === undefined) || (id === null)) {
	   // alert('entrou if undefined' );
		var selCidade = $("combo_cidade");
		var idCidade = selCidade.options[selCidade.selectedIndex].value;
		
	} else {
		idCidade = id;
	}
	startLoadingAnimation();
	cidadeAtual = idCidade;
	var params = {"loc":idCidade};
	var url = vUrlMapa + "/tesla/ajax/BuscaCanais?" + xmlhttpreq_encode_dict(params);
	asyncGetJson(url, handleCanaisResponse, handleCanaisErro);
}
               
//-----------------------------------------------------------------------------------------
// doExecComboCidade()
//
//-----------------------------------------------------------------------------------------
function doExecComboCidade() {  
    limparRota();
 	var vInput = $("campo_endereco");
	vInput.value = "";
	limpaResultados();
	limpaComboCategorias();
	limpaComboCanais();
	doBuscaCanais();
}
        
//-----------------------------------------------------------------------------------------
// handleCategoriasResponse(results)
//-----------------------------------------------------------------------------------------
function handleCategoriasResponse(results) {
    stopLoadingAnimation();
	results = JSON.parse(results.responseText);
	if (!results["success"]) {
		return;
	}
	var selectCategorias = $("combo_categorias");
	selectCategorias.options.length = 0;
	var vDados = results["result"]["categorias"];
	selectCategorias.options[0] = new Option(" -- Selecione -- ", "-1");
	if (vDados.length > 0) {
		for (i = 0; i < vDados.length; i= i +1
		) {
			selectCategorias.options[i + 1] = new Option(vDados[i].nome, vDados[i].id);
		}//for
	} //if  
}
               
               
//-----------------------------------------------------------------------------------------
// handleCategoriasErro(req)
//-----------------------------------------------------------------------------------------
function handleCategoriasErro(req) {
   stopLoadingAnimation();
  //displayLocateMsg('Estamos sem condi覺es momentaneamente de realizar buscas.', true);
}

//-----------------------------------------------------------------------------------------
// doBuscaCategorias()
//-----------------------------------------------------------------------------------------
function doBuscaCategorias() {
 	if (vFirstCategoria) {
		canalAtual = 7;
		categoriaAtual = -1;
		cidadeatual = 1;
	} else {
		var selCidade = $("combo_cidade");
		var idCidade = selCidade.options[selCidade.selectedIndex].value;
		var selCanais = $("combo_canal");
		var idCanal = selCanais.options[selCanais.selectedIndex].value;
		canalAtual = idCanal;
		categoriaAtual = -1;
		cidadeatual = idCidade;
	}
	startLoadingAnimation();
	var params = {};
	params["loc"] = cidadeAtual;
	params["canal"] = canalAtual;
	var url = vUrlMapa + "/tesla/ajax/BuscaCategorias?" + xmlhttpreq_encode_dict(params);
	asyncGetJson(url, handleCategoriasResponse, handleCategoriasErro);
}                                 
//-----------------------------------------------------------------------------------------
// showVW(locais)
//
//-----------------------------------------------------------------------------------------
function showVW(vDados) {
    
	/*
	if ( vRotaOverlay !== null) {
	   
	    var icon = createPesquisaIcon(1);
	    var point = new GPoint(xOrigem, yOrigem);
       
	    var popupHTML = '<div style="text-align: left; padding: 10px;"><table cellspacing="0" cellpadding="0" border="0"><tr valign="top">';
	    popupHTML += ' <td><h3>' + vParEndOrigem  + '</h3></td>';
	    popupHTML += '</tr>';
	    popupHTML += '<tr/><td> Latitude  : ' + xOrigem    + '</td></tr>';
        popupHTML += '<tr/><td> Longitude : ' + yOrigem  + '</td></tr>';
	    popupHTML += '</table></div>';
	    var pt1 = new GxMarker(point, icon, popupHTML, '' , false, 0);
	    map.addOverlay(pt1);     
	        
	    icon = createPesquisaIcon(-1);
	    point = new GPoint(xDestino, yDestino);
       
	    popupHTML = '<div style="text-align: left; padding: 10px;"><table cellspacing="0" cellpadding="0" border="0"><tr valign="top">';
	    popupHTML += ' <td><h3>' + vParEndDestino + '</h3></td>';
	    popupHTML += '</tr>';
	    popupHTML += '<tr/><td> Latitude  : ' + xDestino   + '</td></tr>';
        popupHTML += '<tr/><td> Longitude : ' + yDestino  + '</td></tr>';
	    popupHTML += '</table></div>';
	    var pt2 = new GxMarker(point, icon, popupHTML, '' , false, 0);
	    map.addOverlay(pt2);
	  
	
	}
	*/
	if ( ptInit != null ){
	   pontoUsuario = criaMarcaUsuario(ptInit);
	   map.addOverlay(pontoUsuario);
	   ptInit = null;
	  
	}
	results = vDados;     
	if (!results["success"]) {
		setElementHTML("div_resultados", "<br/><span class=\"error\">" + results["result"] + "</span>");
		setElementHTML("lista_paginas", "");
		setElementHTML("total_locais", "");
		return;
	}
	if ( vetVW.length < 1 ) {
	  
	  if (results["result"]["vw_list"].length > 0) {
		for (var b = 0; b < results["result"]["vw_list"].length; b = b + 1) {
			var vw = results["result"]["vw_list"][b];
			var m = criaMarcaVW(vw);
			map.addOverlay(m);
			vetVW.push(m);
		}//for                
	  }
	}
}
               
               
//-----------------------------------------------------------------------------------------
// showLocais(locais)
//
//-----------------------------------------------------------------------------------------
function showLocais(vDados) {
    doBuscaVW();
    if ( vDados.responseText  ==   null ){
       results = vDados;
       var aux = results["success"]      
    }else{
	  results = JSON.parse(vDados.responseText);
	} 
	setVisible("div_painel_resultados", true);
 	if (!results["success"]) {
		setElementHTML("div_resultados", "<br/><span class=\"error\">" + results["result"] + "</span>");
		setElementHTML("lista_paginas", "");
		setElementHTML("total_locais", "");
		return;
	}
	markers = new Array();
	var r = "<table>";
	if (results["result"]["locais"].length > 0) {
		var index = resultsPage * resultsItemsPerPage + 1;
		idx = 0;
		for (var b = 0; b < results["result"]["locais"].length; b = b + 1) {
			var biz = results["result"]["locais"][b];
			var vStr = biz["id"];
			var bizdUrl = "http://" + biz["id"];
			r += "<tr><td><span onMouseOver=\"showPopupIndex(" + index + ")\" onMouseOut=\"hidePopupIndex(" + index + ")\">";
			idx = b + 1;
			//alert ( "/img/icones/resultados/ball_mapa_"+  idx + ".gif");
			r += "<img src=\"/img/icones/resultados/ball_mapa_"+  idx + ".gif\" hspace=\"2\" border=\"0\"></span></td>";
			
			// r += idx + ". ";
			var vNome = biz["name"].substr(0,15);
			if (vStr) {
				r += "<td><span onMouseOver=\"showPopupIndex(" + index + ")\" onMouseOut=\"hidePopupIndex(" + index + ")\"><a href=\"" + bizdUrl + "\" target=\"_top\"><font size=-2>" + vNome+ "</a></span></td></tr>";
			} else {
			    
				r += "<td><span onMouseOver=\"showPopupIndex(" + index + ")\" onMouseOut=\"hidePopupIndex(" + index + ")\"><span><font size=-2>" + vNome+ "</span></span></td>";
			}
			var m = criaMarcaDeLocal(biz, index, false);
			markers[index] = m;
			map.addOverlay(m);
			vetPt.push(m);
			index++;
		}
		r += "</table>";
		var pager = pagerControls(results["result"]["total"], 5, resultsItemsPerPage, resultsPage, function (page) {
			return "javascript:setResultsPage(" + page + ");";
		});
		if (pager === null) {
			setElementHTML("lista_paginas", "");
		} else {
			setElementHTML("lista_paginas", "<table><tr><td></td></tr></table>" + pager);
		}
		setElementHTML("total_locais", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(" + results["result"]["total"] + " Encontrados)");
	} else {
		r = "<br/>Nenhum local encontrado";
		setElementHTML("lista_paginas", "");
		setElementHTML("total_locais", "");
	}
	setElementHTML("div_resultados", r);	
}
//-----------------------------------------------------------------------------------------
// handleCategoriasResponse(results)
//-----------------------------------------------------------------------------------------
function handleLocaisResponse(results) {
    stopLoadingAnimation();   
	if ( ajustaZoom !== null ){
	    vRs = JSON.parse(results.responseText);
	   ajustaZoom = null;	  
	   var vZoom = vRs["result"]["zoom"];	   
	   map.setCenter( map.getCenter(), vZoom);
	}
	showLocais(results);
}               
//-----------------------------------------------------------------------------------------
// handleCategoriasErro(req)
//-----------------------------------------------------------------------------------------
function handleLocaisErro(req) {
    stopLoadingAnimation();
	//alert("erro Ajax busca locais");
                  //displayLocateMsg('Estamos sem condi覺es momentaneamente de realizar buscas.', true);
}

//-----------------------------------------------------------------------------------------
// doBuscaCategorias()
// Faz um request para mudar de Cidade (localidae)
//-----------------------------------------------------------------------------------------
function doBuscaLocais() {
	var selCidade = $("combo_cidade");
	var idCidade = selCidade.options[selCidade.selectedIndex].value;
	var selCanais = $("combo_canal");
	var idCanal = selCanais.options[selCanais.selectedIndex].value;
	var selCategorias = $("combo_categorias");
	var idCategoria = selCategorias.options[selCategorias.selectedIndex].value;
	var params = getAdjustedMapBounds(map, $("div_google_map"));
	canalAtual = idCanal;
	categoriaAtual = idCategoria;
	cidadeatual = idCidade;	             
	if (idCategoria != -1) {
	    startLoadingAnimation();
	    var vAuxPt = null; 
	    while ( vetPt.length  > 0) {
	      vAuxPt = vetPt.pop();
	      map.removeOverlay(vAuxPt);
	    }
		params["start"] = resultsPage * resultsItemsPerPage;
		params["count"] = resultsItemsPerPage;
		params["canal"] = idCanal;
		params["cidade"] = idCidade;
		params["categoria"] = idCategoria;
		if ( ajustaZoom == null )
		  params["zoom"] =  -1;
		else
		 params["zoom"] =  map.getZoom();
		var url = vUrlMapa + "/tesla/ajax/BuscaLocais?" + xmlhttpreq_encode_dict(params);
		asyncGetJson(url, handleLocaisResponse, handleLocaisErro);
	}
}
     
//-----------------------------------------------------------------------------------------
// doExecCompoCanal()
//
//-----------------------------------------------------------------------------------------
function doExecCompoCanal() {
	limpaResultados();
	limpaComboCategorias();
	doBuscaCategorias();
	doBuscaVW();
	mostraPontoUsuario();
}        
//-----------------------------------------------------------------------------------------
 // doExecComboCategorias()
 //
//-----------------------------------------------------------------------------------------
function doExecComboCategorias() {
	limpaResultados();
	ajustaZoom = true;
	doBuscaVW();
	doBuscaLocais();
	mostraPontoUsuario();
}               
//-----------------------------------------------------------------------------------------
// handleCategoriasResponse(results)
//-----------------------------------------------------------------------------------------
function handleVWResponse(results) {
	showVW(results);
}              
 //-----------------------------------------------------------------------------------------
 // handleVWErro(req)
 //-----------------------------------------------------------------------------------------
function handleVWErro(req) {
	//alert("erro Ajax busca locais");
                  //displayLocateMsg('Estamos sem condi覺es momentaneamente de realizar buscas.', true);
}

//-----------------------------------------------------------------------------------------
// doBuscaVW()
// Faz um request para mudar de Cidade (localidae)
//-----------------------------------------------------------------------------------------
function doBuscaVW() {
	showVW(vAgenciasVW);
}


