//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------

function getCookie(c_name){
  if (document.cookie.length > 0){
     c_start=document.cookie.indexOf(c_name + "=")
     if (c_start!=-1){ 
       c_start=c_start + c_name.length+1 
       c_end=document.cookie.indexOf(";",c_start)
       if (c_end==-1) c_end=document.cookie.length
          return unescape(document.cookie.substring(c_start,c_end))
     } 
  }
  return ""
}
//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------

function setCookie(c_name,value,expiredays){
  
  var exdate=new Date()
  exdate.setDate(exdate.getDate() + expiredays)
  document.cookie = c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}

//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------

function checkCookie(){
   var ptCity = getCookie('mapa_id_city');
  if (ptCity!=null && ptCity!=""  && ptCity == cidadeAtual) {
    
     return  buscaPtUsuarioCookie();
   }else{
      
      return null;
   }
   
}



//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------

function gravaPtUsuarioCookie(pt){
 
  setCookie('mapa_pt_longitude', pt.longitude,365);
  setCookie('mapa_pt_latitude', pt.latitude,365);
  setCookie('mapa_pt_nome', pt.nome,365);
  setCookie('mapa_pt_rua' , pt.rua ,365);
  setCookie('mapa_pt_bairro' , pt.bairro ,365);
  setCookie('mapa_pt_cidade' , pt.cidade ,365);
  setCookie('mapa_pt_estado' , pt.estado ,365);
   setCookie('mapa_id_city' , cidadeAtual,365);
   
 
}


//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------

function buscaPtUsuarioCookie(){
  var pt = new Object();
  pt.longitude = getCookie('mapa_pt_longitude');
  pt.latitude = getCookie('mapa_pt_latitude');
  pt.nome = getCookie('mapa_pt_nome');
  pt.rua = getCookie('mapa_pt_rua');
  pt.bairro = getCookie('mapa_pt_bairro');
  pt.cidade = getCookie('mapa_pt_cidade');
  pt.estado = getCookie('mapa_pt_estado');
  
  return pt;
}


//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------

function limparRota(){
   $('directions').style.display = 'none';
    gdir.clear();
}


//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------
function xmlhttpreq_encode_dict(dict){ 
	var result_string = "";
	var start = true;
	for (var i in dict){ 
		if (!start) {result_string += "&";}
		else start = false;
		result_string += encodeURIComponent(i) + "=" + encodeURIComponent(dict[i]);
	}
	return result_string; 
}


//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------
function imageUrl(){
  var iUrlStr = imagesHostUrl ;
  return iUrlStr;
}

//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------
function swap(imgId, imgSrc) {
	var imgObj = $(imgId);
	imgObj.src = imgSrc;
}



//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------
function setVisible(id, vis) {
	var tmp = $(id);
	if (vis) {
		tmp.style.visibility = "visible";
		tmp.style.display = "block";
	} else {
		tmp.style.visibility = "hidden";
		tmp.style.display = "none";
	}
}
              

//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------
               //<![CDATA[
var map = null;
var markers = null;
var queryType = null;
var queryArg = null;
var currentRequest = null;
var currentCat = null;
var grupoAtual = "";
var subcatList = null;
var subcatPage = 0;
var resultsPage = 0;
var subcatItemsPerPage = 10;
var resultsItemsPerPage = 10;
var mapSize = null;
var newMapSize = null;
var mapCenter = null;
var mapResizingInterval = null;
var mapResizeFlag = false;
            
 //-----------------------------------------------------------------------------------------
 // excerpt(text, maxLength)
  //-----------------------------------------------------------------------------------------
function excerpt(text, maxLength) {
	if (text.length <= maxLength) {
		return text;
	}
	return text.substring(0, maxLength - 3) + "...";
}

 //-----------------------------------------------------------------------------------------
 //
 //-----------------------------------------------------------------------------------------
function pagerControls(numItems, maxPages, itemsPerPage, currentPage, pageLinkFunc) {
	if (numItems <= itemsPerPage) {
		return null;
	}
	var html = "<center><img src=http://www.mapadeamericana.com.br/mapa/imagens/cab2_mapas2.png border=0 vspace=5><br></center>";
	var numPages = Math.ceil(numItems / itemsPerPage);
	var prevPages = false;
	var nextPages = false;
	var firstPage;
	var lastPage;
	if (numPages <= maxPages) {
		firstPage = 0;
		lastPage = numPages;
	} else {
		var pageRadius = Math.floor((maxPages - 1) / 2);
		if ((currentPage - pageRadius) <= 0) {
			nextPages = true;
			firstPage = 0;
		} else {
			if ((currentPage + pageRadius) >= (numPages - 1)) {
				prevPages = true;
				firstPage = numPages - maxPages;
			} else {
				nextPages = true;
				prevPages = true;
				firstPage = currentPage - pageRadius;
			}
		}
		lastPage = firstPage + maxPages;
	}
	if (lastPage > 99) {
		lastPage = 99;
	}
	if (currentPage > 0) {
		html += "<a href=\"" + pageLinkFunc(currentPage - 1) + "\"><img src=http://www.mapadeamericana.com.br/mapa/imagens/cab2_mapas2.png border=0></a> ";
	}
	if (prevPages) {
		html += " ... ";
	}
	for (var i = firstPage; i < lastPage; i = i + 1) {
		if (i == currentPage) {
			html += " " + (i + 1) + " ";
		} else {
			html += "<a href=\"" + pageLinkFunc(i) + "\">" + (i + 1) + "</a> ";
		}
	}
	if (nextPages) {
		html += " ... ";
	}
	if (currentPage < (lastPage - 1)) {
		html += "<a href=\"" + pageLinkFunc(currentPage + 1) + "\"><img src=http://www.mapadeamericana.com.br/mapa/imagens/cab2_mapas2.png border=0></a> ";
	}
	return html;
}
/*pagerControls */
               
//-----------------------------------------------------------------------------------------
// setResultsPage(page)
//-----------------------------------------------------------------------------------------
function setResultsPage(page) {
	resultsPage = page;
	updateResults();
}


 //-----------------------------------------------------------------------------------------
// startLoadingAnimation()
//-----------------------------------------------------------------------------------------
function startLoadingAnimation() {
	$("loading_animation").style.visibility = "visible";
}


 //-----------------------------------------------------------------------------------------
// stopLoadingAnimation()
//-----------------------------------------------------------------------------------------
function stopLoadingAnimation() {
	$("loading_animation").style.visibility = "hidden";
}

//-----------------------------------------------------------------------------------------
// updateQueryStatus()
//-----------------------------------------------------------------------------------------
function updateQueryStatus() {
	if (inFlightQueries === 0) {
		stopLoadingAnimation();
	} else {
		startLoadingAnimation();
	}
}
var highlightMarker = null;

//-----------------------------------------------------------------------------------------
//  showPopupIndex(index)
//-----------------------------------------------------------------------------------------
function showPopupIndex(index) {

	markers[index].showMouseOver();
	highlightMarker = new GMarker(markers[index].getPoint(), createSliceIcon(index, SLICE_STYLE_HIGHLIGHTED));
	map.addOverlay(highlightMarker);
}

 //-----------------------------------------------------------------------------------------
 // hidePopupIndex(index)
//-----------------------------------------------------------------------------------------
function hidePopupIndex(index) {
	markers[index].hideMouseOver();
	map.removeOverlay(highlightMarker);
}



//-----------------------------------------------------------------------------------------
 // fillSort()
 //-----------------------------------------------------------------------------------------
function fillSort() {
	var sortSelect = $("sort_select");
	sortSelect.options.length = 0;
	var sortOptions = [];
	if (queryType == "search") {
		sortOptions = searchSortOptions;
	} else {
		if (queryType == "browse") {
			sortOptions = browseSortOptions;
		}
	}
	for (var i = 0; i < sortOptions.length; i = i + 1) {
		var selected = (i === 0);
		sortSelect.options[i] = new Option(sortOptions[i][1], sortOptions[i][0], selected, selected);
	}
}

              
 //-----------------------------------------------------------------------------------------
// updateResultsRepage()
 //-----------------------------------------------------------------------------------------
function updateResultsRepage() {
	resultsPage = 0;
	updateResults();
}


 //-----------------------------------------------------------------------------------------
 // updateResults()
 //-----------------------------------------------------------------------------------------
function updateResults() {
	doBuscaLocais();
}


//-----------------------------------------------------------------------------------------
// handleMapChange()
 //-----------------------------------------------------------------------------------------
function handleMapChange() {
   	  if( (vIDL !== null) && vIDL != '' ){
            resultsPage = 0;
            startLoadingAnimation();
            ajustaZoom = null;
            handleLocaisResponse(resultEndInicial);
             vIDL = null;
            doBuscaVW();
            setElementHTML("lista_paginas", "");
		    setElementHTML("total_locais", "");
      }else{
     	if ((canalAtual != -1) && (categoriaAtual != -1)) {
   	      if ( vRotaBalao == null ){
      	     updateResultsRepage();
	      }else
	      vRotaBalao = null;
	    }else{
	      doBuscaVW();
    	}
      }
   
}
 //-----------------------------------------------------------------------------------------
// displayLocateMsg(msg, error)
 //-----------------------------------------------------------------------------------------
function displayLocateMsg(msg, error) {
	var html = "";
	if (msg === null) {
		html = "Click and arraste em qualquer lugar do mapa abaixo para ver os resultados em outra area!";
	} else {
		if (error) {
			html = "<span class=\"error\">" + msg + "</span>";
		} else {
			html = "<span class=\"grey\">" + msg + "</span>";
		}
	}
	setElementHTML("location_message", html);
}
 //-----------------------------------------------------------------------------------------
// function checkResizeEnd()
//-----------------------------------------------------------------------------------------
function checkResizeEnd() {
	if (!mapResizeFlag) {
		newMapSize = map.getBounds();
		if (!mapSize.equals(newMapSize)) {
			mapCenter = map.getCenter();
			map.checkResize();
			map.setCenter(mapCenter);
			handleMapChange();
			mapSize = newMapSize;
		}
		clearInterval(mapResizingInterval);
		mapResizingInterval = null;
	}
	mapResizeFlag = false;
} 
//-----------------------------------------------------------------------------------------
// closeAllModalWindows() 
//----------------------------------------------------------------------------------------- 
  function closeAllModalWindowsX() {
      pontoUsuario = vDadosPesquisa[vIndicePesquisa];
	  vCenter = new GLatLng(parseFloat(vDadosPesquisa[vIndicePesquisa].latitude), parseFloat(vDadosPesquisa[vIndicePesquisa].longitude));
	  map.setCenter(vCenter, 15);
      Windows.closeAllModalWindows();
    return true;
  }    
     
//-----------------------------------------------------------------------------------------
//enderecoInicialResponse(results)
//-----------------------------------------------------------------------------------------
function enderecoInicialResponse(results) { 
	vCenter = null;
	var vTotal = results["total"];
	vIndicePesquisa = 0;
	if (vTotal > 0) { 
	    vDadosPesquisa = results["result"]["vet_enderecos"];  
	    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].numero +', ' +  vDadosPesquisa[i].bairro +  '</option>';    
	      }
	      vHtml = vHtml +'</select><tr><td></table>';
          Dialog.alert(vHtml, {className: "alphacube", height:200,  width:270, cancelLabel:"",  okLabel: "ok", ok: closeAllModalWindowsX});
          pontoUsuario = vDadosPesquisa[0];
		  vCenter = new GLatLng(parseFloat(vDadosPesquisa[0].latitude), parseFloat(vDadosPesquisa[0].longitude));  
        }else{
  		  pontoUsuario = vDadosPesquisa[0];
		  vCenter = new GLatLng(parseFloat(vDadosPesquisa[0].latitude), parseFloat(vDadosPesquisa[0].longitude));
	    }
	
	} else {
	    pontoUsuario = null;
		handleMapChange();
	}
}



            //]]>
//-----------------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------------

